Skip to content

Commit

Permalink
Merge pull request #11 from jaraco/feature/simple-state
Browse files Browse the repository at this point in the history
Simply store the cookies to user data dir
  • Loading branch information
jaraco authored Dec 4, 2022
2 parents e1c9011 + 1cd109e commit a5af48f
Show file tree
Hide file tree
Showing 11 changed files with 72 additions and 134 deletions.
12 changes: 12 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
v3.0.0
======

Project no longer exposes a "cache" (or related options for cache-path).
Instead, state from cookies from the API is stored in an "app data"
path (platform-specific).

It's no longer possible to disable the "cache". Cookies are persisted
unconditionally.

As a result, a UUID is persisted only if an API login succeeded.

v2.0.0
======

Expand Down
3 changes: 2 additions & 1 deletion conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ def instance_client(request):
return

request.instance.client = jaraco.abode.Client(
username='foobar', password='deadbeef', disable_cache=True
username='foobar',
password='deadbeef',
)


Expand Down
22 changes: 0 additions & 22 deletions jaraco/abode/cache.py

This file was deleted.

9 changes: 0 additions & 9 deletions jaraco/abode/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import jaraco.abode
from . import Client
from .helpers import urls
from .helpers import constants as CONST
from .helpers import timeline as TIMELINE

_LOGGER = logging.getLogger('abodecl')
Expand Down Expand Up @@ -75,13 +74,6 @@ def build_parser():

parser.add_argument('--mfa', help='Multifactor authentication code')

parser.add_argument(
'--cache',
metavar='pickle_file',
help='Create/update/use a pickle cache for the username and password.',
default=CONST.CACHE_PATH,
)

parser.add_argument(
'--mode',
help='Output current alarm mode',
Expand Down Expand Up @@ -222,7 +214,6 @@ def _create_client_instance(args):
username=args.username,
password=args.password,
get_devices=args.mfa is None,
cache_path=args.cache,
)


Expand Down
63 changes: 15 additions & 48 deletions jaraco/abode/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
"""

import logging
import os
import uuid

from more_itertools import always_iterable
from requests_toolbelt import sessions
from requests.exceptions import RequestException
from jaraco.net.http import cookies
from jaraco.functools import retry

import jaraco
from .automation import Automation
Expand All @@ -18,15 +19,23 @@
from .helpers import urls
from .helpers import constants as CONST
from .helpers import errors as ERROR
from . import collections as COLLECTIONS
from . import cache as CACHE
from .devices.base import Device
from . import settings
from . import config


_LOGGER = logging.getLogger(__name__)


@retry(
retries=1,
cleanup=lambda: config.paths.user_data.joinpath('cookies.json').unlink(),
trap=Exception,
)
def _cookies():
return cookies.ShelvedCookieJar.create(config.paths.user_data)


class Client:
"""Client to an Abode system."""

Expand All @@ -37,16 +46,12 @@ def __init__(
auto_login=False,
get_devices=False,
get_automations=False,
cache_path=CONST.CACHE_PATH,
disable_cache=False,
):
"""Init Abode object."""
self._session = None
self._token = None
self._panel = None
self._user = None
self._cache_path = cache_path
self._disable_cache = disable_cache
self._username = username
self._password = password

Expand All @@ -58,22 +63,8 @@ def __init__(

self._automations = None

# Create a requests session to persist the cookies
self._session = sessions.BaseUrlSession(urls.BASE)

# Create a new cache template
self._cache = {
'uuid': str(uuid.uuid1()),
}

# Load and merge an existing cache
if not disable_cache:
self._load_cache()

# Load persisted cookies (which contains the UUID and the session ID)
# if available
if self._cache.get('cookies'):
self._session.cookies = self._cache['cookies']
self._session.cookies = _cookies()

if auto_login:
self.login()
Expand Down Expand Up @@ -101,7 +92,7 @@ def login(self, username=None, password=None, mfa_code=None): # noqa: C901
login_data = {
'id': username,
'password': password,
'uuid': self._cache['uuid'],
'uuid': self._session.cookies.get('uuid') or str(uuid.uuid1()),
}

if mfa_code is not None:
Expand All @@ -119,11 +110,6 @@ def login(self, username=None, password=None, mfa_code=None): # noqa: C901

raise AuthenticationException(ERROR.UNKNOWN_MFA_TYPE)

# Persist cookies (which contains the UUID and the session ID) to disk
if self._session.cookies.get_dict():
self._cache['cookies'] = self._session.cookies
self._save_cache()

oauth_response = self._session.get(urls.OAUTH_TOKEN)
AuthenticationException.raise_for(oauth_response)
oauth_response_object = oauth_response.json()
Expand Down Expand Up @@ -332,29 +318,10 @@ def events(self):
@property
def uuid(self):
"""Get the UUID."""
return self._cache['uuid']
return self._session.cookies['uuid']

def _get_session(self):
# Perform a generic update so we know we're logged in
self.send_request("get", urls.PANEL)

return self._session

def _load_cache(self):
"""Load existing cache and merge for updating if required."""
if not self._disable_cache and os.path.exists(self._cache_path):
_LOGGER.debug("Cache found at: %s", self._cache_path)
loaded_cache = CACHE.load_cache(self._cache_path)

if loaded_cache:
COLLECTIONS.update(self._cache, loaded_cache)
else:
_LOGGER.debug("Removing invalid cache file: %s", self._cache_path)
os.remove(self._cache_path)

self._save_cache()

def _save_cache(self):
"""Trigger a cache save."""
if not self._disable_cache:
CACHE.save_cache(self._cache, self._cache_path)
11 changes: 0 additions & 11 deletions jaraco/abode/collections.py

This file was deleted.

4 changes: 4 additions & 0 deletions jaraco/abode/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import app_paths


paths = app_paths.AppPaths.get_paths(appname='Abode', appauthor=False)
2 changes: 0 additions & 2 deletions jaraco/abode/helpers/constants.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
CACHE_PATH = './abode.pickle'

# NOTIFICATION CONSTANTS
SOCKETIO_URL = 'wss://my.goabode.com/socket.io/'

Expand Down
4 changes: 3 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@ install_requires =
jaraco.collections
jaraco.context
jaraco.classes
jaraco.net >= 9
more_itertools
importlib_resources
bx_py_utils
app_paths

[options.packages.find]
exclude =
Expand Down Expand Up @@ -58,7 +60,7 @@ testing =
pytest-enabler >= 1.3

# local
requests_mock>=1.3.0
requests_mock
types-requests
jaraco.collections >= 3.6

Expand Down
Loading

0 comments on commit a5af48f

Please sign in to comment.