Ejemplo n.º 1
0
    def addDefaultShow(indexer, indexer_id, name, status):
        """
        Adds a new show with the default settings
        """
        if not findCertainShow(sickrage.srCore.SHOWLIST, int(indexer_id)):
            sickrage.srLogger.info("Adding show " + str(indexer_id))
            root_dirs = sickrage.srConfig.ROOT_DIRS.split('|')

            try:
                location = root_dirs[int(root_dirs[0]) + 1]
            except Exception:
                location = None

            if location:
                showPath = os.path.join(location, sanitizeFileName(name))
                dir_exists = makeDir(showPath)

                if not dir_exists:
                    sickrage.srLogger.warning("Unable to create the folder %s , can't add the show" % showPath)
                    return
                else:
                    chmodAsParent(showPath)

                sickrage.srCore.SHOWQUEUE.addShow(int(indexer), int(indexer_id), showPath,
                                              default_status=status,
                                              quality=int(sickrage.srConfig.QUALITY_DEFAULT),
                                              flatten_folders=int(sickrage.srConfig.FLATTEN_FOLDERS_DEFAULT),
                                              paused=sickrage.srConfig.TRAKT_START_PAUSED,
                                              default_status_after=status,
                                              archive=sickrage.srConfig.ARCHIVE_DEFAULT)
            else:
                sickrage.srLogger.warning("There was an error creating the show, no root directory setting found")
                return
Ejemplo n.º 2
0
    def addDefaultShow(indexer, indexer_id, name, status):
        """
        Adds a new show with the default settings
        """
        if not findCertainShow(sickrage.srCore.SHOWLIST, int(indexer_id)):
            sickrage.srLogger.info("Adding show " + str(indexer_id))
            root_dirs = sickrage.srConfig.ROOT_DIRS.split('|')

            try:
                location = root_dirs[int(root_dirs[0]) + 1]
            except Exception:
                location = None

            if location:
                showPath = os.path.join(location, sanitizeFileName(name))
                dir_exists = makeDir(showPath)

                if not dir_exists:
                    sickrage.srLogger.warning("Unable to create the folder %s , can't add the show" % showPath)
                    return
                else:
                    chmodAsParent(showPath)

                sickrage.srCore.SHOWQUEUE.addShow(int(indexer), int(indexer_id), showPath,
                                              default_status=status,
                                              quality=int(sickrage.srConfig.QUALITY_DEFAULT),
                                              flatten_folders=int(sickrage.srConfig.FLATTEN_FOLDERS_DEFAULT),
                                              paused=sickrage.srConfig.TRAKT_START_PAUSED,
                                              default_status_after=status,
                                              archive=sickrage.srConfig.ARCHIVE_DEFAULT)
            else:
                sickrage.srLogger.warning("There was an error creating the show, no root directory setting found")
                return
Ejemplo n.º 3
0
def getSubtitlesPath(video_path):
    if os.path.isabs(sickrage.srConfig.SUBTITLES_DIR):
        new_subtitles_path = sickrage.srConfig.SUBTITLES_DIR
    elif sickrage.srConfig.SUBTITLES_DIR:
        new_subtitles_path = os.path.join(os.path.dirname(video_path), sickrage.srConfig.SUBTITLES_DIR)
        dir_exists = makeDir(new_subtitles_path)
        if not dir_exists:
            sickrage.srLogger.error('Unable to create subtitles folder ' + new_subtitles_path)
        else:
            chmodAsParent(new_subtitles_path)
    else:
        new_subtitles_path = os.path.join(os.path.dirname(video_path))

    return new_subtitles_path
Ejemplo n.º 4
0
def getSubtitlesPath(video_path):
    if os.path.isabs(sickrage.srConfig.SUBTITLES_DIR):
        new_subtitles_path = sickrage.srConfig.SUBTITLES_DIR
    elif sickrage.srConfig.SUBTITLES_DIR:
        new_subtitles_path = os.path.join(os.path.dirname(video_path),
                                          sickrage.srConfig.SUBTITLES_DIR)
        dir_exists = makeDir(new_subtitles_path)
        if not dir_exists:
            sickrage.srLogger.error('Unable to create subtitles folder ' +
                                    new_subtitles_path)
        else:
            chmodAsParent(new_subtitles_path)
    else:
        new_subtitles_path = os.path.join(os.path.dirname(video_path))

    return new_subtitles_path
Ejemplo n.º 5
0
    def start(self):
        self.PID = os.getpid()

        # set socket timeout
        socket.setdefaulttimeout(sickrage.srConfig.SOCKET_TIMEOUT)

        # init version updater
        self.VERSIONUPDATER = srVersionUpdater()

        # init updater and get current version
        self.VERSION = self.VERSIONUPDATER.updater.version

        # init services
        self.SCHEDULER = srScheduler()
        self.WEBSERVER = srWebServer()
        self.INDEXER_API = srIndexerApi

        # init caches
        self.NAMECACHE = srNameCache()

        # init queues
        self.SHOWUPDATER = srShowUpdater()
        self.SHOWQUEUE = srShowQueue()
        self.SEARCHQUEUE = srSearchQueue()

        # init searchers
        self.DAILYSEARCHER = srDailySearcher()
        self.BACKLOGSEARCHER = srBacklogSearcher()
        self.PROPERSEARCHER = srProperSearcher()
        self.TRAKTSEARCHER = srTraktSearcher()
        self.SUBTITLESEARCHER = srSubtitleSearcher()

        # init postprocessor
        self.AUTOPOSTPROCESSOR = srPostProcessor()

        # migrate old database file names to new ones
        if not os.path.exists(main_db.MainDB().filename) and os.path.exists("sickbeard.db"):
            helpers.moveFile("sickbeard.db", main_db.MainDB().filename)

        # initialize the main SB database
        main_db.MainDB().InitialSchema().upgrade()

        # initialize the cache database
        cache_db.CacheDB().InitialSchema().upgrade()

        # initialize the failed downloads database
        failed_db.FailedDB().InitialSchema().upgrade()

        # fix up any db problems
        main_db.MainDB().SanityCheck()

        # load data for shows from database
        self.load_shows()

        if sickrage.srConfig.DEFAULT_PAGE not in ('home', 'schedule', 'history', 'news', 'IRC'):
            sickrage.srConfig.DEFAULT_PAGE = 'home'

        if not makeDir(sickrage.srConfig.CACHE_DIR):
            sickrage.srLogger.error("!!! Creating local cache dir failed")
            sickrage.srConfig.CACHE_DIR = get_temp_dir()

        # Check if we need to perform a restore of the cache folder
        try:
            restore_dir = os.path.join(sickrage.DATA_DIR, 'restore')
            if os.path.exists(restore_dir) and os.path.exists(os.path.join(restore_dir, 'cache')):
                def restore_cache(src_dir, dst_dir):
                    def path_leaf(path):
                        head, tail = os.path.split(path)
                        return tail or os.path.basename(head)

                    try:
                        if os.path.isdir(dst_dir):
                            bak_filename = '{}-{}'.format(path_leaf(dst_dir), datetime.now().strftime('%Y%m%d_%H%M%S'))
                            shutil.move(dst_dir, os.path.join(os.path.dirname(dst_dir), bak_filename))

                        shutil.move(src_dir, dst_dir)
                        sickrage.srLogger.info("Restore: restoring cache successful")
                    except Exception as E:
                        sickrage.srLogger.error("Restore: restoring cache failed: {}".format(E.message))

                restore_cache(os.path.join(restore_dir, 'cache'), sickrage.srConfig.CACHE_DIR)
        except Exception as e:
            sickrage.srLogger.error("Restore: restoring cache failed: {}".format(e.message))
        finally:
            if os.path.exists(os.path.join(sickrage.DATA_DIR, 'restore')):
                try:
                    removetree(os.path.join(sickrage.DATA_DIR, 'restore'))
                except Exception as e:
                    sickrage.srLogger.error("Restore: Unable to remove the restore directory: {}".format(e.message))

                for cleanupDir in ['mako', 'sessions', 'indexers']:
                    try:
                        removetree(os.path.join(sickrage.srConfig.CACHE_DIR, cleanupDir))
                    except Exception as e:
                        sickrage.srLogger.warning(
                            "Restore: Unable to remove the cache/{} directory: {1}".format(cleanupDir, e))

        if sickrage.srConfig.WEB_PORT < 21 or sickrage.srConfig.WEB_PORT > 65535:
            sickrage.srConfig.WEB_PORT = 8081

        if not sickrage.srConfig.WEB_COOKIE_SECRET:
            sickrage.srConfig.WEB_COOKIE_SECRET = generateCookieSecret()

        # attempt to help prevent users from breaking links by using a bad url
        if not sickrage.srConfig.ANON_REDIRECT.endswith('?'):
            sickrage.srConfig.ANON_REDIRECT = ''

        if not re.match(r'\d+\|[^|]+(?:\|[^|]+)*', sickrage.srConfig.ROOT_DIRS):
            sickrage.srConfig.ROOT_DIRS = ''

        sickrage.srConfig.NAMING_FORCE_FOLDERS = check_force_season_folders()
        if sickrage.srConfig.NZB_METHOD not in ('blackhole', 'sabnzbd', 'nzbget'):
            sickrage.srConfig.NZB_METHOD = 'blackhole'

        if not sickrage.srConfig.PROVIDER_ORDER:
            sickrage.srConfig.PROVIDER_ORDER = self.providersDict[GenericProvider.NZB].keys() + \
                                         self.providersDict[GenericProvider.TORRENT].keys()

        if sickrage.srConfig.TORRENT_METHOD not in (
                'blackhole', 'utorrent', 'transmission', 'deluge', 'deluged', 'download_station', 'rtorrent',
                'qbittorrent', 'mlnet'):
            sickrage.srConfig.TORRENT_METHOD = 'blackhole'

        if sickrage.srConfig.PROPER_SEARCHER_INTERVAL not in ('15m', '45m', '90m', '4h', 'daily'):
            sickrage.srConfig.PROPER_SEARCHER_INTERVAL = 'daily'

        if sickrage.srConfig.AUTOPOSTPROCESSOR_FREQ < sickrage.srConfig.MIN_AUTOPOSTPROCESSOR_FREQ:
            sickrage.srConfig.AUTOPOSTPROCESSOR_FREQ = sickrage.srConfig.MIN_AUTOPOSTPROCESSOR_FREQ

        if sickrage.srConfig.NAMECACHE_FREQ < sickrage.srConfig.MIN_NAMECACHE_FREQ:
            sickrage.srConfig.NAMECACHE_FREQ = sickrage.srConfig.MIN_NAMECACHE_FREQ

        if sickrage.srConfig.DAILY_SEARCHER_FREQ < sickrage.srConfig.MIN_DAILY_SEARCHER_FREQ:
            sickrage.srConfig.DAILY_SEARCHER_FREQ = sickrage.srConfig.MIN_DAILY_SEARCHER_FREQ

        sickrage.srConfig.MIN_BACKLOG_SEARCHER_FREQ = get_backlog_cycle_time()
        if sickrage.srConfig.BACKLOG_SEARCHER_FREQ < sickrage.srConfig.MIN_BACKLOG_SEARCHER_FREQ:
            sickrage.srConfig.BACKLOG_SEARCHER_FREQ = sickrage.srConfig.MIN_BACKLOG_SEARCHER_FREQ

        if sickrage.srConfig.VERSION_UPDATER_FREQ < sickrage.srConfig.MIN_VERSION_UPDATER_FREQ:
            sickrage.srConfig.VERSION_UPDATER_FREQ = sickrage.srConfig.MIN_VERSION_UPDATER_FREQ

        if sickrage.srConfig.SHOWUPDATE_HOUR > 23:
            sickrage.srConfig.SHOWUPDATE_HOUR = 0
        elif sickrage.srConfig.SHOWUPDATE_HOUR < 0:
            sickrage.srConfig.SHOWUPDATE_HOUR = 0

        if sickrage.srConfig.SUBTITLE_SEARCHER_FREQ < sickrage.srConfig.MIN_SUBTITLE_SEARCHER_FREQ:
            sickrage.srConfig.SUBTITLE_SEARCHER_FREQ = sickrage.srConfig.MIN_SUBTITLE_SEARCHER_FREQ

        sickrage.srConfig.NEWS_LATEST = sickrage.srConfig.NEWS_LAST_READ

        if sickrage.srConfig.SUBTITLES_LANGUAGES[0] == '':
            sickrage.srConfig.SUBTITLES_LANGUAGES = []

        sickrage.srConfig.TIME_PRESET = sickrage.srConfig.TIME_PRESET_W_SECONDS.replace(":%S", "")

        # initialize metadata_providers
        self.metadataProviderDict = get_metadata_generator_dict()
        for cur_metadata_tuple in [(sickrage.srConfig.METADATA_KODI, kodi),
                                   (sickrage.srConfig.METADATA_KODI_12PLUS, kodi_12plus),
                                   (sickrage.srConfig.METADATA_MEDIABROWSER, mediabrowser),
                                   (sickrage.srConfig.METADATA_PS3, ps3),
                                   (sickrage.srConfig.METADATA_WDTV, wdtv),
                                   (sickrage.srConfig.METADATA_TIVO, tivo),
                                   (sickrage.srConfig.METADATA_MEDE8ER, mede8er)]:
            (cur_metadata_config, cur_metadata_class) = cur_metadata_tuple
            tmp_provider = cur_metadata_class.metadata_class()
            tmp_provider.set_config(cur_metadata_config)

            self.metadataProviderDict[tmp_provider.name] = tmp_provider

        # add version checker job to scheduler
        self.SCHEDULER.add_job(
            self.VERSIONUPDATER.run,
            srIntervalTrigger(
                **{'hours': sickrage.srConfig.VERSION_UPDATER_FREQ, 'min': sickrage.srConfig.MIN_VERSION_UPDATER_FREQ}),
            name="VERSIONUPDATER",
            id="VERSIONUPDATER",
            replace_existing=True
        )

        # add network timezones updater job to scheduler
        self.SCHEDULER.add_job(
            update_network_dict,
            srIntervalTrigger(**{'days': 1}),
            name="TZUPDATER",
            id="TZUPDATER",
            replace_existing=True
        )

        # add namecache updater job to scheduler
        self.SCHEDULER.add_job(
            self.NAMECACHE.run,
            srIntervalTrigger(**{'minutes': sickrage.srConfig.NAMECACHE_FREQ, 'min': sickrage.srConfig.MIN_NAMECACHE_FREQ}),
            name="NAMECACHE",
            id="NAMECACHE",
            replace_existing=True
        )

        # add show queue job to scheduler
        self.SCHEDULER.add_job(
            self.SHOWQUEUE.run,
            srIntervalTrigger(**{'seconds': 3}),
            name="SHOWQUEUE",
            id="SHOWQUEUE",
            replace_existing=True
        )

        # add search queue job to scheduler
        self.SCHEDULER.add_job(
            self.SEARCHQUEUE.run,
            srIntervalTrigger(**{'seconds': 1}),
            name="SEARCHQUEUE",
            id="SEARCHQUEUE",
            replace_existing=True
        )

        # add show updater job to scheduler
        self.SCHEDULER.add_job(
            self.SHOWUPDATER.run,
            srIntervalTrigger(
                **{'hours': 1,
                   'start_date': datetime.now().replace(hour=sickrage.srConfig.SHOWUPDATE_HOUR)}),
            name="SHOWUPDATER",
            id="SHOWUPDATER",
            replace_existing=True
        )

        # add daily search job to scheduler
        self.SCHEDULER.add_job(
            self.DAILYSEARCHER.run,
            srIntervalTrigger(
                **{'minutes': sickrage.srConfig.DAILY_SEARCHER_FREQ, 'min': sickrage.srConfig.MIN_DAILY_SEARCHER_FREQ}),
            name="DAILYSEARCHER",
            id="DAILYSEARCHER",
            replace_existing=True
        )

        # add backlog search job to scheduler
        self.SCHEDULER.add_job(
            self.BACKLOGSEARCHER.run,
            srIntervalTrigger(
                **{'minutes': sickrage.srConfig.BACKLOG_SEARCHER_FREQ,
                   'min': sickrage.srConfig.MIN_BACKLOG_SEARCHER_FREQ}),
            name="BACKLOG",
            id="BACKLOG",
            replace_existing=True
        )

        # add auto-postprocessing job to scheduler
        job = self.SCHEDULER.add_job(
            self.AUTOPOSTPROCESSOR.run,
            srIntervalTrigger(**{'minutes': sickrage.srConfig.AUTOPOSTPROCESSOR_FREQ,
                                 'min': sickrage.srConfig.MIN_AUTOPOSTPROCESSOR_FREQ}),
            name="POSTPROCESSOR",
            id="POSTPROCESSOR",
            replace_existing=True
        )
        (job.pause, job.resume)[sickrage.srConfig.PROCESS_AUTOMATICALLY]()

        # add find proper job to scheduler
        job = self.SCHEDULER.add_job(
            self.PROPERSEARCHER.run,
            srIntervalTrigger(**{
                'minutes': {'15m': 15, '45m': 45, '90m': 90, '4h': 4 * 60, 'daily': 24 * 60}[
                    sickrage.srConfig.PROPER_SEARCHER_INTERVAL]}),
            name="PROPERSEARCHER",
            id="PROPERSEARCHER",
            replace_existing=True
        )
        (job.pause, job.resume)[sickrage.srConfig.DOWNLOAD_PROPERS]()

        # add trakt.tv checker job to scheduler
        job = self.SCHEDULER.add_job(
            self.TRAKTSEARCHER.run,
            srIntervalTrigger(**{'hours': 1}),
            name="TRAKTSEARCHER",
            id="TRAKTSEARCHER",
            replace_existing=True,
        )
        (job.pause, job.resume)[sickrage.srConfig.USE_TRAKT]()

        # add subtitles finder job to scheduler
        job = self.SCHEDULER.add_job(
            self.SUBTITLESEARCHER.run,
            srIntervalTrigger(**{'hours': sickrage.srConfig.SUBTITLE_SEARCHER_FREQ}),
            name="SUBTITLESEARCHER",
            id="SUBTITLESEARCHER",
            replace_existing=True
        )
        (job.pause, job.resume)[sickrage.srConfig.USE_SUBTITLES]()

        # add scheduler callback
        self.SCHEDULER.start()
Ejemplo n.º 6
0
def main():
    global srCore, srConfig, srLogger, DATA_DIR

    if sys.version_info < (2, 7):
        print("Sorry, SiCKRAGE requires Python 2.7+")
        sys.exit(1)

    # add sickrage module to python system path
    path = os.path.dirname(os.path.realpath(__file__))
    if path not in sys.path:
        sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))

    try:
        opts, _ = getopt.getopt(sys.argv[1:], "hqdp::", [
            'help', 'dev', 'quiet', 'nolaunch', 'daemon', 'pidfile=', 'port=',
            'datadir=', 'config=', 'noresize', 'install-optional', 'ssl',
            'debug'
        ])
    except getopt.GetoptError:
        sys.exit(help_message(PROG_DIR))

    # defaults
    PIDFILE = os.path.abspath(os.path.join(DATA_DIR, 'sickrage.pid'))
    DEVELOPER = False
    DAEMONIZE = False
    WEB_PORT = None
    INSTALL_OPTIONAL = False
    WEB_NOLAUNCH = False
    SSL = False
    DEBUG = False
    CONFIG_FILE = "config.ini"
    CONSOLE = not hasattr(sys, "frozen")

    for o, a in opts:
        # help message
        if o in ('-h', '--help'):
            sys.exit(help_message(PROG_DIR))

        # For now we'll just silence the logging
        if o in ('-q', '--quiet'):
            CONSOLE = False

        # developer mode
        if o in ('--dev', ):
            print("!!! DEVELOPER MODE ENABLED !!!")
            DEVELOPER = 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', ):
            WEB_NOLAUNCH = True

        # Override default/configured port
        if o in ('-p', '--port'):
            try:
                WEB_PORT = 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'):
            DAEMONIZE = (False, True)[not sys.platform == 'win32']
            WEB_NOLAUNCH = True
            CONSOLE = False

        # Write a pidfile if requested
        if o in ('--pidfile', ):
            PIDFILE = str(a)

            # If the pidfile already exists, sickrage may still be running, so exit
            if os.path.exists(PIDFILE):
                sys.exit("PID file: " + PIDFILE + " already exists. Exiting.")

        # Specify folder to use as the data dir
        if o in ('--datadir', ):
            DATA_DIR = os.path.abspath(os.path.expanduser(a))

        # Specify folder to load the config file from
        if o in ('--config', ):
            CONFIG_FILE = os.path.abspath(os.path.expanduser(a))

        # Prevent resizing of the banner/posters even if PIL is installed
        if o in ('--noresize', ):
            NO_RESIZE = True

        # Install optional packages from requirements folder
        if o in ('--install-optional', ):
            INSTALL_OPTIONAL = True

        # Install ssl packages from requirements folder
        if o in ('--ssl', ):
            SSL = True

        # Install ssl packages from requirements folder
        if o in ('--debug', ):
            print("!!! DEBUGGING MODE ENABLED !!!")
            DEBUG = True

    try:
        # daemonize sickrage ?
        if DAEMONIZE:
            daemonize(PIDFILE)

        import core
        from core.helpers import makeDir

        # Make sure that we can create the data dir
        if not os.access(DATA_DIR, os.F_OK):
            try:
                os.makedirs(DATA_DIR, 0o744)
            except os.error:
                raise SystemExit("Unable to create data directory '" +
                                 DATA_DIR + "'")

        # Make sure we can write to the data dir
        if not os.access(DATA_DIR, os.W_OK):
            raise SystemExit("Data directory must be writeable '" + DATA_DIR +
                             "'")

        print("Starting SiCKRAGE ...")

        # init logger
        srLogger = core.srLogger()

        # init core
        srCore = core.srCore()

        # init config
        srConfig = core.srConfig(CONFIG_FILE)

        # load config
        srConfig.load_config()

        # start logger
        srLogger.logFile = os.path.abspath(
            os.path.join(DATA_DIR, srConfig.LOG_DIR, srConfig.LOG_FILE))
        srLogger.logSize = srConfig.LOG_SIZE
        srLogger.logNr = srConfig.LOG_NR
        srLogger.consoleLogging = CONSOLE
        srLogger.debugLogging = DEBUG or srConfig.DEBUG
        srLogger.fileLogging = makeDir(
            os.path.abspath(os.path.join(DATA_DIR, srConfig.LOG_DIR)))
        srLogger.start()

        # start core
        srCore.start()

        # start web-ui
        srCore.WEBSERVER.open_browser = (True, False)[WEB_NOLAUNCH]
        srCore.WEBSERVER.port = (srConfig.WEB_PORT,
                                 WEB_PORT)[WEB_PORT is not None]
        srCore.WEBSERVER.start()
    except ImportError:
        # install pip package manager
        install_pip()

        # install required packages
        install_requirements()

        # restart sickrage silently
        os.execl(sys.executable, sys.executable, *sys.argv)
    except KeyboardInterrupt:
        pass
    except Exception:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_tb(exc_traceback)
        traceback.print_exception(exc_type, exc_value, exc_traceback)
        sys.exit(1)
    sys.exit(0)
Ejemplo n.º 7
0
def main():
    global srCore, srConfig, srLogger

    if sys.version_info < (2, 7):
        print("Sorry, SiCKRAGE requires Python 2.7+")
        sys.exit(1)

    print("Starting SiCKRAGE ...")

    # add sickrage module to python system path
    path = os.path.dirname(os.path.realpath(__file__))
    if path not in sys.path:
        sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))

    # set thread name
    threading.currentThread().setName('MAIN')

    PROG_DIR = os.path.abspath(os.path.dirname(__file__))
    DATA_DIR = os.path.join(os.path.expanduser("~"), '.sickrage')
    CONFIG_FILE = "config.ini"

    try:
        opts, _ = getopt.getopt(
            sys.argv[1:], "hqdp::",
            ['help',
             'dev',
             'quiet',
             'nolaunch',
             'daemon',
             'pidfile=',
             'port=',
             'datadir=',
             'config=',
             'noresize',
             'install-optional',
             'ssl',
             'debug']
        )
    except getopt.GetoptError:
        sys.exit(help_message(PROG_DIR))

    # defaults
    PIDFILE = os.path.abspath(os.path.join(DATA_DIR, 'sickrage.pid'))
    DEVELOPER = False
    DAEMONIZE = False
    WEB_PORT = 8081
    INSTALL_OPTIONAL = False
    WEB_NOLAUNCH = False
    SSL = False
    DEBUG = False

    CONSOLE = not hasattr(sys, "frozen")

    for o, a in opts:
        # help message
        if o in ('-h', '--help'):
            sys.exit(help_message(PROG_DIR))

        # For now we'll just silence the logging
        if o in ('-q', '--quiet'):
            CONSOLE = False

        # developer mode
        if o in ('--dev',):
            print("!!! DEVELOPER MODE ENABLED !!!")
            DEVELOPER = 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',):
            WEB_NOLAUNCH = True

        # Override default/configured port
        if o in ('-p', '--port'):
            try:
                WEB_PORT = 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'):
            DAEMONIZE = (False, True)[not sys.platform == 'win32']
            WEB_NOLAUNCH = True
            CONSOLE = False

        # Write a pidfile if requested
        if o in ('--pidfile',):
            PIDFILE = str(a)

            # If the pidfile already exists, sickrage may still be running, so exit
            if os.path.exists(PIDFILE):
                sys.exit("PID file: " + PIDFILE + " already exists. Exiting.")

        # Specify folder to use as the data dir
        if o in ('--datadir',):
            DATA_DIR = os.path.abspath(a)

        # Specify folder to load the config file from
        if o in ('--config',):
            CONFIG_FILE = os.path.abspath(a)

        # Prevent resizing of the banner/posters even if PIL is installed
        if o in ('--noresize',):
            NO_RESIZE = True

        # Install optional packages from requirements folder
        if o in ('--install-optional',):
            INSTALL_OPTIONAL = True

        # Install ssl packages from requirements folder
        if o in ('--ssl',):
            SSL = True

        # Install ssl packages from requirements folder
        if o in ('--debug',):
            print("!!! DEBUGGING MODE ENABLED !!!")
            DEBUG = True

    try:
        # daemonize sickrage ?
        if DAEMONIZE:
            daemonize(PIDFILE)

        # install/upgrade pip and ssl contexts for required/optional imports
        if not DEVELOPER:
            REQS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'requirements'))

            # install pip package manager
            install_pip(path=REQS_DIR, user=root_check())

            # install required packages
            install_requirements(path=REQS_DIR, optional=INSTALL_OPTIONAL, ssl=SSL, user=root_check())

        import core
        from core.helpers import makeDir

        # init logger
        srLogger = core.srLogger()

        # init core
        srCore = core.srCore(PROG_DIR, DATA_DIR)

        # init config
        srConfig = core.srConfig(CONFIG_FILE)

        # load config
        srConfig.load_config()

        # start logger
        srLogger.logFile = os.path.abspath(os.path.join(srCore.DATA_DIR, srConfig.LOG_DIR, srConfig.LOG_FILE))
        srLogger.logSize = srConfig.LOG_SIZE
        srLogger.logNr = srConfig.LOG_NR
        srLogger.consoleLogging = CONSOLE
        srLogger.debugLogging = DEBUG or srConfig.DEBUG
        srLogger.fileLogging = makeDir(os.path.abspath(os.path.join(srCore.DATA_DIR, srConfig.LOG_DIR)))
        srLogger.start()

        # start core
        srCore.start()

        # start web-ui
        srCore.WEBSERVER.open_browser = (True, False)[WEB_NOLAUNCH]
        srCore.WEBSERVER.port = (srConfig.WEB_PORT, WEB_PORT)[WEB_PORT != srConfig.WEB_PORT]
        srCore.WEBSERVER.start()
    except KeyboardInterrupt:
        pass
    except Exception:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_tb(exc_traceback)
        traceback.print_exception(exc_type, exc_value, exc_traceback)
        sys.exit(1)
    sys.exit(0)
Ejemplo n.º 8
0
def main():
    global srCore, srConfig, srLogger, DATA_DIR

    if sys.version_info < (2, 7):
        print("Sorry, SiCKRAGE requires Python 2.7+")
        sys.exit(1)

    # add sickrage module to python system path
    path = os.path.dirname(os.path.realpath(__file__))
    if path not in sys.path:
        sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))

    # set thread name
    threading.currentThread().setName("MAIN")

    try:
        opts, _ = getopt.getopt(
            sys.argv[1:],
            "hqdp::",
            [
                "help",
                "dev",
                "quiet",
                "nolaunch",
                "daemon",
                "pidfile=",
                "port=",
                "datadir=",
                "config=",
                "noresize",
                "install-optional",
                "ssl",
                "debug",
            ],
        )
    except getopt.GetoptError:
        sys.exit(help_message(PROG_DIR))

    # defaults
    PIDFILE = os.path.abspath(os.path.join(DATA_DIR, "sickrage.pid"))
    DEVELOPER = False
    DAEMONIZE = False
    WEB_PORT = None
    INSTALL_OPTIONAL = False
    WEB_NOLAUNCH = False
    SSL = False
    DEBUG = False
    CONFIG_FILE = "config.ini"
    CONSOLE = not hasattr(sys, "frozen")

    for o, a in opts:
        # help message
        if o in ("-h", "--help"):
            sys.exit(help_message(PROG_DIR))

        # For now we'll just silence the logging
        if o in ("-q", "--quiet"):
            CONSOLE = False

        # developer mode
        if o in ("--dev",):
            print("!!! DEVELOPER MODE ENABLED !!!")
            DEVELOPER = 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",):
            WEB_NOLAUNCH = True

        # Override default/configured port
        if o in ("-p", "--port"):
            try:
                WEB_PORT = 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"):
            DAEMONIZE = (False, True)[not sys.platform == "win32"]
            WEB_NOLAUNCH = True
            CONSOLE = False

        # Write a pidfile if requested
        if o in ("--pidfile",):
            PIDFILE = str(a)

            # If the pidfile already exists, sickrage may still be running, so exit
            if os.path.exists(PIDFILE):
                sys.exit("PID file: " + PIDFILE + " already exists. Exiting.")

        # Specify folder to use as the data dir
        if o in ("--datadir",):
            DATA_DIR = os.path.abspath(a)

        # Specify folder to load the config file from
        if o in ("--config",):
            CONFIG_FILE = os.path.abspath(a)

        # Prevent resizing of the banner/posters even if PIL is installed
        if o in ("--noresize",):
            NO_RESIZE = True

        # Install optional packages from requirements folder
        if o in ("--install-optional",):
            INSTALL_OPTIONAL = True

        # Install ssl packages from requirements folder
        if o in ("--ssl",):
            SSL = True

        # Install ssl packages from requirements folder
        if o in ("--debug",):
            print("!!! DEBUGGING MODE ENABLED !!!")
            DEBUG = True

    try:
        print("Starting SiCKRAGE ...")

        # Make sure that we can create the data dir
        if not os.access(DATA_DIR, os.F_OK):
            try:
                os.makedirs(DATA_DIR, 0o744)
            except os.error:
                raise SystemExit("Unable to create data directory '" + DATA_DIR + "'")

        # Make sure we can write to the data dir
        if not os.access(DATA_DIR, os.W_OK):
            raise SystemExit("Data directory must be writeable '" + DATA_DIR + "'")

        # daemonize sickrage ?
        if DAEMONIZE:
            daemonize(PIDFILE)

        # install/upgrade pip and ssl contexts for required/optional imports
        if not DEVELOPER:
            # install pip package manager
            install_pip()

            # install required packages
            install_requirements(optional=INSTALL_OPTIONAL, ssl=SSL)

        import core
        from core.helpers import makeDir

        # init logger
        srLogger = core.srLogger()

        # init core
        srCore = core.srCore()

        # init config
        srConfig = core.srConfig(CONFIG_FILE)

        # load config
        srConfig.load_config()

        # start logger
        srLogger.logFile = os.path.abspath(os.path.join(DATA_DIR, srConfig.LOG_DIR, srConfig.LOG_FILE))
        srLogger.logSize = srConfig.LOG_SIZE
        srLogger.logNr = srConfig.LOG_NR
        srLogger.consoleLogging = CONSOLE
        srLogger.debugLogging = DEBUG or srConfig.DEBUG
        srLogger.fileLogging = makeDir(os.path.abspath(os.path.join(DATA_DIR, srConfig.LOG_DIR)))
        srLogger.start()

        # start core
        srCore.start()

        # start web-ui
        srCore.WEBSERVER.open_browser = (True, False)[WEB_NOLAUNCH]
        srCore.WEBSERVER.port = (srConfig.WEB_PORT, WEB_PORT)[WEB_PORT is not None]
        srCore.WEBSERVER.start()
    except KeyboardInterrupt:
        pass
    except Exception:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_tb(exc_traceback)
        traceback.print_exception(exc_type, exc_value, exc_traceback)
        sys.exit(1)
    sys.exit(0)