Skip to content

Commit

Permalink
Adds wrapper around uploading a file to Matrix (#1)
Browse files Browse the repository at this point in the history
* WIP upload_files

* Fix type hinting on upload

* allow filename to be specified when uploading

---------

Co-authored-by: Mo Balaa <balaa@fractalnetworks.co>
  • Loading branch information
justin-russell and thebalaa authored Dec 14, 2023
1 parent 5cf40fc commit 9cdc2e0
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions fractal/matrix/async_client.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
import logging
import os
from typing import Any, Dict, List, Optional, Union
from typing import Any, Callable, Dict, List, Optional, Union

import aiohttp
from aiofiles import open as aiofiles_open
from aiofiles import os as aiofiles_os
from fractal.matrix.utils import parse_matrix_id
from nio import (
AsyncClient,
AsyncClientConfig,
JoinError,
MessageDirection,
RegisterResponse,
RoomGetStateEventError,
RoomInviteError,
RoomMessagesError,
RoomPutStateError,
RoomSendResponse,
TransferMonitor,
UploadError,
)
from nio.responses import RegisterErrorResponse

from fractal.matrix.utils import parse_matrix_id

from .exceptions import GetLatestSyncTokenError

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -222,6 +224,35 @@ async def register_with_token(

return res.access_token

async def upload_file(
self,
file_path: str,
monitor: Optional[TransferMonitor] = None,
filename: Optional[str] = None,
) -> str:
"""
Uploads a file to the homeserver.
Args:
file_path (str): The path to the file to upload.
monitor (Optional[TransferMonitor]): A transfer monitor to use. Defaults to None.
Returns:
str: The content uri of the uploaded file.
"""
file_stat = await aiofiles_os.stat(file_path)
logger.info(f"Uploading file: {file_path}")
async with aiofiles_open(file_path, "r+b") as f:
if monitor:
res, _ = await self.upload(
f, filesize=file_stat.st_size, monitor=monitor, filename=filename
)
else:
res, _ = await self.upload(f, filesize=file_stat.st_size, filename=filename)
if isinstance(res, UploadError):
raise Exception("Failed to upload file.")
return res.content_uri


class MatrixClient:
"""
Expand Down

0 comments on commit 9cdc2e0

Please sign in to comment.