Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 44 additions & 3 deletions docs/fsspec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
---------------

Expand All @@ -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
---------------
Expand Down
14 changes: 14 additions & 0 deletions docs/upgrading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <fsspec>` 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
-----------------------------

Expand Down
230 changes: 206 additions & 24 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
from pydrive2.files import (
FOLDER_MIME_TYPE,
ApiRequestError,
FileNotDownloadableError,
_FileMetadataPages,
)
from pydrive2.fs.cache import DirectoryCache
Expand All @@ -47,8 +48,10 @@
logger = logging.getLogger(__name__)

_INFO_FIELDS = "mimeType,size,md5Checksum"
_SHORTCUT_FIELDS = "shortcutDetails(targetId,targetMimeType)"
Comment thread
shcheklein marked this conversation as resolved.
Resolved
_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
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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):
Expand All @@ -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]
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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)
Comment thread
shcheklein marked this conversation as resolved.
Resolved
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

Expand Down Expand Up @@ -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)(
Expand Down
Loading