예제 #1
0
def test_get_pushes_error():
    response1 = Mock()
    response1.status_code = 400
    response1.json.return_value = {"pushes": []}

    session = Mock()
    session.get.side_effect = [response1]

    pb = PushBullet("apikey")
    pb._session = session

    with pytest.raises(PushbulletError):
        pb.get_pushes()
예제 #2
0
class Flow:
    def __init__(self, googleapi, api_key, email, **_):
        if api_key == 'YOUR_API_KEY_HERE':
            raise ValueError('Missing api key in settings')

        self.email = email
        self.pb = PushBullet(api_key)

        self.credentials_storage_path = googleapi.credentials_storage_path
        self.flow = flow_from_clientsecrets(
            filename=googleapi.client_secrets_path,
            scope='https://www.googleapis.com/auth/calendar.readonly',
            redirect_uri='urn:ietf:wg:oauth:2.0:oob')

        self.last_check = None
        self.callback = lambda: None

    def run(self, callback):
        self.callback = callback

        authorize_url = self.flow.step1_get_authorize_url()
        self.pb.push_link('Google Auth Request', authorize_url, email=self.email)
        self.last_check = datetime.now()

    def iter_received_codes(self):
        pushes = self.pb.get_pushes(modified_after=self.last_check.timestamp())
        self.last_check = datetime.now()
        for push in pushes:
            if push['type'] == 'note' and push['sender_email'] == self.email:
                self.pb.dismiss_push(push['iden'])
                yield push['body'].strip()

    def check_response(self):
        if self.last_check is None:
            return

        for code in self.iter_received_codes():
            try:
                credential = self.flow.step2_exchange(code)
                Storage(self.credentials_storage_path).put(credential)
                break
            except (ValueError, FlowExchangeError) as error:
                self.pb.push_note('', 'Error: ' + str(error), email=self.email)
        else:
            return

        self.last_check = None
        self.callback()
        self.pb.push_note('', 'Authentication complete', email=self.email)
def test_get_pushes_no_cursor():
    response1 = Mock()
    response1.status_code = 200
    response1.json.return_value = {"pushes": []}

    session = Mock()
    session.get.side_effect = [response1]

    pb = PushBullet("apikey")
    pb._session = session

    pushes = pb.get_pushes(filter_inactive=False)

    assert len(pushes) == 0
    session.get.assert_called_once_with(pb.PUSH_URL,
                                        params={
                                            "modified_after": None,
                                            "limit": None
                                        })
예제 #4
0
def test_get_pushes_no_cursor():
    response1 = Mock()
    response1.status_code = 200
    response1.json.return_value = {
        "pushes": ["push1", "push2"],
        "cursor": "cursor1"
    }

    response2 = Mock()
    response2.status_code = 200
    response2.json.return_value = {"pushes": ["push3"]}

    session = Mock()
    session.get.side_effect = [response1, response2]

    pb = PushBullet("apikey")
    pb._session = session

    pushes = pb.get_pushes(filter_inactive=False)

    assert len(pushes) == 3

    assert session.get.call_count == 2
def start(api_key,root):
    # flag used to count number of attempt left
    flag = 10
    while 1:
        if is_connected():
            try:
                pb =PushBullet(api_key)
            except:
                tkinter.messagebox.showinfo('Invalid Key','Entered key is invalid!')
                break
            pushMsg =pb.push_note("PYTHON : ","Found Internet Connectivity, is this you? if not message 'No' otherwise message 'Yes' ")
            time.sleep(30)
            val = pb.get_pushes()
            action = val[0]['body']
            print(action)
            if action.lower() == 'no':
               intruder_pic()
               Image_send(pb)
               time.sleep(10)
               logOff()
               root.destroy()
               break
            elif action.lower() == 'yes':
                flag = 10
                time.sleep(3600)
            else:
                flag -= 1
                if flag == 0:
                    intruder_pic()
                    Image_send(pb)
                    time.sleep(10)
                    logOff()
                    root.destroy()
                    break
                time.sleep(60)    
        else:
            time.sleep(600)
예제 #6
0
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()
예제 #7
0
from pushbullet import PushBullet

api_key = "<API KEY>"

pb = PushBullet(api_key)
pushes = pb.get_pushes()
print 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']):
        print 'Good'
    elif 'Cloud' in body:
        print 'Not Bad'
    elif any(x in body for x in ['Rain', 'Shower', 'Snow']):
        print 'Bad'
#items = pushes[1]
#for item in items:
#print item
#pb.dismiss_push(item.get('iden'))
#pb.delete_push(item.get('iden'))
예제 #8
0
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()
예제 #9
0
from pushbullet import PushBullet

api_key = "<API KEY>"

pb = PushBullet(api_key)
pushes = pb.get_pushes()
print 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']):
        print 'Good'
    elif 'Cloud' in body:
        print 'Not Bad'
    elif any(x in body for x in ['Rain', 'Shower', 'Snow']):
        print 'Bad'
#items = pushes[1]
#for item in items:
    #print item
    #pb.dismiss_push(item.get('iden'))
    #pb.delete_push(item.get('iden'))
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)
예제 #11
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)
class lattefy():
    def __init__(self):
        #Pushbullet API data
        self.token = "BXRMMQMOGoLoQY4LWLsOOzf8ep3vlD5F"
        self.pb = PushBullet(self.token)
        self.pb.contacts
    
        #Coffee orders array
        self.orders = deque([])
        
        #Setting up SPI connection
        self.SPI_bus = smbus.SMBus(1)
        self.SPI_address = 0x04
        
        #Threading Pushbullet checks
        self.hilo=threading.Thread(target=self.pbCycle)
        self.hilo.start()
        
        #Threading buttons checks
        self.hilo2=threading.Thread(target=self.btnCycle)
        self.hilo2.start()
        
        while True:
            if True:
                if len(self.orders) > 0:
                    try:
                        self.SPI_bus.write_byte(self.SPI_address, self.orders[0]) #Send order number to Arduino
                    except:
                        pass
                    #self.makeOrder(self.orders[0])
                    self.orders.popleft()
                    #time.sleep(5)
                    #self.SPI_bus.write_byte(self.SPI_address, 3) #Ask Arduino to buzz
                    time.sleep(1)
                #else:
                    #self.SPI_bus.write_byte(self.SPI_address, 0) #Send blank
                    #time.sleep(1.5)
            else:
                print("No hay tazas libres")

    def get_sender(self,sender_iden,sender_name,sender_email):
        for contact in self.pb.contacts:
            if contact.email == sender_email:
                return contact
                break
        else:
            success, contact = self.pb.new_contact(sender_name,sender_email)
            return contact
    
    def get_body(self,push):
        try:
            body = push["body"]
            return body
        except:
            return ""
    
    def get_order(self,order):
        if order == "caféconleche":
            return 1
        elif order == "cafésolo":
            return 2
        else:
            return 0
    
    def buzz(self):        
        p = GPIO.PWM(buzzer, 3000)
        p.start(0)
        p.ChangeFrequency(900) #900Hz
        p.ChangeDutyCycle(70)
        time.sleep(0.1)
        p.stop()
        time.sleep(0.1)
        p.start(0)
        p.ChangeFrequency(900)
        p.ChangeDutyCycle(70)
        time.sleep(0.1)
        p.stop()
 
    def pbCycle(self):
        while True:
            success, self.pushes = self.pb.get_pushes()
            #print(self.pushes)
            for push in self.pushes:
                if push["dismissed"] == False:
                    re_body = self.get_body(push)
                    body = re_body.lower()
                    body = body.split(" ")
                    body = "".join(body)
                    sender_iden = push["sender_iden"]
                    sender_name = push["sender_name"]
                    sender_email = push["sender_email"]
                    order_result = self.get_order(body)
                    if order_result > 0:
                        if order_result == 1:
                            print("Preparando café con leche")
                        elif order_result == 2:
                            print("Preparando café solo")
                        self.get_sender(sender_iden,sender_name,sender_email).push_note("¡Orden terminada!","Ya puedes recoger tu {0}".format(re_body))
                        time.sleep(2)
                        self.orders.append(order_result)
                    else:
                        self.get_sender(sender_iden,sender_name,sender_email).push_note("Error","Servicio no reconocido, prueba a pedir un 'café con leche' o un 'café solo'")
                    success_now, pushes_now = self.pb.get_pushes()
                    self.pb.dismiss_push(pushes_now[0]["iden"])
                    self.pb.dismiss_push(push["iden"])
            time.sleep(1)
    
    def btnCycle(self):
        while True:
            if GPIO.input(btn1) == 1:
                self.orders.append(1)
                time.sleep(0.4)
            elif GPIO.input(btn2) == 1:
                self.orders.append(2)
                time.sleep(0.4)
                
    def makeOrder(self,order):
        time.sleep(1)
        if order == 1:
            print("Café")
            print("Liberar café en el filtro")
            self.SPI_bus.write_byte(self.SPI_address, 4) #Servo 0 
            time.sleep(1)
            print("Calentar agua")
            print("Abrir filtro")
            print("Comprobar nivel de la taza")
            time.sleep(1)
            self.SPI_bus.write_byte(self.SPI_address, 5) #Servo 170
            time.sleep(1)
        elif order == 2:
            print("Té")