diff --git a/arrange_schedule.py b/arrange_schedule.py index dd29a9f..0c86a24 100644 --- a/arrange_schedule.py +++ b/arrange_schedule.py @@ -23,6 +23,7 @@ import json import sys import config.settings as setting +from display_object import * class loadScheduleError(Exception): def __init__(self,value): @@ -83,12 +84,12 @@ def find_next_schedule(): return_msg["error"] = gen_error_msg(e.args[1]) return return_msg -def find_text_acticity(json_obj): +def get_candidates(arrange_mode_attr): """ According current `arrange_mode` and `condition`, to find out - candidates text data returns to caller + candidates data returns to caller - return text candidates for displaying + return candidates for displaying Variables: arrange_mode: Different mode has different method to select candidates @@ -103,86 +104,33 @@ def find_text_acticity(json_obj): return_msg = {} return_msg["result"] = "fail" deal_result = [] - arrange_condition = [] try: - arrange_mode = json_obj["arrange_mode"] - if "condition" in json_obj: - arrange_condition = json_obj["condition"] + arrange_mode = arrange_mode_attr["arrange_mode"] + arrange_condition = arrange_mode_attr.get('condition',[]) except: return_msg["error"] = "input parameter missing" return return_msg - #find texts that may be schedule orderById = ModeUtil.checkOrderById(arrange_mode) conditionAssigned = ModeUtil.checkConditionAssigned(arrange_mode) with TextDao() as textDao: - pure_result= textDao.findActivities(conditionAssigned,orderById,arrange_mode,arrangeCondition=arrange_condition) - #restruct results of query - for result_row in pure_result: - if len(result_row)==2: - deal_result.append([result_row[0], int(result_row[1])]) - elif len(result_row)==3: - deal_result.append([result_row[0], int(result_row[1]), float(result_row[2])]) - else: - "DO NOTHING" + test_candidates= textDao.findActivities(conditionAssigned,orderById,arrange_mode,arrangeCondition=arrange_condition) - candidates = ModeUtil.selectDisplayCandidates(arrange_mode,deal_result) - - return_msg["ans_list"] = candidates - return_msg["result"] = "success" - return return_msg - except DB_Exception as e: - return_msg["error"] = gen_error_msg(e.args[1]) - return return_msg - -def find_image_acticity(json_obj): - """ - According current `arrange_mode` and `condition`, to find out - candidates image data returns to caller - - return image candidates for displaying - - Variables: - arrange_mode: Different mode has different method to select candidates - arrange_condition: The type_id list of data_type will be used by some - arrange_mode - orderById: According to arrange_mode, the candidates should sort by id - or not - conditionAssigned: According to arrange_mode, the candidates should in - arrange_condition or not. - """ - try: - return_msg = {} - return_msg["result"] = "fail" - deal_result = [] - arrange_mode = 1 - arrange_condition = [] - try: - arrange_mode = json_obj["arrange_mode"] - if "condition" in json_obj: - arrange_condition = json_obj["condition"] - except: - return_msg["error"] = "input parameter missing" - return return_msg - - #find images that may be schedule - orderById = ModeUtil.checkOrderById(arrange_mode) + with ImageDao() as imageDao: + image_candidates= imageDao.findActivities(conditionAssigned,orderById,arrange_mode,arrangeCondition=arrange_condition) - conditionAssigned = ModeUtil.checkConditionAssigned(arrange_mode) + candidates = list(test_candidates) + list(image_candidates) - with ImageDao() as imageDao: - pure_result= imageDao.findActivities(conditionAssigned,orderById,arrange_mode,arrangeCondition=arrange_condition) - #restruct results of query - for result_row in pure_result: + for result_row in candidates: if len(result_row)==2: deal_result.append([result_row[0], int(result_row[1])]) elif len(result_row)==3: deal_result.append([result_row[0], int(result_row[1]), float(result_row[2])]) else: "DO NOTHING" - + candidates = ModeUtil.selectDisplayCandidates(arrange_mode,deal_result) return_msg["ans_list"] = candidates @@ -225,18 +173,9 @@ def find_activity(json_obj): if arrange_mode in [3,4,5] and len(arrange_condition) == 0: return_msg["error"] = 'Then arrange mode {mode} need to assgin condition'.format(mode=arrange_mode) return return_msg - - #get text activity - receive_obj = find_text_acticity(json_obj) - if receive_obj["result"] == "success": - for text_data in receive_obj['ans_list']: - deal_obj.append(text_data) - - #get image activity - receive_obj = find_image_acticity(json_obj) - if receive_obj["result"] == "success": - for image_data in receive_obj['ans_list']: - deal_obj.append(image_data) + + receive_obj = get_candidates(json_obj) + deal_obj = receive_obj['ans_list'] deal_obj = mix_image_and_text(arrange_mode,deal_obj) @@ -265,28 +204,14 @@ def expire_data_check(): try: return_msg = {} return_msg["result"] = "fail" - deal_result = [] with ImageDao() as imageDao: - pure_result = imageDao.getExpiredIds() + expired_images = imageDao.markExpired() - #update expire data - for expired_image_id in pure_result: - deal_result.append(expired_image_id[0]) - with ImageDao() as imageDao: - imageDao.markExpired(expired_image_id[0]) - - #find expire text data with TextDao() as textDao: - pure_result = textDao.getExpiredIds() - - #update expire data - for expired_text_id in pure_result: - deal_result.append(expired_text_id[0]) - with TextDao() as textDao: - textDao.markExpired(expired_text_id[0]) + expired_texts = textDao.markExpired() - for target_id in deal_result: + for target_id in expired_images+expired_texts: with ScheduleDao() as scheduleDao: scheduleDao.markExpiredSchedule(targetId=target_id) @@ -471,7 +396,6 @@ def set_schedule_log(json_obj): return_msg["error"] = gen_error_msg(e.args[1]) return return_msg -#future can write to log.txt. now just print it def read_system_setting(): return_msg = {} return_msg["result"] = "fail" @@ -488,7 +412,6 @@ def read_system_setting(): return_msg["result"] = "success" return return_msg -#future can write to log.txt. now just print it def read_arrange_mode(): try: return_msg = {} @@ -514,10 +437,10 @@ def delete_old_cwb_img(server_dir,user_id): error_list_id = [] with ImageDao() as imageDao: Ids=imageDao.getCwbImgIds() - for num2 in range(len(Ids)): + for id in Ids: try: send_obj["server_dir"] = server_dir - send_obj["target_id"] = str(Ids[num2][0]) + send_obj["target_id"] = str(id) send_obj["user_id"] = user_id receive_obj = delete_image_or_text_data(send_obj) if receive_obj["result"] == "fail": @@ -527,12 +450,6 @@ def delete_old_cwb_img(server_dir,user_id): continue return error_list_id -def mark_old_cwb_img(error_list_id): - for error_id in error_list_id: - with ImageDao() as imageDao: - imageDao.markExpired(targetId=error_id,markOldData=True) - -# def crawler_cwb_img(json_obj): try: return_msg = {} @@ -544,7 +461,6 @@ def crawler_cwb_img(json_obj): return_msg["error"] = "input parameter missing" return return_msg now_time = time.time() - send_obj = {} receive_obj = {} with DataTypeDao() as dataTypeDao: @@ -565,21 +481,22 @@ def crawler_cwb_img(json_obj): now_time -= 60 continue - error_list_id = delete_old_cwb_img(server_dir,user_id) + error_id_list = delete_old_cwb_img(server_dir,user_id) - mark_old_cwb_img(error_list_id) - - #upload new file - send_obj["server_dir"] = server_dir - send_obj["file_type"] = weather_data_type["typeId"] - send_obj["filepath"] = target_img - send_obj["start_date"] = time.strftime("%Y-%m-%d", time.localtime(time.time())) - send_obj["end_date"] = time.strftime("%Y-%m-%d", time.localtime(time.time()+86400)) - send_obj["start_time"] = "00:00:00" - send_obj["end_time"] = "23:59:59" - send_obj["display_time"] = 5 - send_obj["user_id"] = user_id - receive_obj = upload_image_insert_db(send_obj) + with ImageDao() as imageDao: + imageDao.markExpired(target=error_id_list) + + display_image = DisplayImage() + display_image.server_dir = server_dir + display_image.type_id = weather_data_type["typeId"] + display_image.filepath = target_img + display_image.start_date = time.strftime("%Y-%m-%d", time.localtime(time.time())) + display_image.end_date = time.strftime("%Y-%m-%d", time.localtime(time.time()+86400)) + display_image.start_time = "00:00:00" + display_image.end_time = "23:59:59" + display_image.display_time = 5 + display_image.user_id = user_id + receive_obj = upload_image_insert_db(display_image) try: if receive_obj["result"] == "success": filepath = receive_obj["img_system_filepath"] @@ -672,28 +589,28 @@ def check_event_exist_or_insert(event, calendar_name=None): # do nothing return else: - send_msg = {} - send_msg["server_dir"] = os.path.dirname(__file__) - send_msg["file_type"] = 6 + display_text = DisplayText() + display_text.server_dir = os.path.dirname(__file__) + display_text.type_id = 6 if 'date' in event['start'].keys(): - send_msg["start_date"] = datetime.datetime.strftime(datetime.datetime.strptime(event['start']['date'],'%Y-%m-%d') - datetime.timedelta(display_days),'%Y-%m-%d') - send_msg["end_date"] = event['start']['date'] + display_text.start_date = datetime.datetime.strftime(datetime.datetime.strptime(event['start']['date'],'%Y-%m-%d') - datetime.timedelta(display_days),'%Y-%m-%d') + display_text.end_date = event['start']['date'] elif 'dateTime' in event['start'].keys(): event_start_date = event['start']['dateTime'].split('T')[0] event_start_time = event['start']['dateTime'].split('T')[1][:5] event_end_date = event['end']['dateTime'].split('T')[0] event_end_time = event['end']['dateTime'].split('T')[1][:5] - send_msg["start_date"] = datetime.datetime.strftime(datetime.datetime.strptime(event['start']['dateTime'].split('T')[0],'%Y-%m-%d') - datetime.timedelta(display_days),'%Y-%m-%d') - send_msg["end_date"] = event_start_date + display_text.start_date = datetime.datetime.strftime(datetime.datetime.strptime(event['start']['dateTime'].split('T')[0],'%Y-%m-%d') - datetime.timedelta(display_days),'%Y-%m-%d') + display_text.end_date = event_start_date else: print("no date and dateTime") return - send_msg["start_time"] = "" - send_msg["end_time"] = "" - send_msg["display_time"] = 10 - send_msg["user_id"] = 1 - send_msg["invisible_title"] = event_id - receive_msg = upload_text_insert_db(send_msg) + display_text.start_time = "" + display_text.end_time = "" + display_text.display_time = 10 + display_text.user_id = 1 + display_text.invisible_title = event_id + receive_msg = upload_text_insert_db(display_text=display_text) addition_msg = rule_base_agent(event) event_file_path = os.path.join('static','calendar_event','{name}.png'.format(name=event_id)) description = event.get('description',addition_msg['description']) @@ -704,7 +621,7 @@ def check_event_exist_or_insert(event, calendar_name=None): else: detailtime = "" - text_file = { "con" : send_msg["end_date"], + text_file = { "con" : display_text.end_date, "title1" : addition_msg['title1'], "title2" : addition_msg['title2'], "description": description, @@ -799,18 +716,17 @@ def save_google_drive_file(service, json_obj): while done is False: status, done = downloader.next_chunk() - #upload new file - send_obj = {} - send_obj["server_dir"] = json_obj['server_dir'] - send_obj["file_type"] = json_obj['data_type'] - send_obj["filepath"] = 'static/img/' + file_name - send_obj["start_date"] = time.strftime("%Y-%m-%d", time.localtime(time.time())) - send_obj["end_date"] = time.strftime("%Y-%m-%d", time.localtime(time.time()+item['time'])) - send_obj["start_time"] = "00:00:00" - send_obj["end_time"] = "23:59:59" - send_obj["display_time"] = 3 - send_obj["user_id"] = json_obj['user_id'] - receive_obj = upload_image_insert_db(send_obj) + display_image = DisplayImage() + display_image.server_dir = json_obj['server_dir'] + display_image.type_id = json_obj['data_type'] + display_image.filepath = os.path.join("static","img",file_name) + display_image.start_date = time.strftime("%Y-%m-%d", time.localtime(time.time())) + display_image.end_date = time.strftime("%Y-%m-%d", time.localtime(time.time()+item['time'])) + display_image.start_time = "00:00:00" + display_image.end_time = "23:59:59" + display_image.display_time = 5 + display_image.user_id = json_obj['user_id'] + receive_obj = upload_image_insert_db(display_image) #save thumbnail image try: @@ -1015,17 +931,17 @@ def crawler_schedule(): def add_news_text(typeId, textFile): now_time = time.time() - send_msg = {} - send_msg["server_dir"] = os.path.dirname(__file__) - send_msg["file_type"] = typeId - send_msg["start_date"] = time.strftime("%Y-%m-%d", time.localtime(now_time)) - send_msg["end_date"] = time.strftime("%Y-%m-%d", time.localtime(now_time)) - send_msg["start_time"] = "" - send_msg["end_time"] = "" - send_msg["display_time"] = 5 - send_msg["user_id"] = 1 - send_msg["invisible_title"] = "news" - receive_msg = upload_text_insert_db(send_msg) + display_text = DisplayText() + display_text.server_dir = os.path.dirname(__file__) + display_text.type_id = typeId + display_text.start_date = time.strftime("%Y-%m-%d", time.localtime(now_time)) + display_text.end_date = time.strftime("%Y-%m-%d", time.localtime(now_time)) + display_text.start_time = "" + display_text.end_time = "" + display_text.display_time = 5 + display_text.user_id = 1 + display_text.invisible_title = "news" + receive_msg = upload_text_insert_db(display_text=display_text) with open(receive_msg["text_system_dir"],"w") as fp: print(json.dumps(textFile),file=fp) @@ -1351,7 +1267,7 @@ def main(): else: #Parent alarm_add_schedule = 1960380833.0 arrange_mode_change = 0 - except: + except Exception as e: receive_obj["result"] = "fail" receive_obj["error"] = "fork3 error" set_system_log(receive_obj) diff --git a/board.py b/board.py index 8e0fb47..c84a089 100644 --- a/board.py +++ b/board.py @@ -22,7 +22,18 @@ def get(self): class Get_DB_Data(BaseHandler): def get(self): - self.write(load_schedule()) + display_content = load_schedule() + if display_content['result'] == 'fail': + pass + elif display_content['display_type'] == 'image': + self.render('show-image.html',img_info=display_content) + elif display_content['display_type'] == 'text': + from tornado.template import Loader + loader = Loader('template') + print(loader.load('show-text.html').generate(text_info=display_content)) + self.render('show-text.html', text_info=display_content) + elif display_content['display_type'] == 'news': + self.render('show-news.html', news_info=display_content) def main(): @@ -33,7 +44,6 @@ def main(): "static_path":os.path.join(base_dir,"static"), "thumbnail_path":os.path.join(base_dir,"thumbnail"), "debug":True, - "xsrf_cookies":True, } application = tornado.web.Application([ tornado.web.url(r"/",MainHandler,name="main"), diff --git a/broadcast_api.py b/broadcast_api.py index 6b98696..c88e16a 100644 --- a/broadcast_api.py +++ b/broadcast_api.py @@ -19,11 +19,11 @@ def getDisplayContent(sche_target_id,return_msg): if targetIdPrefix == "imge": with ImageDao() as imageDao: file_info = imageDao.getIdSysName(Id=sche_target_id) - return_msg["file_type"] = "image" + return_msg["display_type"] = "image" elif targetIdPrefix == "text": with TextDao() as textDao: file_info = textDao.getIdSysName(Id=sche_target_id) - return_msg["file_type"] = "text" + return_msg["display_type"] = "text" else : raise Exception("target id type error {}".format(targetIdPrefix)) @@ -41,16 +41,18 @@ def getDisplayContent(sche_target_id,return_msg): raise Exception("No such type id {}".format(type_id)) targetFile = os.path.join("static", type_dir, system_file_name) - return_msg["file"] = os.path.join(type_dir, system_file_name) return_msg["type_name"] = type_name - - if return_msg["file_type"] == "text": + if return_msg["display_type"] == "image": + return_msg["img"] = targetFile + elif return_msg["display_type"] == "text": if not os.path.isfile(targetFile) : raise Exception("Text file doesn't exists") else : with open(targetFile,"r") as fp: file_content = json.load(fp) - return_msg["file_text"] = file_content + if file_content.get('text_type','') == 'news': + return_msg['display_type'] = 'news' + return_msg.update(file_content) def load_schedule(): """ @@ -69,21 +71,18 @@ def load_schedule(): if next_schedule is None: return_msg["error"] = "no schedule" return return_msg - return_msg["schedule_id"] = next_schedule['schedule_id'] return_msg["display_time"] = int(next_schedule['display_time']) sche_target_id = next_schedule['sche_target_id'] getDisplayContent(sche_target_id,return_msg) - #update display count - if return_msg["file_type"] == "image": + if return_msg["display_type"] == "image": with ImageDao() as imageDao: imageDao.addDisplayCount(sche_target_id) - elif return_msg["file_type"] == "text": + elif return_msg["display_type"] in ["text","news"]: with TextDao() as textDao: textDao.addDisplayCount(sche_target_id) - return_msg["result"] = "success" return return_msg except DB_Exception as e: diff --git a/config/settings.py b/config/settings.py index 4a72202..cfe9449 100644 --- a/config/settings.py +++ b/config/settings.py @@ -11,3 +11,5 @@ shutdown = 0, max_db_log = 100, min_db_activity = 10) + +bluetooth_enable = True \ No newline at end of file diff --git a/dataAccessObjects.py b/dataAccessObjects.py index 03fd174..53ba957 100644 --- a/dataAccessObjects.py +++ b/dataAccessObjects.py @@ -1,4 +1,5 @@ from mysql import * +from display_object import * class DefaultDao(): def __init__(self): @@ -29,14 +30,26 @@ def addDisplayCount(self,targetId): dataName=self.dataName,targetId=targetId,tableName=self.tableName) self.db.cmd(sql) - def markExpired(self,targetId,markOldData=None): - sql = 'UPDATE {tableName} SET {dataName}_is_expire=1 WHERE {dataName}_id="{targetId}"'.format( - dataName=self.dataName,targetId=targetId,tableName=self.tableName) - if markOldData: - sql += ' and {dataName}_is_expire=0 and {dataName}_is_delete=0'.format( - dataName=self.dataName) - self.db.cmd(sql) - + def markExpired(self,target=None): + target_list = None + if not target: + sql = 'SELECT {dataName}_id FROM {tableName} '\ + +'WHERE {dataName}_is_delete=0 and {dataName}_is_expire=0 and (TO_DAYS(NOW())>TO_DAYS({dataName}_end_date) '\ + +'or (TO_DAYS(NOW())=TO_DAYS({dataName}_end_date) and TIME_TO_SEC(DATE_FORMAT(NOW(), "%H:%i:%s"))>TIME_TO_SEC({dataName}_end_time)))' + sql = sql.format(dataName=self.dataName,tableName=self.tableName) + target_list = to_list(self.db.query(sql)) + elif not isinstance(target,list): + target_list = [target] + else: + target_list = target + + sql_template = 'UPDATE {tableName} SET {dataName}_is_expire=1 WHERE {dataName}_id="{targetId}"' + for targetId in target_list: + sql = sql_template.format(dataName=self.dataName,targetId=targetId,tableName=self.tableName) + self.db.cmd(sql) + + return target_list + def markDeleted(self,targetId,userId): sql = 'UPDATE {tableName} SET {dataName}_is_delete=1,{dataName}_last_edit_user_id={userId} WHERE {dataName}_id="{targetId}"'.format( dataName=self.dataName,targetId=targetId,userId=userId,tableName=self.tableName) @@ -63,14 +76,6 @@ def findActivities(self,conditionAssigned,orderById,arrangeMode,arrangeCondition sql = sql.format(dataName=self.dataName,tableName=self.tableName) ret = self.db.query(sql) return ret - - def getExpiredIds(self): - sql = 'SELECT {dataName}_id FROM {tableName} '\ - +'WHERE {dataName}_is_delete=0 and {dataName}_is_expire=0 and (TO_DAYS(NOW())>TO_DAYS({dataName}_end_date) '\ - +'or (TO_DAYS(NOW())=TO_DAYS({dataName}_end_date) and TIME_TO_SEC(DATE_FORMAT(NOW(), "%H:%i:%s"))>TIME_TO_SEC({dataName}_end_time)))' - sql = sql.format(dataName=self.dataName,tableName=self.tableName) - Ids = self.db.query(sql) - return Ids def generateNewId(self): sql = 'SELECT {dataName}_id FROM {tableName} ORDER BY {dataName}_upload_time DESC, {dataName}_id DESC LIMIT 1'.format( @@ -81,17 +86,17 @@ def generateNewId(self): else: return "{prefix}0000000001".format(prefix=self.prefix) - def updateEditedData(self,data): + def updateEditedData(self,display_object): sql = 'UPDATE {tableName} ' - update = 'SET type_id={data[typeId]}, {dataName}_start_date="{data[startDate]}", ' \ - + '{dataName}_end_date="{data[endDate]}", {dataName}_start_time="{data[startTime]}", ' \ - + '{dataName}_end_time="{data[endTime]}", {dataName}_display_time={data[displayTime]}, ' \ - + '{dataName}_last_edit_user_id="{data[editUserId]}"' + update = 'SET type_id={display_object.type_id}, {dataName}_start_date="{display_object.start_date}", ' \ + + '{dataName}_end_date="{display_object.end_date}", {dataName}_start_time="{display_object.start_time}", ' \ + + '{dataName}_end_time="{display_object.end_time}", {dataName}_display_time={display_object.display_time}, ' \ + + '{dataName}_last_edit_user_id="{display_object.user_id}"' if self.tableName == "text_data": - update += ', text_invisible_title="{data[invisibleTitle]}"' + update += ', text_invisible_title="{display_object.invisible_title}"' sql += update - sql += ' WHERE {dataName}_id="{data[Id]}"' - sql = sql.format(tableName=self.tableName,dataName=self.dataName,data=data) + sql += ' WHERE {dataName}_id="{display_object.id}"' + sql = sql.format(tableName=self.tableName,dataName=self.dataName,display_object=display_object) self.db.cmd(sql) def getIdSysName(self,Id): @@ -105,23 +110,23 @@ def getIdSysName(self,Id): #TODO raise exception return None - def insertData(self,data): + def insertData(self,display_object): sql = 'INSERT INTO {tableName} ' \ + '({dataName}_id, type_id, {dataName}_system_name, ' \ + '{column}, {dataName}_start_date, ' \ + '{dataName}_end_date, {dataName}_start_time, {dataName}_end_time, ' \ + '{dataName}_display_time, user_id)' \ + ' VALUES ' \ - + '("{data[id]}", {data[typeId]}, "{data[systemName]}", {value}, "{data[startDate]}",' \ - + ' "{data[endDate]}", "{data[startTime]}", "{data[endTime]}", {data[displayTime]}, {data[userId]})' + + '("{display_object.id}", {display_object.type_id}, "{display_object.system_name}", {value}, "{display_object.start_date}",' \ + + ' "{display_object.end_date}", "{display_object.start_time}", "{display_object.end_time}", {display_object.display_time}, {display_object.user_id})' if self.tableName == "image_data": column = "img_thumbnail_name, img_file_name" - value = '"{data[thumbnailName]}", "{data[fileName]}"'.format(data=data) + value = '"{display_image.thumbnail_name}", "{display_image.file_name}"'.format(display_image=display_object) elif self.tableName == "text_data": column = "text_invisible_title" - value = '"{data[invisibleTitle]}"'.format(data=data) + value = '"{display_text.invisible_title}"'.format(display_text=display_object) - sql = sql.format(column=column, value=value, dataName=self.dataName, tableName=self.tableName, data=data) + sql = sql.format(column=column, value=value, dataName=self.dataName, tableName=self.tableName, display_object=display_object) self.db.cmd(sql) class UserDao(DefaultDao): @@ -282,9 +287,6 @@ class ImageDao(DataManipulateDao): dataName = 'img' tableName = 'image_data' prefix = 'imge' - def markExpired(self,imgId): - super().markExpired(targetId=imgId) - def checkExisted(self,typeId,fileName): sql = 'SELECT COUNT(*) FROM image_data WHERE img_is_expire=0 and img_is_delete=0 '\ +'and type_id={typeId} and img_file_name="{fileName}"'.format(typeId=typeId,fileName=fileName) @@ -334,12 +336,9 @@ def addLikeCount(self,targetId): sql = 'UPDATE image_data SET img_like_count=img_like_count+1 WHERE img_id="{targetId}"'.format(targetId=str(targetId)) self.db.cmd(sql) - def generateNewId(self): - return super().generateNewId() - def getCwbImgIds(self): sql = "SELECT img_id FROM image_data WHERE img_is_delete=0 and img_file_name like 'CV1_TW_3600_%'" - Ids = self.db.query(sql) + Ids = to_list(self.db.query(sql)) return Ids def getDisplayImgs(self,userId=None): @@ -378,9 +377,6 @@ def checkExisted(self,eventId): eventId=eventId) return self.queryOneValue(sql) - def markExpired(self,textId): - super().markExpired(targetId=textId) - def addLikeCount(self,targetId): sql = 'UPDATE text_data SET text_like_count=text_like_count+1 WHERE text_id="{targetId}"'.format(targetId=str(targetId)) self.db.cmd(sql) @@ -390,9 +386,6 @@ def getTextMeta(self,textId): ret = self.db.query(sql) return ret[0] - def generateNewId(self): - return super().generateNewId() - def getDisplayTexts(self,userId=None): sql = "SELECT text_id, type_id, text_upload_time, text_start_date, text_end_date, text_start_time, text_end_time, text_display_time, text_display_count " \ + "FROM text_data WHERE text_is_delete=0 AND text_is_expire=0" @@ -419,12 +412,7 @@ def getNowUserPrefer(self,dataType,UserId): sql = 'SELECT pref_data_type_{dataType}'.format(dataType=dataType) \ + ' FROM user_prefer WHERE pref_is_delete=0 and user_id="{UserId}"'.format(UserId=str(UserId)) \ + ' ORDER BY pref_set_time DESC LIMIT 1' - res = self.db.query(sql) - if len(res): - return res - else: - #TODO raise exception - return None + return self.queryOneValue(sql) def insertUserPrefer(self,prefId,userId,prefStr): sql = 'INSERT INTO user_prefer' \ diff --git a/display_object.py b/display_object.py new file mode 100644 index 0000000..d5fbc01 --- /dev/null +++ b/display_object.py @@ -0,0 +1,20 @@ + +class DisplayObject(object): + user_id = None + id = None + type_id = None + system_name = "" + start_date = None + end_date = None + start_time = None + end_time = None + display_time = None + server_dir = "" + +class DisplayImage(DisplayObject): + filepath = "" + file_name = "" + thumbnail_name = "" + +class DisplayText(DisplayObject): + invisible_title = None \ No newline at end of file diff --git a/mysql.py b/mysql.py index 0e7f652..46102d2 100644 --- a/mysql.py +++ b/mysql.py @@ -74,3 +74,15 @@ def __exit__(self, exc_type, exc_value, traceback): self.db.close() except: "Do Nothing" + +def to_list(sql_results): + """ + Transform the results from mysql query (tuple) to list + """ + ret = list() + for tup in sql_results: + if len(tup) == 1: + ret.append(tup[0]) + else: + ret.append(list(tup)) + return ret \ No newline at end of file diff --git a/server.py b/server.py index 2e6268c..3dc2451 100644 --- a/server.py +++ b/server.py @@ -18,6 +18,7 @@ from apiclient import discovery from pprint import pprint import datetime +from display_object import * define('port',default=3000,help='run the server on the given port',type=int) define('log_file_prefix',default='server.log',help='log file name',type=str) @@ -125,20 +126,19 @@ def get(self): self.redirect("/signin") def post(self): - send_msg = {} receive_msg = {} upload_path = os.path.join(os.path.dirname(__file__),"static","img") thumbnail_filepath = os.path.join(os.path.dirname(__file__),"static","thumbnail") - send_msg = get_upload_meta_data(self) - send_msg["file_dir"] = upload_path + display_object = get_upload_meta_data(self) if self.get_argument('type') == 'image': try: + display_object.__class__ = DisplayImage file_metas=self.request.files['file'] for meta in file_metas: filepath = os.path.join(upload_path,meta['filename']) - send_msg["filepath"] = filepath + display_object.filepath = filepath store_image(filepath,meta['body']) - receive_msg = upload_image_insert_db(send_msg) + receive_msg = upload_image_insert_db(display_image=display_object) filepath = receive_msg["img_system_filepath"] thumbnail_filepath=os.path.join(thumbnail_filepath,receive_msg["img_thumbnail_name"]) @@ -149,7 +149,8 @@ def post(self): except: self.redirect("/upload") else: - receive_msg = upload_text_insert_db(send_msg) + display_object.__class__ = DisplayText + receive_msg = upload_text_insert_db(display_text=display_object) text_file = get_upload_text_data(self) if text_file['result'] == 'success': @@ -179,28 +180,29 @@ def post(self): img = None text = None text_content = None - send_msg = {} receive_msg = {} - send_msg = get_upload_meta_data(self) + display_object = get_upload_meta_data(self) if self.get_argument("type") == "image": - send_msg["img_id"] = tornado.escape.xhtml_escape(self.get_argument("img_id")) - receive_msg = edit_image_data(send_msg) + display_object.__class__ = DisplayImage + display_object.id = tornado.escape.xhtml_escape(self.get_argument("img_id")) + receive_msg = edit_image_data(display_image=display_object) if receive_msg["result"] == "success": flash = "Edit "+self.get_argument("img_id")+" successed " else: flash = "Edit "+self.get_argument("img_id")+" failed " img = get_img_meta(self.get_argument("img_id")) else: - send_msg["text_id"] = tornado.escape.xhtml_escape(self.get_argument("text_id")) - send_msg["invisible_title"] = send_msg["text_id"] - send_msg["text_file"] = get_upload_text_data(self) - receive_msg = edit_text_data(send_msg) + display_object.__class__ = DisplayText + display_object.id = tornado.escape.xhtml_escape(self.get_argument("text_id")) + display_object.invisible_title = display_object.id + display_object.text_file = get_upload_text_data(self) + receive_msg = edit_text_data(display_text=display_object) if receive_msg["result"] == "success": flash = "Edit "+self.get_argument("text_id")+" successed " else: flash = "Edit "+self.get_argument("text_id")+" failed " text = get_text_meta(self.get_argument("text_id")) - text_content = read_text_data(send_msg["text_id"]) + text_content = read_text_data(display_object.id) data_types = display_data_types() self.render("edit.html",img=img,text=text,data_types=data_types,flash=flash,text_content=text_content) diff --git a/server_api.py b/server_api.py index 75ef841..5935b40 100644 --- a/server_api.py +++ b/server_api.py @@ -21,6 +21,7 @@ from apiclient import discovery import datetime from dataAccessObjects import * +from display_object import * class ArgumentUtil(): """Provide the interface to get argument from handler @@ -71,15 +72,15 @@ def getArguments(self): class UploadArgumentsUtil(ArgumentUtil): def getArguments(self): - uploadData = {} - uploadData['file_type'] = self.getArgument('data_type') - uploadData['start_date'] = self.getArgument('start_date') - uploadData['end_date'] = self.getArgument('end_date') - uploadData['start_time'] = self.getArgument('start_time') - uploadData['end_time'] = self.getArgument('end_time') - uploadData['display_time'] = self.getArgument('display_time') - return uploadData -# + 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 + def add_like_count(target_id): try: if target_id[0:4]=="imge": @@ -174,44 +175,19 @@ def check_bluetooth_id_exist(bluetooth_id): return isUsed except: return -1 -# -def check_bluetooth_mode_available(): - file_dir = "setting" - file_name = "server_setting.txt" - #check setting file exist - if not os.path.exists(file_dir): - return -1 - if not os.path.isfile(file_dir+'/'+file_name): - return -1 - + +def check_bluetooth_mode_enable(): try: - #read setting file - filename = file_dir + '/' + file_name - file_pointer = open(filename,"r") - bluetooth_available = 0 - for line in file_pointer: - pure_data = [] - pure_data = line.rstrip('\n').split(' ') - if pure_data[0] == "bluetooth_enable": - bluetooth_available = int(pure_data[1]) - file_pointer.close() - - #check function available - if bluetooth_available==1: - return 1 - else : - return 0 - - return 0 + from config.settings import bluetooth_enable + + return bluetooth_enable except Exception as e: print(str(e)) - return -1 -# + return False + def load_now_user_prefer(user_id): try: - now_hour = time.localtime(time.time())[3] - #use now time to choose preference rule - data_type = "" + now_hour = time.localtime(time.time()).tm_hour if now_hour >= 7 and now_hour < 11: data_type = "01" elif now_hour >= 11 and now_hour < 13: @@ -224,21 +200,15 @@ def load_now_user_prefer(user_id): data_type = "05" with UserPreferDao() as userPreferDao: - pure_result = userPreferDao.getNowUserPrefer(dataType=data_type,UserId=user_id) + user_pref_str = userPreferDao.getNowUserPrefer(dataType=data_type,UserId=user_id) - #reshap pref_data_type_XX from varchar to int array - data_type_array = [] - if len(pure_result) > 0 and pure_result[0][0] is not None: - str_condition = pure_result[0][0].split(' ') - for num1 in range(len(str_condition)): - data_type_array.append(int(str_condition[num1])) + if user_pref_str: + return [int(type_id) for type_id in user_pref_str.split(' ')] else: - return -1 - - return data_type_array + return [] except: return -1 -# + def set_insert_customer_text_msg(): try: send_msg = {} @@ -336,8 +306,11 @@ def collect_user_prefer_data(user_id, prefer_data_type): return return_msg except: return return_msg -# + def insert_customized_schedule(user_id, prefer_data_type): + """ + Deprecated + """ from arrange_schedule import edit_schedule try: @@ -379,7 +352,7 @@ def deal_with_bluetooth_id(bluetooth_id): user_id=0 #check bluetooth mode available - if check_bluetooth_mode_available()==0: + if not check_bluetooth_mode_enable(): return_msg["error"] = "the bluetooth function is closed" return return_msg @@ -515,11 +488,10 @@ def get_upload_meta_data(handler): uploadArgUtil = UploadArgumentsUtil(handler) user_name = handler.get_current_user().decode('utf-8') - meta_data = uploadArgUtil.getArguments() - meta_data["server_dir"] = os.path.dirname(__file__) - meta_data["user_id"] = get_user_id(user_name) - - return meta_data + 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): @@ -598,45 +570,28 @@ def get_abs_type_dir(type_id,server_dir): type_dir = dataTypeDao.getTypeDir(typeId=type_id) return os.path.join(server_dir,"static",type_dir) -# -def upload_image_insert_db(json_obj): +def upload_image_insert_db(display_image): try: return_msg = {} return_msg["result"] = "fail" - try: - server_dir = json_obj["server_dir"] - type_id = json_obj["file_type"] - img_filepath = json_obj["filepath"] - img_start_date = json_obj["start_date"] - img_end_date = json_obj["end_date"] - img_start_time = json_obj["start_time"] - img_end_time = json_obj["end_time"] - img_display_time = json_obj["display_time"] - user_id = json_obj["user_id"] - except: - return_msg["error"] = "input parameter missing" - return return_msg - img_id = "" - img_file_name = os.path.split(img_filepath)[1] - user_level_low_bound = 100 - #default - if len(img_start_time)==0: - img_start_time = "00:00:00" - if len(img_end_time)==0: - img_end_time = "23:59:59" + img_file_name = os.path.split(display_image.filepath)[1] - receive_msg = check_user_level(str(user_id)) + 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(type_id,server_dir) + img_type_dir = get_abs_type_dir(display_image.type_id,display_image.server_dir) except: - return_msg["error"] = "no such type id : " + str(type_id) + return_msg["error"] = "no such type id : " + str(display_image.type_id) return return_msg - #generate new id with ImageDao() as imageDao: img_id = imageDao.generateNewId() @@ -644,41 +599,32 @@ def upload_image_insert_db(json_obj): img_thumbnail_name = "thumbnail_" + img_system_name img_system_filepath = os.path.join(img_type_dir, img_system_name) try: - copyfile(img_filepath, img_system_filepath) - if os.path.isfile(img_filepath) and os.path.isfile(img_system_filepath): - os.remove(img_filepath) + 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(img_filepath) and os.path.isfile(img_system_filepath): + 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 - #insert images data to mysql - img_data = {} - img_data["id"] = img_id - img_data["typeId"] = str(type_id) - img_data["systemName"] = img_system_name - img_data["thumbnailName"] = img_thumbnail_name - img_data["fileName"] = img_file_name - img_data["startDate"] = img_start_date - img_data["endDate"] = img_end_date - img_data["startTime"] = img_start_time - img_data["endTime"] = img_end_time - img_data["displayTime"] = str(img_display_time) - img_data["userId"] = str(user_id) + 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(data=img_data) + imageDao.insertData(display_object=display_image) except DB_Exception as e: - return_msg["error"] = "insert mysql error ({filename}) {msg}".format(filename=img_filepath,msg=str(e)) + return_msg["error"] = "insert mysql error ({filename}) {msg}".format(filename=display_image.filepath,msg=str(e)) try: - copyfile(img_system_filepath, img_filepath) - if os.path.isfile(img_filepath) and os.path.isfile(img_system_filepath): + 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=img_filepath,msg=str(e)) + return_msg["error"] = "insert mysql error ({filename}) {msg}".format(filename=display_image.filepath,msg=str(e)) except: "DO NOTHING" return return_msg @@ -692,24 +638,10 @@ def upload_image_insert_db(json_obj): return_msg["error"] = e.args[1] return return_msg -# -def edit_image_data(json_obj): +def edit_image_data(display_image): try: return_msg = {} return_msg["result"] = "fail" - try: - server_dir = json_obj["server_dir"] - img_id = json_obj["img_id"] - type_id = json_obj["file_type"] - img_start_date = json_obj["start_date"] - img_end_date = json_obj["end_date"] - img_start_time = json_obj["start_time"] - img_end_time = json_obj["end_time"] - img_display_time = json_obj["display_time"] - user_id = json_obj["user_id"] - except: - return_msg["error"] = "input parameter missing" - return return_msg user_level_low_bound = 100 user_level_high_bound = 10000 @@ -717,9 +649,9 @@ def edit_image_data(json_obj): #check user level with UserDao() as userDao: - user_level = userDao.getUserLevel(user_id) + user_level = userDao.getUserLevel(display_image.user_id) if not user_level: - return_msg['error'] = 'No user_id "{user_id}"'.format(user_id=user_id) + return_msg['error'] = 'No user_id "{user_id}"'.format(user_id=display_image.user_id) return return_msg else: if user_level < user_level_low_bound: @@ -727,31 +659,31 @@ def edit_image_data(json_obj): return return_msg #check self image with ImageDao() as imageDao: - imgInfo = imageDao.getIdSysName(Id=str(img_id)) + imgInfo = imageDao.getIdSysName(Id=str(display_image.id)) try: - if imgInfo["userId"] != user_id and user_level < user_level_high_bound: + if imgInfo["userId"] != display_image.user_id and user_level < user_level_high_bound: return_msg["error"] = "can not modify other user image " return return_msg img_type_id = imgInfo["typeId"] except: - return_msg["error"] = "no such image id : {img_id}".format(img_id=img_id) + return_msg["error"] = "no such image id : {id}".format(id=display_image.id) return return_msg #check if we need to move the file old_dir = "" new_dir = "" - if img_type_id == type_id: + if img_type_id == display_image.type_id: "DO NOTHING" else : #get img_system_name with ImageDao() as imageDao: - img_info = imageDao.getIdSysName(Id=str(img_id)) + img_info = imageDao.getIdSysName(Id=str(display_image.id)) img_sys_name = img_info["systemName"] if img_sys_name: old_dir = img_sys_name new_dir = img_sys_name else: - return_msg["error"] = "no such image id : {img_id}".format(img_id=img_id) + return_msg["error"] = "no such image id : {id}".format(id=display_image.id) return return_msg #get old image type dir @@ -760,16 +692,16 @@ def edit_image_data(json_obj): if type_dir: old_dir = type_dir + old_dir else: - return_msg["error"] = "no such image type : {type_id}".format(type_id=str(img_type_id)) + return_msg["error"] = "no such image type : {type_id}".format(type_id=img_type_id) return return_msg #get new image type dir with DataTypeDao() as dataTypeDao: - type_dir = dataTypeDao.getTypeDir(typeId=str(type_id)) + type_dir = dataTypeDao.getTypeDir(typeId=str(display_image.type_id)) if type_dir: new_dir = type_dir + new_dir else: - return_msg["error"] = "no such image type : {type_id}".format(type_id=str(type_id)) + 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 @@ -777,8 +709,8 @@ def edit_image_data(json_obj): "DO NOTHING" else : try: - old_dir = os.path.join(server_dir,"static",old_dir) - new_dir = os.path.join(server_dir,"static",new_dir) + old_dir = os.path.join(display_image.server_dir,"static",old_dir) + new_dir = os.path.join(display_image.server_dir,"static",new_dir) copyfile(old_dir, new_dir) if os.path.isfile(old_dir) and os.path.isfile(new_dir): os.remove(old_dir) @@ -790,20 +722,10 @@ def edit_image_data(json_obj): "DO NOTHING" return_msg["error"] = "move file error : " + old_dir return return_msg - - #start to modify mysql - img_data = {} - img_data["typeId"] = str(type_id) - img_data["startDate"] = img_start_date - img_data["endDate"] = img_end_date - img_data["startTime"] = img_start_time - img_data["endTime"] = img_end_time - img_data["displayTime"] = str(img_display_time) - img_data["editUserId"] = str(user_id) - img_data["Id"] = img_id + try: with ImageDao() as imageDao: - imageDao.updateEditedData(data=img_data) + imageDao.updateEditedData(display_object=display_image) except DB_Exception as e: try: copyfile(new_dir, old_dir) @@ -827,73 +749,40 @@ def edit_image_data(json_obj): return_msg["error"] = e.args[1] return return_msg -#never debug this function -def upload_text_insert_db(json_obj): +def upload_text_insert_db(display_text): try: return_msg = {} return_msg["result"] = "fail" - try: - server_dir = json_obj["server_dir"] - type_id = json_obj["file_type"] - text_start_date = json_obj["start_date"] - text_end_date = json_obj["end_date"] - text_start_time = json_obj["start_time"] - text_end_time = json_obj["end_time"] - text_display_time = json_obj["display_time"] - user_id = json_obj["user_id"] - except: - return_msg["error"] = "input parameter missing" - return return_msg - text_id = "" - system_file_dir = "" - text_system_name = "" - user_level_low_bound = 100 - #default - if len(text_start_time)==0: - text_start_time = "00:00:00" - if len(text_end_time)==0: - text_end_time = "23:59:59" + 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(user_id) + receive_msg = check_user_level(display_text.user_id) if 'fail' in receive_msg: return_msg['result'] = receive_msg['error'] - #generate new id with TextDao() as textDao: text_id = textDao.generateNewId() - - if "invisible_title" in json_obj: - invisible_title = json_obj["invisible_title"] - else: - invisible_title = text_id #get file place with DataTypeDao() as dataTypeDao: - type_dir = dataTypeDao.getTypeDir(typeId=str(type_id)) + type_dir = dataTypeDao.getTypeDir(typeId=str(display_text.type_id)) try: text_system_name = text_id + ".txt" - system_file_dir = os.path.join(server_dir, "static", type_dir) + 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(type_id) + return_msg["error"] = "no such type id : " + str(display_text.type_id) return return_msg - - #insert text data to mysql - text_data = {} - text_data["id"] = text_id - text_data["typeId"] = str(type_id) - text_data["systemName"] = text_system_name - text_data["invisibleTitle"] = invisible_title - text_data["startDate"] = text_start_date - text_data["endDate"] = text_end_date - text_data["startTime"] = text_start_time - text_data["endTime"] = text_end_time - text_data["displayTime"] = str(text_display_time) - text_data["userId"] = str(user_id) + + 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(data=text_data) + textDao.insertData(display_object=display_text) return_msg["text_id"] = text_id return_msg["text_system_dir"] = system_file_dir @@ -904,25 +793,10 @@ def upload_text_insert_db(json_obj): return return_msg # -def edit_text_data(json_obj): +def edit_text_data(display_text): try: return_msg = {} return_msg["result"] = "fail" - try: - server_dir = json_obj["server_dir"] - text_id = json_obj["text_id"] - invisible_title = json_obj["invisible_title"] - type_id = json_obj["file_type"] - text_start_date = json_obj["start_date"] - text_end_date = json_obj["end_date"] - text_start_time = json_obj["start_time"] - text_end_time = json_obj["end_time"] - text_display_time = json_obj["display_time"] - user_id = json_obj["user_id"] - text_file = json_obj["text_file"] - except: - return_msg["error"] = "input parameter missing" - return return_msg user_level_low_bound = 100 user_level_high_bound = 10000 @@ -930,9 +804,9 @@ def edit_text_data(json_obj): #check user level with UserDao() as userDao: - user_level = userDao.getUserLevel(user_id) + user_level = userDao.getUserLevel(display_text.user_id) if not user_level: - return_msg['error'] = 'No user_id "{user_id}"'.format(user_id=user_id) + return_msg['error'] = 'No user_id "{user_id}"'.format(user_id=display_text.user_id) return return_msg else: if user_level < user_level_low_bound: @@ -940,27 +814,27 @@ def edit_text_data(json_obj): return return_msg #check self text with TextDao() as textDao: - textInfo = textDao.getIdSysName(Id=str(text_id)) + textInfo = textDao.getIdSysName(Id=str(display_text.id)) try: - if textInfo["userId"] != user_id and user_level < user_level_high_bound: + if textInfo["userId"] != display_text.user_id and user_level < user_level_high_bound: return_msg["error"] = "can not modify other user text" return return_msg text_type_id = int(textInfo["typeId"]) except: - return_msg["error"] = "no such text id : {text_id}".format(text_id=text_id) + return_msg["error"] = "no such text id : {text_id}".format(text_id=display_text.id) return return_msg old_dir = "" new_dir = "" #get text_system_name with TextDao() as textDao: - text_info = textDao.getIdSysName(Id=str(text_id)) + text_info = textDao.getIdSysName(Id=str(display_text.id)) text_sys_name = text_info["systemName"] try: old_dir = text_sys_name new_dir = text_sys_name except: - return_msg["error"] = "no such text id : {text_id}".format(text_id=text_id) + return_msg["error"] = "no such text id : {text_id}".format(text_id=display_text.id) return return_msg #get old text type dir @@ -973,17 +847,17 @@ def edit_text_data(json_obj): return return_msg #check if we need to move the file - if text_type_id == type_id: - old_dir = os.path.join(server_dir,"static",old_dir) + if text_type_id == display_text.type_id: + old_dir = os.path.join(display_text.server_dir,"static",old_dir) new_dir = old_dir else : #get new text type dir with DataTypeDao() as dataTypeDao: - type_dir = dataTypeDao.getTypeDir(typeId=str(type_id)) + type_dir = dataTypeDao.getTypeDir(typeId=str(display_text.type_id)) try: new_dir = type_dir + new_dir except: - return_msg["error"] = "no such text type : " + str(type_id) + return_msg["error"] = "no such text type : " + str(display_text.type_id) return return_msg #check if we need to move the file @@ -991,8 +865,8 @@ def edit_text_data(json_obj): new_dir = 'static/'+new_dir else : try: - old_dir = os.path.join(server_dir,"static",old_dir) - new_dir = os.path.join(server_dir,"static",new_dir) + old_dir = os.path.join(display_text.server_dir,"static",old_dir) + new_dir = os.path.join(display_text.server_dir,"static",new_dir) copyfile(old_dir, new_dir) if os.path.isfile(old_dir) and os.path.isfile(new_dir): os.remove(old_dir) @@ -1005,22 +879,11 @@ def edit_text_data(json_obj): return_msg["error"] = "move file error : " + old_dir return return_msg with open(new_dir,'w') as fp: - print(json.dumps(text_file),file=fp) - - #start to modify mysql - text_data = {} - text_data["typeId"] = str(type_id) - text_data["invisibleTitle"] = invisible_title - text_data["startDate"] = text_start_date - text_data["endDate"] = text_end_date - text_data["startTime"] = text_start_time - text_data["endTime"] = text_end_time - text_data["displayTime"] = str(text_display_time) - text_data["editUserId"] = str(user_id) - text_data["Id"] = text_id + print(json.dumps(display_text.text_file),file=fp) + try: with TextDao() as textDao: - textDao.updateEditedData(data=text_data) + textDao.updateEditedData(display_object=display_text) except DB_Exception as e: try: copyfile(new_dir, old_dir) diff --git a/setting/server_setting.txt b/setting/server_setting.txt deleted file mode 100644 index e528f67..0000000 --- a/setting/server_setting.txt +++ /dev/null @@ -1 +0,0 @@ -bluetooth_enable 1 diff --git a/static/css/template.css b/static/css/template.css index d3b0eb9..5603b65 100644 --- a/static/css/template.css +++ b/static/css/template.css @@ -81,7 +81,6 @@ p#like_count { } #news { - background-color: #275D86; padding-top: 60px; } diff --git a/static/js/board_size_reset.js b/static/js/board_size_reset.js index 7e3ad24..4dbf965 100644 --- a/static/js/board_size_reset.js +++ b/static/js/board_size_reset.js @@ -1,8 +1,11 @@ $('div.container').height(screen.height * 0.98); $('div.container').width(screen.width * 0.9); -$('div.header').height(screen.height * 0.35); -$('div.header').width(screen.width * 0.9); -$('div.content').height(screen.height * 0.63); -$('div.content').width(screen.width * 0.9); -$('div.bar').height(screen.height * 0.01); -$('div.bar').width(screen.width * 0.9); + +function setup_textwindow(){ + $('div.header').height(screen.height * 0.35); + $('div.header').width(screen.width * 0.9); + $('div.content').height(screen.height * 0.63); + $('div.content').width(screen.width * 0.9); + $('div.bar').height(screen.height * 0.01); + $('div.bar').width(screen.width * 0.9); +} \ No newline at end of file diff --git a/static/js/load_schedule.js b/static/js/load_schedule.js index 3c77e6e..f204cd6 100644 --- a/static/js/load_schedule.js +++ b/static/js/load_schedule.js @@ -25,62 +25,9 @@ function load_schedule(){ contentType : 'application/text', // ajax success // success: function(jsonRes){ - // case1 - fail // - if(jsonRes.result == "fail"){ - console.log("fail"); - console.log(jsonRes); - } - // case2 - same // - else if(last_schedule_id == jsonRes.schedule_id){ - console.log("same"); - } - // case3 - text // - else if(jsonRes.file_type == "text"){ - console.log("text"); - last_schedule_id = jsonRes.schedule_id; - resetTextDisplay(); - // 1. preference // - if ('preference' in jsonRes.file_text){ - setPreferenceDisplay(); - if(jsonRes.file_text.preference === 1){ - setDateInfo(); - setConstellationInfo(jsonRes); - if( jsonRes.file_text.news.length > 0){ - $('img#qrcode1').attr('src',String(jsonRes.file_text.news[0].QR)); - $('div#newsTitle1').text(jsonRes.file_text.news[0].title); - $('img#qrcode2').attr('src',String(jsonRes.file_text.news[1].QR)); - $('div#newsTitle2').text(jsonRes.file_text.news[1].title); - } - } - } - // 2. forum news // - else if('text_type' in jsonRes.file_text && jsonRes.file_text.text_type=='news'){ - setNewsDisplay(); - setNewsInfo(jsonRes); - } - // 3. other announcement // - else{ - setAnnouncementDisplay(jsonRes); - setConInfo(jsonRes); - setAnnouncementInfo(jsonRes); - } - - if ('event_id' in jsonRes.file_text){ - $('img#event_qrcode').css('display','inline'); - $('img#event_qrcode').attr('src',String(jsonRes.file_text.event_id)); - } - } - // case4 - image // - else if(jsonRes.file_type == "image"){ - console.log("text"); - last_schedule_id = jsonRes.schedule_id; - setImageDisplay(); - setImageInfo(jsonRes); - } - // else handling // - else{ - - } + $('div.container').html(jsonRes) + setImageInfo() + setup_textwindow() }, // ajax error // error: function (xhr, textStatus, error) { @@ -92,142 +39,7 @@ function load_schedule(){ }); } -// text // -function resetTextDisplay(){ - $('img#pic').css('display','none'); - $('div.like_count').css('display','none'); - $('div.title2').css('display','none'); - $('img#event_qrcode').css('display','none'); - $('footer').css('display','none'); - $('div#user_pref').css('display','none'); - $('div#news').css('display','none'); - $('img#qrcode1').css('display','none'); - $('img#qrcode2').css('display','none'); -} - -function setDateInfo(jsonRes){ - var datetime = new Date(Date.parse(jsonRes.file_text.date)); - var weekday = getWeekday(datetime); - var year = datetime.getFullYear(); - var month = datetime.getMonth() + 1; - var date = datetime.getDate(); - $('div#week b').text(weekday); - $('div#year b').text(year); - $('div#date b').text(String(month)+'.'+String(date)); -} - -function getWeekday(datetime){ - var week = ["Mon.", "Tue.", "Wed.", "Thu.", "Fri.", "Sat.", "Sun."]; - return week[datetime.getDay()]; -} - -function setPreferenceDisplay(){ - $('div#user_pref').css('display','inline'); - $('img#qrcode1').css('display','inline'); - $('img#qrcode2').css('display','inline'); -} - -function setConstellationInfo(jsonRes){ - $('div#name b').text(jsonRes.file_text.nickname); - $('div#star b').text(jsonRes.file_text.constellation.name); - $('div#overall b').text(jsonRes.file_text.constellation.value[0]); - $('div#love b').text(jsonRes.file_text.constellation.value[1]); - $('div#career b').text(jsonRes.file_text.constellation.value[2]); - $('div#wealth b').text(jsonRes.file_text.constellation.value[3]); -} - -function setNewsDisplay(){ - $('div#news').css('display','inline'); -} - -function setNewsInfo(jsonRes){ - $('div#forum-1').text(jsonRes.file_text.forum_name1); - $('p#title-1').text(jsonRes.file_text.title1); - $('img#qrcode-1').attr('src',String(jsonRes.file_text.QR1)); - $('div#forum-2').text(jsonRes.file_text.forum_name2); - $('p#title-2').text(jsonRes.file_text.title2); - $('img#qrcode-2').attr('src',String(jsonRes.file_text.QR2)); -} - -function setAnnouncementDisplay(jsonRes){ - $('div.title2').css('display','inline'); - if(jsonRes.type_name === "獲獎公告"){ - $('footer').css('display','inline'); - } - else{ - $('footer').css('display','none') - } -} - -function setConInfo(jsonRes){ - if ( 'con' in jsonRes.file_text){ - $('span#con').html(jsonRes.file_text.con); - } - else{ - if (jsonRes.type_name === "獲獎公告"){ - $('span#con').html("賀!"); - } - else{ - $('span#con').html("活動公告"); - } - } -} - -function setAnnouncementInfo(jsonRes){ - $('#title1').html(jsonRes.file_text.title1); - $('#title2').html(jsonRes.file_text.title2); - if('location' in jsonRes.file_text && jsonRes.file_text.location != ''){ - $('#location').html('地點: ' + jsonRes.file_text.location) - } - else{ - $('#location').html('') - } - if('detailtime' in jsonRes.file_text && jsonRes.file_text.detailtime != ''){ - $('#detailtime').html('時間: ' + jsonRes.file_text.detailtime) - } - else{ - $('#detailtime').html('') - } - $('#description').html(jsonRes.file_text.description); - if(jsonRes.type_name === "獲獎公告"){ - if ('background_color' in jsonRes.file_text){ - $('div.header').css('background-color',jsonRes.file_text.background_color); - $('div.bar').css('background-color',jsonRes.file_text.background_color); - } - else{ - $('div.header').css('background-color','#CE0000'); - $('div.bar').css('background-color','#CE0000'); - } - $('div.congratulation').html(jsonRes.file_text.year+"年"+jsonRes.file_text.month+"月 資訊學院全體師生慶賀"); - } - else{ - if ('background_color' in jsonRes.file_text){ - $('div.header').css('background-color',jsonRes.file_text.background_color); - } - else{ - $('div.header').css('background-color','#FF8000'); - } - } -} - -// image // -function setImageDisplay(){ - $('div.title2').css('display','none'); - $('div#user_pref').css('display','none'); - $('div#news').css('display','none'); - $('img#pic').css('display','inline'); - $('img#like').css('display','inline'); - $('div.like_count').css('display','inline'); - $('p#like_count').css('display','inline'); -} - -function setImageInfo(jsonRes){ - $('img#pic').attr('src',"/static/" + jsonRes.file); +function setImageInfo(){ $('img#pic').height(screen.height * 0.98); $('img#pic').css('maxWidth',($(window).width() * 0.85 | 0 )); - $('img#like').attr('src',"/static/img/Like.png"); - if('like_count' in jsonRes){ - $('p#like_count').text(jsonRes.like_count); - } } - diff --git a/template/board.html b/template/board.html index 185bb5b..721e113 100644 --- a/template/board.html +++ b/template/board.html @@ -8,106 +8,7 @@