示例#1
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = Blink(username=USERNAME, password=PASSWORD)
     self.blink.sync["test"] = BlinkSyncModule(self.blink, "test", "1234",
                                               [])
     self.blink.urls = BlinkURLHandler("test")
     self.blink.session = create_session()
示例#2
0
 def login_only(self):
     self.blink = Blink()
     creds = self.blink_location / "creds.json"
     started = self.blink.start()
     if started:
         self.blink.save(creds)
     return started
示例#3
0
class CustBlink:
    def __init__(self, blink_location, blink_period):
        self.blink_location = blink_location
        self.blink_period = blink_period
        if not blink_location.is_dir():
            blink_location.mkdir()

    def login_only(self):
        self.blink = Blink()
        creds = self.blink_location / "creds.json"
        started = self.blink.start()
        if started:
            self.blink.save(creds)
        return started

    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
示例#4
0
 def setUp(self):
     """Set up Blink module."""
     self.blink_no_cred = Blink()
     self.blink = Blink(username=USERNAME, password=PASSWORD)
     self.blink.sync['test'] = BlinkSyncModule(self.blink, 'test', '1234',
                                               [])
     self.blink.urls = BlinkURLHandler('test')
     self.blink.session = create_session()
示例#5
0
    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
示例#6
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = Blink(motion_interval=0)
     self.blink.last_refresh = 0
     self.blink.urls = BlinkURLHandler("test")
     self.blink.sync["test"] = BlinkSyncModule(self.blink, "test", "1234",
                                               [])
     self.camera = BlinkCamera(self.blink.sync)
     self.mock_start = [
         {
             "syncmodule": {
                 "id": 1234,
                 "network_id": 5678,
                 "serial": "12345678",
                 "status": "foobar",
             }
         },
         {
             "event": True
         },
         {},
         {},
         None,
         {
             "devicestatus": {}
         },
     ]
     self.blink.sync["test"].network_info = {"network": {"armed": True}}
示例#7
0
 def setUp(self):
     """Set up Blink module."""
     self.blink = Blink()
     self.blink.urls = BlinkURLHandler("test")
     self.blink.sync["test"] = BlinkSyncModule(self.blink, "test", 1234, [])
     self.camera = BlinkCamera(self.blink.sync["test"])
     self.camera.name = "foobar"
     self.blink.sync["test"].cameras["foobar"] = self.camera
示例#8
0
def _send_blink_2fa_pin(auth, pin):
    """Send 2FA pin to blink servers."""
    blink = Blink()
    blink.auth = auth
    blink.setup_login_ids()
    blink.setup_urls()
    return auth.send_auth_key(blink, pin)
示例#9
0
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
示例#10
0
    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)
示例#11
0
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"
示例#12
0
    async def async_step_user(self, user_input=None):
        """Handle a flow initiated by the user."""
        errors = {}
        if user_input is not None:
            self.data[CONF_USERNAME] = user_input["username"]
            self.data[CONF_PASSWORD] = user_input["password"]

            await self.async_set_unique_id(self.data[CONF_USERNAME])

            if CONF_SCAN_INTERVAL in user_input:
                self.data[CONF_SCAN_INTERVAL] = user_input[CONF_SCAN_INTERVAL]

            self.blink = Blink(
                username=self.data[CONF_USERNAME],
                password=self.data[CONF_PASSWORD],
                motion_interval=DEFAULT_OFFSET,
                legacy_subdomain=False,
                no_prompt=True,
                device_id=DEVICE_ID,
            )

            try:
                response = await validate_input(self.hass, self.blink)
                self.data["login_response"] = response
                return self.async_create_entry(
                    title=DOMAIN,
                    data=self.data,
                )
            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,
        )
示例#13
0
文件: __init__.py 项目: jbouwh/core
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
示例#14
0
class BlinkSession:

    def __init__(
            self
    ):
        self.auth_file = AUTH_FILE
        self.blink = Blink()

    def _auth_file_exists(self):
        return os.path.exists(self.auth_file)

    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 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
示例#15
0
class TestBlinkSetup(unittest.TestCase):
    """Test the Blink class in blinkpy."""
    def setUp(self):
        """Set up Blink module."""
        self.blink_no_cred = Blink()
        self.blink = Blink(username=USERNAME, password=PASSWORD)
        self.blink.sync['test'] = BlinkSyncModule(self.blink, 'test', '1234',
                                                  [])
        self.blink.urls = BlinkURLHandler('test')
        self.blink.session = create_session()

    def tearDown(self):
        """Clean up after test."""
        self.blink = None
        self.blink_no_cred = None

    def test_initialization(self, mock_sess):
        """Verify we can initialize blink."""
        self.assertEqual(self.blink.version, __version__)
        # pylint: disable=protected-access
        self.assertEqual(self.blink._username, USERNAME)
        # pylint: disable=protected-access
        self.assertEqual(self.blink._password, PASSWORD)

    def test_no_credentials(self, mock_sess):
        """Check that we throw an exception when no username/password."""
        with self.assertRaises(BlinkAuthenticationException):
            self.blink_no_cred.get_auth_token()
        # pylint: disable=protected-access
        self.blink_no_cred._username = USERNAME
        with self.assertRaises(BlinkAuthenticationException):
            self.blink_no_cred.get_auth_token()

    def test_no_auth_header(self, mock_sess):
        """Check that we throw an exception when no auth header given."""
        # pylint: disable=unused-variable
        (region_id, region), = mresp.LOGIN_RESPONSE['region'].items()
        self.blink.urls = BlinkURLHandler(region_id)
        with self.assertRaises(BlinkException):
            self.blink.get_ids()

    @mock.patch('blinkpy.blinkpy.getpass.getpass')
    def test_manual_login(self, getpwd, mock_sess):
        """Check that we can manually use the login() function."""
        getpwd.return_value = PASSWORD
        with mock.patch('builtins.input', return_value=USERNAME):
            self.assertTrue(self.blink_no_cred.login())
        # pylint: disable=protected-access
        self.assertEqual(self.blink_no_cred._username, USERNAME)
        # pylint: disable=protected-access
        self.assertEqual(self.blink_no_cred._password, PASSWORD)

    def test_bad_request(self, mock_sess):
        """Check that we raise an Exception with a bad request."""
        self.blink.session = create_session()
        explog = ("ERROR:blinkpy.helpers.util:"
                  "Cannot obtain new token for server auth.")
        with self.assertRaises(BlinkException):
            http_req(self.blink, reqtype='bad')

        with self.assertLogs() as logrecord:
            http_req(self.blink, reqtype='post', is_retry=True)
        self.assertEqual(logrecord.output, [explog])

    def test_authentication(self, mock_sess):
        """Check that we can authenticate Blink up properly."""
        authtoken = self.blink.get_auth_token()['TOKEN_AUTH']
        expected = mresp.LOGIN_RESPONSE['authtoken']['authtoken']
        self.assertEqual(authtoken, expected)

    def test_reauthorization_attempt(self, mock_sess):
        """Check that we can reauthorize after first unsuccessful attempt."""
        original_header = self.blink.get_auth_token()
        # pylint: disable=protected-access
        bad_header = {'Host': self.blink._host, 'TOKEN_AUTH': 'BADTOKEN'}
        # pylint: disable=protected-access
        self.blink._auth_header = bad_header
        self.assertEqual(self.blink.auth_header, bad_header)
        api.request_homescreen(self.blink)
        self.assertEqual(self.blink.auth_header, original_header)

    @mock.patch('blinkpy.api.request_networks')
    def test_multiple_networks(self, mock_net, mock_sess):
        """Check that we handle multiple networks appropriately."""
        mock_net.return_value = {
            'networks': [{
                'id': 1234,
                'account_id': 1111
            }, {
                'id': 5678,
                'account_id': 2222
            }]
        }
        self.blink.networks = {
            '0000': {
                'onboarded': False,
                'name': 'foo'
            },
            '5678': {
                'onboarded': True,
                'name': 'bar'
            },
            '1234': {
                'onboarded': False,
                'name': 'test'
            }
        }
        self.blink.get_ids()
        self.assertTrue('5678' in self.blink.network_ids)
        self.assertEqual(self.blink.account_id, 2222)

    @mock.patch('blinkpy.api.request_networks')
    def test_multiple_onboarded_networks(self, mock_net, mock_sess):
        """Check that we handle multiple networks appropriately."""
        mock_net.return_value = {
            'networks': [{
                'id': 0000,
                'account_id': 2222
            }, {
                'id': 5678,
                'account_id': 1111
            }]
        }
        self.blink.networks = {
            '0000': {
                'onboarded': False,
                'name': 'foo'
            },
            '5678': {
                'onboarded': True,
                'name': 'bar'
            },
            '1234': {
                'onboarded': True,
                'name': 'test'
            }
        }
        self.blink.get_ids()
        self.assertTrue('5678' in self.blink.network_ids)
        self.assertTrue('1234' in self.blink.network_ids)
        self.assertEqual(self.blink.account_id, 1111)

    @mock.patch('blinkpy.blinkpy.time.time')
    def test_throttle(self, mock_time, mock_sess):
        """Check throttling functionality."""
        now = self.blink.refresh_rate + 1
        mock_time.return_value = now
        self.assertEqual(self.blink.last_refresh, None)
        self.assertEqual(self.blink.check_if_ok_to_update(), True)
        self.assertEqual(self.blink.last_refresh, None)
        with mock.patch('blinkpy.sync_module.BlinkSyncModule.refresh',
                        return_value=True):
            self.blink.refresh()

        self.assertEqual(self.blink.last_refresh, now)
        self.assertEqual(self.blink.check_if_ok_to_update(), False)
        self.assertEqual(self.blink.last_refresh, now)

    def test_sync_case_insensitive_dict(self, mock_sess):
        """Check that we can access sync modules ignoring case."""
        self.assertEqual(self.blink.sync['test'].name, 'test')
        self.assertEqual(self.blink.sync['TEST'].name, 'test')

    @mock.patch('blinkpy.api.request_login')
    def test_unexpected_login(self, mock_login, mock_sess):
        """Check that we appropriately handle unexpected login info."""
        mock_login.return_value = None
        self.assertFalse(self.blink.get_auth_token())

    @mock.patch('blinkpy.api.request_homescreen')
    def test_get_cameras(self, mock_home, mock_sess):
        """Check retrieval of camera information."""
        mock_home.return_value = {
            'cameras': [{
                'name': 'foo',
                'network_id': 1234,
                'id': 5678
            }, {
                'name': 'bar',
                'network_id': 1234,
                'id': 5679
            }, {
                'name': 'test',
                'network_id': 4321,
                'id': 0000
            }]
        }
        result = self.blink.get_cameras()
        self.assertEqual(
            result, {
                '1234': [{
                    'name': 'foo',
                    'id': 5678
                }, {
                    'name': 'bar',
                    'id': 5679
                }],
                '4321': [{
                    'name': 'test',
                    'id': 0000
                }]
            })

    @mock.patch('blinkpy.api.request_homescreen')
    def test_get_cameras_failure(self, mock_home, mock_sess):
        """Check that on failure we initialize empty info and move on."""
        mock_home.return_value = {}
        result = self.blink.get_cameras()
        self.assertEqual(result, {})
示例#16
0
class TestBlinkSetup(unittest.TestCase):
    """Test the Blink class in blinkpy."""
    def setUp(self):
        """Set up Blink module."""
        self.blink = Blink(username=USERNAME, password=PASSWORD)
        self.blink.sync["test"] = BlinkSyncModule(self.blink, "test", "1234",
                                                  [])
        self.blink.urls = BlinkURLHandler("test")
        self.blink.session = create_session()

    def tearDown(self):
        """Clean up after test."""
        self.blink = None

    def test_initialization(self, mock_sess):
        """Verify we can initialize blink."""
        self.assertEqual(self.blink.version, __version__)
        self.assertEqual(self.blink.login_handler.data["username"], USERNAME)
        self.assertEqual(self.blink.login_handler.data["password"], PASSWORD)

    def test_bad_request(self, mock_sess):
        """Check that we raise an Exception with a bad request."""
        self.blink.session = create_session()
        explog = "WARNING:blinkpy.helpers.util:" "Response from server: 200 - foo"
        with self.assertRaises(BlinkException):
            http_req(self.blink, reqtype="bad")

        with self.assertLogs() as logrecord:
            http_req(self.blink, reqtype="post", is_retry=True)
        self.assertEqual(logrecord.output, [explog])

    def test_authentication(self, mock_sess):
        """Check that we can authenticate Blink up properly."""
        authtoken = self.blink.get_auth_token()["TOKEN_AUTH"]
        expected = mresp.LOGIN_RESPONSE["authtoken"]["authtoken"]
        self.assertEqual(authtoken, expected)

    def test_reauthorization_attempt(self, mock_sess):
        """Check that we can reauthorize after first unsuccessful attempt."""
        original_header = self.blink.get_auth_token()
        # pylint: disable=protected-access
        bad_header = {"Host": self.blink._host, "TOKEN_AUTH": "BADTOKEN"}
        # pylint: disable=protected-access
        self.blink._auth_header = bad_header
        self.assertEqual(self.blink.auth_header, bad_header)
        api.request_homescreen(self.blink)
        self.assertEqual(self.blink.auth_header, original_header)

    def test_multiple_networks(self, mock_sess):
        """Check that we handle multiple networks appropriately."""
        self.blink.networks = {
            "0000": {
                "onboarded": False,
                "name": "foo"
            },
            "5678": {
                "onboarded": True,
                "name": "bar"
            },
            "1234": {
                "onboarded": False,
                "name": "test"
            },
        }
        self.blink.get_ids()
        self.assertTrue("5678" in self.blink.network_ids)

    def test_multiple_onboarded_networks(self, mock_sess):
        """Check that we handle multiple networks appropriately."""
        self.blink.networks = {
            "0000": {
                "onboarded": False,
                "name": "foo"
            },
            "5678": {
                "onboarded": True,
                "name": "bar"
            },
            "1234": {
                "onboarded": True,
                "name": "test"
            },
        }
        self.blink.get_ids()
        self.assertTrue("0000" not in self.blink.network_ids)
        self.assertTrue("5678" in self.blink.network_ids)
        self.assertTrue("1234" in self.blink.network_ids)

    @mock.patch("blinkpy.blinkpy.time.time")
    def test_throttle(self, mock_time, mock_sess):
        """Check throttling functionality."""
        now = self.blink.refresh_rate + 1
        mock_time.return_value = now
        self.assertEqual(self.blink.last_refresh, None)
        self.assertEqual(self.blink.check_if_ok_to_update(), True)
        self.assertEqual(self.blink.last_refresh, None)
        with mock.patch("blinkpy.sync_module.BlinkSyncModule.refresh",
                        return_value=True):
            self.blink.refresh()

        self.assertEqual(self.blink.last_refresh, now)
        self.assertEqual(self.blink.check_if_ok_to_update(), False)
        self.assertEqual(self.blink.last_refresh, now)

    def test_sync_case_insensitive_dict(self, mock_sess):
        """Check that we can access sync modules ignoring case."""
        self.assertEqual(self.blink.sync["test"].name, "test")
        self.assertEqual(self.blink.sync["TEST"].name, "test")

    @mock.patch("blinkpy.api.request_login")
    def test_unexpected_login(self, mock_login, mock_sess):
        """Check that we appropriately handle unexpected login info."""
        mock_login.return_value = None
        self.assertFalse(self.blink.get_auth_token())

    @mock.patch("blinkpy.api.request_homescreen")
    def test_get_cameras(self, mock_home, mock_sess):
        """Check retrieval of camera information."""
        mock_home.return_value = {
            "cameras": [
                {
                    "name": "foo",
                    "network_id": 1234,
                    "id": 5678
                },
                {
                    "name": "bar",
                    "network_id": 1234,
                    "id": 5679
                },
                {
                    "name": "test",
                    "network_id": 4321,
                    "id": 0000
                },
            ]
        }
        result = self.blink.get_cameras()
        self.assertEqual(
            result,
            {
                "1234": [{
                    "name": "foo",
                    "id": 5678
                }, {
                    "name": "bar",
                    "id": 5679
                }],
                "4321": [{
                    "name": "test",
                    "id": 0000
                }],
            },
        )

    @mock.patch("blinkpy.api.request_homescreen")
    def test_get_cameras_failure(self, mock_home, mock_sess):
        """Check that on failure we initialize empty info and move on."""
        mock_home.return_value = {}
        result = self.blink.get_cameras()
        self.assertEqual(result, {})

    @mock.patch.object(LoginHandler, "send_auth_key")
    @mock.patch.object(Blink, "setup_post_verify")
    def test_startup_prompt(self, mock_send_key, mock_verify, mock_sess):
        """Test startup logic with command-line prompt."""
        mock_send_key.return_value = True
        mock_verify.return_value = True
        self.blink.no_prompt = False
        self.blink.key_required = True
        self.blink.available = True
        with mock.patch("builtins.input", return_value="1234"):
            self.blink.start()
        self.assertFalse(self.blink.key_required)

    def test_startup_no_prompt(self, mock_sess):
        """Test startup with no_prompt flag set."""
        self.blink.key_required = True
        self.blink.no_prompt = True
        self.blink.start()
        self.assertTrue(self.blink.key_required)
示例#17
0
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
示例#18
0
def _blink_startup_wrapper(entry):
    """Startup wrapper for blink."""
    blink = Blink(
        username=entry.data[CONF_USERNAME],
        password=entry.data[CONF_PASSWORD],
        motion_interval=DEFAULT_OFFSET,
        legacy_subdomain=False,
        no_prompt=True,
        device_id=DEVICE_ID,
    )
    blink.refresh_rate = entry.data[CONF_SCAN_INTERVAL]

    try:
        blink.login_response = entry.data["login_response"]
        blink.setup_params(entry.data["login_response"])
    except KeyError:
        blink.get_auth_token()

    blink.setup_params(entry.data["login_response"])
    blink.setup_post_verify()
    return blink
示例#19
0
 def __init__(
         self
 ):
     self.auth_file = AUTH_FILE
     self.blink = Blink()
示例#20
0
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')

blob_blink.upload_from_string(
   data=json.dumps(CREDS),
示例#21
0
 def setUp(self):
     """Initialize the blink module."""
     self.blink = Blink()
     self.blink.session = create_session()
     # pylint: disable=protected-access
     self.blink._auth_header = {}
 def test_initialization(self):
     """Verify we can initialize blink."""
     blink = Blink()
     self.assertEqual(blink.version, __version__)
 def setUp(self):
     """Initialize blink test object."""
     self.blink = Blink()
     self.blink.available = True
class TestBlinkSetup(unittest.TestCase):
    """Test the Blink class in blinkpy."""
    def setUp(self):
        """Initialize blink test object."""
        self.blink = Blink()
        self.blink.available = True

    def tearDown(self):
        """Cleanup blink test object."""
        self.blink = None

    def test_initialization(self):
        """Verify we can initialize blink."""
        blink = Blink()
        self.assertEqual(blink.version, __version__)

    def test_network_id_failure(self):
        """Check that with bad network data a setup error is raised."""
        self.blink.networks = None
        with self.assertRaises(BlinkSetupError):
            self.blink.setup_network_ids()

    def test_multiple_networks(self):
        """Check that we handle multiple networks appropriately."""
        self.blink.networks = {
            "0000": {
                "onboarded": False,
                "name": "foo"
            },
            "5678": {
                "onboarded": True,
                "name": "bar"
            },
            "1234": {
                "onboarded": False,
                "name": "test"
            },
        }
        self.blink.setup_network_ids()
        self.assertTrue("5678" in self.blink.network_ids)

    def test_multiple_onboarded_networks(self):
        """Check that we handle multiple networks appropriately."""
        self.blink.networks = {
            "0000": {
                "onboarded": False,
                "name": "foo"
            },
            "5678": {
                "onboarded": True,
                "name": "bar"
            },
            "1234": {
                "onboarded": True,
                "name": "test"
            },
        }
        self.blink.setup_network_ids()
        self.assertTrue("0000" not in self.blink.network_ids)
        self.assertTrue("5678" in self.blink.network_ids)
        self.assertTrue("1234" in self.blink.network_ids)

    @mock.patch("blinkpy.blinkpy.time.time")
    def test_throttle(self, mock_time):
        """Check throttling functionality."""
        now = self.blink.refresh_rate + 1
        mock_time.return_value = now
        self.assertEqual(self.blink.last_refresh, None)
        self.assertEqual(self.blink.check_if_ok_to_update(), True)
        self.assertEqual(self.blink.last_refresh, None)
        with mock.patch("blinkpy.sync_module.BlinkSyncModule.refresh",
                        return_value=True), mock.patch(
                            "blinkpy.blinkpy.Blink.get_homescreen",
                            return_value=True):
            self.blink.refresh(force=True)

        self.assertEqual(self.blink.last_refresh, now)
        self.assertEqual(self.blink.check_if_ok_to_update(), False)
        self.assertEqual(self.blink.last_refresh, now)

    def test_sync_case_insensitive_dict(self):
        """Check that we can access sync modules ignoring case."""
        self.blink.sync["test"] = 1234
        self.assertEqual(self.blink.sync["test"], 1234)
        self.assertEqual(self.blink.sync["TEST"], 1234)
        self.assertEqual(self.blink.sync["tEsT"], 1234)

    @mock.patch("blinkpy.api.request_camera_usage")
    @mock.patch("blinkpy.api.request_homescreen")
    def test_setup_cameras(self, mock_home, mock_req):
        """Check retrieval of camera information."""
        mock_home.return_value = {}
        mock_req.return_value = {
            "networks": [
                {
                    "network_id":
                    1234,
                    "cameras": [
                        {
                            "id": 5678,
                            "name": "foo"
                        },
                        {
                            "id": 5679,
                            "name": "bar"
                        },
                    ],
                },
                {
                    "network_id": 4321,
                    "cameras": [{
                        "id": 0000,
                        "name": "test"
                    }]
                },
            ]
        }
        result = self.blink.setup_camera_list()
        self.assertEqual(
            result,
            {
                "1234": [{
                    "name": "foo",
                    "id": 5678
                }, {
                    "name": "bar",
                    "id": 5679
                }],
                "4321": [{
                    "name": "test",
                    "id": 0000
                }],
            },
        )

    @mock.patch("blinkpy.api.request_camera_usage")
    def test_setup_cameras_failure(self, mock_home):
        """Check that on failure we raise a setup error."""
        mock_home.return_value = {}
        with self.assertRaises(BlinkSetupError):
            self.blink.setup_camera_list()
        mock_home.return_value = None
        with self.assertRaises(BlinkSetupError):
            self.blink.setup_camera_list()

    def test_setup_urls(self):
        """Check setup of URLS."""
        self.blink.auth.region_id = "test"
        self.blink.setup_urls()
        self.assertEqual(self.blink.urls.subdomain, "rest-test")

    def test_setup_urls_failure(self):
        """Check that on failure we raise a setup error."""
        self.blink.auth.region_id = None
        with self.assertRaises(BlinkSetupError):
            self.blink.setup_urls()

    @mock.patch("blinkpy.api.request_networks")
    def test_setup_networks(self, mock_networks):
        """Check setup of networks."""
        mock_networks.return_value = {"summary": "foobar"}
        self.blink.setup_networks()
        self.assertEqual(self.blink.networks, "foobar")

    @mock.patch("blinkpy.api.request_networks")
    def test_setup_networks_failure(self, mock_networks):
        """Check that on failure we raise a setup error."""
        mock_networks.return_value = {}
        with self.assertRaises(BlinkSetupError):
            self.blink.setup_networks()
        mock_networks.return_value = None
        with self.assertRaises(BlinkSetupError):
            self.blink.setup_networks()

    @mock.patch("blinkpy.blinkpy.Auth.send_auth_key")
    def test_setup_prompt_2fa(self, mock_key):
        """Test setup with 2fa prompt."""
        self.blink.auth.data["username"] = "******"
        self.blink.key_required = True
        mock_key.return_value = True
        with mock.patch("builtins.input", return_value="foo"):
            self.blink.setup_prompt_2fa()
        self.assertFalse(self.blink.key_required)
        mock_key.return_value = False
        with mock.patch("builtins.input", return_value="foo"):
            self.blink.setup_prompt_2fa()
        self.assertTrue(self.blink.key_required)

    @mock.patch("blinkpy.blinkpy.Blink.setup_camera_list")
    @mock.patch("blinkpy.api.request_networks")
    @mock.patch("blinkpy.blinkpy.Blink.setup_owls")
    def test_setup_post_verify(self, mock_owl, mock_networks, mock_camera):
        """Test setup after verification."""
        self.blink.available = False
        self.blink.key_required = True
        mock_owl.return_value = True
        mock_networks.return_value = {
            "summary": {
                "foo": {
                    "onboarded": False,
                    "name": "bar"
                }
            }
        }
        mock_camera.return_value = []
        self.assertTrue(self.blink.setup_post_verify())
        self.assertTrue(self.blink.available)
        self.assertFalse(self.blink.key_required)

    @mock.patch("blinkpy.api.request_networks")
    def test_setup_post_verify_failure(self, mock_networks):
        """Test failed setup after verification."""
        self.blink.available = False
        mock_networks.return_value = {}
        self.assertFalse(self.blink.setup_post_verify())
        self.assertFalse(self.blink.available)

    def test_merge_cameras(self):
        """Test merging of cameras."""
        self.blink.sync = {
            "foo": MockSync({
                "test": 123,
                "foo": "bar"
            }),
            "bar": MockSync({
                "fizz": "buzz",
                "bar": "foo"
            }),
        }
        combined = self.blink.merge_cameras()
        self.assertEqual(combined["test"], 123)
        self.assertEqual(combined["foo"], "bar")
        self.assertEqual(combined["fizz"], "buzz")
        self.assertEqual(combined["bar"], "foo")

    @mock.patch("blinkpy.blinkpy.BlinkOwl.start")
    def test_initialize_blink_minis(self, mock_start):
        """Test blink mini initialization."""
        mock_start.return_value = True
        self.blink.homescreen = {
            "owls": [
                {
                    "enabled": False,
                    "id": 1,
                    "name": "foo",
                    "network_id": 2,
                    "onboarded": True,
                    "status": "online",
                    "thumbnail": "/foo/bar",
                    "serial": "1234",
                },
                {
                    "enabled": True,
                    "id": 3,
                    "name": "bar",
                    "network_id": 4,
                    "onboarded": True,
                    "status": "online",
                    "thumbnail": "/foo/bar",
                    "serial": "abcd",
                },
            ]
        }
        self.blink.sync = {}
        self.blink.setup_owls()
        self.assertEqual(self.blink.sync["foo"].__class__, BlinkOwl)
        self.assertEqual(self.blink.sync["bar"].__class__, BlinkOwl)
        self.assertEqual(self.blink.sync["foo"].arm, False)
        self.assertEqual(self.blink.sync["bar"].arm, True)
        self.assertEqual(self.blink.sync["foo"].name, "foo")
        self.assertEqual(self.blink.sync["bar"].name, "bar")

    def test_blink_mini_cameras_returned(self):
        """Test that blink mini cameras are found if attached to sync module."""
        self.blink.network_ids = ["1234"]
        self.blink.homescreen = {
            "owls": [{
                "id": 1,
                "name": "foo",
                "network_id": 1234,
                "onboarded": True,
                "enabled": True,
                "status": "online",
                "thumbnail": "/foo/bar",
                "serial": "abc123",
            }]
        }
        result = self.blink.setup_owls()
        self.assertEqual(self.blink.network_ids, ["1234"])
        self.assertEqual(result, [{
            "1234": {
                "name": "foo",
                "id": "1234",
                "type": "mini"
            }
        }])

        self.blink.no_owls = True
        self.blink.network_ids = []
        self.blink.get_homescreen()
        result = self.blink.setup_owls()
        self.assertEqual(self.blink.network_ids, [])
        self.assertEqual(result, [])

    @mock.patch("blinkpy.api.request_camera_usage")
    def test_blink_mini_attached_to_sync(self, mock_usage):
        """Test that blink mini cameras are properly attached to sync module."""
        self.blink.network_ids = ["1234"]
        self.blink.homescreen = {
            "owls": [{
                "id": 1,
                "name": "foo",
                "network_id": 1234,
                "onboarded": True,
                "enabled": True,
                "status": "online",
                "thumbnail": "/foo/bar",
                "serial": "abc123",
            }]
        }
        mock_usage.return_value = {
            "networks": [{
                "cameras": [],
                "network_id": 1234
            }]
        }
        result = self.blink.setup_camera_list()
        self.assertEqual(
            result, {"1234": [{
                "name": "foo",
                "id": "1234",
                "type": "mini"
            }]})
示例#25
0
import os
import io
import os.path
import atexit

from flask import Flask, request, send_file
from flask_restful import Resource, Api, reqparse

from blinkpy.blinkpy import Blink
from blinkpy.auth import Auth
from blinkpy.helpers.util import json_load

version='0.1.4'
blink=Blink()
blinkStatus = 0
statusMessage = ''

blinkCredentials = os.environ.get("BLINK_CREDENTIAL_FILE")
blinkDownloadDir=os.environ.get("BLINK_DOWNLOAD_DIR")

if not blinkCredentials:
    blinkCredentials = "dwmdahoam.blink.credentials"
if not blinkDownloadDir:
    blinkDownloadDir = "."

def create_app():
    """ This function creates our flask app """
    flask_app = Flask(__name__)
    flask_app.logger.disabled = True

    flask_app.app_context().push()
示例#26
0
def start():
    """Startup blink app."""
    blink = Blink()
    blink.auth = Auth(json_load(CREDFILE))
    blink.start()
    return blink