Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
2154 lines (2005 loc) · 82.2 KB
/
Copy pathindex.html
File metadata and controls
2154 lines (2005 loc) · 82.2 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
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Deploy Google Apps Scripts</title>
<style>
/* ── Reset & base ────────────────────────────────────────────────────── */
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Google Sans', Roboto, Arial, sans-serif;
background: #f8f9fa;
color: #202124;
min-height: 100vh;
}
/* ── Layout ──────────────────────────────────────────────────────────── */
.container {
max-width: 760px;
margin: 0 auto;
padding: 40px 24px 80px;
}
header {
text-align: center;
margin-bottom: 40px;
}
header h1 {
font-size: 28px;
font-weight: 400;
color: #1a73e8;
margin-bottom: 8px;
}
header p {
font-size: 15px;
color: #5f6368;
}
/* ── Cards ───────────────────────────────────────────────────────────── */
.card {
background: #fff;
border-radius: 8px;
box-shadow:
0 1px 3px rgba(60, 64, 67, 0.15),
0 1px 2px rgba(60, 64, 67, 0.3);
padding: 24px;
margin-bottom: 20px;
}
.card h2 {
font-size: 16px;
font-weight: 500;
margin-bottom: 16px;
display: flex;
align-items: center;
gap: 8px;
}
.card h2 .step-badge {
background: #1a73e8;
color: #fff;
border-radius: 50%;
width: 24px;
height: 24px;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 13px;
flex-shrink: 0;
}
/* ── Inputs ──────────────────────────────────────────────────────────── */
label {
display: block;
font-size: 13px;
color: #5f6368;
margin-bottom: 4px;
}
input[type='text'] {
width: 100%;
padding: 10px 12px;
border: 1px solid #dadce0;
border-radius: 4px;
font-size: 14px;
color: #202124;
transition: border-color 0.15s;
}
input[type='text']:focus {
outline: none;
border-color: #1a73e8;
box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}
/* ── Script list ─────────────────────────────────────────────────────── */
.script-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.script-option {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 14px;
border: 1px solid #dadce0;
border-radius: 6px;
cursor: pointer;
transition:
border-color 0.15s,
background 0.15s;
}
.script-option:hover {
background: #f1f3f4;
}
.script-option:has(input[type='checkbox']:checked) {
border-color: #1a73e8;
background: #e8f0fe;
}
.script-option input[type='checkbox'] {
margin-top: 3px;
flex-shrink: 0;
accent-color: #1a73e8;
width: 16px;
height: 16px;
}
.script-option .script-info strong {
display: block;
font-size: 14px;
}
.script-option .script-info span {
font-size: 13px;
color: #5f6368;
}
/* ── Buttons ─────────────────────────────────────────────────────────── */
.btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 20px;
border: none;
border-radius: 4px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition:
background 0.15s,
box-shadow 0.15s;
}
.btn-primary {
background: #1a73e8;
color: #fff;
}
.btn-primary:hover {
background: #1765cc;
}
.btn-primary:disabled {
background: #a8c7fa;
cursor: not-allowed;
}
.btn-outline {
background: #fff;
color: #1a73e8;
border: 1px solid #dadce0;
}
.btn-outline:hover {
background: #f1f3f4;
}
/* ── Status / result ─────────────────────────────────────────────────── */
#status-area {
display: none;
}
.status-msg {
padding: 14px 16px;
border-radius: 6px;
font-size: 14px;
display: flex;
align-items: center;
gap: 10px;
}
.status-info {
background: #e8f0fe;
color: #1765cc;
}
.status-ok {
background: #e6f4ea;
color: #137333;
}
.status-error {
background: #fce8e6;
color: #c5221f;
}
.result-link {
display: inline-flex;
align-items: center;
gap: 6px;
color: #1a73e8;
text-decoration: none;
font-weight: 500;
}
.result-link:hover {
text-decoration: underline;
}
/* ── Setup instructions ───────────────────────────────────────────────── */
details summary {
cursor: pointer;
font-size: 14px;
color: #1a73e8;
user-select: none;
margin-top: 12px;
}
details[open] summary {
margin-bottom: 12px;
}
.setup-steps {
padding-left: 20px;
}
.setup-steps li {
font-size: 13px;
margin-bottom: 8px;
line-height: 1.5;
}
.setup-steps a {
color: #1a73e8;
}
code {
background: #f1f3f4;
padding: 2px 6px;
border-radius: 3px;
font-size: 12px;
}
/* ── Form controls for Step 3 ──────────────────────────────────────── */
select,
textarea {
width: 100%;
padding: 10px 12px;
border: 1px solid #dadce0;
border-radius: 4px;
font-size: 14px;
color: #202124;
font-family: inherit;
transition: border-color 0.15s;
background: #fff;
}
select:focus,
textarea:focus {
outline: none;
border-color: #1a73e8;
box-shadow: 0 0 0 2px rgba(26, 115, 232, 0.2);
}
textarea {
resize: vertical;
min-height: 60px;
}
.field-group {
margin-bottom: 16px;
}
.field-help {
font-size: 12px;
color: #5f6368;
margin-top: 4px;
line-height: 1.4;
}
.field-help a {
color: #1a73e8;
}
.field-row {
display: flex;
gap: 16px;
}
.field-row .field-group {
flex: 1;
}
/* ── Error detail (copyable) ─────────────────────────────────────────── */
.error-detail {
margin-top: 6px;
font-size: 11px;
color: #555;
background: #fff8f8;
border: 1px solid #f5c6cb;
border-radius: 4px;
padding: 6px 8px;
font-family: monospace;
white-space: pre-wrap;
word-break: break-all;
max-height: 120px;
overflow-y: auto;
user-select: text;
}
.copy-btn {
margin-top: 4px;
font-size: 11px;
padding: 2px 8px;
border: 1px solid #ccc;
border-radius: 4px;
background: #f8f8f8;
cursor: pointer;
color: #444;
}
.copy-btn:hover {
background: #eee;
}
/* ── Spinner ─────────────────────────────────────────────────────────── */
.spinner {
width: 18px;
height: 18px;
border: 2px solid rgba(255, 255, 255, 0.4);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.7s linear infinite;
flex-shrink: 0;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>🚀 Deploy Google Apps Scripts</h1>
<p>
Deploy a script from this repository directly to your Google account
using your browser.
</p>
</header>
<!-- Step 1 – Sign in -->
<div class="card">
<h2><span class="step-badge">1</span>Sign in with Google</h2>
<p style="font-size: 13px; color: #5f6368; margin-bottom: 14px">
Sign in to the Google account where you want the script project
created. You will be asked to grant permission to create and edit Apps
Script projects.
</p>
<button
class="btn btn-outline"
id="btn-signin"
onclick="handleSignIn()"
>
<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
<path
fill="#4285F4"
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
/>
<path
fill="#34A853"
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
/>
<path
fill="#FBBC05"
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.84z"
/>
<path
fill="#EA4335"
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
/>
</svg>
Sign in with Google
</button>
<span
id="auth-status"
style="font-size: 13px; margin-left: 12px; color: #5f6368"
></span>
</div>
<!-- Step 2 – Choose script & deploy (hidden until sign-in) -->
<div class="card" id="step2-card" style="display: none">
<h2><span class="step-badge">2</span>Choose scripts to deploy</h2>
<div class="script-list" id="script-list">
<!-- populated by JS -->
</div>
<div style="text-align: right; margin-top: 16px">
<button
class="btn btn-primary"
id="btn-deploy"
onclick="handleDeploy()"
disabled
>
Deploy to my account
</button>
</div>
</div>
<!-- Status / result area -->
<div id="status-area">
<div id="status-msg" class="status-msg"></div>
</div>
<div class="card" id="step3-card" style="display: none">
<h2><span class="step-badge">3</span>Configure your scripts</h2>
<div id="step3-scripts"></div>
</div>
</div>
<!-- Google Identity Services -->
<script src="https://accounts.google.com/gsi/client" async defer></script>
<script src="https://apis.google.com/js/api.js" async defer></script>
<script>
/**
* Deployment page for the Google Apps Script Productivity Suite.
*
* Uses the Google Identity Services (GIS) token-based OAuth flow to obtain
* an access token, then calls the Apps Script REST API to create a new project
* and upload the selected script's source files.
*/
// ── Constants ────────────────────────────────────────────────────────────────
const APPS_SCRIPT_API = 'https://script.googleapis.com/v1'
// OAuth 2.0 Client ID for the Petry-Projects Google Cloud project.
const OAUTH_CLIENT_ID =
'873060687431-smmudbpd5rlogt0r7immp0u3tdqb2t3p.apps.googleusercontent.com'
// Required OAuth scopes:
// script.projects — create, read, and update Apps Script projects
// drive.readonly — detect existing projects + browse via Picker API
// gmail.labels — list Gmail labels for config dropdowns
// calendar.readonly — list calendars for config dropdowns
// email — get user's email for default recipient
const OAUTH_SCOPE =
'https://www.googleapis.com/auth/script.projects ' +
'https://www.googleapis.com/auth/drive.readonly ' +
'https://www.googleapis.com/auth/gmail.labels ' +
'https://www.googleapis.com/auth/calendar.readonly ' +
'email'
// Script catalog — mirrors src/deploy/index.js getScriptCatalog().
// version must match the // @version tag in each script's code.gs.
const SCRIPT_CATALOG = [
{
id: 'gmail-to-drive-by-labels',
name: 'Gmail to Drive By Labels',
version: '1.0.0',
description:
'Archives emails from specific Gmail labels into a Google Doc ' +
'(text) and a Google Drive Folder (attachments).',
triggerFn: 'storeEmailsAndAttachments',
},
{
id: 'calendar-to-sheets',
name: 'Calendar to Sheets',
version: '1.0.0',
description:
'Syncs Google Calendar events into a Google Sheet, keeping rows ' +
'up to date on changes and deletions.',
triggerFn: 'syncAllCalendarsToSheetsGAS',
},
{
id: 'calendar-to-briefing-doc',
name: 'Calendar to Briefing Doc',
version: '2.0.0',
description:
'Generates a weekly calendar briefing and emails it to configured ' +
'recipients, grouped by day with times, locations, attendees, and ' +
'conflict warnings. Shows which calendar each event comes from.',
triggerFn: 'generateWeeklyBriefing',
},
]
// Base URL for fetching raw script files from this repository on GitHub.
const GITHUB_RAW_BASE =
'https://raw.githubusercontent.com/combsmith/google-app-scripts/main/src'
// Default Apps Script manifest required by the API for every project.
// oauthScopes is intentionally omitted — Google infers required scopes
// from the uploaded code so the project's runtime permissions are never
// accidentally restricted. executionApi.access is set to 'MYSELF' so
// the project is registered as API-executable on creation.
const APPSSCRIPT_MANIFEST = JSON.stringify({
timeZone: 'America/New_York',
dependencies: {},
exceptionLogging: 'STACKDRIVER',
runtimeVersion: 'V8',
executionApi: { access: 'MYSELF' },
})
// localStorage key used to persist deployed scriptIds for idempotency.
const DEPLOY_STORAGE_KEY = 'gas_copilot_deployed'
// localStorage key used to record which projects have had setup() run.
const SETUP_STORAGE_KEY = 'gas_copilot_setup_done'
// ── Google Picker ─────────────────────────────────────────────────────────────
// Google Picker view IDs — lowercase strings match the Picker API constants.
const PICKER_VIEW_ID = {
DOCUMENTS: 'documents',
FOLDERS: 'folders',
SPREADSHEETS: 'spreadsheets',
}
/**
* Opens the Google Drive Picker for the given viewId.
* Calls callback({ id, name }) when the user picks a resource.
* Always opens in list view with folder navigation enabled.
*/
function openPicker(viewId, callback) {
if (typeof gapi === 'undefined') {
alert(
'Google APIs not available. Please refresh the page and try again.'
)
return
}
gapi.load('picker', () => {
if (!google?.picker) {
alert(
'Google Picker failed to load. Please check your connection and refresh.'
)
return
}
const view = new google.picker.DocsView(viewId)
view.setIncludeFolders(true)
view.setParent('root')
view.setMode(google.picker.DocsViewMode.LIST)
if (viewId === PICKER_VIEW_ID.FOLDERS) {
view.setSelectFolderEnabled(true)
}
// Add a Shared Drives view so the left-side navigation panel
// appears (it only renders when there are multiple views).
const sharedView = new google.picker.DocsView(viewId)
sharedView.setIncludeFolders(true)
sharedView.setEnableDrives(true)
sharedView.setMode(google.picker.DocsViewMode.LIST)
if (viewId === PICKER_VIEW_ID.FOLDERS) {
sharedView.setSelectFolderEnabled(true)
}
const picker = new google.picker.PickerBuilder()
.addView(view)
.addView(sharedView)
.enableFeature(google.picker.Feature.SUPPORT_DRIVES)
.setOAuthToken(accessToken)
.setCallback((data) => {
if (
data[google.picker.Response.ACTION] ===
google.picker.Action.PICKED
) {
const docs = data[google.picker.Response.DOCUMENTS]
if (!docs || docs.length === 0) return
const doc = docs[0]
callback({
id: doc[google.picker.Document.ID],
name: doc[google.picker.Document.NAME],
})
}
})
.build()
picker.setVisible(true)
})
}
function browseForFile(viewId, inputId) {
openPicker(viewId, (result) => {
const el = document.getElementById(inputId)
if (el) el.value = result.id
})
}
window.browseForFile = browseForFile
// ── State ─────────────────────────────────────────────────────────────────────
let tokenClient = null
let accessToken = null
let userCalendars = [] // populated after sign-in
let userEmail = '' // populated after sign-in
let userGmailLabels = [] // populated after sign-in
// catalogId → { scriptId, title } for verified existing deployments
const deployedScripts = new Map()
// ── Idempotency helpers ───────────────────────────────────────────────────────
/**
* Returns the Apps Script project ID previously deployed for
* (catalogId, title), or null if none recorded.
*/
function getStoredScriptId(catalogId, title) {
try {
const map = JSON.parse(
localStorage.getItem(DEPLOY_STORAGE_KEY) || '{}'
)
const id = map[catalogId + '\n' + title]
return id ? validateScriptId(id) : null
} catch {
return null
}
}
/**
* Persists the mapping (catalogId, title) → scriptId so subsequent
* deploys can reuse the same Apps Script project.
*/
function storeScriptId(catalogId, title, scriptId) {
try {
const map = JSON.parse(
localStorage.getItem(DEPLOY_STORAGE_KEY) || '{}'
)
map[catalogId + '\n' + title] = scriptId
localStorage.setItem(DEPLOY_STORAGE_KEY, JSON.stringify(map))
} catch {
// best-effort; ignore storage errors
}
}
/**
* Returns true if the user has previously confirmed that setup() was
* run for the given Apps Script project ID.
*/
function isSetupDone(scriptId) {
try {
const map = JSON.parse(
localStorage.getItem(SETUP_STORAGE_KEY) || '{}'
)
return !!map[scriptId]
} catch {
return false
}
}
/**
* Records that setup() has been run for scriptId and updates the
* on-screen CTA to reflect the trigger is now active.
* Exposed as window.confirmSetupDone for use by inline onclick handlers.
*/
function confirmSetupDone(scriptId) {
try {
validateScriptId(scriptId)
} catch {
return // reject tampered IDs
}
try {
const map = JSON.parse(
localStorage.getItem(SETUP_STORAGE_KEY) || '{}'
)
map[scriptId] = true
localStorage.setItem(SETUP_STORAGE_KEY, JSON.stringify(map))
} catch {
// best-effort; ignore storage errors
}
const section = document.getElementById('setup-section-' + scriptId)
if (section) {
section.innerHTML = `<div style="font-size:12px;color:#137333;">⏱ Trigger previously activated.</div>`
}
}
window.confirmSetupDone = confirmSetupDone
/**
* Generates the source for setup.gs — an idempotent function that
* deletes any existing hourly trigger for `triggerFn` and creates a
* fresh one. This file is uploaded alongside code.gs and config.gs.
* The user must run setup() once manually from the Apps Script editor
* to activate the hourly trigger.
*/
function buildSetupSource(triggerFn) {
if (!/^[a-zA-Z_]\w*$/.test(triggerFn)) {
throw new Error(
'Invalid trigger function name: ' + JSON.stringify(triggerFn)
)
}
return (
"var HOURLY_TRIGGER_FN = '" +
triggerFn +
"';\n\n" +
'function setup() {\n' +
' var triggers = ScriptApp.getProjectTriggers();\n' +
' for (var i = 0; i < triggers.length; i++) {\n' +
' if (triggers[i].getHandlerFunction() === HOURLY_TRIGGER_FN) {\n' +
' ScriptApp.deleteTrigger(triggers[i]);\n' +
' }\n' +
' }\n' +
' ScriptApp.newTrigger(HOURLY_TRIGGER_FN)\n' +
' .timeBased()\n' +
' .everyHours(1)\n' +
' .create();\n' +
'}\n'
)
}
// ── DOM helpers ───────────────────────────────────────────────────────────────
function showStatus(type, html) {
const area = document.getElementById('status-area')
const msg = document.getElementById('status-msg')
area.style.display = 'block'
msg.className = `status-msg status-${type}`
msg.innerHTML = html
area.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
}
function setDeployEnabled() {
const hasToken = !!accessToken
const checked = Array.from(
document.querySelectorAll('input[name="script"]:checked')
)
const hasScript = checked.length > 0
const btn = document.getElementById('btn-deploy')
btn.disabled = !(hasToken && hasScript)
// Update button label based on deployment state
if (hasScript) {
const allDeployed = checked.every((el) =>
deployedScripts.has(el.value)
)
const anyNeedsUpdate = checked.some((el) => {
const v = scriptVersions.get(el.value)
return v && v.needsUpdate
})
if (anyNeedsUpdate) {
btn.textContent = 'Update & Deploy to my account'
} else if (allDeployed) {
btn.textContent = 'Re-deploy to my account'
} else {
btn.textContent = 'Deploy to my account'
}
} else {
btn.textContent = 'Deploy to my account'
}
}
// ── User info ─────────────────────────────────────────────────────────────────
async function fetchUserEmail() {
if (!accessToken) return
try {
const res = await fetch(
'https://www.googleapis.com/oauth2/v2/userinfo',
{ headers: { Authorization: `Bearer ${accessToken}` } }
)
if (!res.ok) return
const data = await res.json()
userEmail = data.email || ''
} catch {
// best-effort
}
}
// ── Calendar API ─────────────────────────────────────────────────────────────
async function fetchUserCalendars() {
if (!accessToken) return
try {
const res = await fetch(
'https://www.googleapis.com/calendar/v3/users/me/calendarList',
{ headers: { Authorization: `Bearer ${accessToken}` } }
)
if (!res.ok) return
const data = await res.json()
userCalendars = (data.items || []).map((c) => ({
id: c.id,
name: c.summaryOverride || c.summary || c.id,
primary: !!c.primary,
}))
} catch {
// best-effort; calendar list just won't be available
}
}
async function fetchGmailLabels() {
if (!accessToken) return
try {
const res = await fetch(
'https://gmail.googleapis.com/gmail/v1/users/me/labels',
{ headers: { Authorization: `Bearer ${accessToken}` } }
)
if (!res.ok) return
const data = await res.json()
userGmailLabels = (data.labels || [])
.filter((l) => l.type === 'user')
.map((l) => l.name)
.sort()
} catch {
// best-effort
}
}
// ── New Label modal ──────────────────────────────────────────────────────
/**
* Creates a single Gmail label via the Gmail API.
*
* @param {string} labelName - Label to create (supports nested paths like "Projects/receipts").
* @returns {Promise<{id: string, name: string}>} The created label object.
* @throws {Error} On expired session, missing input, or API failure.
*/
async function createGmailLabel(labelName) {
if (!accessToken) {
throw new Error(
'Please sign in again — your session may have expired.'
)
}
if (!labelName) {
throw new Error('Label name is required.')
}
const res = await fetch(
'https://gmail.googleapis.com/gmail/v1/users/me/labels',
{
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: labelName }),
}
)
if (!res.ok) {
const text = await res.text()
const isDuplicate =
res.status === 409 || text.toLowerCase().includes('already')
let msg = `Failed to create label (${res.status})`
if (isDuplicate) {
msg = `Label "${labelName}" already exists`
}
const err = new Error(msg)
err.status = res.status
err.isDuplicate = isDuplicate
throw err
}
return res.json()
}
/**
* Rebuilds a label <select> or fills a text <input> with the current
* userGmailLabels list, optionally pre-selecting a value.
*/
function refreshLabelDropdown(selectId, selectedValue) {
const el = document.getElementById(selectId)
if (!el) return
if (el.tagName === 'INPUT') {
el.value = selectedValue || ''
return
}
if (el.tagName !== 'SELECT') return
const opts = userGmailLabels
.map(
(l) =>
'<option value="' +
escapeHtml(l) +
'"' +
(l === selectedValue ? ' selected' : '') +
'>' +
escapeHtml(l) +
'</option>'
)
.join('')
el.innerHTML = '<option value="">— Select label —</option>' + opts
}
/**
* Opens the "New Label" modal for a Gmail to Drive config card.
* The modal creates both a trigger label and a "-archived" processed
* label in one action, then refreshes both dropdowns.
*/
function openNewLabelModal(triggerSelectId, processedSelectId) {
// Remove any existing modal
const existing = document.getElementById('new-label-modal-overlay')
if (existing) existing.remove()
const overlay = document.createElement('div')
overlay.id = 'new-label-modal-overlay'
overlay.style.cssText =
'position:fixed;inset:0;background:rgba(0,0,0,0.5);display:flex;' +
'align-items:center;justify-content:center;z-index:9999;'
overlay.innerHTML =
'<div id="new-label-modal" style="background:#fff;border-radius:12px;' +
'box-shadow:0 8px 32px rgba(0,0,0,0.25);padding:28px 32px;width:440px;max-width:92vw;">' +
'<h3 style="font-size:18px;font-weight:500;margin-bottom:4px;color:#202124;">Create New Gmail Labels</h3>' +
'<p style="font-size:13px;color:#5f6368;margin-bottom:20px;">' +
'Enter a label name. Both the trigger label and its <strong>-archived</strong> counterpart will be created in your Gmail account.</p>' +
'<div style="margin-bottom:16px;">' +
'<label style="display:block;font-size:13px;color:#5f6368;margin-bottom:4px;">Label name</label>' +
'<input type="text" id="new-label-modal-input" placeholder="e.g. Projects/receipts" ' +
'style="width:100%;padding:10px 12px;border:1px solid #dadce0;border-radius:4px;font-size:14px;color:#202124;box-sizing:border-box;" />' +
'</div>' +
'<div id="new-label-modal-preview" style="background:#f8f9fa;border-radius:6px;padding:12px 14px;margin-bottom:16px;display:none;">' +
'<div style="font-size:12px;color:#5f6368;margin-bottom:6px;font-weight:500;">Labels to create:</div>' +
'<div id="new-label-preview-trigger" style="font-size:13px;color:#202124;padding:2px 0;"></div>' +
'<div id="new-label-preview-processed" style="font-size:13px;color:#202124;padding:2px 0;"></div>' +
'</div>' +
'<div id="new-label-modal-error" style="color:#c5221f;font-size:13px;margin-bottom:12px;display:none;"></div>' +
'<div id="new-label-modal-success" style="color:#137333;font-size:13px;margin-bottom:12px;display:none;"></div>' +
'<div style="display:flex;justify-content:flex-end;gap:10px;">' +
'<button type="button" id="new-label-modal-cancel" class="btn btn-outline" style="padding:8px 18px;font-size:14px;">Cancel</button>' +
'<button type="button" id="new-label-modal-create" class="btn btn-primary" style="padding:8px 18px;font-size:14px;" disabled>Create Labels</button>' +
'</div>' +
'</div>'
document.body.appendChild(overlay)
const input = document.getElementById('new-label-modal-input')
const preview = document.getElementById('new-label-modal-preview')
const previewTrigger = document.getElementById(
'new-label-preview-trigger'
)
const previewProcessed = document.getElementById(
'new-label-preview-processed'
)
const errorEl = document.getElementById('new-label-modal-error')
const successEl = document.getElementById('new-label-modal-success')
const createBtn = document.getElementById('new-label-modal-create')
const cancelBtn = document.getElementById('new-label-modal-cancel')
// Live preview as user types
input.addEventListener('input', function () {
const name = input.value.trim()
if (name) {
previewTrigger.textContent = '\u2705 ' + name
previewProcessed.textContent = '\u2705 ' + name + '-archived'
preview.style.display = ''
createBtn.disabled = false
} else {
preview.style.display = 'none'
createBtn.disabled = true
}
errorEl.style.display = 'none'
successEl.style.display = 'none'
})
let isCreating = false
function closeModal(force) {
if (isCreating && !force) return
overlay.remove()
document.removeEventListener('keydown', onEsc)
}
// Close on overlay click (but not modal body)
overlay.addEventListener('click', function (e) {
if (e.target === overlay) closeModal()
})
// Close on Escape
function onEsc(e) {
if (e.key === 'Escape') closeModal()
}
document.addEventListener('keydown', onEsc)
cancelBtn.addEventListener('click', function () {
closeModal()
})
// Create both labels
createBtn.addEventListener('click', async function () {
const name = input.value.trim()
if (!name) return
const archivedName = name + '-archived'
isCreating = true
input.disabled = true
createBtn.disabled = true
cancelBtn.disabled = true
createBtn.textContent = 'Creating...'
errorEl.style.display = 'none'
successEl.style.display = 'none'
try {
// Create trigger label (treat 409/duplicate as success)
try {
await createGmailLabel(name)
} catch (err) {
if (!err.isDuplicate) throw err
}
if (!userGmailLabels.includes(name)) userGmailLabels.push(name)
previewTrigger.innerHTML =
'<span style="color:#137333;">\u2705 ' +
escapeHtml(name) +
' — created</span>'
// Create archived label (treat 409/duplicate as success)
try {
await createGmailLabel(archivedName)
} catch (err) {
if (!err.isDuplicate) throw err
}
if (!userGmailLabels.includes(archivedName))
userGmailLabels.push(archivedName)
previewProcessed.innerHTML =
'<span style="color:#137333;">\u2705 ' +
escapeHtml(archivedName) +
' — created</span>'
// Refresh the label list and auto-select both dropdowns
await fetchGmailLabels()
refreshLabelDropdown(triggerSelectId, name)
refreshLabelDropdown(processedSelectId, archivedName)