PageRenderTime 21ms CodeModel.GetById 7ms app.highlight 3ms RepoModel.GetById 9ms app.codeStats 0ms

/BaconographyW8Core/PlatformServices/ImageAPI/Imgur.cs

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