Example #1
0
def to_process_written_code(pageNum, problemIndex):
    memberId = session[SessionResources().const.MEMBER_ID]
    memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]
    problemName = remove_space_in_problemName(problemIndex)
    filePath, tempPath = make_path(PATH, memberIdIndex, memberId, problemName)
    try:
        os.mkdir(tempPath)
        usedLanguageName, usedLanguageVersion, fileName = write_code_in_file(
            tempPath)
        fileSize = os.stat(os.path.join(tempPath, fileName)).st_size
        fileIndex = 1
        submissionIndex = get_submission_index(memberIdIndex, problemIndex)
        delete_submitted_files_data(submissionIndex)
        insert_submitted_files(submissionIndex, fileIndex, fileName, filePath,
                               fileSize)
        send_to_celery(memberIdIndex, problemIndex, submissionIndex,
                       usedLanguageName, usedLanguageVersion, fileSize,
                       problemName, filePath, tempPath)
        Log.info(OtherResources().const.WRITED_CODE_SUBMITTED)
    except OSError as e:
        Log.error(str(e))
        submit_error(tempPath, pageNum, OtherResources().const.FILE_ERROR)
    except Exception as e:
        dao.rollback()
        Log.error(str(e))
        print e
        submit_error(tempPath, pageNum, OtherResources().const.DB_ERROR)

    time.sleep(0.4)

    return page_move(pageNum)
Example #2
0
def sign_in():
    '''
    @@ Success sign in flash
    
    When the page redirected from sign up page,
    It display flash message.    
    '''
        
    """ main page before sign in"""
    error = None
    if request.method == 'POST':       
        error = check_user_info(request.form)
                    
    isLogin = len(session._get_current_object())
    if isLogin:
        isLogin = session[SessionResources().const.MEMBER_ID_INDEX]
        memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]
    else:
        memberIdIndex = None
        
    return render_template(HTMLResources().const.MAIN_HTML,
                           noticeRecords = select_notices(memberIdIndex,
                                                          isLogin),
                           topCoders = select_top_coder(),
                           error = error)
Example #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()
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 id_check(select, error=None):
    if request.method == 'POST':
        password = get_request_value(form=request.form, name='password')
        if password:
            check = select_member(memberIdIndex=session[
                SessionResources().const.MEMBER_ID_INDEX]).first()

            # 암호가 일치 할 때
            #Checking Success
            if len(password) <= 20\
               and check_password_hash (check.password,
                                        TripleDES.encrypt(str(password))):
                # for all user
                if select == 'account':
                    return redirect(
                        url_for(RouteResources().const.EDIT_PERSONAL))
                # server manager
                elif SETResources().const.ADMINISTRATOR in session[
                        SessionResources().const.AUTHORITY]:
                    if select == 'user_submit':
                        return redirect(url_for('.user_submit',
                                                pageNum=int(1)))
                    elif select == 'manage_problem':
                        return redirect(
                            url_for(
                                '.manage_problem',
                                problemLevel=LanguageResources().const.All[1],
                                pageNum=int(1)))
                    elif select == 'manage_problem_set':
                        return redirect(
                            url_for('.manage_problem_set',
                                    activeTabIndex=LanguageResources().const.
                                    All[1],
                                    pageNum=int(1)))
                    elif select == 'manage_user':
                        return redirect(
                            url_for(
                                '.manage_user',
                                sortCondition=LanguageResources().const.ID[1],
                                filterCondition=' ',
                                keyWord=' ',
                                pageNum=int(1)))
                    elif select == 'manage_service':
                        return redirect(url_for('.manage_service'))
                        # 암호가 일치 하지 않을 때
            else:
                error = LanguageResources().const.WrongPassword
        else:
            error = LanguageResources().const.WrongPassword

    return render_template(HTMLResources().const.ID_CHECK_HTML, error=error)
Example #6
0
def sign_in_newPage(to, params, error = None):

    if request.method == "POST":        
        error = check_user_info(request.form)
                    
    isLogin = len(session._get_current_object())
    if isLogin:
        isLogin = session[SessionResources().const.MEMBER_ID_INDEX]
    else:
        return render_template("signin.html")
    
    # params = {a:b, c:d}
    params = params[1:-1].encode('utf8').split(', ')
    tmp_params = params
    params = []
    
    for i in tmp_params:
        key, value = i.split(':')
        key = key.replace('\'', '')
        value = value.lstrip()
        
        if key == 'pageNum': key = 'page'
        
        params.append(key+'='+value)
    
    def getkey(item):
        return item.split('=')[0]
    
    params = sorted(params, key=getkey)
    params = '%26'.join(params) # %26 == &
    params = params.replace('u\'', '')
    params = params.replace('\'', '')
    
    return redirect(request.url_root+to+"%3F"+params) # %3F == ?
Example #7
0
def download_file():
    try:
        # Absolute Path
        directory = '/mnt/shared/Past/'
        # File Name StudentId_MemberName.zip
        filename = session[SessionResources().const.MEMBER_ID] + '_'\
        + session[SessionResources().const.MEMBER_NAME] + '.zip'

        Log.info(session[SessionResources().const.MEMBER_ID] \
                 + ' download '\
                 + directory\
                 + '/'  + filename)

        return send_from_directory(directory=directory, filename=filename)
    except Exception:
        pass
def unknown_error(error=None):
    from GradeServer.utils.utilArticleQuery import select_notices
    from GradeServer.utils.utilRankQuery import select_top_coder

    from GradeServer.resource.htmlResources import HTMLResources
    from GradeServer.resource.sessionResources import SessionResources

    #from GradeServer.GradeServer_logger import Log

    isLogin = len(session._get_current_object())
    if isLogin:
        isLogin = session[SessionResources().const.MEMBER_ID_INDEX]
        memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]
    else:
        memberIdIndex = None

    return render_template(HTMLResources().const.MAIN_HTML,
                           noticeRecords=select_notices(
                               memberIdIndex, isLogin),
                           topCoders=select_top_coder(),
                           error=error)
Example #9
0
def to_process_uploaded_files(problemIndex, pageNum, browserName,
                              browserVersion):
    memberId = session[SessionResources().const.MEMBER_ID]
    memberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]
    problemName = remove_space_in_problemName(problemIndex)
    filePath, tempPath = make_path(PATH, memberIdIndex, memberId, problemName)

    try:
        os.mkdir(tempPath)
        uploadFiles = request.files.getlist(OtherResources().const.GET_FILES)
        usedLanguageName = request.form[
            OtherResources().const.USED_LANGUAGE_NAME]
        usedLanguageVersion = request.form[
            OtherResources().const.USED_LANGUAGE_VERSION]
        submissionIndex = get_submission_index(memberIdIndex, problemIndex)
        sumOfSubmittedFileSize = file_save(submissionIndex, uploadFiles,
                                           tempPath, filePath)
        send_to_celery(memberIdIndex, problemIndex, submissionIndex,
                       usedLanguageName, usedLanguageVersion,
                       sumOfSubmittedFileSize, problemName, filePath, tempPath)
        Log.info(OtherResources().const.FILE_SUBMITTED)
    except OSError as e:
        Log.error(str(e))
        submit_error(tempPath, pageNum,
                     OtherResources().const.FILE_ERROR, browserName,
                     browserVersion)
    except Exception as e:
        dao.rollback()
        Log.error(str(e))
        print e
        submit_error(tempPath, pageNum,
                     OtherResources().const.DB_ERROR, browserName,
                     browserVersion)

    time.sleep(0.4)

    return page_move(pageNum, browserName, browserVersion)
Example #10
0
def check_user_info(request_form, error = None):
    checker = True
    language = {'kr':0, # default
                'en':1}
        
    for form in request_form:
            if "language" in form:
                checker = False
                lang = get_request_value(form = request.form,
                                         name = 'language')
                session['language'] = language[lang]
                
    if checker: 
        try:
            """ DB Password check """
            memberId = get_request_value(form = request.form,
                                         name = 'memberId')
            password = get_request_value(form = request.form,
                                         name = 'password')
            
            check = select_match_member_id(memberId = memberId).first()
            
            #Checking Success
            if memberId == memberId\
               and check_password_hash(check.password,
                                       TripleDES.encrypt(str(password))):
                #push Session Cache 
                session[SessionResources().const.MEMBER_ID_INDEX] = check.memberIdIndex
                session[SessionResources().const.MEMBER_ID] = memberId
                session[SessionResources().const.MEMBER_NAME] = check.memberName
                session[SessionResources().const.AUTHORITY] = list(check.authority)
                session[SessionResources().const.LAST_ACCESS_DATE] = datetime.now()
                
                # set default language
                session['language'] = language['kr']
                                            
                # Commit Exception
                try:
                    update_recent_access_date(session[SessionResources().const.MEMBER_ID_INDEX],
                                              datetime.now())
                    dao.commit()
                except Exception:
                    dao.rollback()
                    error = LanguageResources().const.DBFailed
            else:
                error = LanguageResources().const.WrongPassword
        # Not Exist MemberId
        except Exception:
            error = LanguageResources().const.WrongPassword
        # Return Login Page
        return error
Example #11
0
    def decorated_function(*args, **kwargs):
        try:
            session_key = \
                request.cookies.get(
                    current_app.config['SESSION_COOKIE_NAME'])

            if not (session.sid == session_key and session.__contains__(
                    SessionResources().const.MEMBER_ID)):
                session.clear()

                return redirect(
                    url_for(RouteResources().const.SIGN_IN_NEWPAGE,
                            to=f.__name__,
                            params=kwargs))

            return f(*args, **kwargs)

        except Exception:
            from GradeServer.utils.utilMessages import unknown_error

            return unknown_error()
Example #12
0
def manage_problem(problemLevel, pageNum, error=None):
    try:
        # Upload Problems Files
        if request.method == 'POST':
            if is_authority(session[SessionResources().const.AUTHORITY])[0]:
                error = post_problem(request)
            else:
                error = LanguageResources().const.GetOutHere

        # GET, POST 공통 사항
        problems = select_problems(None if problemLevel == LanguageResources().
                                   const.All[1] else problemLevel)

        try:
            count = select_count(problems.subquery().c.problemIndex).first().\
                                                          count

            problemRecords = get_page_record(problems, pageNum=pageNum).all()

        except Exception:
            count = 0
            problemRecords = []

        return render_template('/manage_problem.html',
                               types=[
                                   ENUMResources().const.SOLUTION,
                                   ENUMResources().const.CHECKER
                               ],
                               levels=[
                                   LanguageResources().const.GoldLevel,
                                   LanguageResources().const.SilverLevel,
                                   LanguageResources().const.BronzeLevel
                               ],
                               problemLevel=problemLevel,
                               problemRecords=problemRecords,
                               pages=get_page_pointed(pageNum, count),
                               error=error)
    except Exception as e:
        return unknown_error(e)
Example #13
0
def problem_list(pageNum):
    """ problem submitting page """
    try:
        # Get Last Submitted History
        lastSubmission = select_last_submissions(memberIdIndex=session[
            SessionResources().const.MEMBER_ID_INDEX]).subquery()

        # Current Submission
        submissions = select_submissions_result(lastSubmission).subquery()

        # Get Problem Informations
        problems = select_all_problems().subquery()

        # Get ProblemList Count
        # Get ProblemListRecords OuterJoin
        try:
            count = select_count(problems.c.problemIndex).first().\
                                                          count

            problemListRecords = get_page_record(
                join_problem_lists_submissions(problems, submissions),
                pageNum=pageNum).all()

        except Exception:
            count = 0
            problemListRecords = []

        # Get Course Information

        browserInformations = request.user_agent.string
        if browserInformations.find('Trident') == -1:
            if browserInformations.find('MSIE') == -1:
                browserVersion = ENUMResources().const.TRUE
            else:
                browserVersion = ENUMResources().const.FALSE
        elif int(browserInformations[browserInformations.find('Trident') +
                                     8]) < 6:
            browserVersion = ENUMResources().const.FALSE
        else:
            browserVersion = ENUMResources().const.TRUE
        wrongTestCaseText = {}
        for problemListRecord in problemListRecords:
            if problemListRecord.wrongTestCaseNumber != 0:
                try:
                    f = open(
                        make_wrong_test_case_path(
                            str(problemListRecord.problemPath),
                            str(problemListRecord.problemName),
                            str(problemListRecord.solutionCheckType),
                            str(problemListRecord.wrongTestCaseNumber)), "r")
                    temp = {problemListRecord.problemName: f.read()}
                    wrongTestCaseText.update(temp)
                    f.close()
                except:
                    pass

        return render_template(HTMLResources().const.PROBLEM_LIST_HTML,
                               problemListRecords=problemListRecords,
                               wrongTestCaseText=wrongTestCaseText,
                               browserVersion=browserVersion,
                               datetime=datetime.now(),
                               pages=get_page_pointed(pageNum=pageNum,
                                                      count=count))
    except Exception as e:
        return unknown_error(e)
Example #14
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)
Example #15
0
def problem_record(status, problemIndex, sortCondition, error=None):
    # Not Accept URL Check
    if sortCondition not in (LanguageResources().const.SubmissionDate[1],
                             LanguageResources().const.Memory[1],
                             LanguageResources().const.FileSize[1],
                             LanguageResources().const.Runtime[1]):
        return page_not_found()

    try:
        memberId = None
        # Request Post
        if request.method == 'POST':
            # Search Event
            if 'memberId' in request.form:
                memberId = get_request_value(form=request.form,
                                             name='memberId')

        # Chart View Value Text
        chartSubmissionDescriptions = [
            LanguageResources().const.TriedPeople,
            LanguageResources().const.SolvedPeople,
            LanguageResources().const.Count,
            LanguageResources().const.Solved,
            LanguageResources().const.WrongAnswer,
            LanguageResources().const.TimeOver,
            LanguageResources().const.MemoryOverflow,
            LanguageResources().const.CompileError,
            LanguageResources().const.RuntimeError
        ]

        # last Submissions of Problem Info
        lastSubmission = select_last_submissions(
            problemIndex=problemIndex).subquery()
        submissions = select_all_submissions(
            problemIndex=problemIndex,
            lastSubmission=lastSubmission).subquery()
        try:
            # Submitted Members Count
            sumOfSubmissionPeopleCount = select_submissions_peoples_counts(
                submissions).subquery()
            # Solved Members Count
            sumOfSolvedPeopleCount = select_solved_peoples_counts(
                submissions).subquery()
            # Problem Record
            problemSubmittedRecords = select_submitted_records_of_problem(
                problemIndex=problemIndex).subquery()
            # Chart SubmissionRecords
            chartSubmissionRecords = select_problem_chart_submissions(
                sumOfSubmissionPeopleCount, sumOfSolvedPeopleCount,
                problemSubmittedRecords).first()
        except Exception:
            chartSubmissionRecords = []

        # Problem Information (LimitedTime, LimitedMemory
        try:
            problemInformation = select_problem(
                problemIndex=problemIndex).first()
        except Exception:
            problemInformation = []

        # Problem Solved Users
        try:
            # Problem Solved Member
            problemSolvedMemberRecords = submissions_sorted(
                select_solved_submissions(submissions).subquery(),
                sortCondition=sortCondition).all()
        except Exception:
            problemSolvedMemberRecords = []

        # Search Failed Problem
        if status != ENUMResources().const.SOLVED\
           and status != ENUMResources().const.JUDGING\
           and status != ENUMResources().const.SERVER_ERROR:
            try:
                # last Submissions of Problem Info
                lastSubmission = select_last_submissions(
                    memberIdIndex=session[
                        SessionResources().const.MEMBER_ID_INDEX],
                    problemIndex=problemIndex).subquery()
                submissions = select_all_submissions(
                    memberIdIndex=session[
                        SessionResources().const.MEMBER_ID_INDEX],
                    problemIndex=problemIndex,
                    lastSubmission=lastSubmission).subquery()
                # Current Failed Problem
                failedProblem = select_failed_problems(submissions).first()
            except Exception:
                failedProblem = []
        else:
            failedProblem = []

        return render_template(
            HTMLResources().const.PROBLEM_RECORD_HTML,
            memberId=memberId,
            status=status,
            problemSolvedMemberRecords=problemSolvedMemberRecords,
            problemInformation=problemInformation,
            chartSubmissionDescriptions=chartSubmissionDescriptions,
            chartSubmissionRecords=chartSubmissionRecords,
            failedProblem=failedProblem,
            error=error)
    except Exception as e:
        return unknown_error(e)
def access_authority_check(problemLevel=None,
                           memberIdIndex=None,
                           submissionIndex=None,
                           problemIndex=None,
                           submissionReplyIndex=None,
                           articleIndex=None,
                           boardReplyIndex=None,
                           isAdministrator=None,
                           isWrite=None,
                           isCode=None):

    try:
        # Zero Index Check
        if memberIdIndex == 0\
           or problemIndex == 0\
           or submissionReplyIndex == 0\
           or (articleIndex == 0 and not isWrite)\
           or boardReplyIndex == 0:
            return False

        # Get Authority type Turple
        authority = is_authority(session[SessionResources().const.AUTHORITY])

        # Get my Index
        thisMemberIdIndex = session[SessionResources().const.MEMBER_ID_INDEX]

        # Authority check authority is turple, size 3
        if isAdministrator and authority[0]:
            if problemLevel\
                 and problemLevel not in (LanguageResources().const.GoldLevel[1],
                                          LanguageResources().const.SilverLevel[1],
                                          LanguageResources().const.BronzeLevel[1]):
                return False

            return True
        elif isAdministrator and not authority[0]:
            return False
        else:
            # Division Index
            if submissionIndex:
                submissionIndex = select_data_of_submission_board(
                    submissionIndex).first()
                memberIdIndex = submissionIndex.memberIdIndex
                problemIndex = submissionIndex.problemIndex

            # MemberIdIndex Check
            if memberIdIndex\
               and not select_member(memberIdIndex).first():
                return False

            if problemIndex\
               and not course_problem_check(isAdministrator,
                                            authority,
                                            memberIdIndex,
                                            problemIndex,
                                            thisMemberIdIndex,
                                            isCode):
                return False

            # Submission Reply Index check
            if submissionReplyIndex:
                replySubmissionIndex = select_replies_on_code(
                    submissionIndex=None,
                    submissionReplyIndex=submissionReplyIndex).first()
                replySubmissionIndex = select_data_of_submission_board(
                    replySubmissionIndex.submissionIndex).first()
                if not course_problem_check(isAdministrator, authority,
                                            replySubmissionIndex.memberIdIndex,
                                            replySubmissionIndex.problemIndex,
                                            thisMemberIdIndex, isCode):
                    return False

            # Board Check
            if articleIndex:
                article = select_article(articleIndex).first()
                if isWrite\
                   and article.writerIdIndex != thisMemberIdIndex:
                    return False
        # All Pass Authority
        return True
    except Exception as e:
        Log.error(str(e))
        return False
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 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))
Example #19
0
def manage_user(filterCondition, keyWord, sortCondition, pageNum, error=None):
    # Not Accept URL Check

    if sortCondition not in (LanguageResources().const.ID[1],
                             LanguageResources().const.Name[1]):
        return page_not_found()

    try:
        # Request Post
        if request.method == 'POST':
            # Search Event
            # FilterCondition
            if len(request.form) <= 2 and 'keyWord' in request.form:
                for form in request.form:
                    if 'keyWord' != form:
                        filterCondition = form
                        keyWord = get_request_value(form=request.form,
                                                    name='keyWord')
                        pageNum = 1

                        break
            elif is_authority(session[SessionResources().const.AUTHORITY])[0]:
                if 'memberDeleted' in request.form:
                    for form in request.form:
                        if 'member' not in form and 'keyWord' not in form:
                            memberIdIndex = form
                            # Get Folder Path
                            member = select_member(
                                memberIdIndex=memberIdIndex).first()

                            try:
                                update_member_deleted(memberIdIndex)
                                dao.commit()

                                userPath = '{0}/Current/{1}_{2}'.format(
                                    projectPath, member.memberId,
                                    member.memberName)
                                # Delete Folder
                                if os.path.exists(userPath):
                                    shutil.rmtree(userPath)
                            except Exception:
                                dao.rollback()
                                error = LanguageResources().const.DBFailed
                else:
                    for form in request.form:
                        # Insert Indivisual
                        if 'memberInsert' in form:
                            insertCount = int(form[len('memberInsert'):]) + 1

                            for i in range(1, insertCount):
                                # Get Input Data
                                detailInformation = get_request_value(
                                    form=request.form,
                                    name='detailInformation{0}'.format(i))
                                memberId = get_request_value(
                                    form=request.form,
                                    name='memberId{0}'.format(i))
                                memberName = get_request_value(
                                    form=request.form,
                                    name='memberName{0}'.format(i))

                                if memberId\
                                   and memberName:
                                    try:
                                        memberIdIndex = select_match_member_id(memberId).first().\
                                                                                         memberIdIndex
                                    except Exception:
                                        memberIdIndex = None
                                    try:
                                        error = insert_member_registration(
                                            memberIdIndex=memberIdIndex,
                                            memberId=memberId,
                                            memberName=memberName,
                                            password=generate_password_hash(
                                                TripleDES.encrypt(
                                                    str(memberId))),
                                            detailInformation=detailInformation
                                        )
                                        dao.commit()

                                        # Get Folder Path
                                        userPath = '{0}/Current/{1}_{2}'.format(
                                            projectPath, memberId, memberName)
                                        # make Folders
                                        if not os.path.exists(userPath):
                                            os.makedirs(userPath)
                                    except Exception:
                                        dao.rollback()
                                        error = LanguageResources(
                                        ).const.DBFailed
                                else:
                                    error = LanguageResources(
                                    ).const.FormValidation
            else:
                error = LanguageResources().const.GetOutHere

        # Get Users
        try:
            members = select_members().subquery()
            # Filter Case
            if filterCondition\
               and filterCondition != ' ':
                if not keyWord:
                    keyWord = ' '
                members = search_members(
                    members,
                    FilterFindParameter(filterCondition=filterCondition,
                                        keyWord=(keyWord if keyWord != ' ' else
                                                 ''))).subquery()
            count = select_count(members.c.memberIdIndex).first().\
                                                          count
            memberRecords = get_page_record(members_sorted(
                members, sortCondition),
                                            pageNum=pageNum)
        except Exception:
            count = 0
            memberRecords = []

        return render_template(
            '/manage_user.html',
            # 검색시 FilterCondition List
            Filters=[
                LanguageResources().const.All,
                LanguageResources().const.ID,
                LanguageResources().const.Name
            ],
            sortCondition=sortCondition,
            filterCondition=filterCondition,
            keyWord=keyWord,
            memberRecords=memberRecords,
            pages=get_page_pointed(pageNum, count),
            count=count,
            error=error)
    except Exception as e:
        return unknown_error(e)
def edit_personal(error=None):
    contactNumber, emailAddress, comment = None, None, None
    try:
        #Get User Information
        try:
            members = select_member(memberIdIndex=session[
                SessionResources().const.MEMBER_ID_INDEX]).subquery()
            memberInformation = select_member(
                memberIdIndex=members.c.memberIdIndex).first()
        except Exception:
            memberInformation = []

        #Get Post
        if request.method == 'POST':
            password = get_request_value(form=request.form, name='password')
            passwordConfirm = get_request_value(form=request.form,
                                                name='passwordConfirm')
            #Get Updating Data
            contactNumber = get_request_value(form=request.form,
                                              name='contactNumber')
            emailAddress = get_request_value(form=request.form,
                                             name='emailAddress')
            comment = get_request_value(form=request.form, name='comment')
            #Password Same
            if (password and passwordConfirm) and password == passwordConfirm:
                #Generate Password
                encryPassword = TripleDES.encrypt(str(password))
                passwordConfirm = None

                password = generate_password_hash(encryPassword)
                #Update DB
                update_members(
                    select_member(memberIdIndex=session[
                        SessionResources().const.MEMBER_ID_INDEX]), password,
                    contactNumber, emailAddress, comment)
            #Password Different
            elif not password and not passwordConfirm:
                #Update DB
                update_members(members=select_member(memberIdIndex=session[
                    SessionResources().const.MEMBER_ID_INDEX]),
                               password=None,
                               contactNumber=contactNumber,
                               emailAddress=emailAddress,
                               comment=comment)
            # Commit Exception
            try:
                dao.commit()

                return redirect(url_for(RouteResources().const.SIGN_IN))
            except Exception:
                dao.rollback()
                error = LanguageResources().const.DBFailed

        return render_template(HTMLResources().const.EDIT_PERSONAL_HTML,
                               memberInformation=memberInformation,
                               contactNumber=contactNumber,
                               emailAddress=emailAddress,
                               comment=comment,
                               error=error)
    except Exception as e:
        return unknown_error(e)