-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
840 lines (701 loc) · 32.6 KB
/
Copy pathapp.py
File metadata and controls
840 lines (701 loc) · 32.6 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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
import json
import os
import threading
import time as time_module
from dataclasses import asdict, is_dataclass
from datetime import datetime, timezone, time, date
from typing import Any, Dict, List, Optional
import streamlit as st
from databricks import sdk
# Set page config
st.set_page_config(
page_title="BrickSwitch - Databricks Apps Manager",
page_icon="🧱",
layout="wide",
initial_sidebar_state="collapsed"
)
# Custom CSS for modern styling
st.markdown("""
<style>
.main-header {
text-align: center;
padding: 1rem 0;
font-weight: 700;
margin-bottom: 1rem;
border-bottom: 2px solid #1f77b4;
}
.status-badge {
padding: 0.2rem 0.6rem;
border-radius: 3px;
font-size: 0.8rem;
font-weight: 600;
display: inline-block;
}
.status-started {
background-color: #28a745;
color: white;
}
.status-stopped {
background-color: #dc3545;
color: white;
}
.compact-metric {
text-align: center;
padding: 0.5rem;
border: 1px solid #ddd;
border-radius: 3px;
margin: 0.2rem 0;
}
</style>
""", unsafe_allow_html=True)
@st.cache_resource(show_spinner=False)
def get_workspace_client() -> sdk.WorkspaceClient:
return sdk.WorkspaceClient()
# Schedule management functions
def get_schedules_file_path():
"""Get the path to the schedules file."""
return os.path.join(os.getcwd(), "app_schedules.json")
def load_schedules() -> Dict[str, Any]:
"""Load schedules from file."""
schedules_file = get_schedules_file_path()
if os.path.exists(schedules_file):
try:
with open(schedules_file, 'r') as f:
return json.load(f)
except Exception:
return {}
return {}
def save_schedules(schedules: Dict[str, Any]):
"""Save schedules to file."""
schedules_file = get_schedules_file_path()
try:
with open(schedules_file, 'w') as f:
json.dump(schedules, f, indent=2, default=str)
except Exception as e:
st.error(f"Failed to save schedules: {e}")
def get_app_schedule(app_id: str) -> Optional[Dict[str, Any]]:
"""Get schedule for a specific app."""
schedules = load_schedules()
return schedules.get(app_id)
def save_app_schedule(app_id: str, schedule: Dict[str, Any]):
"""Save schedule for a specific app."""
schedules = load_schedules()
schedules[app_id] = schedule
save_schedules(schedules)
def delete_app_schedule(app_id: str):
"""Delete schedule for a specific app."""
schedules = load_schedules()
if app_id in schedules:
del schedules[app_id]
save_schedules(schedules)
def is_app_scheduled_to_run(app_id: str) -> bool:
"""Check if app should be running based on schedule."""
schedule = get_app_schedule(app_id)
if not schedule or not schedule.get("enabled", False):
return False
now = datetime.now()
current_time = now.time()
current_date = now.date()
current_weekday = now.strftime("%A")
# Check if today is a custom off date
custom_off_dates = schedule.get("custom_off_dates", [])
if current_date.isoformat() in custom_off_dates:
return False
# Check weekend setting
if schedule.get("weekend_off", False) and current_weekday in ["Saturday", "Sunday"]:
return False
# Check additional off days
if current_weekday in schedule.get("additional_off_days", []):
return False
# Check time range
start_time = time.fromisoformat(schedule.get("start_time", "09:00:00"))
stop_time = time.fromisoformat(schedule.get("stop_time", "18:00:00"))
return start_time <= current_time <= stop_time
def get_schedule_status(app_id: str) -> str:
"""Get a human-readable schedule status."""
schedule = get_app_schedule(app_id)
if not schedule:
return "No schedule"
if not schedule.get("enabled", False):
return "Schedule disabled"
if is_app_scheduled_to_run(app_id):
return "Should be running"
else:
return "Should be stopped"
def get_execution_log_file():
"""Get path to execution log file."""
return os.path.join(os.getcwd(), "schedule_execution.log")
def log_execution(message: str):
"""Log execution message with timestamp."""
timestamp = datetime.now().isoformat()
log_entry = f"[{timestamp}] {message}\n"
try:
with open(get_execution_log_file(), "a") as f:
f.write(log_entry)
except Exception:
pass # Fail silently if logging fails
def get_app_current_state(app_id: str) -> str:
"""Get current state of an app from Databricks."""
try:
workspace_client = get_workspace_client()
# List all apps and find the one with matching name
for app in workspace_client.apps.list():
app_data = _serialize(app)
if app_data.get("name") == app_id:
active_deployment = app_data.get("active_deployment", {})
status = active_deployment.get("status", {})
if active_deployment and status.get("message"):
return "started"
else:
return "stopped"
return "not_found"
except Exception:
return "unknown"
def execute_schedules():
"""Execute all scheduled actions."""
schedules = load_schedules()
workspace_client = get_workspace_client()
results = []
log_execution("Starting schedule execution")
for app_id, schedule in schedules.items():
if not schedule.get("enabled", False):
continue
should_run = is_app_scheduled_to_run(app_id)
current_state = get_app_current_state(app_id)
try:
action_needed = None
if should_run and current_state == "stopped":
action_needed = "start"
elif not should_run and current_state == "started":
action_needed = "stop"
if action_needed:
if action_needed == "start":
workspace_client.apps.start(app_id)
message = f"Started app {app_id}"
else:
workspace_client.apps.stop(app_id)
message = f"Stopped app {app_id}"
results.append(message)
log_execution(message)
else:
message = f"App {app_id}: no action needed (should_run={should_run}, current_state={current_state})"
results.append(message)
except Exception as e:
error_msg = f"App {app_id}: error - {e}"
results.append(error_msg)
log_execution(error_msg)
log_execution(f"Schedule execution completed. {len(results)} actions processed.")
return results
def get_scheduler_status_file():
"""Get path to scheduler status file."""
return os.path.join(os.getcwd(), "scheduler_status.json")
def save_scheduler_status(running: bool):
"""Save scheduler status to file."""
status_file = get_scheduler_status_file()
try:
with open(status_file, 'w') as f:
json.dump({"running": running, "updated_at": datetime.now().isoformat()}, f)
except Exception:
pass
def load_scheduler_status() -> bool:
"""Load scheduler status from file."""
status_file = get_scheduler_status_file()
if os.path.exists(status_file):
try:
with open(status_file, 'r') as f:
status = json.load(f)
return status.get("running", False)
except Exception:
return False
return False
def schedule_worker():
"""Background worker that executes schedules every minute."""
log_execution("Scheduler worker thread started")
while True:
try:
# Check if we should continue running by reading from file
# (can't access st.session_state from background thread)
if not load_scheduler_status():
log_execution("Scheduler stopped (status file indicates false)")
break
# Execute schedules
execute_schedules()
# Wait for 60 seconds before next execution, checking every second
for _ in range(60):
if not load_scheduler_status():
log_execution("Scheduler stopped during wait period")
break
time_module.sleep(1)
else:
# Continue if we didn't break out of the loop
continue
# If we broke out of the wait loop, exit
break
except Exception as e:
log_execution(f"Scheduler error: {e}")
# Even on error, check if we should continue
if load_scheduler_status():
time_module.sleep(60) # Wait a minute before retrying
else:
break
log_execution("Scheduler worker thread stopped")
def start_scheduler():
"""Start the background scheduler."""
if st.session_state.get("scheduler_running", False):
return False # Already running
st.session_state["scheduler_running"] = True
save_scheduler_status(True)
scheduler_thread = threading.Thread(target=schedule_worker, daemon=True)
scheduler_thread.start()
st.session_state["scheduler_thread"] = scheduler_thread
log_execution("Scheduler started")
return True
def stop_scheduler():
"""Stop the background scheduler."""
if not st.session_state.get("scheduler_running", False):
return False # Not running
st.session_state["scheduler_running"] = False
save_scheduler_status(False)
# Wait a moment for the thread to see the change
time_module.sleep(2)
log_execution("Scheduler stop requested")
return True
def cleanup_dead_thread():
"""Clean up dead scheduler thread."""
if "scheduler_thread" in st.session_state:
thread = st.session_state["scheduler_thread"]
if thread and not thread.is_alive():
log_execution("Cleaning up dead scheduler thread")
del st.session_state["scheduler_thread"]
st.session_state["scheduler_running"] = False
save_scheduler_status(False)
return True
return False
def is_scheduler_running():
"""Check if scheduler is running."""
# Initialize from file on first load
if "scheduler_running" not in st.session_state:
st.session_state["scheduler_running"] = load_scheduler_status()
# Clean up dead threads
cleanup_dead_thread()
# Return current status
return st.session_state.get("scheduler_running", False)
def _format_timestamp(raw_value: Any) -> str:
if not raw_value:
return "-"
if isinstance(raw_value, str):
return raw_value
try:
if isinstance(raw_value, (int, float)):
dt = datetime.fromtimestamp(raw_value / 1000, tz=timezone.utc).astimezone()
return dt.strftime("%Y-%m-%d %H:%M:%S")
except Exception:
pass
return str(raw_value)
def _serialize(obj: Any) -> Any:
if obj is None:
return None
if isinstance(obj, (str, int, float, bool)):
return obj
if isinstance(obj, list):
return [_serialize(item) for item in obj]
if isinstance(obj, dict):
return {key: _serialize(value) for key, value in obj.items()}
if is_dataclass(obj):
return _serialize(asdict(obj))
if hasattr(obj, "as_dict"):
return _serialize(obj.as_dict())
if hasattr(obj, "__dict__"):
return _serialize({key: value for key, value in obj.__dict__.items() if not key.startswith("_")})
return str(obj)
def _normalize_app(app: Any) -> Dict[str, Any]:
serialized = _serialize(app) or {}
# Extract from the actual API response structure
name = serialized.get("name") or ""
description = serialized.get("description") or ""
creator = serialized.get("creator") or ""
url = serialized.get("url") or ""
# Extract state from active_deployment status
active_deployment = serialized.get("active_deployment") or {}
status = active_deployment.get("status") or {}
state = status.get("state") or {}
# Determine app state - if active_deployment exists and has status, it's likely running
app_state = "started" if active_deployment and status.get("message") else "stopped"
# Extract source code path from active_deployment
deployment_artifacts = active_deployment.get("deployment_artifacts") or {}
source_code_path = (
active_deployment.get("source_code_path") or
deployment_artifacts.get("source_code_path") or
""
)
# Extract service principal info
service_principal_name = serialized.get("service_principal_name") or ""
service_principal_id = serialized.get("service_principal_id") or ""
# Use the name as the app_id for API calls (this is what the API expects)
app_id = name
normalized = {
"app_id": app_id,
"name": name,
"display_name": name, # Use name as display_name
"description": description,
"state": app_state,
"default_url": url,
"source_code_path": source_code_path,
"creator_user_name": creator,
"created": _format_timestamp(serialized.get("create_time")),
"updated": _format_timestamp(serialized.get("update_time")),
"last_deployed": _format_timestamp(active_deployment.get("update_time")) if active_deployment else "-",
"service_principal_name": service_principal_name,
"service_principal_id": service_principal_id,
"compute_status": serialized.get("compute_status") or {},
"active_deployment": active_deployment,
"raw": serialized,
}
return normalized
@st.cache_data(ttl=60, show_spinner=False)
def load_apps() -> List[Dict[str, Any]]:
workspace_client = get_workspace_client()
apps: List[Dict[str, Any]] = []
for app in workspace_client.apps.list():
apps.append(_normalize_app(app))
return apps
def main():
# Initialize scheduler status on first load
if "scheduler_initialized" not in st.session_state:
st.session_state["scheduler_initialized"] = True
st.session_state["scheduler_running"] = load_scheduler_status()
# If status file says running but no thread exists, start it
if st.session_state["scheduler_running"] and "scheduler_thread" not in st.session_state:
scheduler_thread = threading.Thread(target=schedule_worker, daemon=True)
scheduler_thread.start()
st.session_state["scheduler_thread"] = scheduler_thread
log_execution("Scheduler thread restarted on app load")
# Compact header
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
if st.button("🔄 Refresh", type="primary"):
load_apps.clear()
st.rerun()
with col2:
st.markdown('<h1 class="main-header">🧱 BrickSwitch</h1>', unsafe_allow_html=True)
with col3:
try:
workspace_client = get_workspace_client()
st.success("Connected", icon="✅")
except Exception as e:
st.error("Disconnected", icon="❌")
st.stop()
# Load apps
with st.spinner("Loading..."):
try:
apps_data = load_apps()
except Exception as exc:
st.error(f"Failed to load apps: {exc}")
st.stop()
if not apps_data:
st.info("No apps found.")
st.stop()
# Compact stats
started_apps = sum(1 for app in apps_data if app["state"].lower() == "started")
stopped_apps = len(apps_data) - started_apps
# Get schedule metrics
schedules = load_schedules()
scheduled_apps = len([s for s in schedules.values() if s.get("enabled", False)])
col1, col2, col3, col4, col5 = st.columns(5)
with col1:
st.markdown(f'<div class="compact-metric"><strong>{len(apps_data)}</strong><br>Total</div>', unsafe_allow_html=True)
with col2:
st.markdown(f'<div class="compact-metric"><strong>{started_apps}</strong><br>Running</div>', unsafe_allow_html=True)
with col3:
st.markdown(f'<div class="compact-metric"><strong>{stopped_apps}</strong><br>Stopped</div>', unsafe_allow_html=True)
with col4:
st.markdown(f'<div class="compact-metric"><strong>{scheduled_apps}</strong><br>Scheduled</div>', unsafe_allow_html=True)
with col5:
filter_text = st.text_input("🔍 Filter", placeholder="Search...", label_visibility="collapsed").strip()
# Schedule execution section
if scheduled_apps > 0:
is_running = is_scheduler_running()
scheduler_status = "🟢 Running" if is_running else "🔴 Stopped"
# Debug info
thread_alive = False
if "scheduler_thread" in st.session_state:
thread = st.session_state["scheduler_thread"]
thread_alive = thread.is_alive() if thread else False
st.markdown(f"**Auto Scheduler: {scheduler_status}**")
# Show debug info in development
if st.checkbox("Show Debug Info", value=False):
st.write(f"Session state scheduler_running: {st.session_state.get('scheduler_running', 'Not set')}")
st.write(f"Thread exists: {'scheduler_thread' in st.session_state}")
st.write(f"Thread alive: {thread_alive}")
st.write(f"Status file exists: {os.path.exists(get_scheduler_status_file())}")
if os.path.exists(get_scheduler_status_file()):
try:
with open(get_scheduler_status_file(), 'r') as f:
status_content = json.load(f)
st.write(f"Status file content: {status_content}")
except:
st.write("Error reading status file")
# Manual cleanup/restart buttons
col_debug1, col_debug2 = st.columns(2)
with col_debug1:
if st.button("🧹 Clean Up Dead Thread"):
if cleanup_dead_thread():
st.success("Dead thread cleaned up")
else:
st.info("No dead thread to clean up")
st.rerun()
with col_debug2:
if st.button("🔄 Force Restart Scheduler"):
# Force stop and restart
st.session_state["scheduler_running"] = False
save_scheduler_status(False)
time_module.sleep(1)
if "scheduler_thread" in st.session_state:
del st.session_state["scheduler_thread"]
# Start fresh
if start_scheduler():
st.success("Scheduler force restarted")
else:
st.error("Failed to restart scheduler")
st.rerun()
col1, col2, col3, col4 = st.columns([1, 1, 1, 1])
with col1:
if is_running:
if st.button("⏹️ Stop Auto Scheduler", help="Stop automatic schedule execution"):
if stop_scheduler():
st.success("Auto scheduler stopped")
st.rerun()
else:
st.error("Failed to stop scheduler")
else:
if st.button("▶️ Start Auto Scheduler", help="Start automatic schedule execution"):
try:
if start_scheduler():
st.success("Auto scheduler started")
st.rerun()
else:
st.error("Failed to start scheduler - already running")
except Exception as e:
st.error(f"Error starting scheduler: {e}")
log_execution(f"Error starting scheduler: {e}")
with col2:
if st.button("🚀 Execute Now", help="Execute all schedules immediately"):
results = execute_schedules()
st.info(f"Manual execution completed. {len(results)} actions processed.")
with st.expander("Execution Results"):
for result in results:
st.write(result)
with col3:
if st.button("📊 Schedule Overview"):
@st.dialog("Schedule Overview")
def show_schedule_overview():
st.markdown("### All App Schedules")
if not schedules:
st.info("No schedules configured.")
return
for app_id, schedule in schedules.items():
if schedule.get("enabled", False):
status = get_schedule_status(app_id)
st.markdown(f"**{app_id}**")
st.markdown(f"- Start: {schedule.get('start_time', 'N/A')}")
st.markdown(f"- Stop: {schedule.get('stop_time', 'N/A')}")
st.markdown(f"- Weekend off: {schedule.get('weekend_off', False)}")
st.markdown(f"- Status: {status}")
st.markdown("---")
show_schedule_overview()
with col4:
if st.button("📜 View Logs"):
@st.dialog("Schedule Execution Logs")
def show_logs():
st.markdown("### Recent Schedule Execution Logs")
log_file = get_execution_log_file()
if os.path.exists(log_file):
try:
with open(log_file, "r") as f:
logs = f.readlines()
# Show last 50 lines
recent_logs = logs[-50:] if len(logs) > 50 else logs
if recent_logs:
for log_line in reversed(recent_logs):
st.text(log_line.strip())
else:
st.info("No logs available.")
except Exception as e:
st.error(f"Failed to read logs: {e}")
else:
st.info("No log file found. Run the scheduler to generate logs.")
show_logs()
if filter_text:
lowered = filter_text.lower()
filtered_apps = [
app for app in apps_data
if lowered in app["display_name"].lower()
or lowered in app["name"].lower()
or lowered in app["app_id"].lower()
or lowered in app["creator_user_name"].lower()
]
else:
filtered_apps = apps_data
# Apps table with action buttons
if filtered_apps:
# Header row
header_cols = st.columns([1, 3, 2, 2, 2, 1, 2, 2])
with header_cols[0]:
st.markdown("**Action**")
with header_cols[1]:
st.markdown("**Name**")
with header_cols[2]:
st.markdown("**State**")
with header_cols[3]:
st.markdown("**Creator**")
with header_cols[4]:
st.markdown("**Updated**")
with header_cols[5]:
st.markdown("**Schedule**")
with header_cols[6]:
st.markdown("**Frontend**")
with header_cols[7]:
st.markdown("**Source**")
st.markdown("---")
# Create table with action buttons and modal dialogs
for i, app in enumerate(filtered_apps):
cols = st.columns([1, 3, 2, 2, 2, 1, 2, 2])
with cols[0]: # Action button column
app_state = app["state"].lower()
if app_state != "started":
if st.button("▶️", key=f"start_{app['app_id']}_{i}", help="Start App"):
# Use st.dialog for confirmation
@st.dialog(f"Start {app['display_name']}?")
def confirm_start():
st.write(f"Are you sure you want to start **{app['display_name']}**?")
col1, col2 = st.columns(2)
with col1:
if st.button("Yes, Start", type="primary", use_container_width=True):
try:
workspace_client = get_workspace_client()
workspace_client.apps.start(app["app_id"])
st.success("App start request sent!")
load_apps.clear()
st.rerun()
except Exception as exc:
st.error(f"Failed to start app: {exc}")
with col2:
if st.button("Cancel", use_container_width=True):
st.rerun()
confirm_start()
else:
if st.button("⏹️", key=f"stop_{app['app_id']}_{i}", help="Stop App"):
# Use st.dialog for confirmation
@st.dialog(f"Stop {app['display_name']}?")
def confirm_stop():
st.write(f"Are you sure you want to stop **{app['display_name']}**?")
col1, col2 = st.columns(2)
with col1:
if st.button("Yes, Stop", type="primary", use_container_width=True):
try:
workspace_client = get_workspace_client()
workspace_client.apps.stop(app["app_id"])
st.success("App stop request sent!")
load_apps.clear()
st.rerun()
except Exception as exc:
st.error(f"Failed to stop app: {exc}")
with col2:
if st.button("Cancel", use_container_width=True):
st.rerun()
confirm_stop()
with cols[1]: # Name
display_name = app["display_name"] or app["name"] or "(Unnamed App)"
st.write(f"**{display_name}**")
with cols[2]: # State with badge
state = app["state"].lower()
if state == "started":
st.markdown('<div class="status-badge status-started">Running</div>', unsafe_allow_html=True)
else:
st.markdown('<div class="status-badge status-stopped">Stopped</div>', unsafe_allow_html=True)
with cols[3]: # Creator
st.write(app["creator_user_name"] or "Unknown")
with cols[4]: # Updated
st.write(app["updated"])
with cols[5]: # Schedule button
schedule_status = get_schedule_status(app["app_id"])
button_text = "⏰" if schedule_status == "No schedule" else "📅"
button_help = f"Schedule App - Current: {schedule_status}"
if st.button(button_text, key=f"schedule_{app['app_id']}_{i}", help=button_help):
# Schedule dialog
@st.dialog(f"Schedule {app['display_name']}")
def schedule_app():
st.markdown(f"### Schedule for **{app['display_name']}**")
# Load existing schedule
existing_schedule = get_app_schedule(app["app_id"]) or {}
col1, col2 = st.columns(2)
with col1:
st.markdown("**Daily Schedule**")
start_time = st.time_input(
"App Start Time",
value=time.fromisoformat(existing_schedule.get("start_time", "09:00:00")),
key=f"start_time_{app['app_id']}"
)
stop_time = st.time_input(
"App Stop Time",
value=time.fromisoformat(existing_schedule.get("stop_time", "18:00:00")),
key=f"stop_time_{app['app_id']}"
)
with col2:
st.markdown("**Options**")
weekend_off = st.checkbox(
"Turn off on weekends",
value=existing_schedule.get("weekend_off", False),
key=f"weekend_off_{app['app_id']}"
)
additional_off_days = st.multiselect(
"Additional off days",
options=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
default=existing_schedule.get("additional_off_days", []),
key=f"off_days_{app['app_id']}"
)
st.markdown("**Custom Off Dates**")
custom_off_dates = st.text_area(
"Define specific off dates (YYYY-MM-DD, one per line)",
value="\n".join(existing_schedule.get("custom_off_dates", [])),
key=f"custom_dates_{app['app_id']}"
)
col1, col2, col3 = st.columns(3)
with col1:
if st.button("Save Schedule", type="primary", use_container_width=True):
schedule_data = {
"start_time": start_time.isoformat(),
"stop_time": stop_time.isoformat(),
"weekend_off": weekend_off,
"additional_off_days": additional_off_days,
"custom_off_dates": [date.strip() for date in custom_off_dates.split('\n') if date.strip()],
"enabled": True,
"created_at": datetime.now().isoformat()
}
save_app_schedule(app["app_id"], schedule_data)
st.success("Schedule saved successfully!")
st.rerun()
with col2:
if existing_schedule and st.button("Delete Schedule", use_container_width=True):
delete_app_schedule(app["app_id"])
st.success("Schedule deleted!")
st.rerun()
with col3:
if st.button("Cancel", use_container_width=True):
st.rerun()
schedule_app()
with cols[6]: # Frontend URL
if app["default_url"]:
st.link_button("🚀", app["default_url"], use_container_width=True, help="Open App")
else:
st.write("—")
with cols[7]: # Source Path
if app["source_code_path"]:
st.link_button("📁", app["source_code_path"], use_container_width=True, help="View Source")
else:
st.write("—")
# Show raw data in expander (not nested)
with st.expander(f"Details: {app['display_name']}", expanded=False):
st.json(app["raw"])
if __name__ == "__main__":
main()