Making the imgur destination more stable, unfortunately Imgur has issues...

This commit is contained in:
Robin 2015-11-06 14:12:30 +01:00
parent 41255df991
commit b64de88b1e
4 changed files with 65 additions and 32 deletions

View file

@ -35,7 +35,7 @@ namespace GreenshotImgurPlugin {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurUtils)); private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurUtils));
private const string SmallUrlPattern = "http://i.imgur.com/{0}s.jpg"; private const string SmallUrlPattern = "http://i.imgur.com/{0}s.jpg";
private static readonly ImgurConfiguration Config = IniConfig.GetIniSection<ImgurConfiguration>(); private static readonly ImgurConfiguration Config = IniConfig.GetIniSection<ImgurConfiguration>();
private const string ImgurAnonymousClientId = "60e8838e21d6b66";
/// <summary> /// <summary>
/// Load the complete history of the imgur uploads, with the corresponding information /// Load the complete history of the imgur uploads, with the corresponding information
/// </summary> /// </summary>
@ -94,8 +94,8 @@ namespace GreenshotImgurPlugin {
/// Use this to make sure Imgur knows from where the upload comes. /// Use this to make sure Imgur knows from where the upload comes.
/// </summary> /// </summary>
/// <param name="webRequest"></param> /// <param name="webRequest"></param>
private static void SetClientId(HttpWebRequest webRequest) { private static void SetClientId(HttpWebRequest webRequest, string clientId) {
webRequest.Headers.Add("Authorization", "Client-ID " + ImgurCredentials.CONSUMER_KEY); webRequest.Headers.Add("Authorization", "Client-ID " + clientId);
} }
/// <summary> /// <summary>
@ -126,7 +126,7 @@ namespace GreenshotImgurPlugin {
webRequest.ContentType = "image/" + outputSettings.Format; webRequest.ContentType = "image/" + outputSettings.Format;
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest); SetClientId(webRequest, ImgurAnonymousClientId);
try { try {
using (var requestStream = webRequest.GetRequestStream()) { using (var requestStream = webRequest.GetRequestStream()) {
ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings); ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings);
@ -152,17 +152,27 @@ namespace GreenshotImgurPlugin {
oAuth.LoginTitle = "Imgur authorization"; oAuth.LoginTitle = "Imgur authorization";
oAuth.Token = Config.ImgurToken; oAuth.Token = Config.ImgurToken;
oAuth.TokenSecret = Config.ImgurTokenSecret; oAuth.TokenSecret = Config.ImgurTokenSecret;
if (string.IsNullOrEmpty(oAuth.Token)) { try
if (!oAuth.Authorize()) { {
return null; if (string.IsNullOrEmpty(oAuth.Token)) {
if (!oAuth.Authorize()) {
return null;
}
StoreOAuthToken(oAuth);
} }
if (!string.IsNullOrEmpty(oAuth.Token)) { }
Config.ImgurToken = oAuth.Token; catch (Exception ex)
{
// Retry
LOG.Error(ex);
if (string.IsNullOrEmpty(oAuth.Token))
{
if (!oAuth.Authorize())
{
return null;
}
StoreOAuthToken(oAuth);
} }
if (!string.IsNullOrEmpty(oAuth.TokenSecret)) {
Config.ImgurTokenSecret = oAuth.TokenSecret;
}
IniConfig.Save();
} }
try { try {
otherParameters.Add("image", new SurfaceContainer(surfaceToUpload, outputSettings, filename)); otherParameters.Add("image", new SurfaceContainer(surfaceToUpload, outputSettings, filename));
@ -171,18 +181,36 @@ namespace GreenshotImgurPlugin {
LOG.Error("Upload to imgur gave an exeption: ", ex); LOG.Error("Upload to imgur gave an exeption: ", ex);
throw; throw;
} finally { } finally {
if (oAuth.Token != null) { StoreOAuthToken(oAuth);
Config.ImgurToken = oAuth.Token;
}
if (oAuth.TokenSecret != null) {
Config.ImgurTokenSecret = oAuth.TokenSecret;
}
IniConfig.Save();
} }
} }
return ImgurInfo.ParseResponse(responseString); return ImgurInfo.ParseResponse(responseString);
} }
/// <summary>
/// Helper method to store the OAuth output, also if the key is null we need to remove it
/// </summary>
/// <param name="oAuth">OAuthSession</param>
private static void StoreOAuthToken(OAuthSession oAuth)
{
bool hasChances = false;
if (oAuth.Token != Config.ImgurToken)
{
Config.ImgurToken = oAuth.Token;
hasChances = true;
}
if (oAuth.TokenSecret != Config.ImgurTokenSecret)
{
Config.ImgurTokenSecret = oAuth.TokenSecret;
hasChances = true;
}
if (hasChances)
{
IniConfig.Save();
}
}
/// <summary> /// <summary>
/// Retrieve the thumbnail of an imgur image /// Retrieve the thumbnail of an imgur image
/// </summary> /// </summary>
@ -195,7 +223,7 @@ namespace GreenshotImgurPlugin {
LOG.InfoFormat("Retrieving Imgur image for {0} with url {1}", imgurInfo.Hash, imgurInfo.SmallSquare); 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); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(string.Format(SmallUrlPattern, imgurInfo.Hash), HTTPMethod.GET);
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest); SetClientId(webRequest, ImgurCredentials.CONSUMER_KEY);
using (WebResponse response = webRequest.GetResponse()) { using (WebResponse response = webRequest.GetResponse()) {
LogRateLimitInfo(response); LogRateLimitInfo(response);
Stream responseStream = response.GetResponseStream(); Stream responseStream = response.GetResponseStream();
@ -217,7 +245,7 @@ namespace GreenshotImgurPlugin {
LOG.InfoFormat("Retrieving Imgur info for {0} with url {1}", hash, url); LOG.InfoFormat("Retrieving Imgur info for {0} with url {1}", hash, url);
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET);
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest); SetClientId(webRequest, ImgurCredentials.CONSUMER_KEY);
string responseString; string responseString;
try { try {
using (WebResponse response = webRequest.GetResponse()) { using (WebResponse response = webRequest.GetResponse()) {
@ -251,7 +279,7 @@ namespace GreenshotImgurPlugin {
string url = Config.ImgurApiUrl + "/delete/" + imgurInfo.DeleteHash; string url = Config.ImgurApiUrl + "/delete/" + imgurInfo.DeleteHash;
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET);
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest); SetClientId(webRequest, ImgurCredentials.CONSUMER_KEY);
string responseString; string responseString;
using (WebResponse response = webRequest.GetResponse()) { using (WebResponse response = webRequest.GetResponse()) {
LogRateLimitInfo(response); LogRateLimitInfo(response);

View file

@ -482,8 +482,9 @@ namespace GreenshotPlugin.Core {
} }
catch (WebException e) { catch (WebException e) {
response = (HttpWebResponse) e.Response; response = (HttpWebResponse) e.Response;
HttpStatusCode statusCode = response.StatusCode; HttpStatusCode statusCode = HttpStatusCode.Unused;
if (response != null) { if (response != null) {
statusCode = response.StatusCode;
LOG.ErrorFormat("HTTP error {0}", statusCode); LOG.ErrorFormat("HTTP error {0}", statusCode);
string errorContent = GetResponseAsString(response); string errorContent = GetResponseAsString(response);
if (alsoReturnContentOnError) if (alsoReturnContentOnError)

View file

@ -476,7 +476,8 @@ namespace GreenshotPlugin.Core {
/// <summary> /// <summary>
/// Get the request token using the consumer key and secret. Also initializes tokensecret /// Get the request token using the consumer key and secret. Also initializes tokensecret
/// </summary> /// </summary>
private void GetRequestToken() { /// <returns>response, this doesn't need to be used!!</returns>
private string GetRequestToken() {
IDictionary<string, object> parameters = new Dictionary<string, object>(); IDictionary<string, object> parameters = new Dictionary<string, object>();
foreach(var value in _requestTokenParameters) { foreach(var value in _requestTokenParameters) {
parameters.Add(value); parameters.Add(value);
@ -493,15 +494,17 @@ namespace GreenshotPlugin.Core {
TokenSecret = _requestTokenResponseParameters[OAUTH_TOKEN_SECRET_KEY]; TokenSecret = _requestTokenResponseParameters[OAUTH_TOKEN_SECRET_KEY];
} }
} }
return response;
} }
/// <summary> /// <summary>
/// Authorize the token by showing the dialog /// Authorize the token by showing the dialog
/// </summary> /// </summary>
/// <param name="requestTokenResponse">Pass the response from the server's request token, so if there is something wrong we can show it.</param>
/// <returns>The request token.</returns> /// <returns>The request token.</returns>
private string GetAuthorizeToken() { private string GetAuthorizeToken(string requestTokenResponse) {
if (string.IsNullOrEmpty(Token)) { if (string.IsNullOrEmpty(Token)) {
Exception e = new Exception("The request token is not set"); Exception e = new Exception("The request token is not set, service responded with: " + requestTokenResponse);
throw e; throw e;
} }
LOG.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink); LOG.DebugFormat("Opening AuthorizationLink: {0}", AuthorizationLink);
@ -567,13 +570,14 @@ namespace GreenshotPlugin.Core {
TokenSecret = null; TokenSecret = null;
Verifier = null; Verifier = null;
LOG.Debug("Creating Token"); LOG.Debug("Creating Token");
try { string requestTokenResponse;
GetRequestToken(); try {
requestTokenResponse = GetRequestToken();
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error(ex); LOG.Error(ex);
throw new NotSupportedException("Service is not available: " + ex.Message); throw new NotSupportedException("Service is not available: " + ex.Message);
} }
if (string.IsNullOrEmpty(GetAuthorizeToken())) { if (string.IsNullOrEmpty(GetAuthorizeToken(requestTokenResponse))) {
LOG.Debug("User didn't authenticate!"); LOG.Debug("User didn't authenticate!");
return false; return false;
} }

View file

@ -27,9 +27,9 @@ environment:
credentials_flickr_consumer_secret: credentials_flickr_consumer_secret:
secure: 9TthlljPHXWPkDDeG3uiFVJ9YJwHZOV0ZsojaIBBuvw= secure: 9TthlljPHXWPkDDeG3uiFVJ9YJwHZOV0ZsojaIBBuvw=
credentials_imgur_consumer_key: credentials_imgur_consumer_key:
secure: XRTg1Ecs6ER9m4779CJAng== secure: z8S4QZ3/InPe3dgCf0CNyS0VGKuRyjjP8WMAq+AkK5OZJxZcbIxwobjgelE5CWYL
credentials_imgur_consumer_secret: credentials_imgur_consumer_secret:
secure: gcCp/gJF8vqmnCUPKyb04H8Oz9mWmiB00U5X7iI/DGr5mxjoCG1khc6/zn6aSSqn secure: ovfXJRorkkKUzbMXuZ4m0U6KF4icngmS+nzSljXJGSKfhI+GNXbMNa//mKYfTCXI
credentials_photobucket_consumer_key: credentials_photobucket_consumer_key:
secure: oo9GD1Y8dkrli6hMfnnYsw== secure: oo9GD1Y8dkrli6hMfnnYsw==
credentials_photobucket_consumer_secret: credentials_photobucket_consumer_secret: