Skip to content

Commit

Permalink
WIP upload_files
Browse files Browse the repository at this point in the history
  • Loading branch information
thebalaa committed Dec 12, 2023
1 parent 5cf40fc commit ec05b06
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions fractal/matrix/async_client.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
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,
Expand All @@ -14,11 +17,10 @@
RoomMessagesError,
RoomPutStateError,
RoomSendResponse,
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,29 @@ async def register_with_token(

return res.access_token

async def upload_file(
self, file_path: str, monitor_func: Optional[Callable[[str, str], None]]
) -> str:
"""
Uploads a file to the homeserver.
Args:
file_path (str): The path to the file to upload.
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_func:
res, _ = await self.upload(f, filesize=file_stat.st_size, monitor=monitor_func)
else:
res, _ = await self.upload(f, filesize=file_stat.st_size)
if isinstance(res, UploadError):
raise Exception("Failed to upload file.")
return res.content_uri


class MatrixClient:
"""
Expand Down

0 comments on commit ec05b06

Please sign in to comment.