-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmove_diff.patch
More file actions
609 lines (598 loc) · 21.9 KB
/
Copy pathmove_diff.patch
File metadata and controls
609 lines (598 loc) · 21.9 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
diff --git a/packages/web/src/components/MoveDriveModal.tsx b/packages/web/src/components/MoveDriveModal.tsx
new file mode 100644
index 0000000..316799a
--- /dev/null
+++ b/packages/web/src/components/MoveDriveModal.tsx
@@ -0,0 +1,87 @@
+import { useState } from 'react';
+import { HardDrive, Loader2 } from 'lucide-react';
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from './ui/dialog';
+import { useDriveStore } from '../stores/driveStore';
+import { api } from '../lib/api';
+import { FileEntry, DriveAccount } from '../types';
+import { formatFileSize } from '../lib/utils';
+
+interface MoveDriveModalProps {
+ file: FileEntry | null;
+ onClose: () => void;
+ onSuccess: () => void;
+ onError: (error: any) => void;
+}
+
+export function MoveDriveModal({ file, onClose, onSuccess, onError }: MoveDriveModalProps) {
+ const { drives } = useDriveStore();
+ const [isMoving, setIsMoving] = useState(false);
+ const [movingToDriveId, setMovingToDriveId] = useState<string | null>(null);
+
+ const availableDrives = drives.filter(d => d.id !== file?.driveAccountId);
+
+ const handleMove = async (drive: DriveAccount) => {
+ if (!file) return;
+ try {
+ setIsMoving(true);
+ setMovingToDriveId(drive.id);
+ await api.moveFileToDrive(file.id, drive.id);
+ onSuccess();
+ } catch (err) {
+ onError(err);
+ } finally {
+ setIsMoving(false);
+ setMovingToDriveId(null);
+ }
+ };
+
+ return (
+ <Dialog open={!!file} onOpenChange={(open) => !open && !isMoving && onClose()}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>Move to Another Drive</DialogTitle>
+ <DialogDescription>
+ Select a destination drive to move "{file?.name}". This may take a moment depending on the file size.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="grid gap-4 py-4">
+ {availableDrives.length === 0 ? (
+ <p className="text-sm text-center text-muted-foreground py-4">
+ No other drives available. Please connect another Google Drive account.
+ </p>
+ ) : (
+ availableDrives.map(drive => (
+ <button
+ key={drive.id}
+ onClick={() => handleMove(drive)}
+ disabled={isMoving}
+ className={`flex items-center p-3 border rounded-lg transition-colors text-left ${
+ isMoving && movingToDriveId !== drive.id
+ ? 'opacity-50 cursor-not-allowed'
+ : 'hover:bg-accent hover:text-accent-foreground'
+ } ${isMoving && movingToDriveId === drive.id ? 'ring-2 ring-primary border-primary bg-accent' : ''}`}
+ >
+ <div className="flex-shrink-0 mr-4">
+ {isMoving && movingToDriveId === drive.id ? (
+ <Loader2 className="w-5 h-5 text-primary animate-spin" />
+ ) : (
+ <HardDrive className="w-5 h-5 text-muted-foreground" />
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium truncate">
+ {drive.email}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ Free space: {formatFileSize(drive.freeSpace)}
+ </p>
+ </div>
+ </button>
+ ))
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/web/src/components/files/FileGrid.tsx b/packages/web/src/components/files/FileGrid.tsx
index b3fffeb..46ceb59 100644
--- a/packages/web/src/components/files/FileGrid.tsx
+++ b/packages/web/src/components/files/FileGrid.tsx
@@ -25,6 +25,7 @@ export interface FileGridProps {
onDeleteFile?: (id: string) => void;
isTargetShared?: (id: string, type: 'file' | 'folder') => boolean;
errorDrives?: Set<string>;
+ onMoveDrive?: (file: FileEntry) => void;
}
export const FileGrid: React.FC<FileGridProps> = ({
@@ -38,6 +39,7 @@ export const FileGrid: React.FC<FileGridProps> = ({
onDeleteFile,
isTargetShared,
errorDrives,
+ onMoveDrive,
}) => {
if (files.length === 0 && subfolders.length === 0) {
return (
@@ -147,6 +149,11 @@ export const FileGrid: React.FC<FileGridProps> = ({
<Pencil className="mr-2 h-4 w-4" /> Rename
</ContextMenuItem>
)}
+ {onMoveDrive && (
+ <ContextMenuItem onClick={() => onMoveDrive(file)}>
+ <ExternalLink className="mr-2 h-4 w-4" /> Move to another drive
+ </ContextMenuItem>
+ )}
{onDeleteFile && (
<>
<ContextMenuSeparator />
diff --git a/packages/web/src/lib/api.ts b/packages/web/src/lib/api.ts
index 9bcbecf..32525f1 100644
--- a/packages/web/src/lib/api.ts
+++ b/packages/web/src/lib/api.ts
@@ -88,6 +88,11 @@ export const api = {
body: JSON.stringify({ name }),
}),
deleteFile: (id: string) => request<{ success: boolean }>(`/api/files/${id}`, { method: 'DELETE' }),
+ moveFileToDrive: (id: string, targetDriveId: string) =>
+ request<{ file: import('../types').FileEntry }>(`/api/files/${id}/move-drive`, {
+ method: 'POST',
+ body: JSON.stringify({ targetDriveId }),
+ }),
// Recent files (uses root contents, sorted by date)
getRecentFiles: () =>
diff --git a/packages/web/src/pages/DashboardPage.tsx b/packages/web/src/pages/DashboardPage.tsx
index e2fe7f0..ee7735f 100644
--- a/packages/web/src/pages/DashboardPage.tsx
+++ b/packages/web/src/pages/DashboardPage.tsx
@@ -1,26 +1,34 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useState, useCallback } from 'react';
import { useDriveStore } from '../stores/driveStore';
import { QuotaBar } from '../components/QuotaBar';
import { FileGrid } from '../components/files/FileGrid';
import { ShareModal } from '../components/ShareModal';
+import { MoveDriveModal } from '../components/MoveDriveModal';
import { formatFileSize, getDriveColor } from '../lib/utils';
import { api } from '../lib/api';
import { useSharedStore } from '../stores/sharedStore';
import { HardDrive, RefreshCw, TrendingUp } from 'lucide-react';
+import { useToastStore } from '../stores/toastStore';
import type { FileEntry } from '../types';
export function DashboardPage() {
const { drives, aggregate, isLoading, fetchDrives } = useDriveStore();
const [recentFiles, setRecentFiles] = useState<FileEntry[]>([]);
const [shareTarget, setShareTarget] = useState<{ id: string, type: 'file' | 'folder' } | null>(null);
+ const [moveFileTarget, setMoveFileTarget] = useState<FileEntry | null>(null);
+ const { addToast } = useToastStore();
const { fetchSharedLinks, isTargetShared } = useSharedStore();
+ const refreshRecent = useCallback(() => {
+ api.getRecentFiles().then((data) => setRecentFiles(data.files.slice(0, 10))).catch(() => {});
+ }, []);
+
useEffect(() => {
fetchDrives();
fetchSharedLinks();
- api.getRecentFiles().then((data) => setRecentFiles(data.files.slice(0, 10))).catch(() => {});
- }, [fetchDrives, fetchSharedLinks]);
+ refreshRecent();
+ }, [fetchDrives, fetchSharedLinks, refreshRecent]);
return (
<div>
@@ -76,6 +84,7 @@ export function DashboardPage() {
return { drive: drives[index], index };
}}
onShare={(id, type) => setShareTarget({ id, type })}
+ onMoveDrive={setMoveFileTarget}
isTargetShared={isTargetShared}
/>
</div>
@@ -95,6 +104,19 @@ export function DashboardPage() {
onClose={() => setShareTarget(null)}
/>
)}
+
+ {moveFileTarget && (
+ <MoveDriveModal
+ file={moveFileTarget}
+ onClose={() => setMoveFileTarget(null)}
+ onSuccess={() => {
+ setMoveFileTarget(null);
+ refreshRecent();
+ addToast('success', 'File moved successfully');
+ }}
+ onError={(msg) => addToast('error', msg)}
+ />
+ )}
</div>
);
}
diff --git a/packages/web/src/pages/FilesPage.tsx b/packages/web/src/pages/FilesPage.tsx
index 518ee8a..31dd958 100644
--- a/packages/web/src/pages/FilesPage.tsx
+++ b/packages/web/src/pages/FilesPage.tsx
@@ -8,6 +8,7 @@ import { DropZone } from '../components/DropZone';
import { UploadModal } from '../components/UploadModal';
import { FilePreviewModal } from '../components/FilePreviewModal';
import { ShareModal } from '../components/ShareModal';
+import { MoveDriveModal } from '../components/MoveDriveModal';
import { Upload, FolderPlus, X } from 'lucide-react';
import { useToastStore } from '../stores/toastStore';
import { useSharedStore } from '../stores/sharedStore';
@@ -26,6 +27,7 @@ export function FilesPage() {
const { addToast } = useToastStore();
const [previewFile, setPreviewFile] = useState<FileEntry | null>(null);
const [shareTarget, setShareTarget] = useState<{ id: string, type: 'file' | 'folder' } | null>(null);
+ const [moveFileTarget, setMoveFileTarget] = useState<FileEntry | null>(null);
const [searchQuery, setSearchQuery] = useState('');
const { fetchSharedLinks, isTargetShared } = useSharedStore();
@@ -140,6 +142,7 @@ export function FilesPage() {
onShare={(id, type) => setShareTarget({ id, type })}
onRenameFile={handleRenameFile}
onDeleteFile={handleDeleteFile}
+ onMoveDrive={setMoveFileTarget}
isTargetShared={isTargetShared}
errorDrives={errorDrives}
/>
@@ -156,6 +159,18 @@ export function FilesPage() {
onClose={() => setShareTarget(null)}
/>
)}
+ {moveFileTarget && (
+ <MoveDriveModal
+ file={moveFileTarget}
+ onClose={() => setMoveFileTarget(null)}
+ onSuccess={() => {
+ setMoveFileTarget(null);
+ refresh();
+ addToast('success', 'File moved successfully');
+ }}
+ onError={(msg) => addToast('error', msg)}
+ />
+ )}
</div>
</DropZone>
);
diff --git a/packages/worker/src/routes/files.ts b/packages/worker/src/routes/files.ts
index 2d8e7e0..0398c34 100644
--- a/packages/worker/src/routes/files.ts
+++ b/packages/worker/src/routes/files.ts
@@ -82,6 +82,101 @@ filesRouter.patch('/:id/move', async (c) => {
return c.json({ success: true });
});
+// Move file to another drive
+filesRouter.post('/:id/move-drive', async (c) => {
+ const userId = c.get('userId');
+ const fileId = c.req.param('id');
+ const body = await c.req.json();
+ const targetDriveId = body.targetDriveId;
+
+ if (typeof targetDriveId !== 'string' || !targetDriveId.trim()) {
+ throw new AppError(400, 'Target drive ID must be a non-empty string');
+ }
+
+ const db = c.env.DB;
+
+ const file = await db.prepare(
+ `SELECT f.*, d.email as driveEmail, d.id as sourceDriveId
+ FROM files f
+ JOIN drive_accounts d ON f.drive_account_id = d.id
+ WHERE f.id = ? AND f.user_id = ?`
+ ).bind(fileId, userId).first<{ driveEmail: string; sourceDriveId: string; google_file_id: string; name: string }>();
+
+ if (!file) {
+ throw new AppError(404, 'File not found or unauthorized');
+ }
+
+ if (file.sourceDriveId === targetDriveId) {
+ throw new AppError(400, 'File is already in the target drive');
+ }
+
+ const targetDrive = await db.prepare(
+ 'SELECT id, email FROM drive_accounts WHERE id = ? AND user_id = ?'
+ ).bind(targetDriveId, userId).first<{ id: string; email: string }>();
+
+ if (!targetDrive) {
+ throw new AppError(404, 'Target drive not found or unauthorized');
+ }
+
+ const driveService = new GoogleDriveService(c.env.KV, c.env.GOOGLE_CLIENT_ID, c.env.GOOGLE_CLIENT_SECRET);
+
+ let shareSuccess = false;
+ let copySuccessId: string | null = null;
+ let trashSuccess = false;
+
+ try {
+ await driveService.shareFile(
+ file.sourceDriveId,
+ file.google_file_id,
+ targetDrive.email,
+ 'writer'
+ );
+ shareSuccess = true;
+
+ const copiedFile = await driveService.copyFile(
+ targetDriveId,
+ file.google_file_id
+ );
+ copySuccessId = copiedFile.id;
+
+ try {
+ await driveService.trashFile(file.sourceDriveId, file.google_file_id);
+ trashSuccess = true;
+ } catch (trashError) {
+ console.error('Failed to trash original file:', trashError);
+ }
+
+ await db.prepare(
+ `UPDATE files
+ SET drive_account_id = ?, google_file_id = ?, google_parent_id = NULL, updated_at = datetime("now")
+ WHERE id = ?`
+ ).bind(targetDriveId, copiedFile.id, fileId).run();
+
+ const updatedFile = await db.prepare('SELECT * FROM files WHERE id = ?').bind(fileId).first<Record<string, unknown>>();
+
+ return c.json({ file: mapFileRow(updatedFile!), success: true });
+ } catch (error) {
+ console.error('Move drive failed:', error);
+
+ if (trashSuccess) {
+ try { await driveService.untrashFile(file.sourceDriveId, file.google_file_id); }
+ catch (e) { console.error('Rollback untrash failed:', e); }
+ }
+
+ if (copySuccessId) {
+ try { await driveService.deleteFile(targetDriveId, copySuccessId); }
+ catch (e) { console.error('Rollback delete failed:', e); }
+ }
+
+ if (shareSuccess) {
+ try { await driveService.revokeShare(file.sourceDriveId, file.google_file_id, targetDrive.email); }
+ catch (e) { console.error('Failed to revoke share:', e); }
+ }
+
+ throw new AppError(500, 'Failed to move file to another drive');
+ }
+});
+
// Initialize upload (returns Google Drive Resumable URL)
filesRouter.post('/upload/init', async (c) => {
const userId = c.get('userId');
diff --git a/packages/worker/src/services/google-drive.ts b/packages/worker/src/services/google-drive.ts
index 18c5034..a9d32c6 100644
--- a/packages/worker/src/services/google-drive.ts
+++ b/packages/worker/src/services/google-drive.ts
@@ -23,6 +23,13 @@ export interface GDriveFolder {
parents?: string[];
}
+export class GoogleDriveError extends Error {
+ constructor(public status: number, message: string, public data?: any) {
+ super(message);
+ this.name = 'GoogleDriveError';
+ }
+}
+
export class GoogleDriveService {
constructor(
private kv: KVNamespace,
@@ -269,6 +276,106 @@ export class GoogleDriveService {
}
}
+ // ─── Move To Another Drive Operations ───
+
+ async shareFile(driveAccountId: string, fileId: string, emailAddress: string, role = 'writer', type = 'user'): Promise<string> {
+ const token = await this.getValidToken(driveAccountId);
+
+ const response = await fetch(`${DRIVE_API}/files/${fileId}/permissions?sendNotificationEmail=false`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ role, type, emailAddress }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ let errorData;
+ try { errorData = JSON.parse(errorText); } catch {}
+ throw new GoogleDriveError(response.status, `Failed to share file: ${errorText}`, errorData);
+ }
+
+ const data: { id: string } = await response.json();
+ return data.id;
+ }
+
+ async revokeShare(driveAccountId: string, fileId: string, permissionId: string): Promise<void> {
+ const token = await this.getValidToken(driveAccountId);
+
+ const response = await fetch(`${DRIVE_API}/files/${fileId}/permissions/${permissionId}`, {
+ method: 'DELETE',
+ headers: { Authorization: `Bearer ${token}` },
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ let errorData;
+ try { errorData = JSON.parse(errorText); } catch {}
+ throw new GoogleDriveError(response.status, `Failed to revoke share: ${errorText}`, errorData);
+ }
+ }
+
+ async copyFile(driveAccountId: string, fileId: string): Promise<GDriveFile> {
+ const token = await this.getValidToken(driveAccountId);
+ const fields = 'id,name,mimeType,size,thumbnailLink,webViewLink,webContentLink,createdTime,modifiedTime';
+
+ const response = await fetch(`${DRIVE_API}/files/${fileId}/copy?fields=${fields}`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}` },
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ let errorData;
+ try { errorData = JSON.parse(errorText); } catch {}
+ throw new GoogleDriveError(response.status, `Failed to copy file: ${errorText}`, errorData);
+ }
+
+ return response.json();
+ }
+
+ async trashFile(driveAccountId: string, fileId: string): Promise<void> {
+ const token = await this.getValidToken(driveAccountId);
+
+ const response = await fetch(`${DRIVE_API}/files/${fileId}`, {
+ method: 'PATCH',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ trashed: true }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ let errorData;
+ try { errorData = JSON.parse(errorText); } catch {}
+ throw new GoogleDriveError(response.status, `Failed to trash file: ${errorText}`, errorData);
+ }
+ }
+
+ async untrashFile(driveAccountId: string, fileId: string): Promise<void> {
+ const token = await this.getValidToken(driveAccountId);
+
+ const response = await fetch(`${DRIVE_API}/files/${fileId}`, {
+ method: 'PATCH',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ trashed: false }),
+ });
+
+ if (!response.ok) {
+ const errorText = await response.text();
+ let errorData;
+ try { errorData = JSON.parse(errorText); } catch {}
+ throw new GoogleDriveError(response.status, `Failed to untrash file: ${errorText}`, errorData);
+ }
+ }
+
// ─── Changes API (for sync) ───
async getStartPageToken(driveAccountId: string): Promise<string> {
diff --git a/packages/worker/tests/google-drive-move.test.ts b/packages/worker/tests/google-drive-move.test.ts
new file mode 100644
index 0000000..0f3a4de
--- /dev/null
+++ b/packages/worker/tests/google-drive-move.test.ts
@@ -0,0 +1,114 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { GoogleDriveService } from '../src/services/google-drive';
+
+describe('GoogleDriveService Move Operations', () => {
+ let service: GoogleDriveService;
+ let mockKv: any;
+
+ beforeEach(() => {
+ mockKv = {
+ get: vi.fn().mockResolvedValue(JSON.stringify({
+ accessToken: 'fake-access-token',
+ refreshToken: 'fake-refresh-token',
+ expiresAt: Date.now() + 3600_000,
+ })),
+ put: vi.fn().mockResolvedValue(undefined),
+ };
+ service = new GoogleDriveService(mockKv, 'client-id', 'client-secret');
+ global.fetch = vi.fn();
+ });
+
+ describe('shareFile', () => {
+ it('sends POST request to share file', async () => {
+ (global.fetch as any).mockResolvedValue({
+ ok: true,
+ json: async () => ({ id: 'permission-id' })
+ });
+
+ const permId = await service.shareFile('driveAccountId', 'fileId', 'test@example.com');
+
+ expect(permId).toBe('permission-id');
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://www.googleapis.com/drive/v3/files/fileId/permissions?sendNotificationEmail=false',
+ expect.objectContaining({
+ method: 'POST',
+ headers: expect.objectContaining({
+ Authorization: 'Bearer fake-access-token',
+ 'Content-Type': 'application/json'
+ }),
+ body: JSON.stringify({
+ role: 'writer',
+ type: 'user',
+ emailAddress: 'test@example.com'
+ })
+ })
+ );
+ });
+ });
+
+ describe('revokeShare', () => {
+ it('sends DELETE request to revoke share', async () => {
+ (global.fetch as any).mockResolvedValue({
+ ok: true
+ });
+
+ await service.revokeShare('driveAccountId', 'fileId', 'permissionId');
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://www.googleapis.com/drive/v3/files/fileId/permissions/permissionId',
+ expect.objectContaining({
+ method: 'DELETE',
+ headers: expect.objectContaining({
+ Authorization: 'Bearer fake-access-token'
+ })
+ })
+ );
+ });
+ });
+
+ describe('copyFile', () => {
+ it('sends POST request to copy file', async () => {
+ (global.fetch as any).mockResolvedValue({
+ ok: true,
+ json: async () => ({ id: 'new-file-id', name: 'Copy' })
+ });
+
+ const file = await service.copyFile('driveAccountId', 'fileId');
+
+ expect(file.id).toBe('new-file-id');
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://www.googleapis.com/drive/v3/files/fileId/copy?fields=id,name,mimeType,size,thumbnailLink,webViewLink,webContentLink,createdTime,modifiedTime',
+ expect.objectContaining({
+ method: 'POST',
+ headers: expect.objectContaining({
+ Authorization: 'Bearer fake-access-token'
+ })
+ })
+ );
+ });
+ });
+
+ describe('trashFile', () => {
+ it('sends PATCH request to trash file', async () => {
+ (global.fetch as any).mockResolvedValue({
+ ok: true
+ });
+
+ await service.trashFile('driveAccountId', 'fileId');
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ 'https://www.googleapis.com/drive/v3/files/fileId',
+ expect.objectContaining({
+ method: 'PATCH',
+ headers: expect.objectContaining({
+ Authorization: 'Bearer fake-access-token',
+ 'Content-Type': 'application/json'
+ }),
+ body: JSON.stringify({
+ trashed: true
+ })
+ })
+ );
+ });
+ });
+});