import re import urllib.parse def is_google_drive_url(url: str) -> bool: # noqa: GR005 -- public API accepts both call styles parsed = urllib.parse.urlparse(url) return parsed.hostname in ["drive.google.com", "docs.google.com"] def _parse_google_drive_folder_id(*, url: str) -> str | None: parsed = urllib.parse.urlparse(url) if not is_google_drive_url(url=url): return None match = re.match(r"^/drive/folders/([-\w]{25,})(?:/|$)", parsed.path) return match.group(1) if match else None def parse_url(url: str) -> tuple[str | None, bool]: # noqa: GR005 -- public API accepts both call styles """Parse URLs especially for Google Drive links. file_id: ID of file on Google Drive. is_download_link: Flag if it is download link of Google Drive. """ parsed = urllib.parse.urlparse(url) query = urllib.parse.parse_qs(parsed.query) is_gdrive = is_google_drive_url(url=url) is_download_link = parsed.path.endswith("/uc") if not is_gdrive: return None, is_download_link file_id = None if "id" in query: file_ids = query["id"] if len(file_ids) == 1: file_id = file_ids[0] else: patterns = [ r"^/file/d/([-\w]+)(?:/(?:edit|view|preview))?/?$", r"^/file/u/[0-9]+/d/([-\w]+)(?:/(?:edit|view|preview))?/?$", r"^/document/d/(.*?)/(edit|htmlview|view)$", r"^/document/u/[0-9]+/d/(.*?)/(edit|htmlview|view)$", r"^/presentation/d/(.*?)/(edit|htmlview|view)$", r"^/presentation/u/[0-9]+/d/(.*?)/(edit|htmlview|view)$", r"^/spreadsheets/d/(.*?)/(edit|htmlview|view)$", r"^/spreadsheets/u/[0-9]+/d/(.*?)/(edit|htmlview|view)$", ] for pattern in patterns: match = re.match(pattern, parsed.path) if match: file_id = match.groups()[0] break return file_id, is_download_link