Skip to content

Commit 8d792f3

Browse files
committed
rewrite settings to reduce code duplication / unneccessary setting dumps
1 parent ff66a71 commit 8d792f3

File tree

10 files changed

+87
-159
lines changed

10 files changed

+87
-159
lines changed

main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,5 +25,5 @@
2525

2626
plugin = RtfmPlugin()
2727
plugin.logs = logs
28-
logs.update_debug(plugin.debug_mode)
28+
logs.update_debug(plugin.better_settings.debug_mode)
2929
plugin.run(setup_default_log_handler=False)

plugin/handlers/settings_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def __init__(self) -> None:
1717
def condition(self, query: Query):
1818
assert self.plugin
1919

20-
return (query.keyword or "*") == self.plugin.main_kw
20+
return (query.keyword or "*") == self.plugin.better_settings.main_kw
2121

2222
async def callback(self, query: Query):
2323
assert self.plugin

plugin/plugin.py

Lines changed: 2 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -102,55 +102,7 @@ def libraries(self) -> dict[str, Library]:
102102

103103
@property
104104
def keywords(self):
105-
return [*list(self.libraries.keys()), self.main_kw]
106-
107-
@property
108-
def main_kw(self) -> str:
109-
return self.better_settings.main_kw
110-
111-
@main_kw.setter
112-
def main_kw(self, value: str) -> None:
113-
self.better_settings.main_kw = value
114-
self.dump_settings()
115-
116-
@property
117-
def static_port(self) -> int:
118-
return self.better_settings.static_port
119-
120-
@static_port.setter
121-
def static_port(self, value: int) -> None:
122-
self.better_settings.static_port = value
123-
self.dump_settings()
124-
125-
@property
126-
def debug_mode(self) -> bool:
127-
return self.better_settings.debug_mode
128-
129-
@debug_mode.setter
130-
def debug_mode(self, value: bool) -> None:
131-
log.debug("Debug Mode Set To: %r", value)
132-
if value != self.better_settings.debug_mode:
133-
self.logs.update_debug(value)
134-
self.better_settings.debug_mode = value
135-
self.dump_settings()
136-
137-
@property
138-
def simple_view(self) -> bool:
139-
return self.better_settings.simple_view
140-
141-
@simple_view.setter
142-
def simple_view(self, value: bool) -> None:
143-
self.better_settings.simple_view = value
144-
self.dump_settings()
145-
146-
@property
147-
def reset_query(self) -> bool:
148-
return self.better_settings.reset_query
149-
150-
@reset_query.setter
151-
def reset_query(self, value: bool) -> None:
152-
self.better_settings.reset_query = value
153-
self.dump_settings()
105+
return [*list(self.libraries.keys()), self.better_settings.main_kw]
154106

155107
async def build_rtfm_lookup_tables(self) -> None:
156108
log.debug("Starting to build cache...")
@@ -276,7 +228,7 @@ async def inner(
276228
*args: P.args, **kwargs: P.kwargs
277229
) -> QueryResponse | ErrorResponse:
278230
resp = await original(*args, **kwargs)
279-
if isinstance(resp, QueryResponse) and self.simple_view:
231+
if isinstance(resp, QueryResponse) and self.better_settings.simple_view:
280232
for res in resp.results:
281233
res.sub = None
282234
return resp

plugin/results.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ async def callback(self) -> ExecuteResponse:
107107
else:
108108
await self.plugin.api.open_url(self.url)
109109

110-
if self.plugin.reset_query:
110+
if self.plugin.better_settings.reset_query:
111111
await self.plugin.last_query.update(text="")
112112

113113
return ExecuteResponse()

plugin/server/api.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77
import msgspec
88
from aiohttp import web
99

10+
from ..settings import RtfmBetterSettings
1011
from .payloads.error import ErrorResponse
1112
from .payloads.get_library import GetLibraryPayload, GetLibraryResponse
1213
from .payloads.settings import (
1314
ExportSettingsResponse,
1415
ImportSettingsRequest,
15-
PluginSettings,
1616
)
1717

1818
if TYPE_CHECKING:
@@ -37,7 +37,7 @@ def build_api(
3737
async def save_settings(request: web.Request):
3838
try:
3939
form_data = decoder.decode(await request.content.read())
40-
payload = PluginSettings.parse_form_data(form_data)
40+
payload = RtfmBetterSettings.parse_form_data(form_data)
4141
except msgspec.DecodeError:
4242
return web.Response(
4343
body=ErrorResponse("Invalid Data Received").encode(), status=400
@@ -64,17 +64,18 @@ async def get_library(request: web.Request):
6464
response = GetLibraryResponse(lib.to_partial())
6565
return web.Response(body=response.encode(), headers=no_cache_headers)
6666

67-
@routes.get("/api/export_settings")
67+
@routes.get("/api/settings/export")
6868
async def export_settings(request: web.Request):
69-
obj = PluginSettings.from_plugin(plugin)
70-
response = ExportSettingsResponse(base64.b64encode(obj.encode()).decode())
69+
response = ExportSettingsResponse(
70+
base64.b64encode(plugin.better_settings.encode()).decode()
71+
)
7172
return web.Response(body=response.encode(), headers=no_cache_headers)
7273

73-
@routes.post("/api/import_settings")
74+
@routes.post("/api/settings/import")
7475
async def import_settings(request: web.Request):
7576
try:
7677
data = ImportSettingsRequest.decode(await request.read())
77-
settings = PluginSettings.decode(base64.b64decode(data.data))
78+
settings = RtfmBetterSettings.decode(base64.b64decode(data.data))
7879
except msgspec.DecodeError as e:
7980
log.exception("Error while import settings", exc_info=e)
8081
return web.Response(

plugin/server/core.py

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -36,17 +36,7 @@ def build_app(
3636
@routes.get("/")
3737
@aiohttp_jinja2.template("index.html")
3838
async def index(request: web.Request):
39-
data = {
40-
"libs": plugin.libraries.values(),
41-
"main_kw": plugin.main_kw,
42-
"port": plugin.static_port,
43-
"rtfm_version": plugin.metadata.version,
44-
"debug_mode": plugin.debug_mode,
45-
"simple_view": plugin.simple_view,
46-
"reset_query": plugin.reset_query,
47-
}
48-
log.debug("Sending data: %r", data)
49-
return data
39+
return {"plugin": plugin}
5040

5141
@routes.get("/style.css")
5242
async def style(request: web.Request):
@@ -121,13 +111,14 @@ async def run_app(
121111
*,
122112
run_forever: bool = True,
123113
) -> None:
114+
static_port = plugin.better_settings.static_port
124115
app = build_app(plugin)
125-
port = await start_runner(app, "localhost", plugin.static_port)
116+
port = await start_runner(app, "localhost", static_port)
126117

127-
if plugin.static_port != 0 and port != plugin.static_port:
118+
if static_port != 0 and port != static_port:
128119
await plugin.api.show_notification(
129120
"rtfm",
130-
f"Your chosen static port ({plugin.static_port}) was already in use so webserver started on port {port}",
121+
f"Your chosen static port ({static_port}) was already in use so webserver started on port {port}",
131122
)
132123

133124
plugin.webserver_port = port

plugin/server/index.html

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,41 +16,41 @@
1616
<p>The rtfm plugin allows you to easily and quickly query manuals and docs.</p>
1717
{% call actions() %}
1818
<a class="button" target="_blank" href="https://github.com/cibere/Flow.Launcher.Plugin.rtfm">Open Github Page</a>
19-
<a class="button" target="_blank" href="https://rtfm.cibere.dev/{{ rtfm_version }}">Open Documentation</a>
19+
<a class="button" target="_blank" href="https://rtfm.cibere.dev/{{ plugin.metadata.version }}">Open Documentation</a>
2020
{% endcall %}
2121
{% endcall %}
2222

2323
<form id="main-form" action="/api/settings" method="POST">
2424
{% call card("Plugin Settings") %}
2525
<div class="two-columns">
2626
{% call input(label="Webserver Port", id="webserver-port-input", description="This is the port that this settings page will be hosted on. If set to 0, the plugin will let your system choose an unused port on startup.") %}
27-
<input type="number" id="webserver-port-input" name="plugin.port" min="0" max="65535" step="1" value="{{ port }}">
27+
<input type="number" id="webserver-port-input" name="plugin.port" min="0" max="65535" step="1" value="{{ plugin.static_port }}">
2828
{% endcall %}
2929
{% call input(label="Main Keyword", id="main-keyword-input", description="This is the keyword that lets you access the settings page, reload the cache, and open up the plugin's log file.") %}
30-
<input type="text" id="main-keyword-input" name="plugin.keyword" value="{{ main_kw }}">
30+
<input type="text" id="main-keyword-input" name="plugin.keyword" value="{{ plugin.main_kw }}">
3131
{% endcall %}
3232
{% call checkbox(label="Debug Mode", id="main-debug-mode-input", description="If checked, the plugin will include debug logs in the plugin's log file.") %}
3333
<input
3434
id="main-debug-mode-input"
3535
type="checkbox"
36-
name="plugin.debug"
37-
{% if debug_mode %}checked{% endif %}
36+
name="plugin.debug_mode"
37+
{% if plugin.debug_mode %}checked{% endif %}
3838
>
3939
{% endcall %}
4040
{% call checkbox(label="Simple View", id="main-simple-view-input", description="If checked, the plugin will remove subtitles from the results it returns") %}
4141
<input
4242
id="main-simple-view-input"
4343
type="checkbox"
44-
name="plugin.simple"
45-
{% if simple_view %}checked{% endif %}
44+
name="plugin.simple_view"
45+
{% if plugin.simple_view %}checked{% endif %}
4646
>
4747
{% endcall %}
4848
{% call checkbox(label="Reset Query", id="main-reset-query-input", description="If checked, the plugin will reset the query to just the keyword when opening a result") %}
4949
<input
5050
id="main-reset-query-input"
5151
type="checkbox"
5252
name="plugin.reset_query"
53-
{% if reset_query %}checked{% endif %}
53+
{% if plugin.reset_query %}checked{% endif %}
5454
>
5555
{% endcall %}
5656
</div>
@@ -74,7 +74,7 @@
7474
{% endcall %}
7575
</div>
7676

77-
{% for lib in libs %}
77+
{% for lib in plugin.libraries.values() %}
7878
{{ doc(location=lib.loc, index=loop.index, type=lib.typename, name=lib.name, cache_results=lib.cache_results, is_api=lib.is_api) }}
7979
{% endfor %}
8080
</form>

plugin/server/payloads/settings.py

Lines changed: 1 addition & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,80 +1,9 @@
11
from __future__ import annotations
22

3-
import asyncio
4-
from collections import defaultdict
5-
from typing import TYPE_CHECKING, Any, Literal
3+
from typing import Literal
64

7-
from ...libraries.library import PartialLibrary
85
from .base import Payload
96

10-
if TYPE_CHECKING:
11-
from ...plugin import RtfmPlugin
12-
13-
14-
class PluginSettings(Payload):
15-
port: int
16-
keyword: str
17-
libraries: list[PartialLibrary]
18-
debug: bool = False
19-
simple: bool = False
20-
reset_query: bool = False
21-
22-
@classmethod
23-
def parse_form_data(cls, data: dict[str, str]) -> PluginSettings:
24-
kwargs: dict[str, Any] = {}
25-
raw_docs: dict[int, dict[str, Any]] = defaultdict(lambda: {})
26-
27-
for key, value in data.items():
28-
parts = key.split(".")
29-
match parts[0]:
30-
case "plugin":
31-
match parts[1]:
32-
case "port":
33-
kwargs["port"] = int(value)
34-
case "keyword":
35-
kwargs["keyword"] = value or "*"
36-
case "debug":
37-
kwargs["debug"] = True
38-
case "simple":
39-
kwargs["simple"] = True
40-
case "reset_query":
41-
kwargs["reset_query"] = True
42-
case "doc":
43-
idx = int(parts[1])
44-
match parts[2]:
45-
case "cache_results":
46-
value = True
47-
case "keyword":
48-
parts[2] = "name"
49-
if not value:
50-
value = "*"
51-
52-
raw_docs[idx][parts[2]] = value
53-
54-
kwargs["libraries"] = [PartialLibrary(**opts) for opts in raw_docs.values()]
55-
return cls(**kwargs)
56-
57-
async def save(self, plugin: RtfmPlugin) -> None:
58-
plugin.static_port = self.port
59-
plugin.main_kw = self.keyword
60-
plugin.debug_mode = self.debug
61-
plugin.simple_view = self.simple
62-
plugin.reset_query = self.reset_query
63-
64-
await plugin.update_libraries(self.libraries)
65-
asyncio.create_task(plugin.build_rtfm_lookup_tables())
66-
67-
@classmethod
68-
def from_plugin(cls, plugin: RtfmPlugin) -> PluginSettings:
69-
return cls(
70-
port=plugin.static_port,
71-
keyword=plugin.main_kw,
72-
debug=plugin.debug_mode,
73-
simple=plugin.simple_view,
74-
reset_query=plugin.reset_query,
75-
libraries=[lib.to_partial() for lib in plugin.libraries.values()],
76-
)
77-
787

798
class ExportSettingsResponse(Payload):
809
data: str

plugin/server/script.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ elements.importBtn.addEventListener("click", () => {
189189
reader.addEventListener("load", async () => {
190190
const data = reader.result;
191191
try {
192-
let response = await fetch("/api/import_settings", {
192+
let response = await fetch("/api/settings/import", {
193193
body: JSON.stringify({data}),
194194
method: "POST",
195195
});
@@ -205,7 +205,7 @@ elements.importBtn.addEventListener("click", () => {
205205

206206
elements.exportBtn.addEventListener("click", async () => {
207207
try {
208-
const data = await fetch("/api/export_settings").then(res => res.json());
208+
const data = await fetch("/api/settings/export").then(res => res.json());
209209
if (!data.success) {
210210
alert("Failed to export settings!");
211211
return;

0 commit comments

Comments
 (0)