Skip to content

Commit

Permalink
Add cache for instance users (#52)
Browse files Browse the repository at this point in the history
  • Loading branch information
RemiRigal authored Jul 19, 2022
1 parent 30dceaa commit 8108dd8
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 7 deletions.
20 changes: 14 additions & 6 deletions plex_auto_languages/plex_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,21 @@ def start_alert_listener(self, error_callback: Callable):
self._alert_listener.start()

def get_instance_users(self):
users = self.cache.get_instance_users()
if users is not None:
return users
users = []
for user in self._plex.myPlexAccount().users():
server_identifiers = [share.machineIdentifier for share in user.servers]
if self.unique_id in server_identifiers:
user.name = user.title
users.append(user)
return users
try:
for user in self._plex.myPlexAccount().users():
server_identifiers = [share.machineIdentifier for share in user.servers]
if self.unique_id in server_identifiers:
user.name = user.title
users.append(user)
self.cache.set_instance_users(users)
return users
except BadRequest:
logger.warning("Unable to retrieve the users of the account, falling back to cache")
return self.cache.get_instance_users(check_validity=False)

def get_all_user_ids(self):
return [self.user_id] + [user.id for user in self.get_instance_users()]
Expand Down
15 changes: 14 additions & 1 deletion plex_auto_languages/plex_server_cache.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from __future__ import annotations
import os
import json
from datetime import datetime
import copy
from typing import TYPE_CHECKING
from datetime import datetime, timedelta
from dateutil.parser import isoparse

from plex_auto_languages.utils.logger import get_logger
Expand Down Expand Up @@ -30,6 +31,9 @@ def __init__(self, plex: PlexServer):
self.newly_added = {} # episode_id: added_at
self.newly_updated = {} # episode_id: updated_at
self.recent_activities = {} # (user_id, item_id): timestamp
# Users cache
self._instance_users = []
self._instance_users_valid_until = datetime.fromtimestamp(0)
# Library cache
self.episode_parts = {}
# Initialization
Expand Down Expand Up @@ -75,6 +79,15 @@ def refresh_library_cache(self):
self._is_refreshing = False
return added, updated

def get_instance_users(self, check_validity=True):
if check_validity and datetime.now() > self._instance_users_valid_until:
return None
return copy.deepcopy(self._instance_users)

def set_instance_users(self, instance_users):
self._instance_users = copy.deepcopy(instance_users)
self._instance_users_valid_until = datetime.now() + timedelta(hours=12)

def _get_cache_file_path(self):
data_dir = self._plex.config.get("data_dir")
cache_dir = os.path.join(data_dir, "cache")
Expand Down
10 changes: 10 additions & 0 deletions tests/test_plex_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from datetime import datetime
from unittest.mock import patch
from plexapi.video import Episode, Show
from plexapi.exceptions import BadRequest
from plexapi.server import PlexServer as BasePlexServer

from plex_auto_languages.track_changes import TrackChanges, NewOrUpdatedTrackChanges
Expand Down Expand Up @@ -98,6 +99,15 @@ def test_get_logged_user(plex):
assert user is None


def test_get_instance_users(plex):
with patch.object(BasePlexServer, "myPlexAccount", side_effect=BadRequest()):
assert plex.get_instance_users() == []
assert len(plex.get_instance_users()) == 1
assert plex.cache._instance_users_valid_until > datetime.fromtimestamp(0)
with patch.object(BasePlexServer, "myPlexAccount", side_effect=BadRequest()):
assert len(plex.get_instance_users()) == 1


def test_get_user_by_id(plex):
user = plex.get_user_by_id(plex.user_id)
assert user.id == plex.user_id
Expand Down
8 changes: 8 additions & 0 deletions tests/test_plex_server_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,14 @@ def test_load_save():
assert old_episode_parts == cache.episode_parts


def test_instance_users(plex):
assert plex.cache.get_instance_users() is None
assert plex.cache.get_instance_users(check_validity=False) == []

plex.cache.set_instance_users(["user1", "user2"])
assert len(plex.cache.get_instance_users()) == 2


def test_refresh(plex):
keys = list(plex.cache.episode_parts.keys())
assert len(keys) > 1
Expand Down

0 comments on commit 8108dd8

Please sign in to comment.