Files
dbx-main/app/integrations/google_drive.py
T
king 52ca60df9a feat(project): 파일 끌어 놓기 → 구글 드라이브 링크, 필터 켠 보드 카드 순서 버그 수정
- 설명란·세부 업무 목록·보드 카드에 파일을 놓으면 드라이브 프로젝트/섹션/업무/세부 업무
  폴더에 올리고 설명에 "파일 이름.확장자" 링크(PROJECT_DRIVE_FOLDER_ID)
- 설명에서 링크를 지우면 우리가 올린 파일만 드라이브 휴지통, 되살리면 복구
- 브라우저별 필터(localStorage)가 켜져 있으면 섹션 안 카드가 제자리로 돌아가던 버그 —
  필터 중에도 순서 변경 허용, 숨은 업무는 제자리. 카드 속 이미지 끌기 오인 방지

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 23:19:16 +09:00

187 lines
9.1 KiB
Python

"""Google 드라이브 — 업무 파일 올리기(설명란·보드 카드·세부 업무에 파일 끌어 놓기, 2026-10-19).
인증은 google_slides 와 같은 설정(서비스 계정 우선, 없으면 OAuth 리프레시 토큰 — Drive 권한 포함)을 쓴다.
- 최상위 폴더 `PROJECT_DRIVE_FOLDER_ID`(기본 = 업무 파일 폴더). 그 아래 `프로젝트/섹션/업무/세부 업무` 폴더를 이름으로
찾고 없으면 만든다(휴지통 폴더 제외). 같은 경로를 두 사람이 동시에 만들지 않게 폴더 찾기·만들기는 한 번에 하나씩.
- 올린 파일은 appProperties `dbxTaskId` = 업무 id — 설명란에서 링크를 지우면 **우리가 올린 파일만** 휴지통으로 보낸다
(다른 사람이 붙여 넣은 드라이브 링크는 건드리지 않음). 링크를 되살리면(되돌리기·잘라 붙이기) 휴지통에서 꺼낸다.
휴지통 파일은 드라이브가 30일 뒤 지운다.
- 서비스 계정은 내 드라이브 저장 용량이 없어 "공유 드라이브" 폴더여야 올라간다(OAuth 토큰이면 그 사용자 드라이브도 됨).
- 비밀값(키/토큰)은 로그·화면에 절대 출력하지 않는다. 라이브러리·설정이 없으면 `enabled = False`.
"""
from __future__ import annotations
import os
import re
import threading
from typing import Any, BinaryIO, Iterable
from app.integrations.google_slides import GoogleSlidesClient, _friendly
DEFAULT_FOLDER_ID = "1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG"
FOLDER_MIME = "application/vnd.google-apps.folder"
TASK_KEY = "dbxTaskId"
CHUNK = 8 * 1024 * 1024
# 설명란 링크에서 드라이브 파일 id — 우리가 넣는 링크 모양(https://drive.google.com/file/d/<id>/view)
FILE_LINK_RE = re.compile(r"https://drive\.google\.com/file/d/([A-Za-z0-9_-]{10,})")
# 폴더 찾기·만들기는 한 번에 하나(같은 폴더가 두 개 생기지 않게). 파일 올리기·휴지통은 호출마다 따로 만든
# 서비스 객체로(googleapiclient 의 HTTP 는 스레드 안전하지 않다) — 큰 파일이 다른 사람 업로드를 막지 않게.
_FOLDER_LOCK = threading.Lock()
class GoogleDriveError(RuntimeError):
"""화면에 보여도 되는 사유(비밀값 없음)."""
def root_folder_id() -> str:
return (os.getenv("PROJECT_DRIVE_FOLDER_ID") or "").strip() or DEFAULT_FOLDER_ID
def file_url(file_id: str) -> str:
return f"https://drive.google.com/file/d/{file_id}/view"
def file_ids_in(html: str) -> set[str]:
"""설명 HTML 안의 드라이브 파일 링크 id 들."""
return set(FILE_LINK_RE.findall(html or ""))
def folder_name(name: Any) -> str:
"""폴더 이름 — 앞뒤 공백·줄바꿈 정리, 너무 길면 자름, 비면 "(이름 없음)"."""
s = re.sub(r"\s+", " ", str(name or "")).strip()[:120]
return s or "(이름 없음)"
def _q(value: str) -> str:
"""Drive 검색어 따옴표 안 글자(역슬래시·작은따옴표 이스케이프)."""
return value.replace("\\", "\\\\").replace("'", "\\'")
class GoogleDriveFiles(GoogleSlidesClient):
"""google_slides 의 인증(서비스 계정·OAuth)을 그대로 쓰고 Drive 만 연다."""
def __init__(self) -> None: # noqa: D107 — 부모 __init__ 대신(Slides 서비스는 만들지 않음)
self.enabled = False
self.reason = ""
self.auth_mode = ""
self._creds: Any = None
try:
import googleapiclient.discovery # noqa: F401
import googleapiclient.http # noqa: F401
except ImportError:
self.reason = "google-api-python-client 미설치"
return
creds = self._service_account_creds()
if creds is None:
creds = self._oauth_creds()
if creds is None:
if not self.reason:
self.reason = "Google 인증 미설정(GOOGLE_SHEETS_CREDENTIALS 또는 GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN 필요)"
return
self._creds = creds
self.enabled = True
def _service(self) -> Any:
from googleapiclient.discovery import build
return build("drive", "v3", credentials=self._creds, cache_discovery=False)
def _check(self) -> None:
if not self.enabled:
raise GoogleDriveError(self.reason or "Google 드라이브 연동이 꺼져 있습니다.")
# ────────────────────────────────────────────────
def ensure_folder_path(self, names: Iterable[str], *, root: str | None = None) -> str:
"""root 아래 names 순서대로 폴더를 찾거나 만들고 마지막 폴더 id."""
self._check()
parent = root or root_folder_id()
with _FOLDER_LOCK:
try:
drive = self._service()
for raw in names:
name = folder_name(raw)
q = (f"'{_q(parent)}' in parents and name = '{_q(name)}' and mimeType = '{FOLDER_MIME}' "
"and trashed = false")
res = drive.files().list(
q=q, fields="files(id)", pageSize=1, supportsAllDrives=True, includeItemsFromAllDrives=True,
corpora="allDrives", orderBy="createdTime",
).execute()
found = res.get("files") or []
if found:
parent = found[0]["id"]
continue
parent = drive.files().create(
body={"name": name, "mimeType": FOLDER_MIME, "parents": [parent]},
fields="id", supportsAllDrives=True,
).execute()["id"]
except GoogleDriveError:
raise
except Exception as exc: # noqa: BLE001
raise GoogleDriveError(_friendly_drive(exc)) from None
return parent
def upload(self, *, folder_id: str, name: str, stream: BinaryIO, mimetype: str, task_id: int) -> dict[str, Any]:
"""폴더에 파일 하나 → {id, name, url}. 이름은 원래 파일 이름.확장자 그대로."""
self._check()
from googleapiclient.http import MediaIoBaseUpload
try:
media = MediaIoBaseUpload(stream, mimetype=mimetype or "application/octet-stream", chunksize=CHUNK,
resumable=True)
meta = {"name": name, "parents": [folder_id], "appProperties": {TASK_KEY: str(int(task_id))}}
f = self._service().files().create(body=meta, media_body=media, fields="id,name",
supportsAllDrives=True).execute()
except Exception as exc: # noqa: BLE001
raise GoogleDriveError(_friendly_drive(exc)) from None
return {"id": f["id"], "name": f.get("name") or name, "url": file_url(f["id"])}
def ours(self, file_id: str) -> dict[str, Any] | None:
"""우리가 올린 파일이면 {trashed, task_id}, 아니면(남의 파일·없는 파일·권한 없음) None."""
self._check()
try:
f = self._service().files().get(fileId=file_id, fields="trashed,appProperties",
supportsAllDrives=True).execute()
except Exception: # noqa: BLE001 — 지워졌거나 볼 수 없는 파일은 건드리지 않는다
return None
tid = (f.get("appProperties") or {}).get(TASK_KEY)
if not tid:
return None
return {"trashed": bool(f.get("trashed")), "task_id": tid}
def set_trashed(self, file_id: str, trashed: bool) -> None:
self._check()
try:
self._service().files().update(fileId=file_id, body={"trashed": bool(trashed)},
supportsAllDrives=True).execute()
except Exception as exc: # noqa: BLE001
raise GoogleDriveError(_friendly_drive(exc)) from None
def _friendly_drive(exc: Exception) -> str:
status = getattr(getattr(exc, "resp", None), "status", None)
text = str(exc)
if "storageQuotaExceeded" in text or "do not have storage quota" in text:
return ("서비스 계정은 내 드라이브에 파일을 올릴 수 없습니다 — 업무 파일 폴더를 공유 드라이브에 두거나 "
"OAuth 토큰(GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN)을 쓰세요.")
if status == 404:
return "업무 파일 폴더를 찾을 수 없습니다(PROJECT_DRIVE_FOLDER_ID·폴더 공유 권한 확인)."
if status == 403 and "insufficient" not in text.lower():
return "Google 드라이브 접근이 거부되었습니다(폴더 편집 권한·Drive API 사용 설정 확인)."
return _friendly(exc).replace("Google 슬라이드 처리 실패", "Google 드라이브 처리 실패")
_CLIENT: GoogleDriveFiles | None = None
_CLIENT_LOCK = threading.Lock()
def get_client() -> GoogleDriveFiles:
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인 — .env 를 고치고 재시작 없이도 사유가 갱신되게)."""
global _CLIENT
with _CLIENT_LOCK:
if _CLIENT is None or not _CLIENT.enabled:
_CLIENT = GoogleDriveFiles()
return _CLIENT