Skip to content

Commit ff4076c

Browse files
Merge pull request #226 from adamtheturtle/simpler-upload
Simplify upload process by removing duplication
2 parents 51ea93f + df1db48 commit ff4076c

File tree

1 file changed

+29
-36
lines changed

1 file changed

+29
-36
lines changed

src/_notion_scripts/upload.py

Lines changed: 29 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,34 @@
1717
from ultimate_notion.blocks import Block
1818
from ultimate_notion.blocks import Image as UnoImage
1919
from ultimate_notion.blocks import Video as UnoVideo
20+
from ultimate_notion.file import UploadedFile
2021
from ultimate_notion.obj_api.blocks import Block as UnoObjAPIBlock
2122

2223

24+
@beartype
25+
def _upload_local_file(
26+
*,
27+
url: str,
28+
session: Session,
29+
) -> UploadedFile | None:
30+
"""
31+
Upload a local file and return the uploaded file object.
32+
"""
33+
parsed = urlparse(url=url)
34+
if parsed.scheme != "file":
35+
return None
36+
37+
file_path = Path(url2pathname(pathname=parsed.path))
38+
with file_path.open(mode="rb") as f:
39+
uploaded_file = session.upload(
40+
file=f,
41+
file_name=file_path.name,
42+
)
43+
44+
uploaded_file.wait_until_uploaded()
45+
return uploaded_file
46+
47+
2348
@beartype
2449
def _block_from_details(
2550
*,
@@ -32,42 +57,10 @@ def _block_from_details(
3257
"""
3358
block = Block.wrap_obj_ref(UnoObjAPIBlock.model_validate(obj=details))
3459

35-
if isinstance(block, UnoImage):
36-
parsed = urlparse(url=block.url)
37-
if parsed.scheme == "file":
38-
file_path = Path(url2pathname(pathname=parsed.path))
39-
with file_path.open(mode="rb") as f:
40-
uploaded_file = session.upload(
41-
file=f,
42-
file_name=file_path.name,
43-
)
44-
45-
uploaded_file.wait_until_uploaded()
46-
return UnoImage(file=uploaded_file, caption=block.caption)
47-
elif isinstance(block, UnoVideo):
48-
parsed = urlparse(url=block.url)
49-
if parsed.scheme == "file":
50-
file_path = Path(url2pathname(pathname=parsed.path))
51-
with file_path.open(mode="rb") as f:
52-
uploaded_file = session.upload(
53-
file=f,
54-
file_name=file_path.name,
55-
)
56-
57-
uploaded_file.wait_until_uploaded()
58-
return UnoVideo(file=uploaded_file, caption=block.caption)
59-
elif isinstance(block, UnoAudio):
60-
parsed = urlparse(url=block.url)
61-
if parsed.scheme == "file":
62-
file_path = Path(url2pathname(pathname=parsed.path))
63-
with file_path.open(mode="rb") as f:
64-
uploaded_file = session.upload(
65-
file=f,
66-
file_name=file_path.name,
67-
)
68-
69-
uploaded_file.wait_until_uploaded()
70-
return UnoAudio(file=uploaded_file, caption=block.caption)
60+
if isinstance(block, (UnoImage, UnoVideo, UnoAudio)):
61+
uploaded_file = _upload_local_file(url=block.url, session=session)
62+
if uploaded_file is not None:
63+
return block.__class__(file=uploaded_file, caption=block.caption)
7164

7265
return block
7366

0 commit comments

Comments
 (0)