modified widgets

This commit is contained in:
2026-02-01 17:45:52 +01:00
parent c14aa3ac8b
commit 13e8d41a80
2 changed files with 497 additions and 3 deletions
+486 -1
View File
@@ -173,7 +173,7 @@ data:
}});
if (response.ok) {{
lastSaved = content;
updateStatus('Saved ', 'saved');
updateStatus('Saved ✓', 'saved');
setTimeout(() => updateStatus(''), 2000);
}} else {{
updateStatus('Save failed', 'error');
@@ -209,6 +209,491 @@ data:
return {"status": "ok", "user": safe_user}
return Response(content="Failed to save", status_code=500)
# ================================
# Unified User Data System (Notes, Todo, Motivation)
# ================================
# File format:
# [Notes]
# Free-form notes text...
#
# [Todo]
# - [ ] Uncompleted task
# - [x] Completed task
#
# [Motivation]
# Quote 1
# Quote 2
def get_userdata_file(user: str) -> str:
"""Get user data file path, with validation."""
safe_user = re.sub(r'[^a-zA-Z0-9_-]', '', user) or "default"
data_dir = os.environ.get("DATA_DIR", "/data")
return os.path.join(data_dir, f"userdata_{safe_user}.txt")
def load_userdata(user: str) -> dict:
"""Load and parse user data file into sections."""
filepath = get_userdata_file(user)
sections = {"Notes": "", "Todo": [], "Motivation": []}
try:
if os.path.exists(filepath):
with open(filepath, "r", encoding="utf-8") as f:
content = f.read()
current_section = None
section_lines = []
for line in content.split('\n'):
stripped = line.strip()
if stripped.startswith('[') and stripped.endswith(']'):
# Save previous section
if current_section == "Notes":
sections["Notes"] = '\n'.join(section_lines).strip()
elif current_section == "Todo":
for l in section_lines:
l = l.strip()
if l.startswith('- [x] '):
sections["Todo"].append({"text": l[6:], "done": True})
elif l.startswith('- [ ] '):
sections["Todo"].append({"text": l[6:], "done": False})
elif current_section == "Motivation":
for l in section_lines:
l = l.strip()
if l:
sections["Motivation"].append(l)
# Start new section
current_section = stripped[1:-1]
section_lines = []
else:
section_lines.append(line)
# Handle last section
if current_section == "Notes":
sections["Notes"] = '\n'.join(section_lines).strip()
elif current_section == "Todo":
for l in section_lines:
l = l.strip()
if l.startswith('- [x] '):
sections["Todo"].append({"text": l[6:], "done": True})
elif l.startswith('- [ ] '):
sections["Todo"].append({"text": l[6:], "done": False})
elif current_section == "Motivation":
for l in section_lines:
l = l.strip()
if l:
sections["Motivation"].append(l)
except Exception as e:
print(f"Error loading userdata for {user}: {e}")
return sections
def save_userdata(user: str, sections: dict) -> bool:
"""Save sections back to user data file."""
filepath = get_userdata_file(user)
try:
lines = []
lines.append("[Notes]")
lines.append(sections.get("Notes", ""))
lines.append("")
lines.append("[Todo]")
for item in sections.get("Todo", []):
mark = "x" if item.get("done") else " "
lines.append(f"- [{mark}] {item.get('text', '')}")
lines.append("")
lines.append("[Motivation]")
for quote in sections.get("Motivation", []):
lines.append(quote)
with open(filepath, "w", encoding="utf-8") as f:
f.write('\n'.join(lines))
return True
except Exception as e:
print(f"Error saving userdata for {user}: {e}")
return False
# --------------------------------
# Todo Widget
# --------------------------------
@APP.get("/userdata/todo")
def todo_widget(key: str = "", user: str = "default", accent: str = "4ade80", bgcolor: str = "0d1117"):
"""Serve the Todo widget HTML page."""
expected_key = os.environ.get("GLANCE_HELPER_KEY", "")
if key != expected_key:
return Response(content="Unauthorized", status_code=401)
safe_user = re.sub(r'[^a-zA-Z0-9_-]', '', user) or "default"
safe_accent = re.sub(r'[^a-fA-F0-9]', '', accent)[:6] or "4ade80"
safe_bgcolor = re.sub(r'[^a-fA-F0-9]', '', bgcolor)[:6] or "0d1117"
sections = load_userdata(safe_user)
todos = sections.get("Todo", [])
# Build todo items HTML
todo_html = ""
for i, item in enumerate(todos):
checked = "checked" if item.get("done") else ""
text_escaped = item.get("text", "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
done_class = "done" if item.get("done") else ""
todo_html += f'''<div class="todo-item {done_class}" data-index="{i}">
<input type="checkbox" class="todo-check" {checked} onchange="toggleTodo({i})">
<span class="todo-text">{text_escaped}</span>
<button class="todo-delete" onclick="deleteTodo({i})" title="Delete">🗑</button>
</div>'''
html = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
:root {{
--accent: #{safe_accent};
--accent-20: #{safe_accent}33;
--accent-40: #{safe_accent}66;
--accent-60: #{safe_accent}99;
--bgcolor: #{safe_bgcolor};
}}
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
html, body {{ background: var(--bgcolor); height: 100%; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: rgba(255,255,255,0.9); }}
.container {{ display: flex; flex-direction: column; height: 100%; padding: 8px; gap: 8px; }}
.todo-list {{ flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 4px; }}
.todo-item {{
display: flex; align-items: center; gap: 8px; padding: 8px 10px;
background: rgba(255,255,255,0.04); border-radius: 6px;
transition: background 0.15s;
}}
.todo-item:hover {{ background: rgba(255,255,255,0.08); }}
.todo-item:hover .todo-delete {{ opacity: 1; }}
.todo-item.done .todo-text {{ opacity: 0.5; text-decoration: line-through; }}
.todo-check {{
width: 18px; height: 18px; cursor: pointer; accent-color: var(--accent);
flex-shrink: 0;
}}
.todo-text {{ flex: 1; font-size: 14px; line-height: 1.4; word-break: break-word; }}
.todo-delete {{
opacity: 0; background: none; border: none; cursor: pointer;
font-size: 14px; padding: 4px; transition: opacity 0.15s;
}}
.todo-delete:hover {{ transform: scale(1.1); }}
.add-form {{ display: flex; gap: 8px; }}
.add-input {{
flex: 1; padding: 10px 12px; border: 1px solid var(--accent-20);
background: rgba(255,255,255,0.06); border-radius: 6px;
color: rgba(255,255,255,0.9); font-size: 14px; outline: none;
}}
.add-input:focus {{ border-color: var(--accent-40); background: rgba(255,255,255,0.1); }}
.add-input::placeholder {{ color: var(--accent-40); }}
.add-btn {{
padding: 10px 16px; background: var(--accent-20); border: none;
border-radius: 6px; color: var(--accent); font-size: 14px; cursor: pointer;
transition: background 0.15s;
}}
.add-btn:hover {{ background: var(--accent-40); }}
.status {{ font-size: 11px; text-align: center; min-height: 16px; opacity: 0.6; }}
.status.error {{ color: #f87171; opacity: 1; }}
.todo-list::-webkit-scrollbar {{ width: 6px; }}
.todo-list::-webkit-scrollbar-track {{ background: transparent; }}
.todo-list::-webkit-scrollbar-thumb {{ background: var(--accent-40); border-radius: 3px; }}
</style>
</head>
<body>
<div class="container">
<div class="add-form">
<input type="text" class="add-input" id="newTodo" placeholder="+ Add a task" onkeypress="if(event.key==='Enter')addTodo()">
<button class="add-btn" onclick="addTodo()">Add</button>
</div>
<div class="todo-list" id="todoList">{todo_html if todo_html else '<div style="opacity:0.5;text-align:center;padding:20px;">No tasks yet</div>'}</div>
<div class="status" id="status"></div>
</div>
<script>
const apiKey = '{expected_key}';
const user = '{safe_user}';
const baseUrl = '/userdata/todo';
function showStatus(msg, isError) {{
const s = document.getElementById('status');
s.textContent = msg;
s.className = 'status' + (isError ? ' error' : '');
if (!isError) setTimeout(() => s.textContent = '', 2000);
}}
async function addTodo() {{
const input = document.getElementById('newTodo');
const text = input.value.trim();
if (!text) return;
try {{
const r = await fetch(baseUrl + '/add?key=' + apiKey + '&user=' + user, {{
method: 'POST',
headers: {{ 'Content-Type': 'application/json' }},
body: JSON.stringify({{ text: text }})
}});
if (r.ok) {{ input.value = ''; location.reload(); }}
else showStatus('Failed to add', true);
}} catch(e) {{ showStatus('Error: ' + e.message, true); }}
}}
async function toggleTodo(index) {{
try {{
const r = await fetch(baseUrl + '/toggle?key=' + apiKey + '&user=' + user + '&index=' + index, {{ method: 'POST' }});
if (!r.ok) showStatus('Failed to update', true);
}} catch(e) {{ showStatus('Error: ' + e.message, true); }}
}}
async function deleteTodo(index) {{
try {{
const r = await fetch(baseUrl + '/delete?key=' + apiKey + '&user=' + user + '&index=' + index, {{ method: 'POST' }});
if (r.ok) location.reload();
else showStatus('Failed to delete', true);
}} catch(e) {{ showStatus('Error: ' + e.message, true); }}
}}
</script>
</body>
</html>"""
return Response(content=html, media_type="text/html")
@APP.post("/userdata/todo/add")
async def todo_add(key: str = "", user: str = "default", content: dict = None):
expected_key = os.environ.get("GLANCE_HELPER_KEY", "")
if key != expected_key:
return Response(content="Unauthorized", status_code=401)
safe_user = re.sub(r'[^a-zA-Z0-9_-]', '', user) or "default"
if content and content.get("text"):
sections = load_userdata(safe_user)
sections["Todo"].append({"text": content["text"].strip(), "done": False})
if save_userdata(safe_user, sections):
return {"status": "ok"}
return Response(content="Failed", status_code=500)
@APP.post("/userdata/todo/toggle")
async def todo_toggle(key: str = "", user: str = "default", index: int = 0):
expected_key = os.environ.get("GLANCE_HELPER_KEY", "")
if key != expected_key:
return Response(content="Unauthorized", status_code=401)
safe_user = re.sub(r'[^a-zA-Z0-9_-]', '', user) or "default"
sections = load_userdata(safe_user)
if 0 <= index < len(sections["Todo"]):
sections["Todo"][index]["done"] = not sections["Todo"][index]["done"]
if save_userdata(safe_user, sections):
return {"status": "ok"}
return Response(content="Failed", status_code=500)
@APP.post("/userdata/todo/delete")
async def todo_delete(key: str = "", user: str = "default", index: int = 0):
expected_key = os.environ.get("GLANCE_HELPER_KEY", "")
if key != expected_key:
return Response(content="Unauthorized", status_code=401)
safe_user = re.sub(r'[^a-zA-Z0-9_-]', '', user) or "default"
sections = load_userdata(safe_user)
if 0 <= index < len(sections["Todo"]):
sections["Todo"].pop(index)
if save_userdata(safe_user, sections):
return {"status": "ok"}
return Response(content="Failed", status_code=500)
# --------------------------------
# Motivation Widget
# --------------------------------
import random as _random
@APP.get("/userdata/motivation")
def motivation_widget(key: str = "", user: str = "default", accent: str = "4ade80", bgcolor: str = "0d1117"):
"""Serve the Motivation widget HTML page with random quote and settings modal."""
expected_key = os.environ.get("GLANCE_HELPER_KEY", "")
if key != expected_key:
return Response(content="Unauthorized", status_code=401)
safe_user = re.sub(r'[^a-zA-Z0-9_-]', '', user) or "default"
safe_accent = re.sub(r'[^a-fA-F0-9]', '', accent)[:6] or "4ade80"
safe_bgcolor = re.sub(r'[^a-fA-F0-9]', '', bgcolor)[:6] or "0d1117"
sections = load_userdata(safe_user)
quotes = sections.get("Motivation", [])
# Pick random quote
current_quote = _random.choice(quotes) if quotes else "Add your first motivational quote!"
current_quote_escaped = current_quote.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
# Build quotes list for modal
quotes_html = ""
for i, q in enumerate(quotes):
q_escaped = q.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
quotes_html += f'<div class="quote-item" data-index="{i}"><span class="quote-text">{q_escaped}</span><button class="quote-delete" onclick="deleteQuote({i})">×</button></div>'
html = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
:root {{
--accent: #{safe_accent};
--accent-20: #{safe_accent}33;
--accent-40: #{safe_accent}66;
--accent-60: #{safe_accent}99;
--bgcolor: #{safe_bgcolor};
}}
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
html, body {{ background: var(--bgcolor); height: 100%; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: rgba(255,255,255,0.9); }}
.container {{ display: flex; flex-direction: column; height: 100%; padding: 12px; position: relative; }}
.settings-btn {{
position: absolute; top: 8px; right: 8px;
background: none; border: none; cursor: pointer;
font-size: 16px; opacity: 0.4; transition: opacity 0.15s;
}}
.settings-btn:hover {{ opacity: 0.8; }}
.quote-display {{
flex: 1; display: flex; align-items: center; justify-content: center;
text-align: center; padding: 8px 28px;
}}
.quote-text-main {{
font-size: 15px; line-height: 1.5; font-style: italic;
color: var(--accent); opacity: 0.9;
}}
.quote-count {{
font-size: 11px; opacity: 0.4; text-align: center; padding-bottom: 4px;
}}
/* Modal */
.modal-overlay {{
display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7);
align-items: center; justify-content: center; z-index: 1000;
}}
.modal-overlay.open {{ display: flex; }}
.modal {{
background: #1a1a2e; border-radius: 12px; width: 90%; max-width: 400px;
max-height: 80%; display: flex; flex-direction: column; box-shadow: 0 10px 40px rgba(0,0,0,0.5);
}}
.modal-header {{
display: flex; justify-content: space-between; align-items: center;
padding: 16px; border-bottom: 1px solid rgba(255,255,255,0.1);
}}
.modal-title {{ font-size: 16px; font-weight: 600; }}
.modal-close {{
background: none; border: none; font-size: 24px; cursor: pointer;
color: rgba(255,255,255,0.6); line-height: 1;
}}
.modal-close:hover {{ color: rgba(255,255,255,0.9); }}
.modal-body {{ flex: 1; overflow-y: auto; padding: 12px; }}
.quote-item {{
display: flex; align-items: flex-start; gap: 8px; padding: 10px;
background: rgba(255,255,255,0.04); border-radius: 6px; margin-bottom: 8px;
}}
.quote-item .quote-text {{ flex: 1; font-size: 13px; line-height: 1.4; word-break: break-word; }}
.quote-delete {{
background: none; border: none; cursor: pointer; font-size: 18px;
color: rgba(255,255,255,0.4); padding: 0 4px; line-height: 1;
}}
.quote-delete:hover {{ color: #f87171; }}
.modal-footer {{ padding: 12px; border-top: 1px solid rgba(255,255,255,0.1); }}
.add-form {{ display: flex; gap: 8px; }}
.add-input {{
flex: 1; padding: 10px 12px; border: 1px solid var(--accent-20);
background: rgba(255,255,255,0.06); border-radius: 6px;
color: rgba(255,255,255,0.9); font-size: 14px; outline: none;
}}
.add-input:focus {{ border-color: var(--accent-40); }}
.add-btn {{
padding: 10px 16px; background: var(--accent-20); border: none;
border-radius: 6px; color: var(--accent); font-size: 14px; cursor: pointer;
}}
.add-btn:hover {{ background: var(--accent-40); }}
.empty-state {{ text-align: center; padding: 20px; opacity: 0.5; font-size: 13px; }}
</style>
</head>
<body>
<div class="container">
<button class="settings-btn" onclick="openModal()" title="Manage quotes">⚙️</button>
<div class="quote-display">
<div class="quote-text-main">"{current_quote_escaped}"</div>
</div>
<div class="quote-count">{len(quotes)} quote{'s' if len(quotes) != 1 else ''}</div>
</div>
<div class="modal-overlay" id="modal" onclick="if(event.target===this)closeModal()">
<div class="modal">
<div class="modal-header">
<div class="modal-title">Manage Quotes</div>
<button class="modal-close" onclick="closeModal()">×</button>
</div>
<div class="modal-body" id="quotesList">
{quotes_html if quotes_html else '<div class="empty-state">No quotes yet. Add your first one below!</div>'}
</div>
<div class="modal-footer">
<div class="add-form">
<input type="text" class="add-input" id="newQuote" placeholder="Add a new quote..." onkeypress="if(event.key==='Enter')addQuote()">
<button class="add-btn" onclick="addQuote()">Add</button>
</div>
</div>
</div>
</div>
<script>
const apiKey = '{expected_key}';
const user = '{safe_user}';
const baseUrl = '/userdata/motivation';
function openModal() {{ document.getElementById('modal').classList.add('open'); }}
function closeModal() {{ document.getElementById('modal').classList.remove('open'); }}
async function addQuote() {{
const input = document.getElementById('newQuote');
const text = input.value.trim();
if (!text) return;
try {{
const r = await fetch(baseUrl + '/add?key=' + apiKey + '&user=' + user, {{
method: 'POST',
headers: {{ 'Content-Type': 'application/json' }},
body: JSON.stringify({{ text: text }})
}});
if (r.ok) {{ input.value = ''; location.reload(); }}
}} catch(e) {{ console.error(e); }}
}}
async function deleteQuote(index) {{
try {{
const r = await fetch(baseUrl + '/delete?key=' + apiKey + '&user=' + user + '&index=' + index, {{ method: 'POST' }});
if (r.ok) location.reload();
}} catch(e) {{ console.error(e); }}
}}
</script>
</body>
</html>"""
return Response(content=html, media_type="text/html")
@APP.post("/userdata/motivation/add")
async def motivation_add(key: str = "", user: str = "default", content: dict = None):
expected_key = os.environ.get("GLANCE_HELPER_KEY", "")
if key != expected_key:
return Response(content="Unauthorized", status_code=401)
safe_user = re.sub(r'[^a-zA-Z0-9_-]', '', user) or "default"
if content and content.get("text"):
sections = load_userdata(safe_user)
sections["Motivation"].append(content["text"].strip())
if save_userdata(safe_user, sections):
return {"status": "ok"}
return Response(content="Failed", status_code=500)
@APP.post("/userdata/motivation/delete")
async def motivation_delete(key: str = "", user: str = "default", index: int = 0):
expected_key = os.environ.get("GLANCE_HELPER_KEY", "")
if key != expected_key:
return Response(content="Unauthorized", status_code=401)
safe_user = re.sub(r'[^a-zA-Z0-9_-]', '', user) or "default"
sections = load_userdata(safe_user)
if 0 <= index < len(sections["Motivation"]):
sections["Motivation"].pop(index)
if save_userdata(safe_user, sections):
return {"status": "ok"}
return Response(content="Failed", status_code=500)
@APP.get("/userdata/motivation/random")
def motivation_random(key: str = "", user: str = "default"):
"""Get a random motivation quote as JSON."""
expected_key = os.environ.get("GLANCE_HELPER_KEY", "")
if key != expected_key:
return Response(content="Unauthorized", status_code=401)
safe_user = re.sub(r'[^a-zA-Z0-9_-]', '', user) or "default"
sections = load_userdata(safe_user)
quotes = sections.get("Motivation", [])
if quotes:
return {"quote": _random.choice(quotes), "total": len(quotes)}
return {"quote": "", "total": 0}
# ================================
# Időkép configuration
# ================================