Example #1
0
def watchList():
    # Query database for user id
    user_id_dict = db.execute("SELECT user_id FROM users WHERE username=:username;", username=session["username"]) 
    user_id = user_id_dict[0]["user_id"] 

    if request.method == "GET":
        # Query database for user watch list
        movies = db.execute("SELECT * FROM mylist WHERE user_id=:user_id;", user_id=user_id)
        if len(movies) == 0:
            # Inform user if user has nothing to watch
            return message("Your watch list is empty.")
        else:    
            return render_template("watchList.html", movies=movies)

    else:
        # Get user input
        movie_id = request.form.get("movie_id")
        # Get movie info
        movie = search_by_id(movie_id)
        title = movie["Title"]
        image = movie["Poster"]  
        # Query database for user watch list
        movie_listed = db.execute("SELECT * FROM mylist WHERE imdbId=:imdbId AND user_id=:user_id;", imdbId=movie_id, user_id=user_id) 
        # Inform user and prevent from leaving multiple feedbacks on the same movie
        if len(movie_listed) > 0:
            return message("You already have this movie in your watch list")
            
            
        else:
            # Update user watch list on database and inform user
            db.execute("INSERT INTO mylist (user_id, imdbId, title, image) VALUES (:user_id, :imdbId, :title, :image);", user_id=user_id, imdbId=movie_id, title=title, image=image)
            flash("Added to your watch list!")
            return redirect("/watchList")
Example #2
0
 def make_field_properties(self, typename):
     if not typename in types:
         message('Value Error', 'Unable to create properties for the type %s' % typename)
     props = []
     for f in types[typename].options or []:
         props.append({"group": "type", "property": f.name, "value": self.request.post_vars[f.name]})
     return props
Example #3
0
def command():
    doc = Document()
    if not request.args or len(request.args)<=2:
        message('Value Error', 'Command requires an function name')
    fn = request.args[2]
    if not hasattr(doc, fn):
        message('Document Command Error', 'Unable to find a command with name %s'%fn)
    return getattr(doc, fn)(request.args[3:])
Example #4
0
 def update_child(self, child_id, **kwargs):
     child_row = self.get_child(child_id)
     if child_row:
         errors = self.validate_child(**kwargs)
         if not errors:
             return self.document.update_document(**kwargs)
         else:
             message('Validation Error', ['<b>%s:</b> %s'%(self.document.META.get_df_name(df), error) for df, error in errors.values()], as_table=True)
Example #5
0
 def remove_document_file(self, documentfile_id, delete_file=False):
     documentfile_row = self.get_document_file(documentfile_id)
     if documentfile_row:
         if delete_file and not self.file_referenced_by_others(documentfile_row[self.db.File].id):
             documentfile_row[self.db.File].delete_record()
         else:
             message(self.T('DocumentFile does not exists.'))
         documentfile_row.delete_record()
         return True
     return False
Example #6
0
 def validate_and_save(self):
     def processor(_vars):
         row = self.db[self.child_name]._filter_fields(**self.request.vars)
         row['__saved'] = (False, len(self.data))
         self.data.insert(0, row)
         self._session_reindex() 
 
     if self.form.accepts(self.request.vars, formname=self._name):
         self.save_data(processor)
     else:
         message(self.T('Validation Error'), ['<b>%s:</b> %s'%(self.document.META.get_df_name(df), error) for df, error in self.form.errors.values()], as_table=True)
Example #7
0
 def add_child(self, **kwargs):
     if not kwargs.has_key('document'):
         kwargs['document'] = self.document.META.id
     if not kwargs.has_key('doc_parent'):
         kwargs['doc_parent'] = self.parent.META.id
     if not kwargs.has_key('data_id'):
         kwargs['doc_parent_id'] = self.parent.id
     errors = self.validate_child(**kwargs)
     if not errors:
         child_id = self.db[self.child_name].insert(**kwargs)
         return child_id
     else:
         message(self.T('Validation Error'), ['<b>%s:</b> %s'%(self.document.META.get_df_name(df), error) for df, error in errors.values()], as_table=True)
Example #8
0
def deleteAccount():
    if request.method == "GET":
        return render_template("deleteAccount.html")

    else:
        # Get user input
        current_password = request.form.get("password")

        # Query database for user hash and user id
        user_data = db.execute("SELECT * FROM users WHERE username=:username;", username=session["username"])
        user_hash = user_data[0]["hash"]
        user_id = user_data[0]["user_id"]

        # Delete user account if user hash matches user input
        if check_password_hash(user_hash, current_password):
            db.execute("DELETE FROM mylist WHERE user_id=:user_id", user_id=user_id)
            db.execute("DELETE FROM movies WHERE user_id=:user_id", user_id=user_id)
            db.execute("DELETE FROM users WHERE user_id=:user_id", user_id=user_id)
            session.clear()
            # Inform user
            flash("Your account has been deleted!")
            return render_template("login.html")
        else:
            # Inform user that input does not match
            return message("Password doesn't match!") 
Example #9
0
 def _validate_doc_name(self, case='Title Case'):
     db = self.META._db
     if db.has_document(self.doc_name):
         message('Document already exists', 'The Document %s already exists in database'%self.doc_name)
     
     if case == 'Title Case': self.doc_name = self.doc_name.title()
     if case == 'UPPER CASE': self.doc_name = self.doc_name.upper()
     
     self.doc_name = self.doc_name.strip()
     
     errors = []
     forbidden = ['%', '"', "'", "#", "*","?", "`", "&", "-", ":"]
     for f in forbidden:
         if f in self.name:
             errors.append((True, str(T("%s not allowed in Document Name"))%f))
             errors = True
     return errors or (None, '')
Example #10
0
def allFeedbacks():
    # Query database for user feedbacks
    movies = db.execute("SELECT DISTINCT * FROM movies JOIN users ON movies.user_id = users.user_id;")
    if len(movies) == 0:
        # Inform user if user has no feedbacks
        return message("There is no feedbacks yet!")
    else:    
        return render_template("allFeedbacks.html", movies=movies)
Example #11
0
def feedback_handler(event, _):
    # Try to decode a JSON document from the body
    try:
        body = json.loads(event["body"])
    except json.JSONDecodeError:
        return helpers.message({"message": "Invalid JSON document"}, 400)

    # Validate the JSON document
    if "photo" not in body:
        return helpers.message({"message": "Missing 'photo' key in body"}, 400)

    if "dog" not in body:
        return helpers.message({"message": "Missing 'dog' key in body"}, 400)

    user_dog = body["dog"]

    # Try to extract the photo from the JSON document
    try:
        photo = base64.b64decode(body["photo"])
    except binascii.Error:
        return helpers.message({"message": "Invalid base64 string for 'photo'"}, 400)

    # Check if the system finds a dog
    dog = has_dog(photo)

    # Store if there was a dog or not as a custom metric
    helpers.metric("DogNoDog", "Dog", int(dog))

    # Store the type of error as a custom metric.
    # FalsePositive: there are no dogs in the picture but the system detected one.
    # FalseNegative: there is a dog in the picture but the system did not detect it.
    # Match: the system correctly detected that there is a dog.
    if dog and not user_dog:
        helpers.metric("DogNoDog", "FalsePositive", 1)
    elif not dog and user_dog:
        helpers.metric("DogNoDog", "FalseNegative", 1)
    else:
        helpers.metric("DogNoDog", "Match", 1)

    # Store the feedback on S3
    save_feedback(photo, user_dog, dog)

    # Send message back to the user
    return helpers.response({"message": "Feedback received"})
Example #12
0
def myFeedbacks():
    if request.method == "GET":
        # Query database for user feedbacks
        movies = db.execute("SELECT * FROM movies JOIN users ON movies.user_id = users.user_id WHERE username=:username;", username=session["username"])
        # Inform user if user has no feedbacks
        if len(movies) == 0:
            return message("You have no feedbacks!")

        else:    
            return render_template("myFeedbacks.html", movies=movies)
Example #13
0
def login():
    """Log user in"""
    # Forget any user_id
    session.clear()
    # upon submitting credentials
    if request.method == "POST":
        log.info("login as POST")
        # Ensure username was submitted
        if not request.form.get("username"):
            return message("must provide username", "Error", 400)
        # Ensure password was submitted
        elif not request.form.get("password"):
            return message("must provide password", "Error", 400)
        # Query database for username
        try:
            rows = db.execute("SELECT * FROM card WHERE username = :username",
                              {
                                  "username": request.form.get("username")
                              }).fetchall()
        except:
            return message("couldn't get user", "Error", 500)
        # Ensure username exists and password is correct
        log.info(f"len(rows): %i", len(rows))
        if len(rows):
            log.info(f"pass_hash: %s", rows[0].pass_hash)
            log.info(
                f"check_password_hash: %r",
                check_password_hash(rows[0].pass_hash.strip(),
                                    request.form.get("password")))
        if len(rows) != 1:
            return message("invalid username", "Error", 400)
        if not check_password_hash(rows[0].pass_hash.strip(),
                                   request.form.get("password")):
            return message("invalid password", "Error", 400)
        # Remember which user has logged in
        session["user_id"] = rows[0].user_id
        # Redirect user to home page
        return redirect("/")
    # showing up to log in
    else:
        log.info("login as GET")
        return render_template("login.html", bgtext=loadbabel())
Example #14
0
 def on_pubmsg(self, client, event):
     """
     Callback for recieving messages from the server
     """
     sender = event.source.split('!')[0]
     if sender != self.nickname:
         msg = message(source=self.name,
                       sender=sender,
                       content=event.arguments[0],
                       time=time())
         self.msg_handler(msg)
Example #15
0
def settings():
    """User Settings"""

    username = session["username"]

    # User reached route via POST (as by submitting a form via POST)
    if request.method == "POST":

        current = request.form.get("current")
        password = request.form.get("password")

        msg = ""
        # Ensure username was submitted
        if not current:
            msg = "must provide current password"

        # Ensure password was submitted
        elif not password:
            msg = "must provide new password"

        # Ensure current password is valid
        rows = db.execute("SELECT * FROM users WHERE username = :username",
                          username=username)
        if not check_password_hash(rows[0]["hash"], current):
            msg = "the current password you entered is not valid"

        # Ensure passwords match
        confirmation = request.form.get("confirmation")
        if password != confirmation:
            msg = "passwords don't match"

        if msg != "":
            return apology(msg)

        # All is valid. Encrypt new password
        else:
            secret = generate_password_hash(password)

            # update users password
            db.execute(
                "UPDATE users SET hash = :secret WHERE username = :username",
                secret=secret,
                username=username)

            # Redirect user to home page
            return message("password successfully updated")

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("settings.html")
Example #16
0
def register():
    """Register user"""
    # Forget any user_id
    session.clear()
    # upon submitting registration form
    if request.method == "POST":
        formusername = request.form.get("username")
        log.info(f"formusername is: %s", formusername)
        password = request.form.get("password")
        confpass = request.form.get("confirmation")
        passhash = generate_password_hash(request.form.get("password"))
        # Ensure username was submitted
        if not formusername:
            return message("must provide username", "Error", 400)
        # Ensure password was submitted
        elif not password:
            return message("must provide password", "Error", 400)
        # Ensure password matches confirmation
        elif password != confpass:
            return message("passwords do not match", "Error", 400)
        # Query database for username
        try:
            # Ensure username does not already exist
            user_lookup = db.execute(
                "SELECT * FROM card WHERE username = :username", {
                    "username": formusername
                }).fetchall()
            log.info(user_lookup)
            if len(user_lookup):
                return message("username taken", "Error", 400)
        except:
            return message("couldn't get user", "Error", 500)
        try:
            # Add user to database
            db.execute(
                'INSERT INTO "card" ("username","pass_hash") VALUES (:username, :pass_hash)',
                {
                    "username": formusername,
                    "pass_hash": passhash
                })
            db.commit()
            # Get new user info
            newrow = db.execute(
                "SELECT * FROM card WHERE username = :username", {
                    "username": request.form.get("username")
                }).fetchall()
            log.info("new card row created:")
            log.info(newrow)
            # Remember user
            session["user_id"] = newrow[0].user_id
        except:
            return message("couldn't update database", "Error", 500)
        # Redirect user to home page
        return redirect("/")
    # upon coming to register
    else:
        return render_template("register.html", bgtext=loadbabel())
Example #17
0
def index():
    """Search page"""
    if request.method == "POST":
        log.info("index as POST")
        # Ensure select_field was submitted
        select_field = request.form.get("select_field")
        if not select_field:
            return message("must select field to search on", "Error", 400)
        # Ensure search_string was submitted
        search_string = request.form.get("search_string")
        if not search_string:
            return message("must input something to search for", "Error", 400)
        # add wildcards to search
        term = "%" + search_string + "%"
        log.info(f"select field: %s", select_field)
        log.info(f"search term: %s", term)
        log.info(f"select field valid?: %r", select_field
                 in {"isbn", "author", "title", "pub_year"})
        # make sure nothing fishy gets into the database command and construct command in text since can't use placeholders for column
        if select_field not in {"isbn", "author", "title", "pub_year"}:
            return message("something wrong with search field", "Error", 400)
        if select_field != "pub_year":
            command = "SELECT * FROM book WHERE " + select_field + " LIKE :term"
        else:
            command = "SELECT * FROM book WHERE CAST(pub_year AS TEXT) LIKE :term"
        log.info(f"command: %s", command)
        search_results = db.execute(command, {"term": term}).fetchall()
        log.debug("Search results:")
        log.debug(search_results)
        return render_template("index.html",
                               bgtext=loadbabel(),
                               select_field=select_field,
                               search_string=search_string,
                               search_results=search_results)
    else:
        log.info("index as GET")
        return render_template("index.html", bgtext=loadbabel())
Example #18
0
def has_dog_handler(event, _):
    # Try to decode a JSON document from the body
    try:
        body = json.loads(event["body"])
    except json.JSONDecodeError:
        return helpers.message({"message": "Invalid JSON document"}, 400)

    # Validate the JSON document
    if "photo" not in body:
        return helpers.message({"message": "Missing 'photo' key in body"}, 400)

    # Try to extract the photo from the JSON document
    try:
        photo = base64.b64decode(body["photo"])
    except binascii.Error:
        return helpers.message({"message": "Invalid base64 string for 'photo'"}, 400)

    # Check if there is a dog
    dog = has_dog(photo)

    # Store if there was a dog or not as a custom metric
    helpers.metric("DogNoDog", "Dog", int(dog))

    return helpers.response({"dog": dog})
Example #19
0
def reviews():
    """show all user reviews"""
    user_id = session.get("user_id")
    if request.method == "POST":
        log.info("reviews as POST")
        # get form input
        book_id = request.form.get("book_id")
        rating = request.form.get("rating")
        review = request.form.get("review")
        log.debug(
            "\nuser with id: %r submitted: \nbook_id: %r\nrating: %r\nreview: %r",
            user_id, book_id, rating, review)
        # add to database
        try:
            db.execute(
                'INSERT INTO "review" ("user_id","book_id","rating","review") VALUES (:user_id, :book_id, :rating, :review)',
                {
                    "user_id": user_id,
                    "book_id": book_id,
                    "rating": rating,
                    "review": review
                })
            db.commit()
        except:
            return message("couldn't add review to database", "Error", 500)
        # Redirect user to reviews page as GET
        return redirect("/reviews")
    else:
        log.info("reviews as GET")
        # lookup all current user's username and reviews, pass to template
        username, = db.execute(
            "SELECT username FROM card WHERE user_id = :user_id", {
                "user_id": user_id
            }).fetchone()
        log.debug("database got username: %s", username)
        book_revs = db.execute(
            "SELECT review.book_id, title, author, rating, review FROM review JOIN book ON review.book_id = book.book_id WHERE user_id = :user_id",
            {
                "user_id": user_id
            }).fetchall()
        log.debug("database got user reviews:")
        log.debug(book_revs)
        return render_template("reviews.html",
                               username=username,
                               book_revs=book_revs,
                               bgtext=loadbabel())
Example #20
0
def updatePassword():
    if request.method == "GET":
        return render_template("updatePassword.html")
    else:
        # Get user input
        current_password = request.form.get("currentPassword")
        new_password = request.form.get("newPassword")

        # Query database for user hash
        user_data = db.execute("SELECT hash FROM users WHERE username=:username;", username=session["username"])
        user_hash = user_data[0]["hash"]
        # Check if user input matches user hash
        if check_password_hash(user_hash, current_password):
            # Generate new hash for new password
            new_hash = generate_password_hash(new_password, method='pbkdf2:sha256', salt_length=8)
            # Update user hash on database and inform user
            db.execute("UPDATE users SET hash=:new_hash WHERE username=:username;", new_hash=new_hash, username=session["username"])
            flash("Your password has been updated!")
            return redirect("/")
        else:
            # Inform user
            return message("Password doesn't match!")    
Example #21
0
def upload_file():

    if request.method == "POST":

        # Ensure file was submitted
        if not request.files['image']:
            return apology("must provide file", 400)

        # Ensure genera was submitted
        elif not request.form.get("genera"):
            return apology("must provide genera", 400)

        gen = request.form.get("genera")
        genera_dat = db.execute("SELECT * FROM genera WHERE genera =:genera",
                                genera=gen)

        if len(gen) > 1 and len(genera_dat) != 0:
            genera = gen
        else:
            return apology("Non valid genera", 400)

        file = request.files['image']
        id = session["user_id"]

        if file and allowed_file(file.filename) and genera:
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))

            db.execute("""INSERT INTO "contributions"(file_name,id,genera)
                    VALUES(:file_name, :id, :genera)""",
                       file_name=filename,
                       id=session["user_id"],
                       genera=genera)

            return message('Thanks a lot for your contribution!',
                           file_name=filename)

    else:
        return render_template("upload.html")
Example #22
0
def run(languages, leclist, convert = False):
  if convert:
    create_directories(leclist)
    convert_to_html(languages, leclist)
  
  LL_dict = {}
  for lang in languages:
    LL_dict[lang] = {}
  for lesson_nr in leclist:
    PATH = "../lections/lek"+str(lesson_nr)+"/"
    OUTFILE = PATH+"lek"+str(lesson_nr)+"_LL.html"
    path = "../lections/lek" + str(lesson_nr)
    
    for infile in glob.glob(os.path.join(path, "*lek"+str(lesson_nr)+"*.html")):
      lang = infile[-7:-5]
      if lang != "LL" and lang in languages:
        message("processing "+infile)

        parser = parsing.MyHTMLParser()
        dehasher = hashing.Dehasher(lesson_nr)
        writer = writing.Writer(dehasher, PATH, HTMLRES_PATH, colordic, merkdic)

        dehasher.inlist = []
        parser.feed(read_html(infile))
        snipdic = parser.snipdic

        if lang == 'en':
          writer.create_html(snipdic, OutsourceTXT = True)
          writer.write_html(HTML_OUTPUT_PATH+"lektion"+str(lesson_nr)+".tmpl")
        else:
          writer.create_html(snipdic)

        LL_dict[lang][dehasher.lesson_nr]=dehasher.inlist

  len_dict = {}
  for lesson_nr in leclist:
    len_dict[lesson_nr] = {}
    for lang in languages:
      len_dict[lesson_nr][lang] = len(LL_dict[lang][lesson_nr])
    len_sort = len_dict[lesson_nr].values()
    len_sort.sort()
    if len_sort[0] != len_sort[-1]:
      message("Different number of foreign language snippets in lection" + str(lesson_nr))
      message(len_dict[lesson_nr])
      
  writer.write_xml(HTML_OUTPUT_PATH+"locallang_deutschkurs.xml", LL_dict)
Example #23
0
def forgotPassword():
    if request.method == "GET":
        return render_template("forgotPassword.html")

    else:
        # Get user input
        email = request.form.get("email")
        new_password = request.form.get("newPassword")

        # Query database for user info
        user_data = db.execute("SELECT * FROM users WHERE email=:email;", email=email)
        # Check if user input is in database
        if (len(user_data) > 0):

            # Generate new hash for new password
            new_hash = generate_password_hash(new_password, method='pbkdf2:sha256', salt_length=8)
            # Update user hash on database and inform user
            db.execute("UPDATE users SET hash=:new_hash WHERE email=:email;", new_hash=new_hash, email=email)
            flash("Your password has been updated!")
            return render_template("login.html")
        else:
            # Inform user email not registered
            return message("Email doesn't match!")     
Example #24
0
 def type_has_option(self, name):
     if not name in types:
         message('Value Error', 'Unknow type %s'%`name`)
     return dumps(types[name].has_key('options'))
Example #25
0
 def make_options_form(self, df_name, typename):
     if not typename in types:
         message('Value Error', 'Unable to create a form for the type %s' % typename)
         return
     return factory(types[typename].options, name=df_name).process(self.request.post_vars)
Example #26
0
 def get_child_in_db(self, child_id):
     child_row = self.db.get_document(self.child_name, child_id)
     if child_row:
         return child_row
     message(self.T('Children Lookup Error'), self.T('Unable to locate document children for this document'), True)
     return False
Example #27
0
def book(book_id):
    """book page with info and reviews"""
    log.info(f"book route with id: %i", book_id)
    # check valid book
    if not book_id:
        return message("no book specified", "Error", 400)
    # get book info
    result = db.execute("SELECT * FROM book WHERE book_id = :book_id", {
        "book_id": book_id
    }).fetchone()
    log.debug("database got result:")
    log.debug(result)
    log.debug("send to api Key: %s", os.environ['GRKEY'])
    log.debug("send to api isbn: %s", result.isbn.strip())
    # get info from goodreads api
    try:
        res = requests.get("https://www.goodreads.com/book/review_counts.json",
                           params={
                               "key": os.environ['GRKEY'],
                               "isbns": result.isbn.strip()
                           })
        log.debug("api got:")
        log.debug(res.json())
        gr_num = res.json()["books"][0]["work_ratings_count"]
        gr_avg = res.json()["books"][0]["average_rating"]
        log.debug("average rating: %s and number of ratings %i", gr_avg,
                  gr_num)
    except:
        gr_num = 0
    # get username to give to template
    user_id = session.get("user_id")
    username, = db.execute(
        "SELECT username FROM card WHERE user_id = :user_id", {
            "user_id": user_id
        }).fetchone()
    log.debug("database got username:"******"SELECT * FROM review WHERE user_id = :user_id AND book_id = :book_id",
        {
            "user_id": user_id,
            "book_id": book_id
        }).fetchone()
    log.debug("database got user review for this book:")
    log.debug(user_rev)
    # get all other reviews for book if exist
    book_revs = db.execute(
        "SELECT username, rating, review FROM review JOIN card ON card.user_id = review.user_id WHERE book_id = :book_id AND username != :username",
        {
            "username": username,
            "book_id": book_id
        }).fetchall()
    log.debug("database got reviews from other users for this book:")
    log.debug(book_revs)
    if not book_revs:
        book_revs = 0
    return render_template("book.html",
                           book=result,
                           gr_num=gr_num,
                           gr_avg=gr_avg,
                           username=username,
                           user_rev=user_rev,
                           book_revs=book_revs,
                           bgtext=loadbabel())