def __init__(self, auth_key, temp_folder, device_name, last_push=0, device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [ d for d in self.pb.devices if d.device_iden == device_iden and d.active ] self.device = results[0] if results else None if not self.device: success, device = self.pb.new_device(device_name) if success: self.device = device else: print("Error ") print(device) self.check_pushes()
def main(): pb = PushBullet(API_KEY) s = Listener(pb,on_push = on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) try: s.run_forever() except KeyboardInterrupt: s.close()
def __init__(self, auth_key, temp_folder, device_name, last_push=time.time(), device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:", device_name, "iden:", device.device_iden) self.device = device except Exception: print("Error: Unable to create device") raise self.check_pushes()
def __init__(self, auth_key, device_name, last_push=time.time(), device_iden=None): self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.download_link) self.last_push = last_push self.device = None if device_iden: results = [ d for d in self.pb.devices if d.device_iden == device_iden and d.active ] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:", device_name, "iden:", device.device_iden) self.device = device except: print("Error: Unable to create device") raise
def main(): apikey = settings.key users = settings.users if apikey == '': print('No pushbullet apikey found in pushy.conf file, or bad formatting') input('Press enter to exit\n>>') return if len(users) < 1: print('No users found in settings.py. Please specifiy at least one (main) user.') input('Press enter to exit \n>>') return pb = Pushbullet(apikey) startup = pb.push_note("Pushy Listener Initiated", "auto start on reboot") handler = PushHandler(pb, users) s = Listener(account=pb, on_push = handler.receive, http_proxy_host = Http_Proxy_Host, http_proxy_port = Http_Proxy_Port) try: s.run_forever() except (Exception, KeyboardInterrupt) as exc: close = pb.push_note('Pushy Listener Closed', '{}'.format(exc)) else: s.close()
def main(): global logger global pidfile global API_KEY global is_alive is_alive = 0 API_KEY = sys.argv[1] logger = logger_init('pushbullet', True) logger.debug("Check PID file") path = os.path.dirname(os.path.realpath(__file__)) + '/../../../../tmp' try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise pidfile = path + '/pushbullet.' + API_KEY + '.pid' createpid = True logger.debug("PID file '" + pidfile + "'") if os.path.exists(pidfile): print("PID file '" + pidfile + "' already exists. Exiting.") logger.debug("PID file '" + pidfile + "' already exists.") logger.debug("Exit 1") sys.exit(1) try: logger.debug("Write PID file") file(pidfile, 'w').write("pid\n") except IOError as e: #logger.error("Line: " + _line()) logger.error("Unable to write PID file: %s [%d]" % (e.strerror, e.errno)) raise SystemExit("Unable to write PID file: %s [%d]" % (e.strerror, e.errno)) logger.debug("Start daemon") daemonize() s = Listener(api_key=API_KEY, on_push=on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) s.run_forever() t = Timer(60, timeout) t.start() sys.exit(0)
def main(): s = Listener(API_KEY, device_id=DEVICE_ID, on_link=on_link, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) try: s.run_forever() except KeyboardInterrupt: s.close()
def run(self): super().run() self.logger.info('Initialized Pushbullet backend - device_id: {}' .format(self.device_name)) self.listener = Listener(account=self.pb, on_push=self.on_push(), http_proxy_host=self.proxy_host, http_proxy_port=self.proxy_port) self.listener.run_forever()
def retrieve_pushes(self): """Retrieve_pushes. Spawn a new Listener and links it to self.on_push. """ from pushbullet import Listener self.listener = Listener(account=self.pushbullet, on_push=self.on_push) _LOGGER.debug("Getting pushes") try: self.listener.run_forever() finally: self.listener.close()
def run_listener(self): from pushbullet import Listener self.logger.info( 'Initializing Pushbullet backend - device_id: {}'.format( self.device_name)) self.listener = Listener(account=self.pb, on_push=self.on_push(), on_error=self.on_error, http_proxy_host=self.proxy_host, http_proxy_port=self.proxy_port) self.listener.run_forever()
def run(self): # noinspection PyPackageRequirements from pushbullet import Listener super().run() self.logger.info( 'Initialized Pushbullet backend - device_id: {}'.format( self.device_name)) self.listener = Listener(account=self.pb, on_push=self.on_push(), http_proxy_host=self.proxy_host, http_proxy_port=self.proxy_port) self.listener.run_forever()
def __init__(self): """Create PushBullet listener.""" self.logger = logging.getLogger(__name__) self.logger.info("Starting PushbulletManager...") self.pb = Pushbullet(os.environ.get("PUSHBULLET_API_TOKEN")) push_list = self.pb.get_pushes(limit=1) if push_list: self.last_mod_time = push_list[0]["modified"] self.pb_listener = Listener(account=self.pb, on_push=self.pb_on_push, on_error=self.pb_on_error, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) self.rmc = ReminderMessageConsumer() self.rmc.start()
def __init__(self, auth_key, temp_folder, device_name, last_push = time.time(), device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:",device_name,"iden:",device.device_iden) self.device = device except: print("Error: Unable to create device") raise self.check_pushes()
def __init__(self, auth_key, temp_folder, device_name, last_push=0, device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: success, device = self.pb.new_device(device_name) if success: self.device = device else: print("Error ") print(device) self.check_pushes()
def __init__(self, parent, account, http_proxy_host=None, http_proxy_port=None): QThread.__init__(self, parent) self.listener = Listener(account, on_push=self.on_push, http_proxy_host=http_proxy_host, http_proxy_port=http_proxy_port) self._account = account self.last_pushes_date = None
def post(self): pb = Pushbullet(API_KEY) push = pb.push_note(title, note) s = Listener(account=pb, on_push=on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT)
def main(): from time import localtime, strftime log = open('PushBulletClient.log', 'a') log.write(strftime('%Y-%m-%d %H:%M:%S', localtime()) + ' Started PushBullet listener, relaying to Home Network\n'); log.close() print 'Started PushBullet listener, relaying to Home Network' global pb pb = Pushbullet(API_KEY) s = Listener(account=pb, on_push=on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) try: s.run_forever() except KeyboardInterrupt: s.close()
class QPushBulletListener(QThread): # signals on_link = pyqtSignal(dict) on_note = pyqtSignal(dict) on_list = pyqtSignal(dict) on_file = pyqtSignal(dict) on_address = pyqtSignal(dict) def __init__(self, parent, account, http_proxy_host=None, http_proxy_port=None): QThread.__init__(self, parent) self.listener = Listener(account, on_push=self.on_push, http_proxy_host=http_proxy_host, http_proxy_port=http_proxy_port) self._account = account self.last_pushes_date = None def on_push(self, notif_push): if notif_push['type'] == 'tickle': success, pushes = self._account.get_pushes(modified_after=str(self.last_pushes_date)) for push in pushes: if 'type' in push: if push['type'] == 'link': self.on_link.emit(push) if push['type'] == 'address': self.on_address.emit(push) if push['type'] == 'note': self.on_note.emit(push) if push['type'] == 'list': self.on_list.emit(push) if push['type'] == 'file': self.on_file.emit(push) self.last_pushes_date = push['modified'] def run(self): self.last_pushes_date = time.time() self.listener.run_forever() def quit(self): try: self.listener.close() except Exception: pass QThread.quit(self)
def _connect(cls, queue): if cls.key and cls.users: cls.pb = Pushbullet(cls.key) cls.handler = PushHandler(cls.users, cls.pb, queue) cls.ear = Listener(account=cls.pb, on_push=cls.handler.catch, http_proxy_host=cls.HPH, http_proxy_port=cls.HPP) else: raise SettingsError('Please check info in your settings.py file')
class PushBulletNotificationProvider: """Provider for an account, leading to one or more sensors.""" def __init__(self, pb): """Start to retrieve pushes from the given Pushbullet instance.""" import threading self.pushbullet = pb self._data = None self.listener = None self.thread = threading.Thread(target=self.retrieve_pushes) self.thread.daemon = True self.thread.start() def on_push(self, data): """Update the current data. Currently only monitors pushes but might be extended to monitor different kinds of Pushbullet events. """ if data["type"] == "push": self._data = data["push"] @property def data(self): """Return the current data stored in the provider.""" return self._data def retrieve_pushes(self): """Retrieve_pushes. Spawn a new Listener and links it to self.on_push. """ from pushbullet import Listener self.listener = Listener(account=self.pushbullet, on_push=self.on_push) _LOGGER.debug("Getting pushes") try: self.listener.run_forever() finally: self.listener.close()
class PushBulletNotificationProvider(): """Provider for an account, leading to one or more sensors.""" def __init__(self, pb): """Start to retrieve pushes from the given Pushbullet instance.""" import threading self.pushbullet = pb self._data = None self.listener = None self.thread = threading.Thread(target=self.retrieve_pushes) self.thread.daemon = True self.thread.start() def on_push(self, data): """Update the current data. Currently only monitors pushes but might be extended to monitor different kinds of Pushbullet events. """ if data['type'] == 'push': self._data = data['push'] @property def data(self): """Return the current data stored in the provider.""" return self._data def retrieve_pushes(self): """Retrieve_pushes. Spawn a new Listener and links it to self.on_push. """ from pushbullet import Listener self.listener = Listener(account=self.pushbullet, on_push=self.on_push) _LOGGER.debug("Getting pushes") try: self.listener.run_forever() finally: self.listener.close()
def run(self): # noinspection PyPackageRequirements from pushbullet import Listener super().run() initialized = False while not initialized: try: self._initialize() initialized = True except Exception as e: self.logger.exception(e) self.logger.error('Pushbullet initialization error: {}'.format(str(e))) time.sleep(30) self.logger.info('Initialized Pushbullet backend - device_id: {}' .format(self.device_name)) self.listener = Listener(account=self.pb, on_push=self.on_push(), http_proxy_host=self.proxy_host, http_proxy_port=self.proxy_port) self.listener.run_forever()
def main(): s = Listener(account=pb, on_push=on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) try: s.run_forever() except KeyboardInterrupt: s.close()
def main(): global pb push = pb.push_note("This is the title", "This is the body") s = Listener(account=pb, on_push=on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) try: s.run_forever() except KeyboardInterrupt: s.close()
def __init__(self, auth_key, device_name, last_push = time.time(), device_iden=None): self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.download_link) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:",device_name,"iden:",device.device_iden) self.device = device except: print("Error: Unable to create device") raise
class Mirrorer(object): def __init__(self, auth_key, temp_folder, device_name, last_push = time.time(), device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:",device_name,"iden:",device.device_iden) self.device = device except: print("Error: Unable to create device") raise self.check_pushes() def save_icon(self, b64_asset): hash = hashlib.md5(b64_asset.encode()).hexdigest() path = os.path.join(self.temp_folder, hash) if os.path.exists(path): return path else: decoded = base64.b64decode(b64_asset) with open(path, "wb") as image: image.write(decoded) return path def check_pushes(self): pushes = self.pb.get_pushes(self.last_push) for push in pushes: if not isinstance(push,dict): # not a push object continue if ((push.get("target_device_iden", self.device.device_iden) == self.device.device_iden) and not (push.get("dismissed", True))): self.notify(push.get("title", ""), push.get("body", "")) self.pb.dismiss_push(push.get("iden")) self.last_push = max(self.last_push, push.get("created")) def watcher(self, push): if push["type"] == "push" and push["push"]["type"] == "mirror": print("MIRROR") image_path = self.save_icon(push["push"]["icon"]) self.notify(push["push"]["title"], push["push"]["body"], image_path) elif push["type"] == "tickle": print("TICKLE") self.check_pushes() def notify(self, title, body, image=None): subprocess.Popen(["notify-send", title, body, "-i", image or ""]) print(title) print(body) def dump_config(self, path): config = {"temp_folder": self.temp_folder, "auth_key": self._auth_key, "device_name": self.device.nickname, "device_iden": self.device.device_iden} with open(path, "w") as conf: json.dump(config, conf) def run(self): try: self.listener.run_forever() except KeyboardInterrupt: self.listener.close()
def test_listener_init(): pb = PushBullet("apikey") listener = Listener(pb) listener.close()
def on_push(data): pushes = pb.get_pushes() latest = pushes[1][0] if 'TodaysWeather' in latest.get('title'): body = latest.get('body') if any(x in body for x in ['Sunny', 'Clear']): GPIO.output(greenPin, True) elif 'Cloud' in body: GPIO.output(yellowPin, True) elif any(x in body for x in ['Rain', 'Shower', 'Snow']): GPIO.output(redPin, True) # sleep 1 hour time.sleep(3600) leds_off() if __name__ == "__main__": pb = PushBullet(api_key) s = Listener(account=pb, on_push=on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) init_leds() try: s.run_forever() except KeyboardInterrupt: s.close() leds_off()
def __createListener(self): self.listener = Listener(account=self.pushBulletManager, on_push=self.on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) self.listener.run_forever()
class PushbulletBackend(Backend): """ This backend will listen for events on a Pushbullet (https://pushbullet.com) channel and propagate them to the bus. This backend is quite useful if you want to synchronize events and actions with your mobile phone (through the Pushbullet app and/or through Tasker), synchronize clipboards, send pictures and files to other devices etc. You can also wrap Platypush messages as JSON into a push body to execute them. Triggers: * :class:`platypush.message.event.pushbullet.PushbulletEvent` if a new push is received Requires: * **requests** (``pip install requests``) * **pushbullet.py** (``pip install git+https://github.com/rbrcsk/pushbullet.py``) """ def __init__(self, token, device='Platypush', proxy_host=None, proxy_port=None, **kwargs): """ :param token: Your Pushbullet API token, see https://docs.pushbullet.com/#authentication :type token: str :param device: Name of the virtual device for Platypush (default: Platypush) :type device: str :param proxy_host: HTTP proxy host (default: None) :type proxy_host: str :param proxy_port: HTTP proxy port (default: None) :type proxy_port: int """ super().__init__(**kwargs) self.token = token self.device_name = device self.proxy_host = proxy_host self.proxy_port = proxy_port self.pb = Pushbullet(token) self.listener = None try: self.device = self.pb.get_device(self.device_name) except: self.device = self.pb.new_device(self.device_name) self.pb_device_id = self.get_device_id() def _get_latest_push(self): t = int(time.time()) - 5 pushes = self.pb.get_pushes(modified_after=str(t), limit=1) if pushes: return pushes[0] def on_push(self): def callback(data): try: # Parse the push try: data = json.loads(data) if isinstance(data, str) else data except Exception as e: self.logger.exception(e) return # If it's a push, get it if data['type'] == 'tickle' and data['subtype'] == 'push': push = self._get_latest_push() elif data['type'] == 'push': push = data['push'] else: return # Not a push notification if not push: return # Post an event, useful to react on mobile notifications if # you enabled notification mirroring on your PushBullet app event = PushbulletEvent(**push) self.on_message(event) if 'body' not in push: return self.logger.debug('Received push: {}'.format(push)) body = push['body'] try: body = json.loads(body) self.on_message(body) except Exception as e: self.logger.debug(('Unexpected message received on the ' + 'Pushbullet backend: {}. Message: {}') .format(str(e), body)) except Exception as e: self.logger.exception(e) return return callback def get_device_id(self): try: return self.pb.get_device(self.device_name).device_iden except Exception as e: device = self.pb.new_device(self.device_name, model='Platypush virtual device', manufacturer='platypush', icon='system') self.logger.info('Created Pushbullet device {}'.format( self.device_name)) return device.device_iden def send_message(self, msg): if isinstance(msg, dict): msg = json.dumps(msg) self.device.push_note(title=None, body=str(msg)) def close(self): if self.listener: self.listener.close() def on_stop(self): return self.close() def run(self): super().run() self.logger.info('Initialized Pushbullet backend - device_id: {}' .format(self.device_name)) self.listener = Listener(account=self.pb, on_push=self.on_push(), http_proxy_host=self.proxy_host, http_proxy_port=self.proxy_port) self.listener.run_forever()
class PushbulletManager(): """Manager interface to and from PushBullet. Note: Requires that the environment variable PUSHBULLET_API_TOKEN is set. """ REMINDER_KEYWORD = r"remi(nder)?\s+" last_mod_time = 0.0 def __init__(self): """Create PushBullet listener.""" self.logger = logging.getLogger(__name__) self.logger.info("Starting PushbulletManager...") self.pb = Pushbullet(os.environ.get("PUSHBULLET_API_TOKEN")) push_list = self.pb.get_pushes(limit=1) if push_list: self.last_mod_time = push_list[0]["modified"] self.pb_listener = Listener(account=self.pb, on_push=self.pb_on_push, on_error=self.pb_on_error, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) self.rmc = ReminderMessageConsumer() self.rmc.start() def run(self): """Listen for messages on PushBullet websocket.""" try: self.logger.info('Waiting for messages. To exit press CTRL+C') self.pb_listener.run_forever() except KeyboardInterrupt: self.rmc.stop() self.rmc.join() raise finally: self.pb_listener.close() def pb_on_error(self, websocket, exception): """Error handler for the PushBullet listener. Re-raise any exception that occurs, as otherwise it will be swallowed up by the PushBullet Listener. """ # If a KeyboardInterrupt is raised during # self.pb_listener.run_forever(), this method is invoked, which is the # only way we'll know about it. raise exception def pb_on_push(self, data): """Push handler for the PushBullet listener""" try: self.logger.debug("Received tickle: %s", str(data)) push_list = self.pb.get_pushes(limit=1, modified_after=self.last_mod_time) if not push_list: self.logger.debug("Ignoring tickle") return latest = push_list[0] self.last_mod_time = latest["modified"] self.logger.info("Latest Push: %s", str(latest)) self.process_push(latest) except Exception: self.logger.exception("Error processing push message") def process_push(self, push): """Process PushBullet JSON message. Passes the message to the ReminderManager if appropriate """ # Pushbullet can also send Links and Images, which don't have a "body" if "body" not in push: self.logger.info("Ignoring non-note push: id=%s type=%s", push["iden"], push["type"]) return if push["dismissed"]: self.logger.debug("Ignoring dismissed push: id=%s, body=%s", push["iden"], push["body"]) return # We require the reminder keyword at beginning of message, to avoid # an infinite loop of pushbullets. if not bool(re.match(self.REMINDER_KEYWORD, push["body"], re.I)): self.logger.info("Ignoring non-reminder push: id=%s, body=%s", push["iden"], push["body"]) return self.logger.info('Received push: id=%s, body=%s', push["iden"], push["body"]) # Strip off reminder keyword first body = re.sub(r'^\S+\s+', '', push["body"]) request = {"body": body, "source": "pushbullet"} self.logger.info("Sending request to reminder RPC service") try: reminder_rpc = ReminderRpcClient() response = reminder_rpc.call(request) self.logger.info("Reminder RPC response: %s", str(response)) except ResponseTimeout as rto: self.logger.exception(str(rto)) response = { "error": { "code": 0, "text": "Unable to connect to server" } } if "error" in response: self.logger.error("Reminder RPC returned error code '%d' (%s)", response["error"]["code"], response["error"]["text"]) self.pb.push_note("Error Setting Reminder", response["error"]["text"]) else: self.logger.info("Received response: %s", str(response)) self.logger.info("Dismissing push: id=%s", push["iden"]) self.pb.dismiss_push(push["iden"]) self.logger.info("Sending response: %s", response["data"]["text"]) self.pb.push_note("Got it!", response["data"]["text"])
GPIO.output(yellowPin, False) GPIO.output(greenPin, False) def on_push(data): pushes = pb.get_pushes() latest = pushes[1][0] if 'TodaysWeather' in latest.get('title'): body = latest.get('body') if any(x in body for x in ['Sunny', 'Clear']): GPIO.output(greenPin, True) elif 'Cloud' in body: GPIO.output(yellowPin, True) elif any(x in body for x in ['Rain', 'Shower', 'Snow']): GPIO.output(redPin, True) # sleep 1 hour time.sleep(3600) leds_off() if __name__ == "__main__": pb = PushBullet(api_key) s = Listener(account=pb, on_push=on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) init_leds() try: s.run_forever() except KeyboardInterrupt: s.close() leds_off()
class NotificationHandler: def __init__(self, pushBulletAPIKey, didReceiveCommand): # Setup pushBullet manager self.pushBulletAPIKey = pushBulletAPIKey self.didReceiveCommand = didReceiveCommand self.pushBulletManager = Pushbullet(self.pushBulletAPIKey) thread = Thread(target=self.__createListener) thread.start() # Setup Notification Queue self.__setupNotificationQueue() def __createListener(self): self.listener = Listener(account=self.pushBulletManager, on_push=self.on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) self.listener.run_forever() def __setupNotificationQueue(self): print("setupNotificationQueue") self.notificationQueue = Queue(maxsize=QUEUE_MAX_SIZE) for i in range(NUM_THREAD): worker = Thread(target=self.__motionNotify, args=()) worker.setDaemon(True) worker.start() def pushNotificationToMobile(self, filePath): self.notificationQueue.put(filePath) def pushToMobile(self, dataDictionary): print("pushToMobile: ", dataDictionary) self.notificationQueue.put(dataDictionary) def __motionNotify(self): print("__motionNotify called") while True: dataDictionary = self.notificationQueue.get() print("upload and notify: ", dataDictionary) if dataDictionary['type'] == "TEXT_MESSAGE": push = self.pushBulletManager.push_note( dataDictionary['text'], '') print("push result: ", push) elif dataDictionary['type'] == "IMAGE_MESSAGE": filePath = dataDictionary['filePath'] print("upload and push file: ", filePath) with open(filePath, "rb") as pic: fileData = self.pushBulletManager.upload_file( pic, dataDictionary['fileName']) push = self.pushBulletManager.push_file(**fileData) print("push result: ", push) if "iden" in push: os.remove(filePath) elif dataDictionary['type'] == "VIDEO_MESSAGE": push = self.pushBulletManager.push_note( "The motion is out. Video uploading...", '') filePath = dataDictionary['filePath'] print("upload and push file: ", filePath) with open(filePath, "rb") as pic: fileData = self.pushBulletManager.upload_file( pic, dataDictionary['fileName']) push = self.pushBulletManager.push_file(**fileData) print("push result: ", push) if "iden" in push: os.remove(filePath) else: print("Not support type: ", dataDictionary['Type']) self.notificationQueue.task_done() def __delete(self): self.listener.close() # to stop the run_forever() def on_push(self, jsonMessage): if jsonMessage["type"] == "tickle" and jsonMessage["subtype"] == "push": allPushes = self.pushBulletManager.get_pushes() latest = allPushes[0] if 'body' in latest: body = latest['body'] print(body) if body.startswith("@"): self.didReceiveCommand(body) # else: # print("latest pushes: ", latest) # else: # print("latest pushes: ", latest) def notifyWithImage(self, filePath): with open(filePath, "rb") as pic: file_data = self.pushBulletManager.upload_file(pic, "picture.jpg") push = self.pushBulletManager.push_file(**file_data) def notifyWithVideo(self, filePath): with open(filePath, "rb") as pic: file_data = self.pushBulletManager.upload_file(pic, "video.h264") push = self.pushBulletManager.push_file(**file_data)
class Mirrorer(object): def __init__(self, auth_key, temp_folder, device_name, last_push=time.time(), device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:", device_name, "iden:", device.device_iden) self.device = device except Exception: print("Error: Unable to create device") raise self.check_pushes() def save_icon(self, b64_asset): hash = hashlib.md5(b64_asset.encode()).hexdigest() path = os.path.join(self.temp_folder, hash) if os.path.exists(path): return path else: decoded = base64.b64decode(b64_asset) with open(path, "wb") as image: image.write(decoded) return path def check_pushes(self): pushes = self.pb.get_pushes(self.last_push) for push in pushes: if not isinstance(push, dict): # not a push object continue if (push.get("target_device_iden", self.device.device_iden) == self.device.device_iden) and not ( push.get("dismissed", True) ): self.notify(push.get("title", ""), push.get("body", "")) self.pb.dismiss_push(push.get("iden")) self.last_push = max(self.last_push, push.get("created")) def watcher(self, push): if push["type"] == "push" and push["push"]["type"] == "mirror": print("MIRROR") image_path = self.save_icon(push["push"]["icon"]) self.notify(push["push"]["title"], push["push"]["body"], image_path) elif push["type"] == "tickle": print("TICKLE") self.check_pushes() def notify(self, title, body, image=None): subprocess.Popen(["notify-send", title, body, "-i", image or ""]) print(title) print(body) def dump_config(self, path): config = { "temp_folder": self.temp_folder, "auth_key": self._auth_key, "device_name": self.device.nickname, "device_iden": self.device.device_iden, } with open(path, "w") as conf: json.dump(config, conf) def run(self): try: self.listener.run_forever() except KeyboardInterrupt: self.listener.close()
class Downloader(object): def __init__(self, auth_key, device_name, last_push=time.time(), device_iden=None): self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.download_link) self.last_push = last_push self.device = None if device_iden: results = [ d for d in self.pb.devices if d.device_iden == device_iden and d.active ] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:", device_name, "iden:", device.device_iden) self.device = device except: print("Error: Unable to create device") raise def get_unique_filename(self, filename, downloads_dir): unique_filename = filename i = 0 while os.path.isfile(downloads_dir + "/" + unique_filename): i += 1 unique_filename = filename + " (%i)" % i return unique_filename def get_filename_from_url(self, url): if url.rfind('/') != -1: title = url[url.rfind('/') + 1:] if len(title) < 1: try: response = requests.get(url) parsed_body = html.fromstring(response.text) titles = parsed_body.xpath('//title/text()') if len(titleArray) == 0: title = "tmptitle" else: title = titles[0] except: title = "tmptitle" return title def download_link(self, push): pushes = self.pb.get_pushes(self.last_push)[1] if (len(pushes) != 0): last_push = pushes[len(pushes) - 2] if last_push.get("url"): url = last_push.get("url") filename = self.get_filename_from_url(url) downloads_dir = glib.get_user_special_dir( glib.USER_DIRECTORY_DOWNLOAD) unique_filename = self.get_unique_filename( filename, downloads_dir) unique_filename_full_path = downloads_dir + "/" + unique_filename urllib.urlretrieve(url, unique_filename_full_path) print "URL: %s Downloaded: %s" % (url, unique_filename_full_path) self.last_push = max(self.last_push, last_push.get("created")) def run(self): try: self.listener.run_forever() except KeyboardInterrupt: self.listener.close() def dump_config(self, path): config = { "auth_key": self._auth_key, "device_name": self.device.nickname, "device_iden": self.device.device_iden } with open(path, "w") as conf: json.dump(config, conf)
logger.debug("Exit 1") sys.exit(1) try: logger.debug("Write PID file") file(pidfile, 'w').write("pid\n") except IOError, e: #logger.error("Line: " + _line()) logger.error("Unable to write PID file: %s [%d]" % (e.strerror, e.errno)) raise SystemExit("Unable to write PID file: %s [%d]" % (e.strerror, e.errno)) logger.debug("Start daemon") daemonize() s = Listener(api_key=API_KEY, on_push=on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) s.run_forever() t = Timer(60, timeout) t.start() sys.exit(0) def timeout(push): global is_alive if is_alive == 0: sys.exit(0)
class Downloader(object): def __init__(self, auth_key, device_name, last_push = time.time(), device_iden=None): self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.download_link) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:",device_name,"iden:",device.device_iden) self.device = device except: print("Error: Unable to create device") raise def get_unique_filename(self, filename, downloads_dir): unique_filename = filename i = 0 while os.path.isfile(downloads_dir+"/"+unique_filename): i+=1 unique_filename=filename+" (%i)" % i return unique_filename def get_filename_from_url(self, url): if url.rfind('/') != -1: title = url[url.rfind('/')+1:] if len(title) < 1: try: response = requests.get(url) parsed_body = html.fromstring(response.text) titles = parsed_body.xpath('//title/text()') if len(titleArray) == 0: title="tmptitle" else: title=titles[0] except: title="tmptitle" return title def download_link(self, push): pushes = self.pb.get_pushes(self.last_push)[1] if (len(pushes) != 0): last_push = pushes[len(pushes)-2] if last_push.get("url"): url = last_push.get("url") filename = self.get_filename_from_url(url) downloads_dir = glib.get_user_special_dir(glib.USER_DIRECTORY_DOWNLOAD) unique_filename = self.get_unique_filename(filename, downloads_dir) unique_filename_full_path = downloads_dir+"/"+unique_filename urllib.urlretrieve (url, unique_filename_full_path) print "URL: %s Downloaded: %s" % (url, unique_filename_full_path) self.last_push = max(self.last_push, last_push.get("created")) def run(self): try: self.listener.run_forever() except KeyboardInterrupt: self.listener.close() def dump_config(self, path): config = {"auth_key": self._auth_key, "device_name": self.device.nickname, "device_iden": self.device.device_iden} with open(path, "w") as conf: json.dump(config, conf)