Esempio n. 1
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
Esempio n. 2
0
def server_settings_dialog(server_id=None):
    """
    Server settings dialog.
    If server_id exists then we're editing a server, otherwise we're adding one.
    """

    server = None

    if server_id:
        try:
            server = XbmcServer.query.get(server_id)

        except:
            logger.log('Error retrieving server details for server ID %s' % server_id , 'WARNING')

    # GET

    if request.method == 'GET':
        return render_template('dialogs/server_settings_dialog.html',
            server = server,
        )

    # POST

    else:
        if not server:
            server = XbmcServer('', 1, '')

        label = request.form['label']
        if not label:
            label = 'XBMC server'

        try:
            server.label = label
            server.position = request.form['position']
            server.hostname = request.form['hostname']
            server.port = request.form['port']
            server.username = request.form['username']
            server.password = request.form['password']
            server.mac_address = request.form['mac_address']

            db_session.add(server)
            db_session.commit()

            active_server = get_setting('active_server')

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

            return render_template('includes/servers.html',
                servers = XbmcServer.query.order_by(XbmcServer.position),
            )

        except:
            logger.log('Error saving XBMC server to database', 'WARNING')
            return jsonify({ 'status': 'error' })

    return jsonify({ 'status': 'error' })
Esempio n. 3
0
def xhr_trakt_hated(user, type):
    logger.log('TRAKT :: Fetching %s\'s hated %s' % (user, type), 'INFO')
    apikey = get_setting_value('trakt_api_key')

    url = 'http://api.trakt.tv/user/library/%s/hated.json/%s/%s/' % (type, apikey, user)

    try:
        result = urllib.urlopen(url).read()
    except:
        logger.log('TRAKT :: Problem fething URL', 'ERROR')
        return render_template('trakt-base.html', message=url_error)

    trakt = json.JSONDecoder().decode(result)

    amount = len(trakt)

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

    return render_template('trakt-hated.html',
        hated = trakt,
        amount = amount,
        type = type.title(),
        user = user,
        title = 'Hated',
    )
Esempio n. 4
0
def gitUpdate():
    """Update Maraschino using git"""
    output, err = runGit('pull origin %s' % branch)

    if not output:
        logger.log('Couldn\'t download latest version', 'ERROR')
        maraschino.USE_GIT = False
        return 'failed'

    for line in output.split('\n'):

        if 'Already up-to-date.' in line:
            logger.log('UPDATER :: Already up to date', 'INFO')
            logger.log('UPDATER :: Git output: ' + str(output), 'DEBUG')
            return 'complete'
        elif line.endswith('Aborting.'):
            logger.log('UPDATER :: Unable to update from git: '+line, 'ERROR')
            logger.log('UPDATER :: Output: ' + str(output), 'DEBUG')
            maraschino.USE_GIT = False
            return 'failed'

    maraschino.CURRENT_COMMIT = maraschino.LATEST_COMMIT
    writeVersion(maraschino.LATEST_COMMIT)
    maraschino.COMMITS_BEHIND = 0

    return 'complete'
Esempio n. 5
0
def xhr_headphones_album(albumid, mobile=False):
    logger.log('HEADPHONES :: Fetching album', 'INFO')

    try:
        headphones = headphones_api('getAlbum&id=%s' % albumid)
    except Exception as e:
        return headphones_exception(e)

    album = headphones['album'][0]

    try:
        album['ThumbURL'] = hp_albumart(album['AlbumID'])
    except:
        pass

    album['TotalDuration'] = 0

    for track in headphones['tracks']:
        if track['TrackDuration'] == None:
            track['TrackDuration'] = 0
        album['TotalDuration'] = album['TotalDuration'] + int(track['TrackDuration'])
        track['TrackDuration'] = convert_track_duration(track['TrackDuration'])

    album['TotalDuration'] = convert_track_duration(album['TotalDuration'])
    album['Tracks'] = len(headphones['tracks'])

    if mobile:
        return headphones
    return render_template('headphones/album.html',
        album=headphones,
        headphones=True,
        compact=hp_compact(),
    )
Esempio n. 6
0
def start_script(script_id):
    #first get the script we want
    script = None
    message = None
    script = Script.query.filter(Script.id == script_id).first()
    now = datetime.datetime.now()

    command = os.path.join(maraschino.SCRIPT_DIR,script.script)

    if (script.parameters):
        command = ''.join([command, ' ', script.parameters])

    #Parameters needed for scripts that update
    host = maraschino.HOST
    port = maraschino.PORT
    webroot = maraschino.WEBROOT

    if not webroot:
        webroot = '/'

    file_ext = os.path.splitext(script.script)[1]

    if (file_ext == '.py'):
        if (script.updates == 1):        
            #these are extra parameters to be passed to any scripts ran, so they 
            #can update the status if necessary
            extras = '--i "%s" --p "%s" --s "%s" --w "%s"' % (host, port, script.id, webroot)

            #the command in all its glory
            command = ''.join([command, ' ', extras])
            script.status="Script Started at: %s" % now.strftime("%m-%d-%Y %H:%M")
        else:
            script.status="Last Ran: %s" % now.strftime("%m-%d-%Y %H:%M")

        command =  ''.join(['python ', command])

    elif (file_ext in ['.sh', '.pl', '.cmd']):
        if (script.updates == 1):
            extras = '%s %s %s %s' % (host, port, script.id, webroot)
            #the command in all its glory
            command = ''.join([command, ' ', extras])
            script.status="Script Started at: %s" % now.strftime("%m-%d-%Y %H:%M")
        else:
            script.status="Last Ran: %s" % now.strftime("%m-%d-%Y %H:%M")

        if(file_ext == '.pl'):
            command = ''.join(['perl ', command])

        if(file_ext == '.cmd'):
            command = ''.join([command])


    logger.log('SCRIPT_LAUNCHER :: %s' % command, 'INFO')
    #now run the command
    subprocess.Popen(command, shell=True)

    db_session.add(script)
    db_session.commit()

    return script_launcher()  
Esempio n. 7
0
def xhr_headphones_artist_action(artistid, action, mobile=False):
    if action == "pause":
        logger.log("HEADPHONES :: Pausing artist", "INFO")
        command = "pauseArtist&id=%s" % artistid
    elif action == "resume":
        logger.log("HEADPHONES :: Resuming artist", "INFO")
        command = "resumeArtist&id=%s" % artistid
    elif action == "refresh":
        logger.log("HEADPHONES :: Refreshing artist", "INFO")
        command = "refreshArtist&id=%s" % artistid
    elif action == "remove":
        logger.log("HEADPHONES :: Removing artist", "INFO")
        command = "delArtist&id=%s" % artistid
    elif action == "add":
        logger.log("HEADPHONES :: Adding artist", "INFO")
        command = "addArtist&id=%s" % artistid

    try:
        if command == "remove":
            headphones_api(command, False)
        elif command == "pause":
            headphones_api(command, False)
        elif command == "resume":
            headphones_api(command, False)
        else:
            Thread(target=headphones_api, args=(command, False)).start()
    except Exception as e:
        if mobile:
            headphones_exception(e)
            return jsonify(error="failed")

        return headphones_exception(e)

    return jsonify(status="successful")
Esempio n. 8
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',
    )
Esempio n. 9
0
def xhr_headphones_artists(mobile=False):
    logger.log("HEADPHONES :: Fetching artists list", "INFO")
    artists = []

    try:
        headphones = headphones_api("getIndex")
        updates = headphones_api("getVersion")
    except Exception as e:
        if mobile:
            headphones_exception(e)
            return artists
        return headphones_exception(e)

    for artist in headphones:
        if not "Fetch failed" in artist["ArtistName"]:
            try:
                artist["Percent"] = int(100 * float(artist["HaveTracks"]) / float(artist["TotalTracks"]))
            except:
                artist["Percent"] = 0

            if not hp_compact() and not mobile:
                try:
                    artist["ThumbURL"] = hp_artistart(artist["ArtistID"])
                except:
                    pass
            artists.append(artist)

    if mobile:
        return artists

    return render_template(
        "headphones-artists.html", headphones=True, artists=artists, updates=updates, compact=hp_compact()
    )
Esempio n. 10
0
def download_image(image, file_path):
    try:
        logger.log('TRAKT :: Creating file %s' % file_path, 'INFO')
        downloaded_image = file(file_path, 'wb')
    except:
        logger.log('TRAKT :: Failed to create file %s' % file_path, 'ERROR')
        logger.log('TRAKT :: Using remote image', 'INFO')
        threads.pop()
        return image

    try:
        logger.log('TRAKT :: Downloading %s' % image, 'INFO')
        image_on_web = urllib.urlopen(image)
        while True:
            buf = image_on_web.read(65536)
            if len(buf) == 0:
                break
            downloaded_image.write(buf)
        downloaded_image.close()
        image_on_web.close()
    except:
        logger.log('TRAKT :: Failed to download %s' % image, 'ERROR')

    threads.pop()

    return
Esempio n. 11
0
def album_library(artistid):
    try:
        xbmc = jsonrpclib.Server(server_api_address())
        version = xbmc.Application.GetProperties(properties=['version'])['version']['major']
        params = {'sort': {'ignorearticle': True}, 'properties': ['year']}

        if version < 12:  # Eden
            params['artistid'] = artistid
            params['properties'].extend(['artistid', 'artist'])
        else:  # Frodo
            params['filter'] = {'artistid': artistid}

        albums = xbmc.AudioLibrary.GetAlbums(**params)['albums']

        if version > 11:  # Frodo
            artist = xbmc.AudioLibrary.GetArtistDetails(artistid=artistid)['artistdetails']['label']
            for album in albums:
                album['artistid'] = artistid
                album['artist'] = artist
    except:
        logger.log('Mobile :: XBMC :: Could not retrieve albums from audio library', 'WARNING')
        albums = []

    return render_template('mobile/xbmc/albums.html',
        albums=albums,
    )
Esempio n. 12
0
def sabnzbd_history_item(id):
    global sabnzbd_history_slots
    if sabnzbd_history_slots:
        for item in sabnzbd_history_slots['slots']:
            if item['nzo_id'] == id:
                return render_template('mobile/sabnzbd/history_item.html',
                    item=item,
                )

        return sabnzbd_history()
    else:
        try:
            sabnzbd = sabnzbd_api(method='history', params='&limit=50')
            sabnzbd = sabnzbd_history_slots = sabnzbd['history']

            for item in sabnzbd_history_slots['slots']:
                if item['nzo_id'] == id:
                    return render_template('mobile/sabnzbd/history_item.html',
                        item=item,
                    )
        except Exception as e:
            logger.log('Mobile :: SabNZBd+ :: Could not retrieve SabNZBd - %s]' % (e), 'WARNING')
            sabnzbd = None

        return render_template('mobile/sabnzbd/history.html',
            history=sabnzbd,
        )
Esempio n. 13
0
def runGit(args):
    """Run git command with args as arguments"""
    git_locations = ['git']

    if platform.system().lower() == 'darwin':
        git_locations.append('/usr/local/git/bin/git')

    output = err = None

    for cur_git in git_locations:
        cmd = cur_git + ' ' + args

        try:
            logger.log('UPDATER :: Trying to execute: "' + cmd + '" with shell in ' + RUNDIR, 'DEBUG')
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd=RUNDIR)
            output, err = p.communicate()
            logger.log('UPDATER :: Git output: ' + output, 'DEBUG')
        except OSError:
            logger.log('UPDATER :: Command ' + cmd + ' didn\'t work, couldn\'t find git', 'WARNING')
            continue

        if 'not found' in output or "not recognized as an internal or external command" in output:
            logger.log('UPDATER :: Unable to find git with command ' + cmd, 'WARNING')
            output = None
        elif 'fatal:' in output or err:
            logger.log('UPDATER :: Git returned bad info. Are you sure this is a git installation?', 'WARNING')
            output = None
        elif output:
            break

    return (output, err)
Esempio n. 14
0
def create_dir(dir):
    if not os.path.exists(dir):
        try:
            logger.log('TRAKT :: Creating dir %s' % dir, 'INFO')
            os.makedirs(dir)
        except:
            logger.log('TRAKT :: Problem creating dir %s' % dir, 'ERROR')
Esempio n. 15
0
def xhr_trakt_trending(type):
    logger.log('TRAKT :: Fetching trending %s' % type, 'INFO')
    apikey = get_setting_value('trakt_api_key')

    url = 'http://api.trakt.tv/%s/trending.json/%s' % (type, apikey)

    try:
        result = urllib.urlopen(url).read()
    except:
        logger.log('TRAKT :: Problem fething URL', 'ERROR')
        return render_template('trakt-base.html', message=url_error)

    trakt = json.JSONDecoder().decode(result)

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

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

    while threads:
        time.sleep(1)

    return render_template('trakt-trending.html',
        trending = trakt,
        type = type.title(),
        title = 'Trending',
    )
Esempio n. 16
0
def tutorial_save():
    global user, servers
    # save login and password on db
    try:
        settings = json.JSONDecoder().decode(request.form['settings'])
        for s in settings:
            setting = get_setting(s['name'])

            if not setting:
                setting = Setting(s['name'])

            setting.value = s['value']
            db_session.add(setting)
        db_session.commit()
        logger.log('Plex :: Successfully saved Plex credentials', 'INFO')
    except:
        return jsonify(success=False, msg='Failed to save plex credentials to db')

    # Delete info for previous accounts
    try:
        PlexServer.query.delete()
    except:
        logger.log('Plex :: Failed to delete old server info', 'WARNING')

    try:
        if loginToPlex(): # login to plex
            servers = getServers()
            if servers: # retrieve servers
                return jsonify(success=True, servers=listServers())
            else:
                return jsonify(sucess=False, msg='Failed to retrieve servers')
        else:
            return jsonify(sucess=False, msg='Failed to login to plex')
    except:
        return jsonify(success=False, msg='Servers not populated Successfully')
Esempio n. 17
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',
    )
Esempio n. 18
0
def xhr_trakt_friends(user=None, mobile=False):
    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)

    if mobile:
        return friends

    return render_template('traktplus/trakt-friends.html',
        friends=friends,
        pending=pending,
        title='Friends',
    )
Esempio n. 19
0
def json_login():
    if not loginToPlex():
        return jsonify(success=False, msg='Failed to login to plex.tv, plese make sure this is a valid username/password.')

    # Delete info for previous accounts
    try:
        PlexServer.query.delete()
    except:
        logger.log('Plex :: Failed to delete old server info', 'WARNING')

    # Populate servers for new user
    if not getServers():
        return jsonify(success=False, msg='Failed to retrieve server information from https://plex.tv/pms/servers.')

    # Set active server to 0 (no server selected)
    try:
        active_server = get_setting('active_server')

        if not active_server:
            active_server = Setting('active_server', 0)
            db_session.add(active_server)
            db_session.commit()

        else:
            active_server.value = 0
            db_session.add(active_server)
            db_session.commit()

    except:
        logger.log('Plex :: Failed to reset server, please make sure to select new one.', 'WARNING')

    # return a list of (server name, server id)
    return jsonify(success=True, servers=listServers())
Esempio n. 20
0
def xhr_headphones_artists():
    logger.log('HEADPHONES :: Fetching artists list', 'INFO')

    try:
        headphones = headphones_api('getIndex')
        updates = headphones_api('getVersion')
    except Exception as e:
        return headphones_exception(e)

    artists = []

    for artist in headphones:
        if not 'Fetch failed' in artist['ArtistName']:
            try:
                artist['Percent'] = int(100 * float(artist['HaveTracks']) / float(artist['TotalTracks']))
            except:
                artist['Percent'] = 0

            if not hp_compact():
                try:
                    artist['ThumbURL'] = hp_artistart(artist['ArtistID'])
                except:
                    pass
            artists.append(artist)

    return render_template('headphones-artists.html',
        headphones=True,
        artists=artists,
        updates=updates,
        compact=hp_compact(),
    )
Esempio n. 21
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
Esempio n. 22
0
def xhr_library_info(type, id):
    logger.log('LIBRARY :: Retrieving %s details' % type, 'INFO')
    xbmc = jsonrpclib.Server(server_api_address())

    try:
        if type == 'movie':
            library = xbmc.VideoLibrary.GetMovieDetails(movieid=id, properties=['title', 'rating', 'year', 'genre', 'plot', 'director', 'thumbnail', 'trailer', 'playcount', 'resume'])
            title = library['moviedetails']['title']

        elif type == 'tvshow':
            library = xbmc.VideoLibrary.GetTVShowDetails(tvshowid=id, properties=['title', 'rating', 'year', 'genre', 'plot', 'premiered', 'thumbnail', 'playcount', 'studio'])
            title = library['tvshowdetails']['title']

        elif type == 'episode':
            library = xbmc.VideoLibrary.GetEpisodeDetails(episodeid=id, properties=['season', 'tvshowid', 'title', 'rating', 'plot', 'thumbnail', 'playcount', 'firstaired', 'resume'])
            title = library['episodedetails']['title']

        elif type == 'artist':
            library = xbmc.AudioLibrary.GetArtistDetails(artistid=id, properties=['description', 'thumbnail', 'genre'])
            title = library['artistdetails']['label']

        elif type == 'album':
            library = xbmc.AudioLibrary.GetAlbumDetails(albumid=id, properties=['artistid', 'title', 'artist', 'year', 'genre', 'description', 'albumlabel', 'rating', 'thumbnail'])
            title = library['albumdetails']['title']

    except:
        logger.log('LIBRARY :: %s' % xbmc_error, 'ERROR')
        return render_library(message=xbmc_error)

    return render_library(library, title)
Esempio n. 23
0
def xhr_headphones_album(albumid, mobile=False):
    logger.log("HEADPHONES :: Fetching album", "INFO")

    try:
        headphones = headphones_api("getAlbum&id=%s" % albumid)
    except Exception as e:
        return headphones_exception(e)

    album = headphones["album"][0]

    try:
        album["ThumbURL"] = hp_albumart(album["AlbumID"])
    except:
        pass

    album["TotalDuration"] = 0

    for track in headphones["tracks"]:
        if track["TrackDuration"] == None:
            track["TrackDuration"] = 0
        album["TotalDuration"] = album["TotalDuration"] + int(track["TrackDuration"])
        track["TrackDuration"] = convert_track_duration(track["TrackDuration"])

    album["TotalDuration"] = convert_track_duration(album["TotalDuration"])
    album["Tracks"] = len(headphones["tracks"])

    if mobile:
        return headphones
    return render_template("headphones-album.html", album=headphones, headphones=True, compact=hp_compact())
Esempio n. 24
0
def mobile_trakt_summary(media, id, season=None, episode=None):

    summary = xhr_trakt_summary(type=media, id=id, season=season, episode=episode, mobile=True)

    if 'genres' in summary:
        summary['genres'] = " / ".join(summary['genres'])

    if media == 'show':
        url = 'http://api.trakt.tv/show/shouts.json/%s/%s' % (trakt_apikey(), id)
    elif media == 'episode':
        url = 'http://api.trakt.tv/show/episode/shouts.json/%s/%s/%s/%s' % (trakt_apikey(), id, season, episode)
    else:
        url = 'http://api.trakt.tv/movie/shouts.json/%s/%s' % (trakt_apikey(), id)

    try:
        shouts = trak_api(url)
    except:
        logger.log('TRAKT :: Failed to retrieve shouts for %s: %s' % (media, id), 'ERROR')
        shouts = []

    return render_template('mobile/trakt/summary.html',
        summary=summary,
        shouts=shouts,
        media=media
    )
Esempio n. 25
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
Esempio n. 26
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
Esempio n. 27
0
def xhr_sickrage():
    params = '/?cmd=future&sort=date'

    try:
        sickrage = sickrage_api(params)

        compact_view = get_setting_value('sickrage_compact') == '1'
        show_airdate = get_setting_value('sickrage_airdate') == '1'

        if sickrage['result'].rfind('success') >= 0:
        	
            logger.log('SICKRAGE :: Successful API call to %s' % params, 'DEBUG')
            sickrage = sickrage['data']

            for time in sickrage:
                for episode in sickrage[time]:
                    episode['image'] = get_pic(episode['indexerid'], 'banner')
                    logger.log('SICKRAGE :: Successful %s' % (episode['image']), 'DEBUG')
    except:
        return render_template('sickrage.html',
            sickrage='',
        )

    return render_template('sickrage.html',
        url=sickrage_url_no_api(),
        app_link=sickrage_url_no_api(),
        sickrage=sickrage,
        missed=sickrage['missed'],
        today=sickrage['today'],
        soon=sickrage['soon'],
        later=sickrage['later'],
        compact_view=compact_view,
        show_airdate=show_airdate,
        
    )
Esempio n. 28
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',
    )
Esempio n. 29
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,
        )
Esempio n. 30
0
def xhr_headphones_artist_action(artistid, action, mobile=False):
    if action == 'pause':
        logger.log('HEADPHONES :: Pausing artist', 'INFO')
        command = 'pauseArtist&id=%s' % artistid
    elif action == 'resume':
        logger.log('HEADPHONES :: Resuming artist', 'INFO')
        command = 'resumeArtist&id=%s' % artistid
    elif action == 'refresh':
        logger.log('HEADPHONES :: Refreshing artist', 'INFO')
        command = 'refreshArtist&id=%s' % artistid
    elif action == 'remove':
        logger.log('HEADPHONES :: Removing artist', 'INFO')
        command = 'delArtist&id=%s' % artistid
    elif action == 'add':
        logger.log('HEADPHONES :: Adding artist', 'INFO')
        command = 'addArtist&id=%s' % artistid

    try:
        if command == 'remove':
            headphones_api(command, False)
        elif command == 'pause':
            headphones_api(command, False)
        elif command == 'resume':
            headphones_api(command, False)
        else:
            Thread(target=headphones_api, args=(command, False)).start()
    except Exception as e:
        if mobile:
            headphones_exception(e)
            return jsonify(error='failed')

        return headphones_exception(e)

    return jsonify(status='successful')
Esempio n. 31
0
def add_edit_script():
    logger.log('SCRIPT_LAUNCHER :: add_edit_script() ', 'DEBUG')
    script = request.form['script_file']
    label = request.form['label']
    parameters = request.form['parameters']
    updates = 0


    try:
        if (request.form['type']):
            updates = 1
    except:
        pass
    #Check that we have the command and label
    if script == '':
        return jsonify({ 'status': 'Command Required' })
    if label == '':
        return jsonify({ 'status': 'Label Required' })

    #figure out if it is a new script or existing script
    if 'script_id' in request.form:
        db_script = Script.query.filter(Script.id == request.form['script_id']).first()
        db_script.script = script
        db_script.label = label
        db_script.parameters = parameters
        db_script.updates = updates

    else:
        db_script = Script(label,script, parameters,updates)

    #save it to the database
    try:
        db_session.add(db_script)
        db_session.commit()
    except Exception, e:
        logger.log('SCRIPT_LAUNCHER :: Add Failed', 'ERROR')
        return jsonify({ 'status': 'Add Failed' })
Esempio n. 32
0
def xhr_headphones_artists(mobile=False):
    logger.log('HEADPHONES :: Fetching artists list', 'INFO')
    artists = []

    try:
        headphones = headphones_api('getIndex')
        updates = headphones_api('getVersion')
    except Exception as e:
        if mobile:
            headphones_exception(e)
            return artists
        return headphones_exception(e)


    for artist in headphones:
        if not 'Fetch failed' in artist['ArtistName']:
            try:
                artist['Percent'] = int(100 * float(artist['HaveTracks']) / float(artist['TotalTracks']))
            except:
                artist['Percent'] = 0

            if not hp_compact() and not mobile:
                try:
                    artist['ThumbURL'] = hp_artistart(artist['ArtistID'])
                except:
                    pass
            artists.append(artist)

    if mobile:
        return artists

    return render_template('headphones-artists.html',
        headphones=True,
        artists=artists,
        updates=updates,
        compact=hp_compact(),
    )
Esempio n. 33
0
def xhr_notify_message():
    label = str(request.form['label'])
    hostname = str(request.form['hostname'])
    message = str(request.form['message'])
    title = str(request.form['title'])
    port = 9777
    icon = os.path.join(RUNDIR, 'static', 'images', 'notifications',
                        request.form['image'])

    if title == "Title":
        title = "Maraschino"

    if not os.path.exists(icon):
        icon = os.path.join(RUNDIR, 'static', 'images', 'maraschino_logo.png')

    if icon[-3:] == "png":
        icon_type = ICON_PNG
    elif icon[-3:] == "jpg":
        icon_type = ICON_JPEG
    elif icon[-4:] == "jpeg":
        icon_type = ICON_JPEG
    elif icon[-3:] == "gif":
        icon_type = ICON_GIF
    else:
        icon_type = ICON_NONE

    addr = (hostname, port)
    sock = socket(AF_INET, SOCK_DGRAM)

    try:
        logger.log('NOTIFY XBMC :: Sending message to %s' % label, 'INFO')
        packet = PacketNOTIFICATION(title, message, icon_type, icon)
        packet.send(sock, addr)
        return jsonify({'status': 'successful'})
    except:
        logger.log('NOTIFY XBMC :: Message failed to send', 'ERROR')
        return jsonify({'error': 'Message failed to send'})
Esempio n. 34
0
def xbmc_get_songs(xbmc, artistid, albumid):
    logger.log('LIBRARY :: Retrieving songs for albumid: %s' % albumid, 'INFO')
    version = xbmc.Application.GetProperties(
        properties=['version'])['version']['major']
    params = {'sort': xbmc_sort('songs')}

    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 "track"'
            % params['sort']['method'], 'INFO')
        change_sort('songs', 'track')
        params['sort'] = xbmc_sort('songs')

    params['properties'] = [
        'album', 'track', 'playcount', 'year', 'albumid', 'thumbnail',
        'rating', 'title', 'duration', 'artist'
    ]

    if version == 11:  #Eden
        params['artistid'] = artistid
        params['albumid'] = albumid

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

    songs = xbmc.AudioLibrary.GetSongs(**params)['songs']

    for song in songs:
        song['artistid'] = artistid
        song['label'] = '%02d. %s' % (song['track'], song['title'])

        if isinstance(song['artist'], list):  #Frodo
            song['artist'] = " / ".join(song['artist'])

    return songs
Esempio n. 35
0
def xhr_headphones_search(type, query, mobile=False):
    if type == 'artist':
        logger.log('HEADPHONES :: Searching for artist', 'INFO')
        command = 'findArtist&name=%s' % urllib.quote(query)
    else:
        logger.log('HEADPHONES :: Searching for album', 'INFO')
        command = 'findAlbum&name=%s' % urllib.quote(query)

    try:
        headphones = headphones_api(command)
    except Exception as e:
        return headphones_exception(e)

    for artist in headphones:
        artist['url'].replace('\/', '/')

        if mobile:
            return headphones

    return render_template('headphones/search_dialog.html',
        headphones=True,
        search=headphones,
        query=query
    )
Esempio n. 36
0
def xhr_trakt_watchlist(user, type=None):
    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 trakt == []:
        trakt = [{'empty': True}]

    return render_template(
        'traktplus/trakt-watchlist.html',
        watchlist=trakt,
        type=type.title(),
        user=user,
        title='Watchlist',
    )
Esempio n. 37
0
def xhr_headphones_control(command):
    if command == 'shutdown':
        logger.log('HEADPHONES :: Shutting down', 'INFO')

    elif command == 'restart':
        logger.log('HEADPHONES :: Restarting', 'INFO')

    elif command == 'update':
        logger.log('HEADPHONES :: Updating', 'INFO')

    elif command == 'force_search':
        logger.log('HEADPHONES :: Forcing wanted album search', 'INFO')
        command = 'forceSearch'

    elif command == 'force_process':
        logger.log('HEADPHONES :: Forcing post process', 'INFO')
        command = 'forceProcess'

    try:
        Thread(target=headphones_api, args=(command, False)).start()
    except Exception as e:
        return headphones_exception(e)

    return jsonify(status='successful')
Esempio n. 38
0
def xhr_trakt_library(user, type=None, mobile=False):
    if not type:
        type = get_setting_value('trakt_default_media')

    logger.log('TRAKT :: Fetching %s\'s %s library' % (user, type), 'INFO')
    url = 'http://api.trakt.tv/user/library/%s/all.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

    return render_template(
        'traktplus/trakt-library.html',
        library=trakt,
        user=user,
        type=type.title(),
        title='Library',
    )
Esempio n. 39
0
def xhr_library_resume_check(type, id):
    logger.log('LIBRARY :: Checking if %s has resume position' % type, 'INFO')
    xbmc = jsonrpclib.Server(server_api_address())

    try:
        if type == 'movie':
            library = xbmc.VideoLibrary.GetMovieDetails(movieid=id, properties=['resume'])

        elif type == 'episode':
            library = xbmc.VideoLibrary.GetEpisodeDetails(episodeid=id, properties=['resume'])

    except:
        logger.log('LIBRARY :: %s' % xbmc_error, 'ERROR')
        return render_library(message=xbmc_error)

    position = library[type + 'details']['resume']['position']

    if position:
        position = format_seconds(position)

        template = render_template('dialogs/library-resume_dialog.html', position=position, library=library)
        return jsonify(resume=True, template=template)
    else:
        return jsonify(resume=False, template=None)
Esempio n. 40
0
def xhr_headphones_album(albumid, mobile=False):
    logger.log('HEADPHONES :: Fetching album', 'INFO')

    try:
        headphones = headphones_api('getAlbum&id=%s' % albumid)
    except Exception as e:
        return headphones_exception(e)

    album = headphones['album'][0]

    try:
        album['ThumbURL'] = hp_albumart(album['AlbumID'])
    except:
        pass

    album['TotalDuration'] = 0

    for track in headphones['tracks']:
        if track['TrackDuration'] == None:
            track['TrackDuration'] = 0
        album['TotalDuration'] = album['TotalDuration'] + int(
            track['TrackDuration'])
        track['TrackDuration'] = convert_track_duration(track['TrackDuration'])

    album['TotalDuration'] = convert_track_duration(album['TotalDuration'])
    album['Tracks'] = len(headphones['tracks'])

    if mobile:
        return headphones
    return render_template(
        'headphones/album.html',
        album=headphones,
        app_link=headphones_url(),
        headphones=True,
        compact=hp_compact(),
    )
Esempio n. 41
0
def tutorial_save():
    global user, servers
    # save login and password on db
    try:
        settings = json.JSONDecoder().decode(request.form['settings'])
        for s in settings:
            setting = get_setting(s['name'])

            if not setting:
                setting = Setting(s['name'])

            setting.value = s['value']
            db_session.add(setting)
        db_session.commit()
        logger.log('Plex :: Successfully saved Plex credentials', 'INFO')
    except:
        return jsonify(success=False,
                       msg='Failed to save plex credentials to db')

    # Delete info for previous accounts
    try:
        PlexServer.query.delete()
    except:
        logger.log('Plex :: Failed to delete old server info', 'WARNING')

    try:
        if loginToPlex():  # login to plex
            servers = getServers()
            if servers:  # retrieve servers
                return jsonify(success=True, servers=listServers())
            else:
                return jsonify(sucess=False, msg='Failed to retrieve servers')
        else:
            return jsonify(sucess=False, msg='Failed to login to plex')
    except:
        return jsonify(success=False, msg='Servers not populated Successfully')
Esempio n. 42
0
def xhr_headphones_artist(artistid, mobile=False):
    logger.log('HEADPHONES :: Fetching artist', 'INFO')

    try:
        albums = headphones_api('getArtist&id=%s' % artistid)
    except Exception as e:
        return headphones_exception(e)

    if not hp_compact() and not mobile:
        for album in albums['albums']:
            try:
                album['ThumbURL'] = hp_albumart(album['AlbumID'])
            except:
                pass

    if mobile:
        return albums

    return render_template(
        'headphones/artist.html',
        albums=albums,
        headphones=True,
        compact=hp_compact(),
    )
Esempio n. 43
0
def xbmc_get_albums(xbmc, artistid):
    logger.log('LIBRARY :: Retrieving albums for artistid: %s' % artistid, 'INFO')
    version = xbmc.Application.GetProperties(properties=['version'])['version']['major']
    params = {}

    params['sort'] = xbmc_sort('albums')
    params['properties'] = ['year', 'rating', 'thumbnail']

    if version == 11: #Eden
        params['artistid'] =  artistid
        params['properties'].extend(['artistid', 'artist'])

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

    albums = xbmc.AudioLibrary.GetAlbums(**params)['albums']

    if version > 11: #Frodo
        artist = xbmc.AudioLibrary.GetArtistDetails(artistid=artistid)['artistdetails']['label']
        for album in albums:
            album['artistid'] = artistid
            album['artist'] = artist

    return albums
Esempio n. 44
0
def get_recently_added_albums(xbmc, album_offset=0, mobile=False):
    num_recent_albums = get_num_recent_albums()
    xbmc_label = get_recent_xbmc_label('recently_added_albums_server')
    using_db = False

    try:
        recently_added_albums = xbmc.AudioLibrary.GetRecentlyAddedAlbums(
            properties=['title', 'year', 'rating', 'artist', 'thumbnail'
                        ])['albums']
        recently_added_db_add(xbmc_label, 'albums', recently_added_albums)

        thumbs = [
            recent_image_file(xbmc_label, 'albums', x['albumid'])[1]
            for x in recently_added_albums
        ]
        cache_dir = os.path.join(DATA_DIR, 'cache', 'xbmc', xbmc_label,
                                 'recent_albums')

        try:
            remove_recent_images(cache_dir, thumbs)
        except:
            logger.log('Failed to delete old images from %s' % cache_dir,
                       'WARNING')

        for album in recently_added_albums:
            album['thumbnail'] = cache_recent_image(xbmc_label, 'albums',
                                                    album['albumid'],
                                                    album['thumbnail'])

    except:
        recently_added_albums = []

    if not recently_added_albums:
        try:
            logger.log('Using cached recently added albums', 'INFO')
            recently_added_albums = RecentlyAdded.query.filter(
                RecentlyAdded.name == '%s_albums' % xbmc_label).first().data

            for album in recently_added_albums:
                thumb = recent_image_file(xbmc_label, 'albums',
                                          album['albumid'])
                album['thumbnail'] = thumb[0] + thumb[1]

            using_db = True
        except:
            recently_added_movies = []
            logger.log('Failed to get recently added albums from database',
                       'ERROR')

    if not mobile and recently_added_albums:
        recently_added_albums = recently_added_albums[
            album_offset:num_recent_albums + album_offset]

    return [recently_added_albums, using_db]
Esempio n. 45
0
def nzb_su(item, cat=None, mobile=False):
    API = get_setting_value('nzb_su_API')

    if not API:
        logger.log('SEARCH :: NZB.su API missing', 'DEBUG')
        return jsonify({'error': "Missing NZB.su API"})

    nzb = nzbsu(apiKey=API)

    if item is not '':
        if cat:
            logger.log(
                'SEARCH :: NZB.su :: Searching for "%s" in category: %s' %
                (item, cat), 'INFO')
            result = nzb.Search(query=item, catId=cat)
        else:
            logger.log(
                'SEARCH :: NZB.su :: Searching for "%s" in all categories' %
                (item), 'INFO')
            result = nzb.Search(item)

        for x in result['channel']['item']:
            x['link'] = urllib.quote(x['link'])

        logger.log(
            'SEARCH :: NZB.su :: Found %i results for %s' %
            (len(result['channel']['item']), item), 'INFO')

    else:
        result = ''

    if mobile:
        return result

    return render_template(
        'search-nzbsu.html',
        site='nzb.su',
        results=result['channel']['item'],
        item=item,
        categories=cat_newznab,
    )
Esempio n. 46
0
def add_edit_script_dialog(script_id=None):
    logger.log('SCRIPT_LAUNCHER :: add_edit_script_dialog', 'DEBUG')
    script = None
    logger.log('SCRIPT_LAUNCHER :: Getting file list', 'DEBUG')
    script_files = get_file_list(
        folder = maraschino.SCRIPT_DIR,
        extensions = ['.py', '.sh', '.pl', '.cmd'],
        prepend_path = False,
        prepend_path_minus_root = True
    )
    logger.log('SCRIPT_LAUNCHER :: Have file list', 'DEBUG')
    if script_id:
        try:
            script = Script.query.filter(Script.id == script_id).first()
        except:
            pass

    logger.log('SCRIPT_LAUNCHER :: Rendering remplate add_edit_script_dialog.html', 'DEBUG')
    return render_template('add_edit_script_dialog.html',
        script = script, script_files = script_files,
    )
Esempio n. 47
0
def get_recently_added_movies(xbmc, movie_offset=0, mobile=False):
    num_recent_videos = get_num_recent_movies()
    xbmc_label = get_recent_xbmc_label('recently_added_movies_server')
    total_movies = 0
    using_db = False

    try:
        recently_added_movies = xbmc.VideoLibrary.GetRecentlyAddedMovies(properties = ['title', 'year', 'rating', 'playcount', 'thumbnail'])['movies']
        recently_added_db_add(xbmc_label, 'movies', recently_added_movies)

        thumbs = [recent_image_file(xbmc_label, 'movies', x['movieid'])[1] for x in recently_added_movies]
        cache_dir = os.path.join(DATA_DIR, 'cache', 'xbmc', xbmc_label, 'recent_movies')

        try:
            remove_recent_images(cache_dir, thumbs)
        except:
            logger.log('Failed to delete old images from %s' % cache_dir, 'WARNING')

        for movie in recently_added_movies:
            movie['thumbnail'] = cache_recent_image(xbmc_label, 'movies', movie['movieid'], movie['thumbnail'])

    except:
        recently_added_movies = []

    if not recently_added_movies:
        try:
            logger.log('Using cached recently added movies', 'INFO')
            recently_added_movies = RecentlyAdded.query.filter(RecentlyAdded.name == '%s_movies' % xbmc_label).first().data

            for movie in recently_added_movies:
                thumb = recent_image_file(xbmc_label, 'movies', movie['movieid'])
                movie['thumbnail'] = thumb[0] + thumb[1]

            using_db = True
        except:
            recently_added_movies = []
            logger.log('Failed to get recently added movies from database', 'ERROR')

    if recently_added_movies:
        if get_setting_value('recently_added_watched_movies') == '0':
            recently_added_movies = get_unwatched(recently_added_movies)

    if mobile:
        return [recently_added_movies, using_db]

    if recently_added_movies:
        total_movies = len(recently_added_movies)
        recently_added_movies = recently_added_movies[movie_offset:num_recent_videos + movie_offset]

    return [recently_added_movies, total_movies, using_db]
Esempio n. 48
0
def xhr_play_file(file_type):
    logger.log('CONTROLS :: Playing %s file' % file_type, 'INFO')
    xbmc = jsonrpclib.Server(server_api_address())
    if file_type == "music":
        file_type = "audio"
        id = 0
    else:
        id = 1

    try:
        xhr_clear_playlist(id)
    except:
        logger.log('CONTROLS :: Failed to clear %s playlist' % file_type,
                   'DEBUG')
        return jsonify({'failed': True})

    file = request.form['file']
    file = urllib.unquote(file.encode('ascii')).decode('utf-8')

    if file_type == "video":
        player = 1
    else:
        player = 0

    try:
        item = {'file': file}
        xbmc.Playlist.Add(playlistid=player, item=item)
    except:
        logger.log('CONTROLS :: Failed to add %s to playlist' % file_type,
                   'DEBUG')
        return jsonify({'failed': True})

    try:
        item = {'playlistid': player}
        xbmc.Player.Open(item)
    except:
        logger.log('CONTROLS :: Failed to open %s' % file_type, 'DEBUG')
        return jsonify({'failed': True})

    return jsonify({'success': True})
Esempio n. 49
0
def switch_server(server_id=None):
    """
    Switches Plex servers manually.
    """
    try:
        active_server = get_setting('active_server')

        if not active_server:
            active_server = Setting('active_server', 0)
            db_session.add(active_server)
            db_session.commit()

        server = PlexServer.query.filter(PlexServer.id == server_id).first()
        if server:
            active_server.value = server_id
            db_session.add(active_server)
            db_session.commit()
            logger.log('Switched active server to ID %s' % server_id, 'INFO')
            try:
                status, msg = plex_update_sections(server_id)
                if not status:
                    logger.log('Plex :: %s' % msg, 'ERROR')
            except Exception as e:
                return jsonify(
                    success=False,
                    msg='Failed to reach server, please check log for details.'
                )
        else:
            logger.log(
                'Switching server prevented, server ID %s does not exist in db'
                % server_id, 'INFO')

    except Exception as e:
        logger.log('Error setting active server to ID %s: %s' % (server_id, e),
                   'WARNING')
        return jsonify(success=False)

    return jsonify(success=True)
Esempio n. 50
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
Esempio n. 51
0
def cp_search(message=None):
    couchpotato = {}
    params = False
    profiles = {}

    try:
        query = request.args['name']
        params = 'q=' + query
    except:
        pass

    if params:
        try:
            logger.log('CouchPotato :: Searching for movie: %s' % (query),
                       'INFO')
            couchpotato = couchpotato_api('movie.search', params=params)
            amount = len(couchpotato['movies'])
            logger.log(
                'CouchPotato :: found %i movies for %s' % (amount, query),
                'INFO')
            if couchpotato['success'] and amount != 0:
                couchpotato = couchpotato['movies']
                try:
                    # logger.log('CouchPotato :: Getting quality profiles', 'INFO')
                    profiles = couchpotato_api('profile.list')
                except Exception as e:
                    log_exception(e)
            else:
                return render_template('couchpotato/search.html',
                                       error='No movies with "%s" were found' %
                                       (query),
                                       couchpotato='results')

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

    else:
        logger.log('CouchPotato :: Loading search template', 'DEBUG')
        couchpotato = None

    return render_template('couchpotato/search.html',
                           data=couchpotato,
                           couchpotato='results',
                           profiles=profiles,
                           error=message)
Esempio n. 52
0
def delete_server(server_id=None):
    """
    Deletes a server.
    """

    try:
        xbmc_server = XbmcServer.query.get(server_id)
        db_session.delete(xbmc_server)
        db_session.commit()

        # Remove the server's cache
        label = xbmc_server.label
        recent_cache = [
            label + '_episodes', label + '_movies', label + '_albums'
        ]

        try:
            for entry in recent_cache:
                recent_db = RecentlyAdded.query.filter(
                    RecentlyAdded.name == entry).first()

                if recent_db:
                    db_session.delete(recent_db)
                    db_session.commit()
        except:
            logger.log('Failed to remove servers database cache', 'WARNING')

        image_dir = os.path.join(maraschino.DATA_DIR, 'cache', 'xbmc',
                                 xbmc_server.label)
        if os.path.isdir(image_dir):
            import shutil

            try:
                shutil.rmtree(image_dir)
            except:
                logger.log('Failed to remove servers image cache', 'WARNING')

        return render_template(
            'includes/servers.html',
            servers=XbmcServer.query.order_by(XbmcServer.position),
        )

    except:
        logger.log('Error deleting server ID %s' % server_id, 'WARNING')
        return jsonify({'status': 'error'})
Esempio n. 53
0
def xhr_headphones_album_status(albumid, status, mobile=False):
    if status == 'wanted':
        logger.log('HEADPHONES :: Marking album as wanted', 'INFO')
        command = 'queueAlbum&id=%s' % albumid
    if status == 'wanted_new':
        logger.log('HEADPHONES :: Marking album as wanted (new)', 'INFO')
        command = 'queueAlbum&new=True&id=%s' % albumid
    if status == 'skipped':
        logger.log('HEADPHONES :: Marking album as skipped', 'INFO')
        command = 'unqueueAlbum&id=%s' % albumid

    try:
        Thread(target=headphones_api, args=(command, False)).start()
    except Exception as e:
        if mobile:
            headphones_exception(e)
            return jsonify(error='failed')

        return headphones_exception(e)

    return jsonify(status='successful')
Esempio n. 54
0
def add_edit_newznab():
    name = request.form['name']
    url = request.form['url']
    apikey = request.form['apikey']

    if url.endswith('/'):
        url = url[:-1]

    if not name:
        return jsonify(error=True)
    if not apikey:
        return jsonify(error=True)
    if not url:
        return jsonify(error=True)

    if 'newznab_id' in request.form:
        logger.log('SEARCH :: Editing Newznab site %s' % request.form['newznab_id'], 'INFO')
        newznab = NewznabSite.query.filter(NewznabSite.id == request.form['newznab_id']).first()
        newznab.name = name
        newznab.url = url
        newznab.apikey = apikey

    else:
        logger.log('SEARCH :: Adding new Newznab site', 'INFO')
        newznab = NewznabSite(
            name=name,
            url=url,
            apikey=apikey
        )

    try:
        db_session.add(newznab)
        db_session.commit()

    except Exception as e:
        logger.log(e, 'DEBUG')
        return jsonify(error=True)

    return xhr_search()
Esempio n. 55
0
def cp_get_movie(id):
    """
    Retrieve movie from CP
    ---- Params -----
    id                  int (comma separated)                       The id of the movie
    """
    try:
        logger.log('CouchPotato :: Retrieving movie info', 'INFO')
        result = couchpotato_api('movie.get', 'id=%s' % id)
        try:
            logger.log('CouchPotato :: Getting quality profiles', 'INFO')
            profiles = couchpotato_api('profile.list')
        except Exception as e:
            log_exception(e)
        logger.log('CouchPotato :: Retrieving movie info (DONE)', 'INFO')
        return render_template('couchpotato/info.html',
            couchpotato=result,
            profiles=profiles,
        )
    except Exception as e:
        log_exception(e)

    return jsonify({'success': False})
Esempio n. 56
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',
    )
Esempio n. 57
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',
    )
Esempio n. 58
0
def xhr_move_playlist_item(playlistid, position1, direction):
    logger.log('CONTROLS :: Moving playlist item %s' % direction, 'INFO')
    xbmc = jsonrpclib.Server(server_api_address())

    if direction == 'up':
        if position1 != 0:
            position2 = position1 - 1
        else:
            logger.log(
                'CONTROLS :: Playlist item is already at first position',
                'INFO')
            return jsonify({'success': True})
    else:
        position2 = position1 + 1

    try:
        xbmc.Playlist.Swap(playlistid=playlistid,
                           position1=position1,
                           position2=position2)
        return jsonify({'success': True})

    except:
        logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR')
        return jsonify({'failed': True})
Esempio n. 59
0
def checkGithub():
    """Check github repo for updates"""
    logger.log('UPDATER :: Checking for updates', 'INFO')

    try:
        maraschino.LATEST_COMMIT = latestCommit()
        if maraschino.FIRST_RUN:
            maraschino.CURRENT_COMMIT = maraschino.LATEST_COMMIT
            writeVersion(maraschino.CURRENT_COMMIT)
    except:
        logger.log('UPDATER :: Could not get latest commit from github',
                   'WARNING')

    if maraschino.CURRENT_COMMIT:

        try:
            maraschino.COMMITS_BEHIND = commitsBehind()
        except:
            logger.log('UPDATER :: Could not get commits behind from github',
                       'WARNING')

        if maraschino.COMMITS_BEHIND >= 1:
            logger.log(
                'UPDATER :: Update available, you are %i commits behind' %
                maraschino.COMMITS_BEHIND, 'INFO')
            maraschino.COMMITS_COMPARE_URL = 'https://github.com/%s/maraschino/compare/%s...%s' % (
                user, maraschino.CURRENT_COMMIT, maraschino.LATEST_COMMIT)

        elif maraschino.COMMITS_BEHIND == 0:
            logger.log('UPDATER :: Up to date', 'INFO')

        elif maraschino.COMMITS_BEHIND == -1:
            logger.log('UPDATER :: Unknown version. Please run the updater',
                       'INFO')

    else:
        logger.log('UPDATER :: Unknown version. Please run the updater',
                   'INFO')

    return maraschino.COMMITS_BEHIND
Esempio n. 60
0
def Update():
    """Update maraschino installation"""
    if maraschino.USE_GIT:
        update = gitUpdate()
        if update == 'complete':
            return True
        else:
            logger.log('Git update failed, attempting tarball update', 'INFO')

    tar_file = joinRundir('maraschino.tar.gz')
    update_folder = joinRundir('maraschino-update')

    # Download repo
    try:
        logger.log('UPDATER :: Downloading update file to %s' % tar_file,
                   'DEBUG')
        url = urllib2.urlopen('https://github.com/%s/maraschino/tarball/%s' %
                              (user, branch))
        f = open(tar_file, 'wb')
        f.write(url.read())
        f.close()
    except:
        logger.log('UPDATER :: Failed to download update file', 'WARNING')
        RemoveUpdateFiles()
        return False

    # Write new hash to file
    try:
        logger.log('UPDATER :: Writing new hash to %s' % version_file, 'DEBUG')
        writeVersion(maraschino.LATEST_COMMIT)
    except:
        logger.log('UPDATER :: Faied to write new hash to version file',
                   'WARNING')
        RemoveUpdateFiles()
        return False

    # Extract to temp folder
    try:
        logger.log('UPDATER :: Extracting %s' % tar_file, 'DEBUG')
        tar = tarfile.open(tar_file)
        tar.extractall(update_folder)
        tar.close()
    except:
        logger.log('Failed to extract update file', 'WARNING')
        RemoveUpdateFiles()
        return False

    # Overwrite old files with new ones
    root_src_dir = os.path.join(
        update_folder,
        '%s-maraschino-%s' % (user, maraschino.LATEST_COMMIT[:7]))

    try:
        logger.log('UPDATER :: Overwriting old files', 'DEBUG')
        for src_dir, dirs, files in os.walk(root_src_dir):
            dst_dir = src_dir.replace(root_src_dir, RUNDIR)
            if not os.path.exists(dst_dir):
                os.mkdir(dst_dir)
            for file_ in files:
                src_file = os.path.join(src_dir, file_)
                dst_file = os.path.join(dst_dir, file_)
                if os.path.exists(dst_file):
                    os.remove(dst_file)
                shutil.move(src_file, dst_dir)
    except:
        logger.log('UPDATER :: Failed to overwrite old files', 'WARNING')
        RemoveUpdateFiles()
        return False

    # Clean up
    RemoveUpdateFiles()
    maraschino.CURRENT_COMMIT = maraschino.LATEST_COMMIT
    maraschino.COMMITS_BEHIND = 0

    return True