示例#1
0
文件: api.py 项目: FedeG/pyload
def callApi(func, *args, **kwargs):
    if not hasattr(PYLOAD.EXTERNAL, func) or func.startswith("_"):
        print "Invalid API call", func
        return HTTPError(404, json.dumps("Not Found"))

    result = getattr(PYLOAD, func)(*[literal_eval(x) for x in args],
                                   **dict([(x, literal_eval(y)) for x, y in kwargs.iteritems()]))

    # null is invalid json  response
    return json.dumps(result or True, cls=TBaseEncoder)
示例#2
0
def callApi(func, *args, **kwargs):
    if not hasattr(PYLOAD.EXTERNAL, func) or func.startswith("_"):
        print("Invalid API call", func)
        return HTTPError(404, json.dumps("Not Found"))

    result = getattr(PYLOAD, func)(*[literal_eval(x) for x in args],
                                   **dict([(x, literal_eval(y)) for x, y in six.iteritems(kwargs)]))

    # null is invalid json  response
    if result is None: result = True

    return json.dumps(result, cls=TBaseEncoder)
示例#3
0
    def parseAttributes(self, filename, name, folder=""):
        """ Parse attribute dict from plugin"""
        data = open(filename, "rb")
        content = data.read()
        data.close()

        attrs = {}
        for m in self.BUILTIN.findall(content) + self.SINGLE.findall(content) + self.MULTI.findall(content):
            #replace gettext function and eval result
            try:
                attrs[m[0]] = literal_eval(m[-1].replace("_(", "("))
            except:
                self.logDebug(folder, name, "Error when parsing: %s" % m[-1])
                self.core.print_exc()

            if not hasattr(Base, "__%s__" % m[0]):
                if m[0] != "type": #TODO remove type from all plugins, its not needed
                    self.logDebug(folder, name, "Unknown attribute '%s'" % m[0])

        return attrs
示例#4
0
    def parseAttributes(self, filename, name, folder=""):
        """ Parse attribute dict from plugin"""
        data = open(filename, "rb")
        content = data.read()
        data.close()

        attrs = {}
        for m in self.BUILTIN.findall(content) + self.SINGLE.findall(content) + self.MULTI.findall(content):
            #replace gettext function and eval result
            try:
                attrs[m[0]] = literal_eval(m[-1].replace("_(", "("))
            except:
                self.logDebug(folder, name, "Error when parsing: %s" % m[-1])
                self.core.print_exc()

            if not hasattr(Base, "__%s__" % m[0]):
                if m[0] != "type": #TODO remove type from all plugins, its not needed
                    self.logDebug(folder, name, "Unknown attribute '%s'" % m[0])

        return attrs
示例#5
0
    def parse(self, folder, pattern=False, home={}):
        """
        returns dict with information 
        home contains parsed plugins from module.
        
        {
        name : {path, version, config, (pattern, re), (plugin, class)}
        }
        
        """
        plugins = {}
        if home:
            pfolder = join("userplugins", folder)
            if not exists(pfolder):
                makedirs(pfolder)
            if not exists(join(pfolder, "__init__.py")):
                f = open(join(pfolder, "__init__.py"), "wb")
                f.close()

        else:
            pfolder = join(pypath, "module", "plugins", folder)

        for f in listdir(pfolder):
            if (isfile(join(pfolder, f)) and f.endswith(".py") or f.endswith("_25.pyc") or f.endswith(
                "_26.pyc") or f.endswith("_27.pyc")) and not f.startswith("_"):
                data = open(join(pfolder, f))
                content = data.read()
                data.close()

                if f.endswith("_25.pyc") and version_info[0:2] != (2, 5):
                    continue
                elif f.endswith("_26.pyc") and version_info[0:2] != (2, 6):
                    continue
                elif f.endswith("_27.pyc") and version_info[0:2] != (2, 7):
                    continue

                name = f[:-3]
                if name[-1] == ".": name = name[:-4]

                version = self.VERSION.findall(content)
                if version:
                    version = float(version[0][1])
                else:
                    version = 0

                # home contains plugins from pyload root
                if home and name in home:
                    if home[name]["v"] >= version:
                        continue

                if name in IGNORE or (folder, name) in IGNORE:
                     continue

                plugins[name] = {}
                plugins[name]["v"] = version

                module = f.replace(".pyc", "").replace(".py", "")

                # the plugin is loaded from user directory
                plugins[name]["user"] = True if home else False
                plugins[name]["name"] = module

                if pattern:
                    pattern = self.PATTERN.findall(content)

                    if pattern:
                        pattern = pattern[0][1]
                    else:
                        pattern = "^unmachtable$"

                    plugins[name]["pattern"] = pattern

                    try:
                        plugins[name]["re"] = re.compile(pattern)
                    except:
                        self.log.error(_("%s has a invalid pattern.") % name)


                # internals have no config
                if folder == "internal":
                    self.core.config.deleteConfig(name)
                    continue

                config = self.CONFIG.findall(content)
                if config:
                    config = literal_eval(config[0].strip().replace("\n", "").replace("\r", ""))
                    desc = self.DESC.findall(content)
                    desc = desc[0][1] if desc else ""

                    if type(config[0]) == tuple:
                        config = [list(x) for x in config]
                    else:
                        config = [list(config)]

                    if folder == "hooks":
                        append = True
                        for item in config:
                            if item[0] == "activated": append = False

                        # activated flag missing
                        if append: config.append(["activated", "bool", "Activated", False])

                    try:
                        self.core.config.addPluginConfig(name, config, desc)
                    except:
                        self.log.error("Invalid config in %s: %s" % (name, config))

                elif folder == "hooks": #force config creation
                    desc = self.DESC.findall(content)
                    desc = desc[0][1] if desc else ""
                    config = (["activated", "bool", "Activated", False],)

                    try:
                        self.core.config.addPluginConfig(name, config, desc)
                    except:
                        self.log.error("Invalid config in %s: %s" % (name, config))

        if not home:
            temp = self.parse(folder, pattern, plugins)
            plugins.update(temp)

        return plugins
示例#6
0
    def parse(self, folder, pattern=False, home={}):
        """
        returns dict with information
        home contains parsed plugins from module.

        {
        name : {path, version, config, (pattern, re), (plugin, class)}
        }

        """
        plugins = {}
        if home:
            pfolder = join("userplugins", folder)
            if not exists(pfolder):
                makedirs(pfolder)
            if not exists(join(pfolder, "__init__.py")):
                f = open(join(pfolder, "__init__.py"), "wb")
                f.close()

        else:
            pfolder = join(pypath, "module", "plugins", folder)

        configs = {}
        for f in listdir(pfolder):
            if (
                (
                    isfile(join(pfolder, f)) and
                    f.endswith(".py") or
                    f.endswith("_27.pyc")
                ) and
                not f.startswith("_")
            ):

                data = open(join(pfolder, f))
                content = data.read()
                data.close()

                if f.endswith("_27.pyc") and sys.version_info[0:2] != (2, 7):
                    continue

                name = f[:-3]
                if name[-1] == ".": name = name[:-4]

                version = self.VERSION.findall(content)
                if version:
                    version = float(version[0][1])
                else:
                    version = 0

                # home contains plugins from pyload root
                if isinstance(home, dict) and name in home:
                    if home[name]["v"] >= version:
                        continue

                if name in IGNORE or (folder, name) in IGNORE:
                     continue

                plugins[name] = {}
                plugins[name]["v"] = version

                module = f.replace(".pyc", "").replace(".py", "")

                # the plugin is loaded from user directory
                plugins[name]["user"] = True if home else False
                plugins[name]["name"] = module

                if pattern:
                    pattern = self.PATTERN.findall(content)

                    if pattern:
                        pattern = pattern[0][1]
                    else:
                        pattern = "^unmachtable$"

                    plugins[name]["pattern"] = pattern

                    try:
                        plugins[name]["re"] = re.compile(pattern)
                    except:
                        self.log.error(_("%s has a invalid pattern.") % name)

                # internals have no config
                if folder == "internal":
                    self.core.config.deleteConfig(name)
                    continue

                config = self.CONFIG.findall(content)
                if config:
                    config = literal_eval(config[0].strip().replace("\n", "").replace("\r", ""))
                    desc = self.DESC.findall(content)
                    desc = desc[0][1] if desc else ""

                    if type(config) == list and all(type(c) == tuple for c in config):
                        config = dict((x[0], x[1:]) for x in config)
                    else:
                        self.log.error("Invalid config in %s: %s" % (name, config))
                        continue

                    if folder == "hooks" and "activated" not in config:
                            config['activated'] = ["bool", "Activated", False]

                    config['desc'] = desc
                    configs[name] = config

                elif folder == "hooks":  # force config creation
                    desc = self.DESC.findall(content)
                    desc = desc[0][1] if desc else ""
                    config['activated'] = ["bool", "Activated", False]

                    config['desc'] = desc
                    configs[name] = config

        if not home:
            temp_plugins, temp_configs = self.parse(folder, pattern, plugins or True)
            plugins.update(temp_plugins)
            configs.update(temp_configs)

        return plugins, configs