|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import asyncio |
| 4 | +import base64 |
4 | 5 | import json |
5 | 6 | import logging |
6 | 7 | import os |
7 | 8 | from typing import TYPE_CHECKING, Callable |
8 | 9 |
|
9 | 10 | import aiohttp_jinja2 |
10 | 11 | import jinja2 |
| 12 | +import msgspec |
11 | 13 | from aiohttp import web |
12 | 14 |
|
13 | 15 | from ..libraries import doc_types, preset_docs |
|
32 | 34 | } |
33 | 35 |
|
34 | 36 |
|
| 37 | +class PartialLibrary(msgspec.Struct): |
| 38 | + name: str |
| 39 | + type: str |
| 40 | + loc: str | None |
| 41 | + use_cache: bool |
| 42 | + |
| 43 | + def to_dict(self): |
| 44 | + return { |
| 45 | + "name": self.name, |
| 46 | + "type": self.type, |
| 47 | + "loc": self.loc, |
| 48 | + "use_cache": self.use_cache, |
| 49 | + } |
| 50 | + |
| 51 | + |
| 52 | +class ImportExportSettings(msgspec.Struct): |
| 53 | + port: int |
| 54 | + keyword: str |
| 55 | + libraries: list[PartialLibrary] |
| 56 | + |
| 57 | + |
35 | 58 | def build_app( |
36 | 59 | write_settings: Callable[[list[dict[str, str]]], Awaitable[None]], |
37 | 60 | plugin: RtfmPlugin, |
@@ -67,6 +90,41 @@ async def set_static_port(request: web.Request): |
67 | 90 | return web.json_response({"success": True}) |
68 | 91 | return web.json_response({"success": False}) |
69 | 92 |
|
| 93 | + @routes.get("/api/export_settings") |
| 94 | + async def export_settings(request: web.Request): |
| 95 | + obj = ImportExportSettings( |
| 96 | + plugin.static_port, |
| 97 | + plugin.main_kw, |
| 98 | + [ |
| 99 | + PartialLibrary( |
| 100 | + lib.name, |
| 101 | + lib.classname, |
| 102 | + None if lib.is_preset else str(lib.loc), |
| 103 | + lib.use_cache, |
| 104 | + ) |
| 105 | + for lib in plugin.libraries.values() |
| 106 | + ], |
| 107 | + ) |
| 108 | + return web.json_response( |
| 109 | + { |
| 110 | + "success": True, |
| 111 | + "data": base64.b64encode(msgspec.json.encode(obj)).decode(), |
| 112 | + } |
| 113 | + ) |
| 114 | + |
| 115 | + @routes.post("/api/import_settings") |
| 116 | + async def import_settings(request: web.Request): |
| 117 | + raw = await request.content.read() |
| 118 | + try: |
| 119 | + data = msgspec.json.decode(base64.b64decode(raw), type=ImportExportSettings) |
| 120 | + except msgspec.DecodeError: |
| 121 | + return web.json_response({"success": False}) |
| 122 | + |
| 123 | + await write_settings([lib.to_dict() for lib in data.libraries]) |
| 124 | + plugin.main_kw = data.keyword |
| 125 | + plugin.static_port = data.port |
| 126 | + return web.json_response({"success": True}) |
| 127 | + |
70 | 128 | @routes.get("/") |
71 | 129 | @aiohttp_jinja2.template("template.html") |
72 | 130 | async def index(request: web.Request): |
|
0 commit comments