Пример #1
0
def castVote(conn, curr, pid, uid):
    '''
    Prompt the user to cast a vote to the selected post.

    Inputs: 
        conn -- sqlite3.Connection
        curr -- sqllite3.Connection
        pid -- selected post (str)
        uid -- uid of the current user (str)
    '''
    print('\n' + bcolor.pink('< Vote on the Post >'))

    prompt = 'Do you want to vote on this post? [y/n] '
    confirm = page.getValidInput(prompt, ['y', 'n'])

    if confirm == 'y':
        # checks if the user has already voted for the selected post
        curr.execute('SELECT * FROM votes WHERE pid = ? and uid = ?;',
                     [pid, uid])

        if curr.fetchone():
            print(
                bcolor.errmsg(
                    "action failed: you've already voted for this post."))
        else:
            vdate = str(date.today())
            vno = getVno(curr)

            curr.execute('INSERT INTO votes VALUES (?, ?, ?, ?);',
                         [pid, vno, vdate, uid])
            conn.commit()

            print()
            print(bcolor.green('Voting Completed!'))
Пример #2
0
def getPInfo(curr):
    '''
    Create a new post.
    Prompt the user for the post information and return it.
    A unique pid is generated and assigned to the new post.

    Input: 
        curr -- sqllite3.Connection
    Return:
        postInfo -- list 
    '''
    while True:
        pid = genPid(curr)
        pdate = str(date.today())
        print()
        title = input("Enter your title: ")
        body = input("Enter your body: ")

        postInfo = [pid, pdate, title, body]

        print('\nPlease double check your information: ')
        print('   Title: {}'.format(title))
        print('   Body: {}'.format(body))
        print()

        prompt = 'Is this correct? [y/n] '
        uin = page.getValidInput(prompt, ['y', 'n'])
        if uin == 'y':
            return postInfo
        else:
            prompt = 'Do you still want to make a post? [y/n] '
            if not page.continueAction(prompt):
                return False
Пример #3
0
def displaySearchResult(resultTable, isPriv):
    '''
    Display 5 posts at a time from the search result.
    Prompt the user to select a post and choose an action to take on.
    Return the index of the selected post and the type of the selected action.

    Inputs:
        resultTable -- list
        isPriv -- bool
    Returns:
        no -- int
        action -- str
    '''
    currRowIndex = 0
    numRows = len(resultTable)
    no = action = domain = None
    validEntries = []
    choseAction = False

    while not choseAction and currRowIndex < numRows:
        currRowIndex = printSearchResult(resultTable, currRowIndex)

        domain = '1-{}'.format(currRowIndex) if currRowIndex > 1 else '1'
        remainingRows = numRows - currRowIndex

        if remainingRows > 0:
            suffix = 's' if remainingRows > 1 else ''
            print("There are {} more row{} to display.\n".format(
                remainingRows, suffix))
            prompt = "Press enter to view more, or pick no. [{}] to select: ".format(
                domain)
            validEntries = ['y', '']
        else:
            prompt = "Search hit bottom. Pick no. [{}] to select: ".format(
                domain)
            validEntries = []

        if len(domain) == 1:
            # there is only one post to choose.
            validEntries.append('1')
        else:
            end = domain.split('-')[1]
            validEntries += list(map(str, range(1, int(end) + 1)))

        opt = page.getValidInput(prompt, validEntries)

        # post is selected
        if opt.isdigit():
            no = int(opt) - 1  # to match zero-index array
            isQues = isQuestion(resultTable[no])
            action = getAction(isQues, isPriv)
            choseAction = True

    return no, action
Пример #4
0
def markAnswer(conn, curr, aid):
    '''
    Mark the selected answer post as accepted and update it into the database.
    Prompts the user whether to overwrite if an accepted answer already exists.

    inputs:
        conn -- sqlite3.Connection
        curr -- sqlite3.Cursor
        aid -- pid of answer post (str)
    '''

    print(bcolor.pink('\n< Mark as Accepted Answer >'))

    curr.execute("SELECT * FROM answers where pid=?;", (aid, ))
    qid = curr.fetchone()['qid']

    prompt = 'Do you want to mark this post as an accepted answer? [y/n] '
    uin = page.getValidInput(prompt, ['y','n'])

    if uin == 'y':

        curr.execute("SELECT * FROM questions where pid=? and theaid IS NOT NULL;", (qid, ))
        aaExists = True if curr.fetchone() else False       # aa: accepted answer
            
        if aaExists:
            prompt = bcolor.warning("Warning: Accepted answer already exists. Proceed to change? [y/n] ")
            uin = page.getValidInput(prompt, ['y','n'])
            if uin == 'y':
                changeAA(conn, curr, qid, aid)
                conn.commit()
            else:
                print('\nMarking answer is cancelled.')
    
        else:
            changeAA(conn, curr, qid, aid)
            conn.commit()
Пример #5
0
def addTag(conn, curr, pid):
    '''
    Add tags to the selected post.

    Inputs: 
        conn -- sqlite3.Connection
        curr -- sqllite3.Cursor
        pid -- pid of the selected post (str)
    '''
    print(bcolor.pink('\n< Add Tags >'))

    currentTags = getCurrentTag(curr, pid)
    displayCurrentTag(currentTags)
    
    valid = False
    while not valid:

        newTags = getValidTag()
        numNewTags = len(newTags)

        duplicates, nonDuplicates = getDuplicateTag(currentTags, newTags)
        numDups = len(duplicates)
        dsuffix = genSuffix(duplicates)
        
        tagsToAdd = True
        if numDups > 0:
            print(bcolor.errmsg('error: post already has the following tag{}: {}'.format(dsuffix, ', '.join(duplicates))))
            
            if numNewTags == numDups: # user enters duplicates only
                tagsToAdd = False
                prompt = 'Do you want to add another tag to the post? [y/n] '
                valid = not page.continueAction(prompt)
            else:
                newTags = nonDuplicates
        
        nsuffix = genSuffix(newTags)
        if tagsToAdd:
            prompt = 'Do you want to add: "{}" ? [y/n] '.format('", "'.join(newTags))
            uin = page.getValidInput(prompt, ['y','n'])
            
            if uin == 'y':
                valid = True
                insertTag(conn, curr, pid, newTags)
                print(bcolor.green("\nTag{} Added!".format(nsuffix)))
            else:
                prompt = 'Do you still want to add tags to the post? [y/n] '
                valid = not page.continueAction(prompt)
Пример #6
0
def giveBadge(conn, curr, uid):
    '''
    Gives a badge to the poster of the selected post.

    Inputs: 
        conn -- sqlite3.Connection
        curr -- sqlite3.Cursor
        uid -- poster of the selected post (str)
    '''
    bdate = str(date.today())

    if not badgeAvailable(curr):
        print(bcolor.errmsg("action failed: badge is not available now."))

    elif isBadgeGivenTdy(curr, uid, bdate):
        print(bcolor.errmsg("action failed: this poster has already received a badge today."))

    else:
        print(bcolor.pink('\n< Give a Badge >'))
        displayAvailBadges(curr)
        valid = False
        while not valid:

            bname = getBadge()
            badgeRow = getBadgeRow(curr, bname)
        
            if badgeRow:    # badge already exists
                prompt = 'Do you want to give badge: "{}" to the poster? [y/n] '.format(badgeRow['bname'])
                uin = page.getValidInput(prompt, ['y','n'])

                if uin == 'y':
                    curr.execute('INSERT INTO ubadges VALUES (?, ?, ?);',(uid, bdate, badgeRow['bname']))
                    conn.commit()
                    print(bcolor.green('\nBadge Awarded to the poster!'))
                    valid = True
            
            else:
                print(bcolor.errmsg('action failed: badge: "{}" is not available.'.format(bname)))

            if not valid:
                prompt = 'Do you still want to give a badge? [y/n] '
                valid = not page.continueAction(prompt)
Пример #7
0
def isChangeValid(nTitle, nBody):
    '''
    Prompt the user to double check the new title and body, and return True if they are valid.

    Inputs:
        nTitle -- str
        nBody -- str
    Return: 
        bool
    '''

    print("\nIs the following information correct?")
    print("\n   Title: {}".format(nTitle))
    print("\n   Body: {}".format(nBody))

    prompt = "\nType 'y' if it is correct. Type 'n' if you want to start over: "
    check = page.getValidInput(prompt, ['y', 'n'])
    if check == 'n':
        return False 
    return True 
Пример #8
0
def getAction(isQues, isPriv):
    '''
    Prompt the user for a post action and return it. 

    inputs:
        isQues -- bool
        isPriv -- bool
    Return:
        action -- str
    '''
    actionDict = availableActions(isQues, isPriv)

    print("Choose an option to:\n")
    for cmd, action in actionDict.items():
        print("   {0}: {1}".format(bcolor.bold(cmd), action))
    print()

    action = page.getValidInput('Enter a command: ', actionDict.keys())

    return action
Пример #9
0
def main(argv):
    '''
    The main loop of the program.

    Error codes:
        0: Success
        1: invalid command line argument
    '''
    db = getDBFrom(argv)
    conn, curr = initConnAndCurrFrom(db)

    try:
        os.system('clear')
        run = True
        while run:
            page.printFirstScreen() 

            opt = page.getValidInput('Enter a command: ', ['si', 'su', 'q'])
            if opt == 'si':
                uid = page.signIn(curr)
                os.system('clear')
                if uid != None:
                    page.mainMenu(conn, curr, uid)
            elif opt == 'su':
                page.signUp(conn, curr)
            else:
                run = False
        sys.exit(0)

    except SystemExit as e:
        if int(str(e)) > 0:
            print(traceback.format_exc())   
    except Exception as e:
        print(traceback.format_exc())
    finally:
        print("\nClosing connection...")
        conn.commit()
        conn.close()