forked from Rawns/Reddit-Wallpaper-Changer
-
Notifications
You must be signed in to change notification settings - Fork 8
/
HelperMethods.cs
552 lines (476 loc) · 25.5 KB
/
HelperMethods.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
using Reddit_Wallpaper_Changer.Properties;
using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
namespace Reddit_Wallpaper_Changer
{
public static class HelperMethods
{
public static void ResetManualOverride()
{
Settings.Default.manualOverride = false;
Settings.Default.Save();
}
//======================================================================
// Export user settings
//======================================================================
public static void ExportSettings(string fileName)
{
try
{
var version = Assembly.GetEntryAssembly().GetName().Version.ToString();
var fileStream = new FileStream(fileName, FileMode.Create);
var sw = new StreamWriter(fileStream);
using (var writer = new XmlTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
writer.WriteStartDocument();
writer.WriteStartElement("RWC-Settings");
writer.WriteElementString("Version", version);
writer.WriteElementString("GrabType", Settings.Default.wallpaperGrabType.ToString());
writer.WriteElementString("Subreddits", Settings.Default.subredditsUsed);
writer.WriteElementString("SearchQuery", Settings.Default.searchQuery);
writer.WriteElementString("ChangeTimerValue", Settings.Default.changeTimeValue.ToString());
writer.WriteElementString("ChangeTimerType", Settings.Default.changeTimeType.ToString());
writer.WriteElementString("StartInTray", Settings.Default.startInTray.ToString());
writer.WriteElementString("IncludeNsfw", Settings.Default.includeNsfw.ToString());
writer.WriteElementString("AutoStart", Settings.Default.autoStart.ToString());
writer.WriteElementString("UseProxy", Settings.Default.useProxy.ToString());
writer.WriteElementString("ProxyServer", Settings.Default.proxyAddress);
writer.WriteElementString("ProxyAuthentication", Settings.Default.proxyAuth.ToString());
writer.WriteElementString("DefaultSaveLocation", Settings.Default.defaultSaveLocation);
writer.WriteElementString("AutoSave", Settings.Default.autoSave.ToString());
writer.WriteElementString("AutoSaveFaves", Settings.Default.autoSaveFaves.ToString());
writer.WriteElementString("WallpaperFade", Settings.Default.wallpaperFade.ToString());
writer.WriteElementString("DisableNotifications", Settings.Default.disableNotifications.ToString());
writer.WriteElementString("SuppressDuplicates", Settings.Default.suppressDuplicates.ToString());
writer.WriteElementString("ValidateWallpaperSize", Settings.Default.sizeValidation.ToString());
writer.WriteElementString("WallpaperInfoPopup", Settings.Default.wallpaperInfoPopup.ToString());
writer.WriteElementString("AutoUpdateCheck", Settings.Default.autoUpdateCheck.ToString());
writer.WriteElementString("WallpaperFit", Settings.Default.wallpaperStyle);
writer.WriteElementString("SetOnAllVirtualDesktops", Settings.Default.setOnAllVirtualDesktops.ToString());
writer.WriteEndElement();
writer.WriteEndDocument();
}
Logger.Instance.LogMessageToFile("Settings have been successfully exported to: " + fileName, LogLevel.Information);
}
catch (Exception ex)
{
Logger.Instance.LogMessageToFile("Unexpected error exporting settings: " + ex.Message, LogLevel.Error);
throw;
}
}
//======================================================================
// Import user settings
//======================================================================
public static void ImportSettings(string fileName)
{
var doc = new XmlDocument();
doc.Load(fileName);
var xnList = doc.SelectNodes("/RWC-Settings");
foreach (XmlNode xn in xnList)
{
try
{
Settings.Default.wallpaperGrabType = int.Parse(xn["GrabType"].InnerText);
Settings.Default.subredditsUsed = xn["Subreddits"].InnerText;
Settings.Default.searchQuery = xn["SearchQuery"].InnerText;
Settings.Default.changeTimeValue = int.Parse(xn["ChangeTimerValue"].InnerText);
Settings.Default.changeTimeType = int.Parse(xn["ChangeTimerType"].InnerText);
Settings.Default.startInTray = bool.Parse(xn["StartInTray"].InnerText);
Settings.Default.includeNsfw = bool.TryParse(xn["IncludeNsfw"]?.InnerText, out var result) && result;
Settings.Default.autoStart = bool.Parse(xn["AutoStart"].InnerText);
Settings.Default.useProxy = bool.Parse(xn["UseProxy"].InnerText);
Settings.Default.proxyAddress = xn["ProxyServer"].InnerText;
Settings.Default.proxyAuth = bool.Parse(xn["ProxyAuthentication"].InnerText);
Settings.Default.defaultSaveLocation = xn["DefaultSaveLocation"].InnerText;
Settings.Default.autoSave = bool.Parse(xn["AutoSave"].InnerText);
Settings.Default.autoSaveFaves = bool.Parse(xn["AutoSaveFaves"].InnerText);
Settings.Default.wallpaperFade = bool.Parse(xn["WallpaperFade"].InnerText);
Settings.Default.disableNotifications = bool.Parse(xn["DisableNotifications"].InnerText);
Settings.Default.suppressDuplicates = bool.Parse(xn["SuppressDuplicates"].InnerText);
Settings.Default.sizeValidation = bool.Parse(xn["ValidateWallpaperSize"].InnerText);
Settings.Default.wallpaperInfoPopup = bool.Parse(xn["WallpaperInfoPopup"].InnerText);
Settings.Default.autoUpdateCheck = bool.Parse(xn["AutoUpdateCheck"].InnerText);
Settings.Default.wallpaperStyle = xn["WallpaperFit"].InnerText;
Settings.Default.setOnAllVirtualDesktops = bool.TryParse(xn["SetOnAllVirtualDesktops"]?.InnerText, out var setOnAllVirtualDesktops) && setOnAllVirtualDesktops;
Settings.Default.Save();
Logger.Instance.LogMessageToFile("Settings have been successfully imported. Restarting RWC.", LogLevel.Information);
}
catch (Exception ex)
{
Logger.Instance.LogMessageToFile("Unexpected error importing settings file: " + ex.Message, LogLevel.Error);
throw;
}
}
}
//======================================================================
// Set up proxy along with any credntials required for auth
//======================================================================
public static WebClient CreateWebClient()
{
var wc = new DecompressableWebClient();
var proxy = CreateProxy();
if (proxy != null)
wc.Proxy = proxy;
return wc;
}
public static async Task<string> UploadLogToPastebinAsync()
{
var data = new NameValueCollection
{
["api_paste_name"] = $"RWC_Log_{DateTime.Now}.log",
["api_paste_expire_date"] = "N",
["api_paste_code"] = File.ReadAllText($@"{Settings.Default.AppDataPath}\Logs\RWC.log"),
["api_dev_key"] = "017c00e3a11ee8c70499c1f4b6b933f0",
["api_option"] = "paste"
};
try
{
byte[] bytes;
using (var wc = CreateWebClient())
{
bytes = await wc.UploadValuesTaskAsync("https://pastebin.com/api/api_post.php", data).ConfigureAwait(false);
}
var response = System.Text.Encoding.UTF8.GetString(bytes);
if (response.StartsWith("Bad API request"))
{
Logger.Instance.LogMessageToFile("Failed to upload log to Pastebin: " + response, LogLevel.Information);
return null;
}
else
{
Logger.Instance.LogMessageToFile("Logfile successfully uploaded to Pastebin: " + response, LogLevel.Information);
return response;
}
}
catch (Exception ex)
{
Logger.Instance.LogMessageToFile("Error uploading logfile to Pastebin: " + ex.Message, LogLevel.Error);
return null;
}
}
//======================================================================
// Check that the selected wallpaper URL is for an image
//======================================================================
public static async Task<bool> ValidateImageAsync(RedditLink redditLink)
{
try
{
if (redditLink.Url.Contains("deviantart"))
return true;
else if (redditLink.Url.StartsWith("https://www.reddit.com/gallery/"))
return true;
else
{
Logger.Instance.LogMessageToFile("Checking to ensure the chosen wallpaper URL is for an image.", LogLevel.Information);
var imageCheck = (HttpWebRequest)WebRequest.Create(redditLink.Url);
imageCheck.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
imageCheck.Timeout = 5000;
imageCheck.Method = "HEAD";
imageCheck.MaximumAutomaticRedirections = 1;
using (var imageResponse = await imageCheck.GetResponseAsync().ConfigureAwait(false))
{
// If anything other than OK, assume that image has been deleted
if (imageResponse.ContentType.StartsWith("image/"))
{
imageCheck.Abort();
Logger.Instance.LogMessageToFile("The chosen URL is for an image.", LogLevel.Information);
redditLink.Url = imageResponse.ResponseUri.AbsoluteUri;
return true;
}
else
{
imageCheck.Abort();
return false;
}
}
}
}
catch (Exception ex)
{
Logger.Instance.LogMessageToFile(ex.ToString(), LogLevel.Error);
return false;
}
}
//======================================================================
// If the URL is an Imgur link, check the Wallpaper is still available
//======================================================================
public static async Task<bool> ValidateImgurImageAsync(string url)
{
try
{
if (url.Contains("imgur"))
{
Logger.Instance.LogMessageToFile("Checking to ensure the chosen wallpaper is still available on Imgur.", LogLevel.Information);
// A request for a deleted image on Imgur will return status code 302 & redirect to http://i.imgur.com/removed.png returning status code 200
var imgurRequest = (HttpWebRequest)WebRequest.Create(url);
imgurRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
imgurRequest.Timeout = 5000;
imgurRequest.Method = "HEAD";
imgurRequest.AllowAutoRedirect = false;
using (var imgurResponse = (HttpWebResponse)await imgurRequest.GetResponseAsync().ConfigureAwait(false))
{
if (imgurResponse.StatusCode == HttpStatusCode.OK)
{
imgurRequest.Abort();
Logger.Instance.LogMessageToFile("The chosen wallpaper is still available on Imgur.", LogLevel.Information);
return true;
}
else
{
imgurRequest.Abort();
return false;
}
}
}
return true;
}
catch
{
return true;
}
}
//======================================================================
// Save current wallpaper
//======================================================================
public static bool SaveCurrentWallpaper(string fileName)
{
try
{
var parsedFileName = StripInvalidCharactersFromFileName(fileName);
if (parsedFileName != fileName)
Logger.Instance.LogMessageToFile($"Removed illegal characters from post title: {parsedFileName}", LogLevel.Information);
var fullFilePath = $@"{Settings.Default.defaultSaveLocation}\{parsedFileName}";
if (!File.Exists(fullFilePath))
File.Copy(Settings.Default.currentWallpaperFile, fullFilePath);
else
Logger.Instance.LogMessageToFile($"Not auto saving {parsedFileName} because it already exists.", LogLevel.Warning);
return true;
}
catch (Exception Ex)
{
Logger.Instance.LogMessageToFile($"Error Saving Wallpaper: {Ex.Message}", LogLevel.Error);
return false;
}
}
public static string StripInvalidCharactersFromFileName(string fileName)
{
foreach (var c in Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(c.ToString(), "_");
}
return fileName;
}
//======================================================================
// Generate thumbnail of the wallpaper and convert to base64 to store in db
//======================================================================
public static async Task<string> GetThumbnailAsync(string url)
{
try
{
using (var wc = CreateWebClient())
{
var bytes = await wc.DownloadDataTaskAsync(url).ConfigureAwait(false);
return ConvertImageBytesToBase64String(bytes);
}
}
catch (Exception ex)
{
Logger.Instance.LogMessageToFile($"Unexpected error generating wallpaper thumbnail for URL {url}: {ex.Message}", LogLevel.Warning);
return "";
}
}
public static string ConvertImageBytesToBase64String(byte[] wallpaperBytes)
{
var wallpaperStream = new MemoryStream(wallpaperBytes);
var bitmapWidth = 150;
var bitmapHeight = 70;
using (var wallpaperBitmap = new Bitmap(wallpaperStream))
using (var thumbnailBitmap = new Bitmap(bitmapWidth, bitmapHeight))
using (var graphics = Graphics.FromImage(thumbnailBitmap))
using (var thumbnailStream = new MemoryStream())
{
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(wallpaperBitmap, new Rectangle(0, 0, bitmapWidth, bitmapHeight));
ImageCodecInfo jpegCodec = null;
foreach (var codec in ImageCodecInfo.GetImageDecoders())
{
if (codec.FormatID == ImageFormat.Jpeg.Guid)
{
jpegCodec = codec;
break;
}
}
if (jpegCodec == null)
throw new Exception("Unable to find Jpeg decoder");
var encoderParameters = new EncoderParameters();
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
thumbnailBitmap.Save(thumbnailStream, jpegCodec, encoderParameters);
return Convert.ToBase64String(thumbnailStream.ToArray());
}
}
public static Task StartSTATask(Action action)
{
var source = new TaskCompletionSource<object>();
var thread = new Thread(() =>
{
try
{
action();
source.SetResult(null);
}
catch (Exception ex)
{
source.SetException(ex);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return source.Task;
}
public static async Task<string> GetImgurJsonStringAsync(Uri uri)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "*/*";
httpWebRequest.Method = "GET";
httpWebRequest.Headers.Add("Authorization", "Client-ID 355f2ab533c2ac7");
using (var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync().ConfigureAwait(false))
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
return await streamReader.ReadToEndAsync().ConfigureAwait(false);
}
}
//======================================================================
// Remove all thumbnails
//======================================================================
public static void RemoveThumbnailCache()
{
try
{
Logger.Instance.LogMessageToFile("Removing thumbnail cache", LogLevel.Information);
var dir = new DirectoryInfo(Settings.Default.thumbnailCache);
foreach (var file in dir.EnumerateFiles("*.jpg"))
{
file.Delete();
}
Settings.Default.rebuildThumbCache = false;
Settings.Default.Save();
Logger.Instance.LogMessageToFile("Thumbnail cache erased.", LogLevel.Information);
}
catch (Exception ex)
{
Logger.Instance.LogMessageToFile("Error rebuilding thumbnail cache: " + ex.Message, LogLevel.Warning);
}
}
//======================================================================
// Set up a thumbnail cache
//======================================================================
public static void SetupThumbnailCache()
{
string thumbnailCachePath;
if (Settings.Default.thumbnailCache.Any())
thumbnailCachePath = Settings.Default.thumbnailCache;
else
thumbnailCachePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\Reddit Wallpaper Changer\ThumbnailCache";
Directory.CreateDirectory(thumbnailCachePath);
Settings.Default.thumbnailCache = thumbnailCachePath;
Settings.Default.Save();
}
//======================================================================
// Log startup info
//======================================================================
public static void LogSettings(string changeTimeType, int screenCount)
{
Logger.Instance.LogMessageToFile("Auto Start: " + Settings.Default.autoStart, LogLevel.Information);
Logger.Instance.LogMessageToFile("Start In Tray: " + Settings.Default.startInTray, LogLevel.Information);
Logger.Instance.LogMessageToFile("Include NSFW: " + Settings.Default.includeNsfw, LogLevel.Information);
Logger.Instance.LogMessageToFile("Proxy Enabled: " + Settings.Default.useProxy, LogLevel.Information);
if (Settings.Default.useProxy)
{
Logger.Instance.LogMessageToFile("Proxy Address:" + Settings.Default.proxyAddress, LogLevel.Information);
Logger.Instance.LogMessageToFile("Proxy Authentication: " + Settings.Default.proxyAuth, LogLevel.Information);
}
Logger.Instance.LogMessageToFile("AppData Directory: " + Settings.Default.AppDataPath, LogLevel.Information);
Logger.Instance.LogMessageToFile("Thumbnail Cache: " + Settings.Default.thumbnailCache, LogLevel.Information);
Logger.Instance.LogMessageToFile("Automatically check for updates: " + Settings.Default.autoUpdateCheck, LogLevel.Information);
Logger.Instance.LogMessageToFile("Save location for wallpapers: " + Settings.Default.defaultSaveLocation, LogLevel.Information);
Logger.Instance.LogMessageToFile("Auto Save Favourite Wallpapers: " + Settings.Default.autoSaveFaves, LogLevel.Information);
Logger.Instance.LogMessageToFile("Auto Save All Wallpapers: " + Settings.Default.autoSave, LogLevel.Information);
Logger.Instance.LogMessageToFile("Wallpaper Grab Type: " + Settings.Default.wallpaperGrabType, LogLevel.Information);
Logger.Instance.LogMessageToFile("Selected Subreddits: " + Settings.Default.subredditsUsed, LogLevel.Information);
Logger.Instance.LogMessageToFile("Wallpaper Fade Effect: " + Settings.Default.wallpaperFade, LogLevel.Information);
Logger.Instance.LogMessageToFile("Search Query: " + Settings.Default.searchQuery, LogLevel.Information);
Logger.Instance.LogMessageToFile("Change wallpaper every " + Settings.Default.changeTimeValue + " " + changeTimeType, LogLevel.Information);
Logger.Instance.LogMessageToFile("Number of detected displays: " + screenCount, LogLevel.Information);
Logger.Instance.LogMessageToFile("Wallpaper Position: " + Settings.Default.wallpaperStyle, LogLevel.Information);
Logger.Instance.LogMessageToFile("Set On All Virtual Desktops: " + Settings.Default.setOnAllVirtualDesktops, LogLevel.Information);
Logger.Instance.LogMessageToFile("Validate wallpaper size: " + Settings.Default.fitWallpaper, LogLevel.Information);
Logger.Instance.LogMessageToFile("Wallpaper Info Popup: " + Settings.Default.wallpaperInfoPopup, LogLevel.Information);
}
//======================================================================
// Set folder path for saving wallpapers
//======================================================================
public static void SetupSavedWallpaperLocation()
{
if (Settings.Default.defaultSaveLocation.Any()) return;
var savedWallpaperPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + @"\Saved Wallpapers";
Directory.CreateDirectory(savedWallpaperPath);
Settings.Default.defaultSaveLocation = savedWallpaperPath;
Settings.Default.Save();
}
public static void SaveToThumbnailCache(string threadId, string thumbnail)
{
var fileName = $@"{Settings.Default.thumbnailCache}\{threadId}.jpg";
if (File.Exists(fileName)) return;
try
{
using (var ms = new MemoryStream(Convert.FromBase64String(thumbnail)))
using (var image = Image.FromStream(ms))
{
image.Save(fileName);
}
}
catch (Exception ex)
{
Logger.Instance.LogMessageToFile($"Unable to save thumbnail: {thumbnail} to file: {fileName}. {ex.Message}", LogLevel.Warning);
}
}
public static IWebProxy CreateProxy()
{
if (Settings.Default.useProxy)
{
try
{
var proxy = new WebProxy(Settings.Default.proxyAddress);
if (Settings.Default.proxyAuth)
{
proxy.Credentials = new NetworkCredential(Settings.Default.proxyUser, Settings.Default.proxyPass);
proxy.UseDefaultCredentials = false;
proxy.BypassProxyOnLocal = false;
}
return proxy;
}
catch (Exception ex)
{
Logger.Instance.LogMessageToFile("Unexpeced error setting proxy: " + ex.Message, LogLevel.Error);
}
}
return null;
}
}
}