forked from microsoft/code-push
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand-executor.ts
More file actions
1319 lines (1098 loc) · 50.9 KB
/
Copy pathcommand-executor.ts
File metadata and controls
1319 lines (1098 loc) · 50.9 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
/// <reference path="../../definitions/generated/code-push.d.ts" />
import * as base64 from "base-64";
import * as chalk from "chalk";
import * as fs from "fs";
import * as moment from "moment";
var opener = require("opener");
import * as os from "os";
import * as path from "path";
var prompt = require("prompt");
import * as Q from "q";
import * as recursiveFs from "recursive-fs";
import * as semver from "semver";
import slash = require("slash");
var Table = require("cli-table");
import * as yazl from "yazl";
import wordwrap = require("wordwrap");
import * as cli from "../definitions/cli";
import { AcquisitionStatus } from "code-push/script/acquisition-sdk";
import { AccessKey, AccountManager, App, CollaboratorMap, CollaboratorProperties, Deployment, DeploymentKey, DeploymentMetrics, Package, Permissions, UpdateMetrics } from "code-push";
var packageJson = require("../package.json");
import Promise = Q.Promise;
var progress = require("progress");
var emailValidator = require("email-validator");
var configFilePath: string = path.join(process.env.LOCALAPPDATA || process.env.HOME, ".code-push.config");
var userAgent: string = packageJson.name + "/" + packageJson.version;
const ACTIVE_METRICS_KEY: string = "Active";
const DOWNLOADED_METRICS_KEY: string = "Downloaded";
interface NameToCountMap {
[name: string]: number;
}
interface IStandardLoginConnectionInfo {
accessKeyName: string;
providerName: string;
providerUniqueId: string;
serverUrl: string;
}
interface IAccessKeyLoginConnectionInfo {
accessKey: string;
serverUrl: string;
}
interface IPackageFile {
isTemporary: boolean;
path: string;
}
export interface UpdateMetricsWithTotalActive extends UpdateMetrics {
totalActive: number;
}
export interface PackageWithMetrics {
metrics?: UpdateMetricsWithTotalActive;
}
export var sdk: AccountManager;
export var log = (message: string | Chalk.ChalkChain): void => console.log(message);
export var loginWithAccessToken = (): Promise<void> => {
if (!connectionInfo) {
return Q.fcall(() => { throw new Error("You are not currently logged in. Run the 'code-push login' command to authenticate with the CodePush server."); });
}
sdk = new AccountManager(connectionInfo.serverUrl, userAgent);
var accessToken: string;
var standardLoginConnectionInfo: IStandardLoginConnectionInfo = <IStandardLoginConnectionInfo>connectionInfo;
var accessKeyLoginConnectionInfo: IAccessKeyLoginConnectionInfo = <IAccessKeyLoginConnectionInfo>connectionInfo;
if (standardLoginConnectionInfo.providerName) {
accessToken = base64.encode(JSON.stringify({
accessKeyName: standardLoginConnectionInfo.accessKeyName,
providerName: standardLoginConnectionInfo.providerName,
providerUniqueId: standardLoginConnectionInfo.providerUniqueId
}));
} else {
accessToken = accessKeyLoginConnectionInfo.accessKey;
}
return sdk.loginWithAccessToken(accessToken);
}
export var confirm = (): Promise<boolean> => {
return Promise<boolean>((resolve, reject, notify): void => {
prompt.message = "";
prompt.delimiter = "";
prompt.start();
prompt.get({
properties: {
response: {
description: chalk.cyan("Are you sure? (Y/n):")
}
}
}, (err: any, result: any): void => {
if (!result.response || result.response === "" || result.response === "Y") {
resolve(true);
} else {
if (result.response !== "n") console.log("Invalid response: \"" + result.response + "\"");
resolve(false);
}
});
});
}
var connectionInfo: IStandardLoginConnectionInfo | IAccessKeyLoginConnectionInfo;
function accessKeyAdd(command: cli.IAccessKeyAddCommand): Promise<void> {
var hostname: string = os.hostname();
return sdk.addAccessKey(hostname, command.description)
.then((accessKey: AccessKey) => {
log("Successfully created a new access key" + (command.description ? (" \"" + command.description + "\"") : "") + ": " + accessKey.name);
});
}
function accessKeyList(command: cli.IAccessKeyListCommand): Promise<void> {
throwForInvalidOutputFormat(command.format);
return sdk.getAccessKeys()
.then((accessKeys: AccessKey[]): void => {
printAccessKeys(command.format, accessKeys);
});
}
function removeLocalAccessKey(): Promise<void> {
return Q.fcall(() => { throw new Error("Cannot remove the access key for the current session. Please run 'code-push logout' if you would like to remove this access key."); });
}
function accessKeyRemove(command: cli.IAccessKeyRemoveCommand): Promise<void> {
if (connectionInfo && (command.accessKeyName === (<IStandardLoginConnectionInfo>connectionInfo).accessKeyName || command.accessKeyName === (<IAccessKeyLoginConnectionInfo>connectionInfo).accessKey)) {
return removeLocalAccessKey();
} else {
return getAccessKeyId(command.accessKeyName)
.then((accessKeyId: string): Promise<void> => {
throwForInvalidAccessKeyId(accessKeyId, command.accessKeyName);
return confirm()
.then((wasConfirmed: boolean): Promise<void> => {
if (wasConfirmed) {
return sdk.removeAccessKey(accessKeyId)
.then((): void => {
log("Successfully removed the \"" + command.accessKeyName + "\" access key.");
});
}
log("Access key removal cancelled.");
});
});
}
}
function appAdd(command: cli.IAppAddCommand): Promise<void> {
return sdk.addApp(command.appName)
.then((app: App): Promise<void> => {
log("Successfully added the \"" + command.appName + "\" app, along with the following default deployments:");
var deploymentListCommand: cli.IDeploymentListCommand = {
type: cli.CommandType.deploymentList,
appName: app.name,
format: "table",
displayKeys: true
};
return deploymentList(deploymentListCommand, /*showPackage=*/ false);
});
}
function appList(command: cli.IAppListCommand): Promise<void> {
throwForInvalidOutputFormat(command.format);
var apps: App[];
return sdk.getApps()
.then((retrievedApps: App[]): Promise<string[][]> => {
apps = retrievedApps;
var deploymentListPromises: Promise<string[]>[] = apps.map((app: App) => {
return sdk.getDeployments(app.id)
.then((deployments: Deployment[]) => {
var deploymentList: string[] = deployments
.map((deployment: Deployment) => deployment.name)
.sort((first: string, second: string) => {
return first.toLowerCase().localeCompare(second.toLowerCase());
});
return deploymentList;
});
});
return Q.all(deploymentListPromises);
})
.then((deploymentLists: string[][]): void => {
printAppList(command.format, apps, deploymentLists);
});
}
function appRemove(command: cli.IAppRemoveCommand): Promise<void> {
return getAppId(command.appName)
.then((appId: string): Promise<void> => {
throwForInvalidAppId(appId, command.appName);
return confirm()
.then((wasConfirmed: boolean): Promise<void> => {
if (wasConfirmed) {
return sdk.removeApp(appId)
.then((): void => {
log("Successfully removed the \"" + command.appName + "\" app.");
});
}
log("App removal cancelled.");
});
});
}
function appRename(command: cli.IAppRenameCommand): Promise<void> {
return getApp(command.currentAppName)
.then((app: App): Promise<void> => {
throwForInvalidApp(app, command.currentAppName);
app.name = command.newAppName;
return sdk.updateApp(app);
})
.then((): void => {
log("Successfully renamed the \"" + command.currentAppName + "\" app to \"" + command.newAppName + "\".");
});
}
function appTransfer(command: cli.IAppTransferCommand): Promise<void> {
throwForInvalidEmail(command.email);
return getAppId(command.appName)
.then((appId: string): Promise<void> => {
throwForInvalidAppId(appId, command.appName);
return confirm()
.then((wasConfirmed: boolean): Promise<void> => {
if (wasConfirmed) {
return sdk.transferApp(appId, command.email)
.then((): void => {
log("Successfully transferred the ownership of app \"" + command.appName + "\" to the account with email \"" + command.email + "\".");
});
}
log("App transfer cancelled.");
});
});
}
function addCollaborator(command: cli.ICollaboratorAddCommand): Promise<void> {
throwForInvalidEmail(command.email);
return getAppId(command.appName)
.then((appId: string): Promise<void> => {
throwForInvalidAppId(appId, command.appName);
return sdk.addCollaborator(appId, command.email)
.then((): void => {
log("Successfully added \"" + command.email + "\" as a collaborator to the app \"" + command.appName + "\".");
});
});
}
function listCollaborators(command: cli.ICollaboratorListCommand): Promise<void> {
throwForInvalidOutputFormat(command.format);
return getAppId(command.appName)
.then((appId: string): Promise<void> => {
throwForInvalidAppId(appId, command.appName);
return sdk.getCollaboratorsList(appId)
.then((retrievedCollaborators: CollaboratorMap): void => {
printCollaboratorsList(command.format, retrievedCollaborators);
});
});
}
function removeCollaborator(command: cli.ICollaboratorRemoveCommand): Promise<void> {
throwForInvalidEmail(command.email);
return getAppId(command.appName)
.then((appId: string): Promise<void> => {
throwForInvalidAppId(appId, command.appName);
return confirm()
.then((wasConfirmed: boolean): Promise<void> => {
if (wasConfirmed) {
return sdk.removeCollaborator(appId, command.email)
.then((): void => {
log("Successfully removed \"" + command.email + "\" as a collaborator from the app \"" + command.appName + "\".");
});
}
log("App collaborator removal cancelled.");
});
});
}
function deleteConnectionInfoCache(): void {
try {
fs.unlinkSync(configFilePath);
log("Successfully logged-out. The session token file located at " + chalk.cyan(configFilePath) + " has been deleted.\r\n");
} catch (ex) {
}
}
function deploymentAdd(command: cli.IDeploymentAddCommand): Promise<void> {
return getAppId(command.appName)
.then((appId: string): Promise<void> => {
throwForInvalidAppId(appId, command.appName);
return sdk.addDeployment(appId, command.deploymentName)
.then((deployment: Deployment): Promise<DeploymentKey[]> => {
return sdk.getDeploymentKeys(appId, deployment.id);
}).then((deploymentKeys: DeploymentKey[]) => {
log("Successfully added the \"" + command.deploymentName + "\" deployment with key \"" + deploymentKeys[0].key + "\" to the \"" + command.appName + "\" app.");
});
})
}
export var deploymentList = (command: cli.IDeploymentListCommand, showPackage: boolean = true): Promise<void> => {
throwForInvalidOutputFormat(command.format);
var theAppId: string;
var deploymentKeyList: string[];
var deployments: Deployment[];
return getAppId(command.appName)
.then((appId: string): Promise<Deployment[]> => {
throwForInvalidAppId(appId, command.appName);
theAppId = appId;
return sdk.getDeployments(appId);
})
.then((retrievedDeployments: Deployment[]): Promise<void> => {
deployments = retrievedDeployments;
if (command.displayKeys) {
var deploymentKeyPromises: Promise<string>[] = deployments.map((deployment: Deployment) => {
return sdk.getDeploymentKeys(theAppId, deployment.id)
.then((deploymentKeys: DeploymentKey[]): string => {
return deploymentKeys[0].key;
});
});
return Q.all(deploymentKeyPromises)
.then((retrievedDeploymentKeyList: string[]) => {
deploymentKeyList = retrievedDeploymentKeyList;
});
}
})
.then(() => {
if (showPackage) {
var metricsPromises: Promise<void>[] = deployments.map((deployment: Deployment) => {
if (deployment.package) {
return sdk.getDeploymentMetrics(theAppId, deployment.id)
.then((metrics: DeploymentMetrics): void => {
if (metrics[deployment.package.label]) {
var totalActive: number = getTotalActiveFromDeploymentMetrics(metrics);
(<PackageWithMetrics>(deployment.package)).metrics = {
active: metrics[deployment.package.label].active,
downloaded: metrics[deployment.package.label].downloaded,
failed: metrics[deployment.package.label].failed,
installed: metrics[deployment.package.label].installed,
totalActive: totalActive
};
}
});
} else {
return Q(<void>null);
}
});
return Q.all(metricsPromises);
}
})
.then(() => {
printDeploymentList(command, deployments, deploymentKeyList, showPackage);
});
}
function deploymentRemove(command: cli.IDeploymentRemoveCommand): Promise<void> {
return getAppId(command.appName)
.then((appId: string): Promise<void> => {
throwForInvalidAppId(appId, command.appName);
return getDeploymentId(appId, command.deploymentName)
.then((deploymentId: string): Promise<void> => {
throwForInvalidDeploymentId(deploymentId, command.deploymentName, command.appName);
return confirm()
.then((wasConfirmed: boolean): Promise<void> => {
if (wasConfirmed) {
return sdk.removeDeployment(appId, deploymentId)
.then((): void => {
log("Successfully removed the \"" + command.deploymentName + "\" deployment from the \"" + command.appName + "\" app.");
})
}
log("Deployment removal cancelled.");
});
});
});
}
function deploymentRename(command: cli.IDeploymentRenameCommand): Promise<void> {
return getAppId(command.appName)
.then((appId: string): Promise<void> => {
throwForInvalidAppId(appId, command.appName);
return getDeployment(appId, command.currentDeploymentName)
.then((deployment: Deployment): Promise<void> => {
throwForInvalidDeployment(deployment, command.currentDeploymentName, command.appName);
deployment.name = command.newDeploymentName;
return sdk.updateDeployment(appId, deployment);
})
.then((): void => {
log("Successfully renamed the \"" + command.currentDeploymentName + "\" deployment to \"" + command.newDeploymentName + "\" for the \"" + command.appName + "\" app.");
});
});
}
function deploymentHistory(command: cli.IDeploymentHistoryCommand): Promise<void> {
throwForInvalidOutputFormat(command.format);
var storedAppId: string;
var storedDeploymentId: string;
var deployments: Deployment[];
var currentUserEmail: string;
return getApp(command.appName)
.then((app: App): Promise<string> => {
throwForInvalidAppId(app.id, command.appName);
storedAppId = app.id;
currentUserEmail = getCurrentUserEmail(app.collaborators);
return getDeploymentId(app.id, command.deploymentName);
})
.then((deploymentId: string): Promise<Package[]> => {
throwForInvalidDeploymentId(deploymentId, command.deploymentName, command.appName);
storedDeploymentId = deploymentId;
return sdk.getPackageHistory(storedAppId, deploymentId);
})
.then((packageHistory: Package[]): Promise<void> => {
return sdk.getDeploymentMetrics(storedAppId, storedDeploymentId)
.then((metrics: DeploymentMetrics): void => {
var totalActive: number = getTotalActiveFromDeploymentMetrics(metrics);
packageHistory.forEach((packageObject: Package) => {
if (metrics[packageObject.label]) {
(<PackageWithMetrics>packageObject).metrics = {
active: metrics[packageObject.label].active,
downloaded: metrics[packageObject.label].downloaded,
failed: metrics[packageObject.label].failed,
installed: metrics[packageObject.label].installed,
totalActive: totalActive
};
}
});
printDeploymentHistory(command, <PackageWithMetrics[]>packageHistory, currentUserEmail);
});
});
}
function deserializeConnectionInfo(): IStandardLoginConnectionInfo | IAccessKeyLoginConnectionInfo {
try {
var savedConnection: string = fs.readFileSync(configFilePath, { encoding: "utf8" });
return JSON.parse(savedConnection);
} catch (ex) {
return;
}
}
function notifyAlreadyLoggedIn(): Promise<void> {
return Q.fcall(() => { throw new Error("You are already logged in from this machine."); });
}
export function execute(command: cli.ICommand): Promise<void> {
connectionInfo = deserializeConnectionInfo();
switch (command.type) {
case cli.CommandType.login:
if (connectionInfo) {
return notifyAlreadyLoggedIn();
}
return login(<cli.ILoginCommand>command);
case cli.CommandType.logout:
return logout(<cli.ILogoutCommand>command);
case cli.CommandType.register:
return register(<cli.IRegisterCommand>command);
}
return loginWithAccessToken()
.then((): Promise<void> => {
switch (command.type) {
case cli.CommandType.accessKeyAdd:
return accessKeyAdd(<cli.IAccessKeyAddCommand>command);
case cli.CommandType.accessKeyList:
return accessKeyList(<cli.IAccessKeyListCommand>command);
case cli.CommandType.accessKeyRemove:
return accessKeyRemove(<cli.IAccessKeyRemoveCommand>command);
case cli.CommandType.appAdd:
return appAdd(<cli.IAppAddCommand>command);
case cli.CommandType.appList:
return appList(<cli.IAppListCommand>command);
case cli.CommandType.appRemove:
return appRemove(<cli.IAppRemoveCommand>command);
case cli.CommandType.appRename:
return appRename(<cli.IAppRenameCommand>command);
case cli.CommandType.appTransfer:
return appTransfer(<cli.IAppTransferCommand>command);
case cli.CommandType.collaboratorAdd:
return addCollaborator(<cli.ICollaboratorAddCommand>command);
case cli.CommandType.collaboratorList:
return listCollaborators(<cli.ICollaboratorListCommand>command);
case cli.CommandType.collaboratorRemove:
return removeCollaborator(<cli.ICollaboratorRemoveCommand>command);
case cli.CommandType.deploymentAdd:
return deploymentAdd(<cli.IDeploymentAddCommand>command);
case cli.CommandType.deploymentHistory:
return deploymentHistory(<cli.IDeploymentHistoryCommand>command);
case cli.CommandType.deploymentList:
return deploymentList(<cli.IDeploymentListCommand>command);
case cli.CommandType.deploymentRemove:
return deploymentRemove(<cli.IDeploymentRemoveCommand>command);
case cli.CommandType.deploymentRename:
return deploymentRename(<cli.IDeploymentRenameCommand>command);
case cli.CommandType.promote:
return promote(<cli.IPromoteCommand>command);
case cli.CommandType.release:
return release(<cli.IReleaseCommand>command);
case cli.CommandType.rollback:
return rollback(<cli.IRollbackCommand>command);
default:
// We should never see this message as invalid commands should be caught by the argument parser.
log("Invalid command: " + JSON.stringify(command));
}
});
}
function generateRandomFilename(length: number): string {
var filename: string = "";
var validChar: string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < length; i++) {
filename += validChar.charAt(Math.floor(Math.random() * validChar.length));
}
return filename;
}
function getAccessKey(accessKeyName: string): Promise<AccessKey> {
return sdk.getAccessKeys()
.then((accessKeys: AccessKey[]): AccessKey => {
for (var i = 0; i < accessKeys.length; ++i) {
var accessKey: AccessKey = accessKeys[i];
if (accessKey.name === accessKeyName) {
return accessKey;
}
}
});
}
function getAccessKeyId(accessKeyName: string): Promise<string> {
return getAccessKey(accessKeyName)
.then((accessKey: AccessKey): string => {
if (accessKey) {
return accessKey.id;
}
return null;
});
}
function getApp(appName: string): Promise<App> {
var ownerEmailValue: string;
var appNameValue: string = appName;
var delimiterIndex: number = appName.indexOf("/");
if (delimiterIndex !== -1) {
ownerEmailValue = appName.substring(0, delimiterIndex);
appNameValue = appName.substring(delimiterIndex + 1);
throwForInvalidEmail(ownerEmailValue);
}
return sdk.getApps()
.then((apps: App[]): App => {
var foundApp = false;
var possibleApp: App;
for (var i = 0; i < apps.length; ++i) {
var app: App = apps[i];
if (app.name === appNameValue) {
var isCurrentUserOwner: boolean = isCurrentAccountOwner(app.collaborators);
if (ownerEmailValue) {
var appOwner: string = getOwnerEmail(app.collaborators);
foundApp = appOwner && appOwner === ownerEmailValue;
} else if (!isCurrentUserOwner) {
// found an app name matching given value but is not the owner of the app
// its possible there is another app with same name of which this user
// is the owner, so keep this pointer for future use.
possibleApp = app;
} else {
foundApp = isCurrentUserOwner;
}
}
if (foundApp) {
return app;
}
}
if (possibleApp) {
return possibleApp;
}
});
}
function isCurrentAccountOwner(map: CollaboratorMap): boolean {
if (map) {
var ownerEmail: string = getOwnerEmail(map);
return ownerEmail && map[ownerEmail].isCurrentAccount;
}
return false;
}
function getCurrentUserEmail(map: CollaboratorMap): string {
if (map) {
for (var key of Object.keys(map)) {
if (map[key].isCurrentAccount) {
return key;
}
}
}
return null;
}
function getOwnerEmail(map: CollaboratorMap): string {
if (map) {
for (var key of Object.keys(map)) {
if (map[key].permission === Permissions.Owner) {
return key;
}
}
}
return null;
}
function getAppId(appName: string): Promise<string> {
return getApp(appName)
.then((app: App): string => {
if (app) {
return app.id;
}
return null;
});
}
function getDeployment(appId: string, deploymentName: string): Promise<Deployment> {
return sdk.getDeployments(appId)
.then((deployments: Deployment[]): Deployment => {
for (var i = 0; i < deployments.length; ++i) {
var deployment: Deployment = deployments[i];
if (deployment.name === deploymentName) {
return deployment;
}
}
});
}
function getDeploymentId(appId: string, deploymentName: string): Promise<string> {
return getDeployment(appId, deploymentName)
.then((deployment: Deployment): string => {
if (deployment) {
return deployment.id;
}
return null;
});
}
function getTotalActiveFromDeploymentMetrics(metrics: DeploymentMetrics): number {
var totalActive = 0;
Object.keys(metrics).forEach((label: string) => {
totalActive += metrics[label].active;
});
return totalActive;
}
function initiateExternalAuthenticationAsync(serverUrl: string, action: string): void {
var message: string = `A browser is being launched to authenticate your account. Follow the instructions ` +
`it displays to complete your ${action === "register" ? "registration" : "login"}.\r\n`;
log(message);
var hostname: string = os.hostname();
var url: string = serverUrl + "/auth/" + action + "?hostname=" + hostname;
opener(url);
}
function login(command: cli.ILoginCommand): Promise<void> {
// Check if one of the flags were provided.
if (command.accessKey) {
sdk = new AccountManager(command.serverUrl, userAgent);
return sdk.loginWithAccessToken(command.accessKey)
.then((): void => {
// The access token is valid.
serializeConnectionInfo(command.serverUrl, command.accessKey);
});
} else {
initiateExternalAuthenticationAsync(command.serverUrl, "login");
return loginWithAccessTokenInternal(command.serverUrl);
}
}
function loginWithAccessTokenInternal(serverUrl: string): Promise<void> {
return requestAccessToken()
.then((accessToken: string): Promise<void> => {
if (accessToken === null) {
// The user has aborted the synchronous prompt (e.g.: via [CTRL]+[C]).
return;
}
if (!accessToken) {
throw new Error("Invalid access token.");
}
sdk = new AccountManager(serverUrl, userAgent);
return sdk.loginWithAccessToken(accessToken)
.then((): void => {
// The access token is valid.
serializeConnectionInfo(serverUrl, accessToken);
});
});
}
function logout(command: cli.ILogoutCommand): Promise<void> {
if (connectionInfo) {
var setupPromise: Promise<void> = loginWithAccessToken();
if (!command.isLocal) {
var accessKeyName: string;
setupPromise = setupPromise
.then((): Promise<string> => {
var standardLoginConnectionInfo: IStandardLoginConnectionInfo = <IStandardLoginConnectionInfo>connectionInfo;
var accessKeyLoginConnectionInfo: IAccessKeyLoginConnectionInfo = <IAccessKeyLoginConnectionInfo>connectionInfo;
if (standardLoginConnectionInfo.accessKeyName) {
accessKeyName = standardLoginConnectionInfo.accessKeyName;
return getAccessKeyId(standardLoginConnectionInfo.accessKeyName);
} else {
accessKeyName = accessKeyLoginConnectionInfo.accessKey;
return getAccessKeyId(accessKeyLoginConnectionInfo.accessKey);
}
})
.then((accessKeyId: string): Promise<void> => {
return sdk.removeAccessKey(accessKeyId);
})
.then((): void => {
log("Removed access key " + accessKeyName + ".");
});
}
return setupPromise
.then((): Promise<void> => sdk.logout(), (): Promise<void> => sdk.logout())
.then((): void => deleteConnectionInfoCache(), (): void => deleteConnectionInfoCache());
}
return Q.fcall(() => { throw new Error("You are not logged in."); });
}
function formatDate(unixOffset: number): string {
var date: moment.Moment = moment(unixOffset);
var now: moment.Moment = moment();
if (now.diff(date, "days") < 30) {
return date.fromNow(); // "2 hours ago"
} else if (now.year() === date.year()) {
return date.format("MMM D"); // "Nov 6"
} else {
return date.format("MMM D, YYYY"); // "Nov 6, 2014"
}
}
function getAppDisplayName(app: App, appNameToCountMap: NameToCountMap): string {
if (appNameToCountMap && appNameToCountMap[app.name] > 1) {
var isCurrentUserOwner: boolean = isCurrentAccountOwner(app.collaborators);
return isCurrentUserOwner ? app.name : getOwnerEmail(app.collaborators) + "/" + app.name;
} else {
return app.name;
}
}
function getNameToCountMap(apps: App[]): NameToCountMap {
var nameToCountMap: NameToCountMap = {};
apps.forEach((app: App) => {
var ownerEmail: string = getOwnerEmail(app.collaborators);
if (!nameToCountMap[app.name]) {
nameToCountMap[app.name] = 1;
} else {
nameToCountMap[app.name] = nameToCountMap[app.name] + 1;
}
});
return nameToCountMap;
}
function printAppList(format: string, apps: App[], deploymentLists: string[][]): void {
var appNameToCountMap: NameToCountMap = getNameToCountMap(apps);
if (format === "json") {
var dataSource: any[] = apps.map((app: App, index: number) => {
return { "name": getAppDisplayName(app, appNameToCountMap), "deployments": deploymentLists[index] };
});
printJson(dataSource);
} else if (format === "table") {
var headers = ["Name", "Deployments"];
printTable(headers, (dataSource: any[]): void => {
apps.forEach((app: App, index: number): void => {
var row = [getAppDisplayName(app, appNameToCountMap), wordwrap(50)(deploymentLists[index].join(", "))];
dataSource.push(row);
});
});
}
}
function getCollaboratorDisplayName(email: string, collaboratorProperties: CollaboratorProperties): string {
return (collaboratorProperties.permission === Permissions.Owner) ? email + chalk.magenta(" (" + Permissions.Owner + ")") : email;
}
function printCollaboratorsList(format: string, collaborators: CollaboratorMap): void {
if (format === "json") {
var dataSource = { "collaborators": collaborators };
printJson(dataSource);
} else if (format === "table") {
var headers = ["E-mail Address"];
printTable(headers, (dataSource: any[]): void => {
Object.keys(collaborators).forEach((email: string): void => {
var row = [getCollaboratorDisplayName(email, collaborators[email])];
dataSource.push(row);
});
});
}
}
function printDeploymentList(command: cli.IDeploymentListCommand, deployments: Deployment[], deploymentKeys: Array<string>, showPackage: boolean = true): void {
if (command.format === "json") {
var dataSource: any[] = deployments.map((deployment: Deployment, index: number) => {
var deploymentJson: any = { "name": deployment.name, "package": deployment.package };
if (command.displayKeys) {
deploymentJson.deploymentKey = deploymentKeys[index];
}
if (deployment.package) {
var packageWithMetrics = <PackageWithMetrics>(deployment.package);
if (packageWithMetrics.metrics) {
delete packageWithMetrics.metrics.totalActive;
}
}
return deploymentJson;
});
printJson(dataSource);
} else if (command.format === "table") {
var headers = ["Name"];
if (command.displayKeys) {
headers.push("Deployment Key");
}
if (showPackage) {
headers.push("Update Metadata");
headers.push("Install Metrics");
}
printTable(headers, (dataSource: any[]): void => {
deployments.forEach((deployment: Deployment, index: number): void => {
var row = [deployment.name];
if (command.displayKeys) {
row.push(deploymentKeys[index]);
}
if (showPackage) {
row.push(getPackageString(deployment.package));
row.push(getPackageMetricsString(<PackageWithMetrics>(deployment.package)));
}
dataSource.push(row);
});
});
}
}
function printDeploymentHistory(command: cli.IDeploymentHistoryCommand, packageHistory: PackageWithMetrics[], currentUserEmail: string): void {
if (command.format === "json") {
packageHistory.forEach((packageObject: PackageWithMetrics) => {
if (packageObject.metrics) {
delete packageObject.metrics.totalActive;
}
});
printJson(packageHistory);
} else if (command.format === "table") {
var headers = ["Label", "Release Time", "App Version", "Mandatory"];
if (command.displayAuthor) {
headers.push("Released By");
}
headers.push("Description", "Install Metrics");
printTable(headers, (dataSource: any[]) => {
packageHistory.forEach((packageObject: Package) => {
var releaseTime: string = formatDate(packageObject.uploadTime);
var releaseSource: string;
if (packageObject.releaseMethod === "Promote") {
releaseSource = `Promoted ${packageObject.originalLabel} from "${packageObject.originalDeployment}"`;
} else if (packageObject.releaseMethod === "Rollback") {
var labelNumber: number = parseInt(packageObject.label.substring(1));
var lastLabel: string = "v" + (labelNumber - 1);
releaseSource = `Rolled back ${lastLabel} to ${packageObject.originalLabel}`;
}
if (releaseSource) {
releaseTime += "\n" + chalk.magenta(`(${releaseSource})`).toString();
}
var row = [packageObject.label, releaseTime, packageObject.appVersion, packageObject.isMandatory ? "Yes" : "No"];
if (command.displayAuthor) {
var releasedBy: string = packageObject.releasedBy ? packageObject.releasedBy : "";
if (currentUserEmail && releasedBy === currentUserEmail) {
releasedBy = "You";
}
row.push(releasedBy);
}
row.push(packageObject.description ? wordwrap(30)(packageObject.description) : "", getPackageMetricsString(packageObject));
dataSource.push(row);
});
});
}
}
function getPackageString(packageObject: Package): string {
if (!packageObject) {
return chalk.magenta("No updates released").toString();
}
return chalk.green("Label: ") + packageObject.label + "\n" +
chalk.green("App Version: ") + packageObject.appVersion + "\n" +
chalk.green("Mandatory: ") + (packageObject.isMandatory ? "Yes" : "No") + "\n" +
chalk.green("Release Time: ") + formatDate(packageObject.uploadTime) + "\n" +
chalk.green("Released By: ") + (packageObject.releasedBy ? packageObject.releasedBy : "") +
(packageObject.description ? wordwrap(70)("\n" + chalk.green("Description: ") + packageObject.description) : "");
}
function getPackageMetricsString(packageObject: PackageWithMetrics): string {
if (!packageObject || !packageObject.metrics) {
return "" + chalk.magenta("No installs recorded");
}
var activePercent: number = packageObject.metrics.totalActive
? packageObject.metrics.active / packageObject.metrics.totalActive * 100
: 0.0;
var percentString: string;
if (activePercent === 100.0) {