-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1627 lines (1410 loc) · 46.8 KB
/
background.js
File metadata and controls
1627 lines (1410 loc) · 46.8 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
// Background service worker for screenshot extension
// ============================================================================
// PRODUCTION LOGGER
// ============================================================================
const DEBUG_MODE = false; // Set to false for production
const logger = {
log: (...args) => { if (DEBUG_MODE) console.log('[Background]', ...args); },
info: (...args) => { if (DEBUG_MODE) console.info('[Background]', ...args); },
warn: (...args) => console.warn('[Background]', ...args),
error: (...args) => console.error('[Background]', ...args)
};
// ============================================================================
// USER-FRIENDLY ERROR MESSAGES
// ============================================================================
const ErrorMessages = {
'No access token': 'Unable to connect to Google Drive. Please sign in again.',
'Not authenticated': 'Please sign in to Google Drive first.',
'No client ID configured': 'Google Drive not configured. Please set up in extension settings.',
'Upload failed': 'Failed to upload. Please check your connection and try again.',
'Failed to set permissions': 'Uploaded successfully, but could not make file public.',
'File size exceeds': 'Screenshot too large (max 10MB). Try a smaller area.',
'Cannot access': 'Cannot capture chrome:// system pages.',
'Failed to fetch': 'Network error. Please check your internet connection.',
'NetworkError': 'No internet connection. Please connect and try again.'
};
function getUserFriendlyError(technicalError) {
for (const [key, msg] of Object.entries(ErrorMessages)) {
if (technicalError.includes(key)) {
return msg;
}
}
return 'Something went wrong. Please try again.';
}
// ============================================================================
// GOOGLE DRIVE API INTEGRATION
// ============================================================================
// Google Drive API integration class
class GoogleDriveUploader {
constructor() {
this.accessToken = null;
this.DRIVE_API_BASE = 'https://www.googleapis.com';
this.MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB limit
// Rate limiting for uploads
this.uploadQueue = [];
this.isProcessingQueue = false;
this.lastUploadTime = 0;
this.MIN_UPLOAD_INTERVAL = 2000; // 2 seconds between uploads
// Folder management
this.folderCache = new Map(); // Cache folder IDs
this.defaultFolderName = 'Screenshots';
// Upload history
this.uploadHistory = [];
this.MAX_HISTORY_SIZE = 100;
// Multi-account support
this.accounts = new Map(); // accountId -> { accessToken, email, name }
this.activeAccountId = null;
// Load saved settings
this.loadSettings();
}
// Load settings from storage
async loadSettings() {
try {
const data = await new Promise((resolve) => {
chrome.storage.sync.get(['driveSettings', 'uploadHistory', 'driveAccounts'], (result) => {
resolve(result);
});
});
if (data.uploadHistory) {
this.uploadHistory = data.uploadHistory;
}
if (data.driveAccounts) {
// Restore account information (but not tokens - those must be re-authenticated)
this.accounts = new Map(Object.entries(data.driveAccounts));
}
if (data.driveSettings) {
this.activeAccountId = data.driveSettings.activeAccountId;
this.defaultFolderName = data.driveSettings.defaultFolderName || 'Screenshots';
}
logger.info('Settings loaded');
} catch (error) {
logger.error('Failed to load settings:', error);
}
}
// Save settings to storage
async saveSettings() {
try {
await new Promise((resolve) => {
chrome.storage.sync.set({
driveSettings: {
activeAccountId: this.activeAccountId,
defaultFolderName: this.defaultFolderName
},
uploadHistory: this.uploadHistory.slice(-this.MAX_HISTORY_SIZE),
driveAccounts: Object.fromEntries(
Array.from(this.accounts.entries()).map(([id, account]) => [
id,
{ email: account.email, name: account.name }
])
)
}, resolve);
});
logger.info('Settings saved');
} catch (error) {
logger.error('Failed to save settings:', error);
}
}
// ============================================================================
// FOLDER MANAGEMENT
// ============================================================================
// Create folder in Google Drive
async createFolder(folderName, parentId = null) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
const metadata = {
name: folderName,
mimeType: 'application/vnd.google-apps.folder'
};
if (parentId) {
metadata.parents = [parentId];
}
const response = await fetch(
`${this.DRIVE_API_BASE}/drive/v3/files`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(metadata)
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to create folder: ${response.status} - ${errorText}`);
}
const result = await response.json();
return result.id;
}
// Find folder by name
async findFolder(folderName, parentId = null) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
// Check cache first
const cacheKey = `${folderName}-${parentId || 'root'}`;
if (this.folderCache.has(cacheKey)) {
return this.folderCache.get(cacheKey);
}
let query = `name='${folderName}' and mimeType='application/vnd.google-apps.folder' and trashed=false`;
if (parentId) {
query += ` and '${parentId}' in parents`;
} else {
query += ` and 'root' in parents`;
}
const response = await fetch(
`${this.DRIVE_API_BASE}/drive/v3/files?q=${encodeURIComponent(query)}&fields=files(id,name)`,
{
method: 'GET',
headers: {
'Authorization': `Bearer ${this.accessToken}`
}
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to find folder: ${response.status} - ${errorText}`);
}
const result = await response.json();
if (result.files && result.files.length > 0) {
const folderId = result.files[0].id;
// Cache the folder ID
this.folderCache.set(cacheKey, folderId);
return folderId;
}
return null;
}
// Get or create folder (with auto-creation)
async getOrCreateFolder(folderName, parentId = null) {
let folderId = await this.findFolder(folderName, parentId);
if (!folderId) {
logger.log(`Folder "${folderName}" not found, creating...`);
folderId = await this.createFolder(folderName, parentId);
logger.log(`Folder created with ID: ${folderId}`);
}
return folderId;
}
// Get or create date-based folder structure (e.g., Screenshots/2026/2026-02-12)
async getOrCreateDateFolder() {
const now = new Date();
const year = now.getFullYear().toString();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const dateFolder = `${year}-${month}-${day}`;
// Create folder hierarchy: Screenshots -> YYYY -> YYYY-MM-DD
const screenshotsFolderId = await this.getOrCreateFolder(this.defaultFolderName);
const yearFolderId = await this.getOrCreateFolder(year, screenshotsFolderId);
const dateFolderId = await this.getOrCreateFolder(dateFolder, yearFolderId);
return dateFolderId;
}
// List folders
async listFolders(parentId = null) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
let query = `mimeType='application/vnd.google-apps.folder' and trashed=false`;
if (parentId) {
query += ` and '${parentId}' in parents`;
} else {
query += ` and 'root' in parents`;
}
const response = await fetch(
`${this.DRIVE_API_BASE}/drive/v3/files?q=${encodeURIComponent(query)}&fields=files(id,name,createdTime)&orderBy=name`,
{
method: 'GET',
headers: {
'Authorization': `Bearer ${this.accessToken}`
}
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to list folders: ${response.status} - ${errorText}`);
}
const result = await response.json();
return result.files || [];
}
// ============================================================================
// OAUTH AND AUTHENTICATION
// ============================================================================
// Get OAuth token (interactive or silent)
async authenticate(interactive = false) {
try {
// Get client ID from storage
const clientId = await new Promise((resolve) => {
chrome.storage.sync.get(['googleDriveClientId'], (result) => {
resolve(result.googleDriveClientId);
});
});
if (!clientId) {
throw new Error('No client ID configured. Please set up Google Drive in extension settings.');
}
// Check for cached token in memory first
if (this.accessToken && !interactive) {
return this.accessToken;
}
// Try to retrieve token from session storage (survives service worker restarts)
if (!interactive) {
const stored = await new Promise((resolve) => {
chrome.storage.session.get(['googleDriveToken'], (result) => {
resolve(result.googleDriveToken);
});
});
if (stored) {
this.accessToken = stored;
logger.info('Reused token from session storage');
return this.accessToken;
}
}
// Construct OAuth URL
const redirectUri = `https://${chrome.runtime.id}.chromiumapp.org/`;
const scope = 'https://www.googleapis.com/auth/drive.file';
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?` +
`client_id=${encodeURIComponent(clientId)}` +
`&response_type=token` +
`&redirect_uri=${encodeURIComponent(redirectUri)}` +
`&scope=${encodeURIComponent(scope)}`;
logger.log('OAuth Debug Info:', {
extensionId: chrome.runtime.id,
redirectUri: redirectUri,
clientId: clientId.substring(0, 20) + '...',
interactive: interactive
});
// Launch OAuth flow
const responseUrl = await new Promise((resolve, reject) => {
const flowOptions = {
url: authUrl,
interactive: interactive
};
// Add timeout settings for non-interactive mode to handle redirects
if (!interactive) {
flowOptions.abortOnLoadForNonInteractive = true;
flowOptions.timeoutMsForNonInteractive = 3000;
}
chrome.identity.launchWebAuthFlow(
flowOptions,
(responseUrl) => {
if (chrome.runtime.lastError) {
const errorMsg = chrome.runtime.lastError.message;
logger.error('OAuth flow error:', errorMsg);
// Provide more helpful error messages
if (errorMsg.includes('did not approve') || errorMsg.includes('user cancelled')) {
reject(new Error('OAuth cancelled. Please click "Allow" on the consent screen to grant access.'));
} else if (errorMsg.includes('redirect_uri_mismatch')) {
reject(new Error(`Redirect URI mismatch. Make sure your Google Cloud OAuth client has this redirect URI: ${redirectUri}`));
} else {
reject(new Error(errorMsg));
}
} else if (!responseUrl) {
reject(new Error('No response from OAuth'));
} else {
logger.log('OAuth success, got response URL');
resolve(responseUrl);
}
}
);
});
// Extract access token from response URL
const params = new URL(responseUrl).hash.substring(1);
const tokenMatch = params.match(/access_token=([^&]+)/);
if (!tokenMatch) {
throw new Error('No access token in response');
}
this.accessToken = tokenMatch[1];
// Store token in session storage (survives service worker restarts)
await new Promise((resolve) => {
chrome.storage.session.set({ googleDriveToken: this.accessToken }, resolve);
});
logger.info('Token stored in session storage');
return this.accessToken;
} catch (error) {
logger.error('Authentication error:', error);
throw error;
}
}
// Upload file to Google Drive
async uploadFile(blob, filename, folderId = null, description = null) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
if (blob.size > this.MAX_FILE_SIZE) {
throw new Error('File size exceeds 10MB limit');
}
// Create metadata
const metadata = {
name: filename,
mimeType: 'image/png'
};
// Add folder parent if specified
if (folderId) {
metadata.parents = [folderId];
}
// Add description if specified
if (description) {
metadata.description = description;
}
// Create multipart form data
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const closeDelim = "\r\n--" + boundary + "--";
// Read blob as array buffer
const fileData = await blob.arrayBuffer();
// Construct multipart body
const metadataPart = delimiter +
'Content-Type: application/json; charset=UTF-8\r\n\r\n' +
JSON.stringify(metadata);
const filePart = delimiter +
'Content-Type: image/png\r\n' +
'Content-Transfer-Encoding: base64\r\n\r\n';
// Convert file data to base64
const base64Data = this._arrayBufferToBase64(fileData);
const multipartBody = metadataPart + filePart + base64Data + closeDelim;
// Upload to Drive
const response = await fetch(
`${this.DRIVE_API_BASE}/upload/drive/v3/files?uploadType=multipart`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': `multipart/related; boundary=${boundary}`
},
body: multipartBody
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Upload failed: ${response.status} - ${errorText}`);
}
const result = await response.json();
return result.id; // Return file ID
}
// ============================================================================
// FILE MANAGEMENT
// ============================================================================
// Delete file from Google Drive
async deleteFile(fileId) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
const response = await fetch(
`${this.DRIVE_API_BASE}/drive/v3/files/${fileId}`,
{
method: 'DELETE',
headers: {
'Authorization': `Bearer ${this.accessToken}`
}
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to delete file: ${response.status} - ${errorText}`);
}
// Remove from upload history
this.uploadHistory = this.uploadHistory.filter(item => item.fileId !== fileId);
await this.saveSettings();
logger.log(`File ${fileId} deleted successfully`);
return true;
}
// Rename file
async renameFile(fileId, newName) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
const response = await fetch(
`${this.DRIVE_API_BASE}/drive/v3/files/${fileId}`,
{
method: 'PATCH',
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: newName })
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to rename file: ${response.status} - ${errorText}`);
}
// Update upload history
const historyItem = this.uploadHistory.find(item => item.fileId === fileId);
if (historyItem) {
historyItem.filename = newName;
await this.saveSettings();
}
logger.log(`File ${fileId} renamed to ${newName}`);
return true;
}
// Update file description
async updateFileDescription(fileId, description) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
const response = await fetch(
`${this.DRIVE_API_BASE}/drive/v3/files/${fileId}`,
{
method: 'PATCH',
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ description })
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to update description: ${response.status} - ${errorText}`);
}
// Update upload history
const historyItem = this.uploadHistory.find(item => item.fileId === fileId);
if (historyItem) {
historyItem.description = description;
await this.saveSettings();
}
logger.log(`File ${fileId} description updated`);
return true;
}
// Get file info
async getFileInfo(fileId) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
const response = await fetch(
`${this.DRIVE_API_BASE}/drive/v3/files/${fileId}?fields=id,name,description,mimeType,size,createdTime,modifiedTime,webViewLink,webContentLink,thumbnailLink`,
{
method: 'GET',
headers: {
'Authorization': `Bearer ${this.accessToken}`
}
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to get file info: ${response.status} - ${errorText}`);
}
return await response.json();
}
// Add to upload history
addToHistory(fileId, filename, link, folderId = null, description = null) {
const historyItem = {
fileId,
filename,
link,
folderId,
description,
timestamp: Date.now(),
date: new Date().toISOString()
};
this.uploadHistory.unshift(historyItem);
// Keep only last MAX_HISTORY_SIZE items
if (this.uploadHistory.length > this.MAX_HISTORY_SIZE) {
this.uploadHistory = this.uploadHistory.slice(0, this.MAX_HISTORY_SIZE);
}
this.saveSettings();
}
// Get upload history
getHistory(limit = 20) {
return this.uploadHistory.slice(0, limit);
}
// Clear upload history
async clearHistory() {
this.uploadHistory = [];
await this.saveSettings();
logger.log('Upload history cleared');
}
// ============================================================================
// BATCH OPERATIONS
// ============================================================================
// Batch upload files
async batchUpload(files) {
if (!Array.isArray(files) || files.length === 0) {
throw new Error('Invalid files array');
}
const results = [];
const errors = [];
for (const file of files) {
try {
const result = await this.shareScreenshot(
file.blobData,
file.filename,
file.folderId,
file.description
);
results.push({
filename: file.filename,
success: true,
...result
});
} catch (error) {
logger.error(`Batch upload error for ${file.filename}:`, error);
errors.push({
filename: file.filename,
success: false,
error: error.message
});
}
}
return {
success: errors.length === 0,
results,
errors,
total: files.length,
uploaded: results.length,
failed: errors.length
};
}
// Batch delete files
async batchDelete(fileIds) {
if (!Array.isArray(fileIds) || fileIds.length === 0) {
throw new Error('Invalid file IDs array');
}
const results = [];
const errors = [];
for (const fileId of fileIds) {
try {
await this.deleteFile(fileId);
results.push({ fileId, success: true });
} catch (error) {
logger.error(`Batch delete error for ${fileId}:`, error);
errors.push({ fileId, success: false, error: error.message });
}
}
return {
success: errors.length === 0,
results,
errors,
total: fileIds.length,
deleted: results.length,
failed: errors.length
};
}
// Helper function to convert ArrayBuffer to base64
_arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
// Make file publicly accessible
async makeFilePublic(fileId) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
const response = await fetch(
`${this.DRIVE_API_BASE}/drive/v3/files/${fileId}/permissions`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${this.accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
type: 'anyone',
role: 'reader'
})
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to set permissions: ${response.status} - ${errorText}`);
}
return await response.json();
}
// Get shareable link (with optional shortening)
async getShareableLink(fileId, shouldShorten = true) {
if (!this.accessToken) {
throw new Error('Not authenticated');
}
const response = await fetch(
`${this.DRIVE_API_BASE}/drive/v3/files/${fileId}?fields=webViewLink,webContentLink`,
{
method: 'GET',
headers: {
'Authorization': `Bearer ${this.accessToken}`
}
}
);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to get link: ${response.status} - ${errorText}`);
}
const result = await response.json();
let link = result.webViewLink || result.webContentLink;
// Clean up query parameters (remove tracking params)
if (link) {
link = link.split('?')[0];
}
// Shorten the link if requested
if (shouldShorten && link) {
try {
const shortened = await urlShortener.shortenWithTinyURL(link);
logger.log('Link shortened:', link, '->', shortened);
return shortened;
} catch (error) {
logger.warn('Shortening failed, using full link:', error);
// Fallback to full link
}
}
return link;
}
// ============================================================================
// ENHANCED SHARING
// ============================================================================
// Generate QR code for link (returns data URL)
async generateQRCode(link) {
try {
// Use QR Server API (free, no API key needed)
const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(link)}`;
const response = await fetch(qrUrl);
if (!response.ok) {
throw new Error('Failed to generate QR code');
}
// Convert to blob and then to data URL
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (error) {
logger.error('QR code generation error:', error);
throw error;
}
}
// Send to webhook (Slack, Discord, etc.)
async sendToWebhook(webhookUrl, message, link, filename) {
try {
// Support both Slack and Discord webhook formats
const isSlack = webhookUrl.includes('slack.com');
const isDiscord = webhookUrl.includes('discord.com');
let payload;
if (isSlack) {
payload = {
text: message || 'New screenshot uploaded',
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `*${filename}*\n${message || 'Screenshot uploaded to Google Drive'}`
}
},
{
type: 'actions',
elements: [
{
type: 'button',
text: {
type: 'plain_text',
text: 'View Screenshot'
},
url: link
}
]
}
]
};
} else if (isDiscord) {
payload = {
content: message || 'New screenshot uploaded',
embeds: [
{
title: filename,
description: 'Screenshot uploaded to Google Drive',
url: link,
color: 3447003, // Blue color
timestamp: new Date().toISOString()
}
]
};
} else {
// Generic webhook format
payload = {
message: message || 'New screenshot uploaded',
filename,
link,
timestamp: new Date().toISOString()
};
}
const response = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`Webhook failed: ${response.status}`);
}
logger.log('Webhook sent successfully');
return true;
} catch (error) {
logger.error('Webhook error:', error);
throw error;
}
}
// Generate email compose link
generateEmailLink(link, filename, subject = null, body = null) {
const defaultSubject = `Screenshot: ${filename}`;
const defaultBody = `Hi,\n\nI've shared a screenshot with you:\n\n${link}\n\nBest regards`;
const emailSubject = encodeURIComponent(subject || defaultSubject);
const emailBody = encodeURIComponent(body || defaultBody);
return `mailto:?subject=${emailSubject}&body=${emailBody}`;
}
// Complete upload flow with rate limiting
async shareScreenshot(blobData, filename, options = {}) {
return new Promise((resolve, reject) => {
// Add to queue with options
this.uploadQueue.push({
blobData,
filename,
options,
resolve,
reject
});
this.processQueue();
});
}
// Process upload queue with rate limiting
async processQueue() {
if (this.isProcessingQueue || this.uploadQueue.length === 0) {
return;
}
this.isProcessingQueue = true;
// Check rate limit
const timeSinceLastUpload = Date.now() - this.lastUploadTime;
if (timeSinceLastUpload < this.MIN_UPLOAD_INTERVAL) {
// Wait before processing
setTimeout(() => {
this.isProcessingQueue = false;
this.processQueue();
}, this.MIN_UPLOAD_INTERVAL - timeSinceLastUpload);
return;
}
const item = this.uploadQueue.shift();
const options = item.options || {};
try {
// Try to reuse existing token if available, otherwise use interactive auth
if (!this.accessToken) {
// First time - go straight to interactive auth
await this.authenticate(true);
} else {
// Have token - try to reuse it, fall back to interactive if it fails
try {
await this.authenticate(false);
} catch (error) {
// Token expired or invalid - get new one interactively
await this.authenticate(true);
}
}
// Convert base64 to blob
const response = await fetch(item.blobData);
const blob = await response.blob();
// Determine folder ID
let folderId = options.folderId;
if (!folderId && options.useAutoFolder !== false) {
// Auto-create date-based folder structure
folderId = await this.getOrCreateDateFolder();
logger.log('Using date folder:', folderId);
}
// Upload file with folder and description
const fileId = await this.uploadFile(
blob,
item.filename,
folderId,
options.description
);
logger.log('File uploaded:', fileId);
// Make public (unless explicitly disabled)
if (options.makePublic !== false) {
await this.makeFilePublic(fileId);
logger.log('File made public');
}
// Get shortened link
const shouldShorten = options.shortenLink !== false;
const link = await this.getShareableLink(fileId, shouldShorten);
logger.log('Link obtained:', link);
// Also get full link as fallback
const fullLink = shouldShorten
? await this.getShareableLink(fileId, false)
: link;
// Generate QR code if requested
let qrCode = null;
if (options.generateQR) {
try {
qrCode = await this.generateQRCode(link);
logger.log('QR code generated');
} catch (error) {
logger.warn('QR code generation failed:', error);
}
}
// Send to webhook if configured
if (options.webhookUrl) {
try {
await this.sendToWebhook(
options.webhookUrl,
options.webhookMessage,
link,