예제 #1
0
def main_cli():
    parser = argparse.ArgumentParser(
        prog=dyndns_updater.__info__.__package_name__,
        description=dyndns_updater.__info__.__description__)

    parser.add_argument('--platform', action='store', required=True)
    parser.add_argument('command', choices=['update'])
    parser.add_argument('domain')
    parser.add_argument('token')
    parser.add_argument(
        '--pushbullettoken',
        action='store',
        help='Access token to have full access to a Pushbullet account.')

    args = parser.parse_args()
    if args.command == 'update':

        if args.platform == 'duckdns':
            ipv4, hasChanged = duckdns_update(args.domain, args.token)

            if hasChanged:
                info_message = 'Current configured IP has changed. Verify the DNS at http://{}.duckdns.org/ ({})'.format(
                    args.domain, ipv4)
                logging.info(info_message)
                if args.pushbullettoken is not None:
                    PushBullet(args.pushbullettoken).push_note(
                        'DNS IP changed', info_message)
            else:
                info_message = 'Current configured IP hasn\'t changed. Verify the DNS at http://{}.duckdns.org/ ({})'.format(
                    args.domain, ipv4)
                logging.info(info_message)
예제 #2
0
 def __init__(self, config, store):
     self.key_words = config.key_words
     self.pushbullet = PushBullet(config.pushbullet_token)
     self.updated_streams = store.stream_changes.pipe(
         filter(lambda change: change['type'] == 'add' or (change[
             'type'] == 'change' and 'name' in change['changed_fields'])),
         pluck('stream'))
예제 #3
0
 def add_alert(self, module, message):
     """ajoute une alerte"""
     if (not module in self.alertes) or self.alertes[module] != message:
         self.alertes[module] = message
         self.write_config()
         pb = PushBullet(self.api_key)
         note = pb.push_note(self.title + " - " + module, message)
예제 #4
0
 def monitor(self):
     current_model_list = os.listdir(self.model_path)
     from pushbullet import PushBullet
     pb = PushBullet(api_key=self.api_key)
     res1 = self.get_model_status(self.model_path, time.ctime())
     res2, status = self.get_process_status(self.pid)
     pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body=res1 + res2)
     while True:
         now_model_list = os.listdir(self.model_path)
         if now_model_list == current_model_list:
             res2, status = self.get_process_status(self.pid)
             if status == 'fail':
                 pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body='运行结束或者异常,请检查电脑运行情况!!!!!!!')
                 break
             else:
                 pass
         else:
             res1 = self.get_model_status(self.model_path, time.ctime())
             res2, status = self.get_process_status(self.pid)
             current_model_list = now_model_list
             if status == 'fail':
                 pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body='运行结束或者异常,请检查电脑运行情况!!!!!!!')
                 break
             else:
                 pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body=res1 + res2)
def push_to_iOS(title, body, pb_key_filename):
    with open(pb_key_filename) as pb_key_file:
        pb_key = pb_key_file.read()

    pb = PushBullet(pb_key)

    pb.push_note(title, body)
예제 #6
0
def plugin(srv, item):
    ''' expects (apikey, device_id) in adddrs '''

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__,
                      item.service, item.target)
    if not HAVE_PUSHBULLET:
        srv.logging.warn("pushbullet is not installed")
        return False

    try:
        apikey, device_id = item.addrs
    except:
        srv.logging.warn("pushbullet target is incorrectly configured")
        return False

    text = item.message
    title = item.get('title', srv.SCRIPTNAME)

    try:
        srv.logging.debug("Sending pushbullet notification to %s..." %
                          (item.target))
        pb = PushBullet(apikey)
        pb.pushNote(device_id, title, text)
        srv.logging.debug("Successfully sent pushbullet notification")
    except Exception, e:
        srv.logging.warning("Cannot notify pushbullet: %s" % (str(e)))
        return False
예제 #7
0
    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()
예제 #8
0
 def __init__(self, pb_apikey):
     #Write your PushBullet API Key Here
     self.pb_apikey = pb_apikey
     self.pb = PushBullet(self.pb_apikey)
     self.notifiedDevices = filter(deviceFilter, self.pb.devices)
     #print self.pb.devices
     return
예제 #9
0
def get_pushbullet_config(logger=None):
    """
    Return PushBullet handle and device to send to
    """

    api_key = settings.pushbullet_key
    try:
        p = PushBullet(api_key)
    except pushbullet.errors.InvalidKeyError:
        print('Invalid PushBullet key')
        sys.exit(1)
    except requests.exceptions.ConnectionError as e:
        if logger:
            logger.error('PushBullet connection error while getting config - ' + str(e))
        return None, None
    devs = p.devices
    sendto_device = None
    try:
        if settings.pushbullet_device_id != None:
            for dev in devs:
                #print dev.device_iden + ' ' + dev.nickname
                if dev.device_iden == settings.pushbullet_device_id:
                    sendto_device = dev
    except AttributeError:
        # pushbullet_device_id wasn't even found in settings.py
        pass
    if not sendto_device:
        print("Please select a device from the PushBullet list and set as pushbullet_device_id in settings.py")
        for dev in devs:
            print("{: >20} {: >40}".format(dev.device_iden, dev.nickname))
        #sys.exit(1)

    return p, sendto_device
예제 #10
0
 def connect(self):
     self.client = PushBullet(self.api_key)
     self.pokemon['sender'] = self.get_sender(self.client,
                                              self.pokemon['channel'])
     self.pokestop['sender'] = self.get_sender(self.client,
                                               self.pokestop['channel'])
     self.gym['sender'] = self.get_sender(self.client, self.gym['channel'])
예제 #11
0
    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()
예제 #12
0
def test_http_proxy_is_not_accepted(pb_refresh):
    proxy = {"http": "https://*****:*****@10.10.1.10:3128/"}

    with pytest.raises(ConnectionError):
        PushBullet("apikey", proxy=proxy)

    pb_refresh.assert_not_called()
예제 #13
0
def test_proxy_is_applied(pb_refresh):
    proxy = {"https": "https://*****:*****@10.10.1.10:3128/"}

    with patch("pushbullet.PushBullet.refresh"):
        pb = PushBullet("apikey", proxy=proxy)

    assert pb._session.proxies == proxy
예제 #14
0
def send_alert_pushbullet(alert, email):
    pb = PushBullet(settings.PUSHBULLET_ACCESS_TOKEN)
    title = 'new alert: %s' % (alert.title, )
    pb.push_link(title,
                 'http://127.0.0.1:8000/',
                 body=alert.get_body(),
                 email=email)
예제 #15
0
def pushNote(args):
    p = PushBullet(args.api_key)
    note = p.pushNote(args.device, args.title, " ".join(args.body))
    if args.json:
        print(json.dumps(note))
        return
    print("Note %s sent to %s" % (note["iden"], note["target_device_iden"]))
예제 #16
0
    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
예제 #17
0
def test_push_sms_plaintext_failure():
    device = Mock()
    device.device_iden = "123"

    mock_response = Mock()
    mock_response.status_code = 500

    session = Mock()
    session.post.return_value = mock_response

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

    with pytest.raises(PushError):
        pb.push_sms(device, "+123456789", "This is an example text")

    session.post.assert_called_once_with(
        pb.EPHEMERALS_URL,
        data=json.dumps({
            "type": "push",
            "push": {
                "type": "messaging_extension_reply",
                "package_name": "com.pushbullet.android",
                "source_user_iden": "123",
                "target_device_iden": "123",
                "conversation_iden": "+123456789",
                "message": "This is an example text",
            },
        }),
    )
예제 #18
0
def test__push_ok():
    mock_response = Mock()
    mock_response.status_code = 200
    mock_response.headers = {"X-Ratelimit-Remaining": "1000"}
    mock_response.json.return_value = {}

    session = Mock()
    session.post.return_value = mock_response

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

    server_response = pb._push({"key": "value"})

    session.post.assert_called_once_with(
        pb.PUSH_URL,
        data=json.dumps({"key": "value"}),
    )

    assert server_response == {
        "rate_limit": {
            "remaining": "1000",
            "limit": None,
            "reset": None,
        }
    }
예제 #19
0
def test_upload_file_request_fails(requests, pb_refresh):
    first_response = Mock()
    first_response.status_code = 400
    first_response.json.return_value = {
        "data": "upload_data",
        "file_url": "imageurl",
        "upload_url": "http://uploadhere.google.com",
    }

    second_response = Mock()
    second_response.status_code = 200

    session = Mock()
    session.post.return_value = first_response

    requests.post.return_value = second_response
    requests.codes.ok = 200

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

    with open("tests/test.png", "rb") as test_file:

        with pytest.raises(PushbulletError):
            pb.upload_file(test_file, "test.png", "image/png")

    requests.post.assert_not_called()
예제 #20
0
def test_push_sms_encrypted_ok(pb_encrypt):
    device = Mock()
    device.device_iden = "123"

    mock_response = Mock()
    mock_response.status_code = 200

    session = Mock()
    session.post.return_value = mock_response

    pb_encrypt.return_value = "encrypted text"

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

    # When
    pb.push_sms(device, "+123456789", "This is an example text")

    session.post.assert_called_once_with(
        pb.EPHEMERALS_URL,
        data=json.dumps({
            "type": "push",
            "push": {
                "ciphertext": "encrypted text",
                "encrypted": True
            },
        }),
    )
예제 #21
0
def pushLink(args):
    p = PushBullet(args.api_key)
    link = p.pushLink(args.device, args.title, args.url)
    if args.json:
        print(json.dumps(link))
        return
    print("Link %s sent to %s" % (link["iden"], link["target_device_iden"]))
예제 #22
0
def pushFile(args):
    p = PushBullet(args.api_key)
    file = p.pushFile(args.device, open(args.file, 'rb'))
    if args.json:
        print(json.dumps(file))
        return
    print("File %s sent to %s" % (file["iden"], file["target_device_iden"]))
예제 #23
0
def pushList(args):
    p = PushBullet(args.api_key)
    lst = p.pushList(args.device, args.title, args.list)
    if args.json:
        print(json.dumps(lst))
        return
    print("List %s sent to %s" % (lst["iden"], lst["target_device_iden"]))
예제 #24
0
def test_encryption():
    pb = PushBullet("apikey", "hunter42")

    original = {"cat": "meow!"}
    encrypted = pb._encrypt_data(original)
    decrpyted = pb._decrypt_data(encrypted)

    assert original == json.loads(decrpyted)
예제 #25
0
 def connect(self):
     self.__client = PushBullet(self.__api_key)
     self.__sender = self.get_sender(self.__channel)
     self.__pokemon['sender'] = self.get_sender(self.__pokemon['channel'])
     self.__pokestop['sender'] = self.get_sender(self.__pokestop['channel'])
     self.__gym['sender'] = self.get_sender(self.__gym['channel'])
     self.__egg['sender'] = self.get_sender(self.__egg['channel'])
     self.__raid['sender'] = self.get_sender(self.__raid['channel'])
예제 #26
0
def get_pushbullet():
    global pushbullet
    if pushbullet is None:
        config = get_config()

        pushbullet = PushBullet(config["pushbullet"]["api-key"])

    return pushbullet
예제 #27
0
def pushAddress(args):
    p = PushBullet(args.api_key)
    address = p.pushAddress(args.device, args.name, " ".join(args.address))
    if args.json:
        print(json.dumps(address))
        return
    print("Address %s sent to %s" %
          (address["iden"], address["target_device_iden"]))
예제 #28
0
def addDevice(args):
    p = PushBullet(args.api_key)
    devices = p.addDevice(args.nickname)
    if args.json:
        print(json.dumps(devices))
        return
    print("Device %s was assigned ID %s" %
          (devices["nickname"], devices["iden"]))
예제 #29
0
def test_encryption_invalid_version():
    pb = PushBullet("apikey", "hunter42")

    original = {"cat": "meow!"}
    encrypted = pb._encrypt_data(original)
    encrypted = "2" + encrypted[1:]

    with pytest.raises(Exception):
        pb._decrypt_data(encrypted)
예제 #30
0
def getDevices(args):
    p = PushBullet(args.api_key)
    devices = p.getDevices()
    if args.json:
        print(json.dumps(devices))
        return
    for device in devices:
        print("%s %s %s" %
              (device["iden"], device["manufacturer"], device["model"]))