Esempio n. 1
0
    def conf_path(self, trans=False):
        if trans:
            gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
            translation = gettext.translation("setup", join(self.path, "locale"),
                languages=[self.config["general"]["language"], "en"], fallback=True)
            translation.install(True)

        print _("Setting new config path, current configuration will not be transfered!")
        path = self.ask(_("CONFIG PATH"), abspath(""))
        try:
            path = join(pypath, path)
            if not exists(path):
                makedirs(path)
            f = open(join(pypath, "module", "config", "configdir"), "wb")
            f.write(path)
            f.close()
            print
            print
            print _("pyLoad config path changed, setup will now close!")
            print
            print
            raw_input(_("Press Enter to exit."))
            sys.exit()
        except Exception, e:
            print _("Setting config path failed: %s") % str(e)
Esempio n. 2
0
    def init(self, first=False):
        """
            set main things up
        """
        self.parser = XMLParser(
            join(self.configdir, "gui.xml"),
            join(self.path, "module", "config", "gui_default.xml"))
        lang = self.parser.xml.elementsByTagName("language").item(
            0).toElement().text()
        if not lang:
            parser = XMLParser(
                join(self.path, "module", "config", "gui_default.xml"))
            lang = parser.xml.elementsByTagName("language").item(
                0).toElement().text()

        gettext.setpaths(
            [join(os.sep, "usr", "share", "pyload", "locale"), None])
        translation = gettext.translation(
            "pyLoadGui",
            join(pypath, "locale"),
            languages=[str(lang), "en"],
            fallback=True,
        )

        install_translation(translation)

        self.connector = Connector()
        self.mainWindow = MainWindow(self.connector)
        self.connWindow = ConnectionManager()
        self.mainloop = self.Loop(self)
        self.connectSignals()

        self.checkClipboard = False
        default = self.refreshConnections()
        self.connData = None
        self.captchaProcessing = False
        self.serverStatus = {"freespace": 0}

        self.core = None  # pyLoadCore if started
        self.connectionLost = False

        if True:  # when used if first, minimizing not working correctly..
            self.tray = TrayIcon()
            self.tray.show()
            self.notification = Notification(self.tray)
            self.connect(self, SIGNAL("showMessage"),
                         self.notification.showMessage)
            self.connect(self.tray.exitAction, SIGNAL("triggered()"),
                         self.slotQuit)
            self.connect(self.tray.showAction, SIGNAL("toggled(bool)"),
                         self.mainWindow.setVisible)
            self.connect(self.mainWindow, SIGNAL("hidden"),
                         self.tray.mainWindowHidden)

        if not first:
            self.connWindow.show()
        else:
            self.connWindow.edit.setData(default)
            data = self.connWindow.edit.getData()
            self.slotConnect(data)
Esempio n. 3
0
    def conf_path(self, trans=False):
        if trans:
            gettext.setpaths(
                [join(os.sep, "usr", "share", "pyload", "locale"), None])
            translation = gettext.translation(
                "setup",
                join(self.path, "locale"),
                languages=[self.config["general"]["language"], "en"],
                fallback=True)
            translation.install(True)

        print _(
            "Setting new configpath, current configuration will not be transfered!"
        )
        path = self.ask(_("Configpath"), abspath(""))
        try:
            path = join(pypath, path)
            if not exists(path):
                makedirs(path)
            f = open(join(pypath, "module", "config", "configdir"), "wb")
            f.write(path)
            f.close()
            print _(
                "Configpath changed, setup will now close, please restart to go on."
            )
            print _("Press Enter to exit.")
            raw_input()
            exit()
        except Exception, e:
            print _("Setting config path failed: %s") % str(e)
Esempio n. 4
0
    def ask_lang(self):
        langs = self.config.getMetaData("general", "language").type.split(";")
        self.lang = self.ask(u"Choose your Language / Wähle deine Sprache", "en", langs)
        gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
        translation = gettext.translation("setup", join(self.path, "locale"), languages=[self.lang, "en"], fallback=True)
        translation.install(True)

        #l10n Input shorthand for yes
        self.yes = _("y")
        #l10n Input shorthand for no
        self.no = _("n")
Esempio n. 5
0
    def set_user(self):
        gettext.setpaths(
            [os.path.join(os.sep, "usr", "share", "pyload", "locale"), None])
        translation = gettext.translation(
            "setup",
            os.path.join(self.path, "locale"),
            languages=[self.config["general"]["language"], "en"],
            fallback=True,
        )
        install_translation(translation)

        from module.database import DatabaseBackend

        db = DatabaseBackend(None)
        db.setup()

        noaction = True
        try:
            while True:
                print(_("Select action"))
                print(_("1 - Create/Edit user"))
                print(_("2 - List users"))
                print(_("3 - Remove user"))
                print(_("4 - Quit"))
                action = input("[1]/2/3/4: ")
                if not action in ("1", "2", "3", "4"):
                    continue
                elif action == "1":
                    print("")
                    username = self.ask(_("Username"), "User")
                    password = self.ask("", "", password=True)
                    db.addUser(username, password)
                    noaction = False
                elif action == "2":
                    print("")
                    print(_("Users"))
                    print("-----")
                    users = db.listUsers()
                    noaction = False
                    for user in users:
                        print(user)
                    print("-----")
                    print("")
                elif action == "3":
                    print("")
                    username = self.ask(_("Username"), "")
                    if username:
                        db.removeUser(username)
                        noaction = False
                elif action == "4":
                    break
        finally:
            if not noaction:
                db.shutdown()
Esempio n. 6
0
    def set_user(self):
        gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
        translation = gettext.translation("setup", join(self.path, "locale"),
            languages=[self.config["general"]["language"], "en"], fallback=True)
        translation.install(True)

        from module.database import DatabaseBackend

        db = DatabaseBackend(None)
        db.setup()

        noaction = True
        try:
            while True:
                print _("Select action")
                print _("1 - Create/Edit user")
                print _("2 - List users")
                print _("3 - Remove user")
                print _("4 - Quit")
                action = raw_input("[1]/2/3/4: ")
                if not action in ("1", "2", "3", "4"):
                    continue
                elif action == "1":
                    print ""
                    username = self.ask(_("Username"), "User")
                    password = self.ask("", "", password=True)
                    db.addUser(username, password)
                    noaction = False
                elif action == "2":
                    print ""
                    print _("Users")
                    print "-----"
                    users = db.getAllUserData()
                    noaction = False
                    for user in users.itervalues():
                        print user.name
                    print "-----"
                    print ""
                elif action == "3":
                    print ""
                    username = self.ask(_("Username"), "")
                    if username:
                        db.removeUser(username)
                        noaction = False
                elif action == "4":
                    db.syncSave()
                    break
        finally:
            if not noaction:
                db.shutdown()
Esempio n. 7
0
    def init(self, first=False):
        """
            set main things up
        """
        self.parser = XMLParser(join(self.configdir, "gui.xml"), join(self.path, "module", "config", "gui_default.xml"))
        lang = self.parser.xml.elementsByTagName("language").item(0).toElement().text()
        if not lang:
            parser = XMLParser(join(self.path, "module", "config", "gui_default.xml"))
            lang = parser.xml.elementsByTagName("language").item(0).toElement().text()

        gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
        translation = gettext.translation("pyLoadGui", join(pypath, "locale"), languages=[str(lang), "en"], fallback=True)
        try:
            translation.install(unicode=(True if sys.stdout.encoding.lower().startswith("utf") else False))
        except:
            translation.install(unicode=False)


        self.connector = Connector()
        self.mainWindow = MainWindow(self.connector)
        self.connWindow = ConnectionManager()
        self.mainloop = self.Loop(self)
        self.connectSignals()

        self.checkClipboard = False
        default = self.refreshConnections()
        self.connData = None
        self.captchaProcessing = False
        self.serverStatus = {"freespace":0}

        self.core = None # pyLoadCore if started
        self.connectionLost = False

        if True: # when used if first, minimizing not working correctly..
            self.tray = TrayIcon()
            self.tray.show()
            self.notification = Notification(self.tray)
            self.connect(self, SIGNAL("showMessage"), self.notification.showMessage)
            self.connect(self.tray.exitAction, SIGNAL("triggered()"), self.slotQuit)
            self.connect(self.tray.showAction, SIGNAL("toggled(bool)"), self.mainWindow.setVisible)
            self.connect(self.mainWindow, SIGNAL("hidden"), self.tray.mainWindowHidden)

        if not first:
            self.connWindow.show()
        else:
            self.connWindow.edit.setData(default)
            data = self.connWindow.edit.getData()
            self.slotConnect(data)
Esempio n. 8
0
env = Environment(loader=loader, extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape'], trim_blocks=True, auto_reload=True,
    bytecode_cache=bcc)

# Filter

env.filters["type"] = lambda x: str(type(x))
env.filters["formatsize"] = format_size
env.filters["getitem"] = lambda x, y: x.__getitem__(y)
if not PREFIX:
    env.filters["url"] = lambda x: x
else:
    env.filters["url"] = lambda x: PREFIX + x if x.startswith("/") else x

# Locale

gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
translation = gettext.translation("django", join(PYLOAD_DIR, "locale"),
    languages=[config.get("general", "language"), "en"],fallback=True)
translation.install(True)
env.install_gettext_translations(translation)

# Middlewares

from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': False,
    'session.data_dir': './tmp',
    'session.auto': False
}
Esempio n. 9
0
def main():
    config = {"addr": "127.0.0.1", "port": "7227", "language": "en"}
    try:
        config["language"] = os.environ["LANG"][0:2]
    except:
        pass

    if (not exists(join(pypath, "locale",
                        config["language"]))) or config["language"] == "":
        config["language"] = "en"

    configFile = ConfigParser.ConfigParser()
    configFile.read(join(homedir, ".pyload-cli"))

    if configFile.has_section("cli"):
        for opt in configFile.items("cli"):
            config[opt[0]] = opt[1]

    gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
    translation = gettext.translation("Cli",
                                      join(pypath, "locale"),
                                      languages=[config["language"], "en"],
                                      fallback=True)
    translation.install(unicode=True)

    interactive = False
    command = None
    username = ""
    password = ""

    shortOptions = 'iu:p:a:hcl:'
    longOptions = [
        'interactive', "username="******"pw=", "address=", "port=", "help",
        "commands", "language="
    ]

    try:
        opts, extraparams = getopt(sys.argv[1:], shortOptions, longOptions)
        for option, params in opts:
            if option in ("-i", "--interactive"):
                interactive = True
            elif option in ("-u", "--username"):
                username = params
            elif option in ("-a", "--address"):
                config["addr"] = params
            elif option in ("-p", "--port"):
                config["port"] = params
            elif option in ("-l", "--language"):
                config["language"] = params
                gettext.setpaths(
                    [join(os.sep, "usr", "share", "pyload", "locale"), None])
                translation = gettext.translation(
                    "Cli",
                    join(pypath, "locale"),
                    languages=[config["language"], "en"],
                    fallback=True)
                translation.install(unicode=True)
            elif option in ("-h", "--help"):
                print_help(config)
                exit()
            elif option in ("--pw"):
                password = params
            elif option in ("-c", "--comands"):
                print_commands()
                exit()

    except GetoptError:
        print 'Unknown Argument(s) "%s"' % " ".join(sys.argv[1:])
        print_help(config)
        exit()

    if len(extraparams) >= 1:
        command = extraparams

    client = False

    if interactive:
        try:
            client = ThriftClient(config["addr"], int(config["port"]),
                                  username, password)
        except WrongLogin:
            pass
        except NoSSL:
            print _("You need py-openssl to connect to this pyLoad Core.")
            exit()
        except NoConnection:
            config["addr"] = False
            config["port"] = False

        if not client:
            if not config["addr"]: config["addr"] = raw_input(_("Address: "))
            if not config["port"]: config["port"] = raw_input(_("Port: "))
            if not username: username = raw_input(_("Username: "******"Password: "******"addr"], int(config["port"]),
                                      username, password)
            except WrongLogin:
                print _("Login data is wrong.")
            except NoConnection:
                print _(
                    "Could not establish connection to %(addr)s:%(port)s." % {
                        "addr": config["addr"],
                        "port": config["port"]
                    })

    else:
        try:
            client = ThriftClient(config["addr"], int(config["port"]),
                                  username, password)
        except WrongLogin:
            print _("Login data is wrong.")
        except NoConnection:
            print _("Could not establish connection to %(addr)s:%(port)s." % {
                "addr": config["addr"],
                "port": config["port"]
            })
        except NoSSL:
            print _("You need py-openssl to connect to this pyLoad core.")

    if interactive and command:
        print _("Interactive mode ignored since you passed some commands.")

    if client:
        writeConfig(config)
        cli = Cli(client, command)
Esempio n. 10
0
def main():
    config = {"addr": "127.0.0.1", "port": "7227", "language": "en"}
    try:
        config["language"] = os.environ["LANG"][0:2]
    except:
        pass

    if (not exists(join(pypath, "locale", config["language"]))) or config["language"] == "":
        config["language"] = "en"

    configFile = ConfigParser.ConfigParser()
    configFile.read(join(homedir, ".pyloadcli"))

    if configFile.has_section("cli"):
        for opt in configFile.items("cli"):
            config[opt[0]] = opt[1]

    gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
    translation = gettext.translation("pyLoadCli", join(pypath, "locale"),
        languages=[config["language"],"en"],fallback=True)
    translation.install(unicode=True)

    interactive = False
    command = None
    username = ""
    password = ""

    shortOptions = 'iu:p:a:hcl:'
    longOptions = ['interactive', "username="******"pw=", "address=", "port=", "help", "commands", "language="]

    try:
        opts, extraparams = getopt(sys.argv[1:], shortOptions, longOptions)
        for option, params in opts:
            if option in ("-i", "--interactive"):
                interactive = True
            elif option in ("-u", "--username"):
                username = params
            elif option in ("-a", "--address"):
                config["addr"] = params
            elif option in ("-p", "--port"):
                config["port"] = params
            elif option in ("-l", "--language"):
                config["language"] = params
                gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
                translation = gettext.translation("pyLoadCli", join(pypath, "locale"),
                    languages=[config["language"],"en"],fallback=True)
                translation.install(unicode=True)
            elif option in ("-h", "--help"):
                print_help(config)
                exit()
            elif option in ("--pw"):
                password = params
            elif option in ("-c", "--comands"):
                print_commands()
                exit()

    except GetoptError:
        print 'Unknown Argument(s) "%s"' % " ".join(sys.argv[1:])
        print_help(config)
        exit()

    if len(extraparams) >= 1:
        command = extraparams

    client = False

    if interactive:
        try:
            client = ThriftClient(config["addr"], int(config["port"]), username, password)
        except WrongLogin:
            pass
        except NoSSL:
            print _("You need py-openssl to connect to this pyLoad Core.")
            exit()
        except NoConnection:
            config["addr"] = False
            config["port"] = False

        if not client:
            if not config["addr"]: config["addr"] = raw_input(_("Address: "))
            if not config["port"]: config["port"] = raw_input(_("Port: "))
            if not username: username = raw_input(_("Username: "******"Password: "******"addr"], int(config["port"]), username, password)
            except WrongLogin:
                print _("Login data is wrong.")
            except NoConnection:
                print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": config["addr"],
                                                                                  "port": config["port"]})

    else:
        try:
            client = ThriftClient(config["addr"], int(config["port"]), username, password)
        except WrongLogin:
            print _("Login data is wrong.")
        except NoConnection:
            print _("Could not establish connection to %(addr)s:%(port)s." % {"addr": config["addr"],
                                                                              "port": config["port"]})
        except NoSSL:
            print _("You need py-openssl to connect to this pyLoad core.")

    if interactive and command: print _("Interactive mode ignored since you passed some commands.")

    if client:
        writeConfig(config)
        cli = Cli(client, command)
Esempio n. 11
0
env = Environment(loader=loader, extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape'], trim_blocks=True, auto_reload=True,
    bytecode_cache=bcc)

# Filter

env.filters["type"] = lambda x: str(type(x))
env.filters["formatsize"] = format_size
env.filters["getitem"] = lambda x, y: x.__getitem__(y)
if not PREFIX:
    env.filters["url"] = lambda x: x
else:
    env.filters["url"] = lambda x: PREFIX + x if x.startswith("/") else x

# Locale

gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
translation = gettext.translation("django", join(PYLOAD_DIR, "locale"),
    languages=[config.get("general", "language"), "en"],fallback=True)
translation.install(True)
env.install_gettext_translations(translation)

# Middlewares

from beaker.middleware import SessionMiddleware

session_opts = {
    'session.type': 'file',
    'session.cookie_expires': False,
    'session.data_dir': './tmp',
    'session.auto': False
}
Esempio n. 12
0
    def start(self):
        langs = self.config.getMetaData("general",
                                        "language")["type"].split(";")
        lang = self.ask(u"Choose your Language / Wähle deine Sprache", "en",
                        langs)
        gettext.setpaths(
            [join(os.sep, "usr", "share", "pyload", "locale"), None])
        translation = gettext.translation("setup",
                                          join(self.path, "locale"),
                                          languages=[lang, "en"],
                                          fallback=True)
        translation.install(True)

        #Input shorthand for yes
        self.yes = _("y")
        #Input shorthand for no
        self.no = _("n")

        #        print ""
        #        print _("Would you like to configure pyLoad via Webinterface?")
        #        print _("You need a Browser and a connection to this PC for it.")
        #        viaweb = self.ask(_("Start initial webinterface for configuration?"), "y", bool=True)
        #        if viaweb:
        #            try:
        #                from module.web import ServerThread
        #                ServerThread.setup = self
        #                from module.web import webinterface
        #                webinterface.run_simple()
        #                return False
        #            except Exception, e:
        #                print "Setup failed with this error: ", e
        #                print "Falling back to commandline setup."

        print ""
        print _("Welcome to the pyLoad Configuration Assistent.")
        print _(
            "It will check your system and make a basic setup in order to run pyLoad."
        )
        print ""
        print _("The value in brackets [] always is the default value,")
        print _(
            "in case you don't want to change it or you are unsure what to choose, just hit enter."
        )
        print _(
            "Don't forget: You can always rerun this assistent with --setup or -s parameter, when you start pyLoadCore."
        )
        print _("If you have any problems with this assistent hit STRG-C,")
        print _(
            "to abort and don't let him start with pyLoadCore automatically anymore."
        )
        print ""
        print _("When you are ready for system check, hit enter.")
        raw_input()

        basic, ssl, captcha, gui, web, js = self.system_check()
        print ""

        if not basic:
            print _(
                "You need pycurl, sqlite and python 2.5, 2.6 or 2.7 to run pyLoad."
            )
            print _("Please correct this and re-run pyLoad.")
            print _("Setup will now close.")
            raw_input()
            return False

        raw_input(
            _("System check finished, hit enter to see your status report."))
        print ""
        print _("## Status ##")
        print ""

        avail = []
        if self.check_module("Crypto"): avail.append(_("container decrypting"))
        if ssl: avail.append(_("ssl connection"))
        if captcha: avail.append(_("automatic captcha decryption"))
        if gui: avail.append(_("GUI"))
        if web: avail.append(_("Webinterface"))
        if js: avail.append(_("extended Click'N'Load"))

        string = ""

        for av in avail:
            string += ", " + av

        print _("Features available:") + string[1:]
        print ""

        if len(avail) < 5:
            print _("Featues missing: ")
            print

            if not self.check_module("Crypto"):
                print _("no py-crypto available")
                print _(
                    "You need this if you want to decrypt container files.")
                print ""

            if not ssl:
                print _("no SSL available")
                print _(
                    "This is needed if you want to establish a secure connection to core or webinterface."
                )
                print _(
                    "If you only want to access locally to pyLoad ssl is not usefull."
                )
                print ""

            if not captcha:
                print _("no Captcha Recognition available")
                print _("Only needed for some hosters and as freeuser.")
                print ""

            if not gui:
                print _("Gui not available")
                print _("The Graphical User Interface.")
                print ""

            if not js:
                print _("no JavaScript engine found")
                print _(
                    "You will need this for some Click'N'Load links. Install Spidermonkey, ossp-js, pyv8 or rhino"
                )

            print _(
                "You can abort the setup now and fix some dependicies if you want."
            )

        con = self.ask(_("Continue with setup?"), self.yes, bool=True)

        if not con:
            return False

        print ""
        print _("Do you want to change the config path? Current is %s"
                ) % abspath("")
        print _(
            "If you use pyLoad on a server or the home partition lives on an iternal flash it may be a good idea to change it."
        )
        path = self.ask(_("Change config path?"), self.no, bool=True)
        if path:
            self.conf_path()
            #calls exit when changed

        print ""
        print _("Do you want to configure login data and basic settings?")
        print _("This is recommend for first run.")
        con = self.ask(_("Make basic setup?"), self.yes, bool=True)

        if con:
            self.conf_basic()

        if ssl:
            print ""
            print _("Do you want to configure ssl?")
            ssl = self.ask(_("Configure ssl?"), self.no, bool=True)
            if ssl:
                self.conf_ssl()

        if web:
            print ""
            print _("Do you want to configure webinterface?")
            web = self.ask(_("Configure webinterface?"), self.yes, bool=True)
            if web:
                self.conf_web()

        print ""
        print _("Setup finished successfully.")
        print _("Hit enter to exit and restart pyLoad")
        raw_input()
        return True
Esempio n. 13
0
    def start(self):
        langs = self.config.getMetaData("general", "language")["type"].split(";")
        lang = self.ask(u"Choose setup language", "en", langs)
        gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
        translation = gettext.translation("setup", join(self.path, "locale"), languages=[lang, "en"], fallback=True)
        translation.install(True)

        #Input shorthand for yes
        self.yes = _("y")
        #Input shorthand for no
        self.no = _("n")

        #        print
        #        print _("Would you like to configure pyLoad via Webinterface?")
        #        print _("You need a Browser and a connection to this PC for it.")
        #        viaweb = self.ask(_("Start initial webinterface for configuration?"), "y", bool=True)
        #        if viaweb:
        #            try:
        #                from module.threads import ServerThread
        #                ServerThread.setup = self
        #                import module.webui as webinterface
        #                webinterface.run_simple()
        #                return False
        #            except Exception, e:
        #                print "Setup failed with this error: ", e
        #                print "Falling back to commandline setup."

        print
        print
        print _("Welcome to the pyLoad Configuration Assistant.")
        print _("It will check your system and make a basic setup in order to run pyLoad.")
        print
        print _("The value in brackets [] always is the default value,")
        print _("in case you don't want to change it or you are unsure what to choose, just hit enter.")
        print _(
            "Don't forget: You can always rerun this assistant with --setup or -s parameter, when you start pyload.py .")
        print _("If you have any problems with this assistant hit STRG-C,")
        print _("to abort and don't let him start with pyload.py automatically anymore.")
        print
        print
        raw_input(_("When you are ready for system check, hit enter."))
        print
        print

        basic, ssl, captcha, web, js = self.system_check()
        print
        print

        if not basic:
            print _("You need pycurl, sqlite and python 2.5, 2.6 or 2.7 to run pyLoad.")
            print _("Please correct this and re-run pyLoad.")
            print
            print _("Setup will now close.")
            print
            print
            raw_input(_("Press Enter to exit."))
            return False

        raw_input(_("System check finished, hit enter to see your status report."))
        print
        print
        print _("## Status ##")
        print

        avail = []
        if self.check_module("Crypto"):
            avail.append(_("container decrypting"))
        if ssl:
            avail.append(_("ssl connection"))
        if captcha:
            avail.append(_("automatic captcha decryption"))
        if web:
            avail.append(_("webinterface"))
        if js:
            avail.append(_("extended Click'N'Load"))

        string = ""

        for av in avail:
            string += ", " + av

        print _("AVAILABLE FEATURES:") + string[1:]
        print

        if len(avail) < 5:
            print _("MISSING FEATURES: ")

            if not self.check_module("Crypto"):
                print _("- no py-crypto available")
                print _("You need this if you want to decrypt container files.")
                print

            if not ssl:
                print _("- no SSL available")
                print _("This is needed if you want to establish a secure connection to core or webinterface.")
                print _("If you only want to access locally to pyLoad ssl is not usefull.")
                print

            if not captcha:
                print _("- no Captcha Recognition available")
                print _("Only needed for some hosters and as freeuser.")
                print

            if not js:
                print _("- no JavaScript engine found")
                print _("You will need this for some Click'N'Load links. Install Spidermonkey, ossp-js, pyv8 or rhino")
                print

            print
            print _("You can abort the setup now and fix some dependicies if you want.")

        print
        con = self.ask(_("Continue with setup?"), self.yes, bool=True)

        if not con:
            return False

        print
        print
        print _("CURRENT CONFIG PATH: %s") % abspath("")
        print
        print _("NOTE: If you use pyLoad on a server or the home partition lives on an iternal flash it may be a good idea to change it.")
        path = self.ask(_("Do you want to change the config path?"), self.no, bool=True)
        if path:
            print
            self.conf_path()
            #calls exit when changed

        print
        print _("Do you want to configure login data and basic settings?")
        print _("This is recommend for first run.")
        con = self.ask(_("Make basic setup?"), self.yes, bool=True)

        if con:
            print
            print
            self.conf_basic()

        if ssl:
            print
            print _("Do you want to configure ssl?")
            ssl = self.ask(_("Configure ssl?"), self.no, bool=True)
            if ssl:
                print
                print
                self.conf_ssl()

        if web:
            print
            print _("Do you want to configure webinterface?")
            web = self.ask(_("Configure webinterface?"), self.yes, bool=True)
            if web:
                print
                print
                self.conf_web()

        print
        print
        print _("Setup finished successfully!")
        print
        print
        raw_input(_("Hit enter to exit and restart pyLoad."))
        return True
Esempio n. 14
0
    def start(self, rpc=True, web=True):
        """ starts the fun :D """

        self.version = CURRENT_VERSION

        if not exists("pyload.conf"):
            from module.setup import Setup

            print("This is your first start, running configuration assistent now.")
            self.config = ConfigParser()
            s = Setup(pypath, self.config)
            res = False
            try:
                res = s.start()
            except SystemExit:
                pass
            except KeyboardInterrupt:
                print("\nSetup interrupted")
            except:
                res = False
                print_exc()
                print("Setup failed")
            if not res:
                remove("pyload.conf")

            exit()

        try: signal.signal(signal.SIGQUIT, self.quit)
        except: pass

        self.config = ConfigParser()

        gettext.setpaths([join(os.sep, "usr", "share", "pyload", "locale"), None])
        translation = gettext.translation("pyLoad", self.path("locale"),
                                          languages=[self.config['general']['language'],"en"],fallback=True)
        install_translation(translation)

        self.debug = self.doDebug or self.config['general']['debug_mode']
        self.remote &= self.config['remote']['activated']

        pid = self.isAlreadyRunning()
        if pid:
            print(_("pyLoad already running with pid %s") % pid)
            exit()

        if not IS_WINDOWS and self.config["general"]["renice"]:
            os.system("renice %d %d" % (self.config["general"]["renice"], os.getpid()))

        if self.config["permission"]["change_group"]:
            if not IS_WINDOWS:
                try:
                    from grp import getgrnam

                    group = getgrnam(self.config["permission"]["group"])
                    os.setgid(group[2])
                except Exception as e:
                    print(_("Failed changing group: %s") % e)

        if self.config["permission"]["change_user"]:
            if not IS_WINDOWS:
                try:
                    from pwd import getpwnam

                    user = getpwnam(self.config["permission"]["user"])
                    os.setuid(user[2])
                except Exception as e:
                    print(_("Failed changing user: %s") % e)

        self.check_file(
            self.config['log']['log_folder'],
            _("folder for logs"),
            is_folder=True,
        )

        if self.debug:
            self.init_logger(logging.DEBUG) # logging level
        else:
            self.init_logger(logging.INFO) # logging level

        sys.excepthook = exceptHook

        self.do_kill = False
        self.do_restart = False
        self.shuttedDown = False

        self.log.info(_("Starting") + " pyLoad %s" % CURRENT_VERSION)
        self.log.info(_("Using home directory: %s") % getcwd())

        self.writePidFile()

        #@TODO refractor

        remote.activated = self.remote
        self.log.debug("Remote activated: %s" % self.remote)

        self.check_install("Crypto", _("pycrypto to decode container files"))
        #img = self.check_install("Image", _("Python Image Libary (PIL) for captcha reading"))
        #self.check_install("pycurl", _("pycurl to download any files"), True, True)
        self.check_file("tmp", _("folder for temporary files"), is_folder=True)
        #tesser = self.check_install("tesseract", _("tesseract for captcha reading"), False) if not IS_WINDOWS else True

        self.captcha = True # checks seems to fail, althoug tesseract is available

        self.check_file(
            self.config['general']['download_folder'],
            _("folder for downloads"),
            is_folder=True,
        )

        if self.config['ssl']['activated']:
            self.check_install("OpenSSL", _("OpenSSL for secure connection"))

        self.setupDB()

        if self.deleteLinks:
            self.log.info(_("All links removed"))
            self.db.purgeLinks()

        set_request_factory(RequestFactory(self))

        self.lastClientConnected = 0

        # later imported because they would trigger api import, and remote value not set correctly
        from module import Api
        from module.HookManager import HookManager
        from module.ThreadManager import ThreadManager

        if Api.activated != self.remote:
            self.log.warning("Import error: API remote status not correct.")

        self.api = Api.Api(self)

        self.scheduler = Scheduler(self)

        #hell yeah, so many important managers :D
        set_plugin_manager(PluginManager(self))
        set_pull_manager(PullManager(self))
        set_thread_manager(ThreadManager(self))
        set_account_manager(AccountManager(self))
        set_captcha_manager(CaptchaManager(self))
        # HookManager sets itself as a singleton
        HookManager(self)
        set_remote_manager(RemoteManager(self))

        thread_manager = get_thread_manager()

        self.js = JsEngine()

        self.log.info(_("Downloadtime: %s") % self.api.isTimeDownload())

        if rpc:
            get_remote_manager().startBackends()

        if web:
            self.init_webserver()

        spaceLeft = freeSpace(self.config["general"]["download_folder"])

        self.log.info(_("Free space: %s") % formatSize(spaceLeft))

        self.config.save() #save so config files gets filled

        link_file = join(pypath, "links.txt")

        if exists(link_file):
            f = open(link_file, "rb")
            if f.read().strip():
                self.api.addPackage("links.txt", [link_file], 1)
            f.close()

        link_file = "links.txt"
        if exists(link_file):
            f = open(link_file, "rb")
            if f.read().strip():
                self.api.addPackage("links.txt", [link_file], 1)
            f.close()

        #self.scheduler.addJob(0, get_account_manager().getAccountInfos)
        self.log.info(_("Activating Accounts..."))
        get_account_manager().getAccountInfos()

        thread_manager.pause = False
        self.running = True

        self.log.info(_("Activating Plugins..."))
        get_hook_manager().coreReady()

        self.log.info(_("pyLoad is up and running"))

        #test api
#        from module.common.APIExerciser import startApiExerciser
#        startApiExerciser(self, 3)

        #some memory stats
#        from guppy import hpy
#        hp=hpy()
#        import objgraph
#        objgraph.show_most_common_types(limit=20)
#        import memdebug
#        memdebug.start(8002)

        locals().clear()

        while True:
            try:
                sleep(2)
            except IOError as e:
                if e.errno != 4:  # errno.EINTR
                    raise

            if self.do_restart:
                self.log.info(_("restarting pyLoad"))
                self.restart()

            if self.do_kill:
                self.shutdown()
                self.log.info(_("pyLoad quits"))
                self.removeLogger()
                _exit(0) #@TODO thrift blocks shutdown

            thread_manager.work()
            self.scheduler.work()