-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGDrive.ts
More file actions
2309 lines (2058 loc) · 76.1 KB
/
GDrive.ts
File metadata and controls
2309 lines (2058 loc) · 76.1 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
declare var window;
/// <reference types="gapi" />
/// <reference types="gapi.auth2" />
/// <reference types="gapi.client" />
/// <reference types="gapi.client.drive-v3" />
/// <reference types="gapi.client.calendar-v3" />
/// <reference types="gapi.client.sheets-v4" />
const nativeExportOptions: Record<string, { label: string; mime: string; ext: string }[]> = {
'application/vnd.google-apps.spreadsheet': [
{ label: 'CSV', mime: 'text/csv', ext: '.csv' },
{ label: 'XLSX', mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ext: '.xlsx' },
{ label: 'PDF', mime: 'application/pdf', ext: '.pdf' },
{ label: 'ODS', mime: 'application/vnd.oasis.opendocument.spreadsheet', ext: '.ods' },
],
'application/vnd.google-apps.document': [
{ label: 'DOCX', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', ext: '.docx' },
{ label: 'PDF', mime: 'application/pdf', ext: '.pdf' },
{ label: 'ODT', mime: 'application/vnd.oasis.opendocument.text', ext: '.odt' },
{ label: 'RTF', mime: 'application/rtf', ext: '.rtf' },
{ label: 'TXT', mime: 'text/plain', ext: '.txt' },
],
'application/vnd.google-apps.presentation': [
{ label: 'PPTX', mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', ext: '.pptx' },
{ label: 'PDF', mime: 'application/pdf', ext: '.pdf' },
{ label: 'ODP', mime: 'application/vnd.oasis.opendocument.presentation', ext: '.odp' },
{ label: 'JPG', mime: 'image/jpeg', ext: '.jpg' },
{ label: 'PNG', mime: 'image/png', ext: '.png' },
{ label: 'SVG', mime: 'image/svg+xml', ext: '.svg' },
],
};
//browser google drive utility
//some types
export type Calendar = {
kind: string,
etag: string,
id: string,
summary: string,
description?: string,
location?: string,
timeZone?: string,
conferenceProperties?: {
allowedConferenceSolutionTypes: [
string
]
}
}
export type Role = 'reader' | 'writer' | 'owner';
export type User = {
displayName: string,
kind: string,
me: boolean,
permissionId: string,
emailAddress: string,
photoLink: string
}
export type Permission = {
id: string,
displayName: string,
type: string,
kind: string,
permissionDetails: [
{
permissionType: string,
inheritedFrom: string,
role: string,
inherited: boolean
}
],
photoLink: string,
emailAddress: string,
role: string,
allowFileDiscovery: boolean,
domain: string,
expirationTime: string,
teamDrivePermissionDetails: [
{
teamDrivePermissionType: string,
inheritedFrom: string,
role: string,
inherited: boolean
}
],
deleted: boolean,
view: string,
pendingOwner: boolean
};
export type FileMetadata = {
id: string;
name: string;
mimeType: string;
parents?: string[];
webViewLink?: string;
iconLink?: string;
thumbnailLink?: string;
size?: string;
createdTime?: string;
modifiedTime?: string;
shared?: boolean;
owners?: Array<User>;
permissions?: Array<Permission>;
}
export type UploadFile = {
name: string;
mimeType: string;
data: File;
};
export type SharingOptions = {
emailMessage?: string;
moveToNewOwnersRoot?: boolean;
sendNotificationEmail?: boolean;
supportsAllDrives?: boolean;
transferOwnership?: boolean;
useDomainAdminAccess?: boolean;
};
export type Attendee = {
email: string;
displayName?: string;
organizer?: boolean;
self?: boolean;
resource?: boolean;
optional?: boolean;
responseStatus?: 'needsAction' | 'declined' | 'tentative' | 'accepted';
};
export type Event = {
summary: string;
location?: string;
description?: string;
colorId?: string;
start: {
dateTime: string;
timeZone: string;
};
end: {
dateTime: string;
timeZone: string;
};
recurrence?: string[];
attendees?: Attendee[];
reminders?: {
useDefault: boolean,
overrides: { method: 'email' | 'popup', minutes: number }[],
};
status?: 'confirmed' | 'tentative' | 'cancelled';
visibility?: 'default' | 'public' | 'private' | 'confidential';
supportsAttachments?: boolean;
guestsCanSeeOtherGuests?: boolean;
guestsCanModify?: boolean;
guestsCanInviteOthers?: boolean;
sendUpdates?: 'all' | 'externalOnly' | 'none';
source?: {
title: string;
url: string;
};
id: string;
[key: string]: any; // To support additional properties
};
// Type Definitions
type SheetName = string;
type Cell = `${string}${number}`; // Simple alias for cell notation, e.g., 'A1', 'B2'
export type Range = `${SheetName}!${Cell}:${Cell}` | `${Cell}:${Cell}` | `${Cell}`;
declare global {
namespace google {
namespace accounts {
namespace oauth2 {
interface TokenClient {
callback: (resp: TokenResponse) => void;
requestAccessToken(opts?: { prompt?: 'consent' | 'none' }): void;
}
interface TokenResponse { access_token?: string; error?: string }
interface TokenClientConfig {
client_id: string;
scope: string;
callback: (resp: TokenResponse) => void;
use_fedcm_for_prompt?: boolean;
use_fedcm_for_button?: boolean;
}
function initTokenClient(cfg: TokenClientConfig): TokenClient;
/**
* Revoke an OAuth2 access token.
* @param token the access token string
* @param callback optional callback when done
*/
function revoke(
token: string,
callback?: () => void
): void;
}
}
}
}
export class GDrive {
//------------------------
//-GOOGLE DRIVE FUNCTIONS-
//------------------------
google: typeof google = (window as any).google;
gapi: typeof gapi = (window as any).gapi;
private tokenClient: google.accounts.oauth2.TokenClient = (window as any).tokenClient;
private accessToken: string;
gapiInited = this.gapi !== undefined;
gsiInited = this.google !== undefined;
isLoggedIn = false;
container: any;
userId: string;
fedcmEnabled = true;
directory = "AppData"; //our directory of choice
directoryId: string; //the unique google id
//fs = fs;
// Toggle: if true we’ll stash to localStorage under storageKey
persistToken = true;
storageKey = '_gdr_tok_25v1'; // obscure but consistent
tokenExpiresAt?: number;
constructor(googleClientId?: string, opts?: {
directory?: string, discoverydocs?: string[], scope?: string, persistToken?: boolean, storageKey?: string
}) {
if (opts?.directory) this.directory = opts.directory;
if (opts?.persistToken) this.persistToken = opts.persistToken;
if (opts?.storageKey) this.storageKey = opts.storageKey;
if (googleClientId)
this.initGapi(googleClientId, opts?.discoverydocs, opts?.scope);
}
/**
* Initialize GAPI + GIS token client.
* @param googleClientID Your OAuth2 client ID
* @param DISCOVERY_DOCS List of discoveryDoc URLs for any APIs you want to load up front
* @param SCOPE Space-delimited list of OAuth2 scopes
*/
initGapi = async (
googleClientID: string,
DISCOVERY_DOCS: string[] = [
// OAuth2 profile & email lookup
'https://www.googleapis.com/discovery/v1/apis/oauth2/v2/rest',
// Drive v3 for file operations
'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest',
// Calendar v3 if you're doing calendar CRUD
'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest',
// Sheets v4 for spreadsheet reads/writes
'https://www.googleapis.com/discovery/v1/apis/sheets/v4/rest'
],
SCOPE: string = [
// Drive file access
'https://www.googleapis.com/auth/drive',
// Calendar read/write
'https://www.googleapis.com/auth/calendar',
// Sheets read/write
'https://www.googleapis.com/auth/spreadsheets',
// Basic profile & email
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email'
].join(' ')
): Promise<boolean> => {
return new Promise(async (resolve, reject) => {
// 1) Sanity check: client ID is required
if (!googleClientID) {
return reject(new Error('googleClientID is required for initGapi'));
}
// 2) Load the core gapi.js
const CLIENT_SCRIPT_ID = 'gapi-client-script';
if (!document.getElementById(CLIENT_SCRIPT_ID)) {
this.loadScript(
CLIENT_SCRIPT_ID,
'https://apis.google.com/js/api.js',
() => {
if (!window.gapi) {
return reject(new Error('gapi not available after script load'));
}
this.gapi = window.gapi;
// 3) Load the GAPI client
this.gapi.load('client', async () => {
try {
// Initialize with any discovery docs
await this.gapi.client.init({ discoveryDocs: DISCOVERY_DOCS });
} catch (err) {
return reject(err);
}
// 4) Now load the GIS (Google Identity Services) library
this._loadGis(googleClientID, SCOPE)
.then(() => resolve(true))
.catch(reject);
});
}
);
} else {
// If script already exists, skip right to loading client + GIS
try {
await this.gapi.client.init({ discoveryDocs: DISCOVERY_DOCS });
await this._loadGis(googleClientID, SCOPE);
resolve(true);
} catch (err) {
reject(err);
}
}
});
};
/**
* @private
* Load Google Identity Services and set up tokenClient
*/
private _loadGis = async (clientId: string, scope: string) => {
return new Promise<void>((resolve, reject) => {
const GSI_SCRIPT_ID = 'gsi-client-script';
this.loadScript(
GSI_SCRIPT_ID,
'https://accounts.google.com/gsi/client',
() => {
if (!window.google || !window.google.accounts) {
return reject(new Error('GIS client not available after load'));
}
this.google = window.google;
this.tokenClient = this.google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope,
callback: (resp) => { }, // placeholder, set in sign-in
use_fedcm_for_prompt: this.fedcmEnabled,
use_fedcm_for_button: this.fedcmEnabled,
});
resolve();
}
);
});
};
static parseFileId(url:string) {
// Extract fileId from common URL patterns
const patterns = [
/\/d\/([A-Za-z0-9_-]+)/, // /d/<id>/
/\/file\/d\/([A-Za-z0-9_-]+)/, // /file/d/<id>/
/open\?id=([A-Za-z0-9_-]+)/, // open?id=<id>
/id=([A-Za-z0-9_-]+)/ // uc?export=download&id=<id>
];
let fileId: string | null = null;
for (const re of patterns) {
const m = url.match(re);
if (m) { fileId = m[1]; break; }
}
return fileId;
}
/**
* Fetches a publicly-shared Google Sheets CSV (or any public Drive file) via fetch,
* returning both its body (text or Blob) and simple metadata (from headers).
* Supports multiple Drive/Docs/Sheets URL formats. No OAuth required.
* Static method does not require gapi or user sign-in
*
* @param urlOrId Full URL to the file (Drive, Docs, Sheets) or raw fileId
* @param opts.exportMime If provided (e.g. 'text/csv'), exports a Sheet tab as CSV
* @param opts.gid (Sheets only) the GID of the tab to export (default: 0)
*/
static async fetchPublicFile(
urlOrId: string,
opts: { exportMime?: string; gid?: number } = {}
): Promise<{
data: string | Blob;
metadata: { contentType: string; fileName?: string; size?: number };
}> {
// 1) Extract fileId from common URL patterns
let fileId: string | null = GDrive.parseFileId(urlOrId);
if (!fileId) {
// assume the string is already a raw fileId
fileId = urlOrId;
}
// 2) Build fetch URL
let fetchUrl: string;
if (opts.exportMime === 'text/csv') {
const gid = opts.gid ?? 0;
fetchUrl = `https://docs.google.com/spreadsheets/d/${fileId}/export?format=csv&gid=${gid}`;
} else {
// direct download via Drive endpoint
fetchUrl = `https://drive.google.com/uc?export=download&id=${fileId}`;
}
// 3) Fetch the resource
const res = await fetch(fetchUrl);
if (!res.ok) {
throw new Error(`fetchPublicFile failed: ${res.status} ${res.statusText}`);
}
// 4) Parse metadata from headers
const contentType = res.headers.get('Content-Type') || '';
const disposition = res.headers.get('Content-Disposition') || '';
const fnMatch = disposition.match(
/filename\*=UTF-8''([^;]+)|filename="([^"]+)"/
);
const fileName = fnMatch
? decodeURIComponent(fnMatch[1] || fnMatch[2])
: undefined;
const sizeHeader = res.headers.get('Content-Length');
const size = sizeHeader ? parseInt(sizeHeader, 10) : undefined;
// 5) Choose body parser
let data: string | Blob;
if (
opts.exportMime === 'text/csv' ||
contentType.startsWith('text/') ||
contentType === 'application/json'
) {
data = await res.text();
} else {
data = await res.blob();
}
return { data, metadata: { contentType, fileName, size } };
}
// -----------------------------------------------------------
// Example usage in index.js (after importing GDrive):
//
// const { data, metadata } = await GDrive.fetchPublicFile(
// 'https://docs.google.com/spreadsheets/d/1gZaAM2l9JVF3TqK_-euYdhe9FHNX8cZcEfnDIG6AOsQ/edit',
// { exportMime: 'text/csv', gid: 0 }
// );
// console.log(metadata); // { contentType, fileName?, size? }
// console.log(data); // CSV string
//
// // then you can parse CSV and render as before…
// -----------------------------------------------------------
/**
* Dynamically load any Google API you need at runtime.
*
* Usage examples:
* await gdrive.loadApi('drive', 'v3'); // load Drive v3
* await gdrive.loadApi('calendar', 'v3'); // load Calendar v3
* await gdrive.loadApi('sheets', 'v4'); // load Sheets v4
* await gdrive.loadApi('gmail', 'v1'); // load Gmail v1
*
* If you need discovery-doc URLs instead, pass them as third arg.
*/
loadApi = async (
apiName: string,
apiVersion: string,
discoveryUrl?: string
): Promise<void> => {
// Safety: ensure gapi.client is ready
if (!this.gapi || !this.gapi.client) {
throw new Error(
'gapi.client not initialized. Did you forget to call initGapi()?'
);
}
// If you have the discovery URL for a custom API:
if (discoveryUrl) {
await this.gapi.client.load(discoveryUrl);
return;
}
// Default: load by API name + version
return new Promise((resolve, reject) => {
this.gapi.client
.load(apiName, apiVersion)
.then(() => resolve())
.catch((err: any) =>
reject(
new Error(
`Failed to load API ${apiName}/${apiVersion}: ${err.message || err}`
)
)
);
});
};
// Updated sign-in using GIS implicit flow.
// This function triggers a popup for user consent and obtains an access token.
handleUserSignIn = () => {
return new Promise((resolve, reject) => {
if (!this.tokenClient) {
console.error("Token client not initialized");
return reject("Token client not initialized");
}
// Set the callback to handle the token response.
this.tokenClient.callback = (tokenResponse) => {
if (tokenResponse.error) {
console.error("Token request error:", tokenResponse.error);
reject(tokenResponse.error);
} else if (tokenResponse.access_token) {
this.accessToken = tokenResponse.access_token;
this.isLoggedIn = true;
if (this.persistToken) {
// compute expiry timestamp
const expiresInMs = ((tokenResponse as any).expires_in || 3600) * 1000;
const expiresAt = Date.now() + expiresInMs;
localStorage.setItem(
this.storageKey,
JSON.stringify({ accessToken: tokenResponse.access_token, expiresAt })
);
}
// Optionally check for your app-specific folder.
if (this.directory && !this.directoryId) {
this.checkFolder(this.directory)
.then(() => resolve(tokenResponse))
.catch(reject);
} else {
resolve(tokenResponse);
}
} else {
console.error("Sign-in incomplete.");
reject("Sign-in incomplete");
}
};
// Request an access token (this will open the consent popup).
this.tokenClient.requestAccessToken({ prompt: 'consent' });
});
};
/**
* Attempt to restore a prior sign-in. If you pass in an explicit tokenResponse
* it will use that; otherwise it will fall back to reading localStorage.
*/
attemptRestoreSignIn = async (
tokenResponse?: { access_token: string; expires_in?: number }
): Promise<google.accounts.oauth2.TokenResponse> => {
// 1) explicit tokenResponse from a prior call?
if (tokenResponse?.access_token) {
// mirror handleUserSignIn’s logic without prompting
this.accessToken = tokenResponse.access_token;
this.tokenExpiresAt = Date.now() + (tokenResponse.expires_in || 3600) * 1000;
this.isLoggedIn = true;
}
// 2) else, if persistToken enabled, try localStorage
else if (this.persistToken) {
const raw = localStorage.getItem(this.storageKey);
if (!raw) throw new Error('no stored token');
const { accessToken, expiresAt } = JSON.parse(raw);
if (Date.now() > expiresAt - 60000) {
localStorage.removeItem(this.storageKey);
throw new Error('stored token expired');
}
this.accessToken = accessToken;
this.tokenExpiresAt = expiresAt;
this.isLoggedIn = true;
} else {
throw new Error('no token to restore');
}
// 3) if needed, ensure your AppData folder exists
if (this.directory && !this.directoryId) {
await this.checkFolder(this.directory);
}
return { access_token: this.accessToken! };
};
// Updated sign-out procedure: revokes the access token via the GIS library.
async signOut() {
if (!this.accessToken) {
return false;
}
await this.google.accounts.oauth2.revoke(this.accessToken, () => {
console.log("Access token revoked");
});
this.accessToken = '';
this.isLoggedIn = false;
return true;
};
// Helper to load external scripts.
loadScript = (scriptId, src, onload) => {
return new Promise((resolve) => {
const script = document.createElement('script');
script.type = "text/javascript";
script.src = src;
script.async = true;
script.defer = true;
script.id = scriptId;
script.onload = () => {
onload();
resolve(true);
};
document.head.appendChild(script);
});
};
// Cleanup: Remove loaded scripts and reset state.
deinit = () => {
// Optionally revoke token or perform other cleanup here.
this.google = undefined as any;
this.gapi = undefined as any;
this.tokenClient = undefined as any;
this.isLoggedIn = false;
this.accessToken = '';
const removeScript = (scriptId) => {
const script = document.getElementById(scriptId);
if (script) {
document.head.removeChild(script);
}
};
removeScript('gapi-client-script');
removeScript('gsi-client-script');
};
async searchDrive(query: string, pageSize = 100, pageToken: string | undefined = undefined, parentFolderId?: string, trashed = false) {
try {
let q = `name contains '${query}' and trashed=${trashed}`;
if (parentFolderId) {
q += ` and '${parentFolderId}' in parents`;
}
const response = await this.gapi.client.drive.files.list({
q,
pageSize,
fields: 'nextPageToken, files(id, name, mimeType)',
pageToken,
});
return {
files: response.result.files,
nextPageToken: response.result.nextPageToken,
};
} catch (error) {
console.error('Error searching Drive:', error);
throw error;
}
}
//check folder found or create if not
checkFolder = (
nameOrId = this.directory,
onResponse = (result) => { },
useId = false,
parentFolderId?: string
) => {
return new Promise((res, rej) => {
let q;
if (useId) {
// If querying by ID, check within the specified parentFolderId or don't specify parent
q = `'${nameOrId}' in parents and mimeType='application/vnd.google-apps.folder'` + (parentFolderId ? ` and '${parentFolderId}' in parents` : '');
} else {
// If querying by name, include parentFolderId in query if provided
// Query by name, potentially within a specific parent folder
q = `name='${nameOrId}' and mimeType='application/vnd.google-apps.folder'`;
if (parentFolderId) {
// Add parentFolderId to the query if provided
q += ` and '${parentFolderId}' in parents`;
}
}
this.gapi.client.drive.files.list({
q,
}).then(async (response) => {
//console.log(response);
if (response.result.files) {
if (response.result.files?.length === 0) {
const result = await this.createDriveFolder(nameOrId, parentFolderId); if (typeof result !== 'object') throw new Error(`${result}`);
if (onResponse) onResponse(result);
if (!this.directoryId) this.directoryId = (result as any).id; // Make sure this is correctly set
res(result);
} else {
if (onResponse) onResponse(response.result);
if (!this.directoryId) this.directoryId = response.result.files[0].id as string; // Set the directory ID from the response
res(response.result);
}
}
}).catch(error => {
console.error('Error checking folder:', error);
rej(error);
});
});
}
createDriveFolder = (
name = this.directory,
parentFolderId?: string
) => {
return new Promise((res, rej) => {
if (this.isLoggedIn) {
let data = {} as any;
data.name = name;
data.mimeType = "application/vnd.google-apps.folder";
if (parentFolderId) data.parents = [parentFolderId];
this.gapi.client.drive.files.create({ 'resource': data }).then((response) => {
//console.log("Created Folder:",response.result);
res(response.result as any);
});
} else {
console.error("Sign in with Google first!");
this.handleUserSignIn().then(async (resp) => {
if (this.isLoggedIn) {
res(await this.createDriveFolder(name, parentFolderId)); //rerun
}
});
}
});
}
async listFolders(folderId = this.directoryId, parent: string | string[] = 'parents') {
try {
const response = await this.gapi.client.drive.files.list({
q: `'${folderId}' in ${parent} and mimeType='application/vnd.google-apps.folder'`,
fields: 'nextPageToken, files(id, name, mimeType)'
});
return response.result.files || [];
} catch (error) {
console.error('Error listing folders:', error);
throw error;
}
}
async getSharableLink(fileId: string): Promise<string | undefined> {
try {
// Check existing permissions
const permissionsResponse = await this.gapi.client.drive.permissions.list({
fileId,
fields: 'permissions(id, role, type)',
});
const permissions = permissionsResponse.result.permissions;
if (!permissions) throw new Error("No permissions!");
const anyonePermission = permissions.find(permission => permission.type === 'anyone' && permission.role === 'reader');
// If 'anyone' permission doesn't exist, create it
if (!anyonePermission) {
await this.gapi.client.drive.permissions.create({
fileId,
resource: {
role: 'reader',
type: 'anyone',
},
});
}
// Fetch the file metadata to get the webViewLink
const fileMetadata = await this.getFileMetadata(fileId);
return fileMetadata.webViewLink;
} catch (error) {
console.error('Error getting sharable link:', error);
throw error;
}
}
async getFileMetadata(fileId: string): Promise<gapi.client.drive.File | FileMetadata> {
try {
const response = await this.gapi.client.drive.files.get({
fileId,
fields: 'id, name, mimeType, parents, webViewLink, iconLink, exportLinks, thumbnailLink, size, createdTime, modifiedTime, shared, owners, permissions',
});
return response.result;
} catch (error) {
console.error('Error getting file metadata:', error);
throw error;
}
}
async getFolderId(folderName, parentFolder = 'root') {
try {
const query = `mimeType='application/vnd.google-apps.folder' and name='${folderName}' ${parentFolder ? `and '${parentFolder}' ` : ``}in parents and trashed=false`;
const response = await this.gapi.client.drive.files.list({
q: query,
fields: 'files(id, name)',
pageSize: 1
});
const folder = response.result.files && response.result.files[0];
if (folder) {
return folder.id;
} else {
//console.error('Folder not found');
return undefined;
}
} catch (error) {
console.error('Error getting folder ID:', error);
throw error;
}
}
/**
* Look up a file by name and then download/export it, returning the Blob.
* @param fileName The name of the file to find in Drive.
* @param exportMimeType Optional MIME type to export native Google files (e.g. 'text/csv').
* @param downloadAs Optional override for the download filename (without extension).
* @param saveToDisk Whether to trigger a save-to-disk download. Defaults to true.
* @param parentFolder The Drive folder ID to search in. Defaults to this.directoryId.
*/
async downloadFileByName(
fileName: string,
exportMimeType?: string,
downloadAs?: string,
saveToDisk: boolean = true,
parentFolder: string = this.directoryId
): Promise<Blob> {
// 1) find the file by name
const meta = await this.getFileMetadataByName(fileName, parentFolder);
if (!meta?.id) {
throw new Error(`No file named "${fileName}" found in folder ${parentFolder}`);
}
// 2) delegate to downloadFile, propagating saveToDisk
return this.downloadFile(
meta.id,
exportMimeType,
downloadAs ?? meta.name,
saveToDisk
);
}
/**
* Download or export a file by its ID, returning the Blob.
* @param fileId The Drive file ID.
* @param exportMimeType Optional export MIME for native Google files.
* @param fileNameOverride Optional override for downloaded filename (without extension).
* @param saveToDisk Whether to trigger a save-to-disk download. Defaults to true.
*/
async downloadFile(
fileId: string,
exportMimeType?: string,
fileNameOverride?: string,
saveToDisk: boolean = true
): Promise<Blob> {
// 1) fetch file metadata (including exportLinks for native types)
const metaResp = await this.gapi.client.drive.files.get({
fileId,
fields: 'id,name,mimeType,exportLinks'
});
const meta = metaResp.result as {
id: string;
name: string;
mimeType: string;
exportLinks?: Record<string, string>;
};
const driveMime = meta.mimeType;
const baseName = fileNameOverride || meta.name;
// 2) determine if it's a native Google file and pick target/export MIME + ext
const options = nativeExportOptions[driveMime] ?? [];
const isNative = options.length > 0;
let targetMime: string | undefined = exportMimeType && options.find(o => o.mime === exportMimeType)?.mime;
let ext = '';
if (isNative) {
if (!targetMime) {
// default to first supported export if none requested
targetMime = options[0].mime;
}
ext = options.find(o => o.mime === targetMime)?.ext ?? '';
}
// 3) actually fetch the data as a Blob
let blob: Blob;
if (isNative && targetMime) {
// a) try direct exportLink if available
const exportUrl = meta.exportLinks?.[targetMime];
if (exportUrl) {
const token = this.gapi.auth.getToken().access_token!;
const res = await fetch(exportUrl, {
headers: { Authorization: `Bearer ${token}` }
});
if (!res.ok) throw new Error(`Export failed: ${res.status}`);
blob = await res.blob();
} else {
// b) fallback to Drive API export endpoint
const resp = await this.gapi.client.drive.files.export({
fileId,
mimeType: targetMime
});
// @ts-ignore: resp.body may be string or ArrayBuffer
blob = new Blob([resp.body!], { type: targetMime });
}
} else {
// raw binary download for non-native files
const token = this.gapi.auth.getToken().access_token;
if (!token) throw new Error('Not signed in');
const res = await fetch(
`https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`,
{ headers: { Authorization: `Bearer ${token}` } }
);
if (!res.ok) throw new Error(`Download failed: ${res.status}`);
blob = await res.blob();
}
// 4) optionally save to disk via anchor click
if (saveToDisk) {
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = baseName + ext;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(a.href);
}
// 5) return the raw Blob regardless of saveToDisk setting
return blob;
}
//https://developers.google.com/drive/api/guides/manage-sharing todo: more perms
async uploadFileToGoogleDrive(
data: Blob | string = 'a,b,c,1,2,3\nd,e,f,4,5,6\n',
fileName: string = `${new Date().toISOString()}.csv`,
mimeType: string | undefined = 'application/vnd.google-apps.spreadsheet',
parentFolder: string | string[] | undefined = this.directoryId,
onProgress: ((this: XMLHttpRequest, ev: ProgressEvent<EventTarget>) => any) | undefined,
overwrite: boolean = false
) {
if (typeof data === 'string') {
const type = fileName.endsWith('.csv') ? 'text/csv' : 'text/plain';
data = new Blob([data], { type });
}
const metadata = {
'name': fileName,
'mimeType': mimeType,
'parents': Array.isArray(parentFolder) ? parentFolder : [parentFolder], // upload to the current directory
};
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
form.append('file', data);
const token = this.gapi.auth.getToken().access_token;
let xhr = new XMLHttpRequest();
if (overwrite) {
const existingFile = await this.getFileMetadataByName(fileName, Array.isArray(parentFolder) ? parentFolder[0] : parentFolder);
if (existingFile) {
// Update the existing file
xhr.open('PATCH', `https://www.googleapis.com/upload/drive/v3/files/${existingFile.id}?uploadType=multipart`);
} else {
// Create a new file
xhr.open('POST', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
}
} else {
xhr.open('POST', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart');
}
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
if (onProgress) xhr.upload.onprogress = onProgress;
return new Promise((resolve, reject) => {
xhr.onload = () => {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(xhr.responseText);
}
};
xhr.onerror = () => reject(xhr.statusText);
xhr.send(form);
});
}
// Add this method to your GDrive class
async uploadFiles(
files: { name: string, mimeType: string, data: Blob | string, parents?: string }[],
folderId = this.directoryId,
uploadProgress?: HTMLProgressElement | HTMLMeterElement | string,
overwrite: boolean = false
) {
if (typeof uploadProgress === 'string') {
uploadProgress = document.getElementById('upload-progress') as HTMLProgressElement;
}
if (uploadProgress) uploadProgress.style.display = 'block';
for (let i = 0; i < files.length; i++) {
const file = files[i];
try {
let existingFileId: string | undefined = undefined;
if (overwrite) {