This repository was archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathmain.js
More file actions
1110 lines (963 loc) · 40 KB
/
main.js
File metadata and controls
1110 lines (963 loc) · 40 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
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
/*
* Copyright (c) 2018 - present Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/* eslint-disable indent */
/* eslint-disable max-len */
define(function (require, exports, module) {
"use strict";
var CommandManager = brackets.getModule("command/CommandManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
Commands = brackets.getModule("command/Commands"),
AppInit = brackets.getModule("utils/AppInit"),
UpdateNotification = brackets.getModule("utils/UpdateNotification"),
DocumentCommandHandlers = brackets.getModule("document/DocumentCommandHandlers"),
NodeDomain = brackets.getModule("utils/NodeDomain"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
FileUtils = brackets.getModule("file/FileUtils"),
Strings = brackets.getModule("strings"),
HealthLogger = brackets.getModule("utils/HealthLogger"),
StateHandlerModule = require("StateHandler"),
MessageIds = require("MessageIds"),
UpdateStatus = require("UpdateStatus"),
UpdateInfoBar = require("UpdateInfoBar");
var _modulePath = FileUtils.getNativeModuleDirectoryPath(module),
_nodePath = "node/AutoUpdateDomain",
_domainPath = [_modulePath, _nodePath].join("/"),
updateDomain,
domainID;
var appSupportDirectory = brackets.app.getApplicationSupportDirectory(),
updateDir = appSupportDirectory + '/updateTemp',
updateJsonPath = updateDir + '/' + 'updateHelper.json';
var StateHandler = StateHandlerModule.StateHandler,
StateHandlerMessages = StateHandlerModule.MessageKeys;
var updateJsonHandler;
var MAX_DOWNLOAD_ATTEMPTS = 6,
downloadAttemptsRemaining;
// Below Strings are to identify an AutoUpdate Event.
var autoUpdateEventNames = {
AUTOUPDATE_DOWNLOAD_START: "DownloadStarted",
AUTOUPDATE_DOWNLOAD_COMPLETED: "DownloadCompleted",
AUTOUPDATE_DOWNLOAD_FAILED: "DownloadFailed",
AUTOUPDATE_DOWNLOAD_COMPLETE_USER_CLICK_RESTART: "DownloadCompletedAndUserClickedRestart",
AUTOUPDATE_DOWNLOAD_COMPLETE_USER_CLICK_LATER: "DownloadCompletedAndUserClickedLater",
AUTOUPDATE_DOWNLOADCOMPLETE_UPDATE_BAR_RENDERED: "DownloadCompleteUpdateBarRendered",
AUTOUPDATE_INSTALLATION_FAILED: "InstallationFailed",
AUTOUPDATE_INSTALLATION_SUCCESS: "InstallationSuccess",
AUTOUPDATE_CLEANUP_FAILED: "AutoUpdateCleanUpFailed"
};
// function map for brackets functions
var functionMap = {};
var _updateParams;
//Namespacing the event
var APP_QUIT_CANCELLED = DocumentCommandHandlers.APP_QUIT_CANCELLED + ".auto-update";
var _nodeErrorMessages = {
UPDATEDIR_READ_FAILED: 0,
UPDATEDIR_CLEAN_FAILED: 1,
CHECKSUM_DID_NOT_MATCH: 2,
INSTALLER_NOT_FOUND: 3,
DOWNLOAD_ERROR: 4,
NETWORK_SLOW_OR_DISCONNECTED: 5
};
var updateProgressKey = "autoUpdateInProgress",
isAutoUpdateInitiated = false;
/**
* Checks if an auto update session is currently in progress
* @returns {boolean} - true if an auto update session is currently in progress, false otherwise
*/
function checkIfAnotherSessionInProgress() {
var result = $.Deferred();
if(updateJsonHandler) {
var state = updateJsonHandler.state;
updateJsonHandler.refresh()
.done(function() {
var val = updateJsonHandler.get(updateProgressKey);
if(val !== null) {
result.resolve(val);
} else {
result.reject();
}
})
.fail(function() {
updateJsonHandler.state = state;
result.reject();
});
}
return result.promise();
}
/**
* Checks if auto update preference is enabled or disabled
* @private
* @returns {boolean} - true if preference enabled, false otherwise
*/
function _isAutoUpdateEnabled() {
return (PreferencesManager.get("autoUpdate.AutoUpdate") !== false);
}
/**
* Receives messages from node
* @param {object} event - event received from node
* @param {object} msgObj - json containing - {
* fn - function to execute on Brackets side
* args - arguments to the above function
* requester - ID of the current requester domain
*/
function receiveMessageFromNode(event, msgObj) {
if (functionMap[msgObj.fn]) {
if(domainID === msgObj.requester) {
functionMap[msgObj.fn].apply(null, msgObj.args);
}
}
}
/*
* Checks if Brackets version got updated
* @returns {boolean} true if version updated, false otherwise
*/
function checkIfVersionUpdated() {
var latestBuildNumber = updateJsonHandler.get("latestBuildNumber"),
currentBuildNumber = Number(/-([0-9]+)/.exec(brackets.metadata.version)[1]);
return latestBuildNumber === currentBuildNumber;
}
/**
* Gets the arguments to a function in an array
* @param {object} args - the arguments object
* @returns {Array} - array of actual arguments
*/
function getFunctionArgs(args) {
if (args.length > 1) {
var fnArgs = new Array(args.length - 1),
i;
for (i = 1; i < args.length; ++i) {
fnArgs[i - 1] = args[i];
}
return fnArgs;
}
return [];
}
/**
* Posts messages to node
* @param {string} messageId - Message to be passed
*/
function postMessageToNode(messageId) {
var msg = {
fn: messageId,
args: getFunctionArgs(arguments),
requester: domainID
};
updateDomain.exec('data', msg);
}
/**
* Checks Install failure scenarios
*/
function checkInstallationStatus() {
var searchParams = {
"updateDir": updateDir,
"installErrorStr": ["ERROR:"],
"bracketsErrorStr": ["ERROR:"],
"encoding": "utf8"
},
// Below are the possible Windows Installer error strings, which will be searched for in the installer logs to track failures.
winInstallErrorStrArr = [
"Installation success or error status",
"Reconfiguration success or error status"
];
if (brackets.platform === "win") {
searchParams.installErrorStr = winInstallErrorStrArr;
searchParams.encoding = "utf16le";
}
postMessageToNode(MessageIds.CHECK_INSTALLER_STATUS, searchParams);
}
/**
* Checks and handles the update success and failure scenarios
*/
function checkUpdateStatus() {
var filesToCache = ['.logs'],
downloadCompleted = updateJsonHandler.get("downloadCompleted"),
updateInitiatedInPrevSession = updateJsonHandler.get("updateInitiatedInPrevSession");
if (downloadCompleted && updateInitiatedInPrevSession) {
var isNewVersion = checkIfVersionUpdated();
updateJsonHandler.reset();
if (isNewVersion) {
// We get here if the update was successful
UpdateInfoBar.showUpdateBar({
type: "success",
title: Strings.UPDATE_SUCCESSFUL,
description: ""
});
HealthLogger.sendAnalyticsData(
autoUpdateEventNames.AUTOUPDATE_INSTALLATION_SUCCESS,
"autoUpdate",
"install",
"complete",
""
);
} else {
// We get here if the update started but failed
checkInstallationStatus();
UpdateInfoBar.showUpdateBar({
type: "error",
title: Strings.UPDATE_FAILED,
description: Strings.GO_TO_SITE
});
}
} else if (downloadCompleted && !updateInitiatedInPrevSession) {
// We get here if the download was complete and user selected UpdateLater
if (brackets.platform === "mac") {
filesToCache = ['.dmg', '.json'];
} else if (brackets.platform === "win") {
filesToCache = ['.msi', '.json'];
}
}
postMessageToNode(MessageIds.PERFORM_CLEANUP, filesToCache);
}
/**
* Send Installer Error Code to Analytics Server
*/
function handleInstallationStatus(statusObj) {
var errorCode = "",
errorline = statusObj.installError;
if (errorline) {
errorCode = errorline.substr(errorline.lastIndexOf(':') + 2, errorline.length);
}
HealthLogger.sendAnalyticsData(
autoUpdateEventNames.AUTOUPDATE_INSTALLATION_FAILED,
"autoUpdate",
"install",
"fail",
errorCode
);
}
/**
* Initializes the state of parsed content from updateHelper.json
* returns Promise Object Which is resolved when parsing is success
* and rejected if parsing is failed.
*/
function initState() {
var result = $.Deferred();
updateJsonHandler.parse()
.done(function() {
result.resolve();
})
.fail(function (code) {
var logMsg;
switch (code) {
case StateHandlerMessages.FILE_NOT_FOUND:
logMsg = "AutoUpdate : updateHelper.json cannot be parsed, does not exist";
break;
case StateHandlerMessages.FILE_NOT_READ:
logMsg = "AutoUpdate : updateHelper.json could not be read";
break;
case StateHandlerMessages.FILE_PARSE_EXCEPTION:
logMsg = "AutoUpdate : updateHelper.json could not be parsed, exception encountered";
break;
case StateHandlerMessages.FILE_READ_FAIL:
logMsg = "AutoUpdate : updateHelper.json could not be parsed";
break;
}
console.log(logMsg);
result.reject();
});
return result.promise();
}
/**
* Sets up the Auto Update environment
*/
function setupAutoUpdate() {
updateJsonHandler = new StateHandler(updateJsonPath);
updateDomain.on('data', receiveMessageFromNode);
updateDomain.exec('initNode', {
messageIds: MessageIds,
updateDir: updateDir,
requester: domainID
});
}
/**
* Initializes the state for AutoUpdate process
* @returns {$.Deferred} - a jquery promise,
* that is resolved with success or failure
* of state initialization
*/
function initializeState() {
var result = $.Deferred();
FileSystem.resolve(updateDir, function (err) {
if (!err) {
result.resolve();
} else {
var directory = FileSystem.getDirectoryForPath(updateDir);
directory.create(function (error) {
if (error) {
console.error('AutoUpdate : Error in creating update directory in Appdata');
result.reject();
} else {
result.resolve();
}
});
}
});
return result.promise();
}
/**
* Handles the auto update event, which is triggered when user clicks GetItNow in UpdateNotification dialog
* @param {object} updateParams - json object containing update information {
* installerName - name of the installer
* downloadURL - download URL
* latestBuildNumber - build number
* checksum - checksum }
*/
function initiateAutoUpdate(updateParams) {
_updateParams = updateParams;
downloadAttemptsRemaining = MAX_DOWNLOAD_ATTEMPTS;
initializeState()
.done(function () {
var setUpdateInProgress = function() {
var initNodeFn = function () {
isAutoUpdateInitiated = true;
postMessageToNode(MessageIds.INITIALIZE_STATE, _updateParams);
};
if (updateJsonHandler.get('latestBuildNumber') !== _updateParams.latestBuildNumber) {
setUpdateStateInJSON('latestBuildNumber', _updateParams.latestBuildNumber)
.done(initNodeFn);
} else {
initNodeFn();
}
};
checkIfAnotherSessionInProgress()
.done(function(inProgress) {
if(inProgress) {
UpdateInfoBar.showUpdateBar({
type: "error",
title: Strings.AUTOUPDATE_ERROR,
description: Strings.AUTOUPDATE_IN_PROGRESS
});
} else {
setUpdateStateInJSON("autoUpdateInProgress", true)
.done(setUpdateInProgress);
}
})
.fail(function() {
setUpdateStateInJSON("autoUpdateInProgress", true)
.done(setUpdateInProgress);
});
})
.fail(function () {
UpdateInfoBar.showUpdateBar({
type: "error",
title: Strings.INITIALISATION_FAILED,
description: ""
});
});
}
/**
* Typical signature of an update entry, with the most frequently used keys
* @typedef {Object} Update~Entry
* @property {Number} buildNumber - The build number for the update
* @property {string} versionString - Version for the update
* @property {string} releaseNotesURL - URL for release notes for the update
* @property {array} newFeatures - Array of new features in the update
* @property {boolean} prerelease - Boolean to distinguish prerelease from a stable release
* @property {Object} platforms - JSON object, containing asset info for the update, for each platform
* Asset info for each platform consists of :
* @property {string} checksum - checksum of the asset
* @property {string} downloadURL - download URL of the asset
*
*/
/**
* Handles and processes the update info, required for app auto update
* @private
* @param {Array} updates - array of {...Update~Entry} update entries
*/
function _updateProcessHandler(updates) {
if (!updates) {
console.warn("AutoUpdate : updates information not available.");
return;
}
var OS = brackets.getPlatformInfo(),
checksum,
downloadURL,
installerName,
platforms,
latestUpdate;
latestUpdate = updates[0];
platforms = latestUpdate ? latestUpdate.platforms : null;
if (platforms && platforms[OS]) {
//If no checksum field is present then we're setting it to 0, just as a safety check,
// although ideally this situation should never occur in releases post its introduction.
checksum = platforms[OS].checksum ? platforms[OS].checksum : 0,
downloadURL = platforms[OS].downloadURL ? platforms[OS].downloadURL : "",
installerName = downloadURL ? downloadURL.split("/").pop() : "";
} else {
// Update not present for current platform
return false;
}
if (!checksum || !downloadURL || !installerName) {
console.warn("AutoUpdate : asset information incorrect for the update");
return false;
}
var updateParams = {
downloadURL: downloadURL,
installerName: installerName,
latestBuildNumber: latestUpdate.buildNumber,
checksum: checksum
};
//Initiate the auto update, with update params
initiateAutoUpdate(updateParams);
}
/**
* Unregisters the App Quit event handler
*/
function resetAppQuitHandler() {
DocumentCommandHandlers.off(APP_QUIT_CANCELLED);
}
/**
* Unsets the Auto Update environment
*/
function unsetAutoUpdate() {
updateJsonHandler = null;
updateDomain.off('data');
resetAppQuitHandler();
}
/**
* Defines preference to enable/disable Auto Update
*/
function setupAutoUpdatePreference() {
PreferencesManager.definePreference("autoUpdate.AutoUpdate", "boolean", true, {
description: Strings.DESCRIPTION_AUTO_UPDATE
});
// Set or unset the auto update, based on preference state change
PreferencesManager.on("change", "autoUpdate.AutoUpdate", function () {
if (_isAutoUpdateEnabled()) {
setupAutoUpdate();
UpdateNotification.registerUpdateHandler(_updateProcessHandler);
} else {
unsetAutoUpdate();
UpdateNotification.resetToDefaultUpdateHandler();
}
});
}
/**
* Creates the Node Domain for Auto Update
*/
function setupAutoUpdateDomain() {
updateDomain = new NodeDomain("AutoUpdate", _domainPath);
}
/**
* Overriding the appReady for Auto update
*/
AppInit.appReady(function () {
// Auto Update is supported on Win and Mac, as of now
if (brackets.platform === "linux" || !(brackets.app.setUpdateParams)) {
return;
}
setupAutoUpdateDomain();
//Bail out if update domain could not be created
if (!updateDomain) {
return;
}
// Check if the update domain is properly initialised
updateDomain.promise()
.done(function () {
setupAutoUpdatePreference();
if (_isAutoUpdateEnabled()) {
domainID = (new Date()).getTime().toString();
setupAutoUpdate();
UpdateNotification.registerUpdateHandler(_updateProcessHandler);
}
})
.fail(function (err) {
console.error("AutoUpdate : node domain could not be initialized.");
return;
});
});
/**
* Enables/disables the state of "Auto Update In Progress" in UpdateHandler.json
*/
function nodeDomainInitialized(reset) {
initState()
.done(function () {
var inProgress = updateJsonHandler.get(updateProgressKey);
if (inProgress && reset) {
setUpdateStateInJSON(updateProgressKey, !reset)
.always(checkUpdateStatus);
} else if (!inProgress) {
checkUpdateStatus();
}
});
}
/**
* Enables/disables the state of "Check For Updates" menu entry under Help Menu
*/
function enableCheckForUpdateEntry(enable) {
var cfuCommand = CommandManager.get(Commands.HELP_CHECK_FOR_UPDATE);
cfuCommand.setEnabled(enable);
UpdateNotification.enableUpdateNotificationIcon(enable);
}
/**
* Checks if it is the first iteration of download
* @returns {boolean} - true if first iteration, false if it is a retrial of download
*/
function isFirstIterationDownload() {
return (downloadAttemptsRemaining === MAX_DOWNLOAD_ATTEMPTS);
}
/**
* Resets the update state in updatehelper.json in case of failure,
* and logs an error with the message
* @param {string} message - the message to be logged onto console
*/
function resetStateInFailure(message) {
updateJsonHandler.reset();
UpdateInfoBar.showUpdateBar({
type: "error",
title: Strings.UPDATE_FAILED,
description: ""
});
enableCheckForUpdateEntry(true);
console.error(message);
}
/**
* Sets the update state in updateHelper.json in Appdata
* @param {string} key - key to be set
* @param {string} value - value to be set
* @returns {$.Deferred} - a jquery promise, that is resolved with
* success or failure of state update in json file
*/
function setUpdateStateInJSON(key, value) {
var result = $.Deferred();
updateJsonHandler.set(key, value)
.done(function () {
result.resolve();
})
.fail(function () {
resetStateInFailure("AutoUpdate : Could not modify updatehelper.json");
result.reject();
});
return result.promise();
}
/**
* Handles a safe download of the latest installer,
* safety is ensured by cleaning up any pre-existing installers
* from update directory before beginning a fresh download
*/
function handleSafeToDownload() {
var downloadFn = function () {
if (isFirstIterationDownload()) {
// For the first iteration of download, show download
//status info in Status bar, and pass download to node
UpdateStatus.showUpdateStatus("initial-download");
postMessageToNode(MessageIds.DOWNLOAD_INSTALLER, true);
} else {
/* For the retry iterations of download, modify the
download status info in Status bar, and pass download to node */
var attempt = (MAX_DOWNLOAD_ATTEMPTS - downloadAttemptsRemaining);
if (attempt > 1) {
var info = attempt.toString() + "/5";
var status = {
target: "retry-download",
spans: [{
id: "attempt",
val: info
}]
};
UpdateStatus.modifyUpdateStatus(status);
} else {
UpdateStatus.showUpdateStatus("retry-download");
}
postMessageToNode(MessageIds.DOWNLOAD_INSTALLER, false);
}
--downloadAttemptsRemaining;
};
if(!isAutoUpdateInitiated) {
isAutoUpdateInitiated = true;
updateJsonHandler.refresh()
.done(function() {
setUpdateStateInJSON('downloadCompleted', false)
.done(downloadFn);
});
} else {
setUpdateStateInJSON('downloadCompleted', false)
.done(downloadFn);
}
}
/**
* Checks if there is an active internet connection available
* @returns {boolean} - true if online, false otherwise
*/
function checkIfOnline() {
return window.navigator.onLine;
}
/**
* Attempts a download of the latest installer, while cleaning up any existing downloaded installers
*/
function attemptToDownload() {
if (checkIfOnline()) {
postMessageToNode(MessageIds.PERFORM_CLEANUP, ['.json'], true);
} else {
enableCheckForUpdateEntry(true);
UpdateStatus.cleanUpdateStatus();
HealthLogger.sendAnalyticsData(
autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_FAILED,
"autoUpdate",
"download",
"fail",
"No Internet connection available."
);
UpdateInfoBar.showUpdateBar({
type: "warning",
title: Strings.DOWNLOAD_FAILED,
description: Strings.INTERNET_UNAVAILABLE
});
setUpdateStateInJSON("autoUpdateInProgress", false);
}
}
/**
* Validates the checksum of a file against a given checksum
* @param {object} params - json containing {
* filePath - path to the file,
* expectedChecksum - the checksum to validate against }
*/
function validateChecksum(params) {
postMessageToNode(MessageIds.VALIDATE_INSTALLER, params);
}
/**
* Gets the latest installer, by either downloading a new one or fetching the cached download.
*/
function getLatestInstaller() {
var downloadCompleted = updateJsonHandler.get('downloadCompleted');
if (!downloadCompleted) {
attemptToDownload();
} else {
validateChecksum();
}
}
/**
* Handles the show status information callback from Node.
* It modifies the info displayed on Status bar.
* @param {object} statusObj - json containing status info {
* target - id of string to display,
* spans - Array containing json objects of type - {
* id - span id,
* val - string to fill the span element with }
* }
*/
function showStatusInfo(statusObj) {
if (statusObj.target === "initial-download") {
HealthLogger.sendAnalyticsData(
autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_START,
"autoUpdate",
"download",
"started",
""
);
UpdateStatus.modifyUpdateStatus(statusObj);
}
UpdateStatus.displayProgress(statusObj);
}
/**
* Handles the error messages from Node, in a popup displayed to the user.
* @param {string} message - error string
*/
function showErrorMessage(message) {
var analyticsDescriptionMessage = "";
switch (message) {
case _nodeErrorMessages.UPDATEDIR_READ_FAILED:
analyticsDescriptionMessage = "Update directory could not be read.";
break;
case _nodeErrorMessages.UPDATEDIR_CLEAN_FAILED:
analyticsDescriptionMessage = "Update directory could not be cleaned.";
break;
}
console.log("AutoUpdate : Clean-up failed! Reason : " + analyticsDescriptionMessage + ".\n");
HealthLogger.sendAnalyticsData(
autoUpdateEventNames.AUTOUPDATE_CLEANUP_FAILED,
"autoUpdate",
"cleanUp",
"fail",
analyticsDescriptionMessage
);
}
/**
* Handles the Cancel button click by user in
* Unsaved changes prompt, which would come up if user
* has dirty files and he/she clicked UpdateNow
*/
function dirtyFileSaveCancelled() {
UpdateInfoBar.showUpdateBar({
type: "warning",
title: Strings.WARNING_TYPE,
description: Strings.UPDATE_ON_NEXT_LAUNCH
});
}
/**
* Registers the App Quit event handler, in case of dirty
* file save cancelled scenario, while Auto Update is scheduled to run on quit
*/
function setAppQuitHandler() {
resetAppQuitHandler();
DocumentCommandHandlers.on(APP_QUIT_CANCELLED, dirtyFileSaveCancelled);
}
/**
* Initiates the update process, when user clicks UpdateNow in the update popup
* @param {string} formattedInstallerPath - formatted path to the latest installer
* @param {string} formattedLogFilePath - formatted path to the installer log file
* @param {string} installStatusFilePath - path to the install status log file
*/
function initiateUpdateProcess(formattedInstallerPath, formattedLogFilePath, installStatusFilePath) {
// Get additional update parameters on Mac : installDir, appName, and updateDir
function getAdditionalParams() {
var retval = {};
var installDir = FileUtils.getNativeBracketsDirectoryPath();
if (installDir) {
var appPath = installDir.split("/Contents/www")[0];
installDir = appPath.substr(0, appPath.lastIndexOf('/'));
var appName = appPath.substr(appPath.lastIndexOf('/') + 1);
retval = {
installDir: installDir,
appName: appName,
updateDir: updateDir
};
}
return retval;
}
// Update function, to carry out app update
var updateFn = function () {
var infoObj = {
installerPath: formattedInstallerPath,
logFilePath: formattedLogFilePath,
installStatusFilePath: installStatusFilePath
};
if (brackets.platform === "mac") {
var additionalParams = getAdditionalParams(),
key;
for (key in additionalParams) {
if (additionalParams.hasOwnProperty(key)) {
infoObj[key] = additionalParams[key];
}
}
}
// Set update parameters for app update
if (brackets.app.setUpdateParams) {
brackets.app.setUpdateParams(JSON.stringify(infoObj), function (err) {
if (err) {
resetStateInFailure("AutoUpdate : Update parameters could not be set for the installer. Error encountered: " + err);
} else {
setAppQuitHandler();
CommandManager.execute(Commands.FILE_QUIT);
}
});
} else {
resetStateInFailure("AutoUpdate : setUpdateParams could not be found in shell");
}
};
setUpdateStateInJSON('updateInitiatedInPrevSession', true)
.done(updateFn);
}
/**
* Detaches the Update Bar Buttons event handlers
*/
function detachUpdateBarBtnHandlers() {
UpdateInfoBar.off(UpdateInfoBar.RESTART_BTN_CLICKED);
UpdateInfoBar.off(UpdateInfoBar.LATER_BTN_CLICKED);
}
/**
* Handles the installer validation callback from Node
* @param {object} statusObj - json containing - {
* valid - (boolean)true for a valid installer, false otherwise,
* installerPath, logFilePath,
* installStatusFilePath - for a valid installer,
* err - for an invalid installer }
*/
function handleValidationStatus(statusObj) {
enableCheckForUpdateEntry(true);
UpdateStatus.cleanUpdateStatus();
if (statusObj.valid) {
// Installer is validated successfully
var statusValidFn = function () {
// Restart button click handler
var restartBtnClicked = function () {
HealthLogger.sendAnalyticsData(
autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_COMPLETE_USER_CLICK_RESTART,
"autoUpdate",
"installNotification",
"installNow ",
"click"
);
detachUpdateBarBtnHandlers();
initiateUpdateProcess(statusObj.installerPath, statusObj.logFilePath, statusObj.installStatusFilePath);
};
// Later button click handler
var laterBtnClicked = function () {
HealthLogger.sendAnalyticsData(
autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_COMPLETE_USER_CLICK_LATER,
"autoUpdate",
"installNotification",
"cancel",
"click"
);
detachUpdateBarBtnHandlers();
setUpdateStateInJSON('updateInitiatedInPrevSession', false);
};
//attaching UpdateBar handlers
UpdateInfoBar.on(UpdateInfoBar.RESTART_BTN_CLICKED, restartBtnClicked);
UpdateInfoBar.on(UpdateInfoBar.LATER_BTN_CLICKED, laterBtnClicked);
UpdateInfoBar.showUpdateBar({
title: Strings.DOWNLOAD_COMPLETE,
description: Strings.CLICK_RESTART_TO_UPDATE,
needButtons: true
});
setUpdateStateInJSON("autoUpdateInProgress", false);
HealthLogger.sendAnalyticsData(
autoUpdateEventNames.AUTOUPDATE_DOWNLOADCOMPLETE_UPDATE_BAR_RENDERED,
"autoUpdate",
"installNotification",
"render",
""
);
};
if(!isAutoUpdateInitiated) {
isAutoUpdateInitiated = true;
updateJsonHandler.refresh()
.done(function() {
setUpdateStateInJSON('downloadCompleted', true)
.done(statusValidFn);
});
} else {
setUpdateStateInJSON('downloadCompleted', true)
.done(statusValidFn);
}
} else {
// Installer validation failed
if (updateJsonHandler.get("downloadCompleted")) {
// If this was a cached download, retry downloading
updateJsonHandler.reset();
var statusInvalidFn = function () {
downloadAttemptsRemaining = MAX_DOWNLOAD_ATTEMPTS;
getLatestInstaller();
};
setUpdateStateInJSON('downloadCompleted', false)
.done(statusInvalidFn);
} else {
// If this is a new download, prompt the message on update bar
var descriptionMessage = "",
analyticsDescriptionMessage = "";
switch (statusObj.err) {
case _nodeErrorMessages.CHECKSUM_DID_NOT_MATCH:
descriptionMessage = Strings.CHECKSUM_DID_NOT_MATCH;
analyticsDescriptionMessage = "Checksum didn't match.";
break;
case _nodeErrorMessages.INSTALLER_NOT_FOUND:
descriptionMessage = Strings.INSTALLER_NOT_FOUND;
analyticsDescriptionMessage = "Installer not found.";
break;
}
HealthLogger.sendAnalyticsData(
autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_FAILED,