def add_edit_application(): name = request.form['name'] url = request.form['url'] description = request.form['description'] image = request.form['image'] position = request.form['position'] if name == '' or url == '': return jsonify({'status': 'error'}) if position == '': position = None if 'application_id' in request.form: application = Application.query.filter( Application.id == request.form['application_id']).first() application.name = name application.url = url application.description = description application.image = image application.position = position else: application = Application( name, url, description, image, position, ) db_session.add(application) db_session.commit() return xhr_applications()
def add_edit_disk(): path = request.form['path'] name = request.form['name'] group = request.form['group'] position = request.form['position'] if path == '': return jsonify({'status': 'error'}) if position == '': position = None if 'disk_id' in request.form: disk = HardDisk.query.filter(HardDisk.id == request.form['disk_id']).first() disk.data = {'path': path, 'name': name, 'group': group} disk.position = position else: disk = HardDisk( data={'path': path, 'name': name, 'group': group}, position=position, ) try: db_session.add(disk) db_session.commit() except: return jsonify({'status': 'error'}) return xhr_diskspace()
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')
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()
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
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()
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' })
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())
def add_edit_disk(): path = request.form['path'] position = request.form['position'] if path == '': return jsonify({ 'status': 'error' }) if position == '': position = None if 'disk_id' in request.form: disk = Disk.query.filter(Disk.id == request.form['disk_id']).first() disk.path = path disk.position = position else: disk = Disk( path, position, ) try: disk_usage(disk.path) db_session.add(disk) db_session.commit() except: return jsonify({ 'status': 'error' }) return xhr_diskspace()
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
def add_edit_application(): name = request.form['name'] url = request.form['url'] description = request.form['description'] image = request.form['image'] position = request.form['position'] if name == '' or url == '': return jsonify({ 'status': 'error' }) if position == '': position = None if 'application_id' in request.form: application = Application.query.filter(Application.id == request.form['application_id']).first() application.name = name application.url = url application.description = description application.image = image application.position = position else: application = Application( name, url, description, image, position, ) db_session.add(application) db_session.commit() return xhr_applications()
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)
def module_settings_save(name): """Save options in settings dialog""" try: settings = json.JSONDecoder().decode(request.form['settings']) except: return jsonify({ 'status': 'error' }) for s in settings: # poll and delay are stored in the modules tables if s['name'] == 'poll' or s['name'] == 'delay': module = get_module(name) if s['name'] == 'poll': module.poll = int(s['value']) if s['name'] == 'delay': module.delay = int(s['value']) db_session.add(module) # other settings are stored in the settings table else: setting = get_setting(s['name']) if not setting: setting = Setting(s['name']) setting.value = s['value'] db_session.add(setting) if s['name'] == 'maraschino_username': maraschino.AUTH['username'] = s['value'] if s['value'] != '' else None if s['name'] == 'maraschino_password': maraschino.AUTH['password'] = s['value'] if s['value'] != '' else None db_session.commit() # you can't cancel server settings - instead, return an updated template # with 'Settings saved' text on the button if name == 'server_settings': return extra_settings_dialog(dialog_type='server_settings', updated=True) elif name == 'plex_login': from maraschino.noneditable import json_login try: return json_login() except: logger.log('Plex :: Failed to populate servers with new credentials', 'ERROR') # for everything else, return the rendered module return module_settings_cancel(name)
def plex_update_sections(id): db_section = { 'movie': {'size': 0, 'sections': {}, 'label': 'movie', 'preferred': 0}, 'home': {'size': 0, 'sections': {}, 'label': 'home', 'preferred': 0}, 'photo': {'size': 0, 'sections': {}, 'label': 'photo', 'preferred': 0}, 'artist': {'size': 0, 'sections': {}, 'label': 'artist', 'preferred': 0}, 'show': {'size': 0, 'sections': {}, 'label': 'show', 'preferred': 0}, } # attempt to get sections from server dbserver = PlexServer.query.filter(PlexServer.id == id).first() try: server = Server(dbserver.localAddresses, token=dbserver.token) sections = server.sections() if not sections: return (False, 'Failed to get sections') except: return (False, 'Failed to retrieve server with id: %i' %id) # keeping old preferred sections try: db_section['movie']['preferred'] = dbserver.sections['movie']['preferred'] db_section['home']['preferred'] = dbserver.sections['home']['preferred'] db_section['photo']['preferred'] = dbserver.sections['photo']['preferred'] db_section['artist']['preferred'] = dbserver.sections['artist']['preferred'] db_section['show']['preferred'] = dbserver.sections['show']['preferred'] except: pass # Go through each section and add it to new section dictionary try: for section in sections: if 'video' in section['thumb']: section['type'] = u'home' db_section[section['type']]['sections'].update( { db_section[section['type']]['size']: { 'key': section['key'], 'type': section['type'], 'title': section['title'], 'uuid': section['uuid'] } } ) db_section[section['type']]['size'] += 1 dbserver.sections = db_section db_session.add(dbserver) db_session.commit() logger.log('Plex :: Successfully updated %s sections' % server, 'INFO') except: logger.log('Plex :: Failed to update sections for server', 'ERROR') return (False, 'Failed to update sections for server') return (True, None)
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"})
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')
def add_module(): """Add a new module to Maraschino""" try: module_id = request.form['module_id'] column = request.form['column'] position = request.form['position'] # make sure that it's a valid module module_info = get_module_info(module_id) if not module_info: raise Exception except: return jsonify({ 'status': 'error' }) module = Module( module_info['name'], column, position, module_info['poll'], module_info['delay'], ) db_session.add(module) # if module template has extra settings then create them in the database # with default values if they don't already exist if 'settings' in module_info: for s in module_info['settings']: setting = get_setting(s['key']) if not setting: setting = Setting(s['key'], s['value']) db_session.add(setting) db_session.commit() module_info['template'] = '%s.html' % (module_info['name']) # if the module is static and doesn't have any extra settings, return # the rendered module if module_info['static'] and not 'settings' in module_info: return render_template('placeholder_template.html', module = module_info ) # otherwise return the rendered module settings dialog else: return module_settings_dialog(module_info['name'])
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')
def init_xbmc_media_settings(): ''' If library settings are not in database, add them with default value. ''' for setting in library_settings: for s in library_settings[setting]: if get_setting(s['key']) == None: new_setting = Setting(key=s['key'], value=s['value']) db_session.add(new_setting) db_session.commit() return
def init_xbmc_media_settings(): """ If library settings are not in database, add them with default value. """ for setting in library_settings: for s in library_settings[setting]: if get_setting(s["key"]) == None: new_setting = Setting(key=s["key"], value=s["value"]) db_session.add(new_setting) db_session.commit() return
def module_settings_save(name): """Save options in settings dialog""" try: settings = json.JSONDecoder().decode(request.form["settings"]) except: return jsonify({"status": "error"}) for s in settings: # poll and delay are stored in the modules tables if s["name"] == "poll" or s["name"] == "delay": module = get_module(name) if s["name"] == "poll": module.poll = int(s["value"]) if s["name"] == "delay": module.delay = int(s["value"]) db_session.add(module) # other settings are stored in the settings table else: setting = get_setting(s["name"]) if not setting: setting = Setting(s["name"]) setting.value = s["value"] db_session.add(setting) if s["name"] == "maraschino_username": maraschino.AUTH["username"] = s["value"] if s["value"] != "" else None if s["name"] == "maraschino_password": maraschino.AUTH["password"] = s["value"] if s["value"] != "" else None db_session.commit() # you can't cancel server settings - instead, return an updated template # with 'Settings saved' text on the button if name == "server_settings": return extra_settings_dialog(dialog_type="server_settings", updated=True) # for everything else, return the rendered module return module_settings_cancel(name)
def recently_added_db_add(server, media_type, recently_added): name = '%s_%s' % (server, media_type) if RecentlyAdded.query.filter(RecentlyAdded.name == name).first() == None: db_session.add(RecentlyAdded(name=name, data=[])) db_session.commit() recent = RecentlyAdded.query.filter(RecentlyAdded.name == name).first() if recently_added: recent.data = recently_added db_session.add(recent) db_session.commit() return
def save_xbmc_settings(media_type): """Save options in settings dialog""" try: settings = json.loads(request.form['settings']) for s in settings: setting = get_setting(s['name']) setting.value = s['value'] db_session.add(setting) db_session.commit() except: return jsonify(error=True) return jsonify(success=True)
def save_xbmc_settings(media_type): """Save options in settings dialog""" try: settings = json.loads(request.form["settings"]) for s in settings: setting = get_setting(s["name"]) setting.value = s["value"] db_session.add(setting) db_session.commit() except: return jsonify(error=True) return jsonify(success=True)
def add_module(): """Add a new module to Maraschino""" try: module_id = request.form["module_id"] column = request.form["column"] position = request.form["position"] # make sure that it's a valid module module_info = get_module_info(module_id) if not module_info: raise Exception except: return jsonify({"status": "error"}) module = Module(module_info["name"], column, position, module_info["poll"], module_info["delay"]) db_session.add(module) # if module template has extra settings then create them in the database # with default values if they don't already exist if "settings" in module_info: for s in module_info["settings"]: setting = get_setting(s["key"]) if not setting: setting = Setting(s["key"], s["value"]) db_session.add(setting) db_session.commit() module_info["template"] = "%s.html" % (module_info["name"]) # if the module is static and doesn't have any extra settings, return # the rendered module if module_info["static"] and not "settings" in module_info: return render_template("placeholder_template.html", module=module_info) # otherwise return the rendered module settings dialog else: return module_settings_dialog(module_info["name"])
def script_status(script_id): status = request.form['status'] if status == '': return jsonify({ 'status': 'error: there was no status passed in' }) script = Script.query.filter(Script.id == script_id).first() script.status = status try: db_session.add(script) db_session.commit() except: return jsonify({ 'status': 'error' }) return script_launcher()
def script_status(script_id): status = request.form['status'] if status == '': return jsonify({'status': 'error: there was no status passed in'}) script = Script.query.filter(Script.id == script_id).first() script.status = status try: db_session.add(script) db_session.commit() except: return jsonify({'status': 'error'}) return script_launcher()
def module_settings_save(name): try: settings = json.JSONDecoder().decode(request.form['settings']) except: return jsonify({ 'status': 'error' }) for s in settings: # poll and delay are stored in the modules tables if s['name'] == 'poll' or s['name'] == 'delay': module = get_module(name) if s['name'] == 'poll': module.poll = int(s['value']) if s['name'] == 'delay': module.delay = int(s['value']) db_session.add(module) # other settings are stored in the settings table else: setting = get_setting(s['name']) if not setting: setting = Setting(s['name']) setting.value = s['value'] db_session.add(setting) db_session.commit() # you can't cancel server settings - instead, return an updated template # with 'Settings saved' text on the button if name == 'server_settings': return server_settings_dialog(updated=True) # for everything else, return the rendered module return module_settings_cancel(name)
def switch_server(server_id=None): """ Switches XBMC servers. """ xbmc_server = XbmcServer.query.get(server_id) try: active_server = get_setting("active_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") except: logger.log("Error setting active server to ID %s" % server_id, "WARNING") return jsonify({"status": "error"}) return jsonify({"status": "success"})
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())
def switch_server(server_id=None): """ Switches XBMC servers. """ xbmc_server = XbmcServer.query.get(server_id) try: active_server = get_setting('active_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') except: logger.log('Error setting active server to ID %s' % server_id , 'WARNING') return jsonify({ 'status': 'error' }) return jsonify({ 'status': 'success' })
def plex_database_upgrade_check(): logger.log('Starting database upgrade check.', 'INFO') from maraschino.models import XbmcServer, MediaServer from maraschino.database import db_session # Check for any servers in the legacy 'XbmcServer' table. If found migrate over to the new tables servers = XbmcServer.query.order_by(XbmcServer.position) for server in servers: # We have servers so migrate them logger.log("The server named '" + server.label + "' is being upgraded!", 'INFO') newServer = MediaServer(server.label, 'XBMC', {'hostname': server.hostname, 'port': server.port, 'username': server.username, 'password': server.password, 'mac_address': server.mac_address}, server.position) db_session.add(newServer) db_session.delete(server) db_session.commit() logger.log('Finished database upgrade check', 'INFO')
def xhr_script_status(script_id): status = request.form['status'] if status == '': return jsonify({ 'status': 'error: there was no status passed in' }) script = Script.query.filter(Script.id == script_id).first() script.status = status try: db_session.add(script) db_session.commit() except: logger.log('SCRIPT_LAUNCHER :: Add Failed', 'ERROR') return jsonify({ 'status': 'error' }) return xhr_script_launcher()
def rearrange_modules(): """Rearrange a module on the page""" try: modules = json.JSONDecoder().decode(request.form["modules"]) except: return jsonify({"status": "error"}) for module in modules: try: m = Module.query.filter(Module.name == module["name"]).first() m.column = module["column"] m.position = module["position"] db_session.add(m) except: pass db_session.commit() return jsonify({"status": "success"})
def rearrange_modules(): """Rearrange a module on the page""" try: modules = json.JSONDecoder().decode(request.form['modules']) except: return jsonify({ 'status': 'error' }) for module in modules: try: m = Module.query.filter(Module.name == module['name']).first() m.column = module['column'] m.position = module['position'] db_session.add(m) except: pass db_session.commit() return jsonify({ 'status': 'success' })
def rearrange_modules(): """Rearrange a module on the page""" try: modules = json.JSONDecoder().decode(request.form['modules']) except: return jsonify({'status': 'error'}) for module in modules: try: m = Module.query.filter(Module.name == module['name']).first() m.column = module['column'] m.position = module['position'] db_session.add(m) except: pass db_session.commit() return jsonify({'status': 'success'})
def legacy_disk_migrate(): logger.log('DISKSPACE :: Migrating legacy disks', 'INFO') disks_db_old = Disk.query.order_by(Disk.position) for disk_old in disks_db_old: disk = HardDisk(data={ 'path': disk_old.path, 'name': disk_old.path, 'group': '', }, position=disk_old.position) try: db_session.add(disk) db_session.delete(disk_old) db_session.commit() except: return jsonify({'status': 'error'})
def addServer(name, address, port, scheme, host, localAddresses, machineIdentifier, createdAt, updatedAt, synced, version, owned, token): s = PlexServer.query.filter( PlexServer.machineIdentifier == machineIdentifier).first() if s: logger.log('Plex :: Updating PlexServer %s in db' % (name), 'INFO') s.name = name s.address = address s.port = port s.scheme = scheme s.host = host s.localAddresses = localAddresses s.machineIdentifier = machineIdentifier s.createdAt = createdAt s.updatedAt = updatedAt s.synced = synced s.version = version s.owned = owned s.token = token else: logger.log('Plex :: Adding PlexServer %s to db' % (name), 'INFO') s = PlexServer( name, address, port, scheme, host, localAddresses, machineIdentifier, createdAt, updatedAt, synced, version, owned, token, ) db_session.add(s) db_session.commit()
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()
def legacy_disk_migrate(): logger.log('DISKSPACE :: Migrating legacy disks', 'INFO') disks_db_old = Disk.query.order_by(Disk.position) for disk_old in disks_db_old: disk = HardDisk( data={ 'path': disk_old.path, 'name': disk_old.path, 'group': '', }, position=disk_old.position ) try: db_session.add(disk) db_session.delete(disk_old) db_session.commit() except: return jsonify({'status': 'error'})
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)
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' })
def index(): from maraschino.models import Module, Setting, Application, XbmcServer from maraschino.database import db_session unorganised_modules = Module.query.order_by(Module.position) num_columns = get_setting_value('num_columns') try: num_columns = int(num_columns) except: logger.log( 'Could not retrieve number of columns settings. Defaulting to 3.', 'WARNING') num_columns = 3 modules = [] for i in range(num_columns): modules.append([]) for module in unorganised_modules: module_info = get_module_info(module.name) module.template = '%s.html' % (module.name) module.static = module_info['static'] if module.column <= num_columns: modules[module.column - 1].append(module) else: modules[num_columns - 1].append( module) # if in a column out of range, place in last column applications = [] try: applications = Application.query.order_by(Application.position) except: pass new_tab = get_setting_value('app_new_tab') == '1' # display random background when not watching media (if setting enabled) # only changes on page refresh background = None if get_setting_value('random_backgrounds') == '1': try: backgrounds = [] custom_dir = 'static/images/backgrounds/custom/' if os.path.exists(os.path.dirname(custom_dir)): # use user-defined custom background backgrounds.extend(get_file_list(custom_dir, ['.jpg', '.png'])) # if no images in directory, use default background that is set in stylesheet if len(backgrounds) == 0: backgrounds = None else: # use backgrounds bundled with Maraschino backgrounds.extend( get_file_list('static/images/backgrounds/', ['.jpg', '.png'])) # select random background background = backgrounds[random.randrange(0, len(backgrounds))] if maraschino.WEBROOT: background = maraschino.WEBROOT + '/' + background except: background = None # show fanart backgrounds when watching media fanart_backgrounds = get_setting_value('fanart_backgrounds') == '1' # get list of servers servers = XbmcServer.query.order_by(XbmcServer.position) if servers.count() == 0: # check if old server settings value is set old_server_hostname = get_setting_value('server_hostname') # create an XbmcServer entry using the legacy settings if old_server_hostname: xbmc_server = XbmcServer( 'XBMC server 1', 1, old_server_hostname, get_setting_value('server_port'), get_setting_value('server_username'), get_setting_value('server_password'), get_setting_value('server_macaddress'), ) try: db_session.add(xbmc_server) db_session.commit() servers = XbmcServer.query.order_by(XbmcServer.position) except: logger.log( 'Could not create new XbmcServer based on legacy settings', 'WARNING') active_server = get_setting_value('active_server') if active_server and active_server != 'undefined': active_server = int(active_server) else: active_server = 1 # show currently playing bar? if get_setting_value('show_currently_playing') == None: show_currently_playing = True else: show_currently_playing = int( get_setting_value('show_currently_playing')) > 0 return render_template( 'index.html', modules=modules, num_columns=num_columns, servers=servers, active_server=active_server, show_currently_playing=show_currently_playing, search_enabled=get_setting_value('search') == '1', background=background, fanart_backgrounds=fanart_backgrounds, applications=applications, show_tutorial=unorganised_modules.count() == 0, show_music=get_setting_value('library_show_music') == '1', show_pvr=get_setting_value('library_show_pvr') == '1', show_files=get_setting_value('library_show_files') == '1', show_power=get_setting_value('library_show_power_buttons') == '1', webroot=maraschino.WEBROOT, kiosk=maraschino.KIOSK, new_tab=new_tab, title_color=get_setting_value('title_color'))
def plex_update_sections(id): db_section = { 'movie': { 'size': 0, 'sections': {}, 'label': 'movie', 'preferred': 0 }, 'home': { 'size': 0, 'sections': {}, 'label': 'home', 'preferred': 0 }, 'photo': { 'size': 0, 'sections': {}, 'label': 'photo', 'preferred': 0 }, 'artist': { 'size': 0, 'sections': {}, 'label': 'artist', 'preferred': 0 }, 'show': { 'size': 0, 'sections': {}, 'label': 'show', 'preferred': 0 }, } # attempt to get sections from server dbserver = PlexServer.query.filter(PlexServer.id == id).first() try: logger.log( 'Accessing Plex Media Server on address %s' % (dbserver.localAddresses), 'DEBUG') server = Server(dbserver.localAddresses, token=dbserver.token) sections = server.sections() if not sections: return (False, 'Failed to get sections') except: logger.log( 'Failed to access Plex Media Server locally, trying external address: %s' % (dbserver.host), 'DEBUG') try: server = Server(dbserver.host, token=dbserver.token) sections = server.sections() if not sections: return (False, 'Failed to get sections') else: logger.log( 'Server connected successfully, marking server as external', 'DEBUG') dbserver.localAddresses = dbserver.host except: return (False, 'Failed to retrieve server with id: %i' % id) # keeping old preferred sections try: db_section['movie']['preferred'] = dbserver.sections['movie'][ 'preferred'] db_section['home']['preferred'] = dbserver.sections['home'][ 'preferred'] db_section['photo']['preferred'] = dbserver.sections['photo'][ 'preferred'] db_section['artist']['preferred'] = dbserver.sections['artist'][ 'preferred'] db_section['show']['preferred'] = dbserver.sections['show'][ 'preferred'] except: pass # Go through each section and add it to new section dictionary try: for section in sections: if 'video' in section['thumb']: section['type'] = u'home' db_section[section['type']]['sections'].update({ db_section[section['type']]['size']: { 'key': section['key'], 'type': section['type'], 'title': section['title'], 'uuid': section['uuid'] } }) db_section[section['type']]['size'] += 1 dbserver.sections = db_section db_session.add(dbserver) db_session.commit() logger.log('Plex :: Successfully updated %s sections' % server, 'INFO') except: logger.log('Plex :: Failed to update sections for server', 'ERROR') return (False, 'Failed to update sections for server') return (True, None)
def change_sort(media, value): setting = get_setting('xbmc_' + media + '_sort') setting.value = value db_session.add(setting) db_session.commit()