Repository navigation
Expand file tree
/
Copy pathsettings.py
More file actions
820 lines (746 loc) · 34.1 KB
/
Copy pathsettings.py
File metadata and controls
820 lines (746 loc) · 34.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
import json
import os
import re
import time
from copy import deepcopy
from env_loader import load_env
from flask import redirect, request, session
from werkzeug.security import check_password_hash, generate_password_hash
load_env()
from ui import h, phone_page
BASE_DIR = os.path.dirname(__file__)
SETTINGS_PATH = os.environ.get("MINIOS_SETTINGS_PATH", os.path.join(BASE_DIR, "settings.json"))
BOARD_SORTS = ("hot", "new", "top")
NEWS_MODES = ("top", "topic", "geo", "search")
NEWS_TOPICS = (
"WORLD",
"NATION",
"BUSINESS",
"TECHNOLOGY",
"ENTERTAINMENT",
"SCIENCE",
"SPORTS",
"HEALTH",
)
NEWS_LANGUAGES = {
"en-US": {"label": "English US", "hl": "en-US", "gl": "US", "ceid": "US:en"},
"tr-TR": {"label": "Turkish TR", "hl": "tr", "gl": "TR", "ceid": "TR:tr"},
"en-GB": {"label": "English UK", "hl": "en-GB", "gl": "GB", "ceid": "GB:en"},
"de-DE": {"label": "German DE", "hl": "de", "gl": "DE", "ceid": "DE:de"},
"fr-FR": {"label": "French FR", "hl": "fr", "gl": "FR", "ceid": "FR:fr"},
"es-ES": {"label": "Spanish ES", "hl": "es", "gl": "ES", "ceid": "ES:es"},
}
WEATHER_TEMPERATURE_UNITS = ("celsius", "fahrenheit")
MANAGEABLE_APPS = ("Minigram", "DuckDuckGo", "Weather", "Notes", "AI", "Finance", "Boards", "Gmail", "News", "Calendar", "Maps", "Chess")
DEFAULTS = {
"minigram": {
"contacts": [],
"timezone": "Europe/Istanbul",
"timestamp_format": "compact",
},
"duckduckgo": {
"cache_ttl": 600,
"reader_mode": True,
"default_region": "",
"default_time": "",
},
"weather": {
"location_name": "Change in settings",
"latitude": 16.16736,
"longitude": 16.15788,
"timezone": "Europe/Istanbul",
"temperature_unit": "celsius",
},
"finance": {
"currency": "USD",
},
"boards": {
"subreddits": [
"blank",
"blank",
"blank",
"blank",
"blank",
"blank",
"blank",
"blank",
],
"default_sort": "hot",
},
"news": {
"default_mode": "topic",
"default_topic": "TECHNOLOGY",
"default_lang": "en-US",
"default_geo": "USA",
"default_query": "technology",
},
"mail": {
"limit": 40,
"cache_ttl": 600,
},
"maps": {
"default_location": "",
},
"apps": {
"disabled": [],
},
"auth": {
"password_hash": "",
"expiry_minutes": 10,
},
"ui": {
"bg_color": "#191f2e",
"icon_size": 44,
"cell_height": 82,
"font_size": 13,
"welcome_seen": False,
},
}
_cache = None
def merge_defaults(data, defaults):
result = deepcopy(defaults)
if not isinstance(data, dict):
return result
for key, value in data.items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key].update(value)
else:
result[key] = value
return result
def load_settings(force=False):
global _cache
if _cache is not None and not force:
return _cache
try:
with open(SETTINGS_PATH, "r", encoding="utf-8") as f:
loaded = json.load(f)
except FileNotFoundError:
loaded = {}
except Exception:
loaded = {}
_cache = merge_defaults(loaded, DEFAULTS)
return _cache
def save_settings(data):
global _cache
data = merge_defaults(data, DEFAULTS)
tmp_path = SETTINGS_PATH + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
os.replace(tmp_path, SETTINGS_PATH)
_cache = data
def app_settings(name):
return load_settings().get(name, deepcopy(DEFAULTS.get(name, {})))
def default_app_setting(name, key):
return deepcopy(DEFAULTS[name][key])
def update_app_settings(name, values):
data = load_settings()
current = dict(data.get(name, {}))
current.update(values)
data[name] = current
save_settings(data)
def lines_to_list(text):
rows = []
for line in (text or "").splitlines():
line = line.strip()
if line:
rows.append(line)
return rows
def list_to_lines(values):
return "\n".join(values or [])
def as_int(value, default):
try:
return int(value)
except Exception:
return default
def as_float(value, default):
try:
return float(value)
except Exception:
return default
def normalize_minigram_contacts(raw_contacts):
contacts = []
seen_ids = set()
if not isinstance(raw_contacts, list):
return contacts
for row in raw_contacts:
if not isinstance(row, dict):
continue
name = str(row.get("name", "")).strip()
telegram_id = as_int(row.get("telegram_id"), 0)
if not name or telegram_id <= 0 or telegram_id in seen_ids:
continue
contacts.append({"name": name, "telegram_id": telegram_id})
seen_ids.add(telegram_id)
return contacts
SETTINGS_CSS = """
.row{display:block;border-top:1px solid #263241;padding:8px 0;color:#fff;}
.small{display:block;color:#91a0af;font-size:11px;margin-top:2px;}
form{margin:0;}
input[type=text],input[type=password],input[type=number],textarea{width:100%;box-sizing:border-box;background:#fff;color:#000;border:0;padding:6px;font-size:13px;margin:0 0 5px;font-family:Arial;}
textarea{height:120px;}
input[type=submit]{background:#95e1ff;color:#000;border:0;padding:6px 8px;font-size:13px;}
.body{background:#0f1620;border:1px solid #263241;padding:6px;margin:6px 0;}
.field{margin:0 0 7px;}
.fieldname{color:#ffd35a;margin:0 0 2px;}
.hint{color:#91a0af;font-size:11px;margin:-3px 0 4px;}
.alert{padding:6px 8px;margin:6px 0;font-size:12px;border-radius:2px;}
.alert-error{background:#5c1d1d;color:#ffb0b0;border:1px solid #852b2b;}
.alert-success{background:#1d4a2a;color:#a3f3b5;border:1px solid #2b703e;}
"""
def save_button():
return "<input type='submit' value='Save'>"
def field(label, control, hint=""):
hint_html = f"<div class='hint'>{h(hint)}</div>" if hint else ""
return f"<div class='field'><div class='fieldname'>{h(label)}</div>{hint_html}{control}</div>"
def register_settings_routes(flask_app, prefix="/settings"):
base = prefix.rstrip("/")
@flask_app.route(base)
@flask_app.route(base + "/")
def settings_index():
rows = [
("Apps", "Enable or disable apps", f"{base}/apps"),
("Appearance", "Colors and sizes", f"{base}/ui"),
("Password", "Set, change, or reset password", f"{base}/password"),
("DuckDuckGo", "Cache and reader mode", f"{base}/duckduckgo"),
("Minigram", "Contacts and timestamps", f"{base}/minigram"),
("Weather", "Location and coordinates", f"{base}/weather"),
("Finance", "Currency", f"{base}/finance"),
("Boards", "Subreddits and sort", f"{base}/boards"),
("News", "Google News defaults", f"{base}/news"),
("Gmail", "Limit and cache TTL", f"{base}/mail"),
("Maps", "Default location", f"{base}/maps"),
("About", "MiniOS info", f"{base}/about"),
]
body = ""
for name, desc, url in rows:
body += f"<a class='row' href='{h(url)}'><strong>{h(name)}</strong><span class='small'>{h(desc)}</span></a>"
return phone_page("Settings", body, nav=[("Apps", "/")], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/minigram", methods=["GET", "POST"])
def settings_minigram():
current = app_settings("minigram")
contacts = normalize_minigram_contacts(current["contacts"])
error = ""
if request.method == "POST":
action = request.form.get("action", "prefs")
if action == "prefs":
fmt = request.form.get("timestamp_format", "").strip() or current["timestamp_format"]
if fmt not in ("compact", "full"):
fmt = current["timestamp_format"]
update_app_settings(
"minigram",
{
"contacts": contacts,
"timezone": request.form.get("timezone", "").strip() or current["timezone"],
"timestamp_format": fmt,
},
)
return redirect(base + "/minigram")
if action == "delete":
delete_id = as_int(request.form.get("telegram_id"), 0)
contacts = [contact for contact in contacts if contact["telegram_id"] != delete_id]
update_app_settings("minigram", {"contacts": contacts})
return redirect(base + "/minigram")
if action == "add":
name = request.form.get("name", "").strip()
telegram_id = as_int(request.form.get("telegram_id"), 0)
if not name:
error = "Name required."
elif telegram_id <= 0:
error = "Telegram ID must be numeric."
elif any(contact["name"].lower() == name.lower() and contact["telegram_id"] != telegram_id for contact in contacts):
error = "Name already used by another ID."
else:
updated = False
for contact in contacts:
if contact["telegram_id"] == telegram_id:
contact["name"] = name
updated = True
break
if not updated:
contacts.append({"name": name, "telegram_id": telegram_id})
update_app_settings("minigram", {"contacts": contacts})
return redirect(base + "/minigram")
tz = current["timezone"]
fmt = current["timestamp_format"]
error_html = f"<div class='body'>{h(error)}</div>" if error else ""
contact_html = "<div class='body'><strong>Contacts</strong><br>"
if contacts:
for contact in contacts:
contact_html += f"""
<div class="row">
<strong>{h(contact["name"])}</strong><span class="small">{contact["telegram_id"]}</span>
<a class="btn btn-danger" href="{base}/minigram/contact/{contact['telegram_id']}/delete" style="float:right;">Delete</a>
</div>
"""
else:
contact_html += "<span class='small'>No contacts yet.</span>"
contact_html += "</div>"
body = f"""
{error_html}
<form method="post" action="{base}/minigram">
<input type="hidden" name="action" value="prefs">
{field("Timezone", f'<input type="text" name="timezone" value="{h(tz)}">', "Example: Europe/Istanbul")}
{field("Timestamp format", f'<input type="text" name="timestamp_format" value="{h(fmt)}">', "compact or full")}
{save_button()}
</form>
<div class="body">
<strong>Add contact</strong>
<form method="post" action="{base}/minigram">
<input type="hidden" name="action" value="add">
{field("Name", '<input type="text" name="name" value="">')}
{field("Telegram ID", '<input type="text" name="telegram_id" value="">', "Numeric Telegram user ID")}
{save_button()}
</form>
</div>
{contact_html}
"""
return phone_page("Minigram Settings", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/minigram/contact/<int:telegram_id>/delete", methods=["GET", "POST"])
def settings_contact_delete(telegram_id):
current = app_settings("minigram")
contacts = list(current.get("contacts", []))
target = next((c for c in contacts if c.get("telegram_id") == telegram_id), None)
if not target:
return redirect(base + "/minigram")
if request.method == "POST":
contacts = [c for c in contacts if c.get("telegram_id") != telegram_id]
update_app_settings("minigram", {"contacts": contacts})
return redirect(base + "/minigram")
body = f"""
<p>Delete contact?</p>
<div class="row">
<strong>{h(target.get('name'))}</strong><br>
<span class="small">Telegram ID: {target.get('telegram_id')}</span>
</div>
<form method="post" action="{base}/minigram/contact/{telegram_id}/delete" style="margin-top:12px;">
<input class="btn btn-danger" type="submit" value="Delete Contact">
<a class="btn" href="{base}/minigram">Cancel</a>
</form>
"""
return phone_page("Delete Contact", body, nav=[("Apps", "/"), ("Settings", base), ("Back", f"{base}/minigram")], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/weather", methods=["GET", "POST"])
def settings_weather():
current = app_settings("weather")
if request.method == "POST":
temp_unit = request.form.get("temperature_unit", "").strip() or current["temperature_unit"]
if temp_unit not in WEATHER_TEMPERATURE_UNITS:
temp_unit = current["temperature_unit"]
update_app_settings(
"weather",
{
"location_name": request.form.get("location_name", "").strip() or current["location_name"],
"latitude": as_float(request.form.get("latitude"), current["latitude"]),
"longitude": as_float(request.form.get("longitude"), current["longitude"]),
"timezone": request.form.get("timezone", "").strip() or current["timezone"],
"temperature_unit": temp_unit,
},
)
return redirect(base)
temp_unit = current["temperature_unit"]
body = f"""
<form method="post" action="{base}/weather">
{field("Location name", f'<input type="text" name="location_name" value="{h(current["location_name"])}">')}
{field("Latitude", f'<input type="text" name="latitude" value="{h(current["latitude"])}">')}
{field("Longitude", f'<input type="text" name="longitude" value="{h(current["longitude"])}">')}
{field("Timezone", f'<input type="text" name="timezone" value="{h(current["timezone"])}">', "Example: Europe/Istanbul")}
{field("Temperature unit", f'<input type="text" name="temperature_unit" value="{h(temp_unit)}">', " or ".join(WEATHER_TEMPERATURE_UNITS))}
{save_button()}
</form>
"""
return phone_page("Weather Settings", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/finance", methods=["GET", "POST"])
def settings_finance():
current = app_settings("finance")
if request.method == "POST":
update_app_settings("finance", {"currency": request.form.get("currency", "").strip() or current["currency"]})
return redirect(base)
body = f"""
<form method="post" action="{base}/finance">
{field("Currency", f'<input type="text" name="currency" value="{h(current["currency"])}">', "Displayed after totals, for example TL or USD")}
{save_button()}
</form>
"""
return phone_page("Finance Settings", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/boards", methods=["GET", "POST"])
def settings_boards():
current = app_settings("boards")
if request.method == "POST":
sort = request.form.get("default_sort", current["default_sort"])
if sort not in BOARD_SORTS:
sort = current["default_sort"]
update_app_settings(
"boards",
{
"subreddits": lines_to_list(request.form.get("subreddits", "")),
"default_sort": sort,
},
)
return redirect(base)
body = f"""
<form method="post" action="{base}/boards">
{field("Followed subreddits", f'<textarea name="subreddits">{h(list_to_lines(current["subreddits"]))}</textarea>', "One subreddit per line")}
{field("Default sort", f'<input type="text" name="default_sort" value="{h(current["default_sort"])}">', ", ".join(BOARD_SORTS))}
{save_button()}
</form>
"""
return phone_page("Boards Settings", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/news", methods=["GET", "POST"])
def settings_news():
current = app_settings("news")
if request.method == "POST":
mode = request.form.get("default_mode", "").strip() or current["default_mode"]
topic = request.form.get("default_topic", "").strip().upper() or current["default_topic"]
lang = request.form.get("default_lang", "").strip() or current["default_lang"]
if mode not in NEWS_MODES:
mode = current["default_mode"]
if topic not in NEWS_TOPICS:
topic = current["default_topic"]
if lang not in NEWS_LANGUAGES:
lang = current["default_lang"]
update_app_settings(
"news",
{
"default_mode": mode,
"default_topic": topic,
"default_lang": lang,
"default_geo": request.form.get("default_geo", "").strip() or current["default_geo"],
"default_query": request.form.get("default_query", "").strip() or current["default_query"],
},
)
return redirect(base)
body = f"""
<form method="post" action="{base}/news">
{field("Default mode", f'<input type="text" name="default_mode" value="{h(current["default_mode"])}">', ", ".join(NEWS_MODES))}
{field("Default topic", f'<input type="text" name="default_topic" value="{h(current["default_topic"])}">', ", ".join(NEWS_TOPICS))}
{field("Default language", f'<input type="text" name="default_lang" value="{h(current["default_lang"])}">', ", ".join(NEWS_LANGUAGES.keys()))}
{field("Default geo", f'<input type="text" name="default_geo" value="{h(current["default_geo"])}">', "Used by geo mode")}
{field("Default search query", f'<input type="text" name="default_query" value="{h(current["default_query"])}">', "Used by search mode")}
{save_button()}
</form>
"""
return phone_page("News Settings", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/mail", methods=["GET", "POST"])
def settings_mail():
current = app_settings("mail")
if request.method == "POST":
update_app_settings(
"mail",
{
"limit": as_int(request.form.get("limit"), current["limit"]),
"cache_ttl": as_int(request.form.get("cache_ttl"), current["cache_ttl"]),
},
)
return redirect(base)
body = f"""
<form method="post" action="{base}/mail">
{field("Mail limit", f'<input type="text" name="limit" value="{h(current["limit"])}">', "Number of recent mails cached")}
{field("Cache TTL", f'<input type="text" name="cache_ttl" value="{h(current["cache_ttl"])}">', "Seconds before auto-refresh")}
{save_button()}
</form>
<div class="small">Gmail address and app password stay in .env only.</div>
"""
return phone_page("Gmail Settings", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/apps", methods=["GET", "POST"])
def settings_apps():
current = app_settings("apps")
disabled = list(current.get("disabled", []))
if request.method == "POST":
app_name = request.form.get("app", "")
if app_name in MANAGEABLE_APPS:
if app_name in disabled:
disabled.remove(app_name)
else:
disabled.append(app_name)
update_app_settings("apps", {"disabled": disabled})
return redirect(base + "/apps")
body = ""
for app_name in MANAGEABLE_APPS:
is_disabled = app_name in disabled
status = "<span style='color:#ff8b8b'>OFF</span>" if is_disabled else "<span style='color:#6fcf97'>ON</span>"
action = "Enable" if is_disabled else "Disable"
body += f"""
<form method="post" action="{base}/apps">
<input type="hidden" name="app" value="{h(app_name)}">
<div class="row"><strong>{h(app_name)}</strong> {status}
<input type="submit" value="{action}" style="float:right;">
</div>
</form>
"""
return phone_page("App Manager", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/ui", methods=["GET", "POST"])
def settings_ui():
current = app_settings("ui")
if request.method == "POST":
action = request.form.get("action", "save")
if action == "reset":
update_app_settings("ui", {
"bg_color": default_app_setting("ui", "bg_color"),
"icon_size": default_app_setting("ui", "icon_size"),
"cell_height": default_app_setting("ui", "cell_height"),
"font_size": default_app_setting("ui", "font_size"),
"welcome_seen": default_app_setting("ui", "welcome_seen"),
})
resp = redirect(base + "/ui")
resp.delete_cookie("minios_welcome")
return resp
else:
bg_raw = request.form.get("bg_color", "").strip()
if bg_raw and re.match(r'^#[0-9a-fA-F]{6}$', bg_raw):
bg_color = bg_raw
else:
bg_color = current["bg_color"]
icon_size = as_int(request.form.get("icon_size"), current["icon_size"])
cell_height = as_int(request.form.get("cell_height"), current["cell_height"])
font_size = as_int(request.form.get("font_size"), current["font_size"])
show_welcome_raw = request.form.get("show_welcome", "").strip().lower()
if show_welcome_raw in ("1", "true", "yes", "on"):
welcome_seen = False
elif show_welcome_raw in ("0", "false", "no", "off"):
welcome_seen = True
else:
welcome_seen = current.get("welcome_seen", False)
update_app_settings("ui", {
"bg_color": bg_color,
"icon_size": icon_size,
"cell_height": cell_height,
"font_size": font_size,
"welcome_seen": welcome_seen,
})
resp = redirect(base + "/ui")
if not welcome_seen:
resp.delete_cookie("minios_welcome")
return resp
welcome_val = "0" if current.get("welcome_seen", False) else "1"
body = f"""
<form method="post" action="{base}/ui">
<input type="hidden" name="action" value="save">
{field("Background Color (Hex)", f'<input type="text" name="bg_color" value="{h(current["bg_color"])}">', hint="Format: #RRGGBB")}
{field("Icon Size (px)", f'<input type="text" name="icon_size" value="{h(current["icon_size"])}">')}
{field("Cell Height (px)", f'<input type="text" name="cell_height" value="{h(current["cell_height"])}">')}
{field("Font Size (px)", f'<input type="text" name="font_size" value="{h(current["font_size"])}">', hint="May be overridden by the browser")}
{field("Show Welcome Popup (1=yes, 0=no)", f'<input type="text" name="show_welcome" value="{welcome_val}">', hint="Show welcome dialog on home screen")}
<input type="submit" value="Save">
</form>
<p style="margin-top: 15px;">
<a class="btn btn-danger" href="{base}/ui/reset">Reset to Defaults</a>
</p>
"""
return phone_page("Appearance", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/ui/reset", methods=["GET", "POST"])
def settings_ui_reset():
if request.method == "POST":
update_app_settings("ui", {
"bg_color": default_app_setting("ui", "bg_color"),
"icon_size": default_app_setting("ui", "icon_size"),
"cell_height": default_app_setting("ui", "cell_height"),
"font_size": default_app_setting("ui", "font_size"),
"welcome_seen": default_app_setting("ui", "welcome_seen"),
})
resp = redirect(base + "/ui")
resp.delete_cookie("minios_welcome")
return resp
body = f"""
<p>Reset appearance settings to default values?</p>
<div class="small" style="margin:8px 0;">This will revert theme colors, font size, cell height, and icon sizes to MiniOS defaults.</div>
<form method="post" action="{base}/ui/reset" style="margin-top:12px;">
<input class="btn btn-danger" type="submit" value="Reset to Defaults">
<a class="btn" href="{base}/ui">Cancel</a>
</form>
"""
return phone_page("Reset Appearance", body, nav=[("Apps", "/"), ("Settings", base), ("Back", f"{base}/ui")], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/duckduckgo", methods=["GET", "POST"])
@flask_app.route(base + "/search", methods=["GET", "POST"])
def settings_duckduckgo():
current = app_settings("duckduckgo")
if not current and "search" in app_settings("search"):
current = app_settings("search")
if request.method == "POST":
cache_ttl = as_int(request.form.get("cache_ttl"), current["cache_ttl"])
reader_mode = request.form.get("reader_mode", "").strip().lower() in ("1", "true", "yes", "enabled", "on")
default_region = request.form.get("default_region", "").strip()
default_time = request.form.get("default_time", "").strip()
update_app_settings("duckduckgo", {
"cache_ttl": max(0, cache_ttl),
"reader_mode": reader_mode,
"default_region": default_region,
"default_time": default_time,
})
return redirect(base + "/duckduckgo")
reader_val = "1" if current.get("reader_mode", True) else "0"
body = f"""
<form method="post" action="{base}/duckduckgo">
{field("Cache TTL (seconds)", f'<input type="text" name="cache_ttl" value="{h(current.get("cache_ttl", 600))}">', "0 to disable search cache")}
{field("Reader Mode (1=on, 0=off)", f'<input type="text" name="reader_mode" value="{h(reader_val)}">', "Show [Reader] link on search results")}
{field("Default Region", f'<input type="text" name="default_region" value="{h(current.get("default_region", ""))}">', "Example: us-en, tr-tr, or blank for all")}
{field("Default Time Filter", f'<input type="text" name="default_time" value="{h(current.get("default_time", ""))}">', "d (day), w (week), m (month), y (year), or blank")}
{save_button()}
</form>
"""
return phone_page("DuckDuckGo Settings", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/maps", methods=["GET", "POST"])
def settings_maps():
current = app_settings("maps")
if request.method == "POST":
loc = request.form.get("default_location", "").strip()
update_app_settings("maps", {"default_location": loc})
return redirect(base)
body = f"""
<form method="post" action="{base}/maps">
{field("Default Location", f'<input type="text" name="default_location" value="{h(current.get("default_location", ""))}">', "Address or lat,lon used when 'From' is empty")}
{save_button()}
</form>
"""
return phone_page("Maps Settings", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/password", methods=["GET", "POST"])
@flask_app.route(base + "/password/set", methods=["GET", "POST"])
@flask_app.route(base + "/password/change", methods=["GET", "POST"])
def settings_password():
auth_cfg = app_settings("auth")
pwd_hash = auth_cfg.get("password_hash", "")
is_set = bool(pwd_hash)
expiry_min = auth_cfg.get("expiry_minutes", 10)
error = ""
msg = request.args.get("msg", "")
if request.method == "POST":
action = request.form.get("action", "")
if action == "save_expiry":
val = as_int(request.form.get("expiry_minutes"), 10)
if val <= 0:
val = 10
update_app_settings("auth", {"expiry_minutes": val})
return redirect(base + "/password?msg=Expiry+duration+saved")
elif action == "save_password":
if not is_set:
pwd = request.form.get("password", "")
confirm = request.form.get("confirm_password", "")
if not pwd:
error = "Password cannot be empty."
elif pwd != confirm:
error = "Passwords do not match."
else:
h_val = generate_password_hash(pwd)
update_app_settings("auth", {"password_hash": h_val})
session["authenticated"] = True
session["last_active"] = time.time()
return redirect(base + "/password?msg=Password+set+successfully")
else:
cur_pwd = request.form.get("current_password", "")
new_pwd = request.form.get("new_password", "")
if not check_password_hash(pwd_hash, cur_pwd):
error = "Current password incorrect."
elif not new_pwd:
error = "New password cannot be empty."
else:
h_val = generate_password_hash(new_pwd)
update_app_settings("auth", {"password_hash": h_val})
session["authenticated"] = True
session["last_active"] = time.time()
return redirect(base + "/password?msg=Password+changed+successfully")
alert_html = ""
if error:
alert_html = f"<div class='alert alert-error'>{h(error)}</div>"
elif msg:
alert_html = f"<div class='alert alert-success'>{h(msg)}</div>"
set_or_change = "Change password" if is_set else "Set password"
opts_html = f"""
<div style="margin:2px 0 10px;">
<a class="btn" style="background:#1a3c5a;" href="{base}/password"><strong>{h(set_or_change)}</strong></a>
<a class="btn" href="{base}/password/reset"><strong>Reset password</strong></a>
</div>
"""
if not is_set:
form_title = "Set Password"
form_inputs = f"""
{field("Password", '<input type="password" name="password" autocomplete="new-password">')}
{field("Confirm Password", '<input type="password" name="confirm_password" autocomplete="new-password">')}
"""
else:
form_title = "Change Password"
form_inputs = f"""
{field("Current Password", '<input type="password" name="current_password" autocomplete="current-password">')}
{field("New Password", '<input type="password" name="new_password" autocomplete="new-password">')}
"""
body = f"""
{alert_html}
{opts_html}
<div class="body">
<strong>{h(form_title)}</strong>
<form method="post" action="{base}/password">
<input type="hidden" name="action" value="save_password">
{form_inputs}
{save_button()}
</form>
</div>
<div class="body">
<strong>Session Expiry</strong>
<form method="post" action="{base}/password">
<input type="hidden" name="action" value="save_expiry">
{field("Expiry duration (minutes)", f'<input type="number" name="expiry_minutes" value="{expiry_min}" min="1" max="1440">', "Default 10 min. Session locks after inactivity.")}
{save_button()}
</form>
</div>
"""
if is_set:
body += f"""<div style="margin-top:10px;"><a class="btn" href="/lock">Lock MiniOS Now</a></div>"""
return phone_page("Password", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/password/reset", methods=["GET", "POST"])
def settings_password_reset():
auth_cfg = app_settings("auth")
pwd_hash = auth_cfg.get("password_hash", "")
is_set = bool(pwd_hash)
error = ""
msg = request.args.get("msg", "")
if request.method == "POST":
confirmation = request.form.get("confirmation", "").strip()
if not is_set:
error = "No password is currently set."
elif confirmation.lower() != "confirm":
error = "Please type 'Confirm' to proceed."
else:
update_app_settings("auth", {"password_hash": ""})
session.pop("authenticated", None)
session.pop("last_active", None)
return redirect(base + "/password?msg=Password+reset+successfully")
alert_html = ""
if error:
alert_html = f"<div class='alert alert-error'>{h(error)}</div>"
elif msg:
alert_html = f"<div class='alert alert-success'>{h(msg)}</div>"
set_or_change = "Change password" if is_set else "Set password"
opts_html = f"""
<div style="margin:2px 0 10px;">
<a class="btn" href="{base}/password"><strong>{h(set_or_change)}</strong></a>
<a class="btn" style="background:#1a3c5a;" href="{base}/password/reset"><strong>Reset password</strong></a>
</div>
"""
if not is_set:
body = f"""
{alert_html}
{opts_html}
<div class="body">
<span class="small">No password is currently set. Use "Set password" to configure one.</span>
</div>
"""
else:
body = f"""
{alert_html}
{opts_html}
<div class="body">
<strong>Reset Password</strong>
<div class="small" style="color:#ffb0b0;margin:6px 0 10px;line-height:1.4;">This will make your MiniOS accessible to everyone. Type Confirm to proceed.</div>
<form method="post" action="{base}/password/reset">
{field("Confirmation", '<input type="text" name="confirmation" autocomplete="off" placeholder="Type Confirm">')}
<input class="btn btn-danger" type="submit" value="Reset Password" style="padding:6px 12px;font-size:13px;cursor:pointer;">
</form>
</div>
"""
return phone_page("Reset Password", body, nav=[("Apps", "/"), ("Settings", base), ("Back", f"{base}/password")], extra_css=SETTINGS_CSS)
@flask_app.route(base + "/about")
def settings_about():
body = """
<div class="row"><strong>MiniOS Version:</strong><span class="small">V2.0.0</span></div>
<div class="row"><strong>Made by:</strong><span class="small">fl0w</span></div>
<div class="row"><strong>Platform:</strong><span class="small">Flask</span></div>
<div class="row"><strong>Target:</strong><span class="small">Opera Mini / Dorado on MocorOS</span></div>
"""
return phone_page("About", body, nav=[("Apps", "/"), ("Settings", base)], extra_css=SETTINGS_CSS)