-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2036 lines (1914 loc) · 113 KB
/
main.py
File metadata and controls
2036 lines (1914 loc) · 113 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 bottle_mysql
import ldap
import datetime
import uuid
import json
import ast
import csv
import os
import glob
import smtplib
import subprocess
import shutil
from dateutil import tz
from dateutil.relativedelta import relativedelta
from bottle import Bottle, run, route, redirect, template, static_file, request, response, post, get, put, HTTPError
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from xhtml2pdf import pisa
from math import sin, cos, acos, radians, degrees
with open('config.json', 'r') as cFile:
cInfo = cFile.read()
cVars = json.loads(cInfo)
dbuser = str(cVars['dbuser'])
dbpass = str(cVars['dbpass'])
dbname = str(cVars['dbname'])
dbhost = str(cVars['dbhost'])
webhost = str(cVars['webhost'])
webport = str(cVars['webport'])
ldap_server = str(cVars['ldap_server'])
base_dn = str(cVars['base_dn'])
search_filter = str(cVars['search_filter'])
search_field = str(cVars['search_field'])
app = Bottle()
plugin = bottle_mysql.Plugin(
dbuser=dbuser, dbpass=dbpass, dbname=dbname, dbhost=dbhost)
app.install(plugin)
# Common functions
def checkToken(db, username, token):
db.execute(
'SELECT COUNT(*) AS count FROM tokens WHERE username=%s AND token=%s', (username, token,))
results = db.fetchone()
if results['count'] == 1:
tokenCheck = True
return tokenCheck
else:
tokenCheck = False
return tokenCheck
# Static files
@app.route('/js/<filename:re:.*\.js>')
def server_static(filename):
return static_file(filename, root='site/js')
@app.route('/images/modis/<filename:re:.*\.png>')
def server_static(filename):
return static_file(filename, root='site/images/modis')
@app.route('/images/viirs/filename:re:.*\.png>')
def server_static(filename):
return static_file(filename, root='site/images/viirs')
@app.route('/tofs/<filename:re:.*\.tof>')
def server_static(filename):
return static_file(filename, root='tofs')
@app.route('/tmp/<filename:re:.*\.tof>')
def server_static(filename):
return static_file(filename, root='tmp')
@app.route('/cars/<filename:re:.*\.pdf>')
def server_static(filename):
return static_file(filename, root='cars')
@app.route('/docs/<filename:re:.*\.pdf>')
def server_static(filename):
return static_file(filename, root='docs')
@app.route('/odf/<filename:re:.*\.odf>')
def server_static(filename):
return static_file(filename, root='odf')
@app.route('/odf<filename:re:.*\.txt>')
def server_static(filename):
return static_file(filename, root='odf')
@app.route('/kml/sites/<filename:re:.*\.kml>')
def server_static(filename):
return static_file(filename, root='kml/sites')
@app.route('/kml/paths/Both/<filename:re:.*\.kml>')
def server_static(filename):
return static_file(filename, root='kml/paths/Both')
@app.route('/kml/paths/Nadir/<filename:re:.*\.kml>')
def server_static(filename):
return static_file(filename, root='kml/paths/Nadir')
@app.route('/kml/paths/Glint/<filename:re:.*\.kml>')
def server_static(filename):
return static_file(filename, root='kml/paths/Glint')
@app.route('/kml/target_data/<filename:re:.*\.zip>')
def server_static(filename):
return static_file(filename, root='kml/target_data')
@app.route('/plots/<filename:re:.*\.png>')
def server_static(filename):
return static_file(filename, root='plots')
# Web Pages
# Home page
@app.route('/')
def index():
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
return template('site/index.html', menuFile=menuFile, footerFile=footerFile)
# TOFs page
@app.route('/tofs')
def tofs(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]
username = cookieInfo.split('.')[1]
now = datetime.datetime.now()
db.execute('SELECT COUNT(*) AS count FROM authentication WHERE cookie=%s AND username=%s AND expirationDate >= %s',
(cookieHex, username, now.strftime('%Y-%m-%d %H:%M:%S'),))
results = db.fetchone()
if results['count'] == 1:
fileList = glob.glob('tofs/*.tof')
latestFile = max(fileList, key=os.path.getctime).split('/')[-1]
latestFileStub = 'tofs/' + \
'_'.join(latestFile.split('_')[0:5]) + '*.tof'
checkDuplicates = sorted(glob.glob(latestFileStub))
if len(checkDuplicates) > 1:
latestFile = checkDuplicates[-1].split('/')[-1]
unusedFiles = checkDuplicates[0:-1]
for f in unusedFiles:
ignoreFile = f.split('/')[-1]
db.execute(
'SELECT COUNT(filename) AS filename FROM tofFiles WHERE filename=%s', (ignoreFile,))
row = db.fetchone()
checkIgnoredFile = row['filename']
if checkIgnoredFile == 0:
db.execute(
'INSERT INTO tofFiles SET filename=%s, ignored=1, createTime="2022-01-01 00:00:00"', (ignoreFile,))
db.execute(
'SELECT COUNT(filename) AS filename FROM tofFiles WHERE filename=%s', (latestFile,))
row = db.fetchone()
fileCheck = row['filename']
if fileCheck != 0:
latestFile = None
else:
pathInfo = 'tofs/'
latestFile = pathInfo + latestFile
db.execute(
'SELECT * FROM tofFiles WHERE ignored=0 order by createTime DESC')
row = db.fetchall()
return template('site/tofs.html', menuFile=menuFile, footerFile=footerFile, row=row, latestFile=latestFile)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
# Upload a new TOF
@app.route('/tofs/upload', method='POST')
def upload_tof(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]
username = cookieInfo.split('.')[1]
now = datetime.datetime.now()
db.execute('SELECT COUNT(*) AS count FROM authentication WHERE cookie=%s AND username=%s AND expirationDate >= %s',
(cookieHex, username, now.strftime('%Y-%m-%d %H:%M:%S'),))
results = db.fetchone()
if results['count'] == 1:
tofFile = request.files.get('tofFile')
latestFile = request.forms.get('latestFile')
overwriteFile = request.forms.get('overwriteFile')
if tofFile.filename == 'empty':
tofFile = None
# First, make sure we have a file to work with. If not, send the user an error message telling them there's no file.
if tofFile == None and latestFile == None and overwriteFile == None:
message = 'You did not select a TOF file and there is no latest TOF file available. Please go back and select a file to upload.'
return template('site/tofs-upload-error.html', menuFile=menuFile, footerFile=footerFile, message=message)
# The overwrite file takes precedence since it only has a value if there's an overwrite situation.
if overwriteFile != None:
name = overwriteFile.split('/')[-1].split('.')[0]
ext = '.' + overwriteFile.split('/')[-1].split('.')[-1]
save_path='tofs/'
os.remove('tofs/%s%s' % (name, ext))
shutil.move('tmp/%s%s' % (name, ext), '%s%s%s' % (save_path, name, ext))
else:
try:
# For whatever kind of TOF is uploaded, we need to check that it has a .tof extension. If not, error out.
name, ext = os.path.splitext(tofFile.filename)
if ext not in ('.tof'):
message = 'This file extension is not allowed. Please go back and upload a .tof file.'
return template('site/tofs-upload-error.html', menuFile=menuFile, footerFile=footerFile, message=message)
save_path = 'tofs/'
# Try to save the uploaded TOF file
try:
tofFile.save(save_path)
# If there's no uploaded TOF file, then we have a latest file or overwrite file situation
except OSError:
db.execute('SELECT tofID FROM tofFiles where filename=%s', (tofFile.filename,))
row = db.fetchone()
# If this is an overwrite situation, then make sure the file hasn't already been ingested into the DB. If it has, let the user know.
if row != None:
message='A file with the same name as the one you are trying to upload has already been ingested into the database. Please contact the website developer for assistance.'
return template('site/tofs-upload-error.html', menuFile=menuFile, footerFile=footerFile, message=message)
# Assuming the user is ok with an overwrite, save the file to the tmp/ directory. Will move it into place on the 2nd pass through this form.
try:
tofFile.save('tmp/')
# If somehow the overwrite file is still in tmp/ when the user goes to overwrite, remove it and then try to save it again
except OSError:
os.remove('tmp/%s%s' % (name, ext))
tofFile.save('tmp/')
overwriteFile = '%s%s%s' % (save_path, name, ext)
# Let the user know a file exists with the same names as the file they're trying to upload. If they're ok with it, we'll pass through this form again.
message = 'You are attempting to upload a new file that has the same name as one already on the filesystem. Neither file has been ingested into the database yet. If you would like to proceed uploading the file you submitted rather than the one of the filesystem, click the button below. Otherwise, go back to the TOFs page and select the latest file.'
return template('site/tofs-upload-overwrite.html', menuFile=menuFile, footerFile=footerFile, message=message, overwriteFile=overwriteFile)
# If there's no TOF file being uploaded (and nothing overwritten) then we'll use the latest file.
except AttributeError:
tofFile = latestFile
name = tofFile.split('/')[-1].split('.')[0]
ext = '.' + tofFile.split('.')[1]
save_path = 'tofs/'
# Make sure the file isn't already in the DB; this is not for an overwrite situation since that gets stopped in its tracks above if a file with the same name is already in there.
db.execute(
'SELECT tofID, filename FROM tofFiles WHERE filename LIKE %s', (name[:-8] + "%",))
row = db.fetchone()
if row != None:
db.execute('DELETE FROM tofFiles WHERE tofID=%s',
(row['tofID'],))
# Begin the ingest process
minGCDate = None
maxGCDate = None
gcInfo = []
selectionInfo = []
with open('%s%s%s' % (save_path, name, ext)) as f:
contents = [line.rstrip() for line in f]
for line in contents:
if '.tof' in line:
filename = line.split(' ')[-1]
elif 'Header' in line or 'BEGIN' in line or 'END' in line:
pass
elif 'Creation Time' in line:
createTime = line.split(' ')[-1].replace('T', ' ')
elif '#' not in line:
infoParts = line.split('\t')
if len(infoParts) == 4:
gcDateTime = datetime.datetime.strptime(
' '.join(infoParts[0:2]), '%y/%m/%d %H:%M:%S')
if minGCDate == None:
minGCDate = gcDateTime
maxGCDate = gcDateTime
orbit = infoParts[3]
info = {'gcDateTime': gcDateTime,
'orbit': orbit}
gcInfo.append(info)
elif len(infoParts) == 10:
siteID = infoParts[0]
name = infoParts[1]
targetTimeUTC = datetime.datetime.strptime(
' '.join(infoParts[2:4]), '%y/%m/%d %H:%M:%S')
db.execute(
'SELECT timezone FROM sites WHERE siteID=%s AND name=%s', (siteID, name,))
tzInfo = db.fetchall()
for t in tzInfo:
timezone = t['timezone']
from_tz = tz.gettz('UTC')
to_tz = tz.gettz(timezone)
utc = targetTimeUTC.replace(tzinfo=from_tz)
targetTimeLocal = utc.astimezone(
to_tz).strftime('%Y-%m-%d %H:%M:%S')
orbit = infoParts[4]
path = infoParts[5]
obsTimeFormatted = infoParts[6]
obsTime = (int(obsTimeFormatted.split(':')[
0]) * 60) + int(obsTimeFormatted.split(':')[1])
firstOrbit = infoParts[7]
lastOrbit = infoParts[8]
minGlintAngle = infoParts[9]
info = {'siteID': siteID,
'name': name,
'targetTimeUTC': targetTimeUTC,
'targetTimeLocal': targetTimeLocal,
'orbit': orbit,
'path': path,
'obsTime': obsTime,
'firstOrbit': firstOrbit,
'lastOrbit': lastOrbit,
'minGlintAngle': minGlintAngle,
'gcDateTime': gcDateTime}
selectionInfo.append(info)
else:
pass
else:
pass
db.execute('INSERT INTO tofFiles (filename, createTime, maxGCDate, minGCDate, createdDate, createdBy) VALUES (%s, %s, %s, %s, %s, %s)',
(filename, createTime, maxGCDate, minGCDate, datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), username,))
db.execute(
'SELECT tofID FROM tofFiles WHERE filename=%s', (filename,))
row = db.fetchone()
thisTofID = row['tofID']
for thisG in gcInfo:
db.execute('INSERT INTO gcs SET tofID=%s, gcDateTime=%s, orbit=%s',
(thisTofID, thisG['gcDateTime'], thisG['orbit'],))
for thisS in selectionInfo:
if thisS['targetTimeUTC'].date() <= maxGCDate.date():
db.execute('INSERT INTO selectedTargets SET tofID=%s, targetID=(SELECT targetID FROM sites WHERE siteID=%s AND name=%s), targetTimeUTC=%s, targetTimeLocal=%s, orbit=%s, path=%s, obsTime=%s, firstOrbit=%s, lastOrbit=%s, minGlintAngle=%s, gcID=(SELECT gcID FROM gcs WHERE gcDateTime=%s AND tofID=%s)',
(thisTofID, thisS['siteID'], thisS['name'], thisS['targetTimeUTC'], thisS['targetTimeLocal'], thisS['orbit'], thisS['path'], thisS['obsTime'], thisS['firstOrbit'], thisS['lastOrbit'], thisS['minGlintAngle'], thisS['gcDateTime'], row['tofID']))
db.execute('SELECT * FROM tofFiles WHERE tofID=%s', (thisTofID,))
row = db.fetchall()
# Make sure the most current ODF file is available for the Future Targets page
os.system('python utils/insert_odf_files.py; python utils/parse_target_options.py > tmp/insert_odf_files_status_parse_target_options_status.txt')
return template('site/tofs-imported.html', menuFile=menuFile, footerFile=footerFile, row=row)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
# E-mail after TOF upload
@ app.route('/tofs/email/<tofID>')
def email_tof(db, tofID):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]
username = cookieInfo.split('.')[1]
now = datetime.datetime.now()
db.execute('SELECT COUNT(*) AS count FROM authentication WHERE cookie=%s AND username=%s AND expirationDate >= %s',
(cookieHex, username, now.strftime('%Y-%m-%d %H:%M:%S'),))
results = db.fetchone()
if results['count'] == 1:
db.execute('SELECT s.name, s.timezone, t.targetTimeUTC, t.targetTimeLocal FROM selectedTargets t, sites s WHERE t.tofID=%s AND s.targetID=t.targetID AND s.name != "noTarget" ORDER BY s.name, t.targetTimeUTC ASC', (tofID,))
row = db.fetchall()
db.execute('SELECT DISTINCT s.name, s.emailRecipients FROM tofFiles f, selectedTargets t, sites s WHERE t.tofID=%s AND s.targetID=t.targetID AND t.tofID=f.tofID AND s.name !="noTarget" ORDER BY s.name ASC', (tofID,))
sites = db.fetchall()
db.execute(
'SELECT minGCdate, maxGCdate FROM tofFiles WHERE tofID=%s', (tofID,))
dateRange = db.fetchall()
return template('site/tofs-email.html', menuFile=menuFile, footerFile=footerFile, row=row, sites=sites, dateRange=dateRange, tofID=tofID)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
@ app.route('/tofs/email/send', method='POST')
def email_tof_send(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]
username = cookieInfo.split('.')[1]
now = datetime.datetime.now()
db.execute('SELECT COUNT(*) AS count FROM authentication WHERE cookie=%s AND username=%s AND expirationDate >= %s',
(cookieHex, username, now.strftime('%Y-%m-%d %H:%M:%S'),))
results = db.fetchone()
if results['count'] == 1:
emailType = request.forms.get('emailType')
tofID = request.forms.get('tofID')
db.execute('SELECT s.name, s.timezone, t.targetTimeUTC, t.targetTimeLocal FROM selectedTargets t, sites s WHERE t.tofID=%s AND s.targetID=t.targetID AND s.name != "noTarget" ORDER BY s.name, t.targetTimeUTC ASC', (tofID,))
row = db.fetchall()
db.execute('SELECT DISTINCT s.name, s.emailRecipients FROM tofFiles f, selectedTargets t, sites s WHERE t.tofID=%s AND s.targetID=t.targetID AND t.tofID=f.tofID AND s.name !="noTarget" ORDER BY s.name ASC', (tofID,))
sites = db.fetchall()
db.execute(
'SELECT minGCdate, maxGCdate FROM tofFiles WHERE tofID=%s', (tofID,))
dateRange = db.fetchall()
for thisSite in sites:
if emailType == 'debug':
toaddr = ', '.join(['contact1@mail.com', 'contact2@mail.com'])
else:
toaddr = thisSite['emailRecipients'] + \
', contact1@mail.com, contact2@mail.com'
server = smtplib.SMTP('localhost', 25)
server.ehlo()
fromaddr = 'test@mail.com'
subject = 'Target List: %s %s to %s UTC' % (
thisSite['name'], dateRange[0]['minGCdate'], dateRange[0]['maxGCdate'])
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = subject
body = 'Dear Team,<br /><br />'
body += 'Your validation site is included in the list of potential targets for the following period, from %s UTC to %s UTC. The dates and times under consideration for your site are:<br /><br />' % (
dateRange[0]['minGCdate'], dateRange[0]['maxGCdate'])
body += '<ul style="list-style: circle; margin-left:40px;">'
for thisRow in row:
if thisRow['name'] == thisSite['name']:
body += '<li>%s %s %s (%s UTC)</li>' % (
thisRow['name'], thisRow['targetTimeLocal'], thisRow['timezone'], thisRow['targetTimeUTC'])
body += '</ul>'
body += '<br />'
body += 'Please notify us if your site should not be targeted for any of these opportunities.<br /><br />'
body += 'Selections will be made by 5 PM Pacific Time before a scheduled target and you will be notified at that time if your site has been selected.<br /><br />'
body += 'The Team thanks you, in advance, for your participation! Questions or concerns can be directed to <a href="mailto:contact1@mail.com">Contact</a>.<br /><br />'
body += 'Thank you,<br /><br />'
body += 'The Team<br /><br />'
body += '<br/>'
msg.attach(MIMEText(body, 'html', 'utf-8'))
text = msg.as_string()
try:
server.sendmail(fromaddr, toaddr.split(','), text)
server.close
print('Message sent')
except:
print('Message failed to send.')
db.execute(
'UPDATE tofFiles SET weekOneEmailDate = NOW() WHERE tofID=%s', (tofID,))
return template('site/tofs-email-send.html', menuFile=menuFile, footerFile=footerFile)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
@ app.route('/tofs/ignore', method='POST')
def tofs_ignore(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]
username = cookieInfo.split('.')[1]
now = datetime.datetime.now()
db.execute('SELECT COUNT(*) AS count FROM authentication WHERE cookie=%s AND username=%s AND expirationDate >= %s',
(cookieHex, username, now.strftime('%Y-%m-%d %H:%M:%S'),))
results = db.fetchone()
if results['count'] == 1:
latestFile = request.forms.get('latestFile')
if latestFile == None:
return template('site/tofs-next-file-ignored.html', menuFile=menuFile, footerFile=footerFile, message='There is no latest file on the system to ignore. Please go back to the TOFs page.')
else:
tofFile = latestFile.split('/')[-1]
db.execute(
'INSERT INTO tofFiles SET filename=%s, ignored=1, createTime="2022-01-01 00:00:00"', (tofFile,))
return template('site/tofs-next-file-ignored.html', menuFile=menuFile, footerFile=footerFile, message='This TOF file will be ignored.')
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
# Sites page
@ app.route('/sites')
def sites(db):
db.execute('SELECT siteID, name, description, ROUND(ST_X(targetGeo), 2) as targetLon, ROUND(ST_Y(targetGeo), 2) as targetLat, targetAlt, ROUND(ST_X(tcconGeo), 2) as tcconLon, ROUND(ST_Y(tcconGeo), 2) as tcconLat, tcconAlt, tcconStatusText, tcconStatusValue, tcconStatusLink, timezone, contact, emailRecipients FROM sites WHERE display=1 ORDER BY name ASC')
row = db.fetchall()
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
return template('site/sites.html', footerFile=footerFile, menuFile=menuFile, row=row)
# Individual site targets page
@ app.route('/sites/<siteName>')
def site_name(db, siteName):
db.execute('SELECT ROUND(ST_X(s.targetGeo), 2) as targetLon, ROUND(ST_Y(s.targetGeo), 2) as targetLat, g.gcDateTime, s.name, t.obsMode, t.orbit, t.orbitURL, t.path, t.targetTimeUTC, t.selectDate, t.carFile, t.tofID, t.emailTime, t.tcconDataAvailable, t.tcconDataStatus, t.ocoDataAvailable, t.ocoDataStatus, t.ocoDataInfo, t.selectedBy, t.modisImage, REPLACE(t.modisImage, ".png", "_thumbnail.png") AS modisThumbnail, t.viirsImage, REPLACE(t.viirsImage, ".png", "_thumbnail.png") AS viirsThumbnail, t.aeronetData, s.accuWeatherLink, s.wuWeatherLink FROM selectedTargets t, sites s, gcs g WHERE t.targetID=s.targetID AND t.gcID=g.gcID AND t.display=1 AND name=%s AND t.selectDate IS NOT NULL ORDER BY g.gcDateTime ASC', (siteName,))
row = db.fetchall()
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
checked = ''
return template('site/selected-targets-site.html', footerFile=footerFile, menuFile=menuFile, row=row, siteName=siteName, checked=checked)
@app.route('/sites/<siteName>', method='POST')
def site_name(db, siteName):
try:
showAllTargets = request.forms.dict['showAllTargets'][0]
except KeyError:
showAllTargets = None
if showAllTargets == 'on':
db.execute('SELECT ROUND(ST_X(s.targetGeo), 2) as targetLon, ROUND(ST_Y(s.targetGeo), 2) as targetLat, g.gcDateTime, s.name, t.obsMode, t.orbit, t.orbitURL, t.path, t.targetTimeUTC, t.selectDate, t.carFile, t.tofID, t.emailTime, t.tcconDataAvailable, t.tcconDataStatus, t.ocoDataAvailable, t.ocoDataStatus, t.ocoDataInfo, t.selectedBy, t.modisImage, REPLACE(t.modisImage, ".png", "_thumbnail.png") AS modisThumbnail, t.viirsImage, REPLACE(t.viirsImage, ".png", "_thumbnail.png") AS viirsThumbnail, t.aeronetData, s.accuWeatherLink, s.wuWeatherLink FROM selectedTargets t, sites s, gcs g WHERE t.targetID=s.targetID AND t.gcID=g.gcID AND t.display=1 AND name=%s ORDER BY g.gcDateTime ASC', (siteName,))
checked = 'CHECKED'
else:
db.execute('SELECT ROUND(ST_X(s.targetGeo), 2) as targetLon, ROUND(ST_Y(s.targetGeo), 2) as targetLat, g.gcDateTime, s.name, t.obsMode, t.orbit, t.orbitURL, t.path, t.targetTimeUTC, t.selectDate, t.carFile, t.tofID, t.emailTime, t.tcconDataAvailable, t.tcconDataStatus, t.ocoDataAvailable, t.ocoDataStatus, t.ocoDataInfo, t.selectedBy, t.modisImage, REPLACE(t.modisImage, ".png", "_thumbnail.png") AS modisThumbnail, t.viirsImage, REPLACe(t.viirsImage, ".png", "_thumbnail.png") AS viirsThumbnail, t.aeronetData, s.accuWeatherLink, s.wuWeatherLink FROM selectedTargets t, sites s, gcs g WHERE t.targetID=s.targetID AND t.gcID=g.gcID AND t.display=1 AND name=%s AND t.selectDate IS NOT NULL ORDER BY g.gcDateTime ASC', (siteName,))
checked = ''
row = db.fetchall()
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
return template('site/selected-targets-site.html', footerFile=footerFile, menuFile=menuFile, row=row, siteName=siteName, checked=checked)
# Site Stats Page
@ app.route('/site-stats')
def site_stats(db):
db.execute(
'SELECT targetID, name, description FROM sites WHERE display=1 ORDER BY name ASC')
row = db.fetchall()
info = []
for site in row:
db.execute('SELECT MAX(targetTimeUTC) as targetTimeUTC FROM selectedTargets WHERE selectDate IS NOT NULL AND targetID=%s', (site['targetID'],))
row = db.fetchone()
lastTargetTime = row['targetTimeUTC']
db.execute(
'SELECT COUNT(*) as numSelections FROM selectedTargets WHERE selectDate IS NOT NULL AND targetID=%s', (site['targetID'],))
row = db.fetchone()
numSelections = row['numSelections']
info.append({'name': site['name'],
'description': site['description'],
'lastTargetTime': lastTargetTime,
'numSelections': numSelections})
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
return template('site/site-stats.html', footerFile=footerFile, menuFile=menuFile, row=info)
# Selected targets page
@ app.route('/selected-targets')
def selected_targets(db):
today = datetime.datetime.now()
endRange = today.date().strftime("%Y-%m-%d")
sixMonthsAgo = datetime.datetime.now() - relativedelta(months=6)
startRange = sixMonthsAgo.date().strftime("%Y-%m-%d")
db.execute('SELECT g.gcDateTime as groundContactTime, s.name, t.orbit, t.obsMode, t.orbitURL, t.path, t.selectionID, t.targetTimeUTC, t.carFile, t.selectDate, t.tofID, t.emailTime, t.tcconDataAvailable, t.tcconDataStatus, t.ocoDataAvailable, t.ocoDataStatus, t.ocoDataInfo, t.selectedBy, t.modisImage, REPLACE(t.modisImage, ".png", "_thumbnail.png") AS modisThumbnail, t.viirsImage, REPLACE(t.viirsImage, ".png", "_thumbnail.png") AS viirsThumbnail, t.aeronetData FROM selectedTargets t, sites s, gcs g WHERE g.gcID=t.gcID AND t.targetID=s.targetID AND t.display=1 AND DATE(g.gcDateTime) >= %s AND DATE(g.gcDateTime) <= %s AND t.selectDate IS NOT NULL ORDER BY g.gcDateTime ASC', (startRange, endRange,))
row = db.fetchall()
checked = ''
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
return template('site/selected-targets.html', footerFile=footerFile, menuFile=menuFile, row=row, endRange=endRange, startRange=startRange, checked=checked)
@ app.route('/selected-targets', method='POST')
def selected_targets_post(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
startRange = request.forms.get('startRange')
endRange = request.forms.get('endRange')
if len(startRange) != 10 or len(endRange) != 10:
message = 'You have entered an invalid start date or end date. Please go back and make sure both dates are in YYYY-MM-DD format.'
return template('site/selected-targets-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
try:
endDateCheck = datetime.datetime.strptime(endRange, '%Y-%m-%d')
startDateCheck = datetime.datetime.strptime(startRange, '%Y-%m-%d')
except ValueError:
message = 'You have entered an invalid start date or end date. Please go back and make sure both dates are in YYYY-MM-DD format.'
return template('site/selected-targets-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
if startDateCheck > endDateCheck:
message = 'You entered a start time greater than the end time. Please go back and adjust your date entries.'
return template('site/selected-targets-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
try:
showNoTargets = request.forms.dict['showNoTarget'][0]
except KeyError:
showNoTargets = None
try:
outputFile = request.forms.dict['outputFile'][0]
except KeyError:
outputFile = None
if outputFile == 'on':
return redirect('/api/report/selected-sites-output?showNoTarget=%s&startRange=%s&endRange=%s' % (showNoTargets, startRange, endRange))
if showNoTargets == 'on':
db.execute('SELECT g.gcDateTime as groundContactTime, s.name, t.selectionID, t.orbit, t.obsMode, t.orbitURL, t.path, t.targetTimeUTC, t.carFile, t.selectDate, t.tofID, t.emailTime, t.tcconDataAvailable, t.tcconDataStatus, t.ocoDataAvailable, t.ocoDataStatus, t.ocoDataInfo, t.selectedBy, t.modisImage, REPLACE(t.modisImage, ".png", "_thumbnail.png") AS modisThumbnail, t.viirsImage, REPLACE(t.viirsImage, ".png", "_thumbnail.png") AS viirsThumbnail, t.aeronetData FROM selectedTargets t, sites s, gcs g WHERE g.gcID=t.gcID AND t.targetID=s.targetID AND t.display=1 AND DATE(g.gcDateTime) >= %s AND DATE(g.gcDateTime) <= %s AND s.name != "noTarget" AND t.selectDate IS NOT NULL ORDER BY g.gcDateTime ASC', (startRange, endRange,))
else:
db.execute('SELECT g.gcDateTime as groundContactTime, s.name, t.selectionID, t.orbit, t.obsMode, t.orbitURL, t.path, t.targetTimeUTC, t.carFile, t.selectDate, t.tofID, t.emailTime, t.tcconDataAvailable, t.tcconDataStatus, t.ocoDataAvailable, t.ocoDataStatus, t.ocoDataInfo, t.selectedBy, t.modisImage, REPLACE(t.modisImage, ".png", "_thumbnail.png") AS modisThumbnail, t.viirsImage, REPLACE(t.viirsImage, ".png", "_thumbnail.png") AS viirsThumbnail, t.aeronetData FROM selectedTargets t, sites s, gcs g WHERE g.gcID=t.gcID AND t.targetID=s.targetID AND t.display=1 AND DATE(g.gcDateTime) >= %s AND DATE(g.gcDateTime) <= %s AND selectDate IS NOT NULL ORDER BY g.gcDateTime ASC', (startRange, endRange,))
row = db.fetchall()
if showNoTargets == 'on':
checked = 'CHECKED'
else:
checked = ''
return template('site/selected-targets.html', footerFile=footerFile, menuFile=menuFile, row=row, endRange=endRange, startRange=startRange, checked=checked)
# Active targets page
@ app.route('/active-targets')
def active_targets(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]
username = cookieInfo.split('.')[1]
now = datetime.datetime.now()
db.execute('SELECT COUNT(*) AS count FROM authentication WHERE cookie=%s AND username=%s AND expirationDate >= %s',
(cookieHex, username, now.strftime('%Y-%m-%d %H:%M:%S'),))
results = db.fetchone()
if results['count'] == 1:
tomorrow = datetime.datetime.now() + datetime.timedelta(days=1)
startRange = tomorrow.date().strftime("%Y-%m-%d")
sevenDaysFromNow = datetime.datetime.now() + relativedelta(days=7)
endRange = sevenDaysFromNow.date().strftime("%Y-%m-%d")
db.execute(
'SELECT DISTINCT orbit FROM gcs WHERE DATE(gcDateTime) >= %s AND DATE(gcDateTime) <= %s', (startRange, endRange,))
orbitNums = db.fetchall()
gcIDresults = []
for thisOrbit in orbitNums:
db.execute(
'SELECT MAX(tofID) AS tofID FROM gcs WHERE orbit = %s', (thisOrbit['orbit'],))
maxTOF = db.fetchone()
db.execute('SELECT gcID FROM gcs WHERE tofID = %s AND orbit = %s',
(maxTOF['tofID'], thisOrbit['orbit'],))
getGC = db.fetchone()
gcIDresults.append(str(getGC['gcID']))
gcList = ','.join(gcIDresults)
if gcList != '':
sql = 'SELECT selectionID FROM selectedTargets s WHERE gcID in (%s)'
db.execute(sql, (gcList,))
selectionResults = db.fetchall()
selectionIDs = []
for s in selectionResults:
selectionIDs.append(str(s['selectionID']))
selectionList = ','.join(selectionIDs)
sql = 'SELECT g.gcDateTime as groundContactTime, s.name, t.orbit, t.orbitURL, t.path, t.targetTimeUTC, t.targetTimeLocal, t.minGlintAngle, t.obsMode, SEC_TO_TIME(t.obsTime) AS obsTime, f.filename, s.tcconStatusText, s.tcconStatusValue, s.tcconStatusLink, s.accuWeatherLink, t.selectionID FROM selectedTargets t, sites s, tofFiles f, gcs g WHERE g.gcID=t.gcID AND t.targetID=s.targetID AND t.display=1 AND t.selectionID IN (%s) AND t.tofID=f.tofID AND t.orbit != 0 ORDER BY t.orbit, g.gcDateTime, s.name ASC'
db.execute(sql, (selectionList,))
row = db.fetchall()
else:
row = ()
if row != ():
for r in row:
if r['accuWeatherLink'] != None:
d0 = datetime.datetime.utcnow().date()
d1 = r['targetTimeUTC'].date()
dayDiff = d1-d0
dayDiff = dayDiff.days
r['accuWeatherLink'] += '?day=%s' % dayDiff
return template('site/active-targets.html', footerFile=footerFile, menuFile=menuFile, row=row, endRange=endRange, startRange=startRange, tomorrow=tomorrow.date())
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
@ app.route('/active-targets', method='POST')
def active_targets_post(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]
username = cookieInfo.split('.')[1]
now = datetime.datetime.now()
db.execute('SELECT COUNT(*) AS count FROM authentication WHERE cookie=%s AND username=%s AND expirationDate >= %s',
(cookieHex, username, now.strftime('%Y-%m-%d %H:%M:%S'),))
results = db.fetchone()
if results['count'] == 1:
startRange = request.forms.get('startRange')
endRange = request.forms.get('endRange')
tomorrow = datetime.datetime.now() + datetime.timedelta(days=1)
sevenDaysAgo = (datetime.datetime.now() -
datetime.timedelta(days=7))
if len(startRange) != 10 or len(endRange) != 10:
message = 'Please go back and enter valid start and end dates in YYYY-MM-DD format.'
return template('site/active-targets-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
try:
if datetime.datetime.strptime(startRange, '%Y-%m-%d') < sevenDaysAgo:
message = 'You may only go back 7 days. Please go back and select a new date.'
return template('site/active-targets-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
except ValueError:
message = 'Please go back and enter a valid start date in YYYY-MM-DD format.'
return template('site/active-targets-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
try:
endDateCheck = datetime.datetime.strptime(endRange, '%Y-%m-%d')
except ValueError:
message = 'Please go back and enter a valid end date in YYYY-MM-DD format.'
return template('site/active-targets-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
if datetime.datetime.strptime(startRange, '%Y-%m-%d') > datetime.datetime.strptime(endRange, '%Y-%m-%d'):
message = 'You entered a start time greater than the end time. Please go back and adjust your date entries.'
return template('site/active-targets-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
try:
outputFile = request.forms.dict['outputFile'][0]
except KeyError:
outputFile = None
if outputFile == 'on':
return redirect('/api/report/active-sites-output?startRange=%s&endRange=%s' % (startRange, endRange))
db.execute(
'SELECT DISTINCT orbit FROM gcs WHERE DATE(gcDateTime) >= %s AND DATE(gcDateTime) <= %s', (startRange, endRange,))
orbitNums = db.fetchall()
gcIDresults = []
for thisOrbit in orbitNums:
db.execute(
'SELECT MAX(tofID) AS tofID FROM gcs WHERE orbit = %s', (thisOrbit['orbit'],))
maxTOF = db.fetchone()
db.execute('SELECT gcID FROM gcs WHERE tofID = %s AND orbit = %s',
(maxTOF['tofID'], thisOrbit['orbit'],))
getGC = db.fetchone()
gcIDresults.append(str(getGC['gcID']))
gcList = ','.join(gcIDresults)
if gcList != '':
sql = 'SELECT selectionID FROM selectedTargets s WHERE gcID in (%s)'
db.execute(sql, (gcList,))
selectionResults = db.fetchall()
selectionIDs = []
for s in selectionResults:
selectionIDs.append(str(s['selectionID']))
selectionList = ','.join(selectionIDs)
sql = 'SELECT g.gcDateTime as groundContactTime, s.name, t.orbit, t.orbitURL, t.path, t.targetTimeUTC, t.targetTimeLocal, t.minGlintAngle, t.obsMode, SEC_TO_TIME(t.obsTime) AS obsTime, f.filename, s.tcconStatusText, s.tcconStatusValue, s.tcconStatusLink, s.accuWeatherLink, t.selectionID FROM selectedTargets t, sites s, tofFiles f, gcs g WHERE g.gcID=t.gcID AND t.targetID=s.targetID AND t.display=1 AND t.selectionID IN (%s) AND t.tofID=f.tofID AND t.orbit != 0 ORDER BY t.orbit, g.gcDateTime, s.name ASC'
db.execute(sql, (selectionList,))
row = db.fetchall()
else:
row = ()
if row != ():
for r in row:
if r['accuWeatherLink'] != None:
d0 = datetime.datetime.utcnow().date()
d1 = r['targetTimeUTC'].date()
dayDiff = d1-d0
dayDiff = dayDiff.days
r['accuWeatherLink'] += '?day=%s' % dayDiff
return template('site/active-targets.html', footerFile=footerFile, menuFile=menuFile, row=row, endRange=endRange, startRange=startRange, tomorrow=tomorrow.date())
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
# Select Targets
@ app.route('/select-target')
def select_targets(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]
username = cookieInfo.split('.')[1]
now = datetime.datetime.now()
db.execute('SELECT COUNT(*) AS count FROM authentication WHERE cookie=%s AND username=%s AND expirationDate >= %s',
(cookieHex, username, now.strftime('%Y-%m-%d %H:%M:%S'),))
results = db.fetchone()
if results['count'] == 1:
searchDate = (datetime.datetime.now() +
datetime.timedelta(days=1)).strftime("%Y-%m-%d")
db.execute(
'SELECT COUNT(*) count FROM selectedTargets WHERE selectDate=%s', (searchDate,))
todayCheck = db.fetchone()['count']
# if todayCheck > 0:
# searchDate = (datetime.datetime.now() +
# datetime.timedelta(days=2)).strftime('%Y-%m-%d')
db.execute(
'SELECT DISTINCT orbit FROM gcs WHERE DATE(gcDateTime) = %s', (searchDate,))
orbitNums = db.fetchall()
gcIDresults = []
for thisOrbit in orbitNums:
db.execute(
'SELECT MAX(tofID) AS tofID FROM gcs WHERE orbit = %s', (thisOrbit['orbit'],))
maxTOF = db.fetchone()
db.execute('SELECT gcID FROM gcs WHERE tofID = %s AND orbit = %s',
(maxTOF['tofID'], thisOrbit['orbit'],))
getGC = db.fetchone()
gcIDresults.append(str(getGC['gcID']))
gcList = ','.join(gcIDresults)
passGCID = None
if gcList != '':
sql = 'SELECT selectionID FROM selectedTargets s WHERE gcID in (%s)'
db.execute(sql, (gcList,))
selectionResults = db.fetchall()
selectionIDs = []
for s in selectionResults:
selectionIDs.append(str(s['selectionID']))
selectionList = ','.join(selectionIDs)
sql = 'SELECT s.selectionID, t.targetID, t.name, s.targetTimeUTC, s.targetTimeLocal, s.minGlintAngle, s.path, s.obsMode, ST_Y(t.targetGeo) AS targetLat, SEC_TO_TIME(s.obsTime) AS obsTime, s.tcconDataAvailable, s.tcconDataStatus, t.tcconStatusText, t.tcconStatusValue, t.tcconStatusLink FROM selectedTargets s, sites t WHERE t.targetID=s.targetID AND s.selectionID IN (%s) AND s.selectedBy IS NULL AND s.selectDate IS NULL'
db.execute(sql, (selectionList,))
siteInfo = db.fetchall()
info = []
for thisSite in siteInfo:
db.execute('SELECT COUNT(*) as numSelections FROM selectedTargets WHERE selectDate IS NOT NULL AND targetID=%s', (thisSite['targetID'],))
results = db.fetchone()
numOfSelections = results['numSelections']
db.execute('SELECT targetTimeUTC FROM selectedTargets WHERE targetID=%s ORDER BY selectDate DESC LIMIT 1', (thisSite['targetID'],))
results = db.fetchone()
lastSelection = results['targetTimeUTC']
H = 15.0 * 1.5
N = datetime.datetime.strptime(
searchDate, '%Y-%m-%d').timetuple().tm_yday
decl = 23.45*sin(radians(360*(N-81)/365))
cospart = cos(
radians(thisSite['targetLat'])) * cos(radians(decl))
sinpart = sin(
radians(thisSite['targetLat'])) * sin(radians(decl))
cos_SZA = cos(radians(H))*cospart + sinpart
SZA_rads = acos(cos_SZA)
sza = degrees(SZA_rads)
i = {'name': thisSite['name'],
'targetTimeUTC': thisSite['targetTimeUTC'],
'targetTimeLocal': thisSite['targetTimeLocal'],
'minGlintAngle': thisSite['minGlintAngle'],
'obsTime': thisSite['obsTime'],
'path': thisSite['path'],
'obsMode': thisSite['obsMode'],
'sza': round(sza, 4),
'tcconDataAvailable': thisSite['tcconDataAvailable'],
'tcconDataStatus': thisSite['tcconDataStatus'],
'tcconStatusText': thisSite['tcconStatusText'],
'tcconStatusValue': thisSite['tcconStatusValue'],
'tcconStatusLink': thisSite['tcconStatusLink'],
'numOfSelections': numOfSelections,
'lastSelection': lastSelection,
'selectionID': thisSite['selectionID']}
info.append(i)
passGCID = gcList.split(',')[0]
else:
info = []
db.execute(
'SELECT targetID, name, description FROM sites WHERE display=1 ORDER BY name ASC')
siteRow = db.fetchall()
siteInfo = []
for site in siteRow:
db.execute('SELECT MAX(targetTimeUTC) as targetTimeUTC FROM selectedTargets WHERE selectDate IS NOT NULL AND targetID=%s', (site['targetID'],))
detailRow = db.fetchone()
lastTargetTime = detailRow['targetTimeUTC']
db.execute(
'SELECT COUNT(*) as numSelections FROM selectedTargets WHERE selectDate IS NOT NULL AND targetID=%s', (site['targetID'],))
countRow = db.fetchone()
numSelections = countRow['numSelections']
siteInfo.append({'name': site['name'],
'description': site['description'],
'lastTargetTime': lastTargetTime,
'numSelections': numSelections})
db.execute('SELECT g.gcDateTime, t.name, s.selectionID, s.targetTimeUTC, s.targetTimeLocal, s.selectDate, s.emailTime, s.selectedBy, s.carFile FROM gcs g, sites t, selectedTargets s WHERE g.gcID=s.gcID AND t.targetID=s.targetID AND s.selectDate IS NOT NULL AND s.selectedBy IS NOT NULL AND DATE(g.gcDateTime)=%s ', (searchDate,))
alreadySelected = db.fetchall()
db.execute(
'SELECT note FROM notes WHERE startDate <= %s AND endDate >= %s', (searchDate, searchDate,))
noteInfo = db.fetchall()
if len(noteInfo) == 0:
noteInfo = None
return template('site/select-target.html', footerFile=footerFile, menuFile=menuFile, info=info, searchDate=searchDate, alreadySelected=alreadySelected, passGCID=passGCID, siteInfo=siteInfo, noteInfo=noteInfo)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
@ app.route('/select-target', method='POST')
def select_targets_post(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]
username = cookieInfo.split('.')[1]
now = datetime.datetime.now()
db.execute('SELECT COUNT(*) AS count FROM authentication WHERE cookie=%s AND username=%s AND expirationDate >= %s',
(cookieHex, username, now.strftime('%Y-%m-%d %H:%M:%S'),))
results = db.fetchone()
if results['count'] == 1:
searchDate = request.forms.get('selectDate')
sevenDaysAgo = (datetime.datetime.now() -
datetime.timedelta(days=7))
try:
if datetime.datetime.strptime(searchDate, '%Y-%m-%d') < sevenDaysAgo:
message = 'You may only go back 7 days. Please go back and select a new date.'
return template('site/select-target-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
except ValueError:
message = 'Please go back and enter a valid date in YYYY-MM-DD format.'
return template('site/select-target-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
if len(searchDate) != 10:
message = 'Please go back and enter a valid date in YYYY-MM-DD format.'
return template('site/select-target-date-error.html', footerFile=footerFile, menuFile=menuFile, message=message)
db.execute(
'SELECT DISTINCT orbit FROM gcs WHERE DATE(gcDateTime) = %s', (searchDate,))
orbitNums = db.fetchall()
gcIDresults = []
for thisOrbit in orbitNums:
db.execute(
'SELECT MAX(tofID) AS tofID FROM gcs WHERE orbit = %s', (thisOrbit['orbit'],))
maxTOF = db.fetchone()
db.execute('SELECT gcID FROM gcs WHERE tofID = %s AND orbit = %s',
(maxTOF['tofID'], thisOrbit['orbit'],))
getGC = db.fetchone()
gcIDresults.append(str(getGC['gcID']))
gcList = ','.join(gcIDresults)
passGCID = None
if gcList != '':
sql = 'SELECT selectionID FROM selectedTargets s WHERE gcID in (%s)'
db.execute(sql, (gcList,))
selectionResults = db.fetchall()
selectionIDs = []
for s in selectionResults:
selectionIDs.append(str(s['selectionID']))
selectionList = ','.join(selectionIDs)
sql = 'SELECT s.selectionID, t.targetID, t.name, s.targetTimeUTC, s.targetTimeLocal, s.minGlintAngle, s.path, s.obsMode, SEC_TO_TIME(s.obsTime) AS obsTime, ST_Y(t.targetGeo) AS targetLat, s.tcconDataAvailable, s.tcconDataStatus, t.tcconStatusText, t.tcconStatusValue, t.tcconStatusLink FROM selectedTargets s, sites t WHERE t.targetID=s.targetID AND s.selectionID IN (%s) AND s.selectedBy IS NULL AND s.selectDate IS NULL'
db.execute(sql, (selectionList,))
siteInfo = db.fetchall()
info = []
for thisSite in siteInfo:
db.execute('SELECT COUNT(*) as numSelections FROM selectedTargets WHERE selectDate IS NOT NULL AND targetID=%s', (thisSite['targetID'],))
results = db.fetchone()
numOfSelections = results['numSelections']
db.execute('SELECT selectDate FROM selectedTargets WHERE targetID=%s ORDER BY selectDate DESC LIMIT 1', (thisSite['targetID'],))
results = db.fetchone()
lastSelection = results['selectDate']
H = 15.0 * 1.5
N = datetime.datetime.strptime(
searchDate, '%Y-%m-%d').timetuple().tm_yday
decl = 23.45*sin(radians(360*(N-81)/365))
cospart = cos(
radians(thisSite['targetLat'])) * cos(radians(decl))
sinpart = sin(
radians(thisSite['targetLat'])) * sin(radians(decl))
cos_SZA = cos(radians(H))*cospart + sinpart
SZA_rads = acos(cos_SZA)
sza = degrees(SZA_rads)
i = {'name': thisSite['name'],
'targetTimeUTC': thisSite['targetTimeUTC'],
'targetTimeLocal': thisSite['targetTimeLocal'],
'minGlintAngle': thisSite['minGlintAngle'],
'path': thisSite['path'],
'obsMode': thisSite['obsMode'],
'obsTime': thisSite['obsTime'],
'sza': round(sza, 4),
'tcconDataAvailable': thisSite['tcconDataAvailable'],
'tcconDataStatus': thisSite['tcconDataStatus'],
'tcconStatusValue': thisSite['tcconStatusValue'],
'tcconStatusLink': thisSite['tcconStatusLink'],
'tcconStatusText': thisSite['tcconStatusText'],
'numOfSelections': numOfSelections,
'lastSelection': lastSelection,
'selectionID': thisSite['selectionID']}
info.append(i)
passGCID = gcList.split(',')[0]
else:
info = []
db.execute(
'SELECT targetID, name, description FROM sites WHERE display=1 ORDER BY name ASC')
siteRow = db.fetchall()
siteInfo = []
for site in siteRow:
db.execute('SELECT MAX(targetTimeUTC) as targetTimeUTC FROM selectedTargets WHERE selectDate IS NOT NULL AND targetID=%s', (site['targetID'],))
detailRow = db.fetchone()
lastTargetTime = detailRow['targetTimeUTC']
db.execute(
'SELECT COUNT(*) as numSelections FROM selectedTargets WHERE selectDate IS NOT NULL AND targetID=%s', (site['targetID'],))
countRow = db.fetchone()
numSelections = countRow['numSelections']
siteInfo.append({'name': site['name'],
'description': site['description'],
'lastTargetTime': lastTargetTime,
'numSelections': numSelections})
db.execute('SELECT g.gcDateTime, t.name, s.selectionID, s.targetTimeUTC, s.targetTimeLocal, s.selectDate, s.emailTime, s.selectedBy, s.carFile FROM gcs g, sites t, selectedTargets s WHERE g.gcID=s.gcID AND t.targetID=s.targetID AND s.selectDate IS NOT NULL AND s.selectedBy IS NOT NULL AND DATE(g.gcDateTime)=%s ', (searchDate,))
alreadySelected = db.fetchall()
db.execute(
'SELECT note FROM notes WHERE startDate <= %s AND endDate >= %s', (searchDate, searchDate,))
noteInfo = db.fetchall()
if len(noteInfo) == 0:
noteInfo = None
print(noteInfo)
return template('site/select-target.html', footerFile=footerFile, menuFile=menuFile, info=info, searchDate=searchDate, alreadySelected=alreadySelected, passGCID=passGCID, siteInfo=siteInfo, noteInfo=noteInfo)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
else:
message = 'Access denied. Please login.'
return template('site/login.html', footerFile=footerFile, menuFile=menuFile, message=message, catchURL=request.url)
@ app.route('/select-target/confirm', method='POST')
def select_targets_confirm(db):
menuFile = 'site/includes/menu.html'
footerFile = 'site/includes/footer.html'
if request.cookies.get('caruser'):
cookieInfo = request.cookies.get('caruser')
cookieHex = cookieInfo.split('.')[0]