def __init__( self, refresh_rate=DEFAULT_REFRESH, motion_interval=DEFAULT_MOTION_INTERVAL, no_owls=False, ): """ Initialize Blink system. :param refresh_rate: Refresh rate of blink information. Defaults to 15 (seconds) :param motion_interval: How far back to register motion in minutes. Defaults to last refresh time. Useful for preventing motion_detected property from de-asserting too quickly. :param no_owls: Disable searching for owl entries (blink mini cameras only known entity). Prevents an uneccessary API call if you don't have these in your network. """ self.auth = Auth() self.account_id = None self.client_id = None self.network_ids = [] self.urls = None self.sync = CaseInsensitiveDict({}) self.last_refresh = None self.refresh_rate = refresh_rate self.networks = [] self.cameras = CaseInsensitiveDict({}) self.video_list = CaseInsensitiveDict({}) self.motion_interval = motion_interval self.version = __version__ self.available = False self.key_required = False self.homescreen = {} self.no_owls = no_owls
async def async_step_user(self, user_input=None): """Handle a flow initiated by the user.""" errors = {} data = {CONF_USERNAME: "", CONF_PASSWORD: "", "device_id": DEVICE_ID} if user_input is not None: data[CONF_USERNAME] = user_input["username"] data[CONF_PASSWORD] = user_input["password"] self.auth = Auth(data, no_prompt=True) await self.async_set_unique_id(data[CONF_USERNAME]) try: await self.hass.async_add_executor_job(validate_input, self.hass, self.auth) return self._async_finish_flow() except Require2FA: return await self.async_step_2fa() except InvalidAuth: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" data_schema = { vol.Required("username"): str, vol.Required("password"): str, } return self.async_show_form( step_id="user", data_schema=vol.Schema(data_schema), errors=errors, )
def start_blink_session( blink_config_file: str, blink_username, blink_password ) -> (bool, object, object): """Starts a blink cam session :param blink_config_file: blink session config file path :type blink_config_file: string :param blink_username: blink username :type blink_username: string :param blink_password: blink password :type blink_password: string :return: authentication_success for existing session or 2FA token required, blink instance, auth instance :rtype authentication_success: boolean :rtype blink: class :rtype auth: class """ blink = Blink(refresh_rate=3) if os.path.exists(blink_config_file): logger.info("using existing blink_config.json") auth = Auth(json_load(blink_config_file), no_prompt=True) authentication_success = True else: logger.info( "no blink_config.json found - 2FA " + "authentication token required" ) auth = Auth( {"username": blink_username, "password": blink_password}, no_prompt=True ) authentication_success = None blink.auth = auth opts = {"retries": 10, "backoff": 2} blink.auth.session = blink.auth.create_session(opts=opts) try: logger.info("start blink session") blink.start() except Exception as err: logger.info("blink session exception occured: {0}".format(err)) pass return authentication_success, blink, auth
def get(self, force_reset=False): if force_reset or not self._auth_file_exists(): self.blink = self._refresh_auth(reset=True) else: self.blink.auth = Auth(login_data=json_load(self.auth_file), no_prompt=True) self.blink.start() if not self.blink.available: return self._refresh_auth(reset=False) return self.blink
def _refresh_auth(self, reset=False): self.blink = Blink() with_sleep = False if not reset and self._auth_file_exists(): self.blink.auth = Auth(json_load(self.auth_file)) with_sleep = True else: self.blink.auth = Auth() self.blink.start() # write auth file self.blink.save(self.auth_file) print('Auth file updated: ' + self.auth_file) if with_sleep: time.sleep(3) return self.get(force_reset=False)
def InitBlink(): global blinkStatus, statusMessage if not os.path.exists(blinkCredentials): blinkStatus = -1 statusMessage ='Blink credential file '+blinkCredentials+' does not exist.' else: auth = Auth(json_load(blinkCredentials)) blink.auth = auth blink.start() blinkStatus = 1 statusMessage = 'Blink started ok' print ('Initblink finished: '+statusMessage)
def reauth(self): self.blink = Blink() creds = self.blink_location / "creds.json" started = False print("Logging in to Blink...") if creds.is_file(): auth = Auth(json_load(creds)) auth.no_prompt = True self.blink.auth = auth started = self.blink.start() return started
def test_empty_init(self, getpwd, genuid): """Test initialization with no params.""" auth = Auth() self.assertDictEqual(auth.data, {}) getpwd.return_value = "bar" genuid.return_value = 1234 with mock.patch("builtins.input", return_value="foo"): auth.validate_login() expected_data = { "username": "******", "password": "******", "uid": 1234, "device_id": const.DEVICE_ID, } self.assertDictEqual(auth.data, expected_data)
def _blink_startup_wrapper(hass, entry): """Startup wrapper for blink.""" blink = Blink() auth_data = deepcopy(dict(entry.data)) blink.auth = Auth(auth_data, no_prompt=True) blink.refresh_rate = entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) if blink.start(): blink.setup_post_verify() elif blink.auth.check_key_required(): _LOGGER.debug("Attempting a reauth flow") _reauth_flow_wrapper(hass, auth_data) return blink
def test_barebones_init(self, getpwd, genuid): """Test basebones initialization.""" login_data = {"username": "******", "password": "******"} auth = Auth(login_data) self.assertDictEqual(auth.data, login_data) getpwd.return_value = "bar" genuid.return_value = 1234 with mock.patch("builtins.input", return_value="foo"): auth.validate_login() expected_data = { "username": "******", "password": "******", "uid": 1234, "device_id": const.DEVICE_ID, } self.assertDictEqual(auth.data, expected_data)
def blink_video_schedule(event, context): """Triggered from a message on a Cloud Pub/Sub topic. Args: event (dict): Event payload. context (google.cloud.functions.Context): Metadata for the event.""" FILENAME = 'blink_creds.json' #FILENAME = re.sub(r"\/.*\/(.*\.\w{1,4}",r'\1',FILE) #BLOB_UPLOAD = BLINK_BUCKET.blob(f"{create_file_path()[1:]}/{FILENAME}") #Set filename format (uploads/year/month/filename). #BLOB_UPLOAD.upload_from_filename(FILE) USER_NAME, PASSWORD = load_credentials() AUTH = Auth({"username": USER_NAME, "password": PASSWORD}, no_prompt=True) pubsub_message = base64.b64decode(event['data']).decode('utf-8') if pubsub_message == 'RUN': blink = Blink() blink.auth = AUTH blink.start() AUTH.send_auth_key(blink, '167363') blink.setup_post_verify() #print(type(blink.save(f'{FILENAME}'))) CREDS = json_load("blink_creds.json") blob_blink = BLINK_BUCKET.blob('blink_creds.json') blob_blink.upload_from_string(data=json.dumps(CREDS), content_type='application/json') print('i am before the cameras') print(blink.cameras.items()) try: for name, camera in blink.cameras.items(): print('i am inside the camera') print(name) # Name of the camera print( camera.attributes) # Print available attributes of camera except ValueError: print('there is some error') blink.download_videos(since='2018/07/04 09:34') return "SUCCESS"
def test_full_init(self): """Test full initialization.""" login_data = { "username": "******", "password": "******", "token": "token", "host": "host", "region_id": "region_id", "client_id": "client_id", "account_id": "account_id", "uid": 1234, "notification_key": 4321, "device_id": "device_id", } auth = Auth(login_data) self.assertEqual(auth.token, "token") self.assertEqual(auth.host, "host") self.assertEqual(auth.region_id, "region_id") self.assertEqual(auth.client_id, "client_id") self.assertEqual(auth.account_id, "account_id") auth.validate_login() self.assertDictEqual(auth.login_attributes, login_data)
def start(): """Startup blink app.""" blink = Blink() blink.auth = Auth(json_load(CREDFILE)) blink.start() return blink
def setUp(self): """Set up Login Handler.""" self.auth = Auth()
return user_name, password def create_file_path(): year = datetime.datetime.now().strftime("%Y") month = datetime.datetime.now().strftime("%m") file_path = f'/uploads/{year}/{month}' return file_path FILENAME= 'blink_creds.json' #FILENAME = re.sub(r"\/.*\/(.*\.\w{1,4}",r'\1',FILE) #BLOB_UPLOAD = BLINK_BUCKET.blob(f"{create_file_path()[1:]}/{FILENAME}") #Set filename format (uploads/year/month/filename). #BLOB_UPLOAD.upload_from_filename(FILE) USER_NAME, PASSWORD = load_credentials() AUTH = Auth({"username": USER_NAME, "password": PASSWORD}, no_prompt=True) blink = Blink() blink.auth = AUTH blink.start() AUTH.send_auth_key(blink, '399587') blink.setup_post_verify() print(type(blink.save(f'{FILENAME}'))) CREDS = json_load("blink_creds.json") blob_blink = BLINK_BUCKET.blob('blink_creds.json')
try: username = data["username"] password = data["password"] except KeyError: print(f" ... File contents of {auth_file} incorrect.") print(" ... Require username and password at minimum.") print(" ... Exiting.") sys.exit(1) if save_session: print(f" ... Saving session file to {session_path}.") json_save({"file": auth_file}, session_path) blink = Blink() auth = Auth(data) blink.auth = auth print(" ... Starting Blink.") print("") blink.start() print("") print(" ... Printing login response.") print("") print(blink.auth.login_response) print("") print(" ... Printing login attributes.") print("") print(blink.auth.login_attributes) print("") input(" ... Press any key to continue: ")
from html.parser import HTMLParser from urllib.request import urlopen import json, time from blinkpy.blinkpy import Blink from blinkpy.auth import Auth blink = Blink() # https://pypi.org/project/blinkpy/ auth = Auth( { "username": "******", "password": "******" }, no_prompt=False) trusted_mac_addresses = ["aa:bb:cc:dd:ee:ff"] blink.auth = auth blink.start() # all this shit below here is to parse my router's device list properly. i love proper object notation, and tried to do this without regex. ;p in_table = False this_device = [] row_name = "" last_tag = "" device_list = {} class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): global in_table, this_device, row_name, last_tag, device_list if tag == "table": in_table = True
OFFSET_SECONDS = 60 TIMEOUT_SECONDS = 60 NOTIFY_ENTITY_NAMES = ["mobile_app_dullage_s_iphone", "mobile_app_iphone"] # NOTIFY_ENTITY_NAMES = ["mobile_app_dullage_s_iphone"] # Debug VIDEO_FILE = os.path.join(SAVE_PATH, VIDEO_FILENAME) IMAGE_FILE = os.path.join(SAVE_PATH, IMAGE_FILENAME) with open(SECRETS_FILE, "r") as secrets_file: secrets = yaml.load(secrets_file) blink = blinkpy.Blink() auth = Auth( { "username": secrets["blinkUsername"], "password": secrets["blinkPassword"], "device_id": "Doorbell Script", }, no_prompt=True, ) blink.auth = auth blink.start() from_time = time.time() - OFFSET_SECONDS loop_start = datetime.today() while True: videos = api.request_videos(blink, time=from_time)["media"] if len(videos) >= 1: break if datetime.today() >= (loop_start + timedelta(seconds=TIMEOUT_SECONDS)):