/
subscriptionService.ts
1038 lines (882 loc) · 29 KB
/
subscriptionService.ts
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
import type {
AuthenticationProviderAuthenticationSessionsChangeEvent,
AuthenticationSession,
Event,
MessageItem,
StatusBarItem,
} from 'vscode';
import {
authentication,
version as codeVersion,
Disposable,
env,
EventEmitter,
MarkdownString,
ProgressLocation,
StatusBarAlignment,
ThemeColor,
Uri,
window,
} from 'vscode';
import { fetch, getProxyAgent } from '@env/fetch';
import { getPlatform } from '@env/platform';
import { configuration } from '../../configuration';
import { Commands, ContextKeys } from '../../constants';
import type { Container } from '../../container';
import { setContext } from '../../context';
import { AccountValidationError } from '../../errors';
import type { RepositoriesChangeEvent } from '../../git/gitProviderService';
import { Logger } from '../../logger';
import { showProDiscountNotification } from '../../messages';
import type { Subscription } from '../../subscription';
import {
computeSubscriptionState,
getSubscriptionPlan,
getSubscriptionPlanName,
getSubscriptionPlanPriority,
getSubscriptionTimeRemaining,
getTimeRemaining,
isSubscriptionExpired,
isSubscriptionPaid,
isSubscriptionTrial,
SubscriptionPlanId,
SubscriptionState,
} from '../../subscription';
import { executeCommand, registerCommand } from '../../system/command';
import { createFromDateDelta } from '../../system/date';
import { gate } from '../../system/decorators/gate';
import { debug, getLogScope, log } from '../../system/decorators/log';
import { memoize } from '../../system/decorators/memoize';
import { once } from '../../system/function';
import { pluralize } from '../../system/string';
import { openWalkthrough } from '../../system/utils';
import { satisfies } from '../../system/version';
import { ensurePlusFeaturesEnabled } from './utils';
// TODO: What user-agent should we use?
const userAgent = 'Visual-Studio-Code-GitLens';
export interface SubscriptionChangeEvent {
readonly current: Subscription;
readonly previous: Subscription;
readonly etag: number;
}
export class SubscriptionService implements Disposable {
private static authenticationProviderId = 'gitlens+';
private static authenticationScopes = ['gitlens'];
private _onDidChange = new EventEmitter<SubscriptionChangeEvent>();
get onDidChange(): Event<SubscriptionChangeEvent> {
return this._onDidChange.event;
}
private _disposable: Disposable;
private _subscription!: Subscription;
private _statusBarSubscription: StatusBarItem | undefined;
private _validationTimer: ReturnType<typeof setInterval> | undefined;
constructor(private readonly container: Container, previousVersion: string | undefined) {
this._disposable = Disposable.from(
once(container.onReady)(this.onReady, this),
this.container.subscriptionAuthentication.onDidChangeSessions(
e => setTimeout(() => this.onAuthenticationChanged(e), 0),
this,
),
configuration.onDidChange(e => {
if (configuration.changed(e, 'plusFeatures')) {
this.updateContext();
}
}),
);
const subscription = this.getStoredSubscription();
// Resets the preview trial state on the upgrade to 13.0
if (subscription != null && satisfies(previousVersion, '< 13.0')) {
subscription.previewTrial = undefined;
}
this.changeSubscription(subscription, true);
setTimeout(() => void this.ensureSession(false), 10000);
}
dispose(): void {
this._statusBarSubscription?.dispose();
this._disposable.dispose();
}
private async onAuthenticationChanged(e: AuthenticationProviderAuthenticationSessionsChangeEvent) {
let session = this._session;
if (session == null && this._sessionPromise != null) {
session = await this._sessionPromise;
}
if (session != null && e.removed?.some(s => s.id === session!.id)) {
this._session = undefined;
this._sessionPromise = undefined;
void this.logout();
return;
}
const updated = e.added?.[0] ?? e.changed?.[0];
if (updated == null) return;
if (updated.id === session?.id && updated.accessToken === session?.accessToken) {
return;
}
this._session = session;
void this.validate();
}
@memoize()
private get baseApiUri(): Uri {
const { env } = this.container;
if (env === 'staging') {
return Uri.parse('https://stagingapi.gitkraken.com');
}
if (env === 'dev') {
return Uri.parse('https://devapi.gitkraken.com');
}
return Uri.parse('https://api.gitkraken.com');
}
@memoize()
private get baseAccountUri(): Uri {
const { env } = this.container;
if (env === 'staging') {
return Uri.parse('https://stagingapp.gitkraken.com');
}
if (env === 'dev') {
return Uri.parse('https://devapp.gitkraken.com');
}
return Uri.parse('https://app.gitkraken.com');
}
@memoize()
private get baseSiteUri(): Uri {
const { env } = this.container;
if (env === 'staging') {
return Uri.parse('https://staging.gitkraken.com');
}
if (env === 'dev') {
return Uri.parse('https://dev.gitkraken.com');
}
return Uri.parse('https://gitkraken.com');
}
private _etag: number = 0;
get etag(): number {
return this._etag;
}
private onReady() {
this._disposable = Disposable.from(
this._disposable,
this.container.git.onDidChangeRepositories(this.onRepositoriesChanged, this),
...this.registerCommands(),
);
this.updateContext();
}
private onRepositoriesChanged(_e: RepositoriesChangeEvent): void {
this.updateContext();
}
private registerCommands(): Disposable[] {
void this.container.viewCommands;
return [
registerCommand(Commands.PlusLearn, openToSide => this.learn(openToSide)),
registerCommand(Commands.PlusLoginOrSignUp, () => this.loginOrSignUp()),
registerCommand(Commands.PlusLogout, () => this.logout()),
registerCommand(Commands.PlusStartPreviewTrial, () => this.startPreviewTrial()),
registerCommand(Commands.PlusManage, () => this.manage()),
registerCommand(Commands.PlusPurchase, () => this.purchase()),
registerCommand(Commands.PlusResendVerification, () => this.resendVerification()),
registerCommand(Commands.PlusValidate, () => this.validate()),
registerCommand(Commands.PlusShowPlans, () => this.showPlans()),
registerCommand(Commands.PlusHide, () => configuration.updateEffective('plusFeatures.enabled', false)),
registerCommand(Commands.PlusRestore, () => configuration.updateEffective('plusFeatures.enabled', true)),
registerCommand('gitlens.plus.reset', () => this.logout(true)),
];
}
async getSubscription(cached = false): Promise<Subscription> {
const promise = this.ensureSession(false);
if (!cached) {
void (await promise);
}
return this._subscription;
}
@debug()
learn(openToSide: boolean = true): void {
void openWalkthrough(this.container.context.extension.id, 'gitlens.plus', undefined, openToSide);
}
@log()
async loginOrSignUp(): Promise<boolean> {
if (!(await ensurePlusFeaturesEnabled())) return false;
// Abort any waiting authentication to ensure we can start a new flow
await this.container.subscriptionAuthentication.abort();
void this.showHomeView();
const session = await this.ensureSession(true);
const loggedIn = Boolean(session);
if (loggedIn) {
const {
account,
plan: { actual, effective },
} = this._subscription;
if (account?.verified === false) {
const confirm: MessageItem = { title: 'Resend Verification', isCloseAffordance: true };
const cancel: MessageItem = { title: 'Cancel' };
const result = await window.showInformationMessage(
`Before you can access ${effective.name}, you must verify your email address.`,
confirm,
cancel,
);
if (result === confirm) {
void this.resendVerification();
}
} else if (isSubscriptionTrial(this._subscription)) {
const remaining = getSubscriptionTimeRemaining(this._subscription, 'days');
const confirm: MessageItem = { title: 'OK', isCloseAffordance: true };
const learn: MessageItem = { title: 'Learn More' };
const result = await window.showInformationMessage(
`Welcome to ${
effective.name
} (Trial). You now have additional access to GitLens+ features on private repos for ${pluralize(
'more day',
remaining ?? 0,
)}.`,
{ modal: true },
confirm,
learn,
);
if (result === learn) {
this.learn();
}
} else if (isSubscriptionPaid(this._subscription)) {
void window.showInformationMessage(
`Welcome to ${actual.name}. You now have additional access to GitLens+ features on private repos.`,
'OK',
);
} else {
void window.showInformationMessage(
`Welcome to ${actual.name}. You have access to GitLens+ features on local & public repos.`,
'OK',
);
}
}
return loggedIn;
}
@log()
async logout(reset: boolean = false): Promise<void> {
return this.logoutCore(reset);
}
private async logoutCore(reset: boolean = false): Promise<void> {
if (this._validationTimer != null) {
clearInterval(this._validationTimer);
this._validationTimer = undefined;
}
await this.container.subscriptionAuthentication.abort();
this._sessionPromise = undefined;
if (this._session != null) {
void this.container.subscriptionAuthentication.removeSession(this._session.id);
this._session = undefined;
} else {
// Even if we don't have a session, make sure to remove any other matching sessions
void this.container.subscriptionAuthentication.removeSessionsByScopes(
SubscriptionService.authenticationScopes,
);
}
if (reset && this.container.debugging) {
this.changeSubscription(undefined);
return;
}
this.changeSubscription({
...this._subscription,
plan: {
actual: getSubscriptionPlan(
SubscriptionPlanId.Free,
this._subscription.plan?.actual?.startedOn != null
? new Date(this._subscription.plan.actual.startedOn)
: undefined,
),
effective: getSubscriptionPlan(
SubscriptionPlanId.Free,
this._subscription.plan?.effective?.startedOn != null
? new Date(this._subscription.plan.actual.startedOn)
: undefined,
),
},
account: undefined,
});
}
@log()
manage(): void {
void env.openExternal(this.baseAccountUri);
}
@log()
async purchase(): Promise<void> {
if (!(await ensurePlusFeaturesEnabled())) return;
if (this._subscription.account == null) {
this.showPlans();
} else {
void env.openExternal(
Uri.joinPath(this.baseAccountUri, 'purchase-license').with({ query: 'product=gitlens&license=PRO' }),
);
}
await this.showHomeView();
}
@gate()
@log()
async resendVerification(): Promise<boolean> {
if (this._subscription.account?.verified) return true;
const scope = getLogScope();
void this.showHomeView(true);
const session = await this.ensureSession(false);
if (session == null) return false;
try {
const rsp = await fetch(Uri.joinPath(this.baseApiUri, 'resend-email').toString(), {
method: 'POST',
agent: getProxyAgent(),
headers: {
Authorization: `Bearer ${session.accessToken}`,
'User-Agent': userAgent,
'Content-Type': 'application/json',
},
body: JSON.stringify({ id: session.account.id }),
});
if (!rsp.ok) {
debugger;
Logger.error(
'',
scope,
`Unable to resend verification email; status=(${rsp.status}): ${rsp.statusText}`,
);
void window.showErrorMessage(`Unable to resend verification email; Status: ${rsp.statusText}`, 'OK');
return false;
}
const confirm = { title: 'Recheck' };
const cancel = { title: 'Cancel' };
const result = await window.showInformationMessage(
"Once you have verified your email address, click 'Recheck'.",
confirm,
cancel,
);
if (result === confirm) {
await this.validate();
return true;
}
} catch (ex) {
Logger.error(ex, scope);
debugger;
void window.showErrorMessage('Unable to resend verification email', 'OK');
}
return false;
}
@log()
async showHomeView(silent: boolean = false): Promise<void> {
if (silent && !configuration.get('plusFeatures.enabled', undefined, true)) return;
if (!this.container.homeView.visible) {
await executeCommand(Commands.ShowHomeView);
}
}
private showPlans(): void {
void env.openExternal(Uri.joinPath(this.baseSiteUri, 'gitlens/pricing'));
}
@gate()
@log()
async startPreviewTrial(silent?: boolean): Promise<void> {
if (!(await ensurePlusFeaturesEnabled())) return;
let { plan, previewTrial } = this._subscription;
if (previewTrial != null) {
void this.showHomeView();
if (!silent && plan.effective.id === SubscriptionPlanId.Free) {
const confirm: MessageItem = { title: 'Extend Your Trial', isCloseAffordance: true };
const cancel: MessageItem = { title: 'Cancel' };
const result = await window.showInformationMessage(
'Your 3-day trial has ended.\nExtend your GitLens Pro trial to continue to use GitLens+ features on private repos, free for an additional 7-days.',
{ modal: true },
confirm,
cancel,
);
if (result === confirm) {
void this.loginOrSignUp();
}
}
return;
}
const startedOn = new Date();
let days;
let expiresOn = new Date(startedOn);
if (!this.container.debugging) {
// Normalize the date to just before midnight on the same day
expiresOn.setHours(23, 59, 59, 999);
expiresOn = createFromDateDelta(expiresOn, { days: 3 });
days = 3;
} else {
expiresOn = createFromDateDelta(expiresOn, { minutes: 1 });
days = 0;
}
previewTrial = {
startedOn: startedOn.toISOString(),
expiresOn: expiresOn.toISOString(),
};
this.changeSubscription({
...this._subscription,
plan: {
...this._subscription.plan,
effective: getSubscriptionPlan(SubscriptionPlanId.Pro, startedOn, expiresOn),
},
previewTrial: previewTrial,
});
if (!silent) {
const confirm: MessageItem = { title: 'OK', isCloseAffordance: true };
const learn: MessageItem = { title: 'Learn More' };
const result = await window.showInformationMessage(
`You have started a ${days}-day GitLens Pro trial of GitLens+ features on private repos.`,
{ modal: true },
confirm,
learn,
);
if (result === learn) {
this.learn();
}
}
}
@gate()
@log()
async validate(): Promise<void> {
const scope = getLogScope();
const session = await this.ensureSession(false);
if (session == null) {
this.changeSubscription(this._subscription);
return;
}
try {
await this.checkInAndValidate(session);
} catch (ex) {
Logger.error(ex, scope);
debugger;
}
}
private _lastCheckInDate: Date | undefined;
@gate<SubscriptionService['checkInAndValidate']>(s => s.account.id)
private async checkInAndValidate(session: AuthenticationSession, showSlowProgress: boolean = false): Promise<void> {
if (!showSlowProgress) return this.checkInAndValidateCore(session);
const validating = this.checkInAndValidateCore(session);
const result = await Promise.race([
validating,
new Promise<boolean>(resolve => setTimeout(() => resolve(true), 3000)),
]);
if (result) {
await window.withProgress(
{
location: ProgressLocation.Notification,
title: 'Validating your GitLens+ account...',
},
() => validating,
);
}
}
@debug<SubscriptionService['checkInAndValidate']>({ args: { 0: s => s?.account.label } })
private async checkInAndValidateCore(session: AuthenticationSession): Promise<void> {
const scope = getLogScope();
try {
const checkInData = {
id: session.account.id,
platform: getPlatform(),
gitlensVersion: this.container.version,
vscodeEdition: env.appName,
vscodeHost: env.appHost,
vscodeVersion: codeVersion,
previewStartedOn: this._subscription.previewTrial?.startedOn,
previewExpiresOn: this._subscription.previewTrial?.expiresOn,
};
const rsp = await fetch(Uri.joinPath(this.baseApiUri, 'gitlens/checkin').toString(), {
method: 'POST',
agent: getProxyAgent(),
headers: {
Authorization: `Bearer ${session.accessToken}`,
'User-Agent': userAgent,
'Content-Type': 'application/json',
},
body: JSON.stringify(checkInData),
});
if (!rsp.ok) {
throw new AccountValidationError('Unable to validate account', undefined, rsp.status, rsp.statusText);
}
const data: GKLicenseInfo = await rsp.json();
this.validateSubscription(data);
this._lastCheckInDate = new Date();
} catch (ex) {
Logger.error(ex, scope);
debugger;
if (ex instanceof AccountValidationError) throw ex;
throw new AccountValidationError('Unable to validate account', ex);
} finally {
this.startDailyValidationTimer();
}
}
private startDailyValidationTimer(): void {
if (this._validationTimer != null) {
clearInterval(this._validationTimer);
}
// Check 4 times a day to ensure we validate at least once a day
this._validationTimer = setInterval(() => {
if (this._lastCheckInDate == null || this._lastCheckInDate.getDate() !== new Date().getDate()) {
void this.ensureSession(false, true);
}
}, 1000 * 60 * 60 * 6);
}
@debug()
private validateSubscription(data: GKLicenseInfo) {
const account: Subscription['account'] = {
id: data.user.id,
name: data.user.name,
email: data.user.email,
verified: data.user.status === 'activated',
};
const effectiveLicenses = Object.entries(data.licenses.effectiveLicenses) as [GKLicenseType, GKLicense][];
const paidLicenses = Object.entries(data.licenses.paidLicenses) as [GKLicenseType, GKLicense][];
let actual: Subscription['plan']['actual'] | undefined;
if (paidLicenses.length > 0) {
paidLicenses.sort(
(a, b) =>
licenseStatusPriority(b[1].latestStatus) - licenseStatusPriority(a[1].latestStatus) ||
getSubscriptionPlanPriority(convertLicenseTypeToPlanId(b[0])) -
getSubscriptionPlanPriority(convertLicenseTypeToPlanId(a[0])),
);
const [licenseType, license] = paidLicenses[0];
actual = getSubscriptionPlan(
convertLicenseTypeToPlanId(licenseType),
new Date(license.latestStartDate),
new Date(license.latestEndDate),
);
}
if (actual == null) {
actual = getSubscriptionPlan(
SubscriptionPlanId.FreePlus,
data.user.firstGitLensCheckIn != null ? new Date(data.user.firstGitLensCheckIn) : undefined,
);
}
let effective: Subscription['plan']['effective'] | undefined;
if (effectiveLicenses.length > 0) {
effectiveLicenses.sort(
(a, b) =>
licenseStatusPriority(b[1].latestStatus) - licenseStatusPriority(a[1].latestStatus) ||
getSubscriptionPlanPriority(convertLicenseTypeToPlanId(b[0])) -
getSubscriptionPlanPriority(convertLicenseTypeToPlanId(a[0])),
);
const [licenseType, license] = effectiveLicenses[0];
effective = getSubscriptionPlan(
convertLicenseTypeToPlanId(licenseType),
new Date(license.latestStartDate),
new Date(license.latestEndDate),
);
}
if (effective == null) {
effective = { ...actual };
}
this.changeSubscription({
...this._subscription,
plan: {
actual: actual,
effective: effective,
},
account: account,
});
}
private _sessionPromise: Promise<AuthenticationSession | null> | undefined;
private _session: AuthenticationSession | null | undefined;
@gate()
@debug()
private async ensureSession(createIfNeeded: boolean, force?: boolean): Promise<AuthenticationSession | undefined> {
if (this._sessionPromise != null && this._session === undefined) {
void (await this._sessionPromise);
}
if (!force && this._session != null) return this._session;
if (this._session === null && !createIfNeeded) return undefined;
if (this._sessionPromise === undefined) {
this._sessionPromise = this.getOrCreateSession(createIfNeeded).then(
s => {
this._session = s;
this._sessionPromise = undefined;
return this._session;
},
() => {
this._session = null;
this._sessionPromise = undefined;
return this._session;
},
);
}
const session = await this._sessionPromise;
return session ?? undefined;
}
@debug()
private async getOrCreateSession(createIfNeeded: boolean): Promise<AuthenticationSession | null> {
const scope = getLogScope();
let session: AuthenticationSession | null | undefined;
try {
session = await authentication.getSession(
SubscriptionService.authenticationProviderId,
SubscriptionService.authenticationScopes,
{
createIfNone: createIfNeeded,
silent: !createIfNeeded,
},
);
} catch (ex) {
session = null;
if (ex instanceof Error && ex.message.includes('User did not consent')) {
Logger.debug(scope, 'User declined authentication');
await this.logoutCore();
return null;
}
Logger.error(ex, scope);
}
// If we didn't find a session, check if we could migrate one from the GK auth provider
if (session === undefined) {
session = await this.container.subscriptionAuthentication.tryMigrateSession();
}
if (session == null) {
Logger.debug(scope, 'No valid session was found');
await this.logoutCore();
return session ?? null;
}
try {
await this.checkInAndValidate(session, createIfNeeded);
} catch (ex) {
Logger.error(ex, scope);
debugger;
if (ex instanceof AccountValidationError) {
const name = session.account.label;
if (
(ex.statusCode != null && ex.statusCode < 500) ||
(ex.statusCode == null && (ex.original as any)?.code !== 'ENOTFOUND')
) {
session = null;
Logger.debug(scope, `Account validation failed (${ex.statusCode ?? (ex.original as any)?.code})`);
await this.logoutCore();
if (createIfNeeded) {
const unauthorized = ex.statusCode === 401;
queueMicrotask(async () => {
const confirm: MessageItem = { title: 'Retry Sign In' };
const result = await window.showErrorMessage(
`Unable to sign in to your (${name}) GitLens+ account. Please try again. If this issue persists, please contact support.${
unauthorized ? '' : ` Error=${ex.message}`
}`,
confirm,
);
if (result === confirm) {
void this.loginOrSignUp();
}
});
}
} else {
session = session ?? null;
if ((ex.original as any)?.code !== 'ENOTFOUND') {
void window.showErrorMessage(
`Unable to sign in to your (${name}) GitLens+ account right now. Please try again in a few minutes. If this issue persists, please contact support. Error=${ex.message}`,
'OK',
);
}
}
}
}
return session;
}
@debug()
private changeSubscription(
subscription: Optional<Subscription, 'state'> | undefined,
silent: boolean = false,
): void {
if (subscription == null) {
subscription = {
plan: {
actual: getSubscriptionPlan(SubscriptionPlanId.Free),
effective: getSubscriptionPlan(SubscriptionPlanId.Free),
},
account: undefined,
state: SubscriptionState.Free,
};
}
// Check if the preview has expired, if not apply it
if (subscription.previewTrial != null && (getTimeRemaining(subscription.previewTrial.expiresOn) ?? 0) > 0) {
subscription = {
...subscription,
plan: {
...subscription.plan,
effective: getSubscriptionPlan(
SubscriptionPlanId.Pro,
new Date(subscription.previewTrial.startedOn),
new Date(subscription.previewTrial.expiresOn),
),
},
};
}
// If the effective plan has expired, then replace it with the actual plan
if (isSubscriptionExpired(subscription)) {
subscription = {
...subscription,
plan: {
...subscription.plan,
effective: subscription.plan.actual,
},
};
}
subscription.state = computeSubscriptionState(subscription);
assertSubscriptionState(subscription);
const previous = this._subscription; // Can be undefined here, since we call this in the constructor
// If the previous and new subscriptions are exactly the same, kick out
if (previous != null && JSON.stringify(previous) === JSON.stringify(subscription)) {
return;
}
void this.storeSubscription(subscription);
this._subscription = subscription;
this._etag = Date.now();
setTimeout(() => {
if (
new Date() < new Date('2022-10-18T00:00:00.000Z') &&
subscription!.account != null &&
!isSubscriptionPaid(subscription!)
) {
void showProDiscountNotification(this.container);
}
}, 5000);
if (!silent) {
this.updateContext();
if (previous != null) {
this._onDidChange.fire({ current: subscription, previous: previous, etag: this._etag });
}
}
}
private getStoredSubscription(): Subscription | undefined {
const storedSubscription = this.container.storage.get('premium:subscription');
const subscription = storedSubscription?.data;
if (subscription != null) {
// Migrate the plan names to the latest names
(subscription.plan.actual as Mutable<Subscription['plan']['actual']>).name = getSubscriptionPlanName(
subscription.plan.actual.id,
);
(subscription.plan.effective as Mutable<Subscription['plan']['effective']>).name = getSubscriptionPlanName(
subscription.plan.effective.id,
);
}
return subscription;
}
private async storeSubscription(subscription: Subscription): Promise<void> {
return this.container.storage.store('premium:subscription', {
v: 1,
data: subscription,
});
}
private updateContext(): void {
this.updateStatusBar();
queueMicrotask(async () => {
let allowed: boolean | 'mixed' = false;
// For performance reasons, only check if we have any repositories
if (this.container.git.repositoryCount !== 0) {
({ allowed } = await this.container.git.access());
}
void setContext(ContextKeys.PlusEnabled, Boolean(allowed) || configuration.get('plusFeatures.enabled'));
void setContext(ContextKeys.PlusRequired, allowed === false);
});
const {
plan: { actual },
state,
} = this._subscription;
void setContext(ContextKeys.Plus, actual.id != SubscriptionPlanId.Free ? actual.id : undefined);
void setContext(ContextKeys.PlusState, state);
}
private updateStatusBar(): void {
const {
account,
plan: { effective },
} = this._subscription;
if (effective.id === SubscriptionPlanId.Free) {
this._statusBarSubscription?.dispose();
this._statusBarSubscription = undefined;
return;
}
const trial = isSubscriptionTrial(this._subscription);
if (!trial && account?.verified !== false) {
this._statusBarSubscription?.dispose();
this._statusBarSubscription = undefined;
return;
}
if (this._statusBarSubscription == null) {
this._statusBarSubscription = window.createStatusBarItem(
'gitlens.plus.subscription',
StatusBarAlignment.Left,
1,
);
}
this._statusBarSubscription.name = 'GitLens+ Subscription';
this._statusBarSubscription.command = Commands.ShowHomeView;
if (account?.verified === false) {
this._statusBarSubscription.text = `$(warning) ${effective.name} (Unverified)`;
this._statusBarSubscription.backgroundColor = new ThemeColor('statusBarItem.warningBackground');
this._statusBarSubscription.tooltip = new MarkdownString(
trial
? `**Please verify your email**\n\nBefore you can start your **${effective.name}** trial, please verify your email address.\n\nClick for details`
: `**Please verify your email**\n\nBefore you can also use GitLens+ features on private repos, please verify your email address.\n\nClick for details`,
true,
);
} else {
const remaining = getSubscriptionTimeRemaining(this._subscription, 'days');
this._statusBarSubscription.text = `${effective.name} (Trial)`;
this._statusBarSubscription.tooltip = new MarkdownString(
`You have ${pluralize('day', remaining ?? 0)} left in your **${
effective.name
}** trial, which gives you additional access to GitLens+ features on private repos.\n\nClick for details`,
true,
);
}
this._statusBarSubscription.show();
}
}
function assertSubscriptionState(subscription: Optional<Subscription, 'state'>): asserts subscription is Subscription {}
interface GKLicenseInfo {
user: GKUser;
licenses: {
paidLicenses: Record<GKLicenseType, GKLicense>;
effectiveLicenses: Record<GKLicenseType, GKLicense>;
};
}
type GKLicenseType =
| 'gitlens-pro'
| 'gitlens-teams'
| 'gitlens-hosted-enterprise'
| 'gitlens-self-hosted-enterprise'
| 'gitlens-standalone-enterprise'
| 'bundle-pro'
| 'bundle-teams'
| 'bundle-hosted-enterprise'
| 'bundle-self-hosted-enterprise'
| 'bundle-standalone-enterprise';
function convertLicenseTypeToPlanId(licenseType: GKLicenseType): SubscriptionPlanId {
switch (licenseType) {
case 'gitlens-pro':
case 'bundle-pro':
return SubscriptionPlanId.Pro;
case 'gitlens-teams':
case 'bundle-teams':
return SubscriptionPlanId.Teams;
case 'gitlens-hosted-enterprise':
case 'gitlens-self-hosted-enterprise':
case 'gitlens-standalone-enterprise':