PageRenderTime 23ms CodeModel.GetById 11ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 1ms

/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
  1using BaconographyWP8.PlatformServices;
  2using Newtonsoft.Json;
  3using Newtonsoft.Json.Linq;
  4using System;
  5using System.Collections;
  6using System.Collections.Generic;
  7using System.IO;
  8using System.Linq;
  9using System.Net;
 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\/(?:gallery\/)?(?:r\/[\w]+\/)?([\w]{5,}(?:[&,][\w]{5,})*)(\.[\w]{3,4})?(?:#(\d*))?(?:\?(?:\d*))?$");
 20        private static Regex albumHashRe = new Regex(@"^https?:\/\/(?:i\.)?imgur.com\/a\/([\w]+)(\..+)?(?:\/)?(?:#\w*)?$");
 21        private static string apiPrefix = "http://api.imgur.com/2/";
 22
 23        internal static bool IsAPI(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            return (albumGroups != null && albumGroups.Count > 2 && string.IsNullOrWhiteSpace(albumGroups[2].Value));
 33        }
 34
 35        internal static async Task<IEnumerable<Tuple<string, string>>> GetImagesFromUri(string title, Uri uri)
 36        {
 37            var href = uri.OriginalString;
 38            var groups = hashRe.Match(href).Groups;
 39            GroupCollection albumGroups = null;
 40
 41            if (groups.Count == 0 || (groups.Count > 0 && string.IsNullOrWhiteSpace(groups[0].Value)))
 42                albumGroups = albumHashRe.Match(href).Groups;
 43
 44            if (groups.Count > 2 && string.IsNullOrWhiteSpace(groups[2].Value))
 45            {
 46                if (Regex.IsMatch(groups[1].Value, "[&,]"))
 47                {
 48                    var hashes = Regex.Split(groups[1].Value, "[&,]");
 49                    //Imgur doesn't really care about the extension and the browsers don't seem to either.
 50                    return hashes
 51                        .Select(hash => Tuple.Create(title, string.Format("http://i.imgur.com/{0}.gif", hash)));
 52
 53                }
 54                else
 55                {
 56                    if (uri.AbsolutePath.ToLower().StartsWith("/gallery"))
 57                    {
 58                        return await GetImagesFromUri(title, new Uri("http://imgur.com/a/" + groups[1].Value));
 59                    }
 60                    else
 61                    {
 62                        //Imgur doesn't really care about the extension and the browsers don't seem to either.
 63                        return new Tuple<string, string>[] { Tuple.Create(title, string.Format("http://i.imgur.com/{0}.gif", groups[1].Value)) };
 64                    }
 65                }
 66            }
 67            else if (albumGroups.Count > 2 && string.IsNullOrWhiteSpace(albumGroups[2].Value))
 68            {
 69                var apiURL = string.Format("{0}album/{1}.json", apiPrefix, albumGroups[1].Value);
 70                var request = HttpWebRequest.CreateHttp(apiURL);
 71                string jsonResult = null;
 72                using (var response = (await SimpleHttpService.GetResponseAsync(request)))
 73                {
 74                    if (response != null)
 75                    {
 76                        jsonResult = await Task<string>.Run(() =>
 77                        {
 78                            using (var sr = new StreamReader(response.GetResponseStream()))
 79                            {
 80                                return sr.ReadToEnd();
 81                            }
 82                        });
 83                    }
 84                }
 85
 86                if(string.IsNullOrWhiteSpace(jsonResult))
 87                    return Enumerable.Empty<Tuple<string, string>>();
 88
 89                var result = JsonConvert.DeserializeObject(jsonResult) as JObject;
 90                if (result != null && result.HasValues)
 91                {
 92                    JToken errorToken;
 93                    if (result.TryGetValue("error", out errorToken))
 94                    {
 95                        return Enumerable.Empty<Tuple<string, string>>();
 96                    }
 97
 98                    var albumTitleElement = (string)((JObject)result.GetValue("album")).GetValue("title");
 99                    var albumTitle = string.IsNullOrWhiteSpace(albumTitleElement) ? title : albumTitleElement;
100
101                    return ((IEnumerable)((JObject)result.GetValue("album")).GetValue("images"))
102                        .Cast<JObject>()
103                        .Select(e => 
104                            {
105                                var caption = (string)((JObject)e.GetValue("image")).GetValue("caption");
106
107                                if (!string.IsNullOrWhiteSpace(caption))
108                                    caption = caption.Replace("&#039;", "'").Replace("&#038;", "&").Replace("&#034;", "\"");
109
110                                return Tuple.Create(string.IsNullOrWhiteSpace(caption) ? albumTitle : caption, (string)((JObject)e.GetValue("links")).GetValue("original"));
111                            });
112                }
113                else
114                    return Enumerable.Empty<Tuple<string, string>>();
115            }
116            else
117                return Enumerable.Empty<Tuple<string, string>>();
118        }
119    }
120}