Example #1
0
def initialize(options={}):
    
    cherrypy.config.update({
                'log.screen':            False,
                'server.thread_pool':     10,
                'server.socket_port':     options['http_port'],
                'server.socket_host':     options['http_host'],
                'engine.autoreload_on':    False,
        })

    conf = {
        '/': {
            'tools.staticdir.root': os.path.join(minstrel.ROOT, 'www')
        },
        '/images':{
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "images"
        },
        '/css':{
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "css"
        },
        '/js':{
            'tools.staticdir.on': True,
            'tools.staticdir.dir': "js"
        },
        '/favicon.ico':{
            'tools.staticfile.on': True,
            'tools.staticfile.filename': "images/favicon.ico"
        }
    }
    
    if options['http_pass'] != "":
        
        conf['/'].update({
            'tools.auth_basic.on': True,
            'tools.auth_basic.realm': 'Minstrel',
            'tools.auth_basic.checkpassword':  cherrypy.lib.auth_basic.checkpassword_dict(
                    {options['http_user']:options['http_pass']})
        })
        

    # Prevent time-outs
    cherrypy.engine.timeout_monitor.unsubscribe()
    
    logger.info("HTTP ROOT: " + options['http_root'])
    
    cherrypy.tree.mount(MinstrelInterface(), options['http_root'], config = conf)
    
    try:
        cherrypy.process.servers.check_port(options['http_host'], options['http_port'])
        cherrypy.server.start()
    except IOError:
        logger.error("Could not bind to port {0} - Is Minstrel already running?".format(options['http_port']))
        sys.exit(0)
    
    cherrypy.server.wait()
Example #2
0
def config_val(type, section, item, default):
    try:
        if type == 'int':
            val = int(CONFIG[section][item])
        else:
            val = CONFIG[section][item]
    except:
        val = default
        try:
            CONFIG[section][item] = val
        except:
            CONFIG[section] = {}
            CONFIG[section][item] = val
    
    logger.info('[{0}][{1}] -> {2}'.format(section, item, val))
    return val
Example #3
0
def shutdown(restart=False, update=False):
    cherrypy.engine.exit();
    
    config_write();
    
    if update:
        pass
    
    if restart:
        popen_list = [sys.executable, MINSTREL_FULLNAME]
        popen_list += ARGS
        if '--nolaunch' not in popen_list:
            popen_list += ['--nolaunch']
        logger.info("Restarting Minstrel with " + str(popen_list))
        subprocess.Popen(popen_list, cwd=os.getcwd())
    
    os._exit(0)
            
Example #4
0
def init():
    with INIT_LOCK:
    
        global __INITIALIZED__, ROOT, DATA_DIR, CONFIG_FILE, CONFIG, DATABASE_FILE, ARGS, ARGS_COMPILED, \
            QUIET, DAEMON, MINSTREL_NAME, HTTP_PORT, HTTP_HOST, HTTP_USER, HTTP_PASS, HTTP_ROOT, \
            LAUNCH_BROWSER, LOG_DIR, TEMPLATES
    
        if __INITIALIZED__:
            return False
        
        # Start the logger
        logger.minstrel_log.initLogger(quiet=QUIET)
        
        # Check configurations
        logger.info("Checking config...")
        check_config_section('General')
        
        try:
            HTTP_PORT = config_int('General', 'http_port', 8085)
        except:
            HTTP_PORT = 8085
        
        if HTTP_PORT < 21 or HTTP_PORT > 65535:
            logger.warn("Invalid HTTP Port setting")
            HTTP_PORT = 8085
        
        # Check all the other HTTP parts
        HTTP_HOST = config_str('General', 'http_host', '0.0.0.0')
        HTTP_USER = config_str('General', 'http_user', '')
        HTTP_PASS = config_str('General', 'http_pass', '')
        HTTP_ROOT = config_str('General', 'http_root', '/')
        
        LAUNCH_BROWSER = bool(config_int('General','launch_browser', 1))
        
        # Check the database
        logger.info("Checking database tables...")
        check_database()
        
        # @todo: Put Some Versioning Check Stuff Here
        # @todo: Git Integration Goes here too
        
        __INITIALIZED__ = True
        return True
Example #5
0
 def restart(self):
     logger.info("Minstrel is restarting (Browser request)")
     threading.Timer(2, minstrel.shutdown, [True]).start()
     return "Restarting minstrel"
     
Example #6
0
 def shutdown(self):
     logger.info("Minstrel is shutting down (Browser request)")
     threading.Timer(2, minstrel.shutdown).start()
     return "Stopping minstrel"
Example #7
0
 def home(self):
     page = PageTemplate(file="dashboard.tmpl")
     logger.info("Web hit /home")
     
     return _sanitize(page)
Example #8
0
def main():
    """
    Main start function
    """
    
    # Fixed Path
    if hasattr(sys, 'frozen'):
        minstrel.MINSTREL_FULLNAME = os.path.normpath(os.path.abspath(sys.executable))
    else: 
        minstrel.MINSTREL_FULLNAME = os.path.normpath(os.path.abspath(__file__))
    
    # File name
    minstrel.MINSTREL_NAME = os.path.basename(minstrel.MINSTREL_FULLNAME)
    
    # Root Directory
    minstrel.ROOT = os.path.dirname(minstrel.MINSTREL_FULLNAME)
    
    # Data Directory
    minstrel.DATA_DIR = os.path.join(minstrel.ROOT, 'data');
    
    # Log directory
    minstrel.LOG_DIR = os.path.join(minstrel.ROOT, 'logs');
    
    # Template Dir
    minstrel.TEMPLATES = os.path.join(minstrel.ROOT, 'www/interfaces/default')
    
    # Arguments
    minstrel.ARGS = sys.argv[1:]
    
    # Argument Parser
    parser = argparse.ArgumentParser(description='Music library management and SABnzbd+ helper')
    
    parser.add_argument('-q', '--quiet', action='store_true', help='Turn off console logging')
    parser.add_argument('-d', '--daemon', action='store_true', help='Run Minstrel as a daemon')
    parser.add_argument('-p', '--port', type=int, help='Force minstrel to run on a specific port')
    parser.add_argument('--config', help='Specify a config file to use')
    parser.add_argument('--nolaunch', action='store_true', help='Prevent the browser from launching when Minstrel starts')
    
    args = parser.parse_args()
    minstrel.ARGS_COMPILED = args
    
    if args.quiet:
        minstrel.QUIET = True
    
    if args.daemon:
        minstrel.QUIET = True
        minstrel.DAEMON = True
    
    if args.config:
        minstrel.CONFIG_FILE = args.config
    else:
        minstrel.CONFIG_FILE = os.path.join(minstrel.ROOT, 'config.ini')
    
    # Attempt to create the data directory
    if not os.path.exists(minstrel.DATA_DIR):
        try:
            os.makedirs(minstrel.DATA_DIR)
        except OSError:
            raise SystemExit('Data directory does not exist and could not be created: ' + minstrel.DATA_DIR)
    
    # Log Directory
    if not os.path.exists(minstrel.LOG_DIR):
        try:
            os.makedirs(minstrel.LOG_DIR)
        except OSError:
            raise SystemExit('Log directory does not exist and could not be created: ' + minstrel.LOG_DIR)
    
    # Make sure we can write to the data directory
    if not os.access(minstrel.DATA_DIR, os.W_OK):
        raise SystemExit('Data directory is not writable: ' + minstrel.DATA_DIR)
    
    # Database
    minstrel.DATABASE_FILE = os.path.join(minstrel.DATA_DIR, 'minstrel.db')
    
    # Config Object
    minstrel.CONFIG = ConfigObj(minstrel.CONFIG_FILE)
    
    # Name our thread
    threading.currentThread().name = "MAIN"
    
    # Actually start doing stuff now
    minstrel.init()
    
    # Are we running a daemon
    if minstrel.DAEMON:
        minstrel.daemonize();
    
    # Lets start the webserver
    if args.port:
        http_port = args.port
        logger.info("Starting Minstrel with forced port: %i" % http_port)
    else:
        http_port = minstrel.HTTP_PORT
    
    webStart.initialize({
         'http_port':   http_port,
         'http_host':   minstrel.HTTP_HOST,
         'http_root':   minstrel.HTTP_ROOT,
         'http_user':   minstrel.HTTP_USER,
         'http_pass':   minstrel.HTTP_PASS
         })