More small fixes, and some refactoring.

git-svn-id: http://svn.code.sf.net/p/greenshot/code/trunk@2140 7dccd23d-a4a3-4e1f-8c07-b4c1b4018ab4
This commit is contained in:
RKrom 2012-10-13 15:14:57 +00:00
commit 048826df3d
8 changed files with 130 additions and 100 deletions

View file

@ -338,36 +338,31 @@ namespace Greenshot {
UpdateUI(); UpdateUI();
// Do loading on a different Thread to shorten the startup // This forces the registration of all destinations inside Greenshot itself.
Thread pluginInitThread = new Thread (delegate() { DestinationHelper.GetAllDestinations();
// Load all the plugins // This forces the registration of all processors inside Greenshot itself.
PluginHelper.Instance.LoadPlugins(this); ProcessorHelper.GetAllProcessors();
// Check destinations, remove all that don't exist // Load all the plugins
foreach(string destination in conf.OutputDestinations.ToArray()) { PluginHelper.Instance.LoadPlugins(this);
if (DestinationHelper.GetDestination(destination) == null) {
conf.OutputDestinations.Remove(destination);
}
}
// we should have at least one!
if (conf.OutputDestinations.Count == 0) {
conf.OutputDestinations.Add(Destinations.EditorDestination.DESIGNATION);
}
if (conf.DisableQuickSettings) {
contextmenu_quicksettings.Visible = false;
} else {
BeginInvoke((MethodInvoker)delegate {
// Do after all plugins & finding the destination, otherwise they are missing!
InitializeQuickSettingsMenu();
});
}
});
pluginInitThread.Name = "Initialize plug-ins";
pluginInitThread.IsBackground = true;
pluginInitThread.SetApartmentState(ApartmentState.STA);
pluginInitThread.Start();
// Check destinations, remove all that don't exist
foreach(string destination in conf.OutputDestinations.ToArray()) {
if (DestinationHelper.GetDestination(destination) == null) {
conf.OutputDestinations.Remove(destination);
}
}
// we should have at least one!
if (conf.OutputDestinations.Count == 0) {
conf.OutputDestinations.Add(Destinations.EditorDestination.DESIGNATION);
}
if (conf.DisableQuickSettings) {
contextmenu_quicksettings.Visible = false;
} else {
// Do after all plugins & finding the destination, otherwise they are missing!
InitializeQuickSettingsMenu();
}
SoundHelper.Initialize(); SoundHelper.Initialize();
// Set the Greenshot icon visibility depending on the configuration. (Added for feature #3521446) // Set the Greenshot icon visibility depending on the configuration. (Added for feature #3521446)

View file

@ -230,7 +230,7 @@ namespace Greenshot.Helpers {
Dictionary<string, Assembly> tmpAssemblies = new Dictionary<string, Assembly>(); Dictionary<string, Assembly> tmpAssemblies = new Dictionary<string, Assembly>();
// Loop over the list of available files and get the Plugin Attributes // Loop over the list of available files and get the Plugin Attributes
foreach (string pluginFile in pluginFiles) { foreach (string pluginFile in pluginFiles) {
LOG.DebugFormat("Checking the following file for plugins: {0}", pluginFile); //LOG.DebugFormat("Checking the following file for plugins: {0}", pluginFile);
try { try {
Assembly assembly = Assembly.LoadFrom(pluginFile); Assembly assembly = Assembly.LoadFrom(pluginFile);
PluginAttribute[] pluginAttributes = assembly.GetCustomAttributes(typeof(PluginAttribute), false) as PluginAttribute[]; PluginAttribute[] pluginAttributes = assembly.GetCustomAttributes(typeof(PluginAttribute), false) as PluginAttribute[];

View file

@ -100,12 +100,16 @@ namespace GreenshotImgurPlugin {
private void CheckHistory() { private void CheckHistory() {
try { try {
ImgurUtils.LoadHistory(); ImgurUtils.LoadHistory();
if (config.ImgurUploadHistory.Count > 0) { host.MainMenu.BeginInvoke((MethodInvoker)delegate {
historyMenuItem.Enabled = true; if (config.ImgurUploadHistory.Count > 0) {
} else { historyMenuItem.Enabled = true;
historyMenuItem.Enabled = false; } else {
} historyMenuItem.Enabled = false;
} catch {}; }
});
} catch (Exception ex) {
LOG.Error("Error loading history", ex);
};
} }
public virtual void Shutdown() { public virtual void Shutdown() {

View file

@ -105,22 +105,20 @@ namespace GreenshotImgurPlugin {
/// <returns>ImgurInfo with details</returns> /// <returns>ImgurInfo with details</returns>
public static ImgurInfo UploadToImgur(Image image, OutputSettings outputSettings, string title, string filename) { public static ImgurInfo UploadToImgur(Image image, OutputSettings outputSettings, string title, string filename) {
IDictionary<string, object> uploadParameters = new Dictionary<string, object>(); IDictionary<string, object> uploadParameters = new Dictionary<string, object>();
IDictionary<string, object> otherParameters = new Dictionary<string, object>();
// add title
if (title != null) {
otherParameters.Add("title", title);
}
// add filename
if (filename != null) {
otherParameters.Add("name", filename);
}
string responseString = null; string responseString = null;
if (config.AnonymousAccess) { if (config.AnonymousAccess) {
// add title
if (title != null) {
uploadParameters.Add("title", title);
}
// add filename
if (filename != null) {
uploadParameters.Add("name", filename);
}
// add key // add key
uploadParameters.Add("key", IMGUR_ANONYMOUS_API_KEY); uploadParameters.Add("key", IMGUR_ANONYMOUS_API_KEY);
HttpWebRequest webRequest = (HttpWebRequest)NetworkHelper.CreateWebRequest(config.ImgurApiUrl + "/upload.xml?" + NetworkHelper.GenerateQueryParameters(uploadParameters)); HttpWebRequest webRequest = (HttpWebRequest)NetworkHelper.CreateWebRequest(config.ImgurApiUrl + "/upload.xml?" + NetworkHelper.GenerateQueryParameters(uploadParameters) + NetworkHelper.GenerateQueryParameters(otherParameters));
webRequest.Method = "POST"; webRequest.Method = "POST";
webRequest.ContentType = "image/" + outputSettings.Format.ToString(); webRequest.ContentType = "image/" + outputSettings.Format.ToString();
webRequest.ServicePoint.Expect100Continue = false; webRequest.ServicePoint.Expect100Continue = false;
@ -158,19 +156,8 @@ namespace GreenshotImgurPlugin {
IniConfig.Save(); IniConfig.Save();
} }
try { try {
string apiUrl = "http://api.imgur.com/2/account/images.xml"; otherParameters.Add("image", new ImageContainer(image, outputSettings, filename));
// sign without parameters responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, "http://api.imgur.com/2/account/images.xml", uploadParameters, otherParameters, null);
oAuth.Sign(HTTPMethod.POST, apiUrl, uploadParameters);
// add title
if (title != null) {
uploadParameters.Add("title", title);
}
// add filename
if (filename != null) {
uploadParameters.Add("name", filename);
}
uploadParameters.Add("image", new ImageContainer(image, outputSettings, filename));
responseString = oAuth.MakeRequest(HTTPMethod.POST, apiUrl, uploadParameters, null);
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error("Upload to imgur gave an exeption: ", ex); LOG.Error("Upload to imgur gave an exeption: ", ex);
throw ex; throw ex;
@ -227,7 +214,7 @@ namespace GreenshotImgurPlugin {
} }
throw wE; throw wE;
} }
LOG.Info(responseString); LOG.Debug(responseString);
ImgurInfo imgurInfo = ImgurInfo.ParseResponse(responseString); ImgurInfo imgurInfo = ImgurInfo.ParseResponse(responseString);
imgurInfo.DeleteHash = deleteHash; imgurInfo.DeleteHash = deleteHash;
return imgurInfo; return imgurInfo;

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\CommonProject.properties" /> <Import Project="..\CommonProject.properties" />
<PropertyGroup> <PropertyGroup>
<ProjectGuid>{9C0ECC4C-7807-4111-916A-4F57BB29788A}</ProjectGuid> <ProjectGuid>{9C0ECC4C-7807-4111-916A-4F57BB29788A}</ProjectGuid>
<OutputType>Library</OutputType> <OutputType>Library</OutputType>
@ -79,4 +79,32 @@ copy "$(ProjectDir)bin\$(Configuration)\$(ProjectName).pdb" "$(SolutionDir)bin\$
mkdir "$(SolutionDir)bin\$(Configuration)\Languages\Plugins\$(ProjectName)" mkdir "$(SolutionDir)bin\$(Configuration)\Languages\Plugins\$(ProjectName)"
copy "$(ProjectDir)\Languages\*.xml" "$(SolutionDir)bin\$(Configuration)\Languages\Plugins\$(ProjectName)\"</PostBuildEvent> copy "$(ProjectDir)\Languages\*.xml" "$(SolutionDir)bin\$(Configuration)\Languages\Plugins\$(ProjectName)\"</PostBuildEvent>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress>
<PlatformTarget>x86</PlatformTarget>
<FileAlignment>4096</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'AnyCPU' ">
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress>
<PlatformTarget>AnyCPU</PlatformTarget>
<FileAlignment>4096</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DefineConstants>DEBUG;TRACE</DefineConstants>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DebugType>None</DebugType>
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DefineConstants>TRACE</DefineConstants>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DebugType>None</DebugType>
<DebugSymbols>false</DebugSymbols>
</PropertyGroup>
</Project> </Project>

View file

@ -78,26 +78,25 @@ namespace GreenshotPhotobucketPlugin {
oAuth.Token = config.Token; oAuth.Token = config.Token;
oAuth.TokenSecret = config.TokenSecret; oAuth.TokenSecret = config.TokenSecret;
Dictionary<string, object> parameters = new Dictionary<string, object>(); IDictionary<string, object> signedParameters = new Dictionary<string, object>();
// add album // add album
parameters.Add("id", "Apex75/greenshot"); signedParameters.Add("id", "Apex75/greenshot");
// add type // add type
parameters.Add("type", "base64"); signedParameters.Add("type", "base64");
// add title // add title
if (title != null) { if (title != null) {
parameters.Add("title", title); signedParameters.Add("title", title);
} }
// add filename // add filename
if (filename != null) { if (filename != null) {
parameters.Add("filename", filename); signedParameters.Add("filename", filename);
} }
IDictionary<string, object> unsignedParameters = new Dictionary<string, object>();
// Add image
unsignedParameters.Add("uploadfile", new ImageContainer(image, outputSettings, filename));
try { try {
string apiUrl = "http://api.photobucket.com/album/!/upload"; string apiUrl = "http://api.photobucket.com/album/!/upload";
oAuth.Sign(HTTPMethod.POST, apiUrl, parameters); responseString = oAuth.MakeOAuthRequest(HTTPMethod.POST, apiUrl, apiUrl.Replace("api.photobucket.com", config.SubDomain), signedParameters, unsignedParameters, null);
apiUrl = apiUrl.Replace("api.photobucket.com", config.SubDomain);
// Add image
parameters.Add("uploadfile", new ImageContainer(image, outputSettings, filename));
responseString = oAuth.MakeRequest(HTTPMethod.POST, apiUrl, parameters, null);
} catch (Exception ex) { } catch (Exception ex) {
LOG.Error("Error uploading to Photobucket.", ex); LOG.Error("Error uploading to Photobucket.", ex);
throw ex; throw ex;

View file

@ -365,7 +365,7 @@ namespace GreenshotPlugin.Core {
LOG.InfoFormat("Searching language directory '{0}' for language files with pattern '{1}'", languagePath, LANGUAGE_FILENAME_PATTERN); LOG.InfoFormat("Searching language directory '{0}' for language files with pattern '{1}'", languagePath, LANGUAGE_FILENAME_PATTERN);
try { try {
foreach (string languageFilepath in Directory.GetFiles(languagePath, LANGUAGE_FILENAME_PATTERN, SearchOption.AllDirectories)) { foreach (string languageFilepath in Directory.GetFiles(languagePath, LANGUAGE_FILENAME_PATTERN, SearchOption.AllDirectories)) {
LOG.DebugFormat("Found language file: {0}", languageFilepath); //LOG.DebugFormat("Found language file: {0}", languageFilepath);
LanguageFile languageFile = LoadFileInfo(languageFilepath); LanguageFile languageFile = LoadFileInfo(languageFilepath);
if (languageFile == null) { if (languageFile == null) {
continue; continue;
@ -385,7 +385,7 @@ namespace GreenshotPlugin.Core {
// Check if we can display the file // Check if we can display the file
if (!string.IsNullOrEmpty(languageFile.LanguageGroup) && unsupportedLanguageGroups.Contains(languageFile.LanguageGroup)) { if (!string.IsNullOrEmpty(languageFile.LanguageGroup) && unsupportedLanguageGroups.Contains(languageFile.LanguageGroup)) {
LOG.InfoFormat("Skipping unsuported (not able to display) language {0}", languageFile.Description); LOG.InfoFormat("Skipping unsuported (not able to display) language {0} from file {1}", languageFile.Description, languageFilepath);
continue; continue;
} }

View file

@ -375,27 +375,31 @@ namespace GreenshotPlugin.Core {
} }
/// <summary> /// <summary>
/// Wrapper /// Submit a web request using oAuth.
/// </summary> /// </summary>
/// <param name="method"></param> /// <param name="method">GET or POST</param>
/// <param name="requestURL"></param> /// <param name="requestURL">The full url, including the querystring for the signing/request</param>
/// <param name="parameters"></param> /// <param name="parametersToSign">Parameters for the request, which need to be signed</param>
/// <returns></returns> /// <param name="additionalParameters">Parameters for the request, which do not need to be signed</param>
public string MakeOAuthRequest(HTTPMethod method, string requestURL, IDictionary<string, object> parameters) { /// <param name="postData">Data to post (MemoryStream)</param>
return MakeOAuthRequest(method, requestURL, parameters, null); /// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string requestURL, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters, IBinaryContainer postData) {
return MakeOAuthRequest(method, requestURL, requestURL, parametersToSign, additionalParameters, postData);
} }
/// <summary> /// <summary>
/// Submit a web request using oAuth. /// Submit a web request using oAuth.
/// </summary> /// </summary>
/// <param name="method">GET or POST</param> /// <param name="method">GET or POST</param>
/// <param name="requestURL">The full url, including the querystring.</param> /// <param name="signUrl">The full url, including the querystring for the signing</param>
/// <param name="parameters">Parameters for the request</param> /// <param name="requestURL">The full url, including the querystring for the request</param>
/// <param name="parametersToSign">Parameters for the request, which need to be signed</param>
/// <param name="additionalParameters">Parameters for the request, which do not need to be signed</param>
/// <param name="postData">Data to post (MemoryStream)</param> /// <param name="postData">Data to post (MemoryStream)</param>
/// <returns>The web server response.</returns> /// <returns>The web server response.</returns>
public string MakeOAuthRequest(HTTPMethod method, string requestURL, IDictionary<string, object> parameters, IBinaryContainer postData) { public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestURL, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters, IBinaryContainer postData) {
if (parameters == null) { if (parametersToSign == null) {
parameters = new Dictionary<string, object>(); parametersToSign = new Dictionary<string, object>();
} }
int retries = 2; int retries = 2;
Exception lastException = null; Exception lastException = null;
@ -407,8 +411,19 @@ namespace GreenshotPlugin.Core {
} }
} }
try { try {
Sign(method, requestURL, parameters); Sign(method, signUrl, parametersToSign);
return MakeRequest(method, requestURL, parameters, postData);
// Join all parameters
IDictionary<string, object> newParameters = new Dictionary<string, object>();
foreach(var parameter in parametersToSign) {
newParameters.Add(parameter);
}
if (additionalParameters != null) {
foreach(var parameter in additionalParameters) {
newParameters.Add(parameter);
}
}
return MakeRequest(method, requestURL, newParameters, postData);
} catch (WebException wEx) { } catch (WebException wEx) {
lastException = wEx; lastException = wEx;
if (wEx.Response != null) { if (wEx.Response != null) {
@ -416,15 +431,16 @@ namespace GreenshotPlugin.Core {
if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) { if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) {
Token = null; Token = null;
TokenSecret = null; TokenSecret = null;
// Remove oauth keys, so they aren't added double // Remove oauth keys, so they aren't added double
IDictionary<string, object> newParameters = new Dictionary<string, object>(); List<string> keysToDelete = new List<string>();
foreach (string parameterKey in parameters.Keys) { foreach (string parameterKey in parametersToSign.Keys) {
if (!parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) { if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) {
newParameters.Add(parameterKey, parameters[parameterKey]); keysToDelete.Add(parameterKey);
} }
} }
parameters = newParameters; foreach(string keyToDelete in keysToDelete) {
parametersToSign.Remove(keyToDelete);
}
continue; continue;
} }
} }
@ -437,6 +453,7 @@ namespace GreenshotPlugin.Core {
throw new Exception("Not authorized"); throw new Exception("Not authorized");
} }
/// <summary> /// <summary>
/// OAuth sign the parameters, meaning all oauth parameters are added to the supplied dictionary. /// OAuth sign the parameters, meaning all oauth parameters are added to the supplied dictionary.
/// And additionally a signature is added. /// And additionally a signature is added.
@ -444,7 +461,7 @@ namespace GreenshotPlugin.Core {
/// <param name="method">Method (POST,PUT,GET)</param> /// <param name="method">Method (POST,PUT,GET)</param>
/// <param name="requestURL">Url to call</param> /// <param name="requestURL">Url to call</param>
/// <param name="parameters">IDictionary<string, string></param> /// <param name="parameters">IDictionary<string, string></param>
public void Sign(HTTPMethod method, string requestURL, IDictionary<string, object> parameters) { private void Sign(HTTPMethod method, string requestURL, IDictionary<string, object> parameters) {
if (parameters == null) { if (parameters == null) {
throw new ArgumentNullException("parameters"); throw new ArgumentNullException("parameters");
} }
@ -497,7 +514,7 @@ namespace GreenshotPlugin.Core {
/// <param name="parameters"></param> /// <param name="parameters"></param>
/// <param name="postData">IBinaryParameter</param> /// <param name="postData">IBinaryParameter</param>
/// <returns>Response from server</returns> /// <returns>Response from server</returns>
public string MakeRequest(HTTPMethod method, string requestURL, IDictionary<string, object> parameters, IBinaryContainer postData) { private string MakeRequest(HTTPMethod method, string requestURL, IDictionary<string, object> parameters, IBinaryContainer postData) {
if (parameters == null) { if (parameters == null) {
throw new ArgumentNullException("parameters"); throw new ArgumentNullException("parameters");
} }
@ -522,7 +539,7 @@ namespace GreenshotPlugin.Core {
requestParameters = parameters; requestParameters = parameters;
} }
if (HTTPMethod.GET == method) { if (HTTPMethod.GET == method || postData != null) {
if (requestParameters.Count > 0) { if (requestParameters.Count > 0) {
// Add the parameters to the request // Add the parameters to the request
requestURL += "?" + NetworkHelper.GenerateQueryParameters(requestParameters); requestURL += "?" + NetworkHelper.GenerateQueryParameters(requestParameters);
@ -540,7 +557,7 @@ namespace GreenshotPlugin.Core {
webRequest.Headers.Add("Authorization: OAuth " + authHeader.ToString()); webRequest.Headers.Add("Authorization: OAuth " + authHeader.ToString());
} }
if (HTTPMethod.POST == method && postData == null && requestParameters != null && requestParameters.Count > 0) { if ((HTTPMethod.POST == method || HTTPMethod.PUT == method) && postData == null && requestParameters != null && requestParameters.Count > 0) {
if (UseMultipartFormData) { if (UseMultipartFormData) {
NetworkHelper.WriteMultipartFormData(webRequest, requestParameters); NetworkHelper.WriteMultipartFormData(webRequest, requestParameters);
} else { } else {