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
| import { Injectable, inject, signal } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, map } from 'rxjs'; import { environment } from '../../../environment' export interface DriveFile { id: string name: string mimeType: string thumbnailLink?: string // 新增:Google Drive 自動產生的縮圖網址 webViewLink?: string // 新增:Google Drive 的檢視網址 } @Injectable({ providedIn: 'root' }) export class GoogleDriveService { private http = inject(HttpClient); // 替換成你的 Client ID private readonly CLIENT_ID =environment.GOOGLE_CLIENT_ID; // 權限範圍:drive.file 僅能存取此 App 建立的檔案;若要讀取所有檔案請改用 private readonly SCOPES = 'https://www.googleapis.com/auth/drive.file';
private readonly DRIVE_API_URL = 'https://www.googleapis.com/drive/v3';
private tokenClient!: google.accounts.oauth2.TokenClient;
// 使用 Signal 儲存 Token,完美支援 Zoneless 與 OnPush accessToken = signal<string | null>(null);
constructor() { console.log(environment.production ? 'Production' : '開發中'); console.log('GoogleDriveService', environment.GOOGLE_CLIENT_ID); this.initTokenClient(); } // 初始化 GAPI 與 GIS private initTokenClient(): void { // 確保 gis script 已載入 if (typeof google !== 'undefined') { // 初始化 GAPI Client (負責呼叫 Drive API) this.tokenClient = google.accounts.oauth2.initTokenClient({ client_id: this.CLIENT_ID, scope: this.SCOPES, callback: (response) => { if (response.access_token) { this.accessToken.set(response.access_token); } }, }); } }
// 觸發 Google 登入與授權視窗 login(): void { if (!this.tokenClient) this.initTokenClient(); this.tokenClient.requestAccessToken({ prompt: 'consent' }); }
// 登出並撤銷 Token logout(): void { const token = this.accessToken(); if (token) { google.accounts.oauth2.revoke(token, () => { this.accessToken.set(null); }); } }
// 取得檔案列表 /* 你在程式中設定的 SCOPES 是 https://googleapis.com。這個權限只允許你的應用程式讀取「由這個應用程式建立或開啟」的檔案,不會顯示你 Google Drive 裡原本就存在的其他檔案。如果你想測試讀取列表是否成功,請先用你的 uploadFile 上傳一個檔案,再按「讀取檔案列表」就能看到它了。 */ listFiles(): Observable<{ files: DriveFile[] }> { // console.log('取得檔案列表', files) const headers = new HttpHeaders({ Authorization: `Bearer ${this.accessToken()}`, }); const redFilesApi = `${this.DRIVE_API_URL}/files`; const params = { pageSize: '10', fields: 'files(id,name,mimeType,thumbnailLink,webViewLink)', } // console.log('取得檔案列表 params', params) return this.http.get<{ files: DriveFile[] }>(redFilesApi, {headers, params: params,}); } // 刪除檔案或資料夾 deleteFile(fileId: string): Observable<void> { const headers = new HttpHeaders({ Authorization: `Bearer ${this.accessToken()}`, }); const deleteFileApi = `${this.DRIVE_API_URL}/files/${fileId}`; return this.http.delete<void>(deleteFileApi, { headers, }); } // 新增:將檔案設為「知道連結的任何人皆可檢視」,以便分享網址 makeFilePublic(fileId: string): Observable<unknown> { const headers = new HttpHeaders({ Authorization: `Bearer ${this.accessToken()}`, 'Content-Type': 'application/json', }); const makeFilePublicApi = `${this.DRIVE_API_URL}/files/${fileId}/permissions`; return this.http.post( makeFilePublicApi, { role: 'reader', type: 'anyone', }, { headers } ); } // 建立資料夾 (可選填 parentId 指定上層資料夾) createFolder(folderName: string, parentId?: string): Observable<DriveFile> { const headers = new HttpHeaders({ Authorization: `Bearer ${this.accessToken()}`, 'Content-Type': 'application/json', });
const metadata: { name: string; mimeType: string; parents?: string[] } = { name: folderName, mimeType: 'application/vnd.google-apps.folder', };
// 如果有指定上層資料夾 ID,則建立在該資料夾內;未指定則建立在雲端硬碟根目錄 if (parentId) { metadata.parents = [parentId]; }
return this.http.post<DriveFile>(`${this.DRIVE_API_URL}/files`, metadata, { headers, }); }
// 上傳檔案 (Multipart 上傳範例) uploadFile(file: File, folderId?: string): Observable<DriveFile> { const metadata: { name: string; mimeType: string; parents?: string[] } = { name: file.name, mimeType: file.type, };
// 指定上傳目標資料夾 if (folderId) { metadata.parents = [folderId]; }
const formData = new FormData(); formData.append( 'metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }) ); formData.append('file', file);
const headers = new HttpHeaders({ Authorization: `Bearer ${this.accessToken()}`, }); // Multipart 上傳,Request Headers 中的 Content-Type: multipart/form-data const apiUploadFileMultipart = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'; // 單純上傳檔案內容 const apiuploadFileMedia ='https://www.googleapis.com/upload/drive/v3/files?uploadType=media' return this.http.post<DriveFile>( apiUploadFileMultipart, formData, { headers } ); } // 取得圖片的本地預覽網址 (Blob URL) getImagePreviewUrl(fileId: string): Observable<string> { const headers = new HttpHeaders({ Authorization: `Bearer ${this.accessToken()}`, });
return this.http .get(`${this.DRIVE_API_URL}/files/${fileId}`, { headers, params: { alt: 'media' }, // 關鍵參數:要求回傳檔案實際內容而非 JSON responseType: 'blob', // 指定回傳二進位資料 }) .pipe(map((blob) => URL.createObjectURL(blob))); } }
|