-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
435 lines (328 loc) · 13.7 KB
/
main.py
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
# -*- coding: utf-8 -*-
import sys, os
from datetime import datetime
from flask import Flask, jsonify, request, render_template
from Announcements import Announcements
from Booklets import Booklets
from Brochures import Brochures
from Alacarte import Alacarte
from Alacarte.AlacarteExcelImport import AlacarteExcelImport
from Cafeteria import Cafeteria
from Cafeteria.ExcelImport import ExcelImport
from Cafeteria.Rating import CafeteriaRating
from Config import Config
from Events import Events
from Helpers.SiteMap import SiteMap
from Phonebook import Phonebook
from Shuttle.ShuttleLocation import ShuttleLocation
from Shuttle import Shuttle
from Admin import Admin
from ImageProcessor import ImageProcessor
import hashlib
from Weather import Weather
lastModificationTime = datetime.now()
sys.stdout.flush()
print ("Server is starting...")
app = Flask(__name__)
def generateServerSideEncryptionData():
#generate an encryption with date
encryptiondata = hashlib.md5(str(lastModificationTime.day) + str(lastModificationTime.isocalendar()[1]) + str(lastModificationTime.month))
return encryptiondata.hexdigest()
def encryption(clientSideEncryptionData):
#checks if the encryption values are same
serverSideEncryptionData = generateServerSideEncryptionData()
if clientSideEncryptionData == serverSideEncryptionData :
return True
else:
return False
def cacheVersion():
# return new cache every time clients ask.
# md5Hash = hashlib.md5(str(lastModificationTime)).hexdigest()
md5Hash = hashlib.md5(str(lastModificationTime)+str(datetime.now().date())).hexdigest()
return jsonify(cacheVersion=md5Hash)
def cacheVersionOf(data):
data = str(data) + "2"
md5Hash = hashlib.md5(data).hexdigest()
return jsonify(cacheVersion=md5Hash)
def readFromWeb(url):
import urllib
resource = urllib.urlopen(url)
return str(resource.read().decode('utf-8'))
# BEG MENU UPLOAD_______
APP_DIR = os.path.dirname(os.path.abspath(__file__))
@app.route("/services/cafeteria/excelupload")
def index():
return render_template("upload.html")
@app.route("/services/cafeteria/exceluploadrawpost", methods=['POST'])
def upload():
target = os.path.join(APP_DIR, "Cafeteria")
if not os.path.isdir(target):
os.mkdir(target)
selected_files = request.files.getlist("file")
time_stamp = datetime.now().isoformat()
for file in selected_files:
file_name = time_stamp+'_'+file.filename
destination = os.path.join(Config.dynamicFilesFolderPath, file_name)# "/".join([target, file_name])
file.save(destination)
ExcelImport(destination).updateCafeteriaMenu()
return render_template("complete.html")
# _______END MENU UPLOAD
# BEG MENU ALACARTE UPLOAD_______
@app.route("/services/alacarte/excelupload")
def index_alacarte():
return render_template("upload_alacarte.html")
@app.route("/services/alacarte/exceluploadrawpost", methods=['POST'])
def upload_alacarte():
target = os.path.join(APP_DIR, "Alacarte")
if not os.path.isdir(target):
os.mkdir(target)
selected_files = request.files.getlist("file")
time_stamp = datetime.now().isoformat()
for file in selected_files:
file_name = time_stamp+'_'+file.filename
destination = os.path.join(Config.dynamicFilesFolderPathAlacarte, file_name)# "/".join([target, file_name])
file.save(destination)
AlacarteExcelImport(destination).updateAlacarteMenu()
return render_template("complete_alacarte.html")
# _______END MENU UPLOAD
@app.route('/images/<fileName>')#
def getImageProcessorDynamicFile(fileName):
from flask import send_from_directory
resolution = str(request.values.get('resolution'))
fileName = str(fileName)
if resolution != "None":
thumbnailFileName = fileName + "." + resolution + ".jpeg"
response = send_from_directory(Config.dynamicFolderPath, thumbnailFileName)
else:
response = send_from_directory(Config.staticFolderPath, fileName)
return response
@app.route('/services/excelexport/<path:path>')
def excelImportService(path):
from flask import send_from_directory
from Admin.ExcelExport import ExcelExport
from Config import Config
from Helpers.JsonApi import JsonApi
export = ExcelExport(jsonUrl= "http://localhost:1072/" + path + "?expandforexcelexport=1", nameOfArrayVariableToListInExcelExportFile=JsonApi().findNameOfTheArrayAtTheTopLevel())
exportFileName = export.do()
response = send_from_directory(Config.dynamicFilesFolderPath, exportFileName,
as_attachment=True,
attachment_filename=exportFileName
)
return response
@app.route('/announcements/category', defaults={'categoryId': -1})
@app.route('/announcements/category/<categoryId>/')
def fetchAnnouncementCategory(categoryId):
result = Announcements().fetchCategory(int(categoryId))
return jsonify(result)
@app.route('/announcements/cacheversion/')
def announcementsCache():
data1 = readFromWeb(Config.announcementServiceUrl + "/0")
data2 = readFromWeb(Config.announcementServiceUrl + "/1")
return cacheVersionOf((data1)+(data2))
@app.route("/admincommands/updatecafeteriamenu")
def updateCafeteriaMenu():
Admin().checkSuperAdminAuth(request.values.get('pw'))
ExcelImport().updateCafeteriaMenu()
return "200"
@app.route("/admincommands/processimages")
def processImages():
Admin().checkSuperAdminAuth(request.values.get('pw'))
ImageProcessor().processAllStaticPhotos()
return "200"
@app.route('/cafeteria/rating/<mealId>', methods=['POST'])
def rateCafeteria(mealId):
return CafeteriaRating().rateMenu(mealId)
@app.route('/cafeteria/rating/<mealId>', methods=['GET'])
def showRating(mealId):
return jsonify(mealRating=CafeteriaRating().getMealRating(str(mealId)))
@app.route('/ip/')
def whatsTheServerIp():
return jsonify(serverIp=Config.serverIp)
@app.route('/ip/cacheversion/')
def whatsTheServerIpCache():
return cacheVersionOf(whatsTheServerIp())
@app.route('/shuttleschedule/')
def shuttleSchedule():
return jsonify(ShuttleSchedule=Shuttle.getWeeklySchedule())
@app.route('/shuttleschedule2/<clientSideEncryptionData>/', methods=['GET'])
def shuttleSchedule2(clientSideEncryptionData):
#if(encryption(clientSideEncryptionData)):
return jsonify(ShuttleSchedule2=Shuttle.getWeeklySchedule2())
@app.route('/shuttle/location/')
def shuttleLocation():
return jsonify(ShuttleLocation=ShuttleLocation().fetchAll())
@app.route('/shuttle/location/raw/')
def shuttleLocationRaw():
Admin().checkSuperAdminAuth(request.values.get('pw'))
return jsonify(ShuttleLocation=ShuttleLocation().raw())
@app.route('/shuttle/location/multipleshuttles/')
def multipleShuttleLocations():
return jsonify(MultipleShuttleLocation=ShuttleLocation().multipleshuttles())
@app.route('/shuttleschedule/cacheversion/')
def cacheShuttle():
shuttleOutput = readFromWeb(Config.shuttleScheduleServiceUrl)
return cacheVersionOf(shuttleOutput)
@app.route('/shuttleschedule2/111/cacheversion/')
def cacheShuttle2():
shuttleOutput = readFromWeb(Config.shuttleScheduleServiceUrl2)
return cacheVersionOf(shuttleOutput)
@app.route('/cafeteriamenu/')
def cafeteriaMenu():
version = request.values.get('version')
try:
version = float(version)
except:
version = 1.0
return jsonify(CafeteriaMenu=Cafeteria().getUpcomingSchedule(version=version))
@app.route('/services/cafeteria/upcomingmeals/')
def cafeteriaUpcomingMeals():
version = request.values.get('version')
try:
version = float(version)
except:
version = 1.0
return jsonify(CafeteriaMenu=Cafeteria().getUpcomingSchedule(version=version))
@app.route('/services/cafeteria/meals/')
@app.route('/services/cafeteria/allmeals/')
def cafeteriaAllMeals():
return jsonify(CafeteriaMenu=Cafeteria().getAllMeals())
@app.route('/services/cafeteria/meals/<mealId>')
def cafeteriaMeals(mealId):
from bson import ObjectId
return jsonify(Cafeteria().getMeal(mealId=ObjectId(mealId)))
@app.route('/cafeteriamenu/cacheversion/')
def cacheCafeteria():
cafeteriaMenuOutput = readFromWeb(Config.cafeteriaMenuServiceUrl)
return cacheVersionOf(cafeteriaMenuOutput)
@app.route('/services/cafeteriarate/meals/')
def cafeteriaRateMeals():
try:
expandforexcelexport = request.values.get('expandforexcelexport') in ['true', '1']
except:
expandforexcelexport = False
mealRatings = CafeteriaRating().getMealRating()
if expandforexcelexport:
mealRatings = Cafeteria().expandRatingsWithMeal(mealRatings)
for mealRating in mealRatings:
mealRating['numberOfRates'] = CafeteriaRating().getMealRateCount(mealId = mealRating['_id'])
result = jsonify(mealRatings = mealRatings)
return result
@app.route('/alacartemenu/')
def alacarteMenu():
version = request.values.get('version')
try:
version = float(version)
except:
version = 1.0
return jsonify(AlacarteMenu=Alacarte().getUpcomingAlacarte(version=version))
@app.route('/alacartemenu/cacheversion/')
def cacheAlacarte():
alacarteMenuOutput = readFromWeb(Config.alacarteMenuServiceUrl)
return cacheVersionOf(alacarteMenuOutput)
@app.route('/upcomingevents/')
def upcomingEvents():
return jsonify(UpcomingEvents=Events().getUpcomingEvents())
@app.route('/upcomingevents/raw/')
def upcomingEventsRaw():
return jsonify(UpcomingEvents=Events().getRawUpcomingEvents())
@app.route('/upcomingevents/cacheversion/')
def cacheEvents():
eventsOutput = readFromWeb(Config.eventsServiceUrl)
return cacheVersionOf(eventsOutput)
@app.route('/phonebook/')
def phonebook():
data = Phonebook().getPhonebookRecords()
return jsonify(Phonebook=data)
@app.route('/phonebook/raw/')
def phonebookRaw():
return jsonify(Phonebook=Phonebook().getRawPhonebookRecords())
@app.route('/phonebook/cacheversion/')
def cachePhonebook():
phoneBookOutput = readFromWeb(Config.phoneBookServiceUrl)
return cacheVersionOf(phoneBookOutput)
@app.route('/academiccalendar/')
def academicCalendar():
from Announcements.MetuAnnouncementsBridge import MetuAcademicAndDormCalendarBridge
result = MetuAcademicAndDormCalendarBridge().fetchAcademicAnnouncements()
return jsonify(AcademicCalendar=result)
@app.route('/academiccalendarnew/')
def academicCalendarNew():
from Announcements.MetuAnnouncementsBridge import MetuAcademicAndDormCalendarBridge
result = MetuAcademicAndDormCalendarBridge().fetchAcademicAnnouncementsNew()
return jsonify(AcademicCalendarNew=result)
@app.route('/academiccalendar/cacheversion/')
def cacheAcademicCalendar():
return cacheVersionOf(academicCalendar())
@app.route('/booklets/')
def booklets():
return jsonify(Booklets=Booklets().getBooklets())
@app.route('/booklets/cacheversion/')
def cacheBooklets():
bookletOutput = readFromWeb(Config.bookletServiceUrl)
return cacheVersionOf(bookletOutput)
@app.route('/brochures/')
def brochures():
return jsonify(Brochures=Brochures().getBrochures())
@app.route('/brochures/cacheversion/')
def cacheBrochures():
brochureOutput = readFromWeb(Config.brochureServiceUrl)
return cacheVersionOf(brochureOutput)
@app.route('/featuredApps/ios/')
def iosFeaturedApps():
links = [
{
"en_appName": "Radio ODTU Northern Cyprus Studios",
"tr_appName": "Radyo ODTU Kuzey Kıbrıs Stüdyoları",
"storeLink": "https://itunes.apple.com/tr/app/radyo-odtu-kks/id1126479317"
}
]
return jsonify(FeaturedApps=links)
@app.route('/featuredApps/android/')
def androidFeaturedApps():
links = [
{
"en_appName": "Radio ODTU Northern Cyprus Studios",
"tr_appName": "Radyo ODTU Kuzey Kıbrıs Stüdyoları",
"storeLink": "https://play.google.com/store/apps/details?id=com.tanss.radyoodtukks"
}
]
return jsonify(FeaturedApps=links)
@app.route('/featuredApps/windows/')
def windowsFeaturedApps():
links = [
{
"en_appName": "Radio ODTU Northern Cyprus Studios",
"tr_appName": "Radyo ODTU Kuzey Kıbrıs Stüdyoları",
"storeLink": "https://www.microsoft.com/en-us/store/p/radyo-odtu-k%C4%B1br%C4%B1s/9nblggh52pwh"
}
]
return jsonify(FeaturedApps=links)
@app.route('/services/weather/overall')
def getDailyWeather():
return jsonify(DailyForecast=Weather().getDaily())
@app.route("/")
def rootPage():
return SiteMap.siteMapString
@app.route("/services/cache/mastercache")
def mastercache():
return cacheVersionOf(
str(cacheBooklets()) +
str(cacheAcademicCalendar()) +
str(cachePhonebook()) +
str(cacheEvents()) +
str(cacheCafeteria()) +
str(cacheShuttle()) +
str(whatsTheServerIpCache()) +
str(announcementsCache())
)
@app.route('/metu/ncc/cng/')
def test():
return jsonify(MyTestValue=str(3.14))
if __name__ == "__main__":
import logging
handler = logging.FileHandler(Config.loggerPath) # errors logged to this file
handler.setLevel(logging.ERROR) # log errors and above
handler.setLevel(logging.WARNING) # log warnings
app.logger.addHandler(handler) # attach the handler to the app's logger
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
app.run(debug=Config.debug, host='0.0.0.0', port=1072, threaded=True)