This is a quick Imgur fix, and reducing the amount of traffic.

This commit is contained in:
Robin 2016-11-03 21:51:27 +01:00
commit a9a745a439
22 changed files with 1136 additions and 757 deletions

View file

@ -25,13 +25,10 @@ using Greenshot.Plugin.Drawing;
using GreenshotPlugin.Core;
using GreenshotPlugin.UnmanagedHelpers;
using System.Drawing.Drawing2D;
using log4net;
namespace Greenshot.Drawing.Filters {
[Serializable()]
[Serializable]
public class BlurFilter : AbstractFilter {
private static ILog LOG = LogManager.GetLogger(typeof(BlurFilter));
public double previewQuality;
public double PreviewQuality {
get { return previewQuality; }
@ -43,7 +40,7 @@ namespace Greenshot.Drawing.Filters {
AddField(GetType(), FieldType.PREVIEW_QUALITY, 1.0d);
}
public unsafe override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) {
public override void Apply(Graphics graphics, Bitmap applyBitmap, Rectangle rect, RenderMode renderMode) {
int blurRadius = GetFieldValueAsInt(FieldType.BLUR_RADIUS);
Rectangle applyRect = ImageHelper.CreateIntersectRectangle(applyBitmap.Size, rect, Invert);
if (applyRect.Width == 0 || applyRect.Height == 0) {
@ -54,7 +51,7 @@ namespace Greenshot.Drawing.Filters {
graphics.SetClip(applyRect);
graphics.ExcludeClip(rect);
}
if (GDIplus.isBlurPossible(blurRadius)) {
if (GDIplus.IsBlurPossible(blurRadius)) {
GDIplus.DrawWithBlur(graphics, applyBitmap, applyRect, null, null, blurRadius, false);
} else {
using (IFastBitmap fastBitmap = FastBitmap.CreateCloneOf(applyBitmap, applyRect)) {
@ -63,7 +60,6 @@ namespace Greenshot.Drawing.Filters {
}
}
graphics.Restore(state);
return;
}
}
}

View file

@ -7,8 +7,17 @@ CHANGE LOG:
All details to our tickets can be found here: https://greenshot.atlassian.net
@DETAILVERSION@
Changes for this release:
This has Imgur improvements for the newer API version, this is a backport from Greenshot 1.2.9
With the move to a new hosting platform, we also noticed our update checks are way to often, this needed to be reduced.
1.2.8.12-cab854b RELEASE
There were some major issues with the authenticated (non anonymous) uploads to Imgur.
After contacting Imgur they told us that their old API was deprecated or disabled, unfortunately this was not communicated.
Although we are working hard on Greenshot 1.3, where we changed most of the Imgur code already, we can't release it.

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -19,7 +19,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using GreenshotPlugin.Controls;
namespace GreenshotImgurPlugin {
@ -27,7 +26,5 @@ namespace GreenshotImgurPlugin {
/// This class is needed for design-time resolving of the language files
/// </summary>
public class ImgurForm : GreenshotForm {
public ImgurForm() : base() {
}
}
}

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -31,24 +31,24 @@ namespace GreenshotImgurPlugin {
/// <summary>
/// Description of ImgurHistory.
/// </summary>
public partial class ImgurHistory : ImgurForm {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurHistory));
private GreenshotColumnSorter columnSorter;
private static ImgurConfiguration config = IniConfig.GetIniSection<ImgurConfiguration>();
private static ImgurHistory instance;
public sealed partial class ImgurHistory : ImgurForm {
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurHistory));
private readonly GreenshotColumnSorter _columnSorter;
private static readonly ImgurConfiguration Config = IniConfig.GetIniSection<ImgurConfiguration>();
private static ImgurHistory _instance;
public static void ShowHistory() {
// Make sure the history is loaded, will be done only once
ImgurUtils.LoadHistory();
if (instance == null) {
instance = new ImgurHistory();
if (_instance == null) {
_instance = new ImgurHistory();
}
instance.Show();
instance.redraw();
_instance.Show();
_instance.Redraw();
}
private ImgurHistory() {
this.ManualLanguageApply = true;
ManualLanguageApply = true;
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
@ -56,21 +56,21 @@ namespace GreenshotImgurPlugin {
AcceptButton = finishedButton;
CancelButton = finishedButton;
// Init sorting
columnSorter = new GreenshotColumnSorter();
this.listview_imgur_uploads.ListViewItemSorter = columnSorter;
columnSorter.SortColumn = 3;
columnSorter.Order = SortOrder.Descending;
redraw();
_columnSorter = new GreenshotColumnSorter();
listview_imgur_uploads.ListViewItemSorter = _columnSorter;
_columnSorter.SortColumn = 3;
_columnSorter.Order = SortOrder.Descending;
Redraw();
if (listview_imgur_uploads.Items.Count > 0) {
listview_imgur_uploads.Items[0].Selected = true;
}
ApplyLanguage();
if (config.Credits > 0) {
this.Text = this.Text + " (" + config.Credits + " credits)";
if (Config.Credits > 0) {
Text = Text + " (" + Config.Credits + " credits)";
}
}
private void redraw() {
private void Redraw() {
// Should fix Bug #3378699
pictureBox1.Image = pictureBox1.ErrorImage;
listview_imgur_uploads.BeginUpdate();
@ -80,9 +80,11 @@ namespace GreenshotImgurPlugin {
foreach (string column in columns) {
listview_imgur_uploads.Columns.Add(column);
}
foreach (ImgurInfo imgurInfo in config.runtimeImgurHistory.Values) {
ListViewItem item = new ListViewItem(imgurInfo.Hash);
item.Tag = imgurInfo;
foreach (ImgurInfo imgurInfo in Config.runtimeImgurHistory.Values) {
var item = new ListViewItem(imgurInfo.Hash)
{
Tag = imgurInfo
};
item.SubItems.Add(imgurInfo.Title);
item.SubItems.Add(imgurInfo.DeleteHash);
item.SubItems.Add(imgurInfo.Timestamp.ToString("yyyy-MM-dd HH:mm:ss", DateTimeFormatInfo.InvariantInfo));
@ -101,7 +103,7 @@ namespace GreenshotImgurPlugin {
private void Listview_imgur_uploadsSelectedIndexChanged(object sender, EventArgs e) {
pictureBox1.Image = pictureBox1.ErrorImage;
if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) {
if (listview_imgur_uploads.SelectedItems.Count > 0) {
deleteButton.Enabled = true;
openButton.Enabled = true;
clipboardButton.Enabled = true;
@ -118,40 +120,39 @@ namespace GreenshotImgurPlugin {
}
private void DeleteButtonClick(object sender, EventArgs e) {
if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) {
if (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;
DialogResult result = MessageBox.Show(Language.GetFormattedString("imgur", LangKey.delete_question, imgurInfo.Title), Language.GetFormattedString("imgur", LangKey.delete_title, imgurInfo.Hash), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes) {
if (result != DialogResult.Yes)
{
continue;
}
// Should fix Bug #3378699
pictureBox1.Image = pictureBox1.ErrorImage;
try {
new PleaseWaitForm().ShowAndWait(ImgurPlugin.Attributes.Name, Language.GetString("imgur", LangKey.communication_wait),
delegate() {
delegate {
ImgurUtils.DeleteImgurImage(imgurInfo);
}
);
} catch (Exception ex) {
LOG.Warn("Problem communicating with Imgur: ", ex);
Log.Warn("Problem communicating with Imgur: ", ex);
}
imgurInfo.Dispose();
}
}
}
redraw();
Redraw();
}
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++) {
if (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);
}
links.AppendLine(Config.UsePageLink ? imgurInfo.Page : imgurInfo.Original);
}
}
ClipboardHelper.SetClipboardData(links.ToString());
@ -160,20 +161,20 @@ namespace GreenshotImgurPlugin {
private void ClearHistoryButtonClick(object sender, EventArgs e) {
DialogResult result = MessageBox.Show(Language.GetString("imgur", LangKey.clear_question), "Imgur", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes) {
config.runtimeImgurHistory.Clear();
config.ImgurUploadHistory.Clear();
Config.runtimeImgurHistory.Clear();
Config.ImgurUploadHistory.Clear();
IniConfig.Save();
redraw();
Redraw();
}
}
private void FinishedButtonClick(object sender, EventArgs e)
{
this.Hide();
Hide();
}
private void OpenButtonClick(object sender, EventArgs e) {
if (listview_imgur_uploads.SelectedItems != null && listview_imgur_uploads.SelectedItems.Count > 0) {
if (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;
System.Diagnostics.Process.Start(imgurInfo.Page);
@ -183,27 +184,23 @@ namespace GreenshotImgurPlugin {
private void listview_imgur_uploads_ColumnClick(object sender, ColumnClickEventArgs e) {
// Determine if clicked column is already the column that is being sorted.
if (e.Column == columnSorter.SortColumn) {
if (e.Column == _columnSorter.SortColumn) {
// Reverse the current sort direction for this column.
if (columnSorter.Order == SortOrder.Ascending) {
columnSorter.Order = SortOrder.Descending;
} else {
columnSorter.Order = SortOrder.Ascending;
}
_columnSorter.Order = _columnSorter.Order == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
} else {
// Set the column number that is to be sorted; default to ascending.
columnSorter.SortColumn = e.Column;
columnSorter.Order = SortOrder.Ascending;
_columnSorter.SortColumn = e.Column;
_columnSorter.Order = SortOrder.Ascending;
}
// Perform the sort with these new sort options.
this.listview_imgur_uploads.Sort();
listview_imgur_uploads.Sort();
}
void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e)
private void ImgurHistoryFormClosing(object sender, FormClosingEventArgs e)
{
instance = null;
_instance = null;
}
}
}

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -19,16 +19,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Windows.Forms;
using GreenshotPlugin.Core;
using GreenshotPlugin.Controls;
namespace GreenshotImgurPlugin {
/// <summary>
/// Description of PasswordRequestForm.
/// </summary>
public partial class SettingsForm : ImgurForm {
public SettingsForm(ImgurConfiguration config) : base() {
public SettingsForm(ImgurConfiguration config)
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
@ -38,14 +36,10 @@ namespace GreenshotImgurPlugin {
ImgurUtils.LoadHistory();
if (config.runtimeImgurHistory.Count > 0) {
historyButton.Enabled = true;
} else {
historyButton.Enabled = false;
}
historyButton.Enabled = config.runtimeImgurHistory.Count > 0;
}
void ButtonHistoryClick(object sender, EventArgs e) {
private void ButtonHistoryClick(object sender, EventArgs e) {
ImgurHistory.ShowHistory();
}
}

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -32,46 +32,44 @@ namespace GreenshotImgurPlugin {
/// </summary>
[IniSection("Imgur", Description="Greenshot Imgur Plugin configuration")]
public class ImgurConfiguration : IniSection {
[IniProperty("ImgurApiUrl", Description="Url to Imgur system.", DefaultValue= "http://api.imgur.com/2")]
public string ImgurApiUrl;
[IniProperty("ImgurApi3Url", Description = "Url to Imgur system.", DefaultValue = "https://api.imgur.com/3")]
public string ImgurApi3Url;
public string ImgurApi3Url { get; set; }
[IniProperty("UploadFormat", Description="What file type to use for uploading", DefaultValue="png")]
public OutputFormat UploadFormat;
public OutputFormat UploadFormat { get; set; }
[IniProperty("UploadJpegQuality", Description="JPEG file save quality in %.", DefaultValue="80")]
public int UploadJpegQuality;
public int UploadJpegQuality { get; set; }
[IniProperty("UploadReduceColors", Description="Reduce color amount of the uploaded image to 256", DefaultValue="False")]
public bool UploadReduceColors;
public bool UploadReduceColors { get; set; }
[IniProperty("CopyLinkToClipboard", Description = "Copy the link, which one is controlled by the UsePageLink, on the clipboard", DefaultValue = "True")]
public bool CopyLinkToClipboard;
public bool CopyLinkToClipboard { get; set; }
[IniProperty("UsePageLink", Description = "Use pagelink instead of direct link on the clipboard", DefaultValue = "False")]
public bool UsePageLink;
public bool UsePageLink { get; set; }
[IniProperty("AnonymousAccess", Description = "Use anonymous access to Imgur", DefaultValue="true")]
public bool AnonymousAccess;
public bool AnonymousAccess { get; set; }
[IniProperty("RefreshToken", Description = "Imgur refresh Token", Encrypted = true, ExcludeIfNull = true)]
public string RefreshToken;
public string RefreshToken { get; set; }
/// <summary>
/// AccessToken, not stored
/// </summary>
public string AccessToken;
public string AccessToken { get; set; }
/// <summary>
/// AccessTokenExpires, not stored
/// </summary>
public DateTimeOffset AccessTokenExpires;
public DateTimeOffset AccessTokenExpires { get; set; }
[IniProperty("AddTitle", Description = "Is the title passed on to Imgur", DefaultValue = "False")]
public bool AddTitle;
public bool AddTitle { get; set; }
[IniProperty("AddFilename", Description = "Is the filename passed on to Imgur", DefaultValue = "False")]
public bool AddFilename;
public bool AddFilename { get; set; }
[IniProperty("FilenamePattern", Description = "Filename for the Imgur upload", DefaultValue = "${capturetime:d\"yyyyMMdd-HHmm\"}")]
public string FilenamePattern;
public string FilenamePattern { get; set; }
[IniProperty("ImgurUploadHistory", Description="Imgur upload history (ImgurUploadHistory.hash=deleteHash)")]
public Dictionary<string, string> ImgurUploadHistory;
public Dictionary<string, string> ImgurUploadHistory { get; set; }
// Not stored, only run-time!
public Dictionary<string, ImgurInfo> runtimeImgurHistory = new Dictionary<string, ImgurInfo>();
@ -100,7 +98,7 @@ namespace GreenshotImgurPlugin {
SettingsForm settingsForm = null;
new PleaseWaitForm().ShowAndWait(ImgurPlugin.Attributes.Name, Language.GetString("imgur", LangKey.communication_wait),
delegate() {
delegate {
settingsForm = new SettingsForm(this);
}
);

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -20,7 +20,6 @@
*/
using System.ComponentModel;
using System.Drawing;
using Greenshot.IniFile;
using Greenshot.Plugin;
using GreenshotPlugin.Core;
@ -29,25 +28,15 @@ namespace GreenshotImgurPlugin {
/// Description of ImgurDestination.
/// </summary>
public class ImgurDestination : AbstractDestination {
private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurDestination));
private static ImgurConfiguration config = IniConfig.GetIniSection<ImgurConfiguration>();
private ImgurPlugin plugin = null;
private readonly ImgurPlugin _plugin;
public ImgurDestination(ImgurPlugin plugin) {
this.plugin = plugin;
_plugin = plugin;
}
public override string Designation {
get {
return "Imgur";
}
}
public override string Designation => "Imgur";
public override string Description {
get {
return Language.GetString("imgur", LangKey.upload_menu_item);
}
}
public override string Description => Language.GetString("imgur", LangKey.upload_menu_item);
public override Image DisplayIcon {
get {
@ -57,10 +46,10 @@ namespace GreenshotImgurPlugin {
}
public override ExportInformation ExportCapture(bool manuallyInitiated, ISurface surface, ICaptureDetails captureDetails) {
ExportInformation exportInformation = new ExportInformation(this.Designation, this.Description);
string uploadURL = null;
exportInformation.ExportMade = plugin.Upload(captureDetails, surface, out uploadURL);
exportInformation.Uri = uploadURL;
ExportInformation exportInformation = new ExportInformation(Designation, Description);
string uploadUrl;
exportInformation.ExportMade = _plugin.Upload(captureDetails, surface, out uploadUrl);
exportInformation.Uri = uploadUrl;
ProcessExport(exportInformation, surface);
return exportInformation;
}

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -27,8 +27,9 @@ namespace GreenshotImgurPlugin
/// <summary>
/// Description of ImgurInfo.
/// </summary>
public class ImgurInfo : IDisposable {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurInfo));
public class ImgurInfo : IDisposable
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurInfo));
public string Hash
{
@ -36,11 +37,13 @@ namespace GreenshotImgurPlugin
set;
}
private string deleteHash;
public string DeleteHash {
get {return deleteHash;}
set {
deleteHash = value;
private string _deleteHash;
public string DeleteHash
{
get { return _deleteHash; }
set
{
_deleteHash = value;
DeletePage = "https://imgur.com/delete/" + value;
}
}
@ -93,25 +96,23 @@ namespace GreenshotImgurPlugin
set;
}
private Image image;
public Image Image {
get {return image;}
set {
if (image != null) {
image.Dispose();
private Image _image;
public Image Image
{
get { return _image; }
set
{
_image?.Dispose();
_image = value;
}
image = value;
}
}
public ImgurInfo() {
}
/// <summary>
/// The public accessible Dispose
/// Will call the GarbageCollector to SuppressFinalize, preventing being cleaned twice
/// </summary>
public void Dispose() {
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
@ -121,16 +122,17 @@ namespace GreenshotImgurPlugin
/// When disposing==true all non-managed resources should be freed too!
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing) {
if (disposing) {
if (image != null) {
image.Dispose();
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_image?.Dispose();
}
_image = null;
}
image = null;
}
public static ImgurInfo ParseResponse(string response) {
LOG.Debug(response);
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.
@ -142,35 +144,41 @@ namespace GreenshotImgurPlugin
response = response.Replace("&reg;", "&#174;");
ImgurInfo imgurInfo = new ImgurInfo();
try {
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(response);
XmlNodeList nodes = doc.GetElementsByTagName("id");
if(nodes.Count > 0) {
imgurInfo.Hash = nodes.Item(0).InnerText;
if (nodes.Count > 0)
{
imgurInfo.Hash = nodes.Item(0)?.InnerText;
}
nodes = doc.GetElementsByTagName("hash");
if (nodes.Count > 0)
{
imgurInfo.Hash = nodes.Item(0).InnerText;
imgurInfo.Hash = nodes.Item(0)?.InnerText;
}
nodes = doc.GetElementsByTagName("deletehash");
if(nodes.Count > 0) {
imgurInfo.DeleteHash = nodes.Item(0).InnerText;
if (nodes.Count > 0)
{
imgurInfo.DeleteHash = nodes.Item(0)?.InnerText;
}
nodes = doc.GetElementsByTagName("type");
if(nodes.Count > 0) {
imgurInfo.ImageType = nodes.Item(0).InnerText;
if (nodes.Count > 0)
{
imgurInfo.ImageType = nodes.Item(0)?.InnerText;
}
nodes = doc.GetElementsByTagName("title");
if(nodes.Count > 0) {
imgurInfo.Title = nodes.Item(0).InnerText;
if (nodes.Count > 0)
{
imgurInfo.Title = nodes.Item(0)?.InnerText;
}
nodes = doc.GetElementsByTagName("datetime");
if(nodes.Count > 0) {
if (nodes.Count > 0)
{
// Version 3 has seconds since Epoch
double secondsSince;
if (double.TryParse(nodes.Item(0).InnerText, out 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;
@ -179,35 +187,30 @@ namespace GreenshotImgurPlugin
nodes = doc.GetElementsByTagName("original");
if (nodes.Count > 0)
{
imgurInfo.Original = nodes.Item(0).InnerText.Replace("http:", "https:");
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:");
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:");
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);
imgurInfo.Page = $"https://imgur.com/{imgurInfo.Hash}";
}
nodes = doc.GetElementsByTagName("small_square");
if(nodes.Count > 0) {
imgurInfo.SmallSquare = nodes.Item(0).InnerText;
imgurInfo.SmallSquare = nodes.Count > 0 ? nodes.Item(0)?.InnerText : $"http://i.imgur.com/{imgurInfo.Hash}s.png";
}
nodes = doc.GetElementsByTagName("large_thumbnail");
if(nodes.Count > 0)
catch (Exception e)
{
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);
Log.ErrorFormat("Could not parse Imgur response due to error {0}, response was: {1}", e.Message, response);
}
return imgurInfo;
}

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -35,13 +35,13 @@ namespace GreenshotImgurPlugin {
/// This is the ImgurPlugin code
/// </summary>
public class ImgurPlugin : IGreenshotPlugin {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(ImgurPlugin));
private static ImgurConfiguration config;
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ImgurPlugin));
private static ImgurConfiguration _config;
public static PluginAttribute Attributes;
private IGreenshotHost host;
private ComponentResourceManager resources;
private ToolStripMenuItem historyMenuItem = null;
private ToolStripMenuItem itemPlugInConfig;
private IGreenshotHost _host;
private ComponentResourceManager _resources;
private ToolStripMenuItem _historyMenuItem;
private ToolStripMenuItem _itemPlugInConfig;
public void Dispose() {
Dispose(true);
@ -50,20 +50,17 @@ namespace GreenshotImgurPlugin {
protected virtual void Dispose(bool disposing) {
if (disposing) {
if (historyMenuItem != null) {
historyMenuItem.Dispose();
historyMenuItem = null;
if (_historyMenuItem != null) {
_historyMenuItem.Dispose();
_historyMenuItem = null;
}
if (itemPlugInConfig != null) {
itemPlugInConfig.Dispose();
itemPlugInConfig = null;
if (_itemPlugInConfig != null) {
_itemPlugInConfig.Dispose();
_itemPlugInConfig = null;
}
}
}
public ImgurPlugin() {
}
public IEnumerable<IDestination> Destinations() {
yield return new ImgurDestination(this);
}
@ -75,114 +72,112 @@ namespace GreenshotImgurPlugin {
/// <summary>
/// Implementation of the IGreenshotPlugin.Initialize
/// </summary>
/// <param name="host">Use the IGreenshotPluginHost interface to register events</param>
/// <param name="captureHost">Use the ICaptureHost interface to register in the MainContextMenu</param>
/// <param name="pluginAttribute">My own attributes</param>
/// <param name="pluginHost">Use the IGreenshotPluginHost interface to register events</param>
/// <param name="myAttributes">My own attributes</param>
/// <returns>true if plugin is initialized, false if not (doesn't show)</returns>
public virtual bool Initialize(IGreenshotHost pluginHost, PluginAttribute myAttributes) {
this.host = (IGreenshotHost)pluginHost;
_host = pluginHost;
Attributes = myAttributes;
// Get configuration
config = IniConfig.GetIniSection<ImgurConfiguration>();
resources = new ComponentResourceManager(typeof(ImgurPlugin));
_config = IniConfig.GetIniSection<ImgurConfiguration>();
_resources = new ComponentResourceManager(typeof(ImgurPlugin));
ToolStripMenuItem itemPlugInRoot = new ToolStripMenuItem("Imgur");
itemPlugInRoot.Image = (Image)resources.GetObject("Imgur");
ToolStripMenuItem itemPlugInRoot = new ToolStripMenuItem("Imgur")
{
Image = (Image) _resources.GetObject("Imgur")
};
historyMenuItem = new ToolStripMenuItem(Language.GetString("imgur", LangKey.history));
historyMenuItem.Tag = host;
historyMenuItem.Click += delegate {
_historyMenuItem = new ToolStripMenuItem(Language.GetString("imgur", LangKey.history))
{
Tag = _host
};
_historyMenuItem.Click += delegate {
ImgurHistory.ShowHistory();
};
itemPlugInRoot.DropDownItems.Add(historyMenuItem);
itemPlugInRoot.DropDownItems.Add(_historyMenuItem);
itemPlugInConfig = new ToolStripMenuItem(Language.GetString("imgur", LangKey.configure));
itemPlugInConfig.Tag = host;
itemPlugInConfig.Click += delegate {
config.ShowConfigDialog();
_itemPlugInConfig = new ToolStripMenuItem(Language.GetString("imgur", LangKey.configure))
{
Tag = _host
};
itemPlugInRoot.DropDownItems.Add(itemPlugInConfig);
_itemPlugInConfig.Click += delegate {
_config.ShowConfigDialog();
};
itemPlugInRoot.DropDownItems.Add(_itemPlugInConfig);
PluginUtils.AddToContextMenu(host, itemPlugInRoot);
Language.LanguageChanged += new LanguageChangedHandler(OnLanguageChanged);
PluginUtils.AddToContextMenu(_host, itemPlugInRoot);
Language.LanguageChanged += OnLanguageChanged;
// retrieve history in the background
Thread backgroundTask = new Thread (new ThreadStart(CheckHistory));
backgroundTask.Name = "Imgur History";
backgroundTask.IsBackground = true;
Thread backgroundTask = new Thread(CheckHistory)
{
Name = "Imgur History",
IsBackground = true
};
backgroundTask.SetApartmentState(ApartmentState.STA);
backgroundTask.Start();
return true;
}
public void OnLanguageChanged(object sender, EventArgs e) {
if (itemPlugInConfig != null) {
itemPlugInConfig.Text = Language.GetString("imgur", LangKey.configure);
if (_itemPlugInConfig != null) {
_itemPlugInConfig.Text = Language.GetString("imgur", LangKey.configure);
}
if (historyMenuItem != null) {
historyMenuItem.Text = Language.GetString("imgur", LangKey.history);
if (_historyMenuItem != null) {
_historyMenuItem.Text = Language.GetString("imgur", LangKey.history);
}
}
private void CheckHistory() {
try {
ImgurUtils.LoadHistory();
host.GreenshotForm.BeginInvoke((MethodInvoker)delegate {
if (config.ImgurUploadHistory.Count > 0) {
historyMenuItem.Enabled = true;
_host.GreenshotForm.BeginInvoke((MethodInvoker)delegate {
if (_config.ImgurUploadHistory.Count > 0) {
_historyMenuItem.Enabled = true;
} else {
historyMenuItem.Enabled = false;
_historyMenuItem.Enabled = false;
}
});
} catch (Exception ex) {
LOG.Error("Error loading history", ex);
};
Log.Error("Error loading history", ex);
}
}
public virtual void Shutdown() {
LOG.Debug("Imgur Plugin shutdown.");
Language.LanguageChanged -= new LanguageChangedHandler(OnLanguageChanged);
Log.Debug("Imgur Plugin shutdown.");
Language.LanguageChanged -= OnLanguageChanged;
}
/// <summary>
/// Implementation of the IPlugin.Configure
/// </summary>
public virtual void Configure() {
config.ShowConfigDialog();
}
/// <summary>
/// This will be called when Greenshot is shutting down
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Closing(object sender, FormClosingEventArgs e) {
LOG.Debug("Application closing, de-registering Imgur Plugin!");
Shutdown();
_config.ShowConfigDialog();
}
/// <summary>
/// Upload the capture to imgur
/// </summary>
/// <param name="captureDetails"></param>
/// <param name="image"></param>
/// <param name="uploadURL">out string for the url</param>
/// <param name="captureDetails">ICaptureDetails</param>
/// <param name="surfaceToUpload">ISurface</param>
/// <param name="uploadUrl">out string for the url</param>
/// <returns>true if the upload succeeded</returns>
public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadURL) {
SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(config.UploadFormat, config.UploadJpegQuality, config.UploadReduceColors);
public bool Upload(ICaptureDetails captureDetails, ISurface surfaceToUpload, out string uploadUrl) {
SurfaceOutputSettings outputSettings = new SurfaceOutputSettings(_config.UploadFormat, _config.UploadJpegQuality, _config.UploadReduceColors);
try {
string filename = Path.GetFileName(FilenameHelper.GetFilenameFromPattern(config.FilenamePattern, config.UploadFormat, captureDetails));
string filename = Path.GetFileName(FilenameHelper.GetFilenameFromPattern(_config.FilenamePattern, _config.UploadFormat, captureDetails));
ImgurInfo imgurInfo = null;
// Run upload in the background
new PleaseWaitForm().ShowAndWait("Imgur plug-in", Language.GetString("imgur", LangKey.communication_wait),
delegate() {
delegate
{
imgurInfo = ImgurUtils.UploadToImgur(surfaceToUpload, outputSettings, captureDetails.Title, filename);
if (imgurInfo != null && config.AnonymousAccess) {
LOG.InfoFormat("Storing imgur upload for hash {0} and delete hash {1}", imgurInfo.Hash, imgurInfo.DeleteHash);
config.ImgurUploadHistory.Add(imgurInfo.Hash, imgurInfo.DeleteHash);
config.runtimeImgurHistory.Add(imgurInfo.Hash, imgurInfo);
if (imgurInfo != null && _config.AnonymousAccess) {
Log.InfoFormat("Storing imgur upload for hash {0} and delete hash {1}", imgurInfo.Hash, imgurInfo.DeleteHash);
_config.ImgurUploadHistory.Add(imgurInfo.Hash, imgurInfo.DeleteHash);
_config.runtimeImgurHistory.Add(imgurInfo.Hash, imgurInfo);
CheckHistory();
}
}
@ -195,34 +190,34 @@ namespace GreenshotImgurPlugin {
}
IniConfig.Save();
if (config.UsePageLink)
if (_config.UsePageLink)
{
uploadURL = imgurInfo.Page;
uploadUrl = imgurInfo.Page;
}
else
{
uploadURL = imgurInfo.Original;
uploadUrl = imgurInfo.Original;
}
if (!string.IsNullOrEmpty(uploadURL) && config.CopyLinkToClipboard)
if (!string.IsNullOrEmpty(uploadUrl) && _config.CopyLinkToClipboard)
{
try
{
ClipboardHelper.SetClipboardData(uploadURL);
ClipboardHelper.SetClipboardData(uploadUrl);
}
catch (Exception ex)
{
LOG.Error("Can't write to clipboard: ", ex);
uploadURL = null;
Log.Error("Can't write to clipboard: ", ex);
uploadUrl = null;
}
}
return true;
}
} catch (Exception e) {
LOG.Error("Error uploading.", e);
Log.Error("Error uploading.", e);
MessageBox.Show(Language.GetString("imgur", LangKey.upload_failure) + " " + e.Message);
}
uploadURL = null;
uploadUrl = null;
return false;
}
}

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -32,7 +32,7 @@ namespace GreenshotImgurPlugin {
/// Description of ImgurUtils.
/// </summary>
public static class ImgurUtils {
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 static readonly ImgurConfiguration Config = IniConfig.GetIniSection<ImgurConfiguration>();
private const string AuthUrlPattern = "https://api.imgur.com/oauth2/authorize?response_type=code&client_id={ClientId}&redirect_uri={RedirectUrl}&state={State}";
@ -64,7 +64,7 @@ namespace GreenshotImgurPlugin {
RetrieveImgurThumbnail(imgurInfo);
Config.runtimeImgurHistory.Add(hash, imgurInfo);
} else {
LOG.DebugFormat("Deleting not found ImgUr {0} from config.", hash);
Log.DebugFormat("Deleting not found ImgUr {0} from config.", hash);
Config.ImgurUploadHistory.Remove(hash);
saveNeeded = true;
}
@ -74,16 +74,16 @@ namespace GreenshotImgurPlugin {
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);
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);
Log.Error("Problem loading ImgUr history for hash " + hash, wE);
}
} catch (Exception e) {
LOG.Error("Problem loading ImgUr history for hash " + hash, e);
Log.Error("Problem loading ImgUr history for hash " + hash, e);
}
}
if (saveNeeded) {
@ -119,7 +119,7 @@ namespace GreenshotImgurPlugin {
if (filename != null && Config.AddFilename) {
otherParameters.Add("name", filename);
}
string responseString;
string responseString = null;
if (Config.AnonymousAccess) {
// add key, we only use the other parameters for the AnonymousAccess
//otherParameters.Add("key", IMGUR_ANONYMOUS_API_KEY);
@ -133,32 +133,40 @@ namespace GreenshotImgurPlugin {
ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings);
}
using (WebResponse response = webRequest.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) {
using (WebResponse response = webRequest.GetResponse())
{
LogRateLimitInfo(response);
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream, true))
{
responseString = reader.ReadToEnd();
}
LogRateLimitInfo(response);
}
}
} catch (Exception ex) {
LOG.Error("Upload to imgur gave an exeption: ", ex);
Log.Error("Upload to imgur gave an exeption: ", ex);
throw;
}
} else {
var oauth2Settings = new OAuth2Settings();
oauth2Settings.AuthUrlPattern = AuthUrlPattern;
oauth2Settings.TokenUrl = TokenUrl;
oauth2Settings.RedirectUrl = "https://imgur.com";
oauth2Settings.CloudServiceName = "Imgur";
oauth2Settings.ClientId = ImgurCredentials.CONSUMER_KEY;
oauth2Settings.ClientSecret = ImgurCredentials.CONSUMER_SECRET;
oauth2Settings.AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser;
oauth2Settings.BrowserSize = new Size(680, 880);
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
oauth2Settings.RefreshToken = Config.RefreshToken;
oauth2Settings.AccessToken = Config.AccessToken;
oauth2Settings.AccessTokenExpires = Config.AccessTokenExpires;
try
{
@ -179,6 +187,10 @@ namespace GreenshotImgurPlugin {
IniConfig.Save();
}
}
if (string.IsNullOrEmpty(responseString))
{
return null;
}
return ImgurInfo.ParseResponse(responseString);
}
@ -188,19 +200,20 @@ namespace GreenshotImgurPlugin {
/// <param name="imgurInfo"></param>
public static void RetrieveImgurThumbnail(ImgurInfo imgurInfo) {
if (imgurInfo.SmallSquare == null) {
LOG.Warn("Imgur URL was null, not retrieving thumbnail.");
Log.Warn("Imgur URL was null, not retrieving thumbnail.");
return;
}
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);
webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest);
// 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 = Image.FromStream(responseStream);
imgurInfo.Image = ImageHelper.FromStream(responseStream);
}
}
}
@ -212,19 +225,24 @@ namespace GreenshotImgurPlugin {
/// <param name="deleteHash"></param>
/// <returns>ImgurInfo</returns>
public static ImgurInfo RetrieveImgurInfo(string hash, string deleteHash) {
string url = Config.ImgurApiUrl + "/image/" + hash;
LOG.InfoFormat("Retrieving Imgur info for {0} with url {1}", hash, url);
string url = Config.ImgurApi3Url + "/image/" + hash + ".xml";
Log.InfoFormat("Retrieving Imgur info for {0} with url {1}", hash, url);
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET);
webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest);
string responseString;
string responseString = null;
try {
using (WebResponse response = webRequest.GetResponse()) {
LogRateLimitInfo(response);
using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) {
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream, true))
{
responseString = reader.ReadToEnd();
}
}
}
} catch (WebException wE) {
if (wE.Status == WebExceptionStatus.ProtocolError) {
if (((HttpWebResponse)wE.Response).StatusCode == HttpStatusCode.NotFound) {
@ -233,9 +251,13 @@ namespace GreenshotImgurPlugin {
}
throw;
}
LOG.Debug(responseString);
ImgurInfo imgurInfo = ImgurInfo.ParseResponse(responseString);
ImgurInfo imgurInfo = null;
if (responseString != null)
{
Log.Debug(responseString);
imgurInfo = ImgurInfo.ParseResponse(responseString);
imgurInfo.DeleteHash = deleteHash;
}
return imgurInfo;
}
@ -244,21 +266,26 @@ namespace GreenshotImgurPlugin {
/// </summary>
/// <param name="imgurInfo"></param>
public static void DeleteImgurImage(ImgurInfo imgurInfo) {
LOG.InfoFormat("Deleting Imgur image for {0}", imgurInfo.DeleteHash);
Log.InfoFormat("Deleting Imgur image for {0}", imgurInfo.DeleteHash);
try {
string url = Config.ImgurApiUrl + "/delete/" + imgurInfo.DeleteHash;
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.GET);
string url = Config.ImgurApi3Url + "/image/" + imgurInfo.DeleteHash + ".xml";
HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, HTTPMethod.DELETE);
webRequest.ServicePoint.Expect100Continue = false;
SetClientId(webRequest);
string responseString;
string responseString = null;
using (WebResponse response = webRequest.GetResponse()) {
LogRateLimitInfo(response);
using (StreamReader reader = new StreamReader(response.GetResponseStream(), true)) {
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream, true))
{
responseString = reader.ReadToEnd();
}
}
LOG.InfoFormat("Delete result: {0}", responseString);
}
Log.InfoFormat("Delete result: {0}", responseString);
} catch (WebException wE) {
// Allow "Bad request" this means we already deleted it
if (wE.Status == WebExceptionStatus.ProtocolError) {
@ -280,7 +307,7 @@ namespace GreenshotImgurPlugin {
/// <param name="key"></param>
private static void LogHeader(IDictionary<string, string> nameValues, string key) {
if (nameValues.ContainsKey(key)) {
LOG.InfoFormat("key={0}", nameValues[key]);
Log.InfoFormat("key={0}", nameValues[key]);
}
}

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -22,7 +22,6 @@
using Greenshot.Plugin;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
@ -32,7 +31,7 @@ using System.Security;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Greenshot")]
[assembly: AssemblyProduct("Imgur Plugin")]
[assembly: AssemblyCopyright("Copyright (C) 2007-2015")]
[assembly: AssemblyCopyright("Copyright (C) 2007-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The PluginAttribute describes the "entryType" and if the plugin is configurable

View file

@ -174,7 +174,7 @@ namespace GreenshotPlugin.Core {
[IniProperty("ExcludeDestinations", Description = "Comma separated list of destinations which should be disabled.")]
public List<string> ExcludeDestinations;
[IniProperty("UpdateCheckInterval", Description="How many days between every update check? (0=no checks)", DefaultValue="1")]
[IniProperty("UpdateCheckInterval", Description="How many days between every update check? (0=no checks)", DefaultValue="14")]
public int UpdateCheckInterval;
[IniProperty("LastUpdateCheck", Description="Last update check")]
public DateTime LastUpdateCheck;
@ -430,12 +430,18 @@ namespace GreenshotPlugin.Core {
// Store version, this can be used later to fix settings after an update
LastSaveWithVersion = Assembly.GetEntryAssembly().GetName().Version.ToString();
} catch {
// Ignore
}
// Disable the AutoReduceColors as it causes issues with Mozzila applications and some others
OutputFileAutoReduceColors = false;
}
// Force update check to 14 days, but only if it's not turned off
if (UpdateCheckInterval < 7 && UpdateCheckInterval > 0)
{
UpdateCheckInterval = 14;
}
// Enable OneNote if upgrading from 1.1
if(ExcludeDestinations != null && ExcludeDestinations.Contains("OneNote")) {
if(LastSaveWithVersion != null && LastSaveWithVersion.StartsWith("1.1")) {

View file

@ -0,0 +1,29 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GreenshotPlugin.Core
{
public delegate TResult Func<out TResult>();
public delegate TResult Func<in T, out TResult>(T arg);
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
}

File diff suppressed because it is too large Load diff

View file

@ -41,10 +41,6 @@ namespace GreenshotPlugin.Core {
public string Link {
get {return _link;}
}
private readonly string _directLink;
public string DirectLink {
get {return _directLink;}
}
private Version _version;
public Version Version {
get {return _version;}
@ -85,11 +81,10 @@ namespace GreenshotPlugin.Core {
}
}
public SourceforgeFile(string file, string pubdate, string link, string directLink) {
public SourceforgeFile(string file, string pubdate, string link) {
this._file = file;
DateTime.TryParse(pubdate, out _pubdate);
this._link = link;
this._directLink = directLink;
}
}
/// <summary>
@ -180,9 +175,6 @@ namespace GreenshotPlugin.Core {
string subdir = match.Groups[2].Value;
string type = match.Groups[3].Value;
string file = match.Groups[4].Value;
// !!! Change this to the mirror !!!
string mirror = "kent";
string directLink = Uri.EscapeUriString("http://"+mirror+".dl.sourceforge.net/project/"+project+"/"+subdir+"/"+type+"/"+file);
Dictionary<string, SourceforgeFile> filesForType;
if (rssFiles.ContainsKey(type)) {
filesForType = rssFiles[type];
@ -190,7 +182,7 @@ namespace GreenshotPlugin.Core {
filesForType = new Dictionary<string, SourceforgeFile>();
rssFiles.Add(type, filesForType);
}
SourceforgeFile rssFile = new SourceforgeFile(file, pubdate, sfLink, directLink);
SourceforgeFile rssFile = new SourceforgeFile(file, pubdate, sfLink);
if (file.EndsWith(".exe") ||file.EndsWith(".zip")) {
string version = Regex.Replace(file, @".*[a-zA-Z_]\-", "");
version = version.Replace(@"\-[a-zA-Z]+.*","");

View file

@ -42,6 +42,7 @@
<Compile Include="Core\CaptureHandler.cs" />
<Compile Include="Core\EventDelay.cs" />
<Compile Include="Core\FastBitmap.cs" />
<Compile Include="Core\Func.cs" />
<Compile Include="Core\WmInputLangChangeRequestFilter.cs" />
<Compile Include="GlobalSuppressions.cs" />
<Compile Include="IEInterop\IHTMLBodyElement.cs" />

View file

@ -1,9 +1,9 @@
/*
* Greenshot - a free and open source screenshot tool
* Copyright (C) 2007-2015 Thomas Braun, Jens Klingen, Robin Krom
* Copyright (C) 2007-2016 Thomas Braun, Jens Klingen, Robin Krom
*
* For more information see: http://getgreenshot.org/
* The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/
* The Greenshot project is hosted on GitHub https://github.com/greenshot/greenshot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -21,9 +21,7 @@
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Security;
using log4net;
using Microsoft.Win32.SafeHandles;
using System.Reflection;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
@ -94,7 +92,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// GDIplus Helpers
/// </summary>
public static class GDIplus {
private static ILog LOG = LogManager.GetLogger(typeof(GDIplus));
private static readonly ILog Log = LogManager.GetLogger(typeof(GDIplus));
[DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)]
private static extern int GdipBitmapApplyEffect(IntPtr bitmap, IntPtr effect, ref RECT rectOfInterest, bool useAuxData, IntPtr auxData, int auxDataSize);
@ -107,7 +105,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
private static extern int GdipCreateEffect(Guid guid, out IntPtr effect);
[DllImport("gdiplus.dll", SetLastError = true, ExactSpelling = true)]
private static extern int GdipDeleteEffect(IntPtr effect);
private static Guid BlurEffectGuid = new Guid("{633C80A4-1843-482B-9EF2-BE2834C5FDD4}");
private static readonly Guid BlurEffectGuid = new Guid("{633C80A4-1843-482B-9EF2-BE2834C5FDD4}");
// Constant "FieldInfo" for getting the nativeImage from the Bitmap
private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGE = typeof(Bitmap).GetField("nativeImage", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
@ -118,7 +116,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
// Constant "FieldInfo" for getting the nativeImageAttributes from the ImageAttributes
private static readonly FieldInfo FIELD_INFO_NATIVE_IMAGEATTRIBUTES = typeof(ImageAttributes).GetField("nativeImageAttributes", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
private static bool isBlurEnabled = Environment.OSVersion.Version.Major >= 6;
private static bool _isBlurEnabled = Environment.OSVersion.Version.Major >= 6;
/// <summary>
/// Get the nativeImage field from the bitmap
/// </summary>
@ -172,14 +170,12 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// This accounts for the "bug" I reported here: http://social.technet.microsoft.com/Forums/en/w8itprogeneral/thread/99ddbe9d-556d-475a-8bab-84e25aa13a2c
/// </summary>
/// <param name="radius"></param>
/// <returns></returns>
public static bool isBlurPossible(int radius) {
if (!isBlurEnabled) {
return false;
} else if (Environment.OSVersion.Version.Minor >= 2 && radius < 20) {
/// <returns>false if blur is not possible</returns>
public static bool IsBlurPossible(int radius) {
if (!_isBlurEnabled) {
return false;
}
return true;
return Environment.OSVersion.Version.Minor < 2 || radius >= 20;
}
/// <summary>
@ -191,25 +187,31 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// <param name="expandEdges">bool true if the edges are expanded with the radius</param>
/// <returns>false if there is no GDI+ available or an exception occured</returns>
public static bool ApplyBlur(Bitmap destinationBitmap, Rectangle area, int radius, bool expandEdges) {
if (!isBlurPossible(radius)) {
if (!IsBlurPossible(radius)) {
return false;
}
IntPtr hBlurParams = IntPtr.Zero;
IntPtr hEffect = IntPtr.Zero;
try {
// Create the GDI+ BlurEffect, using the Guid
int status = GdipCreateEffect(BlurEffectGuid, out hEffect);
if (status != 0)
{
return false;
}
// Create a BlurParams struct and set the values
BlurParams blurParams = new BlurParams();
blurParams.Radius = radius;
blurParams.ExpandEdges = expandEdges;
var blurParams = new BlurParams
{
Radius = radius,
ExpandEdges = expandEdges
};
// Allocate space in unmanaged memory
hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams));
// Copy the structure to the unmanaged memory
Marshal.StructureToPtr(blurParams, hBlurParams, false);
// Create the GDI+ BlurEffect, using the Guid
int status = GdipCreateEffect(BlurEffectGuid, out hEffect);
// Set the blurParams to the effect
GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams));
@ -226,8 +228,8 @@ namespace GreenshotPlugin.UnmanagedHelpers {
// Everything worked, return true
return true;
} catch (Exception ex) {
isBlurEnabled = false;
LOG.Error("Problem using GdipBitmapApplyEffect: ", ex);
_isBlurEnabled = false;
Log.Error("Problem using GdipBitmapApplyEffect: ", ex);
return false;
} finally {
try {
@ -240,8 +242,8 @@ namespace GreenshotPlugin.UnmanagedHelpers {
Marshal.FreeHGlobal(hBlurParams);
}
} catch (Exception ex) {
isBlurEnabled = false;
LOG.Error("Problem cleaning up ApplyBlur: ", ex);
_isBlurEnabled = false;
Log.Error("Problem cleaning up ApplyBlur: ", ex);
}
}
}
@ -251,7 +253,7 @@ namespace GreenshotPlugin.UnmanagedHelpers {
/// </summary>
/// <returns>false if there is no GDI+ available or an exception occured</returns>
public static bool DrawWithBlur(Graphics graphics, Bitmap image, Rectangle source, Matrix transform, ImageAttributes imageAttributes, int radius, bool expandEdges) {
if (!isBlurPossible(radius)) {
if (!IsBlurPossible(radius)) {
return false;
}
@ -259,20 +261,26 @@ namespace GreenshotPlugin.UnmanagedHelpers {
IntPtr hEffect = IntPtr.Zero;
try {
// Create the GDI+ BlurEffect, using the Guid
int status = GdipCreateEffect(BlurEffectGuid, out hEffect);
if (status != 0)
{
return false;
}
// Create a BlurParams struct and set the values
BlurParams blurParams = new BlurParams();
blurParams.Radius = radius;
var blurParams = new BlurParams
{
Radius = radius,
ExpandEdges = false
};
//blurParams.Padding = radius;
blurParams.ExpandEdges = false;
// Allocate space in unmanaged memory
hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams));
// Copy the structure to the unmanaged memory
Marshal.StructureToPtr(blurParams, hBlurParams, true);
// Create the GDI+ BlurEffect, using the Guid
int status = GdipCreateEffect(BlurEffectGuid, out hEffect);
// Set the blurParams to the effect
GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams));
@ -284,15 +292,15 @@ namespace GreenshotPlugin.UnmanagedHelpers {
IntPtr hAttributes = GetNativeImageAttributes(imageAttributes);
// Create a RECT from the Rectangle
RECTF sourceRECF = new RECTF(source);
RECTF sourceRecf = new RECTF(source);
// Apply the effect to the bitmap in the specified area
GdipDrawImageFX(hGraphics, hBitmap, ref sourceRECF, hMatrix, hEffect, hAttributes, GpUnit.UnitPixel);
GdipDrawImageFX(hGraphics, hBitmap, ref sourceRecf, hMatrix, hEffect, hAttributes, GpUnit.UnitPixel);
// Everything worked, return true
return true;
} catch (Exception ex) {
isBlurEnabled = false;
LOG.Error("Problem using GdipDrawImageFX: ", ex);
_isBlurEnabled = false;
Log.Error("Problem using GdipDrawImageFX: ", ex);
return false;
} finally {
try {
@ -305,8 +313,8 @@ namespace GreenshotPlugin.UnmanagedHelpers {
Marshal.FreeHGlobal(hBlurParams);
}
} catch (Exception ex) {
isBlurEnabled = false;
LOG.Error("Problem cleaning up DrawWithBlur: ", ex);
_isBlurEnabled = false;
Log.Error("Problem cleaning up DrawWithBlur: ", ex);
}
}
}

View file

@ -67,12 +67,14 @@ deploy:
auth_token:
secure: 4sYcNGg7byBFtR7EkJHS8d3H3qP0u0LodlJWCV7g/4jEyv3vvVxqzh19zZ6Zgrf1
prerelease: true
draft: true
on:
build_type: UNSTABLE
- provider: GitHub
tag: Greenshot-$(build_type)-$(APPVEYOR_BUILD_VERSION)
auth_token:
secure: 4sYcNGg7byBFtR7EkJHS8d3H3qP0u0LodlJWCV7g/4jEyv3vvVxqzh19zZ6Zgrf1
draft: true
on:
build_type: RELEASE
notifications: