|
1 | 1 | import json |
| 2 | +import mimetypes |
| 3 | +import os |
| 4 | +from typing import Dict, Optional |
| 5 | +from urllib.parse import unquote |
2 | 6 |
|
3 | | -from jupyter_server.base.handlers import APIHandler |
| 7 | +from jupyter_server.base.handlers import JupyterHandler |
4 | 8 | import tornado |
5 | 9 |
|
6 | | -class RouteHandler(APIHandler): |
7 | | - # The following decorator should be present on all verb methods (head, get, post, |
8 | | - # patch, put, delete, options) to ensure only authorized user can request the |
9 | | - # Jupyter server |
| 10 | + |
| 11 | +# Maximum avatar file size (5MB) |
| 12 | +MAX_AVATAR_SIZE = 5 * 1024 * 1024 |
| 13 | + |
| 14 | +# Module-level cache: {persona_id: avatar_path} |
| 15 | +# This is populated when personas are initialized/refreshed |
| 16 | +_avatar_cache: Dict[str, str] = {} |
| 17 | + |
| 18 | + |
| 19 | +def build_avatar_cache(persona_managers: dict) -> None: |
| 20 | + """ |
| 21 | + Build the avatar cache from all persona managers. |
| 22 | +
|
| 23 | + This should be called when personas are initialized or refreshed. |
| 24 | + """ |
| 25 | + global _avatar_cache |
| 26 | + _avatar_cache = {} |
| 27 | + |
| 28 | + for room_id, persona_manager in persona_managers.items(): |
| 29 | + for persona in persona_manager.personas.values(): |
| 30 | + try: |
| 31 | + avatar_path = persona.defaults.avatar_path |
| 32 | + if avatar_path and os.path.exists(avatar_path): |
| 33 | + _avatar_cache[persona.id] = avatar_path |
| 34 | + except Exception: |
| 35 | + # Skip personas with invalid avatar paths |
| 36 | + continue |
| 37 | + |
| 38 | + |
| 39 | +def clear_avatar_cache() -> None: |
| 40 | + """Clear the avatar cache. Called during persona refresh.""" |
| 41 | + global _avatar_cache |
| 42 | + _avatar_cache = {} |
| 43 | + |
| 44 | + |
| 45 | +class AvatarHandler(JupyterHandler): |
| 46 | + """ |
| 47 | + Handler for serving persona avatar files. |
| 48 | +
|
| 49 | + Looks up avatar files by persona ID and serves the image file |
| 50 | + with appropriate content-type headers. |
| 51 | + """ |
| 52 | + |
10 | 53 | @tornado.web.authenticated |
11 | | - def get(self): |
12 | | - self.finish(json.dumps({ |
13 | | - "data": "This is /jupyter-ai-persona-manager/get-example endpoint!" |
14 | | - })) |
| 54 | + async def get(self, persona_id: str): |
| 55 | + """Serve an avatar file by persona ID.""" |
| 56 | + # URL-decode the persona ID |
| 57 | + persona_id = unquote(persona_id) |
| 58 | + |
| 59 | + # Get the avatar file path |
| 60 | + avatar_path = self._find_avatar_file(persona_id) |
| 61 | + |
| 62 | + if avatar_path is None: |
| 63 | + raise tornado.web.HTTPError(404, f"Avatar not found for persona") |
| 64 | + |
| 65 | + # Check file size |
| 66 | + try: |
| 67 | + file_size = os.path.getsize(avatar_path) |
| 68 | + if file_size > MAX_AVATAR_SIZE: |
| 69 | + self.log.error(f"Avatar file too large: {file_size} bytes (max: {MAX_AVATAR_SIZE})") |
| 70 | + raise tornado.web.HTTPError(413, "Avatar file too large") |
| 71 | + except OSError as e: |
| 72 | + self.log.error(f"Error checking avatar file size: {e}") |
| 73 | + raise tornado.web.HTTPError(500, "Error accessing avatar file") |
| 74 | + |
| 75 | + # Serve the file |
| 76 | + try: |
| 77 | + # Set content type based on file extension |
| 78 | + content_type, _ = mimetypes.guess_type(avatar_path) |
| 79 | + if content_type: |
| 80 | + self.set_header("Content-Type", content_type) |
| 81 | + |
| 82 | + # Read and serve the file |
| 83 | + with open(avatar_path, 'rb') as f: |
| 84 | + content = f.read() |
| 85 | + self.write(content) |
| 86 | + |
| 87 | + await self.finish() |
| 88 | + except Exception as e: |
| 89 | + self.log.error(f"Error serving avatar file: {e}") |
| 90 | + raise tornado.web.HTTPError(500, f"Error serving avatar file: {str(e)}") |
| 91 | + |
| 92 | + def _find_avatar_file(self, persona_id: str) -> Optional[str]: |
| 93 | + """ |
| 94 | + Find the avatar file path by persona ID using the module-level cache. |
| 95 | +
|
| 96 | + The cache is built when personas are initialized or refreshed, |
| 97 | + so this is an O(1) lookup instead of iterating all personas. |
| 98 | + """ |
| 99 | + return _avatar_cache.get(persona_id) |
0 commit comments