Exemplo n.º 1
0
        public static void DeleteImgurImage(ImgurInfo imgurInfo)
        {
            LOG.InfoFormat("Deleting Imgur image for {0}", imgurInfo.DeleteHash);

            try {
                string url = config.ImgurApiUrl + "/delete/" + imgurInfo.DeleteHash;
                HttpWebRequest webRequest = (HttpWebRequest)NetworkHelper.CreateWebRequest(url);

                //webRequest.Method = "DELETE";
                webRequest.Method = "GET";
                webRequest.ServicePoint.Expect100Continue = false;

                string responseString;
                using (WebResponse response = webRequest.GetResponse()) {
                    LogCredits(response);
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) {
                        responseString = reader.ReadToEnd();
                    }
                }
                LOG.InfoFormat("Delete result: {0}", responseString);
            } catch (WebException wE) {
                // Allow "Bad request" this means we already deleted it
                if (wE.Status == WebExceptionStatus.ProtocolError) {
                    if (((HttpWebResponse)wE.Response).StatusCode != HttpStatusCode.BadRequest) {
                        throw ;
                    }
                }
            }
            // Make sure we remove it from the history, if no error occured
            config.runtimeImgurHistory.Remove(imgurInfo.Hash);
            config.ImgurUploadHistory.Remove(imgurInfo.Hash);
            imgurInfo.Image = null;
        }
Exemplo n.º 2
0
        private void ClipboardButtonClick(object sender, EventArgs e)
        {
            StringBuilder links = new StringBuilder();

            if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0)
            {
                for (int i = 0; i < listview_imgur_uploads.SelectedItems.Count; i++)
                {
                    ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[i].Tag;
                    if (config.UsePageLink)
                    {
                        links.AppendLine(imgurInfo.Page);
                    }
                    else
                    {
                        links.AppendLine(imgurInfo.Original);
                    }
                }
            }
            ClipboardHelper.SetClipboardData(links.ToString());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Retrieve the thumbnail of an imgur image
        /// </summary>
        /// <param name="imgurInfo"></param>
        public static void RetrieveImgurThumbnail(ImgurInfo imgurInfo)
        {
            if (imgurInfo.SmallSquare == null)
            {
                Log.Warn("Imgur URL was null, not retrieving thumbnail.");
                return;
            }
            Log.InfoFormat("Retrieving Imgur image for {0} with url {1}", imgurInfo.Hash, imgurInfo.SmallSquare);
            HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(string.Format(SmallUrlPattern, imgurInfo.Hash), HTTPMethod.GET);

            webRequest.ServicePoint.Expect100Continue = false;
            // Not for getting the thumbnail, in anonymous modus
            //SetClientId(webRequest);
            using (WebResponse response = webRequest.GetResponse()) {
                LogRateLimitInfo(response);
                Stream responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    imgurInfo.Image = ImageHelper.FromStream(responseStream);
                }
            }
        }
Exemplo n.º 4
0
 private void Listview_imgur_uploadsSelectedIndexChanged(object sender, EventArgs e)
 {
     pictureBox1.Image = pictureBox1.ErrorImage;
     if (listview_imgur_uploads.SelectedItems.Count > 0)
     {
         deleteButton.Enabled    = true;
         openButton.Enabled      = true;
         clipboardButton.Enabled = true;
         if (listview_imgur_uploads.SelectedItems.Count == 1)
         {
             ImgurInfo imgurInfo = (ImgurInfo)listview_imgur_uploads.SelectedItems[0].Tag;
             pictureBox1.Image = imgurInfo.Image;
         }
     }
     else
     {
         pictureBox1.Image       = pictureBox1.ErrorImage;
         deleteButton.Enabled    = false;
         openButton.Enabled      = false;
         clipboardButton.Enabled = false;
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Delete an imgur image, this is done by specifying the delete hash
        /// </summary>
        /// <param name="imgurInfo"></param>
        public static void DeleteImgurImage(ImgurInfo imgurInfo)
        {
            Log.InfoFormat("Deleting Imgur image for {0}", imgurInfo.DeleteHash);

            try {
                string         url        = Config.ImgurApi3Url + "/image/" + imgurInfo.DeleteHash + ".xml";
                HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.DELETE);
                webRequest.ServicePoint.Expect100Continue = false;
                SetClientId(webRequest);
                string responseString = null;
                using (WebResponse response = webRequest.GetResponse()) {
                    LogRateLimitInfo(response);
                    var responseStream = response.GetResponseStream();
                    if (responseStream != null)
                    {
                        using (StreamReader reader = new StreamReader(responseStream, true))
                        {
                            responseString = reader.ReadToEnd();
                        }
                    }
                }
                Log.InfoFormat("Delete result: {0}", responseString);
            } catch (WebException wE) {
                // Allow "Bad request" this means we already deleted it
                if (wE.Status == WebExceptionStatus.ProtocolError)
                {
                    if (((HttpWebResponse)wE.Response).StatusCode != HttpStatusCode.BadRequest)
                    {
                        throw;
                    }
                }
            }
            // Make sure we remove it from the history, if no error occured
            Config.runtimeImgurHistory.Remove(imgurInfo.Hash);
            Config.ImgurUploadHistory.Remove(imgurInfo.Hash);
            imgurInfo.Image = null;
        }
Exemplo n.º 6
0
		/// <summary>
		/// Retrieve the thumbnail of an imgur image
		/// </summary>
		/// <param name="imgurInfo"></param>
		public static void RetrieveImgurThumbnail(ImgurInfo imgurInfo) {
			if (imgurInfo.SmallSquare == null) {
				LOG.Warn("Imgur URL was null, not retrieving thumbnail.");
				return;
			}
			LOG.InfoFormat("Retrieving Imgur image for {0} with url {1}", imgurInfo.Hash, imgurInfo.SmallSquare);
			HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(string.Format(SmallUrlPattern, imgurInfo.Hash), HTTPMethod.GET);
			webRequest.ServicePoint.Expect100Continue = false;
			SetClientId(webRequest);
			using (WebResponse response = webRequest.GetResponse()) {
				LogRateLimitInfo(response);
				Stream responseStream = response.GetResponseStream();
				if (responseStream != null)
				{
					imgurInfo.Image = Image.FromStream(responseStream);
				}
			}
		}
Exemplo n.º 7
0
        public static void RetrieveImgurThumbnail(ImgurInfo imgurInfo)
        {
            if (imgurInfo.SmallSquare == null) {
                LOG.Warn("Imgur URL was null, not retrieving thumbnail.");
                return;
            }
            LOG.InfoFormat("Retrieving Imgur image for {0} with url {1}", imgurInfo.Hash, imgurInfo.SmallSquare);
            HttpWebRequest webRequest = (HttpWebRequest)NetworkHelper.CreateWebRequest(imgurInfo.SmallSquare);
            webRequest.Method = "GET";
            webRequest.ServicePoint.Expect100Continue = false;

            using (WebResponse response = webRequest.GetResponse()) {
                LogCredits(response);
                Stream responseStream = response.GetResponseStream();
                imgurInfo.Image = Image.FromStream(responseStream);
            }
            return;
        }
Exemplo n.º 8
0
		public static ImgurInfo ParseResponse(string response) {
			LOG.Debug(response);
			// This is actually a hack for BUG-1695
			// The problem is the (C) sign, we send it HTML encoded "&reg;" to Imgur and get it HTML encoded in the XML back 
			// Added all the encodings I found quickly, I guess these are not all... but it should fix the issue for now.
			response = response.Replace("&cent;", "&#162;");
			response = response.Replace("&pound;", "&#163;");
			response = response.Replace("&yen;", "&#165;");
			response = response.Replace("&euro;", "&#8364;");
			response = response.Replace("&copy;", "&#169;");
			response = response.Replace("&reg;", "&#174;");

			ImgurInfo imgurInfo = new ImgurInfo();
			try {
				XmlDocument doc = new XmlDocument();
				doc.LoadXml(response);
				XmlNodeList nodes = doc.GetElementsByTagName("id");
				if(nodes.Count > 0) {
					imgurInfo.Hash = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("hash");
				if (nodes.Count > 0)
				{
					imgurInfo.Hash = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("deletehash");
				if(nodes.Count > 0) {
					imgurInfo.DeleteHash = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("type");
				if(nodes.Count > 0) {
					imgurInfo.ImageType = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("title");
				if(nodes.Count > 0) {
					imgurInfo.Title = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("datetime");
				if(nodes.Count > 0) {
					// Version 3 has seconds since Epoch
					double secondsSince;
					if (double.TryParse(nodes.Item(0).InnerText, out secondsSince))
					{
						var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
						imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime;
					}
				}
				nodes = doc.GetElementsByTagName("original");
				if (nodes.Count > 0)
				{
					imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:");
				}
				// Version 3 API only has Link
				nodes = doc.GetElementsByTagName("link");
				if (nodes.Count > 0)
				{
					imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:");
				}
				nodes = doc.GetElementsByTagName("imgur_page");
				if (nodes.Count > 0)
				{
					imgurInfo.Page = nodes.Item(0).InnerText.Replace("http:", "https:");
				}
				else
				{
					// Version 3 doesn't have a page link in the response
					imgurInfo.Page = string.Format("https://imgur.com/{0}", imgurInfo.Hash);
				}
				nodes = doc.GetElementsByTagName("small_square");
				if(nodes.Count > 0) {
					imgurInfo.SmallSquare = nodes.Item(0).InnerText;
				}
				nodes = doc.GetElementsByTagName("large_thumbnail");
				if(nodes.Count > 0)
				{
                    imgurInfo.LargeThumbnail = nodes.Item(0).InnerText.Replace("http:", "https:");
				}
			} catch(Exception e) {
				LOG.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
			}
			return imgurInfo;
		}
Exemplo n.º 9
0
        public static void LoadHistory()
        {
            if (config.runtimeImgurHistory.Count == config.ImgurUploadHistory.Count)
            {
                return;
            }
            // Load the ImUr history
            List <string> hashes = new List <string>();

            foreach (string hash in config.ImgurUploadHistory.Keys)
            {
                hashes.Add(hash);
            }

            bool saveNeeded = false;

            foreach (string hash in hashes)
            {
                if (config.runtimeImgurHistory.ContainsKey(hash))
                {
                    // Already loaded
                    continue;
                }
                try {
                    ImgurInfo imgurInfo = ImgurUtils.RetrieveImgurInfo(hash, config.ImgurUploadHistory[hash]);
                    if (imgurInfo != null)
                    {
                        ImgurUtils.RetrieveImgurThumbnail(imgurInfo);
                        config.runtimeImgurHistory.Add(hash, imgurInfo);
                    }
                    else
                    {
                        LOG.DebugFormat("Deleting not found ImgUr {0} from config.", hash);
                        config.ImgurUploadHistory.Remove(hash);
                        saveNeeded = true;
                    }
                } catch (WebException wE) {
                    bool redirected = false;
                    if (wE.Status == WebExceptionStatus.ProtocolError)
                    {
                        HttpWebResponse response = ((HttpWebResponse)wE.Response);
                        // Image no longer available
                        if (response.StatusCode == HttpStatusCode.Redirect)
                        {
                            LOG.InfoFormat("ImgUr image for hash {0} is no longer available", hash);
                            config.ImgurUploadHistory.Remove(hash);
                            redirected = true;
                        }
                    }
                    if (!redirected)
                    {
                        LOG.Error("Problem loading ImgUr history for hash " + hash, wE);
                    }
                } catch (Exception e) {
                    LOG.Error("Problem loading ImgUr history for hash " + hash, e);
                }
            }
            if (saveNeeded)
            {
                // Save needed changes
                IniConfig.Save();
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Do the actual upload to Imgur
        /// For more details on the available parameters, see: http://api.imgur.com/resources_anon
        /// </summary>
        /// <param name="surfaceToUpload">ISurface to upload</param>
        /// <param name="outputSettings">OutputSettings for the image file format</param>
        /// <param name="title">Title</param>
        /// <param name="filename">Filename</param>
        /// <returns>ImgurInfo with details</returns>
        public static ImgurInfo UploadToImgur(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename)
        {
            IDictionary <string, object> uploadParameters = new Dictionary <string, object>();
            IDictionary <string, object> otherParameters  = new Dictionary <string, object>();

            // add title
            if (title != null && config.AddTitle)
            {
                otherParameters.Add("title", title);
            }
            // add filename
            if (filename != null && config.AddFilename)
            {
                otherParameters.Add("name", filename);
            }
            string responseString = null;

            if (config.AnonymousAccess)
            {
                // add key, we only use the other parameters for the AnonymousAccess
                otherParameters.Add("key", IMGUR_ANONYMOUS_API_KEY);
                HttpWebRequest webRequest = (HttpWebRequest)NetworkHelper.CreateWebRequest(config.ImgurApiUrl + "/upload.xml?" + NetworkHelper.GenerateQueryParameters(otherParameters));
                webRequest.Method      = "POST";
                webRequest.ContentType = "image/" + outputSettings.Format.ToString();
                webRequest.ServicePoint.Expect100Continue = false;
                try {
                    using (var requestStream = webRequest.GetRequestStream()) {
                        ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings);
                    }

                    using (WebResponse response = webRequest.GetResponse()) {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) {
                            responseString = reader.ReadToEnd();
                        }
                        LogCredits(response);
                    }
                } catch (Exception ex) {
                    LOG.Error("Upload to imgur gave an exeption: ", ex);
                    throw;
                }
            }
            else
            {
                OAuthSession oAuth = new OAuthSession(ImgurCredentials.CONSUMER_KEY, ImgurCredentials.CONSUMER_SECRET);
                oAuth.BrowserSize     = new Size(650, 500);
                oAuth.CallbackUrl     = "http://getgreenshot.org";
                oAuth.AccessTokenUrl  = "http://api.imgur.com/oauth/access_token";
                oAuth.AuthorizeUrl    = "http://api.imgur.com/oauth/authorize";
                oAuth.RequestTokenUrl = "http://api.imgur.com/oauth/request_token";
                oAuth.LoginTitle      = "Imgur authorization";
                oAuth.Token           = config.ImgurToken;
                oAuth.TokenSecret     = config.ImgurTokenSecret;
                if (string.IsNullOrEmpty(oAuth.Token))
                {
                    if (!oAuth.Authorize())
                    {
                        return(null);
                    }
                    if (!string.IsNullOrEmpty(oAuth.Token))
                    {
                        config.ImgurToken = oAuth.Token;
                    }
                    if (!string.IsNullOrEmpty(oAuth.TokenSecret))
                    {
                        config.ImgurTokenSecret = oAuth.TokenSecret;
                    }
                    IniConfig.Save();
                }
                try {
                    otherParameters.Add("image", new SurfaceContainer(surfaceToUpload, outputSettings, filename));
                    responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, "http://api.imgur.com/2/account/images.xml", uploadParameters, otherParameters, null);
                } catch (Exception ex) {
                    LOG.Error("Upload to imgur gave an exeption: ", ex);
                    throw;
                } finally {
                    if (oAuth.Token != null)
                    {
                        config.ImgurToken = oAuth.Token;
                    }
                    if (oAuth.TokenSecret != null)
                    {
                        config.ImgurTokenSecret = oAuth.TokenSecret;
                    }
                    IniConfig.Save();
                }
            }
            return(ImgurInfo.ParseResponse(responseString));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Load the complete history of the imgur uploads, with the corresponding information
        /// </summary>
        public static void LoadHistory()
        {
            if (!IsHistoryLoadingNeeded())
            {
                return;
            }

            bool saveNeeded = false;

            // Load the ImUr history
            foreach (string hash in Config.ImgurUploadHistory.Keys.ToList())
            {
                if (Config.runtimeImgurHistory.ContainsKey(hash))
                {
                    // Already loaded
                    continue;
                }

                try
                {
                    var       deleteHash = Config.ImgurUploadHistory[hash];
                    ImgurInfo imgurInfo  = RetrieveImgurInfo(hash, deleteHash);
                    if (imgurInfo != null)
                    {
                        RetrieveImgurThumbnail(imgurInfo);
                        Config.runtimeImgurHistory[hash] = imgurInfo;
                    }
                    else
                    {
                        Log.InfoFormat("Deleting unknown ImgUr {0} from config, delete hash was {1}.", hash, deleteHash);
                        Config.ImgurUploadHistory.Remove(hash);
                        Config.runtimeImgurHistory.Remove(hash);
                        saveNeeded = true;
                    }
                } catch (WebException wE) {
                    bool redirected = false;
                    if (wE.Status == WebExceptionStatus.ProtocolError)
                    {
                        HttpWebResponse response = (HttpWebResponse)wE.Response;

                        if (response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            Log.Error("Imgur loading forbidden", wE);
                            break;
                        }
                        // Image no longer available?
                        if (response.StatusCode == HttpStatusCode.Redirect)
                        {
                            Log.InfoFormat("ImgUr image for hash {0} is no longer available, removing it from the history", hash);
                            Config.ImgurUploadHistory.Remove(hash);
                            Config.runtimeImgurHistory.Remove(hash);
                            redirected = true;
                        }
                    }
                    if (!redirected)
                    {
                        Log.Error("Problem loading ImgUr history for hash " + hash, wE);
                    }
                } catch (Exception e) {
                    Log.Error("Problem loading ImgUr history for hash " + hash, e);
                }
            }
            if (saveNeeded)
            {
                // Save needed changes
                IniConfig.Save();
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Do the actual upload to Imgur
        /// For more details on the available parameters, see: http://api.imgur.com/resources_anon
        /// </summary>
        /// <param name="surfaceToUpload">ISurface to upload</param>
        /// <param name="outputSettings">OutputSettings for the image file format</param>
        /// <param name="title">Title</param>
        /// <param name="filename">Filename</param>
        /// <returns>ImgurInfo with details</returns>
        public static ImgurInfo UploadToImgur(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename)
        {
            IDictionary <string, object> otherParameters = new Dictionary <string, object>();

            // add title
            if (title != null && Config.AddTitle)
            {
                otherParameters["title"] = title;
            }
            // add filename
            if (filename != null && Config.AddFilename)
            {
                otherParameters["name"] = filename;
            }
            string responseString = null;

            if (Config.AnonymousAccess)
            {
                // add key, we only use the other parameters for the AnonymousAccess
                //otherParameters.Add("key", IMGUR_ANONYMOUS_API_KEY);
                HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(Config.ImgurApi3Url + "/upload.xml?" + NetworkHelper.GenerateQueryParameters(otherParameters), HTTPMethod.POST);
                webRequest.ContentType = "image/" + outputSettings.Format;
                webRequest.ServicePoint.Expect100Continue = false;

                SetClientId(webRequest);
                try {
                    using (var requestStream = webRequest.GetRequestStream()) {
                        ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings);
                    }

                    using (WebResponse response = webRequest.GetResponse())
                    {
                        LogRateLimitInfo(response);
                        var responseStream = response.GetResponseStream();
                        if (responseStream != null)
                        {
                            using (StreamReader reader = new StreamReader(responseStream, true))
                            {
                                responseString = reader.ReadToEnd();
                            }
                        }
                    }
                } catch (Exception ex) {
                    Log.Error("Upload to imgur gave an exeption: ", ex);
                    throw;
                }
            }
            else
            {
                var oauth2Settings = new OAuth2Settings
                {
                    AuthUrlPattern     = AuthUrlPattern,
                    TokenUrl           = TokenUrl,
                    RedirectUrl        = "https://imgur.com",
                    CloudServiceName   = "Imgur",
                    ClientId           = ImgurCredentials.CONSUMER_KEY,
                    ClientSecret       = ImgurCredentials.CONSUMER_SECRET,
                    AuthorizeMode      = OAuth2AuthorizeMode.EmbeddedBrowser,
                    BrowserSize        = new Size(680, 880),
                    RefreshToken       = Config.RefreshToken,
                    AccessToken        = Config.AccessToken,
                    AccessTokenExpires = Config.AccessTokenExpires
                };

                // Copy the settings from the config, which is kept in memory and on the disk

                try
                {
                    var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, Config.ImgurApi3Url + "/upload.xml", oauth2Settings);
                    otherParameters["image"] = new SurfaceContainer(surfaceToUpload, outputSettings, filename);

                    NetworkHelper.WriteMultipartFormData(webRequest, otherParameters);

                    responseString = NetworkHelper.GetResponseAsString(webRequest);
                }
                finally
                {
                    // Copy the settings back to the config, so they are stored.
                    Config.RefreshToken       = oauth2Settings.RefreshToken;
                    Config.AccessToken        = oauth2Settings.AccessToken;
                    Config.AccessTokenExpires = oauth2Settings.AccessTokenExpires;
                    Config.IsDirty            = true;
                    IniConfig.Save();
                }
            }
            if (string.IsNullOrEmpty(responseString))
            {
                return(null);
            }
            return(ImgurInfo.ParseResponse(responseString));
        }
Exemplo n.º 13
0
        public static ImgurInfo ParseResponse(string response)
        {
            LOG.Debug(response);
            // This is actually a hack for BUG-1695
            // The problem is the (C) sign, we send it HTML encoded "&reg;" to Imgur and get it HTML encoded in the XML back
            // Added all the encodings I found quickly, I guess these are not all... but it should fix the issue for now.
            response = response.Replace("&cent;", "&#162;");
            response = response.Replace("&pound;", "&#163;");
            response = response.Replace("&yen;", "&#165;");
            response = response.Replace("&euro;", "&#8364;");
            response = response.Replace("&copy;", "&#169;");
            response = response.Replace("&reg;", "&#174;");

            ImgurInfo imgurInfo = new ImgurInfo();

            try {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(response);
                XmlNodeList nodes = doc.GetElementsByTagName("id");
                if (nodes.Count > 0)
                {
                    imgurInfo.Hash = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("hash");
                if (nodes.Count > 0)
                {
                    imgurInfo.Hash = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("deletehash");
                if (nodes.Count > 0)
                {
                    imgurInfo.DeleteHash = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("type");
                if (nodes.Count > 0)
                {
                    imgurInfo.ImageType = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("title");
                if (nodes.Count > 0)
                {
                    imgurInfo.Title = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("datetime");
                if (nodes.Count > 0)
                {
                    // Version 3 has seconds since Epoch
                    double secondsSince;
                    if (double.TryParse(nodes.Item(0).InnerText, out secondsSince))
                    {
                        var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
                        imgurInfo.Timestamp = epoch.AddSeconds(secondsSince).DateTime;
                    }
                }
                nodes = doc.GetElementsByTagName("original");
                if (nodes.Count > 0)
                {
                    imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:");
                }
                // Version 3 API only has Link
                nodes = doc.GetElementsByTagName("link");
                if (nodes.Count > 0)
                {
                    imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:");
                }
                nodes = doc.GetElementsByTagName("imgur_page");
                if (nodes.Count > 0)
                {
                    imgurInfo.Page = nodes.Item(0).InnerText.Replace("http:", "https:");
                }
                else
                {
                    // Version 3 doesn't have a page link in the response
                    imgurInfo.Page = string.Format("https://imgur.com/{0}", imgurInfo.Hash);
                }
                nodes = doc.GetElementsByTagName("small_square");
                if (nodes.Count > 0)
                {
                    imgurInfo.SmallSquare = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("large_thumbnail");
                if (nodes.Count > 0)
                {
                    imgurInfo.LargeThumbnail = nodes.Item(0).InnerText.Replace("http:", "https:");
                }
            } catch (Exception e) {
                LOG.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
            }
            return(imgurInfo);
        }
Exemplo n.º 14
0
        public static ImgurInfo ParseResponse(string response)
        {
            LOG.Debug(response);
            // This is actually a hack for BUG-1695
            // The problem is the (C) sign, we send it HTML encoded "&reg;" to Imgur and get it HTML encoded in the XML back
            // Added all the encodings I found quickly, I guess these are not all... but it should fix the issue for now.
            response = response.Replace("&cent;", "&#162;");
            response = response.Replace("&pound;", "&#163;");
            response = response.Replace("&yen;", "&#165;");
            response = response.Replace("&euro;", "&#8364;");
            response = response.Replace("&copy;", "&#169;");
            response = response.Replace("&reg;", "&#174;");

            ImgurInfo imgurInfo = new ImgurInfo();

            try {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(response);
                XmlNodeList nodes = doc.GetElementsByTagName("hash");
                if (nodes.Count > 0)
                {
                    imgurInfo.Hash = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("deletehash");
                if (nodes.Count > 0)
                {
                    imgurInfo.DeleteHash = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("type");
                if (nodes.Count > 0)
                {
                    imgurInfo.ImageType = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("title");
                if (nodes.Count > 0)
                {
                    imgurInfo.Title = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("datetime");
                if (nodes.Count > 0)
                {
                    imgurInfo.Timestamp = DateTime.Parse(nodes.Item(0).InnerText);
                }
                nodes = doc.GetElementsByTagName("original");
                if (nodes.Count > 0)
                {
                    imgurInfo.Original = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("imgur_page");
                if (nodes.Count > 0)
                {
                    imgurInfo.Page = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("small_square");
                if (nodes.Count > 0)
                {
                    imgurInfo.SmallSquare = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("large_thumbnail");
                if (nodes.Count > 0)
                {
                    imgurInfo.LargeThumbnail = nodes.Item(0).InnerText;
                }
            } catch (Exception e) {
                LOG.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
            }
            return(imgurInfo);
        }
Exemplo n.º 15
0
        public static ImgurInfo ParseResponse(string response)
        {
            LOG.Debug(response);
            // This is actually a hack for BUG-1695
            // The problem is the (C) sign, we send it HTML encoded "&reg;" to Imgur and get it HTML encoded in the XML back
            // Added all the encodings I found quickly, I guess these are not all... but it should fix the issue for now.
            response = response.Replace("&cent;", "&#162;");
            response = response.Replace("&pound;", "&#163;");
            response = response.Replace("&yen;", "&#165;");
            response = response.Replace("&euro;", "&#8364;");
            response = response.Replace("&copy;", "&#169;");
            response = response.Replace("&reg;", "&#174;");

            ImgurInfo imgurInfo = new ImgurInfo();
            try {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(response);
                XmlNodeList nodes = doc.GetElementsByTagName("hash");
                if(nodes.Count > 0) {
                    imgurInfo.Hash = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("deletehash");
                if(nodes.Count > 0) {
                    imgurInfo.DeleteHash = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("type");
                if(nodes.Count > 0) {
                    imgurInfo.ImageType = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("title");
                if(nodes.Count > 0) {
                    imgurInfo.Title = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("datetime");
                if(nodes.Count > 0) {
                    imgurInfo.Timestamp =  DateTime.Parse(nodes.Item(0).InnerText);
                }
                nodes = doc.GetElementsByTagName("original");
                if(nodes.Count > 0) {
                    imgurInfo.Original = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("imgur_page");
                if(nodes.Count > 0) {
                    imgurInfo.Page = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("small_square");
                if(nodes.Count > 0) {
                    imgurInfo.SmallSquare = nodes.Item(0).InnerText;
                }
                nodes = doc.GetElementsByTagName("large_thumbnail");
                if(nodes.Count > 0) {
                    imgurInfo.LargeThumbnail = nodes.Item(0).InnerText;
                }
            } catch(Exception e) {
                LOG.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
            }
            return imgurInfo;
        }