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)
def conf_path(self, trans=False): if trans: 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) print(_("Setting new configpath, current configuration will not be transfered!")) path = self.ask(_("Configpath"), os.path.abspath("")) try: path = os.path.join(pypath, path) if not os.path.exists(path): os.makedirs(path) f = open(os.path.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.")) input() exit() except Exception as e: print(_("Setting config path failed: %s") % str(e))
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()
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, ) install_translation(translation) 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, ) install_translation(translation) 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"] = input(_("Address: ")) if not config["port"]: config["port"] = input(_("Port: ")) if not username: username = 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)
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()
env.filters["path_make_relative"] = path_make_relative env.filters["path_make_absolute"] = path_make_absolute env.filters["decode"] = decode env.filters["type"] = lambda x: str(type(x)) env.filters["formatsize"] = formatSize env.filters["getitem"] = lambda x, y: x.__getitem__(y) env.filters["url"] = lambda x: PREFIX + x if x.startswith("/") else x 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, ) install_translation(translation) env.install_gettext_translations(translation) from beaker.middleware import SessionMiddleware session_opts = { 'session.type': 'file', 'session.cookie_expires': False, 'session.data_dir': './tmp', 'session.auto': False } web = StripPathMiddleware(SessionMiddleware(app(), session_opts)) web = GZipMiddleWare(web) if PREFIX:
def start(self): langs = self.config.getMetaData("general", "language")["type"].split(";") lang = self.ask("Choose your Language / Wähle deine Sprache", "en", langs) gettext.setpaths([os.path.join(os.sep, "usr", "share", "pyload", "locale"), None]) translation = gettext.translation( "setup", os.path.join(self.path, "locale"), languages=[lang, "en"], fallback=True, ) install_translation(translation) #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.")) input() basic, ssl, captcha, gui, web, js = self.system_check() print("") if not basic: print(_("You need pycurl, sqlite and Python 2.7 or newer to run pyLoad.")) print(_("Please correct this and re-run pyLoad.")) print(_("Setup will now close.")) input() return False input(_("System check finished, hit enter to see your status report.")) print("") print(_("## Status ##")) print("") avail = [] if self.check_module("Cryptodome"): 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("Cryptodome"): 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 OCR 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") % os.path.abspath("")) print(_( "If you use pyLoad on a server or the home partition lives on an internal 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")) input() return True