diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..69d33c9e 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -84,6 +84,47 @@ visits every matching folder. If a file and a folder both match the starting path, the default ``withdirs=False`` lists only files inside the folder. +.. _fsspec-google-files: + +Google files and shortcuts +-------------------------- + +Docs, Sheets, Slides and Drawings have no stored file on Drive. Reads +export them the way Drive's web app and rclone do: Docs as ``.docx``, +Sheets as ``.xlsx``, Slides as ``.pptx`` and Drawings as ``.svg``. +``cat_file()``, ``open()`` and ``get()`` all return the exported bytes. +Drive exports files up to 10 MB. + +Listings show Drive's names, so ``cat_file()`` reads every path that +``ls()`` or ``find()`` returns. When ``get()`` names a local file after +the Drive item, it adds the extension. A local name of its own is used as +given: + +.. code-block:: python + + fs.get("root/reports", "local/", recursive=True) + # local/reports/budget.xlsx, local/reports/summary.docx, ... + + fs.get("root/reports/summary", "local/notes") # writes local/notes + +If two items get the same local name, such as a Doc named ``summary`` and +a file named ``summary.docx``, ``get()`` keeps the first and skips the +other with a warning. + +Forms, Sites, Maps and other Google types have no export. A recursive +``get()`` skips them and logs a warning. Reading one by its path raises +:class:`~pydrive2.files.FileNotDownloadableError`. + +A shortcut to a file reads as its target, under the shortcut's name. +Shortcuts to folders are not followed, because following them can visit a +folder twice or loop. A recursive ``get()`` skips them with a warning, as +it does a shortcut whose target is deleted or not shared with the +account. Reading either kind by its path raises +``FileNotDownloadableError``. + +To read a Doc in another format, use the core API, for example +``drive.CreateFile({"id": doc_id}).GetContentString(mimetype="text/plain")``. + Directory cache --------------- @@ -104,9 +145,9 @@ Trashed items Drive queries for directory entries exclude trashed items. For a bare file ID, ``exists()`` returns false and ``info()`` raises ``FileNotFoundError`` -when the item is in the trash. Opening or downloading by ID requests the -content directly. Drive can still serve a trashed file this way if the -account has access. +when the item is in the trash. Opening by ID reads the item's type once, +then requests the content. Drive can still serve a trashed file this way +if the account has access. Failed requests --------------- diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 9f28692a..8b1ae6e3 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -74,6 +74,20 @@ Filesystem listings and path lookups read Drive metadata pages directly. If your application intercepts requests through ``GoogleDrive.ListFile()``, use the HTTP transport to observe those filesystem requests. +Google files in the filesystem +------------------------------ + +The :doc:`fsspec filesystem ` exports Docs, Sheets, Slides and +Drawings as ``.docx``, ``.xlsx``, ``.pptx`` and ``.svg``, as Drive's web +app and rclone do. PyDrive2 1.x exported them as plain text, which Drive +offers only for Docs and Slides. ``get()`` adds the extension to local +names that it takes from Drive. A recursive ``get()`` follows shortcuts +to files and skips Forms and shortcuts to folders with a warning. See +:ref:`fsspec-google-files`. + +The core API is unchanged. To read a Doc's text, call +``GetContentString(mimetype="text/plain")`` on the file. + Drive API fields and requests ----------------------------- diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index dfac751e..ae7c075c 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -38,6 +38,7 @@ from pydrive2.files import ( FOLDER_MIME_TYPE, ApiRequestError, + FileNotDownloadableError, _FileMetadataPages, ) from pydrive2.fs.cache import DirectoryCache @@ -47,8 +48,10 @@ logger = logging.getLogger(__name__) _INFO_FIELDS = "mimeType,size,md5Checksum" +_SHORTCUT_FIELDS = "shortcutDetails(targetId,targetMimeType)" _LIST_FIELDS = ( - f"nextPageToken,incompleteSearch,files(id,name,parents,{_INFO_FIELDS})" + "nextPageToken,incompleteSearch," + f"files(id,name,parents,{_INFO_FIELDS},{_SHORTCUT_FIELDS})" ) _NAME_FIELDS = "nextPageToken,incompleteSearch,files(id,name,parents,mimeType)" _MAX_QUERY_TERMS = 50 @@ -71,6 +74,30 @@ for suffix in ("", ".readonly", ".metadata", ".metadata.readonly") } _APP_DATA_SCOPES = {_DRIVE_SCOPE + ".appdata", _DRIVE_SCOPE + ".appfolder"} +_SHORTCUT_MIME_TYPE = "application/vnd.google-apps.shortcut" +_GOOGLE_MIME_PREFIX = "application/vnd.google-apps." +# rclone's default --drive-export-formats: the extension and export type. +_EXPORT_FORMATS = { + "application/vnd.google-apps.document": ( + ".docx", + ( + "application/vnd.openxmlformats-officedocument" + ".wordprocessingml.document" + ), + ), + "application/vnd.google-apps.spreadsheet": ( + ".xlsx", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ), + "application/vnd.google-apps.presentation": ( + ".pptx", + ( + "application/vnd.openxmlformats-officedocument" + ".presentationml.presentation" + ), + ), + "application/vnd.google-apps.drawing": (".svg", "image/svg+xml"), +} COMMON_SETTINGS = { "get_refresh_token": True, @@ -90,10 +117,14 @@ class _ListedChild: ambiguous: bool size: int | None checksum: str | None + mime_type: str | None = None + target_id: str | None = None + target_mime_type: str | None = None @classmethod def from_drive(cls, parent, item): size = item.get("size") + target = item.get("shortcutDetails") or {} return cls( id=item["id"], parent=parent, @@ -102,6 +133,9 @@ def from_drive(cls, parent, item): ambiguous=len(item.get("parents", ())) > 1, size=int(size) if size is not None else None, checksum=item.get("md5Checksum"), + mime_type=item["mimeType"], + target_id=target.get("targetId"), + target_mime_type=target.get("targetMimeType"), ) def entry(self, name, detail=True): @@ -112,6 +146,44 @@ def entry(self, name, detail=True): return _regular_file_entry(name, self.size, self.checksum) +@dataclass(frozen=True, slots=True) +class _Download: + """What a read of a path downloads, and how Drive exports it.""" + + path: str + item_id: str + mime_type: str | None + export_type: str | None = None + extension: str = "" + shortcut: bool = False + + +@dataclass(slots=True) +class _GetCall: + """One get() call, which names local files after remote ones.""" + + recursive: bool + written: set[str] = field(default_factory=set) + + +def _download_of(path, item_id, mime_type, target_id=None, target_type=None): + shortcut = mime_type == _SHORTCUT_MIME_TYPE + if shortcut: + if target_type == FOLDER_MIME_TYPE: + raise FileNotDownloadableError(f"{path} is a shortcut to a folder") + item_id, mime_type = target_id, target_type + if mime_type in _EXPORT_FORMATS: + extension, export_type = _EXPORT_FORMATS[mime_type] + return _Download( + path, item_id, mime_type, export_type, extension, shortcut + ) + if mime_type and mime_type.startswith(_GOOGLE_MIME_PREFIX): + raise FileNotDownloadableError( + f"Drive has no download for {path} ({mime_type})" + ) + return _Download(path, item_id, mime_type, shortcut=shortcut) + + @dataclass class _PathMatch: folders: list[str] @@ -606,6 +678,8 @@ def __init__( self._dirs = DirectoryCache(self.root) self._mount_lock = threading.RLock() self._root_lock = threading.RLock() + # The get() call running in this thread, if any. + self._get_call = threading.local() self._root_metadata: dict = {} self._creation_locks: WeakValueDictionary = WeakValueDictionary() self._forget_new_ids() @@ -881,6 +955,69 @@ def _lookup_item(self, path): ) return item_id, metadata.get("mimeType") == FOLDER_MIME_TYPE + def _readable(self, path, *, allow_trashed=False): + """The download a read of the path makes, from its name lookup.""" + _, base = self._split_mounted_path(path) + if base or self.root in _ROOT_ALIASES: + match, _ = self._lookup_path(base) + item_id = _select_item_id(path, match.ids) + if item_id in match.folders: + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), path + ) + item = next(item for item in match.files if item.id == item_id) + return _download_of( + path, + item_id, + item.mime_type, + item.target_id, + item.target_mime_type, + ) + # A filesystem opened at a file ID knows its type from the root. + metadata = self._get_root_metadata() + if metadata.get("trashed") and not allow_trashed: + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), path + ) + mime_type = metadata.get("mimeType") + if mime_type == FOLDER_MIME_TYPE: + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), path + ) + if mime_type != _SHORTCUT_MIME_TYPE: + return _download_of(path, self.root, mime_type) + # Only a shortcut opened by its own ID needs a request for its target. + root = self.client.CreateFile({"id": self.root}) + _gdrive_retry_repeatable(root.FetchMetadata)(fields=_SHORTCUT_FIELDS) + target = root.get("shortcutDetails", {}) + return _download_of( + path, + self.root, + mime_type, + target.get("targetId"), + target.get("targetMimeType"), + ) + + def _download_file(self, download): + # The known type sends a Google file straight to its export. + metadata = {"id": download.item_id} + if download.mime_type: + metadata["mimeType"] = download.mime_type + # it does not create a file on the remote + return self.client.CreateFile(metadata) + + @contextmanager + def _missing_target(self, download): + try: + yield + except ApiRequestError as exc: + if download.shortcut and _is_not_found(exc): + raise FileNotDownloadableError( + f"{download.path} is a shortcut to a file that is gone " + "or not shared with this account" + ) from exc + raise + def _forget_new_ids(self): self._new_ids: dict[str, deque[str]] = { "files": deque(), @@ -1345,25 +1482,70 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): destination_parent, dst_name, parent_path=parent_path ) + def get(self, rpath, lpath, recursive=False, **kwargs): + """Copy files to local paths, exporting Google files as rclone does. + + Google Docs, Sheets, Slides and Drawings are saved as .docx, .xlsx, + .pptx and .svg files. When the local name comes from the remote + name, it gets that extension. A recursive copy follows shortcuts to + files and skips what Drive has no download for, such as a Google + Form or a shortcut to a folder. When two items get the same local + name, the first one is kept and the other is skipped with a warning. + """ + outer = getattr(self._get_call, "current", None) + self._get_call.current = _GetCall(recursive) + try: + return super().get(rpath, lpath, recursive=recursive, **kwargs) + finally: + self._get_call.current = outer + def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): - with _translate_not_found(rpath): - item_id, is_folder = self._lookup_item(rpath) - if is_folder: - os.makedirs(lpath, exist_ok=True) - return None - parent = os.path.dirname(os.fspath(lpath)) - if parent: - os.makedirs(parent, exist_ok=True) - return self._gdrive_get_file( - item_id, lpath, callback=callback, block_size=block_size + call = getattr(self._get_call, "current", None) + try: + with _translate_not_found(rpath): + self._get_readable_file( + rpath, os.fspath(lpath), callback, block_size, call + ) + except FileNotDownloadableError as exc: + if not (call and call.recursive): + raise + logger.warning("Skipping %s: %s", rpath, exc) + + def _get_readable_file(self, rpath, lpath, callback, block_size, call): + try: + download = self._readable(rpath) + except IsADirectoryError: + os.makedirs(lpath, exist_ok=True) + return + if call is not None: + remote_name = posixpath.basename(rpath.rstrip("/")) + if os.path.basename(lpath) == remote_name: + lpath += download.extension + # A Doc named "a" and a file named "a.docx" share a local name. + if lpath in call.written: + logger.warning( + "Skipping %s: another item was saved as %s", rpath, lpath + ) + return + parent = os.path.dirname(lpath) + if parent: + os.makedirs(parent, exist_ok=True) + with self._missing_target(download): + self._gdrive_get_file( + download, lpath, callback=callback, block_size=block_size ) + if call is not None: + call.written.add(lpath) - def _gdrive_get_file(self, item_id, lpath, callback=None, block_size=None): - param = {"id": item_id} - # it does not create a file on the remote - gdrive_file = self.client.CreateFile(param) + def _gdrive_get_file( + self, download, lpath, callback=None, block_size=None + ): + gdrive_file = self._download_file(download) - options = {"acknowledge_abuse": self._acknowledge_abuse} + options = { + "acknowledge_abuse": self._acknowledge_abuse, + "mimetype": download.export_type, + } if block_size: options["chunksize"] = block_size @@ -1392,14 +1574,14 @@ def _open(self, path, mode, block_size=None, **kwargs): self._split_file_path(path) return GDriveBufferedWriter(self, path) with _translate_not_found(path): - item_id = self._get_item_id(path) - return self._gdrive_open_file(item_id, block_size) - - def _gdrive_open_file(self, item_id, block_size=None): - param = {"id": item_id} - # it does not create a file on the remote - gdrive_file = self.client.CreateFile(param) - options = {} + # Drive serves a trashed file by its ID, so a read by ID does too. + download = self._readable(path, allow_trashed=True) + with self._missing_target(download): + return self._gdrive_open_file(download, block_size) + + def _gdrive_open_file(self, download, block_size=None): + gdrive_file = self._download_file(download) + options = {"mimetype": download.export_type} if block_size not in (None, "default") and block_size > 0: options["chunksize"] = block_size fd = _gdrive_retry_repeatable(gdrive_file.GetContentIOBuffer)( diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..25a676d9 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -13,6 +13,7 @@ from googleapiclient.http import HttpRequest from pydrive2.drive import GoogleDrive +from pydrive2.files import FileNotDownloadableError from pydrive2.fs import GDriveFileSystem from pydrive2.test.test_util import ( GDRIVE_USER_CREDENTIALS_DATA, @@ -734,3 +735,70 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( fs.cp_file(f"root/{workspace_files}-link", remote_dir + "/copy") assert len(lost) == 1 assert items_below(fs_factory()[0], remote_dir) == ["copy"] + + +@pytest.fixture +def google_files(fs, remote_dir): + """A folder of Google files, a plain file and two shortcuts.""" + fs.pipe_file(remote_dir + "/data.txt", b"data") + name = posixpath.basename(remote_dir) + (folder,) = fs.client.ListFile({"q": f"name = '{name}'"}).GetList() + + def create(name, kind, **metadata): + item = fs.client.CreateFile( + { + "name": name, + "mimeType": f"application/vnd.google-apps.{kind}", + "parents": [folder["id"]], + **metadata, + } + ) + pydrive_retry(item.Upload) + return item + + document = create("doc", "document") + create("sheet", "spreadsheet") + create("slides", "presentation") + create("drawing", "drawing") + create("form", "form") + create( + "doc-link", "shortcut", shortcutDetails={"targetId": document["id"]} + ) + # The shortcut points at the folder it is in. + create( + "folder-link", "shortcut", shortcutDetails={"targetId": folder["id"]} + ) + return remote_dir + + +def test_recursive_get_after_google_files_writes_office_files_and_skips_the_rest( + fs, tmp_path, google_files, caplog +): + target = tmp_path / "target" + fs.get(google_files, str(target), recursive=True) + office = ["doc-link.docx", "doc.docx", "sheet.xlsx", "slides.pptx"] + assert sorted(os.listdir(target)) == sorted( + [*office, "data.txt", "drawing.svg"] + ) + assert {name: (target / name).read_bytes()[:2] for name in office} == ( + dict.fromkeys(office, b"PK") + ) + assert b"