def join(): try: username = request.form['username'] passwd1 = request.form['password1'] passwd2 = request.form['password2'] if passwd1 != passwd2: flash('passwords do not match') return redirect(url_for('index')) hashed = bcrypt.hashpw(passwd1.encode('utf-8'), bcrypt.gensalt()) hashed_str = hashed.decode('utf-8') conn = lookup.getConn(CONN) try: lookup.insertPass(conn, username, hashed_str) except Exception as err: # this is not getting thrown flash('That username is taken.') #: {}'.format(repr(err))) return redirect(url_for('index')) uid = lookup.getUIDFirst(conn) # print(uid) flash('FYI, you were issued UID {}'.format(uid)) session['username'] = username session['uid'] = uid session['logged_in'] = True # session['visits'] = 1 return redirect( url_for('profile', uid=uid)) #should put username in instead? more readable except Exception as err: flash('form submission error ' + str(err)) return redirect(url_for('index'))
def login(): try: username = request.form['username'] passwd = request.form['password'] conn = lookup.getConn(CONN) row = lookup.getLogin(conn, username) if row is None: # Same response as wrong password, # so no information about what went wrong flash('login incorrect. Try again or join') return redirect(url_for('index')) hashed = row['passhash'] hashed2 = bcrypt.hashpw(passwd.encode('utf-8'), hashed.encode('utf-8')) #.encode('utf-8')) hashed2_str = hashed2.decode('utf-8') if hashed2_str == hashed: flash('successfully logged in as ' + username) session['username'] = username session['uid'] = row['uid'] print(session['uid']) session['logged_in'] = True # session['visits'] = 1 return redirect(url_for('profile', uid=session['uid'])) else: flash('login incorrect. Try again or join') return redirect(url_for('index')) except Exception as err: flash('form submission error: ' + str(err)) return redirect(url_for('index'))
def worksByTerm(search_kind, search_term): '''searches for works by work, author or tag. if no term then default to all''' if 'uid' in session: term = search_term kind = search_kind conn = lookup.getConn(CONN) filters = [] completion = None audience = None sortBy = None exclude = session['filters'] if 'filters' in session else [] if (request.method == "POST") and not (kind == "author"): filters = request.form.getlist('warnings[]') sortBy = request.form.get('sortby') completion = request.form.get('finished') audience = request.form.get('audience') res = (lookup.searchAuthors(conn, term) if kind == "author" else lookup.searchWorks(conn, kind, term, set(filters + exclude))) # print (str(res)) if not kind == "author": # print("pre everything\n", str(res)) if completion: res = ([work for work in res if not work['wip']] if completion == 'wip' else [work for work in res if work['wip']]) # print ("completion\n", str(res)) if audience: res = [work for work in res if work['audience'] == audience] if sortBy: if sortBy == 'avgRating': for work in res: if work.get('avgRating') == None: work.update({'avgRating': 0}) # print ("checking\n {}".format(str(res))) res = sorted(res, reverse=True, key=lambda work: work[sortBy]) # print ("sorted byyyyy\n {}".format(str(res))) resKind = "Authors" if kind == "author" else "Works" nm = "Tag" if (kind == "tag") else "Term" if not res: flash("No {} Found Including {}: {} :( ".format(resKind, nm, term)) return render_template('search.html', resKind=resKind, term=term, res=res, warnings=lookup.getTags(conn, 'warnings'), page_title="Search") else: flash('Log in to search.') return redirect(url_for('index'))
def join(): try: username = request.form['username'] passwd1 = request.form['password1'] passwd2 = request.form['password2'] if passwd1 != passwd2: flash('Passwords do not match') return redirect(url_for('index')) if len(passwd1) < 12: flash('Passwords must be at least 12 characters long') return redirect(url_for('index')) hashed = bcrypt.hashpw(passwd1.encode('utf-8'), bcrypt.gensalt()) hashed_str = hashed.decode('utf-8') conn = lookup.getConn(CONN) lock.acquire() try: lookup.insertPass(conn, username, hashed_str) except Exception as err: # this is not getting thrown flash('That username is taken.') #: {}'.format(repr(err))) return redirect(url_for('index')) uid = lookup.getUIDFirst(conn) lock.release() # print(uid) flash('FYI, you were issued UID {}'.format(uid)) session['username'] = username session['uid'] = uid session['logged_in'] = True # session['visits'] = 1 return redirect(url_for('profile', username=username)) except Exception as err: flash('Form submission error ' + str(err)) return redirect(url_for('index'))
def prefs(uid): try: if 'uid' in session: uid = session['uid'] conn = lookup.getConn(CONN) prefs = lookup.getPrefs(conn, uid) tids = [tag['tid'] for tag in prefs] allTags = [ tag for tag in lookup.getTags(conn, 'genre') if tag['tid'] not in tids ] if prefs: return render_template('profile.html', uid=uid, prefs=prefs, allTags=allTags) else: return render_template('profile.html', uid=uid, prefs={}, allTags=allTags) else: flash("Please log in or join") return redirect(url_for('index')) except Exception as err: flash('Error: ' + str(err)) return redirect(url_for('index'))
def updateProfile(): conn = lookup.getConn(CONN) uid = session['uid'] dob = request.form.get('dob') lookup.updateProfile(conn, uid, dob) username = session['username'] return redirect(url_for('profile', username=username))
def history(): if 'uid' in session: uid = session['uid'] conn = lookup.getConn(CONN) hist = lookup.getHistory(conn, uid) return render_template('history.html', history=hist) else: return redirect(url_for('index'))
def markFinished(sid): if 'uid' in session: conn = lookup.getConn(CONN) lookup.setFinished(conn, sid) return (redirect(url_for('manage'))) else: flash('Log in to manage your works.') return redirect(url_for('index'))
def read(sid, cnum): conn = lookup.getConn(CONN) # print("sid: "+str(sid)) # print("cnum: "+str(cnum)) try: chapter = lookup.getChapter(conn, sid, cnum) print('Chapter dict:') print(chapter) cid = chapter['cid'] # print(cid) try: uid = session['uid'] #add to history print(lookup.addToHistory(conn, uid, sid)) comments = lookup.getComments(conn, uid, cid) # print('Comments:') # print(comments) infile = open(chapter['filename'], 'r') story = infile.read() infile.close() allch = lookup.getChapters(conn, sid) numChap = lookup.getNumChaps(conn, sid)['count(cid)'] # print(numChap) work = lookup.getStory(conn, sid) print(work) if uid == work['uid']: allComments = lookup.getAllComments(conn, cid) else: allComments = None if 'username' not in session: return redirect(url_for('index')) if session['username'] == work['username']: isUpdate = True else: isUpdate = False return render_template('read.html', title=work['title'], story=story, chapter=chapter, author=work['username'], cnum=cnum, sid=sid, update=isUpdate, allch=allch, comments=comments, uid=uid, maxCh=numChap, allComments=allComments) except Exception as err: print(err) return redirect(url_for('index')) except Exception as err: return redirect(url_for('notFound'))
def markHelpful(): '''allows authors to mark particular comments as helpful or unhelpful''' conn = lookup.getConn(CONN) helpful = request.form.get('helpful') rid = request.form.get('rid') #review id lookup.changeHelpful(conn, rid, helpful) return jsonify(helpful=helpful, rid=rid)
def update(sid, cnum): try: conn = lookup.getConn(CONN) authorid = lookup.getAuthorId(conn, sid)[0] print(authorid, session['uid']) if 'uid' in session and session['uid'] == authorid: if request.method == "GET": chapter = lookup.getChapter(conn, sid, cnum) story = "" if chapter: infile = open(chapter['filename'], 'r') story = infile.read() infile.close() allch = lookup.getChapters(conn, sid) return render_template('write.html', title='Update Story', sid=sid, cnum=cnum, story=story, allch=allch) if request.method == "POST": sometext = request.form['write'] somehtml = bleach.clean( sometext, #allowed tags, attributes, and styles tags=[ 'b', 'blockquote', 'i', 'em', 'strong', 'p', 'ul', 'br', 'li', 'ol', 'span' ], attributes=['style'], styles=['text-decoration', 'text-align']) dirname = os.path.dirname(__file__) relative = 'uploaded/' + 'sid' + str(sid) + 'cnum' + str( cnum) + '.html' filename = os.path.join(dirname, relative) outfile = open(filename, 'w') outfile.write(somehtml) outfile.close() chapter = lookup.getChapter(conn, sid, cnum) if not chapter: lookup.setChapter(conn, sid, cnum, filename) return redirect(url_for('read', sid=sid, cnum=cnum)) else: flash('''You are not authorized to edit this work. Please log in with the account associated with this work''' ) return redirect(url_for('index')) except Exception as err: flash('some kind of error ' + str(err)) return redirect(url_for('index'))
def select(): if request.method == "GET": conn = lookup.getConn('achan_db') incompleteList = lookup.selectIncomplete(conn) return render_template('select.html', page_title="Movie Select", movies=incompleteList) elif request.method == "POST": tid = request.form['menu-tt'] return redirect(url_for('update', tt=tid))
def rateAjax(): conn = lookup.getConn(CONN) rating = request.form.get('rating') sid = request.form.get('sid') uid = session['uid'] lookup.addRating(conn, uid, sid, rating) avgRating = float(lookup.calcAvgRating(conn, sid)['avg(rating)']) lookup.updateAvgRating(conn, sid, avgRating) return jsonify(rating=rating, avgRating=avgRating)
def history(): if 'uid' in session: uid = session['uid'] conn = lookup.getConn(CONN) hist = lookup.getHistory(conn, uid) username = session['username'] if 'username' in session else "" return render_template('history.html', history=hist, page_title="{}'s History".format(username)) else: return redirect(url_for('index'))
def search(): if request.method == "GET": return render_template('search.html', page_title="Movie Search") elif request.method == "POST": conn = lookup.getConn('achan_db') ask = request.form['search-title'] id = lookup.searchMovie(conn, ask) if id == None: flash("No movie matches. Please try again.") return render_template('search.html', page_title="Movie Search") return redirect(url_for('update', tt=id))
def add(): try: if request.method == "GET": if 'uid' in session: uid = session['uid'] conn = lookup.getConn(CONN) genre = lookup.getTags(conn, 'genre') warnings = lookup.getTags(conn, 'warnings') audience = lookup.getTags(conn, 'audience') isFin = lookup.getTags(conn, 'isFin') return render_template('add.html', warnings=warnings, genre=genre, audience=audience, isFin=isFin, page_title="Add a Story") else: flash("Please log in or join") return redirect(url_for('index')) if request.method == "POST": uid = session['uid'] title = request.form['title'] summary = request.form['summary'] genre = request.form.getlist('genre') audience = request.form['audience'] warnings = request.form.getlist('warnings') status = request.form['isFin'] if status == '32': status = 1 #work is finished elif status == '33': status = 0 #work is in progress conn = lookup.getConn(CONN) sid = lookup.addStory(conn, uid, title, summary, status)[0] lookup.addTags(conn, sid, genre, warnings, audience, status) return redirect(url_for('update', sid=sid)) except Exception as err: flash('Error: ' + str(err)) return redirect(url_for('index'))
def updateProfile(): if 'uid' in session: conn = lookup.getConn(CONN) uid = session['uid'] dob = request.form.get('dob') lookup.updateProfile(conn, uid, dob) username = session['username'] return redirect(url_for('profile', username=username)) else: flash('Log in to bookmark works.') return redirect(url_for('index'))
def addComment(): conn = lookup.getConn(CONN) commentText = request.form["commentText"] cid = request.form['chapcid'] if 'uid' in session: uid = session['uid'] lookup.addComment(conn, commentText, uid, cid) flash('Comment submitted!') return redirect(request.referrer) else: return redirect(url_for('index'))
def update(tt): conn = lookup.getConn('achan_db') if request.method == "GET": movie = lookup.getMovie(conn, tt) return render_template('update.html', page_title="Update Movie", defaultform=movie) #POST update elif request.method == "POST" and request.form['submit'] == 'update': title = request.form['movie-title'] newtt = request.form['movie-tt'] release = request.form['movie-release'] director = request.form['movie-director'] addedby = request.form['movie-addedby'] #Error checking works = True #initialize the boolean if not newtt.isdigit(): flash('error: tt must be numeric') works = False #the form won't work elif newtt != tt: isThere = lookup.checkMovie(conn, newtt) if isThere: flash("Movie already exists") works = False elif not release.isdigit(): flash('error: release year must be numeric') works = False elif not addedby.isdigit(): flash('error: addedby must be numeric') works = False #Redirects if works == False: #if the form doesn't work i = lookup.getMovie(conn, tt) return render_template('update.html', page_title="Update Movie", defaultform=i) #if the form works, then we update lookup.updateMovie(conn, tt, newtt, title, release, addedby, director) flash('Movie was updated successfully') i = lookup.getMovie(conn, newtt) return render_template('update.html', page_title="Update Movie", defaultform=i) #POST delete elif request.method == "POST" and request.form['submit'] == 'delete': lookup.deleteMovie(conn, tt) flash('Movie was successfully deleted') return redirect(url_for('index'))
def rateAjax(): # print('rateAjax called') conn = lookup.getConn(CONN) rating = request.form.get('rating') sid = request.form.get('sid') uid = session['uid'] # print("rating to add:") # print(rating) lookup.addRating(conn, uid, sid, rating) avgRating = float(lookup.calcAvgRating(conn, sid)['avg(rating)']) # print("average rating for sid " + str(sid)) # print(avgRating) lookup.updateAvgRating(conn, sid, avgRating) return jsonify(rating=rating, avgRating=avgRating)
def manage(): try: if 'uid' in session: uid = session['uid'] conn = lookup.getConn(CONN) stories = lookup.getStories(conn, uid) return render_template('manage.html', stories=stories, page_title="Manage My Stories") else: flash("Please log in or join") return redirect(url_for('index')) except Exception as err: flash('Error: ' + str(err)) return redirect(url_for('index'))
def bookmarks(): if 'uid' in session: uid = session['uid'] conn = lookup.getConn(CONN) username = session['username'] if 'username' in session else '' books = lookup.getBookmarks(conn, uid) if not books: flash("No bookmarked works were found") return render_template('bookmarks.html', res=books, page_title="{}'s Bookmarks".format(username)) else: flash("Please log in") return redirect(url_for('index'))
def worksByTerm(search_kind, search_term): term = search_term kind = search_kind conn = lookup.getConn(CONN) #search for works like the search term #if no search term, defaults to all movies res = (lookup.searchAuthors(conn, term) if kind == "author" else lookup.searchWorks(conn, kind, term)) resKind = "Authors" if kind == "author" else "Works" nm = "Tag" if (kind == "tag") else "Term" if not res: flash("No {} Found Including {}: {} :( ".format(resKind, nm, term)) #return "<p>{}</p>".format(res) return render_template('search.html', resKind=resKind, term=term, res=res)
def recommendations(): if 'uid' in session: if request.method == "POST": filters = tuple(request.form.getlist('warnings[]')) else: uid = session['uid'] conn = lookup.getConn(CONN) warnings = lookup.getTags(conn, 'warnings') recs = lookup.getRecs(conn, uid) print(recs) # return render_template('recommendations.html', recommendations=recs) return render_template('search.html', resKind="Recs", res=recs, warnings=[]) else: return redirect(url_for('index'))
def profile(username): conn = lookup.getConn(CONN) # try: if request.method == "POST": if 'uid' in session: uid = session['uid'] # conn = lookup.getConn(CONN) lookup.updatePrefs(conn, uid, request.form.getlist('pref[]'), False) flash('Your preferences have been updated!') # don't trust the URL; it's only there for decoration if 'username' in session: currentUsername = session['username'] uid = lookup.getUID(conn, username) #session['uid'] prefs = lookup.getPrefs(conn, uid, False) # tids = [tag['tid'] for tag in prefs] allTags = [ tag for tag in lookup.getTags(conn, 'genre') if tag['tid'] not in prefs ] stories = lookup.getStories(conn, uid) # session['visits'] = 1+int(session['visits']) if prefs: giveprefs = [ tag for tag in lookup.getTags(conn, 'genre') if tag['tid'] in prefs ] else: giveprefs = [] return render_template('profile.html', page_title="{}'s Profile".format(username), username=username, uid=uid, prefs=giveprefs, allTags=allTags, stories=stories, currentUsername=currentUsername) else: flash('You are not logged in. Please login or join') return redirect(url_for('index'))
def recommendations(): if 'uid' in session: uid = session['uid'] conn = lookup.getConn(CONN) warnings = lookup.getTags(conn, 'warnings') username = session['username'] if 'username' in session else '' recs = lookup.getRecs(conn, uid, session['filters']) if not recs: flash("No works fitting your preferences were found") return render_template('search.html', resKind="Recs", res=recs, warnings=[], page_title="{}'s Home".format(username)) return redirect(url_for('index'))
def worksByTerm(search_kind, search_term): term = search_term kind = search_kind conn = lookup.getConn(CONN) if (request.method == "POST") and not (kind == "author"): filters = tuple(request.form.getlist('warnings[]')) res = lookup.searchWorks(conn, kind, term, filters) # if no search term, defaults to all movies else: res = (lookup.searchAuthors(conn, term) if kind == "author" else lookup.searchWorks(conn, kind, term, [])) resKind = "Authors" if kind == "author" else "Works" nm = "Tag" if (kind == "tag") else "Term" if not res: flash("No {} Found Including {}: {} :( ".format(resKind, nm, term)) # return "<p>{}</p>".format(str(res)) return render_template('search.html', resKind=resKind, term=term, res=res, warnings=lookup.getTags(conn, 'warnings'))
def addBookmark(): if 'uid' in session: book = request.form['changemark'] uid = session['uid'] sid = request.form['sid'] conn = lookup.getConn(CONN) isBooked = lookup.isBookmarked(conn, sid, uid) if isBooked and book == "Bookmarked": lookup.removeBookmark(conn, sid, uid) flash("Bookmark removed") elif isBooked is None and book == "Add Bookmark": lookup.addBookmark(conn, sid, uid) flash("Bookmark added") else: flash("Bookmark unchanged") return redirect(request.referrer) else: flash('Log in to bookmark works.') return redirect(url_for('index'))
def insert(): if request.method == "GET": return render_template('insert.html', page_title="Movie Insert") elif request.method == "POST": conn = lookup.getConn('achan_db') tid = request.form['movie-tt'] mtitle = request.form['movie-title'] year = request.form['movie-release'] #Error checking redirect = True #initialize to say whether to redirect or not if not tid.isdigit(): flash('error: tt must be numeric') redirect = False #will go back to the same page elif not year.isdigit(): flash('error: release year must be numeric') redirect = False elif lookup.checkMovie(tid) is not None: flash( 'error: Movie already exists. Movie with tt=%s is already in database', [tid]) redirect = False elif mtitle == "": flash('error: Missing title') redirect = False elif tid == "": flash('error: Missing tt') redirect = False elif year == "": flash('error: Missing year') redirect = False if redirect == False: #go back to the same page return redirect(url_for('insert', page_title="Movie Insert")) #Go to the update page lookup.insertMovie(conn, tid, mtitle, year) return redirect(url_for('update', tt=tid))
def addCommentAjax(): conn = lookup.getConn(CONN) commentText = request.form.get("commentText") print(commentText) cid = request.form.get('cid') cnum = request.form.get('cnum') sid = request.form.get('sid') try: if 'uid' in session: uid = session['uid'] lookup.addComment(conn, commentText, uid, cid) flash('Comment submitted!') return jsonify(error=False, commentText=commentText, uid=uid, cid=cid) else: flash("Log in before commenting.") return redirect(url_for('index')) except Exception as err: print(err) return jsonify({'error': True, 'err': str(err)})