示例#1
0
def initialize_ring():
    cache_file = Path("token.cache")

    def token_updated(token):
        cache_file.write_text(json.dumps(token))

    def otp_callback():
        auth_code = input("2FA code: ")
        return auth_code

    if cache_file.is_file():
        auth = Auth("CamBot/1.0", json.loads(cache_file.read_text()),
                    token_updated)
    else:
        username = input("Username: "******"Password: "******"CamBot/1.0", None, token_updated)
        try:
            auth.fetch_token(username, password)
        except MissingTokenError:
            auth.fetch_token(username, password, otp_callback())

    ring = Ring(auth)
    ring.update_data()
    return ring
示例#2
0
def main():
    if cache_file.is_file():
        auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()), token_updated)
    else:
        username = input("Username: "******"Password: "******"MyProject/1.0", None, token_updated)
        try:
            auth.fetch_token(username, password)
        except MissingTokenError:
            auth.fetch_token(username, password, otp_callback())

    ring = Ring(auth)
    ring.update_data()

    devices = ring.devices()
    print(devices)

    doorbells = devices["doorbots"]
    chimes = devices["chimes"]
    stickup_cams = devices["stickup_cams"]

    print(doorbells)
    print(chimes)
    print(stickup_cams)
示例#3
0
def ring(mock_ring_requests):
    """Return ring object."""
    auth = Auth("PythonRingDoorbell/0.6")
    auth.fetch_token("foo", "bar")
    ring = Ring(auth)
    ring.update_data()
    return ring
示例#4
0
def ringOperations(emailname):
    s3 = boto3.client('s3')
    getCacheFileFromBucket(BUCKET_NAME, emailname)

    if cache_file.is_file():
        cachefile = open(CACHE_FILE_NAME, "r")
        tokendata = json.loads(cachefile.read())
        cachefile.close()
        auth = Auth("MyProject/1.0", tokendata, token_updated)
        uploadCacheFileToBucket(BUCKET_NAME, CACHE_FILE_NAME, emailname)

    ring = Ring(auth)
    ring.update_data()

    devices = ring.devices()

    getLatestMotionVideo(devices)
    getFrameFromVideo()
    sourceKey = "video_frame.png"
    imagelabels = getlabels(BUCKET_NAME, sourceKey)
    imagefaces = getfaces(BUCKET_NAME, sourceKey)
    imagetext = gettext(BUCKET_NAME, sourceKey)
    addImageInfotoTable(imagelabels, imagetext, imagefaces)

    s3.delete_object(Bucket=BUCKET_NAME, Key=sourceKey)
    s3.delete_object(Bucket=BUCKET_NAME, Key="last_trigger.mp4")
示例#5
0
 def __init__(self):
     if cache_file.is_file():
         auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()),
                     token_updated)
     else:
         username = input("Username: "******"Password: "******"MyProject/1.0", None, token_updated)
         try:
             auth.fetch_token(username, password)
         except MissingTokenError:
             auth.fetch_token(username, password, otp_callback())
     self.ring = Ring(auth)
     self.ring.update_data()
示例#6
0
    def setUp(self, mock):
        """Setup unit test and load mock."""
        from ring_doorbell import Ring
        mock.get('https://api.ring.com/clients_api/ring_devices',
                 text=load_fixture('ring_devices.json'))
        mock.post('https://api.ring.com/clients_api/session',
                  text=load_fixture('ring_session.json'))
        mock.put('https://api.ring.com/clients_api/device',
                 text=load_fixture('ring_devices.json'))

        self.ring = Ring(USERNAME, PASSWORD, cache_file=CACHE)
        self.ring_persistent = \
            Ring(USERNAME, PASSWORD, cache_file=CACHE, persist_token=True)

        self.assertTrue(hasattr(self.ring, "update"))
def initialize_ring():
    if cache_file.is_file():
        auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()),
                    token_updated)
    else:
        auth = Auth("MyProject/1.0", None, token_updated)
        try:
            auth.fetch_token(config.ringuser, config.ringpassword)
        except MissingTokenError:
            auth.fetch_token(config.ringuser, config.ringpassword,
                             otp_callback())

    ring = Ring(auth)
    ring.update_data()
    return ring
示例#8
0
def connectToRingAPI():
    global myring
    global mypath
    myring = Ring('*****@*****.**', 'password')
    mypath = '/home/joep/FibaroRingCam/'
    currenttime = time.strftime("%b %d %H:%M:%S")
    print ('{} Connected to ring: {}'.format(currenttime, myring.is_connected))
示例#9
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up a sensor for a Ring device."""
    from ring_doorbell import Ring

    ring = Ring(config.get(CONF_USERNAME), config.get(CONF_PASSWORD))

    persistent_notification = loader.get_component('persistent_notification')
    try:
        ring.is_connected
    except (ConnectTimeout, HTTPError) as ex:
        _LOGGER.error("Unable to connect to Ring service: %s", str(ex))
        persistent_notification.create(
            hass, 'Error: {}<br />'
            'You will need to restart hass after fixing.'
            ''.format(ex),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)
        return False

    sensors = []
    for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
        for device in ring.chimes:
            if 'chime' in SENSOR_TYPES[sensor_type][1]:
                sensors.append(RingSensor(hass,
                                          device,
                                          sensor_type))

        for device in ring.doorbells:
            if 'doorbell' in SENSOR_TYPES[sensor_type][1]:
                sensors.append(RingSensor(hass,
                                          device,
                                          sensor_type))

    add_devices(sensors, True)
    return True
示例#10
0
def setup(hass, config):
    """Set up Ring component."""
    conf = config[DOMAIN]
    username = conf.get(CONF_USERNAME)
    password = conf.get(CONF_PASSWORD)

    persistent_notification = loader.get_component('persistent_notification')
    try:
        from ring_doorbell import Ring

        cache = hass.config.path(DEFAULT_CACHEDB)
        ring = Ring(username=username, password=password, cache_file=cache)
        if not ring.is_connected:
            return False
        hass.data['ring'] = ring
    except (ConnectTimeout, HTTPError) as ex:
        _LOGGER.error("Unable to connect to Ring service: %s", str(ex))
        persistent_notification.create(
            hass,
            'Error: {}<br />'
            'You will need to restart hass after fixing.'
            ''.format(ex),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)
        return False
    return True
示例#11
0
def main(download_only=False):
    if cache_file.is_file():
        auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()), token_updated)
    else:
        username = os.environ.get('USERNAME')
        password = os.environ.get('PASSWORD')
        auth = Auth("MyProject/1.0", None, token_updated)
        try:
            auth.fetch_token(username, password)
        except MissingTokenError:
            auth.fetch_token(username, password, otp_callback())

    ring = Ring(auth)
    ring.update_data()

    wait_for_update(ring, download_only=download_only)
示例#12
0
def total_video_count():
    print("getting the total number of videos in the ring account\n\n")
    myring = Ring(
        config.username, config.password
    )  # enters the username and the password from the config file
    doorbell = myring.doorbells[
        0]  # selects the first doorbell from the doorbell query lists.

    events = []  # events is a list that will store  info from the histroy.
    counter = 0  # a counter that will be used to count the number of videos
    history = doorbell.history(
        limit=100
    )  # get the information about the last 100 videos taken. Histroy is set to thiss.
    while (
            len(history) > 0
    ):  # keeps doing it until it gets all of the videos info from the ring account.
        events += history  # info from histroy is added to events.
        counter += len(
            history)  # tells us the total amount of videos in the account.
        history = doorbell.history(
            older_than=history[-1]['id']
        )  # gets 100 videos that are older than  the last video listed in the list.
    print("total amount of videos is " +
          str(counter))  # prints out the total amount of videos
    return counter  # returns the counter so it can be used later on.
示例#13
0
    def blocking_login(self):
        def token_updater(token):
            asyncio.run_coroutine_threadsafe(self.token_updated(token),
                                             self.loop).result()

        if self._token != "":
            self._auth = Auth(self._ridentifier + "/1.0", self._token,
                              token_updater)
        else:
            if self._password != "":
                self._auth = Auth(self._ridentifier + "/1.0", None,
                                  token_updater)
                if self._2facode:
                    self._auth.fetch_token(self._username, self._password,
                                           self._2facode)
                else:
                    try:
                        self._auth.fetch_token(self._username, self._password)
                    except AccessDeniedError:
                        return "AccessDenied: wrong username or password"
                    except MissingTokenError:
                        return "please set 2fa_code"
            else:
                return "please set password"
        self._ring = Ring(self._auth)
示例#14
0
def collect(event, context):
    myring = Ring(username, password)

    push_to_dynamo(myring.doorbells)
    push_to_dynamo(myring.stickup_cams)

    return "Done"
示例#15
0
def main():


    videocount = total_vide_count() # video count holds the total amount of videos
    downloasdurl = [] # this will hold all of the download urls.

    eventidlist = [] # the list that will hold the video ID's
    myring = Ring(config.username, config.password) # enters the password and username for ring.
    doorbell = myring.doorbells[0] # gets the first doorbell found in the ring list.
    for doorbell in myring.doorbells:

        # listing the last 100 events of any kind
        for event in doorbell.history(limit=100):

            # print('ID:       %s' % event['id'])  prints every single ID in the histroy list.
            eventidlist.append(event['id']) # appends the eventids to the eventidlist.
            # print('--' * 50)
        print("the length of eventid list is " + str(len(eventidlist))) # prints the length of list id eventidlist
        print("eventidlist is " + str(eventidlist))  # prints out all of the items in the eventID list.
        histroy = doorbell.history(limit=100, older_than=eventidlist[-1])  # defines histroy to get all of the videos older than the last video listed in the list.

        while(len(eventidlist) < videocount):
            histroy = doorbell.history(limit=100, older_than=eventidlist[-1]) # defines histroy to get all of the videos older than the last video listed in the list.

            for event in histroy:
                # print('ID:       %s' % event['id'])
                eventidlist.append(event['id'])  # adds the IDs to the list.
                eventidlist = list(dict.fromkeys(eventidlist)) # removes any duplicates in the list.
            print("the length of eventid list is " + str(len(eventidlist))) # prints the length of the list
            print("event id list is " + str(eventidlist)) # prints what is in the list.
def main():
    global cache_file, token_updated, ring
    if not cache_file.is_file():
        print("Token not found", file=sys.stderr)
        exit(1)

    print("Instantiating ring api...")
    auth = Auth(user_agent="SmartThingsApi/0.1",
                token=json.loads(cache_file.read_text()),
                token_updater=token_updated)
    ring = Ring(auth)
    ring.update_data()
    print("Instantiating background job...")
    scheduler = BackgroundScheduler()
    scheduler.add_job(pingring, 'interval', hours=2)
    scheduler.start()
    print("Starting web server...")
    run()
示例#17
0
def main():
    if cache_file.is_file():
        auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()),
                    token_updated)
    else:
        username = input("Username: "******"Password: "******"MyProject/1.0", None, token_updated)
        try:
            auth.fetch_token(username, password)
        except MissingTokenError:
            auth.fetch_token(username, password, otp_callback())

    ring = Ring(auth)
    ring.update_data()

    devices = ring.devices()
    print(devices)

    doorbells = devices["doorbots"]
    chimes = devices["chimes"]
    stickup_cams = devices["stickup_cams"]

    print(doorbells)
    #print(chimes)
    #print(stickup_cams)
    x = 0
    y = 0
    limit = 100
    doorbell = devices['doorbots'][0]
    typelist = {
        "motion",
        "ding",
    }
    for rt in typelist:
        print(rt)
        for i in doorbell.history(limit=limit, kind=rt):
            print(i['id'])
            doorbell.recording_download(
                doorbell.history(limit=limit, kind=rt)[x]['id'],
                filename=str(i['created_at'].strftime("%m-%d-%Y-%H-%M-%S")) +
                '.mp4',
                override=True)
            x += 1
示例#18
0
def main():
    if cache_file.is_file():
        print("Token has already been set up, loading...")
        auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()),
                    token_updated)
    else:
        username = my_email
        print(
            "This is the first time setting up, getting the token set up now..."
        )
        password = getpass.getpass("Password: "******"MyProject/1.0", None, token_updated)
        try:
            auth.fetch_token(username, password)
        except MissingTokenError:
            auth.fetch_token(username, password, otp_callback())

    ring = Ring(auth)
    ring.update_data()
    def fetch_video_urls(self, username, password):
        ring_obj = Ring(username, password)
        number_of_cam = len(ring_obj.devices['stickup_cams'])
        video_urls = []
        for counter in range(0, number_of_cam):
            stickup_cam = ring_obj.stickup_cams[counter]
            counter = counter + 1
            video_urls.append(
                stickup_cam.recording_url(stickup_cam.last_recording_id))

        return video_urls
示例#20
0
def setup(hass, config):
    """Set up the Ring component."""
    conf = config[DOMAIN]
    username = conf[CONF_USERNAME]
    password = conf[CONF_PASSWORD]
    scan_interval = conf[CONF_SCAN_INTERVAL]

    try:
        from ring_doorbell import Ring

        cache = hass.config.path(DEFAULT_CACHEDB)
        ring = Ring(username=username, password=password, cache_file=cache)
        if not ring.is_connected:
            return False
        hass.data[DATA_RING_CHIMES] = chimes = ring.chimes
        hass.data[DATA_RING_DOORBELLS] = doorbells = ring.doorbells
        hass.data[DATA_RING_STICKUP_CAMS] = stickup_cams = ring.stickup_cams

        ring_devices = chimes + doorbells + stickup_cams

    except (ConnectTimeout, HTTPError) as ex:
        _LOGGER.error("Unable to connect to Ring service: %s", str(ex))
        hass.components.persistent_notification.create(
            "Error: {}<br />"
            "You will need to restart hass after fixing."
            "".format(ex),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID,
        )
        return False

    def service_hub_refresh(service):
        hub_refresh()

    def timer_hub_refresh(event_time):
        hub_refresh()

    def hub_refresh():
        """Call ring to refresh information."""
        _LOGGER.debug("Updating Ring Hub component")

        for camera in ring_devices:
            _LOGGER.debug("Updating camera %s", camera.name)
            camera.update()

        dispatcher_send(hass, SIGNAL_UPDATE_RING)

    # register service
    hass.services.register(DOMAIN, "update", service_hub_refresh)

    # register scan interval for ring
    track_time_interval(hass, timer_hub_refresh, scan_interval)

    return True
 def __init__(self, username, password, history_limit):
     self.ring = Ring(username, password)
     self.history_limit = history_limit
     if self.ring.is_connected:
         if self.ring.stickup_cams is not None and len(
                 self.ring.stickup_cams) > 0:
             self.cameras = self.ring.stickup_cams
         else:
             raise Exception("Unable to connect to find any devices")
     else:
         raise Exception("Unable to connect to the Ring API")
示例#22
0
def main():
    # initialize logger for debugging
    initialize_logger()

    if cache_file.is_file():
        auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()),
                    token_updated)
    else:
        # initialize ring account username and password
        username = config('user')
        password = config('pw')

        # use the Authenticator of the ring_doorbell API
        # tries to fetch token for authentication
        # requests user input for the code if necessary
        auth = Auth("MyProject/1.0", None, token_updated)
        try:
            auth.fetch_token(username, password)
        except MissingTokenError:
            auth.fetch_token(username, password, otp_callback())

    threshold = input(
        "Enter the percentage where-in you want to get reminders: ")
    # loop for checking battery life
    while True:
        ring = Ring(auth)
        ring.update_data()

        # filter the Ring Devices
        devices = ring.devices()
        front_door = devices['authorized_doorbots']

        battery_life = front_door[0].battery_life
        logging.info(f'The current battery life is {battery_life}')
        # if battery is less than threshold, send the e-mail
        if (battery_life <= int(threshold)):
            logging.info("Sending the email")
            send_email(battery_life)

        # loop sleeps for 6 hours 21600
        sleep(3600)
示例#23
0
    def test_basic_attributes(self, get_mock, post_mock):
        """Test the Ring class and methods."""
        from ring_doorbell import Ring

        myring = Ring(USERNAME, PASSWORD, cache_file=CACHE)
        self.assertTrue(myring.is_connected)
        self.assertIsInstance(myring.cache, dict)
        self.assertFalse(myring.debug)
        self.assertEqual(1, len(myring.chimes))
        self.assertEqual(2, len(myring.doorbells))
        self.assertFalse(myring._persist_token)
        self.assertEquals('http://localhost/', myring._push_token_notify_url)
示例#24
0
def init():

    email = ADDON.getSetting('email')
    password = ADDON.getSetting('password')
    items = ADDON.getSetting('items')

    if len(email) <= 7:
        return showModal(ADDON.getLocalizedString(30200))
    if not re.match(r'[\w.-]+@[\w.-]+.\w+', email):
        return showModal(ADDON.getLocalizedString(30200))
    if len(password) <= 3:
        return showModal(ADDON.getLocalizedString(30201))
    if items.isdigit() == False:
        return showModal(ADDON.getLocalizedString(30202))

    try:
        myring = Ring(email, password)
    except:
        return showModal(ADDON.getLocalizedString(30203))

    if mode is None:
        events = []
        for device in list(myring.stickup_cams + myring.doorbells):
            for event in device.history(limit=items):
                event['formatted'] = format_event(device, event)
                event['doorbell_id'] = device.id
                events.append(event)
        sorted_events = sorted(events, key=lambda k: k['id'], reverse=True)
        for event in sorted_events:
            url = build_url({
                'mode': 'play',
                'doorbell_id': event['doorbell_id'],
                'video_id': event['id']
            })
            li = xbmcgui.ListItem(str(event['formatted']),
                                  iconImage='DefaultVideo.png')
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=url,
                                        listitem=li,
                                        isFolder=True)
        xbmcplugin.endOfDirectory(addon_handle)
    else:
        if mode[0] == 'play':
            doorbell_id = args['doorbell_id'][0]
            video_id = args['video_id'][0]
            for doorbell in list(myring.stickup_cams + myring.doorbells):
                if doorbell.id == doorbell_id:
                    try:
                        url = doorbell.recording_url(video_id)
                        play_video(url)
                    except:
                        return showModal(ADDON.getLocalizedString(30204))
示例#25
0
def main():
    if cache_file.is_file():
        auth = Auth(
            "HomeAssistant/0.105.0dev0",
            json.loads(cache_file.read_text()),
            token_updated,
        )
    else:
        username = input("Username: "******"Password: "******"Hello {ring.session['profile']['first_name']}")
    print()
    pprint(ring.devices_data)
示例#26
0
class DoorbellManager(object):
    def __init__(self):
        if cache_file.is_file():
            auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()),
                        token_updated)
        else:
            username = input("Username: "******"Password: "******"MyProject/1.0", None, token_updated)
            try:
                auth.fetch_token(username, password)
            except MissingTokenError:
                auth.fetch_token(username, password, otp_callback())
        self.ring = Ring(auth)
        self.ring.update_data()

    def get_doorbell(self):
        devices = self.ring.devices()
        bell = devices["doorbots"][0]
        return bell

    def get_dings(self) -> DoorbellEvent:
        bell = self.get_doorbell()
        events = bell.history(limit=15, kind="ding")
        dings = list()
        for event in events:
            ding = DoorbellEvent(event)
            # ding.print()
            dings.append(ding)
        dings = sorted(dings, key=lambda ding: ding.timesince)
        return dings

    def get_last_ding(self) -> DoorbellEvent:
        dings = self.get_dings()
        if len(dings) > 0:
            ding = dings[0]
            return ding
        return None
示例#27
0
def main():
    if cache_file.is_file():
        auth = Auth("MyProject/1.0", json.loads(cache_file.read_text()),
                    token_updated)
    else:
        username = input("Username: "******"Password: "******"MyProject/1.0", None, token_updated)
        try:
            auth.fetch_token(username, password)
        except MissingTokenError:
            auth.fetch_token(username, password, otp_callback())

    ring = Ring(auth)
    ring.update_data()

    devices = ring.devices()
    pprint(devices)

    # play with the API to figure out which camera you want
    deck = devices['doorbots'][0]
    download(deck)
    print('\nDONE.')
示例#28
0
    def test_chime_attributes(self, get_mock, post_mock):
        """Test the Ring Chime class and methods."""
        from ring_doorbell import Ring

        myring = Ring(USERNAME, PASSWORD, cache_file=CACHE)
        dev = myring.chimes[0]

        self.assertEqual('123 Main St', dev.address)
        self.assertNotEqual(99999, dev.account_id)
        self.assertEqual('abcdef123', dev.id)
        self.assertEqual('chime', dev.kind)
        self.assertIsNotNone(dev.latitude)
        self.assertEqual('America/New_York', dev.timezone)
        self.assertEqual(2, dev.volume)
示例#29
0
def main():
    if cache_file.is_file():
        token = json.loads(cache_file.read_text())
        auth = Auth("Ringer/1.0", token, token_updated)
        print(f"Token expires at {expires_at_to_datetime(token['expires_at'])}")
    else:
        username = input("Username: "******"Password: "******"Ringer/1.0", None, token_updated)
        try:
            auth.fetch_token(username, password)
        except MissingTokenError:
            auth.fetch_token(username, password, otp_callback())

    ring = Ring(auth)
    ring.update_data()

    devices = ring.devices()
    pprint(devices)

    doorbell = devices['doorbots'][0]
    history = doorbell.history(limit=100, kind='motion')
    id = history[0]['id']
    doorbell.recording_download(
        id,
        filename=f'doorbell_motion_{id}.mp4',
        override=True)

    cams = devices['stickup_cams']
    for cam in cams:
        history = cam.history(limit=100, kind='motion')
        id = history[0]['id']
        cam.recording_download(
            id,
            filename=f'cam_motion_{id}.mp4',
            override=True)
示例#30
0
    def test_doorbell_alerts(self, get_mock, post_mock):
        """Test the Ring DoorBell alerts."""
        from ring_doorbell import Ring

        myring = Ring(USERNAME, PASSWORD, cache_file=CACHE, persist_token=True)
        for dev in myring.doorbells:
            self.assertEqual('America/New_York', dev.timezone)

            # call alerts
            dev.check_alerts()

            self.assertIsInstance(dev.alert, dict)
            self.assertIsInstance(dev.alert_expires_at, datetime)
            self.assertTrue(datetime.now() <= dev.alert_expires_at)
            self.assertIsNotNone(dev._ring.cache_file)