Esempio n. 1
0
def plugin_delete(key):
    message = None
    if request.method == 'POST':
        show_form = False
        try:
            plugin = Plugin(key)
            title = 'Plugin {} version {} deleted'.format(
                plugin.name, plugin.version)
            plugin.delete(key)
            log("Plugin %s has been deleted" % key)
        except DoesNotExist:
            return render_error('<b>{}</b> does not exists'.format(key))
    else:
        try:
            plugin = Plugin(key)
            title = 'Confirm deletion of Plugin {} version {}?'.format(
                plugin.name, plugin.version)
            show_form = True
            log("Plugin %s deletion confirmation asked" % key)
        except DoesNotExist:
            return render_error('{} does not exists'.format(key))

    return render_template('delete.html',
                           title=title,
                           plugin=plugin,
                           show_form=show_form,
                           message=message)
Esempio n. 2
0
    def post(self, key, metadata_key):
        try:
            plugin = Plugin(key)
        except DoesNotExist:
            abort(404)

        metadata_value = request.data
        plugin.set_metadata(metadata_key, metadata_value)
        # Re-read
        plugin = Plugin(plugin.key)
        return {metadata_key: getattr(plugin, metadata_key)}
Esempio n. 3
0
    def __init__(self,
                 answers,
                 APP,
                 dryrun=False,
                 debug=False,
                 stop=False,
                 answers_format=ANSWERS_FILE_SAMPLE_FORMAT,
                 **kwargs):

        self.debug = debug
        self.dryrun = dryrun
        self.stop = stop
        self.kwargs = kwargs

        if "answers_output" in kwargs:
            self.answers_output = kwargs["answers_output"]

        if os.environ and "IMAGE" in os.environ:
            self.app_path = APP
            APP = os.environ["IMAGE"]
            del os.environ["IMAGE"]
        elif "image" in kwargs:
            logger.warning("Setting image to %s" % kwargs["image"])

            self.app_path = APP
            APP = kwargs["image"]
            del kwargs["image"]

        self.kwargs = kwargs

        if APP and os.path.exists(APP):
            self.app_path = APP
        else:
            if not self.app_path:
                self.app_path = os.getcwd()
            install = Install(answers,
                              APP,
                              dryrun=dryrun,
                              target_path=self.app_path,
                              answers_format=answers_format)
            install.install()
            printStatus("Install Successful.")

        self.nulecule_base = Nulecule_Base(target_path=self.app_path,
                                           dryrun=dryrun,
                                           file_format=answers_format)
        if "ask" in kwargs:
            self.nulecule_base.ask = kwargs["ask"]

        workdir = None
        if "workdir" in kwargs:
            workdir = kwargs["workdir"]

        self.utils = Utils(self.app_path, workdir)
        if "workdir" not in kwargs:
            kwargs["workdir"] = self.utils.workdir

        self.answers_file = answers
        self.plugin = Plugin()
        self.plugin.load_plugins()
Esempio n. 4
0
 def delete(self, key):
     try:
         plugin = Plugin(key)
     except DoesNotExist:
         abort(404)
     plugin.delete(plugin.key)
     return {'result': 'success'}
Esempio n. 5
0
 def load_plugins():
     plugins = []
     for p in PLUGINS:
         plugin = Plugin(name=p.get("name"),
                         rootpath=p.get("rootpath"),
                         plugin_id=p.get("plugin_id"))
         plugins.append(plugin)
     return plugins
Esempio n. 6
0
def plugin_test():
    plugin = Plugin()
    plugin.import_folder('/home/floeuser/floe/dev/plugins')
    
    for name in plugin.list():
        print(name)
    print(plugin.call('func1'))
    plugin.call('func2', 'pos arg 1', 'pos arg 2', kwarg1='kwarg1', kwarg2='kwarg2', kwarg3='kwarg3')
    print(plugin.call('func3'))
    print(plugin.call('func4'))
Esempio n. 7
0
def plugin_details(key):
    message = None
    try:
        plugin = Plugin(key)
    except DoesNotExist:
        return render_error('<b>{}</b> does not exists'.format(key))
    log("Plugin details for %s" % key)
    return render_template('details.html',
                           title="{} - ver. {}".format(plugin.name,
                                                       plugin.version),
                           plugin=plugin,
                           message=message)
Esempio n. 8
0
def plugin_download(key, package_name):
    try:
        plugin = Plugin(key)
        plugin.incr_downloads()
        response = make_response(plugin.blob)
        response.headers['Content-Type'] = 'application/zip'
        response.headers['Content-Disposition'] = \
            'inline; filename=%s.zip' % package_name
        log("Plugin %s downloaded" % key)
        return response
    except DoesNotExist:
        return render_error('<b>{}</b> does not exists'.format(key))
Esempio n. 9
0
    def __init__(self, threads:int=20, listener_timeout:int=600, request_timeout:int=50):
        self._request_timout = request_timeout

        signal.signal(signal.SIGTERM, self.stop)

        self._pool = multiprocessing.pool.ThreadPool(threads + 1)
        self._lock = multiprocessing.Lock()

        self._plugin = Plugin()
        self._timeout = Timeout(self.stop, listener_timeout)
        self._connections = Connections(threads)
        self._listener = Listener(self.handle_connection)
        self._listener.run()
Esempio n. 10
0
def handle(msg):
	from plugin import Plugin
	cmd = None
	content_type, chat_type, chat_id, msg_date, msg_id = telepot.glance(msg, long=True)
	if (str(content_type) is 'text') and (str(chat_type) == "private"):
		if ('entities' in msg):
			if ('bot_command' == msg['entities'][0]['type']):
				try:
					cmd = Plugin(msg).command()
				except Exception as error:
					print(error)
				finally:
					if (not cmd is None):
						api.sendMessage(chat_id, cmd, reply_to_message_id=msg_id, parse_mode="HTML")
Esempio n. 11
0
    def down(self, callback, who, arg):
        """down <url> -- checks to see if the site is down."""

        if 'http://' not in arg:
            inp = 'http://' + arg
        else:
            inp = arg

        try:
            p = Plugin('wow', 'such doge')
            p.get_head(url=inp)
            return inp + ' seems to be up.'
        except:
            return inp + ' seems to be down.'
Esempio n. 12
0
 def load_conf(self, app, configfile):
     #print configfile 
     file_object = open(configfile)
     all_the_text = None
     try:
         all_the_text = file_object.read()            
     finally:
         file_object.close()
 
     config = json.loads(all_the_text)
     _key = config.keys();
     if "input" in _key:
         plugin_input = config['input']
         for i in range(len(plugin_input)):
             self.register_plugin(Plugin(self, plugin_input[i]))
     
     if "output" in _key:
         plugin_input = config['output']
         for i in range(len(plugin_input)):
             self.register_plugin(Plugin(self, plugin_input[i]))
             
     self.scheduler.init_app(app)
     self.scheduler.start()
Esempio n. 13
0
def invalidate_cache_if_changed():
    store = Path(sys.path[0] + '/store.json')
    stored_data = json.loads((store.read_text() if store.exists() else '{}')
                             or '{}')
    stored_plugins = {
        int(id): Plugin(data)
        for id, data in stored_data.items()
    }
    store.write_text(json.dumps({id: p.data for id, p in plugins.items()}))

    if my_plugin_id not in stored_plugins:
        return plugins  # no changes, the first message in history
    if plugins[my_plugin_id].data != stored_plugins[my_plugin_id].data:
        return stored_plugins
Esempio n. 14
0
def loadPlugin():
    plugin = Plugin("builtinCommands")

    plugin.registerCommand(CreateNode)
    plugin.registerCommand(CreateAttribute)
    plugin.registerCommand(DeleteObjects)
    plugin.registerCommand(ConnectAttributes)
    plugin.registerCommand(DisconnectInput)
    plugin.registerCommand(CollapseNodes)
    plugin.registerCommand(ExplodeCollapsedNode)
    plugin.registerCommand(SetAttributeValue)
    plugin.registerCommand(SetupDynamicAttribute)
    plugin.registerCommand(CollapseExecutableNodes)

    return plugin
Esempio n. 15
0
    def __init__(self):
        self.myMonitor = Monitor()
        self.myMonitor.myService = self

        self.myPlayer = Player()
        self.myPlayer.myService = self

        self.myConfig = Config(sys.argv)
        self.myConfig.myService = self
        self.myPredefined = self.myConfig.predefined
        self.jsonRPC = self.myConfig.jsonRPC
        self.channels = self.myConfig.channels

        self.myPlugin = Plugin(sys.argv)
        self.myBuilder = self.myPlugin.builder

        self.autoTune = True
Esempio n. 16
0
    def LoadPlugin(self, plugin_filename):

        if not os.path.exists(plugin_filename):

            print "Error loading plugin, %s doesn't exist" % plugin_filename

            return False

        try:

            plugin_entry = Plugin(plugin_filename)

        except errors.PluginFileError, e:

            print "Error Loading Plugin %s, %s" % (plugin_filename, e)

            return False
Esempio n. 17
0
 def __run_plugin__(self, filename, verbose, raw):
     try:
         plugin = Plugin(filename, self.__ossim_config,
                         self.__severity_list, verbose, raw)
     except (PluginError, PluginConfigParserError) as e:
         if verbose > 0:
             print ''
             Output.warning(e.msg)
         else:
             self.__summary.append({'plugin': e.plugin, 'warning': e.msg})
     except Exception as e:
         print ''
         Output.error('Unknown error parsing plugin "%s": %s' %
                      (filename, str(e)))
     else:
         if (plugin.get_enable()) and (plugin.get_checks_len() > 0) and (
                 plugin.check_category(self.__category_list)):
             self.__summary.append(plugin.run())
         else:
             del plugin
Esempio n. 18
0
    def __init__(self, answers, APP, dryrun=False, debug=False, **kwargs):

        self.debug = debug
        self.dryrun = dryrun
        self.kwargs = kwargs
        if "answers_output" in kwargs:
            self.answers_output = kwargs["answers_output"]

        if APP and os.path.exists(APP):
            self.app_path = APP
        else:
            raise Exception("App path %s does not exist." % APP)

        self.params = Params(target_path=self.app_path)
        if "ask" in kwargs:
            self.params.ask = kwargs["ask"]

        self.utils = Utils(self.params)

        self.answers_file = answers
        self.plugin = Plugin()
        self.plugin.load_plugins()
Esempio n. 19
0
    def __run_plugin__(self, filename, verbose, raw):
        # Parse the plugin configuration file.
        # Check if file exists
        if not path.isfile(filename):
            msg = 'Plugin file does not exist: %s' % filename
            self.__generate_blocked_output(config_file=None,
                                           plugin=filename,
                                           plugin_data={},
                                           sections=[],
                                           error_msg=msg)
            return

        # Check for file extension.
        if not filename.endswith('.plg'):
            msg = 'File extension is not .plg'
            self.__generate_blocked_output(config_file=None,
                                           plugin=filename,
                                           plugin_data={},
                                           sections=[],
                                           error_msg=msg)
            return

        # Check for db connections and some other basic param config
        cfg_msg = ''
        for key in self.__successful_config.keys():
            if not self.__successful_config[key]['result']:
                cfg_msg = ';'.join(
                    [cfg_msg, self.__successful_config[key]['error']])
        if cfg_msg != '':
            self.__generate_blocked_output(config_file=None,
                                           plugin=filename,
                                           plugin_data={},
                                           sections=[],
                                           error_msg=cfg_msg)

        config_file = None
        try:
            config_file = self.__load_plugin_file(filename)
        except PluginError as e:
            self.__generate_blocked_output(config_file=None,
                                           plugin=e.plugin,
                                           plugin_data={},
                                           sections=[],
                                           error_msg=e.msg)

            return

        # Fill the Plugin Object
        if config_file:
            try:
                plugin = Plugin(filename, config_file,
                                self.__alienvault_config, self.__severity_list,
                                self.__appliance_type_list,
                                self.__ignore_dummy_platform, verbose, raw)

                if (plugin.get_checks_len() > 0) and (plugin.check_category(
                        self.__category_list)):
                    result = plugin.run()
                    self.__in_strike_zone &= result.get('strike_zone', True)
                    self.__summary[plugin.get_name()] = result
                else:
                    del plugin

            except (PluginError, PluginConfigParserError, CheckError) as e:

                if verbose > 0:
                    Output.warning(e.msg)

                sections = []
                try:
                    sections = config_file.sections()
                except Exception:
                    pass

                self.__generate_blocked_output(config_file=config_file,
                                               plugin=e.plugin,
                                               plugin_data=e.kwargs,
                                               sections=sections,
                                               error_msg=e.msg)

            except KeyError, msg:
                Output.error('Unknown error running plugin "%s": %s' %
                             (filename, str(msg)))
Esempio n. 20
0
def loadPlugin():
    plugin = Plugin("builtinNodes")

    plugin.registerAttribute("NumericAttribute", _coral.NumericAttribute)

    plugin.registerNode("Int",
                        _coral.IntNode,
                        tags=["numeric"],
                        description="Generate an int.")
    plugin.registerNode("Float",
                        _coral.FloatNode,
                        tags=["numeric"],
                        description="Generate a float.")
    plugin.registerNode(
        "Vec3",
        _coral.Vec3Node,
        tags=["numeric"],
        description="Generate a vec3.\nWorks with single or array values.")
    plugin.registerNode(
        "Vec3ToFloats",
        _coral.Vec3ToFloats,
        tags=["numeric"],
        description=
        "Get x, y, z values from a vec3.\nWorks with single or array values.")
    plugin.registerNode(
        "Col4",
        _coral.Col4Node,
        tags=["numeric"],
        description="Generate a col4.\nWorks with single or array values.")
    plugin.registerNode(
        "Col4ToFloats",
        _coral.Col4ToFloats,
        tags=["numeric"],
        description=
        "Get r, g, b, a values from a col4.\nWorks with single or array values."
    )
    plugin.registerNode(
        "Col4Reverse",
        _coral.Col4Reverse,
        tags=["numeric"],
        description=
        "Get 1-rgb. Alpha doesn't change.\nWorks with single or array values.")
    plugin.registerNode(
        "Quat",
        _coral.QuatNode,
        tags=["numeric"],
        description="Generate a quaternion.\nWorks with single or array values."
    )
    plugin.registerNode(
        "QuatToFloats",
        _coral.QuatToFloats,
        tags=["numeric"],
        description=
        "Get r, x, y, z values from a quaternion.\nWorks with single or array values."
    )
    plugin.registerNode("QuatToAxisAngle",
                        _coral.QuatToAxisAngle,
                        tags=["numeric"],
                        description="Convert a quaternion to axis/angle.")
    plugin.registerNode("QuatToEulerRotation",
                        _coral.QuatToEulerRotation,
                        tags=["numeric"],
                        description="Convert a quaternion to euler rotation.")
    plugin.registerNode(
        "QuatToMatrix44",
        _coral.QuatToMatrix44,
        tags=["numeric"],
        description="Convert a quaternion to a rotation matrix.")
    plugin.registerNode("Matrix44",
                        _coral.Matrix44Node,
                        tags=["numeric"],
                        description="Generate a Matrix44.")
    plugin.registerNode("ConstantArray",
                        _coral.ConstantArray,
                        tags=["numeric"],
                        description="Generate an array from a constant value.")
    plugin.registerNode("ArraySize",
                        _coral.ArraySize,
                        tags=["numeric"],
                        description="Get the size of a numeric array")
    plugin.registerNode(
        "BuildArray",
        _coral.BuildArray,
        tags=["numeric"],
        description="Build a numeric array by adding each individual element.")
    plugin.registerNode(
        "RangeArray",
        _coral.RangeArray,
        tags=["numeric"],
        description=
        "Generate an array from the given range, each element of the array is a progressive value of the range."
    )
    plugin.registerNode(
        "Matrix44Translation",
        _coral.Matrix44Translation,
        tags=["numeric"],
        description=
        "Get the translation values of a matrix44.\nWorks with single or array values."
    )
    plugin.registerNode(
        "Matrix44RotationAxis",
        _coral.Matrix44RotationAxis,
        tags=["numeric"],
        description=
        "Get each rotation axis of a matrix44 as three individual vectors.\nWorks with single or array values."
    )
    plugin.registerNode(
        "Matrix44FromVectors",
        _coral.Matrix44FromVectors,
        tags=["numeric"],
        description=
        "Build a matrix44 from vec3 values.\nWorks with single or array values."
    )
    plugin.registerNode(
        "Matrix44EulerRotation",
        _coral.Matrix44EulerRotation,
        tags=["numeric"],
        description=
        "Get the euler angles from a matrix44.\nWorks with single or array values."
    )
    plugin.registerNode(
        "Matrix44ToQuat",
        _coral.Matrix44ToQuat,
        tags=["numeric"],
        description=
        "Get the quaternion from a matrix44.\nWorks with single or array values."
    )
    plugin.registerNode(
        "RangeLoop",
        _coral.RangeLoop,
        tags=["numeric"],
        description=
        "Generate a value that will loop in a given range of values.\nWorks with single or array values."
    )
    plugin.registerNode(
        "RandomNumber",
        _coral.RandomNumber,
        tags=["numeric"],
        description=
        "Generate a random number.\nWorks with single or array values.")
    plugin.registerNode(
        "ArrayIndices",
        _coral.ArrayIndices,
        tags=["numeric", "loop"],
        description=
        "Build an array composed by all the indexes extracted from the given input array."
    )
    plugin.registerNode("GetArrayElement",
                        _coral.GetArrayElement,
                        tags=["numeric"],
                        description="Get a single element of an array.")
    plugin.registerNode("SetArrayElement",
                        _coral.SetArrayElement,
                        tags=["numeric"],
                        description="Set a single element of an array.")
    plugin.registerNode(
        "GetSimulationStep",
        _coral.GetSimulationStep,
        tags=["numeric", "simulation"],
        description=
        "Get the values stored by SetSimulationStep and reuse them in the simulation step.\nWhen the step attribute is set to 0 the simulation is reset and the data is taken from the source."
    )
    plugin.registerNode(
        "SetSimulationStep",
        _coral.SetSimulationStep,
        tags=["numeric", "simulation"],
        description=
        "Set some numeric values and make them available to a GetSimulationStep node connected to the same source.\n"
    )
    plugin.registerNode("FindPointsInRange",
                        _coral.FindPointsInRange,
                        tags=["numeric"])

    plugin.registerNode("Add", _coral.AddNode, tags=["math"])
    plugin.registerNode("Sub", _coral.SubNode, tags=["math"])
    plugin.registerNode("Mul", _coral.MulNode, tags=["math"])
    plugin.registerNode("Div", _coral.DivNode, tags=["math"])
    plugin.registerNode("Abs", _coral.Abs, tags=["math"])
    plugin.registerNode("Atan2", _coral.Atan2, tags=["math"])
    plugin.registerNode("Sqrt", _coral.Sqrt, tags=["math"])
    plugin.registerNode("Pow", _coral.Pow, tags=["math"])
    plugin.registerNode("Exp", _coral.Exp, tags=["math"])
    plugin.registerNode("Log", _coral.Log, tags=["math"])
    plugin.registerNode("Ceil", _coral.Ceil, tags=["math"])
    plugin.registerNode("Floor", _coral.Floor, tags=["math"])
    plugin.registerNode("Round", _coral.Round, tags=["math"])
    plugin.registerNode("Length", _coral.Length, tags=["math"])
    plugin.registerNode("Inverse", _coral.Inverse, tags=["math"])
    plugin.registerNode("CrossProduct", _coral.CrossProduct, tags=["math"])
    plugin.registerNode("DotProduct", _coral.DotProduct, tags=["math"])
    plugin.registerNode("Normalize", _coral.Normalize, tags=["math"])
    plugin.registerNode("TrigonometricFunc",
                        _coral.TrigonometricFunc,
                        tags=["math"])
    plugin.registerNode("Radians", _coral.Radians, tags=["math"])
    plugin.registerNode("Degrees", _coral.Degrees, tags=["math"])
    plugin.registerNode("Min", _coral.Min, tags=["math"])
    plugin.registerNode("Max", _coral.Max, tags=["math"])
    plugin.registerNode("Average", _coral.Average, tags=["math"])
    plugin.registerNode("Slerp", _coral.Slerp, tags=["math"])
    plugin.registerNode("QuatMultiply", _coral.QuatMultiply, tags=["math"])
    plugin.registerNode("Negate", _coral.Negate, tags=["math"])

    plugin.registerAttribute("ImageAttribute", _coral.ImageAttribute)
    plugin.registerNode("Image", _coral.ImageNode, tags=["image"])

    plugin.registerAttribute("GeoAttribute", _coral.GeoAttribute)
    plugin.registerAttribute("GeoInstanceArrayAttribute",
                             _coral.GeoInstanceArrayAttribute)
    plugin.registerNode("SetGeoPoints", _coral.SetGeoPoints, tags=["geometry"])
    plugin.registerNode("GetGeoPoints", _coral.GetGeoPoints, tags=["geometry"])
    plugin.registerNode("GetGeoNormals",
                        _coral.GetGeoNormals,
                        tags=["geometry"],
                        description="Get one normal vector per vertex.")
    plugin.registerNode("ObjImporter", _coral.ObjImporter, tags=["geometry"])
    plugin.registerNode("GeoGrid", _coral.GeoGrid, tags=["geometry"])
    plugin.registerNode("GeoSphere", _coral.GeoSphere, tags=["geometry"])
    plugin.registerNode("GeoCube", _coral.GeoCube, tags=["geometry"])
    plugin.registerNode("GeoNeighbourPoints",
                        _coral.GeoNeighbourPoints,
                        tags=["geometry"])
    plugin.registerNode("GetGeoElements",
                        _coral.GetGeoElements,
                        tags=["geometry"])
    plugin.registerNode("GetGeoSubElements",
                        _coral.GetGeoSubElements,
                        tags=["geometry"])
    plugin.registerNode("GeoInstanceGenerator",
                        _coral.GeoInstanceGenerator,
                        tags=["geometry"])

    plugin.registerAttribute("StringAttribute", _coral.StringAttribute)
    plugin.registerNode("String", _coral.StringNode, tags=["generic"])
    plugin.registerNode("Time", timeNode.TimeNode, tags=["generic"])
    plugin.registerNode("ImportCIOTransforms",
                        _coral.ImportCIOTransforms,
                        tags=["generic"])
    plugin.registerNode("ImportCIOSkinWeights",
                        _coral.ImportCIOSkinWeights,
                        tags=["generic"])

    plugin.registerNode("LoopInput", _coral.LoopInputNode, tags=["loop"])
    plugin.registerNode("LoopOutput", _coral.LoopOutputNode, tags=["loop"])
    plugin.registerNode("ForLoop", _coral.ForLoopNode, tags=["loop"])

    plugin.registerNode("ProcessSimulation",
                        _coral.ProcessSimulationNode,
                        tags=["generic", "simulation"])

    plugin.registerAttribute("BoolAttribute", _coral.BoolAttribute)
    plugin.registerNode("Bool", _coral.BoolNode, tags=["conditional"])
    plugin.registerNode("IfGreaterThan",
                        _coral.IfGreaterThan,
                        tags=["conditional"])
    plugin.registerNode("IfLessThan", _coral.IfLessThan, tags=["conditional"])
    plugin.registerNode("ConditionalValue",
                        _coral.ConditionalValue,
                        tags=["conditional"])

    plugin.registerNode("SplinePoint", _coral.SplinePoint, tags=["curve"])

    plugin.registerNode("SkinWeightDeformer",
                        _coral.SkinWeightDeformer,
                        tags=["deformers"])

    return plugin
Esempio n. 21
0
from plugin import Plugin

plugin = Plugin("echo", "General", "A very simple Echo plugin")


def setup():
    plugin.add_command("echo", echo, "make someone agree with you for once")


async def echo(command):
    """Echo back the command's arguments"""
    response = " ".join(command.args)
    await plugin.reply(command, response)


setup()
Esempio n. 22
0
 def get(self, key, metadata_key):
     try:
         plugin = Plugin(key)
     except DoesNotExist:
         abort(404)
     return {metadata_key: getattr(plugin, metadata_key)}
Esempio n. 23
0
from nio import AsyncClient, UnknownEvent
from plugin import Plugin
import logging
logger = logging.getLogger(__name__)

plugin = Plugin("sampleplugin", "General", "Just a simple sample.")


def setup():

    plugin.add_command(
        "sample", sample_command,
        "A simple sample command, producing a simple sample output")
    plugin.add_command("sample_store", sample_store,
                       "Store a message persistently")
    plugin.add_command("sample_read", sample_read, "Read the stored message")
    plugin.add_command("sample_clear", sample_clear,
                       "Clear the stored message")
    plugin.add_command("sample_link_user", sample_link_user,
                       "Given a displayname, try to produce a userlink")
    plugin.add_command("sample_reaction_test", sample_reaction_test,
                       "Post a message and record reactions to this message")
    plugin.add_hook("m.reaction", hook_reactions)
    """The following part demonstrates defining a configuration value to be expected in the plugin's configuration file and reading the value"""

    plugin.add_config("default_message",
                      "this is the default message",
                      is_required=True)
    """
    Define a configuration value to be loaded at startup.
    The value supplied is a default value that is used if no configuration was found in the configuration file 
Esempio n. 24
0
        7: f"<font color=\"red\">fairly</font> {condition}",
        8: f"<font color=\"red\">pretty darn</font> {condition}",
        9: f"<font color=\"red\">extremely</font> {condition}",
        10: f"the {condition}est of all! {nick} scores a <font color=\"red\">perfect</font> 10 on the {condition.replace(' ', '-')}-o-meter!! I bow to {nick}'s"
            f" {condition}ness...",
    }

    return comments[level]


async def meter(command):

    try:
        nick = command.args[0]
        condition = " ".join(command.args[1:])
        if not condition:
            raise IndexError
        else:
            level: int = random.randint(0, 10)
            text: str = f"{condition.replace(' ', '-')}-o-Meter {build_gauge(level)} <font color=\"{get_level_color(level)}\">{str(level)}</font>/10 {nick} is " \
                        f"{get_comment(level, nick, condition)}"
            await send_typing(command.client, command.room.room_id, text)

    except (ValueError, IndexError):

        await send_text_to_room(command.client, command.room.room_id, "Usage: `meter <target> <condition>`")


plugin = Plugin("meter", "General", "Plugin to provide a simple, randomized !meter")
plugin.add_command("meter", meter, "accurately measure someones somethingness")
Esempio n. 25
0
    def __update_document(self, action, isapi=False):
        """ add/update document controller

			创建/修改文档的路由

			Argument:
			isapi:是否为操作接口,False为view路由,True为API操作
		"""
        pid = int(self.get_argument('pid', 0))
        tid = int(self.get_argument('tid', 0))
        did = int(self.get_argument('did', 0))

        if pid == 0 or tid == 0:
            logging.warning('CGI Param error!')
            self.write(json.dumps(Error.CGIREQUESTERR))
            return
        pass

        if isapi == False:
            # 获取文档信息
            _doc_data = {}
            if did != 0:
                _doc = ModDocument(self.application)
                _doc_data = _doc.get_document_one(pid, tid, did)
                if _doc_data is None:
                    self.write(json.dumps(Error.DBEMPTYERR))
                    return
            pass
            publish_url = "" if 'publish_url' not in _doc_data else _doc_data[
                'publish_url'][1]
            publish_url = "" if publish_url is None else publish_url
            # render document page for view
            _field = ModField(self.application)
            n, _field_list = _field.get_field_list(pid, tid, detail=True)
            if n < 0:
                self.write(json.dumps(_field_list))
                return
            _plugin = Plugin(self.application)
            form_html = ""
            form_submit_js = ""
            form_js = ""
            form_css = ""
            form_fields = []
            vue_data = []
            remove_list = []
            for i in range(0, len(_field_list)):
                # build_result = _plugin.make_field_html(pid,tid,_field_list[i]['field_id'])
                _field_list[i]['algorithm'] = Algorithm.parse_algorithm(
                    _field_list[i]['algorithm'])
                _field_cfg = self.application.core.get_field_detail(
                    _field_list[i]['field_type'])
                # 只处理input类型的插件
                if _field_cfg['type'] == 'input' and _field_list[i][
                        'enable'] == 1:
                    # 合成html css js
                    form_html = form_html + _field_cfg['html'].replace(
                        '{$field_id}', str(
                            _field_list[i]['field_id'])).replace(
                                '{$field_name}', _field_list[i]
                                ['field_name']) + '\n<!--auto html code-->\n'
                    form_submit_js = form_submit_js + Common.js_encode(
                        _field_cfg['submit']).replace(
                            '{$field_id}', str(_field_list[i]['field_id'])
                        ) + '\n//cms auto js code\n'
                    form_js = form_js + _field_cfg['js'].replace(
                        '{$field_id}', str(_field_list[i]['field_id'])
                    ) + '\n//cms auto js code\n'
                    form_css = form_css + _field_cfg[
                        'css'] + '\n/*cms auto css */\n'
                    # form_fields.append(str(_field_list[i]['field_id']))
                    # 生成vue_user_data
                    if 'sp_' + str(_field_list[i]['field_id']) in _doc_data:
                        _field_list[i]['field_value'] = _doc_data[
                            'sp_' + str(_field_list[i]['field_id'])][1]
                    else:
                        _field_list[i]['field_value'] = _field_list[i][
                            'default_value']
                    _field_list[i]['field_value'] = str(base64.b64encode(
                        urllib.parse.quote(
                            _field_list[i]['field_value']).encode(
                                encoding='utf-8')),
                                                        encoding='utf-8')
                    #_field_list[i]['field_value'] = _field_list[i]['field_value'].replace("'", "\\'").replace("\n",
                    #                                                                                          "\\n").replace(
                    #    "\r", "")
                else:
                    # out类插件和enable=0的插件不显示
                    remove_list.append(_field_list[i])
                pass
                form_fields.append(str(_field_list[i]['field_id']))
            # 清除所有out类型插件
            for t in remove_list:
                _field_list.remove(t)
            form = {
                'html': form_html,
                'js': form_js,
                'css': form_css,
                'submit': form_submit_js
            }
            self.render_ex('editor_document.html',
                           action=action,
                           project_id=pid,
                           template_id=tid,
                           document_id=did,
                           forminfo=form,
                           form_fields=(',').join(form_fields),
                           fields_data=_field_list,
                           publish_url=publish_url)
        else:
            # add/update document api
            form_fields = self.get_argument('field_ids', '')
            if form_fields == '':
                self.write(json.dumps(Error.CGIREQUESTERR))
                return
            data = {}
            for sp in form_fields.split(','):
                data['sp_' + sp] = self.get_argument('_sp' + sp + "_value", '')
            # 获取登录用户昵称
            curent_user = self.userinfo['nick_name'] if self.userinfo[
                'nick_name'].strip() != '' else self.userinfo['username']
            url = self.get_argument('publish_url', '')
            _doc = ModDocument(self.application)
            result = _doc.update(pid,
                                 tid,
                                 document_id=did,
                                 publish_url=url,
                                 user=curent_user,
                                 data=data)
            self.write(json.dumps(result))
Esempio n. 26
0
import time

from plugin import Plugin

# You SHOULD name instance of Plugin() as plugin, otherwise it wouldn't work
# TODO: Fix it
plugin = Plugin(name="Core", description="Core plugin for server (containts all basic stuff)", version="0.1")

# You can do this to make code shorter and cleaner
event = plugin.event

plugin.log("Initialized successfully...")


@event("player_command")
def handler(player, command, args):
    if command == "stop":
        player.send_chat("Server stopping... You will be kicked in two seconds")
        time.sleep(2)
        plugin.log(player.nickname + " has stopped the server!")
        from twisted.internet import reactor  # Import reactor and call stop methods
        reactor.removeAll()
        reactor.iterate()
        reactor.stop()
    if command == "tppos":
        # If command called with 3 arguments
        if len(args) == 3:
            # Set player position
            try:
                x, y, z = [float(arg) for arg in args]  # Convert strings to floats
                player.set_position(x, y, z)
Esempio n. 27
0
def classFactory(iface):
    from plugin import Plugin
    return Plugin(iface, version())
Esempio n. 28
0
    try:
        roomsdb = pickle.load(open(roomsfile, "rb"))
    except FileNotFoundError:
        roomsdb = {}

    if room_id in allowed_rooms and room_id in roomsdb.keys():
        # Remove special characters before translation
        message = sub('[^A-z0-9\-\.\?!:\sÄäÜüÖö]+', '', message)
        trans = googletrans.Translator()
        logger.debug(f"Detecting language for message: {message}")
        message_source_lang = trans.detect(message).lang
        if roomsdb[room_id]["bidirectional"]:
            languages = [roomsdb[room_id]["source_langs"][0], roomsdb[room_id["dest_lang"]]]
            if message_source_lang in languages:
                # there has to be a simpler way, but my brain is tired
                dest_lang = set(languages).difference([message_source_lang])
                if len(dest_lang) == 1:
                    dest_lang = dest_lang.pop()
                    translated = trans.translate(message, dest=dest_lang).text
                    await send_text_to_room(client, room_id, translated)
        else:
            if message_source_lang != roomsdb[room_id]["dest_lang"] and (roomsdb[room_id]["source_langs"] == ['any'] or message_source_lang in roomsdb[room_id]["source_langs"]):
                translated = trans.translate(message, dest=roomsdb[room_id]["dest_lang"]).text
                await send_text_to_room(client, room_id, translated)


plugin = Plugin("translate", "General", "Provide near-realtime translations of all room-messages via Google Translate")
plugin.add_command("translate", switch, "`translate [[bi] source_lang... dest_lang]` - translate text from "
                                        "one or more source_lang to dest_lang", allowed_rooms)
plugin.add_hook("m.room.message", translate, allowed_rooms)
    def __init__(self, parent):
        self.doing_task_event_loop = False
        self.doing_task_callback = False
        self.listening = False

        wx.Panel.__init__(self, parent)

        # Read only Text Area
        self.textbox = wx.TextCtrl(self,
                                   style=wx.TE_MULTILINE | wx.TE_READONLY)
        self.horizontal_text = wx.BoxSizer()
        self.horizontal_text.Add(self.textbox, proportion=1, flag=wx.EXPAND)

        # Main Input controls
        self.listen_port_label = wx.StaticText(self, label="Listen Port")
        self.listen_port_text = wx.TextCtrl(self, size=(50, -1), value="5000")
        self.broadcast_checkbox = wx.CheckBox(self, label="Allow Broadcast")
        self.button_open = wx.Button(self, label="Open")
        self.button_listen = wx.Button(self, label="Listen")
        self.subhorizontal_inputs1 = wx.BoxSizer()
        self.subhorizontal_inputs1.Add(self.listen_port_label, 0, wx.RIGHT, 5)
        self.subhorizontal_inputs1.Add(self.listen_port_text, 0, wx.RIGHT, 5)
        self.subhorizontal_inputs1.Add(self.broadcast_checkbox, 0, wx.RIGHT,
                                       92)
        self.subhorizontal_inputs1.Add(self.button_open, 0, wx.RIGHT, 5)
        self.subhorizontal_inputs1.Add(self.button_listen, 0, wx.RIGHT, 5)

        self.destination_ip_label = wx.StaticText(self, label="Destination IP")
        self.destination_ip_text = wx.TextCtrl(self,
                                               size=(150, -1),
                                               value="127.0.0.1")
        self.destination_port_label = wx.StaticText(self, label="Port")
        self.destination_port_text = wx.TextCtrl(self,
                                                 size=(50, -1),
                                                 value="5000")
        self.subhorizontal_inputs2 = wx.BoxSizer()
        self.subhorizontal_inputs2.Add(self.destination_ip_label, 0, wx.RIGHT,
                                       5)
        self.subhorizontal_inputs2.Add(self.destination_ip_text, 0, wx.RIGHT,
                                       5)
        self.subhorizontal_inputs2.Add(self.destination_port_label, 0,
                                       wx.RIGHT, 5)
        self.subhorizontal_inputs2.Add(self.destination_port_text, 0, wx.RIGHT,
                                       5)

        self.message_label = wx.StaticText(self, label="Message")
        self.message_text = wx.TextCtrl(self,
                                        size=(250, -1),
                                        value="Lorem ipsum dolor sit amet")
        self.button_send = wx.Button(self, label="Send")
        self.subhorizontal_inputs3 = wx.BoxSizer()
        self.subhorizontal_inputs3.Add(self.message_label, 0, wx.RIGHT, 15)
        self.subhorizontal_inputs3.Add(self.message_text, 0, wx.RIGHT, 5)
        self.subhorizontal_inputs3.Add(self.button_send, 0, wx.RIGHT, 5)

        self.vertical_input_controls = wx.BoxSizer(wx.VERTICAL)
        self.vertical_input_controls.Add(self.subhorizontal_inputs1, 0,
                                         wx.BOTTOM, 15)
        self.vertical_input_controls.Add(self.subhorizontal_inputs2, 0,
                                         wx.BOTTOM, 5)
        self.vertical_input_controls.Add(self.subhorizontal_inputs3, 0,
                                         wx.BOTTOM, 5)

        self.button_task_event_loop = wx.Button(
            self, label="Start task - event loop")
        self.vertical_extras = wx.BoxSizer(wx.VERTICAL)
        self.vertical_extras.Add(self.button_task_event_loop, 0,
                                 wx.ALIGN_RIGHT)

        self.horizontal_input_controls = wx.BoxSizer()
        self.horizontal_input_controls.Add(self.vertical_input_controls, 2, 0,
                                           0)
        self.horizontal_input_controls.Add(self.vertical_extras, 1, 0, 0)

        # Main box
        self.vertical_main = wx.BoxSizer(wx.VERTICAL)
        self.vertical_main.Add(self.horizontal_text, 2, wx.EXPAND | wx.BOTTOM,
                               10)
        self.vertical_main.Add(self.horizontal_input_controls, 1, wx.LEFT, 10)
        self.SetSizerAndFit(self.vertical_main)

        # Binds and inits
        self.Bind(wx.EVT_BUTTON, self.on_click_button_task_event_loop,
                  self.button_task_event_loop)
        self.Bind(wx.EVT_BUTTON, self.on_click_button_open, self.button_open)
        self.Bind(wx.EVT_BUTTON, self.on_click_button_listen,
                  self.button_listen)
        self.Bind(wx.EVT_BUTTON, self.on_click_button_send, self.button_send)
        self.button_listen.Disable()
        self.textbox.AppendText('Panel created on thread: {}\n'.format(
            threading.current_thread().ident))

        self.udp_plugin = Plugin("notapplicable")
Esempio n. 30
0
 def get(self, key):
     try:
         plugin = Plugin(key)
     except DoesNotExist:
         abort(404)
     return {key: base64.b64encode(plugin.blob)}