Exemplo n.º 1
0
 /// <summary>
 /// Selects and returns the next image
 /// </summary>
 /// <returns>Next image</returns>
 /// <remarks>Switches pages if needed</remarks>
 public ImgurImage NextImage()
 {
     if (lvImages.SelectedItems.Count > 0)
     {
         ListViewItem I = lvImages.SelectedItems[0];
         I.Text = ((ImgurImage)I.Tag).title;
         if (I.Index < lvImages.Items.Count - 1)
         {
             ListViewItem NextItem = lvImages.Items[I.Index + 1];
             lvImages.SelectedItems.Clear();
             NextItem.Selected = true;
             NextItem.EnsureVisible();
             return((ImgurImage)NextItem.Tag);
         }
         else if (CurrentPage < Pages)
         {
             ShowImages((ImageFilter)lvImages.Tag, ++CurrentPage, (bool)tbFilter.Tag ? null : tbFilter.Text);
             I          = lvImages.Items[0];
             I.Selected = true;
             I.EnsureVisible();
             return((ImgurImage)I.Tag);
         }
     }
     return(null);
 }
Exemplo n.º 2
0
        private void FillAlbums()
        {
            Imgur             I      = new Imgur(S);
            List <ImgurAlbum> Albums = new List <ImgurAlbum>();

            Invoke((MethodInvoker) delegate
            {
                cbAlbum.Enabled = false;
                cbAlbum.Items.Clear();
                cbAlbum.Items.Add("Working...");
                cbAlbum.Items.Add("<none>");
                cbAlbum.SelectedIndex = 0;
            });
            Albums.AddRange(I.GetAccountAlbums().OrderBy(m => m.title));
            Invoke((MethodInvoker) delegate
            {
                cbAlbum.Items.RemoveAt(0);
                cbAlbum.SelectedIndex = 0;
                foreach (ImgurAlbum A in Albums)
                {
                    cbAlbum.Items.Add(new AlbumEntry(A));
                }
                cbAlbum.Enabled = true;
            });
        }
Exemplo n.º 3
0
 /// <summary>
 /// Selects and returns the previous image
 /// </summary>
 /// <returns>Previous image</returns>
 /// <remarks>Switches pages if needed</remarks>
 public ImgurImage PrevImage()
 {
     if (lvImages.SelectedItems.Count > 0)
     {
         ListViewItem I = lvImages.SelectedItems[0];
         //Update title in case it was changed in the form
         I.Text = ((ImgurImage)I.Tag).title;
         if (I.Index > 0)
         {
             ListViewItem PrevItem = lvImages.Items[I.Index - 1];
             lvImages.SelectedItems.Clear();
             PrevItem.Selected = true;
             PrevItem.EnsureVisible();
             return((ImgurImage)PrevItem.Tag);
         }
         else if (CurrentPage > 1)
         {
             ShowImages((ImageFilter)lvImages.Tag, --CurrentPage, (bool)tbFilter.Tag ? null : tbFilter.Text);
             I          = lvImages.Items.OfType <ListViewItem>().Last();
             I.Selected = true;
             I.EnsureVisible();
             return((ImgurImage)I.Tag);
         }
     }
     return(null);
 }
Exemplo n.º 4
0
        /// <summary>
        /// Gets the thumbnail associated with the given metadata
        /// </summary>
        /// <param name="I">Image metadata</param>
        /// <returns>Image file, null if not found</returns>
        /// <remarks>Downloads the image to cache if necessary</remarks>
        public static byte[] GetThumbnail(ImgurImage I)
        {
            string ThumbFile = Path.Combine(_thumbDir, GetThumbnailName(I));

            if (!File.Exists(ThumbFile))
            {
                File.WriteAllBytes(ThumbFile, Imgur.GetImage(I, ImgurImageSize.BigSquare, false));
            }
            return(File.ReadAllBytes(ThumbFile));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Saves changes
        /// </summary>
        /// <returns>"True", if saved</returns>
        private bool Save()
        {
            string newTitle = string.IsNullOrEmpty(tbTitle.Text) ? null : tbTitle.Text;
            string newDesc  = string.IsNullOrEmpty(tbDesc.Text) ? null : tbDesc.Text;

            if (I.title != newTitle || I.description != newDesc)
            {
                //Replace empty strings with null
                I.title       = newTitle;
                I.description = newDesc;

                Imgur     imgur         = new Imgur(S);
                bool      Result        = false;
                Exception TaskException = null;
                Task.Run(async delegate
                {
                    try
                    {
                        Result = await imgur.SetImageDescription(I, I.title, I.description);
                    }
                    catch (Exception ex)
                    {
                        TaskException = ex;
                        Result        = false;
                    }
                }).Wait();
                if (Result)
                {
                    //Replace updated image in cache
                    ImgurImage[] All = Cache.Images;
                    for (int i = 0; i < All.Length; i++)
                    {
                        if (All[i].id == I.id)
                        {
                            All[i] = I;
                        }
                    }
                    Cache.Images = All;
                    return(true);
                }
                else
                {
                    if (TaskException != null)
                    {
                        MessageBox.Show("Unable to set new image properties", "Unable to update image", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show($"Unable to set new image properties. Details: {TaskException.Message}", "Unable to update image", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                return(false);
            }
            return(true);
        }
Exemplo n.º 6
0
        static void Main()
        {
            Settings S;

            if (File.Exists(SettingsFile))
            {
                //Load existing settings
                S = Tools.LoadSettings(SettingsFile);
            }
            else
            {
                //Create default settings
                S = new Settings()
                {
                    Client = new Client()
                    {
                        //I recommend you also set a secret in the settings.
                        //Without a secret we can get a token, but not refresh it
                        Id = "a5e26e2dac343b6"
                    }
                };
                Tools.SaveSettings(S, SettingsFile);
            }

            //Clear any invalid items from the cache
            if (Cache.Images != null)
            {
                ImgurImage[] CacheImages = Cache.Images;
                if (CacheImages.Any(m => m == null))
                {
                    Cache.Images = CacheImages.Where(m => m != null).ToArray();
                }
            }

            //Try to refresh the token if expired or close to expiration
            Imgur I = new Imgur(S);

            //Update initial credits values
            I.CheckCredits().Wait();
            if (!string.IsNullOrEmpty(S.Token.Access) && S.Token.Expires < DateTime.UtcNow.AddDays(7))
            {
                if (I.RenewToken().Result)
                {
                    Tools.SaveSettings(S, SettingsFile);
                }
                else
                {
                    MessageBox.Show("Unable to refresh your API token.\r\nPlease Authorize the application again.", "Token Refresh Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FrmMain(S));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Gets the image file associated with the given metadata
        /// </summary>
        /// <param name="I">Image metadata</param>
        /// <returns>Image file, null if not found</returns>
        /// <remarks>Downloads the image to cache if necessary</remarks>
        public static byte[] GetImage(ImgurImage I)
        {
            string ImageFile = Path.Combine(_imageDir, GetImageName(I));

            if (!File.Exists(ImageFile))
            {
                //Add image to cache if not found
                File.WriteAllBytes(ImageFile, Imgur.GetImage(I, ImgurImageSize.Original, false));
                //New images are at the start
                Images = (new ImgurImage[] { I }).Concat(Images).ToArray();
            }
            return(File.ReadAllBytes(ImageFile));
        }
Exemplo n.º 8
0
 private bool DeleteAlbums(ImgurAlbum[] Albums)
 {
     if (Albums.Length > 0)
     {
         Imgur I = new Imgur(S);
         if (MessageBox.Show("Delete the selected albums? Images will not be deleted", $"Delete {Albums.Length} albums", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
         {
             Task.WaitAll(Albums.Select(m => I.DeleteAlbum(m)).ToArray());
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 9
0
        /// <summary>
        /// Uploads the selected image
        /// </summary>
        /// <param name="sender">Event sender</param>
        /// <param name="e">Event arguments</param>
        private async void BtnUpload_Click(object sender, EventArgs e)
        {
            byte[] Data = null;
            try
            {
                if (UseClipboard)
                {
                    using (MemoryStream MS = new MemoryStream())
                    {
                        pbPreview.Image.Save(MS, ImageFormat.Png);
                        Data = MS.ToArray();
                    }
                }
                else
                {
                    Data = File.ReadAllBytes(tbImage.Text);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Unable to read file. Reason: {ex.Message}", "File read Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (Data != null)
            {
                Imgur I = new Imgur(S);
                try
                {
                    ImgurImage img = await I.UploadImage(Data, Path.GetFileName(tbImage.Text), tbTitle.Text, tbDescription.Text);

                    if (img != null)
                    {
                        //Add new image
                        Cache.Images = (new ImgurImage[] { img }).Concat(Cache.Images).ToArray();
                        DialogResult = DialogResult.OK;
                        Close();
                    }
                    else
                    {
                        throw new Exception("Imgur API did not accept the image");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Unable to upload your image. Reason: {ex.Message}", "File read Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Exemplo n.º 10
0
 /// <summary>
 /// Sets the currently shown image
 /// </summary>
 /// <param name="I">Current image</param>
 private void SetImage(ImgurImage I)
 {
     this.I       = I;
     Text         = $"Image Properties [{I.name}] ({I.views} views)";
     tbTitle.Text = I.title;
     //Imgur uses \n only
     if (string.IsNullOrEmpty(I.description))
     {
         tbDesc.Text = string.Empty;
     }
     else
     {
         tbDesc.Lines = I.description.Split('\n');
     }
     if (!I.animated)
     {
         using (MemoryStream MS = new MemoryStream(Cache.GetImage(I)))
         {
             using (Image img = Image.FromStream(MS))
             {
                 pbImage.Image = (Image)img.Clone();
             }
         }
     }
     else
     {
         //var Imgur = new Imgur(S);
         //This is a temporary solution until I can figure out how to play GIF animations again
         using (MemoryStream MS = new MemoryStream(Imgur.GetImage(I, ImgurImageSize.HugeThumbnail, false)))
         {
             using (Image img = Image.FromStream(MS))
             {
                 pbImage.Image = (Image)img.Clone();
             }
         }
     }
     ScaleImage();
     tbTitle.Focus();
     tbTitle.SelectAll();
 }
Exemplo n.º 11
0
 /// <summary>
 /// Initializes a new main form
 /// </summary>
 /// <param name="S">Current settings</param>
 public FrmMain(Settings S)
 {
     this.S = S;
     InitializeComponent();
     TbFilter_Leave(null, null);
     //Program.Main already tries to authorize.
     //If the date is still in the past, the user has to do so manually.
     if (S.Token.Expires < DateTime.UtcNow)
     {
         using (frmAuth f = new frmAuth(S))
         {
             if (f.ShowDialog() == DialogResult.OK)
             {
                 Tools.SaveSettings(S, Program.SettingsFile);
             }
             else
             {
                 MessageBox.Show("Could not authorize this application. Will exit now.", "No Authorization", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 Environment.Exit(1);
                 return;
             }
         }
     }
     I = new Imgur(S);
     if (S.UI.MainWindowMaximized)
     {
         WindowState = FormWindowState.Maximized;
     }
     else
     {
         Size ConfigSize = S.UI.MainWindowSize;
         if (ConfigSize.Height >= MinimumSize.Height && ConfigSize.Width >= MinimumSize.Width)
         {
             Size = ConfigSize;
         }
     }
     InitPages();
 }
Exemplo n.º 12
0
 /// <summary>
 /// Authorizes the application using OAuth2
 /// </summary>
 /// <param name="sender">Event sender</param>
 /// <param name="e">Event arguments</param>
 private void AuthorizeToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (S.Token.Expires < DateTime.UtcNow || MessageBox.Show($"This app is already authorized until {S.Token.Expires.ToShortDateString()} and connected to your account. Reauthorization will erase the cache.\r\nContinue?", "Authorization", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
     {
         using (frmAuth fAuth = new frmAuth(S))
         {
             if (fAuth.ShowDialog() == DialogResult.OK)
             {
                 Cache.ClearThumbnails();
                 Cache.ClearImages();
                 using (frmCacheBuilder fCache = new frmCacheBuilder(S))
                 {
                     fCache.ShowDialog();
                 }
                 I = new Imgur(S);
                 InitPages();
             }
             else
             {
                 MessageBox.Show("Unable to authorize your client. Your current authorization will be kept. Please try again", "Authorization Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
         }
     }
 }
Exemplo n.º 13
0
        private void LoadAlbums()
        {
            Imgur     I  = new Imgur(S);
            ImageList IL = new ImageList()
            {
                ImageSize  = new Size(160, 160),
                ColorDepth = ColorDepth.Depth32Bit
            };

            lvAlbums.Items.Clear();
            lvAlbums.Items.Add("Loading...");
            lvAlbums.Enabled = false;
            Thread T = new Thread(delegate()
            {
                using (MemoryStream MS = new MemoryStream(Tools.ConvertImage(Tools.GetResource("imgur.ico"), ImageFormat.Jpeg), false))
                {
                    IL.Images.Add(Image.FromStream(MS));
                }
                List <ListViewItem> Entries = new List <ListViewItem>();

                foreach (ImgurAlbum Album in I.GetAccountAlbums())
                {
                    if (Album.cover == null)
                    {
                        if (Album.images_count > 0)
                        {
                            ImgurImage[] AlbumImages = I.GetAlbumImages(Album.id).Result;
                            if (AlbumImages != null)
                            {
                                //Use first image as cover
                                Album.cover = AlbumImages[0].id;
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(Album.cover))
                    {
                        using (MemoryStream MS = new MemoryStream(Cache.GetThumbnail(Album.cover), false))
                        {
                            IL.Images.Add(Image.FromStream(MS));
                        }
                    }
                    ListViewItem Item = new ListViewItem(Album.title ?? string.Empty)
                    {
                        ImageIndex  = string.IsNullOrEmpty(Album.cover) ? 0 : IL.Images.Count - 1,
                        Tag         = Album,
                        ToolTipText = $"[{Album.title}] {Album.description}"
                    };
                    Entries.Add(Item);
                }
                Invoke((MethodInvoker) delegate
                {
                    lvAlbums.SuspendLayout();
                    lvAlbums.Items.Clear();
                    if (lvAlbums.LargeImageList != null)
                    {
                        lvAlbums.LargeImageList.Dispose();
                    }
                    lvAlbums.LargeImageList = IL;
                    lvAlbums.Items.AddRange(Entries.ToArray());
                    lvAlbums.ResumeLayout();
                    lvAlbums.Enabled = true;
                });
            })
            {
                IsBackground = true
            };

            T.Start();
        }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new cache builder
 /// </summary>
 /// <param name="S">Current settings</param>
 public frmCacheBuilder(Settings S)
 {
     InitializeComponent();
     I = new Imgur(S);
 }
Exemplo n.º 15
0
        private async void BtnStartUpload_Click(object sender, EventArgs e)
        {
            SetControlState(false);
            Stack <FileNameItem> ItemList = new Stack <FileNameItem>(lbFileList.Items.OfType <FileNameItem>().Reverse());
            Imgur I = new Imgur(S);

            if (ItemList.Count > 0)
            {
                string        AlbumId = cbAlbum.SelectedIndex > 0 ? ((AlbumEntry)cbAlbum.SelectedItem).Id : null;
                List <string> Images  = AlbumId == null ? null : (await I.GetAlbumImages(AlbumId)).Select(m => m.id).ToList();

                lbFileList.SelectedIndex = 0;
                while (ItemList.Count > 0)
                {
                    FileNameItem Current = ItemList.Pop();
                    ImgurImage   Img     = await I.UploadImage(
                        File.ReadAllBytes(Current.LongName),
                        Path.GetFileName(Current.LongName),
                        FormatFileString(tbTitle.Text, Current.LongName),
                        cbDescDate.Checked?DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss \U\T\C") : "");

                    if (Img != null)
                    {
                        if (Images != null)
                        {
                            Images.Add(Img.id);
                        }
                        Cache.GetImage(Img);
                        lbFileList.Items.RemoveAt(0);
                    }
                    else
                    {
                        //Add failed image back to the queue
                        ItemList.Push(Current);
                        //Ask user to retry or cancel
                        if (MessageBox.Show("Failed to upload an image. Response: " + I.LastError, "Upload failed", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                        {
                            break;
                        }
                    }
                }
                if (Images != null)
                {
                    while (
                        !await I.SetAlbumImages(AlbumId, Images) &&
                        MessageBox.Show("Failed to add uploaded images to the album. Response: " + I.LastError, "Album change failed", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Retry)
                    {
                        ;
                    }
                }
                if (lbFileList.Items.Count == 0)
                {
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    SetControlState(true);
                }
            }
            else
            {
                MessageBox.Show("Please select at least one file to upload.", "No files", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }