Example #1
0
def couchpotato_api(method, params=None, use_json=True, dev=False):
    username = get_setting_value('couchpotato_user')
    password = get_setting_value('couchpotato_password')

    if params:
        params = '/?%s' % params
    else:
        params = '/'

    params = (params).replace(' ', '%20')
    url = '%s/%s%s' % (couchpotato_url(), method, params)
    req = urllib2.Request(url)

    if username and password:
        base64string = base64.encodestring(
            '%s:%s' % (username, password)).replace('\n', '')
        req.add_header("Authorization", "Basic %s" % base64string)

    data = urllib2.urlopen(req).read()
    if dev:
        print url
        print data
    if use_json:
        data = json.JSONDecoder().decode(data)
    return data
Example #2
0
def loginToPlex(username=None, password=None):
    global user
    if username is None:
        if not get_setting_value('myPlex_username') or not get_setting_value(
                'myPlex_password'):
            logger.log('Plex :: Missing Plex Credentials in db', 'INFO')
            return False
        else:
            username = get_setting_value('myPlex_username')
            password = get_setting_value('myPlex_password')

    logger.log('Plex :: Logging into plex.tv', 'INFO')
    try:
        user = User(username, password)
        user, token = user.MyPlexSignIn()

        if user is '':
            logger.log('Plex :: Log in FAILED', 'ERROR')
            return False  # failed to sign in

        setting = get_setting('myPlex_token')
        if not setting:
            setting = Setting('myPlex_token')

        setting.value = token
        db_session.add(setting)
        db_session.commit()
        logger.log('Plex :: Log in successful', 'INFO')
        return True
    except:
        logger.log('Plex :: Log in FAILED', 'ERROR')
        return False
Example #3
0
def xhr_trakt_trending(type=None):
    if not type:
        type = get_setting_value('trakt_default_media')

    limit = int(get_setting_value('trakt_trending_limit'))
    logger.log('TRAKT :: Fetching trending %s' % type, 'INFO')

    url = 'http://api.trakt.tv/%s/trending.json/%s' % (type, trakt_apikey())
    try:
        trakt = trak_api(url)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    if len(trakt) > limit:
        trakt = trakt[:limit]

    for item in trakt:
        item['images']['poster'] = cache_image(item['images']['poster'], type)

    while THREADS:
        time.sleep(1)

    return render_template(
        'traktplus/trakt-trending.html',
        trending=trakt,
        type=type.title(),
        title='Trending',
    )
Example #4
0
def xhr_trakt_trending(type=None, mobile=False):
    if not type:
        type = get_setting_value('trakt_default_media')

    limit = int(get_setting_value('trakt_trending_limit'))
    logger.log('TRAKT :: Fetching trending %s' % type, 'INFO')

    url = 'http://api.trakt.tv/%s/trending.json/%s' % (type, trakt_apikey())
    try:
        trakt = trak_api(url)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    if mobile:
        return trakt

    if len(trakt) > limit:
        trakt = trakt[:limit]

    for item in trakt:
        item['images']['poster'] = cache_image(item['images']['poster'], type)

    while THREADS:
        time.sleep(1)

    return render_template('traktplus/trakt-trending.html',
        trending=trakt,
        type=type.title(),
        title='Trending',
    )
Example #5
0
def loginToPlex(username=None, password=None):
    global user
    if username is None:
        if not get_setting_value('myPlex_username') or not get_setting_value('myPlex_password'):
            logger.log('Plex :: Missing Plex Credentials in db', 'INFO')
            return False
        else:
            username = get_setting_value('myPlex_username')
            password = get_setting_value('myPlex_password')

    logger.log('Plex :: Logging into plex.tv', 'INFO')
    try:
        user = User(username, password)
        user, token = user.MyPlexSignIn()

        if user is '':
            logger.log('Plex :: Log in FAILED', 'ERROR')
            return False # failed to sign in

        setting = get_setting('myPlex_token')
        if not setting:
            setting = Setting('myPlex_token')

        setting.value = token
        db_session.add(setting)
        db_session.commit()
        logger.log('Plex :: Log in successful', 'INFO')
        return True
    except:
        logger.log('Plex :: Log in FAILED', 'ERROR')
        return False
Example #6
0
def xhr_performance():
    global processSchedule
    global processList
    
    info = {}
    settings = {}
    
    if (processSchedule == None):
        logger.log("Process List SCHEDULE Job is Starting", 'INFO')
        SCHEDULE.add_interval_job(get_process_performance, seconds=5)
        processSchedule = 1
    
    #Get Memory Status and NetIO Status
    physicalMemory = psutil.virtual_memory()
    swapMemory = psutil.swap_memory()
    netio = psutil.net_io_counters(False)
    
    #Get settings
    settings['show_cpu_utilization'] = get_setting_value('show_cpu_utilization')
    settings['show_network_utilization'] = get_setting_value('show_network_utilization')
    settings['show_process_utilization'] = get_setting_value('show_process_utilization')
    
    #Get Memory Stats
    info['usedPhyMemory'] = convert_bytes(physicalMemory.used)
    info['availPhyMemory'] = convert_bytes(physicalMemory.free)
    info['totalPhyMemory'] = convert_bytes(physicalMemory.total)
    info['usedSwapMemory'] = convert_bytes(swapMemory.used)
    info['availSwapMemory'] = convert_bytes(swapMemory.free)
    info['totalSwapMemory'] = convert_bytes(swapMemory.total)
    
    #Display Network Status
    if (settings['show_network_utilization'] == '1'):
        info['bytesSent'] = convert_bytes(netio.bytes_sent)
        info['bytesSentRate'] = updateSentRate(netio.bytes_sent)
        info['bytesRecv'] = convert_bytes(netio.bytes_recv)
        info['bytesRecvRate'] = updateDownloadRate(netio.bytes_recv)
        info['packetSent'] = convert_bytes(netio.packets_sent).replace('B', '')
        info['packetRecv'] = convert_bytes(netio.packets_recv).replace('B', '')
        info['errin'] = netio.errin
        info['errout'] = netio.errout
    
    # must have some delay to prevent errors
    if (settings['show_cpu_utilization'] == '1'):
        i = 0
        cpuList = [ ]
        cpuPerCore = namedtuple('CPUPerCore', "index CPUpercentage")
        for item in psutil.cpu_percent(0.1, True):
            cpuList.append(cpuPerCore(index=i, CPUpercentage=item))
            i += 1
        info['totalCPUCol'] = i     #used for html format table
        info['cpuPercent'] = cpuList
        info['cpuOverall'] = psutil.cpu_percent(0.1, False)
        info['cpuTimes'] = psutil.cpu_times_percent(0.1, False)
    
    if (settings['show_process_utilization'] == '1'):
        info['processPerformance'] = processList
    
    # Render the template for our module
    return render_template('performance.html', result = info, settings = settings)
def login_string():
    try:
        login = '******' % (get_setting_value('couchpotato_user'), get_setting_value('couchpotato_password'))

    except:
        login = ''

    return login
def headphones_url():
    port = get_setting_value('headphones_port')
    url_base = get_setting_value('headphones_host')

    if port:
        url_base = '%s:%s' % (url_base, port)

    return headphones_http() + url_base
Example #9
0
def xbmc_sort(media_type):
    '''
    Return sort values for media type.
    '''
    sort = {}
    sort['method'] = get_setting_value('xbmc_' + media_type + '_sort')
    sort['ignorearticle'] = get_setting_value('library_ignore_the') == '1'
    sort['order'] = get_setting_value('xbmc_' + media_type + '_sort_order')

    return sort
Example #10
0
def xbmc_sort(media_type):
    """
    Return sort values for media type.
    """
    sort = {}
    sort["method"] = get_setting_value("xbmc_" + media_type + "_sort")
    sort["ignorearticle"] = get_setting_value("library_ignore_the") == "1"
    sort["order"] = get_setting_value("xbmc_" + media_type + "_sort_order")

    return sort
Example #11
0
def xbmc_sort(media_type):
    '''
    Return sort values for media type.
    '''
    sort = {}
    sort['method'] = get_setting_value('xbmc_'+media_type+'_sort')
    sort['ignorearticle'] = get_setting_value('library_ignore_the') == '1'
    sort['order'] = get_setting_value('xbmc_'+media_type+'_sort_order')

    return sort
def couchpotato_url_no_api():
    port = get_setting_value('couchpotato_port')
    url_base = get_setting_value('couchpotato_ip')
    
    if port:
        url_base = '%s:%s' % ( url_base, port )
    
    if login_string():
        return couchpotato_http() + login_string() + url_base
        
    return couchpotato_http() + url_base
Example #13
0
def couchpotato_url_no_api():
    port = get_setting_value("couchpotato_port")
    url_base = get_setting_value("couchpotato_ip")
    webroot = get_setting_value("couchpotato_webroot")

    if port:
        url_base = "%s:%s" % (url_base, port)

    if webroot:
        url_base = "%s/%s" % (url_base, webroot)

    return couchpotato_http() + url_base
Example #14
0
def headphones_url():
    port = get_setting_value("headphones_port")
    url_base = get_setting_value("headphones_host")
    webroot = get_setting_value("headphones_webroot")

    if port:
        url_base = "%s:%s" % (url_base, port)

    if webroot:
        url_base = "%s/%s" % (url_base, webroot)

    return headphones_http() + url_base
Example #15
0
def couchpotato_url_no_api():
    port = get_setting_value('couchpotato_port')
    url_base = get_setting_value('couchpotato_ip')
    webroot = get_setting_value('couchpotato_webroot')

    if port:
        url_base = '%s:%s' % (url_base, port)

    if webroot:
        url_base = '%s/%s' % (url_base, webroot)

    return couchpotato_http() + url_base
Example #16
0
def headphones_url():
    port = get_setting_value('headphones_port')
    url_base = get_setting_value('headphones_host')
    webroot = get_setting_value('headphones_webroot')

    if port:
        url_base = '%s:%s' % (url_base, port)

    if webroot:
        url_base = '%s/%s' % (url_base, webroot)

    return headphones_http() + url_base
Example #17
0
def couchpotato_url_no_api():
    port = get_setting_value('couchpotato_port')
    url_base = get_setting_value('couchpotato_ip')
    webroot = get_setting_value('couchpotato_webroot')

    if port:
        url_base = '%s:%s' % (url_base, port)

    if webroot:
        url_base = '%s/%s' % (url_base, webroot)

    return couchpotato_http() + url_base
Example #18
0
def trak_api(url, params={}):
    username = get_setting_value('trakt_username')
    password = hashlib.sha1(get_setting_value('trakt_password')).hexdigest()

    params = json.JSONEncoder().encode(params)
    request = urllib2.Request(url, params)
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)

    response = urllib2.urlopen(request)
    response = response.read()

    return json.JSONDecoder().decode(response)
Example #19
0
def couchpotato_proxy(url):
    username = get_setting_value("couchpotato_user")
    password = get_setting_value("couchpotato_password")

    url = "%s/file.cache/%s" % (couchpotato_url(), url)
    req = urllib2.Request(url)

    if username and password:
        base64string = base64.encodestring("%s:%s" % (username, password)).replace("\n", "")
        req.add_header("Authorization", "Basic %s" % base64string)

    img = StringIO.StringIO(urllib2.urlopen(req).read())
    logger.log("CouchPotato :: Fetching image from %s" % (url), "DEBUG")
    return send_file(img, mimetype="image/jpeg")
Example #20
0
def couchpotato_proxy(url):
    username = get_setting_value('couchpotato_user')
    password = get_setting_value('couchpotato_password')

    url = '%s/file.cache/%s' % (couchpotato_url(), url)
    req = urllib2.Request(url)

    if username and password:
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        req.add_header("Authorization", "Basic %s" % base64string)

    img = StringIO.StringIO(urllib2.urlopen(req).read())
    logger.log('CouchPotato :: Fetching image from %s' % (url), 'DEBUG')
    return send_file(img, mimetype='image/jpeg')
Example #21
0
def couchpotato_proxy(url):
    username = get_setting_value('couchpotato_user')
    password = get_setting_value('couchpotato_password')

    url = '%s/file.cache/%s' % (couchpotato_url(), url)
    request = urllib2.Request(url)

    if username and password:
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

    img = StringIO.StringIO(urllib2.urlopen(request).read())
    logger.log('CouchPotato :: Fetching image from %s' % (url), 'DEBUG')
    return send_file(img, mimetype='image/jpeg')
Example #22
0
def xbmc_get_movies(xbmc):
    logger.log('LIBRARY :: Retrieving movies', 'INFO')

    sort = xbmc_sort('movies')
    properties = ['playcount', 'thumbnail', 'year', 'rating', 'set']

    movies = xbmc.VideoLibrary.GetMovies(sort=sort, properties=properties)['movies']

    if get_setting_value('xbmc_movies_view_sets') == '1':
        movies = xbmc_movies_with_sets(xbmc, movies)

    if get_setting_value('xbmc_movies_hide_watched') == '1':
        movies = [x for x in movies if not x['playcount']]

    return movies
Example #23
0
def xbmc_get_movies(xbmc):
    logger.log('LIBRARY :: Retrieving movies', 'INFO')

    sort = xbmc_sort('movies')
    properties = ['playcount', 'thumbnail', 'year', 'rating', 'set']

    movies = xbmc.VideoLibrary.GetMovies(sort=sort, properties=properties)['movies']

    if get_setting_value('xbmc_movies_view_sets') == '1':
        movies = xbmc_movies_with_sets(xbmc, movies)

    if get_setting_value('xbmc_movies_hide_watched') == '1':
        movies = [x for x in movies if not x['playcount']]

    return movies
Example #24
0
def xbmc_get_movies(xbmc):
    logger.log("LIBRARY :: Retrieving movies", "INFO")

    sort = xbmc_sort("movies")
    properties = ["playcount", "thumbnail", "year", "rating", "set"]

    movies = xbmc.VideoLibrary.GetMovies(sort=sort, properties=properties)["movies"]

    if get_setting_value("xbmc_movies_view_sets") == "1":
        movies = xbmc_movies_with_sets(xbmc, movies)

    if get_setting_value("xbmc_movies_hide_watched") == "1":
        movies = [x for x in movies if not x["playcount"]]

    return movies
Example #25
0
def xbmc_get_episodes(xbmc, tvshowid, season):
    logger.log("LIBRARY :: Retrieving episodes for tvshowid: %s season: %s" % (tvshowid, season), "INFO")
    version = xbmc.Application.GetProperties(properties=["version"])["version"]["major"]
    params = {"sort": xbmc_sort("episodes")}

    if version < 12 and params["sort"]["method"] in ["rating", "playcount", "random"]:  # Eden
        logger.log(
            'LIBRARY :: Sort method "%s" is not supported in XBMC Eden. Reverting to "episode"'
            % params["sort"]["method"],
            "INFO",
        )
        change_sort("episodes", "episode")
        params["sort"] = xbmc_sort("episodes")

    params["tvshowid"] = tvshowid
    params["season"] = season
    params["properties"] = [
        "playcount",
        "season",
        "episode",
        "tvshowid",
        "showtitle",
        "thumbnail",
        "firstaired",
        "rating",
    ]

    episodes = xbmc.VideoLibrary.GetEpisodes(**params)["episodes"]

    if get_setting_value("xbmc_episodes_hide_watched") == "1":
        episodes = [x for x in episodes if not x["playcount"]]

    return episodes
Example #26
0
def xhr_trakt_watchlist(user, type=None, mobile=False):
    if not type:
        type = get_setting_value('trakt_default_media')

    logger.log('TRAKT :: Fetching %s\'s %s watchlist' % (user, type), 'INFO')
    url = 'http://api.trakt.tv/user/watchlist/%s.json/%s/%s/' % (
        type, trakt_apikey(), user)

    try:
        trakt = trak_api(url)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    if mobile:
        return trakt

    if trakt == []:
        trakt = [{'empty': True}]

    return render_template(
        'traktplus/trakt-watchlist.html',
        watchlist=trakt,
        type=type.title(),
        user=user,
        title='Watchlist',
    )
Example #27
0
def xhr_couchpotato(status="active"):
    status_string = "status=%s" % status
    template = "couchpotato.html"

    if status is not "active":
        template = "couchpotato/all.html"
    try:
        logger.log('CouchPotato :: Fetching "%s movies" list' % status, "INFO")
        couchpotato = couchpotato_api("movie.list", params=status_string)

    except Exception as e:
        log_exception(e)
        couchpotato = None

    logger.log('CouchPotato :: Fetching "%s movies" list (DONE)' % status, "INFO")
    if status == "wanted" and not type(couchpotato) is list:
        logger.log("CouchPotato :: Wanted movies list is empty", "INFO")
        return cp_search("There are no movies in your wanted list.")

    return render_template(
        template,
        url=couchpotato_url(),
        couchpotato=couchpotato,
        compact_view=get_setting_value("couchpotato_compact") == "1",
    )
Example #28
0
def xbmc_get_seasons(xbmc, tvshowid):
    logger.log('LIBRARY :: Retrieving seasons for tvshowid: %s' % tvshowid,
               'INFO')
    version = xbmc.Application.GetProperties(
        properties=['version'])['version']['major']
    params = {'sort': xbmc_sort('seasons')}

    if version < 12 and params['sort']['method'] in [
            'rating', 'playcount', 'random'
    ]:  #Eden
        logger.log(
            'LIBRARY :: Sort method "%s" is not supported in XBMC Eden. Reverting to "label"'
            % params['sort']['method'], 'INFO')
        change_sort('seasons', 'label')
        params['sort'] = xbmc_sort('seasons')

    params['tvshowid'] = tvshowid
    params['properties'] = [
        'playcount', 'showtitle', 'tvshowid', 'season', 'thumbnail', 'episode'
    ]

    seasons = xbmc.VideoLibrary.GetSeasons(**params)['seasons']

    if get_setting_value('xbmc_seasons_hide_watched') == '1':
        seasons = [x for x in seasons if not x['playcount']]

    #Add episode playcounts to seasons
    for season in seasons:
        episodes = xbmc.VideoLibrary.GetEpisodes(tvshowid=tvshowid,
                                                 season=season['season'],
                                                 properties=['playcount'
                                                             ])['episodes']
        season['unwatched'] = len([x for x in episodes if not x['playcount']])

    return seasons
Example #29
0
def xhr_couchpotato(status='active'):
    profiles = {}
    status_string = 'status=%s' % status
    template = 'couchpotato.html'

    if status is not 'active':
        template = 'couchpotato/all.html'
    try:
        logger.log('CouchPotato :: Fetching "%s movies" list' % status, 'INFO')
        couchpotato = couchpotato_api('movie.list', params=status_string)

    except Exception as e:
        log_exception(e)
        couchpotato = None

    logger.log('CouchPotato :: Fetching "%s movies" list (DONE)' % status, 'INFO')
    if status == 'wanted' and not type(couchpotato) is list:
        logger.log('CouchPotato :: Wanted movies list is empty', 'INFO')
        return cp_search('There are no movies in your wanted list.')

    profiles = couchpotato_api('profile.list')

    for movie in couchpotato['movies']:
        for profile in profiles['list']:
            if profile['_id'] == movie['profile_id']:
                movie['profile_label'] = profile['label']

    return render_template(template,
        url=couchpotato_url(),
        app_link=couchpotato_url_no_api(),
        couchpotato=couchpotato,
        profiles=profiles,
        compact_view=get_setting_value('couchpotato_compact') == '1',
    )
Example #30
0
def xhr_couchpotato(status="active"):
    profiles = {}
    status_string = "status=%s" % status
    template = "couchpotato.html"

    if status is not "active":
        template = "couchpotato/all.html"
    try:
        logger.log('CouchPotato :: Fetching "%s movies" list' % status, "INFO")
        couchpotato = couchpotato_api("movie.list", params=status_string)

    except Exception as e:
        log_exception(e)
        couchpotato = None

    logger.log('CouchPotato :: Fetching "%s movies" list (DONE)' % status, "INFO")
    if status == "wanted" and not type(couchpotato) is list:
        logger.log("CouchPotato :: Wanted movies list is empty", "INFO")
        return cp_search("There are no movies in your wanted list.")

    profiles = couchpotato_api("profile.list")

    for movie in couchpotato["movies"]:
        for profile in profiles["list"]:
            if profile["_id"] == movie["profile_id"]:
                movie["profile_label"] = profile["label"]

    return render_template(
        template,
        url=couchpotato_url(),
        app_link=couchpotato_url_no_api(),
        couchpotato=couchpotato,
        profiles=profiles,
        compact_view=get_setting_value("couchpotato_compact") == "1",
    )
Example #31
0
def xhr_trakt_watchlist(user, type=None, mobile=False):
    if not type:
        type = get_setting_value('trakt_default_media')

    logger.log('TRAKT :: Fetching %s\'s %s watchlist' % (user, type), 'INFO')
    url = 'http://api.trakt.tv/user/watchlist/%s.json/%s/%s/' % (type, trakt_apikey(), user)

    try:
        trakt = trak_api(url)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    if mobile:
        return trakt

    if trakt == []:
        trakt = [{'empty': True}]

    return render_template('traktplus/trakt-watchlist.html',
        watchlist=trakt,
        type=type.title(),
        user=user,
        title='Watchlist',
    )
Example #32
0
def xhr_couchpotato(status=False):
    if status:
        status_string = 'status=%s' % status
        template = 'couchpotato/all.html'
    else:
        status = 'wanted'
        status_string = False
        template = 'couchpotato.html'
    try:
        logger.log('CouchPotato :: Fetching "%s movies" list' % status, 'INFO')
        couchpotato = couchpotato_api('movie.list', params=status_string)
        if couchpotato['success'] and not couchpotato['empty']:
            couchpotato = couchpotato['movies']

    except Exception as e:
        log_exception(e)
        couchpotato = None

    logger.log('CouchPotato :: Fetching "%s movies" list (DONE)' % status,
               'INFO')

    if status == 'wanted' and not type(couchpotato) is list:
        logger.log('CouchPotato :: Wanted movies list is empty', 'INFO')
        return cp_search('There are no movies in your wanted list.')

    return render_template(
        template,
        url=couchpotato_url(),
        couchpotato=couchpotato,
        compact_view=get_setting_value('couchpotato_compact') == '1',
    )
Example #33
0
def xhr_trakt_recommendations(type=None):
    if not type:
        type = get_setting_value('trakt_default_media')

    logger.log('TRAKT :: Fetching %s recommendations' % type, 'INFO')

    url = 'http://api.trakt.tv/recommendations/%s/%s' % (type, trakt_apikey())

    params = {'hide_collected': True, 'hide_watchlisted': True}
    try:
        recommendations = trak_api(url, params)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    random.shuffle(recommendations)

    for item in recommendations:
        item['poster'] = cache_image(item['images']['poster'], type)

    while THREADS:
        time.sleep(1)

    return render_template(
        'traktplus/trakt-recommendations.html',
        type=type.title(),
        recommendations=recommendations,
        title='Recommendations',
    )
Example #34
0
def get_process_performance():
    ''' Gets the list of processes that are using the most CPU and RAM on the system '''
    global processList
    global enableThread
       
    #Create anmed tuple to store list
    Process = namedtuple('Process', "pid name cpu_percent memory_percent")
      
    Plist = [ ]

    #Create a list of all processes with info about them
    for pid in psutil.process_iter():
        try:
            #Do we have a process that has 'python'
            if ('python' in pid.name.lower()):
                #get python script name
                Plist.append(Process(pid=pid.pid, name=extractPythonScriptName(pid), cpu_percent=round(pid.get_cpu_percent(), 3), memory_percent=round(pid.get_memory_percent(), 2)))
            else:
                #Use generic name
                Plist.append(Process(pid=pid.pid, name=pid.name, cpu_percent=round(pid.get_cpu_percent(), 3), memory_percent=round(pid.get_memory_percent(), 2)))
        
        except psutil.AccessDenied:
            pass
    
    #Sort the list first by CPU then by Memory. Get top x
    Plist = sorted(Plist, key=lambda x: (x.cpu_percent, x.memory_percent), reverse=True)
    
    #Assign list
    processList = Plist[:int(get_setting_value('top_process_number'))]
Example #35
0
def xbmc_get_seasons(xbmc, tvshowid):
    logger.log('LIBRARY :: Retrieving seasons for tvshowid: %s' % tvshowid, 'INFO')
    version = xbmc.Application.GetProperties(properties=['version'])['version']['major']
    params = {'sort': xbmc_sort('seasons')}

    if version < 12 and params['sort']['method'] in ['rating', 'playcount', 'random']: #Eden
        logger.log('LIBRARY :: Sort method "%s" is not supported in XBMC Eden. Reverting to "label"' % params['sort']['method'], 'INFO')
        change_sort('seasons', 'label')
        params['sort'] = xbmc_sort('seasons')

    params['tvshowid'] = tvshowid
    params['properties'] = ['playcount', 'showtitle', 'tvshowid', 'season', 'thumbnail', 'episode']

    seasons = xbmc.VideoLibrary.GetSeasons(**params)['seasons']

    if get_setting_value('xbmc_seasons_hide_watched') == '1':
        seasons = [x for x in seasons if not x['playcount']]

    #Add episode playcounts to seasons
    for season in seasons:
        episodes = xbmc.VideoLibrary.GetEpisodes(
            tvshowid=tvshowid,
            season=season['season'],
            properties=['playcount']
        )['episodes']
        season['unwatched'] = len([x for x in episodes if not x['playcount']])

    return seasons
Example #36
0
def server_settings():
    servers = XbmcServer.query.order_by(XbmcServer.position)

    if servers.count() == 0:
        return {
            'hostname': None,
            'port': None,
            'username': None,
            'password': None,
        }

    active_server = get_setting_value('active_server')

    # if active server is not defined, set it

    if not active_server:
        active_server = Setting('active_server', servers.first().id)
        db_session.add(active_server)
        db_session.commit()

    try:
        server = servers.get(active_server)

    except:
        logger.log('Could not retrieve active server, falling back on first entry' , 'WARNING')
        server = servers.first()

    return {
        'hostname': server.hostname,
        'port': server.port,
        'username': server.username,
        'password': server.password,
        'type': server.type,
        'mac_address': server.mac_address,
    }
Example #37
0
def xbmc_get_moviesets(xbmc, setid):
    logger.log('LIBRARY :: Retrieving movie set: %s' % setid, 'INFO')
    version = xbmc.Application.GetProperties(properties=['version'])['version']['major']

    sort = xbmc_sort('movies')
    properties = ['playcount', 'thumbnail', 'year', 'rating', 'set']
    params = {'sort': sort, 'properties': properties}

    if version == 11: #Eden
        params['properties'].append('setid')

    else: #Frodo
        params['filter'] = {'setid':setid}

    movies = xbmc.VideoLibrary.GetMovies(**params)['movies']

    if version == 11: #Eden
        movies = [x for x in movies if setid in x['setid']]
        setlabel = xbmc.VideoLibrary.GetMovieSetDetails(setid=setid)['setdetails']['label']
        for movie in movies:
            movie['set'] = setlabel

    if get_setting_value('xbmc_movies_hide_watched') == '1':
        movies = [x for x in movies if not x['playcount']]

    movies[0]['setid'] = setid
    return movies
Example #38
0
def xbmc_get_episodes(xbmc, tvshowid, season):
    logger.log(
        'LIBRARY :: Retrieving episodes for tvshowid: %s season: %s' %
        (tvshowid, season), 'INFO')
    version = xbmc.Application.GetProperties(
        properties=['version'])['version']['major']
    params = {'sort': xbmc_sort('episodes')}

    if version < 12 and params['sort']['method'] in [
            'rating', 'playcount', 'random'
    ]:  #Eden
        logger.log(
            'LIBRARY :: Sort method "%s" is not supported in XBMC Eden. Reverting to "episode"'
            % params['sort']['method'], 'INFO')
        change_sort('episodes', 'episode')
        params['sort'] = xbmc_sort('episodes')

    params['tvshowid'] = tvshowid
    params['season'] = season
    params['properties'] = [
        'playcount', 'season', 'episode', 'tvshowid', 'showtitle', 'thumbnail',
        'firstaired', 'rating'
    ]

    episodes = xbmc.VideoLibrary.GetEpisodes(**params)['episodes']

    if get_setting_value('xbmc_episodes_hide_watched') == '1':
        episodes = [x for x in episodes if not x['playcount']]

    return episodes
Example #39
0
def xbmc_get_moviesets(xbmc, setid):
    logger.log("LIBRARY :: Retrieving movie set: %s" % setid, "INFO")
    version = xbmc.Application.GetProperties(properties=["version"])["version"]["major"]

    sort = xbmc_sort("movies")
    properties = ["playcount", "thumbnail", "year", "rating", "set"]
    params = {"sort": sort, "properties": properties}

    if version == 11:  # Eden
        params["properties"].append("setid")

    else:  # Frodo
        params["filter"] = {"setid": setid}

    movies = xbmc.VideoLibrary.GetMovies(**params)["movies"]

    if version == 11:  # Eden
        movies = [x for x in movies if setid in x["setid"]]
        setlabel = xbmc.VideoLibrary.GetMovieSetDetails(setid=setid)["setdetails"]["label"]
        for movie in movies:
            movie["set"] = setlabel

    if get_setting_value("xbmc_movies_hide_watched") == "1":
        movies = [x for x in movies if not x["playcount"]]

    movies[0]["setid"] = setid
    return movies
Example #40
0
def xbmc_get_seasons(xbmc, tvshowid):
    logger.log("LIBRARY :: Retrieving seasons for tvshowid: %s" % tvshowid, "INFO")
    version = xbmc.Application.GetProperties(properties=["version"])["version"]["major"]
    params = {"sort": xbmc_sort("seasons")}

    if version < 12 and params["sort"]["method"] in ["rating", "playcount", "random"]:  # Eden
        logger.log(
            'LIBRARY :: Sort method "%s" is not supported in XBMC Eden. Reverting to "label"'
            % params["sort"]["method"],
            "INFO",
        )
        change_sort("seasons", "label")
        params["sort"] = xbmc_sort("seasons")

    params["tvshowid"] = tvshowid
    params["properties"] = ["playcount", "showtitle", "tvshowid", "season", "thumbnail", "episode"]

    seasons = xbmc.VideoLibrary.GetSeasons(**params)["seasons"]

    if get_setting_value("xbmc_seasons_hide_watched") == "1":
        seasons = [x for x in seasons if not x["playcount"]]

    # Add episode playcounts to seasons
    for season in seasons:
        episodes = xbmc.VideoLibrary.GetEpisodes(tvshowid=tvshowid, season=season["season"], properties=["playcount"])[
            "episodes"
        ]
        season["unwatched"] = len([x for x in episodes if not x["playcount"]])

    return seasons
Example #41
0
def xbmc_get_moviesets(xbmc, setid):
    logger.log('LIBRARY :: Retrieving movie set: %s' % setid, 'INFO')
    version = xbmc.Application.GetProperties(
        properties=['version'])['version']['major']

    sort = xbmc_sort('movies')
    properties = ['playcount', 'thumbnail', 'year', 'rating', 'set']
    params = {'sort': sort, 'properties': properties}

    if version == 11:  #Eden
        params['properties'].append('setid')

    else:  #Frodo
        params['filter'] = {'setid': setid}

    movies = xbmc.VideoLibrary.GetMovies(**params)['movies']

    if version == 11:  #Eden
        movies = [x for x in movies if setid in x['setid']]
        setlabel = xbmc.VideoLibrary.GetMovieSetDetails(
            setid=setid)['setdetails']['label']
        for movie in movies:
            movie['set'] = setlabel

    if get_setting_value('xbmc_movies_hide_watched') == '1':
        movies = [x for x in movies if not x['playcount']]

    movies[0]['setid'] = setid
    return movies
Example #42
0
def xhr_trakt_get_lists(user=None):
    if not user:
        user = get_setting_value('trakt_username')

    logger.log('TRAKT :: Fetching %s\'s custom lists' % user, 'INFO')
    url = 'http://api.trakt.tv/user/lists.json/%s/%s' % (trakt_apikey(), user)

    try:
        trakt = trak_api(url)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    if request.method == 'GET':
        return render_template('traktplus/trakt-custom_lists.html',
                               lists=trakt,
                               user=user,
                               title='lists')

    else:
        return render_template(
            'traktplus/trakt-add_to_list.html',
            lists=trakt,
            custom_lists=True,
            media=request.form,
        )
Example #43
0
def xhr_trakt_get_lists(user=None, mobile=False):
    if not user:
        user = get_setting_value('trakt_username')

    logger.log('TRAKT :: Fetching %s\'s custom lists' % user, 'INFO')
    url = 'http://api.trakt.tv/user/lists.json/%s/%s' % (trakt_apikey(), user)

    try:
        trakt = trak_api(url)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    if request.method == 'GET':
        if mobile:
            return trakt

        return render_template('traktplus/trakt-custom_lists.html',
            lists=trakt,
            user=user,
            title='lists'
        )

    else:
        return render_template('traktplus/trakt-add_to_list.html',
            lists=trakt,
            custom_lists=True,
            media=request.form,
        )
Example #44
0
def xhr_trakt_recommendations(type=None, mobile=False):
    if not type:
        type = get_setting_value('trakt_default_media')

    logger.log('TRAKT :: Fetching %s recommendations' % type, 'INFO')

    url = 'http://api.trakt.tv/recommendations/%s/%s' % (type, trakt_apikey())

    params = {
        'hide_collected': True,
        'hide_watchlisted': True
    }
    try:
        recommendations = trak_api(url, params)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    random.shuffle(recommendations)

    for item in recommendations:
        item['poster'] = cache_image(item['images']['poster'], type)

    while THREADS:
        time.sleep(1)

    if mobile:
        return recommendations

    return render_template('traktplus/trakt-recommendations.html',
        type=type.title(),
        recommendations=recommendations,
        title='Recommendations',
    )
Example #45
0
def xhr_couchpotato(status=False):
    if status:
        status_string = 'status=%s' % status
        template = 'couchpotato-all.html'
    else:
        status = 'wanted'
        status_string = False
        template = 'couchpotato.html'
    try:
        logger.log('CouchPotato :: Fetching "%s movies" list' % status, 'INFO')
        couchpotato = couchpotato_api('movie.list', params=status_string)
        if couchpotato['success'] and not couchpotato['empty']:
            couchpotato = couchpotato['movies']

    except Exception as e:
        log_exception(e)
        couchpotato = None

    logger.log('CouchPotato :: Fetching "%s movies" list (DONE)' % status, 'INFO')

    if status == 'wanted' and not type(couchpotato) is list:
        logger.log('CouchPotato :: Wanted movies list is empty', 'INFO')
        return cp_search('There are no movies is your wanted list.')

    return render_template(template,
        url=couchpotato_url(),
        couchpotato=couchpotato,
        compact_view=get_setting_value('couchpotato_compact') == '1',
    )
Example #46
0
def xhr_trakt_friends(user=None):
    logger.log('TRAKT :: Fetching friends list', 'INFO')
    pending = []
    if not user:
        friends_url = 'http://api.trakt.tv/user/friends.json/%s/%s' % (
            trakt_apikey(), get_setting_value('trakt_username'))
        pending_url = 'http://api.trakt.tv/friends/requests/%s' % trakt_apikey(
        )
    else:
        friends_url = 'http://api.trakt.tv/user/friends.json/%s/%s' % (
            trakt_apikey(), user)

    try:
        friends = trak_api(friends_url)
        if not user:
            pending = trak_api(pending_url)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    return render_template(
        'traktplus/trakt-friends.html',
        friends=friends,
        pending=pending,
        title='Friends',
    )
Example #47
0
def xhr_trakt_calendar(type, mobile=False):
    logger.log('TRAKT :: Fetching %s calendar' % type, 'INFO')
    username = get_setting_value('trakt_username')

    if type == 'my shows':
        url = 'http://api.trakt.tv/user/calendar/shows.json/%s/%s' % (
            trakt_apikey(), username)
    else:
        url = 'http://api.trakt.tv/calendar/%s.json/%s/' % (type,
                                                            trakt_apikey())

    try:
        trakt = trak_api(url)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    if mobile:
        return trakt

    return render_template(
        'traktplus/trakt-calendar.html',
        calendar=trakt,
        type=type.title(),
        title='Calendar',
    )
Example #48
0
def trak_api(url, params={}, dev=False):
    username = get_setting_value('trakt_username')
    password = hashlib.sha1(get_setting_value('trakt_password')).hexdigest()

    params = json.JSONEncoder().encode(params)
    request = urllib2.Request(url, params)
    base64string = base64.encodestring('%s:%s' % (username, password)).replace(
        '\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)

    response = urllib2.urlopen(request)
    response = response.read()
    response = json.JSONDecoder().decode(response)

    if dev:
        print url
        print json.dumps(response, sort_keys=True, indent=4)

    return response
Example #49
0
def headphones_api(command, use_json=True, dev=False):
    username = get_setting_value('headphones_user')
    password = get_setting_value('headphones_password')
    apikey = get_setting_value('headphones_api')

    url = '%s/api?apikey=%s&cmd=%s' % (headphones_url(), apikey, command)

    request = urllib2.Request(url)
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)
    data = urllib2.urlopen(request).read()

    if use_json:
        data = json.JSONDecoder().decode(data)

    if dev:
        print 'DEVELOPER :: %s' % url
        print 'DEVELOPER :: %s' % data

    return data
Example #50
0
def weather_speed(speed):
    if not speed.isdigit():
        return speed

    speed = int(speed)

    if get_setting_value('weather_use_kilometers') == '1':
        speed = speed * 1.609
        return str(int(speed)) + 'kph'
    else:
        return str(int(speed)) + 'mph'
Example #51
0
def get_xbmc_media_settings(media_type):
    '''
    Return settings for media type.
    '''

    settings = library_settings[media_type]

    for s in settings:
        s['value'] = get_setting_value(s['key'])

    return settings
Example #52
0
def savePreferredSection(type, id):
    try:
        server = PlexServer.query.filter(
            PlexServer.id == get_setting_value('active_server')).first()
        server.sections[type]['preferred'] = int(id)
        db_session.add(server)
        db_session.commit()
        logger.log('Plex :: Changed preferred %s section to %i' % (type, id),
                   'INFO')
        return jsonify(success=True)
    except:
        return jsonify(success=False, msg='Failed to set preferred category')
Example #53
0
def xhr_headphones_image(type, id):
    if type == 'artist':
        cache_url = headphones_api('getArtistThumb&id=' + id)
    else:
        cache_url = headphones_api('getAlbumThumb&id=' + id)

    if cache_url:
        url = '%s/%s' % (headphones_url(), cache_url)
    else:
        img = RUNDIR + '/static/images/applications/HeadPhones.png'
        return send_file(img, mimetype='image/jpeg')

    username = get_setting_value('headphones_user')
    password = get_setting_value('headphones_password')

    request = urllib2.Request(url)
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)

    img = StringIO.StringIO(urllib2.urlopen(request).read())
    return send_file(img, mimetype='image/jpeg')
Example #54
0
def xhr_trakt_profile(user=None, mobile=False):
    if not user:
        user = get_setting_value('trakt_username')

    logger.log('TRAKT :: Fetching %s\'s profile information' % user, 'INFO')

    url = 'http://api.trakt.tv/user/profile.json/%s/%s/' % (trakt_apikey(),
                                                            user)

    try:
        trakt = trak_api(url)
    except Exception as e:
        trakt_exception(e)
        return render_template('traktplus/trakt-base.html', message=e)

    if 'status' in trakt and trakt['status'] == 'error':
        logger.log('TRAKT :: Error accessing user profile', 'INFO')
        movies_progress = 0
        episodes_progress = 0

    else:
        for item in trakt['watched']:
            item['watched'] = time.ctime(int(item['watched']))

        movies = trakt['stats']['movies']

        try:
            movies_progress = 100 * float(movies['watched_unique']) / float(
                movies['collection'])
        except:
            movies_progress = 0

        episodes = trakt['stats']['episodes']

        try:
            episodes_progress = 100 * float(
                episodes['watched_unique']) / float(episodes['collection'])
        except:
            episodes_progress = 0

    if mobile:
        return trakt

    return render_template(
        'traktplus/trakt-user_profile.html',
        profile=trakt,
        user=user,
        movies_progress=int(movies_progress),
        episodes_progress=int(episodes_progress),
        title='Profile',
    )
Example #55
0
def weather_temp(temp):
    if not temp.isdigit():
        return temp

    temp = int(temp)
    degrees = unichr(176)

    if get_setting_value('weather_use_celcius') == '1':
        temp = temp - 32
        temp = temp * 5
        temp = temp / 9
        return str(int(temp)) + degrees + 'C'
    else:
        return str(int(temp)) + degrees + 'F'
Example #56
0
def update_xbmc_object():
    host = get_setting_value('server_hostname')
    try:
        icon = os.path.abspath('static/images/maraschino_logo.png')

        if not os.path.exists(icon):
            icon = os.path.abspath(
                'maraschino/static/images/maraschino_logo.png')

        xbmc = XBMCClient('Maraschino', icon, ip=host)

    except:
        xbmc = None

    return xbmc
Example #57
0
def getServers():
    global user, servers
    if not get_setting_value("myPlex_token"):
        logger.log(
            'Plex :: Cannot retrieve servers, need to sign in to plex first',
            'ERROR')
        return False

    logger.log('Plex :: Getting servers from myPlex servers.xml', 'INFO')
    try:
        user = User(get_setting_value('myPlex_username'),
                    get_setting_value('myPlex_password'),
                    get_setting_value('myPlex_token'))
        servers = user.getServers()
    except:
        logger.log(
            'Plex :: Failed to retrieve server information from myPlex account',
            'ERROR')
        return False

    # Storing server information into db
    try:
        for server in servers:
            server['localAddresses'] = server['localAddresses'].split(',')[0]
            addServer(server['name'], server['address'], server['port'],
                      server['scheme'], server['host'],
                      server['localAddresses'], server['machineIdentifier'],
                      server['createdAt'], server['updatedAt'],
                      server['synced'], server['version'], server['owned'],
                      server['accessToken'])
    except:
        logger.log('Plex :: Failed to store server information in database',
                   'ERROR')
        return False

    return servers
Example #58
0
def xhr_search(site=0):
    if get_setting_value('search') == '0':
        logger.log(
            'SEARCH :: Search fature not enabled, please enable it on the top right corner menu',
            'INFO')
        return ''

    try:
        site = int(site)
        if site == 0:
            newznab = NewznabSite.query.order_by(NewznabSite.id).first()
        else:
            newznab = NewznabSite.query.filter(NewznabSite.id == site).first()
        categories = cat_newznab(newznab.url)
    except Exception, e:
        logger.log('SEARCH :: Exception %s' % e, 'ERROR')
Example #59
0
def xhr_search(site=1):
    if get_setting_value('search') == '0':
        logger.log('SEARCH :: Search fature not enabled, please enable it on the top right corner menu', 'INFO')
        return ''

    site = int(site)
    newznab = NewznabSite.query.filter(NewznabSite.id == site).first()
    categories = cat_newznab(newznab.url)

    return render_template('search.html',
        site=site,
        newznab_sites=get_newznab_sites(),
        categories=categories,
        category=0,
        maxage=0
    )