forked from CampusPulse/access-directory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1628 lines (1235 loc) · 42.6 KB
/
Copy pathapp.py
File metadata and controls
1628 lines (1235 loc) · 42.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import io
import subprocess
from enum import Enum
from flask import Flask, render_template, request, redirect, abort, url_for, make_response
import logging
from werkzeug.utils import secure_filename
from werkzeug.exceptions import HTTPException
import hashlib
import re
from functools import wraps
from random import shuffle
from PIL import Image as PilImage
from relative_datetime import DateTimeUtils
from PIL.ExifTags import TAGS as EXIF_TAGS, Base as ExifBase
from datetime import datetime, timezone
from db import (
db,
func,
text,
inspect,
with_polymorphic,
ShelterType,
ButtonActivation,
MountSurface,
MountStyle,
PowerSource,
Building,
Location,
AccessPoint,
DoorButton,
Elevator,
AccessPointStatus,
Image,
Tag,
AccessPointTag,
ImageAccessPointRelation,
Feedback,
StatusType
)
from flask_migrate import Migrate, stamp, upgrade
from flask_cors import CORS, cross_origin
from s3 import S3Bucket
from typing import Optional
import shutil
import pandas as pd
import json_log_formatter
from pathlib import Path
from dotenv import load_dotenv
from helpers import floor_to_integer, RoomNumber, integer_to_floor, MapLocation, ServiceNowStatus, ServiceNowUpdateType
app = Flask(__name__)
CORS(app,origins=["*" if app.config["DEBUG"] else "https://*.campuspulse.app"], allow_headers=[
"Accept", "Authorization", "Content-Type"])
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# loading variables from .env file
load_dotenv()
logging.info("Starting up...")
configpath = Path("config.py")
if configpath.exists():
app.config.from_pyfile(configpath)
else:
app.config.from_pyfile(Path("config.env.py"))
if app.config["JSON_LOGS"] is True:
formatter = json_log_formatter.JSONFormatter()
json_handler = logging.StreamHandler()
json_handler.setFormatter(formatter)
logger.addHandler(json_handler)
logging.info("Starting up...")
git_cmd = ["git", "rev-parse", "--short", "HEAD"]
app.config["GIT_REVISION"] = subprocess.check_output(git_cmd).decode("utf-8").rstrip()
logging.info(f"Connecting to S3 Bucket {app.config['BUCKET_NAME']}")
s3_bucket = S3Bucket(
app.config["BUCKET_NAME"],
app.config["S3_KEY"],
app.config["S3_SECRET"],
app.config["S3_URL"],
)
app.config["SQLALCHEMY_DATABASE_URI"] = (
f'postgresql://{app.config["DBUSER"]}:{app.config["DBPWD"]}@{app.config["DBHOST"]}:{app.config["DBPORT"]}/{app.config["DBNAME"]}'
)
logging.info(f"Connecting to DB {app.config['DBNAME']}")
db.init_app(app)
migrate = Migrate(app, db)
with app.app_context():
# detect if database is empty
# if so create and stamp it
insp = inspect(db.engine)
if not insp.get_table_names():
logger.info("No database tables found. Creating Database")
db.create_all()
stamp(directory="migrations")
else:
# if database wasnt empty, attempt to upgrade the db
# This should do nothing if its already up to date
logger.info("Checking for database schema upgrades...")
upgrade(directory="migrations")
########################
#
# region Helpers
#
########################
class ImageType(Enum):
THUMB = "thumb"
RESIZED = "resized"
ORIGINAL = "original"
def get_latest_naming_version():
return 1
def path_for_image(file_hash:str, image_type: ImageType, naming_version=0) -> str:
if file_hash is None:
return None
if naming_version == 0:
return file_hash
elif naming_version == 1:
return f"{file_hash}_{image_type.value}.jpg"
"""
Create a JSON object for a access_point
"""
def access_point_json(access_point: AccessPoint):
image_data = db.session.execute(
db.select(Image)
.join(ImageAccessPointRelation, Image.id == ImageAccessPointRelation.image_id)
.where(ImageAccessPointRelation.access_point_id == access_point.id)
.order_by(ImageAccessPointRelation.ordering)
).scalars()
images = [image_json(i) for i in image_data]
thumbnail = get_item_thumbnail(access_point)
naming_version = thumbnail.naming_version if thumbnail is not None else None
thumbnail = thumbnail.fullsizehash if thumbnail is not None else None
thumbnail = s3_bucket.get_file_s3(path_for_image(thumbnail, ImageType.THUMB, naming_version=naming_version))
rn = RoomNumber(access_point.location.floor_number, access_point.location.room_number)
status = get_item_status(access_point)
status_style = None
statusUpdated = "No Data"
if status is None:
status_style = statusDataToStyle(StatusType.UNKNOWN, "No Data")
else:
status_style = statusDataToStyle(status.status_type, status.status, f"Ticket Number: {status.ref}")
relative_time, direction = DateTimeUtils.relative_datetime(status.timestamp)
statusUpdated = relative_time + " ago" if direction == "past" else ""
# TODO: use marshmallow to serialize
base_data = {
"id": access_point.id,
"thumbnail_ref": access_point.thumbnail_ref or "",
"building_name": access_point.location.building.name,
"room": access_point.location.room_number,
"floor": access_point.location.floor_number,
"notes": access_point.remarks,
"active": "checked" if access_point.active else "unchecked",
"status": status_style,
"status_updated": statusUpdated,
"images": images,
"tags": getTags(access_point.id),
"report_url": f"https://report.campuspulse.app/elevator?room={rn.to_string()}&building={access_point.location.building.number}:{access_point.location.building.acronym}"
}
if thumbnail is not None:
base_data.update({"thumbnail": thumbnail})
if access_point.location.nickname is not None:
base_data.update({"location_nick": access_point.location.nickname})
if access_point.location.additional_info is not None:
base_data.update({"location_info": access_point.location.additional_info})
if access_point.location.latitude is not None and access_point.location.longitude:
base_data.update({"coordinates": MapLocation.to_string(access_point.location.latitude, access_point.location.longitude)})
if isinstance(access_point, Elevator):
title = access_point.location.building.human_name()
title += f" - "
title += access_point.location.human_name()
base_data.update(
{
"title": title,
"room": rn.to_string(),
}
)
if access_point.floor_min != access_point.floor_max:
base_data.update({
"floor": f"{integer_to_floor(access_point.floor_min)} to {integer_to_floor(access_point.floor_max)}",
})
return base_data
"""
Create a JSON object for Feedback
"""
def feedback_json(feedback: Feedback):
feedback = feedback[0]
dt = datetime.now(timezone.utc)
dt = dt.replace(tzinfo=None)
fb_dt = feedback.time
diff = dt - fb_dt
return {
"id": feedback.feedback_id,
"access_point_id": feedback.access_point_id,
"notes": feedback.notes,
"contact": feedback.contact,
"approxtime": f"{diff.days} days ago", # approx_time,
"exacttime": fb_dt,
}
"""
Create a JSON object for a tag
"""
def tag_json(tag: Tag):
return {"name": tag.name, "description": tag.description}
"""
Create a JSON object for an image
"""
def image_json(image: Image):
out = {
"imgurl": s3_bucket.get_file_s3(path_for_image(image.fullsizehash, ImageType.RESIZED, naming_version=image.naming_version)),
"caption": image.caption or "",
"alttext": image.alttext or "",
"attribution": image.attribution or "Anonymous",
"datecreated": image.datecreated,
"id": image.id,
}
if image.fullsizehash != None:
out["fullsizeimage"] = s3_bucket.get_file_s3(path_for_image(image.fullsizehash, ImageType.ORIGINAL, naming_version=image.naming_version))
return out
"""
Crop a given image to a centered square
"""
def crop_center(pil_img, crop_width, crop_height):
img_width, img_height = pil_img.size
return pil_img.crop(
(
(img_width - crop_width) // 2,
(img_height - crop_height) // 2,
(img_width + crop_width) // 2,
(img_height + crop_height) // 2,
)
)
def limit_height(pil_img, height_limit):
"""
Scale an image such that the height is equal to the height limit and the aspect ratio remains the same
"""
# scale width proportionally to height
width = (pil_img.width * height_limit) // pil_img.height
(width, height) = (width, height_limit)
# set new dimensions
return pil_img.resize((width, height))
"""
Search all access points given query
"""
def searchAccessPoints(query):
return list(
map(
access_point_json,
db.session.execute(
db.select(AccessPoint)
.where(
text(
"access_point.text_search_index @@ websearch_to_tsquery(:query)"
)
)
.order_by(AccessPoint.id)
.limit(150),
{"query": query},
).scalars(),
)
)
"""
Get access points in list, paginated
"""
def getAccessPointsPaginated(page_num):
return list(
map(
access_point_json,
db.session.execute(
db.select(AccessPoint)
.where(AccessPoint.active)
.order_by(AccessPoint.id.asc())
.offset(page_num * app.config["ITEMSPERPAGE"])
.limit(app.config["ITEMSPERPAGE"])
).scalars(),
)
)
"""
Get all access points
"""
def getAllAccessPoints():
return list(
map(
access_point_json,
db.paginate(
db.select(AccessPoint).order_by(AccessPoint.id.asc()),
per_page=200,
).items,
)
)
"""
Get all access points
"""
def getAllBuildings():
b = db.session.execute(db.select(Building).order_by(Building.id.asc())).scalars()
return b
"""
Get all tags
"""
def getAllTags():
return list(db.session.execute(db.select(Tag)).scalars())
"""
Get Feedback for a AccessPoint
"""
def getAccessPointFeedback(access_point_id):
return list(
map(
feedback_json,
db.session.execute(
db.select(Feedback).where(Feedback.access_point_id == access_point_id)
),
)
)
"""
Get all access points from year
"""
def getAllAccessPointsFromYear(year):
return list(
map(
access_point_json,
db.paginate(
db.select(AccessPoint)
.where(AccessPoint.year == year)
.order_by(AccessPoint.id.asc()),
per_page=150,
).items,
)
)
"""
Get all tags
"""
def getAllTags():
return list(db.session.execute(db.select(Tag.name)).scalars())
"""
Get Tag details
"""
def getTagDetails(name):
return tag_json(
db.session.execute(db.select(Tag).where(Tag.name == name)).scalar_one()
)
"""
Exports database tables to CSV files
Stores in provided directory
"""
def export_database(dir, public):
if public:
access_point_select = db.select(
AccessPoint.id,
AccessPoint.notes,
AccessPoint.remarks,
AccessPoint.year,
AccessPoint.location,
AccessPoint.spotify,
).order_by(AccessPoint.id.asc())
else:
access_point_select = db.select(
AccessPoint.id,
AccessPoint.title,
AccessPoint.private_notes,
AccessPoint.notes,
AccessPoint.remarks,
AccessPoint.year,
AccessPoint.location,
AccessPoint.spotify,
).order_by(AccessPoint.id.asc())
feedback_select = db.select(Feedback).order_by(Feedback.feedback_id.asc())
feedback_df = pd.read_sql(feedback_select, db.engine)
feedback_df.to_csv(dir + "feedback.csv")
access_points_df = pd.read_sql(access_point_select, db.engine)
access_points_df["tags"] = access_points_df.apply(
lambda x: getTags(x["id"]), axis=1
)
images_select = (
db.select(
Image.id, Image.caption, Image.alttext, Image.attribution, Image.datecreated
)
.join(
ImageAccessPointRelation, ImageAccessPointRelation.image_id == Image.id
)
.where(ImageAccessPointRelation.ordering != 0)
.order_by(Image.id.asc())
)
images_df = pd.read_sql(images_select, db.engine)
if not Path(dir).exists():
Path(dir).mkdir()
access_points_df.to_csv(dir + "access_points.csv")
images_df.to_csv(dir + "images.csv")
"""
Exports images to <path>/images
"""
def export_images(path):
access_points = db.session.execute(
db.select(AccessPoint).order_by(AccessPoint.id.asc())
).scalars()
for m in access_points:
# TODO: migrate this to download the images
images = db.session.execute(
db.select(Image)
.join(
ImageAccessPointRelation, ImageAccessPointRelation.image_id == Image.id
)
.where(ImageAccessPointRelation.access_point_id == m.id)
.filter(ImageAccessPointRelation.ordering != 0)
).scalars()
basepath = path + "images/" + str(m.id) + "/"
if not Path(basepath).exists():
Path(basepath).mkdir()
for i in images:
s3_bucket.get_file(i.fullsizehash, basepath + str(i.ordering) + ".jpg")
"""
Imports data export into database, S3
"""
def import_data(file):
return
"""
Get access point details
"""
def getAccessPoint(id):
access_point = db.session.execute(
db.select(AccessPoint).where(AccessPoint.id == id)
).scalar()
if access_point == None:
logging.warning("DB Response was None")
logging.warning(f"ID was '{id}'")
return None
accessPointInfo = access_point_json(access_point)
logging.debug(accessPointInfo)
return accessPointInfo
def checkYearExists(year):
if not year.isdigit():
return False
integer_pattern = r"^[+-]?\d+$"
# Use re.match to check if the variable matches the integer pattern
if not re.match(integer_pattern, year):
return False
return True
def checkAccessPointExists(id):
# Check id is not bad
if not id.isdigit():
return False
return (
db.session.execute(db.select(AccessPoint).where(AccessPoint.id == id)).scalar()
!= None
)
"""
Get all access points with given tag
"""
def getAccessPointsTagged(tag):
return list(
map(
access_point_json,
db.session.execute(
db.select(AccessPoint)
.select_from(AccessPointTag)
.join(Tag, AccessPointTag.tag_id == Tag.id)
.join(AccessPoint, AccessPoint.id == AccessPointTag.access_point_id)
.where(Tag.name == tag)
).scalars(),
)
)
"""
Get all tags / Get all tags on certain access point
(logic based on whether access_point_id is passed in)
"""
def getTags(access_point_id=None):
if access_point_id == None:
return db.session.execute(db.select(Tag.name)).scalars()
else:
return list(
db.session.execute(
db.select(Tag.name)
.join(AccessPointTag, AccessPointTag.tag_id == Tag.id)
.where(AccessPointTag.access_point_id == access_point_id)
).scalars()
)
"""
Get a random assortment of images from DB, excluding thumbnails
"""
def getRandomImages(count):
images = list(
map(
image_json,
db.session.execute(
db.select(Image)
.join(
ImageAccessPointRelation, ImageAccessPointRelation.image_id == Image.id
)
.where(ImageAccessPointRelation.ordering != 0)
.order_by(func.random())
.limit(count)
).scalars(),
)
)
shuffle(images)
return images
def detachAllImagesFromItem(item_id: int, keep_files=False):
"""De-associates or deletes all images from the database given the id of the item to detach from
If images are used more than once, they are kept, and only the reference is removed. If image has no other references, its deletion is determined by `keep_files`
Args:
item_id (int): the id of the item to remove the images from
keep_files (bool, optional): Whether to keep files when they would otherwise be deleted. Defaults to False.
"""
image_refs = db.session.execute(
db.select(ImageAccessPointRelation).where(ImageAccessPointRelation.access_point_id == item_id)
).scalars()
for image_ref in image_refs:
detachImageByRef(image_ref)
def detachImageByID(image_id: int, item_id: int, keep_files=False):
"""De-associates or deletes images from the database given the id of an image and the item to detach it from
If images are used more than once, they are kept, and only the reference is removed. If image has no other references, its deletion is determined by `keep_files`
Args:
image_id (int): the id of the image to remove
item_id (int): the id of the item to remove the images from
keep_files (bool, optional): Whether to keep files when they would otherwise be deleted. Defaults to False.
"""
image = db.session.execute(
db.select(Image).where(Image.id == image_id)
).scalars().first()
image_ref = db.session.execute(
db.select(ImageAccessPointRelation).where(ImageAccessPointRelation.image_id == image_id, ImageAccessPointRelation.access_point_id == item_id )
).scalars().first()
detachImageByRef(image_ref)
def detachImageByRef(image_ref, keep_files=False):
image = image_ref.image
# check how many total references to this image exist
total_ref_count = db.session.execute(
db.select(func.count()).where(
ImageAccessPointRelation.image_id == image.id
)
).scalar()
#if theres only this one reference, remove all three images from S3 and remove it from the database
if total_ref_count <= 1:
s3_bucket.remove_file(path_for_image(image.fullsizehash, ImageType.ORIGINAL, naming_version=image.naming_version))
s3_bucket.remove_file(path_for_image(image.fullsizehash, ImageType.RESIZED, naming_version=image.naming_version))
s3_bucket.remove_file(path_for_image(image.fullsizehash, ImageType.THUMB, naming_version=image.naming_version))
db.session.delete(image)
# remove the reference to this image
db.session.delete(image_ref)
def statusDataToStyle(statustype: StatusType, message:str, context:str=None):
"""return a JSON block of style information for a given status configuration
Args:
type (StatusType): The type of status
message (str): the message to display in the status
hovertext (str, optional): Text to display on hover. Defaults to None.
Returns:
dict: a dict of style info to pass to a template
"""
bgcolor = "#b3b3b3" # default gray
textcolor = "#000"
border = True
bordercolor = "#000"
if statustype == StatusType.BROKEN:
bgcolor = "#ff4d4d" #65% red
# textcolor = ""
border = False
elif statustype == StatusType.IN_PROGRESS:
bgcolor = "yellow"
# textcolor = ""
border = False
elif statustype == StatusType.FIXED:
bgcolor = "green"
textcolor = "#fff"
border = False
elif statustype == StatusType.VERIFIED:
bgcolor = "#6666ff" #70% blue
textcolor = "#fff"
border = False
data = {
"text_color": textcolor,
"background_color": bgcolor,
"border": border,
"message": message
}
if border:
data.update({
"border_color": bordercolor
})
if context is not None:
data.update({
"title": context
})
return data
########################
#
# region Pages
#
########################
@app.route("/")
def home():
return redirect("/map", code=302)
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/map")
def map_page():
return render_template("map.html")
@app.route("/catalog")
def catalog():
query = request.args.get("q")
page = int(request.args.get("p", "1"))
if query == None:
return render_template(
"catalog.html",
q=query,
page=page,
accessPoints=getAccessPointsPaginated(page - 1),
tags=getAllTags(),
)
else:
return render_template(
"filtered.html",
pageTitle=f"Query - {query}",
subHeading="Search Query",
q=query,
accessPoints=searchAccessPoints(query),
)
@app.route("/tags?t=<tag>")
@app.route("/tags")
def tags():
tag = request.args.get("t")
if tag == None:
return render_template("404.html"), 404
else:
return render_template(
"filtered.html",
pageTitle=f"Tag - {tag}",
subHeading=getTagDetails(tag)["description"],
accessPoints=getAccessPointsTagged(tag),
)
"""
Page for specific access point details
"""
@app.route("/access_points/<id>")
def access_point(id):
if checkAccessPointExists(id):
return render_template(
"access_point.html", accessPointDetails=getAccessPoint(id)
)
else:
return render_template("404.html"), 404
"""
Generic error handler
"""
@app.errorhandler(HTTPException)
def not_found(e):
app.logger.error(e)
return render_template("404.html"), 404
########################
#
# region Ingest
#
########################
@app.route("/email_webhook", methods=["POST"])
def email_webhook():
webhook_credential = app.config["WEBHOOK_CREDENTIAL"]
# check to make sure that the POST came from an authorized source (NFSN) and not some random person POSTing stuff to this endpoint
if request.args.get("token") != webhook_credential:
return ("Unauthorized", 401)
from_addr = request.form.get("From")
app.logger.info(from_addr)
# check to make sure the email is FROM RIT's system
if not from_addr.endswith("<help@rit.edu>"):
print("invalid email")
return
subject = request.form.get("Subject")
app.logger.info(subject)
# ensure this is not a ticket about a door button (we dont have those in the DB yet)
if "Automated Accessible Door Operator" in subject:
return
# Log POST fields (headers and body)
# POST fields: From, To, Subject, Date, and Message-ID
# The main message body as "Body" (also POST)
for key, value in request.form.items():
app.logger.debug(f"POST: {key} => {value}")
html_body = None
for key, file in request.files.items(multi=True):
if file.mimetype == 'text/html':
html_body = file.read()
if html_body is None:
logger.error("Email sent via webhook did not have an HTML component to the multipart body")
statusUpdate = ServiceNowStatus.from_email(from_addr, subject, html_body)
return ("", 200)
########################
#
# region Management Helpers
#
########################
def debug_only(f):
@wraps(f)
def wrapped(**kwargs):
if app.config["DEBUG"]:
return f(**kwargs)
return abort(404)
return wrapped
def make_thumbnail(input_file, output_file, raise_if_already=True):
"""
Given an input file (as a filename to an image), downscale it to a thumbnail and store it in the (file or string filepath) represented by output_file
"""
with PilImage.open(input_file) as im:
if im.width == 256 or im.height == 256:
if raise_if_already:
raise ValueError("Thumbnail requested from image that is already thumbnail size.")
im = crop_center(im, min(im.size), min(im.size))
im.thumbnail((256, 256))
exif = im.getexif()
exif[ExifBase.ImageWidth.value] = im.width
exif[ExifBase.ImageLength.value] = im.height
im = im.convert("RGB")
im.save(output_file, "JPEG", exif=exif)
def set_thumbnail(item, image):
item.thumbnail_ref = image.id
# db.session.commit()
def get_item_thumbnail(item):
"""Fetch the thumbnail image for the provided item.
This first checks the item's `thumbnail_ref` column for a reference to the Image that should be used. If it cant find one, it grabs the first image associated with that item sorted by the image's `ordering` column.
Args:
item (AccessPoint): The item (in this case AccessPoint) to fetch an image for
Returns:
Image: The image representing the thumbnail (or None if no images could be found by either method)
"""
thumbnail = None
if item.thumbnail_ref is not None:
# theres probably a better, more "sqlalchemy" way to do this tbh
thumbnail = db.session.execute(
db.select(Image)
.where(Image.id == item.thumbnail_ref)
).scalars().first()
if thumbnail is None:
# else lookup the related images and get the first one by order
thumbnail = db.session.execute(
db.select(Image)
.join(ImageAccessPointRelation, Image.id == ImageAccessPointRelation.image_id)
.where(ImageAccessPointRelation.access_point_id == item.id)
.order_by(ImageAccessPointRelation.ordering.asc())
).scalars().first()
return thumbnail
def associate_thumbnail(file_hash, thumbnail_file, item_identifier):
"""
associate a thumbnail from S3 with a particular item in the database
"""
thumbnail_file.seek(0)
created = creationTimeFromFileExif(thumbnail_file)
img = Image(
fullsizehash=file_hash,
ordering=0,
datecreated=created
)
db.session.add(img)
db.session.flush()
img_id = img.id
db.session.add(
ImageAccessPointRelation(
image_id=img_id, access_point_id=item_identifier
)
)
db.session.commit()
def get_item_status(item):
"""Fetch the status for the provided item.
Args:
item (AccessPoint): The item (in this case AccessPoint) to fetch status for
Returns:
AccessPointStatus: the status of the access point, or None if none were found
"""
status = db.session.execute(
db.select(AccessPointStatus)
.where(AccessPointStatus.access_point_id == item.id)
.order_by(AccessPointStatus.timestamp.desc())
).scalars().first()