2017-11-09 05:04:48 +01:00
|
|
|
import logging
|
|
|
|
import json
|
|
|
|
import websocket
|
|
|
|
|
|
|
|
from .. import Backend
|
|
|
|
|
|
|
|
class PushbulletBackend(Backend):
|
2017-11-29 02:42:36 +01:00
|
|
|
def _init(self, token, device):
|
2017-11-09 05:04:48 +01:00
|
|
|
self.token = token
|
2017-11-09 05:10:15 +01:00
|
|
|
self.device = device
|
2017-11-09 05:04:48 +01:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _on_init(ws):
|
|
|
|
logging.info('Connection opened')
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _on_close(ws):
|
|
|
|
logging.info('Connection closed')
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _on_msg(ws, msg):
|
|
|
|
ws.backend._on_push(msg)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _on_error(ws, e):
|
|
|
|
logging.exception(e)
|
2017-11-27 09:56:59 +01:00
|
|
|
self.ws.close()
|
|
|
|
self._init_socket()
|
2017-11-09 05:04:48 +01:00
|
|
|
|
|
|
|
def _on_push(self, data):
|
2017-11-29 02:42:36 +01:00
|
|
|
try:
|
|
|
|
data = json.loads(data) if isinstance(data, str) else push
|
|
|
|
except Exception as e:
|
|
|
|
logging.exception(e)
|
|
|
|
return
|
2017-11-09 05:04:48 +01:00
|
|
|
|
|
|
|
if data['type'] != 'push':
|
|
|
|
return # Not a push notification
|
|
|
|
|
|
|
|
push = data['push']
|
|
|
|
logging.debug('Received push: {}'.format(push))
|
|
|
|
|
|
|
|
if 'body' not in push:
|
|
|
|
return
|
|
|
|
|
|
|
|
body = push['body']
|
|
|
|
try:
|
|
|
|
body = json.loads(body)
|
|
|
|
except ValueError as e:
|
|
|
|
return
|
|
|
|
|
|
|
|
self.on_msg(body)
|
|
|
|
|
2017-11-27 09:56:59 +01:00
|
|
|
def _init_socket(self):
|
2017-11-09 05:04:48 +01:00
|
|
|
self.ws = websocket.WebSocketApp(
|
|
|
|
'wss://stream.pushbullet.com/websocket/' + self.token,
|
|
|
|
on_open = self._on_init,
|
|
|
|
on_message = self._on_msg,
|
|
|
|
on_error = self._on_error,
|
|
|
|
on_close = self._on_close)
|
|
|
|
|
|
|
|
self.ws.backend = self
|
2017-11-27 09:56:59 +01:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
self.init_socket()
|
2017-11-09 05:04:48 +01:00
|
|
|
self.ws.run_forever()
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|
|
|
|
|