Ejemplo n.º 1
0
    def handleEvent(eventname, **kwargs):
        """
        Event handler for scripts class, adds own processing time

        :param eventname: *emonitor.modules.scripts.script.Script*
        :param kwargs: *time*
        :return: kwargs
        """
        stime = time.time()
        hdl = [
            hdl
            for hdl in Eventhandler.getEventhandlers(event=eventname)
            if hdl.handler == "emonitor.modules.scripts.script.Script"
        ]

        scriptname = ""
        if len(hdl) == 1:
            if "in.scriptname" in hdl[0].getParameterList("in"):
                scriptname = hdl[0].getParameterValue("in.scriptname")

        for m in Monitor.getMonitors():
            for l in m.getLayouts():
                if l.trigger == eventname:  # find client id for defined event
                    if "mode" in kwargs.keys() and kwargs["mode"] != "test":
                        monitorserver.sendMessage(str(m.id), "execute|%s" % scriptname)  # execute script on client

        if "time" not in kwargs[0]:
            kwargs["time"] = []
        kwargs["time"].append(u'scripts: script "{}" done in {} sec.'.format(scriptname, time.time() - stime))
        return kwargs
Ejemplo n.º 2
0
def getFrontendContent(**params):
    """
    Deliver frontend content of module messages

    :return: data of messages
    """
    if 'area' in request.args:
        params['area'] = request.args.get('area')

    if 'area' not in params:
        params['area'] = 'center'
    if 'activeacc' not in params:
        params['activeacc'] = 0

    if request.form.get('action') == 'updatemessage':
        sd = datetime.datetime.strptime('%s %s' % (request.form.get('messages.startdate'), '00:00:00'), "%d.%m.%Y %H:%M:%S")
        ed = datetime.datetime.strptime('%s %s' % (request.form.get('messages.enddate'), '23:59:59'), "%d.%m.%Y %H:%M:%S")
        if request.form.get('messages.id') != 'None':  # update message
            msg = Messages.getMessages(id=request.form.get('messages.id'))
            msg.startdate = sd
            msg.enddate = ed
        else:  # create new message
            msg = Messages('', '', sd, ed, 0, request.form.get('messages.type'))
            db.session.add(msg)
        msg.name = request.form.get('messages.name')
        msg.remark = request.form.get('messages.remark')
        msg.state = int(request.form.get('messages.state'))
        msg.monitors = request.form.getlist('messages.monitors')
        cron = dict(day_of_week='*', hour='*')
        if len(request.form.getlist('messages.cron.day_of_week')) > 0:
            cron['day_of_week'] = ",".join(request.form.getlist('messages.cron.day_of_week'))
        if len(request.form.getlist('messages.cron.hour')) > 0:
            cron['hour'] = ",".join(request.form.getlist('messages.cron.hour'))
        attributes = dict(cron=cron)

        # add type specific fields
        for fn in msg.type.getFieldNames():
            attributes[fn] = request.form.get('messages.' + fn)

        msg.attributes = attributes
        db.session.commit()
        Messages.updateMessageTrigger()

    elif request.args.get('action') == 'deletemessage':
        message = Messages.getMessages(id=int(request.args.get('messageid')))
        message.type.action(mid=message.id, action='delete')  # run delete action if implemented in module
        db.session.delete(message)
        db.session.commit()

    elif request.args.get('action') == 'editmessage':
        monitors = Monitor.getMonitors()
        if request.args.get('messageid', '0') == '0':  # add new message
            message = Messages('', '', datetime.datetime.now(), datetime.datetime.now(), 0, '')
            message.monitors = [str(m.id) for m in monitors]
        else:  # edit message
            message = Messages.getMessages(id=int(request.args.get('messageid')))
        return render_template('frontend.messages_edit.html', message=message, implementations=filter(lambda x: str(x[1]) != 'base', MessageType.getMessageTypes()), frontendarea=params['area'], frontendmodules=frontend.frontend.modules, frontendmoduledef=Settings.get('frontend.default'), monitors=monitors)

    messages = {'1': Messages.getMessages(state=1), '0': Messages.getMessages(state=0)}
    return render_template('frontend.messages_smallarea.html', messages=messages, frontendarea=params['area'], frontendmodules=frontend.frontend.modules, frontendmoduledef=Settings.get('frontend.default'), monitors=Monitor.getMonitors())
Ejemplo n.º 3
0
    def handleEvent(eventname, **kwargs):
        """
        Event handler for scripts class, adds own processing time

        :param eventname: *emonitor.modules.scripts.script.Script*
        :param kwargs: *time*
        :return: kwargs
        """
        stime = time.time()
        hdl = [hdl for hdl in Eventhandler.getEventhandlers(event=eventname) if hdl.handler == 'emonitor.modules.scripts.script.Script']

        scriptname = ""
        if len(hdl) == 1:
            if "in.scriptname" in hdl[0].getParameterList('in'):
                scriptname = hdl[0].getParameterValue("in.scriptname")

        for m in Monitor.getMonitors():
            for l in m.getLayouts():
                if l.trigger == eventname:  # find client id for defined event
                    if 'mode' in kwargs.keys() and kwargs['mode'] != 'test':
                        monitorserver.sendMessage(str(m.id), 'execute|%s' % scriptname)  # execute script on client
                    else:
                        logger.info('script started TESTMODE: %s' % scriptname)

        if 'time' not in kwargs.keys():
            kwargs['time'] = []
        kwargs['time'].append(u'scripts: script "{}" done in {} sec.'.format(scriptname, time.time() - stime))
        return kwargs
    def getClients(self):
        signal.send('monitorserver', 'clientsearchstart', clients=[])
        monitors = Monitor.getMonitors()
        message, results = self.sendMessageWithReturn('0', 'ping')

        clients = {}
        for res in results:
            _id = res['data'].split('|')[0]
            clients[_id] = [(res['from'][0], res['name'])]
            if _id not in [str(m.id) for m in monitors]:
                clients[_id].append(None)
        for monitor in monitors:
            if str(monitor.id) in clients.keys():
                clients[str(monitor.id)].append(monitor)
            else:
                clients[str(monitor.id)] = [None, monitor]
        MonitorServer.clients = {'clients': clients, 'time': datetime.datetime.now()}
        signal.send('monitorserver', 'clientsearchdone', clients=clients.keys())
        return clients
def getFrontendData(self):
    """
    Deliver frontend content of module monitors (ajax)

    :return: rendered template as string or json dict
    """
    from emonitor.extensions import monitorserver
    if request.args.get('action') == 'monitoroverview':
        return render_template('frontend.monitors.html', monitors=Monitor.getMonitors())

    elif request.args.get('action') == 'ping':  # search from monitors
        clients = monitorserver.getClients()  # start discovery
        return dict(clients=[k for k in clients.keys() if clients[k][0]])

    elif request.args.get('action') == 'changelayout':  # load monitorlayout
        #monitorserver.changeLayout(request.args.get('id'), request.args.get('layoutid'))
        monitorserver.changeLayout(request.args.get('id'), layoutid=request.args.get('layoutid'))  # TODO
        return ""
    return ""
Ejemplo n.º 6
0
    def getClients(self):
        """
        client search method collects answer of each client and delivers list.

        client answer syntax: | separated string - clientid|state|parameters
        """
        signal.send('monitorserver', 'clientsearchstart', clients=[])
        monitors = Monitor.getMonitors()
        message, results = self.sendMessageWithReturn('0', 'ping')

        clients = {}
        for res in results:
            _state = _id = ""
            _data = res['data'].split('|')
            print "data:", _data
            if _data[0]:
                _id = _data[0]
            if _data[1]:
                _state = _data[1]
            if len(_data) > 2:
                _params = _data[2:]
            else:
                _params = []
            if _state == 'initneed':
                self.sendMessage(_id, 'load')
            clients[_id] = [(res['from'][0], res['name'], _params)]
            if _id not in [str(m.id) for m in monitors]:
                clients[_id].append(None)
        for monitor in monitors:
            if str(monitor.id) in clients.keys():
                clients[str(monitor.id)].append(monitor)
            else:
                clients[str(monitor.id)] = [None, monitor]
        MonitorServer.clients = {
            'clients': clients,
            'time': datetime.datetime.now()
        }
        signal.send('monitorserver',
                    'clientsearchdone',
                    clients=clients.keys())
        return clients
Ejemplo n.º 7
0
def getFrontendData(self):
    """
    Deliver frontend content of module monitors (ajax)

    :return: rendered template as string or json dict
    """
    from emonitor.extensions import monitorserver
    if request.args.get('action') == 'monitoroverview':
        return render_template('frontend.monitors.html',
                               monitors=Monitor.getMonitors())

    elif request.args.get('action') == 'ping':  # search from monitors
        clients = monitorserver.getClients()  # start discovery
        return dict(clients=[k for k in clients.keys() if clients[k][0]])

    elif request.args.get('action') == 'changelayout':  # load monitorlayout
        #monitorserver.changeLayout(request.args.get('id'), request.args.get('layoutid'))
        monitorserver.changeLayout(
            request.args.get('id'),
            layoutid=request.args.get('layoutid'))  # TODO
        return ""
    return ""
Ejemplo n.º 8
0
    def getClients(self):
        """
        client search method collects answer of each client and delivers list.

        client answer syntax: | separated string - clientid|state|parameters
        """
        signal.send('monitorserver', 'clientsearchstart', clients=[])
        monitors = Monitor.getMonitors()
        message, results = self.sendMessageWithReturn('0', 'ping')

        clients = {}
        for res in results:
            _state = _id = ""
            _data = res['data'].split('|')
            print "data:", _data
            if _data[0]:
                _id = _data[0]
            if _data[1]:
                _state = _data[1]
            if len(_data) > 2:
                _params = _data[2:]
            else:
                _params = []
            if _state == 'initneed':
                self.sendMessage(_id, 'load')
            clients[_id] = [(res['from'][0], res['name'], _params)]
            if _id not in [str(m.id) for m in monitors]:
                clients[_id].append(None)
        for monitor in monitors:
            if str(monitor.id) in clients.keys():
                clients[str(monitor.id)].append(monitor)
            else:
                clients[str(monitor.id)] = [None, monitor]
        MonitorServer.clients = {'clients': clients, 'time': datetime.datetime.now()}
        signal.send('monitorserver', 'clientsearchdone', clients=clients.keys())
        return clients
Ejemplo n.º 9
0
def getFrontendData(self):
    """
    Deliver frontend content of module alarms (ajax)

    :return: rendered template as string or json dict
    """
    from emonitor.extensions import monitorserver

    if "download" in request.path:  # deliver file
        with open('{}{}'.format(current_app.config.get('PATH_TMP'), request.path.split('download/')[-1]), 'rb') as data:
            si = StringIO.StringIO(data.read()).getvalue()
            output = make_response(si)
        if request.path.split('/')[-1].startswith('temp'):  # remove if filename starts with temp == temporary file
            os.remove('{}{}'.format(current_app.config.get('PATH_TMP'), request.path.split('download/')[-1]))
        output.headers["Content-Disposition"] = "attachment; filename=report.{}".format(request.path.split('.')[-1])
        output.headers["Content-type"] = "application/x.download"
        return output

    if request.args.get('action') == 'editalarm':
        
        if request.args.get('alarmid', '0') == '0':  # add new alarm
            alarm = Alarm(datetime.datetime.now(), '', 2, 0)

        else:  # edit alarm
            alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        return render_template('frontend.alarms_edit.html', alarm=alarm, cities=City.getCities(), objects=AlarmObject.getAlarmObjects(), cars=Car.getCars(), frontendarea=request.args.get('frontendarea'))

    elif request.args.get('action') == 'alarmmonitor':  # send alarm to monitor
        for monitor in Monitor.getMonitors():
            scheduler.deleteJobForEvent('changeLayout')  # send update to monitors
            for l in MonitorLayout.getLayouts(mid=int(monitor.id)):
                if l.trigger == 'alarm_added':
                    #monitorserver.sendMessage(str(monitor.id), 'load', ['layoutid=%s' % l.id, 'alarmid=%s' % request.args.get('alarmid')])  TODO changed from list
                    monitorserver.sendMessage(str(monitor.id), 'load', layoutid=l.id, alarmid=request.args.get('alarmid'))

    elif request.args.get('action') == 'printalarm':
        Printers.getPrinters(pid=int(request.args.get('printerdef'))).doPrint(object=Alarm.getAlarms(id=int(request.args.get('alarmid'))), id=request.args.get('alarmid'), copies=1)
        return ""

    elif request.args.get('action') == 'routeinfo':
        return render_template('frontend.alarms_routing.html', routing=Alarm.getAlarms(id=request.args.get('alarmid')).getRouting())

    elif request.args.get('action') == 'routecoords':
        return jsonify(Alarm.getAlarms(id=request.args.get('alarmid')).getRouting())

    elif request.args.get('action') == 'message':
        return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms(id=request.args.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area'), reload=request.args.get('reload', 'true'))

    elif request.args.get('action') == 'addmessage':  # add message
        if request.form.get('messagetext') != "":
            alarm = Alarm.getAlarms(request.form.get('alarmid'))
            alarm.addHistory(request.form.get('messagestate'), request.form.get('messagetext'))
            db.session.commit()
        return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms(request.form.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area'))

    elif request.args.get('action') == 'deletemessage':  # delete selected message
        alarm = Alarm.getAlarms(request.args.get('alarmid'))
        for msg in alarm.history:
            if str(msg.timestamp) == request.args.get('datetime'):
                db.session.delete(msg)
        db.session.commit()
        return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms(request.args.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area'))

    elif request.args.get('action') == 'housecoordinates':  # return a dict with coordinats of housenumber
        if request.args.get('alarmid') != "None":
            alarm = Alarm.getAlarms(id=int(request.args.get('alarmid')))
            if alarm and alarm.housenumber:
                return {'lat': map(lambda x: x[0], alarm.housenumber.points), 'lng': map(lambda x: x[1], alarm.housenumber.points)}
        return []

    elif request.args.get('action') == 'evalhouse':  # try to eval housenumer
        street = Street.getStreets(id=request.args.get('streetid'))
        if street:
            points = dict(lat=[], lng=[])
            for hn in street.housenumbers:
                if str(hn.number) == request.args.get('housenumber').strip():
                    points['lat'].extend(map(lambda x: x[0], hn.points))
                    points['lng'].extend(map(lambda x: x[1], hn.points))
            return points
        return {}

    elif request.args.get('action') == 'alarmsforstate':  # render alarms for given state
        if 'alarmfilter' not in session:
            session['alarmfilter'] = 7
        return render_template('frontend.alarms_alarm.html', alarms=Alarm.getAlarms(days=int(session['alarmfilter']), state=int(request.args.get('state', '-1'))), printdefs=Printers.getActivePrintersOfModule('alarms'))

    elif request.args.get('action') == 'collective':  # render collective form
        reports = [r for r in AlarmReport.getReports() if r.reporttype.multi]
        if len(reports) == 0:
            return ""
        return render_template('frontend.alarms_collective.html', alarms=Alarm.getAlarms(state=2), reports=reports)

    elif request.args.get('action') == 'docollective':  # build collective form
        if request.args.get('ids') == "":
            ids = []
        else:
            ids = request.args.get('ids').split(',')
        f = AlarmReport.getReports(request.args.get('form')).createReport(ids=ids)
        _path, _filename = os.path.split(f)
        shutil.move(f, "{}{}".format(current_app.config.get('PATH_TMP'), _filename))
        return _filename

    elif request.args.get('action') == 'alarmpriocars':  # show prio cars
        cars = []
        c = Settings.getIntList('alarms.spc_cars.{}'.format(request.args.get('state')))
        if len(c) == 0:
            return ""
        for alarm in Alarm.getAlarms(state=request.args.get('state')):
            cars.extend([car for car in alarm.cars1 if car.id in c])
        cars = Counter(cars)
        return render_template('frontend.alarms_cars.html', cars=cars)

    elif request.args.get('action') == 'showdetailsform':  # build alarmdetails edtit form
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        if alarm.street.city:
            fields = AlarmField.getAlarmFields(dept=alarm.street.city.dept)
        else:
            fields = AlarmField.getAlarmFields(dept=Department.getDefaultDepartment().id)
        return render_template('frontend.alarms_fields.html', alarm=alarm, fields=fields, reports=AlarmReport.getReports())

    elif request.args.get('action') == 'saveextform':  # store ext-form values
        alarm = Alarm.getAlarms(id=request.form.get('alarmid'))
        for field in AlarmField.getAlarmFields(dept=alarm.street.city.dept):
            field.saveForm(request, alarm)
        db.session.commit()

    return ""
Ejemplo n.º 10
0
def monitorContent(clientid=0):
    """
    Create monitor area under url */monitor*

    :return: rendered template */emonitor/monitor/templates/monitor.html*
    """
    alarmid = None
    footer = 0
    count = []
    pos = 0

    if 'alarmid' in request.args:  # eval active alarms or defined id
        alarmid = int(request.args.get('alarmid'))
        if len(Alarm.getActiveAlarms()) > 0:
            count = Alarm.getActiveAlarms()
    elif len(Alarm.getActiveAlarms()) > 0:
        alarmid = Alarm.getActiveAlarms()[0].id
        count = Alarm.getActiveAlarms()
    alarm = Alarm.getAlarms(id=alarmid)

    defmonitor = Monitor.getMonitors(clientid=int(clientid))
    try:
        layout = defmonitor.currentlayout
    except AttributeError:
        return render_template('monitor-test.html')

    if 'layoutid' in request.args:  # eval current layout
        layout = defmonitor.layout(int(request.args.get('layoutid')))
    else:
        try: layout = defmonitor.getLayouts(triggername='default')[0]
        except: pass

    if len(count) > 0:  # eval layout for current and next alarm
        footer = 1
        nextalarm = currentalarm = count[0]
        for c in count:
            if c.id == alarmid:
                pos = count.index(c) + 1
                currentalarm = count[(pos - 1) % len(count)]
                nextalarm = count[pos % len(count)]

            for j in [job for job in scheduler.get_jobs(name='changeLayout') if "'alarmid', %s" % c.id in str(job.args)]:
                scheduler.remove_job(j.id)  # layout changes for given alarm

        for l in defmonitor.getLayouts(triggername='alarm_added'):
            for tr in l.trigger.split(';'):  # support more than one trigger for layout
                if ('.' in tr and len(count) >= 1 and tr.split('.')[-1] == currentalarm.get('alarmtype')) or ('.' not in tr and currentalarm.get('alarmtype', '') == ""):
                    layout = l
                    break

        if len(count) > 1:
            for l in defmonitor.getLayouts(triggername='alarm_added'):
                for tr in l.trigger.split(';'):  # support more than one trigger for layout
                    if ('.' in tr and tr.split('.')[-1] == nextalarm.get('alarmtype')) or ('.' not in tr and nextalarm.get('alarmtype', '') == ""):
                        if int(l.mintime) != 0:
                            #scheduler.add_job(monitorserver.changeLayout, next_run_time=datetime.datetime.fromtimestamp(time.time() + float(l.mintime)), args=[defmonitor.clientid, l.id, [('alarmid', nextalarm.id), ('monitorid', defmonitor.id)]])
                            scheduler.add_job(monitorserver.changeLayout, next_run_time=datetime.datetime.fromtimestamp(time.time() + float(l.mintime)), args=[defmonitor.clientid, l.id], kwargs=dict(alarmid=nextalarm.id))  # TODO

    # render content for monitor
    content = '<div id="content">%s</div>' % layout.htmllayout
    for w in re.findall('\[\[\s?(.+?)\s?\]\]', content):
        for widgets in current_app.blueprints['widget'].modules:
            for widget in widgets.getMonitorWidgets():
                if widget.getName() == w:
                    params = widget.addParameters(alarmid=alarmid, alarm=alarm, clientid=clientid, layout=layout)
                    if params and 'footer' in params and params['footer'] == 1:
                        footer = 1
                    content = content.replace(u'[[%s]]' % w, widget.getHTML(request))

    return render_template('monitor.html', content=content, clientid=clientid, theme=layout.theme, activecount=len(count), footer=footer, position=pos, app_name=current_app.config.get('PROJECT'), app_version=current_app.config.get('APP_VERSION'))
Ejemplo n.º 11
0
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 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"
Ejemplo n.º 13
0
def getFrontendData(self):
    """
    Deliver frontend content of module alarms (ajax)

    :return: rendered template as string or json dict
    """
    from emonitor.extensions import monitorserver

    if "download" in request.path:  # deliver file
        with open(
                '{}{}'.format(current_app.config.get('PATH_TMP'),
                              request.path.split('download/')[-1]),
                'rb') as data:
            si = StringIO.StringIO(data.read()).getvalue()
            output = make_response(si)
        if request.path.split('/')[-1].startswith(
                'temp'
        ):  # remove if filename starts with temp == temporary file
            os.remove('{}{}'.format(current_app.config.get('PATH_TMP'),
                                    request.path.split('download/')[-1]))
        output.headers[
            "Content-Disposition"] = "attachment; filename=report.{}".format(
                request.path.split('.')[-1])
        output.headers["Content-type"] = "application/x.download"
        return output

    if request.args.get('action') == 'editalarm':

        if request.args.get('alarmid', '0') == '0':  # add new alarm
            alarm = Alarm(datetime.datetime.now(), '', 2, 0)

        else:  # edit alarm
            alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        return render_template('frontend.alarms_edit.html',
                               alarm=alarm,
                               cities=City.getCities(),
                               objects=AlarmObject.getAlarmObjects(),
                               cars=Car.getCars(),
                               frontendarea=request.args.get('frontendarea'))

    elif request.args.get('action') == 'alarmmonitor':  # send alarm to monitor
        for monitor in Monitor.getMonitors():
            scheduler.deleteJobForEvent(
                'changeLayout')  # send update to monitors
            for l in MonitorLayout.getLayouts(mid=int(monitor.id)):
                if l.trigger == 'alarm_added':
                    #monitorserver.sendMessage(str(monitor.id), 'load', ['layoutid=%s' % l.id, 'alarmid=%s' % request.args.get('alarmid')])  TODO changed from list
                    monitorserver.sendMessage(
                        str(monitor.id),
                        'load',
                        layoutid=l.id,
                        alarmid=request.args.get('alarmid'))

    elif request.args.get('action') == 'printalarm':
        Printers.getPrinters(pid=int(request.args.get('printerdef'))).doPrint(
            object=Alarm.getAlarms(id=int(request.args.get('alarmid'))),
            id=request.args.get('alarmid'),
            copies=1)
        return ""

    elif request.args.get('action') == 'routeinfo':
        return render_template(
            'frontend.alarms_routing.html',
            routing=Alarm.getAlarms(
                id=request.args.get('alarmid')).getRouting())

    elif request.args.get('action') == 'routecoords':
        return jsonify(
            Alarm.getAlarms(id=request.args.get('alarmid')).getRouting())

    elif request.args.get('action') == 'message':
        return render_template(
            'frontend.alarms_message.html',
            alarm=Alarm.getAlarms(id=request.args.get('alarmid')),
            messagestates=AlarmHistory.historytypes,
            area=request.args.get('area'),
            reload=request.args.get('reload', 'true'))

    elif request.args.get('action') == 'addmessage':  # add message
        if request.form.get('messagetext') != "":
            alarm = Alarm.getAlarms(request.form.get('alarmid'))
            alarm.addHistory(request.form.get('messagestate'),
                             request.form.get('messagetext'))
            db.session.commit()
        return render_template('frontend.alarms_message.html',
                               alarm=Alarm.getAlarms(
                                   request.form.get('alarmid')),
                               messagestates=AlarmHistory.historytypes,
                               area=request.args.get('area'))

    elif request.args.get(
            'action') == 'deletemessage':  # delete selected message
        alarm = Alarm.getAlarms(request.args.get('alarmid'))
        for msg in alarm.history:
            if str(msg.timestamp) == request.args.get('datetime'):
                db.session.delete(msg)
        db.session.commit()
        return render_template('frontend.alarms_message.html',
                               alarm=Alarm.getAlarms(
                                   request.args.get('alarmid')),
                               messagestates=AlarmHistory.historytypes,
                               area=request.args.get('area'))

    elif request.args.get(
            'action'
    ) == 'housecoordinates':  # return a dict with coordinats of housenumber
        if request.args.get('alarmid') != "None":
            alarm = Alarm.getAlarms(id=int(request.args.get('alarmid')))
            if alarm and alarm.housenumber:
                return {
                    'lat': map(lambda x: x[0], alarm.housenumber.points),
                    'lng': map(lambda x: x[1], alarm.housenumber.points)
                }
        return []

    elif request.args.get('action') == 'evalhouse':  # try to eval housenumer
        street = Street.getStreets(id=request.args.get('streetid'))
        if street:
            points = dict(lat=[], lng=[])
            for hn in street.housenumbers:
                if str(hn.number) == request.args.get('housenumber').strip():
                    points['lat'].extend(map(lambda x: x[0], hn.points))
                    points['lng'].extend(map(lambda x: x[1], hn.points))
            return points
        return {}

    elif request.args.get(
            'action') == 'alarmsforstate':  # render alarms for given state
        if 'alarmfilter' not in session:
            session['alarmfilter'] = 7
        return render_template(
            'frontend.alarms_alarm.html',
            alarms=Alarm.getAlarms(days=int(session['alarmfilter']),
                                   state=int(request.args.get('state', '-1'))),
            printdefs=Printers.getActivePrintersOfModule('alarms'))

    elif request.args.get('action') == 'collective':  # render collective form
        reports = [r for r in AlarmReport.getReports() if r.reporttype.multi]
        if len(reports) == 0:
            return ""
        return render_template('frontend.alarms_collective.html',
                               alarms=Alarm.getAlarms(state=2),
                               reports=reports)

    elif request.args.get('action') == 'docollective':  # build collective form
        if request.args.get('ids') == "":
            ids = []
        else:
            ids = request.args.get('ids').split(',')
        f = AlarmReport.getReports(
            request.args.get('form')).createReport(ids=ids)
        _path, _filename = os.path.split(f)
        shutil.move(
            f, "{}{}".format(current_app.config.get('PATH_TMP'), _filename))
        return _filename

    elif request.args.get('action') == 'alarmpriocars':  # show prio cars
        cars = []
        c = Settings.getIntList('alarms.spc_cars.{}'.format(
            request.args.get('state')))
        if len(c) == 0:
            return ""
        for alarm in Alarm.getAlarms(state=request.args.get('state')):
            cars.extend([car for car in alarm.cars1 if car.id in c])
        cars = Counter(cars)
        return render_template('frontend.alarms_cars.html', cars=cars)

    elif request.args.get(
            'action') == 'showdetailsform':  # build alarmdetails edtit form
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        if alarm.street.city:
            fields = AlarmField.getAlarmFields(dept=alarm.street.city.dept)
        else:
            fields = AlarmField.getAlarmFields(
                dept=Department.getDefaultDepartment().id)
        return render_template('frontend.alarms_fields.html',
                               alarm=alarm,
                               fields=fields,
                               reports=AlarmReport.getReports())

    elif request.args.get('action') == 'saveextform':  # store ext-form values
        alarm = Alarm.getAlarms(id=request.form.get('alarmid'))
        for field in AlarmField.getAlarmFields(dept=alarm.street.city.dept):
            field.saveForm(request, alarm)
        db.session.commit()

    return ""