forked from canneverbe/Ketarin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Updater.cs
1078 lines (943 loc) · 41.6 KB
/
Updater.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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using CDBurnerXP;
using CDBurnerXP.IO;
using CookComputing.XmlRpc;
using FTPLib;
using Ketarin.Forms;
using MyDownloader.Core;
using MyDownloader.Extension.Protocols;
using Settings = CDBurnerXP.Settings;
namespace Ketarin
{
/// <summary>
/// Handles the updating process of a list of
/// application jobs.
/// </summary>
public class Updater
{
public const SecurityProtocolType DefaultHttpProtocols = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
private ApplicationJob[] m_Jobs;
private Dictionary<ApplicationJob, short> m_Progress;
private readonly Dictionary<ApplicationJob, Status> m_Status = new Dictionary<ApplicationJob,Status>();
private readonly Dictionary<ApplicationJob, long> m_Size = new Dictionary<ApplicationJob, long>();
private bool m_CancelUpdates;
protected int m_LastProgress = -1;
private List<ApplicationJobError> m_Errors;
private byte m_NoProgressCounter;
private bool m_OnlyCheck;
private int m_ThreadLimit = 2;
private readonly List<Thread> m_Threads = new List<Thread>();
private readonly CookieContainer m_Cookies = new CookieContainer();
private static readonly List<WebRequest> m_Requests = new List<WebRequest>();
private bool m_InstallUpdated;
#region Properties
/// <summary>
/// Forces all applications, even if no updates exist, to download.
/// Also ignores the CheckForUpdatesOnly property of applications.
/// </summary>
public bool ForceDownload
{
get;
set;
}
/// <summary>
/// Ignores the CheckForUpdatesOnly property of applications (for setups).
/// </summary>
public bool IgnoreCheckForUpdatesOnly
{
get;
set;
}
/// <summary>
/// Gets the list of errors which happened after an update process.
/// </summary>
public ApplicationJobError[] Errors
{
get
{
return m_Errors.ToArray();
}
}
/// <summary>
/// Gets whether or not the updating process is still ongoing.
/// </summary>
public bool IsBusy { get; private set; }
#endregion
/// <summary>
/// Represents a download status of an application.
/// </summary>
public enum Status
{
Idle,
Downloading,
UpdateAvailable,
UpdateSuccessful,
NoUpdate,
Failure,
}
#region JobProgressChangedEventArgs
/// <summary>
/// Holds all necessary information for the event that
/// the download progress of an application changed.
/// </summary>
public class JobProgressChangedEventArgs : ProgressChangedEventArgs
{
private readonly ApplicationJob m_Job;
#region Properties
/// <summary>
/// Gets the application for which the download progress changed.
/// </summary>
public ApplicationJob ApplicationJob
{
get
{
return m_Job;
}
}
#endregion
public JobProgressChangedEventArgs(int progressPercentage, ApplicationJob job)
: base(progressPercentage, null)
{
m_Job = job;
}
}
#endregion
#region JobStatusChangedEventArgs
/// <summary>
/// Holds all necessary information for the event that
/// the update status of an application changed.
/// </summary>
public class JobStatusChangedEventArgs : EventArgs
{
private readonly ApplicationJob m_Job;
private readonly Status m_NewStatus;
#region Properties
/// <summary>
/// Gets the application of which the status has changed.
/// </summary>
public ApplicationJob ApplicationJob
{
get
{
return m_Job;
}
}
/// <summary>
/// Gets the new status of the application.
/// </summary>
public Status NewStatus
{
get
{
return m_NewStatus;
}
}
#endregion
public JobStatusChangedEventArgs(ApplicationJob job, Status newStatus)
{
m_Job = job;
m_NewStatus = newStatus;
}
}
#endregion
/// <summary>
/// Occurs when the download progress of an application changed.
/// </summary>
public event EventHandler<JobProgressChangedEventArgs> ProgressChanged;
/// <summary>
/// Occurs when the upgrade status of an application changed.
/// </summary>
public event EventHandler<JobStatusChangedEventArgs> StatusChanged;
/// <summary>
/// Occurs when the updater has finished the whole upgrade process.
/// </summary>
public event EventHandler UpdateCompleted;
/// <summary>
/// Occurs when updates for applications downloaded from the online database
/// have been found and provides a list of XML definitions for those applications.
/// </summary>
public event EventHandler<GenericEventArgs<string[]>> UpdatesFound;
#region Public control methods
/// <summary>
/// Allows all routines involved in the update to
/// store the corresponding WebRequest here. When the user
/// cancels the process, these WebRequests wil be aborted,
/// so that it finishes more or less instantly.
/// </summary>
internal static void AddRequestToCancel(WebRequest reqest)
{
lock (m_Requests)
{
m_Requests.Add(reqest);
}
}
/// <summary>
/// Cancels the updating progress.
/// </summary>
public void Cancel()
{
m_CancelUpdates = true;
lock (m_Requests)
{
foreach (WebRequest req in m_Requests)
{
try
{
req.Abort();
}
catch (NotSupportedException)
{
continue;
}
catch (InvalidOperationException)
{
// ObjectDisposedException with FileWebRequest
continue;
}
}
m_Requests.Clear();
}
}
/// <summary>
/// Returns the download size of a given application in bytes.
/// </summary>
/// <returns>-1 if the size cannot be determined, -2 if no file size has been determined yet</returns>
public long GetDownloadSize(ApplicationJob job)
{
if (m_Size == null || !m_Size.ContainsKey(job)) return -1;
return m_Size[job];
}
/// <summary>
/// Returns the progress of the given application.
/// </summary>
/// <returns>-1 for no progress yet, otherwise 0 to 100</returns>
public short GetProgress(ApplicationJob job)
{
if (m_Progress == null || !m_Progress.ContainsKey(job)) return -1;
return m_Progress[job];
}
/// <summary>
/// Returns the current status of a given application.
/// </summary>
/// <returns>Idle by default</returns>
public Status GetStatus(ApplicationJob job)
{
if (m_Status == null || !m_Status.ContainsKey(job)) return Status.Idle;
return m_Status[job];
}
/// <summary>
/// Starts one or more threads which update the given
/// applications asynchronously.
/// </summary>
/// <param name="onlyCheck">Specifies whether or not to download the updates</param>
public void BeginUpdate(ApplicationJob[] jobs, bool onlyCheck, bool installUpdated)
{
IsBusy = true;
m_Jobs = jobs;
m_ThreadLimit = Convert.ToInt32(Settings.GetValue("ThreadCount", 2));
m_OnlyCheck = onlyCheck;
m_InstallUpdated = installUpdated;
m_Requests.Clear();
// Initialise progress and status
m_Progress = new Dictionary<ApplicationJob, short>();
foreach (ApplicationJob job in m_Jobs)
{
m_Progress[job] = (short)((ForceDownload || job.Enabled) ? 0 : -1);
m_Status[job] = Status.Idle;
m_Size[job] = -2;
}
m_Threads.Clear();
Thread thread = new Thread(UpdateApplications);
thread.Start();
}
/// <summary>
/// Checks for which of the given applications updates
/// are available asynchronously.
/// </summary>
public void BeginCheckForOnlineUpdates(ApplicationJob[] jobs)
{
DateTime lastUpdate = (DateTime)Settings.GetValue("LastUpdateCheck", DateTime.MinValue);
if (lastUpdate.Date == DateTime.Now.Date)
{
// Only check once a day
return;
}
Settings.SetValue("LastUpdateCheck", DateTime.Now);
Thread thread = new Thread(this.CheckForOnlineUpdates) {IsBackground = true};
thread.Start(jobs);
}
/// <summary>
/// Checks for which of the given applications updates
/// are available. Fires an event when finished.
/// </summary>
private void CheckForOnlineUpdates(object argument)
{
ApplicationJob[] jobs = argument as ApplicationJob[];
// Build an array containing all GUIDs and dates
List<RpcAppGuidAndDate> sendInfo = new List<RpcAppGuidAndDate>();
foreach (ApplicationJob job in jobs.Where(job => !job.CanBeShared))
{
sendInfo.Add(new RpcAppGuidAndDate(job.Guid, job.DownloadDate));
}
if (sendInfo.Count == 0)
{
// Nothing to do
return;
}
try
{
IKetarinRpc proxy = XmlRpcProxyGen.Create<IKetarinRpc>();
string[] updatedApps = proxy.GetUpdatedApplications(sendInfo.ToArray());
OnUpdatesFound(updatedApps);
}
catch (Exception ex)
{
// If updating fails, it does not hurt and should not annoy anyone.
// Just write a log entry, just in case
LogDialog.Log("Failed checking for online database updates", ex);
}
}
#endregion
/// <summary>
/// Performs the actual update check for the current applications.
/// Starts multiple threads if necessary.
/// </summary>
private void UpdateApplications()
{
m_CancelUpdates = false;
m_Errors = new List<ApplicationJobError>();
LogDialog.Log(string.Format("Update started with {0} application(s)", m_Jobs.Length));
try
{
ApplicationJob previousJob = null;
foreach (ApplicationJob job in m_Jobs)
{
// Skip if disabled
if (!job.Enabled && m_Jobs.Length > 1) continue;
// Wait until we can start a new thread:
// - Thread limit is not reached
// - The next application is not to be downloaded exclusively
// - The application previously started is not to be downloaded exclusively
// - Setup is taking place
while (m_Threads.Count >= m_ThreadLimit || (m_Threads.Count > 0 && (m_InstallUpdated || job.ExclusiveDownload || (previousJob != null && previousJob.ExclusiveDownload))))
{
Thread.Sleep(200);
foreach (Thread activeThread in m_Threads)
{
if (!activeThread.IsAlive)
{
m_Threads.Remove(activeThread);
break;
}
}
}
// Stop if cancelled
if (m_CancelUpdates) break;
Thread newThread = new Thread(this.StartNewThread);
previousJob = job;
newThread.Start(job);
m_Threads.Add(newThread);
}
// Now, wait until all threads have finished
while (m_Threads.Count > 0)
{
Thread.Sleep(200);
foreach (Thread activeThread in m_Threads)
{
if (!activeThread.IsAlive)
{
m_Threads.Remove(activeThread);
break;
}
}
}
try
{
string postUpdateCommand = Settings.GetValue("PostUpdateCommand", "") as string;
ScriptType postUpdateCommandType = Command.ConvertToScriptType(Settings.GetValue("PostUpdateCommandType", ScriptType.Batch.ToString()) as string);
new Command(postUpdateCommand, postUpdateCommandType).Execute(null);
}
catch (ApplicationException ex)
{
LogDialog.Log("Post update command failed.", ex);
}
LogDialog.Log("Update finished");
}
finally
{
IsBusy = false;
m_Progress.Clear();
m_Size.Clear();
OnUpdateCompleted();
}
}
/// <summary>
/// Performs the update process of a single application.
/// Catches most exceptions and stores them for later use.
/// </summary>
private void StartNewThread(object paramJob)
{
ApplicationJob job = paramJob as ApplicationJob;
m_Status[job] = Status.Downloading;
OnStatusChanged(job);
string requestedUrl = string.Empty;
int numTries = 0;
int maxTries = Convert.ToInt32(Settings.GetValue("RetryCount", 1));
try
{
while (numTries < maxTries)
{
try
{
numTries++;
m_Status[job] = DoDownload(job, out requestedUrl);
// If there is a custom column variable, and it has not been been downloaded yet,
// make sure that we fetch it now "unnecessarily" so that the column contains a current value.
Dictionary<string, string> customColumns = SettingsDialog.CustomColumns;
foreach (KeyValuePair<string, string> column in customColumns)
{
if (!string.IsNullOrEmpty(column.Value) && !job.Variables.HasVariableBeenDownloaded(column.Value))
{
job.Variables.ReplaceAllInString("{" + column.Value.TrimStart('{').TrimEnd('}') + "}");
}
}
if (customColumns.Count > 0)
{
job.Save(); // cached variable content
}
// Install if updated
if (m_InstallUpdated && m_Status[job] == Status.UpdateSuccessful)
{
job.Install(null);
}
// If no exception happened, we immediately leave the loop
break;
}
catch (SQLiteException ex)
{
// If "locked" exception (slow USB device eg.) continue trying
if (ex.ErrorCode == (int)SQLiteErrorCode.Locked)
{
numTries--;
LogDialog.Log(job, ex);
}
else
{
throw;
}
}
catch (Exception ex)
{
WebException webException = ex as WebException;
if (webException != null && webException.Status == WebExceptionStatus.RequestCanceled)
{
// User cancelled the process -> Do nothing
m_Status[job] = Status.Failure;
break;
}
// Only throw an exception if we have run out of tries
if (numTries == maxTries)
{
throw;
}
else
{
LogDialog.Log(job, ex);
}
}
}
}
catch (WebException ex)
{
LogDialog.Log(job, ex);
this.HandleUpdateFailed(job, new ApplicationJobError(job, ex, (ex.Response != null) ? ex.Response.ResponseUri.ToString() : requestedUrl));
}
catch (FileNotFoundException ex)
{
// Executing command failed
LogDialog.Log(job, ex);
m_Errors.Add(new ApplicationJobError(job, ex));
}
catch (Win32Exception ex)
{
// Executing command failed
LogDialog.Log(job, ex);
m_Errors.Add(new ApplicationJobError(job, ex));
}
catch (IOException ex)
{
LogDialog.Log(job, ex);
this.HandleUpdateFailed(job, new ApplicationJobError(job, ex));
}
catch (UnauthorizedAccessException ex)
{
LogDialog.Log(job, ex);
this.HandleUpdateFailed(job, new ApplicationJobError(job, ex));
}
catch (UriFormatException ex)
{
LogDialog.Log(job, ex);
this.HandleUpdateFailed(job, new ApplicationJobError(job, ex, requestedUrl));
}
catch (NotSupportedException ex)
{
// Invalid URI prefix
LogDialog.Log(job, ex);
this.HandleUpdateFailed(job, new ApplicationJobError(job, ex, requestedUrl));
}
catch (NonBinaryFileException ex)
{
LogDialog.Log(job, ex);
this.HandleUpdateFailed(job, new ApplicationJobError(job, ex, requestedUrl));
}
catch (TargetPathInvalidException ex)
{
LogDialog.Log(job, ex);
this.HandleUpdateFailed(job, new ApplicationJobError(job, ex, requestedUrl));
}
catch (CommandErrorException ex)
{
LogDialog.Log(job, ex);
this.HandleUpdateFailed(job, new ApplicationJobError(job, ex, requestedUrl));
}
catch (ApplicationException ex)
{
// Error executing custom C# script
LogDialog.Log(job, ex);
m_Errors.Add(new ApplicationJobError(job, ex));
}
catch (SQLiteException ex)
{
LogDialog.Log(job, ex);
this.HandleUpdateFailed(job, new ApplicationJobError(job, ex, requestedUrl));
}
m_Progress[job] = 100;
OnStatusChanged(job);
}
/// <summary>
/// Handles download failure (set failed state, add to errors) and executes the "update failed"
/// command for additional control.
/// </summary>
private void HandleUpdateFailed(ApplicationJob job, ApplicationJobError error)
{
// Execute: Default update failed command
string updateFailedCommand = Settings.GetValue("UpdateFailedCommand", "") as string;
ScriptType defaultPreCommandType = Command.ConvertToScriptType(Settings.GetValue("UpdateFailedCommandType", ScriptType.Batch.ToString()) as string);
m_Status[job] = Status.Failure;
if (!string.IsNullOrEmpty(updateFailedCommand))
{
int exitCode = new Command(updateFailedCommand, defaultPreCommandType).Execute(job, null, error);
// Do not show failure in error window.
if (exitCode == 1)
{
LogDialog.Log(job, "Update failed command returned '1', ignoring error");
return;
}
}
m_Errors.Add(error);
}
/// <summary>
/// Executes the actual download (determines the URL to download from). Does not handle exceptions,
/// but takes care of proper cleanup.
/// </summary>
/// <param name="job">The job to process</param>
/// <param name="requestedUrl">The URL from which has been downloaded</param>
/// <returns>true, if a new update has been found and downloaded, false otherwise</returns>
protected Status DoDownload(ApplicationJob job, out string requestedUrl)
{
// Lower security policies
try
{
ServicePointManager.CheckCertificateRevocationList = false;
}
catch (PlatformNotSupportedException)
{
// .NET bug under special circumstances
}
ServicePointManager.ServerCertificateValidationCallback = delegate {
return true;
};
// If we want to download multiple files simultaneously
// from the same server, we need to "remove" the connection limit.
ServicePointManager.DefaultConnectionLimit = 50;
string downloadUrl;
if (job.DownloadSourceType == ApplicationJob.SourceType.FileHippo)
{
downloadUrl = ExternalServices.FileHippoDownloadUrl(job.FileHippoId, job.AvoidDownloadBeta);
}
else
{
downloadUrl = job.FixedDownloadUrl;
// Now replace variables
downloadUrl = job.Variables.ReplaceAllInString(downloadUrl);
}
requestedUrl = downloadUrl;
if (string.IsNullOrEmpty(downloadUrl))
{
// No download URL specified, only check if update is required
if (job.RequiresDownload(null, null))
{
return Status.UpdateAvailable;
}
return Status.NoUpdate;
}
Uri url = new Uri(downloadUrl);
return this.DoDownload(job, url);
}
/// <summary>
/// Executes the actual download from an URL. Does not handle exceptions,
/// but takes care of proper cleanup.
/// </summary>
/// <exception cref="NonBinaryFileException">This exception is thrown, if the resulting file is not of a binary type</exception>
/// <exception cref="TargetPathInvalidException">This exception is thrown, if the resulting target path of an application is not valid</exception>
/// <param name="job">The job to process</param>
/// <param name="urlToRequest">URL from which should be downloaded</param>
/// <returns>true, if a new update has been found and downloaded, false otherwise</returns>
protected Status DoDownload(ApplicationJob job, Uri urlToRequest)
{
// Determine number of segments to create
int segmentCount = Convert.ToInt32(Settings.GetValue("SegmentCount", 1));
job.Variables.ResetDownloadCount();
WebRequest req = KetarinProtocolProvider.CreateRequest(urlToRequest, job, this.m_Cookies);
AddRequestToCancel(req);
using (WebResponse response = WebClient.GetResponse(req))
{
LogDialog.Log(job, "Server source file: " + req.RequestUri.AbsolutePath);
// Occasionally, websites are not available and an error page is encountered
// For the case that the content type is just plain wrong, ignore it if the size is higher than 500KB
HttpWebResponse httpResponse = response as HttpWebResponse;
if (httpResponse != null && response.ContentLength < 500000)
{
if (response.ContentType.StartsWith("text/xml") || response.ContentType.StartsWith("application/xml"))
{
// If an XML file is served, maybe we have a PAD file
ApplicationJob padJob = ApplicationJob.ImportFromPad(httpResponse);
if (padJob != null)
{
job.CachedPadFileVersion = padJob.CachedPadFileVersion;
return this.DoDownload(job, new Uri(padJob.FixedDownloadUrl));
}
}
if (response.ContentType.StartsWith("text/html"))
{
bool avoidNonBinary = (bool)Settings.GetValue("AvoidDownloadingNonBinaryFiles", true);
if (httpResponse.StatusCode != HttpStatusCode.OK || avoidNonBinary)
{
throw NonBinaryFileException.Create(response.ContentType, httpResponse.StatusCode);
}
}
}
long fileSize = GetContentLength(response);
if (fileSize == 0)
{
throw new IOException("Source file on server is empty (ContentLength = 0).");
}
string targetFileName = job.GetTargetFile(response, urlToRequest.AbsoluteUri);
LogDialog.Log(job, "Determined target file name: " + targetFileName);
// Only download, if the file size or date has changed
if (!ForceDownload && !job.RequiresDownload(response, targetFileName))
{
// If file already exists (created by user),
// the download is not necessary. We still need to
// set the file name.
// If the file exists, but not at the target location
// (after renaming), do not reset the previous location.
if (File.Exists(targetFileName))
{
job.PreviousLocation = targetFileName;
}
job.Save();
return Status.NoUpdate;
}
// Skip downloading!
// Installing also requires a forced download
if (!ForceDownload && !m_InstallUpdated && (m_OnlyCheck || (job.CheckForUpdatesOnly && !IgnoreCheckForUpdatesOnly)))
{
LogDialog.Log(job, "Skipped downloading updates");
return Status.UpdateAvailable;
}
// Execute: Default pre-update command
string defaultPreCommand = Settings.GetValue("PreUpdateCommand", "") as string;
// For starting external download managers: {preupdate-url}
defaultPreCommand = UrlVariable.Replace(defaultPreCommand, "preupdate-url", urlToRequest.ToString(), job);
ScriptType defaultPreCommandType = Command.ConvertToScriptType(Settings.GetValue("PreUpdateCommandType", ScriptType.Batch.ToString()) as string);
int exitCode = new Command(defaultPreCommand, defaultPreCommandType).Execute(job, targetFileName);
if (exitCode == 1)
{
LogDialog.Log(job, "Default pre-update command returned '1', download aborted");
throw new CommandErrorException();
}
else if (exitCode == 2)
{
LogDialog.Log(job, "Default pre-update command returned '2', download skipped");
return Status.UpdateAvailable;
}
// Execute: Application pre-update command
exitCode = new Command(UrlVariable.Replace(job.ExecutePreCommand, "preupdate-url", urlToRequest.ToString(), job), job.ExecutePreCommandType).Execute(job, targetFileName);
if (exitCode == 1)
{
LogDialog.Log(job, "Pre-update command returned '1', download aborted");
throw new CommandErrorException();
}
else if (exitCode == 2)
{
LogDialog.Log(job, "Pre-update command returned '2', download skipped");
return Status.UpdateAvailable;
}
else if (exitCode == 3)
{
LogDialog.Log(job, "Pre-update command returned '3', external download");
job.LastUpdated = DateTime.Now;
job.Save();
job.ExecutePostUpdateCommands();
return Status.UpdateSuccessful;
}
// Read all file contents to a temporary location
string tmpLocation = Path.GetTempFileName();
DateTime lastWriteTime = ApplicationJob.GetLastModified(response);
// Only use segmented downloader with more than one segment.
if (segmentCount > 1)
{
// Response can be closed now, new one will be created.
response.Dispose();
m_Size[job] = fileSize;
Downloader d = new Downloader(new ResourceLocation { Url = urlToRequest.AbsoluteUri, ProtocolProvider = new KetarinProtocolProvider(job, m_Cookies) }, null, tmpLocation, segmentCount);
d.Start();
while (d.State < DownloaderState.Ended)
{
if (m_CancelUpdates)
{
d.Pause();
break;
}
this.OnProgressChanged(d.Segments.Sum(x => x.Transfered), fileSize, job);
Thread.Sleep(250);
}
if (d.State == DownloaderState.EndedWithError)
{
throw d.LastError;
}
}
else
{
// Read contents from the web and put into file
using (Stream sourceFile = response.GetResponseStream())
{
using (FileStream targetFile = File.Create(tmpLocation))
{
long byteCount = 0;
int readBytes;
m_Size[job] = fileSize;
// Only create buffer once and re-use.
const int bufferSize = 1024 * 1024;
byte[] buffer = new byte[bufferSize];
do
{
if (m_CancelUpdates) break;
// Some adjustment for SCP download: Read only up to the max known bytes
int maxRead = (fileSize > 0) ? (int) Math.Min(fileSize - byteCount, bufferSize) : bufferSize;
if (maxRead == 0) break;
readBytes = sourceFile.Read(buffer, 0, maxRead);
if (readBytes > 0) targetFile.Write(buffer, 0, readBytes);
byteCount += readBytes;
this.OnProgressChanged(byteCount, fileSize, job);
} while (readBytes > 0);
}
}
}
if (m_CancelUpdates)
{
m_Progress[job] = 0;
OnStatusChanged(job);
return Status.Failure;
}
// If each version has a different file name (version number),
// we might only want to keep one of them. Also, we might
// want to free some space on the target location.
if (job.DeletePreviousFile && job.NumberOfRevisions <= 1)
{
PathEx.TryDeleteFiles(job.PreviousLocation);
}
try
{
File.SetLastWriteTime(tmpLocation, lastWriteTime);
}
catch (ArgumentException)
{
// Invalid file date. Ignore and just use DateTime.Now
}
// File downloaded. Now let's check if the hash value is valid or abort otherwise!
if (!string.IsNullOrEmpty(job.HashVariable) && job.HashType != HashType.None)
{
string varName = job.HashVariable.Trim('{', '}');
string expectedHash = job.Variables.ReplaceAllInString("{" + varName + "}").Trim();
// Compare online hash with actual current hash.
if (!string.IsNullOrEmpty(expectedHash))
{
string currentHash = job.GetFileHash(tmpLocation);
if (string.Compare(expectedHash, currentHash, StringComparison.OrdinalIgnoreCase) != 0)
{
LogDialog.Log(job, string.Format("File downloaded, but hash of downloaded file {0} does not match the expected hash {1}.", currentHash, expectedHash));
File.Delete(tmpLocation);
throw new IOException("Hash verification failed.");
}
}
}
try
{
FileInfo downloadedFileInfo = new FileInfo(tmpLocation);
job.LastFileSize = downloadedFileInfo.Length;
job.LastFileDate = downloadedFileInfo.LastWriteTime;
}
catch (Exception ex)
{
LogDialog.Log(job, ex);
}
try
{
// Before copying, we might have to create the directory
Directory.CreateDirectory(Path.GetDirectoryName(targetFileName));
// Take care of creating backups before overwriting the file if desired.
job.BackupRevisions(targetFileName);
// Copying might fail if variables have been replaced with bad values.
// However, we cannot rely on functions to clean up the path, since they
// might actually parse the path incorrectly and return an even worse path.
File.Copy(tmpLocation, targetFileName, true);
}
catch (ArgumentException)
{
throw new TargetPathInvalidException(targetFileName);
}
catch (NotSupportedException)
{
throw new TargetPathInvalidException(targetFileName);
}
File.Delete(tmpLocation);
// At this point, the update is complete
job.LastUpdated = DateTime.Now;
job.PreviousLocation = targetFileName;
}
job.Save();
job.ExecutePostUpdateCommands();
return Status.UpdateSuccessful;
}
/// <summary>
/// Determines the actual content length in a more reliable
/// way for FTP downloads.
/// </summary>
/// <returns>-1 if no size could be determined</returns>
private static long GetContentLength(WebResponse response)
{
HttpWebResponse http = response as HttpWebResponse;
if (http != null)
{
return http.ContentLength;
}
FtpWebResponse ftp = response as FtpWebResponse;
if (ftp != null)
{
if (ftp.ContentLength > 0)
{
return ftp.ContentLength;
}
else
{
// There is a problem with the .NET FTP implementation:
// "TYPE I" is never sent unless a file is requested, but is sometimes
// required by FTP servers to get the file size (otherwise error 550).
// Thus, we use a custom FTP library from code project for this task.
FTP ftpConnection = null;
try
{
ftpConnection = new FTP(response.ResponseUri.Host, "anonymous", "[email protected]");
return ftpConnection.GetFileSize(response.ResponseUri.LocalPath);
}
catch (Exception)
{
// Limited trust in this code...
return -1;
}
finally
{
if (ftpConnection != null) ftpConnection.Disconnect();
}
}
}
ScpWebResponse scp = response as ScpWebResponse;