Passed
Push — develop ( 3c901c...de3ad7 )
by Dean
02:43
created

PlexPlaylistHandler   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Test Coverage

Coverage 82.5%
Metric Value
dl 0
loc 72
ccs 33
cts 40
cp 0.825
rs 10
wmc 14

4 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 12 2
C build_key() 0 34 7
A parse() 0 13 4
A __init__() 0 5 1
1 1
from plugin.sync.core.playlist.mapper.handlers.base import PlaylistHandler
2
3 1
from plex.objects.library.metadata import Movie, Show, Season, Episode
4 1
import logging
5
6 1
log = logging.getLogger(__name__)
7
8
9 1
class PlexPlaylistHandler(PlaylistHandler):
10 1
    def __init__(self, task):
11 1
        super(PlexPlaylistHandler, self).__init__(task)
12
13 1
        self.playlist = None
14 1
        self.items = None
15
16 1
    def load(self, playlist, items=None):
17 1
        if items is None:
18
            # Fetch playlist items
19 1
            items = playlist.items()
20
21 1
        self.playlist = playlist
22
23 1
        self.items = {}
24 1
        self.table = {}
25
26
        # Parse items into the `items` and `table` attribute
27 1
        self.parse(items)
28
29
    #
30
    # Item parser
31
    #
32
33 1
    def build_key(self, item):
34 1
        i_type = type(item)
35
36 1
        if hasattr(item, 'show'):
37 1
            root = item.show
38
        else:
39 1
            root = item
40
41
        # Retrieve guid for `item`
42 1
        guids = list(self.task.map.by_key(root.rating_key))
43
44 1
        if len(guids) < 1:
45
            log.warn('Unable to find any guids for item #%s (guids: %r)', root.rating_key, guids)
46
            return None
47
48 1
        if len(guids) > 1:
49
            log.info('Multiple guids returned for %r: %r', item, guids)
50
51 1
        guid = guids[0]
52
53
        # Try map `guid` to a primary agent
54 1
        guid = self.task.state.trakt.table(item).get(guid, guid)
55
56
        # Build key for `item`
57 1
        if i_type in [Movie, Show]:
58 1
            return [guid]
59
60 1
        if i_type is Season:
61
            return [guid, item.index]
62
63 1
        if i_type is Episode:
64 1
            return [guid, item.season.index, item.index]
65
66
        raise ValueError('Unknown item type: %r' % i_type)
67
68 1
    def parse(self, items):
69 1
        for index, item in enumerate(items):
70 1
            keys = self.build_key(item)
71
72 1
            if keys is None:
73
                continue
74
75
            # Update `items`
76 1
            self.items[tuple(keys)] = (index, item)
77
78
            # Update `table`
79 1
            if not self.path_set(self.table, keys, (index, item)):
80
                log.info('Unable to update table (keys: %r)', keys)
81