예제 #1
0
    def test_session_user(self):
        """The session_user procedure finds the name of the logged in
        user from the session cookie if present

        Test relies on working generate_session
        """

        # first test with no cookie
        nick_from_cookie = users.session_user(self.db)
        self.assertEqual(nick_from_cookie, None, "Expected None in case with no cookie, got %s" % str(nick_from_cookie))

        request.cookies[users.COOKIE_NAME] = 'fake sessionid'
        nick_from_cookie = users.session_user(self.db)

        self.assertEqual(nick_from_cookie, None, "Expected None in case with invalid session id, got %s" % str(nick_from_cookie))

        # run tests for all test users
        for password, nick, avatar in self.users:

            users.generate_session(self.db, nick)

            sessionid = self.get_cookie_value(users.COOKIE_NAME)

            request.cookies[users.COOKIE_NAME] = sessionid

            nick_from_cookie = users.session_user(self.db)

            self.assertEqual(nick_from_cookie, nick)
예제 #2
0
    def test_session_user(self):
        """The session_user procedure finds the name of the logged in
        user from the session cookie if present

        Test relies on working generate_session
        """

        # first test with no cookie
        nick_from_cookie = users.session_user(self.db)
        self.assertEqual(
            nick_from_cookie, None,
            "Expected None in case with no cookie, got %s" %
            str(nick_from_cookie))

        request.cookies[users.COOKIE_NAME] = 'fake sessionid'
        nick_from_cookie = users.session_user(self.db)

        self.assertEqual(
            nick_from_cookie, None,
            "Expected None in case with invalid session id, got %s" %
            str(nick_from_cookie))

        # run tests for all test users
        for password, nick, avatar in self.users:

            users.generate_session(self.db, nick)

            sessionid = self.get_cookie_value(users.COOKIE_NAME)

            request.cookies[users.COOKIE_NAME] = sessionid

            nick_from_cookie = users.session_user(self.db)

            self.assertEqual(nick_from_cookie, nick)
예제 #3
0
def index(db):

    # Get the top 10 users
    job_id = interface.position_list(db, 10)
    info = {'positions': job_id}
    name = users.session_user(db)
    if users.session_user(db):
        nick = {'nick': name}
        return template('index_login.html', nick)
    else:
        return template('index.html', info)
예제 #4
0
def index(db):
    """Passing positions data to the index.html page by calling the position_list function from interface.py
    sending that info to the index.html where it is separated and displayed accordingly.
    Returns the template along with the most recent 10 positions to be displayed in the homepage"""
    position = interface.position_list(db, 10)
    info = {
                'positions': position
            }
    if users.session_user(db):
        """If the user has logged in, then render "login_index" template. 
        Pass the username and avatar of the user to display in the template"""
        return template('login_index', info, user=users.session_user(db),
                        avatar=users.get_avatar(db, users.session_user(db)))
    else:
        return template('index.html', info)
예제 #5
0
def index():
    """Index of Psst site"""
    db = COMP249Db()
    username = session_user(db)
    loginString = ""
    content = ""
    http = ""
    str = ""
    avatar = ""
    list = interface.post_list(db, usernick=None, limit=50)

    # if user not logged in
    if not username:
        # display input field for username and password if the user not logged in
        loginString = "<h3>member login</h3><br><form id='loginform' method='POST' action ='/login'><input type='text' name='nick' placeholder='username' class='focus' onKeyPress='return submitenter(this,event)'><input type='password' name='password' placeholder='password' class='focus' onKeyPress='return submitenter(this,event)'></form>"

    # if user logged in
    if username:
        avatar = interface.user_avatar(db,username)
        # display the input field for adding posts instead of the title
        str = str + "<form action='/post' id='postform' method='POST'><input type='postfield' name='post' placeholder='post content, formats: [i]image urls[/i][t]title[/t][p]contents[/p]#tags #tags2' value='[i]image urls[/i][t]title[/t][p]contents[/p]#tags #tags2' class='focus' onKeyPress='return submitenter(this,event)'></form>"
        loginString = "<a href='/users/" + username + "'><img src='" + avatar + "'><h3 style='text-align:center; margin-left:0px;'>" + username + "</h3></a><br><form action= '/logout' id='logoutform' name='logoutform' method='POST' ><input type='submit' value='logout' class='sun-flower-button'></form>"

    for item in list:
        content = interface.post_to_html(item[3])
        http = interface.post_to_html(content)
        dt = datetime.datetime.strptime(item[1],"%Y-%m-%d %H:%M:%S")
        dt_string = dt.strftime("%b %d, %Y %I:%M%p").upper()
        str = str + "<div class='entry'><a href='/users/" + item[2] + "'><div class='item'><img src='" + item[4] + "'> <p>" + item[2].upper() + "</p></div></a><div class='date'><p>" + dt_string + "</p></div>" + http + "<hr></div>" # contents display

    return template('base.tpl', base=str, validate='', login=loginString)
예제 #6
0
    def test_single_like_per_user(self):
        """Tests if user has current like for an image in likes table.
        And if a like is stored, then tests that user can dislike - removing like(s)
        in the likes table under that user"""

        filename = self.images[0][0]

        for password, nick, avatar in self.users:
            users.generate_session(self.db, nick)
            sessionid = self.get_cookie_value(users.COOKIE_NAME)
            request.cookies[users.COOKIE_NAME] = sessionid
            user = users.session_user(self.db)

            # adds like if user has not yet liked the image
            if not interface.like_exists(self.db, filename, user):
                interface.add_like(self.db, filename, user)

            # there should be a like stored by the user for the image
            self.assertTrue(interface.like_exists(self.db, filename, user))

            # records current number of likes for the image
            like_count = interface.count_likes(self.db, filename)

            # unlike the image
            interface.unlike(self.db, filename, user)

            # checks that number of likes for image has decremented by 1
            # and that the user no longer likes the image
            self.assertTrue(like_count - 1,
                            interface.count_likes(self.db, filename))
            self.assertFalse(interface.like_exists(self.db, filename, user))
예제 #7
0
파일: main.py 프로젝트: rako210/Comp4050
def task(db):
    """"
    Will take the form from addtask.html and add the respective task to the database
    """
    userID = get_user_id(db)
    owner = users.session_user(db)
    title = request.forms.get("title")
    location = request.forms.get("location")
    description = request.forms.get("descrip")
    cost = request.forms.get("cost")
    category = request.forms.get("category")
    print(category)

    balanceCheck = database.deduct_accountBalance(db, owner, cost)
    if balanceCheck is False:
        return {
            'result':
            "False",
            'bannerMessage':
            'You do not have enough coins in your account to post this job, '
            'either complete jobs to gain coins or delete some of your other jobs'
        }

    # database.add_jobListing(db, userID, owner, title,
    #                        location, description, cost)
    database.add_jobListing(db, userID, owner, title, location, description,
                            cost, category)
    return {'result': "True", 'bannerMessage': "Task Successfully Added"}
예제 #8
0
파일: main.py 프로젝트: allandeee/FlowTow
def upload():
    """Request to Upload an image; When a user is logged in, they have the
    ability to upload an image of there choice. It must be of image file type.
    If it is not the right file type, they will be presented with the File error display.
    Otherwise, they will be redirected to the My Images page."""
    db = COMP249Db()

    curr_user = users.session_user(db)
    if not curr_user:
        redirect('/')

    imagefile = request.files.get('imagefile')
    name, ext = os.path.splitext(imagefile.filename)
    if ext not in ('.jpeg', '.jpg', '.png', '.gif'):
        print("extension error")
        return template('fileerror.html',
                        title="File Error",
                        session=None,
                        name=None)

    save_path = os.path.join(UPLOAD_DIR, imagefile.filename)
    imagefile.save(save_path)

    interface.add_image(db, imagefile.filename, curr_user)

    redirect('/my')
예제 #9
0
def registerSubmit():
    """
    注册用户填写完毕后提交请求
    :return:
    """
    flowTowDataBase = COMP249Db()
    userNick = users.session_user(db=flowTowDataBase)
    if userNick:
        registerInfo = "Please logout first"
        showRegister = False
    else:
        nick = request.POST.get("nick")
        password = request.POST.get("password")
        if users.add_user(flowTowDataBase, nick, password):
            registerInfo = "Registered successfully!You can login in the upper right corner now."
            showRegister = False
        else:
            registerInfo = "Registration failed, your registered user name already exists."
            showRegister = True
    renderDict = {
        "title": "FlowTow!",
        "homeActive": False,
        "aboutActive": False,
        "userNick": userNick,
        "myActive": False,
        "registerInfo": registerInfo,
        "showRegister": showRegister
    }
    return template("register", renderDict)
예제 #10
0
def search():
    """Search feature, can search user name and / or contents"""
    db = COMP249Db()
    username = session_user(db) # retrieve user session information from the database
    loginString = ""
    content = ""
    http = ""
    avatar = ""

    if 'search' in request.forms:
        search = request.forms['search'] # get user inputs from the search field
        str = "<h2>Search results for '" + search + "':</h2>" # title
        list = interface.post_list(db, usernick=None, limit=50)
        if not username: # display the things below only if user not logged in
            # display input field for username and password if the user not logged in
            loginString = "<h3>member login</h3></br><form id='loginform' method='POST' action ='/login'><input type='text' name='nick' placeholder='username' class='focus' onKeyPress='return submitenter(this,event)'><input type='password' name='password' placeholder='password' class='focus' onKeyPress='return submitenter(this,event)'></form>"

        if username: # display the things below only if user logged in
            avatar = interface.user_avatar(db,username)
            loginString = "<a href='/users/" + username + "'><img src='" + avatar + "'><h3 style='text-align:center; margin-left:0px;'>" + username + "</h3></a><br><form action= '/logout' id='logoutform' name='logoutform' method='POST' ><input type='submit' value='logout' class='sun-flower-button'></form>"

        for item in list:
            content = interface.post_to_html(item[3])
            http = interface.post_to_html(content)
            dt = datetime.datetime.strptime(item[1],"%Y-%m-%d %H:%M:%S")
            dt_string = dt.strftime("%b %d, %Y %I:%M%p").upper()
            if ((bool(search.lower() in item[2].lower())) | (bool(search.lower() in http.lower()))):
                str = str + "<div class='entry'><a href='/users/" + item[2] + "'><div class='item'><img src='" + item[4] + "'> <p>" + item[2].upper() + "</p></div></a><div class='date'><p>" + dt_string + "</p></div>" + http + "<hr></div>" # contents display

        return template('base.tpl', base=str, validate='', login=loginString)
예제 #11
0
    def test_single_like_per_user(self):
        """Tests if user has current like for an image in likes table.
        And if a like is stored, then tests that user can dislike - removing like(s)
        in the likes table under that user"""

        filename = self.images[0][0]

        for password, nick, avatar in self.users:
            users.generate_session(self.db, nick)
            sessionid = self.get_cookie_value(users.COOKIE_NAME)
            request.cookies[users.COOKIE_NAME] = sessionid
            user = users.session_user(self.db)

            # adds like if user has not yet liked the image
            if not interface.like_exists(self.db, filename, user):
                interface.add_like(self.db, filename, user)

            # there should be a like stored by the user for the image
            self.assertTrue(interface.like_exists(self.db, filename, user))

            # records current number of likes for the image
            like_count = interface.count_likes(self.db, filename)

            # unlike the image
            interface.unlike(self.db, filename, user)

            # checks that number of likes for image has decremented by 1
            # and that the user no longer likes the image
            self.assertTrue(like_count-1, interface.count_likes(self.db, filename))
            self.assertFalse(interface.like_exists(self.db, filename, user))
예제 #12
0
파일: main.py 프로젝트: jackdvpt/Psst
def search_page():
    """
    As a user i can search for the posts that have been made on the site
    Returns all posts that contain the search term.
    """
    db = PsstDb()
    post = request.query['search']
    type = request.query['adv']
    re = interface.post_search(db, post, type)
    advanced_message = ""
    if int(type) > 1:
        if type == '1':
            advanced_message = ' With the criteria that the post starts with it'
        elif type == '2':
            advanced_message = ' With the criteria that the post ends with it'
        elif type == '3':
            advanced_message = ' With the criteria that the post is an exact match'
    if len(re) > 0:
        contents = 'You have searched for "' + str(
            post) + '"' + advanced_message
    else:
        contents = 'Your search for "' + str(
            post) + '" has no results' + advanced_message
    user = {
        'login': has_visited(),
        'searchVal': str(post),
        'usernamed': users.session_user(db),
        'title': 'Search for "' + str(post) + '"',
        'content': contents,
        'posts': re
    }
    return template('index', user)
예제 #13
0
def mentions(username):
    """Generate the webpage that displays @users"""
    db = COMP249Db()
    uname = session_user(db) # retrieve user session information from the database
    loginString = ""
    content = ""
    http = ""
    list = interface.post_list_mentions(db, usernick=username, limit=50)
    str = ""
    avatar = ""

    str = "<h2>Posts mentioned " + username + ":</h2>" # title
    if not uname:
        # display input field for username and password if the user not logged in
        loginString = "<h3>member login</h3></br><form id='loginform' method='POST' action ='/login'><input type='text' name='nick' placeholder='username' class='focus' onKeyPress='return submitenter(this,event)'><input type='password' name='password' placeholder='password' class='focus' onKeyPress='return submitenter(this,event)'></form>"

    if uname:
        avatar = interface.user_avatar(db,uname)
        loginString = "<a href='/users/" + uname + "'><img src='" + avatar + "'><h3 style='text-align:center; margin-left:0px;'>" + uname + "</h3></a><br><form action= '/logout' id='logoutform' name='logoutform' method='POST' ><input type='submit' value='logout' class='sun-flower-button'></form>"

    for item in list:
        content = interface.post_to_html(item[3])
        http = interface.post_to_html(content)
        dt = datetime.datetime.strptime(item[1],"%Y-%m-%d %H:%M:%S")
        dt_string = dt.strftime("%b %d, %Y %I:%M%p").upper()
        str = str + "<div class='entry'><a href='/users/" + item[2] + "'><div class='item'><img src='" + item[4] + "'> <p>" + item[2].upper() + "</p></div></a><div class='date'><p>" + dt_string + "</p></div>" + http + "<hr></div>" # contents display

    return template('base.tpl', base=str, validate='', login=loginString)
예제 #14
0
파일: main.py 프로젝트: jackdvpt/Psst
def register():
    """
    As a user when i register for PSST! i should be told if any of my information is wrong
        Handels the forms for users registration
        Checks that the details are valid (not null, username doesnt have space)
        Then adds to the database
            If the username already exists it returns an page with an error
    """
    db = PsstDb()
    nickname = request.forms.get('username')
    password = request.forms.get('pass')
    picture = request.forms.get('pic')
    valid = users.checkValid(nickname, password, picture)
    if valid < 0:
        info = {
            'login': has_visited(),
            'searchVal': "",
            'usernamed': users.session_user(db),
            'title': "Welcome to Psst",
            'comment': 'Registration Failed',
            'posts': []
        }
        if valid == -1:
            info[
                'comment'] = 'Registration Failed, Looks like your username has something wrong with it'
        if valid == -2:
            info[
                'comment'] = 'Registration Failed, Looks like your password has something wrong with it'
        if valid == -3:
            info[
                'comment'] = 'Registration Failed, Looks like your picture has something wrong with it'
        return template('register', info)
    else:
        temp = users.add_user(db, nickname, password, picture)
        if temp == -1:
            info = {
                'login': has_visited(),
                'searchVal': "",
                'usernamed': users.session_user(db),
                'title': "Welcome to Psst",
                'content':
                'Registration Failed, Please try again. Error. Go back. Nothing more to see here. Youll need to try again (your username may already exist)',
                'posts': []
            }
            return template('index', info)
        else:
            redirect('/')
예제 #15
0
파일: main.py 프로젝트: jackdvpt/Psst
def login():
    """
    As a registered user when i wish to log out i see a button that will log me out of PSST!
    Removes the users session from the database then redirectes them to the homepage
    """
    db = PsstDb()
    users.delete_session(db, users.session_user(db))
    redirect('/')
예제 #16
0
def logout(db):
    # Method to logout.
    # First checking if the active user is logged in or not. If the user is logged in and has an active session, then
    # deleting the session from sessions table and redirecting to the index page.
    active_user = users.session_user(db)
    if active_user is not None:
        users.delete_session(db,active_user)
    return redirect("/")
예제 #17
0
def new_post():
    db = COMP249Db()
    message = request.forms.get('post')
    interface.post_add(db, users.session_user(db), message)

    response.set_header('Location', '/')
    response.status = 303
    return 'Redirect to /'
예제 #18
0
파일: main.py 프로젝트: m8ypie/fpmg-249-2
def logout():
    """ Removes cookie from user
    :return: The homepage
    """
    user = users.session_user(db)
    if user is not None:
        users.delete_session(db, user)
    redirect('/', 302)
예제 #19
0
def post_(db):
    usernick = session_user(db)
    company = request.forms.get('company')
    title = request.forms.get('title')
    location = request.forms.get('location')
    description = request.forms.get('description')
    position_add(db, usernick, title, location, company, description)
    redirect("/")
예제 #20
0
def new_post():
    db = COMP249Db()
    message = request.forms.get('post')
    interface.post_add(db, users.session_user(db), message)

    response.set_header('Location', '/')
    response.status = 303
    return 'Redirect to /'
예제 #21
0
파일: main.py 프로젝트: m8ypie/fpmg-249-2
def post():
    """ Saves provided post to database
    :return: Home page
    """
    content = request.forms.get("post")
    user = users.session_user(db)
    if user is not None:
        interface.post_add(db, user, content)
    redirect('/')
예제 #22
0
파일: main.py 프로젝트: jackdvpt/Psst
def index():
    """Home page, displays the welcome message and the most recent posts"""
    db = PsstDb()
    name = users.session_user(db)
    if users.follows(db, users.session_user(db)) > 0:
        re = interface.post_list_follows(db, users.get_following(db, name),
                                         name, 50)
    else:
        re = interface.post_list(db, None, 50)
    info = {
        'login': has_visited(),
        'searchVal': "",
        'usernamed': users.session_user(db),
        'title': "Welcome to Psst",
        'content': 'Welcome to Psst',
        'posts': re
    }
    return template('index', info)
예제 #23
0
def logout():
    """Logout"""
    db = COMP249Db()
    username = session_user(db) # retrieve user session information from the database
    if username:
        delete_session(db, username) # remove user session
        response.set_header('Location', '/')
        response.status = 303
        return "Redirect to /" # redirect to /
예제 #24
0
def post(db):
    name = users.session_user(db)
    title = request.forms.get('title')
    location = request.forms.get('location')
    company = request.forms.get('company')
    description = request.forms.get('description')

    interface.position_add(db, name, title, location, company, description)
    redirect('/')
예제 #25
0
def index():
    """Generate the main page of the app 
    with a list of the most recent posts"""

    db = COMP249Db()
    session_user = users.session_user(db)
    info = {'title': "¡Welcome to Psst!", 'posts': interface.post_list(db)}

    return template('index', info, session_user=session_user)
예제 #26
0
def logout():
    """
    处理登出
    :return:重定向至首页
    """
    flowTowDataBase = COMP249Db()
    requestUser = users.session_user(flowTowDataBase)
    users.delete_session(db=flowTowDataBase, usernick=requestUser)
    return redirect('/')
예제 #27
0
파일: main.py 프로젝트: allandeee/FlowTow
def aboutpg():
    """About page; Displays information on the Flowtow site."""
    db = COMP249Db()
    curr_session = None
    curr_user = None
    if request.get_cookie(COOKIE_NAME):
        curr_session = request.get_cookie(COOKIE_NAME)
        curr_user = users.session_user(db)
    return template('aboutpg.html', title="About", session=curr_session, name=curr_user)
예제 #28
0
def about(db):
    """
    :return: Returns a static template page about.html when the request is made to the server for route '/about.html'
    """
    active_user = users.session_user(db)
    message = dict() # Creating dictionary entry for message passing which can be accessed in html.
    message["user"] = active_user
    message["title"] = "About this site"
    return template("about", message=message)
예제 #29
0
def logout():
    """Logout"""
    db = COMP249Db()
    username = session_user(db) # retrieve user session information from the database
    if username:
        delete_session(db, username) # remove user session
        response.set_header('Location', '/')
        response.status = 303
        return "Redirect to /" # redirect to /
예제 #30
0
파일: main.py 프로젝트: allandeee/FlowTow
def logout():
    """Post request for Logout; Upon login, if user submits logout form
    their session and cookie is deleted. They are then redirected to the Main Page."""
    db = COMP249Db()
    curr_user = users.session_user(db)
    if curr_user:
        users.delete_session(db, curr_user)
        response.delete_cookie(COOKIE_NAME)
    redirect('/')
예제 #31
0
def like(db):
    """Add a like to an existing image"""

    filename = bottle.request.forms.get('filename')

    user = users.session_user(db)
    model.add_like(db, filename, user)

    bottle.redirect('/')
예제 #32
0
파일: main.py 프로젝트: allandeee/FlowTow
def logout():
    """Post request for Logout; Upon login, if user submits logout form
    their session and cookie is deleted. They are then redirected to the Main Page."""
    db = COMP249Db()
    curr_user = users.session_user(db)
    if curr_user:
        users.delete_session(db, curr_user)
        response.delete_cookie(COOKIE_NAME)
    redirect('/')
예제 #33
0
파일: main.py 프로젝트: allandeee/FlowTow
def unlike():
    """Post request to Unlike image; If a user has liked an image,
    they are able to unlike the image (reverse the like process)."""
    db = COMP249Db()
    img = request.forms.get('filename')
    curr_user = None
    if request.get_cookie(COOKIE_NAME):
        curr_user = users.session_user(db)
    interface.unlike(db, img, curr_user)
    redirect('/')
예제 #34
0
def add_database(db):
    """Logged in user can add new positions
    using position_add() from interface.py to add positions"""
    usernick = users.session_user(db)
    title = request.query.title
    location = request.query.location
    company = request.query.company
    description = request.query.description
    interface.position_add(db, usernick, title, location, company, description)
    redirect('/')
예제 #35
0
파일: main.py 프로젝트: allandeee/FlowTow
def unlike():
    """Post request to Unlike image; If a user has liked an image,
    they are able to unlike the image (reverse the like process)."""
    db = COMP249Db()
    img = request.forms.get('filename')
    curr_user = None
    if request.get_cookie(COOKIE_NAME):
        curr_user = users.session_user(db)
    interface.unlike(db, img, curr_user)
    redirect('/')
예제 #36
0
def index(db):
    """Generate the main page of the app"""

    info = {
        'user': users.session_user(db),
        'title': "¡Welcome to FlowTow!",
        'images': model.list_images(db, 3)
    }

    return bottle.template('index', info)
예제 #37
0
def add_post():
    """Adding post"""
    db = COMP249Db()
    username = session_user(db) # retrieve user session information from the database
    if username:
        content = request.forms['post'] # get user inputs from the input form 'post'
        interface.post_add(db, username, content) # add post by post_add function of interface.py
        response.set_header('Location', '/')
        response.status = 303
        return "Redirect to /" # redirect to /
예제 #38
0
파일: main.py 프로젝트: rako210/Comp4050
def report(db):
    """form post function for user reporting"""
    userLoggedIn = users.session_user(db)
    userBeingReported = request.forms.get("userBeingReported")
    complaint = request.forms.get("complaint")
    if userLoggedIn == userBeingReported:
        return template('temp4')
    else:
        res = report_user(userLoggedIn, userBeingReported, complaint)
        return template('temp5')
예제 #39
0
파일: main.py 프로젝트: allandeee/FlowTow
def like_img():
    """Post request to Like image; Upon login, when the user likes an image,
    that image information is retrieved and the number of likes is increased by adding
    to the likes table."""
    db = COMP249Db()
    img_liked = request.forms.get('filename')
    curr_user = None
    if request.get_cookie(COOKIE_NAME):
        curr_user = users.session_user(db)
    interface.add_like(db, img_liked, curr_user)
    redirect('/')
예제 #40
0
def index():
    """Main page of the application"""

    db = COMP249Db()

    info = {}

    info['user'] = users.session_user(db)
    info['title'] = "¡Welcome to FlowTow!"
    info['images'] = interface.list_images(db, 3)

    return template('index', info)
예제 #41
0
파일: main.py 프로젝트: allandeee/FlowTow
def index():
    """Main page; Displays the 3 latest images. Navbar is displayed from all pages.
    Login form is also displayed for user."""
    db = COMP249Db()
    curr_session = None
    curr_user = None
    img_list = interface.list_images(db, 3)
    if request.get_cookie(COOKIE_NAME):
        curr_session = request.get_cookie(COOKIE_NAME)
        curr_user = users.session_user(db)
    return template('index.html', title="FlowTow", images=img_list, session=curr_session, name=curr_user,
                    interface=interface, db=db)
예제 #42
0
def index():
    """Index of Psst site"""
    db = COMP249Db()
    username = session_user(db)
    loginString = ""
    private = "#private" # string that makes the post private
    content = ""
    http = ""
    list = interface.post_list(db, usernick=None, limit=50)

    # if user not logged in
    if not username:
        str = "<h2><b>Welcome to Psst.</b> Latest pssts:</h2>" # title
        # display input field for username and password if the user not logged in
        loginString = "<form id='loginform' method='POST' action ='/login'><input type='text' name='nick' placeholder='username' class='focus' onKeyPress='return submitenter(this,event)'><input type='password' name='password' placeholder='password' class='focus' onKeyPress='return submitenter(this,event)'></form>"
        str = str + "<table>"
        for item in list:
            content = interface.post_to_html(item[3])
            http = interface.post_to_html(content)

            # not display the posts with the '#private' tag
            if(bool(private.lower() in http.lower())==False):
                str = str + "<tr>"
                str = str + "<td valign='top'><img src='" + item[4] + "' width='45'></td>" # user avatar
                str = str + "<td valign='bottom'><a href='/users/" + item[2] + "'>@" + item[2] + ": </a>" + http + " - <i>posted on " + item[
                    1] + "</i></br></br></td></tr>" # username and contents
                users(item[2]) # generate /users/username page by users() function
                mentions(item[2]) # generate /mentions/username page by mentions function

    # if user logged in
    if username:
        # display the input field for adding posts instead of the title
        str = "<form action='/post' id='postform' method='POST'><input type='postfield' name='post' placeholder='post pssts (you can add #private tag to make the psst privately)' class='focus' onKeyPress='return submitenter(this,event)'></form>"
        for item in list:
            if(username==item[2]): # if user logged in, display his/her avatar, name, previous posts, the post mention, and logout option
                loginString = "<form action= '/logout' id='logoutform' name='logoutform' method='POST' ><table><tr><td><img src='" + item[4] + "' width='85'></td><td><h3>Logged in as " + username + "</h3><p><a href='/users/" + username + "'>Posted pssts</a></p><p><a href='/mentions/" + username + "'>@me pssts</a></p><p><a href='javascript: document.logoutform.submit();'>Logout</a></p></td></tr></table></form>"
        str = str + "<table>"
        at_user = "******" + username
        for item in list:
            content = interface.post_to_html(item[3])
            http = interface.post_to_html(content)

            # this if situation is for private message feature
            if((bool(private.lower() in http.lower()) == False) | (bool(at_user.lower() in http.lower())) | (bool(private.lower() in http.lower()) & bool(username.lower() in item[2].lower()))):
                str = str + "<tr>"
                str = str + "<td valign='top'><img src='" + item[4] + "' width='45'></td>" # user avatar
                str = str + "<td valign='bottom'><a href='/users/" + item[2] + "'>@" + item[2] + ": </a>" + http + " - <i>posted on " + item[
                        1] + "</i></br></br></td></tr>" # username and contents
                users(item[2]) # generate /users/username page by users() function
                mentions(item[2]) # generate /mentions/username page by mentions function
    str = str + "</table>"
    return template('base.tpl', base=str, validate='', login=loginString)
예제 #43
0
파일: main.py 프로젝트: allandeee/FlowTow
def my():
    """My Images page; Displays images uploaded by the user.
    If there is no user logged in, they are redirected to the Main page."""
    db = COMP249Db()
    curr_session = None
    curr_user = None
    if request.get_cookie(COOKIE_NAME):
        curr_session = request.get_cookie(COOKIE_NAME)
        curr_user = users.session_user(db)
    else:
        redirect('/')
    img_list = interface.list_images(db, 3, curr_user)
    return template('index.html', title="FlowTow", images=img_list, session=curr_session, name=curr_user,
                    interface=interface, db=db)
예제 #44
0
def search():
    """Search feature, can search user name and / or contents"""
    db = COMP249Db()
    username = session_user(db) # retrieve user session information from the database
    private = "#private" # string that makes the post private
    loginString = ""
    content = ""
    http = ""
    if 'search' in request.forms:
        search = request.forms['search'] # get user inputs from the search field
        str = "<h2>Search results for '" + search + "':</h2>" # title
        list = interface.post_list(db, usernick=None, limit=50)
        if not username: # display the things below only if user not logged in
            # display input field for username and password if the user not logged in
            loginString = "<form id='loginform' method='POST' action ='/login'><input type='text' name='nick' placeholder='username' class='focus' onKeyPress='return submitenter(this,event)'><input type='password' name='password' placeholder='password' class='focus' onKeyPress='return submitenter(this,event)'></form>"
            str = str + "<table>"
            for item in list:
                content = interface.post_to_html(item[3])
                http = interface.post_to_html(content)

                # this if situation is for private message feature
                if ((bool(private.lower() in http.lower())==False) & ((bool(search.lower() in item[2].lower())) | (bool(search.lower() in http.lower())))):
                    str = str + "<tr>"
                    str = str + "<td valign='top'><img src='" + item[4] + "' width='45'></td>" # user avatar
                    str = str + "<td valign='bottom'><a href='/users/" + item[2] + "'>@" + item[2] + ": </a>" + http + " - <i>posted on " + \
                          item[1] + "</i></br></br></td></tr>" # username and contents
                    users(item[2]) # generate /users/username page by users() function
                    mentions(item[2]) # generate /mentions/username page by mentions() function
            str = str + "</table>"
        if username: # display the things below only if user logged in
            at_user = "******" + username
            for item in list:
                if(username==item[2]): # if user logged in, display his/her avatar, name, previous posts, the post mention, and logout option
                    loginString = "<form action= '/logout' id='logoutform' name='logoutform' method='POST' ><table><tr><td><img src='" + item[4] + "' width='85'></td><td><h3>Logged in as " + username + "</h3><p><a href='/users/" + username + "'>Posted pssts</a></p><p><a href='/mentions/" + username + "'>@me pssts</a></p><p><a href='javascript: document.logoutform.submit();'>Logout</a></p></td></tr></table></form>"
            str = str + "<table>"
            for item in list:
                content = interface.post_to_html(item[3])
                http = interface.post_to_html(content)

                # this if situation is for private message feature
                if (((bool(private.lower() in http.lower()) == False) | (bool(at_user.lower() in http.lower())) | (bool(private.lower() in http.lower()) & bool(username.lower() in item[2].lower()))) & ((bool(search.lower() in item[2].lower())) | (bool(search.lower() in http.lower())))):
                    str = str + "<tr>"
                    str = str + "<td valign='top'><img src='" + item[4] + "' width='45'></td>" # user avatar
                    str = str + "<td valign='bottom'><a href='/users/" + item[2] + "'>@" + item[2] + ": </a>" + http + " - <i>posted on " + \
                          item[1] + "</i></br></br></td></tr>" # username and contents
                    users(item[2]) # generate /users/username page by users() function
                    mentions(item[2]) # generate /mentions/username page by mentions() function
            str = str + "</table>"
        return template('base.tpl', base=str, validate='', login=loginString)
예제 #45
0
파일: main.py 프로젝트: allandeee/FlowTow
def delete():
    """Post request to Delete image; When a user is logged in, and
    chooses to delete one of their own images, all traces of the image is deleted.
    This includes the database, and also the image directory/path.
    The user is then redirected to My Images page."""
    db = COMP249Db()

    curr_user = users.session_user(db)
    if not curr_user:
        redirect('/')

    img = request.forms.get('filename')
    interface.delete_image(db, img, curr_user)
    os.remove(os.path.join(UPLOAD_DIR, img))
    redirect('/my')
예제 #46
0
def index(failed=False):
    db = COMP249Db()

    current_user = users.session_user(db)
    if current_user:
        html = get_form("logout")
    else:
        html = get_form("login")
        if failed:
            html += "Login Failed, please try again"

    posts = interface.post_list(db)

    for post in posts:
        html += format_post(post)

    return template('general', title="Welcome to Psst!", content=html)
예제 #47
0
def mentions(name):

    db = COMP249Db()

    posts = interface.post_list_mentions(db, name)
    html = ""

    if users.session_user(db):
        html += get_form("logout")

    for post in posts:
        html += format_post(post)

    avatar = '<img src="' + posts[0][3] + '" alt="avatar">'

    title = name + "'s Mentions"
    return template('general', title=title, root="mentions/" + name, content=html)
예제 #48
0
def users(username):
    """Generate the webpage that displays the user posts"""
    db = COMP249Db()
    uname = session_user(db) # retrieve user session information from the database
    loginString = ""
    private = "#private" # string that makes the post private
    list = interface.post_list(db, usernick=username, limit=50)
    list2 = interface.post_list(db, usernick=None, limit=50)
    str = ""
    for item in list:
        str = "<h2><b>" + item[2] + "</b> posted pssts:</h2>" # title
    if not uname:
        # display input field for username and password if the user not logged in
        loginString = "<form id='loginform' method='POST' action ='/login'><input type='text' name='nick' placeholder='username' class='focus' onKeyPress='return submitenter(this,event)'><input type='password' name='password' placeholder='password' class='focus' onKeyPress='return submitenter(this,event)'></form>"
        str = str + "<table>"
        content = ""
        http = ""
        for item in list2:
            if (username == item[2]):
                content = interface.post_to_html(item[3])
                http = interface.post_to_html(content)

                # not display the posts with the #private tag
                if(bool(private.lower() in http.lower())==False):
                    str = str + "<tr>"
                    str = str + "<td valign='top'><img src='" + item[4] + "' width='45'></td>" # user avatar
                    str = str + "<td valign='bottom'><a href='/users/" + item[2] + "'>@" + item[2] + ": </a>" + http + " - <i>posted on " + \
                          item[1] + "</i></br></br></td></tr>" # username and contents
        str = str + "</table>"
    if uname:
        for item in list2:
            if(uname==item[2]): # if user logged in, display his/her avatar, name, previous posts, the post mention, and logout option
                loginString = "<form action= '/logout' id='logoutform' name='logoutform' method='POST' ><table><tr><td><img src='" + item[4] + "' width='85'></td><td><h3>Logged in as " + uname + "</h3><p><a href='/users/" + uname + "'>Posted pssts</a></p><p><a href='/mentions/" + uname + "'>@me pssts</a></p><p><a href='javascript: document.logoutform.submit();'>Logout</a></p></td></tr></table></form>"
        str = str + "<table>"
        content = ""
        http = ""
        for item in list2:
            if (username == item[2]): # display the post only if the username and the author is the same person
                content = interface.post_to_html(item[3])
                http = interface.post_to_html(content)
                str = str + "<tr>"
                str = str + "<td valign='top'><img src='" + item[4] + "' width='45'></td>" # user avatar
                str = str + "<td valign='bottom'><a href='/users/" + item[2] + "'>@" + item[2] + ": </a>" + http + " - <i>posted on " + \
                      item[1] + "</i></br></br></td></tr>" # username and contents
        str = str + "</table>"
    return template('base.tpl', base=str, validate='', login=loginString)
예제 #49
0
def tags(tag):

    db = COMP249Db()

    posts = interface.post_list_mentions(db, tag)
    html = ""

    if users.session_user(db):
        html += get_form("logout")

    for post in posts:
        html += format_post(post)

    avatar = '<img src="' + posts[0][3] + '" alt="avatar">'

    title = "Pssts about " + tag
    return template('general', title=title, root="tag/" + tag, content=html)
예제 #50
0
def user_page(name):
    db = COMP249Db()

    posts = interface.post_list(db, name)
    html = ""

    if users.session_user(db):
        html += get_form("logout")

    for post in posts:
        html += format_post(post)

    avatar = ""
    if posts:
        avatar += '<div id="avatar"><img src="' + posts[0][3] + '" alt="avatar"></div>'

    title = name + "'s Profile"
    return template('users', title=title, root="users/" + name, content=html, avatar=avatar)
예제 #51
0
def get_form(type):
    if type == "login":
        form = """
            <form id='loginform' method='post' action='/login'>
            <input type='text' name='nick'>
            <input type='password' name='password'>
            <input type='submit' value='Login' >
            </form>
        """
    if type == "logout":
        form = """
            Logged in as %s
            <form id='logoutform' method='post' action='/logout'>
            <input type='submit' value='logout' >
            </form>
            <form id='postform' method='post' action='/post'>
            <input type='text' name='post'>
            <input type='submit' value='post'>
            </form>
        """ % users.session_user(COMP249Db())
    return form
예제 #52
0
파일: main.py 프로젝트: allandeee/FlowTow
def upload():
    """Request to Upload an image; When a user is logged in, they have the
    ability to upload an image of there choice. It must be of image file type.
    If it is not the right file type, they will be presented with the File error display.
    Otherwise, they will be redirected to the My Images page."""
    db = COMP249Db()

    curr_user = users.session_user(db)
    if not curr_user:
        redirect('/')

    imagefile = request.files.get('imagefile')
    name, ext = os.path.splitext(imagefile.filename)
    if ext not in ('.jpeg', '.jpg', '.png', '.gif'):
        print("extension error")
        return template('fileerror.html', title="File Error", session=None, name=None)

    save_path = os.path.join(UPLOAD_DIR, imagefile.filename)
    imagefile.save(save_path)

    interface.add_image(db, imagefile.filename, curr_user)

    redirect('/my')
예제 #53
0
def logout():
    db = COMP249Db()
    users.delete_session(db, users.session_user(db))
    response.set_header('Location', '/')
    response.status = 303
    return 'Redirect to /'