Пример #1
0
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
Пример #2
0
def insert_submitted_files(submissionIndex, fileIndex, fileName, filePath, fileSize):
    submittedFiles = SubmittedFiles(submissionIndex = submissionIndex,
                                    fileIndex = fileIndex,
                                    fileName = fileName,
                                    filePath = filePath,
                                    fileSize = fileSize)                
    dao.add(submittedFiles)
Пример #3
0
def code_reply_like_click(submissionReplyIndex):
    # 댓글 좋아요
    # 내가 Reply에 누른 좋아요 정보
    try:
        isReplyLike = select_replies_on_code_is_like(submissionReplyIndex,
                                                     memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]).first().\
                                                                                                                                         isLikeCancelled
    except Exception:
        # Non-Exist Case
        isReplyLike = None

        # 좋아요를 누른적 없을 때
    if not isReplyLike:
        # Insert Like
        dao.add(
            insert_likes_on_reply_of_code(
                submissionReplyIndex,
                memberIdIndex=session[
                    SessionResources().const.MEMBER_ID_INDEX]))
        # 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

        # Update Like
        update_replies_on_code_is_like(
            submissionReplyIndex,
            memberIdIndex=session[SessionResources().const.MEMBER_ID_INDEX],
            isLikeCancelled=isLikeCancelled)

    # Like or UnLIke
    update_replies_on_code_like_counting(submissionReplyIndex,
                                         LIKE_INCREASE=LIKE_INCREASE)
    try:
        dao.commit()

        # return like count
        try:
            count = select_replies_on_code(submissionIndex = None,
                                           submissionReplyIndex = submissionReplyIndex).first().\
                                                                                        sumOfLikeCount
        except Exception:
            count = 0

        return Response(str(count))
    except Exception:
        dao.rollback()

    return Response()
Пример #4
0
def insert_to_submissions(submissionIndex, submissionCount, solutionCheckCount, usedLanguageIndex, sumOfSubmittedFileSize):
    submissions = Submissions(submissionIndex = submissionIndex,
                              submissionCount = submissionCount,
                              solutionCheckCount = solutionCheckCount,
                              status = ENUMResources().const.JUDGING,
                              codeSubmissionDate = datetime.now(),
                              sumOfSubmittedFileSize = sumOfSubmittedFileSize,
                              usedLanguageIndex = usedLanguageIndex)
    dao.add(submissions)
def insert_submitted_files(memberId, courseId, problemId, fileIndex, fileName, filePath, fileSize):
    submittedFiles = SubmittedFiles(memberId = memberId,
                                    courseId = courseId,
                                    problemId = problemId,
                                    fileIndex = fileIndex,
                                    fileName = fileName,
                                    filePath = filePath,
                                    fileSize = fileSize)                
    dao.add(submittedFiles)
Пример #6
0
def article_like_click(articleIndex):
    # 게시글 좋아요  Push
    # 내가 게시글에 누른 좋아요 정보
    try:
        isLikeCancelled = select_article_is_like(articleIndex,
                                                 memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]).first().\
                                                                                                                    isLikeCancelled
    except Exception:
        # Non-Exist Case
        isLikeCancelled = None

        # 좋아요를 누른적 없을 때
    if not isLikeCancelled:
        # Insert Like
        dao.add(
            insert_likes_on_board(
                articleIndex,
                memberIdIndex=session[
                    SessionResources().const.MEMBER_ID_INDEX]))
        # 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 Like
        update_article_is_like(
            articleIndex,
            memberIdIndex=session[SessionResources().const.MEMBER_ID_INDEX],
            isLikeCancelled=isLikeCancelled)
    # Article 좋아요 갯수 올리기
    update_article_like_counting(articleIndex, LIKE_INCREASE=LIKE_INCREASE)

    try:
        dao.commit()
        # return like count
        try:
            count =  select_article(articleIndex = articleIndex).first().\
                                                                 sumOfLikeCount
        except Exception:
            count = 0

        return Response(str(count))
    except Exception:
        dao.rollback()

    return Response()
def code_reply_like_click(submissionReplyIndex):
        # 댓글 좋아요
        # 내가 Reply에 누른 좋아요 정보
    try:
        isReplyLike = select_replies_on_code_is_like(submissionReplyIndex,
                                                     memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]).first().\
                                                                                                                                         isLikeCancelled
    except Exception:
        # Non-Exist Case
        isReplyLike = None
        
                        # 좋아요를 누른적 없을 때
    if not isReplyLike:
        # Insert Like
        dao.add(insert_likes_on_reply_of_code(submissionReplyIndex,
                                              memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]))
        # 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
            
        # Update Like
        update_replies_on_code_is_like(submissionReplyIndex,
                                       memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX],
                                       isLikeCancelled = isLikeCancelled)
            
    # Like or UnLIke
    update_replies_on_code_like_counting(submissionReplyIndex,
                                         LIKE_INCREASE = LIKE_INCREASE)
    try:
        dao.commit()
        
        # return like count
        try:
            count = select_replies_on_code(submissionIndex = None,
                                           submissionReplyIndex = submissionReplyIndex).first().\
                                                                                        sumOfLikeCount
        except Exception:
            count = 0
        
        return Response(str(count))
    except Exception:
        dao.rollback()
        
    return Response()
def article_like_click(articleIndex):
        # 게시글 좋아요  Push
        # 내가 게시글에 누른 좋아요 정보
    try:
        isLikeCancelled = select_article_is_like(articleIndex,
                                                 memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]).first().\
                                                                                                                    isLikeCancelled
    except Exception:
        # Non-Exist Case
        isLikeCancelled = None
            
        # 좋아요를 누른적 없을 때
    if not isLikeCancelled:
        # Insert Like
        dao.add(insert_likes_on_board(articleIndex,
                                      memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]))
        # 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 Like
        update_article_is_like(articleIndex,
                               memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX],
                               isLikeCancelled = isLikeCancelled)
    # Article 좋아요 갯수 올리기
    update_article_like_counting(articleIndex,
                                 LIKE_INCREASE = LIKE_INCREASE)
    
    
    try:
        dao.commit()
        # return like count
        try:
            count =  select_article(articleIndex = articleIndex).first().\
                                                                 sumOfLikeCount
        except Exception:
            count = 0
        
        return Response(str(count))
    except Exception:
        dao.rollback()
        
    return Response()
def insert_to_submissions(courseId, memberId, problemId, submissionCount, solutionCheckCount, viewCount, usedLanguageIndex, sumOfSubmittedFileSize):
    submissions = Submissions(memberId = memberId,
                              problemId = problemId,
                              courseId = courseId,
                              submissionCount = submissionCount,
                              solutionCheckCount = solutionCheckCount,
                              viewCount = viewCount,
                              status = ENUMResources.const.JUDGING,
                              codeSubmissionDate = datetime.now(),
                              sumOfSubmittedFileSize = sumOfSubmittedFileSize,
                              usedLanguageIndex = usedLanguageIndex)
    dao.add(submissions)
Пример #10
0
def insert_into_departmentDetailsOfMembers(memberId, collegeIndex, departmentIndex):
    departmentInformation = DepartmentsDetailsOfMembers(memberId = memberId,
                                                        collegeIndex = int(collegeIndex),
                                                        departmentIndex = int(departmentIndex))
    dao.add(departmentInformation)

    try:
        dao.commit()
    except:
        dao.rollback()
        return False
            
    return True
Пример #11
0
def insert_team_member_id(teamName, teamMemberId, isTeamMaster = ENUMResources().const.FALSE):
    # if not exist Records then Insert
    if not dao.query(RegisteredTeamMembers).\
               filter(RegisteredTeamMembers.teamName == teamName,
                      RegisteredTeamMembers.teamMemberId == teamMemberId).\
               first():
        dao.add(RegisteredTeamMembers(teamName = teamName,
                                      teamMemberId = teamMemberId,
                                      isTeamMaster = isTeamMaster))
        dao.commit()
    # else then Update
    else:
        dao.query(RegisteredTeamMembers).\
            filter(RegisteredTeamMembers.teamName == teamName,
                   RegisteredTeamMembers.teamMemberId == teamMemberId).\
            update(dict(isDeleted = ENUMResources().const.FALSE,
                        isTeamMaster =isTeamMaster)) 
Пример #12
0
def insert_member_registration(memberIdIndex,
                               memberId,
                               memberName,
                               password,
                               detailInformation,
                               error=None):
    if memberIdIndex:
        # Duplication Registrations
        error = LanguageResources().const.Exist
    else:
        dao.add(
            insert_members(memberId=memberId,
                           memberName=memberName,
                           password=password,
                           signedInDate=datetime.now(),
                           detailInformation=detailInformation))

    return error
Пример #13
0
def get_submission_index(memberIdIndex, problemIndex):
                              
    try:
        submissionIndex = dao.query(DataOfSubmissionBoard.submissionIndex).\
                          filter(and_(DataOfSubmissionBoard.memberIdIndex == memberIdIndex,
                                      DataOfSubmissionBoard.problemIndex == problemIndex)).first().\
                          submissionIndex
    except:
        dataOfSubmissionBoard = DataOfSubmissionBoard(memberIdIndex = memberIdIndex,
                                                      problemIndex = problemIndex)
        
        dao.add(dataOfSubmissionBoard)
        dao.commit()

        submissionIndex = dao.query(DataOfSubmissionBoard.submissionIndex).\
                              filter(and_(DataOfSubmissionBoard.memberIdIndex == memberIdIndex,
                                          DataOfSubmissionBoard.problemIndex == problemIndex)).first().\
                              submissionIndex
    return submissionIndex
Пример #14
0
def insert_into_Members(memberId, password, memberName, authority, signedInDate, comment):
    '''
    @@ TODO
    
    Default authority is USER.
    So if you want to make an account for server administrator,
    you change the authority in database terminal.
    '''
    newMember = Members(memberId = memberId,
                        password = password,
                        memberName = memberName,
                        authority = authority,
                        signedInDate = signedInDate,
                        comment = comment)
    dao.add(newMember)
    try:
        dao.commit()
    except:
        dao.rollback()
        return False
    
    return True
def write(articleIndex, error = None):
    articleType, problemIndex, title, content, articlesOnBoard = None, None, None, None, None
    try:
        # Modify Case
        if articleIndex: 
            try:
                articlesOnBoard = select_article(articleIndex).subquery()
                articlesOnBoard = join_problems_name(subquery = articlesOnBoard,
                                                     subProblemIndex = articlesOnBoard.c.problemIndex).first()
            except Exception:
                articlesOnBoard = []
                        
                # 작성시 빈칸 검사
        if request.method == 'POST':
            if not articleIndex\
               or articlesOnBoard.writerIdIndex == session[SessionResources().const.MEMBER_ID_INDEX]:
                # Get ProblemIndex
                problemIndex = get_request_value(form = request.form,
                                                 name = 'problemIndex')
                # Get ArticleType
                articleType = get_request_value(form = request.form,
                                                name = 'articleType')
                                # 타이틀 가져오기
                title = get_request_value(form = request.form,
                                          name = 'title')
                # Get Exist Content
                content = get_request_value(form = request.form,
                                            name = 'content')
                
                # Success Post
                if title and len(title) <= 100\
                   and content:
                    updateDate = datetime.now()
                    updateIp = socket.gethostbyname(socket.gethostname())
                                    # 새로 작성
                    if not articleIndex:
                        newPost = insert_articles_on_board(problemIndex = problemIndex,
                                                           memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX],
                                                           articleType = articleType,
                                                           articleParameter = ArticleParameter(title = title,
                                                                                               content = content,
                                                                                               updateDate = updateDate,
                                                                                               updateIp = updateIp))
                        dao.add(newPost)
                        # Commit Exception
                        try:
                            dao.commit()
                        except exc.SQLAlchemyError:
                            dao.rollback()
                            error = LanguageResources().const.DBFailed
                            
                        return redirect(url_for(RouteResources().const.ARTICLE_BOARD,
                                                filterCondition = ' ',
                                                keyWord = ' ',
                                                pageNum = 1))
                                        # 게시물 수정    
                    else:
                                                # 수정 할 글 정보
                        update_article_modify(articleIndex,
                                              problemIndex = problemIndex,
                                              articleType = articleType,
                                              articleParameter = ArticleParameter(title = title,
                                                                                  content = content,
                                                                                  updateIp = updateIp,
                                                                                  updateDate = updateDate))
                        
                        # Commit Exception
                        try:
                            dao.commit()
                        except exc.SQLAlchemyError:
                            dao.rollback()
                            error = LanguageResources().const.DBFailed
                        
                        return redirect(url_for(RouteResources().const.ARTICLE_READ,
                                                articleIndex = articleIndex))
            else:
                error = LanguageResources().const.GetOutHere
                
        return render_template(HTMLResources().const.ARTICLE_WRITE_HTML,
                               articlesOnBoard = articlesOnBoard,
                               articleTypes = [ENUMResources().const.NOTICE,
                                               ENUMResources().const.QUESTION,
                                               ENUMResources().const.NORMAL],
                               articleType = articleType,
                               problemIndex = problemIndex,
                               title = title,
                               content = content,
                               error = error)
    except Exception as e:
        # Unknown Error
        return unknown_error(e)
def submission_code(memberIdIndex, status, problemIndex, error = None):
    try:
        # Get endDateOfSubmission of Problem
        # are Not Access. conditions is an Administrator and endOfSubmission ago
        if SETResources().const.ADMINISTRATOR in session[SessionResources().const.AUTHORITY]\
           or memberIdIndex == session[SessionResources().const.MEMBER_ID_INDEX]:
            
            # Get SubmissionIndex
            dataOfSubmissionBoard = select_data_of_submission_board(None,
                                                                    memberIdIndex,
                                                                    problemIndex)
            if dataOfSubmissionBoard.first():
                submissionIndex = dataOfSubmissionBoard.first().submissionIndex
                                # 내가 Code에 누른 좋아요 정보
                try:
                    isLikeCancelled = select_code_is_like(submissionIndex,
                                                          memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]).first().\
                                                          isLikeCancelled
                except Exception:
                    # Non-Exist Case
                    isLikeCancelled = None
            
                if request.method == 'POST':
                    authorityCheck = is_authority(session[SessionResources().const.AUTHORITY])
                    
                    for form in request.form:
                                        # 댓글 달기
                        if form == 'writeCodeReply':
                                                # 새로운 댓글 정보articleParameter
                            codeReplyContent = get_request_value(form = request.form,
                                                                 name = 'writeCodeReply')
                            
                            if codeReplyContent:
                                dao.add(insert_replies_on_code(submissionIndex,
                                                               memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX],
                                                               articleParameter = ArticleParameter(title = None,
                                                                                                   content = codeReplyContent,
                                                                                                   updateIp = socket.gethostbyname(socket.gethostname()),
                                                                                                   updateDate = datetime.now())))
                                # remove duplicated read count
                                update_code_view_reply_counting(submissionIndex,
                                                                VIEW_INCREASE = -1,
                                                                REPLY_INCREASE = 1)
                                
                            break 
                                                # 댓글 삭제   
                        elif 'deleteCodeReply' in form:
                            # Get Reply Index
                            replyIndex = len('deleteCodeReply')
                            submissionReplyIndex = int(form[replyIndex:])
                                                  
                            try:
                                writerIndex = select_replies_on_code(submissionIndex = None,
                                                                     submissionReplyIndex = submissionReplyIndex).first()
                            except Exception:
                                writerIndex = None
                            if (authorityCheck[0] or authorityCheck[1])\
                               or writerIndex.codeReplierIdIndex == session['memberIdIndex']:
                                    
                                update_replies_on_code_delete(submissionReplyIndex,
                                                              isDeleted = ENUMResources().const.TRUE)
                                # remove duplicated read count
                                update_code_view_reply_counting(submissionIndex,
                                                                VIEW_INCREASE = -1,
                                                                REPLY_INCREASE = -1)
                            else:
                                error = LanguageResources().const.GetOutHere
                            
                            break 
                        # Commit Modify
                        elif 'modifyCodeReplyContent' in form:
                            replyIndex = len('modifyCodeReplyContent')
                            submissionReplyIndex = int(form[replyIndex:])
                            try:
                                writerIndex = select_replies_on_code(submissionIndex = None,
                                                                     submissionReplyIndex = submissionReplyIndex).first()
                            except Exception:
                                writerIndex = None
                            if writerIndex.codeReplierIdIndex == session['memberIdIndex']:
                                submissionReplyContent = get_request_value(form = request.form,
                                                                           name = 'modifyCodeReplyContent{0}'.format(form[replyIndex:]))
                                
                                if submissionReplyContent:
                                    #update comment
                                    update_replies_on_code_modify(submissionReplyIndex,
                                                                  ArticleParameter(title = None,
                                                                                   content = submissionReplyContent,
                                                                                   updateIp = socket.gethostbyname(socket.gethostname()),
                                                                                   updateDate = datetime.now()))
                                    # remove duplicated read count
                                    update_code_view_reply_counting(submissionIndex,
                                                                    VIEW_INCREASE = -1)
                            else:
                                error = LanguageResources().const.GetOutHere
                                
                            break
                    # end Loop
                    # Commit Exception
                    try:
                        dao.commit()
                    except Exception:
                        dao.rollback()
                        error = LanguageResources().const.DBFailed
                
                try:
                    # replies 정보
                    repliesOnSubmissionRecords = select_replies_on_code(submissionIndex).subquery()
                    repliesOnSubmissionRecords = join_member_id(repliesOnSubmissionRecords,
                                                                repliesOnSubmissionRecords.c.codeReplierIdIndex)
                                        # 내가 게시글 리플에 누른 좋아요 정보
                    repliesOnSubmissionIsLikeRecords = select_replies_on_code_like(repliesOnSubmissionRecords.subquery(),
                                                                                   session[SessionResources().const.MEMBER_ID_INDEX]).all()
                    repliesOnSubmissionRecords = repliesOnSubmissionRecords.all()  
                except Exception:
                    repliesOnSubmissionIsLikeRecords = []
                    repliesOnSubmissionRecords = []
                    
                                # 읽은 횟수 카운팅
                update_code_view_reply_counting(submissionIndex,
                                                VIEW_INCREASE = 1)
                
                # Commit Exception
                try:
                    dao.commit()
                except Exception:
                    dao.rollback()
                    
                # Problem Information (LimitedTime, LimitedMemory
                try:
                    problemName = select_problem(problemIndex = problemIndex).first().\
                                                                              problemName
                except Exception:
                    problemName = None
                    
                # Problem Solved Users
                try:
                    # last Submissions Info
                    lastSubmission = select_last_submissions(memberIdIndex = memberIdIndex,
                                                             problemIndex = problemIndex).subquery()
                    problemSolvedMemberRecords = select_all_submissions(memberIdIndex = memberIdIndex,
                                                                        problemIndex = problemIndex,
                                                                        lastSubmission = lastSubmission).first()
                except Exception:
                    problemSolvedMemberRecords = []
                    
                # Submitted Files Information
                import codecs
                try:
                    submittedFileRecords = select_submitted_files(dataOfSubmissionBoard.subquery()).all()
                    fileData = []
                    
                    for raw in submittedFileRecords:
                        # Open
                        filePath = '{0}/{1}'.format(raw.filePath,
                                                    raw.fileName)
                        # EUC_KR type
                        try:
                            with codecs.open(filePath,
                                             'r',
                                             encoding = 'cp949') as f:
                                # Read
                                data = f.read()
                                fileData.append(data)
                        # UTF-8 Type
                        except Exception:
                            with codecs.open(filePath,
                                             'r',
                                             encoding = 'utf8') as f:
                                # Read
                                data = f.read()
                                fileData.append(data)
                except Exception:
                    submittedFileRecords = []
                    fileData = []
                    
                return render_template(HTMLResources().const.SUBMISSION_CODE_HTML,
                                       memberIdIndex = memberIdIndex,
                                       submissionIndex = submissionIndex,
                                       submittedFileRecords = submittedFileRecords,
                                       fileData = fileData,
                                       problemName = problemName,
                                       problemSolvedMemberRecords = problemSolvedMemberRecords,
                                       isLikeCancelled = isLikeCancelled,
                                       sumOfLikeCount = dataOfSubmissionBoard.first().\
                                                                              sumOfLikeCount,
                                       repliesOnSubmissionIsLikeRecords = repliesOnSubmissionIsLikeRecords,
                                       repliesOnSubmissionRecords = repliesOnSubmissionRecords,
                                       browserName = request.user_agent.browser,
                                       browserVersion = request.user_agent.version,
                                       error = error)
        #Access Rejection
        else:
            return redirect(url_for(RouteResources().const.PROBLEM_RECORD,
                                    status = status,
                                    problemIndex = problemIndex,
                                    sortCondition = LanguageResources().const.SubmissionDate[1]))
    except Exception as e:
        return unknown_error(e)
Пример #17
0
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()
Пример #18
0
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))
Пример #19
0
def class_manage_problem():
    global projectPath
    global newProblems
    
    modalError = None

    error, allProblems = get_all_problems()
    if error:
        return render_template('/class_manage_problem.html',
                               error = error, 
                               SETResources = SETResources,
                               SessionResources = SessionResources,
                               LanguageResources = LanguageResources,
                               modalError = error,
                               allProblems = [],
                               ownCourses = [],
                               ownProblems = [])
    
    ownCourses = get_own_courses(session[SessionResources().const.MEMBER_ID])
    ownProblems = get_own_problems(session[SessionResources().const.MEMBER_ID])
        
    if request.method == 'POST':
        isNewProblem = True
        numberOfNewProblems = (len(request.form)-1)/7
        keys = {'courseId':0,
                'courseName':1,
                'problemId':2,
                'problemName':3,
                'isAllInputCaseInOneFile':4,
                'startDate':5,
                'endDate':6,
                'openDate':7,
                'closeDate':8}
        
        # courseId,courseName,problemId,problemName,isAllInputCaseInOneFile,startDate,endDate,openDate,closeDate
        newProblem = [['' for _ in range(len(keys.keys()))] for __ in range(numberOfNewProblems+1)]
        for form in request.form:
            if DELETE in form:
                isNewProblem = False
                courseId,problemId = form.split('_')[1:]
                if delete_registered_problem(courseId, problemId):
                    break
                                    
            elif EDIT in form:
                isNewProblem = False
                editTarget,courseId,problemId,targetData = form[5:].split('_')
                targetData = request.form[form]

                # actually editTarget is 'id' value of tag. 
                # That's why it may have 'Tab' at the last of id to clarify whether it's 'all' tab or any tab of each course.
                # so when user pushes one of tab and modify the data,then we need to re-make the editTarget 
                if TAB in editTarget:
                    editTarget = editTarget[:-3]
                for registeredProblem, registeredCourse, problemName in ownProblems:
                    if registeredCourse.courseId == courseId and\
                       registeredProblem.problemId == int(problemId):
                        kwargs = { editTarget : targetData }
                        if update_registered_problem_info(courseId, problemId, dict(**kwargs)):
                            break
                                                
            # addition problem
            else:
                value,index = re.findall('\d+|\D+',form)
                index = int(index)
                data = request.form[form]
                newProblem[index-1][keys[value]] = data
        
        if error:
            return render_template('/class_manage_problem.html',
                                   error = error, 
                                   SETResources = SETResources,
                                   SessionResources = SessionResources,
                                   LanguageResources = LanguageResources,
                                   modalError = modalError,
                                   allProblems = allProblems,
                                   ownCourses = ownCourses,
                                   ownProblems = ownProblems)
            
        # when 'add' button is pushed,insert new problem into RegisteredProblems table
        if isNewProblem:
            for index in range(numberOfNewProblems+1):
                newProblems.append(newProblem[index])
            for problem in newProblems:
                # if openDate,closeDate are empty then same with startDate,endDate
                
                if not problem[keys['openDate']]:
                    problem[keys['openDate']] = problem[keys['startDate']]
                    
                if not problem[keys['closeDate']]:
                    problem[keys['closeDate']] = problem[keys['endDate']]
                    
                if not problem[keys['isAllInputCaseInOneFile']]:
                    problem[keys['isAllInputCaseInOneFile']] = ENUMResources().const.FALSE
                else:
                    problem[keys['isAllInputCaseInOneFile']] = ENUMResources().const.TRUE
                    
                if problem[keys['courseId']]:
                    problem[keys['courseId']],problem[keys['courseName']] = problem[keys['courseId']].split(' ',1)
                    
                if problem[keys['problemId']]:
                    problem[keys['problemId']],problem[keys['problemName']] = problem[keys['problemId']].split(' ',1)
                    try:
                        solutionCheckType = dao.query(Problems).\
                                                filter(Problems.problemId == problem[keys['problemId']]).\
                                                first().solutionCheckType
                    except:
                        error = 'error has been occurred while getting solution check type'
                        return render_template('/class_manage_problem.html',
                                               error = error, 
                                               SETResources = SETResources,
                                               SessionResources = SessionResources,
                                               LanguageResources = LanguageResources,
                                               modalError = modalError,
                                               allProblems = allProblems,
                                               ownCourses = ownCourses,
                                               ownProblems = ownProblems)
                    
                    pathOfTestCase = '%s/%s_%s/%s_%s_%s' % (problemsPath,
                                                            problem[keys['problemId']],
                                                            problem[keys['problemName']],
                                                            problem[keys['problemId']],
                                                            problem[keys['problemName']],
                                                            solutionCheckType)

                    numberOfTestCase = get_case_count(pathOfTestCase, problem[keys['isAllInputCaseInOneFile']])
                                    
                # validation check before insert new problem
                isValid = True
                for key in problem:
                    if not key:
                        isValid = False
                        break
                    
                if not isValid:
                    continue

                newProblem = RegisteredProblems(problemId = problem[keys['problemId']],
                                                courseId = problem[keys['courseId']],
                                                isAllInputCaseInOneFile = problem[keys['isAllInputCaseInOneFile']],
                                                limittedFileSize = limitedFileSize,
                                                numberOfTestCase = numberOfTestCase,
                                                startDateOfSubmission = problem[keys['startDate']],
                                                endDateOfSubmission = problem[keys['endDate']],
                                                openDate = problem[keys['openDate']],
                                                closeDate = problem[keys['closeDate']])
                
                dao.add(newProblem)
                
                try:
                    dao.commit()
                except exc.SQLAlchemyError:
                    dao.rollback()
                    error = 'Error has been occurred while making a new problem'
                    return render_template('/class_manage_problem.html',
                                           error = error, 
                                           SETResources = SETResources,
                                           SessionResources = SessionResources,
                                           LanguageResources = LanguageResources,
                                           modalError = modalError,
                                           allProblems = allProblems,
                                           ownCourses = ownCourses,
                                           ownProblems = ownProblems)

                
                newProblemRecord = SubmittedRecordsOfProblems(problemId = problem[keys['problemId']],
                                                              courseId = problem[keys['courseId']])
                dao.add(newProblemRecord)
                
                try:
                    dao.commit()
                except exc.SQLAlchemyError:
                    dao.rollback()
                    error = 'Error has been occurred while creating new record'
                    return render_template('/class_manage_problem.html',
                                           error = error, 
                                           SETResources = SETResources,
                                           SessionResources = SessionResources,
                                           LanguageResources = LanguageResources,
                                           modalError = modalError,
                                           allProblems = allProblems,
                                           ownCourses = ownCourses,
                                           ownProblems = ownProblems)
                
            newProblems = []
                
            return redirect(url_for('.class_manage_problem'))
        
    ownProblems = get_own_problems(session[SessionResources().const.MEMBER_ID])
    
    return render_template('/class_manage_problem.html',
                           error = error, 
                           SETResources = SETResources,
                           SessionResources = SessionResources,
                           LanguageResources = LanguageResources,
                           modalError = modalError,
                           allProblems = allProblems,
                           ownCourses = ownCourses,
                           ownProblems = ownProblems)
Пример #20
0
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()
Пример #21
0
def class_add_user():
    global newUsers
    error = None
    targetUserIdToDelete = []
    authorities = ['Course Admin','User']
    keys = {'memberId':0,
            'memberName':1,
            'authority':2,
            'collegeIndex':3,
            'collegeName':4,
            'departmentIndex':5,
            'departmentName':6,
            'courseId':7}
    
    ownCourses = get_own_courses(session[SessionResources().const.MEMBER_ID])

    if error:
        return render_template('/class_add_user.html',
                               error = error, 
                               SETResources = SETResources,
                               SessionResources = SessionResources,
                               LanguageResources = LanguageResources,
                               ownCourses = [],
                               allUsers = [],
                               allColleges = [],
                               allDepartments = [],
                               authorities = authorities,
                               newUsers = newUsers)
        
    try:
        allUsers = (dao.query(Members,
                              Colleges,
                              Departments).\
                        join(DepartmentsDetailsOfMembers,
                             Members.memberId == DepartmentsDetailsOfMembers.memberId).\
                        join(Colleges,
                             DepartmentsDetailsOfMembers.collegeIndex == Colleges.collegeIndex).\
                        join(Departments,
                             DepartmentsDetailsOfMembers.departmentIndex == Departments.departmentIndex).\
                        filter(or_(Members.authority == SETResources().const.USER,
                                   Members.authority == SETResources().const.COURSE_ADMINISTRATOR)).\
                        group_by(Members.memberId)).\
                   all()
    except:
        error = 'Error has been occurred while searching all users'
        return render_template('/class_add_user.html',
                               error = error, 
                               SETResources = SETResources,
                               SessionResources = SessionResources,
                               LanguageResources = LanguageResources,
                               ownCourses = ownCourses,
                               allUsers = [],
                               allColleges = [],
                               allDepartments = [],
                               authorities = authorities,
                               newUsers = newUsers)
    
    allColleges = get_colleges()
    
    
    try:
        allDepartments = (dao.query(DepartmentsOfColleges,
                                    Colleges,
                                    Departments).\
                              join(Colleges,
                                   Colleges.collegeIndex == DepartmentsOfColleges.collegeIndex).\
                              join(Departments,
                                   Departments.departmentIndex == DepartmentsOfColleges.departmentIndex).\
                              filter(Colleges.isAbolished == SETResources().const.FALSE).\
                              filter(Departments.isAbolished == SETResources().const.FALSE)).\
                         all()
    except:
        error = 'Error has been occurred while searching all departments'
        return render_template('/class_add_user.html',
                               error = error, 
                               SETResources = SETResources,
                               SessionResources = SessionResources,
                               LanguageResources = LanguageResources,
                               ownCourses = ownCourses,
                               allUsers = allUsers,
                               allColleges = allColleges,
                               allDepartments = allDepartments,
                               authorities = authorities,
                               newUsers = newUsers)
    
    if request.method == 'POST':
        if 'addIndivisualUser' in request.form:
            # ( number of all form data - 'addIndivisualUser' form ) / forms for each person(id,name,college,department,authority)
            numberOfUsers = (len(request.form) - 1) / 5
            newUser = [['' for _ in range(len(keys.keys()))] for __ in range(numberOfUsers + 1)]
            
            error, newUser = set_form_value_into_array(keys, request.form, newUser)
                
            if error:
                return render_template('/class_add_user.html',
                                       error = error, 
                                       SETResources = SETResources,
                                       SessionResources = SessionResources,
                                       LanguageResources = LanguageResources,
                                       ownCourses = ownCourses,
                                       allUsers = allUsers,
                                       allColleges = allColleges,
                                       allDepartments = allDepartments,
                                       authorities = authorities,
                                       newUsers = newUsers)
                            
            for index in range(numberOfUsers):
                if check_validation(newUser[index]):
                    newUsers.append(newUser[index])
                
        elif 'addUserGroup' in request.form:
            files = request.files.getlist('files')
            courseId = request.form['courseId'].split()[0]
            
            error = set_array_from_file(files, keys, courseId)
            
            if error:
                return render_template('/class_add_user.html',
                                       error = error, 
                                       SETResources = SETResources,
                                       SessionResources = SessionResources,
                                       LanguageResources = LanguageResources,
                                       ownCourses = ownCourses,
                                       allUsers = allUsers,
                                       allColleges = allColleges,
                                       allDepartments = allDepartments,
                                       authorities = authorities,
                                       newUsers = newUsers)
                        
        elif 'addUser' in request.form:
            for newUser in newUsers:
                isExist = dao.query(Members).filter(Members.memberId == newUser[0]).first() 
                if not isExist:
                
                    if newUser[keys['authority']] == 'Course Admin':
                        newUser[keys['authority']] = SETResources().const.COURSE_ADMINISTRATOR
                            
                    tripleDes = initialize_tripleDes_class()
                    password = generate_password_hash(tripleDes.encrypt(str(newUser[keys['memberId']])))
                
                    # at first insert to 'Members'. Duplicated tuple will be ignored.
                    freshman = Members(memberId = newUser[keys['memberId']],
                                       password = password,
                                       memberName = newUser[keys['memberName']],
                                       authority = newUser[keys['authority']],
                                       signedInDate = datetime.now())
                    dao.add(freshman)
                    
                    try:
                        dao.commit()
                    except exc.SQLAlchemyError:
                        dao.rollback()
                        error = 'Error has been occurred while adding new users'
                        return render_template('/class_add_user.html',
                                               error = error, 
                                               SETResources = SETResources,
                                               SessionResources = SessionResources,
                                               LanguageResources = LanguageResources,
                                               ownCourses = ownCourses,
                                               allUsers = allUsers,
                                               allColleges = allColleges,
                                               allDepartments = allDepartments,
                                               authorities = authorities,
                                               newUsers = newUsers)
                        
                isExist = dao.query(Registrations).\
                              filter(and_(Registrations.memberId == newUser[keys['memberId']],
                                          Registrations.courseId == newUser[keys['courseId']].split()[0])).\
                              first()
                # new member
                if not isExist:
                    # then insert to 'Registrations'.
                    freshman = Registrations(memberId = newUser[keys['memberId']],
                                             courseId = newUser[keys['courseId']].split()[0])
                    dao.add(freshman)
                    
                    try:
                        dao.commit()
                    except exc.SQLAlchemyError:
                        dao.rollback()
                        error = 'Error has been occurred while registering new users'
                        return render_template('/class_add_user.html',
                                               error = error, 
                                               SETResources = SETResources,
                                               SessionResources = SessionResources,
                                               LanguageResources = LanguageResources,
                                               ownCourses = ownCourses,
                                               allUsers = allUsers,
                                               allColleges = allColleges,
                                               allDepartments = allDepartments,
                                               authorities = authorities,
                                               newUsers = newUsers)
                    
                    
                    departmentInformation = DepartmentsDetailsOfMembers(memberId = newUser[keys['memberId']],
                                                                        collegeIndex = newUser[keys['collegeIndex']],
                                                                        departmentIndex = newUser[keys['departmentIndex']])
                    dao.add(departmentInformation)
                    
                    try:
                        dao.commit()
                    except exc.SQLAlchemyError:
                        dao.rollback()
                # old member
                else:
                    # suppose the user's department is different with his registered information    
                    departmentInformation = DepartmentsDetailsOfMembers(memberId = newUser[keys['memberId']],
                                                                        collegeIndex = newUser[keys['collegeIndex']],
                                                                        departmentIndex = newUser[keys['departmentIndex']])
                    dao.add(departmentInformation)
                    try:
                        dao.commit()
                    except exc.SQLAlchemyError:
                        dao.rollback()
                        
                courseName = dao.query(RegisteredCourses).\
                                 filter(RegisteredCourses.courseId == newUser[keys['courseId']].split()[0]).\
                                 first().\
                                 courseName

                memberPath = '%s/%s/%s_%s/%s_%s' % (projectPath,
                                                    coursesPath,
                                                    newUser[keys['courseId']].split()[0],
                                                    courseName.replace(' ', ''),
                                                    newUser[keys['memberId']],
                                                    newUser[keys['memberName']].replace(' ', ''))
                
                if not os.path.exists(memberPath):
                    os.makedirs(memberPath)
                
            newUsers = [] # initialize add user list
            return redirect(url_for('.class_manage_user'))
            
        elif 'deleteUser' in request.form:
            for form in request.form:
                if not form is 'deleteUser':
                    targetUserIdToDelete.append(form)
                                    
        # if id list is not empty
        if len(targetUserIdToDelete) != 0:
            # each target user id
            for targetUser in targetUserIdToDelete:
                index = 0
                # each new user id
                for newUser in newUsers:
                    # if target id and new user id are same
                    if targetUser == newUser[keys['memberId']]:
                        del newUsers[index]
                        break
                    index += 1
    
    return render_template('/class_add_user.html',
                           error = error, 
                           SETResources = SETResources,
                           SessionResources = SessionResources,
                           LanguageResources = LanguageResources,
                           ownCourses = ownCourses,
                           allUsers = allUsers,
                           allColleges = allColleges,
                           allDepartments = allDepartments,
                           authorities = authorities,
                           newUsers = newUsers)
Пример #22
0
def submission_code(memberIdIndex, status, problemIndex, error=None):
    try:
        # Get endDateOfSubmission of Problem
        # are Not Access. conditions is an Administrator and endOfSubmission ago
        if SETResources().const.ADMINISTRATOR in session[SessionResources().const.AUTHORITY]\
           or memberIdIndex == session[SessionResources().const.MEMBER_ID_INDEX]:

            # Get SubmissionIndex
            dataOfSubmissionBoard = select_data_of_submission_board(
                None, memberIdIndex, problemIndex)
            if dataOfSubmissionBoard.first():
                submissionIndex = dataOfSubmissionBoard.first().submissionIndex
                # 내가 Code에 누른 좋아요 정보
                try:
                    isLikeCancelled = select_code_is_like(submissionIndex,
                                                          memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]).first().\
                                                          isLikeCancelled
                except Exception:
                    # Non-Exist Case
                    isLikeCancelled = None

                if request.method == 'POST':
                    authorityCheck = is_authority(
                        session[SessionResources().const.AUTHORITY])

                    for form in request.form:
                        # 댓글 달기
                        if form == 'writeCodeReply':
                            # 새로운 댓글 정보articleParameter
                            codeReplyContent = get_request_value(
                                form=request.form, name='writeCodeReply')

                            if codeReplyContent:
                                dao.add(
                                    insert_replies_on_code(
                                        submissionIndex,
                                        memberIdIndex=session[SessionResources(
                                        ).const.MEMBER_ID_INDEX],
                                        articleParameter=ArticleParameter(
                                            title=None,
                                            content=codeReplyContent,
                                            updateIp=socket.gethostbyname(
                                                socket.gethostname()),
                                            updateDate=datetime.now())))
                                # remove duplicated read count
                                update_code_view_reply_counting(
                                    submissionIndex,
                                    VIEW_INCREASE=-1,
                                    REPLY_INCREASE=1)

                            break
                            # 댓글 삭제
                        elif 'deleteCodeReply' in form:
                            # Get Reply Index
                            replyIndex = len('deleteCodeReply')
                            submissionReplyIndex = int(form[replyIndex:])

                            try:
                                writerIndex = select_replies_on_code(
                                    submissionIndex=None,
                                    submissionReplyIndex=submissionReplyIndex
                                ).first()
                            except Exception:
                                writerIndex = None
                            if (authorityCheck[0] or authorityCheck[1])\
                               or writerIndex.codeReplierIdIndex == session['memberIdIndex']:

                                update_replies_on_code_delete(
                                    submissionReplyIndex,
                                    isDeleted=ENUMResources().const.TRUE)
                                # remove duplicated read count
                                update_code_view_reply_counting(
                                    submissionIndex,
                                    VIEW_INCREASE=-1,
                                    REPLY_INCREASE=-1)
                            else:
                                error = LanguageResources().const.GetOutHere

                            break
                        # Commit Modify
                        elif 'modifyCodeReplyContent' in form:
                            replyIndex = len('modifyCodeReplyContent')
                            submissionReplyIndex = int(form[replyIndex:])
                            try:
                                writerIndex = select_replies_on_code(
                                    submissionIndex=None,
                                    submissionReplyIndex=submissionReplyIndex
                                ).first()
                            except Exception:
                                writerIndex = None
                            if writerIndex.codeReplierIdIndex == session[
                                    'memberIdIndex']:
                                submissionReplyContent = get_request_value(
                                    form=request.form,
                                    name='modifyCodeReplyContent{0}'.format(
                                        form[replyIndex:]))

                                if submissionReplyContent:
                                    #update comment
                                    update_replies_on_code_modify(
                                        submissionReplyIndex,
                                        ArticleParameter(
                                            title=None,
                                            content=submissionReplyContent,
                                            updateIp=socket.gethostbyname(
                                                socket.gethostname()),
                                            updateDate=datetime.now()))
                                    # remove duplicated read count
                                    update_code_view_reply_counting(
                                        submissionIndex, VIEW_INCREASE=-1)
                            else:
                                error = LanguageResources().const.GetOutHere

                            break
                    # end Loop
                    # Commit Exception
                    try:
                        dao.commit()
                    except Exception:
                        dao.rollback()
                        error = LanguageResources().const.DBFailed

                try:
                    # replies 정보
                    repliesOnSubmissionRecords = select_replies_on_code(
                        submissionIndex).subquery()
                    repliesOnSubmissionRecords = join_member_id(
                        repliesOnSubmissionRecords,
                        repliesOnSubmissionRecords.c.codeReplierIdIndex)
                    # 내가 게시글 리플에 누른 좋아요 정보
                    repliesOnSubmissionIsLikeRecords = select_replies_on_code_like(
                        repliesOnSubmissionRecords.subquery(), session[
                            SessionResources().const.MEMBER_ID_INDEX]).all()
                    repliesOnSubmissionRecords = repliesOnSubmissionRecords.all(
                    )
                except Exception:
                    repliesOnSubmissionIsLikeRecords = []
                    repliesOnSubmissionRecords = []

                    # 읽은 횟수 카운팅
                update_code_view_reply_counting(submissionIndex,
                                                VIEW_INCREASE=1)

                # Commit Exception
                try:
                    dao.commit()
                except Exception:
                    dao.rollback()

                # Problem Information (LimitedTime, LimitedMemory
                try:
                    problemName = select_problem(problemIndex = problemIndex).first().\
                                                                              problemName
                except Exception:
                    problemName = None

                # Problem Solved Users
                try:
                    # last Submissions Info
                    lastSubmission = select_last_submissions(
                        memberIdIndex=memberIdIndex,
                        problemIndex=problemIndex).subquery()
                    problemSolvedMemberRecords = select_all_submissions(
                        memberIdIndex=memberIdIndex,
                        problemIndex=problemIndex,
                        lastSubmission=lastSubmission).first()
                except Exception:
                    problemSolvedMemberRecords = []

                # Submitted Files Information
                import codecs
                try:
                    submittedFileRecords = select_submitted_files(
                        dataOfSubmissionBoard.subquery()).all()
                    fileData = []

                    for raw in submittedFileRecords:
                        # Open
                        filePath = '{0}/{1}'.format(raw.filePath, raw.fileName)
                        # EUC_KR type
                        try:
                            with codecs.open(filePath, 'r',
                                             encoding='cp949') as f:
                                # Read
                                data = f.read()
                                fileData.append(data)
                        # UTF-8 Type
                        except Exception:
                            with codecs.open(filePath, 'r',
                                             encoding='utf8') as f:
                                # Read
                                data = f.read()
                                fileData.append(data)
                except Exception:
                    submittedFileRecords = []
                    fileData = []

                return render_template(HTMLResources().const.SUBMISSION_CODE_HTML,
                                       memberIdIndex = memberIdIndex,
                                       submissionIndex = submissionIndex,
                                       submittedFileRecords = submittedFileRecords,
                                       fileData = fileData,
                                       problemName = problemName,
                                       problemSolvedMemberRecords = problemSolvedMemberRecords,
                                       isLikeCancelled = isLikeCancelled,
                                       sumOfLikeCount = dataOfSubmissionBoard.first().\
                                                                              sumOfLikeCount,
                                       repliesOnSubmissionIsLikeRecords = repliesOnSubmissionIsLikeRecords,
                                       repliesOnSubmissionRecords = repliesOnSubmissionRecords,
                                       browserName = request.user_agent.browser,
                                       browserVersion = request.user_agent.version,
                                       error = error)
        #Access Rejection
        else:
            return redirect(
                url_for(
                    RouteResources().const.PROBLEM_RECORD,
                    status=status,
                    problemIndex=problemIndex,
                    sortCondition=LanguageResources().const.SubmissionDate[1]))
    except Exception as e:
        return unknown_error(e)
def read(articleIndex, error = None):
    ''' when you push a title of board content '''
    try:
                # 내가 게시글에 누른 좋아요 정보
        try:
            isLikeCancelled = select_article_is_like(articleIndex,
                                                     memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]).first().\
                                                                                                                        isLikeCancelled
        except Exception:
            # Non-Exist Case
            isLikeCancelled = None
            
        if request.method == 'POST':
            authorityCheck = is_authority(session[SessionResources().const.AUTHORITY])
            for form in request.form:
                
                                # 댓글 달기
                if form == 'writeArticleReply':
                                        # 새로운 댓글 정보articleParameter
                    boardReplyContent = get_request_value(form = request.form,
                                                          name = 'writeArticleReply')
                    
                    if boardReplyContent:
                        dao.add(insert_replies_on_board(articleIndex,
                                                        session[SessionResources().const.MEMBER_ID_INDEX],
                                                        ArticleParameter(title = None,
                                                                         content = boardReplyContent,
                                                                         updateIp = socket.gethostbyname(socket.gethostname()),
                                                                         updateDate = datetime.now())))
                        # remove duplicated read count
                        update_view_reply_counting(articleIndex,
                                                   VIEW_INCREASE = -1,
                                                   REPLY_INCREASE = 1)
                        
                    break 
                                # 댓글 삭제   
                elif 'deleteArticleReply' in form:
                    # Get Reply Index
                    replyIndex = len('deleteArticleReply')
                    boardReplyIndex = int(form[replyIndex:])
                                          
                    try:
                        writerIndex = select_replies_on_board(articleIndex = None,
                                                              boardReplyIndex = boardReplyIndex).first()
                    except Exception:
                        writerIndex = None
                    if authorityCheck[0]\
                       or writerIndex.boardReplierIdIndex == session[SessionResources().const.MEMBER_ID_INDEX]:
                            
                        update_replies_on_board_delete(boardReplyIndex,
                                                       isDeleted = ENUMResources().const.TRUE)
                        # remove duplicated read count
                        update_view_reply_counting(articleIndex,
                                                   VIEW_INCREASE = -1,
                                                   REPLY_INCREASE = -1)
                    else:
                        error = LanguageResources().const.GetOutHere
                    
                    break 
                # Commit Modify
                elif 'modifyArticleReplyContent' in form:
                    replyIndex = len('modifyArticleReplyContent')
                    boardReplyIndex = int(form[replyIndex:])
                    try:
                        writerIndex = select_replies_on_board(articleIndex = None,
                                                              boardReplyIndex = boardReplyIndex).first()
                    except Exception:
                        writerIndex = None
                    if writerIndex.boardReplierIdIndex == session[SessionResources().const.MEMBER_ID_INDEX]:
                        boardReplyContent = get_request_value(form = request.form,
                                                              name = 'modifyArticleReplyContent{0}'.format(form[replyIndex:]))
                        
                        if boardReplyContent:
                            #update comment
                            update_replies_on_board_modify(boardReplyIndex,
                                                           ArticleParameter(title = None,
                                                                            content = boardReplyContent,
                                                                            updateIp = socket.gethostbyname(socket.gethostname()),
                                                                            updateDate = datetime.now()))
                            # remove duplicated read count
                            update_view_reply_counting(articleIndex,
                                                       VIEW_INCREASE = -1)
                    else:
                        error = LanguageResources().const.GetOutHere
                        
                    break
                
                            # 게시물 삭제
                elif form == 'deleteArticle':
                    try:
                        writerIndex = select_article(articleIndex = articleIndex).first()
                    except Exception:
                        writerIndex = None
                    if authorityCheck[0]\
                       or writerIndex.writerIdIndex == session[SessionResources().const.MEMBER_ID_INDEX]:
                        update_article_delete(articleIndex,
                                              isDeleted = ENUMResources().const.TRUE)                    
                        # Commit Exception
                        try:
                            dao.commit()
                        except Exception:
                            dao.rollback()
                            error = LanguageResources().const.DBFailed
                            
                        return redirect(url_for(RouteResources().const.ARTICLE_BOARD,
                                                filterCondition = ' ',
                                                keyWord = ' ',
                                                pageNum = 1))
                    else:
                        error = LanguageResources().const.GetOutHere
            # end Loop
            # Commit Exception
            try:
                dao.commit()
            except Exception:
                dao.rollback()
                error = LanguageResources().const.DBFailed
            
        # Get or Post
                # 게시글 정보
        try:
            articlesOnBoard = select_article(articleIndex).subquery()
                
            #Get ProblemName
            articlesOnBoard = join_problems_name(subquery = articlesOnBoard,
                                                 subProblemIndex = articlesOnBoard.c.problemIndex).subquery()
            # Get MemberId
            articlesOnBoard = join_member_id(articlesOnBoard,
                                             subMemberIdIndex = articlesOnBoard.c.\
                                                                                 writerIdIndex).first()
        except Exception:
            articlesOnBoard = []
            
        try:
            # replies 정보
            repliesOnBoardRecords = select_replies_on_board(articleIndex).subquery()
            # Get MemberId
            repliesOnBoardRecords = join_member_id(repliesOnBoardRecords,
                                                   subMemberIdIndex = repliesOnBoardRecords.c.\
                                                                                            boardReplierIdIndex)
                        # 내가 게시글 리플에 누른 좋아요 정보
            repliesOnBoardIsLikeRecords = select_replies_on_board_like(repliesOnBoardRecords.subquery(),
                                                                       memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]).all()
            repliesOnBoardRecords = repliesOnBoardRecords.all()  
        except Exception:
            repliesOnBoardIsLikeRecords = []
            repliesOnBoardRecords = []
            
                # 읽은 횟수 카운팅
        update_view_reply_counting(articleIndex,
                                   VIEW_INCREASE = 1)
        
        # Commit Exception
        try:
            dao.commit()
        except Exception:
            dao.rollback()
            
        return render_template(HTMLResources().const.ARTICLE_READ_HTML,
                               articlesOnBoard = articlesOnBoard,
                               repliesOnBoardRecords = repliesOnBoardRecords,
                               repliesOnBoardIsLikeRecords = repliesOnBoardIsLikeRecords,
                               isLikeCancelled = isLikeCancelled,
                               error = error)
    except Exception:
        # Exception View    
        return redirect(url_for(RouteResources().const.ARTICLE_BOARD,
                                pageNum = 1))
Пример #24
0
def read(articleIndex, error=None):
    ''' when you push a title of board content '''
    try:
        # 내가 게시글에 누른 좋아요 정보
        try:
            isLikeCancelled = select_article_is_like(articleIndex,
                                                     memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]).first().\
                                                                                                                        isLikeCancelled
        except Exception:
            # Non-Exist Case
            isLikeCancelled = None

        if request.method == 'POST':
            authorityCheck = is_authority(
                session[SessionResources().const.AUTHORITY])
            for form in request.form:

                # 댓글 달기
                if form == 'writeArticleReply':
                    # 새로운 댓글 정보articleParameter
                    boardReplyContent = get_request_value(
                        form=request.form, name='writeArticleReply')

                    if boardReplyContent:
                        dao.add(
                            insert_replies_on_board(
                                articleIndex, session[
                                    SessionResources().const.MEMBER_ID_INDEX],
                                ArticleParameter(title=None,
                                                 content=boardReplyContent,
                                                 updateIp=socket.gethostbyname(
                                                     socket.gethostname()),
                                                 updateDate=datetime.now())))
                        # remove duplicated read count
                        update_view_reply_counting(articleIndex,
                                                   VIEW_INCREASE=-1,
                                                   REPLY_INCREASE=1)

                    break
                    # 댓글 삭제
                elif 'deleteArticleReply' in form:
                    # Get Reply Index
                    replyIndex = len('deleteArticleReply')
                    boardReplyIndex = int(form[replyIndex:])

                    try:
                        writerIndex = select_replies_on_board(
                            articleIndex=None,
                            boardReplyIndex=boardReplyIndex).first()
                    except Exception:
                        writerIndex = None
                    if authorityCheck[0]\
                       or writerIndex.boardReplierIdIndex == session[SessionResources().const.MEMBER_ID_INDEX]:

                        update_replies_on_board_delete(
                            boardReplyIndex,
                            isDeleted=ENUMResources().const.TRUE)
                        # remove duplicated read count
                        update_view_reply_counting(articleIndex,
                                                   VIEW_INCREASE=-1,
                                                   REPLY_INCREASE=-1)
                    else:
                        error = LanguageResources().const.GetOutHere

                    break
                # Commit Modify
                elif 'modifyArticleReplyContent' in form:
                    replyIndex = len('modifyArticleReplyContent')
                    boardReplyIndex = int(form[replyIndex:])
                    try:
                        writerIndex = select_replies_on_board(
                            articleIndex=None,
                            boardReplyIndex=boardReplyIndex).first()
                    except Exception:
                        writerIndex = None
                    if writerIndex.boardReplierIdIndex == session[
                            SessionResources().const.MEMBER_ID_INDEX]:
                        boardReplyContent = get_request_value(
                            form=request.form,
                            name='modifyArticleReplyContent{0}'.format(
                                form[replyIndex:]))

                        if boardReplyContent:
                            #update comment
                            update_replies_on_board_modify(
                                boardReplyIndex,
                                ArticleParameter(title=None,
                                                 content=boardReplyContent,
                                                 updateIp=socket.gethostbyname(
                                                     socket.gethostname()),
                                                 updateDate=datetime.now()))
                            # remove duplicated read count
                            update_view_reply_counting(articleIndex,
                                                       VIEW_INCREASE=-1)
                    else:
                        error = LanguageResources().const.GetOutHere

                    break

                    # 게시물 삭제
                elif form == 'deleteArticle':
                    try:
                        writerIndex = select_article(
                            articleIndex=articleIndex).first()
                    except Exception:
                        writerIndex = None
                    if authorityCheck[0]\
                       or writerIndex.writerIdIndex == session[SessionResources().const.MEMBER_ID_INDEX]:
                        update_article_delete(
                            articleIndex, isDeleted=ENUMResources().const.TRUE)
                        # Commit Exception
                        try:
                            dao.commit()
                        except Exception:
                            dao.rollback()
                            error = LanguageResources().const.DBFailed

                        return redirect(
                            url_for(RouteResources().const.ARTICLE_BOARD,
                                    filterCondition=' ',
                                    keyWord=' ',
                                    pageNum=1))
                    else:
                        error = LanguageResources().const.GetOutHere
            # end Loop
            # Commit Exception
            try:
                dao.commit()
            except Exception:
                dao.rollback()
                error = LanguageResources().const.DBFailed

        # Get or Post
        # 게시글 정보
        try:
            articlesOnBoard = select_article(articleIndex).subquery()

            #Get ProblemName
            articlesOnBoard = join_problems_name(
                subquery=articlesOnBoard,
                subProblemIndex=articlesOnBoard.c.problemIndex).subquery()
            # Get MemberId
            articlesOnBoard = join_member_id(articlesOnBoard,
                                             subMemberIdIndex = articlesOnBoard.c.\
                                                                                 writerIdIndex).first()
        except Exception:
            articlesOnBoard = []

        try:
            # replies 정보
            repliesOnBoardRecords = select_replies_on_board(
                articleIndex).subquery()
            # Get MemberId
            repliesOnBoardRecords = join_member_id(repliesOnBoardRecords,
                                                   subMemberIdIndex = repliesOnBoardRecords.c.\
                                                                                            boardReplierIdIndex)
            # 내가 게시글 리플에 누른 좋아요 정보
            repliesOnBoardIsLikeRecords = select_replies_on_board_like(
                repliesOnBoardRecords.subquery(),
                memberIdIndex=session[
                    SessionResources().const.MEMBER_ID_INDEX]).all()
            repliesOnBoardRecords = repliesOnBoardRecords.all()
        except Exception:
            repliesOnBoardIsLikeRecords = []
            repliesOnBoardRecords = []

            # 읽은 횟수 카운팅
        update_view_reply_counting(articleIndex, VIEW_INCREASE=1)

        # Commit Exception
        try:
            dao.commit()
        except Exception:
            dao.rollback()

        return render_template(
            HTMLResources().const.ARTICLE_READ_HTML,
            articlesOnBoard=articlesOnBoard,
            repliesOnBoardRecords=repliesOnBoardRecords,
            repliesOnBoardIsLikeRecords=repliesOnBoardIsLikeRecords,
            isLikeCancelled=isLikeCancelled,
            error=error)
    except Exception:
        # Exception View
        return redirect(
            url_for(RouteResources().const.ARTICLE_BOARD, pageNum=1))
Пример #25
0
def write(articleIndex, error=None):
    articleType, problemIndex, title, content, articlesOnBoard = None, None, None, None, None
    try:
        # Modify Case
        if articleIndex:
            try:
                articlesOnBoard = select_article(articleIndex).subquery()
                articlesOnBoard = join_problems_name(
                    subquery=articlesOnBoard,
                    subProblemIndex=articlesOnBoard.c.problemIndex).first()
            except Exception:
                articlesOnBoard = []

                # 작성시 빈칸 검사
        if request.method == 'POST':
            if not articleIndex\
               or articlesOnBoard.writerIdIndex == session[SessionResources().const.MEMBER_ID_INDEX]:
                # Get ProblemIndex
                problemIndex = get_request_value(form=request.form,
                                                 name='problemIndex')
                # Get ArticleType
                articleType = get_request_value(form=request.form,
                                                name='articleType')
                # 타이틀 가져오기
                title = get_request_value(form=request.form, name='title')
                # Get Exist Content
                content = get_request_value(form=request.form, name='content')

                # Success Post
                if title and len(title) <= 100\
                   and content:
                    updateDate = datetime.now()
                    updateIp = socket.gethostbyname(socket.gethostname())
                    # 새로 작성
                    if not articleIndex:
                        newPost = insert_articles_on_board(
                            problemIndex=problemIndex,
                            memberIdIndex=session[
                                SessionResources().const.MEMBER_ID_INDEX],
                            articleType=articleType,
                            articleParameter=ArticleParameter(
                                title=title,
                                content=content,
                                updateDate=updateDate,
                                updateIp=updateIp))
                        dao.add(newPost)
                        # Commit Exception
                        try:
                            dao.commit()
                        except exc.SQLAlchemyError:
                            dao.rollback()
                            error = LanguageResources().const.DBFailed

                        return redirect(
                            url_for(RouteResources().const.ARTICLE_BOARD,
                                    filterCondition=' ',
                                    keyWord=' ',
                                    pageNum=1))
                        # 게시물 수정
                    else:
                        # 수정 할 글 정보
                        update_article_modify(
                            articleIndex,
                            problemIndex=problemIndex,
                            articleType=articleType,
                            articleParameter=ArticleParameter(
                                title=title,
                                content=content,
                                updateIp=updateIp,
                                updateDate=updateDate))

                        # Commit Exception
                        try:
                            dao.commit()
                        except exc.SQLAlchemyError:
                            dao.rollback()
                            error = LanguageResources().const.DBFailed

                        return redirect(
                            url_for(RouteResources().const.ARTICLE_READ,
                                    articleIndex=articleIndex))
            else:
                error = LanguageResources().const.GetOutHere

        return render_template(HTMLResources().const.ARTICLE_WRITE_HTML,
                               articlesOnBoard=articlesOnBoard,
                               articleTypes=[
                                   ENUMResources().const.NOTICE,
                                   ENUMResources().const.QUESTION,
                                   ENUMResources().const.NORMAL
                               ],
                               articleType=articleType,
                               problemIndex=problemIndex,
                               title=title,
                               content=content,
                               error=error)
    except Exception as e:
        # Unknown Error
        return unknown_error(e)
Пример #26
0
def post_problem(request, error=None):
    if 'upload' in request.form:
        files = request.files.getlist('files')
        # Get Fle Failed
        if not list(files)[0].filename:
            return LanguageResources().const.UploadingFileError

        # read each uploaded file(zip)
        for fileData in files:
            # create temporary path to store new problem before moving into 'Problems' folder
            tmpPath = '%s/tmp' % projectPath
            '''
            @@ Check and Delete temporary folder
            
            If temporary folder 'tmp' is exist, then it means it had an error at past request.
            So, remove the temporary folder 'tmp' first.
            '''
            if os.path.exists(tmpPath):
                try:
                    subprocess.call('rm -rf %s' % tmpPath, shell=True)
                except OSError:
                    return LanguageResources().const.DeleteFolderError

            # unzip file
            with zipfile.ZipFile(fileData, 'r') as z:
                z.extractall(tmpPath)

            try:
                rowProblemName = re.split('_|\.',
                                          os.listdir(tmpPath)[0])[0].\
                                             replace(' ', '\ ')
            except OSError:
                return LangaugeResources().const.ListingFilesError
            '''
            @@ Decode problem name
            
            If the problem zip's made on window environment, problem name's broken
            So it needs to be decoded by cp949
            '''
            problemName = str(rowProblemName.decode('cp949'))
            # if decoded name is the same with before decoding,
            # it means the file is not created on window environment
            isFromWindow = True if rowProblemName != problemName\
                           else False

            if isFromWindow:
                error = handle_file_came_from_window(rowProblemName,
                                                     problemName)
                if error: return error

            problemInformationPath = ('%s/%s.txt' %
                                      (tmpPath, problemName)).replace(
                                          '\ ', ' ')
            try:
                # 'open' command can handle space character without '\' mark,
                # Replace '\ ' to just space ' '
                problemInfoFile = open(problemInformationPath, 'r')
                problemInformation = problemInfoFile.read()

                try:
                    problemInfoFile.close()
                except IOError:
                    return LanguageResources().const.ClosingFileError

            except IOError:
                return LanguageResources().const.ReadingFileError
            '''
            @@ Decode problem meta information
            
            Problem meta information(.txt) file needs to be decoded as well as problem folder name
            '''
            if isFromWindow:
                problemInformation = problemInformation.decode('cp949')
            # slice and make key, value pairs from csv form
            problemInformation = problemInformation.replace(' ', '').split(',')
            if len(problemInformation) != 5:
                return LanguageResources().const.NotEnoughInfoError
            # re-slice and make information from 'key=value'
            for eachInformation in problemInformation:
                key, value = eachInformation.split('=')
                if key == 'Name':
                    # 'value' doesn't have a space character because of 'replace(' ', '')' command above
                    # Don't use 'value' for problem name
                    problemName = problemName.replace('\ ', ' ')
                elif key == 'Difficulty':
                    try:
                        problemDifficulty = int(value)
                    except ValueError:
                        return LanguageResources().const.DifficultyCharError
                elif key == 'SolutionCheckType':
                    solutionCheckType = ENUMResources().const.SOLUTION if value == 'Solution'\
                                        else ENUMResources().const.CHECKER
                elif key == 'LimitedTime':
                    limitedTime = int(value)
                elif key == 'LimitedMemory':
                    limitedMemory = int(value)
            # Insert new problem
            problemPath = '%s/%s' % (problemsPath, problemName.replace(
                ' ', ''))
            if not select_problem(
                    problemIndex=None,
                    problemName=problemName,
                    isDeleted=ENUMResources().const.TRUE).first():
                dao.add(
                    insert_problem(problemName, problemDifficulty,
                                   solutionCheckType, limitedTime,
                                   limitedMemory, problemPath))
            else:
                # Duplication Case
                update_problem_deleted(select_problem(problemIndex = None,
                                                      problemName = problemName,
                                                      isDeleted = ENUMResources().const.TRUE).first().\
                                                                                 problemIndex,
                                       isDeleted = ENUMResources().const.FALSE)

            newProblemPath='%s/%s_%s' %\
                           (tmpPath, problemName, solutionCheckType)
            if change_directory_to(newProblemPath): return

            try:
                # current path : ../tmp/problemName_solutionCheckType
                inOutCases=\
                    [filename for filename in os.listdir(os.getcwd())]
            except OSError:
                return LanguageResources().const.ListingFilesError

            for filename in inOutCases:
                rowFileName = filename
                fileName='%s_%s' %\
                         (problemName, rowFileName.split('_', 1)[1])

                if rename_file(rowFileName, str(fileName)): return
            '''
            @@ Changing directory/file name
            
            work flow
            1. Remove space on its name
                from> Hello World 
                to> HelloWorld
                
            2. Attach problem ID ahead of the name
                from> HelloWorld
                to> 12345_HelloWorld
                * 12345 is created problem id
            '''
            currentPath, error = get_current_path()
            if error: return error

            # inside of SOLUTION or CHECKER folder
            error = remove_space_from_names_in(currentPath)
            if error: return error

            # move to outside of the folder
            if change_directory_to(tmpPath): return error

            currentPath, error = get_current_path()
            if error: return error

            # inside of Problem folder
            error = remove_space_from_names_in(currentPath)
            if error: return error

            # create final goal path
            if not os.path.exists(problemPath):
                os.makedirs(problemPath)

            problemName = problemName.replace(' ', '')
            problemDescriptionPath = '%s/%s' % (problemDescriptionsPath,
                                                problemName)
            if not os.path.exists(problemDescriptionPath):
                os.makedirs(problemDescriptionPath)

            error = rename_file('%s/*' % tmpPath, '%s/' % problemPath)
            if error: return error

            try:
                subprocess.call('cp %s/%s.pdf %s/' %\
                                (problemPath, problemName,\
                                problemDescriptionPath), shell=True)
            except:
                return LanguageResources().const.NotExistPDF

            error = remove_carriage_return(problemPath + '/' + problemName +
                                           '_' + solutionCheckType)
            if error: return error

    # Modify or Deleted Case
    else:
        if 'problemModify' in request.form:
            # Seach ProblemIndex
            updateProblemCount, updateCount = len(request.form) / 5, 0

            for form in request.form:
                if updateProblemCount == updateCount:
                    break
                elif 'problem' not in form\
                      and 'limited' not in form:
                    updateCount = updateCount + 1
                    update_problem(
                        problemIndex=form,
                        problemDifficulty=request.form['problemDifficulty' +
                                                       form],
                        solutionCheckType=request.form['problemType' + form],
                        limitedTime=request.form['limitedTime' + form],
                        limitedMemory=request.form['limitedMemory' + form])
        elif 'problemDeleted' in request.form:
            # Get ProblemIndex
            for form in request.form:
                if 'problem' not in form:
                    update_problem_deleted(problemIndex=form)

    try:
        dao.commit()
        if 'upload' in request.form:
            # update numberOfTestCase
            problem = select_problem(problemIndex=None,
                                     problemName=problemName).first()
            testCasePath = '{0}/Problems/{1}/{2}_SOLUTION/'.format(
                projectPath, problem.problemName, problem.problemName)

            numberOfTestCase = len(
                fnmatch.filter(os.listdir(testCasePath), '*.txt')) / 2
            update_number_of_test_case(problem.problemIndex, numberOfTestCase)

            try:
                dao.add(
                    insert_submitted_records_of_problems(problem.problemIndex))

                dao.commit()
            except Exception:
                dao.rollback()
        elif 'problemDeleted' in request.form:
            # Get ProblemIndex
            for form in request.form:
                if 'problem' not in form:
                    # Delete Folder
                    problem = select_problem(
                        int(form),
                        isDeleted=ENUMResources().const.TRUE).first()
                    problemPath = '{0}/Problems/{1}/'.format(
                        projectPath, problem.problemName)
                    if os.path.exists(problemPath):
                        shutil.rmtree(problemPath)

    except exc.SQLAlchemyError:
        dao.rollback()
        error = LanguageResources().const.DBFailed

    return error