source: src/mapservice/server_impl/database/Model.py@ ae2ff15

debian/bullseye
Last change on this file since ae2ff15 was ae2ff15, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago
  • Fixed testing environment
    • Fixed some issues in the API and it's serving
  • Property mode set to 100644
File size: 13.4 KB
RevLine 
[5e4cb73]1'''
[ec9e811]2 Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
[5e4cb73]3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16'''
17import flask
18from flask_sqlalchemy import SQLAlchemy
[13cbe66]19from sqlalchemy import inspect, text, Enum, event, select, func
[fc99a86]20from sqlalchemy.orm.attributes import get_history
[13cbe66]21from geoalchemy2 import Geometry
22from geoalchemy2.shape import to_shape
[ac11efe]23from sqlalchemy_utc import UtcDateTime
[a88607b]24from sqlalchemy_utils import create_view, database_exists, create_database
[5e4cb73]25import hashlib
26import datetime
[041e464]27import enum
[fc99a86]28import connexion
[5ec7c42]29from pathlib import Path
30import sys
31import os
[5e4cb73]32
33db = SQLAlchemy()
34
[041e464]35class OsmType(enum.Enum):
36 Node = 1
37 Way = 2
38 Relation = 3
39
[ec9e811]40def wkb_to_dict(wkbelement):
41 point = to_shape(wkbelement)
42 return {'longitude': point.x, 'latitude': point.y}
43
[5e4cb73]44class User(db.Model):
45 __tablename__ = "users"
46
47 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
48 username = db.Column(db.String(255), nullable=False, unique=True)
49 password = db.Column(db.String(50), nullable=False)
50 salt = db.Column(db.String(50), nullable=False)
51 email = db.Column(db.String(255), nullable=False)
52 first_name = db.Column(db.String(255))
53 last_name = db.Column(db.String(255))
54 activated = db.Column(db.Boolean(), default=False)
55 activation_code = db.Column(db.String(255), default='1234')
56 #activation_code = db.Column(db.String(255), server_default=text('LEFT(MD5(NOW()), 50)'))
[bd0cb38]57 license_accepted = db.Column(db.Boolean(), default=False)
[5e4cb73]58
59 def to_dict(user):
60 result = {
61 'username': user.username,
62 'password': user.password,
63 'salt': user.salt,
64 'email': user.email,
65 'firstName': "",
66 'lastName': "",
67 'activated': user.activated,
[ae2ff15]68 'licenseAccepted': user.license_accepted
[5e4cb73]69 }
70 if user.first_name is not None:
71 result['firstName'] = user.first_name
72 if user.last_name is not None:
[8311276]73 result['lastName'] = user.last_name
[5e4cb73]74 if user.activation_code is not None:
75 result['activationCode'] = user.activation_code
76
77 return result
78
[be25db1]79 def factory(username, password, email):
80 salt = hashlib.md5('{}{}'.format(username, datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')).encode()).hexdigest()
81 password = hashlib.md5('{}{}'.format(password, salt).encode()).hexdigest()
82 activation_code = hashlib.md5('{}'.format(datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')).encode()).hexdigest()
83 return User(username=username, password=password, email=email, salt=salt, activated=False, activation_code=activation_code)
[5e4cb73]84
85 def password_verify(self, password):
86 return hashlib.md5("{}{}".format(password, self.salt).encode()).hexdigest() == self.password
87
[fc99a86]88 @staticmethod
89 def loggedin_username():
[ec8d5d0]90 if not 'user' in connexion.context:
91 return None
[fc99a86]92 return connexion.context['user']
93
94 @staticmethod
95 def loggedin_user():
96 username = User.loggedin_username()
[ec8d5d0]97 if username is None:
98 return None
[fc99a86]99 user = User.query.filter_by(username=username).all()
100 if len(user) != 1:
101 return None
102 return user[0]
[5e4cb73]103
104class ApiKey(db.Model):
105 __tablename__ = "apikeys"
106
107 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
108 user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'))
[13cbe66]109 key = db.Column(db.String(255), nullable=False, unique=True)
[5e4cb73]110 user = db.relationship("User", backref=db.backref("apikeys"), lazy=True)
111
112class Water(db.Model):
113 __tablename__ = "waters"
114
115 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
116 name = db.Column(db.String(255), nullable=False)
117 manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
[041e464]118 osm_id = db.Column(db.Integer)
119 osm_type = db.Column(Enum(OsmType))
[1e7f556]120 manager = db.relationship("User", backref=db.backref("waters"), lazy=True)
[5e4cb73]121
122 def to_dict(obj):
[be25db1]123 result = { 'waterId': obj.id, 'name': obj.name }
[5e4cb73]124 if obj.manager:
125 result['manager'] = obj.manager.username
126 if obj.osm_id:
[be25db1]127 result['osmId'] = obj.osm_id
[5e4cb73]128 if obj.osm_type:
[041e464]129 result['osmType'] = obj.osm_type.name
[13cbe66]130 if obj.gauges:
131 result['gauges'] = []
132 for gauge in obj.gauges:
133 result['gauges'].append(gauge.to_dict())
[ac11efe]134 if obj.logs:
135 logs = []
136 for log in obj.logs:
137 logs.append(log.meta_data())
138 result['logs'] = logs
[5e4cb73]139 return result
140
[13cbe66]141class Gauge(db.Model):
142 __tablename__ = "gauges"
143
144 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
145 name = db.Column(db.String(255), nullable=False)
146 manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
147 water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
148 # POINT(Lon Lat)
149 location = db.Column(Geometry(geometry_type='POINT', srid=4326, management=True))
[5e16955]150 reference_water_level_gauge_height = db.Column(db.Float, nullable = False)
[13cbe66]151 comment = db.Column(db.String(255))
[5e4cb73]152 #osm_id = db.Column(db.Integer)
153 #osm_type = db.Column(db.String(255))
154 #osm_class = db.Column(db.String(255))
[13cbe66]155 manager = db.relationship("User", backref=db.backref("gauges"), lazy=True)
156 water = db.relationship("Water", backref=db.backref("gauges"), lazy=True)
157
158 def to_dict(obj):
159 result = { 'gaugeId': obj.id, 'name': obj.name }
160 if obj.manager:
161 result['manager'] = obj.manager.username
[ec9e811]162 location = wkb_to_dict(obj.location)
[13cbe66]163 result['location'] = [location['longitude'], location['latitude']]
[5e16955]164 result['referenceWaterLevelGaugeHeight'] = obj.reference_water_level_gauge_height
[ec9e811]165 if obj.water:
166 result['water'] = { 'label': obj.water.name, 'id': obj.water.id }
[ac11efe]167 if obj.logs:
168 logs = []
169 for log in obj.logs:
170 logs.append(log.meta_data())
171 result['logs'] = logs
[13cbe66]172 if obj.comment:
173 result['comment'] = obj.comment
174 return result
175
176 def to_geojson(obj):
[ec9e811]177 location = wkb_to_dict(obj.location)
[13cbe66]178 result = {
179 'type': 'Feature',
180 'geometry': {
181 'type': 'Point',
182 'coordinates': [location['longitude'], location['latitude']]
183 },
184 'properties': {
[5e16955]185 'name': obj.name,
186 'referenceWaterLevelGaugeHeight': obj.reference_water_level_gauge_height
[13cbe66]187 }
188 }
189 if obj.manager:
190 result['properties']['manager'] = obj.manager.username
191 if obj.comment:
192 result['properties']['comment'] = obj.comment
193 return result
194
[ec8d5d0]195class Device(db.Model):
196 __tablename__ = "devices"
197
198 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
199 name = db.Column(db.String(255), nullable=False)
200 owner_id = db.Column(db.Integer, db.ForeignKey('users.id'))
201 sensor_depth = db.Column(db.Float, nullable=False)
202 comment = db.Column(db.String(255))
203
204 owner = db.relationship("User", backref=db.backref("devices"), lazy=True)
205
206 def to_dict(obj):
207 result = { 'deviceId': obj.id, 'name': obj.name, 'sensorDepth': obj.sensor_depth }
[ac11efe]208 if obj.logs:
209 logs = []
210 for log in obj.logs:
211 logs.append(log.meta_data())
212 result['logs'] = logs
[ec8d5d0]213 if obj.comment:
214 result['comment'] = obj.comment
215 return result
[306f18a]216
217class ProcessingStatus(db.Model):
218 __tablename__ = "processingstatus"
219
220 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
221 label = db.Column(db.String(255), nullable=False)
[ac11efe]222
[306f18a]223 @staticmethod
224 def insert_states():
[a88607b]225 states = [ 'Undefined', 'Queued for Parsing', 'Parsing', 'Queued for Processing', 'Processing', 'Deployed', 'To Old', 'Error' ]
[306f18a]226 changed = False
227 for state in states:
228 query = ProcessingStatus.query.filter_by(label=state).all()
229 if len(query) != 1:
230 state = ProcessingStatus(label=state)
231 db.session.add(state)
232 changed = True
233 if changed:
234 db.session.commit()
235
[ac11efe]236class Log(db.Model):
237 __tablename__ = "logs"
238
239 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
240 submitter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
241 water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
242 device_id = db.Column(db.Integer, db.ForeignKey('devices.id'))
243 gauge_id = db.Column(db.Integer, db.ForeignKey('gauges.id'))
[f601952]244 gauge_height = db.Column(db.Float, nullable=False)
[ec9e811]245 start = db.Column(UtcDateTime, nullable=True)
246 end = db.Column(UtcDateTime, nullable=True)
[306f18a]247 processing_state = db.Column(db.Integer, db.ForeignKey('processingstatus.id'), default=1)
[ac11efe]248 comment = db.Column(db.String(255))
249
250 submitter = db.relationship("User", backref=db.backref("logs"), lazy=True)
251 water = db.relationship("Water", backref=db.backref("logs"), lazy=True)
252 device = db.relationship("Device", backref=db.backref("logs"), lazy=True)
253 gauge = db.relationship("Gauge", backref=db.backref("logs"), lazy=True)
[306f18a]254 processingstatus = db.relationship("ProcessingStatus", backref=db.backref("logs"), lazy=True)
[ac11efe]255
256 def meta_data(obj):
257 result = {
258 'logId': obj.id,
259 'submitter': obj.submitter.username,
[ec9e811]260 'water': {
261 'id': obj.water.id,
262 'label': obj.water.name,
263 },
264 'device': {
265 'id': obj.device.id,
266 'label': obj.device.name,
267 },
268 'gauge': {
269 'id': obj.gauge.id,
270 'label': obj.gauge.name,
271 },
[f601952]272 'gaugeHeight': obj.gauge_height,
[ec9e811]273 'start': '',
[306f18a]274 'end': '',
275 'processingState': {
276 'id': obj.processingstatus.id,
277 'label': obj.processingstatus.label
278 }
[ac11efe]279 }
[ec9e811]280 if obj.start is not None:
281 result['start'] = obj.start.isoformat('T')
282 if obj.end is not None:
283 result['end'] = obj.end.isoformat('T')
284
[ac11efe]285 entries_count = 0
286 if obj.log_entries:
287 entries_count = len(obj.log_entries)
288 result['entriesCount'] = entries_count
289 if obj.comment:
290 result['comment'] = obj.comment
291 return result
292
293 def log(obj):
294 result = { 'metaData': obj.meta_data() }
295 entries = []
296 if obj.log_entries:
297 for log in obj.log_entries:
298 entries.append(log.to_dict())
299 result['entries'] = entries
300 return result
[ec9e811]301
302 def to_geojson(obj):
303 result = {
[1a7f9da]304 'type': 'FeatureCollection',
305 'features': []
[ec9e811]306 }
307 if obj.log_entries:
308 for log in obj.log_entries:
309 location = wkb_to_dict(log.location)
[1a7f9da]310 feature = {
311 'type': 'Feature',
312 'geometry': {
313 'type': 'Point',
314 'coordinates': [location['longitude'], location['latitude']]
315 },
316 'properties': {
317 'datetime': log.datetime.isoformat('T')
318 }
[ec9e811]319 }
[1a7f9da]320 if log.water_depth is not None:
321 feature['properties']['waterDepth'] = log.water_depth
322 result['features'].append(feature)
[ec9e811]323 return result
[ac11efe]324
325class LogEntry(db.Model):
326 __tablename__ = "logentries"
327
328 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
329 log_id = db.Column(db.Integer, db.ForeignKey('logs.id'))
330 datetime = db.Column(UtcDateTime, nullable=False)
331 # POINT(Lon Lat)
332 location = db.Column(Geometry(geometry_type='POINT', srid=4326, management=True))
333 water_depth = db.Column(db.Float)
334
335 log = db.relationship("Log", backref=db.backref("log_entries"), lazy=True)
336
337 def to_dict(obj):
338 result = {'datetime': obj.datetime.isoformat('T') }
[ec9e811]339 location = wkb_to_dict(obj.location)
[ac11efe]340 result['location'] = [location['longitude'], location['latitude']]
341 if obj.water_depth:
342 result['waterDepth'] = obj.water_depth
343 return result
[306f18a]344
345class LogView(db.Model):
346 __table__ = create_view(
347 name='logview',
348 metadata=db.Model.metadata,
349 selectable=select(
350 [
[5e16955]351 Log.id,
[306f18a]352 Log.submitter_id,
353 Log.water_id,
354 Log.device_id,
355 Log.gauge_id,
[f601952]356 Log.gauge_height,
[306f18a]357 Log.start,
358 Log.end,
359 ProcessingStatus.label,
360 func.Envelope(func.MakeLine(LogEntry.location)).label('envelope')
361 ],
362 from_obj=(Log.__table__.join(LogEntry, Log.id == LogEntry.log_id).join(ProcessingStatus, Log.processing_state == ProcessingStatus.id)),
363 group_by=(Log.id)
[5ec7c42]364 ),
365 cascade_on_drop=False
[306f18a]366 )
367
368class Queue(db.Model):
369 __tablename__ = "queue"
[ac11efe]370
[306f18a]371 log_id = db.Column(db.Integer, db.ForeignKey('logs.id'), primary_key=True)
372 datetime = db.Column(UtcDateTime, nullable=False, default=datetime.datetime.now(datetime.timezone.utc))
373
374 log = db.relationship("Log", backref=db.backref("queue"), lazy=True)
[5e4cb73]375
[ae2ff15]376def db_setup(force = False):
377 if not database_exists(db.engine.url) or force:
[a88607b]378 create_database(db.engine.url)
379 if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
[5ec7c42]380 result = db.engine.execute('SELECT count(name) FROM sqlite_master WHERE type="table" AND name="spatial_ref_sys"')
381 if result.fetchone()[0] == 1:
382 print('Spatial lite extension already loaded')
383 else:
384 print("Initiate spatial meta data for Spatialite...")
385 db.engine.execute(select([func.InitSpatialMetaData()]))
386 print("...Finished")
[a88607b]387 db.create_all()
388 ProcessingStatus.insert_states()
[5ec7c42]389
390def load_spatialite(dbapi_conn, connection_record):
391 if not 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
392 return
393
394 paths = [os.path.join(sys.prefix, 'lib'), os.path.join(sys.prefix, 'lib64'), '/usr/lib', '/usr/lib64']
395 for path in paths:
396 if _load_spatialite_from_path(path, dbapi_conn, connection_record):
[ae2ff15]397 return True
[5ec7c42]398 raise FileNotFoundError('mod_spatialite not found in folders {}'.format(', '.join(paths)))
399
400def _load_spatialite_from_path(search_path, dbapi_conn, connection_record):
401 for path in Path(search_path).rglob('mod_spatialite.so*'):
402 if os.path.exists(path):
[ae2ff15]403 if flask.current_app.config['DEBUG'] and (not 'TESTING' in flask.current_app.config or not flask.current_app.config['TESTING']):
404 print('Enabling spatial lite extension. This may take a while')
[5ec7c42]405 # From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
406 dbapi_conn.enable_load_extension(True)
407 dbapi_conn.load_extension(str(path.resolve()))
408 return True
409 return False
Note: See TracBrowser for help on using the repository browser.