Add additional histroy methods

This commit is contained in:
zSeriesGuy 2019-11-16 16:35:20 -05:00
parent 481e55bbe4
commit d9820775a6
4 changed files with 167 additions and 1 deletions

View file

@ -294,6 +294,13 @@ class Library(PlexObject):
part += urlencode(kwargs)
return self._server.query(part, method=self._server._session.post)
def history(self):
""" Get Play History for all library Sections for the owner. """
hist = []
for section in self.sections():
hist.extend(section.history())
return hist
class LibrarySection(PlexObject):
""" Base class for a single library section.
@ -633,6 +640,10 @@ class LibrarySection(PlexObject):
return myplex.sync(client=client, clientId=clientId, sync_item=sync_item)
def history(self):
""" Get Play History for this library Section for the owner. """
return self._server.history(librarySectionID=self.key, accountID=1)
class MovieSection(LibrarySection):
""" Represents a :class:`~plexapi.library.LibrarySection` section containing movies.

View file

@ -600,6 +600,15 @@ class MyPlexAccount(PlexObject):
raise BadRequest('(%s) %s %s; %s' % (response.status_code, codename, response.url, errtext))
return response.json()['token']
def history(self):
""" Get Play History for all library sections on all servers for the owner. """
servers = [x for x in self.resources() if x.provides == 'server' and x.owned]
hist = []
for server in servers:
conn = server.connect()
hist.extend(conn.history(accountID=1))
return hist
class MyPlexUser(PlexObject):
""" This object represents non-signed in users such as friends and linked
@ -654,6 +663,8 @@ class MyPlexUser(PlexObject):
self.title = data.attrib.get('title', '')
self.username = data.attrib.get('username', '')
self.servers = self.findItems(data, MyPlexServerShare)
for server in self.servers:
server.accountID = self.id
def get_token(self, machineIdentifier):
try:
@ -663,6 +674,25 @@ class MyPlexUser(PlexObject):
except Exception:
log.exception('Failed to get access token for %s' % self.title)
def server(self, name):
""" Returns the :class:`~plexapi.myplex.MyPlexServerShare` that matches the name specified.
Parameters:
name (str): Name of the server to return.
"""
for server in self.servers:
if name.lower() == server.name.lower():
return server
raise NotFound('Unable to find server %s' % name)
def history(self):
""" Get all Play History for a user in all shared servers. """
hist = []
for server in self.servers:
hist.extend(server.history())
return hist
class Section(PlexObject):
""" This refers to a shared section. The raw xml for the data presented here
@ -689,6 +719,11 @@ class Section(PlexObject):
self.type = data.attrib.get('type')
self.shared = utils.cast(bool, data.attrib.get('shared'))
def history(self):
""" Get all Play History for a user for this section in this shared server. """
server = self._server._server.resource(self._server.name).connect()
return server.history(accountID=self._server.accountID, librarySectionID=self.sectionKey)
class MyPlexServerShare(PlexObject):
""" Represents a single user's server reference. Used for library sharing.
@ -711,6 +746,7 @@ class MyPlexServerShare(PlexObject):
""" Load attribute values from Plex XML response. """
self._data = data
self.id = utils.cast(int, data.attrib.get('id'))
self.accountID = utils.cast(int, data.attrib.get('accountID'))
self.serverId = utils.cast(int, data.attrib.get('serverId'))
self.machineIdentifier = data.attrib.get('machineIdentifier')
self.name = data.attrib.get('name')
@ -720,7 +756,21 @@ class MyPlexServerShare(PlexObject):
self.owned = utils.cast(bool, data.attrib.get('owned'))
self.pending = utils.cast(bool, data.attrib.get('pending'))
def section(self, name):
""" Returns the :class:`~plexapi.myplex.Section` that matches the name specified.
Parameters:
name (str): Name of the section to return.
"""
for section in self.sections():
if name.lower() == section.title.lower():
return section
raise NotFound('Unable to find section %s' % name)
def sections(self):
""" Returns a list of all :class:`~plexapi.myplex.Section` objects shared with this user.
"""
url = MyPlexAccount.FRIENDSERVERS.format(machineId=self.machineIdentifier, serverId=self.id)
data = self._server.query(url)
sections = []
@ -731,6 +781,11 @@ class MyPlexServerShare(PlexObject):
return sections
def history(self):
""" Get all Play History for a user in this shared server. """
server = self._server.resource(self.name).connect()
return server.history(accountID=self.accountID)
class MyPlexResource(PlexObject):
""" This object represents resources connected to your Plex server that can provide

View file

@ -322,7 +322,7 @@ class PlexServer(PlexObject):
# figure out what method this is..
return self.query(part, method=self._session.put)
def history(self, maxresults=9999999, mindate=None, ratingKey=None):
def history(self, maxresults=9999999, mindate=None, ratingKey=None, accountID=None, librarySectionID=None):
""" Returns a list of media items from watched history. If there are many results, they will
be fetched from the server in batches of X_PLEX_CONTAINER_SIZE amounts. If you're only
looking for the first <num> results, it would be wise to set the maxresults option to that
@ -333,11 +333,17 @@ class PlexServer(PlexObject):
mindate (datetime): Min datetime to return results from. This really helps speed
up the result listing. For example: datetime.now() - timedelta(days=7)
ratingKey (int/str) Request history for a specific ratingKey item.
accountID (int/str) Request history for a specific account ID.
librarySectionID (int/str) Request history for a specific library section ID.
"""
results, subresults = [], '_init'
args = {'sort': 'viewedAt:desc'}
if ratingKey:
args['metadataItemID'] = ratingKey
if accountID:
args['accountID'] = accountID
if librarySectionID:
args['librarySectionID'] = librarySectionID
if mindate:
args['viewedAt>'] = int(mindate.timestamp())
args['X-Plex-Container-Start'] = 0

94
tests/test_history.py Normal file
View file

@ -0,0 +1,94 @@
# -*- coding: utf-8 -*-
import pytest
from datetime import datetime
from plexapi.exceptions import BadRequest, NotFound
from . import conftest as utils
def test_history_Movie(movie):
movie.markWatched()
history = movie.history()
assert len(history)
movie.markUnwatched()
def test_history_Show(show):
show.markWatched()
history = show.history()
assert len(history)
show.markUnwatched()
def test_history_Season(show):
season = show.season('Season 1')
season.markWatched()
history = season.history()
assert len(history)
season.markUnwatched()
def test_history_Episode(episode):
episode.markWatched()
history = episode.history()
assert len(history)
episode.markUnwatched()
def test_history_Artist(artist):
history = artist.history()
def test_history_Album(album):
history = album.history()
def test_history_Track(track):
history = track.history()
def test_history_MyAccount(account, movie, show):
movie.markWatched()
show.markWatched()
history = account.history()
assert len(history)
movie.markUnwatched()
show.markUnwatched()
def test_history_MyLibrary(plex, movie, show):
movie.markWatched()
show.markWatched()
history = plex.library.history()
assert len(history)
movie.markUnwatched()
show.markUnwatched()
def test_history_MySection(plex, movie):
movie.markWatched()
history = plex.library.section('Movies').history()
assert len(history)
movie.markUnwatched()
def test_history_MyServer(plex, movie):
movie.markWatched()
history = plex.history()
assert len(history)
movie.markUnwatched()
def test_history_User(account, shared_username):
user = account.user(shared_username)
history = user.history()
def test_history_UserServer(account, shared_username, plex):
userSharedServer = account.user(shared_username).server(plex.friendlyName)
history = userSharedServer.history()
def test_history_UserSection(account, shared_username, plex):
userSharedServerSection = account.user(shared_username).server(plex.friendlyName).section('Movies')
history = userSharedServerSection.history()