6 from threading import Thread
8 from datetime import datetime
12 import renderer_catalog
15 import trigger_catalog
19 def filter_news_during_dinnertime(page: str) -> bool:
21 is_dinnertime = now.hour >= 17 and now.hour <= 20
22 return not is_dinnertime or not (
25 or "mynorthwest" in page
33 def thread_change_current() -> None:
34 page_chooser = chooser.weighted_random_chooser_with_triggers(
35 trigger_catalog.get_triggers(), [filter_news_during_dinnertime]
41 (page, triggered) = page_chooser.choose_next_page()
44 print("chooser[%s] - WE ARE TRIGGERED." % utils.timestamp())
47 "chooser[%s] - EMERGENCY PAGE %s LOAD NEEDED"
48 % (utils.timestamp(), page)
51 f = open(os.path.join(constants.pages_dir, "current.shtml"), "w")
55 print("chooser[%s] - page does not exist?!" % (utils.timestamp()))
58 swap_page_target = now + constants.refresh_period_sec
60 # Also notify XMLHTTP clients that they need to refresh now.
61 path = os.path.join(constants.pages_dir, "reload_immediately.html")
63 f.write("Reload, suckers!")
66 # Fix this hack... maybe read the webserver logs and see if it
67 # actually was picked up?
71 elif now >= swap_page_target:
75 "chooser[%s] - nominal choice got the same page..."
80 print("chooser[%s] - nominal choice of %s" % (utils.timestamp(), page))
82 f = open(os.path.join(constants.pages_dir, "current.shtml"), "w")
86 print("chooser[%s] - page does not exist?!" % (utils.timestamp()))
89 swap_page_target = now + constants.refresh_period_sec
93 def emit_wrapped(f, filename) -> None:
94 def pick_background_color() -> str:
96 if now.hour <= 6 or now.hour >= 21:
98 elif now.hour == 7 or now.hour == 20:
103 age = utils.describe_age_of_file_briefly(f"pages/{filename}")
104 bgcolor = pick_background_color()
108 <TITLE>Kitchen Kiosk</TITLE>
109 <LINK rel="stylesheet" type="text/css" href="style.css">
110 <SCRIPT TYPE="text/javascript">
112 // Zoom the 'contents' div to fit without scrollbars and then make
114 function zoomScreen() {
117 document.getElementById("content").style.zoom = z+"%%";
118 var body = document.body;
119 var html = document.documentElement;
120 var height = Math.max(body.scrollHeight,
125 var windowHeight = window.innerHeight;
126 var width = Math.max(body.scrollWidth,
131 var windowWidth = window.innerWidth;
132 var heightRatio = height / windowHeight;
133 var widthRatio = width / windowWidth;
135 if (heightRatio <= 1.0 && widthRatio <= 1.0) {
140 document.getElementById("content").style.visibility = "visible";
143 // Load IMG tags with DATA-SRC attributes late.
144 function lateLoadImages() {
145 var image = document.getElementsByTagName('img');
146 for (var i = 0; i < image.length; i++) {
147 if (image[i].getAttribute('DATA-SRC')) {
148 image[i].setAttribute('SRC', image[i].getAttribute('DATA-SRC'));
153 // Operate the clock at the top of the page.
154 function runClock() {
155 var today = new Date();
156 var h = today.getHours();
157 var ampm = h >= 12 ? 'pm' : 'am';
159 h = h ? h : 12; // the hour '0' should be '12'
160 var m = maybeAddZero(today.getMinutes());
162 if (today.getSeconds() %% 2 == 0) {
163 colon = "<FONT STYLE='color: #%s; font-size: 4vmin; font-weight: bold'>:</FONT>";
165 document.getElementById("time").innerHTML = h + colon + m + ampm;
166 document.getElementById("date").innerHTML = today.toDateString();
167 var t = setTimeout(function(){runClock()}, 1000);
170 // Helper method for running the clock.
171 function maybeAddZero(x) {
172 return (x < 10) ? "0" + x : x;
175 // Do something on page load.
176 function addLoadEvent(func) {
177 var oldonload = window.onload;
178 if (typeof window.onload != 'function') {
179 window.onload = func;
181 window.onload = function() {
190 // Sleep thread helper.
191 const sleep = (milliseconds) => {
192 return new Promise(resolve => setTimeout(resolve, milliseconds))
195 var loadedDate = new Date();
197 addLoadEvent(zoomScreen);
198 addLoadEvent(runClock);
199 addLoadEvent(lateLoadImages);
201 // Runs the countdown line at the bottom and is responsible for
202 // normal page reloads caused by the expiration of a timer.
203 (function countdown() {
206 var now = new Date();
207 var deltaMs = now.getTime() - loadedDate.getTime();
209 var remainingMs = (totalMs - deltaMs);
211 if (remainingMs > 0) {
212 var hr = document.getElementById("countdown");
213 var width = (remainingMs / (totalMs - 5000)) * 100.0;
215 hr.style.visibility = "visible";
216 hr.style.width = " ".concat(width, "%%");
217 hr.style.backgroundColor = "maroon";
220 // Reload unconditionally after 22 sec.
221 window.location.reload();
224 // Brief sleep before doing it all over again.
225 sleep(50).then(() => {
231 // Periodically checks for emergency reload events.
235 var xhr = new XMLHttpRequest();
237 'http://wannabe.house/kiosk/pages/reload_immediately.html');
240 if (xhr.status === 200) {
241 window.location.reload();
243 sleep(500).then(() => {
254 <TABLE style="height:100%%; width:100%%" BORDER=0>
257 <DIV id="date"> </DIV>
259 <TD ALIGN="center"><FONT COLOR=#bbbbbb>
260 <DIV id="info"></DIV></FONT>
263 <DIV id="time"> </DIV>
266 <TR STYLE="vertical-align:top">
268 <DIV ID="content" STYLE="zoom: 1; visibility: hidden;">
269 <!-- BEGIN main page contents. -->
270 <!--#include virtual=\"%s\"-->
271 <!-- END main page contents. -->
274 <DIV STYLE="position: absolute; top:1030px; width:99%%">
276 <FONT SIZE=2 COLOR=#bbbbbb>%s @ %s ago.</FONT>
278 <HR id="countdown" STYLE="width:0px;
285 background-color:#ffffff;">
293 constants.refresh_period_sec * 1000,
302 def thread_invoke_renderers() -> None:
304 print(f"renderer[{utils.timestamp()}]: invoking all renderers in catalog...")
305 for r in renderer_catalog.get_renderers():
309 except Exception as e:
310 traceback.print_exc()
312 f"renderer[{utils.timestamp()}] unknown exception in {r.get_name()}, swallowing it."
315 traceback.print_exc()
317 f"renderer[{utils.timestamp()}] unknown error in {r.get_name()}, swallowing it."
319 delta = time.time() - now
322 f"renderer[{utils.timestamp()}]: Warning: {r.get_name()}'s rendering took {delta:%5.2f}s."
325 f"renderer[{utils.timestamp()}]: thread having a little break for {constants.render_period_sec}s..."
327 time.sleep(constants.render_period_sec)
330 if __name__ == "__main__":
331 logging.basicConfig()
332 changer_thread = None
333 renderer_thread = None
335 if changer_thread == None or not changer_thread.is_alive():
337 f"MAIN[{utils.timestamp()}] - (Re?)initializing chooser thread... (wtf?!)"
339 changer_thread = Thread(target=thread_change_current, args=())
340 changer_thread.start()
341 if renderer_thread == None or not renderer_thread.is_alive():
343 f"MAIN[{utils.timestamp()}] - (Re?)initializing render thread... (wtf?!)"
345 renderer_thread = Thread(target=thread_invoke_renderers, args=())
346 renderer_thread.start()
348 print("Should never get here.")