Exemplo n.º 1
0
def refresh_users():
    logger.info("Tautulli Users :: Requesting users list refresh...")
    result = plextv.PlexTV().get_full_users_list()

    server_id = plexpy.CONFIG.PMS_IDENTIFIER
    if not server_id:
        logger.error(
            "Tautulli Users :: No PMS identifier, cannot refresh users. Verify server in settings."
        )
        return

    if result:
        monitor_db = database.MonitorDatabase()

        # Keep track of user_id to update is_active status
        user_ids = [0]  # Local user always considered active

        for item in result:
            user_ids.append(helpers.cast_to_int(item['user_id']))

            if item.get('shared_libraries'):
                item['shared_libraries'] = ';'.join(item['shared_libraries'])
            elif item.get('server_token'):
                libs = libraries.Libraries().get_sections()
                item['shared_libraries'] = ';'.join(
                    [str(l['section_id']) for l in libs])

            keys_dict = {"user_id": item.pop('user_id')}

            # Check if we've set a custom avatar if so don't overwrite it.
            if keys_dict['user_id']:
                avatar_urls = monitor_db.select(
                    'SELECT thumb, custom_avatar_url '
                    'FROM users WHERE user_id = ?', [keys_dict['user_id']])
                if avatar_urls:
                    if not avatar_urls[0]['custom_avatar_url'] or \
                            avatar_urls[0]['custom_avatar_url'] == avatar_urls[0]['thumb']:
                        item['custom_avatar_url'] = item['thumb']
                else:
                    item['custom_avatar_url'] = item['thumb']

            # Check if title is the same as the username
            if item['title'] == item['username']:
                item['title'] = None

            monitor_db.upsert('users', key_dict=keys_dict, value_dict=item)

        query = 'UPDATE users SET is_active = 0 WHERE user_id NOT IN ({})'.format(
            ', '.join(['?'] * len(user_ids)))
        monitor_db.action(query=query, args=user_ids)

        logger.info("Tautulli Users :: Users list refreshed.")
        return True
    else:
        logger.warn("Tautulli Users :: Unable to refresh users list.")
        return False
Exemplo n.º 2
0
def refresh_users():
    logger.info(u"Tautulli Users :: Requesting users list refresh...")
    result = plextv.PlexTV().get_full_users_list()

    if result:
        monitor_db = database.MonitorDatabase()

        for item in result:

            if item.get('shared_libraries'):
                item['shared_libraries'] = ';'.join(item['shared_libraries'])
            elif item.get('server_token'):
                libs = libraries.Libraries().get_sections()
                item['shared_libraries'] = ';'.join(
                    [str(l['section_id']) for l in libs])

            keys_dict = {"user_id": item.pop('user_id')}

            # Check if we've set a custom avatar if so don't overwrite it.
            if keys_dict['user_id']:
                avatar_urls = monitor_db.select(
                    'SELECT thumb, custom_avatar_url '
                    'FROM users WHERE user_id = ?', [keys_dict['user_id']])
                if avatar_urls:
                    if not avatar_urls[0]['custom_avatar_url'] or \
                            avatar_urls[0]['custom_avatar_url'] == avatar_urls[0]['thumb']:
                        item['custom_avatar_url'] = item['thumb']
                else:
                    item['custom_avatar_url'] = item['thumb']

            monitor_db.upsert('users', item, keys_dict)

        logger.info(u"Tautulli Users :: Users list refreshed.")
        return True
    else:
        logger.warn(u"Tautulli Users :: Unable to refresh users list.")
        return False
Exemplo n.º 3
0
    def write_session_history(self,
                              session=None,
                              import_metadata=None,
                              is_import=False,
                              import_ignore_interval=0):
        section_id = session[
            'section_id'] if not is_import else import_metadata['section_id']

        if not is_import:
            user_data = users.Users()
            user_details = user_data.get_details(user_id=session['user_id'])

            library_data = libraries.Libraries()
            library_details = library_data.get_details(section_id=section_id)

            # Return false if failed to retrieve user or library details
            if not user_details or not library_details:
                return False

        if session:
            logging_enabled = False

            # Reload json from raw stream info
            if session.get('raw_stream_info'):
                raw_stream_info = json.loads(session['raw_stream_info'])
                # Don't overwrite id, session_key, stopped
                raw_stream_info.pop('id', None)
                raw_stream_info.pop('session_key', None)
                raw_stream_info.pop('stopped', None)
                session.update(raw_stream_info)

            session = defaultdict(str, session)

            if is_import:
                if str(session['stopped']).isdigit():
                    stopped = int(session['stopped'])
                else:
                    stopped = int(time.time())
            elif session['stopped']:
                stopped = int(session['stopped'])
            else:
                stopped = int(time.time())
                self.set_session_state(session_key=session['session_key'],
                                       state='stopped',
                                       stopped=stopped)

            if str(session['rating_key']).isdigit(
            ) and session['media_type'] in ('movie', 'episode', 'track'):
                logging_enabled = True
            else:
                logger.debug(
                    u"Tautulli ActivityProcessor :: ratingKey %s not logged. Does not meet logging criteria. "
                    u"Media type is '%s'" %
                    (session['rating_key'], session['media_type']))
                return session['id']

            if str(session['paused_counter']).isdigit():
                real_play_time = stopped - session['started'] - int(
                    session['paused_counter'])
            else:
                real_play_time = stopped - session['started']

            if not is_import and plexpy.CONFIG.LOGGING_IGNORE_INTERVAL:
                if (session['media_type'] == 'movie' or session['media_type'] == 'episode') and \
                        (real_play_time < int(plexpy.CONFIG.LOGGING_IGNORE_INTERVAL)):
                    logging_enabled = False
                    logger.debug(
                        u"Tautulli ActivityProcessor :: Play duration for ratingKey %s is %s secs which is less than %s "
                        u"seconds, so we're not logging it." %
                        (session['rating_key'], str(real_play_time),
                         plexpy.CONFIG.LOGGING_IGNORE_INTERVAL))
            if not is_import and session['media_type'] == 'track':
                if real_play_time < 15 and session['duration'] >= 30:
                    logging_enabled = False
                    logger.debug(
                        u"Tautulli ActivityProcessor :: Play duration for ratingKey %s is %s secs, "
                        u"looks like it was skipped so we're not logging it" %
                        (session['rating_key'], str(real_play_time)))
            elif is_import and import_ignore_interval:
                if (session['media_type'] == 'movie' or session['media_type'] == 'episode') and \
                        (real_play_time < int(import_ignore_interval)):
                    logging_enabled = False
                    logger.debug(
                        u"Tautulli ActivityProcessor :: Play duration for ratingKey %s is %s secs which is less than %s "
                        u"seconds, so we're not logging it." %
                        (session['rating_key'], str(real_play_time),
                         import_ignore_interval))

            if not is_import and not user_details['keep_history']:
                logging_enabled = False
                logger.debug(
                    u"Tautulli ActivityProcessor :: History logging for user '%s' is disabled."
                    % user_details['username'])
            elif not is_import and not library_details['keep_history']:
                logging_enabled = False
                logger.debug(
                    u"Tautulli ActivityProcessor :: History logging for library '%s' is disabled."
                    % library_details['section_name'])

            if logging_enabled:

                # Fetch metadata first so we can return false if it fails
                if not is_import:
                    logger.debug(
                        u"Tautulli ActivityProcessor :: Fetching metadata for item ratingKey %s"
                        % session['rating_key'])
                    pms_connect = pmsconnect.PmsConnect()
                    metadata = pms_connect.get_metadata_details(
                        rating_key=str(session['rating_key']))
                    if not metadata:
                        return False
                    else:
                        media_info = {}
                        if 'media_info' in metadata and len(
                                metadata['media_info']) > 0:
                            media_info = metadata['media_info'][0]
                else:
                    metadata = import_metadata
                    ## TODO: Fix media info from imports. Temporary media info from import session.
                    media_info = session

                # logger.debug(u"Tautulli ActivityProcessor :: Attempting to write sessionKey %s to session_history table..."
                #              % session['session_key'])
                keys = {'id': None}
                values = {
                    'started': session['started'],
                    'stopped': stopped,
                    'rating_key': session['rating_key'],
                    'parent_rating_key': session['parent_rating_key'],
                    'grandparent_rating_key':
                    session['grandparent_rating_key'],
                    'media_type': session['media_type'],
                    'user_id': session['user_id'],
                    'user': session['user'],
                    'ip_address': session['ip_address'],
                    'paused_counter': session['paused_counter'],
                    'player': session['player'],
                    'product': session['product'],
                    'product_version': session['product_version'],
                    'platform': session['platform'],
                    'platform_version': session['platform_version'],
                    'profile': session['profile'],
                    'machine_id': session['machine_id'],
                    'bandwidth': session['bandwidth'],
                    'location': session['location'],
                    'quality_profile': session['quality_profile'],
                    'view_offset': session['view_offset']
                }

                # logger.debug(u"Tautulli ActivityProcessor :: Writing sessionKey %s session_history transaction..."
                #              % session['session_key'])
                self.db.upsert(table_name='session_history',
                               key_dict=keys,
                               value_dict=values)

                # Check if we should group the session, select the last two rows from the user
                query = 'SELECT id, rating_key, view_offset, user_id, reference_id FROM session_history \
                         WHERE user_id = ? ORDER BY id DESC LIMIT 2 '

                args = [session['user_id']]

                result = self.db.select(query=query, args=args)

                new_session = prev_session = None
                # Get the last insert row id
                last_id = self.db.last_insert_id()

                if len(result) > 1:
                    new_session = {
                        'id': result[0]['id'],
                        'rating_key': result[0]['rating_key'],
                        'view_offset': result[0]['view_offset'],
                        'user_id': result[0]['user_id'],
                        'reference_id': result[0]['reference_id']
                    }

                    prev_session = {
                        'id': result[1]['id'],
                        'rating_key': result[1]['rating_key'],
                        'view_offset': result[1]['view_offset'],
                        'user_id': result[1]['user_id'],
                        'reference_id': result[1]['reference_id']
                    }

                query = 'UPDATE session_history SET reference_id = ? WHERE id = ? '
                # If rating_key is the same in the previous session, then set the reference_id to the previous row, else set the reference_id to the new id
                if prev_session is None and new_session is None:
                    args = [last_id, last_id]
                elif prev_session['rating_key'] == new_session[
                        'rating_key'] and prev_session[
                            'view_offset'] <= new_session['view_offset']:
                    args = [prev_session['reference_id'], new_session['id']]
                else:
                    args = [new_session['id'], new_session['id']]

                self.db.action(query=query, args=args)

                # logger.debug(u"Tautulli ActivityProcessor :: Successfully written history item, last id for session_history is %s"
                #              % last_id)

                # Write the session_history_media_info table

                # logger.debug(u"Tautulli ActivityProcessor :: Attempting to write to sessionKey %s session_history_media_info table..."
                #              % session['session_key'])
                keys = {'id': last_id}
                values = {
                    'rating_key':
                    session['rating_key'],
                    'video_decision':
                    session['video_decision'],
                    'audio_decision':
                    session['audio_decision'],
                    'transcode_decision':
                    session['transcode_decision'],
                    'duration':
                    session['duration'],
                    'container':
                    session['container'],
                    'bitrate':
                    session['bitrate'],
                    'width':
                    session['width'],
                    'height':
                    session['height'],
                    'video_bit_depth':
                    session['video_bit_depth'],
                    'video_bitrate':
                    session['video_bitrate'],
                    'video_codec':
                    session['video_codec'],
                    'video_codec_level':
                    session['video_codec_level'],
                    'video_width':
                    session['video_width'],
                    'video_height':
                    session['video_height'],
                    'video_resolution':
                    session['video_resolution'],
                    'video_framerate':
                    session['video_framerate'],
                    'aspect_ratio':
                    session['aspect_ratio'],
                    'audio_codec':
                    session['audio_codec'],
                    'audio_bitrate':
                    session['audio_bitrate'],
                    'audio_channels':
                    session['audio_channels'],
                    'subtitle_codec':
                    session['subtitle_codec'],
                    'transcode_protocol':
                    session['transcode_protocol'],
                    'transcode_container':
                    session['transcode_container'],
                    'transcode_video_codec':
                    session['transcode_video_codec'],
                    'transcode_audio_codec':
                    session['transcode_audio_codec'],
                    'transcode_audio_channels':
                    session['transcode_audio_channels'],
                    'transcode_width':
                    session['transcode_width'],
                    'transcode_height':
                    session['transcode_height'],
                    'transcode_hw_requested':
                    session['transcode_hw_requested'],
                    'transcode_hw_full_pipeline':
                    session['transcode_hw_full_pipeline'],
                    'transcode_hw_decoding':
                    session['transcode_hw_decoding'],
                    'transcode_hw_decode':
                    session['transcode_hw_decode'],
                    'transcode_hw_decode_title':
                    session['transcode_hw_decode_title'],
                    'transcode_hw_encoding':
                    session['transcode_hw_encoding'],
                    'transcode_hw_encode':
                    session['transcode_hw_encode'],
                    'transcode_hw_encode_title':
                    session['transcode_hw_encode_title'],
                    'stream_container':
                    session['stream_container'],
                    'stream_container_decision':
                    session['stream_container_decision'],
                    'stream_bitrate':
                    session['stream_bitrate'],
                    'stream_video_decision':
                    session['stream_video_decision'],
                    'stream_video_bitrate':
                    session['stream_video_bitrate'],
                    'stream_video_codec':
                    session['stream_video_codec'],
                    'stream_video_codec_level':
                    session['stream_video_codec_level'],
                    'stream_video_bit_depth':
                    session['stream_video_bit_depth'],
                    'stream_video_height':
                    session['stream_video_height'],
                    'stream_video_width':
                    session['stream_video_width'],
                    'stream_video_resolution':
                    session['stream_video_resolution'],
                    'stream_video_framerate':
                    session['stream_video_framerate'],
                    'stream_audio_decision':
                    session['stream_audio_decision'],
                    'stream_audio_codec':
                    session['stream_audio_codec'],
                    'stream_audio_bitrate':
                    session['stream_audio_bitrate'],
                    'stream_audio_channels':
                    session['stream_audio_channels'],
                    'stream_subtitle_decision':
                    session['stream_subtitle_decision'],
                    'stream_subtitle_codec':
                    session['stream_subtitle_codec'],
                    'stream_subtitle_container':
                    session['stream_subtitle_container'],
                    'stream_subtitle_forced':
                    session['stream_subtitle_forced'],
                    'subtitles':
                    session['subtitles'],
                    'synced_version':
                    session['synced_version'],
                    'synced_version_profile':
                    session['synced_version_profile'],
                    'optimized_version':
                    session['optimized_version'],
                    'optimized_version_profile':
                    session['optimized_version_profile'],
                    'optimized_version_title':
                    session['optimized_version_title']
                }

                # logger.debug(u"Tautulli ActivityProcessor :: Writing sessionKey %s session_history_media_info transaction..."
                #              % session['session_key'])
                self.db.upsert(table_name='session_history_media_info',
                               key_dict=keys,
                               value_dict=values)

                # Write the session_history_metadata table
                directors = ";".join(metadata['directors'])
                writers = ";".join(metadata['writers'])
                actors = ";".join(metadata['actors'])
                genres = ";".join(metadata['genres'])
                labels = ";".join(metadata['labels'])

                # logger.debug(u"Tautulli ActivityProcessor :: Attempting to write to sessionKey %s session_history_metadata table..."
                #              % session['session_key'])
                keys = {'id': last_id}
                values = {
                    'rating_key': session['rating_key'],
                    'parent_rating_key': session['parent_rating_key'],
                    'grandparent_rating_key':
                    session['grandparent_rating_key'],
                    'title': session['title'],
                    'parent_title': session['parent_title'],
                    'grandparent_title': session['grandparent_title'],
                    'full_title': session['full_title'],
                    'media_index': metadata['media_index'],
                    'parent_media_index': metadata['parent_media_index'],
                    'section_id': metadata['section_id'],
                    'thumb': metadata['thumb'],
                    'parent_thumb': metadata['parent_thumb'],
                    'grandparent_thumb': metadata['grandparent_thumb'],
                    'art': metadata['art'],
                    'media_type': session['media_type'],
                    'year': metadata['year'],
                    'originally_available_at':
                    metadata['originally_available_at'],
                    'added_at': metadata['added_at'],
                    'updated_at': metadata['updated_at'],
                    'last_viewed_at': metadata['last_viewed_at'],
                    'content_rating': metadata['content_rating'],
                    'summary': metadata['summary'],
                    'tagline': metadata['tagline'],
                    'rating': metadata['rating'],
                    'duration': metadata['duration'],
                    'guid': metadata['guid'],
                    'directors': directors,
                    'writers': writers,
                    'actors': actors,
                    'genres': genres,
                    'studio': metadata['studio'],
                    'labels': labels
                }

                # logger.debug(u"Tautulli ActivityProcessor :: Writing sessionKey %s session_history_metadata transaction..."
                #              % session['session_key'])
                self.db.upsert(table_name='session_history_metadata',
                               key_dict=keys,
                               value_dict=values)

            # Return the session row id when the session is successfully written to the database
            return session['id']
Exemplo n.º 4
0
 def _get_sections(self):
     return libraries.Libraries().get_sections()
Exemplo n.º 5
0
def check_recently_added():

    with monitor_lock:
        # add delay to allow for metadata processing
        delay = plexpy.CONFIG.NOTIFY_RECENTLY_ADDED_DELAY
        time_threshold = int(time.time()) - delay
        time_interval = plexpy.CONFIG.MONITORING_INTERVAL

        pms_connect = pmsconnect.PmsConnect()
        recently_added_list = pms_connect.get_recently_added_details(
            count='10')

        library_data = libraries.Libraries()
        if recently_added_list:
            recently_added = recently_added_list['recently_added']

            for item in recently_added:
                library_details = library_data.get_details(
                    section_id=item['section_id'])

                if not library_details['do_notify_created']:
                    continue

                metadata = []

                if 0 < time_threshold - int(item['added_at']) <= time_interval:
                    if item['media_type'] == 'movie':
                        metadata_list = pms_connect.get_metadata_details(
                            item['rating_key'])
                        if metadata_list:
                            metadata = [metadata_list['metadata']]
                        else:
                            logger.error(u"PlexPy Monitor :: Unable to retrieve metadata for rating_key %s" \
                                         % str(item['rating_key']))

                    else:
                        metadata_list = pms_connect.get_metadata_children_details(
                            item['rating_key'])
                        if metadata_list:
                            metadata = metadata_list['metadata']
                        else:
                            logger.error(u"PlexPy Monitor :: Unable to retrieve children metadata for rating_key %s" \
                                         % str(item['rating_key']))

                if metadata:

                    if not plexpy.CONFIG.NOTIFY_RECENTLY_ADDED_GRANDPARENT:
                        for item in metadata:

                            library_details = library_data.get_details(
                                section_id=item['section_id'])

                            if 0 < time_threshold - int(
                                    item['added_at']) <= time_interval:
                                logger.debug(
                                    u"PlexPy Monitor :: Library item %s has been added to Plex."
                                    % str(item['rating_key']))

                                # Check if any notification agents have notifications enabled
                                if any(d['on_created'] for d in notifiers.
                                       available_notification_agents()):
                                    # Fire off notifications
                                    threading.Thread(
                                        target=notification_handler.
                                        notify_timeline,
                                        kwargs=dict(
                                            timeline_data=item,
                                            notify_action='created')).start()

                    else:
                        item = max(metadata, key=lambda x: x['added_at'])

                        if 0 < time_threshold - int(
                                item['added_at']) <= time_interval:
                            if item['media_type'] == 'episode' or item[
                                    'media_type'] == 'track':
                                metadata_list = pms_connect.get_metadata_details(
                                    item['grandparent_rating_key'])

                                if metadata_list:
                                    item = metadata_list['metadata']
                                else:
                                    logger.error(u"PlexPy Monitor :: Unable to retrieve grandparent metadata for grandparent_rating_key %s" \
                                                 % str(item['rating_key']))

                            logger.debug(
                                u"PlexPy Monitor :: Library item %s has been added to Plex."
                                % str(item['rating_key']))

                            # Check if any notification agents have notifications enabled
                            if any(d['on_created'] for d in
                                   notifiers.available_notification_agents()):
                                # Fire off notifications
                                threading.Thread(
                                    target=notification_handler.
                                    notify_timeline,
                                    kwargs=dict(
                                        timeline_data=item,
                                        notify_action='created')).start()
Exemplo n.º 6
0
    def write_session_history(self,
                              session=None,
                              import_metadata=None,
                              is_import=False,
                              import_ignore_interval=0):
        section_id = session[
            'section_id'] if not is_import else import_metadata['section_id']

        if not is_import:
            user_data = users.Users()
            user_details = user_data.get_details(user_id=session['user_id'])

            library_data = libraries.Libraries()
            library_details = library_data.get_details(section_id=section_id)

            # Return false if failed to retrieve user or library details
            if not user_details or not library_details:
                return False

        if session:
            logging_enabled = False

            if is_import:
                if str(session['stopped']).isdigit():
                    stopped = int(session['stopped'])
                else:
                    stopped = int(time.time())
            elif session['stopped']:
                stopped = int(session['stopped'])
            else:
                stopped = int(time.time())
                self.set_session_state(session_key=session['session_key'],
                                       state='stopped',
                                       stopped=stopped)

            if plexpy.CONFIG.MOVIE_LOGGING_ENABLE and str(session['rating_key']).isdigit() and \
                    session['media_type'] == 'movie':
                logging_enabled = True
            elif plexpy.CONFIG.TV_LOGGING_ENABLE and str(session['rating_key']).isdigit() and \
                    session['media_type'] == 'episode':
                logging_enabled = True
            elif plexpy.CONFIG.MUSIC_LOGGING_ENABLE and str(session['rating_key']).isdigit() and \
                    session['media_type'] == 'track':
                logging_enabled = True
            else:
                logger.debug(
                    u"PlexPy ActivityProcessor :: ratingKey %s not logged. Does not meet logging criteria. "
                    u"Media type is '%s'" %
                    (session['rating_key'], session['media_type']))

            if str(session['paused_counter']).isdigit():
                real_play_time = stopped - session['started'] - int(
                    session['paused_counter'])
            else:
                real_play_time = stopped - session['started']

            if not is_import and plexpy.CONFIG.LOGGING_IGNORE_INTERVAL:
                if (session['media_type'] == 'movie' or session['media_type'] == 'episode') and \
                        (real_play_time < int(plexpy.CONFIG.LOGGING_IGNORE_INTERVAL)):
                    logging_enabled = False
                    logger.debug(
                        u"PlexPy ActivityProcessor :: Play duration for ratingKey %s is %s secs which is less than %s "
                        u"seconds, so we're not logging it." %
                        (session['rating_key'], str(real_play_time),
                         plexpy.CONFIG.LOGGING_IGNORE_INTERVAL))
            if not is_import and session['media_type'] == 'track':
                if real_play_time < 15 and session['duration'] >= 30:
                    logging_enabled = False
                    logger.debug(
                        u"PlexPy ActivityProcessor :: Play duration for ratingKey %s is %s secs, "
                        u"looks like it was skipped so we're not logging it" %
                        (session['rating_key'], str(real_play_time)))
            elif is_import and import_ignore_interval:
                if (session['media_type'] == 'movie' or session['media_type'] == 'episode') and \
                        (real_play_time < int(import_ignore_interval)):
                    logging_enabled = False
                    logger.debug(
                        u"PlexPy ActivityProcessor :: Play duration for ratingKey %s is %s secs which is less than %s "
                        u"seconds, so we're not logging it." %
                        (session['rating_key'], str(real_play_time),
                         import_ignore_interval))

            if not is_import and not user_details['keep_history']:
                logging_enabled = False
                logger.debug(
                    u"PlexPy ActivityProcessor :: History logging for user '%s' is disabled."
                    % user_details['username'])
            elif not is_import and not library_details['keep_history']:
                logging_enabled = False
                logger.debug(
                    u"PlexPy ActivityProcessor :: History logging for library '%s' is disabled."
                    % library_details['section_name'])

            if logging_enabled:

                # Fetch metadata first so we can return false if it fails
                if not is_import:
                    logger.debug(
                        u"PlexPy ActivityProcessor :: Fetching metadata for item ratingKey %s"
                        % session['rating_key'])
                    pms_connect = pmsconnect.PmsConnect()
                    result = pms_connect.get_metadata_details(
                        rating_key=str(session['rating_key']))
                    if result:
                        metadata = result['metadata']
                    else:
                        return False
                else:
                    metadata = import_metadata

                # logger.debug(u"PlexPy ActivityProcessor :: Attempting to write to session_history table...")
                query = 'INSERT INTO session_history (started, stopped, rating_key, parent_rating_key, ' \
                        'grandparent_rating_key, media_type, user_id, user, ip_address, paused_counter, player, ' \
                        'platform, machine_id, view_offset) VALUES ' \
                        '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'

                args = [
                    session['started'], stopped, session['rating_key'],
                    session['parent_rating_key'],
                    session['grandparent_rating_key'], session['media_type'],
                    session['user_id'], session['user'], session['ip_address'],
                    session['paused_counter'], session['player'],
                    session['platform'], session['machine_id'],
                    session['view_offset']
                ]

                # logger.debug(u"PlexPy ActivityProcessor :: Writing session_history transaction...")
                self.db.action(query=query, args=args)

                # Check if we should group the session, select the last two rows from the user
                query = 'SELECT id, rating_key, view_offset, user_id, reference_id FROM session_history \
                         WHERE user_id = ? ORDER BY id DESC LIMIT 2 '

                args = [session['user_id']]

                result = self.db.select(query=query, args=args)

                new_session = prev_session = last_id = None
                if len(result) > 1:
                    new_session = {
                        'id': result[0]['id'],
                        'rating_key': result[0]['rating_key'],
                        'view_offset': result[0]['view_offset'],
                        'user_id': result[0]['user_id'],
                        'reference_id': result[0]['reference_id']
                    }

                    prev_session = {
                        'id': result[1]['id'],
                        'rating_key': result[1]['rating_key'],
                        'view_offset': result[1]['view_offset'],
                        'user_id': result[1]['user_id'],
                        'reference_id': result[1]['reference_id']
                    }
                else:
                    # Get the last insert row id
                    result = self.db.select(
                        query='SELECT last_insert_rowid() AS last_id')
                    last_id = result[0]['last_id'] if result else None

                query = 'UPDATE session_history SET reference_id = ? WHERE id = ? '
                # If rating_key is the same in the previous session, then set the reference_id to the previous row, else set the reference_id to the new id
                if prev_session == new_session == None:
                    args = [last_id, last_id]
                elif prev_session['rating_key'] == new_session[
                        'rating_key'] and prev_session[
                            'view_offset'] <= new_session['view_offset']:
                    args = [prev_session['reference_id'], new_session['id']]
                else:
                    args = [new_session['id'], new_session['id']]

                self.db.action(query=query, args=args)

                # logger.debug(u"PlexPy ActivityProcessor :: Successfully written history item, last id for session_history is %s"
                #              % last_id)

                # Write the session_history_media_info table

                # Generate a combined transcode decision value
                if session['video_decision'] == 'transcode' or session[
                        'audio_decision'] == 'transcode':
                    transcode_decision = 'transcode'
                elif session['video_decision'] == 'copy' or session[
                        'audio_decision'] == 'copy':
                    transcode_decision = 'copy'
                else:
                    transcode_decision = 'direct play'

                # logger.debug(u"PlexPy ActivityProcessor :: Attempting to write to session_history_media_info table...")
                query = 'INSERT INTO session_history_media_info (id, rating_key, video_decision, audio_decision, ' \
                        'duration, width, height, container, video_codec, audio_codec, bitrate, video_resolution, ' \
                        'video_framerate, aspect_ratio, audio_channels, transcode_protocol, transcode_container, ' \
                        'transcode_video_codec, transcode_audio_codec, transcode_audio_channels, transcode_width, ' \
                        'transcode_height, transcode_decision) VALUES ' \
                        '(last_insert_rowid(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'

                args = [
                    session['rating_key'], session['video_decision'],
                    session['audio_decision'], session['duration'],
                    session['width'], session['height'], session['container'],
                    session['video_codec'], session['audio_codec'],
                    session['bitrate'], session['video_resolution'],
                    session['video_framerate'], session['aspect_ratio'],
                    session['audio_channels'], session['transcode_protocol'],
                    session['transcode_container'],
                    session['transcode_video_codec'],
                    session['transcode_audio_codec'],
                    session['transcode_audio_channels'],
                    session['transcode_width'], session['transcode_height'],
                    transcode_decision
                ]

                # logger.debug(u"PlexPy ActivityProcessor :: Writing session_history_media_info transaction...")
                self.db.action(query=query, args=args)

                # Write the session_history_metadata table
                directors = ";".join(metadata['directors'])
                writers = ";".join(metadata['writers'])
                actors = ";".join(metadata['actors'])
                genres = ";".join(metadata['genres'])
                labels = ";".join(metadata['labels'])

                # Build media item title
                if session['media_type'] == 'episode' or session[
                        'media_type'] == 'track':
                    full_title = '%s - %s' % (metadata['grandparent_title'],
                                              metadata['title'])
                elif session['media_type'] == 'movie':
                    full_title = metadata['title']
                else:
                    full_title = metadata['title']

                # logger.debug(u"PlexPy ActivityProcessor :: Attempting to write to session_history_metadata table...")
                query = 'INSERT INTO session_history_metadata (id, rating_key, parent_rating_key, ' \
                        'grandparent_rating_key, title, parent_title, grandparent_title, full_title, media_index, ' \
                        'parent_media_index, section_id, thumb, parent_thumb, grandparent_thumb, art, media_type, ' \
                        'year, originally_available_at, added_at, updated_at, last_viewed_at, content_rating, ' \
                        'summary, tagline, rating, duration, guid, directors, writers, actors, genres, studio, labels) ' \
                        'VALUES (last_insert_rowid(), ' \
                        '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'

                args = [
                    session['rating_key'], session['parent_rating_key'],
                    session['grandparent_rating_key'], session['title'],
                    session['parent_title'], session['grandparent_title'],
                    full_title, metadata['media_index'],
                    metadata['parent_media_index'], metadata['section_id'],
                    metadata['thumb'], metadata['parent_thumb'],
                    metadata['grandparent_thumb'], metadata['art'],
                    session['media_type'], metadata['year'],
                    metadata['originally_available_at'], metadata['added_at'],
                    metadata['updated_at'], metadata['last_viewed_at'],
                    metadata['content_rating'], metadata['summary'],
                    metadata['tagline'], metadata['rating'],
                    metadata['duration'], metadata['guid'], directors, writers,
                    actors, genres, metadata['studio'], labels
                ]

                # logger.debug(u"PlexPy ActivityProcessor :: Writing session_history_metadata transaction...")
                self.db.action(query=query, args=args)

            # Return true when the session is successfully written to the database
            return True
Exemplo n.º 7
0
def check_recently_added():

    with monitor_lock:
        # add delay to allow for metadata processing
        delay = plexpy.CONFIG.NOTIFY_RECENTLY_ADDED_DELAY
        time_threshold = int(time.time()) - delay
        time_interval = plexpy.CONFIG.MONITORING_INTERVAL

        pms_connect = pmsconnect.PmsConnect()
        recently_added_list = pms_connect.get_recently_added_details(
            count='10')

        library_data = libraries.Libraries()
        if recently_added_list:
            recently_added = recently_added_list['recently_added']

            for item in recently_added:
                library_details = library_data.get_details(
                    section_id=item['section_id'])

                if not library_details['do_notify_created']:
                    continue

                metadata = []

                if 0 < time_threshold - int(item['added_at']) <= time_interval:
                    if item['media_type'] == 'movie':
                        metadata = pms_connect.get_metadata_details(
                            item['rating_key'])
                        if metadata:
                            metadata = [metadata]
                        else:
                            logger.error(u"Tautulli Monitor :: Unable to retrieve metadata for rating_key %s" \
                                         % str(item['rating_key']))

                    else:
                        metadata = pms_connect.get_metadata_children_details(
                            item['rating_key'])
                        if not metadata:
                            logger.error(u"Tautulli Monitor :: Unable to retrieve children metadata for rating_key %s" \
                                         % str(item['rating_key']))

                if metadata:

                    if not plexpy.CONFIG.NOTIFY_GROUP_RECENTLY_ADDED:
                        for item in metadata:

                            library_details = library_data.get_details(
                                section_id=item['section_id'])

                            if 0 < time_threshold - int(
                                    item['added_at']) <= time_interval:
                                logger.debug(
                                    u"Tautulli Monitor :: Library item %s added to Plex."
                                    % str(item['rating_key']))

                                plexpy.NOTIFY_QUEUE.put({
                                    'timeline_data':
                                    item.copy(),
                                    'notify_action':
                                    'on_created'
                                })

                    else:
                        item = max(metadata, key=lambda x: x['added_at'])

                        if 0 < time_threshold - int(
                                item['added_at']) <= time_interval:
                            if item['media_type'] == 'episode' or item[
                                    'media_type'] == 'track':
                                metadata = pms_connect.get_metadata_details(
                                    item['grandparent_rating_key'])

                                if metadata:
                                    item = metadata
                                else:
                                    logger.error(u"Tautulli Monitor :: Unable to retrieve grandparent metadata for grandparent_rating_key %s" \
                                                 % str(item['rating_key']))

                            logger.debug(
                                u"Tautulli Monitor :: Library item %s added to Plex."
                                % str(item['rating_key']))

                            # Check if any notification agents have notifications enabled
                            plexpy.NOTIFY_QUEUE.put({
                                'timeline_data':
                                item.copy(),
                                'notify_action':
                                'on_created'
                            })