Menu

[r2337]: / trunk / Src / UUpdateMgr.pas  Maximize  Restore  History

Download this file

461 lines (424 with data), 14.2 kB

  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
{
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/
*
* Copyright (C) 2005-2012, Peter Johnson (www.delphidabbler.com).
*
* $Rev$
* $Date$
*
* Object used to manage database updates from web.
}
unit UUpdateMgr;
interface
uses
// Delphi
SysUtils,
// Project
UDOSDateTime, UEncodings, Web.UDBDownloadMgr;
type
{
TUpdateResult:
Possible results of download.
}
TUpdateResult = (
urUpdated, // files were updated: downloaded, deleted or both
urNoUpdate, // no files were updated: up to date
urCancelled, // use cancelled download
urError // an error occurred
);
{
TUpdateStatus:
Possible states during download.
}
TUpdateStatus = (
usLogOn, // logging on to web service
usCheckForUpdates, // checking for updates
usDownloadStart, // starting to download database
usDownloadEnd, // finished downloading database
usUpdating, // updating local files
usNoUpdate, // no update required
usLogOff, // logging off web service
usCompleted, // completed update process: can display result
usCancelled // cancelled update process
);
{
TUploadStatusEvent:
Event triggered when update status changes.
@param Sender [in] Reference to object triggering event.
@param Status [in] Current download status
@param Cancel [in,out] Flag that handler can set true to abort the update.
}
TUpdateStatusEvent = procedure(Sender: TObject; Status: TUpdateStatus;
var Cancel: Boolean) of object;
{
TUpdateDownloadEvent:
Event triggered when downloading data to report progress.
@param Sender [in] Reference to object triggering event.
@param BytesHandled [in] Number of bytes downloaded to date.
@param TotalBytes [in] Total number of bytes to be downloaded.
@param Cancel [in/out] Flag that handler can set true to abort the update.
}
TUpdateDownloadEvent = procedure(Sender: TObject; const BytesHandled,
TotalBytes: Int64; var Cancel: Boolean) of object;
{
TUpdateMgr:
Manages update of CodeSnip database from web.
}
TUpdateMgr = class(TObject)
strict private
fCancelled: Boolean;
{Flag true if update is cancelled}
fDownloadMgr: TDBDownloadMgr;
{Object used to interact with web service}
fLocalDir: string;
{Directory where CodeSnip "database" files are stored on local machine}
fLongError: string;
{Value of LongError property}
fShortError: string;
{Value of ShortError property}
fOnStatus: TUpdateStatusEvent;
{Event handler for OnStatus event}
fOnDownloadProgress: TUpdateDownloadEvent;
{Event handler for OnDownloadProgress event}
procedure DownloadProgresshandler(Sender: TObject; const BytesToDate,
ExpectedBytes: Int64);
{Handles download manager's OnProgress event by passing values to own
OnDownloadProgress event.
@param Sender [in] Not used.
@param BytesToDate [in] Bytes downloaded to date.
@param ExpectedBytes [in] Total number of bytes in download.
}
function LocalFileCount: Integer;
{Counts files in local database.
@return Number of files in local database.
}
function NewestLocalFileDate: IDOSDateTime;
{Finds date of most recently updated file in local database.
@return Object representing DOS file date of newest file.
}
function UpdateNeeded: Boolean;
{Checks if local files need to be updated. This is the case when there are
newer files on remote database than in local database.
@return True if update needed, false if not.
}
function PerformUpdate: Boolean;
{Updates local files from remote database.
@return True if update succeeded or false if update was cancelled.
}
function LogOn: Boolean;
{Logs on to web server.
@return True if log on successful or false if user cancelled.
}
function DownloadDatabase(out Data: TEncodedData): Boolean;
{Downloads database from web server.
@param Data [out] Receives downloaded data.
@return True on success or false if cancelled.
}
function UpdateLocalDatabase(const Data: TEncodedData): Boolean;
{Udpates files in local database from stream of data that has been
downloaded from web server.
@param Data [in] Data containing updates.
@return True if successfully updated, false if cancelled.
}
function HandleException(const E: Exception): Boolean;
{Handles various kinds of known exception, converting exceptions into long
and short messages that are stored in LongError and ShortError properties.
@param E [in] Exception to handle.
@return True if exception handled and false if not handled.
}
strict protected
function NotifyStatus(Status: TUpdateStatus): Boolean; virtual;
{Notifies change in download status by triggering OnStatus event. Checks
if download was cancelled in event handler.
@param Status [in] Status code to be notified.
@return False if cancel flagged when event handler returns, true
otherwise.
}
public
constructor Create(const LocalDir: string);
{Class constructor. Sets up object.
@param LocalDir [in] Directory storing data files on local machine.
}
destructor Destroy; override;
{Class destructor. Tears down object.
}
function Execute: TUpdateResult;
{Performs the update.
@return Value indicating whether successfully updated, no update needed,
user cancelled or error.
}
property LongError: string read fLongError;
{Full description of last update error}
property ShortError: string read fShortError;
{Abbreviated description of last update error}
property OnStatus: TUpdateStatusEvent read fOnStatus write fOnStatus;
{Event triggered when update status changes. Informs of current status and
gives user a chance to cancel the update}
property OnDownloadProgress: TUpdateDownloadEvent
read fOnDownloadProgress write fOnDownloadProgress;
{Event triggered while downloading data from web server. Tracks download
progress}
end;
implementation
uses
// Delphi
Classes,
// Project
IntfCommon, UConsts, UFileUpdater, UUtils, UExceptions;
resourcestring
// Error messages
sGeneralUpdateError = 'Update Error';
sChecksumShortError = 'Corrupt File Error';
sChecksumLongError = '%s'
+ EOL2
+ 'This is probably caused by an internet transmisson error. Please try '
+ 'downloading again. If the problem persists please report it.';
{ TUpdateMgr }
constructor TUpdateMgr.Create(const LocalDir: string);
{Class constructor. Sets up object.
@param LocalDir [in] Directory storing data files on local machine.
}
begin
inherited Create;
// Create download manager to download from remote web server
fDownloadMgr := TDBDownloadMgr.Create;
fDownloadMgr.OnProgress := DownloadProgressHandler;
// Record local data directory & ensure it exists
fLocalDir := LocalDir;
EnsureFolders(fLocalDir);
end;
destructor TUpdateMgr.Destroy;
{Class destructor. Tears down object.
}
begin
fDownloadMgr.Free;
inherited;
end;
function TUpdateMgr.DownloadDatabase(out Data: TEncodedData): Boolean;
{Downloads database from web server.
@param Data [out] Receives downloaded data.
@return True on success or false if cancelled.
}
begin
Result := False;
if not NotifyStatus(usDownloadStart) then
Exit;
Data := fDownloadMgr.GetDatabase(True);
if not NotifyStatus(usDownloadEnd) then
Exit;
Result := not fCancelled;
end;
procedure TUpdateMgr.DownloadProgresshandler(Sender: TObject;
const BytesToDate, ExpectedBytes: Int64);
{Handles download manager's OnProgress event by passing values to own
OnDownloadProgress event.
@param Sender [in] Not used.
@param BytesToDate [in] Bytes downloaded to date.
@param ExpectedBytes [in] Total number of bytes in download.
}
begin
if Assigned(fOnDownloadProgress) then
fOnDownloadProgress(Self, BytesToDate, ExpectedBytes, fCancelled);
end;
function TUpdateMgr.Execute: TUpdateResult;
{Performs the update.
@return Value indicating whether successfully updated, no update needed,
user cancelled or error.
}
begin
// Assume user cancelled
Result := urCancelled;
try
try
// Log on to web server
if not LogOn then
Exit;
// Check if we need an update
if UpdateNeeded then
begin
if not PerformUpdate then
Exit;
Result := urUpdated;
end
else
begin
if not NotifyStatus(usNoUpdate) then
Exit;
Result := urNoUpdate;
end;
// Log off web server
if not NotifyStatus(usLogOff) then
Exit;
fDownloadMgr.LogOff;
if not NotifyStatus(usCompleted) then
Exit;
except
// Handle known exceptions
on E: Exception do
begin
Result := urError;
if not HandleException(E) then
raise;
end;
end;
finally
if fCancelled then
NotifyStatus(usCancelled);
end;
end;
function TUpdateMgr.HandleException(const E: Exception): Boolean;
{Handles various kinds of known exception, converting exceptions into long and
short messages that are stored in LongError and ShortError properties.
@param E [in] Exception to handle.
@return True if exception handled and false if not handled.
}
begin
if E is EDBDownloadMgr then
begin
// Download manager exceptions provide both long and short error messages
fLongError := E.Message;
fShortError := (E as EDBDownloadMgr).ShortMsg;
Result := True;
end
else if E is EFileUpdater then
begin
// File updater exception represent checksum errors
fLongError := Format(sChecksumLongError, [E.Message]);
fShortError := sChecksumShortError;
Result := True;
end
else if E is ECodeSnip then
begin
// General non-bug exceptions
fLongError := E.Message;
fShortError := sGeneralUpdateError;
Result := True;
end
else
// Don't handle any other exception types
Result := False;
end;
function TUpdateMgr.LocalFileCount: Integer;
{Counts files in local database.
@return Number of files in local database.
}
var
LocalFiles: TStringList; // list of files in local database directory
begin
LocalFiles := TStringList.Create;
try
ListFiles(fLocalDir, '*.*', LocalFiles);
Result := LocalFiles.Count;
finally
LocalFiles.Free;
end;
end;
function TUpdateMgr.LogOn: Boolean;
{Logs on to web server.
@return True if log on successful or false if user cancelled.
}
begin
Result := False;
if not NotifyStatus(usLogOn) then
Exit;
fDownloadMgr.LogOn;
Result := True;
end;
function TUpdateMgr.NewestLocalFileDate: IDOSDateTime;
{Finds date of most recently updated file in local database.
@return Object representing DOS file date of newest file.
}
var
LocalFiles: TStringList; // list of files in local data directory
FileName: string; // name of a file in local data directory
FileDate: IDOSDateTime; // DOS date of a file
begin
Result := TDOSDateTimeFactory.CreateFromDOSTimeStamp(0);
// Get all files in directory
LocalFiles := TStringList.Create;
try
ListFiles(fLocalDir, '*.*', LocalFiles);
if LocalFiles.Count > 0 then
begin
for FileName in LocalFiles do
begin
FileDate := TDOSDateTimeFactory.CreateFromFile(FileName);
if Result.CompareTo(FileDate) < 0 then
(Result as IAssignable).Assign(FileDate);
end;
end;
finally
LocalFiles.Free;
end;
end;
function TUpdateMgr.NotifyStatus(Status: TUpdateStatus): Boolean;
{Notifies change in download status by triggering OnStatus event. Checks if
download was cancelled in event handler.
@param Status [in] Status code to be notified.
@return False if cancel flagged when event handler returns, true
otherwise.
}
begin
if Assigned(fOnStatus) then
fOnStatus(Self, Status, fCancelled);
Result := not fCancelled;
end;
function TUpdateMgr.PerformUpdate: Boolean;
{Updates local files from remote database.
@return True if update succeeded or false if update was cancelled.
}
var
Data: TEncodedData; // stores downloaded data
begin
Result := False;
if fCancelled then
Exit;
if DownloadDatabase(Data) then
Result := UpdateLocalDatabase(Data);
end;
function TUpdateMgr.UpdateLocalDatabase(const Data: TEncodedData): Boolean;
{Udpates files in local database from stream of data that has been downloaded
from web server.
@param Data [in] Data containing updates.
@return True if successfully updated, false if cancelled.
}
var
Updater: TFileUpdater; // object that performs file updates.
begin
Result := False;
if not NotifyStatus(usUpdating) then
Exit;
Updater := TFileUpdater.Create(fLocalDir, Data);
try
Updater.Execute;
Result := True;
finally
Updater.Free;
end;
end;
function TUpdateMgr.UpdateNeeded: Boolean;
{Checks if local files need to be updated. This is the case when there are
newer files on remote database than in local database, or if numbers of files
in local database and remote database differ.
@return True if update needed, false if not.
}
var
LastDatabaseUpdate: IDOSDateTime; // date of newest file in remote database
begin
Result := False;
if not NotifyStatus(usCheckForUpdates) then
Exit;
// first check if file counts match
Result := fDownloadMgr.FileCount <> LocalFileCount;
if not Result then
begin
// file count OK: compare last update dates
LastDatabaseUpdate := TDOSDateTimeFactory.CreateFromUnixTimeStamp(
StrToInt64(fDownloadMgr.LastUpdate)
);
Result := LastDatabaseUpdate.CompareTo(NewestLocalFileDate) > 0;
end;
end;
end.
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.