| 1 |
# vim:fileencoding=utf-8 |
| 2 |
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net> |
| 3 |
from __python__ import bound_methods, hash_literals |
| 4 |
|
| 5 |
MAX_RETRIES = 10 |
| 6 |
|
| 7 |
|
| 8 |
class Watcher: |
| 9 |
def __init__(self, autoreload_port): |
| 10 |
host = document.location.host.split(':')[0] |
| 11 |
self.url = 'ws://' + host + ':' + autoreload_port |
| 12 |
self.retries = 0 |
| 13 |
self.interval = 100 |
| 14 |
self.disable = False |
| 15 |
self.opened_at_least_once = False |
| 16 |
self.reconnect() |
| 17 |
|
| 18 |
def reconnect(self): |
| 19 |
try: |
| 20 |
self.ws = WebSocket(self.url) |
| 21 |
except DOMException as e: |
| 22 |
if e.name == 'SecurityError': |
| 23 |
console.log('Not allowed to connect to auto-reload watcher, probably because using a self-signed, or otherwise invalid SSL certificate') |
| 24 |
return |
| 25 |
raise |
| 26 |
|
| 27 |
self.ws.onopen = def (event): |
| 28 |
self.retries = 0 |
| 29 |
self.opened_at_least_once = True |
| 30 |
self.interval = 100 |
| 31 |
print('Connected to reloading WebSocket server at: ' + self.url) |
| 32 |
window.addEventListener('beforeunload', def (event): |
| 33 |
print('Shutting down connection to reload server, before page unload') |
| 34 |
self.disable = True |
| 35 |
self.ws.close() |
| 36 |
) |
| 37 |
|
| 38 |
self.ws.onmessage = def (event): |
| 39 |
if event.data is not 'ping': |
| 40 |
print('Received message from reload server: ' + event.data) |
| 41 |
if event.data is 'reload': |
| 42 |
self.reload_app() |
| 43 |
|
| 44 |
self.ws.onclose = def (event): |
| 45 |
if self.disable or not self.opened_at_least_once: |
| 46 |
return |
| 47 |
print('Connection to reload server closed with code: ' + event.code + ' and reason: ' + event.reason) |
| 48 |
self.retries += 1 |
| 49 |
if (self.retries < MAX_RETRIES): |
| 50 |
setTimeout(self.reconnect, self.interval) |
| 51 |
else: |
| 52 |
self.reload_app() |
| 53 |
|
| 54 |
def reload_app(self): |
| 55 |
window.location.reload(True) |
| 56 |
|
| 57 |
|
| 58 |
def create_auto_reload_watcher(autoreload_port): |
| 59 |
if not create_auto_reload_watcher.watcher: |
| 60 |
create_auto_reload_watcher.watcher = Watcher(autoreload_port) |
| 61 |
return create_auto_reload_watcher.watcher |