Guest User

pushbullet plugin

a guest
Aug 7th, 2015
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.39 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab
  3. #########################################################################
  4. #  Copyright 2011 KNX-User-Forum e.V.           http://knx-user-forum.de/
  5. #########################################################################
  6. #  This file is part of SmartHome.py.    http://mknx.github.io/smarthome/
  7. #
  8. #  SmartHome.py is free software: you can redistribute it and/or modify
  9. #  it under the terms of the GNU General Public License as published by
  10. #  the Free Software Foundation, either version 3 of the License, or
  11. #  (at your option) any later version.
  12. #
  13. #  SmartHome.py is distributed in the hope that it will be useful,
  14. #  but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. #  GNU General Public License for more details.
  17. #
  18. #  You should have received a copy of the GNU General Public License
  19. #  along with SmartHome.py. If not, see <http://www.gnu.org/licenses/>.
  20. #########################################################################
  21.  
  22. import logging
  23.  
  24. import json
  25. import requests
  26. import magic
  27. import os
  28. import re
  29.  
  30. logger = logging.getLogger("Pushbullet")
  31.  
  32. class Pushbullet(object):
  33.     _apiurl = "https://api.pushbullet.com/v2/pushes"
  34.     _upload_apiurl = "https://api.pushbullet.com/v2/upload-request"
  35.  
  36.     def __init__(self, smarthome, apikey=None, deviceid=None, debug=False):
  37.         self._apikey = apikey
  38.         self._deviceid = deviceid
  39.         self._sh = smarthome
  40.         self._debug = debug
  41.  
  42.     def run(self):
  43.         pass
  44.  
  45.     def stop(self):
  46.         pass
  47.  
  48.     def note(self, title, body, deviceid=None, apikey=None):
  49.         return self._push(data={"type": "note", "title": title, "body": body}, deviceid=deviceid, apikey=apikey)
  50.  
  51.     def link(self, title, url, deviceid=None, apikey=None, body=None):
  52.         return self._push(data={"type": "link", "title": title, "url": url, "body": body}, deviceid=deviceid, apikey=apikey)
  53.  
  54.     def address(self, name, address, deviceid=None, apikey=None):
  55.         return self._push(data={"type": "address", "name": name, "address": address}, deviceid=deviceid, apikey=apikey)
  56.  
  57.     def list(self, title, items, deviceid=None, apikey=None):
  58.         return self._push(data={"type": "list", "title": title, "items": items}, deviceid=deviceid, apikey=apikey)
  59.  
  60.     def file(self, filepath, deviceid=None, apikey=None, body=None):
  61.         if os.path.exists(filepath) == False:
  62.             logger.error("Trying to push non existing file: {0}".format(filepath))
  63.             return
  64.  
  65.         return self._upload_and_push_file(filepath, body, deviceid, apikey)
  66.  
  67.     def _upload_and_push_file(self, filepath, body=None, deviceid=None, apikey=None):
  68.         try:
  69.             headers = {"User-Agent": "SmartHome.py", "Content-Type": "application/json"}
  70.  
  71.             if apikey == None:
  72.                 apikey = self._apikey
  73.  
  74.             upload_request_response = requests.post(self._upload_apiurl, data=json.dumps({"file_name": os.path.basename(filepath), "file_type": magic.from_file(filepath, mime=True).decode("UTF-8")}), headers=headers, auth=(apikey,""))
  75.  
  76.             if self._is_response_ok(upload_request_response) == True:
  77.                 data = upload_request_response.json()
  78.                 upload_response = requests.post(data["upload_url"], data=data["data"], headers={"User-Agent": "SmartHome.py"}, files={"file": open(filepath, "rb")})
  79.  
  80.                 if self._is_response_ok(upload_response) == True:
  81.                     if body == None:
  82.                         body = ""
  83.  
  84.                     return self._push(data={"type": "file", "file_name": data["file_name"], "file_type": data["file_type"], "file_url": data["file_url"], "body": body}, deviceid=deviceid, apikey=apikey)
  85.                 else:
  86.                     logger.error("Error while uploading file: {0}".format(upload_response.text))
  87.             else:
  88.                 logger.error("Error while requesting upload: {0}".format(upload_request_response.text))
  89.         except Exception as exception:
  90.             logger.error("Could not send file to Pushbullet notification. Error: {0}".format(exception))
  91.  
  92.     def _push(self, data, deviceid=None, apikey=None):
  93.         if apikey == None:
  94.             apikey = self._apikey
  95.  
  96.         if deviceid == None:
  97.             deviceid = self._deviceid
  98.  
  99.         if re.match(r"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", deviceid):
  100.             data["email"] = deviceid
  101.         else:
  102.             data["device_iden"] = deviceid
  103.  
  104.         try:
  105.             response = requests.post(self._apiurl, data=json.dumps(data), headers={"User-Agent": "SmartHome.py", "Content-Type": "application/json"}, auth=(apikey,""))
  106.             if self._is_response_ok(response) == False:
  107.                 logger.error("Could not send Pushbullet notification. Error: {0}".format(response.text))
  108.  
  109.             return response.json()
  110.         except Exception as exception:
  111.             logger.error("Could not send Pushbullet notification. Error: {0}".format(exception))
  112.  
  113.     def _is_response_ok(self, response):
  114.         if response.status_code == 200 or response.status_code == 204:
  115.             logger.debug("Pushbullet returns: Notification submitted.")
  116.  
  117.             return True
  118.         elif response.status_code == 400:
  119.             logger.warning("Pushbullet returns: Bad Request - Often missing a required parameter.")
  120.         elif response.status_code == 401:
  121.             logger.warning("Pushbullet returns: Unauthorized - No valid API key provided.")
  122.         elif response.status_code == 402:
  123.             logger.warning("Pushbullet returns: Request Failed - Parameters were valid but the request failed.")
  124.         elif response.status_code == 403:
  125.             logger.warning("Pushbullet returns: Forbidden - The API key is not valid for that request.")
  126.         elif response.status_code == 404:
  127.             logger.warning("Pushbullet returns: Not Found - The requested item doesn't exist.")
  128.         elif response.status_code >= 500:
  129.             logger.warning("Pushbullet returns: Server errors - something went wrong on PushBullet's side.")
  130.         else:
  131.             logger.error("Pushbullet returns unknown HTTP status code = {0}".format(response.status_code))
  132.  
  133.         if self._debug == True:
  134.             logger.warning("Response was: {}".format(response.text))
  135.  
  136.         return False
Advertisement
Add Comment
Please, Sign In to add comment