Ejemplo n.º 1
0
 def updateAdminSubNavigation(self):
     """
     Add subnavigation for admin area with sections for alarmkey module
     """
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(('/admin/alarmkeys/%s' % dep.id, dep.name))
Ejemplo n.º 2
0
 def updateAdminSubNavigation(self):
     """
     Add submenu entries for admin area
     """
     from emonitor.modules.settings.department import Department
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(('/admin/cars/%s' % dep.id, dep.name))
Ejemplo n.º 3
0
 def updateAdminSubNavigation(self):
     """
     Add subnavigation for admin area with sections for alarmkey module
     """
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(
             ('/admin/alarmkeys/%s' % dep.id, dep.name))
Ejemplo n.º 4
0
 def updateAdminSubNavigation(self):
     """
     Add submenu entries for admin area
     """
     from emonitor.modules.settings.department import Department
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(('/admin/persons/%s' % dep.id, dep.name))
     self.adminsubnavigation.append(('/admin/persons/0', babel.gettext('admin.persons.edit...')))
Ejemplo n.º 5
0
 def updateAdminSubNavigation(self):
     """
     Add submenu entries for admin area
     """
     from emonitor.modules.settings.department import Department
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(
             ('/admin/cars/%s' % dep.id, dep.name))
Ejemplo n.º 6
0
 def updateAdminSubNavigation(self):
     """
     Add submenu entries for admin area
     """
     from emonitor.modules.settings.department import Department
     self.adminsubnavigation = []
     for dep in Department.getDepartments():
         self.adminsubnavigation.append(
             ('/admin/persons/%s' % dep.id, dep.name))
     self.adminsubnavigation.append(
         ('/admin/persons/0', babel.gettext('admin.persons.edit...')))
def getAdminContent(self, **params):
    """
    Deliver admin content of module cars

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')
    
    if len(module) < 2:
        module.append(u'1')
        
    if request.method == 'POST':
        if request.form.get('action') == 'createcars':  # add car
            params.update({'car': Car('', '', '', '', '', int(module[1])), 'departments': Department.getDepartments(), 'cartypes': Settings.getCarTypes()})
            return render_template('admin.cars_edit.html', **params)

        elif request.form.get('action') == 'updatecars':  # save car
            if request.form.get('car_id') != 'None':  # update car
                car = Car.getCars(id=request.form.get('car_id'))
                
            else:  # add car
                car = Car('', '', '', '', '', module[1])
                db.session.add(car)

            car.name = request.form.get('edit_name')
            car.description = request.form.get('edit_description')
            car.fmsid = request.form.get('edit_fmsid')
            car.active = request.form.get('edit_active')
            car.type = request.form.get('edit_type')
            car._dept = request.form.get('edit_department')
            db.session.commit()
            
        elif request.form.get('action') == 'cancel':
            pass
            
        elif request.form.get('action').startswith('editcars_'):  # edit car
            params.update({'car': Car.getCars(id=request.form.get('action').split('_')[-1]), 'departments': Department.getDepartments(), 'cartypes': Settings.getCarTypes()})
            return render_template('admin.cars_edit.html', **params)

        elif request.form.get('action').startswith('deletecars_'):  # delete car
            db.session.delete(Car.getCars(id=request.form.get('action').split('_')[-1]))
            db.session.commit()
    try:
        cars = Department.getDepartments(module[1]).getCars()
    except AttributeError:
        cars = []
    params.update({'cars': cars})
    return render_template('admin.cars.html', **params)
Ejemplo n.º 8
0
    def evalMaterial(fieldname, **params):
        cars = Car.getCars(params=['onlyactive'])
        carlist = [u'{} {}'.format(c.dept.name, c.name) for c in cars]
        c = [[], []]

        departements = Department.getDepartments()
        for p in [l for l in re.split(r"[\s]{2,}|[\n]+", FezAlarmFaxChecker().fields[fieldname][0])]:
            addcar = None
            if len([d for d in departements if d.name == p.strip()]) == 1:  # department default found
                c = [[u'default'], [0]]
                FezAlarmFaxChecker().logger.debug(u'material: "{}" default department found'.format(p.strip()))
                continue

            # try list or car names
            repl = difflib.get_close_matches(p.strip(), carlist, 1, cutoff=0.7)
            if len(repl) == 1:
                addcar = filter(lambda x: u'{} {}'.format(x.dept.name, x.name) == repl[0], cars)[0]
                addcar = addcar.name, addcar.id

            else:  # try list of car descriptions
                descriptionlist = [u'{} {}'.format(cn.dept.name, cn.description) for cn in cars]
                repl = difflib.get_close_matches(p.strip(), descriptionlist, 1, cutoff=0.7)
                if len(repl) == 1:
                    addcar = filter(lambda x: u'{} {}'.format(x.dept.name, x.description) == repl[0], cars)[0]
                    addcar = addcar.name, addcar.id
                else:
                    t = ""
                    for x in p.split():  # try parts of name and stop after first match
                        t += x
                        repl = difflib.get_close_matches(t, carlist, 1, cutoff=0.7)
                        if len(repl) == 1:
                            addcar = filter(lambda x: u'{} {}'.format(x.dept.name, x.name) == repl[0], cars)[0]
                            addcar = addcar.name, addcar.id
                            break
            if addcar and addcar[1] not in c[1]:
                c[0].append(addcar[0])
                c[1].append(addcar[1])

        if len(c[0]) > 0:
            FezAlarmFaxChecker().logger.debug(u'material: done with {}, {}'.format(c[0], c[1]))
            FezAlarmFaxChecker().fields[fieldname] = (u','.join(c[0]), u','.join([str(_c) for _c in c[1]]))
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmkeys

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

    if len(module) < 2:
        module.append(u'1')
    
    if len(module) > 2 and module[2] == 'upload':  # upload alarmkeys
        params.update({'': int(module[1]), 'department': module[1]})
        return render_template('admin.alarmkeys.upload.html', **params)
    
    else:
        depid = 1
        try:
            if int(module[1]):
                depid = int(module[1])
        except:
            pass
            
        if request.method == 'POST':
            if request.form.get('action') == 'adddefault':  # add default aao
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': 0})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'savedefault':  # save default aao
                alarmkeycar = AlarmkeyCars.getAlarmkeyCars(kid=9999, dept=request.form.get('deptid'))  # 9999 = default department
                if not alarmkeycar:  # add
                    alarmkeycar = AlarmkeyCars(9999, request.form.get('deptid'), '', '', '')
                    db.session.add(alarmkeycar)

                alarmkeycar.cars1 = request.form.get('cars1')
                alarmkeycar.cars2 = request.form.get('cars2')
                alarmkeycar.materials = request.form.get('material')
                if alarmkeycar.kid != 9999 and request.form.get('cars1') == request.form.get('cars2') == request.form.get('material') == '':  # remove
                    db.session.delete(alarmkeycar)
                db.session.commit()
                
            elif request.form.get('action') == 'editdefault':  # edit default aao
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': -1})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'addkey':  # add key
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': -2})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'savekey':  # save key
                if request.form.get('keyid') == 'None':  # add new
                    alarmkey = Alarmkey('', '', '', '')
                    db.session.add(alarmkey)
                    db.session.commit()

                else:  # update existing
                    alarmkey = Alarmkey.getAlarmkeys(request.form.get('keyid'))

                alarmkey.category = request.form.get('category')
                alarmkey.key = request.form.get('key')
                alarmkey.key_internal = request.form.get('keyinternal')
                alarmkey.remark = request.form.get('remark')
                alarmkey.setCars(int(request.form.get('deptid')), cars1=request.form.get('cars1'), cars2=request.form.get('cars2'), material=request.form.get('material'))
                db.session.commit()
                
            elif request.form.get('action').startswith('deletecars_'):  # delete car definition
                _op, _kid, _dept = request.form.get('action').split('_')
                keycar = AlarmkeyCars.getAlarmkeyCars(kid=_kid, dept=_dept)
                if keycar:
                    db.session.delete(keycar)
                    db.session.commit()

                # delete key if no definied cars
                if len(AlarmkeyCars.getAlarmkeyCars(kid=_kid)) == 0:
                    key = Alarmkey.getAlarmkeys(id=_kid)
                    db.session.delete(key)
                db.session.commit()
                
            elif request.form.get('action').startswith('editcars_'):  # edit key with cars
                _op, _kid, _dept = request.form.get('action').split('_')
                params.update({'alarmkey': Alarmkey.getAlarmkeys(id=_kid), 'depid': _dept, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': 1})
                return render_template('admin.alarmkeys_actions.html', **params)

        alarmkeys_count = []
        ak = Alarmkey
        counted_keys = db.get(ak.category.label('category'), func.count(ak.key).label('key'), ak.id.label('id')).group_by(ak.category)
        _sum = 0
        for r in counted_keys.all():
            alarmkeys_count.append([r.category, r.key, r.id])
            _sum += int(r.key)

        params.update({'alarmkeys_count': alarmkeys_count, 'depid': depid, 'defaultcars': Alarmkey.getDefault(depid), 'sum': _sum})
        return render_template('admin.alarmkeys.html', **params)
Ejemplo n.º 10
0
 def checkDefinition(self):
     if len(Department.getDepartments()) == 0:
         return Module.INITNEEDED
     return Module.CHECKOK
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module streets

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')
    if len(module) < 2:
        if City.getDefaultCity():
            module.append(u'{}'.format(City.getDefaultCity().id))
        else:
            module.append(u'1')

    if len(module) == 2:  # cities
        if module[1] == '0':  # city list

            if request.method == 'POST':

                if request.form.get('action').startswith('detailcity_'):  # edit city
                    params.update({'city': City.getCities(id=request.form.get('action').split('_')[-1]), 'departments': Department.getDepartments(), 'maps': Map.getMaps()})
                    return render_template('admin.streets.city_edit.html', **params)

                elif request.form.get('action') == 'updatecity':  # update existing city
                    if request.form.get('city_id') != 'None':  # update city
                        city = City.getCities(id=request.form.get('city_id'))
                        city.name = request.form.get('cityname')
                        city.subcity = request.form.get('subcity')
                        city._dept = request.form.get('department')
                        city.mapname = request.form.get('citymap')
                        city.color = request.form.get('colorname')
                        city.default = request.form.get('citydefault')
                        city.osmid = request.form.get('osmid')
                        city.osmname = request.form.get('osmname')

                    else:  # add city
                        city = City(request.form.get('cityname'), request.form.get('department'),
                                    request.form.get('citymap'), request.form.get('citydefault'),
                                    request.form.get('subcity'), request.form.get('colorname'),
                                    request.form.get('osmid'), request.form.get('osmname'))
                        db.session.add(city)

                    db.session.commit()
                    cache.clear()

                elif request.form.get('action') == 'createcity':  # add city
                    params.update({'city': City('', '', '', '', '', '', 0, ''), 'departments': Department.getDepartments(), 'maps': Map.getMaps()})
                    return render_template('admin.streets.city_edit.html', **params)

                elif request.form.get('action').startswith('deletecity_'):  # delete city
                    db.session.delete(City.getCities(id=request.form.get('action').split('_')[-1]))
                    db.session.commit()
                self.updateAdminSubNavigation()
                cache.clear()

            params.update({'cities': City.getCities()})
            return render_template('admin.streets.city_list.html', **params)

        else:  # show city details
            if request.method == 'POST':
                if request.form.get('action').startswith('detailstreet_'):  # edit street
                    tileserver = {'lat': Settings.get('defaultLat'),
                                  'lng': Settings.get('defaultLng'),
                                  'zoom': Settings.get('defaultZoom'),
                                  'map': Map.getDefaultMap()}
                    params.update({'street': Street.getStreets(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver})
                    return render_template('admin.streets_edit.html', **params)

                elif request.form.get('action') == 'createstreet':  # add street
                    tileserver = {'lat': Settings.get('defaultLat'),
                                  'lng': Settings.get('defaultLng'),
                                  'zoom': Settings.get('defaultZoom'),
                                  'map': Map.getDefaultMap()}

                    params.update({'street': Street('', '', int(module[1]), '', '', '', '', '', ''), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver})
                    return render_template('admin.streets_edit.html', **params)

                elif request.form.get('action').startswith('deletestreets_'):  # delete street
                    db.session.delete(Street.getStreets(id=request.form.get('action').split('_')[-1]))
                    db.session.commit()
                    cache.clear()

                elif request.form.get('action') == 'savestreet':  # save street
                    if request.form.get('street_id') != 'None':  # update existing street
                        street = Street.getStreets(id=request.form.get('street_id'))
                        street.name = request.form.get('edit_name')
                        street.navigation = request.form.get('edit_navigation')
                        c = request.form.get('edit_cityid').split('_')
                        if len(c) < 2:
                            c.append('')
                        street.cityid = c[0]
                        street.subcity = c[1]
                        street.lat = request.form.get('edit_lat')
                        street.lng = request.form.get('edit_lng')
                        street.zoom = request.form.get('edit_zoom')
                        street.active = request.form.get('edit_active')
                        db.session.commit()
                        #cache.delete_memoized(City.streets)

                    else:  # add street
                        c = request.form.get('edit_cityid').split('_')
                        if len(c) < 2:
                            c.append('')  # subcity
                        city = [ct for ct in City.getCities() if str(ct.id) == c[0]][0]
                        city.addStreet(Street(request.form.get('edit_name'), request.form.get('edit_navigation'), int(c[0]), c[1], request.form.get('edit_lat'), request.form.get('edit_lng'), request.form.get('edit_zoom'), request.form.get('edit_active'), ''))
                        db.session.commit()
                    cache.clear()

            try:
                streets = Street.getStreets(cityid=module[-1])
            except AttributeError:
                streets = []
            chars = {}
            for s in streets:
                chars[s.name[0].upper()] = 0
            params.update({'streets': streets, 'chars': sorted(chars.keys()), 'city': City.getCities(id=module[-1])})
            return render_template('admin.streets.html', **params)

    return "streets"
Ejemplo n.º 13
0
    def evalMaterial(field, **params):
        cars = Car.getCars(params=['onlyactive'])
        carlist = [u'{} {}'.format(c.dept.name, c.name) for c in cars]
        c = [[], []]
        for p in [l for l in re.split(r"[\s]{2,}|[\n]+", field.value[0])]:
            addcar = None
            if len([
                    d for d in Department.getDepartments()
                    if d.name in p.strip()
            ]) == 1:  # department default found
                c = [[u'default'] + c[0], [0] + c[1]]
                GenericAlarmFaxChecker().logger.debug(
                    u'material: "{}" default department found'.format(
                        p.strip()))
                continue

            # try list or car names
            repl = difflib.get_close_matches(p.strip(), carlist, 1, cutoff=0.7)
            if len(repl) == 1:
                addcar = filter(
                    lambda x: u'{} {}'.format(x.dept.name, x.name) == repl[0],
                    cars)[0]
                addcar = addcar.name, addcar.id

            else:  # try list of car descriptions
                descriptionlist = [
                    u'{} {}'.format(cn.dept.name, cn.description)
                    for cn in cars
                ]
                repl = difflib.get_close_matches(p.strip(),
                                                 descriptionlist,
                                                 1,
                                                 cutoff=0.7)
                if len(repl) == 1:
                    addcar = filter(
                        lambda x: u'{} {}'.format(x.dept.name, x.description)
                        == repl[0], cars)[0]
                    addcar = addcar.name, addcar.id
                else:
                    t = ""
                    for x in p.split(
                    ):  # try parts of name and stop after first match
                        t += x
                        repl = difflib.get_close_matches(t,
                                                         carlist,
                                                         1,
                                                         cutoff=0.7)
                        if len(repl) == 1:
                            addcar = filter(
                                lambda x: u'{} {}'.format(x.dept.name, x.name)
                                == repl[0], cars)[0]
                            addcar = addcar.name, addcar.id
                            break
            if addcar and addcar[1] not in c[1]:
                c[0].append(addcar[0])
                c[1].append(addcar[1])

        if len(c[0]) > 0:
            GenericAlarmFaxChecker().logger.debug(
                u'material: done with {}, {}'.format(c[0], c[1]))
            field.value = (u','.join(c[0]), u','.join([str(_c)
                                                       for _c in c[1]]))
Ejemplo n.º 14
0
 def checkDefinition(self):
     if len(Department.getDepartments()) == 0:
         return Module.INITNEEDED
     return Module.CHECKOK
Ejemplo n.º 15
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'])
Ejemplo n.º 16
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module cars

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

    if len(module) < 2:
        module.append(u'1')

    if request.method == 'POST':
        if request.form.get('action') == 'createcars':  # add car
            params.update({
                'car': Car('', '', '', '', '', int(module[1])),
                'departments': Department.getDepartments(),
                'cartypes': Settings.getCarTypes()
            })
            return render_template('admin.cars_edit.html', **params)

        elif request.form.get('action') == 'updatecars':  # save car
            if request.form.get('car_id') != 'None':  # update car
                car = Car.getCars(id=request.form.get('car_id'))

            else:  # add car
                car = Car('', '', '', '', '', module[1])
                db.session.add(car)

            car.name = request.form.get('edit_name')
            car.description = request.form.get('edit_description')
            car.fmsid = request.form.get('edit_fmsid')
            car.active = request.form.get('edit_active')
            car.type = request.form.get('edit_type')
            car._dept = request.form.get('edit_department')
            db.session.commit()

        elif request.form.get('action') == 'cancel':
            pass

        elif request.form.get('action').startswith('editcars_'):  # edit car
            params.update({
                'car':
                Car.getCars(id=request.form.get('action').split('_')[-1]),
                'departments':
                Department.getDepartments(),
                'cartypes':
                Settings.getCarTypes()
            })
            return render_template('admin.cars_edit.html', **params)

        elif request.form.get('action').startswith(
                'deletecars_'):  # delete car
            db.session.delete(
                Car.getCars(id=request.form.get('action').split('_')[-1]))
            db.session.commit()
    try:
        cars = Department.getDepartments(module[1]).getCars()
    except AttributeError:
        cars = []
    params.update({'cars': cars})
    return render_template('admin.cars.html', **params)
Ejemplo n.º 17
0
 def getDepartment(self):
     if self.street.city:
         return Department.getDepartments(id=self.street.city.dept)
     else:
         Department.getDefaultDepartment()
Ejemplo n.º 18
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module settings

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

    def chunks(l, n):
        return [l[i:i + n] for i in range(0, len(l), n)]

    if len(module) == 2:
        if module[1] == 'department':  # department submodule
            if request.method == 'POST':
                if request.form.get('action') == 'savedept':  # save department
                    if request.form.get('dep_id') != 'None':  # update
                        department = Department.getDepartments(request.form.get('dep_id'))
                        l = request.form.get('dep_pos')
                    else:  # add
                        l = len(Department.getDepartments()) + 1
                        department = Department('', '', '', 0)
                        db.session.add(department)
                    department.name = request.form.get('dep_name')
                    department.shortname = request.form.get('dep_shortname')
                    department.color = request.form.get('dep_color')
                    department.set(u'address_name', unicode(request.form.get('dep_address_name')))
                    department.set(u'address_street', unicode(request.form.get('dep_address_street')))
                    department.set(u'address_city', unicode(request.form.get('dep_address_city')))
                    department.set(u'address_phone', unicode(request.form.get('dep_address_phone')))
                    department.set(u'address_fax', unicode(request.form.get('dep_address_fax')))
                    department.set(u'address_email', unicode(request.form.get('dep_address_email')))
                    if len(request.files) > 0:
                        uploadfile = request.files.get('dep_logo')
                        if uploadfile.filename != '':
                            _fname, _fext = os.path.splitext(uploadfile.filename)
                            db.session.flush()  # flush to get department id of new department
                            fname = os.path.join(current_app.config.get('PATH_DATA'), 'departmentlogo_{}{}'.format(department.id, _fext))
                            uploadfile.save(fname)
                            department.set(u'logo', u'departmentlogo_{}{}'.format(department.id, _fext))  # store relative path from data directory
                        elif request.form.get('logoaction') == 'deletelogo':
                            if os.path.exists('{}{}'.format(current_app.config.get('PATH_DATA'), department.attributes['logo'])):
                                os.remove('{}{}'.format(current_app.config.get('PATH_DATA'), department.attributes['logo']))
                                department.set(u'logo', u'')
                    department.orderpos = l
                    department.defaultcity = request.form.get('dep_city')
                    db.session.commit()
                    
                elif request.form.get('action') == 'createdepartment':  # add department
                    params.update({'department': Department('', '', '', 0), 'cities': City.getCities()})
                    return render_template('admin.settings.department_actions.html', **params)

                elif request.form.get('action').startswith('detaildept_'):  # edit department
                    params.update({'department': Department.getDepartments(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities()})
                    return render_template('admin.settings.department_actions.html', **params)

                elif request.form.get('action').startswith('deletedept_'):  # delete department
                    _c = []
                    for city in City.getCities():
                        if city.department.id == int(request.form.get('action').split('_')[-1]):
                            _c.append(city.name)
                    if len(_c) == 0:
                        db.session.delete(Department.getDepartments(id=request.form.get('action').split('_')[-1]))
                        db.session.commit()
                    else:
                        params.update({'error': babel.gettext('admin.settings.department_deleteerror1', cities=', '.join(_c))})
                    
                elif request.form.get('action') == 'ordersetting':  # change department order
                    for _id in request.form.getlist('departmentids'):
                        Department.getDepartments(id=_id).orderpos = request.form.getlist('departmentids').index(_id) + 1
                    db.session.commit()
            
            params.update({'departments': Department.getDepartments(), 'cities': City.getCities()})
            return render_template('admin.settings.department.html', **params)

        elif module[1] == 'cars':
            if request.method == 'POST':
                if request.form.get('action') == 'updatetypes':
                    Settings.set('cartypes', [i for i in chunks(request.form.getlist('cartype'), 2) if i[0] != ''])
                    db.session.commit()
            params.update({'cartypes': Settings.getCarTypes()})
            return render_template('admin.settings.cars.html', **params)

        elif module[1] == 'communication':
            from emonitor.extensions import communication
            if request.method == 'POST':
                if request.form.get('action') == 'telegramsettings':
                    vals = Settings.get('telegramsettings')
                    vals['telegramkey'] = request.form.get('telegrambot').strip()
                    vals['welcomemsg'] = request.form.get('welcometext')
                    vals['helpmsg'] = request.form.get('helptext')
                    Settings.set('telegramsettings', vals)
                    db.session.commit()
                    tb = communication.telegram
                    if not tb:
                        communication.init_app(app=communication.app)
                        tb = communication.telegram
                    else:
                        tb.stop()
                    try:
                        tb.updateToken(vals['telegramkey'])
                    except AttributeError:
                        pass

                elif request.form.get('action') == 'telegramgroups':
                    vals = Settings.get('telegramsettings')
                    g = {}
                    for f in filter(lambda x: x.startswith('groupname_'), request.form):
                        _id = f.split('_')[-1]  # fieldname in form
                        if request.form.get('groupname_' + _id) in ['newgroup', '']:
                            continue
                        g[request.form.get('groupname_' + _id)] = request.form.get('members_selectable_' + _id).split(';')
                    vals['groups'] = g
                    Settings.set('telegramsettings', vals)
                    db.session.commit()

            params.update({'bot': communication.telegram, 'settings': Settings.getYaml('telegramsettings'), 'configtelegramkey': current_app.config.get('TELEGRAMKEY', '')})
            return render_template('admin.settings.communication.html', **params)

        elif module[1] == 'start':

            if request.method == 'POST':
                if request.form.get('action') == 'updatestart':  # update start page definition
                    areas = dict()
                    areas['center'] = {'module': request.form.get('center.module'), 'width': '0', 'visible': 1}
                    areas['west'] = {'module': request.form.get('west.module'), 'moduleadd': request.form.getlist('west.module.add'), 'width': '.%s' % request.form.get('west.width'), 'visible': request.form.get('west.visible')}
                    areas['east'] = {'module': request.form.get('east.module'), 'moduleadd': request.form.getlist('east.module.add'), 'width': '.%s' % request.form.get('east.width'), 'visible': request.form.get('east.visible')}

                    Settings.set('frontend.default', areas)
                    db.session.commit()

            def modname(obj):  # get translation for sorting of module
                _t = "module.%s" % obj.info['name']
                return babel.gettext(_t)

            params.update({'mods': sorted([m for m in current_app.blueprints['frontend'].modules.values() if m.frontendContent() == 1], key=modname), 'center': Settings.getFrontendSettings('center'), 'west': Settings.getFrontendSettings('west'), 'east': Settings.getFrontendSettings('east')})
            return render_template('admin.settings.start.html', **params)

    else:

        if request.method == 'POST':  # save settings
            if request.form.get('action') == 'observerstate':
                Settings.set('observer.interval', request.form.get('observerinterval'))
                _jobserver = scheduler.get_jobs('observerinterval')[0]
                if Settings.get('observer.interval', '0') == '0':
                    _jobserver.pause()
                else:
                    scheduler.reschedule_job(_jobserver.id, trigger=eMonitorIntervalTrigger(seconds=int(Settings.get('observer.interval', current_app.config.get('OBSERVERINTERVAL', 2)))))
            elif request.form.get('action') == 'monitorping':
                Settings.set('monitorping', request.form.get('monitorping'))
                _jping = scheduler.get_jobs('monitorping')[0]
                if Settings.get('monitorping', '0') == '0':
                    _jping.pause()
                else:
                    scheduler.reschedule_job(_jping.id, trigger=eMonitorIntervalTrigger(minutes=int(Settings.get('monitorping', current_app.config.get('MONITORPING', 2)))))

        paths = dict(pathdata=current_app.config.get('PATH_DATA'), pathtmp=current_app.config.get('PATH_TMP'), pathincome=current_app.config.get('PATH_INCOME'), pathdone=current_app.config.get('PATH_DONE'))
        params.update({'paths': paths, 'observerinterval': Settings.get('observer.interval', current_app.config.get('OBSERVERINTERVAL')), 'monitorping': Settings.get('monitorping', current_app.config.get('MONITORPING')), 'alarmsevalfields': Settings.get('alarms.evalfields'), 'alembic': alembic})
        return render_template('admin.settings.html', **params)
    return redirect("/admin/settings", code=302)
Ejemplo n.º 19
0
    def handleEvent(eventname, **kwargs):
        """
        Eventhandler for alarm class

        :param eventname: name of event
        :param kwargs: parameter list: error, fields, filename, id, incomepath, mode, time
        :return: all kwargs
        """
        try:
            from emonitor import app
            global LASTALARM

            alarm_fields = dict()
            stime = time.time()
            alarmtype = None
            for t in AlarmType.getAlarmTypes():
                if re.search(t.keywords.replace('\r\n', '|'), kwargs.get('text', '')):
                    alarm_fields = t.interpreterclass().buildAlarmFromText(t, kwargs.get('text', ''))
                    if alarm_fields.get('error'):
                        kwargs['error'] = alarm_fields['error']
                        del alarm_fields['error']
                    alarmtype = t
                    break
            alarm = Alarm(datetime.datetime.now(), '', 1, 0)
            etime = time.time()

            _missing = 0
            for p in ['time', 'city', 'address', 'key']:
                if p not in alarm_fields:  # test required fields
                    _missing += 1
                    kwargs['error'] = kwargs.get('error', 'Missing parameter:') + "<br/>- '{}'".format(p)
            try:
                t = datetime.datetime.strptime(alarm_fields.get('time')[0], '%d.%m.%Y - %H:%M:%S')
            except ValueError:
                t = datetime.datetime.now()
            alarm.timestamp = t

            kwargs['id'] = u'<ul><li>-test-</li></ul>'  # add dummy id
            kwargs['fields'] = u'<ul>'  # set evaluated fields from fax
            for k in sorted(alarm_fields):  # add field values as unicode string
                if len(alarm_fields[k]) > 1:
                    kwargs['fields'] = u'{}<li><b>{}:</b>\n   <small style="color:silver">value:</small> "{}" &rarr; <small style="color:silver">id:</small> {}</li>'.format(kwargs.get('fields'), k, alarm_fields[k][0], alarm_fields[k][1])
                else:
                    kwargs['fields'] = u'{}<li><b>{}:</b>\n  <small style="color:silver">value:</small> "{}"</li>'.format(kwargs.get('fields'), k, alarm_fields[k])
            kwargs['fields'] = kwargs.get('fields', ' ') + '</ul></pre>\n\n<h5> ALARM-Object</h5>\n<pre><ul>'

            if _missing == 0:  # all required parameters found
                if kwargs.get('mode') != 'test':
                    if not os.path.exists('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/'))):
                        os.makedirs('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/')))

                    try:
                        shutil.copy2('{incomepath}{filename}'.format(**kwargs), '{}{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs.get('filename'))[1]))
                    except:
                        pass

                try:  # remove file
                    os.remove('{incomepath}{filename}'.format(**kwargs))
                except:
                    pass
                kwargs['filename'] = '{}{}'.format(t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs['filename'])[1])
                logger.debug('alarm_fields: {}'.format(alarm_fields))

                if len(alarm_fields) == 0:  # no alarmfields found
                    kwargs['id'] = 0
                    logger.error('no alarm fields found.')
                    return kwargs

                if not alarmtype:  # alarmtype not found
                    kwargs['id'] = 0
                    kwargs['error'] = kwargs.get('error', '') + 'alarmtype not found'
                    logger.error('alarmtype not found.')
                    return kwargs

                # position
                if alarm_fields.get('lat'):
                    _position = dict(lat=alarm_fields.get('lat')[0], lng=alarm_fields.get('lng')[0])
                else:
                    _position = dict(lat=u'0.0', lng=u'0.0')
                if USE_NOMINATIM == 1:
                    try:
                        url = 'http://nominatim.openstreetmap.org/search'
                        params = 'format=json&city={}&street={}'.format(alarm_fields['city'][0], alarm_fields['address'][0])
                        if 'streetno' in alarm_fields:
                            params += ' {}'.format(alarm_fields['streetno'][0].split()[0])  # only first value
                        r = requests.get('{}?{}'.format(url, params))
                        _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon'])
                    except:
                        pass

                # create alarm object
                if alarm_fields.get('key', [u'', 0])[0] == u'':
                    if alarmtype.translation(u'_bma_main_') in alarm_fields.get('remark', [u'', 0])[0] or alarmtype.translation(u'_bma_main_') in alarm_fields.get('person', [u'', 0])[0]:
                        alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).all()
                        if len(alarmkey) > 0:
                            alarm_fields['key'] = ('{}: {}'.format(alarmkey[0].category, alarmkey[0].key), str(alarmkey[0].id))
                        else:
                            alarm_fields['key'] = (alarmtype.translation(u'_bma_key_'), u'0')

                if alarm_fields.get('time', [u'', 0])[1] == 1:  # found correct time
                    t = datetime.datetime.strptime(alarm_fields.get('time', [u'', 0])[0], '%d.%m.%Y - %H:%M:%S')
                else:
                    t = datetime.datetime.now()
                alarm.timestamp = t

                alarm.set('id.key', alarm_fields['key'][1])
                alarm._key = alarm_fields['key'][0]
                alarm.material = dict(cars1='', cars2='', material='')  # set required attributes
                alarm.set('marker', '0')
                alarm.set('filename', kwargs['filename'])
                alarm.set('priority', '1')  # set normal priority
                alarm.set('alarmtype', alarmtype.name)  # set checker name
                alarm.position = _position
                alarm.state = 1

                # city
                if alarm_fields.get('city', ['', 0])[1] > 0:
                    alarm.city = City.getCities(id=alarm_fields.get('city')[1])
                    if alarm_fields.get('address'):
                        alarm.street = Street.getStreets(id=alarm_fields.get('address')[1])
                else:  # city not found -> build from fax
                    url = 'http://nominatim.openstreetmap.org/search'

                    if len(alarm_fields.get('city', [u'', 0])[0].split()) > 0:
                        params = u'format=json&city={}&street={}'.format(alarm_fields.get('city', [u'', 0])[0].split()[0], alarm_fields.get('address', [u'', 0])[0])
                        if alarm_fields.get('streetno'):
                            try:
                                params += u' {}'.format(alarm_fields.get('streetno')[0].split()[0])  # only first value
                            except:
                                pass
                            alarm.set('streetno', alarm_fields.get('streetno')[0])
                    try:
                        r = requests.get(u'{}?{}'.format(url, params))
                        logger.debug(u'load address data from nomination with parameters: city={} street={}'.format(alarm_fields.get('city')[0].split()[0], alarm_fields.get('address', ['', 0])[0]))
                        _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon'])
                        alarm.position = _position
                    except:
                        pass
                    if len(alarm_fields.get('city', ['', 0])[0].split()) > 0:
                        alarm.set('city', alarm_fields.get('city', ['', 0])[0].split()[0])
                    alarm.set('id.city', alarm_fields.get('city')[1])
                    alarm.set('address', alarm_fields.get('address', ['', 0])[0])
                    if alarm_fields.get('address', [u'', 0])[1] != 0:
                        alarm.street = Street.getStreets(id=alarm_fields.get('address')[1])

                    if alarm_fields.get('cars'):  # add cars found in material
                        for _c in alarm_fields.get('cars')[1].split(';'):
                            alarm.set('k.cars1', alarm.get('k.cars1') + ';' + _c)

                # street / street2
                if alarm_fields.get('address', [u'', 0]) != '':
                    # check correct city -> change if street has different city
                    if len(str(alarm_fields.get('address')[1]).split(';')) > 0 and alarm_fields.get('address')[1] != 0:
                        _c = []

                        for s in str(alarm_fields.get('address')[1]).split(';'):
                            _s = Street.getStreets(id=s)
                            if _s.cityid and _s.cityid not in _c and _s.cityid == alarm_fields.get('city', [u'', 0])[1]:
                                _c.append(_s.cityid)
                                alarm.street = _s
                                if alarm_fields.get('object', [u'', 0])[1] == 0:
                                    if not alarm_fields.get('lat') and not alarm_fields.get('lng'):
                                        alarm.position = dict(lat=_s.lat, lng=_s.lng, zoom=_s.zoom)
                                        if _position['lat'] != u'0.0' and _position['lng'] != u'0.0':  # set marker if nominatim delivers result
                                            alarm.position = _position
                                            alarm.set('marker', '1')
                    else:  # add unknown street
                        alarm.set('id.address', 0)
                        alarm.set('address', alarm_fields['address'][0])
                # houseno
                if alarm_fields.get('streetno'):
                    alarm.set('streetno', alarm_fields.get('streetno')[0])
                    if alarm_fields.get('id.streetno') and alarm_fields.get('lat') and alarm_fields.get('lng'):
                        alarm.position = dict(lat=alarm_fields.get('lat')[0], lng=alarm_fields.get('lng')[0])
                        alarm.set('id.streetno', alarm_fields.get('id.streetno')[1])
                    else:
                        # new
                        hn = alarm.street.getHouseNumber(name=alarm_fields.get('streetno')[0])
                        if hn:
                            alarm.position = hn.getPosition(0)
                    if alarm_fields.get('zoom'):
                        alarm.set('zoom', alarm_fields.get('zoom')[0])

                # crossing
                if alarm_fields.get('crossing', [u'', 0])[0] != '':
                    if alarm_fields.get('crossing', [u'', 0])[1] != alarm_fields.get('address',[u'', 0])[1]:
                        alarm.set('id.address2', alarm_fields.get('crossing')[1])
                        alarm.set('address2', alarm_fields.get('crossing')[0])
                    else:
                        alarm.set('id.address2', '0')
                        alarm.set('address2', alarm_fields.get('crossing')[0])

                # addresspart
                if alarm_fields.get('addresspart', [u'', 0])[0] != u'' and alarm_fields.get('addresspart', [u'', 0])[0] != alarm_fields.get('address', [u'', 0])[0]:
                    if alarm_fields.get('addresspart')[1] > 0:
                        if len(str(alarm_fields.get('addresspart')[1]).split(';')) > 0:
                            _c = []

                            for s in str(alarm_fields.get('addresspart')[1]).split(';'):
                                try:
                                    _s = Street.getStreets(id=s)
                                    if _s.cityid not in _c and _s.cityid == alarm_fields.get('city')[1]:
                                        _c.append(_s.cityid)
                                        alarm.set('id.address2', _s.id)
                                except:
                                    pass
                        else:
                            alarm.set('id.address2', alarm_fields.get('addresspart')[1])
                    else:
                        alarm.set('id.address2', '0')
                    alarm.set('address2', alarm_fields.get('addresspart')[0])

                # person
                if alarm_fields.get('person', [u'', 0])[0] != u'':
                    alarm.set('person', alarm_fields.get('person')[0])
                # alarmplan
                if alarm_fields.get('alarmplan', [u'', 0])[0] != u'':
                    alarm.set('alarmplan', alarm_fields.get('alarmplan')[0])

                # alarmobject
                _ao = None
                if alarm_fields.get('object', [u'', 0])[0] != u'' and alarm_fields.get('city', [u'', 0])[1] > 0:
                    alarm.set('object', alarm_fields.get('object')[0])
                    alarm.set('id.object', alarm_fields.get('object')[1])
                    # alarmplan from object
                    if alarm_fields.get('object')[1] != 0:
                        _ao = AlarmObject.getAlarmObjects(id=alarm_fields.get('object')[1])

                    if _ao:
                        if _ao.alarmplan != 0:
                            alarm.set('alarmplan', _ao.alarmplan)
                        elif alarm_fields.get('alarmplan'):
                            alarm.set('alarmplan', alarm_fields.get('alarmplan')[0])

                        if _ao.street.id != alarm_fields.get('address', [u'', 0])[1]:  # street config from alarmobject
                            alarm.street = Street.getStreets(id=_ao.street.id)
                            if _ao.streetno == "":
                                alarm.set('streetno', alarm_fields.get('streetno')[0])
                            else:
                                alarm.set('streetno', _ao.streetno)
                        alarm.position = dict(lat=_ao.lat, lng=_ao.lng, zoom=_ao.zoom)

                # remark
                if alarm_fields.get('remark', [u'', 0])[0] != u'':
                    alarm.set('remark', alarm_fields.get('remark')[0])
                    _bma = 0
                    for v in alarmtype.translation(u'_bma_main_').split():
                        if v in alarm_fields.get('remark', [u'', 0])[0] or v in alarm_fields.get('person', [u'', 0])[0]:
                            _bma = 1
                            break
                    if _bma == 1:
                        alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).first()
                        if alarmkey:
                            alarm.set('id.key', alarmkey.id)
                            alarm._key = u'{}: {}'.format(alarmkey.category, alarmkey.key)
                        else:
                            alarm.set('id.key', '0')
                            alarm._key = alarmtype.translation(u'_bma_key_')
                # additional remarks
                if alarm_fields.get('remark2', [u'', 0])[0] != u'':
                    alarm.set('remark', u'{}\n{}'.format(alarm.get('remark'), alarm_fields.get('remark2')[0]))

                # material
                if alarm.get('id.key') != 0 and alarm_fields.get('city'):  # found key with aao
                    if alarm_fields.get('city')[1] not in [0, -1]:  # default city
                        if Department.getDepartments(id=alarm.city.dept).defaultcity == alarm_fields.get('city')[1]:  # default city for dep
                            if alarm_fields.get('material'):
                                if str(alarm_fields.get('material')[1])[0] == '0':  # default cars for aao
                                    try:
                                        alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.street.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.street.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.street.city.dept)]))
                                    except AttributeError:
                                        alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)]))

                                for _c in u'{}'.format(alarm_fields.get('material')[1]).split(','):  # add additional cars
                                    if _c != '0' and _c not in alarm.get('k.cars1').split(','):
                                        alarm.set('k.cars1', u'{},{}'.format(alarm.get('k.cars1'), _c))

                        else:  # only alarmed material
                            alarm.material = dict(cars1=alarm_fields.get('material', [u'', ''])[1])

                    else:  # else city
                        if alarm_fields.get('material', [u'', u''])[1] == u'0':  # default cars for aao
                            alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)]))
                        else:
                            alarm.material = dict(cars1=u','.join(list(OrderedDict.fromkeys(filter(lambda x: x != '0', str(alarm_fields.get('material', ['', '-1'])[1]).split(','))))))

                else:  # default aao of current department (without aao)
                    if alarm_fields.get('city', [u'', 0])[1] != 0:  # found city -> use default aao
                        if City.getCities(id=alarm_fields.get('city')[1]):
                            c = City.getCities(id=alarm_fields.get('city')[1]).dept
                        else:
                            c = City.getDefaultCity().dept
                        akc = Alarmkey.getDefault(c)
                        if len(akc.cars1) + len(akc.cars2) + len(akc.materials) == 0:  # no default aao defined
                            # use cars of fax
                            alarm.material = {'cars1': re.sub(r'^0,', '', alarm_fields.get('material')[1]), 'cars2': '', 'material': ''}
                        else:  # use cars of default aao
                            alarm.material = dict(cars1=u','.join([str(c.id) for c in akc.cars1]), cars2=u",".join([str(c.id) for c in akc.cars2]), material=u",".join([str(c.id) for c in akc.materials]))

                    l = (u'{},{},{}'.format(alarm.get('k.cars1'), alarm.get('k.cars2'), alarm.get('k.material'))).split(',')
                    if len(set(str(alarm_fields.get('material', ([], '-1'))[1]).split(',')).intersection(set(l))) == 0:
                        _dep = Department.getDefaultDepartment()
                        for c in str(alarm_fields.get('material', ([], '-1'))[1]).split(','):
                            if c == u'0':  # default of home department needed
                                alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(_dep.id)]), cars2=u",".join([str(c.id) for c in alarm.key.getCars2(_dep.id)]), material=u",".join([str(c.id) for c in alarm.key.getMaterial(_dep.id)]))
                                break
                        if u'0' not in str(alarm_fields.get('material', ([], '-1'))[1]):  # only single car needed
                            alarm.set('k.cars1', u'{},{}'.format(alarm_fields.get('material', ([], '-1'))[1], alarm.get('k.cars1')))

                if _ao and _ao.hasOwnAAO():  # use aao of current object
                    alarm.material = dict(cars1=u",".join([str(c.id) for c in _ao.getCars1()]), cars2=u",".join([str(c.id) for c in _ao.getCars2()]), material=u",".join([str(c.id) for c in _ao.getMaterial()]))

                if not kwargs.get('time'):
                    kwargs['time'] = []
                kwargs['time'].append('alarm creation done in {} sec.'.format(etime - stime))

            if kwargs.get('mode') != 'test':
                db.session.add(alarm)
                db.session.commit()
                signal.send('alarm', 'added', alarmid=alarm.id)
                Alarm.changeState(alarm.id, 1)  # activate alarm
                logger.info('alarm created with id {} ({})'.format(alarm.id, (etime - stime)))
            else:

                _cdict = Car.getCarsDict()
                for a in sorted(alarm.attributes):
                    try:
                        if a in ['k.cars1', 'k.cars2', 'k.material']:
                            kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">id:</small> "%s" &rarr; "%s"</li>' % (a, alarm.get(a), ", ".join([_cdict[int(_c)].name for _c in alarm.get(a).split(',') if _c not in ['', '0']]))
                        elif a in 'id.key':
                            if alarm.get(a) > 0:
                                _k = Alarmkey.getAlarmkeys(id=alarm.get(a))
                                kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">id:</small> "%s" &rarr; "%s: %s"</li>' % (a, alarm.get(a), _k.category, _k.key)
                            else:
                                kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % (a, alarm.get(a))
                                kwargs['fields'] += '<li><b>key:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % alarm._key
                        elif a == 'id.address':
                            kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">id:</small> "%s" &rarr; "%s"</li>' % (a, alarm.get(a), Street.getStreets(id=alarm.get(a)).name)
                        elif a == 'id.object':
                            kwargs['id.object'] = '<li><b>%s:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % (a, alarm.get(a))
                            kwargs['object'] = '<li><b>object:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % alarm.get('object')
                        else:
                            kwargs['fields'] += '<li><b>%s:</b>\n   <small style="color:silver">value:</small> "%s"</li>' % (a, alarm.get(a))
                    except (AttributeError, KeyError):
                        kwargs['fields'] += '<li style="color:red"><b>%s:</b>\n   <small style="color:silver">value:</small> "%s" (error)</li>' % (a, alarm.get(a))
                kwargs['fields'] += "</ul>"
                db.session.rollback()
                logger.info('alarm created in TESTMODE (%s)' % (etime - stime))
        except:
            signal.send('alarm', 'error', message='alarms.errorincreation', text=kwargs.get('text', ''))

        return kwargs
Ejemplo n.º 20
0
 def getDepartment(self):
     if self.street.city:
         return Department.getDepartments(id=self.street.city.dept)
     else:
         Department.getDefaultDepartment()
Ejemplo n.º 21
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmkeys

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

    if len(module) < 2:
        module.append(u'1')
    
    if len(module) > 2 and module[2] == 'upload':  # upload alarmkeys
        params.update({'': int(module[1]), 'department': module[1]})
        return render_template('admin.alarmkeys.upload.html', **params)
    
    else:
        depid = 1
        try:
            if module[1].isnumeric():
                depid = int(module[1])
        except:
            pass

        if request.method == 'POST':
            if depid == 0:
                if request.form.get('action', '') == 'createset':  # add alarmkeyset
                    params.update({'alarmkeyset': AlarmkeySet('', '', datetime.date.today(), datetime.date.today(), ''), 'setbases': AlarmkeySet.getBases(), 'orphankeys': Alarmkey.getOrphanKeys()})
                    return render_template('admin.alarmkeys.set_actions.html', **params)

                elif request.form.get('action', '').startswith('deleteset_'):
                    db.session.delete(AlarmkeySet.getAlarmkeySets(request.form.get('action', '').split('_')[-1]))
                    db.session.commit()

                elif request.form.get('action', '').startswith('detailset_'):  # edit alarmkeyset
                    params.update({'alarmkeyset': AlarmkeySet.getAlarmkeySets(request.form.get('action').split('_')[-1]), 'setbases': AlarmkeySet.getBases(), 'orphankeys': Alarmkey.getOrphanKeys()})
                    return render_template('admin.alarmkeys.set_actions.html', **params)

                elif request.form.get('action', '') == 'savealarmkeyset':  # save alarmkeyset
                    if request.form.get('set_id', '') == 'None':  # add
                        akset = AlarmkeySet('', '', datetime.date.today(), datetime.date.today(), '')
                        db.session.add(akset)
                    else:
                        akset = AlarmkeySet.getAlarmkeySets(request.form.get('set_id'))
                    akset.name = request.form.get('set_name')
                    if request.form.get('set_startdate', '') != "":
                        akset.startdate = datetime.datetime.strptime(request.form.get('set_startdate'), '%d.%m.%Y')
                    else:
                        akset.startdate = None
                    if request.form.get('set_enddate', '') != "":
                        akset.enddate = datetime.datetime.strptime(request.form.get('set_enddate'), '%d.%m.%Y')
                    else:
                        akset.enddate = None
                    akset.remark = request.form.get('set_remark')
                    akset.base = request.form.get('set_base')
                    db.session.commit()
                    if 'set_assignorphan' in request.form.keys():  # add all orphan keys to current set
                        for key in Alarmkey.getOrphanKeys():
                            key._keyset = int(akset.id)
                        db.session.commit()

                elif request.form.get('action', '').startswith('deletebase_'):
                    if os.path.exists("{}alarmkeysetbase/{}".format(current_app.config.get('PATH_DATA'), "_".join(request.form.get('action', '').split('_')[1:]))):
                        os.remove("{}alarmkeysetbase/{}".format(current_app.config.get('PATH_DATA'), "_".join(request.form.get('action', '').split('_')[1:])))

                params.update({'aksets': AlarmkeySet.getAlarmkeySets(), 'akbases': AlarmkeySet.getBases()})
                return render_template('admin.alarmkeys.set_list.html', **params)

            if request.form.get('action') == 'adddefault':  # add default aao
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'cars': Car.getCars(), 'type': 0})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'savedefault':  # save default aao
                alarmkeycar = AlarmkeyCars.getAlarmkeyCars(kid=9999, dept=request.form.get('deptid'))  # 9999 = default department
                if not alarmkeycar:  # add
                    alarmkeycar = AlarmkeyCars(9999, request.form.get('deptid'), '', '', '')
                    db.session.add(alarmkeycar)

                alarmkeycar.cars1 = request.form.get('cars1')
                alarmkeycar.cars2 = request.form.get('cars2')
                alarmkeycar.materials = request.form.get('material')
                if alarmkeycar.kid != 9999 and request.form.get('cars1') == request.form.get('cars2') == request.form.get('material') == '':  # remove
                    db.session.delete(alarmkeycar)
                db.session.commit()
                
            elif request.form.get('action') == 'editdefault':  # edit default aao
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'aksets': AlarmkeySet.getAlarmkeySets(), 'cars': Car.getCars(), 'type': -1})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'addkey':  # add key
                params.update({'alarmkey': Alarmkey('', '', '', ''), 'depid': depid, 'departments': Department.getDepartments(), 'aksets': AlarmkeySet.getAlarmkeySets(), 'cars': Car.getCars(), 'type': -2})
                return render_template('admin.alarmkeys_actions.html', **params)

            elif request.form.get('action') == 'savekey':  # save key
                if request.form.get('keyid') == 'None':  # add new
                    alarmkey = Alarmkey('', '', '', '')
                    db.session.add(alarmkey)
                    db.session.commit()

                else:  # update existing
                    alarmkey = Alarmkey.getAlarmkeys(request.form.get('keyid'))

                alarmkey.category = request.form.get('category')
                alarmkey.key = request.form.get('key')
                alarmkey.key_internal = request.form.get('keyinternal')
                alarmkey.remark = request.form.get('remark')
                if request.form.get('keyset', '') == '':
                    alarmkey._keyset = None
                else:
                    alarmkey._keyset = request.form.get('keyset')
                alarmkey.setCars(int(request.form.get('deptid')), cars1=request.form.get('cars1'), cars2=request.form.get('cars2'), material=request.form.get('material'))

                alarmkey.keysetitem = None
                if request.form.get('keyset', '') != "":
                    keyset = AlarmkeySet.getAlarmkeySets(request.form.get('keyset'))
                    if keyset:
                        item = filter(lambda x: x.get('stichwort') == alarmkey.category and x.get('schlagwort') == alarmkey.key, keyset.alarmkeys)
                        if len(item) > 0:
                            alarmkey.keysetitem = item[0].get('nr')
                db.session.commit()  # readd

            elif request.form.get('action').startswith('deletecars_'):  # delete car definition
                _op, _kid, _dept = request.form.get('action').split('_')
                keycar = AlarmkeyCars.getAlarmkeyCars(kid=_kid, dept=_dept)
                if keycar:
                    db.session.delete(keycar)
                    db.session.commit()

                # delete key if no definied cars
                if len(AlarmkeyCars.getAlarmkeyCars(kid=_kid)) == 0:
                    key = Alarmkey.getAlarmkeys(id=_kid)
                    db.session.delete(key)
                db.session.commit()
                
            elif request.form.get('action').startswith('editcars_'):  # edit key with cars
                _op, _kid, _dept = request.form.get('action').split('_')
                params.update({'alarmkey': Alarmkey.getAlarmkeys(id=_kid), 'depid': _dept, 'departments': Department.getDepartments(), 'aksets': AlarmkeySet.getAlarmkeySets(), 'cars': Car.getCars(), 'type': 1})
                return render_template('admin.alarmkeys_actions.html', **params)

        if depid == 0:  # edit options
            params.update({'aksets': AlarmkeySet.getAlarmkeySets(), 'departments': Department.getDepartments(), 'akbases': AlarmkeySet.getBases()})
            return render_template('admin.alarmkeys.set_list.html', **params)

        params.update({'depid': depid, 'defaultcars': Alarmkey.getDefault(depid), 'aksets': AlarmkeySet.getAlarmkeySets()})
        return render_template('admin.alarmkeys.html', **params)
Ejemplo n.º 22
0
    def handleEvent(eventname, **kwargs):
        """
        Eventhandler for alarm class

        :param eventname: name of event
        :param kwargs: parameter list: error, fields, filename, id, incomepath, mode, time
        :return: all kwargs
        """
        from emonitor import app
        global LASTALARM

        alarm_fields = dict()
        stime = time.time()
        alarmtype = None
        for t in AlarmType.getAlarmTypes():
            #if re.search(t.keywords.replace('\r\n', '|'), unicode(kwargs['text'], errors='ignore')):
            if re.search(t.keywords.replace('\r\n', '|'), kwargs['text']):
                alarm_fields = t.interpreterclass().buildAlarmFromText(t, kwargs['text'])
                if u'error' in alarm_fields.keys():
                    kwargs['error'] = alarm_fields['error']
                    del alarm_fields['error']
                alarmtype = t
                break

        # copy file -> original name
        if 'time' in alarm_fields and alarm_fields['time'][1] == 1:  # found correct time
            t = datetime.datetime.strptime(alarm_fields['time'][0], '%d.%m.%Y - %H:%M:%S')
        else:
            t = datetime.datetime.now()

        if not os.path.exists('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/'))):
            os.makedirs('{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/')))

        try:
            shutil.copy2('{}{}'.format(kwargs['incomepath'], kwargs['filename']), '{}{}{}'.format(app.config.get('PATH_DONE'), t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs['filename'])[1]))
        except:
            pass
        try:  # remove file
            os.remove('{}{}'.format(kwargs['incomepath'], kwargs['filename']))
        except:
            pass
        kwargs['filename'] = '{}{}'.format(t.strftime('%Y/%m/%Y%m%d-%H%M%S'), os.path.splitext(kwargs['filename'])[1])
        logger.debug('alarm_fields: {}'.format(alarm_fields))

        if len(alarm_fields) == 0:  # no alarmfields found
            kwargs['id'] = 0
            logger.error('no alarm fields found.')
            return kwargs

        kwargs['fields'] = ''
        for k in alarm_fields:
            kwargs['fields'] = u'{}\n-{}:\n  {}'.format(kwargs['fields'], k, alarm_fields[k])

        if not alarmtype:  # alarmtype not found
            kwargs['id'] = 0
            kwargs['error'] = 'alarmtype not found'
            logger.error('alarmtype not found.')
            return kwargs

        # position
        _position = dict(lat=u'0.0', lng=u'0.0')
        if USE_NOMINATIM == 1:
            try:
                url = 'http://nominatim.openstreetmap.org/search'
                params = 'format=json&city={}&street={}'.format(alarm_fields['city'][0], alarm_fields['address'][0])
                if 'streetno' in alarm_fields:
                    params += ' {}'.format(alarm_fields['streetno'][0].split()[0])  # only first value
                r = requests.get('{}?{}'.format(url, params))
                _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon'])
            except:
                pass

        # create alarm object
        if 'key' not in alarm_fields.keys() or alarm_fields['key'][0] == u'':
            if alarmtype.translation(u'_bma_main_') in alarm_fields['remark'][0] or alarmtype.translation(u'_bma_main_') in alarm_fields['person'][0]:
                alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).all()
                if len(alarmkey) > 0:
                    alarm_fields['key'] = ('{}: {}'.format(alarmkey[0].category, alarmkey[0].key), str(alarmkey[0].id))
                else:
                    alarm_fields['key'] = (alarmtype.translation(u'_bma_key_'), u'0')

        if 'time' in alarm_fields and alarm_fields['time'][1] == 1:  # found correct time
            t = datetime.datetime.strptime(alarm_fields['time'][0], '%d.%m.%Y - %H:%M:%S')
        else:
            t = datetime.datetime.now()

        alarm = Alarm(t, alarm_fields['key'][0], 1, 0)
        alarm.set('id.key', alarm_fields['key'][1])
        alarm.material = dict(cars1='', cars2='', material='')  # set required attributes
        alarm.set('marker', '0')
        alarm.set('filename', kwargs['filename'])
        alarm.set('priority', '1')  # set normal priority
        alarm.set('alarmtype', alarmtype.name)  # set checker name
        alarm.state = 1

        # city
        if 'city' in alarm_fields and alarm_fields['city'][1] != 0:
            alarm.city = City.getCities(id=alarm_fields['city'][1])
            if alarm_fields['address'][1] != 0:
                alarm.street = Street.getStreets(id=alarm_fields['address'][1])
        else:  # city not found -> build from fax
            url = 'http://nominatim.openstreetmap.org/search'
            params = u'format=json&city={}&street={}'.format(alarm_fields['city'][0].split()[0], alarm_fields['address'][0])
            if 'streetno' in alarm_fields and alarm_fields['streetno'][0]:
                params += u' {}'.format(alarm_fields['streetno'][0].split()[0])  # only first value
                alarm.set('streetno', alarm_fields['streetno'][0])

            r = requests.get(u'{}?{}'.format(url, params))
            logger.debug('load address data from nomination with parameters: city=%s street=%s' % (alarm_fields['city'][0].split()[0], alarm_fields['address'][0]))
            try:
                _position = dict(lat=r.json()[0]['lat'], lng=r.json()[0]['lon'])
                alarm.position = _position
            except:
                pass

            alarm.set('city', alarm_fields['city'][0].split()[0])
            alarm.set('id.city', alarm_fields['city'][1])
            alarm.set('address', alarm_fields['address'][0])
            if alarm_fields['address'][1] != 0:
                alarm.street = Street.getStreets(id=alarm_fields['address'][1])

            if 'cars' in alarm_fields:  # add cars found in material
                for _c in alarm_fields['cars'][1].split(';'):
                    alarm.set('k.cars1', alarm.get('k.cars1') + ';' + _c)

        # street / street2
        if 'address' in alarm_fields and alarm_fields['address'][0] != '':
            # check correct city -> change if street has different city
            if len(str(alarm_fields['address'][1]).split(';')) > 0 and alarm_fields['address'][1] != 0:
                _c = []

                for s in str(alarm_fields['address'][1]).split(';'):
                    _s = Street.getStreets(id=s)
                    if _s.cityid and _s.cityid not in _c and _s.cityid == alarm_fields['city'][1]:
                        _c.append(_s.cityid)
                        alarm.street = _s
                        if 'object' in alarm_fields and str(alarm_fields['object'][1]) == '0':
                            if 'lat' not in alarm_fields and 'lng' not in alarm_fields:
                                alarm.position = dict(lat=_s.lat, lng=_s.lng, zoom=_s.zoom)
                                if _position['lat'] != u'0.0' and _position['lng'] != u'0.0':  # set marker if nominatim delivers result
                                    alarm.position = _position
                                    alarm.set('marker', '1')
            else:  # add unknown street
                alarm.set('id.address', 0)
                alarm.set('address', alarm_fields['address'][0])
        # houseno
        if 'streetno' in alarm_fields.keys():
            alarm.set('streetno', alarm_fields['streetno'][0])
            if 'id.streetno' in alarm_fields and 'lat' in alarm_fields and 'lng' in alarm_fields:
                alarm.position = dict(lat=alarm_fields['lat'][0], lng=alarm_fields['lng'][0])
                alarm.set('id.streetno', alarm_fields['id.streetno'][1])
            else:
                # new
                hn = alarm.street.getHouseNumber(name=alarm_fields['streetno'][0])
                if hn:
                    alarm.position = hn.getPosition(0)
            if 'zoom' in alarm_fields.keys():
                alarm.set('zoom', alarm_fields['zoom'][0])

        # crossing
        if 'crossing' in alarm_fields and alarm_fields['crossing'][0] != '':
            if 'crossing' in alarm_fields and alarm_fields['address'][1] != alarm_fields['crossing'][1]:
                alarm.set('id.address2', alarm_fields['crossing'][1])
                alarm.set('address2', alarm_fields['crossing'][0])
            else:
                alarm.set('id.address2', '0')
                alarm.set('address2', alarm_fields['crossing'][0])

        # addresspart
        if 'addresspart' in alarm_fields and alarm_fields['addresspart'][0] != '' and alarm_fields['addresspart'][0] != alarm_fields['address'][0]:
            if alarm_fields['addresspart'][1] > 0:
                if len(str(alarm_fields['addresspart'][1]).split(';')) > 0:
                    _c = []

                    for s in str(alarm_fields['addresspart'][1]).split(';'):
                        try:
                            _s = Street.getStreets(id=s)
                            if _s.cityid not in _c and _s.cityid == alarm_fields['city'][1]:
                                _c.append(_s.cityid)
                                alarm.set('id.address2', _s.id)
                        except:
                            pass
                else:
                    alarm.set('id.address2', alarm_fields['addresspart'][1])
            else:
                alarm.set('id.address2', '0')
            alarm.set('address2', alarm_fields['addresspart'][0])

        # person
        if 'person' in alarm_fields and alarm_fields['person'][0] != '':
            alarm.set('person', alarm_fields['person'][0])
        # alarmplan
        if 'alarmplan' in alarm_fields and alarm_fields['alarmplan'][0] != '':
            alarm.set('alarmplan', alarm_fields['alarmplan'][0])

        # alarmobject
        _ao = None
        if 'object' in alarm_fields and alarm_fields['object'][0] != '' and 'city' in alarm_fields and alarm_fields['city'][1] > 0:
            alarm.set('object', alarm_fields['object'][0])
            alarm.set('id.object', alarm_fields['object'][1])
            # alarmplan from object
            if alarm_fields['object'][1] != 0:
                _ao = AlarmObject.getAlarmObjects(id=alarm_fields['object'][1])

            if _ao:
                if _ao.alarmplan != 0:
                    alarm.set('alarmplan', _ao.alarmplan)
                if _ao.street.id != alarm_fields['address'][1]:  # street config from alarmobject
                    alarm.street = Street.getStreets(id=_ao.street.id)
                    if _ao.streetno == "":
                        alarm.set('streetno', alarm_fields['streetno'][0])
                    else:
                        alarm.set('streetno', _ao.streetno)
                alarm.position = dict(lat=_ao.lat, lng=_ao.lng, zoom=_ao.zoom)

        # remark
        if 'remark' in alarm_fields and alarm_fields['remark'][0] != '':
            alarm.set('remark', alarm_fields['remark'][0])
            if alarmtype.translation(u'_bma_main_') in alarm_fields['remark'][0] or alarmtype.translation(u'_bma_main_') in alarm_fields['person'][0]:
                alarmkey = Alarmkey.query.filter(Alarmkey.key.like(u"%{}%".format(alarmtype.translation(u'_bma_')))).first()
                if alarmkey:
                    alarm.set('id.key', alarmkey.id)
                    alarm._key = u'{}: {}'.format(alarmkey.category, alarmkey.key)
                else:
                    alarm.set('id.key', '0')
                    alarm._key = alarmtype.translation(u'_bma_key_')
        # additional remarks
        if 'remark2' in alarm_fields and alarm_fields['remark2'][0] != '':
            alarm.set('remark', u'%s\n%s' % (alarm.get('remark'), alarm_fields['remark2'][0]))

        # material
        if alarm.get('id.key') != 0 and 'city' in alarm_fields:  # found key with aao
            if alarm_fields['city'][1] != 0:  # default city
                if Department.getDepartments(id=alarm.city.dept).defaultcity == alarm_fields['city'][1]:  # default city for dep
                    if 'material' in alarm_fields:
                        if str(alarm_fields['material'][1])[0] == '0':  # default cars for aao
                            try:
                                alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.street.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.street.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.street.city.dept)]))
                            except AttributeError:
                                alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)]))

                        for _c in u'{}'.format(alarm_fields['material'][1]).split(','):  # add additional cars
                            if _c != '0' and _c not in alarm.get('k.cars1').split(','):
                                alarm.set('k.cars1', u'{},{}'.format(alarm.get('k.cars1'), _c))

                else:  # only alarmed material
                    alarm.material = dict(cars1=alarm_fields['material'][1])

            else:  # else city
                if alarm_fields['material'][1] == u'0':  # default cars for aao
                    alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(alarm.city.dept)]), cars2=u','.join([str(c.id) for c in alarm.key.getCars2(alarm.city.dept)]), material=u','.join([str(c.id) for c in alarm.key.getMaterial(alarm.city.dept)]))
                else:
                    alarm.material = dict(cars1=u','.join(list(OrderedDict.fromkeys(filter(lambda x: x != '0', str(alarm_fields['material'][1]).split(','))))))

        else:  # default aao of current department (without aao)
            if alarm_fields['city'][1] != 0:  # found city -> use default aao
                c = City.getCities(id=alarm_fields['city'][1]).dept
                akc = Alarmkey.getDefault(c)
                alarm.material = dict(cars1=u','.join([str(c.id) for c in akc.cars1]), cars2=u",".join([str(c.id) for c in akc.cars2]), material=u",".join([str(c.id) for c in akc.materials]))

            l = (u'%s,%s,%s' % (alarm.get('k.cars1'), alarm.get('k.cars2'), alarm.get('k.material'))).split(',')
            if len(set(str(alarm_fields['material'][1]).split(',')).intersection(set(l))) == 0:
                _dep = Department.getDefaultDepartment()
                for c in alarm_fields['material'][1].split(','):
                    if c == u'0':  # default of home department needed
                        alarm.material = dict(cars1=u','.join([str(c.id) for c in alarm.key.getCars1(_dep.id)]), cars2=u",".join([str(c.id) for c in alarm.key.getCars2(_dep.id)]), material=u",".join([str(c.id) for c in alarm.key.getMaterial(_dep.id)]))
                        break
                if u'0' not in alarm_fields['material'][1]:  # only single car needed
                    alarm.set('k.cars1', u'{},{}'.format(alarm_fields['material'][1], alarm.get('k.cars1')))

        if _ao and _ao.hasOwnAAO():  # use aao of current object
            alarm.material = dict(cars1=u",".join([str(c.id) for c in _ao.getCars1()]), cars2=u",".join([str(c.id) for c in _ao.getCars2()]), material=u",".join([str(c.id) for c in _ao.getMaterial()]))

        if 'time' not in kwargs.keys():
            kwargs['time'] = []
        etime = time.time()
        kwargs['time'].append('alarm creation done in %s sec.' % (etime - stime))

        if kwargs['mode'] != 'test':
            db.session.add(alarm)
            db.session.commit()
            signal.send('alarm', 'added', alarmid=alarm.id)
            Alarm.changeState(alarm.id, 1)  # activate alarm
            logger.info('alarm created with id %s (%s)' % (alarm.id, (etime - stime)))
        else:
            kwargs['fields'] += '\n\n--------------------------\nALARM-Object\n'
            _cdict = Car.getCarsDict()
            for a in alarm.attributes:
                try:
                    if a in ['k.cars1', 'k.cars2', 'k.material']:
                        kwargs['fields'] += '\n-%s:\n  %s -> %s' % (a, alarm.get(a), ", ".join([_cdict[int(_c)].name for _c in alarm.get(a).split(',') if _c != ""]))
                    elif a in 'id.key':
                        _k = Alarmkey.getAlarmkeys(id=alarm.get(a))
                        kwargs['fields'] += '\n-%s:\n  %s -> %s: %s' % (a, alarm.get(a), _k.category, _k.key)
                    elif a == 'id.address':
                        kwargs['fields'] += '\n-%s:\n  %s -> %s' % (a, alarm.get(a), Street.getStreets(id=alarm.get(a)).name)
                    else:
                        kwargs['fields'] += '\n-%s:\n  %s' % (a, alarm.get(a))
                except (AttributeError, KeyError):
                    kwargs['fields'] += '\n-%s:\n  %s (error)' % (a, alarm.get(a))
            kwargs['id'] = '-0'  # add dummy id
            db.session.rollback()
            logger.info('alarm created in TESTMODE (%s)' % (etime - stime))
        return kwargs
Ejemplo n.º 23
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module streets

    :param params: use given parameters of request
    :return: rendered template as string
    """
    module = request.view_args['module'].split('/')
    if len(module) < 2:
        if City.getDefaultCity():
            module.append(u'{}'.format(City.getDefaultCity().id))
        else:
            module.append(u'1')

    if len(module) == 2:  # cities
        if module[1] == '0':  # city list

            if request.method == 'POST':

                if request.form.get('action').startswith('detailcity_'):  # edit city
                    params.update({'city': City.getCities(id=request.form.get('action').split('_')[-1]), 'departments': Department.getDepartments(), 'maps': Map.getMaps()})
                    return render_template('admin.streets.city_edit.html', **params)

                elif request.form.get('action') == 'updatecity':  # update existing city
                    if request.form.get('city_id') != 'None':  # update city
                        city = City.getCities(id=request.form.get('city_id'))
                        city.name = request.form.get('cityname')
                        city.subcity = request.form.get('subcity')
                        city.dept = request.form.get('department')
                        city.mapname = request.form.get('citymap')
                        city.color = request.form.get('colorname')
                        city.default = request.form.get('citydefault')
                        city.osmid = request.form.get('osmid')
                        city.osmname = request.form.get('osmname')

                    else:  # add city
                        city = City(request.form.get('cityname'), request.form.get('department'),
                                    request.form.get('citymap'), request.form.get('citydefault'),
                                    request.form.get('subcity'), request.form.get('colorname'),
                                    request.form.get('osmid'), request.form.get('osmname'))
                        db.session.add(city)

                    db.session.commit()
                    cache.clear()

                elif request.form.get('action') == 'createcity':  # add city
                    params.update({'city': City('', '', '', '', '', '', 0, ''), 'departments': Department.getDepartments(), 'maps': Map.getMaps()})
                    return render_template('admin.streets.city_edit.html', **params)

                elif request.form.get('action').startswith('deletecity_'):  # delete city
                    db.session.delete(City.getCities(id=request.form.get('action').split('_')[-1]))
                    db.session.commit()
                self.updateAdminSubNavigation()
                cache.clear()

            params.update({'cities': City.getCities()})
            return render_template('admin.streets.city_list.html', **params)

        else:  # show city details
            if request.method == 'POST':
                if request.form.get('action').startswith('detailstreet_'):  # edit street
                    tileserver = {'lat': Settings.get('defaultLat'),
                                  'lng': Settings.get('defaultLng'),
                                  'zoom': Settings.get('defaultZoom'),
                                  'map': Map.getDefaultMap()}
                    params.update({'street': Street.getStreets(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver})
                    return render_template('admin.streets_edit.html', **params)

                elif request.form.get('action') == 'createstreet':  # add street
                    tileserver = {'lat': Settings.get('defaultLat'),
                                  'lng': Settings.get('defaultLng'),
                                  'zoom': Settings.get('defaultZoom'),
                                  'map': Map.getDefaultMap()}

                    params.update({'street': Street('', '', int(module[1]), '', '', '', '', '', ''), 'cities': City.getCities(), 'maps': Map.getMaps(), 'tileserver': tileserver})
                    return render_template('admin.streets_edit.html', **params)

                elif request.form.get('action').startswith('deletestreets_'):  # delete street
                    db.session.delete(Street.getStreets(id=request.form.get('action').split('_')[-1]))
                    db.session.commit()
                    cache.clear()

                elif request.form.get('action', '').startswith('deleteallsteets_'):
                    print "delete all streets of", request.form.get('action').split('_')[-1]
                    for s in Street.getStreets(cityid=request.form.get('action').split('_')[-1]):
                        db.session.delete(s)
                    db.session.commit()
                    cache.clear()

                elif request.form.get('action') == 'savestreet':  # save street
                    if request.form.get('street_id') != 'None':  # update existing street
                        street = Street.getStreets(id=request.form.get('street_id'))
                        street.name = request.form.get('edit_name')
                        street.navigation = request.form.get('edit_navigation')
                        c = request.form.get('edit_cityid').split('_')
                        if len(c) < 2:
                            c.append('')
                        street.cityid = c[0]
                        street.subcity = c[1]
                        street.lat = request.form.get('edit_lat')
                        street.lng = request.form.get('edit_lng')
                        street.zoom = request.form.get('edit_zoom')
                        street.active = request.form.get('edit_active')
                        db.session.commit()
                        #cache.delete_memoized(City.streets)

                    else:  # add street
                        c = request.form.get('edit_cityid').split('_')
                        if len(c) < 2:
                            c.append('')  # subcity
                        city = [ct for ct in City.getCities() if str(ct.id) == c[0]][0]
                        city.addStreet(Street(request.form.get('edit_name'), request.form.get('edit_navigation'), int(c[0]), c[1], request.form.get('edit_lat'), request.form.get('edit_lng'), request.form.get('edit_zoom'), request.form.get('edit_active'), 0))
                        db.session.commit()
                    cache.clear()

            try:
                streets = Street.getStreets(cityid=module[-1])
            except AttributeError:
                streets = []
            chars = {}
            for s in streets:
                chars[s.name[0].upper()] = 0
            params.update({'streets': streets, 'chars': sorted(chars.keys()), 'city': City.getCities(id=module[-1])})
            return render_template('admin.streets.html', **params)

    return "streets"
Ejemplo n.º 24
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmkeys

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

    if len(module) < 2:
        module.append(u'1')

    if len(module) > 2 and module[2] == 'upload':  # upload alarmkeys
        params.update({'': int(module[1]), 'department': module[1]})
        return render_template('admin.alarmkeys.upload.html', **params)

    else:
        depid = 1
        try:
            if module[1].isnumeric():
                depid = int(module[1])
        except:
            pass

        if request.method == 'POST':
            if depid == 0:
                if request.form.get('action',
                                    '') == 'createset':  # add alarmkeyset
                    params.update({
                        'alarmkeyset':
                        AlarmkeySet('', '', datetime.date.today(),
                                    datetime.date.today(), ''),
                        'setbases':
                        AlarmkeySet.getBases(),
                        'orphankeys':
                        Alarmkey.getOrphanKeys()
                    })
                    return render_template('admin.alarmkeys.set_actions.html',
                                           **params)

                elif request.form.get('action', '').startswith('deleteset_'):
                    db.session.delete(
                        AlarmkeySet.getAlarmkeySets(
                            request.form.get('action', '').split('_')[-1]))
                    db.session.commit()

                elif request.form.get(
                        'action',
                        '').startswith('detailset_'):  # edit alarmkeyset
                    params.update({
                        'alarmkeyset':
                        AlarmkeySet.getAlarmkeySets(
                            request.form.get('action').split('_')[-1]),
                        'setbases':
                        AlarmkeySet.getBases(),
                        'orphankeys':
                        Alarmkey.getOrphanKeys()
                    })
                    return render_template('admin.alarmkeys.set_actions.html',
                                           **params)

                elif request.form.get(
                        'action', '') == 'savealarmkeyset':  # save alarmkeyset
                    if request.form.get('set_id', '') == 'None':  # add
                        akset = AlarmkeySet('', '', datetime.date.today(),
                                            datetime.date.today(), '')
                        db.session.add(akset)
                    else:
                        akset = AlarmkeySet.getAlarmkeySets(
                            request.form.get('set_id'))
                    akset.name = request.form.get('set_name')
                    if request.form.get('set_startdate', '') != "":
                        akset.startdate = datetime.datetime.strptime(
                            request.form.get('set_startdate'), '%d.%m.%Y')
                    else:
                        akset.startdate = None
                    if request.form.get('set_enddate', '') != "":
                        akset.enddate = datetime.datetime.strptime(
                            request.form.get('set_enddate'), '%d.%m.%Y')
                    else:
                        akset.enddate = None
                    akset.remark = request.form.get('set_remark')
                    akset.base = request.form.get('set_base')
                    db.session.commit()
                    if 'set_assignorphan' in request.form.keys(
                    ):  # add all orphan keys to current set
                        for key in Alarmkey.getOrphanKeys():
                            key._keyset = int(akset.id)
                        db.session.commit()

                elif request.form.get('action', '').startswith('deletebase_'):
                    if os.path.exists("{}alarmkeysetbase/{}".format(
                            current_app.config.get('PATH_DATA'), "_".join(
                                request.form.get('action',
                                                 '').split('_')[1:]))):
                        os.remove("{}alarmkeysetbase/{}".format(
                            current_app.config.get('PATH_DATA'), "_".join(
                                request.form.get('action',
                                                 '').split('_')[1:])))

                params.update({
                    'aksets': AlarmkeySet.getAlarmkeySets(),
                    'akbases': AlarmkeySet.getBases()
                })
                return render_template('admin.alarmkeys.set_list.html',
                                       **params)

            if request.form.get('action') == 'adddefault':  # add default aao
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': 0
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get(
                    'action') == 'savedefault':  # save default aao
                alarmkeycar = AlarmkeyCars.getAlarmkeyCars(
                    kid=9999, dept=request.form.get(
                        'deptid'))  # 9999 = default department
                if not alarmkeycar:  # add
                    alarmkeycar = AlarmkeyCars(9999,
                                               request.form.get('deptid'), '',
                                               '', '')
                    db.session.add(alarmkeycar)

                alarmkeycar.cars1 = request.form.get('cars1')
                alarmkeycar.cars2 = request.form.get('cars2')
                alarmkeycar.materials = request.form.get('material')
                if alarmkeycar.kid != 9999 and request.form.get(
                        'cars1') == request.form.get(
                            'cars2') == request.form.get(
                                'material') == '':  # remove
                    db.session.delete(alarmkeycar)
                db.session.commit()

            elif request.form.get(
                    'action') == 'editdefault':  # edit default aao
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'aksets': AlarmkeySet.getAlarmkeySets(),
                    'cars': Car.getCars(),
                    'type': -1
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get('action') == 'addkey':  # add key
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'aksets': AlarmkeySet.getAlarmkeySets(),
                    'cars': Car.getCars(),
                    'type': -2
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get('action') == 'savekey':  # save key
                if request.form.get('keyid') == 'None':  # add new
                    alarmkey = Alarmkey('', '', '', '')
                    db.session.add(alarmkey)
                    db.session.commit()

                else:  # update existing
                    alarmkey = Alarmkey.getAlarmkeys(request.form.get('keyid'))

                alarmkey.category = request.form.get('category')
                alarmkey.key = request.form.get('key')
                alarmkey.key_internal = request.form.get('keyinternal')
                alarmkey.remark = request.form.get('remark')
                if request.form.get('keyset', '') == '':
                    alarmkey._keyset = None
                else:
                    alarmkey._keyset = request.form.get('keyset')
                alarmkey.setCars(int(request.form.get('deptid')),
                                 cars1=request.form.get('cars1'),
                                 cars2=request.form.get('cars2'),
                                 material=request.form.get('material'))

                alarmkey.keysetitem = None
                if request.form.get('keyset', '') != "":
                    keyset = AlarmkeySet.getAlarmkeySets(
                        request.form.get('keyset'))
                    if keyset:
                        item = filter(
                            lambda x: x.get('stichwort') == alarmkey.category
                            and x.get('schlagwort') == alarmkey.key,
                            keyset.alarmkeys)
                        if len(item) > 0:
                            alarmkey.keysetitem = item[0].get('nr')
                db.session.commit()  # readd

            elif request.form.get('action').startswith(
                    'deletecars_'):  # delete car definition
                _op, _kid, _dept = request.form.get('action').split('_')
                keycar = AlarmkeyCars.getAlarmkeyCars(kid=_kid, dept=_dept)
                if keycar:
                    db.session.delete(keycar)
                    db.session.commit()

                # delete key if no definied cars
                if len(AlarmkeyCars.getAlarmkeyCars(kid=_kid)) == 0:
                    key = Alarmkey.getAlarmkeys(id=_kid)
                    db.session.delete(key)
                db.session.commit()

            elif request.form.get('action').startswith(
                    'editcars_'):  # edit key with cars
                _op, _kid, _dept = request.form.get('action').split('_')
                params.update({
                    'alarmkey': Alarmkey.getAlarmkeys(id=_kid),
                    'depid': _dept,
                    'departments': Department.getDepartments(),
                    'aksets': AlarmkeySet.getAlarmkeySets(),
                    'cars': Car.getCars(),
                    'type': 1
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

        if depid == 0:  # edit options
            params.update({
                'aksets': AlarmkeySet.getAlarmkeySets(),
                'departments': Department.getDepartments(),
                'akbases': AlarmkeySet.getBases()
            })
            return render_template('admin.alarmkeys.set_list.html', **params)

        alarmkeys_count = []
        ak = Alarmkey
        counted_keys = db.get(ak.category.label('category'),
                              func.count(ak.key).label('key'),
                              ak.id.label('id')).group_by(ak.category, ak.id)
        _sum = 0
        for r in counted_keys.all():
            alarmkeys_count.append([r.category, r.key, r.id])
            _sum += int(r.key)

        params.update({
            'depid': depid,
            'defaultcars': Alarmkey.getDefault(depid),
            'aksets': AlarmkeySet.getAlarmkeySets()
        })
        return render_template('admin.alarmkeys.html', **params)
Ejemplo n.º 25
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module settings

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

    def chunks(l, n):
        return [l[i:i + n] for i in range(0, len(l), n)]

    if len(module) == 2:
        if module[1] == 'department':  # department submodule
            if request.method == 'POST':
                if request.form.get('action') == 'savedept':  # save department
                    if request.form.get('dep_id') != 'None':  # update
                        department = Department.getDepartments(request.form.get('dep_id'))
                        l = request.form.get('dep_pos')
                    else:  # add
                        l = len(Department.getDepartments()) + 1
                        department = Department('', '', '', 0)
                        db.session.add(department)
                    department.name = request.form.get('dep_name')
                    department.shortname = request.form.get('dep_shortname')
                    department.color = request.form.get('dep_color')
                    department.set(u'address_name', unicode(request.form.get('dep_address_name')))
                    department.set(u'address_street', unicode(request.form.get('dep_address_street')))
                    department.set(u'address_city', unicode(request.form.get('dep_address_city')))
                    department.set(u'address_phone', unicode(request.form.get('dep_address_phone')))
                    department.set(u'address_fax', unicode(request.form.get('dep_address_fax')))
                    department.set(u'address_email', unicode(request.form.get('dep_address_email')))
                    if len(request.files) > 0:
                        uploadfile = request.files.get('dep_logo')
                        if uploadfile.filename != '':
                            _fname, _fext = os.path.splitext(uploadfile.filename)
                            db.session.flush()  # flush to get department id of new department
                            fname = os.path.join(current_app.config.get('PATH_DATA'), 'departmentlogo_{}{}'.format(department.id, _fext))
                            uploadfile.save(fname)
                            department.set(u'logo', u'departmentlogo_{}{}'.format(department.id, _fext))  # store relative path from data directory
                        elif request.form.get('logoaction') == 'deletelogo':
                            if os.path.exists('{}{}'.format(current_app.config.get('PATH_DATA'), department.attributes['logo'])):
                                os.remove('{}{}'.format(current_app.config.get('PATH_DATA'), department.attributes['logo']))
                                department.set(u'logo', u'')
                    department.orderpos = l
                    department.defaultcity = request.form.get('dep_city')
                    db.session.commit()
                    
                elif request.form.get('action') == 'createdepartment':  # add department
                    params.update({'department': Department('', '', '', 0), 'cities': City.getCities()})
                    return render_template('admin.settings.department_actions.html', **params)

                elif request.form.get('action').startswith('detaildept_'):  # edit department
                    params.update({'department': Department.getDepartments(id=request.form.get('action').split('_')[-1]), 'cities': City.getCities()})
                    return render_template('admin.settings.department_actions.html', **params)

                elif request.form.get('action').startswith('deletedept_'):  # delete department
                    _c = []
                    for city in City.getCities():
                        if city.department.id == int(request.form.get('action').split('_')[-1]):
                            _c.append(city.name)
                    if len(_c) == 0:
                        db.session.delete(Department.getDepartments(id=request.form.get('action').split('_')[-1]))
                        db.session.commit()
                    else:
                        params.update({'error': babel.gettext('admin.settings.department_deleteerror1', cities=', '.join(_c))})
                    
                elif request.form.get('action') == 'ordersetting':  # change department order
                    for _id in request.form.getlist('departmentids'):
                        Department.getDepartments(id=_id).orderpos = request.form.getlist('departmentids').index(_id) + 1
                    db.session.commit()
            
            params.update({'departments': Department.getDepartments(), 'cities': City.getCities()})
            return render_template('admin.settings.department.html', **params)

        elif module[1] == 'cars':
            if request.method == 'POST':
                if request.form.get('action') == 'updatetypes':
                    Settings.set('cartypes', [i for i in chunks(request.form.getlist('cartype'), 2) if i[0] != ''])
                    db.session.commit()
            params.update({'cartypes': Settings.getCarTypes()})
            return render_template('admin.settings.cars.html', **params)

        elif module[1] == 'communication':
            from emonitor.extensions import communication
            if request.method == 'POST':
                if request.form.get('action') == 'telegramsettings':
                    vals = Settings.get('telegramsettings')
                    vals['telegramkey'] = request.form.get('telegrambot').strip()
                    vals['welcomemsg'] = request.form.get('welcometext')
                    vals['helpmsg'] = request.form.get('helptext')
                    Settings.set('telegramsettings', vals)
                    db.session.commit()
                    tb = communication.telegram
                    if not tb:
                        communication.init_app(app=communication.app)
                        tb = communication.telegram
                    #else:
                     #   tb.stop()
                    try:
                        tb.updateToken(vals['telegramkey'])
                    except AttributeError:
                        pass

                elif request.form.get('action') == 'telegramgroups':
                    vals = Settings.get('telegramsettings')
                    g = {}
                    for f in filter(lambda x: x.startswith('groupname_'), request.form):
                        _id = f.split('_')[-1]  # fieldname in form
                        if request.form.get('groupname_' + _id) in ['newgroup', '']:
                            continue
                        g[request.form.get('groupname_' + _id)] = request.form.get('members_selectable_' + _id).split(';')
                    vals['groups'] = g
                    Settings.set('telegramsettings', vals)
                    db.session.commit()

            params.update({'bot': communication.telegram, 'settings': Settings.getYaml('telegramsettings'), 'configtelegramkey': current_app.config.get('TELEGRAMKEY', '')})
            return render_template('admin.settings.communication.html', **params)

        elif module[1] == 'start':

            if request.method == 'POST':
                if request.form.get('action') == 'updatestart':  # update start page definition
                    areas = dict()
                    areas['center'] = {'module': request.form.get('center.module'), 'width': '0', 'visible': 1}
                    areas['west'] = {'module': request.form.get('west.module'), 'moduleadd': request.form.getlist('west.module.add'), 'width': '.%s' % request.form.get('west.width'), 'visible': request.form.get('west.visible')}
                    areas['east'] = {'module': request.form.get('east.module'), 'moduleadd': request.form.getlist('east.module.add'), 'width': '.%s' % request.form.get('east.width'), 'visible': request.form.get('east.visible')}

                    Settings.set('frontend.default', areas)
                    db.session.commit()

            def modname(obj):  # get translation for sorting of module
                _t = "module.%s" % obj.info['name']
                return babel.gettext(_t)

            params.update({'mods': sorted([m for m in current_app.blueprints['frontend'].modules.values() if m.frontendContent() == 1], key=modname), 'center': Settings.getFrontendSettings('center'), 'west': Settings.getFrontendSettings('west'), 'east': Settings.getFrontendSettings('east')})
            return render_template('admin.settings.start.html', **params)

    else:

        if request.method == 'POST':  # save settings
            if request.form.get('action') == 'observerstate':
                Settings.set('observer.interval', request.form.get('observerinterval'))
                if 'observerinterval' in [j.name for j in scheduler.get_jobs()]:  # use file
                    _jobserver = scheduler.get_jobs('observerinterval')[0]
                    if Settings.get('observer.interval', '0') == '0':
                        _jobserver.pause()
                    else:
                        scheduler.reschedule_job(_jobserver.id, trigger=eMonitorIntervalTrigger(seconds=int(Settings.get('observer.interval', current_app.config.get('OBSERVERINTERVAL', 2)))))

            elif request.form.get('action') == 'monitorping':
                Settings.set('monitorping', request.form.get('monitorping'))
                _jping = scheduler.get_jobs('monitorping')[0]
                if Settings.get('monitorping', '0') == '0':
                    _jping.pause()
                else:
                    scheduler.reschedule_job(_jping.id, trigger=eMonitorIntervalTrigger(minutes=int(Settings.get('monitorping', current_app.config.get('MONITORPING', 2)))))

        paths = dict(pathdata=current_app.config.get('PATH_DATA'), pathtmp=current_app.config.get('PATH_TMP'), pathincome=current_app.config.get('PATH_INCOME'), pathdone=current_app.config.get('PATH_DONE'))
        params.update({'paths': paths, 'observerinterval': Settings.get('observer.interval', current_app.config.get('OBSERVERINTERVAL')), 'watchdog': 'observerinterval' not in [j.name for j in scheduler.get_jobs()], 'monitorping': Settings.get('monitorping', current_app.config.get('MONITORPING')), 'alarmsevalfields': Settings.get('alarms.evalfields'), 'alembic': alembic})
        return render_template('admin.settings.html', **params)
    return redirect("/admin/settings", code=302)
Ejemplo n.º 26
0
def getAdminContent(self, **params):
    """
    Deliver admin content of module alarmkeys

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

    if len(module) < 2:
        module.append(u'1')

    if len(module) > 2 and module[2] == 'upload':  # upload alarmkeys
        params.update({'': int(module[1]), 'department': module[1]})
        return render_template('admin.alarmkeys.upload.html', **params)

    else:
        depid = 1
        try:
            if int(module[1]):
                depid = int(module[1])
        except:
            pass

        if request.method == 'POST':
            if request.form.get('action') == 'adddefault':  # add default aao
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': 0
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get(
                    'action') == 'savedefault':  # save default aao
                alarmkeycar = AlarmkeyCars.getAlarmkeyCars(
                    kid=9999, dept=request.form.get(
                        'deptid'))  # 9999 = default department
                if not alarmkeycar:  # add
                    alarmkeycar = AlarmkeyCars(9999,
                                               request.form.get('deptid'), '',
                                               '', '')
                    db.session.add(alarmkeycar)

                alarmkeycar.cars1 = request.form.get('cars1')
                alarmkeycar.cars2 = request.form.get('cars2')
                alarmkeycar.materials = request.form.get('material')
                if alarmkeycar.kid != 9999 and request.form.get(
                        'cars1') == request.form.get(
                            'cars2') == request.form.get(
                                'material') == '':  # remove
                    db.session.delete(alarmkeycar)
                db.session.commit()

            elif request.form.get(
                    'action') == 'editdefault':  # edit default aao
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': -1
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get('action') == 'addkey':  # add key
                params.update({
                    'alarmkey': Alarmkey('', '', '', ''),
                    'depid': depid,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': -2
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

            elif request.form.get('action') == 'savekey':  # save key
                if request.form.get('keyid') == 'None':  # add new
                    alarmkey = Alarmkey('', '', '', '')
                    db.session.add(alarmkey)
                    db.session.commit()

                else:  # update existing
                    alarmkey = Alarmkey.getAlarmkeys(request.form.get('keyid'))

                alarmkey.category = request.form.get('category')
                alarmkey.key = request.form.get('key')
                alarmkey.key_internal = request.form.get('keyinternal')
                alarmkey.remark = request.form.get('remark')
                alarmkey.setCars(int(request.form.get('deptid')),
                                 cars1=request.form.get('cars1'),
                                 cars2=request.form.get('cars2'),
                                 material=request.form.get('material'))
                db.session.commit()

            elif request.form.get('action').startswith(
                    'deletecars_'):  # delete car definition
                _op, _kid, _dept = request.form.get('action').split('_')
                keycar = AlarmkeyCars.getAlarmkeyCars(kid=_kid, dept=_dept)
                if keycar:
                    db.session.delete(keycar)
                    db.session.commit()

                # delete key if no definied cars
                if len(AlarmkeyCars.getAlarmkeyCars(kid=_kid)) == 0:
                    key = Alarmkey.getAlarmkeys(id=_kid)
                    db.session.delete(key)
                db.session.commit()

            elif request.form.get('action').startswith(
                    'editcars_'):  # edit key with cars
                _op, _kid, _dept = request.form.get('action').split('_')
                params.update({
                    'alarmkey': Alarmkey.getAlarmkeys(id=_kid),
                    'depid': _dept,
                    'departments': Department.getDepartments(),
                    'cars': Car.getCars(),
                    'type': 1
                })
                return render_template('admin.alarmkeys_actions.html',
                                       **params)

        alarmkeys_count = []
        ak = Alarmkey
        counted_keys = db.get(ak.category.label('category'),
                              func.count(ak.key).label('key'),
                              ak.id.label('id')).group_by(ak.category)
        _sum = 0
        for r in counted_keys.all():
            alarmkeys_count.append([r.category, r.key, r.id])
            _sum += int(r.key)

        params.update({
            'alarmkeys_count': alarmkeys_count,
            'depid': depid,
            'defaultcars': Alarmkey.getDefault(depid),
            'sum': _sum
        })
        return render_template('admin.alarmkeys.html', **params)
Ejemplo n.º 27
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'])