def insert_invitee_id(teamName, inviteeId): # Update or Insert # if not exist then Insert if not dao.query(TeamInvitations).\ filter(TeamInvitations.teamName == teamName, TeamInvitations.inviteeId == inviteeId).\ first(): newInvitee = TeamInvitations(teamName = teamName, inviteeId = inviteeId) dao.add(newInvitee) # else then Update else : dao.query(TeamInvitations).\ filter(TeamInvitations.teamName == teamName, TeamInvitations.inviteeId == inviteeId).\ update(dict(isDeleted = ENUMResources().const.FaLSE)) # Commit Exception try: dao.commit() flash(inviteeId + get_message('inviteeSucceeded')) except Exception: dao.rollback() return get_message('updateFailed') return None
def id_check(select, error = None): if request.method == 'POST': # 암호를 입력 안했을 때 if not request.form['password']: error ='Password' + get_message('fillData') else: try: memberId = session[SessionResources().const.MEMBER_ID] password = request.form['password'] check = select_match_member(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = memberId)).first() # 암호가 일치 할 때 #Checking Success if check_password_hash (check.password, TripleDES.encrypt(str(password))): # for all user if select == 'account': return redirect(url_for(RouteResources().const.EDIT_PERSONAL)) # server manager elif SETResources().const.SERVER_ADMINISTRATOR in session[SessionResources().const.AUTHORITY][0]: if select == 'server_manage_collegedepartment': return redirect(url_for('.server_manage_collegedepartment', collegePageNum = int(1), departmentPageNum = int(1))) elif select == 'server_manage_class': return redirect(url_for('.server_manage_class', pageNum = int(1))) elif select == 'server_manage_problem': return redirect(url_for('.server_manage_problem', activeTabId = OtherResources().const.ALL, pageNum = int(1))) elif select == 'server_manage_user': return redirect(url_for('.server_manage_user', activeTabId = OtherResources().const.ALL, pageNum = int(1))) elif select == 'server_manage_service': return redirect(url_for('.server_manage_service')) # class manager elif SETResources().const.COURSE_ADMINISTRATOR in session[SessionResources().const.AUTHORITY][0]: if select == 'user_submit': return redirect(url_for('.class_user_submit')) elif select == 'cm_manage_problem': return redirect(url_for('.class_manage_problem')) elif select == 'cm_manage_user': return redirect(url_for('.class_manage_user')) elif select == 'cm_manage_service': return redirect(url_for('.class_manage_service')) else: return unknown_error() # 암호가 일치 하지 않을 때 else: error = get_message('wrongPassword') except Exception as e: Log.error(str(e)) raise e return render_template(HTMLResources().const.ID_CHECK_HTML, error = error)
def get_member_name(memberIdIndex): try: memberName = select_member(memberIdIndex = memberIdIndex).first().\ memberName return memberName except: return unknown_error(get_message('dbError'))
def get_course_name(courseId): try: courseName = select_course_information(courseId).first().\ courseName return courseName except Exception as e: return unknown_error(get_message('dbError'))
def get_member_name(memberId): try: memberName = select_match_member(MemberCourseProblemParameter(memberId = memberId)).first().\ memberName return memberName except Exception as e: return unknown_error(get_message('dbError'))
def get_used_language_version(usedLanguage): try: usedLanguageVersion = dao.query(Languages.languageVersion).\ first().\ languageVersion except: return unknown_error(get_message('dbError')) return usedLanguageVersion
def get_problem_name(problemIndex): try: problemName = select_problem(problemIndex = problemIndex).first().\ problemName return problemName except: return unknown_error(get_message('dbError'))
def submit_error(tempPath, pageNum, error, browserName=None, browserVersion=None): os.system(OtherResources().const.DELETE_COMMAND % tempPath) flash(get_message(error)) return page_move(pageNum, browserName, browserVersion)
def get_member_name(memberId): try: memberName = dao.query(Members.memberName).\ filter(Members.memberId == memberId).\ first().\ memberName return memberName except Exception as e: return unknown_error(get_message('dbError'))
def get_course_name(courseId): try: courseName = dao.query(RegisteredCourses.courseName).\ filter(RegisteredCourses.courseId == courseId).\ first().\ courseName return courseName except Exception as e: return unknown_error(get_message('dbError'))
def get_used_language_index(usedLanguageName): try: usedLanguageIndex = dao.query(Languages.languageIndex).\ filter(Languages.languageName == usedLanguageName).\ first().\ languageIndex except Exception as e: return unknown_error(get_message('dbError')) return usedLanguageIndex
def get_used_language_index(usedLanguageName, usedLanguageVersion = None): try: usedLanguageIndex = dao.query(Languages.languageIndex).\ filter(Languages.languageName == usedLanguageName, Languages.languageVersion == usedLanguageVersion).\ first().\ languageIndex except: return unknown_error(get_message('dbError')) return usedLanguageIndex
def get_problem_name(problemId): try: problemName = select_problem_informations(MemberCourseProblemParameter(memberId = None, courseId = None, problemId = problemId)).first().\ problemName return problemName except: return unknown_error(get_message('dbError'))
def decorated_function(*args, **kwargs): try: # moved from URL, error will occur if not request.referrer: return unknown_error(get_message('invalidAccess')) return f(*args, **kwargs) except Exception: return unknown_error ()
def get_used_language_version(courseId, usedLanguage): try: usedLanguageVersion = dao.query(Languages.languageVersion).\ join(LanguagesOfCourses, LanguagesOfCourses.languageIndex == Languages.languageIndex).\ filter(LanguagesOfCourses.courseId == courseId, LanguagesOfCourses.languageIndex == usedLanguage).\ first().\ languageVersion except Exception as e: return unknown_error(get_message('dbError')) return usedLanguageVersion
def get_problem_info(problemIndex, problemName): try: problemPath, limitedTime, limitedMemory, solutionCheckType, numberOfTestCase = dao.query(Problems.problemPath, Problems.limitedTime, Problems.limitedMemory, Problems.solutionCheckType, Problems.numberOfTestCase).\ filter(Problems.problemIndex == problemIndex).\ first() except: return unknown_error(get_message('dbError')) return problemPath, limitedTime, limitedMemory, solutionCheckType, numberOfTestCase
def team_invitation(teamName, accept, error = None): """ 팀 초대 수락 & 거절 """ try: # Delete Invitee dao.query(TeamInvitations).\ filter(TeamInvitations.teamName == teamName, TeamInvitations.inviteeId == session[SessionResources().const.MEMBER_ID]).\ update(dict(isDeleted = ENUMResources().const.TRUE)) # 초대 수락 if accept == OtherResources().const.ACCEPT: insert_team_member_id(teamName, session[SessionResources().const.MEMBER_ID]) # Commit Exception try: dao.commit() flash(teamName + get_message('acceptInvitee')) except Exception: dao.rollback() error = get_message('updateFailed') # 초대 걱절 else: # elif == REJECT: # Commit Exception try: dao.commit() flash(teamName + get_message('rejectInvitee')) except Exception: dao.rollback() error = get_message('updateFailed') return redirect(url_for(RouteResources().const.TEAM, pageNum = 1, error = error)) except Exception: # Unknown Error return unknown_error()
def get_problem_info(problemId, problemName): try: problemPath, limitedTime, limitedMemory, solutionCheckType, isAllInputCaseInOneFile, numberOfTestCase = dao.query(Problems.problemPath, Problems.limitedTime, Problems.limitedMemory, Problems.solutionCheckType, RegisteredProblems.isAllInputCaseInOneFile, RegisteredProblems.numberOfTestCase).\ join(RegisteredProblems, Problems.problemId == RegisteredProblems.problemId).\ filter(Problems.problemId == problemId).\ first() problemCasesPath = '%s/%s_%s_%s' %(problemPath, problemId, problemName, solutionCheckType) except Exception as e: return unknown_error(get_message('dbError')) return problemPath, limitedTime, limitedMemory, solutionCheckType, isAllInputCaseInOneFile, numberOfTestCase, problemCasesPath
def check_invitee_member(inviteeId, teamName = None): # 인풋 폼안에 아이디가 있을 때 if inviteeId: # 존재 하는 사용자 인지 확인 if not dao.query(select_match_member(memberId = inviteeId).subquery()).\ first(): return get_message('notExists') # 자가 자신 초대 방지 elif inviteeId == session[SessionResources().const.MEMBER_ID]: return get_message('notSelf') # MakeTeam In Invitee elif not teamName: # 초대 한 애를 또 초대 하는거를 방지 if inviteeId in gTeamMembersId: return get_message('alreadyExists') # Invitee Id Add gTeamMembersId.append(inviteeId) return None # ManageTeam In Invitee else: # 초대 중복 방지 if dao.query(TeamInvitations).\ filter(TeamInvitations.teamName == teamName, TeamInvitations.inviteeId == inviteeId, TeamInvitations.isDeleted == ENUMResources().const.FALSE).\ first(): return get_message('alreadyExists') # 팀원 초대 방지 elif dao.query(RegisteredTeamMembers.teamMemberId).\ filter(RegisteredTeamMembers.teamName == teamName, RegisteredTeamMembers.teamMemberId == inviteeId, RegisteredTeamMembers.isDeleted == ENUMResources().const.FALSE).\ first(): return get_message('notTeamMemberInvitee') # 조건에 충족 될 때 else: return insert_invitee_id(teamName, inviteeId) # None 값 일 때 else: return '아이디' + get_message('fillData')
def rank(activeTabCourseId, sortCondition, pageNum, error =None): try: findMemberId = None try: # Auto Complete MemberIds memberRecords = select_all_users().all() except Exception: memberRecords = [] # Last Submission Max Count submissions = select_ranks(select_last_submissions(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = None, courseId = activeTabCourseId)).subquery()).subquery() # records count try: count = select_count(submissions.c.memberId).first().\ count except Exception: count = 0 # Paging Pointed pages = get_page_pointed(pageNum = pageNum, count = count) submissions = ranks_sorted(submissions, sortCondition = sortCondition) # Find MemberId 뷰 호출 if request.method == 'POST': # Finding MemberId findMemberId = request.form['memberId'] # 순차 탐색으로 찾아야 함 for i in range(1, pages['allPage'] + 1): # memberId in Pages ranks = get_page_record(submissions, pageNum = i).subquery() # finding MemberId in Pages try: if select_match_member_sub(ranks, memberCourseProblemParameter = MemberCourseProblemParameter(memberId = findMemberId)).first().\ memberId: # Finding move to page pageNum = i # searchLine Check break except Exception: pass else: # 같은 아이디가 없을 때 메세지 error = get_message('notExists') # 랭크 정보 try: rankMemberRecords = get_page_record(submissions, pageNum = pageNum).all() except Exception: rankMemberRecords = [] try: myCourses = select_accept_courses().all() except Exception: myCourses = [] # myCourses Default Add ALL myCourses.insert(0, OtherResources().const.ALL) return render_template(HTMLResources().const.RANK_HTML, activeTabCourseId = activeTabCourseId, sortCondition = sortCondition, memberRecords = memberRecords, rankMemberRecords = rankMemberRecords, myCourses = myCourses, pages = pages, findMemberId = findMemberId, error = error) # 페이지 정보 except Exception: return unknown_error()
def submit_error(tempPath, pageNum, error, browserName = None, browserVersion = None): os.system(OtherResources().const.DELETE_COMMAND % tempPath) flash(get_message(error)) return page_move(pageNum, browserName, browserVersion)
def team_manage(teamName, error = None): """ 팀 관리 페이지 """ try: global gTeamMembersId, gTeamName, gTeamDescription try: # 자동 완성을 위한 모든 유저기록 memberRecords = dao.query(select_all_user().subqeury()).\ all() except Exception: memberRecords = [] # 팀 정보 try: teamInformation = dao.query(Teams).\ filter(Teams.teamName == teamName, Teams.isDeleted == ENUMResources().const.FALSE).first() except Exception: # None Type Exception teamInformation = [] # 팀 멤버 정보 try: teamMemberRecords = dao.query(RegisteredTeamMembers.teamMemberId).\ filter(RegisteredTeamMembers.teamName == teamName, RegisteredTeamMembers.isDeleted == ENUMResources().const.FALSE).\ order_by(RegisteredTeamMembers.isTeamMaster.asc(), RegisteredTeamMembers.teamMemberId.asc()).all() except Exception: # None Type Exception teamMemberRecords = [] # 팀장이 아닌 애가 왔을 때 if session[SessionResources().const.MEMBER_ID] != teamMemberRecords[0].teamMemberId: return unknown_error(error = get_message('accessFailed')) if request.method == 'GET': # init gTeamMembersId = copy.deepcopy(teamMemberRecords) gTeamName, gTeamDescription =None, None return render_template(HTMLResources().const.TEAM_MANAGE_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, memberRecords = memberRecords, teamInformation =teamInformation, gTeamMembersId = gTeamMembersId, gTeamName = gTeamName, gTeamDescription = gTeamDescription) elif request.method == 'POST': # 인풋이 없다면 기존 이름 가져옴 gTeamName =request.form['teamName'] if request.form['teamName'] else teamInformation.teamName gTeamDescription = request.form['teamDescription'] if request.form['teamDescription'] else teamInformation.teamDescription for form in request.form: # Saving Team if form == 'saveTeam': # 팀과 팀 멤버 변경은 동시에 업데이트 # Update Team # 중복 팀명 확인 if gTeamName != teamName and\ not dao.query(check_team_name(gTeamName).subquery()).\ first(): dao.query(Teams).\ filter(Teams.teamName == teamName).\ update(dict(teamName = gTeamName, teamDescription = gTeamDescription)) # Update TeamMembers index = 0 for raw in teamMemberRecords: if index < len(gTeamMembersId) and\ raw.teamMemberId == gTeamMembersId[index].teamMemberId: index += 1 # 삭제 팀원 적용 else: dao.query(RegisteredTeamMembers).\ filter(RegisteredTeamMembers.teamName == teamName, RegisteredTeamMembers.teamMemberId == raw.teamMemberId).\ update(dict(isDeleted = ENUMResources().const.TRUE)) # Commit Exception try: dao.commit() #init del gTeamMembersId[:] gTeamName, gTeamDescription = None, None flash(get_message('updateSucceeded')) except Exception: dao.rollback() error =get_message('updateFailed') return redirect(url_for(RouteResources().const.TEAM, pageNum = 1, error = error)) # Invitee Members elif form == 'inviteeMember': try: inviteeId = request.form['inviteeId'].split()[0] except Exception: inviteeId = None # teamMember Invitee error = check_invitee_member(inviteeId, teamName) return render_template(HTMLResources().const.TEAM_MANAGE_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, memberRecords = memberRecords, teamInformation = teamInformation, gTeamMembersId = gTeamMembersId, gTeamName = gTeamName, gTeamDescription = gTeamDescription, error = error) # Delete Members elif 'deleteMember' in form: # form의 name이 deleteMemberi -> i=Index이므로 해당 인덱스 값 제거 gTeamMembersId.pop(int(form[-1])) return render_template(HTMLResources().const.TEAM_MANAGE_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, memberRecords = memberRecords, teamInformation = teamInformation, gTeamMembersId = gTeamMembersId, gTeamName = gTeamName, gTeamDescription = gTeamDescription) # Delete Team elif form == 'deleteTeam': dao.query(Teams).\ filter(Teams.teamName == teamName).\ update(dict(isDeleted = ENUMResources().const.TRUE)) dao.query(RegisteredTeamMembers).\ filter(RegisteredTeamMembers.teamName == teamName).\ update(dict(isDeleted = ENUMResources().const.TRUE)) dao.query(TeamInvitations).\ filter(TeamInvitations.teamName == teamName).\ update(dict(isDeleted = ENUMResources().const.TRUE)) # Commit Exception try: dao.commit() #init del gTeamMembersId[:] gTeamName, gTeamDescription = None, None flash(get_message('removeTeamSucceeded')) except Exception: dao.rollback() error = get_message('updateFailed') return redirect(url_for(RouteResources().const.TEAM, pageNum = 1, error =error)) except Exception: # Unknown Error del gTeamMembersId[:] gTeamName, gTeamDescription = None, None return unknown_error()
def sign_in(): ''' @@ Success sign in flash When the page redirected from sign up page, It display flash message. ''' if '?' in request.url: flash('Signed up successfully') """ main page before sign in""" from GradeServer.utils.utilMessages import get_message from GradeServer.utils.memberCourseProblemParameter import MemberCourseProblemParameter from GradeServer.utils.utilArticleQuery import select_notices from GradeServer.utils.utilUserQuery import select_match_member from GradeServer.utils.utilRankQuery import select_top_coder from GradeServer.resource.htmlResources import HTMLResources from GradeServer.resource.sessionResources import SessionResources error = None if request.method == 'POST': checker = True language = {'kr':0, # default 'en':1} for form in request.form: if "language" in form: checker = False lang = request.form['language'] session['language'] = language[lang] if checker: if not request.form['memberId']: error = '아이디' + get_message('fillData') elif not request.form['password']: error = '암호' + get_message('fillData') else: try: """ DB Password check """ memberId = request.form['memberId'].split()[0] password = request.form['password'] check = select_match_member(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = memberId)).first() from werkzeug.security import check_password_hash from GradeServer.GradeServer_py3des import TripleDES #Checking Success if check_password_hash (check.password, TripleDES.encrypt(str(password))): flash(get_message('login')) #push Session Cache session[SessionResources().const.MEMBER_ID] = memberId session[SessionResources().const.MEMBER_NAME] = check.memberName session[SessionResources().const.AUTHORITY] = list(check.authority) session[SessionResources().const.LAST_ACCESS_DATE] = datetime.now() # set default language session['language'] = language['kr'] update_recent_access_date(memberId) # Commit Exception try: dao.commit() except Exception: dao.rollback() error = get_message('updateFailed') else: error = get_message('tryAgain') # Not Exist MemberId except Exception: error = get_message('notExists') return render_template(HTMLResources().const.MAIN_HTML, noticeRecords = select_notices(), topCoderId = select_top_coder(), error = error)
def edit_personal(error = None): contactNumber, emailAddress, comment = None, None, None try: #Get User Information try: memberInformation = join_member_informations(select_match_member(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = session[SessionResources().const.MEMBER_ID])).subquery()).first() except Exception: #None Type Exception memberInformation = [] #Get Post if request.method == 'POST': password = request.form['password'] passwordConfirm = request.form['passwordConfirm'] #Get Updating Data contactNumber = request.form['contactNumber'] emailAddress = request.form['emailAddress'] comment = request.form['comment'] #Password Same if(password and passwordConfirm) and password == passwordConfirm: #Generate Password tripleDes = triple_des(OtherResources().const.TRIPLE_DES_KEY, mode = ECB, IV = "\0\0\0\0\0\0\0\0", pad = None, padmode = PAD_PKCS5) # ID, Password NO if password == memberInformation.password\ or password == memberInformation.memberId: error = get_message('pattenFailed') else: password = generate_password_hash(tripleDes.encrypt(str(password))) passwordConfirm = None #Update DB update_member_informations(select_match_member(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = session[SessionResources().const.MEMBER_ID])), password, contactNumber, emailAddress, comment) # Commit Exception try: dao.commit() flash(get_message('updateSucceeded')) return redirect(url_for(RouteResources().const.SIGN_IN)) except Exception: dao.rollback() error = get_message('upateFailed') #Password Different elif not password and not passwordConfirm: #Update DB update_member_informations(members = select_match_member(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = session[SessionResources().const.MEMBER_ID])), password = None, contactNumber = contactNumber, emailAddress = emailAddress, comment = comment) # Commit Exception try: dao.commit() flash(get_message('updateSucceeded')) return redirect(url_for(RouteResources().const.SIGN_IN)) except Exception: dao.rollback() error = get_message('upateFailed') else: error = get_message('wrongPassword') return render_template(HTMLResources().const.EDIT_PERSONAL_HTML, memberInformation = memberInformation, contactNumber = contactNumber, emailAddress = emailAddress, comment = comment, error = error) except Exception: return unknown_error()
def make_team(error = None): """ doesn't have any application of button. you need to make the button app. """ try: global gTeamMembersId, gTeamName, gTeamDescription # 자동 완성을 위한 모든 유저기록 try : memberRecords = select_all_users().all() except Exception: memberRecords = [] print "?", memberRecords for k in memberRecords: print k.memberId if request.method == 'GET': del gTeamMembersId[:] gTeamName, gTeamDescription = None, None return render_template(HTMLResources().const.TEAM_MAKE_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, memberRecords = memberRecords) elif request.method == 'POST': # 뷰를 인벨리 데이트 하기전에 인풋값 저장 gTeamName = request.form['teamName'] gTeamDescription = request.form['teamDescription'] if request.form['teamDescription'] else None for form in request.form: # Making Team if form == 'makeTeam': # 인풋 확인 if not gTeamName: return render_template(HTMLResources().const.TEAM_MAKE_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, memberRecords = memberRecords, gTeamMembersId = gTeamMembersId, gTeamDescription = gTeamDescription, error = '팀 명' + get_message('fillData')) # 중복 팀명 확인 try: if check_team_name(gTeamName).first().\ isDeleted == ENUMResources().const.FALSE: # don't Exception return render_template(HTMLResources().const.TEAM_MAKE_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, memberRecords = memberRecords, gTeamMembersId = gTeamMembersId, gTeamDescription = gTeamDescription, error = get_message('existTeamName')) # Deleted Teams else: # Update Team dao.query(Teams).\ filter(Teams.teamName == gTeamName).\ update(dict(isDeleted = ENUMResources().const.FALSE)) except Exception: # Insert Team newTeam = Teams(teamName = gTeamName, teamDescription = gTeamDescription) dao.add(newTeam) # Commit Exception try: # this Commit Succeeded Go Next Step dao.commit() # 마스터 정보first().teamName insert_team_member_id(gTeamName, session[SessionResources().const.MEMBER_ID], ENUMResources().const.TRUE) # this Commit Succeeded Go Next Step try: dao.commit() for inviteeId in gTeamMembersId: error = insert_invitee_id(gTeamName, inviteeId) # Exception Check if error: break #init del gTeamMembersId[:] gTeamName, gTeamDescription = None, None flash(get_message('makeTeamSucceeded')) return redirect(url_for(RouteResources().const.TEAM, pageNum = 1)) except Exception: dao.rollback() error = get_message('updateFailed') except Exception: dao.rollback() error = get_message('updateFailed') # Add Members elif form == 'inviteeMember': try: inviteeId = request.form['inviteeId'].split()[0] except Exception: inviteeId = None # teamMember Invitee error = check_invitee_member(inviteeId) break # Delete Members elif 'deleteInviteeMember' in form: # form의 name이 deleteMemberi -> i=Index이므로 해당 인덱스 값 제거 gTeamMembersId.pop(int(form[-1])) break return render_template(HTMLResources().const.TEAM_MAKE_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, memberRecords = memberRecords, gTeamMembersId = gTeamMembersId, gTeamName = gTeamName, gTeamDescription = gTeamDescription, error = error) except Exception: # Unknown Error del gTeamMembersId[:] gTeamName, gTeamDescription = None, None return unknown_error()
def submit_error(tempPath, courseId, pageNum, error, browserName = None, browserVersion = None): os.system("rm -rf %s" % tempPath) flash(get_message(error)) return page_move(courseId, pageNum, browserName, browserVersion)
def write(activeTabCourseId, articleIndex, error =None): title, content, articlesOnBoard = None, None, None try: # 수강 과목 정보 myCourses = select_current_courses(select_accept_courses().subquery()).subquery() # Modify Case if articleIndex > 0: try: articlesOnBoard = join_courses_names(select_article(articleParameter = ArticleParameter(articleIndex = articleIndex), isDeleted = ENUMResources().const.FALSE).subquery(), myCourses).first() except Exception: articlesOnBoard = [] try: myCourses = dao.query(myCourses).all() except Exception: myCourses = [] # 작성시 빈칸 검사 if request.method == 'POST': # Not None try: courseId = request.form['courseId'] # request.form['courseId']가 ex)2015100101 전산학 실습 일경우 중간의 공백을 기준으로 나눔 courseId = courseId.split()[0] if courseId == OtherResources().const.ALL: courseId = None # 타이틀 가져오기 title = request.form['title'] # Get Exist Content content = request.form['content'] if not title: error ='제목' +get_message('fillData') elif not request.form['content']: error ='내용' +get_message('fillData') elif len(title) > 50: error = 'Title is too long. please write less than 50 letters' # All Fill InputText else: isNotice = ENUMResources().const.TRUE currentDate = datetime.now() currentIP = socket.gethostbyname(socket.gethostname()) # 새로 작성 if articleIndex == 0: # Set isNotice if SETResources().const.USER in session['authority']: isNotice = ENUMResources().const.FALSE # user None courseId reject newPost = ArticlesOnBoard(problemId = None, courseId = courseId, writerId = session[SessionResources().const.MEMBER_ID], isNotice = isNotice, title = title, content = content, writtenDate = currentDate, writerIp = currentIP) dao.add(newPost) # Commit Exception try: dao.commit() flash(get_message('writtenPost')) except Exception: dao.rollback() error =get_message('updateFailed') return redirect(url_for(RouteResources().const.BOARD, activeTabCourseId = activeTabCourseId, pageNum = 1)) # 게시물 수정 else: # 수정 할 글 정보 articlesOnBoard = select_article(articleParameter = ArticleParameter(articleIndex = articleIndex), isDeleted = ENUMResources().const.FALSE).update(dict(courseId = courseId, title = title, content = content, writtenDate = currentDate, writerIp = currentIP)) # Commit Exception try: dao.commit() flash(get_message('modifiedPost')) except Exception: dao.rollback() error =get_message('updateFailed') return redirect(url_for(RouteResources().const.ARTICLE_READ, activeTabCourseId = activeTabCourseId, articleIndex = articleIndex)) except Exception: # User None Course Posting Rejection if SETResources().const.USER in session['authority']: error = get_message('banPosting') else: error = get_message() return render_template(HTMLResources().const.ARTICLE_WRITE_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, myCourses = myCourses, articlesOnBoard = articlesOnBoard, title = title, content = content, error = error) except Exception: # Unknown Error return unknown_error()
def read(activeTabCourseId, articleIndex, error = None): ''' when you push a title of board content ''' try: # 내가 게시글에 누른 좋아요 정보 try: isLikeCancelled = select_article_is_like(articleParameter = ArticleParameter(articleIndex = articleIndex, boardLikerId = session[SessionResources().const.MEMBER_ID])).first().\ isLikeCancelled except Exception: # Non-Exist Case isLikeCancelled = None if request.method == 'POST': # flash message Init flashMsg =None for form in request.form: # 게시글 좋아요 Push if form == 'articleLike': # 좋아요를 누른적 없을 때 if not isLikeCancelled: # Counting +1 LIKE_INCREASE = 1 else: # 다시 좋아요 누를 때 if isLikeCancelled == ENUMResources().const.TRUE: # Counting +1 LIKE_INCREASE = 1 isLikeCancelled = ENUMResources().const.FALSE # 좋아요 취소 할 때 else: # if it's already exist then change the value of 'pushedLike' # Counting -1 LIKE_INCREASE = -1 isLikeCancelled = ENUMResources().const.TRUE update_article_like_counting(articleParameter = ArticleParameter(articleIndex = articleIndex), LIKE_INCREASE = LIKE_INCREASE) if not isLikeCancelled: # Insert Like dao.add(LikesOnBoard(articleIndex = articleIndex, boardLikerId = session[SessionResources().const.MEMBER_ID])) else: # Update Like update_article_is_like(articleParameter = ArticleParameter(articleIndex = articleIndex, boardLikerId = session[SessionResources().const.MEMBER_ID]), isLikeCancelled = isLikeCancelled) # remove duplicated read count update_view_reply_counting(articleParameter = ArticleParameter(articleIndex = articleIndex), VIEW_INCREASE = -1) break # 댓글 달기 elif form == 'writeArticleReply': # 새로운 댓글 정보 boardReplyContent = request.form['writeArticleReply'] if boardReplyContent: dao.add(RepliesOnBoard(articleIndex = articleIndex, boardReplierId = session[SessionResources().const.MEMBER_ID], boardReplyContent = boardReplyContent, boardReplierIp = socket.gethostbyname(socket.gethostname()), boardRepliedDate = datetime.now())) # remove duplicated read count update_view_reply_counting(articleParameter = ArticleParameter(articleIndex = articleIndex), VIEW_INCREASE = -1, REPLY_INCREASE = 1) flashMsg =get_message('writtenComment') else: error = 'data' + get_message('fillData') break # 댓글 좋아요 elif 'articleReplyLike' in form: # the name starts with 'articleReplyLike' and it has its unique number idIndex = len('articleReplyLike') # 내가 게시글에 누른 좋아요 정보 try: isReplyLike = select_replies_on_board_is_like(replyParameter = ReplyParameter(boardReplyIndex = int(form[idIndex:]), boardReplyLikerId = session[SessionResources().const.MEMBER_ID])).first().\ isLikeCancelled except Exception: # Non-Exist Case isReplyLike = None # 좋아요를 누른적 없을 때 if not isReplyLike: # Counting +1 LIKE_INCREASE = 1 else: # 다시 좋아요 누를 때 if isReplyLike == ENUMResources().const.TRUE: # Counting +1 LIKE_INCREASE = 1 isLikeCancelled = ENUMResources().const.FALSE # 좋아요 취소 할 때 else: # if it's already exist then change the value of 'pushedLike' # Counting -1 LIKE_INCREASE = -1 isLikeCancelled = ENUMResources().const.TRUE # Like or UnLIke update_replies_on_board_like_counting(replyParameter = ReplyParameter(boardReplyIndex = int(form[idIndex:])), LIKE_INCREASE = LIKE_INCREASE) if not isReplyLike: # Insert Like dao.add(LikesOnReplyOfBoard(boardReplyIndex = int(form[idIndex:]), boardReplyLikerId = session[SessionResources().const.MEMBER_ID])) else: # Update Like update_replies_on_board_is_like(replyParameter = ReplyParameter(boardReplyIndex = int(form[idIndex:]), boardReplyLikerId = session[SessionResources().const.MEMBER_ID]), isLikeCancelled = isLikeCancelled) # remove duplicated read count update_view_reply_counting(articleParameter = ArticleParameter(articleIndex = articleIndex), VIEW_INCREASE = -1) break # 댓글 삭제 elif 'deleteArticleReply' in form: idIndex = len('deleteArticleReply') update_replies_on_board_delete(replyParameter = ReplyParameter(boardReplyIndex = int(form[idIndex:])), isDeleted = ENUMResources().const.TRUE) # remove duplicated read count update_view_reply_counting(articleParameter = ArticleParameter(articleIndex = articleIndex), VIEW_INCREASE = -1, REPLY_INCREASE = -1) flashMsg = get_message('deletedComment') break # Commit Modify elif 'modifyArticleReplyContent' in form: idIndex = len('modifyArticleReplyContent') boardReplyContent = request.form['modifyArticleReplyContent' + form[idIndex:]] if boardReplyContent: #update comment update_replies_on_board_modify(replyParameter = ReplyParameter(boardReplyIndex = int(form[idIndex:]), boardReplyLikerId = None, boardReplyContent = boardReplyContent)) # remove duplicated read count update_view_reply_counting(articleParameter = ArticleParameter(articleIndex = articleIndex), VIEW_INCREASE = -1) flashMsg =get_message('modifiedComment') else: error = 'data' + get_message('fillData') break # 게시물 삭제 elif form == 'deleteArticle': update_article_delete(articleParameter = ArticleParameter(articleIndex = articleIndex), isDeleted = ENUMResources().const.TRUE) # Commit Exception try: dao.commit() flash(get_message('deletedPost')) except Exception: dao.rollback() error = get_message('updateFailed') return redirect(url_for(RouteResources().const.BOARD, activeTabCourseId = OtherResources().const.ALL, pageNum = 1)) # end Loop # Commit Exception try: dao.commit() # if flash Message exist if flashMsg: flash(flashMsg) except Exception: dao.rollback() error = get_message('updateFailed') # 게시글 정보 try: articlesOnBoard = select_article(articleParameter = ArticleParameter(articleIndex = articleIndex), isDeleted = ENUMResources().const.FALSE) articlesOnBoard = join_courses_names(articlesOnBoard.subquery(), select_current_courses(select_accept_courses().subquery()).subquery()).first() except Exception: articlesOnBoard = [] try: # replies 정보 repliesOnBoardRecords = select_replies_on_board(articleParameter = ArticleParameter(articleIndex = articleIndex), isDeleted = ENUMResources().const.FALSE) # 내가 게시글 리플에 누른 좋아요 정보 repliesOnBoardIsLikeRecords = select_replies_on_board_like(repliesOnBoardRecords.subquery(), memberCourseProblemParameter = MemberCourseProblemParameter(memberId = session[SessionResources().const.MEMBER_ID])).all() except Exception: repliesOnBoardIsLikeRecords = [] try: repliesOnBoardRecords = repliesOnBoardRecords.all() except Exception: repliesOnBoardRecords = [] # 나의 댓글 좋아요 여부 적용 subIndex = 0 isLikeRecords = [] for i in range(0, len(repliesOnBoardRecords)): # 나의 댓글 좋아요 정보 비교 isLikeRecords.append(ENUMResources().const.TRUE) for j in range(subIndex, len(repliesOnBoardIsLikeRecords)): if repliesOnBoardRecords[i].boardReplyIndex == repliesOnBoardIsLikeRecords[j].boardReplyIndex: isLikeRecords[i] = repliesOnBoardIsLikeRecords[j].isLikeCancelled # 다음 시작 루프 인덱스 변경 subIndex = j break # 읽은 횟수 카운팅 update_view_reply_counting(articleParameter = ArticleParameter(articleIndex = articleIndex), VIEW_INCREASE = 1) # Commit Exception try: dao.commit() except Exception: dao.rollback() return render_template(HTMLResources().const.ARTICLE_READ_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, articlesOnBoard = articlesOnBoard, activeTabCourseId = activeTabCourseId, repliesOnBoardRecords = repliesOnBoardRecords, isLikeRecords = isLikeRecords, isLikeCancelled = isLikeCancelled, error = error) except Exception: # Exception View return redirect(url_for(RouteResources().const.BOARD, activeTabCourseId = OtherResources().const.ALL, pageNum = 1))
def sign_in(): ''' @@ Success sign in flash When the page redirected from sign up page, It display flash message. ''' if '?' in request.url: flash('Signed up successfully') ''' main page before sign in''' from GradeServer.utils.utilMessages import get_message from GradeServer.utils.memberCourseProblemParameter import MemberCourseProblemParameter from GradeServer.utils.utilArticleQuery import select_notices from GradeServer.utils.utilQuery import select_accept_courses, select_past_courses, select_current_courses, select_match_member from GradeServer.utils.utilRankQuery import select_top_coder from GradeServer.resource.setResources import SETResources from GradeServer.resource.htmlResources import HTMLResources from GradeServer.resource.sessionResources import SessionResources from GradeServer.resource.languageResources import LanguageResources error = None if request.method == 'POST': checker = True language = {'kr':0, # default 'en':1} for form in request.form: if "language" in form: checker = False lang = request.form['language'] session['language'] = language[lang] if checker: if not request.form['memberId']: error = '아이디' + get_message('fillData') elif not request.form['password']: error = '암호' + get_message('fillData') else: try: """ DB Password check """ memberId = request.form['memberId'].split()[0] password = request.form['password'] check = select_match_member(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = memberId)).first() from werkzeug.security import check_password_hash from GradeServer.resource.otherResources import OtherResources from GradeServer.py3Des.pyDes import * tripleDes = triple_des(OtherResources().const.TRIPLE_DES_KEY, mode = ECB, IV = "\0\0\0\0\0\0\0\0", pad = None, padmode = PAD_PKCS5) #Checking Success if check_password_hash (check.password, tripleDes.encrypt(str(password))): flash(get_message('login')) #push Session Cache session[SessionResources().const.MEMBER_ID] = memberId session[SessionResources().const.AUTHORITY] = list(check.authority) session[SessionResources().const.LAST_ACCESS_DATE] = datetime.now() # set default language session['language'] = language['kr'] ownCourses = select_accept_courses().subquery() # Get My Accept Courses try: session[SessionResources().const.OWN_CURRENT_COURSES] = select_current_courses(ownCourses).all() except Exception: session[SessionResources().const.OWN_CURRENT_COURSES] = [] try: session[SessionResources().const.OWN_PAST_COURSES] = select_past_courses(ownCourses).all() except Exception: session[SessionResources().const.OWN_PAST_COURSES] = [] update_recent_access_date(memberId) # Commit Exception try: dao.commit() except Exception: dao.rollback() error = get_message('updateFailed') else: error = get_message('tryAgain') # Not Exist MemberId except Exception: error = get_message('notExists') return render_template(HTMLResources().const.MAIN_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, noticeRecords = select_notices(), topCoderId = select_top_coder(), error = error)
def submission_code(memberId, courseId, problemId, error = None): try: # Get endDateOfSubmission of Problem try: endDateOfSubmission = select_problems_of_course(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = None, courseId = courseId, problemId = problemId)).first().\ endDateOfSubmission except Exception: endDateOfSubmission = None # are Not Access. conditions is an Administrator and endOfSubmission ago if SETResources().const.SERVER_ADMINISTRATOR in session[SessionResources().const.AUTHORITY]\ or SETResources().const.COURSE_ADMINISTRATOR in session[SessionResources().const.AUTHORITY]\ or endDateOfSubmission <= datetime.now(): # last Submissions Info lastSubmission = select_last_submissions(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = memberId, courseId = courseId, problemId = problemId)).subquery() # Code View Count Up update_submission_code_view_count(lastSubmission, memberCourseProblemParameter = MemberCourseProblemParameter(memberId = memberId, courseId = courseId, problemId = problemId)) # Commit Exception try: dao.commit() except Exception: dao.rollback() error = get_message('updateFailed') # Problem Information (LimitedTime, LimitedMemory try: problemName = select_problem_informations(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = None, courseId = None, problemId = problemId)).first().\ problemName except Exception: problemName = None # Problem Solved Users try: # last Submissions Info submissions = select_all_submissions(lastSubmission, memberCourseProblemParameter = MemberCourseProblemParameter(memberId = memberId, courseId = courseId, problemId = problemId)).subquery() problemSolvedMemberRecords = select_solved_submissions(submissions).first() except Exception: problemSolvedMemberRecords = [] # Submitted Files Information try: submittedFileRecords = select_submitted_files(memberCourseProblemParameter = MemberCourseProblemParameter(memberId = memberId, courseId = courseId, problemId = problemId)).all() fileData = [] for raw in submittedFileRecords: # Open filePath = raw.filePath + '/' +raw.fileName file = open(filePath) # Read data = file.read() # Close file.close() fileData.append(data) except Exception: submittedFileRecords = [] fileData = [] return render_template(HTMLResources().const.SUBMISSION_CODE_HTML, SETResources = SETResources, SessionResources = SessionResources, LanguageResources = LanguageResources, submittedFileRecords = submittedFileRecords, fileData = fileData, problemName = problemName, problemSolvedMemberRecords = problemSolvedMemberRecords, error = error) #Access Rejection else: flash('코드를 볼 권한이 없습니다!!!') return redirect(url_for(RouteResources().const.PROBLEM_RECORD, courseId = courseId, problemId = problemId, sortCondition = OtherResources().const.RUN_TIME)) except Exception: return unknown_error()