def getAdminData(self):
    """
    Deliver admin content of module monitors (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get("action") == "thumb":  # create dynamic thumbnail of layout
        layout = MonitorLayout.getLayouts(id=request.args.get("id"))
        return layout.getLayoutThumb()

    if request.args.get("action") == "widgetparams":  # params: width, height, w_id,
        return render_template(
            "admin.monitors.actions.html",
            width=request.args.get("width"),
            height=request.args.get("height"),
            widget=request.args.get("w_id"),
        )  # macro='widgetparams'

    if request.args.get("action") == "ping":  # ping clients
        from emonitor.extensions import monitorserver

        clients = monitorserver.getClients()  # start discovery
        return dict(clients=[k for k in clients.keys() if clients[k][0]])

    if request.args.get("action") == "schedules":  # get active schedules
        return render_template(
            "admin.monitors.actions_actions.html", schedjobs=scheduler.get_jobs()
        )  # macro='schedjobs'

    return ""
Exemplo n.º 2
0
 def layout(self, layoutid):
     """
     Get MonitorLayout for given id
     :param layoutid: id as integer
     :return: :py:class:`emonitor.modules.monitors.monitorlayout.MonitorLayout`
     """
     l = MonitorLayout.getLayouts(id=int(layoutid))
     if l:
         return l
     else:  # deliver default layout
         return self.currentlayout
Exemplo n.º 3
0
 def layout(self, layoutid):
     """
     Get MonitorLayout for given id
     :param layoutid: id as integer
     :return: :py:class:`emonitor.modules.monitors.monitorlayout.MonitorLayout`
     """
     l = MonitorLayout.getLayouts(id=int(layoutid))
     if l:
         return l
     else:  # deliver default layout
         return self.currentlayout
Exemplo n.º 4
0
def getAdminData(self):
    """
    Deliver admin content of module monitors (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'thumb':  # create dynamic thumbnail of layout
        layout = MonitorLayout.getLayouts(id=request.args.get('id'))
        return layout.getLayoutThumb()
    
    if request.args.get('action') == 'widgetparams':  # params: width, height, w_id,
        return render_template('admin.monitors.actions.html', width=request.args.get('width'), height=request.args.get('height'), widget=request.args.get('w_id'))  # macro='widgetparams'
        
    if request.args.get('action') == 'ping':  # ping clients
        from emonitor.extensions import monitorserver
        clients = monitorserver.getClients()  # start discovery
        return dict(clients=[k for k in clients.keys() if clients[k][0]])

    if request.args.get('action') == 'schedules':  # get active schedules
        return render_template('admin.monitors.actions_actions.html', schedjobs=scheduler.get_jobs())  # macro='schedjobs'
        
    return ""
Exemplo n.º 5
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 ""
Exemplo n.º 6
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"
Exemplo n.º 8
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 ""