forked from dart-lang/dart-pad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.dart
1072 lines (934 loc) · 38.4 KB
/
github.dart
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) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library playground;
import 'dart:async';
import 'dart:convert' show json;
import 'dart:html' hide Console;
import 'dart:math';
import 'package:encrypt/encrypt.dart';
import 'package:http/http.dart' as http;
import 'package:mdc_web/mdc_web.dart';
import 'package:stream_transform/stream_transform.dart';
import 'dart_pad.dart';
import 'elements/analysis_results_controller.dart';
import 'elements/button.dart';
import 'elements/elements.dart';
import 'playground.dart';
import 'sharing/gists.dart';
import 'sharing/mutable_gist.dart';
const localStorageKeyForGitHubRandomState = 'github_random_state';
const localStorageKeyForGitHubAvatarUrl = 'github_avatar_url';
const localStorageKeyForQueryParamsPreOAuthRequest = 'gh_pre_auth_query_params';
const localStorageKeyForGitHubOAuthToken = 'github_oauth_token';
const localStorageKeyForGitHubUserLogin = 'github_user_login';
const queryParamRedirectBeforeLogin = 'initiateGitHubLogin';
class GitHubUIController {
static const entryPointGitHubOAuthInitiate = 'github_oauth_initiate';
final Playground _playground;
late final GitHubAuthenticationController _githubAuthController;
final _githubMenuItemLogin = querySelector('#github-login-item') as LIElement;
final _githubMenuItemCreatePublic =
querySelector('#github-createpublic-item') as LIElement;
final _githubMenuItemCreatePrivate =
querySelector('#github-createprivate-item') as LIElement;
final _githubMenuItemFork = querySelector('#github-fork-item') as LIElement;
final _githubMenuItemUpdate =
querySelector('#github-update-item') as LIElement;
final _githubMenuItemStar = querySelector('#github-star-item') as LIElement;
final _githubMenuItemOpenOnGithub =
querySelector('#github-open-on-github-item') as LIElement;
final _githubMenuItemLogout =
querySelector('#github-logout-item') as LIElement;
final _starUnstarButton = querySelector('#gist_star_button') as SpanElement;
final Element _starIconHolder = querySelector('#gist_star_inner_icon')!;
final Element _starMenuIconHolder =
querySelector('#github-star-item .mdc-select__icon')!;
final _starMenuItemText =
querySelector('#github-star-item .mdc-list-item__text') as SpanElement;
final _titleElement = DElement(querySelector('header .header-gist-name')!);
final _myGistsDropdownButton =
querySelector('#my-gists-dropdown-button') as ButtonElement;
final _starredGistsDropdownButton =
querySelector('#starred-gists-dropdown-button') as ButtonElement;
MDCMenu? _starredGistsMenu;
MDCMenu? _myGistsMenu;
bool _prevAuthenticationState = false;
bool _inGithubAuthStateChangeHandler = false;
String _gistIdOfLastStarredReport = '';
bool _starredStateOfLastStarReport = false;
GitHubUIController(this._playground) {
_githubAuthController = GitHubAuthenticationController(
Uri.parse(window.location.toString()), _playground.snackbar);
if (_githubAuthController.delayedGitHubLoginRequested) {
// A delayed GitHub login has been requested, so initiate it.
// This occurs when the user was on a NON `dartpad.dev` url,
// and selected the GitHub login menu. We must initiate that
// starting from `dartpad.dev`, so we were redirected to `dartpad.dev`
// with an added query parameter (defined by [queryParamRedirectBeforeLogin]).
// This query parameter has been detected and indicates that we should
// continue as if the user has selected the 'GitHub login' menu.
_attemptToAquireGitHubToken();
return;
}
initGitHubMenu();
setupGithubGistListeners();
_githubAuthController.postCreationFireAutheticatedStateChangeEvent();
}
void initGitHubMenu() {
final githubMenuButton =
querySelector('#github-menu-button') as ButtonElement;
final githubMenu = MDCMenu(querySelector('#github-menu'))
..setAnchorCorner(AnchorCorner.bottomLeft)
..setAnchorElement(githubMenuButton)
..hoistMenuToBody();
MDCButton(githubMenuButton, isIcon: true)
.onClick
.listen((_) => Playground.toggleMenu(githubMenu));
githubMenu.listen('MDCMenu:selected', (e) {
final idx = (e as CustomEvent).detail['index'] as int?;
switch (idx) {
case 0: // login
_attemptToAquireGitHubToken();
break;
case 1: // create public gist
_saveGist();
break;
case 2: // create private gist
_saveGist(public: false);
break;
case 3: // fork gists
_forkGist();
break;
case 4: //update gists
_updateGist();
break;
case 5: //star gists
_starredButtonClickHandler(null);
break;
case 6: //open on github
window.open('https://gist.github.com/${_playground.mutableGist.id}',
'_blank');
// And in 10 seconds check with github and update our my gists and starred menus.
// This is just another wait to force a check with github to sync
// our menus up. (The long delay in starred API results updating can be frustrating
// on the client end waiting for the github server to report the change).
_githubAuthController.updateUsersGistAndStarredGistsList(
starredCheckDelay: 10000);
break;
case 7: //logout
_githubAuthController.logoutUnauthenticate();
break;
}
});
}
void setUnsavedLocalEdits([bool unsavedLocalEdits = false]) {
final unsavedLocalEditsSpan =
querySelector('#unsaved-local-edit') as SpanElement;
unsavedLocalEdits = unsavedLocalEdits || _playground.mutableGist.dirty;
if (unsavedLocalEdits) {
unsavedLocalEditsSpan.removeAttribute('hidden');
} else {
unsavedLocalEditsSpan.setAttribute('hidden', true);
}
}
void setupGithubGistListeners() {
_playground.mutableGist.onChanged
.debounce(Duration(milliseconds: 100))
.listen((_) {
setUnsavedLocalEdits();
});
_playground.mutableGist.property('id').onChanged!.listen((_) {
// The gist Id has changed.
_setGithubMenuItemStates(_githubAuthController, _playground.mutableGist);
});
_githubAuthController.onAuthStateChanged.listen((authenticated) {
_setGithubMenuItemStates(_githubAuthController, _playground.mutableGist);
_handleGithubAuthStateChange(authenticated);
});
_githubAuthController.onMyGistListChanged.listen((authenticated) {
_updateMyGistMenuState();
});
_githubAuthController.onStarredGistListChanged.listen((authenticated) {
_updateStarredGistMenuState();
});
_starUnstarButton.onClick
.debounce(Duration(milliseconds: 100))
.listen(_starredButtonClickHandler);
// This will only happen when we make 'contenteditable' true while authenticated.
_titleElement.element.onInput
.debounce(Duration(milliseconds: 100))
.listen((_) {
_playground.mutableGist.description = _titleElement.text;
setUnsavedLocalEdits();
});
}
void _setGithubMenuItemStates(GitHubAuthenticationController githubController,
MutableGist mutableGist) {
final hasId = mutableGist.hasId;
final loggedIn = githubController.userLogin.isNotEmpty;
_setMenuItemState(_githubMenuItemLogin, !loggedIn);
_setMenuItemState(_githubMenuItemLogout, loggedIn);
_setMenuItemState(_githubMenuItemCreatePublic,
loggedIn /*&& !hasId*/); // Now let them create public without forking, uncomment `** hasId` for force forking.
_setMenuItemState(_githubMenuItemCreatePrivate,
loggedIn); // Let then create private gist without forking.
_setMenuItemState(_githubMenuItemFork, loggedIn && hasId);
_setMenuItemState(_githubMenuItemUpdate, loggedIn && hasId);
_setMenuItemState(_githubMenuItemStar, loggedIn && hasId);
_setMenuItemState(_githubMenuItemOpenOnGithub, loggedIn && hasId);
}
void _updateMyGistMenuState() {
final myGists = querySelector('#my-gists') as DivElement;
if (_githubAuthController.myGistList.isEmpty) {
// Hide the starred gist menu.
myGists.setAttribute('hidden', true);
} else {
myGists.removeAttribute('hidden');
}
final firstTime = (_myGistsMenu == null);
_myGistsMenu = _buildOrUpdateMyGistsMenu(_myGistsMenu);
if (firstTime) {
MDCButton(_myGistsDropdownButton)
.onClick
.listen((e) => Playground.toggleMenu(_myGistsMenu));
}
}
void _updateStarredGistMenuState() {
final starredGists = querySelector('#starred-gists') as DivElement;
if (_githubAuthController.starredGistList.isEmpty) {
// Hide the starred gist menu.
starredGists.setAttribute('hidden', true);
} else {
starredGists.removeAttribute('hidden');
}
final firstTime = (_starredGistsMenu == null);
_starredGistsMenu = _buildOrUpdateStarredGistsMenu(_starredGistsMenu);
if (firstTime) {
MDCButton(_starredGistsDropdownButton)
.onClick
.listen((e) => Playground.toggleMenu(_starredGistsMenu));
}
}
void _handleGithubAuthStateChange(bool authenticated) {
if (_inGithubAuthStateChangeHandler) {
return;
}
_inGithubAuthStateChangeHandler = true;
final avUrl = _githubAuthController.avatarUrl;
final loginUser = _githubAuthController.userLogin;
if (!_prevAuthenticationState && loginUser.isNotEmpty) {
_playground.snackbar
.showMessage('You are now logged into GitHub as $loginUser');
}
final avatarImg = querySelector('#github-avatar') as ImageElement;
if (avUrl.isNotEmpty) {
avatarImg.src = avUrl;
avatarImg.removeAttribute('hidden');
} else {
avatarImg.removeAttribute('src');
avatarImg.setAttribute('hidden', true);
}
final loggedInAsLi = querySelector('#logged_in_as') as LIElement;
final loggedInAsText = querySelector('#logged_in_as_text') as SpanElement;
if (loginUser.isNotEmpty) {
loggedInAsText.innerText = 'Logged in as $loginUser';
loggedInAsLi.removeAttribute('hidden');
} else {
loggedInAsLi.setAttribute('hidden', true);
}
// If we have logged out then update the gists menus (remove items/hide them).
if (_prevAuthenticationState && !authenticated) {
_updateStarredGistMenuState();
_updateMyGistMenuState();
}
if (authenticated) {
getStarReportOnLoadingGist(_playground.mutableGist.id ?? '');
_titleElement.setAttr('contenteditable', 'true');
} else {
hideGistStarredButton();
_titleElement.clearAttr('contenteditable');
}
_prevAuthenticationState = loginUser.isNotEmpty;
_inGithubAuthStateChangeHandler = false;
}
void _attemptToAquireGitHubToken() {
// Remember all of our current query params.
var curUrl = Uri.parse(window.location.toString());
final params = Map<String, String?>.from(curUrl.queryParameters);
if (params.containsKey(queryParamRedirectBeforeLogin)) {
// Remove the [queryParamRedirectBeforeLogin] parameter from the URL,
// we have detected it (after redirect to `dartpad.dev`)
// and now we are initiating the GitHub login. We no longer needed it,
// (and we want to prevent a 'loop').
params.remove(queryParamRedirectBeforeLogin);
curUrl = curUrl.replace(queryParameters: params);
}
final jsonParams = json.encode(params);
if (window.location.hostname != 'dartpad.dev') {
// We have to START our login from `dartpad.dev` as that's where we
// will be returning. We add an additional query parameter
// defined by [queryParamRedirectBeforeLogin] to indicate that we
// should initiate the GitHub login when we arrive at `dartpad.dev`.
// That way to the user it is 'transparent' and the login automatically
// continues when they get there.
params.addAll({queryParamRedirectBeforeLogin: 'true'});
// Change scheme and port also in case those were different also.
final newUrl = curUrl.replace(
scheme: 'https',
host: 'dartpad.dev',
port: 443,
queryParameters: params);
window.location.href = newUrl.toString();
return;
}
window.localStorage[localStorageKeyForQueryParamsPreOAuthRequest] =
jsonParams;
// Use current dartServices root url and add the GitHub OAuth initiation
// end point to it.
final baseUrl = '${dartServices.rootUrl}$entryPointGitHubOAuthInitiate/';
final redirectUrl =
_githubAuthController.makeRandomSecureAuthInitiationUrl(baseUrl);
// Set our window to the redirect URL and get on our way to github OAuth.
window.location.href = redirectUrl;
}
Future<void> _saveGist({bool public = true}) async {
final token = _githubAuthController.githubOAuthAccessToken;
if (token.isNotEmpty) {
final createdGistId = await gistLoader.createGist(
_playground.mutableGist.createGist(), public, token);
_reloadPageWithNewGistId(createdGistId);
setUnsavedLocalEdits();
// Now update our menus to reflect new gist.
_githubAuthController.updateUsersGistAndStarredGistsList();
} else {
_playground.showSnackbar(
'Must be authenticated with GitHub in order to save gist');
}
}
Future<void> _updateGist() async {
final token = _githubAuthController.githubOAuthAccessToken;
if (token.isNotEmpty) {
final Gist clonedGist = _playground.mutableGist.createGist();
await gistLoader.updateGist(clonedGist, token);
setUnsavedLocalEdits();
_playground.showSnackbar('Gist successfully updated');
// Update the backing gist because it is now in github.
_playground.mutableGist.setBackingGist(clonedGist);
// Now update our menus to reflect new gist (description could have changed).
_githubAuthController.updateUsersGistAndStarredGistsList();
} else {
_playground.showSnackbar(
'Must be authenticated with GitHub in order to fork gist');
}
}
Future<void> _forkGist() async {
final token = _githubAuthController.githubOAuthAccessToken;
final unsavedLocalEdits = _playground.mutableGist.dirty;
if (token.isNotEmpty) {
final forkedGistId = await gistLoader.forkGist(
_playground.mutableGist.createGist(), unsavedLocalEdits, token);
if (forkedGistId == GistLoader.gistAlreadyForked) {
_playground.showSnackbar('Failed to fork gist - already a fork');
return;
} else if (forkedGistId == GistLoader.gistNotFound) {
_playground.showSnackbar('Failed to fork gist - gist not found');
return;
}
setUnsavedLocalEdits();
_playground.showSnackbar(unsavedLocalEdits
? 'Gist successfully forked and updated with local edits'
: 'Gist successfully forked'); // This wont have time to show KLUDGE
_reloadPageWithNewGistId(forkedGistId);
// Now update our menus to reflect new gist.
_githubAuthController.updateUsersGistAndStarredGistsList();
} else {
_playground.showSnackbar(
'Must be authenticated with GitHub in order to fork gist');
}
}
void _reloadPageWithNewGistId(String gistId) {
var url = Uri.parse(window.location.toString());
final params = Map<String, String?>.from(url.queryParameters);
params['id'] = gistId;
url = url.replace(queryParameters: params);
window.location.href = url.toString();
}
void _setMenuItemState(LIElement menuitem, bool enabled) {
if (enabled) {
menuitem.classes.remove('mdc-list-item--disabled');
} else {
menuitem.classes.add('mdc-list-item--disabled');
}
}
String _truncateWithEllipsis(String text, int maxlength,
{String ellipsis = '...'}) {
return (text.length < maxlength)
? text
: text.replaceRange(maxlength, text.length, ellipsis);
}
void _myGistMenuHandler(Event e) {
final index = (e as CustomEvent).detail['index'] as int;
final mygists = _githubAuthController.myGistList;
if (index >= 0 && index <= mygists.length) {
final gistId = mygists.elementAt(index).id!;
_playground.showGist(gistId);
}
}
MDCMenu _buildOrUpdateMyGistsMenu(MDCMenu? existingMenu) {
existingMenu?.destroy();
final element = querySelector('#my-gists-menu')!;
element.children.clear();
final mygists = _githubAuthController.myGistList;
if (mygists.isNotEmpty) {
final listElement = _mdcList();
element.children.add(listElement);
for (final gist in mygists) {
var menuTitle = gist.description ?? 'no description';
if (menuTitle.isEmpty) menuTitle = gist.files[0].name;
final menuElement = _mdcListItem(children: [
SpanElement()
..classes.add('mdc-list-item__text')
..setAttribute('title', '$menuTitle (${gist.id})')
..text = _truncateWithEllipsis(menuTitle, 24),
]);
listElement.children.add(menuElement);
}
}
final mygistsMenu = MDCMenu(element)
..setAnchorCorner(AnchorCorner.bottomLeft)
..setAnchorElement(_myGistsDropdownButton)
..hoistMenuToBody();
if (existingMenu == null) {
// Only add the first time, tried unlisten() at top of each creation
// but it did not work and resulted in multiple handlers.
mygistsMenu.listen('MDCMenu:selected', _myGistMenuHandler);
}
return mygistsMenu;
}
void _starredGistMenuHandler(Event e) {
final index = (e as CustomEvent).detail['index'] as int;
final starredGists = _githubAuthController.starredGistList;
if (index >= 0 && index <= starredGists.length) {
final gistId = starredGists.elementAt(index).id!;
_playground.showGist(gistId);
}
}
MDCMenu _buildOrUpdateStarredGistsMenu(MDCMenu? existingMenu) {
existingMenu?.destroy();
final element = querySelector('#starred-gists-menu')!;
element.children.clear();
final starredGists = _githubAuthController.starredGistList;
if (starredGists.isNotEmpty) {
final listElement = _mdcList();
element.children.add(listElement);
for (final gist in starredGists) {
var menuTitle = gist.description ?? 'no description';
if (menuTitle.isEmpty) menuTitle = gist.files[0].name;
final menuElement = _mdcListItem(children: [
SpanElement()
..classes.add('mdc-list-item__text')
..setAttribute('title', '$menuTitle (${gist.id})')
..text = _truncateWithEllipsis(menuTitle, 24),
]);
listElement.children.add(menuElement);
}
}
final starredGistsMenu = MDCMenu(element)
..setAnchorCorner(AnchorCorner.bottomLeft)
..setAnchorElement(_starredGistsDropdownButton)
..hoistMenuToBody();
if (existingMenu == null) {
// Only add the first time, tried unlisten() at top of each creation
// but it did not work and resulted in multiple handlers.
starredGistsMenu.listen('MDCMenu:selected', _starredGistMenuHandler);
}
return starredGistsMenu;
}
/// This hides the star/not starred indicator (and toggle button).
/// This is called by playground when loading a new gist with no-known state
/// and it will reappear once correct state is known.
void hideGistStarredButton() {
final starUnstarButton = querySelector('#gist_star_button') as SpanElement;
starUnstarButton.hidden = true;
}
Future<void> _starredButtonClickHandler(_) async {
if (_starUnstarButton.hidden ||
!_playground.mutableGist.hasId ||
_gistIdOfLastStarredReport.isEmpty ||
_gistIdOfLastStarredReport != _playground.mutableGist.id) {
// Do nothing, don't know state of current gist.
return;
}
final gistIdWeAreToggling = _gistIdOfLastStarredReport;
// Clear until we report back (prevents another click until done).
_gistIdOfLastStarredReport = '';
if (!_starredStateOfLastStarReport) {
// Immediately set state to where we think it's going, and we will update
// after we get verification from API.
_setStateOfStarredButton(true);
await gistLoader.starGist(
gistIdWeAreToggling, _githubAuthController.githubOAuthAccessToken);
await getStarReportOnLoadingGist(gistIdWeAreToggling, true);
// Now update our menus to reflect change in starred gists.
_githubAuthController.updateUsersGistAndStarredGistsList(
starredCheckDelay: 60000);
} else {
// Immediately set state to where we think it's going, and we will update
// after we get verification from API.
_setStateOfStarredButton(false);
await gistLoader.unstarGist(
gistIdWeAreToggling, _githubAuthController.githubOAuthAccessToken);
await getStarReportOnLoadingGist(gistIdWeAreToggling, true);
// Now update our menus to reflect change in starred gists.
_githubAuthController.updateUsersGistAndStarredGistsList(
starredCheckDelay: 60000);
}
}
void _setStateOfStarredButton(bool starred) {
_starUnstarButton.hidden = false;
if (starred) {
// Title bar gist star indicator.
_starIconHolder.innerText = 'star';
_starUnstarButton.title = 'Click to Unstar this gist';
// Menu item star gist action.
_starMenuIconHolder.innerText = 'star_outline';
_starMenuItemText.innerText = 'Unstar Gist';
} else {
// Title bar gist star indicator.
_starIconHolder.innerText = 'star_outline';
_starUnstarButton.title = 'Click to Star this gist';
// Menu item star gist action.
_starMenuIconHolder.innerText = 'star';
_starMenuItemText.innerText = 'Star Gist';
}
}
/// Request a report on the state of this Gist's star status for the
/// currently authenticated user, updates UI once known.
Future<void> getStarReportOnLoadingGist(String gistId,
[bool dontHideStarButton = false]) async {
if (!dontHideStarButton) hideGistStarredButton();
if (_githubAuthController.githubOAuthAccessToken.isNotEmpty &&
gistId.isNotEmpty) {
_gistIdOfLastStarredReport = '';
final starred = await gistLoader.checkIfGistIsStarred(
gistId, _githubAuthController.githubOAuthAccessToken);
_gistIdOfLastStarredReport = gistId;
_starredStateOfLastStarReport = starred;
_setStateOfStarredButton(starred);
}
}
UListElement _mdcList() => UListElement()
..classes.add('mdc-list')
..attributes.addAll({
'aria-hidden': 'true',
'aria-orientation': 'vertical',
'tabindex': '-1'
});
LIElement _mdcListItem({List<Element> children = const []}) {
final element = LIElement()
..classes.add('mdc-list-item')
..attributes.addAll({'role': 'menuitem'});
for (final child in children) {
element.children.add(child);
}
return element;
}
}
/// This handles interacting with our authentication initiation endpoint and
/// interacting with GitHub API endpoints for getting user info.
/// (The process of initiating and interacting with GitHub OAuth server
/// must happen from the server. Known secrets must be preserved there
/// and cannot exist on the client side).
class GitHubAuthenticationController {
static const _githubApiUrl = 'https://api.github.com';
static const maxNumberOfGistToLoad = 100;
final Uri launchUri;
late final http.Client _client;
final MDCSnackbar snackbar;
late final bool delayedGitHubLoginRequested;
final _authenticatedStateChangeController =
StreamController<bool>.broadcast();
final _myGistListUpdateController = StreamController.broadcast();
final _starredGistListUpdateController = StreamController.broadcast();
final _gistStarredCheckerReportController = StreamController.broadcast();
Stream<bool> get onAuthStateChanged =>
_authenticatedStateChangeController.stream;
Stream get onMyGistListChanged => _myGistListUpdateController.stream;
Stream get onStarredGistListChanged =>
_starredGistListUpdateController.stream;
Stream get onGistStarredCheckerReport =>
_gistStarredCheckerReportController.stream;
final List<Gist> _myGistList = [];
final List<Gist> _starredGistList = [];
List<Gist> get myGistList => _myGistList;
List<Gist> get starredGistList => _starredGistList;
String? _pendingUserInfoRequest;
String? _pendingUserGistRequest;
String? _pendingUserStarredGistRequest;
GitHubAuthenticationController(this.launchUri, this.snackbar,
{http.Client? client}) {
// Check for parameters in query uri.
_client = client ?? http.Client();
final params = Map<String, String?>.from(launchUri.queryParameters);
final ghTokenFromUrl = params['gh'] ?? '';
final ghScope = params['scope'] ?? '';
delayedGitHubLoginRequested =
(params[queryParamRedirectBeforeLogin] != null);
if (delayedGitHubLoginRequested) {
// A delayed GitHub login has been requested, as we must arrived from
// a redirect from another dartpad url. We return early here because
// a login to GitHub is going to be automatically initiated immediately.
return;
}
if (ghTokenFromUrl.isNotEmpty) {
final String perAuthParamsJson =
window.localStorage[localStorageKeyForQueryParamsPreOAuthRequest] ??
'';
try {
final restoreParams = Map<String, String?>.from(
json.decode(perAuthParamsJson) as Map<dynamic, dynamic>);
final Uri restoredUrl =
launchUri.replace(queryParameters: restoreParams);
window.history.replaceState({}, 'DartPad', restoredUrl.toString());
} catch (e) {
window.console.log(
'Caught exception doing restoreParams : exception ${e.toString()}');
}
if (ghTokenFromUrl == 'noauth' || ghTokenFromUrl == 'authfailed') {
// ERROR was encountered during trip to GH auth.
snackbar.showMessage('Error encountered during GitHub OAuth Request');
return;
}
if (!ghScope.contains('gists')) {
// Give error message but continue in this case.
snackbar.showMessage(
'Error: The scope "gists" was not included with the GitHub OAuth Token');
}
// Now decrypt the GH token and try and init user.
final ghAuthToken =
decryptAuthTokenFromReturnedSecureAuthToken(ghTokenFromUrl);
// Set provided a gh token, if new this will do query on user info.
githubOAuthAccessToken = ghAuthToken;
} else {
// There was no gh token in the window URL, but we may have STORED GH
// authorization in local storage... so we trigger an authentication state change anyway.
}
}
void postCreationFireAutheticatedStateChangeEvent() {
_authenticatedStateChangeController.add(githubOAuthAccessToken != '');
updateUsersGistAndStarredGistsList();
}
Timer? starGistsChecklDelayTimer;
void updateUsersGistAndStarredGistsList({int starredCheckDelay = 100}) {
// Now go and get the lists of user's gists and starred gists.
getUsersGists();
// Github takes a while to update the returned list of starred gists
// after a star/unstar operation, so in those cases we wait
// and extra amount of time... - 60seconds ? long enough?
starGistsChecklDelayTimer?.cancel();
starGistsChecklDelayTimer =
Timer(Duration(milliseconds: starredCheckDelay), () {
getUsersStarredGists();
});
}
void logoutUnauthenticate() {
_myGistList.clear();
_starredGistList.clear();
avatarUrl = '';
userLogin = '';
// Set auth token last as it will fire event.
githubOAuthAccessToken = '';
_authenticatedStateChangeController.add(false);
}
bool get authenticated {
return (githubOAuthAccessToken != '');
}
/*
Request user info from GitHub API.
GET /user
Parameters
Name Type In Description
accept string header Setting toapplication/vnd.github.v3+json is recommended.
https://docs.github.com/en/rest/reference/users#get-the-authenticated-user
example of PUBLIC returned data
{
"login": "octocat",
"id": 1,
"node_id": "MDQ6VXNlcjE=",
"avatar_url": "https://github.com/images/error/octocat_happy.gif",
"gravatar_id": "",
"url": "https://api.github.com/users/octocat",
....
"type": "User",
"site_admin": false,
"name": "monalisa octocat",
"company": "GitHub",
"blog": "https://github.com/blog",
"location": "San Francisco",
"email": "[email protected]",
"hireable": false,
"bio": "There once was...",
"twitter_username": "monatheoctocat",
"public_repos": 2,
"public_gists": 1,
"followers": 20,
"following": 0,
"created_at": "2008-01-14T04:33:35Z",
"updated_at": "2008-01-14T04:33:35Z"
}
*/
Future<void> getUserInfo() async {
final accessToken = githubOAuthAccessToken;
if (accessToken.isEmpty) return;
if (_pendingUserInfoRequest == accessToken) {
// Already processing a request.
return;
}
_pendingUserInfoRequest = accessToken;
try {
// Load the gist using the github gist API:
// https://developer.github.com/v3/gists/#get-a-single-gist.
final response =
await _client.get(Uri.parse('$_githubApiUrl/user'), headers: {
'accept': 'application/vnd.github.v3+json',
'Authorization': 'token $accessToken'
});
_pendingUserInfoRequest = null;
if (response.statusCode == 404) {
throw const GistLoaderException(GistLoaderFailureType.contentNotFound);
} else if (response.statusCode == 403) {
throw const GistLoaderException(
GistLoaderFailureType.rateLimitExceeded);
} else if (response.statusCode != 200) {
throw const GistLoaderException(GistLoaderFailureType.unknown);
} else {
// statusCode 200.
final user = json.decode(response.body) as Map<String, dynamic>;
if (user.containsKey('avatar_url')) {
avatarUrl = user['avatar_url'] as String;
}
if (user.containsKey('login')) {
userLogin = user['login'] as String;
}
_authenticatedStateChangeController.add(true);
}
} catch (e) {
window.console.log('getUserInfo Exception ${e.toString()}');
}
}
/*
Request user's gist info from GitHub API.
GET /gists
Parameters
Name Type In Description
accept string header Setting toapplication/vnd.github.v3+json is recommended.
since string query Only show notifications updated after the given time. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ.
per_page integer query Results per page (max 100) Default: 30
page integer query Page number of the results to fetch. Default: 1
https://docs.github.com/en/rest/reference/gists#list-gists-for-the-authenticated-user
Example Return:
[
{
"url": "https://api.github.com/gists/aa5a315d61ae9438b18d",
....
"id": "aa5a315d61ae9438b18d",
....
"files": {
"hello_world.rb": {
"filename": "hello_world.rb",
"type": "application/x-ruby",
"language": "Ruby",
"raw_url": "https://gist.githubusercontent.com/octocat/6cad326836d38bd3a7ae/raw/db9c55113504e46fa076e7df3a04ce592e2e86d8/hello_world.rb",
"size": 167
}
},
"public": true,
"created_at": "2010-04-14T02:15:15Z",
"updated_at": "2011-06-20T11:34:15Z",
"description": "Hello World Examples",
"comments": 0,
"user": null,
"comments_url": "https://api.github.com/gists/aa5a315d61ae9438b18d/comments/",
"owner": {
....
},
"truncated": false
}
]
*/
Future<void> getUsersGists() async {
final accessToken = githubOAuthAccessToken;
if (accessToken.isEmpty) return;
if (_pendingUserGistRequest == accessToken) {
// Already processing a request.
return;
}
_pendingUserGistRequest = accessToken;
try {
// Load the gist using the github gist API:
// https://developer.github.com/v3/gists/#get-a-single-gist.
final response = await _client.get(
Uri.parse('$_githubApiUrl/gists?per_page=$maxNumberOfGistToLoad'),
headers: {
'accept': 'application/vnd.github.v3+json',
'Authorization': 'token $accessToken'
});
_pendingUserGistRequest = null;
if (response.statusCode == 404) {
throw const GistLoaderException(GistLoaderFailureType.contentNotFound);
} else if (response.statusCode == 403) {
throw const GistLoaderException(
GistLoaderFailureType.rateLimitExceeded);
} else if (response.statusCode != 200) {
throw const GistLoaderException(GistLoaderFailureType.unknown);
} else {
// StatusCode 200.
_myGistList.clear();
final List<dynamic> gistslist =
json.decode(response.body) as List<dynamic>;
if (gistslist.isNotEmpty) {
for (int i = 0; i < gistslist.length; i++) {
// Now decode each one.
final gist = Gist.fromMap(gistslist[i] as Map<String, dynamic>);
if (gist.hasDartContent()) {
_myGistList.add(gist);
}
}
}
_myGistListUpdateController.add(null);
}
} catch (e) {
window.console.log('getUsersGists Exception ${e.toString()}');
}
}
/*
List the authenticated user's starred gists:
GET /gists/starred
(otherwise this api entry point works same as get user's gists)
https://docs.github.com/en/rest/reference/gists#list-starred-gists
*/
Future<void> getUsersStarredGists() async {
final accessToken = githubOAuthAccessToken;
if (accessToken.isEmpty) return;
if (_pendingUserStarredGistRequest == accessToken) {
// Already processing a request.
return;
}
_pendingUserStarredGistRequest = accessToken;
try {
// Load the gist using the github gist API:
// https://developer.github.com/v3/gists/#get-a-single-gist.
final response = await _client.get(
Uri.parse('$_githubApiUrl/gists/starred?per_page=100'),
headers: {
'accept': 'application/vnd.github.v3+json',
'Authorization': 'token $accessToken'
});
_pendingUserStarredGistRequest = null;
if (response.statusCode == 404) {
throw const GistLoaderException(GistLoaderFailureType.contentNotFound);
} else if (response.statusCode == 403) {
throw const GistLoaderException(
GistLoaderFailureType.rateLimitExceeded);
} else if (response.statusCode != 200) {
throw const GistLoaderException(GistLoaderFailureType.unknown);
} else {
// StatusCode 200.
_starredGistList.clear();
final List<dynamic> gistslist =
json.decode(response.body) as List<dynamic>;
if (gistslist.isNotEmpty) {
for (int i = 0; i < gistslist.length; i++) {
// Now decode each one.
final gist = Gist.fromMap(gistslist[i] as Map<String, dynamic>);
if (gist.hasDartContent()) {
_starredGistList.add(gist);
}
}
}
_starredGistListUpdateController.add(null);
}
} catch (e) {
window.console.log('getUsersStarredGists Exception ${e.toString()}');
}
}
set githubOAuthAccessToken(String newtoken) {
if (window.localStorage[localStorageKeyForGitHubOAuthToken] != newtoken) {
if (newtoken.isNotEmpty) {
window.localStorage[localStorageKeyForGitHubOAuthToken] = newtoken;
// Get the user info for this token.
getUserInfo();
} else {
window.localStorage.remove(localStorageKeyForGitHubOAuthToken);
avatarUrl = '';
userLogin = '';
}
}
}
String get githubOAuthAccessToken =>
window.localStorage[localStorageKeyForGitHubOAuthToken] ?? '';
set avatarUrl(String url) {
if (url.isNotEmpty) {
window.localStorage[localStorageKeyForGitHubAvatarUrl] = url;
} else {
window.localStorage.remove(localStorageKeyForGitHubAvatarUrl);
}