def run(self): if self.enable_https: protocol = "https" self.server = HTTPServer(self.app, ssl_options={ "certfile": self.https_cert, "keyfile": self.https_key }) else: protocol = "http" self.server = HTTPServer(self.app) logging.info("Starting SiCKRAGE web server on [{}://{}:{}/]".format( protocol, self.options[b'host'], self.options[b'port'])) try: self.server.listen(self.options[b'port'], self.options[b'host']) except: if sickbeard.LAUNCH_BROWSER and not self.daemon: sickbeard.launchBrowser( 'https' if sickbeard.ENABLE_HTTPS else 'http', self.options[b'port'], sickbeard.WEB_ROOT) logging.info("Launching browser and exiting") logging.info( "Could not start webserver on port %s, already in use!" % self.options[b'port']) ek(os._exit, 1) try: self.io_loop.start() self.io_loop.close(True) except (IOError, ValueError): # Ignore errors like "ValueError: I/O operation on closed kqueue fd". These might be thrown during a reload. pass
def run(self): if self.enable_https: protocol = "https" self.server = HTTPServer(self.app, ssl_options={"certfile": self.https_cert, "keyfile": self.https_key}) else: protocol = "http" self.server = HTTPServer(self.app) logging.info("Starting SiCKRAGE web server on [{}://{}:{}/]".format(protocol, self.options[b'host'], self.options[b'port'])) try: self.server.listen(self.options[b'port'], self.options[b'host']) except: if sickbeard.LAUNCH_BROWSER and not self.daemon: sickbeard.launchBrowser('https' if sickbeard.ENABLE_HTTPS else 'http', self.options[b'port'], sickbeard.WEB_ROOT) logging.info("Launching browser and exiting") logging.info("Could not start webserver on port %s, already in use!" % self.options[b'port']) ek(os._exit, 1) try: self.io_loop.start() self.io_loop.close(True) except (IOError, ValueError): # Ignore errors like "ValueError: I/O operation on closed kqueue fd". These might be thrown during a reload. pass
def run(self): if self.enable_https: protocol = 'https' self.server = HTTPServer(self.app, ssl_options={'certfile': self.https_cert, 'keyfile': self.https_key}) else: protocol = 'http' self.server = HTTPServer(self.app) logger.log('Starting Medusa on {scheme}://{host}:{port}/'.format (scheme=protocol, host=self.options['host'], port=self.options['port'])) try: self.server.listen(self.options['port'], self.options['host']) except Exception: if sickbeard.LAUNCH_BROWSER and not self.daemon: sickbeard.launchBrowser('https' if sickbeard.ENABLE_HTTPS else 'http', self.options['port'], sickbeard.WEB_ROOT) logger.log('Launching browser and exiting') logger.log('Could not start the web server on port {port}, already in use!'.format(port=self.options['port'])) os._exit(1) # pylint: disable=protected-access try: self.io_loop.start() self.io_loop.close(True) except (IOError, ValueError): # Ignore errors like 'ValueError: I/O operation on closed kqueue fd'. These might be thrown during a reload. pass
def run(self): if self.enable_https: protocol = "https" self.server = HTTPServer(self.app, ssl_options={"certfile": self.https_cert, "keyfile": self.https_key}) else: protocol = "http" self.server = HTTPServer(self.app) logger.log(u"Starting SickRage on " + protocol + "://" + str(self.options['host']) + ":" + str( self.options['port']) + "/") try: self.server.listen(self.options['port'], self.options['host']) except Exception: if sickbeard.LAUNCH_BROWSER and not self.daemon: sickbeard.launchBrowser('https' if sickbeard.ENABLE_HTTPS else 'http', self.options['port'], sickbeard.WEB_ROOT) logger.log(u"Launching browser and exiting") logger.log(u"Could not start webserver on port {0}, already in use!".format(self.options['port'])) os._exit(1) # pylint: disable=protected-access try: self.io_loop.start() self.io_loop.close(True) except (IOError, ValueError): # Ignore errors like "ValueError: I/O operation on closed kqueue fd". These might be thrown during a reload. pass
def run(self): if self.enable_https: protocol = "https" self.server = HTTPServer(self.app, ssl_options={"certfile": self.https_cert, "keyfile": self.https_key}) else: protocol = "http" self.server = HTTPServer(self.app) logger.log( u"Starting SickRage on " + protocol + "://" + str(self.options["host"]) + ":" + str(self.options["port"]) + "/" ) try: self.server.listen(self.options["port"], self.options["host"]) except Exception: if sickbeard.LAUNCH_BROWSER and not self.daemon: sickbeard.launchBrowser( "https" if sickbeard.ENABLE_HTTPS else "http", self.options["port"], sickbeard.WEB_ROOT ) logger.log(u"Launching browser and exiting") logger.log(u"Could not start webserver on port {0}, already in use!".format(self.options["port"])) os._exit(1) # pylint: disable=protected-access try: self.io_loop.start() self.io_loop.close(True) except (IOError, ValueError): # Ignore errors like "ValueError: I/O operation on closed kqueue fd". These might be thrown during a reload. pass
def run(self): if self.enable_https: protocol = "https" ssl_options = {"certfile": self.https_cert, "keyfile": self.https_key} else: protocol = "http" ssl_options = None logger.log("Starting SickRage on " + protocol + "://" + str(self.options['host']) + ":" + str( self.options['port']) + "/") try: self.server = self.app.listen(self.options['port'], self.options['host'], ssl_options=ssl_options, xheaders=sickbeard.HANDLE_REVERSE_PROXY, protocol=protocol) except SocketError as ex: err_msg = "" if ex.errno == errno.EADDRINUSE: # Address/port combination already in use if sickbeard.LAUNCH_BROWSER and not self.daemon: sickbeard.launchBrowser('https' if sickbeard.ENABLE_HTTPS else 'http', self.options['port'], sickbeard.WEB_ROOT) logger.log("Launching browser and exiting") err_msg = "already in use!" logger.log("Could not start webserver on port {0}: {1}".format(self.options['port'], err_msg or ex)) os._exit(1) # pylint: disable=protected-access except Exception as ex: logger.log("Could not start webserver on port {0}: {1}".format(self.options['port'], ex)) os._exit(1) # pylint: disable=protected-access try: self.io_loop.start() self.io_loop.close(True) except (IOError, ValueError): # Ignore errors like "ValueError: I/O operation on closed kqueue fd". These might be thrown during a reload. pass
def startup(): # Fire up all our threads sickbeard.start() # Launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER and not noLaunch and not sickbeard.DAEMON: sickbeard.launchBrowser(startPort) # Start an update if we're supposed to if forceUpdate or sickbeard.UPDATE_SHOWS_ON_START: sickbeard.showUpdateScheduler.action.run(force=True) # @UndefinedVariable
def startup(): # Fire up all our threads sickbeard.start() # Launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER and not noLaunch and not sickbeard.DAEMON: sickbeard.launchBrowser(startPort) # Start an update if we're supposed to if forceUpdate or sickbeard.UPDATE_SHOWS_ON_START: sickbeard.showUpdateScheduler.action.run( force=True) # @UndefinedVariable
def run(self): global restart, startPort, forceUpdate, noLaunch, web_options # Use this PID for everything sickbeard.PID = os.getpid() try: webserveInit.initWebServer(web_options) except IOError: logger.log(u"Unable to start web server, is something else running on port %d?" % startPort, logger.ERROR) if sickbeard.LAUNCH_BROWSER and not sickbeard.DAEMON: logger.log(u"Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser(startPort) sys.exit() # Fire up all our threads sickbeard.start() # Launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER and not noLaunch: sickbeard.launchBrowser(startPort) if sickbeard.LAUNCH_BROWSER and not (noLaunch or sickbeard.DAEMON or restart): sickbeard.launchBrowser(startPort) # reset this if sickrage was restarted restart = False # start IO loop IOLoop.current().start() # close IO loop IOLoop.current().close(True) # stop all tasks sickbeard.halt() # save all shows to DB sickbeard.saveAll()
class SickRage(object): def __init__(self): # system event callback for shutdown/restart sickbeard.events = Events(self.shutdown) # daemon constants self.runAsDaemon = False self.CREATEPID = False self.PIDFILE = '' # webserver constants self.webserver = None self.forcedPort = None self.noLaunch = False def help_message(self): """ print help message for commandline options """ help_msg = "\n" help_msg += "Usage: " + sickbeard.MY_FULLNAME + " <option> <another option>\n" help_msg += "\n" help_msg += "Options:\n" help_msg += "\n" help_msg += " -h --help Prints this message\n" help_msg += " -q --quiet Disables logging to console\n" help_msg += " --nolaunch Suppress launching web browser on startup\n" if sys.platform == 'win32' or sys.platform == 'darwin': help_msg += " -d --daemon Running as real daemon is not supported on Windows\n" help_msg += " On Windows and MAC, --daemon is substituted with: --quiet --nolaunch\n" else: help_msg += " -d --daemon Run as double forked daemon (includes options --quiet --nolaunch)\n" help_msg += " --pidfile=<path> Combined with --daemon creates a pidfile (full path including filename)\n" help_msg += " -p <port> --port=<port> Override default/configured port to listen on\n" help_msg += " --datadir=<path> Override folder (full path) as location for\n" help_msg += " storing database, configfile, cache, logfiles \n" help_msg += " Default: " + sickbeard.PROG_DIR + "\n" help_msg += " --config=<path> Override config filename (full path including filename)\n" help_msg += " to load configuration from \n" help_msg += " Default: config.ini in " + sickbeard.PROG_DIR + " or --datadir location\n" help_msg += " --noresize Prevent resizing of the banner/posters even if PIL is installed\n" return help_msg def fix_clients_nonsense(self): files = ["sickbeard/clients/download_station.py", "sickbeard/clients/utorrent.py", "sickbeard/clients/qbittorrent.py", "sickbeard/clients/transmission.py", "sickbeard/clients/deluge.py", "sickbeard/clients/deluged.py", "sickbeard/clients/rtorrent.py" ] for file in files: file = ek.ek(os.path.join, sickbeard.PROG_DIR, file) try: if ek.ek(os.path.exists, file): ek.ek(os.remove, file) except: pass try: if ek.ek(os.path.exists, file + "c"): ek.ek(os.remove, file + "c") except: pass def start(self): # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__)) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] sickbeard.SYS_ENCODING = None try: locale.setlocale(locale.LC_ALL, "") sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): pass # For OSes that are poorly configured I'll just randomly force UTF-8 if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in ('ANSI_X3.4-1968', 'US-ASCII', 'ASCII'): sickbeard.SYS_ENCODING = 'UTF-8' if not hasattr(sys, "setdefaultencoding"): reload(sys) if sys.platform == 'win32': if sys.getwindowsversion()[0] >= 6 and sys.stdout.encoding == 'cp65001': sickbeard.SYS_ENCODING = 'UTF-8' try: # pylint: disable=E1101 # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) except: sys.exit("Sorry, you MUST add the SickRage folder to the PYTHONPATH environment variable\n" + "or find another way to force Python to use " + sickbeard.SYS_ENCODING + " for string encoding.") # Need console logging for SickBeard.py and SickBeard-console.exe self.consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = "MAIN" try: opts, args = getopt.getopt(sys.argv[1:], "hfqdp::", ['help', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize']) # @UnusedVariable except getopt.GetoptError: sys.exit(self.help_message()) for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(self.help_message()) # For now we'll just silence the logging if o in ('-q', '--quiet'): self.consoleLogging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch',): self.noLaunch = True # Override default/configured port if o in ('-p', '--port'): try: self.forcedPort = int(a) except ValueError: sys.exit("Port: " + str(a) + " is not a number. Exiting.") # Run as a double forked daemon if o in ('-d', '--daemon'): self.runAsDaemon = True # When running as daemon disable consoleLogging and don't start browser self.consoleLogging = False self.noLaunch = True if sys.platform == 'win32' or sys.platform == 'darwin': self.runAsDaemon = False # Write a pidfile if requested if o in ('--pidfile',): self.CREATEPID = True self.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if os.path.exists(self.PIDFILE): sys.exit("PID file: " + self.PIDFILE + " already exists. Exiting.") # Specify folder to load the config file from if o in ('--config',): sickbeard.CONFIG_FILE = os.path.abspath(a) # Specify folder to use as the data dir if o in ('--datadir',): sickbeard.DATA_DIR = os.path.abspath(a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize',): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if self.CREATEPID: if self.runAsDaemon: pid_dir = os.path.dirname(self.PIDFILE) if not os.access(pid_dir, os.F_OK): sys.exit("PID dir: " + pid_dir + " doesn't exist. Exiting.") if not os.access(pid_dir, os.W_OK): sys.exit("PID dir: " + pid_dir + " must be writable (write permissions). Exiting.") else: if self.consoleLogging: sys.stdout.write("Not running in daemon mode. PID file creation disabled.\n") self.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = os.path.join(sickbeard.DATA_DIR, "config.ini") # Make sure that we can create the data dir if not os.access(sickbeard.DATA_DIR, os.F_OK): try: os.makedirs(sickbeard.DATA_DIR, 0744) except os.error, e: raise SystemExit("Unable to create datadir '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the data dir if not os.access(sickbeard.DATA_DIR, os.W_OK): raise SystemExit("Datadir must be writeable '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the config file if not os.access(sickbeard.CONFIG_FILE, os.W_OK): if os.path.isfile(sickbeard.CONFIG_FILE): raise SystemExit("Config file '" + sickbeard.CONFIG_FILE + "' must be writeable.") elif not os.access(os.path.dirname(sickbeard.CONFIG_FILE), os.W_OK): raise SystemExit( "Config file root dir '" + os.path.dirname(sickbeard.CONFIG_FILE) + "' must be writeable.") os.chdir(sickbeard.DATA_DIR) # Check if we need to perform a restore first try: restoreDir = os.path.join(sickbeard.DATA_DIR, 'restore') if self.consoleLogging and os.path.exists(restoreDir): if self.restoreDB(restoreDir, sickbeard.DATA_DIR): sys.stdout.write("Restore: restoring DB and config.ini successful...\n") else: sys.stdout.write("Restore: restoring DB and config.ini FAILED!\n") except Exception as e: sys.stdout.write("Restore: restoring DB and config.ini FAILED!\n") # Load the config and publish it to the sickbeard package if self.consoleLogging and not os.path.isfile(sickbeard.CONFIG_FILE): sys.stdout.write("Unable to find '" + sickbeard.CONFIG_FILE + "' , all settings will be default!" + "\n") sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.consoleLogging) if self.runAsDaemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() # Fix clients old files self.fix_clients_nonsense() # Build from the DB to start with self.loadShowsFromDB() if self.forcedPort: logger.log(u"Forcing web server to port " + str(self.forcedPort)) self.startPort = self.forcedPort else: self.startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: self.webhost = '::' else: self.webhost = '0.0.0.0' # web server options self.web_options = { 'port': int(self.startPort), 'host': self.webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': os.path.join(sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': os.path.join(sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), } # start web server self.webserver = SRWebServer(self.web_options) self.webserver.start() if self.consoleLogging: print "Starting up SickRage " + sickbeard.BRANCH + " from " + sickbeard.CONFIG_FILE # Fire up all our threads sickbeard.start() # Build internal name cache name_cache.buildNameCache() # Prepopulate network timezones, it isn't thread safe network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # Check for metadata indexer updates for shows (Disabled until we use api) #sickbeard.showUpdateScheduler.forceRun() # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.noLaunch or self.runAsDaemon): sickbeard.launchBrowser('https' if sickbeard.ENABLE_HTTPS else 'http', self.startPort, sickbeard.WEB_ROOT) # main loop while (True): time.sleep(1)
def start(self): # do some preliminary stuff sickbeard.MY_FULLNAME = ek(os.path.normpath, ek(os.path.abspath, __file__)) sickbeard.MY_NAME = ek(os.path.basename, sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = ek(os.path.dirname, sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] try: locale.setlocale(locale.LC_ALL, "") sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): sickbeard.SYS_ENCODING = 'UTF-8' # pylint: disable=no-member if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING.lower() in ('ansi_x3.4-1968', 'us-ascii', 'ascii', 'charmap') or \ (sys.platform.startswith('win') and sys.getwindowsversion()[0] >= 6 and str(getattr(sys.stdout, 'device', sys.stdout).encoding).lower() in ('cp65001', 'charmap')): sickbeard.SYS_ENCODING = 'UTF-8' # TODO: Continue working on making this unnecessary, this hack creates all sorts of hellish problems if not hasattr(sys, "setdefaultencoding"): reload(sys) try: # pylint: disable=no-member # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) except Exception: sys.exit("Sorry, you MUST add the SickRage folder to the PYTHONPATH environment variable\n" + "or find another way to force Python to use " + sickbeard.SYS_ENCODING + " for string encoding.") # Need console logging for SickBeard.py and SickBeard-console.exe self.consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = u"MAIN" try: opts, _ = getopt.getopt( sys.argv[1:], "hqdp::", ['help', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize'] ) except getopt.GetoptError: sys.exit(self.help_message()) for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(self.help_message()) # For now we'll just silence the logging if o in ('-q', '--quiet'): self.consoleLogging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch',): self.noLaunch = True # Override default/configured port if o in ('-p', '--port'): try: self.forcedPort = int(a) except ValueError: sys.exit("Port: " + str(a) + " is not a number. Exiting.") # Run as a double forked daemon if o in ('-d', '--daemon'): self.runAsDaemon = True # When running as daemon disable consoleLogging and don't start browser self.consoleLogging = False self.noLaunch = True if sys.platform == 'win32' or sys.platform == 'darwin': self.runAsDaemon = False # Write a pidfile if requested if o in ('--pidfile',): self.CREATEPID = True self.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if ek(os.path.exists, self.PIDFILE): sys.exit("PID file: " + self.PIDFILE + " already exists. Exiting.") # Specify folder to load the config file from if o in ('--config',): sickbeard.CONFIG_FILE = ek(os.path.abspath, a) # Specify folder to use as the data dir if o in ('--datadir',): sickbeard.DATA_DIR = ek(os.path.abspath, a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize',): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if self.CREATEPID: if self.runAsDaemon: pid_dir = ek(os.path.dirname, self.PIDFILE) if not ek(os.access, pid_dir, os.F_OK): sys.exit("PID dir: " + pid_dir + " doesn't exist. Exiting.") if not ek(os.access, pid_dir, os.W_OK): sys.exit("PID dir: " + pid_dir + " must be writable (write permissions). Exiting.") else: if self.consoleLogging: sys.stdout.write(u"Not running in daemon mode. PID file creation disabled.\n") self.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = ek(os.path.join, sickbeard.DATA_DIR, "config.ini") # Make sure that we can create the data dir if not ek(os.access, sickbeard.DATA_DIR, os.F_OK): try: ek(os.makedirs, sickbeard.DATA_DIR, 0744) except os.error: raise SystemExit("Unable to create datadir '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the data dir if not ek(os.access, sickbeard.DATA_DIR, os.W_OK): raise SystemExit("Datadir must be writeable '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the config file if not ek(os.access, sickbeard.CONFIG_FILE, os.W_OK): if ek(os.path.isfile, sickbeard.CONFIG_FILE): raise SystemExit("Config file '" + sickbeard.CONFIG_FILE + "' must be writeable.") elif not ek(os.access, ek(os.path.dirname, sickbeard.CONFIG_FILE), os.W_OK): raise SystemExit( "Config file root dir '" + ek(os.path.dirname, sickbeard.CONFIG_FILE) + "' must be writeable.") ek(os.chdir, sickbeard.DATA_DIR) # Check if we need to perform a restore first restoreDir = ek(os.path.join, sickbeard.DATA_DIR, 'restore') if ek(os.path.exists, restoreDir): success = self.restoreDB(restoreDir, sickbeard.DATA_DIR) if self.consoleLogging: sys.stdout.write(u"Restore: restoring DB and config.ini %s!\n" % ("FAILED", "SUCCESSFUL")[success]) # Load the config and publish it to the sickbeard package if self.consoleLogging and not ek(os.path.isfile, sickbeard.CONFIG_FILE): sys.stdout.write(u"Unable to find '" + sickbeard.CONFIG_FILE + "' , all settings will be default!" + "\n") sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.consoleLogging) if self.runAsDaemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() # Build from the DB to start with self.loadShowsFromDB() if self.forcedPort: logger.log(u"Forcing web server to port " + str(self.forcedPort)) self.startPort = self.forcedPort else: self.startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: self.webhost = '' else: self.webhost = '0.0.0.0' # web server options self.web_options = { 'port': int(self.startPort), 'host': self.webhost, 'data_root': ek(os.path.join, sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), } # start web server self.webserver = SRWebServer(self.web_options) self.webserver.start() if self.consoleLogging: print "Starting up SickRage " + sickbeard.BRANCH + " from " + sickbeard.CONFIG_FILE # Clean up after update if sickbeard.GIT_NEWVER: toclean = ek(os.path.join, sickbeard.CACHE_DIR, 'mako') for root, dirs, files in ek(os.walk, toclean, topdown=False): for name in files: ek(os.remove, ek(os.path.join, root, name)) for name in dirs: ek(os.rmdir, ek(os.path.join, root, name)) sickbeard.GIT_NEWVER = False # Fire up all our threads sickbeard.start() # Build internal name cache name_cache.buildNameCache() # Prepopulate network timezones, it isn't thread safe network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # # Check for metadata indexer updates for shows (Disabled until we use api) # sickbeard.showUpdateScheduler.forceRun() # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.noLaunch or self.runAsDaemon): sickbeard.launchBrowser('https' if sickbeard.ENABLE_HTTPS else 'http', self.startPort, sickbeard.WEB_ROOT) # main loop while True: time.sleep(1)
def start(self): # Rename the main thread threading.currentThread().name = "MAIN" # initalize encoding defaults encodingInit() # do some preliminary stuff sickbeard.MY_FULLNAME = ek(os.path.normpath, ek(os.path.abspath, __file__)) sickbeard.MY_NAME = ek(os.path.basename, sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = ek(os.path.dirname, sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] # Need console logging for SickBeard.py and SickBeard-console.exe self.consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Do this before importing sickbeard, to prevent locked files and incorrect import oldtornado = ek(os.path.abspath, ek(os.path.join, ek(os.path.dirname, __file__), 'tornado')) if ek(os.path.isdir, oldtornado): ek(shutil.move, oldtornado, oldtornado + '_kill') ek(removetree, oldtornado + '_kill') try: opts, _ = getopt.getopt( sys.argv[1:], "hqdp::", ['help', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize'] ) except getopt.GetoptError: sys.exit(self.help_message()) for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(self.help_message()) # For now we'll just silence the logging if o in ('-q', '--quiet'): self.consoleLogging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch',): self.noLaunch = True # Override default/configured port if o in ('-p', '--port'): try: self.forcedPort = int(a) except ValueError: sys.exit("Port: " + str(a) + " is not a number. Exiting.") # Run as a double forked daemon if o in ('-d', '--daemon'): self.runAsDaemon = True # When running as daemon disable consoleLogging and don't start browser self.consoleLogging = False self.noLaunch = True if sys.platform == 'win32' or sys.platform == 'darwin': self.runAsDaemon = False # Write a pidfile if requested if o in ('--pidfile',): self.CREATEPID = True self.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if ek(os.path.exists, self.PIDFILE): sys.exit("PID file: " + self.PIDFILE + " already exists. Exiting.") # Specify folder to load the config file from if o in ('--config',): sickbeard.CONFIG_FILE = ek(os.path.abspath, a) # Specify folder to use as the data dir if o in ('--datadir',): sickbeard.DATA_DIR = ek(os.path.abspath, a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize',): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if self.CREATEPID: if self.runAsDaemon: pid_dir = ek(os.path.dirname, self.PIDFILE) if not ek(os.access, pid_dir, os.F_OK): sys.exit("PID dir: " + pid_dir + " doesn't exist. Exiting.") if not ek(os.access, pid_dir, os.W_OK): sys.exit("PID dir: " + pid_dir + " must be writable (write permissions). Exiting.") else: if self.consoleLogging: sys.stdout.write("Not running in daemon mode. PID file creation disabled.\n") self.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = ek(os.path.join, sickbeard.DATA_DIR, "config.ini") # Make sure that we can create the data dir if not ek(os.access, sickbeard.DATA_DIR, os.F_OK): try: ek(os.makedirs, sickbeard.DATA_DIR, 0o744) except os.error: raise SystemExit("Unable to create datadir '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the data dir if not ek(os.access, sickbeard.DATA_DIR, os.W_OK): raise SystemExit("Datadir must be writeable '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the config file if not ek(os.access, sickbeard.CONFIG_FILE, os.W_OK): if ek(os.path.isfile, sickbeard.CONFIG_FILE): raise SystemExit("Config file '" + sickbeard.CONFIG_FILE + "' must be writeable.") elif not ek(os.access, ek(os.path.dirname, sickbeard.CONFIG_FILE), os.W_OK): raise SystemExit( "Config file root dir '" + ek(os.path.dirname, sickbeard.CONFIG_FILE) + "' must be writeable.") ek(os.chdir, sickbeard.DATA_DIR) # Check if we need to perform a restore first restoreDir = ek(os.path.join, sickbeard.DATA_DIR, 'restore') if ek(os.path.exists, restoreDir): success = self.restoreDB(restoreDir, sickbeard.DATA_DIR) if self.consoleLogging: sys.stdout.write("Restore: restoring DB and config.ini %s!\n" % ("FAILED", "SUCCESSFUL")[success]) # Load the config and publish it to the sickbeard package if self.consoleLogging and not ek(os.path.isfile, sickbeard.CONFIG_FILE): sys.stdout.write("Unable to find '" + sickbeard.CONFIG_FILE + "' , all settings will be default!" + "\n") sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.consoleLogging) if self.runAsDaemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() # Build from the DB to start with self.loadShowsFromDB() if self.forcedPort: logging.info("Forcing web server to port " + str(self.forcedPort)) self.startPort = self.forcedPort else: self.startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: self.webhost = '::' else: self.webhost = '0.0.0.0' # start tornado web server self.webserver = SRWebServer({ 'port': int(self.startPort), 'host': self.webhost, 'data_root': ek(os.path.join, sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), }).start() # Clean up after update if sickbeard.GIT_NEWVER: toclean = ek(os.path.join, sickbeard.CACHE_DIR, 'mako') for root, dirs, files in ek(os.walk, toclean, topdown=False): for name in files: ek(os.remove, ek(os.path.join, root, name)) for name in dirs: ek(os.rmdir, ek(os.path.join, root, name)) sickbeard.GIT_NEWVER = False # Fire up all our threads logging.info("Starting SiCKRAGE BRANCH:[{}] CONFIG:[{}]".format(sickbeard.BRANCH, sickbeard.CONFIG_FILE)) sickbeard.start() # Build internal name cache name_cache.buildNameCache() # Prepopulate network timezones, it isn't thread safe network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # # Check for metadata indexer updates for shows (Disabled until we use api) # sickbeard.showUpdateScheduler.forceRun() # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.noLaunch or self.runAsDaemon): sickbeard.launchBrowser('https' if sickbeard.ENABLE_HTTPS else 'http', self.startPort, sickbeard.WEB_ROOT) # main loop while True: time.sleep(1)
def main(): # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__)) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.MY_ARGS = sys.argv[1:] try: locale.setlocale(locale.LC_ALL, "") except (locale.Error, IOError): pass sickbeard.SYS_ENCODING = locale.getpreferredencoding() # for OSes that are poorly configured I'll just force UTF-8 if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in ('ANSI_X3.4-1968', 'US-ASCII'): sickbeard.SYS_ENCODING = 'UTF-8' sickbeard.CONFIG_FILE = os.path.join(sickbeard.PROG_DIR, "config.ini") # need console logging for SickBeard.py and SickBeard-console.exe consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # rename the main thread threading.currentThread().name = "MAIN" try: opts, args = getopt.getopt(sys.argv[1:], "qfdp:", ['quiet', 'forceupdate', 'daemon', 'port=', 'tvbinz']) except getopt.GetoptError: print "Available options: --quiet, --forceupdate, --port, --daemon" sys.exit() forceUpdate = False forcedPort = None for o, a in opts: # for now we'll just silence the logging if (o in ('-q', '--quiet')): consoleLogging = False # for now we'll just silence the logging if (o in ('--tvbinz')): sickbeard.SHOW_TVBINZ = True # should we update right away? if (o in ('-f', '--forceupdate')): forceUpdate = True # use a different port if (o in ('-p', '--port')): forcedPort = int(a) # Run as a daemon if (o in ('-d', '--daemon')): if sys.platform == 'win32': print "Daemonize not supported under Windows, starting normally" else: consoleLogging = False sickbeard.DAEMON = True if consoleLogging: print "Starting up Sick Beard "+SICKBEARD_VERSION+" from " + sickbeard.CONFIG_FILE # load the config and publish it to the sickbeard package if not os.path.isfile(sickbeard.CONFIG_FILE): logger.log(u"Unable to find config.ini, all settings will be default", logger.ERROR) sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # initialize the config and our threads sickbeard.initialize(consoleLogging=consoleLogging) sickbeard.showList = [] if sickbeard.DAEMON: daemonize() # use this pid for everything sickbeard.PID = os.getpid() if forcedPort: logger.log(u"Forcing web server to port "+str(forcedPort)) startPort = forcedPort else: startPort = sickbeard.WEB_PORT logger.log(u"Starting Sick Beard on http://localhost:"+str(startPort)) if sickbeard.WEB_LOG: log_dir = sickbeard.LOG_DIR else: log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic # reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: webhost = '::' else: webhost = '0.0.0.0' try: initWebServer({ 'port': startPort, 'host': webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'data'), 'web_root': sickbeard.WEB_ROOT, 'log_dir': log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, }) except IOError: logger.log(u"Unable to start web server, is something else running on port %d?" % startPort, logger.ERROR) if sickbeard.LAUNCH_BROWSER: logger.log(u"Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser(startPort) sys.exit() # build from the DB to start with logger.log(u"Loading initial show list") loadShowsFromDB() # fire up all our threads sickbeard.start() # launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER: sickbeard.launchBrowser(startPort) # start an update if we're supposed to if forceUpdate: sickbeard.showUpdateScheduler.action.run(force=True) # stay alive while my threads do the work while (True): time.sleep(1) return
def start(self): # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__)) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] sickbeard.SYS_ENCODING = None try: locale.setlocale(locale.LC_ALL, '') except (locale.Error, IOError): pass try: sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): pass # For OSes that are poorly configured I'll just randomly force UTF-8 if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in ('ANSI_X3.4-1968', 'US-ASCII', 'ASCII'): sickbeard.SYS_ENCODING = 'UTF-8' if not hasattr(sys, 'setdefaultencoding'): moves.reload_module(sys) try: # pylint: disable=E1101 # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) except: print('Sorry, you MUST add the SickGear folder to the PYTHONPATH environment variable') print('or find another way to force Python to use %s for string encoding.' % sickbeard.SYS_ENCODING) sys.exit(1) # Need console logging for SickBeard.py and SickBeard-console.exe self.consoleLogging = (not hasattr(sys, 'frozen')) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = 'MAIN' try: opts, args = getopt.getopt(sys.argv[1:], 'hfqdp::', ['help', 'forceupdate', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize']) # @UnusedVariable except getopt.GetoptError: sys.exit(self.help_message()) for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(self.help_message()) # For now we'll just silence the logging if o in ('-q', '--quiet'): self.consoleLogging = False # Should we update (from indexer) all shows in the DB right away? if o in ('-f', '--forceupdate'): self.forceUpdate = True # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch',): self.noLaunch = True # Override default/configured port if o in ('-p', '--port'): try: self.forcedPort = int(a) except ValueError: sys.exit('Port: %s is not a number. Exiting.' % a) # Run as a double forked daemon if o in ('-d', '--daemon'): self.runAsDaemon = True # When running as daemon disable consoleLogging and don't start browser self.consoleLogging = False self.noLaunch = True if sys.platform == 'win32': self.runAsDaemon = False # Write a pidfile if requested if o in ('--pidfile',): self.CREATEPID = True self.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if os.path.exists(self.PIDFILE): sys.exit('PID file: %s already exists. Exiting.' % self.PIDFILE) # Specify folder to load the config file from if o in ('--config',): sickbeard.CONFIG_FILE = os.path.abspath(a) # Specify folder to use as the data dir if o in ('--datadir',): sickbeard.DATA_DIR = os.path.abspath(a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize',): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if self.CREATEPID: if self.runAsDaemon: pid_dir = os.path.dirname(self.PIDFILE) if not os.access(pid_dir, os.F_OK): sys.exit(u"PID dir: %s doesn't exist. Exiting." % pid_dir) if not os.access(pid_dir, os.W_OK): sys.exit(u'PID dir: %s must be writable (write permissions). Exiting.' % pid_dir) else: if self.consoleLogging: print(u'Not running in daemon mode. PID file creation disabled') self.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = os.path.join(sickbeard.DATA_DIR, 'config.ini') # Make sure that we can create the data dir if not os.access(sickbeard.DATA_DIR, os.F_OK): try: os.makedirs(sickbeard.DATA_DIR, 0o744) except os.error: sys.exit(u'Unable to create data directory: %s Exiting.' % sickbeard.DATA_DIR) # Make sure we can write to the data dir if not os.access(sickbeard.DATA_DIR, os.W_OK): sys.exit(u'Data directory: %s must be writable (write permissions). Exiting.' % sickbeard.DATA_DIR) # Make sure we can write to the config file if not os.access(sickbeard.CONFIG_FILE, os.W_OK): if os.path.isfile(sickbeard.CONFIG_FILE): sys.exit(u'Config file: %s must be writeable (write permissions). Exiting.' % sickbeard.CONFIG_FILE) elif not os.access(os.path.dirname(sickbeard.CONFIG_FILE), os.W_OK): sys.exit(u'Config file directory: %s must be writeable (write permissions). Exiting' % os.path.dirname(sickbeard.CONFIG_FILE)) os.chdir(sickbeard.DATA_DIR) if self.consoleLogging: print(u'Starting up SickGear from %s' % sickbeard.CONFIG_FILE) # Load the config and publish it to the sickbeard package if not os.path.isfile(sickbeard.CONFIG_FILE): print(u'Unable to find "%s", all settings will be default!' % sickbeard.CONFIG_FILE) sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) CUR_DB_VERSION = db.DBConnection().checkDBVersion() if CUR_DB_VERSION > 0: if CUR_DB_VERSION < MIN_DB_VERSION: print(u'Your database version (%s) is too old to migrate from with this version of SickGear' \ % CUR_DB_VERSION) sys.exit(u'Upgrade using a previous version of SG first, or start with no database file to begin fresh') if CUR_DB_VERSION > MAX_DB_VERSION: print(u'Your database version (%s) has been incremented past what this version of SickGear supports' \ % CUR_DB_VERSION) sys.exit( u'If you have used other forks of SG, your database may be unusable due to their modifications') # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.consoleLogging) if self.runAsDaemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() if self.forcedPort: logger.log(u'Forcing web server to port %s' % self.forcedPort) self.startPort = self.forcedPort else: self.startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: self.webhost = '::' else: self.webhost = '0.0.0.0' # web server options self.web_options = { 'port': int(self.startPort), 'host': self.webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': os.path.join(sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': os.path.join(sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), } # start web server try: # used to check if existing SG instances have been started sickbeard.helpers.wait_for_free_port(self.web_options['host'], self.web_options['port']) self.webserver = WebServer(self.web_options) self.webserver.start() except Exception: logger.log(u'Unable to start web server, is something else running on port %d?' % self.startPort, logger.ERROR) if sickbeard.LAUNCH_BROWSER and not self.runAsDaemon: logger.log(u'Launching browser and exiting', logger.ERROR) sickbeard.launchBrowser(self.startPort) os._exit(1) # Check if we need to perform a restore first restoreDir = os.path.join(sickbeard.DATA_DIR, 'restore') if os.path.exists(restoreDir): if self.restore(restoreDir, sickbeard.DATA_DIR): logger.log(u'Restore successful...') else: logger.log_error_and_exit(u'Restore FAILED!') # Build from the DB to start with self.loadShowsFromDB() # Fire up all our threads sickbeard.start() # Build internal name cache name_cache.buildNameCache() # refresh network timezones network_timezones.update_network_dict() # load all ids from xem startup_background_tasks = threading.Thread(name='FETCH-XEMDATA', target=sickbeard.scene_exceptions.get_xem_ids) startup_background_tasks.start() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # Start an update if we're supposed to if self.forceUpdate or sickbeard.UPDATE_SHOWS_ON_START: sickbeard.showUpdateScheduler.action.run(force=True) # @UndefinedVariable # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.noLaunch or self.runAsDaemon): sickbeard.launchBrowser(self.startPort) # main loop while True: time.sleep(1)
def start(self): # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__)) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] sickbeard.SYS_ENCODING = None try: locale.setlocale(locale.LC_ALL, '') except (locale.Error, IOError): pass try: sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): pass # For OSes that are poorly configured I'll just randomly force UTF-8 if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in ('ANSI_X3.4-1968', 'US-ASCII', 'ASCII'): sickbeard.SYS_ENCODING = 'UTF-8' if not hasattr(sys, 'setdefaultencoding'): reload(sys) try: # pylint: disable=E1101 # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) except: print 'Sorry, you MUST add the SickGear folder to the PYTHONPATH environment variable' print 'or find another way to force Python to use %s for string encoding.' % sickbeard.SYS_ENCODING sys.exit(1) # Need console logging for SickBeard.py and SickBeard-console.exe self.consoleLogging = (not hasattr(sys, 'frozen')) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = 'MAIN' try: opts, args = getopt.getopt(sys.argv[1:], 'hfqdp::', ['help', 'forceupdate', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize']) # @UnusedVariable except getopt.GetoptError: sys.exit(self.help_message()) for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(self.help_message()) # For now we'll just silence the logging if o in ('-q', '--quiet'): self.consoleLogging = False # Should we update (from indexer) all shows in the DB right away? if o in ('-f', '--forceupdate'): self.forceUpdate = True # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch',): self.noLaunch = True # Override default/configured port if o in ('-p', '--port'): try: self.forcedPort = int(a) except ValueError: sys.exit('Port: %s is not a number. Exiting.' % a) # Run as a double forked daemon if o in ('-d', '--daemon'): self.runAsDaemon = True # When running as daemon disable consoleLogging and don't start browser self.consoleLogging = False self.noLaunch = True if sys.platform == 'win32': self.runAsDaemon = False # Write a pidfile if requested if o in ('--pidfile',): self.CREATEPID = True self.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if os.path.exists(self.PIDFILE): sys.exit('PID file: %s already exists. Exiting.' % self.PIDFILE) # Specify folder to load the config file from if o in ('--config',): sickbeard.CONFIG_FILE = os.path.abspath(a) # Specify folder to use as the data dir if o in ('--datadir',): sickbeard.DATA_DIR = os.path.abspath(a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize',): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if self.CREATEPID: if self.runAsDaemon: pid_dir = os.path.dirname(self.PIDFILE) if not os.access(pid_dir, os.F_OK): sys.exit(u"PID dir: %s doesn't exist. Exiting." % pid_dir) if not os.access(pid_dir, os.W_OK): sys.exit(u'PID dir: %s must be writable (write permissions). Exiting.' % pid_dir) else: if self.consoleLogging: print u'Not running in daemon mode. PID file creation disabled' self.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = os.path.join(sickbeard.DATA_DIR, 'config.ini') # Make sure that we can create the data dir if not os.access(sickbeard.DATA_DIR, os.F_OK): try: os.makedirs(sickbeard.DATA_DIR, 0744) except os.error: sys.exit(u'Unable to create data directory: %s Exiting.' % sickbeard.DATA_DIR) # Make sure we can write to the data dir if not os.access(sickbeard.DATA_DIR, os.W_OK): sys.exit(u'Data directory: %s must be writable (write permissions). Exiting.' % sickbeard.DATA_DIR) # Make sure we can write to the config file if not os.access(sickbeard.CONFIG_FILE, os.W_OK): if os.path.isfile(sickbeard.CONFIG_FILE): sys.exit(u'Config file: %s must be writeable (write permissions). Exiting.' % sickbeard.CONFIG_FILE) elif not os.access(os.path.dirname(sickbeard.CONFIG_FILE), os.W_OK): sys.exit(u'Config file directory: %s must be writeable (write permissions). Exiting' % os.path.dirname(sickbeard.CONFIG_FILE)) os.chdir(sickbeard.DATA_DIR) if self.consoleLogging: print u'Starting up SickGear from %s' % sickbeard.CONFIG_FILE # Load the config and publish it to the sickbeard package if not os.path.isfile(sickbeard.CONFIG_FILE): print u'Unable to find "%s", all settings will be default!' % sickbeard.CONFIG_FILE sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) CUR_DB_VERSION = db.DBConnection().checkDBVersion() if CUR_DB_VERSION > 0: if CUR_DB_VERSION < MIN_DB_VERSION: print u'Your database version (%s) is too old to migrate from with this version of SickGear' \ % CUR_DB_VERSION sys.exit(u'Upgrade using a previous version of SG first, or start with no database file to begin fresh') if CUR_DB_VERSION > MAX_DB_VERSION: print u'Your database version (%s) has been incremented past what this version of SickGear supports' \ % CUR_DB_VERSION sys.exit( u'If you have used other forks of SG, your database may be unusable due to their modifications') # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.consoleLogging) if self.runAsDaemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() if self.forcedPort: logger.log(u'Forcing web server to port %s' % self.forcedPort) self.startPort = self.forcedPort else: self.startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: self.webhost = '::' else: self.webhost = '0.0.0.0' # web server options self.web_options = { 'port': int(self.startPort), 'host': self.webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': os.path.join(sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': os.path.join(sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), } # start web server try: # used to check if existing SG instances have been started sickbeard.helpers.wait_for_free_port(self.web_options['host'], self.web_options['port']) self.webserver = WebServer(self.web_options) self.webserver.start() except Exception: logger.log(u'Unable to start web server, is something else running on port %d?' % self.startPort, logger.ERROR) if sickbeard.LAUNCH_BROWSER and not self.runAsDaemon: logger.log(u'Launching browser and exiting', logger.ERROR) sickbeard.launchBrowser(self.startPort) os._exit(1) # Check if we need to perform a restore first restoreDir = os.path.join(sickbeard.DATA_DIR, 'restore') if os.path.exists(restoreDir): if self.restore(restoreDir, sickbeard.DATA_DIR): logger.log(u'Restore successful...') else: logger.log_error_and_exit(u'Restore FAILED!') # Build from the DB to start with self.loadShowsFromDB() # Fire up all our threads sickbeard.start() # Build internal name cache name_cache.buildNameCache() # refresh network timezones network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # Start an update if we're supposed to if self.forceUpdate or sickbeard.UPDATE_SHOWS_ON_START: sickbeard.showUpdateScheduler.action.run(force=True) # @UndefinedVariable # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.noLaunch or self.runAsDaemon): sickbeard.launchBrowser(self.startPort) # main loop while True: time.sleep(1)
def main(): """ TV for me """ # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__)) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] sickbeard.DAEMON = False sickbeard.CREATEPID = False sickbeard.SYS_ENCODING = None try: locale.setlocale(locale.LC_ALL, "") sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): pass # For OSes that are poorly configured I'll just randomly force UTF-8 if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in ( 'ANSI_X3.4-1968', 'US-ASCII', 'ASCII'): sickbeard.SYS_ENCODING = 'UTF-8' if not hasattr(sys, "setdefaultencoding"): reload(sys) try: # pylint: disable=E1101 # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) except: sys.exit( "Sorry, you MUST add the Sick Beard folder to the PYTHONPATH environment variable\n" + "or find another way to force Python to use " + sickbeard.SYS_ENCODING + " for string encoding.") # Need console logging for SickBeard.py and SickBeard-console.exe consoleLogging = (not hasattr( sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = "MAIN" try: opts, args = getopt.getopt(sys.argv[1:], "hfqda:p::", [ 'help', 'forceupdate', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'addr=', 'port=', 'datadir=', 'config=', 'noresize' ]) # @UnusedVariable except getopt.GetoptError: sys.exit(help_message()) forceUpdate = False forcedHost = None forcedPort = None noLaunch = False for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(help_message()) # Should we update (from tvdb) all shows in the DB right away? if o in ('-f', '--forceupdate'): forceUpdate = True # Disables logging to console if o in ('-q', '--quiet'): consoleLogging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch', ): noLaunch = True # Run as a double forked daemon if o in ('-d', '--daemon'): sickbeard.DAEMON = True # When running as daemon disable consoleLogging and don't start browser consoleLogging = False noLaunch = True if sys.platform == 'win32': sickbeard.DAEMON = False # Write a pidfile if requested if o in ('--pidfile', ): sickbeard.CREATEPID = True sickbeard.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if os.path.exists(sickbeard.PIDFILE): sys.exit("PID file: " + sickbeard.PIDFILE + " already exists. Exiting.") # Override default/configured port if o in ('-p', '--port'): try: forcedPort = int(a) except ValueError: sys.exit("Port: " + str(a) + " is not a number. Exiting.") # Override default/configured host if o in ('-a', '--addr'): try: forcedHost = str(a) except ValueError: sys.exit("Host: " + str(a) + " is not a string. Exiting.") # Specify folder to use as data dir (storing database, configfile, cache, logfiles) if o in ('--datadir', ): sickbeard.DATA_DIR = os.path.abspath(a) # Specify filename to load the config information from if o in ('--config', ): sickbeard.CONFIG_FILE = os.path.abspath(a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize', ): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if sickbeard.CREATEPID: if sickbeard.DAEMON: pid_dir = os.path.dirname(sickbeard.PIDFILE) if not os.access(pid_dir, os.F_OK): sys.exit("PID dir: " + pid_dir + " doesn't exist. Exiting.") if not os.access(pid_dir, os.W_OK): sys.exit("PID dir: " + pid_dir + " must be writable (write permissions). Exiting.") else: if consoleLogging: sys.stdout.write( "Not running in daemon mode. PID file creation disabled.\n" ) sickbeard.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = os.path.join(sickbeard.DATA_DIR, "config.ini") # Make sure that we can create the data dir if not os.access(sickbeard.DATA_DIR, os.F_OK): try: os.makedirs(sickbeard.DATA_DIR, 0744) except os.error: sys.exit("Unable to create data directory: " + sickbeard.DATA_DIR + " Exiting.") # Make sure we can write to the data dir if not os.access(sickbeard.DATA_DIR, os.W_OK): sys.exit("Data directory: " + sickbeard.DATA_DIR + " must be writable (write permissions). Exiting.") # Make sure we can write to the config file if not os.access(sickbeard.CONFIG_FILE, os.W_OK): if os.path.isfile(sickbeard.CONFIG_FILE): sys.exit("Config file: " + sickbeard.CONFIG_FILE + " must be writeable (write permissions). Exiting.") elif not os.access(os.path.dirname(sickbeard.CONFIG_FILE), os.W_OK): sys.exit("Config file directory: " + os.path.dirname(sickbeard.CONFIG_FILE) + " must be writeable (write permissions). Exiting") os.chdir(sickbeard.DATA_DIR) if consoleLogging: sys.stdout.write("Starting up Sick Beard " + SICKBEARD_VERSION + "\n") if not os.path.isfile(sickbeard.CONFIG_FILE): sys.stdout.write("Unable to find '" + sickbeard.CONFIG_FILE + "' , all settings will be default!" + "\n") # Load the config and publish it to the sickbeard package sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=consoleLogging) sickbeard.showList = [] if sickbeard.DAEMON: daemonize() # Use this PID for everything sickbeard.PID = os.getpid() if forcedPort: logger.log(u"Forcing web server to port " + str(forcedPort)) startPort = forcedPort else: startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: log_dir = sickbeard.LOG_DIR else: log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: webhost = '::' else: webhost = '127.0.0.1' if forcedHost: logger.log(u"Forcing web server to address " + str(forcedHost)) webhost = forcedHost try: initWebServer({ 'port': startPort, 'host': webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'data'), 'web_root': sickbeard.WEB_ROOT, 'log_dir': log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'https_cert': sickbeard.HTTPS_CERT, 'https_key': sickbeard.HTTPS_KEY, }) except IOError: logger.log( u"Unable to start web server, is something else running on port: " + str(startPort), logger.ERROR) if sickbeard.LAUNCH_BROWSER and not sickbeard.DAEMON: logger.log(u"Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser(webhost, startPort) sys.exit( "Unable to start web server, is something else running on port: " + str(startPort)) # Build from the DB to start with logger.log(u"Loading initial show list") loadShowsFromDB() # Fire up all our threads sickbeard.start() # Launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER and not noLaunch and not sickbeard.DAEMON: sickbeard.launchBrowser(webhost, startPort) # Start an update if we're supposed to if forceUpdate: sickbeard.showUpdateScheduler.action.run( force=True) # @UndefinedVariable # Stay alive while my threads do the work while (True): if sickbeard.invoked_command: sickbeard.invoked_command() sickbeard.invoked_command = None time.sleep(1) return
'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': sickbeard.HTTPS_CERT, 'https_key': sickbeard.HTTPS_KEY, }) except IOError: logger.log( u"Unable to start web server, is something else running on port %d?" % startPort, logger.ERROR) if sickbeard.LAUNCH_BROWSER and not sickbeard.DAEMON: logger.log(u"Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser(startPort) sys.exit() # Build from the DB to start with logger.log(u"Loading initial show list") loadShowsFromDB() # Fire up all our threads sickbeard.start() # Launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER and not noLaunch and not sickbeard.DAEMON: sickbeard.launchBrowser(startPort) # Start an update if we're supposed to if forceUpdate or sickbeard.UPDATE_SHOWS_ON_START:
def start(self): # pylint: disable=too-many-branches,too-many-statements """ Start SickRage """ # do some preliminary stuff sickbeard.MY_FULLNAME = ek(os.path.normpath, ek(os.path.abspath, __file__)) sickbeard.MY_NAME = ek(os.path.basename, sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = ek(os.path.dirname, sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] try: locale.setlocale(locale.LC_ALL, '') sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): sickbeard.SYS_ENCODING = 'UTF-8' # pylint: disable=no-member if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING.lower() in ('ansi_x3.4-1968', 'us-ascii', 'ascii', 'charmap') or \ (sys.platform.startswith('win') and sys.getwindowsversion()[0] >= 6 and str(getattr(sys.stdout, 'device', sys.stdout).encoding).lower() in ('cp65001', 'charmap')): sickbeard.SYS_ENCODING = 'UTF-8' # TODO: Continue working on making this unnecessary, this hack creates all sorts of hellish problems if not hasattr(sys, 'setdefaultencoding'): reload(sys) try: # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) # pylint: disable=no-member except (AttributeError, LookupError): sys.exit('Sorry, you MUST add the SickRage folder to the PYTHONPATH environment variable\n' 'or find another way to force Python to use %s for string encoding.' % sickbeard.SYS_ENCODING) # Need console logging for SickBeard.py and SickBeard-console.exe self.console_logging = (not hasattr(sys, 'frozen')) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = 'MAIN' try: opts, _ = getopt.getopt( sys.argv[1:], 'hqdp::', ['help', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize'] ) except getopt.GetoptError: sys.exit(self.help_message()) for option, value in opts: # Prints help message if option in ('-h', '--help'): sys.exit(self.help_message()) # For now we'll just silence the logging if option in ('-q', '--quiet'): self.console_logging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if option in ('--nolaunch',): self.no_launch = True # Override default/configured port if option in ('-p', '--port'): try: self.forced_port = int(value) except ValueError: sys.exit('Port: {0} is not a number. Exiting.'.format(value)) # Run as a double forked daemon if option in ('-d', '--daemon'): self.run_as_daemon = True # When running as daemon disable console_logging and don't start browser self.console_logging = False self.no_launch = True if sys.platform == 'win32' or sys.platform == 'darwin': self.run_as_daemon = False # Write a pid file if requested if option in ('--pidfile',): self.create_pid = True self.pid_file = str(value) # If the pid file already exists, SickRage may still be running, so exit if ek(os.path.exists, self.pid_file): sys.exit('PID file: {0} already exists. Exiting.'.format(self.pid_file)) # Specify folder to load the config file from if option in ('--config',): sickbeard.CONFIG_FILE = ek(os.path.abspath, value) # Specify folder to use as the data directory if option in ('--datadir',): sickbeard.DATA_DIR = ek(os.path.abspath, value) # Prevent resizing of the banner/posters even if PIL is installed if option in ('--noresize',): sickbeard.NO_RESIZE = True # The pid file is only useful in daemon mode, make sure we can write the file properly if self.create_pid: if self.run_as_daemon: pid_dir = ek(os.path.dirname, self.pid_file) if not ek(os.access, pid_dir, os.F_OK): sys.exit('PID dir: {0} doesn\'t exist. Exiting.'.format(pid_dir)) if not ek(os.access, pid_dir, os.W_OK): sys.exit('PID dir: {0} must be writable (write permissions). Exiting.'.format(pid_dir)) else: if self.console_logging: sys.stdout.write('Not running in daemon mode. PID file creation disabled.\n') self.create_pid = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = ek(os.path.join, sickbeard.DATA_DIR, 'config.ini') # Make sure that we can create the data dir if not ek(os.access, sickbeard.DATA_DIR, os.F_OK): try: ek(os.makedirs, sickbeard.DATA_DIR, 0o744) except os.error: raise SystemExit('Unable to create data directory: {0}'.format(sickbeard.DATA_DIR)) # Make sure we can write to the data dir if not ek(os.access, sickbeard.DATA_DIR, os.W_OK): raise SystemExit('Data directory must be writeable: {0}'.format(sickbeard.DATA_DIR)) # Make sure we can write to the config file if not ek(os.access, sickbeard.CONFIG_FILE, os.W_OK): if ek(os.path.isfile, sickbeard.CONFIG_FILE): raise SystemExit('Config file must be writeable: {0}'.format(sickbeard.CONFIG_FILE)) elif not ek(os.access, ek(os.path.dirname, sickbeard.CONFIG_FILE), os.W_OK): raise SystemExit('Config file root dir must be writeable: {0}'.format(ek(os.path.dirname, sickbeard.CONFIG_FILE))) ek(os.chdir, sickbeard.DATA_DIR) # Check if we need to perform a restore first restore_dir = ek(os.path.join, sickbeard.DATA_DIR, 'restore') if ek(os.path.exists, restore_dir): success = self.restore_db(restore_dir, sickbeard.DATA_DIR) if self.console_logging: sys.stdout.write('Restore: restoring DB and config.ini {0}!\n'.format(('FAILED', 'SUCCESSFUL')[success])) # Load the config and publish it to the sickbeard package if self.console_logging and not ek(os.path.isfile, sickbeard.CONFIG_FILE): sys.stdout.write('Unable to find {0}, all settings will be default!\n'.format(sickbeard.CONFIG_FILE)) sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.console_logging) if self.run_as_daemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() # Build from the DB to start with self.load_shows_from_db() logger.log('Starting SickRage [{branch}] using \'{config}\''.format (branch=sickbeard.BRANCH, config=sickbeard.CONFIG_FILE)) self.clear_cache() if self.forced_port: logger.log('Forcing web server to port {port}'.format(port=self.forced_port)) self.start_port = self.forced_port else: self.start_port = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.web_host = sickbeard.WEB_HOST else: self.web_host = '' if sickbeard.WEB_IPV6 else '0.0.0.0' # web server options self.web_options = { 'port': int(self.start_port), 'host': self.web_host, 'data_root': ek(os.path.join, sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), } # start web server self.web_server = SRWebServer(self.web_options) self.web_server.start() # Fire up all our threads sickbeard.start() # Build internal name cache name_cache.buildNameCache() # Pre-populate network timezones, it isn't thread safe network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # Check for metadata indexer updates for shows (sets the next aired ep!) # sickbeard.showUpdateScheduler.forceRun() # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.no_launch or self.run_as_daemon): sickbeard.launchBrowser('https' if sickbeard.ENABLE_HTTPS else 'http', self.start_port, sickbeard.WEB_ROOT) # main loop while True: time.sleep(1)
def main(): # use this pid for everything sickbeard.PID = os.getpid() # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(sys.argv[0])) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.MY_ARGS = sys.argv[1:] sickbeard.CONFIG_FILE = os.path.join(sickbeard.PROG_DIR, "config.ini") # need console logging for SickBeard.py and SickBeard-console.exe consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # rename the main thread threading.currentThread().name = "MAIN" try: opts, args = getopt.getopt(sys.argv[1:], "qfp:", ['quiet', 'force-update', 'port=', 'tvbinz']) except getopt.GetoptError: print "Available options: --quiet, --forceupdate, --port" sys.exit() forceUpdate = False forcedPort = None for o, a in opts: # for now we'll just silence the logging if (o in ('-q', '--quiet')): consoleLogging = False # for now we'll just silence the logging if (o in ('--tvbinz')): sickbeard.SHOW_TVBINZ = True # should we update right away? if (o in ('-f', '--forceupdate')): forceUpdate = True # should we update right away? if (o in ('-p', '--port')): forcedPort = int(a) if consoleLogging: print "Starting up Sick Beard "+SICKBEARD_VERSION+" from " + sickbeard.CONFIG_FILE # load the config and publish it to the sickbeard package if not os.path.isfile(sickbeard.CONFIG_FILE): logger.log(u"Unable to find config.ini, all settings will be default", logger.ERROR) sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # initialize the config and our threads sickbeard.initialize(consoleLogging=consoleLogging) sickbeard.showList = [] if forcedPort: logger.log(u"Forcing web server to port "+str(forcedPort)) startPort = forcedPort else: startPort = sickbeard.WEB_PORT logger.log(u"Starting Sick Beard on http://localhost:"+str(startPort)) if sickbeard.WEB_LOG: log_dir = sickbeard.LOG_DIR else: log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic # reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: webhost = '::' else: webhost = '0.0.0.0' try: initWebServer({ 'port': startPort, 'host': webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'data'), 'web_root': sickbeard.WEB_ROOT, 'log_dir': log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, }) except IOError: logger.log(u"Unable to start web server, is something else running on port %d?" % startPort, logger.ERROR) if sickbeard.LAUNCH_BROWSER: logger.log(u"Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser(startPort) sys.exit() # build from the DB to start with logger.log(u"Loading initial show list") loadShowsFromDB() # set up the lists sickbeard.updateAiringList() sickbeard.updateComingList() # fire up all our threads sickbeard.start() # launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER: sickbeard.launchBrowser(startPort) # start an update if we're supposed to if forceUpdate: sickbeard.showUpdateScheduler.action.run(force=True) # stay alive while my threads do the work while (True): time.sleep(1) return
def start(self): # Rename the main thread threading.currentThread().name = "MAIN" # initalize encoding defaults encodingInit() # do some preliminary stuff sickbeard.MY_FULLNAME = ek(os.path.normpath, ek(os.path.abspath, __file__)) sickbeard.MY_NAME = ek(os.path.basename, sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = ek(os.path.dirname, sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] # Need console logging for SickBeard.py and SickBeard-console.exe self.consoleLogging = (not hasattr( sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Do this before importing sickbeard, to prevent locked files and incorrect import oldtornado = ek( os.path.abspath, ek(os.path.join, ek(os.path.dirname, __file__), 'tornado')) if ek(os.path.isdir, oldtornado): ek(shutil.move, oldtornado, oldtornado + '_kill') ek(removetree, oldtornado + '_kill') try: opts, _ = getopt.getopt(sys.argv[1:], "hqdp::", [ 'help', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize' ]) except getopt.GetoptError: sys.exit(self.help_message()) for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(self.help_message()) # For now we'll just silence the logging if o in ('-q', '--quiet'): self.consoleLogging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch', ): self.noLaunch = True # Override default/configured port if o in ('-p', '--port'): try: self.forcedPort = int(a) except ValueError: sys.exit("Port: " + str(a) + " is not a number. Exiting.") # Run as a double forked daemon if o in ('-d', '--daemon'): self.runAsDaemon = True # When running as daemon disable consoleLogging and don't start browser self.consoleLogging = False self.noLaunch = True if sys.platform == 'win32' or sys.platform == 'darwin': self.runAsDaemon = False # Write a pidfile if requested if o in ('--pidfile', ): self.CREATEPID = True self.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if ek(os.path.exists, self.PIDFILE): sys.exit("PID file: " + self.PIDFILE + " already exists. Exiting.") # Specify folder to load the config file from if o in ('--config', ): sickbeard.CONFIG_FILE = ek(os.path.abspath, a) # Specify folder to use as the data dir if o in ('--datadir', ): sickbeard.DATA_DIR = ek(os.path.abspath, a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize', ): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if self.CREATEPID: if self.runAsDaemon: pid_dir = ek(os.path.dirname, self.PIDFILE) if not ek(os.access, pid_dir, os.F_OK): sys.exit("PID dir: " + pid_dir + " doesn't exist. Exiting.") if not ek(os.access, pid_dir, os.W_OK): sys.exit("PID dir: " + pid_dir + " must be writable (write permissions). Exiting.") else: if self.consoleLogging: sys.stdout.write( "Not running in daemon mode. PID file creation disabled.\n" ) self.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = ek(os.path.join, sickbeard.DATA_DIR, "config.ini") # Make sure that we can create the data dir if not ek(os.access, sickbeard.DATA_DIR, os.F_OK): try: ek(os.makedirs, sickbeard.DATA_DIR, 0o744) except os.error: raise SystemExit("Unable to create datadir '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the data dir if not ek(os.access, sickbeard.DATA_DIR, os.W_OK): raise SystemExit("Datadir must be writeable '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the config file if not ek(os.access, sickbeard.CONFIG_FILE, os.W_OK): if ek(os.path.isfile, sickbeard.CONFIG_FILE): raise SystemExit("Config file '" + sickbeard.CONFIG_FILE + "' must be writeable.") elif not ek(os.access, ek(os.path.dirname, sickbeard.CONFIG_FILE), os.W_OK): raise SystemExit("Config file root dir '" + ek(os.path.dirname, sickbeard.CONFIG_FILE) + "' must be writeable.") ek(os.chdir, sickbeard.DATA_DIR) # Check if we need to perform a restore first restoreDir = ek(os.path.join, sickbeard.DATA_DIR, 'restore') if ek(os.path.exists, restoreDir): success = self.restoreDB(restoreDir, sickbeard.DATA_DIR) if self.consoleLogging: sys.stdout.write("Restore: restoring DB and config.ini %s!\n" % ("FAILED", "SUCCESSFUL")[success]) # Load the config and publish it to the sickbeard package if self.consoleLogging and not ek(os.path.isfile, sickbeard.CONFIG_FILE): sys.stdout.write("Unable to find '" + sickbeard.CONFIG_FILE + "' , all settings will be default!" + "\n") sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.consoleLogging) if self.runAsDaemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() # Build from the DB to start with self.loadShowsFromDB() if self.forcedPort: logging.info("Forcing web server to port " + str(self.forcedPort)) self.startPort = self.forcedPort else: self.startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: self.webhost = '::' else: self.webhost = '0.0.0.0' # start tornado web server sickbeard.WEB_SERVER = SRWebServer({ 'port': int(self.startPort), 'host': self.webhost, 'data_root': ek(os.path.join, sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), }).start() # Clean up after update if sickbeard.GIT_NEWVER: toclean = ek(os.path.join, sickbeard.CACHE_DIR, 'mako') for root, dirs, files in ek(os.walk, toclean, topdown=False): for name in files: ek(os.remove, ek(os.path.join, root, name)) for name in dirs: ek(os.rmdir, ek(os.path.join, root, name)) sickbeard.GIT_NEWVER = False # Fire up all our threads logging.info("Starting SiCKRAGE:[{}] CONFIG:[{}]".format( sickbeard.BRANCH, sickbeard.CONFIG_FILE)) sickbeard.start() # Build internal name cache name_cache.buildNameCache() # Prepopulate network timezones, it isn't thread safe network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # Check for metadata indexer updates for shows (Disabled until we use api) # sickbeard.showUpdateScheduler.forceRun() # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.noLaunch or self.runAsDaemon): sickbeard.launchBrowser( 'https' if sickbeard.ENABLE_HTTPS else 'http', self.startPort, sickbeard.WEB_ROOT) # main loop while True: time.sleep(1)
def start(self): """ Start SickChill """ # do some preliminary stuff sickbeard.MY_FULLNAME = ek(os.path.normpath, ek(os.path.abspath, __file__)) sickbeard.MY_NAME = ek(os.path.basename, sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = ek(os.path.dirname, sickbeard.MY_FULLNAME) sickbeard.LOCALE_DIR = ek(os.path.join, sickbeard.PROG_DIR, 'locale') sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] try: locale.setlocale(locale.LC_ALL, '') sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): sickbeard.SYS_ENCODING = 'UTF-8' if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING.lower() in ('ansi_x3.4-1968', 'us-ascii', 'ascii', 'charmap') or \ (sys.platform.startswith('win') and sys.getwindowsversion()[0] >= 6 and str(getattr(sys.stdout, 'device', sys.stdout).encoding).lower() in ('cp65001', 'charmap')): sickbeard.SYS_ENCODING = 'UTF-8' # TODO: Continue working on making this unnecessary, this hack creates all sorts of hellish problems if not hasattr(sys, 'setdefaultencoding'): reload_module(sys) try: # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) except (AttributeError, LookupError): sys.exit( 'Sorry, you MUST add the SickChill folder to the PYTHONPATH environment variable\n' 'or find another way to force Python to use {} for string encoding.' .format(sickbeard.SYS_ENCODING)) # Rename the main thread threading.currentThread().name = 'MAIN' args = SickChillArgumentParser(sickbeard.PROG_DIR).parse_args() if args.force_update: result = self.force_update() sys.exit(int(not result)) # Ok -> 0 , Error -> 1 # Need console logging for SickBeard.py and SickBeard-console.exe sickbeard.NO_RESIZE = args.noresize self.console_logging = (not hasattr(sys, 'frozen')) or ( sickbeard.MY_NAME.lower().find('-console') > 0) and not args.quiet self.no_launch = args.nolaunch self.forced_port = args.port if args.daemon: self.run_as_daemon = platform.system() != 'Windows' self.console_logging = False self.no_launch = True self.create_pid = bool(args.pidfile) self.pid_file = args.pidfile if self.pid_file and ek(os.path.exists, self.pid_file): # If the pid file already exists, SickChill may still be running, so exit raise SystemExit('PID file: {0} already exists. Exiting.'.format( self.pid_file)) sickbeard.DATA_DIR = ek( os.path.abspath, args.datadir) if args.datadir else sickbeard.DATA_DIR sickbeard.CONFIG_FILE = ek( os.path.abspath, args.config) if args.config else ek( os.path.join, sickbeard.DATA_DIR, 'config.ini') # The pid file is only useful in daemon mode, make sure we can write the file properly if self.create_pid: if self.run_as_daemon: pid_dir = ek(os.path.dirname, self.pid_file) if not ek(os.access, pid_dir, os.F_OK): sys.exit('PID dir: {0} doesn\'t exist. Exiting.'.format( pid_dir)) if not ek(os.access, pid_dir, os.W_OK): raise SystemExit( 'PID dir: {0} must be writable (write permissions). Exiting.' .format(pid_dir)) else: if self.console_logging: sys.stdout.write( 'Not running in daemon mode. PID file creation disabled.\n' ) self.create_pid = False # Make sure that we can create the data dir if not ek(os.access, sickbeard.DATA_DIR, os.F_OK): try: ek(os.makedirs, sickbeard.DATA_DIR, 0o744) except os.error: raise SystemExit('Unable to create data directory: {0}'.format( sickbeard.DATA_DIR)) # Make sure we can write to the data dir if not ek(os.access, sickbeard.DATA_DIR, os.W_OK): raise SystemExit('Data directory must be writeable: {0}'.format( sickbeard.DATA_DIR)) # Make sure we can write to the config file if not ek(os.access, sickbeard.CONFIG_FILE, os.W_OK): if ek(os.path.isfile, sickbeard.CONFIG_FILE): raise SystemExit('Config file must be writeable: {0}'.format( sickbeard.CONFIG_FILE)) elif not ek(os.access, ek(os.path.dirname, sickbeard.CONFIG_FILE), os.W_OK): raise SystemExit( 'Config file root dir must be writeable: {0}'.format( ek(os.path.dirname, sickbeard.CONFIG_FILE))) ek(os.chdir, sickbeard.DATA_DIR) # Check if we need to perform a restore first restore_dir = ek(os.path.join, sickbeard.DATA_DIR, 'restore') if ek(os.path.exists, restore_dir): success = self.restore_db(restore_dir, sickbeard.DATA_DIR) if self.console_logging: sys.stdout.write( 'Restore: restoring DB and config.ini {0}!\n'.format( ('FAILED', 'SUCCESSFUL')[success])) # Load the config and publish it to the sickbeard package if self.console_logging and not ek(os.path.isfile, sickbeard.CONFIG_FILE): sys.stdout.write( 'Unable to find {0}, all settings will be default!\n'.format( sickbeard.CONFIG_FILE)) sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE, encoding='UTF-8', options={'indent_type': ' '}) # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.console_logging) if self.run_as_daemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() # Build from the DB to start with self.load_shows_from_db() logger.log('Starting SickChill [{branch}] using \'{config}\''.format( branch=sickbeard.BRANCH, config=sickbeard.CONFIG_FILE)) self.clear_cache() if self.forced_port: logger.log('Forcing web server to port {port}'.format( port=self.forced_port)) self.start_port = self.forced_port else: self.start_port = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.web_host = sickbeard.WEB_HOST else: self.web_host = '' if sickbeard.WEB_IPV6 else '0.0.0.0' # web server options self.web_options = { 'port': int(self.start_port), 'host': self.web_host, 'data_root': ek(os.path.join, sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), } # start web server self.web_server = SRWebServer(self.web_options) self.web_server.start() # Fire up all our threads sickbeard.start() # Build internal name cache name_cache.buildNameCache() # Pre-populate network timezones, it isn't thread safe network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # Check for metadata indexer updates for shows (sets the next aired ep!) # sickbeard.showUpdateScheduler.forceRun() # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.no_launch or self.run_as_daemon): sickbeard.launchBrowser( 'https' if sickbeard.ENABLE_HTTPS else 'http', self.start_port, sickbeard.WEB_ROOT) # main loop while True: time.sleep(1)
def main(): # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(sys.argv[0])) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) config_file = os.path.join(sickbeard.PROG_DIR, "config.ini") # need console logging for SickBeard.py and SickBeard-console.exe consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find("-console") > 0) # rename the main thread threading.currentThread().name = "MAIN" try: opts, args = getopt.getopt(sys.argv[1:], "qfp:", ["quiet", "force-update", "port=", "tvbinz"]) except getopt.GetoptError: print "Available options: --quiet, --forceupdate, --port" sys.exit() forceUpdate = False forcedPort = None for o, a in opts: # for now we'll just silence the logging if o in ("-q", "--quiet"): consoleLogging = False # for now we'll just silence the logging if o in ("--tvbinz"): sickbeard.SHOW_TVBINZ = True # should we update right away? if o in ("-f", "--forceupdate"): forceUpdate = True # should we update right away? if o in ("-p", "--port"): forcedPort = int(a) if consoleLogging: print "Starting up Sick Beard " + SICKBEARD_VERSION + " from " + config_file # load the config and publish it to the sickbeard package if not os.path.isfile(config_file): logger.log("Unable to find config.ini, all settings will be default", logger.ERROR) sickbeard.CFG = ConfigObj(config_file) # initialize the config and our threads sickbeard.initialize(consoleLogging=consoleLogging) sickbeard.showList = [] if forcedPort: logger.log("Forcing web server to port " + str(forcedPort)) startPort = forcedPort else: startPort = sickbeard.WEB_PORT logger.log("Starting Sick Beard on http://localhost:" + str(startPort)) try: initWebServer( { "port": startPort, "data_root": os.path.join(sickbeard.PROG_DIR, "data"), "web_root": sickbeard.WEB_ROOT, "log_dir": sickbeard.LOG_DIR if sickbeard.WEB_LOG else None, "username": sickbeard.WEB_USERNAME, "password": sickbeard.WEB_PASSWORD, } ) except IOError: logger.log( "Unable to start web server, is something else running on port %d?" % sickbeard.WEB_PORT, logger.ERROR ) if sickbeard.LAUNCH_BROWSER: logger.log("Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser() sys.exit() # build from the DB to start with logger.log("Loading initial show list") loadShowsFromDB() # set up the lists sickbeard.updateAiringList() sickbeard.updateComingList() sickbeard.updateMissingList() # fire up all our threads sickbeard.start() # launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER: sickbeard.launchBrowser() # start an update if we're supposed to if forceUpdate: sickbeard.showUpdateScheduler.action.run(force=True) # stay alive while my threads do the work while True: time.sleep(1) return
def openBrowserAction_(self, sender): NSLog("openeing browser oO") sickbeard.launchBrowser()
def main(): # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__)) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.MY_ARGS = sys.argv[1:] try: locale.setlocale(locale.LC_ALL, "") except (locale.Error, IOError): pass sickbeard.SYS_ENCODING = locale.getpreferredencoding() # for OSes that are poorly configured I'll just force UTF-8 if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in ("ANSI_X3.4-1968", "US-ASCII"): sickbeard.SYS_ENCODING = "UTF-8" sickbeard.CONFIG_FILE = os.path.join(sickbeard.PROG_DIR, "config.ini") # need console logging for SickBeard.py and SickBeard-console.exe consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find("-console") > 0) # rename the main thread threading.currentThread().name = "MAIN" try: opts, args = getopt.getopt(sys.argv[1:], "qfdp:", ["quiet", "forceupdate", "daemon", "port=", "tvbinz"]) except getopt.GetoptError: print "Available options: --quiet, --forceupdate, --port, --daemon" sys.exit() forceUpdate = False forcedPort = None for o, a in opts: # for now we'll just silence the logging if o in ("-q", "--quiet"): consoleLogging = False # for now we'll just silence the logging if o in ("--tvbinz"): sickbeard.SHOW_TVBINZ = True # should we update right away? if o in ("-f", "--forceupdate"): forceUpdate = True # use a different port if o in ("-p", "--port"): forcedPort = int(a) # Run as a daemon if o in ("-d", "--daemon"): if sys.platform == "win32": print "Daemonize not supported under Windows, starting normally" else: consoleLogging = False sickbeard.DAEMON = True if consoleLogging: print "Starting up Sick Beard " + SICKBEARD_VERSION + " from " + sickbeard.CONFIG_FILE # load the config and publish it to the sickbeard package if not os.path.isfile(sickbeard.CONFIG_FILE): logger.log(u"Unable to find config.ini, all settings will be default", logger.ERROR) sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # initialize the config and our threads sickbeard.initialize(consoleLogging=consoleLogging) sickbeard.showList = [] if sickbeard.DAEMON: daemonize() # use this pid for everything sickbeard.PID = os.getpid() if forcedPort: logger.log(u"Forcing web server to port " + str(forcedPort)) startPort = forcedPort else: startPort = sickbeard.WEB_PORT logger.log(u"Starting Sick Beard on http://localhost:" + str(startPort)) if sickbeard.WEB_LOG: log_dir = sickbeard.LOG_DIR else: log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic # reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != "0.0.0.0": webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: webhost = "::" else: webhost = "0.0.0.0" try: initWebServer( { "port": startPort, "host": webhost, "data_root": os.path.join(sickbeard.PROG_DIR, "data"), "web_root": sickbeard.WEB_ROOT, "log_dir": log_dir, "username": sickbeard.WEB_USERNAME, "password": sickbeard.WEB_PASSWORD, } ) except IOError: logger.log(u"Unable to start web server, is something else running on port %d?" % startPort, logger.ERROR) if sickbeard.LAUNCH_BROWSER: logger.log(u"Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser(startPort) sys.exit() # build from the DB to start with logger.log(u"Loading initial show list") loadShowsFromDB() # fire up all our threads sickbeard.start() # launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER: sickbeard.launchBrowser(startPort) # start an update if we're supposed to if forceUpdate: sickbeard.showUpdateScheduler.action.run(force=True) # stay alive while my threads do the work while True: time.sleep(1) return
def start(self): # pylint: disable=too-many-branches,too-many-statements """ Start SickRage """ # do some preliminary stuff sickbeard.MY_FULLNAME = ek(os.path.normpath, ek(os.path.abspath, __file__)) sickbeard.MY_NAME = ek(os.path.basename, sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = ek(os.path.dirname, sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] try: locale.setlocale(locale.LC_ALL, "") sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): sickbeard.SYS_ENCODING = "UTF-8" # pylint: disable=no-member if ( not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING.lower() in ("ansi_x3.4-1968", "us-ascii", "ascii", "charmap") or ( sys.platform.startswith("win") and sys.getwindowsversion()[0] >= 6 and str(getattr(sys.stdout, "device", sys.stdout).encoding).lower() in ("cp65001", "charmap") ) ): sickbeard.SYS_ENCODING = "UTF-8" # TODO: Continue working on making this unnecessary, this hack creates all sorts of hellish problems if not hasattr(sys, "setdefaultencoding"): reload(sys) try: # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) # pylint: disable=no-member except (AttributeError, LookupError): sys.exit( "Sorry, you MUST add the SickRage folder to the PYTHONPATH environment variable\n" "or find another way to force Python to use %s for string encoding." % sickbeard.SYS_ENCODING ) # Need console logging for SickBeard.py and SickBeard-console.exe self.console_logging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find("-console") > 0) # Rename the main thread threading.currentThread().name = "MAIN" try: opts, _ = getopt.getopt( sys.argv[1:], "hqdp::", ["help", "quiet", "nolaunch", "daemon", "pidfile=", "port=", "datadir=", "config=", "noresize"], ) except getopt.GetoptError: sys.exit(self.help_message()) for option, value in opts: # Prints help message if option in ("-h", "--help"): sys.exit(self.help_message()) # For now we'll just silence the logging if option in ("-q", "--quiet"): self.console_logging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if option in ("--nolaunch",): self.no_launch = True # Override default/configured port if option in ("-p", "--port"): try: self.forced_port = int(value) except ValueError: sys.exit("Port: %s is not a number. Exiting." % value) # Run as a double forked daemon if option in ("-d", "--daemon"): self.run_as_daemon = True # When running as daemon disable console_logging and don't start browser self.console_logging = False self.no_launch = True if sys.platform == "win32" or sys.platform == "darwin": self.run_as_daemon = False # Write a pid file if requested if option in ("--pidfile",): self.create_pid = True self.pid_file = str(value) # If the pid file already exists, SickRage may still be running, so exit if ek(os.path.exists, self.pid_file): sys.exit("PID file: %s already exists. Exiting." % self.pid_file) # Specify folder to load the config file from if option in ("--config",): sickbeard.CONFIG_FILE = ek(os.path.abspath, value) # Specify folder to use as the data directory if option in ("--datadir",): sickbeard.DATA_DIR = ek(os.path.abspath, value) # Prevent resizing of the banner/posters even if PIL is installed if option in ("--noresize",): sickbeard.NO_RESIZE = True # The pid file is only useful in daemon mode, make sure we can write the file properly if self.create_pid: if self.run_as_daemon: pid_dir = ek(os.path.dirname, self.pid_file) if not ek(os.access, pid_dir, os.F_OK): sys.exit("PID dir: %s doesn't exist. Exiting." % pid_dir) if not ek(os.access, pid_dir, os.W_OK): sys.exit("PID dir: %s must be writable (write permissions). Exiting." % pid_dir) else: if self.console_logging: sys.stdout.write("Not running in daemon mode. PID file creation disabled.\n") self.create_pid = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = ek(os.path.join, sickbeard.DATA_DIR, "config.ini") # Make sure that we can create the data dir if not ek(os.access, sickbeard.DATA_DIR, os.F_OK): try: ek(os.makedirs, sickbeard.DATA_DIR, 0o744) except os.error: raise SystemExit("Unable to create data directory: %s" % sickbeard.DATA_DIR) # Make sure we can write to the data dir if not ek(os.access, sickbeard.DATA_DIR, os.W_OK): raise SystemExit("Data directory must be writeable: %s" % sickbeard.DATA_DIR) # Make sure we can write to the config file if not ek(os.access, sickbeard.CONFIG_FILE, os.W_OK): if ek(os.path.isfile, sickbeard.CONFIG_FILE): raise SystemExit("Config file must be writeable: %s" % sickbeard.CONFIG_FILE) elif not ek(os.access, ek(os.path.dirname, sickbeard.CONFIG_FILE), os.W_OK): raise SystemExit( "Config file root dir must be writeable: %s" % ek(os.path.dirname, sickbeard.CONFIG_FILE) ) ek(os.chdir, sickbeard.DATA_DIR) # Check if we need to perform a restore first restore_dir = ek(os.path.join, sickbeard.DATA_DIR, "restore") if ek(os.path.exists, restore_dir): success = self.restore_db(restore_dir, sickbeard.DATA_DIR) if self.console_logging: sys.stdout.write("Restore: restoring DB and config.ini %s!\n" % ("FAILED", "SUCCESSFUL")[success]) # Load the config and publish it to the sickbeard package if self.console_logging and not ek(os.path.isfile, sickbeard.CONFIG_FILE): sys.stdout.write("Unable to find %s, all settings will be default!\n" % sickbeard.CONFIG_FILE) sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.console_logging) if self.run_as_daemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() # Build from the DB to start with self.load_shows_from_db() logger.log("Starting SickRage [%s] from '%s'" % (sickbeard.BRANCH, sickbeard.CONFIG_FILE)) self.clear_cache() if self.forced_port: logger.log("Forcing web server to port %s" % self.forced_port) self.start_port = self.forced_port else: self.start_port = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != "0.0.0.0": self.web_host = sickbeard.WEB_HOST else: self.web_host = "" if sickbeard.WEB_IPV6 else "0.0.0.0" # web server options self.web_options = { "port": int(self.start_port), "host": self.web_host, "data_root": ek(os.path.join, sickbeard.PROG_DIR, "gui", sickbeard.GUI_NAME), "web_root": sickbeard.WEB_ROOT, "log_dir": self.log_dir, "username": sickbeard.WEB_USERNAME, "password": sickbeard.WEB_PASSWORD, "enable_https": sickbeard.ENABLE_HTTPS, "handle_reverse_proxy": sickbeard.HANDLE_REVERSE_PROXY, "https_cert": ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), "https_key": ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), } # start web server self.web_server = SRWebServer(self.web_options) self.web_server.start() # Fire up all our threads sickbeard.start() # Build internal name cache # name_cache.buildNameCache() # Pre-populate network timezones, it isn't thread safe network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # # Check for metadata indexer updates for shows (Disabled until we use api) # sickbeard.showUpdateScheduler.forceRun() # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.no_launch or self.run_as_daemon): sickbeard.launchBrowser("https" if sickbeard.ENABLE_HTTPS else "http", self.start_port, sickbeard.WEB_ROOT) # main loop while True: time.sleep(1)
def start(self): # pylint: disable=too-many-branches,too-many-statements """ Start SickRage """ # do some preliminary stuff sickbeard.MY_FULLNAME = ek(os.path.normpath, ek(os.path.abspath, __file__)) sickbeard.MY_NAME = ek(os.path.basename, sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = ek(os.path.dirname, sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] try: locale.setlocale(locale.LC_ALL, '') sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): sickbeard.SYS_ENCODING = 'UTF-8' # pylint: disable=no-member if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING.lower() in ('ansi_x3.4-1968', 'us-ascii', 'ascii', 'charmap') or \ (sys.platform.startswith('win') and sys.getwindowsversion()[0] >= 6 and str(getattr(sys.stdout, 'device', sys.stdout).encoding).lower() in ('cp65001', 'charmap')): sickbeard.SYS_ENCODING = 'UTF-8' # TODO: Continue working on making this unnecessary, this hack creates all sorts of hellish problems if not hasattr(sys, 'setdefaultencoding'): reload(sys) try: # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) # pylint: disable=no-member except (AttributeError, LookupError): sys.exit( 'Sorry, you MUST add the SickRage folder to the PYTHONPATH environment variable\n' 'or find another way to force Python to use %s for string encoding.' % sickbeard.SYS_ENCODING) # Need console logging for SickBeard.py and SickBeard-console.exe self.console_logging = (not hasattr( sys, 'frozen')) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = 'MAIN' try: opts, _ = getopt.getopt(sys.argv[1:], 'hqdp::', [ 'help', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize' ]) except getopt.GetoptError: sys.exit(self.help_message()) for option, value in opts: # Prints help message if option in ('-h', '--help'): sys.exit(self.help_message()) # For now we'll just silence the logging if option in ('-q', '--quiet'): self.console_logging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if option in ('--nolaunch', ): self.no_launch = True # Override default/configured port if option in ('-p', '--port'): try: self.forced_port = int(value) except ValueError: sys.exit( 'Port: {0} is not a number. Exiting.'.format(value)) # Run as a double forked daemon if option in ('-d', '--daemon'): self.run_as_daemon = True # When running as daemon disable console_logging and don't start browser self.console_logging = False self.no_launch = True if sys.platform == 'win32' or sys.platform == 'darwin': self.run_as_daemon = False # Write a pid file if requested if option in ('--pidfile', ): self.create_pid = True self.pid_file = str(value) # If the pid file already exists, SickRage may still be running, so exit if ek(os.path.exists, self.pid_file): sys.exit('PID file: {0} already exists. Exiting.'.format( self.pid_file)) # Specify folder to load the config file from if option in ('--config', ): sickbeard.CONFIG_FILE = ek(os.path.abspath, value) # Specify folder to use as the data directory if option in ('--datadir', ): sickbeard.DATA_DIR = ek(os.path.abspath, value) # Prevent resizing of the banner/posters even if PIL is installed if option in ('--noresize', ): sickbeard.NO_RESIZE = True # The pid file is only useful in daemon mode, make sure we can write the file properly if self.create_pid: if self.run_as_daemon: pid_dir = ek(os.path.dirname, self.pid_file) if not ek(os.access, pid_dir, os.F_OK): sys.exit('PID dir: {0} doesn\'t exist. Exiting.'.format( pid_dir)) if not ek(os.access, pid_dir, os.W_OK): sys.exit( 'PID dir: {0} must be writable (write permissions). Exiting.' .format(pid_dir)) else: if self.console_logging: sys.stdout.write( 'Not running in daemon mode. PID file creation disabled.\n' ) self.create_pid = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = ek(os.path.join, sickbeard.DATA_DIR, 'config.ini') # Make sure that we can create the data dir if not ek(os.access, sickbeard.DATA_DIR, os.F_OK): try: ek(os.makedirs, sickbeard.DATA_DIR, 0o744) except os.error: raise SystemExit('Unable to create data directory: {0}'.format( sickbeard.DATA_DIR)) # Make sure we can write to the data dir if not ek(os.access, sickbeard.DATA_DIR, os.W_OK): raise SystemExit('Data directory must be writeable: {0}'.format( sickbeard.DATA_DIR)) # Make sure we can write to the config file if not ek(os.access, sickbeard.CONFIG_FILE, os.W_OK): if ek(os.path.isfile, sickbeard.CONFIG_FILE): raise SystemExit('Config file must be writeable: {0}'.format( sickbeard.CONFIG_FILE)) elif not ek(os.access, ek(os.path.dirname, sickbeard.CONFIG_FILE), os.W_OK): raise SystemExit( 'Config file root dir must be writeable: {0}'.format( ek(os.path.dirname, sickbeard.CONFIG_FILE))) ek(os.chdir, sickbeard.DATA_DIR) # Check if we need to perform a restore first restore_dir = ek(os.path.join, sickbeard.DATA_DIR, 'restore') if ek(os.path.exists, restore_dir): success = self.restore_db(restore_dir, sickbeard.DATA_DIR) if self.console_logging: sys.stdout.write( 'Restore: restoring DB and config.ini {0}!\n'.format( ('FAILED', 'SUCCESSFUL')[success])) # Load the config and publish it to the sickbeard package if self.console_logging and not ek(os.path.isfile, sickbeard.CONFIG_FILE): sys.stdout.write( 'Unable to find {0}, all settings will be default!\n'.format( sickbeard.CONFIG_FILE)) sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.console_logging) if self.run_as_daemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() # Build from the DB to start with self.load_shows_from_db() logger.log('Starting SickRage [{branch}] using \'{config}\''.format( branch=sickbeard.BRANCH, config=sickbeard.CONFIG_FILE)) self.clear_cache() if self.forced_port: logger.log('Forcing web server to port {port}'.format( port=self.forced_port)) self.start_port = self.forced_port else: self.start_port = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.web_host = sickbeard.WEB_HOST else: self.web_host = '' if sickbeard.WEB_IPV6 else '0.0.0.0' # web server options self.web_options = { 'port': int(self.start_port), 'host': self.web_host, 'data_root': ek(os.path.join, sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': ek(os.path.join, sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), } # start web server self.web_server = SRWebServer(self.web_options) self.web_server.start() # Fire up all our threads sickbeard.start() # Build internal name cache name_cache.buildNameCache() # Pre-populate network timezones, it isn't thread safe network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # Check for metadata indexer updates for shows (sets the next aired ep!) # sickbeard.showUpdateScheduler.forceRun() # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.no_launch or self.run_as_daemon): sickbeard.launchBrowser( 'https' if sickbeard.ENABLE_HTTPS else 'http', self.start_port, sickbeard.WEB_ROOT) # main loop while True: time.sleep(1)
def main(): # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(sys.argv[0])) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) config_file = os.path.join(sickbeard.PROG_DIR, "config.ini") # need console logging for SickBeard.py and SickBeard-console.exe consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # rename the main thread threading.currentThread().name = "MAIN" try: opts, args = getopt.getopt(sys.argv[1:], "q", ['quiet']) except getopt.GetoptError: print "Available options: --quiet" sys.exit() for o, a in opts: # for now we'll just silence the logging if (o in ('-q', '--quiet')): consoleLogging = False if consoleLogging: print "Starting up Sick Beard "+SICKBEARD_VERSION+" from " + config_file # load the config and publish it to the sickbeard package if not os.path.isfile(config_file): logger.log("Unable to find config.ini, all settings will be default", logger.ERROR) sickbeard.CFG = ConfigObj(config_file) # initialize the config and our threads sickbeard.initialize(consoleLogging=consoleLogging) sickbeard.showList = [] try: initWebServer({ 'port': sickbeard.WEB_PORT, 'data_root': os.path.join(sickbeard.PROG_DIR, 'data'), 'web_root': sickbeard.WEB_ROOT, 'log_dir': sickbeard.LOG_DIR if sickbeard.WEB_LOG else None, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, }) except IOError: logger.log("Unable to start web server, is something else running on port %d?" % sickbeard.WEB_PORT, logger.ERROR) if sickbeard.LAUNCH_BROWSER: logger.log("Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser() sys.exit() # build from the DB to start with logger.log("Loading initial show list") loadShowsFromDB() # set up the lists sickbeard.updateAiringList() sickbeard.updateComingList() sickbeard.updateMissingList() # fire up all our threads sickbeard.start() # launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER: sickbeard.launchBrowser() # stay alive while my threads do the work while (True): time.sleep(1) return
'port': startPort, 'host': webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'data'), 'web_root': sickbeard.WEB_ROOT, 'log_dir': log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'https_cert': sickbeard.HTTPS_CERT, 'https_key': sickbeard.HTTPS_KEY, }) except IOError: logger.log(u"Unable to start web server, is something else running on port %d?" % startPort, logger.ERROR) if sickbeard.LAUNCH_BROWSER and not sickbeard.DAEMON: logger.log(u"Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser(startPort) sys.exit() # build from the DB to start with logger.log(u"Loading initial show list") loadShowsFromDB() # fire up all our threads sickbeard.start() # launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER and not noLaunch and not sickbeard.DAEMON: sickbeard.launchBrowser(startPort) # start an update if we're supposed to if forceUpdate:
def start(self): # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__)) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] try: locale.setlocale(locale.LC_ALL, "") sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): sickbeard.SYS_ENCODING = 'UTF-8' # pylint: disable=E1101 if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING.lower() in ('ansi_x3.4-1968', 'us-ascii', 'ascii', 'charmap') or \ (sys.platform.startswith('win') and sys.getwindowsversion()[0] >= 6 and str(getattr(sys.stdout, 'device', sys.stdout).encoding).lower() in ('cp65001', 'charmap')): sickbeard.SYS_ENCODING = 'UTF-8' # TODO: Continue working on making this unnecessary, this hack creates all sorts of hellish problems if not hasattr(sys, "setdefaultencoding"): reload(sys) try: # pylint: disable=E1101 # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) except Exception: sys.exit( "Sorry, you MUST add the SickRage folder to the PYTHONPATH environment variable\n" + "or find another way to force Python to use " + sickbeard.SYS_ENCODING + " for string encoding.") # Need console logging for SickBeard.py and SickBeard-console.exe self.consoleLogging = (not hasattr( sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = u"MAIN" try: opts, _ = getopt.getopt(sys.argv[1:], "hqdp::", [ 'help', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize' ]) except getopt.GetoptError: sys.exit(self.help_message()) for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(self.help_message()) # For now we'll just silence the logging if o in ('-q', '--quiet'): self.consoleLogging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch', ): self.noLaunch = True # Override default/configured port if o in ('-p', '--port'): try: self.forcedPort = int(a) except ValueError: sys.exit("Port: " + str(a) + " is not a number. Exiting.") # Run as a double forked daemon if o in ('-d', '--daemon'): self.runAsDaemon = True # When running as daemon disable consoleLogging and don't start browser self.consoleLogging = False self.noLaunch = True if sys.platform == 'win32' or sys.platform == 'darwin': self.runAsDaemon = False # Write a pidfile if requested if o in ('--pidfile', ): self.CREATEPID = True self.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if os.path.exists(self.PIDFILE): sys.exit("PID file: " + self.PIDFILE + " already exists. Exiting.") # Specify folder to load the config file from if o in ('--config', ): sickbeard.CONFIG_FILE = os.path.abspath(a) # Specify folder to use as the data dir if o in ('--datadir', ): sickbeard.DATA_DIR = os.path.abspath(a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize', ): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if self.CREATEPID: if self.runAsDaemon: pid_dir = os.path.dirname(self.PIDFILE) if not os.access(pid_dir, os.F_OK): sys.exit("PID dir: " + pid_dir + " doesn't exist. Exiting.") if not os.access(pid_dir, os.W_OK): sys.exit("PID dir: " + pid_dir + " must be writable (write permissions). Exiting.") else: if self.consoleLogging: sys.stdout.write( u"Not running in daemon mode. PID file creation disabled.\n" ) self.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = os.path.join(sickbeard.DATA_DIR, "config.ini") # Make sure that we can create the data dir if not os.access(sickbeard.DATA_DIR, os.F_OK): try: os.makedirs(sickbeard.DATA_DIR, 0744) except os.error: raise SystemExit("Unable to create datadir '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the data dir if not os.access(sickbeard.DATA_DIR, os.W_OK): raise SystemExit("Datadir must be writeable '" + sickbeard.DATA_DIR + "'") # Make sure we can write to the config file if not os.access(sickbeard.CONFIG_FILE, os.W_OK): if os.path.isfile(sickbeard.CONFIG_FILE): raise SystemExit("Config file '" + sickbeard.CONFIG_FILE + "' must be writeable.") elif not os.access(os.path.dirname(sickbeard.CONFIG_FILE), os.W_OK): raise SystemExit("Config file root dir '" + os.path.dirname(sickbeard.CONFIG_FILE) + "' must be writeable.") os.chdir(sickbeard.DATA_DIR) # Check if we need to perform a restore first restoreDir = os.path.join(sickbeard.DATA_DIR, 'restore') if os.path.exists(restoreDir): success = self.restoreDB(restoreDir, sickbeard.DATA_DIR) if self.consoleLogging: sys.stdout.write( u"Restore: restoring DB and config.ini %s!\n" % ("FAILED", "SUCCESSFUL")[success]) # Load the config and publish it to the sickbeard package if self.consoleLogging and not os.path.isfile(sickbeard.CONFIG_FILE): sys.stdout.write(u"Unable to find '" + sickbeard.CONFIG_FILE + "' , all settings will be default!" + "\n") sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=self.consoleLogging) if self.runAsDaemon: self.daemonize() # Get PID sickbeard.PID = os.getpid() # Build from the DB to start with self.loadShowsFromDB() if self.forcedPort: logger.log(u"Forcing web server to port " + str(self.forcedPort)) self.startPort = self.forcedPort else: self.startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: self.log_dir = sickbeard.LOG_DIR else: self.log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': self.webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: self.webhost = '::' else: self.webhost = '0.0.0.0' # web server options self.web_options = { 'port': int(self.startPort), 'host': self.webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'gui', sickbeard.GUI_NAME), 'web_root': sickbeard.WEB_ROOT, 'log_dir': self.log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'handle_reverse_proxy': sickbeard.HANDLE_REVERSE_PROXY, 'https_cert': os.path.join(sickbeard.PROG_DIR, sickbeard.HTTPS_CERT), 'https_key': os.path.join(sickbeard.PROG_DIR, sickbeard.HTTPS_KEY), } # start web server self.webserver = SRWebServer(self.web_options) self.webserver.start() if self.consoleLogging: print "Starting up SickRage " + sickbeard.BRANCH + " from " + sickbeard.CONFIG_FILE # Clean up after update if sickbeard.GIT_NEWVER: toclean = os.path.join(sickbeard.CACHE_DIR, 'mako') for root, dirs, files in os.walk(toclean, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) sickbeard.GIT_NEWVER = False # Fire up all our threads sickbeard.start() # Build internal name cache name_cache.buildNameCache() # Prepopulate network timezones, it isn't thread safe network_timezones.update_network_dict() # sure, why not? if sickbeard.USE_FAILED_DOWNLOADS: failed_history.trimHistory() # # Check for metadata indexer updates for shows (Disabled until we use api) # sickbeard.showUpdateScheduler.forceRun() # Launch browser if sickbeard.LAUNCH_BROWSER and not (self.noLaunch or self.runAsDaemon): sickbeard.launchBrowser( 'https' if sickbeard.ENABLE_HTTPS else 'http', self.startPort, sickbeard.WEB_ROOT) # main loop while True: time.sleep(1)
def main(): """ TV for me """ # do some preliminary stuff sickbeard.MY_FULLNAME = os.path.normpath(os.path.abspath(__file__)) sickbeard.MY_NAME = os.path.basename(sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = os.path.dirname(sickbeard.MY_FULLNAME) sickbeard.DATA_DIR = sickbeard.PROG_DIR sickbeard.MY_ARGS = sys.argv[1:] sickbeard.DAEMON = False sickbeard.CREATEPID = False sickbeard.SYS_ENCODING = None try: locale.setlocale(locale.LC_ALL, "") sickbeard.SYS_ENCODING = locale.getpreferredencoding() except (locale.Error, IOError): pass # For OSes that are poorly configured I'll just randomly force UTF-8 if not sickbeard.SYS_ENCODING or sickbeard.SYS_ENCODING in ('ANSI_X3.4-1968', 'US-ASCII', 'ASCII'): sickbeard.SYS_ENCODING = 'UTF-8' if not hasattr(sys, "setdefaultencoding"): reload(sys) try: # pylint: disable=E1101 # On non-unicode builds this will raise an AttributeError, if encoding type is not valid it throws a LookupError sys.setdefaultencoding(sickbeard.SYS_ENCODING) except: sys.exit("Sorry, you MUST add the Sick Beard folder to the PYTHONPATH environment variable\n" + "or find another way to force Python to use " + sickbeard.SYS_ENCODING + " for string encoding.") # Need console logging for SickBeard.py and SickBeard-console.exe consoleLogging = (not hasattr(sys, "frozen")) or (sickbeard.MY_NAME.lower().find('-console') > 0) # Rename the main thread threading.currentThread().name = "MAIN" try: opts, args = getopt.getopt(sys.argv[1:], "hfqdp::", ['help', 'forceupdate', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=', 'datadir=', 'config=', 'noresize']) # @UnusedVariable except getopt.GetoptError: sys.exit(help_message()) forceUpdate = False forcedPort = None noLaunch = False for o, a in opts: # Prints help message if o in ('-h', '--help'): sys.exit(help_message()) # Should we update (from tvdb) all shows in the DB right away? if o in ('-f', '--forceupdate'): forceUpdate = True # Disables logging to console if o in ('-q', '--quiet'): consoleLogging = False # Suppress launching web browser # Needed for OSes without default browser assigned # Prevent duplicate browser window when restarting in the app if o in ('--nolaunch',): noLaunch = True # Run as a double forked daemon if o in ('-d', '--daemon'): sickbeard.DAEMON = True # When running as daemon disable consoleLogging and don't start browser consoleLogging = False noLaunch = True if sys.platform == 'win32': sickbeard.DAEMON = False # Write a pidfile if requested if o in ('--pidfile',): sickbeard.CREATEPID = True sickbeard.PIDFILE = str(a) # If the pidfile already exists, sickbeard may still be running, so exit if os.path.exists(sickbeard.PIDFILE): sys.exit("PID file: " + sickbeard.PIDFILE + " already exists. Exiting.") # Override default/configured port if o in ('-p', '--port'): try: forcedPort = int(a) except ValueError: sys.exit("Port: " + str(a) + " is not a number. Exiting.") # Specify folder to use as data dir (storing database, configfile, cache, logfiles) if o in ('--datadir',): sickbeard.DATA_DIR = os.path.abspath(a) # Specify filename to load the config information from if o in ('--config',): sickbeard.CONFIG_FILE = os.path.abspath(a) # Prevent resizing of the banner/posters even if PIL is installed if o in ('--noresize',): sickbeard.NO_RESIZE = True # The pidfile is only useful in daemon mode, make sure we can write the file properly if sickbeard.CREATEPID: if sickbeard.DAEMON: pid_dir = os.path.dirname(sickbeard.PIDFILE) if not os.access(pid_dir, os.F_OK): sys.exit("PID dir: " + pid_dir + " doesn't exist. Exiting.") if not os.access(pid_dir, os.W_OK): sys.exit("PID dir: " + pid_dir + " must be writable (write permissions). Exiting.") else: if consoleLogging: sys.stdout.write("Not running in daemon mode. PID file creation disabled.\n") sickbeard.CREATEPID = False # If they don't specify a config file then put it in the data dir if not sickbeard.CONFIG_FILE: sickbeard.CONFIG_FILE = os.path.join(sickbeard.DATA_DIR, "config.ini") # Make sure that we can create the data dir if not os.access(sickbeard.DATA_DIR, os.F_OK): try: os.makedirs(sickbeard.DATA_DIR, 0744) except os.error: sys.exit("Unable to create data directory: " + sickbeard.DATA_DIR + " Exiting.") # Make sure we can write to the data dir if not os.access(sickbeard.DATA_DIR, os.W_OK): sys.exit("Data directory: " + sickbeard.DATA_DIR + " must be writable (write permissions). Exiting.") # Make sure we can write to the config file if not os.access(sickbeard.CONFIG_FILE, os.W_OK): if os.path.isfile(sickbeard.CONFIG_FILE): sys.exit("Config file: " + sickbeard.CONFIG_FILE + " must be writeable (write permissions). Exiting.") elif not os.access(os.path.dirname(sickbeard.CONFIG_FILE), os.W_OK): sys.exit("Config file directory: " + os.path.dirname(sickbeard.CONFIG_FILE) + " must be writeable (write permissions). Exiting") os.chdir(sickbeard.DATA_DIR) if consoleLogging: sys.stdout.write("Starting up Sick Beard " + SICKBEARD_VERSION + "\n") if not os.path.isfile(sickbeard.CONFIG_FILE): sys.stdout.write("Unable to find '" + sickbeard.CONFIG_FILE + "' , all settings will be default!" + "\n") # Load the config and publish it to the sickbeard package sickbeard.CFG = ConfigObj(sickbeard.CONFIG_FILE) # Initialize the config and our threads sickbeard.initialize(consoleLogging=consoleLogging) sickbeard.showList = [] if sickbeard.DAEMON: daemonize() # Use this PID for everything sickbeard.PID = os.getpid() if forcedPort: logger.log(u"Forcing web server to port " + str(forcedPort)) startPort = forcedPort else: startPort = sickbeard.WEB_PORT if sickbeard.WEB_LOG: log_dir = sickbeard.LOG_DIR else: log_dir = None # sickbeard.WEB_HOST is available as a configuration value in various # places but is not configurable. It is supported here for historic reasons. if sickbeard.WEB_HOST and sickbeard.WEB_HOST != '0.0.0.0': webhost = sickbeard.WEB_HOST else: if sickbeard.WEB_IPV6: webhost = '::' else: webhost = '0.0.0.0' try: initWebServer({ 'port': startPort, 'host': webhost, 'data_root': os.path.join(sickbeard.PROG_DIR, 'data'), 'web_root': sickbeard.WEB_ROOT, 'log_dir': log_dir, 'username': sickbeard.WEB_USERNAME, 'password': sickbeard.WEB_PASSWORD, 'enable_https': sickbeard.ENABLE_HTTPS, 'https_cert': sickbeard.HTTPS_CERT, 'https_key': sickbeard.HTTPS_KEY, 'whitelist': sickbeard.WEB_WHITELIST, }) except IOError: logger.log(u"Unable to start web server, is something else running on port: " + str(startPort), logger.ERROR) if sickbeard.LAUNCH_BROWSER and not sickbeard.DAEMON: logger.log(u"Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser(startPort) sys.exit("Unable to start web server, is something else running on port: " + str(startPort)) # Build from the DB to start with logger.log(u"Loading initial show list") loadShowsFromDB() # Fire up all our threads sickbeard.start() # Launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER and not noLaunch and not sickbeard.DAEMON: sickbeard.launchBrowser(startPort) # Start an update if we're supposed to if forceUpdate: sickbeard.showUpdateScheduler.action.run(force=True) # @UndefinedVariable # Stay alive while my threads do the work while (True): if sickbeard.invoked_command: sickbeard.invoked_command() sickbeard.invoked_command = None time.sleep(1) return
def main(): # do some preliminary stuff sickbeard.PROG_DIR = os.path.dirname(os.path.normpath(os.path.abspath(sys.argv[0]))) sickbeard.CONFIG_FILE = "config.ini" # rename the main thread threading.currentThread().name = "MAIN" print "Starting up Sick Beard "+SICKBEARD_VERSION+" from " + os.path.join(sickbeard.PROG_DIR, sickbeard.CONFIG_FILE) # load the config and publish it to the sickbeard package if not os.path.isfile(os.path.join(sickbeard.PROG_DIR, sickbeard.CONFIG_FILE)): logger.log("Unable to find config.ini, all settings will be default", logger.ERROR) sickbeard.CFG = ConfigObj(os.path.join(sickbeard.PROG_DIR, sickbeard.CONFIG_FILE)) # initialize the config and our threads sickbeard.initialize() sickbeard.showList = [] # setup cherrypy logging if os.path.isdir(sickbeard.LOG_DIR) and sickbeard.WEB_LOG: cherry_log = os.path.join(sickbeard.LOG_DIR, "cherrypy.log") logger.log("Using " + cherry_log + " for cherrypy log") else: cherry_log = None # cherrypy setup cherrypy.config.update({ 'server.socket_port': sickbeard.WEB_PORT, 'server.socket_host': '0.0.0.0', 'log.screen': False, 'log.access_file': cherry_log }) userpassdict = {sickbeard.WEB_USERNAME: sickbeard.WEB_PASSWORD} checkpassword = cherrypy.lib.auth_basic.checkpassword_dict(userpassdict) if sickbeard.WEB_USERNAME == "" or sickbeard.WEB_PASSWORD == "": useAuth = False else: useAuth = True conf = { '/': { 'tools.staticdir.root': os.path.join(sickbeard.PROG_DIR, 'data'), 'tools.auth_basic.on': useAuth, 'tools.auth_basic.realm': 'SickBeard', 'tools.auth_basic.checkpassword': checkpassword }, '/images': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'images' }, '/js': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'js' }, '/css': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'css' }, } cherrypy.tree.mount(WebInterface(), sickbeard.WEB_ROOT, conf) try: cherrypy.server.start() cherrypy.server.wait() except IOError: logger.log("Unable to start web server, is something else running on port %d?" % sickbeard.WEB_PORT, logger.ERROR) if sickbeard.LAUNCH_BROWSER: logger.log("Launching browser and exiting", logger.ERROR) sickbeard.launchBrowser() sys.exit() # build from the DB to start with logger.log("Loading initial show list") loadShowsFromDB() # set up the lists sickbeard.updateAiringList() sickbeard.updateComingList() sickbeard.updateMissingList() # fire up all our threads sickbeard.start() # launch browser if we're supposed to if sickbeard.LAUNCH_BROWSER: sickbeard.launchBrowser() # stay alive while my threads do the work while (True): time.sleep(1) return