Example #1
0
 def export_static(filename):
     filename, extension = os.path.splitext(filename)
     try:
         id, template = filename.split('-')
         if extension not in ['.pdf', '.html', '.png']:
             abort(404)
         elif extension == '.pdf':
             return Response(Module.getPdf(
                 Alarm.getExportData('.html',
                                     id=id,
                                     style=template,
                                     args=request.args)),
                             mimetype="application/pdf")
         elif extension == '.html':
             return Response(Alarm.getExportData(extension,
                                                 id=id,
                                                 style=template,
                                                 args=request.args),
                             mimetype="text/html")
         elif extension == '.png':
             return Response(Alarm.getExportData(extension,
                                                 id=id,
                                                 style=template,
                                                 filename=filename,
                                                 args=request.args),
                             mimetype="image/png")
     except ValueError:
         return abort(404)
Example #2
0
 def export_static(filename):
     filename, extension = os.path.splitext(filename)
     try:
         id, template = filename.split('-')
         if extension not in ['.pdf', '.html', '.png']:
             abort(404)
         elif extension == '.pdf':
             return Response(Module.getPdf(Alarm.getExportData('.html', id=id, style=template, args=request.args)), mimetype="application/pdf")
         elif extension == '.html':
             return Response(Alarm.getExportData(extension, id=id, style=template, args=request.args), mimetype="text/html")
         elif extension == '.png':
             return Response(Alarm.getExportData(extension, id=id, style=template, filename=filename, args=request.args), mimetype="image/png")
     except ValueError:
         return abort(404)
Example #3
0
    def handleEvent(eventname, **kwargs):
        hdl = [hdl for hdl in Eventhandler.getEventhandlers(event=eventname) if hdl.handler == 'emonitor.communication.Communication'][0]
        if hdl:
            from emonitor.extensions import communication
            params = {}
            for p in hdl.getParameterValues('in'):
                params[p[0].split('.')[-1]] = p[1]
            if params["sendertype"] == 'telegram':
                for group, members in Settings.getYaml('telegramsettings').__dict__['groups'].items():
                    if group == params['group']:
                        from telegram import InlineKeyboardMarkup, InlineKeyboardButton
                        args = {'id': int(kwargs.get('alarmid')), 'style': params['style'], 'addressees': members[:-1], 'keyboard': InlineKeyboardMarkup, 'button': InlineKeyboardButton}
                        attrs = Alarm.getExportData('telegram', **args)
                        for member in members[:-1]:
                            if params['id'] == 'alarmid':  # send alarm details with location
                                try:
                                    if params.get('style') in ['text', 'details']:
                                        communication.telegram.sendMessage(member, attrs['details'], reply_markup=attrs['reply'])
                                    elif params.get('style') == 'venue':
                                        communication.telegram.sendVenue(member, attrs['text'], lat=attrs['lat'], lng=attrs['lng'], address=attrs['address'], reply_markup=attrs['reply'])
                                except:
                                    print "error handleEvent"
                                return kwargs

            elif params["sendertype"] == 'mailer':
                # TODO: implement mail notification
                pass

        return kwargs
Example #4
0
        def link_callback(uri, rel):
            """
            Callback method for links

            :param uri:
            :param rel:
            :return: fixed string for link
            """
            if '/export/' in uri and not rel:  # create tmp-files for export items
                if "/alarms/" in uri and uri.endswith('png'):
                    f, ext = os.path.splitext(uri)
                    from emonitor.modules.alarms.alarm import Alarm
                    fname = '{}{}'.format(current_app.config.get('PATH_TMP'),
                                          '{}.png'.format(random.random()))
                    with open(fname, 'wb') as tmpimg:  # write tmp image file
                        tmpimg.write(
                            Alarm.getExportData(
                                '.png',
                                style=uri.split('-')[1][:-4],
                                id=f.split('/')[-1].split('-')[0]))
                        images.append(fname)
                    return fname
            return "%s/emonitor/modules%s" % (
                current_app.config.get('PROJECT_ROOT'), uri
            )  # make absolute links
def getFrontendData(self):
    """
    Deliver frontend content of module streets (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'streetcoords':  # get map parameter for given streetid

        if request.args.get('id') not in ['', 'None']:
            street = Street.getStreets(id=request.args.get('id'))
            return {'lat': street.lat, 'lng': street.lng, 'zoom': street.zoom, 'way': street.navigation,
                    'cityid': street.cityid, 'cityname': street.city.name}

    elif request.args.get('action') == 'housecoords':  # deliver center of housenumbers
        if request.args.get('streetid') != '' and request.args.get('housenumber') != '':
            street = Street.getStreet(id=request.args.get('streetid'))
            hnumber = street.getHouseNumber(number=request.args.get('housenumber').split()[0])
            if hnumber:
                return hnumber.getPosition(0)

            return {'lat': street.lat, 'lng': street.lng}
        return {}

    elif request.args.get('action') == 'defaultposition':

        return {'defaultlat': float(Settings.get('defaultLat')),
                'defaultlng': float(Settings.get('defaultLng')),
                'defaultzoom': int(Settings.get('defaultZoom'))}

    elif request.args.get('action') == 'alarmposition':
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        if alarm:
            return {'id': request.args.get('alarmid'), 'alarmlat': alarm.lat, 'alarmlng': alarm.lng,
                    'alarmzoom': alarm.zoom, 'marker': alarm.marker, 'alarmprio': alarm.priority,
                    'alarmstreet': alarm.street.name, 'alarmstreetno': alarm.get('streetno'),
                    'alarmstreet2': alarm.get('address2'), 'alarmcity': alarm.city.name,
                    'alarmsubcity': alarm.street.subcity}
        else:
            return {'id': '0'}

    elif request.args.get('action') == 'streetslookup':
        streets = {}
        cities = {}
        for c in City.getCities():
            cities[c.id] = c.name
            for k, street in c.streets.iteritems():
                if street.active:
                    try:
                        streets[str(street.id)] = '%s (%s)' % (street.name, c.name)
                    except:
                        streets[str(street.id)] = '%s (-%s-)' % (street.name, street.cityid)
        return streets

    elif request.args.get('action') == 'defaultmap':
        dmap = Map.getDefaultMap()
        return {'tileserver': dmap.tileserver, 'name': dmap.name}

    return ""
Example #6
0
    def handleEvent(eventname, **kwargs):
        from emonitor.extensions import scheduler

        if eventname == "client_income":
            return kwargs
        params = dict()

        try:
            hdl = [
                hdl for hdl in Eventhandler.getEventhandlers(event=eventname)
                if hdl.handler == 'emonitor.monitorserver.MonitorServer'
            ][0]

            for p in [
                    v[1] for v in hdl.getParameterValues('in') if v[1] != ''
            ]:  # required parameters for method
                if p in kwargs:
                    params[p] = kwargs[p]
        except:
            hdl = []
            logger.error('handleEvent: {}'.format(traceback.format_exc()))

        if kwargs['mode'] != 'test':
            for monitorlayout in MonitorLayout.getLayouts():
                try:
                    if monitorlayout.trigger == eventname:
                        for p in hdl.getParameterValues('in'):
                            if p[0] == 'in.condition' and p[
                                    1] == '!activealarm':
                                if Alarm.getActiveAlarms().count() == 0:
                                    MonitorServer.changeLayout(
                                        monitorlayout.monitor.clientid,
                                        monitorlayout.id, **params)

                        scheduler.deleteJobForEvent('changeLayout')
                        MonitorServer.changeLayout(
                            monitorlayout.monitor.clientid, monitorlayout.id,
                            **params)
                        if monitorlayout.nextid != 0:
                            scheduler.add_job(
                                MonitorServer.changeLayout,
                                next_run_time=datetime.datetime.fromtimestamp(
                                    time.time() + monitorlayout.maxtime),
                                args=[
                                    monitorlayout.monitor.clientid,
                                    monitorlayout.nextid, params
                                ])
                except:
                    pass
                finally:
                    pass

        if 'time' not in kwargs.keys():
            kwargs['time'] = []
        kwargs['time'].append('monitorserver: message sent')
        return kwargs
Example #7
0
    def handleEvent(eventname, **kwargs):
        hdl = [
            hdl for hdl in Eventhandler.getEventhandlers(event=eventname)
            if hdl.handler == 'emonitor.communication.Communication'
        ][0]
        if hdl:
            from emonitor.extensions import communication
            params = {}
            for p in hdl.getParameterValues('in'):
                params[p[0].split('.')[-1]] = p[1]
            if params["sendertype"] == 'telegram':
                for group, members in Settings.getYaml(
                        'telegramsettings').__dict__['groups'].items():
                    if group == params['group']:
                        from telegram import InlineKeyboardMarkup, InlineKeyboardButton
                        args = {
                            'id': int(kwargs.get('alarmid')),
                            'style': params['style'],
                            'addressees': members[:-1],
                            'keyboard': InlineKeyboardMarkup,
                            'button': InlineKeyboardButton
                        }
                        attrs = Alarm.getExportData('telegram', **args)
                        for member in members[:-1]:
                            if params[
                                    'id'] == 'alarmid':  # send alarm details with location
                                try:
                                    if params.get('style') in [
                                            'text', 'details'
                                    ]:
                                        communication.telegram.sendMessage(
                                            member,
                                            attrs['details'],
                                            reply_markup=attrs['reply'])
                                    elif params.get('style') == 'venue':
                                        communication.telegram.sendVenue(
                                            member,
                                            attrs['text'],
                                            lat=attrs['lat'],
                                            lng=attrs['lng'],
                                            address=attrs['address'],
                                            reply_markup=attrs['reply'])
                                except:
                                    print "error handleEvent"
                                return kwargs

            elif params["sendertype"] == 'mailer':
                # TODO: implement mail notification
                pass

        return kwargs
Example #8
0
        def link_callback(uri, rel):
            """
            Callback method for links

            :param uri:
            :param rel:
            :return: fixed string for link
            """
            if '/export/' in uri and not rel:  # create tmp-files for export items
                if "/alarms/" in uri and uri.endswith('png'):
                    f, ext = os.path.splitext(uri)
                    from emonitor.modules.alarms.alarm import Alarm
                    fname = '{}{}'.format(current_app.config.get('PATH_TMP'), '{}.png'.format(random.random()))
                    with open(fname, 'wb') as tmpimg:  # write tmp image file
                        tmpimg.write(Alarm.getExportData('.png', style=uri.split('-')[1][:-4], id=f.split('/')[-1].split('-')[0]))
                        images.append(fname)
                    return fname
            return "%s/emonitor/modules%s" % (current_app.config.get('PROJECT_ROOT'), uri)  # make absolute links
Example #9
0
    def msg_responder(bot, update, **kwargs):
        """
        Responder for incoming messages
        :param bot:
        :param update:
        :param kwargs:
        """
        if update.callback_query.data.startswith('file_'):  # send file
            bot.sendDocument(update.callback_query.message.chat_id, open(TelegramBot.app.config.get('PATH_DONE') + update.callback_query.data.split('_')[-1], 'rb'), 'details.pdf', 'details')

        elif update.callback_query.data.startswith('details_'):  # details_[type]_[id]
            if update.callback_query.data.split('_')[1] == 'alarm':
                from telegram import InlineKeyboardMarkup, InlineKeyboardButton
                args = {'id': int(update.callback_query.data.split('_')[-1]), 'style': 'details', 'addressees': [update.callback_query.message.chat_id], 'keyboard': InlineKeyboardMarkup, 'button': InlineKeyboardButton}
                attrs = Alarm.getExportData('telegram', **args)
                for addressee in [update.callback_query.message.chat_id]:
                    bot.sendMessage(addressee, attrs['details'], reply_markup=attrs['reply'], parse_mode='Markdown')
                return

        elif update.callback_query.data.startswith('location_'):
            bot.sendLocation(update.callback_query.message.chat_id, update.callback_query.data.split('_')[1], update.callback_query.data.split('_')[2])
Example #10
0
    def msg_responder(bot, update, **kwargs):
        """
        Responder for incoming messages
        :param bot:
        :param update:
        :param kwargs:
        """
        if update.callback_query.data.startswith('file_'):  # send file
            bot.sendDocument(
                update.callback_query.message.chat_id,
                open(
                    TelegramBot.app.config.get('PATH_DONE') +
                    update.callback_query.data.split('_')[-1], 'rb'),
                'details.pdf', 'details')

        elif update.callback_query.data.startswith(
                'details_'):  # details_[type]_[id]
            if update.callback_query.data.split('_')[1] == 'alarm':
                from telegram import InlineKeyboardMarkup, InlineKeyboardButton
                args = {
                    'id': int(update.callback_query.data.split('_')[-1]),
                    'style': 'details',
                    'addressees': [update.callback_query.message.chat_id],
                    'keyboard': InlineKeyboardMarkup,
                    'button': InlineKeyboardButton
                }
                attrs = Alarm.getExportData('telegram', **args)
                for addressee in [update.callback_query.message.chat_id]:
                    bot.sendMessage(addressee,
                                    attrs['details'],
                                    reply_markup=attrs['reply'],
                                    parse_mode='Markdown')
                return

        elif update.callback_query.data.startswith('location_'):
            bot.sendLocation(update.callback_query.message.chat_id,
                             update.callback_query.data.split('_')[1],
                             update.callback_query.data.split('_')[2])
Example #11
0
    def handleEvent(eventname, **kwargs):
        from emonitor.extensions import scheduler

        if eventname == "client_income":
            return kwargs
        params = dict()
        
        try:
            hdl = [hdl for hdl in Eventhandler.getEventhandlers(event=eventname) if hdl.handler == 'emonitor.monitorserver.MonitorServer'][0]
            
            for p in [v[1] for v in hdl.getParameterValues('in') if v[1] != '']:  # required parameters for method
                if p in kwargs:
                    params[p] = kwargs[p]
        except:
            hdl = []
            logger.error('handleEvent: {}'.format(traceback.format_exc()))

        if kwargs['mode'] != 'test':
            for monitorlayout in MonitorLayout.getLayouts():
                try:
                    if monitorlayout.trigger == eventname:
                        for p in hdl.getParameterValues('in'):
                            if p[0] == 'in.condition' and p[1] == '!activealarm':
                                if Alarm.getActiveAlarms().count() == 0:
                                    MonitorServer.changeLayout(monitorlayout.monitor.clientid, monitorlayout.id, **params)

                        scheduler.deleteJobForEvent('changeLayout')
                        MonitorServer.changeLayout(monitorlayout.monitor.clientid, monitorlayout.id, **params)
                        if monitorlayout.nextid != 0:
                            scheduler.add_job(MonitorServer.changeLayout, next_run_time=datetime.datetime.fromtimestamp(time.time() + monitorlayout.maxtime), args=[monitorlayout.monitor.clientid, monitorlayout.nextid, params])
                except:
                    pass
                finally: pass
        
        if 'time' not in kwargs.keys():
            kwargs['time'] = []
        kwargs['time'].append('monitorserver: message sent')
        return kwargs
Example #12
0
def getFrontendContent(**params):
    """
    Deliver frontend content of module alarms

    :return: data of alarms
    """
    from emonitor.extensions import monitorserver

    if 'alarmfilter' not in session:
        session['alarmfilter'] = '7'
    if request.args.get('alarmfilter'):  # filter for alarms last x days, -1 no filter set
        session['alarmfilter'] = request.args.get('alarmfilter', '7')

    if 'area' in request.args:
        params['area'] = request.args.get('area')
    if 'state' in request.args:
        params['activeacc'] = request.args.get('state')

    if request.form.get('action') == 'updatealarm':
        if request.form.get('alarm_id') != 'None':  # update alarm
            alarm = Alarm.getAlarms(request.form.get('alarm_id'))
        else:  # create new alarm
            d = datetime.datetime.strptime('%s %s' % (request.form.get('edit_timestamp_date'), request.form.get('edit_timestamp_time')), "%d.%m.%Y %H:%M:%S")
            alarm = Alarm(d, request.form.get('edit_keyid'), 2, 0)
            db.session.add(alarm)
            params['activeacc'] = 1
        try:
            alarm.timestamp = datetime.datetime.strptime('%s %s' % (request.form.get('edit_timestamp_date'), request.form.get('edit_timestamp_time')), "%d.%m.%Y %H:%M:%S")
        except ValueError:
            alarm.timestamp = datetime.datetime.now()
        alarm._key = request.form.get('edit_key')

        alarm.set(u'id.key', request.form.get('edit_keyid'))
        alarm.set(u'k.cars1', request.form.get('val_cars1'))
        alarm.set(u'k.cars2', request.form.get('val_cars2'))
        alarm.set(u'k.material', request.form.get('val_material'))

        alarm.set(u'marker', request.form.get('marker'))
        alarm.set(u'id.city', request.form.get('edit_city'))
        _city = City.getCities(id=request.form.get('edit_cityname'))
        if _city:
            alarm.set(u'city', _city.name)
        else:
            alarm.set(u'city', request.form.get('edit_cityname'))

        alarm.set(u'streetno', request.form.get('edit_streetno'))
        street = Street.getStreets(id=request.form.get('edit_addressid'))
        hnumber = None
        if street:
            alarm.set(u'id.address', street.id)
            try:
                hnumber = [h for h in street.housenumbers if h.number == request.form.get('edit_streetno').split()[0]]
                if len(hnumber) > 0:
                    alarm.set(u'lat', hnumber[0].points[0][0])
                    alarm.set(u'lng', hnumber[0].points[0][1])
            except IndexError:
                pass
        elif request.form.get('edit_addressid') == 'None':
            alarm.set(u'id.address', '')
        else:
            alarm.set(u'id.address', request.form.get('edit_addressid'))
        alarm.set(u'address', request.form.get('edit_address'))
        if request.form.get('edit_object') != '0':
            alarm.set(u'id.object', request.form.get('edit_object'))
        else:  # remove object definition if present
            if u'id.object' in alarm.attributes:
                del alarm.attributes[u'id.object']
            if u'object' in alarm.attributes:
                del alarm.attributes[u'object']
        alarm.set(u'priority', request.form.get('edit_priority'))
        alarm.set(u'remark', request.form.get('edit_remark'))
        alarm.set(u'person', request.form.get('edit_person'))

        if request.form.get(u'edit_address2').strip() != '':
            alarm.set(u'address2', request.form.get('edit_address2'))

        if (request.form.get(u'marker') == '1' and not hnumber) or request.form.get('update_position') == '1':
            alarm.set(u'routing', '')
            alarm.set(u'lat', request.form.get('lat'))
            alarm.set(u'lng', request.form.get('lng'))
            alarm.set(u'zoom', request.form.get('zoom'))
        try:
            d = datetime.datetime.strptime('%s %s' % (request.form.get('edit_endtimestamp_date'), request.form.get('edit_endtimestamp_time')), "%d.%m.%Y %H:%M:%S")
        except ValueError:
            d = datetime.datetime.now()
        alarm.set(u'endtimestamp', d)
        db.session.commit()
        signal.send('alarm', 'updated', alarmid=alarm.id)
        if request.form.get('alarm_id') == u'None':  # create new
            Alarm.changeState(alarm.id, 0)  # prepare alarm
            return redirect('/alarms?area=%s&state=1' % params['area'])
        elif alarm.state == 1:  # active alarm update
            monitorserver.sendMessage('0', 'reset')  # refresh monitor layout
        return redirect('/alarms?area=%s&state=0' % params['area'])

    elif request.args.get('action') == 'editalarm':
        if request.args.get('alarmid', '0') == '0':  # add new alarm
            alarm = Alarm(datetime.datetime.now(), '', 2, 0)
            #flash(babel.gettext(u'alarms.alarmadded'), 'alarms.add')
        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(), departments=Department.getDepartments(), frontendarea=params['area'], frontendmodules=frontend.modules, frontendmoduledef=Settings.get('frontend.default'))

    elif request.args.get('action') == 'refresh':  # refresh alarm section
        params['area'] = request.args.get('area')
        params['activeacc'] = int(request.args.get('activeacc'))

    elif request.args.get('action') == 'finishalarm':  # finish selected alarm
        Alarm.changeState(int(request.args.get('alarmid')), 2)
        params['area'] = request.args.get('area')

    elif request.args.get('action') == 'activatealarm':  # activate selected alarm
        ret = Alarm.changeState(int(request.args.get('alarmid')), 1)
        if len(ret) > 0:
            flash(render_template_string("{{ _('alarms.carsinuse') }}</br><b>" + ", ".join([r.name for r in sorted(ret, key=attrgetter('name'))]) + "</b>"), 'alarms')
        params['area'] = request.args.get('area')
        params['activeacc'] = 0

    elif request.args.get('action') == 'deletealarm':  # delete selected alarm
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        refresh = 1 or alarm.state == 1  # check if alarm is active
        try:
            # delete file if not used in any other alarm
            c = Alarm.query.filter(Alarm.attributes.any(value=alarm.get('filename'), name="filename")).count()
            if c == 1 and os.path.exists("{}{}".format(current_app.config.get('PATH_DONE'), alarm.get('filename'))):
                os.remove("{}{}".format(current_app.config.get('PATH_DONE'), alarm.get('filename')))
        except:
            pass
        alarm.state = -1
        alarm.updateSchedules()
        db.session.delete(alarm)
        db.session.commit()
        if refresh:
            monitorserver.sendMessage('0', 'reset')  # refresh monitor layout
        signal.send('alarm', 'deleted', alarmid=request.args.get('alarmid'))

    elif request.args.get('action') == 'archivealarm':  # archive selected alarms, id=0 == all
        if ";" in request.args.get('alarmid'):  # archive selected alarms
            for alarmid in request.args.get('alarmid').split(';'):
                Alarm.changeState(int(alarmid), 3)
        elif int(request.args.get('alarmid')) == 0:  # archive all alarms
            Alarm.changeStates(3)
        else:  # archive single selected alarm
            Alarm.changeState(int(request.args.get('alarmid')), 3)
        params['area'] = request.args.get('area')

    stats = dict.fromkeys(Alarm.ALARMSTATES.keys() + ['3'], 0)
    for s, c in Alarm.getAlarmCount(days=int(session['alarmfilter'])):  # s=state, c=count(ids of state)
        if str(s) in stats.keys():
            stats[str(s)] = c

    if 'area' not in params:
        params['area'] = 'center'
    if 'activeacc' not in params:
        params['activeacc'] = 0
    return render_template('frontend.alarms_smallarea.html', alarmstates=Alarm.ALARMSTATES, stats=stats, frontendarea=params['area'], activeacc=str(params['activeacc']), printdefs=Printers.getActivePrintersOfModule('alarms'), frontendmodules=frontend.modules, frontendmoduledef=Settings.get('frontend.default'), alarmfilter=session['alarmfilter'])
Example #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 ""
 def createReport(self, alarms, fields):
     return self._report.createReport(alarmlist=[Alarm.getAlarms(id=alarm) for alarm in alarms], fielddefinition=fields)
Example #15
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'))
Example #16
0
def getAdminData(self):
    """
    Deliver admin content of module alarms (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get('action') == 'upload':
        if request.files:
            ufile = request.files['uploadfile']
            fname = os.path.join(current_app.config.get('PATH_TMP'), ufile.filename)
            ufile.save(fname)

            scheduler.add_job(processFile, args=[current_app.config.get('PATH_TMP'), ufile.filename])  # schedule operation
        return ""

    elif request.args.get('action') == 'uploadchecker':
        if request.files:
            ufile = request.files['uploadfile']
            if not os.path.exists('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)):
                ufile.save('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename))
                try:
                    cls = imp.load_source('emonitor.modules.alarms.inc', 'emonitor/modules/alarms/inc/%s' % ufile.filename)
                    if isinstance(getattr(cls, cls.__all__[0])(), AlarmFaxChecker):
                        return "ok"
                except:
                    pass
                os.remove('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename))
                return babel.gettext(u'admin.alarms.checkernotvalid')
        return ""

    elif request.args.get('action') == 'uploaddefinition':
        """
        add alarmtype with given config for uploadfile
        """
        alarmtype = AlarmType.buildFromConfigFile(request.files['uploadfile'])
        if not alarmtype:
            db.session.rollback()
            return babel.gettext(u'admin.alarms.incorrecttypedefinition')
        db.session.add(alarmtype)
        db.session.commit()
        return "ok"

    elif request.args.get('action') == 'gettypedefinition':
        """
        export alarmtype definition as cfg-file
        """
        alarmtype = AlarmType.getAlarmTypes(request.args.get('alarmtype'))
        if alarmtype:
            return Response(alarmtype.getConfigFile(), mimetype="application/x.download; charset=utf-8")
        else:
            return None

    elif request.args.get('action') == 'getkeywords':
        """
        send list with all keywords of alarmtype
        """
        for f in [f for f in os.listdir('%s/emonitor/modules/alarms/inc/' % current_app.config.get('PROJECT_ROOT')) if f.endswith('.py')]:
            if f == request.args.get('checker'):
                cls = imp.load_source('emonitor.modules.alarms.inc', 'emonitor/modules/alarms/inc/%s' % f)
                cls = getattr(cls, cls.__all__[0])()
                return {u'keywords': "\n".join(cls.getDefaultConfig()[u'keywords']), u'variables': cls.getDefaultConfig()[u'translations'], u'attributes': cls.getDefaultConfig()[u'attributes']}
        return ""

    elif request.args.get('action') == 'alarmsforstate':
        alarms = Alarm.getAlarms(state=int(request.args.get('state')))
        return render_template('admin.alarms_alarm.html', alarms=alarms)

    elif request.args.get('action') == 'alarmsarchive':
        for id in request.args.get('alarmids').split(','):
            Alarm.changeState(int(id), 3)
        return ""

    elif request.args.get('action') == 'savefieldorder':  # change order of fields
        fields = []
        deptid = '0'
        for f in request.args.get('order').split(','):
            t, deptid, name = f.split('.')
            fields.append(name)
        if int(deptid):
            for dbfield in AlarmField.getAlarmFields(dept=deptid):
                dbfield.position = fields.index(dbfield.fieldtype)
            db.session.commit()
        return ""

    elif request.args.get('action') == 'addreport':
        f = request.files['template']
        fname = "{}.{}".format(random.random(), f.filename.split('.')[-1])
        fpath = '{}alarmreports/{}'.format(current_app.config.get('PATH_DATA'), fname[2:])
        f.save(fpath)

        if f.filename.endswith('pdf'):
            fields = getFormFields(fpath)
            content = render_template('admin.alarms.report_fields.html', filepath='{}alarmreports/{}'.format(current_app.config.get('PATH_DATA'), fname[2:]), fileinfo=getPDFInformation(fpath), fields=fields, multi=max(fields.values()) > 1)
        else:
            content = ""
            fields = []
        return {'filename': fname, 'content': content}

    elif request.args.get('action') == 'reportdetails':
        return render_template('admin.alarms.report_details.html', report=AlarmReport.getReports(id=request.args.get('reportid')), reporttype=AlarmReport.getReportTypes(request.args.get('template')), departments=request.args.get('departments'))

    elif request.args.get('action') == 'reportfieldlookup':
        ret = OrderedDict()

        ret['basic'] = []  # add basic information from AFBasic class
        for f in AFBasic().getFields():
            ret['basic'].append({'id': f.name, 'value': f.id})

        alarmfields = {}
        for alarmfield in AlarmField.getAlarmFields():
            if str(alarmfield.dept) not in request.args.get('departments').split(','):
                continue
            if alarmfield.fieldtype not in alarmfields:
                alarmfields[alarmfield.fieldtype] = []
            alarmfields[alarmfield.fieldtype].append(alarmfield)

        l = ""
        for alarmfield in list(chain.from_iterable([f for f in alarmfields.values() if len(f) == len(request.args.get('departments').split(','))])):
            if '%s' % alarmfield.name not in ret:
                ret['%s' % alarmfield.name] = [{'id': '%s-list' % alarmfield.fieldtype, 'value': '%s (%s)' % (alarmfield.name, babel.gettext('admin.alarms.list'))}]
            for f in alarmfield.getFields():
                if f.getLabel().strip() not in ["", '<leer>']:  # dismiss empty values
                    if f.name[0] != ' ':
                        value = '%s' % babel.gettext(f.getLabel())
                        l = value
                    else:  # add name of kategory
                        value = '%s > %s' % (l, babel.gettext(f.getLabel()))
                    ret['%s' % alarmfield.name].append({'id': '%s-%s' % (alarmfield.fieldtype, f.id), 'value': value})
        return ret
Example #17
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarms

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

    if len(module) > 1:
        if module[1] == 'types':
            impl = []  # load implementations of faxchecker
            for f in [f for f in os.listdir('%s/emonitor/modules/alarms/inc/' % current_app.config.get('PROJECT_ROOT')) if f.endswith('.py')]:
                if not f.startswith('__'):
                    cls = imp.load_source('emonitor.modules.alarms.inc', 'emonitor/modules/alarms/inc/%s' % f)
                    if isinstance(getattr(cls, cls.__all__[0])(), AlarmFaxChecker):
                        impl.append((f, getattr(cls, cls.__all__[0])(), AlarmType.getAlarmTypeByClassname(f)))

            if request.method == 'POST':
                if request.form.get('action') == 'createtype':  # add type
                    params.update({'alarmtype': AlarmType('', ''), 'interpreter': impl})
                    return render_template('admin.alarms.type_actions.html', **params)

                elif request.form.get('action').startswith('deleteinterpreter_'):  # delete checker
                    for cls in impl:
                        if cls[0] == request.form.get('action')[18:]:
                            if os.path.exists('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), cls[0])):
                                os.remove('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), cls[0]))
                            if os.path.exists('%s/emonitor/modules/alarms/inc/%sc' % (current_app.config.get('PROJECT_ROOT'), cls[0])):
                                os.remove('%s/emonitor/modules/alarms/inc/%sc' % (current_app.config.get('PROJECT_ROOT'), cls[0]))
                            impl.remove(cls)

                elif request.form.get('action').startswith('editalarmtype_'):  # edit type
                    params.update({'alarmtype': AlarmType.getAlarmTypes(id=int(request.form.get('action').split('_')[-1])), 'interpreter': impl})
                    return render_template('admin.alarms.type_actions.html', **params)

                elif request.form.get('action').startswith('deletetype_'):  # delete type
                    atype = AlarmType.getAlarmTypes(id=int(request.form.get('action').split('_')[-1]))
                    for e in [e for e in events.events if e.name in ['alarm_added.{}'.format(atype.name), 'alarm_changestate.{}'.format(atype.name)]]:
                        # delete event handlers and monitor layout
                        for eh in Eventhandler.getEventhandlers(event=e.name):
                            for ml in MonitorLayout.query.filter(MonitorLayout.trigger.like('%{}%'.format(eh.event))).all():
                                if ';' in ml.trigger:
                                    _tr = ml.trigger.split(';')
                                    del _tr[_tr.index(e.name)]
                                    ml.trigger = ";".join(_tr)
                                else:
                                    db.session.remove(ml)
                            db.session.delete(eh)
                        # delete event
                        del events.events[events.events.index(e)]
                    db.session.delete(atype)
                    db.session.commit()

                elif request.form.get('action') == 'updatetype':  # update type
                    if request.form.get('type_id') == 'None':  # add type
                        atype = AlarmType('', '')
                        db.session.add(atype)
                        events.addEvent('alarm_added.{}'.format(request.form.get('edit_name')), handlers=[], parameters=[])
                        events.addEvent('alarm_changestate.{}'.format(request.form.get('edit_name')), handlers=[], parameters=[])
                    else:  # update type
                        atype = AlarmType.getAlarmTypes(id=int(request.form.get('type_id')))
                        for e in [e for e in events.events if e.name in ['alarm_added.{}'.format(atype.name), 'alarm_changestate.{}'.format(atype.name)]]:
                            # update event handler and monitor layout
                            newname = '{}.{}'.format(e.name.split('.')[0], request.form.get('edit_name'))
                            for eh in Eventhandler.getEventhandlers(event=e.name):
                                for ml in MonitorLayout.query.filter(MonitorLayout.trigger.like('%{}%'.format(eh.event))).all():
                                    ml.trigger = ml.trigger.replace(e.name, newname)
                                eh.event = newname
                            # update event
                            e.name = newname

                    atype.name = request.form.get('edit_name')
                    atype.keywords = request.form.get('edit_keywords')
                    atype.interpreter = request.form.get('edit_interpreter')
                    atype.attributes = dict(zip(request.form.getlist('attribute_name'), request.form.getlist('attribute_value')))
                    atype.translations = dict(zip(request.form.getlist('alarmtypevariables'), request.form.getlist('alarmtypetranslation')))
                    db.session.commit()

                    if request.form.get('type_id') == 'None':  # add predefined keywords and sections
                        # add pre-defined sections
                        for checker in [i for i in impl if i[0] == request.form.get('edit_interpreter')]:
                            if request.form.get('edit_keywords') == "":
                                atype.keywords = "\n".join(checker[1].getDefaultConfig()['keywords'])
                            sections = checker[1].getDefaultConfig()['sections']
                            i = 1
                            for key in sections:
                                db.session.add(AlarmSection(atype.id, key, sections[key][0], 1, sections[key][1], i))
                                i += 1
                        db.session.commit()

                elif request.form.get('action').startswith('createsection_'):  # add section
                    alarmtype = AlarmType.getAlarmTypes(id=int(request.form.get('action').split('_')[-1]))
                    params.update({'alarmtype': alarmtype, 'section': AlarmSection(alarmtype.id, '', '', 0, '', 0), 'functions': alarmtype.interpreterclass().getEvalMethods()})
                    return render_template('admin.alarms.sections_actions.html', **params)

                elif request.form.get('action') == 'updatesection':  # save section
                    db.session.rollback()
                    if request.form.get('section_id') == 'None':  # add
                        section = AlarmSection(request.form.get('edit_tid'), '', '', '', '', '')
                        section.orderpos = 1 + len(AlarmSection.getSections())
                        db.session.add(section)

                    else:  # update
                        section = AlarmSection.getSections(id=int(request.form.get('section_id')))
                        section.orderpos = request.form.get('edit_orderpos')

                    section.tid = request.form.get('edit_tid')
                    section.name = request.form.get('edit_name')
                    section.key = request.form.get('edit_key')
                    section.method = request.form.get('edit_method')
                    section.active = request.form.get('edit_active')
                    alarmtype = AlarmType.getAlarmTypes(request.form.get('edit_tid'))
                    if alarmtype.interpreterclass().configtype == 'generic':
                        attrs = {'start': request.form.get('edit_start'), 'end': request.form.get('edit_end')}
                        if 'edit_multiline' in request.form.keys():
                            attrs['multiline'] = 'True'
                        section.attributes = attrs
                    db.session.commit()

                elif request.form.get('action') == 'updateorder':
                    for item in [i for i in request.form if i.startswith('position_')]:
                        ids = request.form.getlist(item)
                        for _id in ids:
                            AlarmSection.getSections(id=_id).orderpos = ids.index(_id) + 1
                    db.session.commit()

                elif request.form.get('action').startswith('editalarmsection_'):  # edit section
                    section = AlarmSection.getSections(id=int(request.form.get('action').split('_')[-1]))
                    params.update({'section': section, 'functions': section.alarmtype.interpreterclass().getEvalMethods(), 'alarmtype': AlarmType.getAlarmTypes(section.tid)})
                    return render_template('admin.alarms.sections_actions.html', **params)

                elif request.form.get('action').startswith('deletealarmsection_'):  # delete section
                    section = AlarmSection.getSections(id=int(request.form.get('action').split('_')[-1]))
                    db.session.delete(section)
                    db.session.commit()

            params.update({'alarmtypes': AlarmType.getAlarmTypes(), 'interpreters': impl})
            return render_template('admin.alarms.type.html', **params)

        elif module[1] == 'report':

            if request.method == 'POST':
                if request.form.get('action') == 'createreport':  # add report
                    params.update({'report': AlarmReport('', '', '', 1, []), 'departments': Department.getDepartments(), 'reporttypes': AlarmReport.getReportTypes()})
                    return render_template('admin.alarms.report_action.html', **params)

                elif request.form.get('action') == 'updatereport':
                    if request.form.get('report_id') == 'None':  # add new report
                        report = AlarmReport('', '', '', '')
                        db.session.add(report)
                    else:
                        report = AlarmReport.getReports(request.form.get('report_id'))

                    report.name = request.form.get('edit_name')
                    if not request.form.get('template').startswith(current_app.config.get('PATH_DATA')):  # internal template
                        report._reporttype = 'internal'
                        report.filename = request.form.get('template').replace("{}/emonitor/modules/alarms/templates/".format(current_app.config.get('PROJECT_ROOT')).replace('\\', '/'), "")
                    else:
                        report._reporttype = 'external'
                        report.filename = request.form.get('template').replace("{}".format(current_app.config.get('PATH_DATA')), "")
                        report.fields = json.loads(request.form.get('fielddefinition'))
                    report.departments = request.form.getlist('edit_department')
                    db.session.commit()

                elif request.form.get('action').startswith('editreport_'):  # edit report
                    report = AlarmReport.getReports(request.form.get('action').split('_')[-1])
                    params.update({'report': report, 'departments': Department.getDepartments(), 'reporttypes': AlarmReport.getReportTypes(), 'alarmfields': AlarmField.getAlarmFields()})
                    return render_template('admin.alarms.report_action.html', **params)

                elif request.form.get('action').startswith('deletereport_'):  # delete report
                    report = AlarmReport.getReports(request.form.get('action').split('_')[-1])
                    if AlarmReport.query.filter(AlarmReport.filename == report.filename).count() == 1 and os.path.exists(report.filename):
                        os.remove(report.filename)
                    db.session.delete(report)
                    db.session.commit()

            params.update({'reports': AlarmReport.getReports(), 'departments': Department.getDepartments()})
            return render_template('admin.alarms.report.html', **params)

        elif module[1] == 'config':
            if request.method == 'POST':
                if request.form.get('action') == 'alarmcarsprio':
                    for k in Alarm.ALARMSTATES.keys():
                        if 'used_cars{}'.format(k) in request.form.keys():
                            Settings.set('alarms.spc_cars.{}'.format(k), request.form.get('used_cars{}'.format(k)))
                    db.session.commit()

                elif request.form.get('action') == 'alarmsettings':
                    Settings.set('alarms.autoclose', request.form.get('settings.autoclose'))
                    for aalarm in [a for a in Alarm.getAlarms() if a.state == 1]:  # only active alarms
                        aalarm.updateSchedules(reference=1)  # use alarmtime as refernce

                elif request.form.get('action') == 'archivesettings':
                    Settings.set('alarms.autoarchive', request.form.get('settings.autoarchive'))
                    for aalarm in [a for a in Alarm.getAlarms() if a.state == 2]:  # only closed alarms
                        aalarm.updateSchedules(reference=1)  # use alarmtime as refernce

                elif request.form.get('action').startswith('save_'):
                    if request.form.get('fieldid') == 'None':
                        field = AlarmField.getAlarmFieldForType(request.form.get('action').split('_')[1], dept=request.form.get('action').split('_')[2])
                        db.session.add(field)
                    else:
                        field = AlarmField.getAlarmFields(id=request.form.get('fieldid'))
                    field.saveConfigForm(request)
                    db.session.commit()

                elif request.form.get('action').startswith('field_delete_'):  # delete definition of field
                    db.session.delete(AlarmField.getAlarmFields(id=request.form.get('action').split('_')[-1]))
                    db.session.commit()

                elif request.form.get('action').startswith('field_add_'):  # add field for department
                    field = AlarmField.getAlarmFieldForType(request.form.get('action').split('_')[-2], dept=request.form.get('action').split('_')[-1])
                    field.name = babel.gettext(field.name)
                    db.session.add(field)
                    db.session.commit()

            fields = {}
            for dept in Department.getDepartments():
                fields[dept.id] = AlarmField.getAlarmFieldsForDepartment(dept.id)
            params.update({'cars': Car.getCars(), 'alarmstates': Alarm.ALARMSTATES, 'settings': Settings, 'departments': Department.getDepartments(), 'fields': fields})
            return render_template('admin.alarms.config.html', **params)

        elif module[1] == 'test':
            params.update({'uploadfileformat': filter(None, sum([Settings.get('ocr.inputformat', []), Settings.get('ocr.inputtextformat', [])], []))})
            return render_template('admin.alarms.test.html', **params)

    else:
        params.update({'alarms': dict(Alarm.getAlarmCount()), 'alarmstates': Alarm.ALARMSTATES, 'help': self.hasHelp('admin')})
        return render_template('admin.alarms.html', **params)
Example #18
0
def getFrontendContent(**params):
    """
    Deliver frontend content of module alarms

    :return: data of alarms
    """
    from emonitor.extensions import monitorserver

    if 'alarmfilter' not in session:
        session['alarmfilter'] = '7'
    if request.args.get(
            'alarmfilter'):  # filter for alarms last x days, -1 no filter set
        session['alarmfilter'] = request.args.get('alarmfilter', '7')

    if 'area' in request.args:
        params['area'] = request.args.get('area')
    if 'state' in request.args:
        params['activeacc'] = request.args.get('state')

    if request.form.get('action') == 'updatealarm':
        if request.form.get('alarm_id') != 'None':  # update alarm
            alarm = Alarm.getAlarms(request.form.get('alarm_id'))
        else:  # create new alarm
            d = datetime.datetime.strptime(
                '%s %s' % (request.form.get('edit_timestamp_date'),
                           request.form.get('edit_timestamp_time')),
                "%d.%m.%Y %H:%M:%S")
            alarm = Alarm(d, request.form.get('edit_keyid'), 2, 0)
            db.session.add(alarm)
            params['activeacc'] = 1
        try:
            alarm.timestamp = datetime.datetime.strptime(
                '%s %s' % (request.form.get('edit_timestamp_date'),
                           request.form.get('edit_timestamp_time')),
                "%d.%m.%Y %H:%M:%S")
        except ValueError:
            alarm.timestamp = datetime.datetime.now()
        alarm._key = request.form.get('edit_key')

        alarm.set(u'id.key', request.form.get('edit_keyid'))
        alarm.set(u'k.cars1', request.form.get('val_cars1'))
        alarm.set(u'k.cars2', request.form.get('val_cars2'))
        alarm.set(u'k.material', request.form.get('val_material'))

        alarm.set(u'marker', request.form.get('marker'))
        alarm.set(u'id.city', request.form.get('edit_city'))
        _city = City.getCities(id=request.form.get('edit_cityname'))
        if _city:
            alarm.set(u'city', _city.name)
        else:
            alarm.set(u'city', request.form.get('edit_cityname'))

        alarm.set(u'streetno', request.form.get('edit_streetno'))
        street = Street.getStreets(id=request.form.get('edit_addressid'))
        hnumber = None
        if street:
            alarm.set(u'id.address', street.id)
            try:
                hnumber = [
                    h for h in street.housenumbers
                    if h.number == request.form.get('edit_streetno').split()[0]
                ]
                if len(hnumber) > 0:
                    alarm.set(u'lat', hnumber[0].points[0][0])
                    alarm.set(u'lng', hnumber[0].points[0][1])
            except IndexError:
                pass
        elif request.form.get('edit_addressid') == 'None':
            alarm.set(u'id.address', '')
        else:
            alarm.set(u'id.address', request.form.get('edit_addressid'))
        alarm.set(u'address', request.form.get('edit_address'))
        if request.form.get('edit_object') != '0':
            alarm.set(u'id.object', request.form.get('edit_object'))
        else:  # remove object definition if present
            if u'id.object' in alarm.attributes:
                del alarm.attributes[u'id.object']
            if u'object' in alarm.attributes:
                del alarm.attributes[u'object']
        alarm.set(u'priority', request.form.get('edit_priority'))
        alarm.set(u'remark', request.form.get('edit_remark'))
        alarm.set(u'person', request.form.get('edit_person'))

        if request.form.get(u'edit_address2').strip() != '':
            alarm.set(u'address2', request.form.get('edit_address2'))

        if (request.form.get(u'marker') == '1'
                and not hnumber) or request.form.get('update_position') == '1':
            alarm.set(u'routing', '')
            alarm.set(u'lat', request.form.get('lat'))
            alarm.set(u'lng', request.form.get('lng'))
            alarm.set(u'zoom', request.form.get('zoom'))
        try:
            d = datetime.datetime.strptime(
                '%s %s' % (request.form.get('edit_endtimestamp_date'),
                           request.form.get('edit_endtimestamp_time')),
                "%d.%m.%Y %H:%M:%S")
        except ValueError:
            d = datetime.datetime.now()
        alarm.set(u'endtimestamp', d)
        db.session.commit()
        signal.send('alarm', 'updated', alarmid=alarm.id)
        if request.form.get('alarm_id') == u'None':  # create new
            Alarm.changeState(alarm.id, 0)  # prepare alarm
            return redirect('/alarms?area=%s&state=1' % params['area'])
        elif alarm.state == 1:  # active alarm update
            monitorserver.sendMessage('0', 'reset')  # refresh monitor layout
        return redirect('/alarms?area=%s&state=0' % params['area'])

    elif request.args.get('action') == 'editalarm':
        if request.args.get('alarmid', '0') == '0':  # add new alarm
            alarm = Alarm(datetime.datetime.now(), '', 2, 0)
            #flash(babel.gettext(u'alarms.alarmadded'), 'alarms.add')
        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(),
            departments=Department.getDepartments(),
            frontendarea=params['area'],
            frontendmodules=frontend.modules,
            frontendmoduledef=Settings.get('frontend.default'))

    elif request.args.get('action') == 'refresh':  # refresh alarm section
        params['area'] = request.args.get('area')
        params['activeacc'] = int(request.args.get('activeacc'))

    elif request.args.get('action') == 'finishalarm':  # finish selected alarm
        Alarm.changeState(int(request.args.get('alarmid')), 2)
        params['area'] = request.args.get('area')

    elif request.args.get(
            'action') == 'activatealarm':  # activate selected alarm
        ret = Alarm.changeState(int(request.args.get('alarmid')), 1)
        if len(ret) > 0:
            flash(
                render_template_string(
                    "{{ _('alarms.carsinuse') }}</br><b>" + ", ".join(
                        [r.name
                         for r in sorted(ret, key=attrgetter('name'))]) +
                    "</b>"), 'alarms')
        params['area'] = request.args.get('area')
        params['activeacc'] = 0

    elif request.args.get('action') == 'deletealarm':  # delete selected alarm
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        refresh = 1 or alarm.state == 1  # check if alarm is active
        try:
            # delete file if not used in any other alarm
            c = Alarm.query.filter(
                Alarm.attributes.any(value=alarm.get('filename'),
                                     name="filename")).count()
            if c == 1 and os.path.exists("{}{}".format(
                    current_app.config.get('PATH_DONE'),
                    alarm.get('filename'))):
                os.remove("{}{}".format(current_app.config.get('PATH_DONE'),
                                        alarm.get('filename')))
        except:
            pass
        alarm.state = -1
        alarm.updateSchedules()
        db.session.delete(alarm)
        db.session.commit()
        if refresh:
            monitorserver.sendMessage('0', 'reset')  # refresh monitor layout
        signal.send('alarm', 'deleted', alarmid=request.args.get('alarmid'))

    elif request.args.get(
            'action'
    ) == 'archivealarm':  # archive selected alarms, id=0 == all
        if ";" in request.args.get('alarmid'):  # archive selected alarms
            for alarmid in request.args.get('alarmid').split(';'):
                Alarm.changeState(int(alarmid), 3)
        elif int(request.args.get('alarmid')) == 0:  # archive all alarms
            Alarm.changeStates(3)
        else:  # archive single selected alarm
            Alarm.changeState(int(request.args.get('alarmid')), 3)
        params['area'] = request.args.get('area')

    stats = dict.fromkeys(Alarm.ALARMSTATES.keys() + ['3'], 0)
    for s, c in Alarm.getAlarmCount(days=int(
            session['alarmfilter'])):  # s=state, c=count(ids of state)
        if str(s) in stats.keys():
            stats[str(s)] = c

    if 'area' not in params:
        params['area'] = 'center'
    if 'activeacc' not in params:
        params['activeacc'] = 0
    return render_template(
        'frontend.alarms_smallarea.html',
        alarmstates=Alarm.ALARMSTATES,
        stats=stats,
        frontendarea=params['area'],
        activeacc=str(params['activeacc']),
        printdefs=Printers.getActivePrintersOfModule('alarms'),
        frontendmodules=frontend.modules,
        frontendmoduledef=Settings.get('frontend.default'),
        alarmfilter=session['alarmfilter'])
Example #19
0
 def createReport(self, alarms, fields):
     return self._report.createReport(
         alarmlist=[Alarm.getAlarms(id=alarm) for alarm in alarms],
         fielddefinition=fields)
Example #20
0
def getFrontendData(self):
    """
    Deliver frontend content of module streets (ajax)

    :return: rendered template as string or json dict
    """
    if request.args.get(
            'action'
    ) == 'streetcoords':  # get map parameter for given streetid

        if request.args.get('id') not in ['', 'None']:
            street = Street.getStreets(id=request.args.get('id'))
            return {
                'lat': street.lat,
                'lng': street.lng,
                'zoom': street.zoom,
                'way': street.navigation,
                'cityid': street.cityid,
                'cityname': street.city.name
            }

    elif request.args.get(
            'action') == 'housecoords':  # deliver center of housenumbers
        if request.args.get('streetid') != '' and request.args.get(
                'housenumber') != '':
            street = Street.getStreet(id=request.args.get('streetid'))
            hnumber = street.getHouseNumber(
                number=request.args.get('housenumber').split()[0])
            if hnumber:
                return hnumber.getPosition(0)

            return {'lat': street.lat, 'lng': street.lng}
        return {}

    elif request.args.get('action') == 'defaultposition':

        return {
            'defaultlat': float(Settings.get('defaultLat')),
            'defaultlng': float(Settings.get('defaultLng')),
            'defaultzoom': int(Settings.get('defaultZoom'))
        }

    elif request.args.get('action') == 'alarmposition':
        alarm = Alarm.getAlarms(id=request.args.get('alarmid'))
        if alarm:
            return {
                'id': request.args.get('alarmid'),
                'alarmlat': alarm.lat,
                'alarmlng': alarm.lng,
                'alarmzoom': alarm.zoom,
                'marker': alarm.marker,
                'alarmprio': alarm.priority,
                'alarmstreet': alarm.street.name,
                'alarmstreetno': alarm.get('streetno'),
                'alarmstreet2': alarm.get('address2'),
                'alarmcity': alarm.city.name,
                'alarmsubcity': alarm.street.subcity
            }
        else:
            return {'id': '0'}

    elif request.args.get('action') == 'streetslookup':
        streets = {}
        cities = {}
        for c in City.getCities():
            cities[c.id] = c.name
            for k, street in c.streets.iteritems():
                if street.active:
                    try:
                        streets[str(
                            street.id)] = '%s (%s)' % (street.name, c.name)
                    except:
                        streets[str(street.id)] = '%s (-%s-)' % (street.name,
                                                                 street.cityid)
        return streets

    elif request.args.get('action') == 'defaultmap':
        dmap = Map.getDefaultMap()
        return {'tileserver': dmap.tileserver, 'name': dmap.name}

    return ""
Example #21
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 ""