-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver_api.py
867 lines (759 loc) · 32.2 KB
/
server_api.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
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
from mysql import mysql
from mysql import DB_Exception
from shutil import copyfile
from display_api import get_user_id
from display_api import display_data_type
from PIL import Image
import os
import os.path
import shutil
import bcrypt
import json
import tornado
import time
import random
from tornado.escape import xhtml_escape
from tornado.web import MissingArgumentError
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import httplib2
from apiclient import discovery
import datetime
from dataAccessObjects import *
from display_object import *
LEVEL_LOW_BOUND = 100
LEVEL_HIGH_BOUND = 10000
class ArgumentUtil():
"""Provide the interface to get argument from handler
This class is the base class defines the basic method for getting
the argument(s).
"""
def __init__(self,requestHandler):
"""
Store request handler as the class variable.
"""
self.handler = requestHandler
def getArgument(self,name):
"""
Get one argument from request handler and transform some
character for security reason.
"""
rawArg = self.handler.get_argument(name)
return xhtml_escape(rawArg)
def getArguments(self):
"""
This method should be implement in derived class.
"""
raise NotImplementedError("The getArgument() is not implemented.")
class UserArgumentsUtil(ArgumentUtil):
def __init__(self,requestHandler):
super().__init__(requestHandler)
def getArguments(self):
userInfo = {}
userInfo['user_name'] = self.getArgument('username')
userInfo['user_password'] = self.getArgument('password')
return userInfo
class UserEditArgumentsUtil(ArgumentUtil):
def getCurUser(self):
return self.handler.get_current_user()
def getArguments(self):
userInfo = {}
userInfo['user_name'] = self.getCurUser()
userInfo['old_password'] = self.getArgument('old_password')
userInfo['new_password'] = self.getArgument('password')
return userInfo
class UploadArgumentsUtil(ArgumentUtil):
def getArguments(self):
display_object = DisplayObject()
display_object.type_id = self.getArgument('data_type')
display_object.start_date = self.getArgument('start_date')
display_object.end_date = self.getArgument('end_date')
display_object.start_time = self.getArgument('start_time')
display_object.end_time = self.getArgument('end_time')
display_object.display_time = self.getArgument('display_time')
return display_object
#find the current displaying schedule
def find_now_schedule():
try:
with ScheduleDao() as scheduleDao:
next_schedule = scheduleDao.getNextSchedule()
# return sche_target_id
if next_schedule != None:
return str(next_schedule['sche_target_id'])
else:
return 0
except:
return -1
#
def random_constellation(user_id):
with UserDao() as userDao:
date = userDao.getUserBirthday(user_id)
if date == None:
constellation = ['摩羯座','水瓶座','雙鱼座','白羊座','金牛座','雙子座','巨蟹座','獅子座','處女座','天秤座','天蝎座','射手座']
constellation = random.choice(constellation)
else:
constellation = Zodiac(date.month,date.day)
return_msg = {}
try:
today=str(datetime.date.today())
with FortuneDao() as fortuneDao:
result = fortuneDao.getFortune(today=today,constellation=constellation)
if result != None:
overall_str="整體運勢" + result[0][0]
love_str="愛情運勢" + result[0][1]
career_str="事業運勢" + result[0][2]
wealth_str="財運運勢" + result[0][3]
return_msg["name"] = constellation
return_msg["value"] = [overall_str,love_str,career_str,wealth_str]
return return_msg
else:
return_msg["error"] = "Can't get fortune data."
except:
return_msg["error"] = "Can't get fortune data."
return return_msg
def check_user_existed_or_signup(user_info):
try:
return_msg = {}
with UserDao() as userDao:
is_existed = userDao.checkUserExisted(userName=user_info['user_name'])
if is_existed:
return_msg['flash'] = 'The name "{name}" has been used'.format(name=user_info['user_name'])
return return_msg
hashed_passwd = bcrypt.hashpw(user_info['user_password'].encode('utf-8'),bcrypt.gensalt())
with UserDao() as userdao:
userdao.createNewUser(userName=user_info['user_name'],userPassword=hashed_passwd)
return_msg['flash'] = 'User "{name}" create success!'.format(name=user_info['user_name'])
return return_msg
except:
return_msg["error"] = "Fail to check whether user is existed or create new user"
return return_msg
def check_user_password(user_info):
try:
return_msg = {}
if user_info['user_name'] == "":
return_msg['fail'] = 'Wrong user name'
return return_msg
with UserDao() as userDao:
password = userDao.getUserPassword(userName=user_info['user_name'])
if password == None:
return_msg['fail'] = 'No such user'
return return_msg
hashed_passwd = password.encode('utf-8')
if bcrypt.checkpw(user_info['user_password'].encode('utf-8'),hashed_passwd):
return_msg['success'] = 'Hello {user_name}'.format(user_name=user_info['user_name'])
else:
return_msg['fail'] = 'Wrong password'
return return_msg
except DB_Exception as e:
return_msg['fail'] = 'DB Exception'
return_msg["error"] = e.args[1]
return return_msg
except Exception as e:
return_msg['fail'] = str(e)
return return_msg
def get_upload_meta_data(handler):
uploadArgUtil = UploadArgumentsUtil(handler)
user_name = handler.get_current_user().decode('utf-8')
display_object = uploadArgUtil.getArguments()
display_object.server_dir = os.path.dirname(__file__)
display_object.user_id = get_user_id(user_name)
return display_object
#get the text data from the handler
def get_upload_text_data(handler):
try:
text_data = {}
text_data['result'] = 'fail'
text_data['con'] = tornado.escape.xhtml_escape(handler.get_argument('con')).replace('&nbsp',' ').replace('<br>','<br>')
text_data['title1'] = tornado.escape.xhtml_escape(handler.get_argument('title1')).replace('&nbsp',' ').replace('<br>','<br>')
text_data['title2'] = tornado.escape.xhtml_escape(handler.get_argument('title2')).replace('&nbsp',' ').replace('<br>','<br>')
text_data['description'] = tornado.escape.xhtml_escape(handler.get_argument('description')).replace('<br>','<br>').replace('&nbsp',' ')
text_data['year'] = tornado.escape.xhtml_escape(handler.get_argument('year'))
text_data['month'] = tornado.escape.xhtml_escape(handler.get_argument('month'))
text_data['background_color'] = tornado.escape.xhtml_escape(handler.get_argument('background_color'))
text_data['result'] = 'success'
return text_data
except Exception as e:
print(str(e))
return text_data
def store_image(filepath,file_content):
with open(filepath,'wb') as fp:
fp.write(file_content)
def store_thumbnail_image(file_path,thumbnail_path):
img = Image.open(file_path)
img.thumbnail((100,100))
img.save(thumbnail_path)
def get_img_meta(img_id):
try:
with ImageDao() as imageDao:
img_data = imageDao.getImgData(imgId=img_id)
#TODO Caller should check return value is not None
return img_data
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
def get_text_meta(text_id):
try:
with TextDao() as textDao:
ret = textDao.getTextMeta(textId=text_id)
return ret
except:
return_msg["error"] = "Can't get text meta."
return return_msg
def check_user_level(user_id):
try:
return_msg = {}
return_msg["result"] = "fail"
#check user level
with UserDao() as userDao:
user_level = userDao.getUserLevel(user_id)
if not user_level:
return_msg['error'] = 'No user_id "{user_id}"'.format(user_id=user_id)
return return_msg
if user_level < LEVEL_LOW_BOUND:
return_msg['error'] = 'User has permission to do this job'
return return_msg
return_msg["result"] = "success"
return return_msg
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
def get_abs_type_dir(type_id,server_dir):
with DataTypeDao() as dataTypeDao:
type_dir = dataTypeDao.getDataType(typeId=type_id).type_dir
return os.path.join(server_dir,"static",type_dir)
def upload_image_insert_db(display_image):
try:
return_msg = {}
return_msg["result"] = "fail"
img_file_name = os.path.split(display_image.filepath)[1]
if len(display_image.start_time)==0:
display_image.start_time = "00:00:00"
if len(display_image.end_time)==0:
display_image.end_time = "23:59:59"
receive_msg = check_user_level(str(display_image.user_id))
if 'fail' in receive_msg:
return_msg['error'] = receive_msg['error']
try:
img_type_dir = get_abs_type_dir(display_image.type_id,display_image.server_dir)
except:
return_msg["error"] = "no such type id : " + str(display_image.type_id)
return return_msg
with ImageDao() as imageDao:
img_id = imageDao.generateNewId()
img_system_name = img_id + os.path.splitext(img_file_name)[1]
img_thumbnail_name = "thumbnail_" + img_system_name
img_system_filepath = os.path.join(img_type_dir, img_system_name)
try:
copyfile(display_image.filepath, img_system_filepath)
if os.path.isfile(display_image.filepath) and os.path.isfile(img_system_filepath):
os.remove(display_image.filepath)
except:
try:
if os.path.isfile(display_image.filepath) and os.path.isfile(img_system_filepath):
os.remove(img_system_filepath)
except:
"DO NOTHING"
return_msg["error"] = "copy or remove file error"
return return_msg
display_image.id = img_id
display_image.system_name = img_system_name
display_image.file_name = img_file_name
display_image.thumbnail_name = img_thumbnail_name
try:
with ImageDao() as imageDao:
imageDao.insertData(display_object=display_image)
except DB_Exception as e:
return_msg["error"] = "insert mysql error ({filename}) {msg}".format(filename=display_image.filepath,msg=str(e))
try:
copyfile(img_system_filepath, display_image.filepath)
if os.path.isfile(display_image.filepath) and os.path.isfile(img_system_filepath):
os.remove(img_system_filepath)
return_msg["error"] = "insert mysql error ({filename}) {msg}".format(filename=display_image.filepath,msg=str(e))
except:
"DO NOTHING"
return return_msg
return_msg["img_id"] = img_id
return_msg["img_system_filepath"] = img_system_filepath
return_msg["img_thumbnail_name"] = img_thumbnail_name
return_msg["result"] = "success"
return return_msg
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
def edit_image_data(display_image):
return_msg = dict(result="fail")
try:
#check user level
with UserDao() as userDao:
user_level = userDao.getUserLevel(display_image.user_id)
if not user_level:
return_msg['error'] = 'No user_id "{user_id}"'.format(user_id=display_image.user_id)
return return_msg
else:
if user_level < LEVEL_LOW_BOUND:
return_msg["error"] = "user right is too low"
return return_msg
#check self image
with ImageDao() as imageDao:
imgInfo = imageDao.getIdSysName(Id=str(display_image.id))
try:
if imgInfo["userId"] != display_image.user_id and user_level < LEVEL_HIGH_BOUND:
return_msg["error"] = "can not modify other user image "
return return_msg
type_id = imgInfo["typeId"]
except:
return_msg["error"] = "no such image id : {id}".format(id=display_image.id)
return return_msg
if type_id == display_image.type_id:
"DO NOTHING"
else :
#get img_system_name
with ImageDao() as imageDao:
img_info = imageDao.getIdSysName(Id=str(display_image.id))
img_sys_name = img_info["systemName"]
if img_sys_name:
old_file_path = img_sys_name
new_file_path = img_sys_name
else:
return_msg["error"] = "no such image id : {id}".format(id=display_image.id)
return return_msg
#get old image type dir
with DataTypeDao() as dataTypeDao:
type_dir = dataTypeDao.getDataType(typeId=str(type_id)).type_dir
if type_dir:
old_file_path = type_dir + old_file_path
else:
return_msg["error"] = "no such image type : {type_id}".format(type_id=type_id)
return return_msg
#get new image type dir
with DataTypeDao() as dataTypeDao:
type_dir = dataTypeDao.getDataType(typeId=str(display_image.type_id)).type_dir
if type_dir:
new_file_path = type_dir + new_file_path
else:
return_msg["error"] = "no such image type : {type_id}".format(type_id=display_image.type_id)
return return_msg
#check if we need to move the file
if old_file_path == new_file_path:
"DO NOTHING"
else :
try:
old_file_path = os.path.join(display_image.server_dir,"static",old_file_path)
new_file_path = os.path.join(display_image.server_dir,"static",new_file_path)
copyfile(old_file_path, new_file_path)
if os.path.isfile(old_file_path) and os.path.isfile(new_file_path):
os.remove(old_file_path)
except:
try:
if os.path.isfile(old_file_path) and os.path.isfile(new_file_path):
os.remove(new_file_path)
except:
"DO NOTHING"
return_msg["error"] = "move file error : " + old_file_path
return return_msg
try:
with ImageDao() as imageDao:
imageDao.updateEditedData(display_object=display_image)
except DB_Exception as e:
try:
copyfile(new_file_path, old_file_path)
if os.path.isfile(old_file_path) and os.path.isfile(new_file_path):
os.remove(new_file_path)
except:
try:
if os.path.isfile(old_file_path) and os.path.isfile(new_file_path):
os.remove(old_file_path)
except:
return_msg["error"] = "move file error : duplicate files : " + old_file_path
return return_msg
return_msg["error"] = "move file error : " + new_file_path
return return_msg
return_msg["error"] = "update mysql error"
return return_msg
return_msg["result"] = "success"
return return_msg
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
def upload_text_insert_db(display_text):
try:
return_msg = {}
return_msg["result"] = "fail"
if len(display_text.start_time)==0:
display_text.start_time = "00:00:00"
if len(display_text.end_time)==0:
display_text.end_time = "23:59:59"
receive_msg = check_user_level(display_text.user_id)
if 'fail' in receive_msg:
return_msg['result'] = receive_msg['error']
with TextDao() as textDao:
text_id = textDao.generateNewId()
#get file place
with DataTypeDao() as dataTypeDao:
type_dir = dataTypeDao.getDataType(typeId=str(display_text.type_id)).type_dir
try:
text_system_name = text_id + ".txt"
system_file_dir = os.path.join(display_text.server_dir, "static", type_dir)
system_file_dir = os.path.join(system_file_dir, text_system_name)
except:
return_msg["error"] = "no such type id : " + str(display_text.type_id)
return return_msg
display_text.id = text_id
display_text.system_name = text_system_name
if display_text.invisible_title == None:
display_text.invisible_title = text_id
with TextDao() as textDao:
textDao.insertData(display_object=display_text)
return_msg["text_id"] = text_id
return_msg["text_system_dir"] = system_file_dir
return_msg["result"] = "success"
return return_msg
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
#
def edit_text_data(display_text):
return_msg = dict(result="fail")
try:
#check user level
with UserDao() as userDao:
user_level = userDao.getUserLevel(display_text.user_id)
if not user_level:
return_msg['error'] = 'No user_id "{user_id}"'.format(user_id=display_text.user_id)
return return_msg
else:
if user_level < LEVEL_LOW_BOUND:
return_msg["error"] = "user right is too low"
return return_msg
#check self text
with TextDao() as textDao:
textInfo = textDao.getIdSysName(Id=str(display_text.id))
try:
if textInfo["userId"] != display_text.user_id and user_level < LEVEL_HIGH_BOUND:
return_msg["error"] = "can not modify other user text"
return return_msg
type_id = int(textInfo["typeId"])
except:
return_msg["error"] = "no such text id : {text_id}".format(text_id=display_text.id)
return return_msg
#get text_system_name
with TextDao() as textDao:
text_info = textDao.getIdSysName(Id=str(display_text.id))
text_sys_name = text_info["systemName"]
try:
old_file_path = text_sys_name
new_file_path = text_sys_name
except:
return_msg["error"] = "no such text id : {text_id}".format(text_id=display_text.id)
return return_msg
#get old text type dir
with DataTypeDao() as dataTypeDao:
type_dir = dataTypeDao.getDataType(typeId=str(type_id)).type_dir
try:
old_file_path = type_dir + old_file_path
except:
return_msg["error"] = "no such text type : " + str(type_id)
return return_msg
#check if we need to move the file
if type_id == display_text.type_id:
old_file_path = os.path.join(display_text.server_dir,"static",old_file_path)
new_file_path = old_file_path
else :
#get new text type dir
with DataTypeDao() as dataTypeDao:
type_dir = dataTypeDao.getDataType(typeId=str(display_text.type_id)).type_dir
try:
new_file_path = type_dir + new_file_path
except:
return_msg["error"] = "no such text type : " + str(display_text.type_id)
return return_msg
#check if we need to move the file
if old_file_path == new_file_path:
new_file_path = 'static/'+new_file_path
else :
try:
old_file_path = os.path.join(display_text.server_dir,"static",old_file_path)
new_file_path = os.path.join(display_text.server_dir,"static",new_file_path)
copyfile(old_file_path, new_file_path)
if os.path.isfile(old_file_path) and os.path.isfile(new_file_path):
os.remove(old_file_path)
except:
try:
if os.path.isfile(old_file_path) and os.path.isfile(new_file_path):
os.remove(new_file_path)
except:
"DO NOTHING"
return_msg["error"] = "move file error : " + old_file_path
return return_msg
with open(new_file_path,'w') as fp:
print(json.dumps(display_text.text_file),file=fp)
try:
with TextDao() as textDao:
textDao.updateEditedData(display_object=display_text)
except DB_Exception as e:
try:
copyfile(new_file_path, old_file_path)
if os.path.isfile(old_file_path) and os.path.isfile(new_file_path):
os.remove(new_file_path)
except:
try:
if os.path.isfile(old_file_path) and os.path.isfile(new_file_path):
os.remove(old_file_path)
except:
return_msg["error"] = "move file error : duplicate files : " + old_file_path
return return_msg
return_msg["error"] = "move file error : " + new_file_path
return return_msg
return_msg["error"] = "update mysql error"
return return_msg
return_msg["result"] = "success"
return_msg["text_system_dir"] = new_file_path
return return_msg
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
#
def delete_image_or_text_data(json_obj):
return_msg = dict(result="fail")
try:
try:
server_dir = json_obj["server_dir"]
target_id = json_obj["target_id"]
user_id = json_obj["user_id"]
except:
return_msg["error"] = "input parameter missing"
return return_msg
#check user level
with UserDao() as userDao:
user_level = userDao.getUserLevel(user_id)
if not user_level:
return_msg['error'] = 'No user_id "{user_id}"'.format(user_id=user_id)
return return_msg
elif user_level < LEVEL_LOW_BOUND:
return_msg["error"] = "user right is too low"
return return_msg
#check self data and get type_id
if target_id[0:4] == "imge":
with ImageDao() as imageDao:
info = imageDao.getIdSysName(Id=target_id)
elif target_id[0:4] == "text":
with TextDao() as textDao:
info = textDao.getIdSysName(Id=target_id)
else :
return_msg["error"] = "target id type error"
return return_msg
try:
if info["userId"] != user_id and user_level < LEVEL_HIGH_BOUND:
return_msg["error"] = "can not modify other user image or text"
return return_msg
target_type_id = int(info["typeId"])
target_file = info["systemName"]
except:
return_msg["error"] = "no such target id : " + str(target_id)
return return_msg
#get file place
with DataTypeDao() as dataTypeDao:
type_dir = dataTypeDao.getDataType(typeId=str(target_type_id)).type_dir
try:
system_file_dir = os.path.join(server_dir, "static", type_dir)
target_file = os.path.join(system_file_dir, target_file)
except:
return_msg["error"] = "no such type id : " + str(type_id)
return return_msg
if os.path.isfile(target_file):
try:
os.remove(target_file)
except:
return_msg["error"] = "Delete file fail"
return return_msg
if target_id[0:4] == "imge":
with ImageDao() as imageDao:
imageDao.markDeleted(target_id,user_id)
elif target_id[0:4] == "text":
with TextDao() as textDao:
textDao.markDeleted(target_id,user_id)
return_msg["result"] = "success"
return return_msg
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
def add_new_data_type(json_obj):
try:
return_msg = {}
return_msg["result"] = "fail"
type_name = json_obj['type_name']
with DataTypeDao() as dataTypeDao:
existed = dataTypeDao.checkTypeExisted(typeName=type_name)
if existed:
return_msg["error"] = "Type name has existed"
return return_msg
with DataTypeDao() as dataTypeDao:
dataTypeDao.insertType(typeName=type_name)
if not os.path.exists("static/"+type_name):
os.makedirs("static/"+type_name)
return_msg["result"] = "success"
return return_msg
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
#
def change_password(json_obj):
try:
return_msg = {}
return_msg["result"] = "fail"
try:
user_name = json_obj["user_name"].decode('utf-8')
old_password = json_obj["old_password"]
new_password = json_obj["new_password"]
except:
return_msg["error"] = "input parameter missing"
return return_msg
user_id = get_user_id(user_name)
if isinstance(user_id,dict):
return_msg["error"] = "no such user name"
return return_msg
with UserDao() as userDao:
password = userDao.getUserPassword(userId=user_id)
try:
hashed_key = password.encode('utf-8')
if bcrypt.checkpw(old_password.encode('utf-8'),hashed_key):
hashed_key = bcrypt.hashpw(new_password.encode('utf-8'),bcrypt.gensalt())
with UserDao() as userDao:
userDao.updatePassword(hashed_key.decode('utf-8'),userId=user_id)
else:
return_msg["error"] = "old password incorrect"
return return_msg
except Exception as e:
return_msg["error"] = str(e)
return return_msg
return_msg["result"] = "success"
return return_msg
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
def read_text_data(text_id):
try:
return_msg = {}
with TextDao() as textDao:
textInfo = textDao.getIdSysName(Id=text_id)
with DataTypeDao() as dataTypeDao:
type_dir = dataTypeDao.getDataType(typeId=textInfo['typeId']).type_dir
filename = os.path.join('static',type_dir,textInfo['systemName'])
with open(filename,'r') as fp:
text_content = json.load(fp)
for key in text_content:
text_content[key] = text_content[key].replace('<br/>','\n').replace(' ',' ').replace('<br>','\n')
return text_content
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
# for google api
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly','https://www.googleapis.com/auth/drive']
CLIENT_SECRET_FILE = 'client_secret.json'
redirect_url = 'http://localhost:3000/googleapi'
def get_credentials(handler=None):
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'google-api-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(filename=CLIENT_SECRET_FILE,scope=SCOPES,redirect_uri=redirect_url)
url = flow.step1_get_authorize_url()
if handler:
handler.redirect(url)
else:
return None
return credentials
def exchange_code_and_store_credentials(code):
flow = client.flow_from_clientsecrets(filename=CLIENT_SECRET_FILE,scope=SCOPES,redirect_uri=redirect_url)
credentials = flow.step2_exchange(code)
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'google-api-quickstart.json')
store = Storage(credential_path)
store.put(credentials)
credentials.set_store(store)
return credentials
def get_upcoming_events(credentials):
target_calendars = ['[email protected]']
events = {}
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
#calendars' ID and name dict
calendars_dict = {}
calendars_dict["[email protected]"] = "Speechs"
calendars_dict["[email protected]"] = "Activities"
calendars_dict["[email protected]"] = "Department"
calendars_dict["zh.taiwan#[email protected]"] = "Holidays"
calendars_dict["[email protected]"] = "School"
try:
calendars = service.calendarList().list().execute()['items']
for calendar in calendars:
target_calendars.append(calendar['id'])
except Exception as e:
print(str(e))
else_events = []
for calendarId in target_calendars:
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
eventsResult = service.events().list(calendarId=calendarId,maxResults=10,timeMin=now).execute()
if calendarId in calendars_dict.keys():
calendar_name = calendars_dict[calendarId]
events[calendar_name] = eventsResult['items']
else:
else_events.extend(eventsResult['items'])
events["Else"] = else_events
return events
#crawler handle
def news_insert_db(json_obj):
try:
return_msg = {}
return_msg["result"] = "fail"
try:
news_data_type = json_obj["data_type"]
news_title = json_obj["title"]
news_serial_number = json_obj["serial_number"]
except:
return_msg["error"] = "input parameter missing"
return return_msg
with NewsQRCodeDao() as newsQRCodeDao:
exist = newsQRCodeDao.checkNewsExisted(news_serial_number)
if not exist:
with NewsQRCodeDao() as newsQRCodeDao:
newsQRCodeDao.insertNews(news_data_type,news_serial_number,news_title)
return_msg["result"] = "success"
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg
def fortune_insert_db(json_obj):
try:
return_msg = {}
return_msg["result"] = "fail"
date = str(datetime.date.today())
try:
constellation = json_obj["constellation"]
overall = json_obj["overall"]
love = json_obj["love"]
career = json_obj["career"]
wealth = json_obj["wealth"]
except:
return_msg["error"] = "input parameter missing"
return return_msg
#check
with FortuneDao() as fortuneDao:
existed = fortuneDao.checkFortuneExisted(date=date,constellation=constellation)
if not existed:
with FortuneDao() as fortuneDao:
fortuneDao.insertFortune(date,constellation,overall,love,career,wealth)
return_msg["result"] = "success"
return return_msg
except DB_Exception as e:
return_msg["error"] = e.args[1]
return return_msg