|
| 1 | +from __future__ import annotations |
| 2 | +from jupyter_ydoc.ybasedoc import YBaseDoc |
| 3 | +from typing import TYPE_CHECKING |
| 4 | + |
| 5 | +if TYPE_CHECKING: |
| 6 | + from typing import Callable, Literal |
| 7 | + from jupyter_server_fileid.manager import BaseFileIdManager |
| 8 | + from ..rooms import YRoomManager |
| 9 | + |
| 10 | + |
| 11 | +class JCollabAPI: |
| 12 | + """ |
| 13 | + Provides the Python API provided by `jupyter_collaboration~=4.0` under |
| 14 | + `self.settings["jupyter_server_ydoc"]`. |
| 15 | + """ |
| 16 | + fileid_manager: BaseFileIdManager |
| 17 | + yroom_manager: YRoomManager |
| 18 | + |
| 19 | + def __init__(self, get_fileid_manager: Callable[[], BaseFileIdManager], yroom_manager: YRoomManager): |
| 20 | + self._get_fileid_manager = get_fileid_manager |
| 21 | + self.yroom_manager = yroom_manager |
| 22 | + |
| 23 | + @property |
| 24 | + def fileid_manager(self) -> BaseFileIdManager: |
| 25 | + return self._get_fileid_manager() |
| 26 | + |
| 27 | + async def get_document( |
| 28 | + self, |
| 29 | + *, |
| 30 | + path: str | None = None, |
| 31 | + content_type: str | None = None, |
| 32 | + file_format: Literal["json", "text"] | None = None, |
| 33 | + room_id: str | None = None, |
| 34 | + copy: bool = True, |
| 35 | + ) -> YBaseDoc: |
| 36 | + """ |
| 37 | + Returns the Jupyter YDoc for a collaborative room. |
| 38 | +
|
| 39 | + You need to provide either a ``room_id`` or the ``path``, |
| 40 | + the ``content_type`` and the ``file_format``. |
| 41 | +
|
| 42 | + The `copy` argument is ignored by `jupyter_server_documents`. |
| 43 | + """ |
| 44 | + |
| 45 | + # Raise exception if required arguments are not given |
| 46 | + if room_id is None and (path is None or content_type is None or file_format is None): |
| 47 | + raise ValueError( |
| 48 | + "You need to provide either a ``room_id`` or the ``path``, the ``content_type`` and the ``file_format``." |
| 49 | + ) |
| 50 | + |
| 51 | + # Compute room_id if not given |
| 52 | + if room_id is None: |
| 53 | + file_id = self.fileid_manager.index(path) |
| 54 | + room_id = f"{file_format}:{content_type}:{file_id}" |
| 55 | + |
| 56 | + # Get or create room using `room_id` |
| 57 | + room = self.yroom_manager.get_room(room_id) |
| 58 | + if not room: |
| 59 | + raise ValueError( |
| 60 | + f"Could not get room using room ID '{room_id}'." |
| 61 | + ) |
| 62 | + |
| 63 | + # Return the Jupyter YDoc once ready |
| 64 | + return await room.get_jupyter_ydoc() |
0 commit comments