//Gets imgur album to random featured image private async Task GetAlbum() { canRandomImage = true; try { string albumURL = currentEventInfo[5]; string albumID = albumURL.Substring(albumURL.IndexOf("/a/") + 3); var client = new ImgurClient(_dataServices.imgurAPI); var endpoint = new AlbumEndpoint(client); featureAlbum = await endpoint.GetAlbumAsync(albumID); string foundImages = null; foreach (var i in featureAlbum.Images) { foundImages += $"{i.Link}\n"; } await _dataServices.ChannelLog("Getting Imgur Info from IMGUR API", $"Album URL: {albumURL}" + $"\nAlbum ID: {albumID}" + $"\nClient Credits Remaining: {client.RateLimit.ClientRemaining} of {client.RateLimit.ClientLimit}" + $"\nImages Found: {foundImages}"); } catch { await _dataServices.ChannelLog($"Unable to get Imgur Album for Random Image for {currentEventInfo[2]}", "Falling back to the image in the cal event."); canRandomImage = false; } }
public async Task GetAlbumAsync_AreEqual() { var fakeHttpMessageHandler = new FakeHttpMessageHandler(); var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(AlbumEndpointResponses.Imgur.GetAlbumResponse) }; fakeHttpMessageHandler.AddFakeResponse(new Uri("https://api.imgur.com/3/album/5F5Cy"), fakeResponse); var client = new ImgurClient("123", "1234"); var endpoint = new AlbumEndpoint(client, new HttpClient(fakeHttpMessageHandler)); var album = await endpoint.GetAlbumAsync("5F5Cy"); Assert.IsNotNull(album); Assert.AreEqual("5F5Cy", album.Id); Assert.AreEqual(null, album.Title); Assert.AreEqual(null, album.Description); Assert.AreEqual(album.DateTime, new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(1446591779)); Assert.AreEqual("79MH23L", album.Cover); Assert.AreEqual(609, album.CoverWidth); Assert.AreEqual(738, album.CoverHeight); Assert.AreEqual("sarah", album.AccountUrl); Assert.AreEqual(9571, album.AccountId); Assert.AreEqual(AlbumPrivacy.Public, album.Privacy); Assert.AreEqual(AlbumLayout.Blog, album.Layout); Assert.AreEqual(4, album.Views); Assert.AreEqual("http://imgur.com/a/5F5Cy", album.Link); Assert.AreEqual(false, album.Favorite); Assert.AreEqual(null, album.Nsfw); Assert.AreEqual(null, album.Section); Assert.AreEqual(3, album.ImagesCount); Assert.AreEqual(3, album.Images.Count()); }
public static async Task <IAlbum> GetAlbumAsync(string id) { var endpoint = new AlbumEndpoint(Client); var album = await endpoint.GetAlbumAsync(id); return(album); }
public async Task GetAlbumAsync_WithAlbum_AreEqual(IAlbum actualAlbum) { var client = new MashapeClient(ClientId, ClientSecret, MashapeKey, OAuth2Token); var endpoint = new AlbumEndpoint(client); var album = await endpoint.GetAlbumAsync(actualAlbum.Id); Assert.AreEqual(actualAlbum.Id, album.Id); }
public async Task GetAlbumAsync_WithAlbum_AreEqual(IAlbum actualAlbum) { var client = new ImgurClient(ClientId, ClientSecret); var endpoint = new AlbumEndpoint(client); var album = await endpoint.GetAlbumAsync(actualAlbum.Id); Assert.AreEqual(actualAlbum.Id, album.Id); }
public async Task BuiTask() { ImgurClient client = new ImgurClient(Globals.Settings.ImgurClientId); AlbumEndpoint endpoint = new AlbumEndpoint(client); IAlbum album = await endpoint.GetAlbumAsync("KJTbv"); int randomInt = Globals.Random.Next(0, album.ImagesCount); string imageLink = album.Images.Select(e => e.Link).ToList()[randomInt]; await this.ReplyAsync(imageLink); }
public async Task GetAlbumAsync_WithIdNull_ThrowsArgumentNullException() { var client = new ImgurClient("123", "1234"); var endpoint = new AlbumEndpoint(client); var exception = await Record.ExceptionAsync( async() => await endpoint.GetAlbumAsync(null).ConfigureAwait(false)) .ConfigureAwait(false); Assert.NotNull(exception); Assert.IsType <ArgumentNullException>(exception); }
public static async Task <(List <object>, int)> CollectImagesTaskAsync(HentaiModel hentai, Action <int, int> setPages) { //var mockUrl = "https://api.imgur.com/3/album/5F5Cy/images"; //https://imgur.com/a/LNKof var galleryId = hentai.Link.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Last(); var client = new ImgurClient("b9a0d31f5189a6e"); var endpoint = new AlbumEndpoint(client); IAlbum album; try { album = await endpoint.GetAlbumAsync(galleryId); } catch (ImgurException e) { hentai.Title = e.Message; return(new List <object>(), 0); } if (hentai.Title == "lul") { hentai.Title = album.Title ?? album.Link; } if (Directory.Exists(hentai.SavePath)) { //var files = Directory.GetFiles(hentai.SavePath, "*.png"); var files = new DirectoryInfo(hentai.SavePath).GetFileSystemInfos("*.???") .OrderBy(fs => int.Parse(fs.Name.Split('.')[0])); var paths = new List <object>(); files.ToList().ForEach(p => paths.Add(p.FullName)); if (files.ToList().Count == album.ImagesCount) { setPages(files.Count(), album.ImagesCount); } return(new List <object>(paths), album.ImagesCount); } setPages(album.Images.Count(), album.ImagesCount); return(new List <object>(album.Images.Select(i => i.Link).ToList()), album.ImagesCount); }
async static public void Test() { string albumURL = "https://imgur.com/a/PItKx"; string albumID = albumURL.Substring(albumURL.IndexOf("/a/") + 3); Console.WriteLine(albumID); Console.WriteLine("TEST WORK STATED"); var client = new ImgurClient("API KEY"); var endpoint = new AlbumEndpoint(client); var album = await endpoint.GetAlbumAsync(albumID); Console.WriteLine("REMAIN: " + client.RateLimit.ClientRemaining); Random _rand = new Random(); var tmpArray = album.Images.ToArray(); var finalimg = tmpArray[(_rand.Next(0, tmpArray.Length))].Link; Console.WriteLine("TEST WORK COMPLETTE " + finalimg); }
/// <summary> /// Provides a list or URLs for each image in an imgur album, or null if not possible /// </summary> /// <param name="albumUrl">URL of imgur album</param> /// <returns>List or URLs, or null</returns> public List <string> GetImgurAlbum(string albumUrl) { try { var albumId = albumUrl.Replace(@"/gallery/", @"/a/").Substring(albumUrl.IndexOf(@"/a/", StringComparison.Ordinal) + 3); var client = new ImgurClient(RSettings.ProgramSettings.ImgurApi); var endpoint = new AlbumEndpoint(client); var images = endpoint.GetAlbumAsync(albumId).Result.Images.Select(i => i.Link).ToList(); _ = _log.LogMessage("Getting Imgur Info from Imgur API" + $"\nAlbum URL: {albumUrl}" + $"\nAlbum ID: {albumId}" + $"\nClient Credits Remaining: {client.RateLimit.ClientRemaining} of {client.RateLimit.ClientLimit}" + $"\nImages Found:\n{string.Join("\n", images)}", false, color: LOG_COLOR); return(images); } catch { return(null); } }
public async Task <IEnumerable <IImage> > GetImgurImageAsync(string id, CancellationToken token) { try { token.ThrowIfCancellationRequested(); var error = string.Empty; //TODO:: Move to config // Given this is using entirely anonymous calls, there is no reason to keep the id and secret...well, a secret. // If this ever becomes popular, and we want to make authenticated calls; then I will register a new client for that purpose. var client = new ImgurClient("5b7f2dbb306592e", "c6321d265e604df392cabd1c1d1fd5002bb918f0"); var albumEndpoint = new AlbumEndpoint(client); try { var album = await albumEndpoint.GetAlbumAsync(id); if (album != null) { return(album.Images); } } catch (Exception e) { error = e.Message; } token.ThrowIfCancellationRequested(); var imageEndpoint = new ImageEndpoint(client); try { var image = await imageEndpoint.GetImageAsync(id); if (image != null) { return new List <IImage> { image } } ; } catch (Exception e) { error = error + e.Message; } if (!string.IsNullOrWhiteSpace(error)) { Log.Error(error); } return(new List <IImage>()); } catch (ImgurException imgurEx) { Log.Error("An error occurred getting an image from Imgur."); Log.Error(imgurEx.Message); return(null); } }
public async Task GetAlbumAsync_WithIdNull_ThrowsArgumentNullException() { var client = new ImgurClient("123", "1234"); var endpoint = new AlbumEndpoint(client); await endpoint.GetAlbumAsync(null); }
public async Task Sync(object context) { if (!Synchronize) { return; } await Task.Run(async() => { // get local files FileInfo[] local = new DirectoryInfo(Root).GetFiles().Where(it => new string[] { ".jpg", ".gif", ".png", ".bmp" }.Contains(it.Extension.ToLowerInvariant())).ToArray(); // get remote files AlbumEndpoint endpoint = new AlbumEndpoint(await ImgurHelper.GetClient()); ImgurAlbum = await endpoint.GetAlbumAsync(Id); bool owned = (await ImgurHelper.GetToken()).AccountId == ImgurAlbum.AccountId.ToString(); // (A) filter for files only in local (not in remote) FileInfo[] onlyLocal = local.Where(l => !ImgurAlbum.Images.Select(r => new Image(r)).Any(r => r.FileName == l.Name)).ToArray(); // (B) filter for files only in remote (not in local) Image[] onlyRemote = ImgurAlbum.Images.Select(r => new Image(r)).Where(r => !local.Any(l => r.FileName == l.Name)).ToArray(); if (owned) //own album { // upload files (A) where not in json FileInfo[] upload = onlyLocal.Where(l => !Images.Any(i => i == l.Name)).ToArray(); foreach (FileInfo img in upload) { Image image = new Image(); image.Name = Path.GetFileNameWithoutExtension(img.Name); image.Link = img.Name; await image.Upload(this); } // download files (B) where not in json Image[] download = onlyRemote.Where(r => !Images.Any(i => i == r.FileName)).ToArray(); foreach (Image img in download) { await img.Download(this); } // delete files (A) from local where in json if (Properties.Settings.Default.DeleteLocalImage) { FileInfo[] deleteLocal = onlyLocal.Where(l => Images.Any(i => i == l.Name)).ToArray(); foreach (FileInfo img in deleteLocal) { bool ok = true; if (Properties.Settings.Default.AskDeleteLocalImage) { MessageDialogResult result = await DialogCoordinator.Instance.ShowMessageAsync(context, "Delete local image?", img.FullName, MessageDialogStyle.AffirmativeAndNegative); ok = result == MessageDialogResult.Affirmative; } if (ok) { File.Delete(img.FullName); } } } // delete files (B) from remote where in json if (Properties.Settings.Default.DeleteRemoteImage) { Image[] deleteRemote = onlyRemote.Where(r => Images.Any(i => i == r.FileName)).ToArray(); foreach (Image img in deleteRemote) { bool ok = true; if (Properties.Settings.Default.AskDeleteRemoteImage) { MessageDialogResult result = await DialogCoordinator.Instance.ShowMessageAsync(context, "Delete Imgur image?", img.Name, MessageDialogStyle.AffirmativeAndNegative); ok = result == MessageDialogResult.Affirmative; } if (ok) { await img.Delete(); } } } } else //not own album { // remove files (A) if (Properties.Settings.Default.DeleteLocalImage) { foreach (FileInfo img in onlyLocal) { bool ok = true; if (Properties.Settings.Default.AskDeleteLocalImage) { MessageDialogResult result = await DialogCoordinator.Instance.ShowMessageAsync(context, "Delete local image?", img.FullName, MessageDialogStyle.AffirmativeAndNegative); ok = result == MessageDialogResult.Affirmative; } if (ok) { File.Delete(img.FullName); } } } // download files (B) foreach (Image img in onlyRemote) { await img.Download(this); } } // update json string[] images = new DirectoryInfo(Root).GetFiles().Where(it => new string[] { ".jpg", ".gif", ".png", ".bmp" }.Contains(it.Extension.ToLowerInvariant())).Select(it => it.Name).ToArray(); App.Current.Dispatcher.Invoke((Action) delegate { Images.Clear(); foreach (string img in images) { Images.Add(img); } }); Save(); }); }
public async Task <IActionResult> UploadFile(string type = "image") { await CheckIsSignoutedAsync(); // Get file Upload from HttpRequest FormData FileModel postedFile = Request.File(); // Check has file if (postedFile == null) { throw new ApiException("File không tồn tại, Vui lòng chọn lại file!", (int)HttpStatusCode.BadRequest); } // is upload image if (type == "image") { postedFile.Name = "image"; // Extention image if (!AcceptedImageFormats.MineTypes.Contains(postedFile.ContentType.ToLower())) { throw new ApiException($"File chỉ hỗ trợ định dạng {string.Join(",", AcceptedImageFormats.MineTypes)}", (int)HttpStatusCode.BadRequest); } // Photo FileSize Upto 10 MB if (postedFile.Length > 10 * 1024 * 1024) { throw new ApiException("Dung lượng file ảnh không được vượt quá 10 MB!", (int)HttpStatusCode.BadRequest); } } // is upload video else if (type == "video") { postedFile.Name = "video"; // Extention Video if (!AcceptedVideoFormats.MineTypes.Contains(postedFile.ContentType.ToLower())) { throw new ApiException($"File chỉ hỗ trợ định dạng {string.Join(",", AcceptedVideoFormats.MineTypes)}", (int)HttpStatusCode.BadRequest); } // Photo FileSize Upto 10 MB if (postedFile.Length > 200 * 1024 * 1024) { throw new ApiException("Dung lượng file video không được vượt quá 200 MB!", (int)HttpStatusCode.BadRequest); } } // not support media type else { throw new ApiException("not support media type", (int)HttpStatusCode.BadRequest); } // Save postedFile to ImgUr API try { var client = new ImgurClient(this.imgUrUploadSettings.ClientID, this.imgUrUploadSettings.ClientSecret); // state=#access_token=d9cb9143c19c67696e26f4ac59b2f7424af7650c&expires_in=315360000&token_type=bearer&refresh_token=ddd479acc0fa1b91b099599f864ac0a9afa82801&account_username=ngnamB&account_id=96736173 var token = new OAuth2Token( accessToken: "d9cb9143c19c67696e26f4ac59b2f7424af7650c", refreshToken: "ddd479acc0fa1b91b099599f864ac0a9afa82801", tokenType: "bearer", accountId: "96736173", accountUsername: "******", expiresIn: 315360000); //var endpoint = new OAuth2Endpoint(client); //var token = endpoint.GetTokenByRefreshTokenAsync("REFRESH_TOKEN"); client.SetOAuth2Token(token); var albumEndpoint = new AlbumEndpoint(client); // https://imgur.com/a/Dsoqayj IAlbum album = await albumEndpoint.GetAlbumAsync("Dsoqayj"); var imageEndpoint = new ImageEndpoint(client); IImage imageOrVideo = await imageEndpoint.UploadImageBinaryAsync(image : postedFile.Bytes, albumId : album.Id); //Debug.Write("Image retrieved. Image Url: " + image.Link); return(Ok(imageOrVideo)); } catch (ImgurException imgurEx) { _logger.LogError("UploadFile---", imgurEx); #if !DEBUG throw new ApiException("An error occurred getting an image from Imgur."); #else throw new ApiException(imgurEx); #endif } }
static void Main(string[] args) { if (args.Length == 0) { StringBuilder syntax = new StringBuilder(); syntax.Append("wimgur, a wallhaven / imgur album downloader"); syntax.Append(Environment.NewLine); syntax.Append("syntax: wallhaven [parameters]"); syntax.Append(Environment.NewLine); syntax.Append("parameters qualify as following: website,search"); syntax.Append(Environment.NewLine); syntax.Append("there can be multiple parameters"); syntax.Append(Environment.NewLine); syntax.Append("website = either wallhaven or imgur, capitalization doesn't matter"); syntax.Append(Environment.NewLine); syntax.Append("search = any valid search on wallhaven, or any valid album on imgur"); syntax.Append(Environment.NewLine); Console.WriteLine(syntax.ToString()); args = Console.ReadLine().Split(' '); } using (WebClient wc = new WebClient()) { foreach (string s in args.Where(o => o.ToLower().Contains("wallhaven"))) { string search = s.Split(',')[1]; if (search.StartsWith("id:")) { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(wc.DownloadString($"https://alpha.wallhaven.cc/tag/{ search.Split(new string[] { "id:" }, StringSplitOptions.None)[1] }")); search = doc.DocumentNode.Descendants("h1").FirstOrDefault(o => o.HasClass("tagname")).InnerText; } Directory.CreateDirectory(search); int i = 1; while (true) { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(wc.DownloadString($"https://alpha.wallhaven.cc/search?q={ search }&page={ i }")); doc.Save("TEMP1.html"); IEnumerable <HtmlNode> list = doc.DocumentNode.SelectNodes("//*[contains(@class,'preview')]") ?? new List <HtmlNode>().AsEnumerable(); if (list.Count() == 0) { break; } foreach (HtmlNode link in list) { doc.LoadHtml(wc.DownloadString(link.Attributes["href"].Value)); doc.Save("TEMP2.html"); HtmlNode picture = doc.DocumentNode.SelectSingleNode("//img[contains(@id,'wallpaper')]"); string pictureLink = "https:" + picture.Attributes["src"].Value; string pictureName = pictureLink.Replace("https://wallpapers.wallhaven.cc/wallpapers/full/", ""); wc.DownloadFile(pictureLink, search + "\\" + pictureName); Console.WriteLine(pictureName); } i++; } } File.Delete("TEMP1.html"); File.Delete("TEMP2.html"); foreach (string s in args.Where(o => o.ToLower().Contains("imgur"))) { string search = s.Split(',')[1]; Directory.CreateDirectory(search); var client = new ImgurClient("569dfa57bdec8ec"); var endpoint = new AlbumEndpoint(client); var album = endpoint.GetAlbumAsync(search).GetAwaiter().GetResult(); foreach (Image img in album.Images) { string name = img.Id + MimeTypeMap.List.MimeTypeMap.GetExtension(img.Type).FirstOrDefault(); wc.DownloadFile(img.Link, search + "\\" + name); Console.WriteLine(name); } } } if (args.FirstOrDefault().Contains("merge")) { string dirname = string.Join(" ", args).Split(',').LastOrDefault(); DirectoryInfo di = Directory.CreateDirectory(dirname); DirectoryInfo current = new DirectoryInfo(Environment.CurrentDirectory); foreach (FileInfo fi in current.GetFiles("*.*", SearchOption.AllDirectories).Where(o => o.FullName != AppDomain.CurrentDomain.BaseDirectory)) { fi.MoveTo(di.FullName + "\\" + fi.Name); } foreach (DirectoryInfo dir in current.GetDirectories().Where(o => o.Name != di.Name)) { dir.Delete(); } } }