Python logger.warn() Examples

The following are 30 code examples of logger.warn(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module logger , or try the search function .
Example #1
Source File: libraries.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_sections(self):
        monitor_db = database.MonitorDatabase()

        try:
            query = 'SELECT section_id, section_name, section_type, agent ' \
                    'FROM library_sections WHERE deleted_section = 0'
            result = monitor_db.select(query=query)
        except Exception as e:
            logger.warn("Tautulli Libraries :: Unable to execute database query for get_sections: %s." % e)
            return None

        libraries = []
        for item in result:
            library = {'section_id': item['section_id'],
                       'section_name': item['section_name'],
                       'section_type': item['section_type'],
                       'agent': item['agent']
                       }
            libraries.append(library)

        return libraries 
Example #2
Source File: plextv.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_plexpass_status(self):
        account_data = self.get_plextv_user_details(output_format='xml')

        try:
            subscription = account_data.getElementsByTagName('subscription')
        except Exception as e:
            logger.warn("Tautulli PlexTV :: Unable to parse XML for get_plexpass_status: %s." % e)
            return False

        if subscription and helpers.get_xml_attr(subscription[0], 'active') == '1':
            plexpy.CONFIG.__setattr__('PMS_PLEXPASS', 1)
            plexpy.CONFIG.write()
            return True
        else:
            logger.debug("Tautulli PlexTV :: Plex Pass subscription not found.")
            plexpy.CONFIG.__setattr__('PMS_PLEXPASS', 0)
            plexpy.CONFIG.write()
            return False 
Example #3
Source File: plextv.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_pin(self, pin=''):
        plextv_response = self.get_plextv_pin(pin=pin,
                                              output_format='xml')

        if plextv_response:
            try:
                xml_head = plextv_response.getElementsByTagName('pin')
                if xml_head:
                    pin = {'id': xml_head[0].getAttribute('id'),
                           'code': xml_head[0].getAttribute('code'),
                           'token': xml_head[0].getAttribute('authToken')
                           }
                    return pin
                else:
                    logger.warn("Tautulli PlexTV :: Could not get Plex authentication pin.")
                    return None

            except Exception as e:
                logger.warn("Tautulli PlexTV :: Unable to parse XML for get_pin: %s." % e)
                return None

        else:
            return None 
Example #4
Source File: plextv.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_plexpy_pms_token(self, force=False):
        if force:
            logger.debug("Tautulli PlexTV :: Forcing refresh of Plex.tv token.")
            devices_list = self.get_devices_list()
            device_id = next((d for d in devices_list if d['device_identifier'] == plexpy.CONFIG.PMS_UUID), {}).get('device_id', None)

            if device_id:
                logger.debug("Tautulli PlexTV :: Removing Tautulli from Plex.tv devices.")
                try:
                    self.delete_plextv_device(device_id=device_id)
                except:
                    logger.error("Tautulli PlexTV :: Failed to remove Tautulli from Plex.tv devices.")
                    return None
            else:
                logger.warn("Tautulli PlexTV :: No existing Tautulli device found.")

        logger.info("Tautulli PlexTV :: Fetching a new Plex.tv token for Tautulli.")
        user = self.get_token()
        if user:
            token = user['auth_token']
            plexpy.CONFIG.__setattr__('PMS_TOKEN', token)
            plexpy.CONFIG.write()
            logger.info("Tautulli PlexTV :: Updated Plex.tv token for Tautulli.")
            return token 
Example #5
Source File: plextv.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_plex_account_details(self):
        account_data = self.get_plextv_user_details(output_format='xml')

        try:
            xml_head = account_data.getElementsByTagName('user')
        except Exception as e:
            logger.warn("Tautulli PlexTV :: Unable to parse XML for get_plex_account_details: %s." % e)
            return None

        for a in xml_head:
            account_details = {"user_id": helpers.get_xml_attr(a, 'id'),
                               "username": helpers.get_xml_attr(a, 'username'),
                               "thumb": helpers.get_xml_attr(a, 'thumb'),
                               "email": helpers.get_xml_attr(a, 'email'),
                               "is_home_user": helpers.get_xml_attr(a, 'home'),
                               "is_restricted": helpers.get_xml_attr(a, 'restricted'),
                               "filter_all": helpers.get_xml_attr(a, 'filterAll'),
                               "filter_movies": helpers.get_xml_attr(a, 'filterMovies'),
                               "filter_tv": helpers.get_xml_attr(a, 'filterTelevision'),
                               "filter_music": helpers.get_xml_attr(a, 'filterMusic'),
                               "filter_photos": helpers.get_xml_attr(a, 'filterPhotos'),
                               "user_token": helpers.get_xml_attr(a, 'authToken')
                               }
            return account_details 
Example #6
Source File: helpers.py    From PyInstaLive with MIT License 6 votes vote down vote up
def generate_json_segments():
    while True:
        pil.livestream_obj['delay'] = (int(pil.epochtime) - pil.livestream_obj['published_time'])
        if 'initial_buffered_duration' not in pil.livestream_obj and pil.broadcast_downloader.initial_buffered_duration:
            pil.livestream_obj['initial_buffered_duration'] = pil.broadcast_downloader.initial_buffered_duration
        pil.livestream_obj['segments'] = pil.broadcast_downloader.segment_meta
        try:
            with open(pil.live_folder_path + ".json", 'w') as json_file:
                json.dump(pil.livestream_obj, json_file, indent=2)
            if not pil.broadcast_downloader.stream_id:
                pil.broadcast_downloader.stream_id = pil.livestream_obj['id']
            #check_if_guesting()
            if pil.kill_segment_thread:
                break
            else:
                time.sleep(2.5)
        except Exception as e:
            logger.warn(str(e)) 
Example #7
Source File: plextv.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_server_times(self):
        servers = self.get_plextv_server_list(output_format='xml')
        server_times = {}

        try:
            xml_head = servers.getElementsByTagName('Server')
        except Exception as e:
            logger.warn("Tautulli PlexTV :: Unable to parse XML for get_server_times: %s." % e)
            return {}

        for a in xml_head:
            if helpers.get_xml_attr(a, 'machineIdentifier') == plexpy.CONFIG.PMS_IDENTIFIER:
                server_times = {"created_at": helpers.get_xml_attr(a, 'createdAt'),
                                "updated_at": helpers.get_xml_attr(a, 'updatedAt'),
                                "version": helpers.get_xml_attr(a, 'version')
                                }
                break

        return server_times 
Example #8
Source File: common.py    From ns4_chatbot with Apache License 2.0 6 votes vote down vote up
def short_url(apiUrl):
    try:
        logger.debug("将长URL[%s]转化成短URL",apiUrl)
        target_url = urllib.quote(str(apiUrl))
        url = "http://suo.im/api.php?format=json&url=" + target_url
        logger.debug("调用短URL生成[%s]", apiUrl)
        request = urllib2.Request(url)
        response = urllib2.urlopen(request,timeout=3)

        result_dict = json.loads(response.read())

        if response.getcode() != 200:
            logger.warn("调用短URL服务失败:%s", result_dict["err"])
            return None

        logger.debug("调用短URL服务返回结果:%s", result_dict["url"])

        return urllib.unquote(result_dict["url"])

    except Exception as e:
        logger.warn("调用短URL服务[%s],发生错误[%s]", apiUrl, str(e))
        return None 
Example #9
Source File: plextv.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_token(self):
        plextv_response = self.get_plex_auth(output_format='xml')

        if plextv_response:
            try:
                xml_head = plextv_response.getElementsByTagName('user')
                if xml_head:
                    user = {'auth_token': xml_head[0].getAttribute('authToken'),
                            'user_id': xml_head[0].getAttribute('id')
                            }
                else:
                    logger.warn("Tautulli PlexTV :: Could not get Plex authentication token.")
            except Exception as e:
                logger.warn("Tautulli PlexTV :: Unable to parse XML for get_token: %s." % e)
                return None

            return user
        else:
            return None 
Example #10
Source File: pmsconnect.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_server_identity(self):
        """
        Return the local machine identity.

        Output: dict
        """
        identity = self.get_local_server_identity(output_format='xml')

        try:
            xml_head = identity.getElementsByTagName('MediaContainer')
        except Exception as e:
            logger.warn("Tautulli Pmsconnect :: Unable to parse XML for get_local_server_identity: %s." % e)
            return {}

        server_identity = {}
        for a in xml_head:
            server_identity = {"machine_identifier": helpers.get_xml_attr(a, 'machineIdentifier'),
                               "version": helpers.get_xml_attr(a, 'version')
                               }

        return server_identity 
Example #11
Source File: __init__.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def check_folder_writable(folder, fallback, name):
    if not folder:
        folder = fallback

    if not os.path.exists(folder):
        try:
            os.makedirs(folder)
        except OSError as e:
            logger.error("Could not create %s dir '%s': %s" % (name, folder, e))
            if fallback and folder != fallback:
                logger.warn("Falling back to %s dir '%s'" % (name, fallback))
                return check_folder_writable(None, fallback, name)
            else:
                return folder, None

    if not os.access(folder, os.W_OK):
        logger.error("Cannot write to %s dir '%s'" % (name, folder))
        if fallback and folder != fallback:
            logger.warn("Falling back to %s dir '%s'" % (name, fallback))
            return check_folder_writable(None, fallback, name)
        else:
            return folder, False

    return folder, True 
Example #12
Source File: __init__.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def analytics_event(category, action, label=None, value=None, **kwargs):
    data = {'category': category, 'action': action}

    if label is not None:
        data['label'] = label

    if value is not None:
        data['value'] = value

    if kwargs:
        data.update(kwargs)

    if TRACKER:
        try:
            TRACKER.send('event', data)
        except Exception as e:
            logger.warn("Failed to send analytics event for category '%s', action '%s': %s" % (category, action, e)) 
Example #13
Source File: users.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_user_names(self, kwargs=None):
        monitor_db = database.MonitorDatabase()

        user_cond = ''
        if session.get_session_user_id():
            user_cond = 'AND user_id = %s ' % session.get_session_user_id()

        try:
            query = 'SELECT user_id, ' \
                    '(CASE WHEN users.friendly_name IS NULL OR TRIM(users.friendly_name) = "" \
                    THEN users.username ELSE users.friendly_name END) AS friendly_name ' \
                    'FROM users ' \
                    'WHERE deleted_user = 0 %s' % user_cond

            result = monitor_db.select(query)
        except Exception as e:
            logger.warn("Tautulli Users :: Unable to execute database query for get_user_names: %s." % e)
            return None

        return session.friendly_name_to_username(result) 
Example #14
Source File: users.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def set_user_login(self, user_id=None, user=None, user_group=None, ip_address=None, host=None, user_agent=None, success=0):

        if user_id is None or str(user_id).isdigit():
            monitor_db = database.MonitorDatabase()

            keys = {'timestamp': helpers.timestamp(),
                    'user_id': user_id}

            values = {'user': user,
                      'user_group': user_group,
                      'ip_address': ip_address,
                      'host': host,
                      'user_agent': user_agent,
                      'success': success}

            try:
                monitor_db.upsert(table_name='user_login', key_dict=keys, value_dict=values)
            except Exception as e:
                logger.warn("Tautulli Users :: Unable to execute database query for set_login_log: %s." % e) 
Example #15
Source File: notifiers.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def get_devices(self):
        db = database.MonitorDatabase()

        try:
            query = 'SELECT * FROM mobile_devices WHERE official = 1'
            result = db.select(query=query)
        except Exception as e:
            logger.warn("Tautulli Notifiers :: Unable to retrieve Android app devices list: %s." % e)
            return {'': ''}

        devices = {}
        for device in result:
            if device['friendly_name']:
                devices[device['device_id']] = device['friendly_name']
            else:
                devices[device['device_id']] = device['device_name']

        return devices 
Example #16
Source File: newsletters.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def send(self):
        self.newsletter = self.generate_newsletter()

        if self.template_error:
            logger.error("Tautulli Newsletters :: %s newsletter failed to render template. Newsletter not sent." % self.NAME)
            return False

        if not self._has_data():
            logger.warn("Tautulli Newsletters :: %s newsletter has no data. Newsletter not sent." % self.NAME)
            return False

        self._save()

        if self.config['save_only']:
            return True

        return self._send() 
Example #17
Source File: mobile_app.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def set_mobile_device_config(mobile_device_id=None, **kwargs):
    if str(mobile_device_id).isdigit():
        mobile_device_id = int(mobile_device_id)
    else:
        logger.error("Tautulli MobileApp :: Unable to set exisiting mobile device: invalid mobile_device_id %s." % mobile_device_id)
        return False

    keys = {'id': mobile_device_id}
    values = {'friendly_name': kwargs.get('friendly_name', '')}

    db = database.MonitorDatabase()
    try:
        db.upsert(table_name='mobile_devices', key_dict=keys, value_dict=values)
        logger.info("Tautulli MobileApp :: Updated mobile device agent: mobile_device_id %s." % mobile_device_id)
        return True
    except Exception as e:
        logger.warn("Tautulli MobileApp :: Unable to update mobile device: %s." % e)
        return False 
Example #18
Source File: mobile_app.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def add_mobile_device(device_id=None, device_name=None, device_token=None, friendly_name=None):
    db = database.MonitorDatabase()

    keys = {'device_id': device_id}
    values = {'device_name': device_name,
              'device_token': device_token,
              'official': validate_device_id(device_id=device_id)}

    if friendly_name:
        values['friendly_name'] = friendly_name

    try:
        result = db.upsert(table_name='mobile_devices', key_dict=keys, value_dict=values)
    except Exception as e:
        logger.warn("Tautulli MobileApp :: Failed to register mobile device in the database: %s." % e)
        return

    if result == 'insert':
        logger.info("Tautulli MobileApp :: Registered mobile device '%s' in the database." % device_name)
    else:
        logger.debug("Tautulli MobileApp :: Re-registered mobile device '%s' in the database." % device_name)

    return True 
Example #19
Source File: datafactory.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def set_img_info(self, img_hash=None, img_title=None, img_url=None, delete_hash=None, service=None):
        monitor_db = database.MonitorDatabase()

        keys = {'img_hash': img_hash}

        if service == 'imgur':
            table = 'imgur_lookup'
            values = {'imgur_title': img_title,
                      'imgur_url': img_url,
                      'delete_hash': delete_hash}
        elif service == 'cloudinary':
            table = 'cloudinary_lookup'
            values = {'cloudinary_title': img_title,
                      'cloudinary_url': img_url}
        else:
            logger.warn("Tautulli DataFactory :: Unable to execute database query for set_img_info: "
                        "service not provided.")
            return

        monitor_db.upsert(table, key_dict=keys, value_dict=values) 
Example #20
Source File: datafactory.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def set_recently_added_item(self, rating_key=''):
        monitor_db = database.MonitorDatabase()

        pms_connect = pmsconnect.PmsConnect()
        metadata = pms_connect.get_metadata_details(rating_key)

        keys = {'rating_key': metadata['rating_key']}

        values = {'added_at': metadata['added_at'],
                  'section_id': metadata['section_id'],
                  'parent_rating_key': metadata['parent_rating_key'],
                  'grandparent_rating_key': metadata['grandparent_rating_key'],
                  'media_type': metadata['media_type'],
                  'media_info': json.dumps(metadata['media_info'])
                  }

        try:
            monitor_db.upsert(table_name='recently_added', key_dict=keys, value_dict=values)
        except Exception as e:
            logger.warn("Tautulli DataFactory :: Unable to execute database query for set_recently_added_item: %s." % e)
            return False

        return True 
Example #21
Source File: libraries.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def undelete(self, section_id=None, section_name=None):
        monitor_db = database.MonitorDatabase()

        try:
            if section_id and section_id.isdigit():
                query = 'SELECT * FROM library_sections WHERE section_id = ?'
                result = monitor_db.select(query=query, args=[section_id])
                if result:
                    logger.info("Tautulli Libraries :: Re-adding library with id %s to database." % section_id)
                    monitor_db.action('UPDATE library_sections '
                                      'SET deleted_section = 0, keep_history = 1, do_notify = 1, do_notify_created = 1 '
                                      'WHERE section_id = ?',
                                      [section_id])
                    return True
                else:
                    return False

            elif section_name:
                query = 'SELECT * FROM library_sections WHERE section_name = ?'
                result = monitor_db.select(query=query, args=[section_name])
                if result:
                    logger.info("Tautulli Libraries :: Re-adding library with name %s to database." % section_name)
                    monitor_db.action('UPDATE library_sections '
                                      'SET deleted_section = 0, keep_history = 1, do_notify = 1, do_notify_created = 1 '
                                      'WHERE section_name = ?',
                                      [section_name])
                    return True
                else:
                    return False

        except Exception as e:
            logger.warn("Tautulli Libraries :: Unable to execute database query for undelete: %s." % e) 
Example #22
Source File: database.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def action(self, query, args=None, return_last_id=False):
        if query is None:
            return

        with db_lock:
            sql_result = None
            attempts = 0

            while attempts < 5:
                try:
                    with self.connection as c:
                        if args is None:
                            sql_result = c.execute(query)
                        else:
                            sql_result = c.execute(query, args)
                    # Our transaction was successful, leave the loop
                    break

                except sqlite3.OperationalError as e:
                    e = str(e)
                    if "unable to open database file" in e or "database is locked" in e:
                        logger.warn("Tautulli Database :: Database Error: %s", e)
                        attempts += 1
                        time.sleep(1)
                    else:
                        logger.error("Tautulli Database :: Database error: %s", e)
                        raise

                except sqlite3.DatabaseError as e:
                    logger.error("Tautulli Database :: Fatal Error executing %s :: %s", query, e)
                    raise

            return sql_result 
Example #23
Source File: web_socket.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def start_thread():
    try:
        # Check for any existing sessions on start up
        activity_pinger.check_active_sessions(ws_request=True)
    except Exception as e:
        logger.error("Tautulli WebSocket :: Failed to check for active sessions: %s." % e)
        logger.warn("Tautulli WebSocket :: Attempt to fix by flushing temporary sessions...")
        database.delete_sessions()

    # Start the websocket listener on it's own thread
    thread = threading.Thread(target=run)
    thread.daemon = True
    thread.start() 
Example #24
Source File: plextv.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def get_devices_list(self):
        devices = self.get_plextv_devices_list(output_format='xml')

        try:
            xml_head = devices.getElementsByTagName('Device')
        except Exception as e:
            logger.warn("Tautulli PlexTV :: Unable to parse XML for get_devices_list: %s." % e)
            return []

        devices_list = []
        for a in xml_head:
            device = {"device_name": helpers.get_xml_attr(a, 'name'),
                      "product": helpers.get_xml_attr(a, 'product'),
                      "product_version": helpers.get_xml_attr(a, 'productVersion'),
                      "platform": helpers.get_xml_attr(a, 'platform'),
                      "platform_version": helpers.get_xml_attr(a, 'platformVersion'),
                      "device": helpers.get_xml_attr(a, 'device'),
                      "model": helpers.get_xml_attr(a, 'model'),
                      "vendor": helpers.get_xml_attr(a, 'vendor'),
                      "provides": helpers.get_xml_attr(a, 'provides'),
                      "device_identifier": helpers.get_xml_attr(a, 'clientIdentifier'),
                      "device_id": helpers.get_xml_attr(a, 'id'),
                      "token": helpers.get_xml_attr(a, 'token')
                      }
            devices_list.append(device)

        return devices_list 
Example #25
Source File: newsletters.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def add_newsletter_config(agent_id=None, **kwargs):
    if str(agent_id).isdigit():
        agent_id = int(agent_id)
    else:
        logger.error("Tautulli Newsletters :: Unable to add new newsletter: invalid agent_id %s."
                     % agent_id)
        return False

    agent = next((a for a in available_newsletter_agents() if a['id'] == agent_id), None)

    if not agent:
        logger.error("Tautulli Newsletters :: Unable to retrieve new newsletter agent: invalid agent_id %s."
                     % agent_id)
        return False

    agent_class = get_agent_class(agent_id=agent['id'])

    keys = {'id': None}
    values = {'agent_id': agent['id'],
              'agent_name': agent['name'],
              'agent_label': agent['label'],
              'id_name': '',
              'friendly_name': '',
              'newsletter_config': json.dumps(agent_class.config),
              'email_config': json.dumps(agent_class.email_config),
              'subject': agent_class.subject,
              'body': agent_class.body,
              'message': agent_class.message
              }

    db = database.MonitorDatabase()
    try:
        db.upsert(table_name='newsletters', key_dict=keys, value_dict=values)
        newsletter_id = db.last_insert_id()
        logger.info("Tautulli Newsletters :: Added new newsletter agent: %s (newsletter_id %s)."
                    % (agent['label'], newsletter_id))
        blacklist_logger()
        return newsletter_id
    except Exception as e:
        logger.warn("Tautulli Newsletters :: Unable to add newsletter agent: %s." % e)
        return False 
Example #26
Source File: plextv.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def get_geoip_lookup(self, ip_address=''):
        if not ip_address or not helpers.is_valid_ip(ip_address):
            return

        geoip_data = self.get_plextv_geoip(ip_address=ip_address, output_format='xml')

        try:
            xml_head = geoip_data.getElementsByTagName('location')
        except Exception as e:
            logger.warn(u"Tautulli PlexTV :: Unable to parse XML for get_geoip_lookup: %s." % e)
            return None

        for a in xml_head:
            coordinates = helpers.get_xml_attr(a, 'coordinates').split(',')
            latitude = longitude = None
            if len(coordinates) == 2:
                latitude, longitude = [helpers.cast_to_float(c) for c in coordinates]

            geo_info = {"code": helpers.get_xml_attr(a, 'code') or None,
                        "country": helpers.get_xml_attr(a, 'country') or None,
                        "region": helpers.get_xml_attr(a, 'subdivisions') or None,
                        "city": helpers.get_xml_attr(a, 'city') or None,
                        "postal_code": helpers.get_xml_attr(a, 'postal_code') or None,
                        "timezone": helpers.get_xml_attr(a, 'time_zone') or None,
                        "latitude": latitude,
                        "longitude": longitude,
                        "continent": None,  # keep for backwards compatibility with GeoLite2
                        "accuracy": None   # keep for backwards compatibility with GeoLite2
                        }

            return geo_info 
Example #27
Source File: activity_handler.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def force_stop_stream(session_key, title, user):
    ap = activity_processor.ActivityProcessor()
    session = ap.get_session_by_key(session_key=session_key)

    row_id = ap.write_session_history(session=session)

    if row_id:
        # If session is written to the database successfully, remove the session from the session table
        logger.info("Tautulli ActivityHandler :: Removing stale stream with sessionKey %s ratingKey %s from session queue"
                    % (session['session_key'], session['rating_key']))
        ap.delete_session(row_id=row_id)
        delete_metadata_cache(session_key)

    else:
        session['write_attempts'] += 1

        if session['write_attempts'] < plexpy.CONFIG.SESSION_DB_WRITE_ATTEMPTS:
            logger.warn("Tautulli ActivityHandler :: Failed to write stream with sessionKey %s ratingKey %s to the database. " \
                        "Will try again in 30 seconds. Write attempt %s."
                        % (session['session_key'], session['rating_key'], str(session['write_attempts'])))
            ap.increment_write_attempts(session_key=session_key)

            # Reschedule for 30 seconds later
            schedule_callback('session_key-{}'.format(session_key), func=force_stop_stream,
                              args=[session_key, session['full_title'], session['user']], seconds=30)

        else:
            logger.warn("Tautulli ActivityHandler :: Failed to write stream with sessionKey %s ratingKey %s to the database. " \
                        "Removing session from the database. Write attempt %s."
                        % (session['session_key'], session['rating_key'], str(session['write_attempts'])))
            logger.info("Tautulli ActivityHandler :: Removing stale stream with sessionKey %s ratingKey %s from session queue"
                        % (session['session_key'], session['rating_key']))
            ap.delete_session(session_key=session_key)
            delete_metadata_cache(session_key) 
Example #28
Source File: datafactory.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def get_recently_added_item(self, rating_key=''):
        monitor_db = database.MonitorDatabase()

        if rating_key:
            try:
                query = 'SELECT * FROM recently_added WHERE rating_key = ?'
                result = monitor_db.select(query=query, args=[rating_key])
            except Exception as e:
                logger.warn("Tautulli DataFactory :: Unable to execute database query for get_recently_added_item: %s." % e)
                return []
        else:
            return []

        return result 
Example #29
Source File: helpers.py    From appetite with Apache License 2.0 5 votes vote down vote up
def get_enchanced_boot_order(boot_order, host_classes):
    """Get the boot order with all classes and structured for use

    The boot_order only shows strict hosts ordering, if any are
    missing they are added to the end of the list.

    Returns: [[host_classes]]
    """
    remaining_hosts = list(host_classes)
    eboot_order = []
    boot_order_list = boot_order.split(" ") if isinstance(boot_order, basestring) else boot_order

    for boot_group in boot_order_list:
        boot_group_list = boot_group.split(",")

        # After all defined host are removed, what is left
        # is put into the last array entry
        for boot_class in boot_group_list:
            if boot_class not in remaining_hosts:
                logger.warn("Boot Order class does not exists in host classes",
                            boot_class=boot_class)
                continue
            remaining_hosts.remove(boot_class)

        eboot_order.append(boot_group_list)
    eboot_order.append(remaining_hosts)

    return eboot_order 
Example #30
Source File: datafactory.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def get_user_devices(self, user_id=''):
        monitor_db = database.MonitorDatabase()

        if user_id:
            try:
                query = 'SELECT machine_id FROM session_history WHERE user_id = ? GROUP BY machine_id'
                result = monitor_db.select(query=query, args=[user_id])
            except Exception as e:
                logger.warn("Tautulli DataFactory :: Unable to execute database query for get_user_devices: %s." % e)
                return []
        else:
            return []

        return [d['machine_id'] for d in result]