forked from ali-rantakari/icalBuddy
-
Notifications
You must be signed in to change notification settings - Fork 13
/
HGCLIAutoUpdater.m
497 lines (405 loc) · 16.8 KB
/
HGCLIAutoUpdater.m
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
// CLI app auto-update code
//
// http://hasseg.org/
//
/*
The MIT License
Copyright (c) 2010 Ali Rantakari
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#import "HGCLIAutoUpdater.h"
#import "HGCLIUtils.h"
NSComparisonResult versionNumberCompare(NSString *first, NSString *second)
{
if (first != nil && second != nil)
{
NSMutableArray *firstComponents = [NSMutableArray arrayWithCapacity:3];
[firstComponents addObjectsFromArray:[first componentsSeparatedByString:@"."]];
NSMutableArray *secondComponents = [NSMutableArray arrayWithCapacity:3];
[secondComponents addObjectsFromArray:[second componentsSeparatedByString:@"."]];
if ([firstComponents count] != [secondComponents count])
{
NSMutableArray *shorter;
NSMutableArray *longer;
if ([firstComponents count] > [secondComponents count])
{
shorter = secondComponents;
longer = firstComponents;
}
else
{
shorter = firstComponents;
longer = secondComponents;
}
NSUInteger countDiff = [longer count] - [shorter count];
for (NSUInteger i = 0; i < countDiff; i++)
[shorter addObject:@"0"];
}
for (NSUInteger i = 0; i < [firstComponents count]; i++)
{
int firstComponentIntVal = [[firstComponents objectAtIndex:i] intValue];
int secondComponentIntVal = [[secondComponents objectAtIndex:i] intValue];
if (firstComponentIntVal < secondComponentIntVal)
return NSOrderedAscending;
else if (firstComponentIntVal > secondComponentIntVal)
return NSOrderedDescending;
}
return NSOrderedSame;
}
else
return NSOrderedSame;
}
@implementation HGCLIAutoUpdater
@synthesize delegate;
@synthesize ansiEscapeHelper;
@synthesize appName;
@synthesize versionCheckHeaderName;
@synthesize currentVersionStr;
@synthesize latestVersionStr;
- (id) initWithAppName:(NSString *)aAppName
currentVersionStr:(NSString *)aCurrentVersionStr
{
if (!(self = [super init]))
return nil;
// set defaults
self.ansiEscapeHelper = [[[ANSIEscapeHelper alloc] init] autorelease];
self.versionCheckHeaderName = @"Orghassegsoftwarelatestversion";
self.appName = aAppName;
self.currentVersionStr = aCurrentVersionStr;
return self;
}
- (void) dealloc
{
self.delegate = nil;
self.ansiEscapeHelper = nil;
self.versionCheckHeaderName = nil;
self.appName = nil;
self.currentVersionStr = nil;
self.latestVersionStr = nil;
[super dealloc];
}
- (NSString *) latestUpdateVersionOnServerWithError:(NSError **)error
{
// check if delegate gives us the URL where we can get the latest version
NSURL *versionCheckURL = nil;
if (self.delegate != nil && [self.delegate respondsToSelector:@selector(latestVersionCheckURLWithCurrentVersion:)])
versionCheckURL = [self.delegate latestVersionCheckURLWithCurrentVersion:self.currentVersionStr];
NSCAssert((versionCheckURL != nil), @"delegate returned nil for latestVersionCheckURLWithCurrentVersion:");
NSURLRequest *request = [NSURLRequest
requestWithURL:versionCheckURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:kServerConnectTimeout
];
NSHTTPURLResponse *response = nil;
NSError *connError = nil;
[NSURLConnection
sendSynchronousRequest:request
returningResponse:&response
error:&connError
];
if (connError == nil && response != nil)
{
NSInteger statusCode = [response statusCode];
if (statusCode >= 400)
{
if (error != NULL)
*error = NS_ERROR(0, ([NSString
stringWithFormat:@"HTTP connection failed. Status code %ld: \"%@\"",
(long) statusCode,
[NSHTTPURLResponse localizedStringForStatusCode:statusCode]]));
return nil;
}
else
{
NSString *thisLatestVersionString = [[response allHeaderFields] valueForKey:self.versionCheckHeaderName];
if (thisLatestVersionString == nil)
{
if (error != NULL)
*error = NS_ERROR(0, @"Error reading latest version number from HTTP header field.");
return nil;
}
else
{
if (versionNumberCompare(self.currentVersionStr, thisLatestVersionString) == NSOrderedAscending)
return thisLatestVersionString;
}
}
}
else
{
if (error != NULL)
{
if (connError != nil)
*error = connError;
else
*error = NS_ERROR(0, @"No response from server.");
}
return nil;
}
return nil;
}
- (void) checkForUpdatesWithUI
{
Printf(@"Checking for updates... ");
NSError *versionCheckError = nil;
self.latestVersionStr = [self latestUpdateVersionOnServerWithError:&versionCheckError];
if (self.latestVersionStr == nil && versionCheckError != nil)
{
PrintfErr(@"...%@", [versionCheckError localizedDescription]);
return;
}
if (self.latestVersionStr == nil)
{
Printf(@"...you're up to date! (current & latest: %@)\n\n", self.currentVersionStr);
return;
}
Printf(@"...update found! (latest: %@ current: %@)\n\n", self.latestVersionStr, self.currentVersionStr);
// check if delegate gives us the URL for a 'latest version' release info web page
NSURL *latestVersionInfoWebURL = nil;
if (self.delegate != nil && [self.delegate respondsToSelector:@selector(latestVersionInfoWebURLWithCurrentVersion:latestVersion:)])
latestVersionInfoWebURL = [self.delegate latestVersionInfoWebURLWithCurrentVersion:self.currentVersionStr latestVersion:self.latestVersionStr];
// check if delegate gives us the URL for a 'latest version' release ZIP archive
NSURL *latestVersionZIPURL = nil;
if (self.delegate != nil && [self.delegate respondsToSelector:@selector(latestVersionZIPURLWithCurrentVersion:latestVersion:)])
latestVersionZIPURL = [self.delegate latestVersionZIPURLWithCurrentVersion:self.currentVersionStr latestVersion:self.latestVersionStr];
if (latestVersionInfoWebURL != nil)
Printf(
@"Navigate to the following URL to see the release notes and download the latest version:\n\n%@\n\n",
latestVersionInfoWebURL
);
Printf(@"What would you like to do?\n");
if (latestVersionInfoWebURL != nil)
Printf(@" w = open the release info website in my browser\n");
Printf(@" q = quit\n");
if (latestVersionZIPURL != nil)
{
Printf(@" a = show a list of what's changed since the current\n");
Printf(@" version and then choose whether to automatically\n");
Printf(@" download and install the latest version\n");
}
if (latestVersionInfoWebURL == nil && latestVersionZIPURL == nil)
return;
char inputChar;
for(;;)
{
Printf(@"[selection]: ");
scanf("%s&*c",&inputChar);
if (inputChar == 'q' || inputChar == 'Q')
return;
if (latestVersionZIPURL != nil
&& (inputChar == 'a' || inputChar == 'A'))
{
[self autoUpdateSelfFromURL:latestVersionZIPURL];
break;
}
if (latestVersionInfoWebURL != nil
&& (inputChar == 'W' || inputChar == 'w'))
{
[[NSWorkspace sharedWorkspace] openURL:latestVersionInfoWebURL];
break;
}
}
}
// This function is subject to buffer overflows and quoting issues (see the
// calls to system() and especially the snprintf() calls before them) but
// this shouldn't be an issue as long as the URLs don't have double quotes
// in them and they are not too long.
//
- (void) autoUpdateSelfFromURL:(NSURL *)latestVersionZIPURL
{
NSCAssert((self.appName != nil), @"self.appName is nil");
NSCAssert((self.currentVersionStr != nil), @"self.currentVersionStr is nil");
NSCAssert((self.latestVersionStr != nil), @"self.latestVersionStr is nil");
NSString *tempDir = NSTemporaryDirectory();
if (tempDir == nil)
tempDir = @"/tmp";
BOOL updateSuccess = NO;
int exitStatus = 0;
size_t CMD_SIZE = 10000;
char cmd [CMD_SIZE];
NSString *archiveFilename = [NSString stringWithFormat:@"%@-autoUpdate-archive.zip", escapeDoubleQuotes(self.appName)];
NSString *archivePath = [tempDir stringByAppendingPathComponent:archiveFilename];
NSString *archiveExtractDirname = [NSString stringWithFormat:@"%@-autoUpdate-tempdir", escapeDoubleQuotes(self.appName)];
NSString *archiveExtractPath = [tempDir stringByAppendingPathComponent:archiveExtractDirname];
// check if delegate gives us the URL for changelog HTML data
NSURL *whatsChangedHTMLURL = nil;
if (self.delegate != nil && [self.delegate respondsToSelector:@selector(releaseNotesHTMLURLWithCurrentVersion:latestVersion:)])
whatsChangedHTMLURL = [self.delegate releaseNotesHTMLURLWithCurrentVersion:self.currentVersionStr latestVersion:self.latestVersionStr];
if (whatsChangedHTMLURL != nil)
{
Printf(@"\n\n");
Printf(@"CHANGES SINCE THE CURRENT VERSION (%@):\n", currentVersionStr);
Printf(@"=============================================\n");
Printf(@"\n");
NSURLRequest *whatsChangedRequest = [NSURLRequest
requestWithURL:whatsChangedHTMLURL
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:kServerConnectTimeout
];
NSHTTPURLResponse *whatsChangedResponse = nil;
NSError *whatsChangedError = nil;
NSData *whatsChangedData = [NSURLConnection
sendSynchronousRequest:whatsChangedRequest
returningResponse:&whatsChangedResponse
error:&whatsChangedError
];
if (whatsChangedError == nil && whatsChangedResponse != nil && whatsChangedData != nil)
{
NSInteger statusCode = [whatsChangedResponse statusCode];
if (statusCode >= 400)
{
PrintfErr(@"\n\nFailed to load list of changes from server (HTTP status code: %d \"%@\")\n\n",
statusCode,
[NSHTTPURLResponse localizedStringForStatusCode:statusCode]
);
return;
}
else
{
NSAttributedString *whatsChangedAttrStr = [[[NSAttributedString alloc]
initWithHTML:whatsChangedData
documentAttributes:NULL
] autorelease];
NSMutableAttributedString *whatsChangedMAttrStr = [[[NSMutableAttributedString alloc] init] autorelease];
[whatsChangedMAttrStr appendAttributedString:whatsChangedAttrStr];
// fix bullet points (replace tabs after bullets with spaces)
replaceInMutableAttrStr(whatsChangedMAttrStr, @"•\t", ATTR_STR(@"• "));
wordWrapMutableAttrStr(whatsChangedMAttrStr, 80);
NSString *whatsChangedFinalOutput = [self.ansiEscapeHelper ansiEscapedStringWithAttributedString:whatsChangedMAttrStr];
Print(whatsChangedFinalOutput);
}
}
else
{
PrintfErr(@"\n\nFailed to load list of changes from server (error: %@)\n\n",
(whatsChangedError != nil)?[whatsChangedError localizedDescription]:@"?"
);
goto cleanup;
}
}
Printf(@"\n\n");
Printf(@"=============================================\n");
Printf(@"Do you want to automatically download and\n");
Printf(@"install the latest version (%@) ?\n", latestVersionStr);
char inputChar = '\0';
while(inputChar != 'y' && inputChar != 'Y' &&
inputChar != 'n' && inputChar != 'N' &&
inputChar != '\n'
)
{
Printf(@"[y/n]: ");
scanf("%s&*c",&inputChar);
}
if (inputChar != 'y' && inputChar != 'Y')
goto cleanup;
NSString *zipURLStr = [latestVersionZIPURL absoluteString];
Printf(@"\n\n");
Printf(@">> Downloading distribution archive...\n");
Printf(@"--------------------------------------------\n");
Printf(@" - downloading from: %@\n", zipURLStr);
Printf(@" - saving archive to: %@\n", archivePath);
Printf(@"\n");
snprintf(
cmd, CMD_SIZE,
"curl \"%s\" > \"%s\"",
[escapeDoubleQuotes(zipURLStr) UTF8String],
[archivePath UTF8String]
);
exitStatus = system(cmd);
if (exitStatus != 0)
{
PrintfErr(@"\n\nAutomatic update failed with exit status %i\n\n", exitStatus);
goto cleanup;
}
Printf(@"\n\n");
Printf(@">> Extracting distribution archive...\n");
Printf(@"--------------------------------------------\n");
Printf(@" - extracting to: %@\n", archiveExtractPath);
Printf(@"\n");
snprintf(
cmd, CMD_SIZE,
"mkdir -p \"%s\" && unzip \"%s\" -d \"%s\"",
[archiveExtractPath UTF8String],
[archivePath UTF8String],
[archiveExtractPath UTF8String]
);
exitStatus = system(cmd);
if (exitStatus != 0)
{
PrintfErr(@"\n\nAutomatic update failed with exit status %i\n\n", exitStatus);
goto cleanup;
}
Printf(@"\n\n");
Printf(@">> Running installation script...\n");
Printf(@"--------------------------------------------\n");
// check if delegate gives us the command for running the installer
NSString *installCmd = @"./install.command"; // default
if (self.delegate != nil && [self.delegate respondsToSelector:@selector(commandToRunInstaller)])
installCmd = [self.delegate commandToRunInstaller];
// notify delegate
if (self.delegate != nil && [self.delegate respondsToSelector:@selector(autoUpdater:willInstallVersion:)])
[self.delegate autoUpdater:self willInstallVersion:self.latestVersionStr];
snprintf(
cmd, CMD_SIZE,
"cd \"%s\" && %s",
[archiveExtractPath UTF8String],
[installCmd UTF8String]
);
exitStatus = system(cmd);
if (exitStatus != 0)
{
PrintfErr(@"\n\nAutomatic update failed with exit status %i\n\n", exitStatus);
goto cleanup;
}
updateSuccess = YES;
cleanup:
Printf(@"\n\n");
Printf(@">> Cleaning up...\n");
Printf(@"--------------------------------------------\n");
BOOL fileDeleteSuccess = NO;
if (archivePath != nil && [[NSFileManager defaultManager] fileExistsAtPath:archivePath])
{
Printf(@" - Moving distribution archive to trash\n");
fileDeleteSuccess = moveFileToTrash(archivePath);
if (!fileDeleteSuccess)
PrintfErr(@" Could not move to trash.\n");
}
if (archiveExtractPath != nil && [[NSFileManager defaultManager] fileExistsAtPath:archiveExtractPath])
{
Printf(@" - Moving temporary extract folder for distribution archive to trash\n");
fileDeleteSuccess = moveFileToTrash(archiveExtractPath);
if (!fileDeleteSuccess)
PrintfErr(@" Could not move to trash.\n");
}
if (updateSuccess)
{
Printf(@"\n\n");
Printf(@"=======================\n");
Printf(@"%@ has been successfully updated to v%@!\n", self.appName, self.latestVersionStr);
Printf(@"\n");
// notify delegate
if (self.delegate != nil && [self.delegate respondsToSelector:@selector(autoUpdater:didInstallVersion:)])
[self.delegate autoUpdater:self didInstallVersion:self.latestVersionStr];
}
else
{
// notify delegate
if (self.delegate != nil && [self.delegate respondsToSelector:@selector(autoUpdater:didFailToInstallVersion:)])
[self.delegate autoUpdater:self didFailToInstallVersion:self.latestVersionStr];
}
}
@end