def get_city(self): # deliver city object if self.get('id.city', '0') != '0': # city found return City.getCities(id=self.get('id.city')) elif self.get('id.city', '0') == '0': # not in list return City(self.get('city', ''), 1, 'osmap', 0, '', '', 0, '') else: return City.getDefaultCity()
def evalCity(fieldname, **params): if fieldname in FezAlarmFaxChecker().fields: _str = FezAlarmFaxChecker().fields[fieldname][0] else: # city not found -> use default city city = City.getDefaultCity() FezAlarmFaxChecker().fields[fieldname] = (city.name, city.id) raise alarmtype = params.get('alarmtype', None) if _str.strip() == '': FezAlarmFaxChecker().fields[fieldname] = ('', 0) cities = City.getCities() for city in cities: # test first word with defined subcities of cities try: repl = difflib.get_close_matches(_str.split()[0], city.subcities + [city.name], 1, cutoff=0.7) if len(repl) > 0: FezAlarmFaxChecker().fields[fieldname] = (repl[0], city.id) return except: pass for city in cities: # test whole string with subcities repl = difflib.get_close_matches(_str, city.subcities + [city.name], 1) if len(repl) > 0: FezAlarmFaxChecker().fields[fieldname] = (repl[0], city.id) return for s in _str.split(): for c in cities: repl = difflib.get_close_matches(s, [c.name], 1, cutoff=0.7) if len(repl) == 1: FezAlarmFaxChecker().fields[fieldname] = (repl[0], c.id) return if alarmtype.translation(u'_default_city_') in _str.lower(): d_city = filter(lambda c: c.default == 1, cities) if len(d_city) == 1: FezAlarmFaxChecker().fields[fieldname] = (d_city[0].name, d_city[0].id) return # use default city city = City.getDefaultCity() FezAlarmFaxChecker().fields[fieldname] = (city.name, city.id) return if _str.startswith('in'): # remove 'in' and plz _str = re.sub(r'in*|[0-9]*', '', _str[2:].strip()) FezAlarmFaxChecker().fields[fieldname] = ( _str, 0) # return original if no match return
def evalCity(fieldname, **params): if fieldname in FezAlarmFaxChecker().fields: _str = FezAlarmFaxChecker().fields[fieldname][0] else: # city not found -> use default city city = City.getDefaultCity() FezAlarmFaxChecker().fields[fieldname] = (city.name, city.id) raise alarmtype = None if 'alarmtype' in params: alarmtype = params['alarmtype'] if _str.strip() == '': FezAlarmFaxChecker().fields[fieldname] = ('', 0) cities = City.getCities() for city in cities: # test first word with defined subcities of cities try: repl = difflib.get_close_matches(_str.split()[0], city.subcities + [city.name], 1, cutoff=0.7) if len(repl) > 0: FezAlarmFaxChecker().fields[fieldname] = (repl[0], city.id) return except: pass for city in cities: # test whole string with subcities repl = difflib.get_close_matches(_str, city.subcities + [city.name], 1) if len(repl) > 0: FezAlarmFaxChecker().fields[fieldname] = (repl[0], city.id) return for s in _str.split(): for c in cities: repl = difflib.get_close_matches(s, [c.name], 1, cutoff=0.7) if len(repl) == 1: FezAlarmFaxChecker().fields[fieldname] = (repl[0], c.id) return if alarmtype.translation(u'_default_city_') in _str.lower(): d_city = filter(lambda c: c.default == 1, cities) if len(d_city) == 1: FezAlarmFaxChecker().fields[fieldname] = (d_city[0].name, d_city[0].id) return # use default city city = City.getDefaultCity() FezAlarmFaxChecker().fields[fieldname] = (city.name, city.id) return if _str.startswith('in'): # remove 'in' and plz _str = re.sub(r'in*|[0-9]*', '', _str[2:].strip()) FezAlarmFaxChecker().fields[fieldname] = (_str, 0) # return original if no match return
def evalCity(field, **params): alarmtype = params.get('alarmtype', None) field.value = (field.value[0], -1) if field.value[0].strip() == '': field.value = ('', -1) cities = City.getCities() for city in cities: # test first word with defined subcities of cities try: repl = difflib.get_close_matches(field.value[0].split()[0], city.subcities + [city.name], 1, cutoff=0.7) if len(repl) > 0: field.value = (repl[0], city.id) return except: pass for city in cities: # test whole string with subcities repl = difflib.get_close_matches(field.value[0], city.subcities + [city.name], 1) if len(repl) > 0: field.value = (repl[0], city.id) return for s in field.value[0].split(): for c in cities: repl = difflib.get_close_matches(s, [c.name], 1, cutoff=0.7) if len(repl) == 1: field.value = (repl[0], c.id) return if alarmtype.translation( u'_default_city_').lower() in field.value[0].lower(): d_city = filter(lambda c: c.default == 1, cities) if len(d_city) == 1: field.value = (d_city[0].name, d_city[0].id) return # use default city city = City.getDefaultCity() field.value = (city.name, city.id) return if field.value[0].startswith('in'): # remove 'in' and plz field.value = (re.sub(r'in*|[0-9]*', '', field.value[0][2:].strip()), field.value[1])
def loadHousenumbersFromOsm(streets): # load all housenumbers from osm """ Load all housenumbers of given street from OpenStreetMap :param streets: list of :py:class:`emonitor.modules.streets.street.Street` :return: number of housenumbers of given streeet """ global URL housenumbers = {} for street in streets: nodes = {} ways = [] city = City.getCities(id=street.cityid) SEARCHSTRING = 'area[name~"%s"];way(area)[building]["addr:street"="%s"];(._;>;);out;' % ( city.osmname, street.name) r = requests.post(URL, data={'data': SEARCHSTRING}) xmldoc = minidom.parseString(r.content) for node in xmldoc.getElementsByTagName('node'): nodes[node.attributes['id'].value] = [ float(node.attributes['lat'].value), float(node.attributes['lon'].value) ] for way in xmldoc.getElementsByTagName('way'): ways.append(way) # try with associatedStreet SEARCHSTRING = 'area[name~"%s"];rel[type=associatedStreet](area)->.allASRelations;way(r.allASRelations:"street")[name="%s"];rel(bw:"street")[type=associatedStreet]->.relationsWithRoleStreet;way(r.relationsWithRoleStreet)[building];(._;>;);out;' % ( city.osmname, street.name) r = requests.post(URL, data={'data': SEARCHSTRING}) xmldoc = minidom.parseString(r.content) for node in xmldoc.getElementsByTagName('node'): nodes[node.attributes['id'].value] = [ float(node.attributes['lat'].value), float(node.attributes['lon'].value) ] for way in xmldoc.getElementsByTagName('way'): ways.append(way) _numbers = 0 for way in ways: nd = [] _id = None for c in way.childNodes: if c.nodeName == "nd": nd.append(nodes[c.attributes['ref'].value]) if c.nodeName == "tag" and c.attributes[ 'k'].value == 'addr:housenumber': _id = c.attributes['v'].value if _id: housenumbers[_id] = nd street.addHouseNumber(_id, housenumbers[_id]) _numbers += 1 signal.send('housenumber', 'osm', street=street.name, hnumbers=_numbers, position=(streets.index(street) + 1, len(streets)), cityid=city.id) signal.send('housenumber', 'osmdone', numbers=len(housenumbers)) return len(housenumbers)
def loadCitiesFromOsm(): """ Load all cities from OpenStreetMap, use bounding box for position :return: rendered template """ global URL map_details = Map.getMaps()[0].getMapBox(tilepath=current_app.config.get('PATH_TILES')) SEARCHSTRING = 'rel[boundary=administrative](%s,%s,%s,%s);out;' % (map_details['min_latdeg'], map_details['min_lngdeg'], map_details['max_latdeg'], map_details['max_lngdeg']) # search all cities in bounding box requests.session() r = requests.post(URL, data={'data': SEARCHSTRING}) xmldoc = minidom.parseString(r.content) relations = xmldoc.getElementsByTagName('relation') osmids = [c.osmid for c in City.getCities()] cities = [] for relation in relations: for tag in relation.childNodes: if tag.nodeName == "tag" and tag.attributes['k'].value == 'name': cities.append([relation.attributes['id'].value, tag.attributes['v'].value, int(relation.attributes['id'].value) in osmids]) cities.sort(lambda x, y: cmp(x[1], y[1])) return render_template('admin.streets.city_osm.html', cities=cities)
def loadCitiesFromOsm(): """ Load all cities from OpenStreetMap, use bounding box for position :return: rendered template """ global URL map_details = Map.getMaps()[0].getMapBox( tilepath=current_app.config.get('PATH_TILES')) SEARCHSTRING = 'rel[boundary=administrative](%s,%s,%s,%s);out;' % ( map_details['min_latdeg'], map_details['min_lngdeg'], map_details['max_latdeg'], map_details['max_lngdeg'] ) # search all cities in bounding box requests.session() r = requests.post(URL, data={'data': SEARCHSTRING}) xmldoc = minidom.parseString(r.content) relations = xmldoc.getElementsByTagName('relation') osmids = [c.osmid for c in City.getCities()] cities = [] for relation in relations: for tag in relation.childNodes: if tag.nodeName == "tag" and tag.attributes['k'].value == 'name': cities.append([ relation.attributes['id'].value, tag.attributes['v'].value, int(relation.attributes['id'].value) in osmids ]) cities.sort(lambda x, y: cmp(x[1], y[1])) return render_template('admin.streets.city_osm.html', cities=cities)
def getFrontendContent(**params): if 'area' not in params.keys() and request.args.get('area', '') != '': params['area'] = request.args.get('area') if 'area' in params.keys() and params['area'] in ['west', 'east']: # small area view return render_template('frontend.locations_smallarea.html', cities=City.getCities(), alarmobjects=AlarmObject.getAlarmObjects(), alarmobjecttypes=AlarmObjectType.getAlarmObjectTypes(), frontendarea=params['area']) return ""
def getFrontendData(self): """ Deliver frontend content of module streets (ajax) :return: rendered template as string or json dict """ if request.args.get('action') == 'streetcoords': # get map parameter for given streetid if request.args.get('id') not in ['', 'None']: street = Street.getStreets(id=request.args.get('id')) return {'lat': street.lat, 'lng': street.lng, 'zoom': street.zoom, 'way': street.navigation, 'cityid': street.cityid, 'cityname': street.city.name} elif request.args.get('action') == 'housecoords': # deliver center of housenumbers if request.args.get('streetid') != '' and request.args.get('housenumber') != '': street = Street.getStreet(id=request.args.get('streetid')) hnumber = street.getHouseNumber(number=request.args.get('housenumber').split()[0]) if hnumber: return hnumber.getPosition(0) return {'lat': street.lat, 'lng': street.lng} return {} elif request.args.get('action') == 'defaultposition': return {'defaultlat': float(Settings.get('defaultLat')), 'defaultlng': float(Settings.get('defaultLng')), 'defaultzoom': int(Settings.get('defaultZoom'))} elif request.args.get('action') == 'alarmposition': alarm = Alarm.getAlarms(id=request.args.get('alarmid')) if alarm: return {'id': request.args.get('alarmid'), 'alarmlat': alarm.lat, 'alarmlng': alarm.lng, 'alarmzoom': alarm.zoom, 'marker': alarm.marker, 'alarmprio': alarm.priority, 'alarmstreet': alarm.street.name, 'alarmstreetno': alarm.get('streetno'), 'alarmstreet2': alarm.get('address2'), 'alarmcity': alarm.city.name, 'alarmsubcity': alarm.street.subcity} else: return {'id': '0'} elif request.args.get('action') == 'streetslookup': streets = {} cities = {} for c in City.getCities(): cities[c.id] = c.name for k, street in c.streets.iteritems(): if street.active: try: streets[str(street.id)] = '%s (%s)' % (street.name, c.name) except: streets[str(street.id)] = '%s (-%s-)' % (street.name, street.cityid) return streets elif request.args.get('action') == 'defaultmap': dmap = Map.getDefaultMap() return {'tileserver': dmap.tileserver, 'name': dmap.name} return ""
def updateAdminSubNavigation(self): """ Add subnavigation for admin area """ from .city import City self.adminsubnavigation = [] for c in City.getCities(): self.adminsubnavigation.append((u"/admin/streets/{}".format(c.id), c.name)) self.adminsubnavigation.append(('/admin/streets/0', babel.gettext('admin.streets.cities.edit...')))
def evalCity(field, **params): alarmtype = params.get('alarmtype', None) field.value = (field.value[0], -1) if field.value[0].strip() == '': field.value = ('', -1) cities = City.getCities() for city in cities: # test first word with defined subcities of cities try: repl = difflib.get_close_matches(field.value[0].split()[0], city.subcities + [city.name], 1, cutoff=0.7) if len(repl) > 0: field.value = (repl[0], city.id) return except: pass for city in cities: # test whole string with subcities repl = difflib.get_close_matches(field.value[0], city.subcities + [city.name], 1) if len(repl) > 0: field.value = (repl[0], city.id) return for s in field.value[0].split(): for c in cities: repl = difflib.get_close_matches(s, [c.name], 1, cutoff=0.7) if len(repl) == 1: field.value = (repl[0], c.id) return if alarmtype.translation(u'_default_city_').lower() in field.value[0].lower(): d_city = filter(lambda c: c.default == 1, cities) if len(d_city) == 1: field.value = (d_city[0].name, d_city[0].id) return # use default city city = City.getDefaultCity() field.value = (city.name, city.id) return if field.value[0].startswith('in'): # remove 'in' and plz field.value = (re.sub(r'in*|[0-9]*', '', field.value[0][2:].strip()), field.value[1])
def updateAdminSubNavigation(self): """ Add subnavigation for admin area """ from .city import City self.adminsubnavigation = [] for c in City.getCities(): self.adminsubnavigation.append( (u"/admin/streets/{}".format(c.id), c.name)) self.adminsubnavigation.append( ('/admin/streets/0', babel.gettext('admin.streets.cities.edit...')))
def getFrontendContent(**params): if 'area' not in params.keys() and request.args.get('area', '') != '': params['area'] = request.args.get('area') if 'area' in params.keys() and params['area'] in ['west', 'east' ]: # small area view return render_template( 'frontend.locations_smallarea.html', cities=City.getCities(), alarmobjects=AlarmObject.getAlarmObjects(), alarmobjecttypes=AlarmObjectType.getAlarmObjectTypes(), frontendarea=params['area']) return ""
def loadHousenumbersFromOsm(streets): # load all housenumbers from osm """ Load all housenumbers of given street from OpenStreetMap :param streets: list of :py:class:`emonitor.modules.streets.street.Street` :return: number of housenumbers of given streeet """ global URL housenumbers = {} for street in streets: nodes = {} ways = [] city = City.getCities(id=street.cityid) SEARCHSTRING = 'area[name~"%s"];way(area)[building]["addr:street"="%s"];(._;>;);out;' % (city.osmname, street.name) r = requests.post(URL, data={'data': SEARCHSTRING}) xmldoc = minidom.parseString(r.content) for node in xmldoc.getElementsByTagName('node'): nodes[node.attributes['id'].value] = [float(node.attributes['lat'].value), float(node.attributes['lon'].value)] for way in xmldoc.getElementsByTagName('way'): ways.append(way) # try with associatedStreet SEARCHSTRING = 'area[name~"%s"];rel[type=associatedStreet](area)->.allASRelations;way(r.allASRelations:"street")[name="%s"];rel(bw:"street")[type=associatedStreet]->.relationsWithRoleStreet;way(r.relationsWithRoleStreet)[building];(._;>;);out;' % (city.osmname, street.name) r = requests.post(URL, data={'data': SEARCHSTRING}) xmldoc = minidom.parseString(r.content) for node in xmldoc.getElementsByTagName('node'): nodes[node.attributes['id'].value] = [float(node.attributes['lat'].value), float(node.attributes['lon'].value)] for way in xmldoc.getElementsByTagName('way'): ways.append(way) _numbers = 0 for way in ways: nd = [] _id = None for c in way.childNodes: if c.nodeName == "nd": nd.append(nodes[c.attributes['ref'].value]) if c.nodeName == "tag" and c.attributes['k'].value == 'addr:housenumber': _id = c.attributes['v'].value if _id: housenumbers[_id] = nd street.addHouseNumber(_id, housenumbers[_id]) _numbers += 1 signal.send('housenumber', 'osm', street=street.name, hnumbers=_numbers, position=(streets.index(street) + 1, len(streets)), cityid=city.id) signal.send('housenumber', 'osmdone', numbers=len(housenumbers)) return len(housenumbers)
def getAdminData(self): """ Deliver admin content of module mapitems (ajax) :return: rendered template as string or json dict """ if request.args.get('action') == 'loadfromosm': # load all objects from osm itemdefinition = [t for t in Settings.get('mapitemdefinition') if t['name'] == request.args.get('type')][0] dbodmids = [int(i.osmid) for i in MapItem.getMapitems(itemtype=itemdefinition['name'])] for cid in itemdefinition['cities']: city = City.getCities(id=cid) for item in MapItem.loadFromOSM(itemdefinition, city.name): if int(item['id']) > 0 and int(item['id']) not in dbodmids: # add item attrs = item.copy() del attrs['id'] db.session.add(MapItem(itemdefinition['name'], int(item['id']), attrs)) else: # update pass # TODO write update method db.session.commit() elif request.args.get('action') == 'uploadlayouter': if request.files: ufile = request.files['uploadfile'] if not os.path.exists('%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)): ufile.save('%s/emonitor/modules/mapitems/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)) try: cls = imp.load_source('emonitor.modules.mapitems.inc', 'emonitor/modules/mapitems/inc/%s' % ufile.filename) if isinstance(getattr(cls, cls.__all__[0])(), ItemLayout): return "ok" except: pass os.remove('%s/emonitor/modules/mapitems/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)) return babel.gettext(u'admin.mapitems.layouternotvalid') return "" elif request.args.get('action') == 'buildtiles': itemdefinition = [t for t in Settings.get('mapitemdefinition') if t['name'] == request.args.get('type')][0] for layouter in MapItem.getLayouters(): if layouter.getName() == itemdefinition['parameters']['layout']: scheduler.add_job(layouter.buildTiles, args=[MapItem.getMapitems(itemdefinition['name']), itemdefinition['attributes']]) break return ""
def getFrontendData(self, params={}): """ Deliver frontend content of module alarmkeys :param params: given parameters of current request :return: data of alarmkeys """ if request.args.get(u'action') == u'keyslookup': keys = {} for k in Alarmkey.getAlarmkeys(): keys[u"{}".format(k.id)] = u'{}: {}'.format(k.category, k.key) return keys elif request.args.get(u'action') == u'categorylookup': key = Alarmkey.getAlarmkeys(id=request.args.get(u'keyid')) return {u'id': key.id, u'category': key.category} elif request.args.get(u'action') == u'carslookup': ret = {u'cars1': [], u'cars2': [], u'material': []} try: city = City.getCities(id=request.args.get(u'cityid')) except ValueError: city = None key = Alarmkey.getAlarmkeys(id=request.args.get(u'keyid')) if request.args.get( u'objectid') != u'0': # use alarmobject and test for aao aobject = AlarmObject.getAlarmObjects( id=request.args.get(u'objectid')) if aobject.hasOwnAAO(): return { u'cars1': [c.id for c in aobject.getCars1()], u'cars2': [c.id for c in aobject.getCars2()], u'material': [m.id for m in aobject.getMaterial()] } if key and city: ret = { u'cars1': [c.id for c in key.getCars1(city.dept)], u'cars2': [c.id for c in key.getCars2(city.dept)], u'material': [m.id for m in key.getMaterial(city.dept)] } return ret return u""
def getFrontendData(self, params={}): """ Deliver frontend content of module alarmkeys :param params: given parameters of current request :return: data of alarmkeys """ if request.args.get(u'action') == u'keyslookup': keys = {} for k in Alarmkey.getAlarmkeys(): keys[u"{}".format(k.id)] = u'{}: {}'.format(k.category, k.key) return keys elif request.args.get(u'action') == u'categorylookup': key = Alarmkey.getAlarmkeys(id=request.args.get(u'keyid')) return {u'id': key.id, u'category': key.category} elif request.args.get(u'action') == u'carslookup': ret = {u'cars1': [], u'cars2': [], u'material': []} try: city = City.getCities(id=request.args.get(u'cityid')) except ValueError: city = None key = Alarmkey.getAlarmkeys(id=request.args.get(u'keyid')) if request.args.get(u'objectid') != u'0': # use alarmobject and test for aao aobject = AlarmObject.getAlarmObjects(id=request.args.get(u'objectid')) if aobject.hasOwnAAO(): return {u'cars1': [c.id for c in aobject.getCars1()], u'cars2': [c.id for c in aobject.getCars2()], u'material': [m.id for m in aobject.getMaterial()]} if key and city: ret = {u'cars1': [c.id for c in key.getCars1(city.dept)], u'cars2': [c.id for c in key.getCars2(city.dept)], u'material': [m.id for m in key.getMaterial(city.dept)]} return ret return u""
def _get_city(self): from emonitor.modules.streets.city import City return City.getCities(self.defaultcity)
def getAdminData(self): """ Deliver admin content of module mapitems (ajax) :return: rendered template as string or json dict """ if request.args.get( 'action') == 'loadfromosm': # load all objects from osm itemdefinition = [ t for t in Settings.get('mapitemdefinition') if t['name'] == request.args.get('type') ][0] dbodmids = [ int(i.osmid) for i in MapItem.getMapitems(itemtype=itemdefinition['name']) ] for cid in itemdefinition['cities']: city = City.getCities(id=cid) for item in MapItem.loadFromOSM(itemdefinition, city.name): if int(item['id']) > 0 and int( item['id']) not in dbodmids: # add item attrs = item.copy() del attrs['id'] db.session.add( MapItem(itemdefinition['name'], int(item['id']), attrs)) else: # update pass # TODO write update method db.session.commit() elif request.args.get('action') == 'uploadlayouter': if request.files: ufile = request.files['uploadfile'] if not os.path.exists( '%s/emonitor/modules/alarms/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)): ufile.save( '%s/emonitor/modules/mapitems/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)) try: cls = imp.load_source( 'emonitor.modules.mapitems.inc', 'emonitor/modules/mapitems/inc/%s' % ufile.filename) if isinstance(getattr(cls, cls.__all__[0])(), ItemLayout): return "ok" except: pass os.remove( '%s/emonitor/modules/mapitems/inc/%s' % (current_app.config.get('PROJECT_ROOT'), ufile.filename)) return babel.gettext(u'admin.mapitems.layouternotvalid') return "" elif request.args.get('action') == 'buildtiles': itemdefinition = [ t for t in Settings.get('mapitemdefinition') if t['name'] == request.args.get('type') ][0] for layouter in MapItem.getLayouters(): if layouter.getName() == itemdefinition['parameters']['layout']: scheduler.add_job(layouter.buildTiles, args=[ MapItem.getMapitems( itemdefinition['name']), itemdefinition['attributes'] ]) break return ""
def evalStreet(fieldname, **params): alarmtype = None options = [] if 'alarmtype' in params: alarmtype = params['alarmtype'] if 'options' in params: options = params['options'] streets = Street.getStreets() _str = FezAlarmFaxChecker().fields[fieldname][0] if 'part' in options: # addresspart, remove city names for c in City.getCities(): if _str.endswith(c.name): _str = _str.replace(c.name, '') pattern = re.compile(r'(?P<street>(^(\D+))) (?P<housenumber>(?P<hn>([0-9]{1,3}((\s?)[a-z])?)).*)' # street with housenumber r'|((?P<streetname>(^(\D+))))' r'|((?P<bab>((.*) (\>) )(?P<direction>(.*))))' # highway r'|((.*) (?P<train>(KM .*).*))') # train else: pattern = re.compile(r'(?P<street>(^(\D+))) (?P<housenumber>(?P<hn>([0-9]{1,3}((\s?)[a-z])?)).*)' # street with housenumber r'|((?P<bab>A[0-9]{2,3} [A-Za-z]+) (?P<direction>(\D*))(( (?P<as>[0-9]*))|(.*)))' # highway r'|((.*)(?P<train>(Bahnstrecke .*)) (?P<km>[0-9]+(.*)))' # train r'|((?P<streetname>(^(\D+))))' ) m = pattern.match(_str) if m: if m.groupdict()['street'] or m.groupdict()['streetname']: # normal street, fields: 'street', 'housenumber' with sub 'hn' repl = difflib.get_close_matches(m.groupdict()['street'] or m.groupdict()['streetname'], [s.name for s in streets], 1) if len(repl) > 0: _streets = [s for s in filter(lambda s: s.name == repl[0], streets)] if len(_streets) > 0: if FezAlarmFaxChecker().fields['city'][1] != 0: # city given for _s in _streets: # find correct city if _s.city.id == FezAlarmFaxChecker().fields['city'][1]: _street = _s _streets = [_s] break FezAlarmFaxChecker().fields[fieldname] = (_street.name, _street.id) FezAlarmFaxChecker().logger.debug(u'street: "{}" ({}) found'.format(_street.name, _street.id)) else: FezAlarmFaxChecker().fields[fieldname] = (m.groupdict()['street'] or m.groupdict()['streetname'], 0) if not re.match(alarmtype.translation(u'_street_'), _str[1]) and 'part' not in options: # ignore 'street' value and part-address FezAlarmFaxChecker().fields['streetno'] = (m.groupdict()['housenumber'], 0) if m.groupdict()['hn'] and FezAlarmFaxChecker().fields['city'][1] != 0: if m.groupdict()['housenumber'] != m.groupdict()['housenumber'].replace('B', '6').replace(u'\xdc', u'0'): _housenumber = m.groupdict()['housenumber'].replace('B', '6').replace(u'\xdc', u'0') _hn = _housenumber else: _housenumber = m.groupdict()['housenumber'].replace('B', '6').replace(u'\xdc', u'0') _hn = m.groupdict()['hn'] if m.groupdict()['hn']: db_hn = filter(lambda h: h.number.replace(' ', '') == _hn.replace(' ', ''), _streets[0].housenumbers) if len(db_hn) == 0: db_hn = filter(lambda h: h.number == _hn.split()[0], _streets[0].housenumbers) if len(db_hn) > 0: FezAlarmFaxChecker().fields['id.streetno'] = (db_hn[0].number, db_hn[0].id) FezAlarmFaxChecker().fields['streetno'] = (_housenumber, db_hn[0].id) FezAlarmFaxChecker().fields['lat'] = (db_hn[0].points[0][0], db_hn[0].id) FezAlarmFaxChecker().fields['lng'] = (db_hn[0].points[0][1], db_hn[0].id) elif _housenumber: FezAlarmFaxChecker().fields['streetno'] = (_housenumber, 0) FezAlarmFaxChecker().fields['lat'] = (_streets[0].lat, 0) FezAlarmFaxChecker().fields['lng'] = (_streets[0].lng, 0) else: FezAlarmFaxChecker().fields['lat'] = (_streets[0].lat, 0) FezAlarmFaxChecker().fields['lng'] = (_streets[0].lng, 0) elif m.groupdict()['bab']: # highway, fields: 'bab', 'direction', 'as' repl = difflib.get_close_matches(u"{} {}".format(m.groupdict()['bab'], m.groupdict()['direction']), [s.name for s in streets], 1) if len(repl) > 0: _streets = [s for s in filter(lambda s: s.name == repl[0], streets)] if len(_streets) > 0: _street = _streets[0] FezAlarmFaxChecker().fields[fieldname] = (_street.name, _street.id) FezAlarmFaxChecker().logger.debug(u'street: "{}" ({}) found'.format(_street.name, _street.id)) return elif m.groupdict()['train']: # train, fields: 'train', 'km' repl = difflib.get_close_matches(m.groupdict()['train'], [s.name for s in streets], 1) if len(repl) > 0: _streets = [s for s in filter(lambda s: s.name == repl[0], streets)] if len(_streets) > 0: _street = _streets[0] FezAlarmFaxChecker().fields[fieldname] = (_street.name, _street.id) FezAlarmFaxChecker().logger.debug(u'street: "{}" ({}) found'.format(_street.name, _street.id)) return else: # not found repl = difflib.get_close_matches(_str, [s.name for s in streets]) if len(repl) >= 1: try: street_id = u';'.join([u'{}'.format(s.id) for s in filter(lambda s: s.name == repl[0], streets)]) except: street_id = u'' FezAlarmFaxChecker().fields[fieldname] = (u'{}'.format(repl[0]), street_id) if 'streetno' not in FezAlarmFaxChecker().fields or FezAlarmFaxChecker().fields['streetno'] == u"": FezAlarmFaxChecker().fields['streetno'] = (u'{}'.format(u" ".join(_str[repl[0].count(u' ') + 1:])).replace(alarmtype.translation(u'_street_'), u'').strip(), street_id) return else: FezAlarmFaxChecker().fields[fieldname] = (_str, 0) return
def getFrontendData(self): """ Deliver frontend content of module alarms (ajax) :return: rendered template as string or json dict """ from emonitor.extensions import monitorserver if "download" in request.path: # deliver file with open('{}{}'.format(current_app.config.get('PATH_TMP'), request.path.split('download/')[-1]), 'rb') as data: si = StringIO.StringIO(data.read()).getvalue() output = make_response(si) if request.path.split('/')[-1].startswith('temp'): # remove if filename starts with temp == temporary file os.remove('{}{}'.format(current_app.config.get('PATH_TMP'), request.path.split('download/')[-1])) output.headers["Content-Disposition"] = "attachment; filename=report.{}".format(request.path.split('.')[-1]) output.headers["Content-type"] = "application/x.download" return output if request.args.get('action') == 'editalarm': if request.args.get('alarmid', '0') == '0': # add new alarm alarm = Alarm(datetime.datetime.now(), '', 2, 0) else: # edit alarm alarm = Alarm.getAlarms(id=request.args.get('alarmid')) return render_template('frontend.alarms_edit.html', alarm=alarm, cities=City.getCities(), objects=AlarmObject.getAlarmObjects(), cars=Car.getCars(), frontendarea=request.args.get('frontendarea')) elif request.args.get('action') == 'alarmmonitor': # send alarm to monitor for monitor in Monitor.getMonitors(): scheduler.deleteJobForEvent('changeLayout') # send update to monitors for l in MonitorLayout.getLayouts(mid=int(monitor.id)): if l.trigger == 'alarm_added': #monitorserver.sendMessage(str(monitor.id), 'load', ['layoutid=%s' % l.id, 'alarmid=%s' % request.args.get('alarmid')]) TODO changed from list monitorserver.sendMessage(str(monitor.id), 'load', layoutid=l.id, alarmid=request.args.get('alarmid')) elif request.args.get('action') == 'printalarm': Printers.getPrinters(pid=int(request.args.get('printerdef'))).doPrint(object=Alarm.getAlarms(id=int(request.args.get('alarmid'))), id=request.args.get('alarmid'), copies=1) return "" elif request.args.get('action') == 'routeinfo': return render_template('frontend.alarms_routing.html', routing=Alarm.getAlarms(id=request.args.get('alarmid')).getRouting()) elif request.args.get('action') == 'routecoords': return jsonify(Alarm.getAlarms(id=request.args.get('alarmid')).getRouting()) elif request.args.get('action') == 'message': return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms(id=request.args.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area'), reload=request.args.get('reload', 'true')) elif request.args.get('action') == 'addmessage': # add message if request.form.get('messagetext') != "": alarm = Alarm.getAlarms(request.form.get('alarmid')) alarm.addHistory(request.form.get('messagestate'), request.form.get('messagetext')) db.session.commit() return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms(request.form.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area')) elif request.args.get('action') == 'deletemessage': # delete selected message alarm = Alarm.getAlarms(request.args.get('alarmid')) for msg in alarm.history: if str(msg.timestamp) == request.args.get('datetime'): db.session.delete(msg) db.session.commit() return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms(request.args.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area')) elif request.args.get('action') == 'housecoordinates': # return a dict with coordinats of housenumber if request.args.get('alarmid') != "None": alarm = Alarm.getAlarms(id=int(request.args.get('alarmid'))) if alarm and alarm.housenumber: return {'lat': map(lambda x: x[0], alarm.housenumber.points), 'lng': map(lambda x: x[1], alarm.housenumber.points)} return [] elif request.args.get('action') == 'evalhouse': # try to eval housenumer street = Street.getStreets(id=request.args.get('streetid')) if street: points = dict(lat=[], lng=[]) for hn in street.housenumbers: if str(hn.number) == request.args.get('housenumber').strip(): points['lat'].extend(map(lambda x: x[0], hn.points)) points['lng'].extend(map(lambda x: x[1], hn.points)) return points return {} elif request.args.get('action') == 'alarmsforstate': # render alarms for given state if 'alarmfilter' not in session: session['alarmfilter'] = 7 return render_template('frontend.alarms_alarm.html', alarms=Alarm.getAlarms(days=int(session['alarmfilter']), state=int(request.args.get('state', '-1'))), printdefs=Printers.getActivePrintersOfModule('alarms')) elif request.args.get('action') == 'collective': # render collective form reports = [r for r in AlarmReport.getReports() if r.reporttype.multi] if len(reports) == 0: return "" return render_template('frontend.alarms_collective.html', alarms=Alarm.getAlarms(state=2), reports=reports) elif request.args.get('action') == 'docollective': # build collective form if request.args.get('ids') == "": ids = [] else: ids = request.args.get('ids').split(',') f = AlarmReport.getReports(request.args.get('form')).createReport(ids=ids) _path, _filename = os.path.split(f) shutil.move(f, "{}{}".format(current_app.config.get('PATH_TMP'), _filename)) return _filename elif request.args.get('action') == 'alarmpriocars': # show prio cars cars = [] c = Settings.getIntList('alarms.spc_cars.{}'.format(request.args.get('state'))) if len(c) == 0: return "" for alarm in Alarm.getAlarms(state=request.args.get('state')): cars.extend([car for car in alarm.cars1 if car.id in c]) cars = Counter(cars) return render_template('frontend.alarms_cars.html', cars=cars) elif request.args.get('action') == 'showdetailsform': # build alarmdetails edtit form alarm = Alarm.getAlarms(id=request.args.get('alarmid')) if alarm.street.city: fields = AlarmField.getAlarmFields(dept=alarm.street.city.dept) else: fields = AlarmField.getAlarmFields(dept=Department.getDefaultDepartment().id) return render_template('frontend.alarms_fields.html', alarm=alarm, fields=fields, reports=AlarmReport.getReports()) elif request.args.get('action') == 'saveextform': # store ext-form values alarm = Alarm.getAlarms(id=request.form.get('alarmid')) for field in AlarmField.getAlarmFields(dept=alarm.street.city.dept): field.saveForm(request, alarm) db.session.commit() return ""
def loadStreetsFromOsm(city=None, format="html"): """ Load all Streets from OpenStreetMap :param optional city: :py:class:`emonitor.modules.streets.city.City` :param optional format: return format, *html*=rendered template, streets as OrderedDict :return: rendered template or dict """ global URL if not city: city = City.getDefaultCity() map_details = Map.getDefaultMap().getMapBox(tilepath=current_app.config.get("PATH_TILES")) SEARCHSTRING = 'area[name~"%s"];way(%s,%s,%s,%s)(area)[highway][name];(._;>;);out;' % ( city.name, map_details["min_latdeg"], map_details["min_lngdeg"], map_details["max_latdeg"], map_details["max_lngdeg"], ) # search all streets for given city r = requests.post(URL, data={"data": SEARCHSTRING}) xmldoc = minidom.parseString(r.content) nodes = xmldoc.getElementsByTagName("node") ways = xmldoc.getElementsByTagName("way") dbosmids = [int(s.osmid or 0) for s in city.getCities()] streets = OrderedDict() n = {} for node in nodes: n[int(node.attributes["id"].value)] = (float(node.attributes["lat"].value), float(node.attributes["lon"].value)) for way in ways: nds = [] osmids = [] name = "" for tag in way.childNodes: if tag.nodeName == "tag" and tag.attributes["k"].value == "name": name = tag.attributes["v"].value osmids.append(int(way.attributes["id"].value)) if tag.nodeName == "nd": _nid = int(tag.attributes["ref"].value) if _nid in n.keys(): nds.append(n[_nid]) if name not in streets.keys(): streets[name] = {"osmids": osmids, "nodes": nds, "indb": False} else: streets[name]["osmids"].extend(osmids) streets[name]["nodes"].extend(nds) if len(set(osmids).intersection(set(dbosmids))) > 0: streets[name]["indb"] = True streets = OrderedDict(sorted(streets.items(), key=lambda t: t[0])) if format == "html": # html output return render_template("admin.streets_osm.html", streets=streets, city=city) else: # data output for name in streets: points = streets[name]["nodes"] if len(points) > 2: cent = centroid_of_polygon(points) streets[name]["center"] = cent elif len(points) == 2: streets[name]["center"] = (((points[0][0] + points[1][0]) / 2), ((points[0][1] + points[1][1]) / 2)) else: streets[name]["center"] = (0.0, 0.0) return streets
def getAdminData(self): """ Deliver admin content of module streets (ajax) :return: rendered template as string or json dict """ if request.args.get('action') == 'loadcitiesfromosm': # get city list from osm return loadCitiesFromOsm() elif request.args.get('action') == 'createcity': # create cities from osm osmids = [c[0] for c in db.get(City.osmid).all()] i = 0 for c in request.args.get('values').split(","): _id, name = c.split('|') if int(_id) not in osmids: # add city db.session.add(City(name, 1, '', 0, '', '', int(_id), '')) db.session.commit() i += 1 flash(babel.gettext('%(i)s admin.streets.cities.osmcitiesadded', i=i)) self.updateAdminSubNavigation() return '1' elif request.args.get('action') == 'loadstreetsfromosm': # get street list from osm return loadStreetsFromOsm(City.getCities(id=request.args.get('cityid'))) elif request.args.get('action') == 'createstreet': # create streets from osm city = City.getCities(id=request.args.get('cityid')) ids = [int(i) for i in request.args.get('values').split(",")] # ids to create osmdata = loadStreetsFromOsm(city=city, format='data') i = 0 for sname in osmdata: if len(set(osmdata[sname]['osmids']).intersection(set(ids))) > 0: # add street _s = osmdata[sname] city.addStreet( Street(sname, '', int(request.args.get('cityid')), '', _s['center'][0], _s['center'][1], 17, 1, _s['osmids'][0])) i += 1 flash(babel.gettext('%(i)s admin.streets.osmstreetsadded', i=i)) return '1' elif request.args.get('action') == 'loadhnumbersfromosm': if 'streetid' in request.args: streets = [Street.getStreets(id=int(request.args.get('streetid')))] elif 'cityid' in request.args: #streets = list(City.getCities(id=request.args.get('cityid')).streets) streets = Street.getStreets(cityid=int(request.args.get('cityid'))) else: streets = Street.getStreets() return str(scheduler.add_job(loadHousenumbersFromOsm, args=[streets])) elif request.args.get('action') == 'loadhnumbers': # load all housenumbers for street street = Street.getStreets(id=request.args.get('streetid')) ret = dict() for hn in street.housenumbers: ret[hn.id] = hn.points return ret elif request.args.get('action') == 'delhousenumber': # delete housenumber hn = Housenumber.getHousenumbers(id=request.args.get('housenumberid')) street = hn.street db.session.delete(hn) db.session.commit() return render_template('admin.streets.housenumber.html', hnumbers=street.housenumbers) elif request.args.get('action') == 'addhousenumber': # add housenumber street = Street.getStreets(id=request.args.get('streetid')) points = [] p = request.args.get('points').split(';') points.append((float(p[0]), float(p[1]))) street.addHouseNumber(request.args.get('hnumber'), points) return render_template('admin.streets.housenumber.html', hnumbers=street.housenumbers) return "NONE"
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'])
def evalStreet(field, **params): alarmtype = params.get('alarmtype', None) options = params.get('options', []) streets = Street.getStreets() if 'part' in options: # addresspart, remove city names for c in City.getCities(): if field.value[0].endswith(c.name): field.value = (field.value[0].replace(c.name, ''), field.value[1]) pattern = re.compile(r'(?P<street>(^(\D+))) (?P<housenumber>(?P<hn>([0-9]{1,3}((\s?)[a-z])?)).*)' # street with housenumber r'|((?P<streetname>((.*[0-9]{4})|(^(\D+)))))' r'|((?P<bab>((.*) (\>) )(?P<direction>(.*))))' # highway r'|((.*) (?P<train>(KM .*).*))') # train else: pattern = re.compile(r'(?P<street>(^(\D+))) (?P<housenumber>(?P<hn>([0-9]{1,3}((\s?)[a-z])?)).*)' # street with housenumber r'|((?P<bab>A[0-9]{2,3} [A-Za-z]+) (?P<direction>(\D*))(( (?P<as>[0-9]*))|(.*)))' # highway r'|((.*)(?P<train>(Bahnstrecke .*)) (?P<km>[0-9]+(.*)))' # train r'|((?P<streetname>((.*[0-9]{4})|(^(\D+)))))' ) m = pattern.match(field.value[0]) if m: if m.groupdict().get('street') or m.groupdict().get('streetname'): # normal street, fields: 'street', 'housenumber' with sub 'hn' repl = difflib.get_close_matches(m.groupdict()['street'] or m.groupdict()['streetname'], [s.name for s in streets], 1) if len(repl) > 0: _streets = [s for s in filter(lambda s: s.name == repl[0], streets)] if len(_streets) > 0: field.value = (_streets[0].name, _streets[0].id) if not re.match(alarmtype.translation(u'_street_'), field.value[0][1]) and 'part' not in options: # ignore 'street' value and part-address GenericAlarmFaxChecker().fields['streetno'] = (m.groupdict()['housenumber'], 0) if m.groupdict()['hn'] and GenericAlarmFaxChecker().fields.get('city', ('', 0))[1] != 0: if m.groupdict()['housenumber'] != m.groupdict()['housenumber'].replace('B', '6').replace(u'\xdc', u'0'): _housenumber = m.groupdict()['housenumber'].replace('B', '6').replace(u'\xdc', u'0') _hn = _housenumber else: _housenumber = m.groupdict()['housenumber'].replace('B', '6').replace(u'\xdc', u'0') _hn = m.groupdict()['hn'] if m.groupdict()['hn']: db_hn = filter(lambda h: h.number.replace(' ', '') == _hn.replace(' ', ''), _streets[0].housenumbers) if len(db_hn) == 0: db_hn = filter(lambda h: h.number == _hn.split()[0], _streets[0].housenumbers) if len(db_hn) > 0: GenericAlarmFaxChecker().fields.update({'id.streetno': (db_hn[0].number, db_hn[0].id), 'streetno': (_housenumber, db_hn[0].id), 'lat': (db_hn[0].points[0][0], db_hn[0].id), 'lng': (db_hn[0].points[0][1], db_hn[0].id)}) elif _housenumber: GenericAlarmFaxChecker().fields.update({'streetno': (_housenumber, 0), 'lat': (_streets[0].lat, 0), 'lng': (_streets[0].lng, 0)}) else: GenericAlarmFaxChecker().fields.update({'lat': (_streets[0].lat, 0), 'lng': (_streets[0].lng, 0)}) else: GenericAlarmFaxChecker().fields.update({'lat': (_streets[0].lat, 0), 'lng': (_streets[0].lng, 0)}) else: repl = difflib.get_close_matches(field.value[0], [s.name for s in streets], 1) if len(repl) > 0: _streets = [s for s in filter(lambda s: s.name == repl[0], streets)] if len(_streets) > 0: field.value = (_streets[0].name, _streets[0].id) elif m.groupdict()['bab']: # highway, fields: 'bab', 'direction', 'as' repl = difflib.get_close_matches(u"{} {}".format(m.groupdict()['bab'], m.groupdict()['direction']), [s.name for s in streets], 1) if len(repl) > 0: _streets = [s for s in filter(lambda s: s.name == repl[0], streets)] if len(_streets) > 0: _street = _streets[0] field.value = (_street.name, _street.id) GenericAlarmFaxChecker().logger.debug(u'street: "{}" ({}) found'.format(_street.name, _street.id)) return elif m.groupdict()['train']: # train, fields: 'train', 'km' repl = difflib.get_close_matches(m.groupdict()['train'], [s.name for s in streets], 1) if len(repl) > 0: _streets = [s for s in filter(lambda s: s.name == repl[0], streets)] if len(_streets) > 0: _street = _streets[0] field.value = (_street.name, _street.id) GenericAlarmFaxChecker().logger.debug(u'street: "{}" ({}) found'.format(_street.name, _street.id)) else: # not found repl = difflib.get_close_matches(field.value[0], [s.name for s in streets]) if len(repl) >= 1: try: street_id = u';'.join([u'{}'.format(s.id) for s in filter(lambda s: s.name == repl[0], streets)]) except: street_id = u'' field.value = (u'{}'.format(repl[0]), street_id) if 'streetno' not in GenericAlarmFaxChecker().fields or GenericAlarmFaxChecker().fields['streetno'] == u"": GenericAlarmFaxChecker().fields['streetno'] = (u'{}'.format(u" ".join(field.value[0][repl[0].count(u' ') + 1:])).replace(alarmtype.translation(u'_street_'), u'').strip(), street_id)
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)
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> "{}" → <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" → "%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" → "%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" → "%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
def getAdminData(self): """ Deliver admin content of module streets (ajax) :return: rendered template as string or json dict """ if request.args.get('action') == 'loadcitiesfromosm': # get city list from osm return loadCitiesFromOsm() elif request.args.get('action') == 'createcity': # create cities from osm osmids = [c[0] for c in db.get(City.osmid).all()] i = 0 for c in request.args.get('values').split(","): _id, name = c.split('|') if int(_id) not in osmids: # add city db.session.add(City(name, 1, '', 0, '', '', int(_id), '')) db.session.commit() i += 1 flash(babel.gettext('%(i)s admin.streets.cities.osmcitiesadded', i=i)) self.updateAdminSubNavigation() return '1' elif request.args.get('action') == 'loadstreetsfromosm': # get street list from osm return loadStreetsFromOsm(City.getCities(id=request.args.get('cityid'))) elif request.args.get('action') == 'createstreet': # create streets from osm city = City.getCities(id=request.args.get('cityid')) ids = [int(i) for i in request.args.get('values').split(",")] # ids to create osmdata = loadStreetsFromOsm(city=city, format='data') i = 0 for sname in osmdata: if len(set(osmdata[sname]['osmids']).intersection(set(ids))) > 0: # add street _s = osmdata[sname] city.addStreet( Street(sname, '', int(request.args.get('cityid')), '', _s['center'][0], _s['center'][1], 17, 1, _s['osmids'][0])) i += 1 flash(babel.gettext('%(i)s admin.streets.osmstreetsadded', i=i)) return '1' elif request.args.get('action') == 'loadhnumbersfromosm': if 'streetid' in request.args: streets = Street.getStreets(id=int(request.args.get('streetid'))) elif 'cityid' in request.args: streets = [City.getCities(id=request.args.get('cityid'))] else: streets = Street.getStreets() return str(scheduler.add_job(loadHousenumbersFromOsm, args=[streets])) elif request.args.get('action') == 'loadhnumbers': # load all housenumbers for street street = Street.getStreets(id=request.args.get('streetid')) ret = dict() for hn in street.housenumbers: ret[hn.id] = hn.points return ret elif request.args.get('action') == 'delhousenumber': # delete housenumber hn = Housenumber.getHousenumbers(id=request.args.get('housenumberid')) street = hn.street db.session.delete(hn) db.session.commit() return render_template('admin.streets.housenumber.html', hnumbers=street.housenumbers) elif request.args.get('action') == 'addhousenumber': # add housenumber street = Street.getStreets(id=request.args.get('streetid')) points = [] p = request.args.get('points').split(';') points.append((float(p[0]), float(p[1]))) street.addHouseNumber(request.args.get('hnumber'), points) return render_template('admin.streets.housenumber.html', hnumbers=street.housenumbers) return "NONE"
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"
def evalStreet(field, **params): alarmtype = params.get('alarmtype', None) options = params.get('options', []) streets = Street.getStreets() if 'part' in options: # addresspart, remove city names for c in City.getCities(): if field.value[0].endswith(c.name): field.value = (field.value[0].replace(c.name, ''), field.value[1]) pattern = re.compile( r'(?P<street>(^(\D+))) (?P<housenumber>(?P<hn>([0-9]{1,3}((\s?)[a-z])?)).*)' # street with housenumber r'|((?P<streetname>((.*[0-9]{4})|(^(\D+)))))' r'|((?P<bab>((.*) (\>) )(?P<direction>(.*))))' # highway r'|((.*) (?P<train>(KM .*).*))') # train else: pattern = re.compile( r'(?P<street>(^(\D+))) (?P<housenumber>(?P<hn>([0-9]{1,3}((\s?)[a-z])?)).*)' # street with housenumber r'|((?P<bab>A[0-9]{2,3} [A-Za-z]+) (?P<direction>(\D*))(( (?P<as>[0-9]*))|(.*)))' # highway r'|((.*)(?P<train>(Bahnstrecke .*)) (?P<km>[0-9]+(.*)))' # train r'|((?P<streetname>((.*[0-9]{4})|(^(\D+)))))') m = pattern.match(field.value[0]) if m: if m.groupdict().get('street') or m.groupdict().get( 'streetname' ): # normal street, fields: 'street', 'housenumber' with sub 'hn' repl = difflib.get_close_matches( m.groupdict()['street'] or m.groupdict()['streetname'], [s.name for s in streets], 1) if len(repl) > 0: _streets = [ s for s in filter(lambda s: s.name == repl[0], streets) ] if len(_streets) > 0: field.value = (_streets[0].name, _streets[0].id) if not re.match( alarmtype.translation(u'_street_'), field.value[0][1] ) and 'part' not in options: # ignore 'street' value and part-address GenericAlarmFaxChecker().fields['streetno'] = ( m.groupdict()['housenumber'], 0) if m.groupdict()['hn'] and GenericAlarmFaxChecker( ).fields.get('city', ('', 0))[1] != 0: if m.groupdict()['housenumber'] != m.groupdict( )['housenumber'].replace('B', '6').replace( u'\xdc', u'0'): _housenumber = m.groupdict( )['housenumber'].replace('B', '6').replace( u'\xdc', u'0') _hn = _housenumber else: _housenumber = m.groupdict( )['housenumber'].replace('B', '6').replace( u'\xdc', u'0') _hn = m.groupdict()['hn'] if m.groupdict()['hn']: db_hn = filter( lambda h: h.number.replace(' ', '') == _hn. replace(' ', ''), _streets[0].housenumbers) if len(db_hn) == 0: db_hn = filter( lambda h: h.number == _hn.split()[0], _streets[0].housenumbers) if len(db_hn) > 0: GenericAlarmFaxChecker().fields.update({ 'id.streetno': (db_hn[0].number, db_hn[0].id), 'streetno': (_housenumber, db_hn[0].id), 'lat': (db_hn[0].points[0][0], db_hn[0].id), 'lng': (db_hn[0].points[0][1], db_hn[0].id) }) elif _housenumber: GenericAlarmFaxChecker().fields.update({ 'streetno': (_housenumber, 0), 'lat': (_streets[0].lat, 0), 'lng': (_streets[0].lng, 0) }) else: GenericAlarmFaxChecker().fields.update({ 'lat': (_streets[0].lat, 0), 'lng': (_streets[0].lng, 0) }) else: GenericAlarmFaxChecker().fields.update({ 'lat': (_streets[0].lat, 0), 'lng': (_streets[0].lng, 0) }) else: repl = difflib.get_close_matches(field.value[0], [s.name for s in streets], 1) if len(repl) > 0: _streets = [ s for s in filter(lambda s: s.name == repl[0], streets) ] if len(_streets) > 0: field.value = (_streets[0].name, _streets[0].id) elif m.groupdict( )['bab']: # highway, fields: 'bab', 'direction', 'as' repl = difflib.get_close_matches( u"{} {}".format(m.groupdict()['bab'], m.groupdict()['direction']), [s.name for s in streets], 1) if len(repl) > 0: _streets = [ s for s in filter(lambda s: s.name == repl[0], streets) ] if len(_streets) > 0: _street = _streets[0] field.value = (_street.name, _street.id) GenericAlarmFaxChecker().logger.debug( u'street: "{}" ({}) found'.format( _street.name, _street.id)) return elif m.groupdict()['train']: # train, fields: 'train', 'km' repl = difflib.get_close_matches(m.groupdict()['train'], [s.name for s in streets], 1) if len(repl) > 0: _streets = [ s for s in filter(lambda s: s.name == repl[0], streets) ] if len(_streets) > 0: _street = _streets[0] field.value = (_street.name, _street.id) GenericAlarmFaxChecker().logger.debug( u'street: "{}" ({}) found'.format( _street.name, _street.id)) else: # not found repl = difflib.get_close_matches(field.value[0], [s.name for s in streets]) if len(repl) >= 1: try: street_id = u';'.join([ u'{}'.format(s.id) for s in filter( lambda s: s.name == repl[0], streets) ]) except: street_id = u'' field.value = (u'{}'.format(repl[0]), street_id) if 'streetno' not in GenericAlarmFaxChecker( ).fields or GenericAlarmFaxChecker( ).fields['streetno'] == u"": GenericAlarmFaxChecker( ).fields['streetno'] = (u'{}'.format(u" ".join( field.value[0][repl[0].count(u' ') + 1:])).replace( alarmtype.translation(u'_street_'), u'').strip(), street_id)
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
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)
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'])
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"
def getAdminContent(self, **params): """ Deliver admin content of module mapitems :param params: use given parameters of request :return: rendered template as string """ module = request.view_args['module'].split('/') if len(module) < 2: module.append( current_app.blueprints['admin'].modules['mapitems']. adminsubnavigation[0][0].split('/')[-1]) # get first submenuitem if len(module) >= 2: if module[1] == 'definition': # definition if request.method == 'POST': if request.form.get('action').startswith( 'edititemtype_'): # edit/add definition TODO: fix typename = request.form.get('action').split('_') itemtype = [ d for d in Settings.get('mapitemdefinition') if d['name'] == typename[1] ] if len(itemtype) > 0: itemtype = itemtype[0] if 'parameters' not in itemtype: itemtype['parameters'] = { 'layout': '', 'tileserver': 0 } if 'key' not in itemtype: itemtype['key'] = [] if 'cities' not in itemtype: itemtype['cities'] = [] if 'itemtype' not in itemtype: itemtype['itemtype'] = 'node' else: itemtype = { 'name': '', 'filter': '', 'attributes': [], 'parameters': {'layout', 'tileserver'}, 'key': [], 'cities': [], 'itemtype': 'node' } params.update({ 'itemtype': itemtype, 'cities': City.getCities(), 'layouters': MapItem.getLayouters() }) return render_template( 'admin.mapitems.definition_actions.html', **params) elif request.form.get('action').startswith( 'deleteitemtype_'): # delete definition itemtypes = Settings.get('mapitemdefinition') for itemtype in itemtypes: if itemtype['name'] == request.form.get( 'action').split('_')[1]: del itemtypes[itemtypes.index(itemtype)] Settings.set('mapitemdefinition', itemtypes) db.session.commit() elif request.form.get( 'action') == 'updateitemtypes': # save definition itemtypes = Settings.get('mapitemdefinition') position = -1 for itemtype in itemtypes: if itemtype['name'] == request.form.get('edit_name'): position = itemtypes.index(itemtype) break if position >= 0: # update type itemtypes[position]['filter'] = request.form.get( 'edit_filter') itemtypes[position]['cities'] = [ int(i) for i in request.form.getlist('edit_cityid') ] itemtypes[position]['itemtype'] = request.form.get( 'edit_itemtype') itemtypes[position]['attributes'] = request.form.get( 'edit_attributes').split('\r\n') itemtypes[position]['parameters'] = { 'layout': request.form.get('edit_layout'), 'tileserver': request.form.get('edit_tileserver') } itemtypes[position]['key'] = request.form.get( 'edit_keys').split('\r\n') else: # add new type it = dict() it['name'] = request.form.get('edit_name') it['filter'] = request.form.get('edit_filter') it['cities'] = [ int(i) for i in request.form.getlist('edit_cityid') ] it['itemtype'] = request.form.get('edit_itemtype') it['attributes'] = request.form.get( 'edit_attributes').split('\r\n') it['parameters'] = { 'layout': request.form.get('edit_layout') } if itemtypes == "": itemtypes = [it] else: itemtypes.append(it) it['key'] = request.form.get('edit_keys').split('\r\n') Settings.set('mapitemdefinition', itemtypes) db.session.commit() current_app.blueprints['admin'].modules[ 'mapitems'].updateAdminSubNavigation() params.update({ 'itemtypes': Settings.get('mapitemdefinition', []), 'layouters': MapItem.getLayouters() }) return render_template('admin.mapitems.definition.html', **params) # deliver default list itemdefinition = [ t for t in Settings.get('mapitemdefinition') if t['name'] == module[1] ][0] itemtypes = MapItem.getMapitems(itemtype=module[1]) page = 0 if len(module) == 3: # pagination active page = int(module[2]) pagination = Pagination(page, PER_PAGE, len(itemtypes)) params.update({ 'itemtypes': itemtypes[page:page + PER_PAGE], 'itemdefinition': itemdefinition, 'pagination': pagination }) return render_template('admin.mapitems.html', **params)
def getAdminContent(self, **params): """ Deliver admin content of module mapitems :param params: use given parameters of request :return: rendered template as string """ module = request.view_args['module'].split('/') if len(module) < 2: module.append(current_app.blueprints['admin'].modules['mapitems'].adminsubnavigation[0][0].split('/')[-1]) # get first submenuitem if len(module) >= 2: if module[1] == 'definition': # definition if request.method == 'POST': if request.form.get('action').startswith('edititemtype_'): # edit/add definition TODO: fix typename = request.form.get('action').split('_') itemtype = [d for d in Settings.get('mapitemdefinition') if d['name'] == typename[1]] if len(itemtype) > 0: itemtype = itemtype[0] if 'parameters' not in itemtype: itemtype['parameters'] = {'layout': '', 'tileserver': 0} if 'key' not in itemtype: itemtype['key'] = [] if 'cities' not in itemtype: itemtype['cities'] = [] if 'itemtype' not in itemtype: itemtype['itemtype'] = 'node' else: itemtype = {'name': '', 'filter': '', 'attributes': [], 'parameters': {'layout', 'tileserver'}, 'key': [], 'cities': [], 'itemtype': 'node'} params.update({'itemtype': itemtype, 'cities': City.getCities(), 'layouters': MapItem.getLayouters()}) return render_template('admin.mapitems.definition_actions.html', **params) elif request.form.get('action').startswith('deleteitemtype_'): # delete definition itemtypes = Settings.get('mapitemdefinition') for itemtype in itemtypes: if itemtype['name'] == request.form.get('action').split('_')[1]: del itemtypes[itemtypes.index(itemtype)] Settings.set('mapitemdefinition', itemtypes) db.session.commit() elif request.form.get('action') == 'updateitemtypes': # save definition itemtypes = Settings.get('mapitemdefinition') position = -1 for itemtype in itemtypes: if itemtype['name'] == request.form.get('edit_name'): position = itemtypes.index(itemtype) break if position >= 0: # update type itemtypes[position]['filter'] = request.form.get('edit_filter') itemtypes[position]['cities'] = [int(i) for i in request.form.getlist('edit_cityid')] itemtypes[position]['itemtype'] = request.form.get('edit_itemtype') itemtypes[position]['attributes'] = request.form.get('edit_attributes').split('\r\n') itemtypes[position]['parameters'] = {'layout': request.form.get('edit_layout'), 'tileserver': request.form.get('edit_tileserver')} itemtypes[position]['key'] = request.form.get('edit_keys').split('\r\n') else: # add new type it = dict() it['name'] = request.form.get('edit_name') it['filter'] = request.form.get('edit_filter') it['cities'] = [int(i) for i in request.form.getlist('edit_cityid')] it['itemtype'] = request.form.get('edit_itemtype') it['attributes'] = request.form.get('edit_attributes').split('\r\n') it['parameters'] = {'layout': request.form.get('edit_layout')} if itemtypes == "": itemtypes = [it] else: itemtypes.append(it) it['key'] = request.form.get('edit_keys').split('\r\n') Settings.set('mapitemdefinition', itemtypes) db.session.commit() current_app.blueprints['admin'].modules['mapitems'].updateAdminSubNavigation() params.update({'itemtypes': Settings.get('mapitemdefinition', []), 'layouters': MapItem.getLayouters()}) return render_template('admin.mapitems.definition.html', **params) # deliver default list itemdefinition = [t for t in Settings.get('mapitemdefinition') if t['name'] == module[1]][0] itemtypes = MapItem.getMapitems(itemtype=module[1]) page = 0 if len(module) == 3: # pagination active page = int(module[2]) pagination = Pagination(page, PER_PAGE, len(itemtypes)) params.update({'itemtypes': itemtypes[page:page + PER_PAGE], 'itemdefinition': itemdefinition, 'pagination': pagination}) return render_template('admin.mapitems.html', **params)
def getFrontendData(self): """ Deliver frontend content of module streets (ajax) :return: rendered template as string or json dict """ if request.args.get( 'action' ) == 'streetcoords': # get map parameter for given streetid if request.args.get('id') not in ['', 'None']: street = Street.getStreets(id=request.args.get('id')) return { 'lat': street.lat, 'lng': street.lng, 'zoom': street.zoom, 'way': street.navigation, 'cityid': street.cityid, 'cityname': street.city.name } elif request.args.get( 'action') == 'housecoords': # deliver center of housenumbers if request.args.get('streetid') != '' and request.args.get( 'housenumber') != '': street = Street.getStreet(id=request.args.get('streetid')) hnumber = street.getHouseNumber( number=request.args.get('housenumber').split()[0]) if hnumber: return hnumber.getPosition(0) return {'lat': street.lat, 'lng': street.lng} return {} elif request.args.get('action') == 'defaultposition': return { 'defaultlat': float(Settings.get('defaultLat')), 'defaultlng': float(Settings.get('defaultLng')), 'defaultzoom': int(Settings.get('defaultZoom')) } elif request.args.get('action') == 'alarmposition': alarm = Alarm.getAlarms(id=request.args.get('alarmid')) if alarm: return { 'id': request.args.get('alarmid'), 'alarmlat': alarm.lat, 'alarmlng': alarm.lng, 'alarmzoom': alarm.zoom, 'marker': alarm.marker, 'alarmprio': alarm.priority, 'alarmstreet': alarm.street.name, 'alarmstreetno': alarm.get('streetno'), 'alarmstreet2': alarm.get('address2'), 'alarmcity': alarm.city.name, 'alarmsubcity': alarm.street.subcity } else: return {'id': '0'} elif request.args.get('action') == 'streetslookup': streets = {} cities = {} for c in City.getCities(): cities[c.id] = c.name for k, street in c.streets.iteritems(): if street.active: try: streets[str( street.id)] = '%s (%s)' % (street.name, c.name) except: streets[str(street.id)] = '%s (-%s-)' % (street.name, street.cityid) return streets elif request.args.get('action') == 'defaultmap': dmap = Map.getDefaultMap() return {'tileserver': dmap.tileserver, 'name': dmap.name} return ""
def getFrontendData(self): """ Deliver frontend content of module alarms (ajax) :return: rendered template as string or json dict """ from emonitor.extensions import monitorserver if "download" in request.path: # deliver file with open( '{}{}'.format(current_app.config.get('PATH_TMP'), request.path.split('download/')[-1]), 'rb') as data: si = StringIO.StringIO(data.read()).getvalue() output = make_response(si) if request.path.split('/')[-1].startswith( 'temp' ): # remove if filename starts with temp == temporary file os.remove('{}{}'.format(current_app.config.get('PATH_TMP'), request.path.split('download/')[-1])) output.headers[ "Content-Disposition"] = "attachment; filename=report.{}".format( request.path.split('.')[-1]) output.headers["Content-type"] = "application/x.download" return output if request.args.get('action') == 'editalarm': if request.args.get('alarmid', '0') == '0': # add new alarm alarm = Alarm(datetime.datetime.now(), '', 2, 0) else: # edit alarm alarm = Alarm.getAlarms(id=request.args.get('alarmid')) return render_template('frontend.alarms_edit.html', alarm=alarm, cities=City.getCities(), objects=AlarmObject.getAlarmObjects(), cars=Car.getCars(), frontendarea=request.args.get('frontendarea')) elif request.args.get('action') == 'alarmmonitor': # send alarm to monitor for monitor in Monitor.getMonitors(): scheduler.deleteJobForEvent( 'changeLayout') # send update to monitors for l in MonitorLayout.getLayouts(mid=int(monitor.id)): if l.trigger == 'alarm_added': #monitorserver.sendMessage(str(monitor.id), 'load', ['layoutid=%s' % l.id, 'alarmid=%s' % request.args.get('alarmid')]) TODO changed from list monitorserver.sendMessage( str(monitor.id), 'load', layoutid=l.id, alarmid=request.args.get('alarmid')) elif request.args.get('action') == 'printalarm': Printers.getPrinters(pid=int(request.args.get('printerdef'))).doPrint( object=Alarm.getAlarms(id=int(request.args.get('alarmid'))), id=request.args.get('alarmid'), copies=1) return "" elif request.args.get('action') == 'routeinfo': return render_template( 'frontend.alarms_routing.html', routing=Alarm.getAlarms( id=request.args.get('alarmid')).getRouting()) elif request.args.get('action') == 'routecoords': return jsonify( Alarm.getAlarms(id=request.args.get('alarmid')).getRouting()) elif request.args.get('action') == 'message': return render_template( 'frontend.alarms_message.html', alarm=Alarm.getAlarms(id=request.args.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area'), reload=request.args.get('reload', 'true')) elif request.args.get('action') == 'addmessage': # add message if request.form.get('messagetext') != "": alarm = Alarm.getAlarms(request.form.get('alarmid')) alarm.addHistory(request.form.get('messagestate'), request.form.get('messagetext')) db.session.commit() return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms( request.form.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area')) elif request.args.get( 'action') == 'deletemessage': # delete selected message alarm = Alarm.getAlarms(request.args.get('alarmid')) for msg in alarm.history: if str(msg.timestamp) == request.args.get('datetime'): db.session.delete(msg) db.session.commit() return render_template('frontend.alarms_message.html', alarm=Alarm.getAlarms( request.args.get('alarmid')), messagestates=AlarmHistory.historytypes, area=request.args.get('area')) elif request.args.get( 'action' ) == 'housecoordinates': # return a dict with coordinats of housenumber if request.args.get('alarmid') != "None": alarm = Alarm.getAlarms(id=int(request.args.get('alarmid'))) if alarm and alarm.housenumber: return { 'lat': map(lambda x: x[0], alarm.housenumber.points), 'lng': map(lambda x: x[1], alarm.housenumber.points) } return [] elif request.args.get('action') == 'evalhouse': # try to eval housenumer street = Street.getStreets(id=request.args.get('streetid')) if street: points = dict(lat=[], lng=[]) for hn in street.housenumbers: if str(hn.number) == request.args.get('housenumber').strip(): points['lat'].extend(map(lambda x: x[0], hn.points)) points['lng'].extend(map(lambda x: x[1], hn.points)) return points return {} elif request.args.get( 'action') == 'alarmsforstate': # render alarms for given state if 'alarmfilter' not in session: session['alarmfilter'] = 7 return render_template( 'frontend.alarms_alarm.html', alarms=Alarm.getAlarms(days=int(session['alarmfilter']), state=int(request.args.get('state', '-1'))), printdefs=Printers.getActivePrintersOfModule('alarms')) elif request.args.get('action') == 'collective': # render collective form reports = [r for r in AlarmReport.getReports() if r.reporttype.multi] if len(reports) == 0: return "" return render_template('frontend.alarms_collective.html', alarms=Alarm.getAlarms(state=2), reports=reports) elif request.args.get('action') == 'docollective': # build collective form if request.args.get('ids') == "": ids = [] else: ids = request.args.get('ids').split(',') f = AlarmReport.getReports( request.args.get('form')).createReport(ids=ids) _path, _filename = os.path.split(f) shutil.move( f, "{}{}".format(current_app.config.get('PATH_TMP'), _filename)) return _filename elif request.args.get('action') == 'alarmpriocars': # show prio cars cars = [] c = Settings.getIntList('alarms.spc_cars.{}'.format( request.args.get('state'))) if len(c) == 0: return "" for alarm in Alarm.getAlarms(state=request.args.get('state')): cars.extend([car for car in alarm.cars1 if car.id in c]) cars = Counter(cars) return render_template('frontend.alarms_cars.html', cars=cars) elif request.args.get( 'action') == 'showdetailsform': # build alarmdetails edtit form alarm = Alarm.getAlarms(id=request.args.get('alarmid')) if alarm.street.city: fields = AlarmField.getAlarmFields(dept=alarm.street.city.dept) else: fields = AlarmField.getAlarmFields( dept=Department.getDefaultDepartment().id) return render_template('frontend.alarms_fields.html', alarm=alarm, fields=fields, reports=AlarmReport.getReports()) elif request.args.get('action') == 'saveextform': # store ext-form values alarm = Alarm.getAlarms(id=request.form.get('alarmid')) for field in AlarmField.getAlarmFields(dept=alarm.street.city.dept): field.saveForm(request, alarm) db.session.commit() return ""