Browse Source

add webserver

master
Florin Tobler 5 months ago
parent
commit
f9c4d3e2db
  1. 0
      chatbug/ui/__init__.py
  2. 20
      chatbug/ui/__main__.py
  3. 3771
      chatbug/ui/bottle.py
  4. 50
      chatbug/ui/bottle_svr.py
  5. 47
      chatbug/ui/file_watchdog.py
  6. 10
      chatbug/ui/server.py
  7. 29
      chatbug/ui/serverwait.py
  8. 30
      chatbug/ui/ui.py

0
chatbug/ui/__init__.py

20
chatbug/ui/__main__.py

@ -0,0 +1,20 @@
from .server import start_server
from .serverwait import wait_for_server
from .ui import start_ui, _start_sandboxed
def start_ui():
svr = start_server(start_thread=False)
url = f"http://localhost:{svr.port}"
# wait_for_server(url)
# # start_ui(threaded=False)
# import webview
# w = webview.create_window('asdf', '../../web/index.html', min_size=(1200, 900), zoomable=True)
# webview.start(ssl=True)
if __name__ == "__main__":
start_ui()

3771
chatbug/ui/bottle.py

File diff suppressed because it is too large

50
chatbug/ui/bottle_svr.py

@ -0,0 +1,50 @@
#tornado needs this or it does not run
import asyncio
try:
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
except AttributeError:
print("Probably running on linux")
from bottle import route, run, response, static_file, request, post
from .file_watchdog import FileWatchdog
class BottleServer:
def __init__(self, listen="0.0.0.0", port=8080, start_thread=True, root="web"):
self.root = root
self.port = port
self.listen = listen
self.wdt = FileWatchdog(self.root)
if start_thread:
import threading
self.thread = threading.Thread(target=self._run, args=())
self.thread.name = "BottleServerThread"
self.thread.daemon = True
self.thread.start()
else:
self._run()
def _home(self):
return static_file("index.html", root= self.root)
def _watchdog(self):
return str(self.wdt.time)
def _files(self, name):
if name.endswith(".vue"):
return static_file(name, root= self.root, mimetype="text/html")
return static_file(name, root= self.root)
def _run(self):
route('/')(self._home)
route('/watchdog')(self._watchdog)
route('/<name:path>')(self._files)
print(f"Starting server at {self.listen}:{self.port}")
run(host=self.listen, port=self.port, debug=False, threaded=True, quiet=True)

47
chatbug/ui/file_watchdog.py

@ -0,0 +1,47 @@
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def __init__(self, function):
self.function = function
def on_any_event(self, _event):
# Handle the event (e.g., file created, modified, deleted)
self.function()
class FileWatchdog:
def __init__(self, path):
self.path = path
self.time = 0
event_handler = MyHandler(lambda: self.event_handler())
self.observer = Observer()
self.observer.schedule(event_handler, path, recursive=True)
self.observer.start()
def event_handler(self):
#print("change detected")
self.time = time.time()
def stop(self):
self.observer.stop()
if __name__ == "__main__":
wdt = FileWatchdog("./web")
try:
while True:
time.sleep(1)
print(wdt.time)
except KeyboardInterrupt:
wdt.stop()

10
chatbug/ui/server.py

@ -0,0 +1,10 @@
from .bottle_svr import BottleServer
def start_server(start_thread=False):
print("server start")
return BottleServer(start_thread=start_thread, root="web")
if __name__ == "__main__":
start_server()

29
chatbug/ui/serverwait.py

@ -0,0 +1,29 @@
import time
import requests
import socket
def wait_for_server(url, timeout=10, retry_interval=0.5):
"""
Waits for a web server to become available by polling its URL.
"""
start_time = time.monotonic()
while time.monotonic() - start_time < timeout:
try:
# First, try a simple TCP connection to check if the port is open
hostname, port = url.split("//")[1].split(":")
port = int(port)
with socket.create_connection((hostname, port), timeout=retry_interval):
pass # If the connection succeeds, continue to the HTTP check
# Then, make an HTTP request to ensure the server is responding correctly
response = requests.get(url, timeout=retry_interval)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
return # Server is up and responding correctly
except (requests.exceptions.RequestException, socket.error) as e:
print(f"Server not yet available: {e}. Retrying in {retry_interval} seconds...")
time.sleep(retry_interval)
raise TimeoutError(f"Server at {url} did not become available within {timeout} seconds.")

30
chatbug/ui/ui.py

@ -0,0 +1,30 @@
import webview
from threading import Thread
def start_ui(threaded=False):
if threaded:
_start_threaded()
else:
_start_normal()
def _start_threaded():
t = Thread(target=start_ui, args=[False])
t.run()
def _start_normal():
webview.create_window('Geargenerator', 'http://localhost:8080', min_size=(1200, 900), zoomable=True)
webview.start()
def _start_sandboxed():
webview.create_window('Geargenerator', 'web_v2/geargenerator.html', min_size=(1200, 900), zoomable=True)
webview.start(ssl=True)
if __name__ == "__main__":
_start_sandboxed()
# start_ui(threaded=False)
Loading…
Cancel
Save