PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/BaconographyWP8Core/PlatformServices/ImageAPI/Imgur.cs

https://github.com/hippiehunter/Baconography
C# | 120 lines | 103 code | 14 blank | 3 comment | 26 complexity | 6ce357054a86e49a03ff5dd996eac883 MD5 | raw file
  1. using BaconographyWP8.PlatformServices;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading.Tasks;
  13. namespace Baconography.PlatformServices.ImageAPI
  14. {
  15. class Imgur
  16. {
  17. //Transliterated from Reddit Enhancement Suite https://github.com/honestbleeps/Reddit-Enhancement-Suite/blob/master/lib/reddit_enhancement_suite.user.js
  18. private static Regex hashRe = new Regex(@"^https?:\/\/(?:[i.]|[edge.]|[www.])*imgur.com\/(?:gallery\/)?(?:r\/[\w]+\/)?([\w]{5,}(?:[&,][\w]{5,})*)(\.[\w]{3,4})?(?:#(\d*))?(?:\?(?:\d*))?$");
  19. private static Regex albumHashRe = new Regex(@"^https?:\/\/(?:i\.)?imgur.com\/a\/([\w]+)(\..+)?(?:\/)?(?:#\w*)?$");
  20. private static string apiPrefix = "http://api.imgur.com/2/";
  21. internal static bool IsAPI(Uri uri)
  22. {
  23. var href = uri.OriginalString;
  24. var groups = hashRe.Match(href).Groups;
  25. GroupCollection albumGroups = null;
  26. if (groups.Count == 0 || (groups.Count > 0 && string.IsNullOrWhiteSpace(groups[0].Value)))
  27. albumGroups = albumHashRe.Match(href).Groups;
  28. return (albumGroups != null && albumGroups.Count > 2 && string.IsNullOrWhiteSpace(albumGroups[2].Value));
  29. }
  30. internal static async Task<IEnumerable<Tuple<string, string>>> GetImagesFromUri(string title, Uri uri)
  31. {
  32. var href = uri.OriginalString;
  33. var groups = hashRe.Match(href).Groups;
  34. GroupCollection albumGroups = null;
  35. if (groups.Count == 0 || (groups.Count > 0 && string.IsNullOrWhiteSpace(groups[0].Value)))
  36. albumGroups = albumHashRe.Match(href).Groups;
  37. if (groups.Count > 2 && string.IsNullOrWhiteSpace(groups[2].Value))
  38. {
  39. if (Regex.IsMatch(groups[1].Value, "[&,]"))
  40. {
  41. var hashes = Regex.Split(groups[1].Value, "[&,]");
  42. //Imgur doesn't really care about the extension and the browsers don't seem to either.
  43. return hashes
  44. .Select(hash => Tuple.Create(title, string.Format("http://i.imgur.com/{0}.gif", hash)));
  45. }
  46. else
  47. {
  48. if (uri.AbsolutePath.ToLower().StartsWith("/gallery"))
  49. {
  50. return await GetImagesFromUri(title, new Uri("http://imgur.com/a/" + groups[1].Value));
  51. }
  52. else
  53. {
  54. //Imgur doesn't really care about the extension and the browsers don't seem to either.
  55. return new Tuple<string, string>[] { Tuple.Create(title, string.Format("http://i.imgur.com/{0}.gif", groups[1].Value)) };
  56. }
  57. }
  58. }
  59. else if (albumGroups.Count > 2 && string.IsNullOrWhiteSpace(albumGroups[2].Value))
  60. {
  61. var apiURL = string.Format("{0}album/{1}.json", apiPrefix, albumGroups[1].Value);
  62. var request = HttpWebRequest.CreateHttp(apiURL);
  63. string jsonResult = null;
  64. using (var response = (await SimpleHttpService.GetResponseAsync(request)))
  65. {
  66. if (response != null)
  67. {
  68. jsonResult = await Task<string>.Run(() =>
  69. {
  70. using (var sr = new StreamReader(response.GetResponseStream()))
  71. {
  72. return sr.ReadToEnd();
  73. }
  74. });
  75. }
  76. }
  77. if(string.IsNullOrWhiteSpace(jsonResult))
  78. return Enumerable.Empty<Tuple<string, string>>();
  79. var result = JsonConvert.DeserializeObject(jsonResult) as JObject;
  80. if (result != null && result.HasValues)
  81. {
  82. JToken errorToken;
  83. if (result.TryGetValue("error", out errorToken))
  84. {
  85. return Enumerable.Empty<Tuple<string, string>>();
  86. }
  87. var albumTitleElement = (string)((JObject)result.GetValue("album")).GetValue("title");
  88. var albumTitle = string.IsNullOrWhiteSpace(albumTitleElement) ? title : albumTitleElement;
  89. return ((IEnumerable)((JObject)result.GetValue("album")).GetValue("images"))
  90. .Cast<JObject>()
  91. .Select(e =>
  92. {
  93. var caption = (string)((JObject)e.GetValue("image")).GetValue("caption");
  94. if (!string.IsNullOrWhiteSpace(caption))
  95. caption = caption.Replace("&#039;", "'").Replace("&#038;", "&").Replace("&#034;", "\"");
  96. return Tuple.Create(string.IsNullOrWhiteSpace(caption) ? albumTitle : caption, (string)((JObject)e.GetValue("links")).GetValue("original"));
  97. });
  98. }
  99. else
  100. return Enumerable.Empty<Tuple<string, string>>();
  101. }
  102. else
  103. return Enumerable.Empty<Tuple<string, string>>();
  104. }
  105. }
  106. }