Skip to content

Commit

Permalink
Merge pull request #342 from SWLBot/dev
Browse files Browse the repository at this point in the history
Release v0.1.4
  • Loading branch information
Billy4195 authored Feb 20, 2018
2 parents 86418a4 + 5d695e6 commit 1acdcca
Show file tree
Hide file tree
Showing 19 changed files with 370 additions and 774 deletions.
228 changes: 72 additions & 156 deletions arrange_schedule.py

Large diffs are not rendered by default.

14 changes: 12 additions & 2 deletions board.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():

Expand All @@ -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"),
Expand Down
21 changes: 10 additions & 11 deletions broadcast_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand All @@ -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():
"""
Expand All @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@
shutdown = 0,
max_db_log = 100,
min_db_activity = 10)

bluetooth_enable = True
86 changes: 37 additions & 49 deletions dataAccessObjects.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from mysql import *
from display_object import *

class DefaultDao():
def __init__(self):
Expand Down Expand Up @@ -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)
Expand All @@ -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(
Expand All @@ -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):
Expand All @@ -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):
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand All @@ -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"
Expand All @@ -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' \
Expand Down
20 changes: 20 additions & 0 deletions display_object.py
Original file line number Diff line number Diff line change
@@ -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
12 changes: 12 additions & 0 deletions mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
32 changes: 17 additions & 15 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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"])
Expand All @@ -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':
Expand Down Expand Up @@ -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)

Expand Down
Loading

0 comments on commit 1acdcca

Please sign in to comment.