示例#1
0
    def init_plex():
        # Ensure client identifier has been generated
        if not Dict['plex.client.identifier']:
            # Generate identifier
            Dict['plex.client.identifier'] = uuid.uuid4()

        # plex.py
        Plex.configuration.defaults.authentication(
            os.environ.get('PLEXTOKEN')
        )

        Plex.configuration.defaults.client(
            identifier=Dict['plex.client.identifier'],

            product='trakt (for Plex)',
            version=PLUGIN_VERSION
        )

        # plex.activity.py
        path = os.path.join(LOG_HANDLER.baseFilename, '..', '..', 'Plex Media Server.log')
        path = os.path.abspath(path)

        Activity['logging'].add_hint(path)

        # plex.metadata.py
        Metadata.configure(
            cache=CacheManager.get(
                'plex.metadata',
                serializer='pickle:///?protocol=2'
            ),
            client=Plex.client
        )
示例#2
0
    def init_plex():
        # Ensure client identifier has been generated
        if not Dict['plex.client.identifier']:
            # Generate identifier
            Dict['plex.client.identifier'] = uuid.uuid4()

        # Retrieve current client identifier
        client_id = Dict['plex.client.identifier']

        if isinstance(client_id, uuid.UUID):
            client_id = str(client_id)

        # plex.py
        Plex.configuration.defaults.authentication(
            os.environ.get('PLEXTOKEN')
        )

        Plex.configuration.defaults.client(
            identifier=client_id,

            product='trakt (for Plex)',
            version=PLUGIN_VERSION
        )

        # plex.activity.py
        path = os.path.join(LOG_HANDLER.baseFilename, '..', '..', 'Plex Media Server.log')
        path = os.path.abspath(path)

        Activity['logging'].add_hint(path)

        # plex.metadata.py
        Metadata.configure(
            client=Plex.client
        )
示例#3
0
    def init_plex():
        # Ensure client identifier has been generated
        if not Dict['plex.client.identifier']:
            # Generate identifier
            Dict['plex.client.identifier'] = uuid.uuid4()

        # plex.py
        Plex.configuration.defaults.authentication(
            os.environ.get('PLEXTOKEN')
        )

        Plex.configuration.defaults.client(
            identifier=Dict['plex.client.identifier'],

            product='trakt (for Plex)',
            version=PLUGIN_VERSION
        )

        # plex.activity.py
        path = os.path.join(LOG_HANDLER.baseFilename, '..', '..', 'Plex Media Server.log')
        path = os.path.abspath(path)

        Activity['logging'].add_hint(path)

        # plex.metadata.py
        Metadata.configure(
            cache=CacheManager.get(
                'plex.metadata',
                serializer='pickle:///?protocol=2'
            ),
            client=Plex.client
        )
示例#4
0
    def init_plex():
        # Ensure client identifier has been generated
        if not Dict['plex.client.identifier']:
            # Generate identifier
            Dict['plex.client.identifier'] = uuid.uuid4()

        # Retrieve current client identifier
        client_id = Dict['plex.client.identifier']

        if isinstance(client_id, uuid.UUID):
            client_id = str(client_id)

        # plex.py
        Plex.configuration.defaults.authentication(os.environ.get('PLEXTOKEN'))

        Plex.configuration.defaults.client(identifier=client_id,
                                           product='trakt (for Plex)',
                                           version=PLUGIN_VERSION)

        # plex.activity.py
        path = os.path.join(LOG_HANDLER.baseFilename, '..', '..',
                            'Plex Media Server.log')
        path = os.path.abspath(path)

        Activity['logging'].add_hint(path)

        # plex.metadata.py
        Metadata.configure(client=Plex.client)
示例#5
0
 def get_metadata(rating_key):
     # Retrieve metadata for `rating_key`
     try:
         metadata = Metadata.get(rating_key)
     except NotImplementedError, e:
         log.debug('%r, ignoring session', e.message)
         return None, None
    def create_session(self, session_key, state):
        """
        :type session_key: str
        :type state: str

        :rtype: WatchSession or None
        """

        log.debug('Creating a WatchSession for the current media')

        item = Plex['status'].sessions().get(session_key)
        if not item:
            log.warn('Unable to find session with key "%s"', session_key)
            return None

        # Metadata
        metadata = Metadata.get(item.rating_key)

        # Guid
        guid = Guid.parse(metadata.guid) if metadata else None

        # Create WatchSession
        ws = WatchSession.from_session(item.session, metadata, guid, item.rating_key, state)
        ws.skip = not metadata

        # Fetch client by `machineIdentifier`
        ws.client = Plex.clients().get(item.session.player.machine_identifier)

        ws.save()

        log.debug('created session: %s', ws)
        return ws
示例#7
0
 def get_metadata(rating_key):
     # Retrieve metadata for `rating_key`
     try:
         metadata = Metadata.get(rating_key)
     except NotImplementedError, e:
         log.debug('%r, ignoring session', e.message)
         return None, None
示例#8
0
    def build_request(cls, session, part=None, rating_key=None, view_offset=None):
        # Retrieve metadata for session
        if part is None:
            part = session.part

        if rating_key is None:
            rating_key = session.rating_key

        # Retrieve metadata
        metadata = Metadata.get(rating_key)

        # Validate metadata
        if not metadata:
            log.warn('Unable to retrieve metadata for rating_key %r', rating_key)
            return None

        if metadata.type not in ['movie', 'episode']:
            log.info('Ignoring session with type %r for rating_key %r', metadata.type, rating_key)
            return None

        # Apply library/section filter
        if not Filters.is_valid_metadata_section(metadata):
            log.info('Ignoring session in filtered section: %r', metadata.section.title)
            return None

        # Parse guid
        guid = Guid.parse(metadata.guid, strict=True)

        if not guid or not guid.valid:
            log_unsupported_guid(log, guid)
            return None

        # Build request from guid/metadata
        if type(metadata) is Movie:
            result = cls.build_movie(metadata, guid, part)
        elif type(metadata) is Episode:
            result = cls.build_episode(metadata, guid, part)
        else:
            log.warn('Unknown metadata type: %r', type(metadata))
            return None

        if not result:
            log.info('Unable to build request for session: %r', session)
            return None

        # Retrieve media progress
        if view_offset is not None:
            # Calculate progress from `view_offset` parameter
            progress = UpdateSession.get_progress(
                metadata.duration, view_offset,
                part, session.part_count, session.part_duration
            )
        else:
            # Use session progress
            progress = session.progress

        # Merge progress into request
        return merge(result, {
            'progress': progress
        })
    def create_session(self, info):
        if not info.get('ratingKey'):
            log.warn('Invalid ratingKey provided from activity info')
            return None

        # Metadata
        metadata = Metadata.get(info['ratingKey'])

        # Guid
        guid = Guid.parse(metadata.guid) if metadata else None

        ws = WatchSession.from_info(info, metadata, guid, info['ratingKey'])
        ws.skip = not metadata

        # Fetch client by `machineIdentifier`
        ws.client = Plex.clients().get(info['machineIdentifier'])

        if not ws.client:
            # Create dummy client from `info`
            ws.client = Client(Plex.client, 'clients')
            ws.client.name = info.get('client', None)
            ws.client.machine_identifier = info.get('machineIdentifier', None)

            ws.client.address = info.get('address', None)
            ws.client.port = info.get('port', None)

        # Create dummy user from `info`
        ws.user = User(Plex.client, 'accounts')
        ws.user.id = info['user_id']
        ws.user.title = info['user_name']

        ws.save()

        log.debug('created session: %s', ws)
        return ws
示例#10
0
    def init_plex():
        # plex.py
        Plex.configuration.defaults.authentication(
            os.environ.get('PLEXTOKEN')
        )

        # plex.activity.py
        path = os.path.join(Core.log.handlers[1].baseFilename, '..', '..', 'Plex Media Server.log')
        path = os.path.abspath(path)

        Activity['logging'].add_hint(path)

        # plex.metadata.py
        Metadata.configure(
            cache=CacheManager.get('metadata'),
            client=Plex.client
        )
示例#11
0
def get_item(key):
    metadata = Metadata.get(key)
    print "metadata:", metadata

    if type(metadata) is Episode:
        guid = Guid.parse(metadata.guid)
        print "guid:", guid

        identifier = Matcher.process(metadata)
        print "identifier:", identifier
示例#12
0
def get_item(key):
    metadata = Metadata.get(key)
    print "metadata:", metadata

    if type(metadata) is Episode:
        guid = Guid.parse(metadata.guid)
        print "guid:", guid

        identifier = Matcher.process(metadata)
        print "identifier:", identifier
示例#13
0
def test(func):
    t_elapsed = []

    print 'test(%r)' % func

    # prime cache
    with Plex.configuration.cache(http=http_cache, matcher=matcher_cache):
        Metadata.configure(cache=metadata_cache)

        # Measure prime-cache task
        elapsed, items = measure(func)

    print '[P] %.02fs' % elapsed

    # Clear http cache
    http_cache.clear()
    time.sleep(1)

    for x in range(10):
        with Plex.configuration.cache(http=http_cache, matcher=matcher_cache):
            Metadata.configure(cache=metadata_cache)

            # Measure task
            elapsed, items = measure(func)

        print '[R] %.02fs' % elapsed
        t_elapsed.append(elapsed)

        # Clear http cache
        http_cache.clear()
        time.sleep(1)

    # Clear matcher/metadata caches
    matcher_cache.clear()
    metadata_cache.clear()

    # Calculate test statistics
    t_min = min(t_elapsed)
    t_max = max(t_elapsed)
    t_avg = sum(t_elapsed) / len(t_elapsed)

    print '] min: %.02f, max: %.02f, avg: %.02f' % (t_min, t_max, t_avg)
    print
示例#14
0
def test(func):
    t_elapsed = []

    print 'test(%r)' % func

    # prime cache
    with Plex.configuration.cache(http=http_cache, matcher=matcher_cache):
        Metadata.configure(cache=metadata_cache)

        # Measure prime-cache task
        elapsed, items = measure(func)

    print '[P] %.02fs' % elapsed

    # Clear http cache
    http_cache.clear()
    time.sleep(1)

    for x in range(10):
        with Plex.configuration.cache(http=http_cache, matcher=matcher_cache):
            Metadata.configure(cache=metadata_cache)

            # Measure task
            elapsed, items = measure(func)

        print '[R] %.02fs' % elapsed
        t_elapsed.append(elapsed)

        # Clear http cache
        http_cache.clear()
        time.sleep(1)

    # Clear matcher/metadata caches
    matcher_cache.clear()
    metadata_cache.clear()

    # Calculate test statistics
    t_min = min(t_elapsed)
    t_max = max(t_elapsed)
    t_avg = sum(t_elapsed) / len(t_elapsed)

    print '] min: %.02f, max: %.02f, avg: %.02f' % (t_min, t_max, t_avg)
    print
示例#15
0
    def build_request(cls, session, rating_key=None, view_offset=None):
        # Retrieve metadata for session
        if rating_key is None:
            rating_key = session.rating_key

        # Retrieve metadata
        metadata = Metadata.get(rating_key)

        # Queue a flush for the metadata cache
        Metadata.cache.flush_queue()

        # Validate metadata
        if not metadata:
            log.warn('Unable to retrieve metadata for rating_key %r',
                     rating_key)
            return None

        if metadata.type not in ['movie', 'episode']:
            log.info('Ignoring session with type %r for rating_key %r',
                     metadata.type, rating_key)
            return None

        # Apply library/section filter
        if not Filters.is_valid_metadata_section(metadata):
            return None

        # Parse guid
        guid = Guid.parse(metadata.guid)

        # Build request from guid/metadata
        if type(metadata) is Movie:
            result = cls.build_movie(metadata, guid)
        elif type(metadata) is Episode:
            result = cls.build_episode(metadata, guid)
        else:
            return None

        if not result:
            return None

        # Retrieve media progress
        if view_offset is not None:
            # Calculate progress from `view_offset` parameter
            progress = UpdateSession.get_progress(metadata.duration,
                                                  view_offset)
        else:
            # Use session progress
            progress = session.progress

        # Merge progress into request
        return merge(result, {'progress': progress})
示例#16
0
    def build_request(cls, session, rating_key=None, view_offset=None):
        # Retrieve metadata for session
        if rating_key is None:
            rating_key = session.rating_key

        # Retrieve metadata
        metadata = Metadata.get(rating_key)

        # Queue a flush for the metadata cache
        Metadata.cache.flush_queue()

        # Validate metadata
        if not metadata:
            log.warn('Unable to retrieve metadata for rating_key %r', rating_key)
            return None

        if metadata.type not in ['movie', 'episode']:
            log.info('Ignoring session with type %r for rating_key %r', metadata.type, rating_key)
            return None

        # Apply library/section filter
        if not Filters.is_valid_metadata_section(metadata):
            return None

        # Parse guid
        guid = Guid.parse(metadata.guid)

        # Build request from guid/metadata
        if type(metadata) is Movie:
            result = cls.build_movie(metadata, guid)
        elif type(metadata) is Episode:
            result = cls.build_episode(metadata, guid)
        else:
            return None

        if not result:
            return None

        # Retrieve media progress
        if view_offset is not None:
            # Calculate progress from `view_offset` parameter
            progress = UpdateSession.get_progress(metadata.duration, view_offset)
        else:
            # Use session progress
            progress = session.progress

        # Merge progress into request
        return merge(result, {
            'progress': progress
        })
    def from_event(cls, info):
        account_key = try_convert(info.get('account_key'), int)
        rating_key = info.get('rating_key')

        if account_key is None or rating_key is None:
            log.warn('Invalid action format: %s', info)
            return None

        if account_key != 1:
            log.debug('Ignoring action from shared account')
            return None

        if WatchSession.is_active(rating_key, lambda ws: not ws.update_required):
            log.debug('Ignoring action, item is currently being watched')
            return False

        metadata = Metadata.get(rating_key)

        if not metadata:
            log.debug('Ignoring action, unable to retrieve metadata')
            return False

        section = metadata.section.title.lower()

        f_allow, _ = get_filter('filter_sections')

        if f_allow is not None and section not in f_allow:
            log.debug('Ignoring action, section has been filtered')
            return False

        guid = Guid.parse(metadata.guid)

        request = {}

        if type(metadata) is Movie:
            request = cls.from_movie(metadata, guid)
        elif type(metadata) is Season:
            request = cls.from_season(metadata, guid)
        elif type(metadata) is Episode:
            request = cls.from_episode(metadata, guid)
        else:
            log.warn('Unsupported metadata type: %r', metadata)
            return None

        log.debug('request: %r', request)

        return request
示例#18
0
    def get_metadata(rating_key):
        # Retrieve metadata for `rating_key`
        try:
            metadata = Metadata.get(rating_key)
        except NotImplementedError as ex:
            log.debug('%r, ignoring session', ex.message)
            return None, None

        # Ensure metadata was returned
        if not metadata:
            return None, None

        # Validate metadata
        if metadata.type not in ['movie', 'episode']:
            log.info('Ignoring metadata with type %r for rating_key %r', metadata.type, rating_key)
            return metadata, None

        # Parse guid
        guid = Guid.parse(metadata.guid, strict=True)

        return metadata, guid
示例#19
0
    def build_request(cls,
                      session,
                      part=None,
                      rating_key=None,
                      view_offset=None):
        # Retrieve metadata for session
        if part is None:
            part = session.part

        if rating_key is None:
            rating_key = session.rating_key

        # Retrieve metadata
        metadata = Metadata.get(rating_key)

        # Validate metadata
        if not metadata:
            log.warn('Unable to retrieve metadata for rating_key %r',
                     rating_key)
            return None

        if metadata.type not in ['movie', 'episode']:
            log.info('Ignoring session with type %r for rating_key %r',
                     metadata.type, rating_key)
            return None

        # Apply library/section filter
        if not Filters.is_valid_metadata_section(metadata):
            log.info('Ignoring session in filtered section: %r',
                     metadata.section.title)
            return None

        # Parse guid
        guid = Guid.parse(metadata.guid, strict=True)

        if not guid or not guid.valid:
            log_unsupported_guid(log, guid)
            return None

        # Build request from guid/metadata
        if type(metadata) is Movie:
            result = cls.build_movie(metadata, guid, part)
        elif type(metadata) is Episode:
            result = cls.build_episode(metadata, guid, part)
        else:
            log.warn('Unknown metadata type: %r', type(metadata))
            return None

        if not result:
            log.info('Unable to build request for session: %r', session)
            return None

        # Retrieve media progress
        if view_offset is not None:
            # Calculate progress from `view_offset` parameter
            progress = UpdateSession.get_progress(metadata.duration,
                                                  view_offset, part,
                                                  session.part_count,
                                                  session.part_duration)
        else:
            # Use session progress
            progress = session.progress

        # Merge progress into request
        return merge(result, {'progress': progress})
示例#20
0
    def on_played(info):
        print "[logging.action.played]", info

        metadata = Metadata.get(info.get('rating_key'))
        print metadata
示例#21
0
    def on_played(info):
        print "[logging.action.played]", info

        metadata = Metadata.get(info.get('rating_key'))
        print metadata