Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a download_file() method to EmbedOrUploadBlock() for image/video downloading #209

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
30 changes: 30 additions & 0 deletions notion/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from cached_property import cached_property
from copy import deepcopy
from urllib.request import quote

from .logger import logger
from .maps import property_map, field_map, mapper
Expand Down Expand Up @@ -635,6 +636,35 @@ def upload_file(self, path):
self.source = data["url"]
self.file_id = data["url"][len(S3_URL_PREFIX) :].split("/")[0]

def download_file(self, path):

# "oneliner" helper to safely unwrap lists, see: https://bit.ly/35SUfMK
unwrap = lambda x: unwrap(next(iter(x), None)) \
if '__iter__' in dir(x) and not isinstance(x, str) else x

record_data = self._get_record_data()
sources = record_data.get("properties", {}).get("source", [])
s3_url = unwrap(sources)
filename = s3_url.split("/")[-1]

params = dict(
table="block",
id=self.id,
name=filename,
download="true",
userId=self._client.current_user.id,
cache="v2",
)

url = f"{BASE_URL}signed/" + quote(s3_url, safe="")

# piggyback off of client's session to proper token is included
resp = self._client.session.get(url, params=params, stream=True)

with open(path, "wb") as fp:
for chunk in resp.iter_content(chunk_size=1024):
fp.write(chunk)


class VideoBlock(EmbedOrUploadBlock):

Expand Down