Exemplo n.º 1
0
def processFile(incomepath, filename):
    """
    run processing in test mode
    """
    params = dict(incomepath=incomepath, filename=filename, mode='test')
    handlers = events.getEvents('file_added').getHandlerList()
    dbhandlers = Eventhandler.getEventhandlers(event='file_added')
    for handler in dbhandlers:  # db
        for hdl in handlers:
            if handler.handler == hdl[0]:
                #p = hdl[1]('file_added', params)
                params.update(hdl[1]('file_added', **params))
                res = []
                for p in handler.getParameterList():
                    try:
                        res.append(u'{}:{}'.format(p, params[p.split('.')[1]]))
                    except:
                        try:
                            if p.split(u'.')[1] in params.keys():
                                res = [u'{}:{}'.format(p, params[p.split('.')[1]])]
                            else:
                                res = [u'error: key not found - {}'.format(p.split('.')[1])]
                                params['error'] = u'error: key not found - {}'.format(p.split('.')[1])
                        except:
                            import traceback
                            print traceback.format_exc()
                if u'error' in params.keys():
                    signal.send('alarm', 'testupload_start', result=res, handler=handler.handler.split('.')[-1], protocol=params['time'][-1], error=params['error'])
                else:
                    signal.send('alarm', 'testupload_start', result=res, handler=handler.handler.split('.')[-1], protocol=params['time'][-1])
    signal.send('alarm', 'testupload_start', result='done')
    return params
Exemplo n.º 2
0
    def getInParameters(self):
        """
        Get list of all input-parameters of eventhandler

        :return: handler list
        """
        event = events.getEvents(self.event)
        if self.position < 2:
            return event.parameters
        elif self.position == '':
            if len(event.getHandlers()) > 0:
                hdl = event.getHandlers()[-1]
                return hdl.getParameterList() + event.parameters  # add event parameters
            else:
                return []
        else:
            for hdl in event.getHandlers():
                if hdl.position == self.position - 1:
                    #return [param.split('=')[0] for param in hdl.parameters.split('\r\n') if param.startswith('out.')]
                    return hdl.getParameterList() + event.parameters  # add event parameters
        return []
Exemplo n.º 3
0
def processFile(incomepath, filename):
    """
    run processing in test mode
    """
    params = dict(incomepath=incomepath, filename=filename, mode='test')
    handlers = events.getEvents('file_added').getHandlerList()
    dbhandlers = Eventhandler.getEventhandlers(event='file_added')
    from emonitor.extensions import db
    db.session.rollback()
    for handler in dbhandlers:  # db
        for hdl in handlers:
            if handler.handler == hdl[0]:
                res = []
                try:
                    params.update(hdl[1]('file_added', **params))
                except:
                    params.update({'error': u'<b>error in handler {}:</b><br/> <em>{}</em><br>'.format(hdl[0], traceback.format_exc().splitlines())})

                for p in handler.getParameterList():
                    try:
                        res.append(u'{}:\n{}'.format(p, params[p.split('.')[1]].strip()))
                    except:
                        try:
                            if p.split(u'.')[1] in params.keys():
                                res = [u'{}:\n{}\n'.format(p, params[p.split('.')[1]].strip())]
                            else:
                                with babel.app.test_request_context('/') as ctx:
                                    ctx.push()
                                    res = [u'<b style="color:red">{}</b><br>'.format(babel.gettext('alarm.testcontext.parametererror').format(p))]
                                    params['error'] = babel.gettext('alarm.handler.missing.parameter').format(p, babel.gettext(handler.handler))
                                    ctx.pop()
                        except:
                            signal.send('alarm', 'testupload_start', result='done')
                res = "\n".join(res)
                if u'error' in params.keys():
                    signal.send('alarm', 'testupload_start', result=res, handler=handler.handler.split('.')[-1], protocol=params['time'][-1], error=params['error'])
                else:
                    signal.send('alarm', 'testupload_start', result=res, handler=handler.handler.split('.')[-1], protocol=params['time'][-1])
    signal.send('alarm', 'testupload_start', result='done')
    return params
Exemplo n.º 4
0
def processFile(incomepath, filename):
    """
    run processing in test mode
    """
    params = dict(incomepath=incomepath, filename=filename, mode='test')
    handlers = events.getEvents('file_added').getHandlerList()
    dbhandlers = Eventhandler.getEventhandlers(event='file_added')
    from emonitor.extensions import db
    db.session.rollback()
    for handler in dbhandlers:  # db
        for hdl in handlers:
            if handler.handler == hdl[0]:
                res = []
                try:
                    params.update(hdl[1]('file_added', **params))
                except:
                    params.update({'error': u'<b>error in handler {}:</b><br/> <em>{}</em><br>'.format(hdl[0], traceback.format_exc().splitlines())})

                for p in handler.getParameterList():
                    try:
                        res.append(u'{}:{}'.format(p, params[p.split('.')[1]]))
                    except:
                        try:
                            if p.split(u'.')[1] in params.keys():
                                res = [u'{}:{}'.format(p, params[p.split('.')[1]])]
                            else:
                                res = [u'<b>error: key not found:</b> <em>{}</em><br>'.format(p.split('.')[1])]
                                if not params.get('error'):
                                    params['error'] = ""
                                params['error'] += u'<b>error: key not found</b> <em>{}</em><br>'.format(p.split('.')[1])
                        except:
                            signal.send('alarm', 'testupload_start', result='done')
                if u'error' in params.keys():
                    signal.send('alarm', 'testupload_start', result=res, handler=handler.handler.split('.')[-1], protocol=params['time'][-1], error=params['error'])
                else:
                    signal.send('alarm', 'testupload_start', result=res, handler=handler.handler.split('.')[-1], protocol=params['time'][-1])
    signal.send('alarm', 'testupload_start', result='done')
    return params
def getAdminData(self, **params):
    """
    Deliver admin content of module events (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'getparams':  # event handler parameter sub form
        event = events.getEvents(name=request.args.get('event'))
        if request.args.get('handler') != '':
            handler = [hdl for hdl in event.getHandlerList() if hdl[0] == request.args.get('handler')][0]  # defined
        else:
            return "- error, no handler given -"

        if request.args.get('id') != 'None':
            eventhandler = Eventhandler.getEventhandlers(request.args.get('id'))  # db
        else:
            eventhandler = Eventhandler(request.args.get('event'), '', '', '')  # db
            
        # previous parameters
        inparameters = eventhandler.getInParameters()
        return render_template('admin.events_data.html', handler=handler, eventhandler=eventhandler, inparameters=inparameters)

    return ""
def getAdminContent(self, **params):
    """
    Deliver admin content of module monitors

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args["module"].split("/")

    if len(module) == 1:  # monitor definition
        if request.method == "POST":
            if request.form.get("action") == "createmonitor":  # add monitor
                params.update(
                    {
                        "monitor": Monitor("", "", "", "", "", "", ""),
                        "orientations": ["monitors.landscape", "monitors.portrait"],
                    }
                )
                return render_template("admin.monitors_actions.html", **params)

            elif request.form.get("action") == "updatemonitors":  # save monitor
                if request.form.get("edit_id") != "None":  # update
                    monitor = Monitor.getMonitors(id=request.form.get("edit_id"))
                else:  # add monitor
                    monitor = Monitor("", "", "", "", "", "", "")
                    db.session.add(monitor)

                monitor.clientid = request.form.get("edit_clientid")
                monitor.name = request.form.get("edit_name")
                monitor.orientation = request.form.get("edit_orientation")
                monitor.resolutionx = request.form.get("edit_resolutionx")
                monitor.resolutiony = request.form.get("edit_resolutiony")
                monitor.formatx = request.form.get("edit_formatx")
                monitor.formaty = request.form.get("edit_formaty")
                db.session.commit()

            elif request.form.get("action").startswith("editmonitor_"):  # edit monitor
                params.update(
                    {
                        "monitor": Monitor.getMonitors(id=int(request.form.get("action").split("_")[-1])),
                        "orientations": ["monitors.landscape", "monitors.portrait"],
                    }
                )
                return render_template("admin.monitors_actions.html", **params)

            elif request.form.get("action").startswith("deletemonitor_"):  # delete monitor
                db.session.delete(Monitor.getMonitors(id=int(request.form.get("action").split("_")[-1])))
                db.session.commit()

            elif request.form.get("action").startswith("createlayout_"):  # layout edit
                mid = int(request.form.get("action").split("_")[-1])
                monitor = Monitor.getMonitors(id=int(request.form.get("action").split("_")[-1]))

                layouts = []
                usedtriggers = []
                for l in monitor.getLayouts():
                    if l.mid == monitor.id:
                        layouts.append(l)
                        usedtriggers.append(l.trigger)

                params.update(
                    {
                        "monitors": Monitor.getMonitors(),
                        "layout": MonitorLayout(mid, "", "", "", 0, 0, ""),
                        "layouts": layouts,
                        "triggers": events.getEvents(),
                        "usedtriggers": usedtriggers,
                        "monitor": Monitor.getMonitors(id=mid),
                        "widgets": current_app.blueprints["widget"].modules,
                    }
                )
                return render_template("admin.monitors.layout_actions.html", **params)

            elif request.form.get("action") == "updatelayout":  # update layout
                if request.form.get("edit_id") != "None":  # update
                    layout = MonitorLayout.getLayouts(id=request.form.get("edit_id"))

                else:  # add layout
                    layout = MonitorLayout("", "", "", "", "", "", "")
                    db.session.add(layout)

                layout.mid = request.form.get("edit_mid")
                layout.trigger = ";".join(sorted(request.form.getlist("edit_trigger")))
                layout.layout = request.form.get("edit_layout").split("\r\n")
                layout.theme = request.form.get("edit_theme")
                layout.mintime = request.form.get("edit_mintime")
                layout.maxtime = request.form.get("edit_maxtime")
                layout.nextid = request.form.get("edit_nextid")
                db.session.commit()

            elif request.form.get("action").startswith("editmonitorlayout_"):  # edit layout
                layout = MonitorLayout.getLayouts(id=int(request.form.get("action").split("_")[-1]))
                layouts = []
                usedtriggers = []
                for l in MonitorLayout.getLayouts(mid=layout.mid):
                    if l.id != layout.id:
                        layouts.append(l)
                        usedtriggers.extend(l.trigger.split(";"))
                params.update(
                    {
                        "monitors": Monitor.getMonitors(),
                        "layout": layout,
                        "layouts": layouts,
                        "triggers": events.getEvents(),
                        "usedtriggers": usedtriggers,
                        "monitor": Monitor.getMonitors(id=layout.mid),
                        "widgets": current_app.blueprints["widget"].modules,
                    }
                )
                return render_template("admin.monitors.layout_actions.html", **params)

            elif request.form.get("action").startswith("deletemonitorlayout_"):  # delete layout
                db.session.delete(MonitorLayout.getLayouts(id=int(request.form.get("action").split("_")[-1])))
                db.session.commit()

        params.update({"monitors": Monitor.getMonitors()})
        return render_template("admin.monitors.html", **params)

    else:
        if module[1] == "style":  # monitor styles

            themecss = {}
            for root, dirs, files in os.walk("%s/emonitor/frontend/web/css" % current_app.config.get("PROJECT_ROOT")):
                for name in [f for f in files if f.startswith("monitor_")]:
                    with open(
                        "%s/emonitor/frontend/web/css/%s" % (current_app.config.get("PROJECT_ROOT"), name), "r"
                    ) as c:
                        themecss[name.split("_")[-1][:-4]] = c.read()

            if request.method == "POST":
                if request.form.get("action") == "savecss":
                    for k in themecss:
                        if themecss[k] != request.form.get(k):
                            with open(
                                "%s/emonitor/frontend/web/css/monitor_%s.css"
                                % (current_app.config.get("PROJECT_ROOT"), k),
                                "w",
                            ) as c:
                                c.write(request.form.get(k))
                            themecss[k] = request.form.get(k)

                # check new theme data
                if request.form.get("newname") != "" and request.form.get("newcss") != "":
                    with open(
                        "%s/emonitor/frontend/web/css/monitor_%s.css"
                        % (current_app.config.get("PROJECT_ROOT"), request.form.get("newname")),
                        "w",
                    ) as c:
                        c.write(request.form.get("newcss"))
                    themecss[request.form.get("newname")] = request.form.get("newcss")

            params.update({"themes": themecss})
            return render_template("admin.monitors.style.html", **params)

        elif module[1] == "current":  # monitors current
            if request.method == "POST":
                pass
            params.update({"monitors": Monitor.getMonitors()})
            return render_template("admin.monitors.current.html", **params)

        elif module[1] == "actions":  # monitors actions
            return render_template("admin.monitors.actions.html", **params)

    return "else"
def getAdminContent(self, **params):
    """
    Deliver admin content of module events

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')
    
    if len(module) > 1:
        pass
        
    else:
        if request.method == 'POST':
            if request.form.get('action').startswith('edithandler_'):  # edit handler
                handler = Eventhandler.getEventhandlers(id=int(request.form.get('action').split('_')[-1]))  # handler defined in db
                handlers = events.getEvents(name=handler.event).getHandlerList()  # all possible handlers for given event
                params.update({'handler': handler, 'handlers': handlers})
                return render_template('admin.events_actions.html', **params)

            elif request.form.get('action').startswith('createhandler_'):  # add handler
                handler = Eventhandler(request.form.get('action').replace('createhandler_', ''), '', '', '')
                handlers = events.getEvents(name=handler.event).getHandlerList()  # all possible handlers for given event
                params.update({'handler': handler, 'handlers': handlers})
                return render_template('admin.events_actions.html', **params)

            elif request.form.get('action') == 'updateeventhandler':  # save handler
                if request.form.get('handler_id') != 'None':  # update
                    hdl = Eventhandler.getEventhandlers(id=request.form.get('handler_id'))
                    hdl.position = request.form.get('edit_position')
                
                else:  # add
                    existing = Eventhandler.getEventhandlers(event=request.form.get('edit_event'))
                    hdl = Eventhandler(request.form.get('edit_event'), '', '', '')
                    db.session.add(hdl)
                    hdl.position = len(existing) + 1
                    
                hdl.handler = request.form.get('edit_handler')
                hdl.parameters = ''
                for k in request.form.keys():
                    if k.startswith('check.in'):  # in parameters
                        if request.form.get(k) == "alternative":  # use alternative text field
                            hdl.parameters += '%s=%s\r\n' % (k[6:], request.form.get('in.' + k[9:]))
                        else:
                            hdl.parameters += '%s=%s\r\n' % (k[6:], request.form.get(k))  # use checkbox

                    elif k.startswith('check.out'):  # out parameters
                        if request.form.get(k) == "alternative":  # use alternative text field
                            hdl.parameters += '%s=%s\r\n' % (k[6:], request.form.get('out.' + k[10:]))
                        else:
                            hdl.parameters += '%s=%s\r\n' % (k[6:], request.form.get(k))  # use checkbox
                db.session.commit()

            elif request.form.get('action').startswith('deletehandler_'):  # delete handler
                handler = Eventhandler.getEventhandlers(id=int(request.form.get('action').split('_')[-1]))
                db.session.delete(handler)
                db.session.commit()
                
            elif request.form.get('action') == 'updateorder':  # update order of handlers/event
                for item in [i for i in request.form if i.startswith('position_')]:
                    ids = request.form.getlist(item)
                    for _id in ids:
                        hdl = Eventhandler.getEventhandlers(id=int(_id))
                        hdl.position = ids.index(_id) + 1
                db.session.commit()
        params.update({'events': events.getEvents(), 'definitions': len(Eventhandler.getEventhandlers())})
        return render_template('admin.events.html', **params)