def create(request): user = users.get_current_user() if not user: HttpResponseRedirect('/reader/') username = request.POST["username"] if not re.match(r"^\w{4,16}$", username): return index( request, "Username can contain only letters and digits, 4-16 characters long" ) r = Reader.byCurrentUser() if not r: r = Reader() r.name = request.POST["name"] r.username = username r.email = user.email() r.id = user.user_id() r.put() return HttpResponseRedirect('/reader')
def register(): body = request.get_json() hashed_password = generate_password_hash(body["password"], method="sha256") new_user = Reader(email=body['email'], password=hashed_password, is_active=True, username=body["username"]) Reader.create(new_user) return jsonify({'message': 'registered successfully'}), 200
def post(self): user = users.get_current_user() current_reader = self.find_current_reader() if current_reader is None: name = self.post_str('name') reader = Reader.all(keys_only=True).filter('name', name).get() if reader is not None: raise HTTPBadRequest("I'm afraid that name's already taken.") current_reader = Reader(emails=[user.email()], name=name) current_reader.put() self.add_flash("Account created successfully.") self.return_see_other('/') else: self.add_flash("You've already got an account!") self.return_return_see_other('/')
def delete(request, identifier): book = Book().get(identifier) readerBook = ReaderBook().byReaderAndBook(Reader.byCurrentUser(), book) readerBook.delete() return HttpResponseRedirect('/')
def index(request, username=None, state=None, page=1): reader = Reader.byUsername(username) if not reader: return HttpResponse('No such username') page = int(page) template_values = {} template_values["currentState"] = state template_values["readOnly"] = True template_values["books"] = [] template_values["toReadCount"] = reader.toReadCount template_values["inProgressCount"] = reader.inProgressCount template_values["finishedCount"] = reader.finishedCount template_values["totalCount"] = reader.totalCount # paging stuff paging.preparePagingTemplateForBookcase(template_values, reader, state, page) # end paging stuff for readerBook in ReaderBook.byReaderAndState(reader, state, page - 1): template_values["books"].append( mapping.toReaderBookTemplate(readerBook.book, readerBook)) template_values["navRoot"] = "/public/" + username return render(template_values)
def markAsTodo(request, identifier): book = Book().get(db.Key(identifier)) readerBook = ReaderBook.byReaderAndBook(Reader.byCurrentUser(), book) readerBook.state = 'unread' readerBook.put() return redirectToBook(book)
def post(self): user = users.get_current_user() if user is None: self.return_unauthorized() if 'associate' in self.request.POST: current_reader = self.find_current_reader() if current_reader is None: reader_key = self.post_str('reader_key') reader = Reader.get_reader(reader_key) if reader.proposed_email == user.email(): reader.proposed_email = '' reader.emails.append(user.email()) reader.put() self.add_flash( "The email address " + user.email() + " has been successfully associated with this reader.") self.return_see_other( '/view_reader?reader_key=' + str(reader.key())) else: self.return_ok( messages=[ "Can't associate " + user.email() + " with the account " + reader.name + """ because the email address you're signed in with doesn't match the proposed email address."""]) else: self.return_bad_request( messages=[ "The email address " + user.email() + """ is already associated with an account."""]) else: self.return_see_other('/')
def find(request, keyword = "", page = 1): page = int(page) if "keywords" in request.GET: keyword = request.GET["keywords"] results = [] if keyword: results = GoogleBooks().search(keyword, page) template_values = { 'totalResults': results.TotalResults, 'results': results.items, 'keywords' : keyword } paging.preparePagingTemplateForSearch(template_values, page, results.TotalResults) else: template_values = {} if Reader.byCurrentUser(): template_values["isLoggedIn"] = True # load template t = get_template('searchresults.html') html = t.render(Context(template_values)) return HttpResponse(html)
def index(request, username=None, state=None, page=1): reader = Reader.byUsername(username) if not reader: return HttpResponse('No such username') page = int(page) template_values = {} template_values["currentState"] = state template_values["readOnly"] = True template_values["books"] = [] template_values["toReadCount"] = reader.toReadCount template_values["inProgressCount"] = reader.inProgressCount template_values["finishedCount"] = reader.finishedCount template_values["totalCount"] = reader.totalCount # paging stuff paging.preparePagingTemplateForBookcase(template_values, reader, state, page) # end paging stuff for readerBook in ReaderBook.byReaderAndState(reader, state, page - 1): template_values["books"].append(mapping.toReaderBookTemplate(readerBook.book, readerBook)) template_values["navRoot"] = "/public/" + username return render(template_values)
def auto_login(self): auto = int(self.settings.get('auto_login', 0)) if not auto: return False logging.info("Auto login as user %s" % auto) self.set_secure_cookie("user_id", str(auto)) user = self.session.query(Reader).get(auto) if not user: logging.info("Init default auto login user") user = Reader(id=auto) user.init_default_user() user.save() login_time = int(time.time()) self.set_secure_cookie("lt", str(login_time)) self.add_msg("success", _("自动登录成功。")) return True
def find(request, keyword="", page=1): page = int(page) if "keywords" in request.GET: keyword = request.GET["keywords"] results = [] if keyword: results = GoogleBooks().search(keyword, page) template_values = { 'totalResults': results.TotalResults, 'results': results.items, 'keywords': keyword } paging.preparePagingTemplateForSearch(template_values, page, results.TotalResults) else: template_values = {} if Reader.byCurrentUser(): template_values["isLoggedIn"] = True # load template t = get_template('searchresults.html') html = t.render(Context(template_values)) return HttpResponse(html)
def get(self): reader_key = self.get_str("reader_key") reader = Reader.get_reader(reader_key) current_reader = self.require_current_reader() if current_reader.key() != reader.key(): self.return_forbidden() self.return_ok(self.page_fields(reader))
def update_reader(id_reader): body = request.get_json() reader_to_update = Reader.update(id_reader, body["name"], body["description"]) if reader_to_update: return reader_to_update.serialize() else: return "Couldn't update reader information", 404
def read_followers(): readers = Reader.read_all() followers = db.session.query(follower).all() each_data = [] result = [] for each_follower in followers: for reader in readers: follower_data = {} follower_username = Reader.read_username_by_id(each_follower[0]) if reader["id"] == each_follower[1]: follower_data["id_followed"] = each_follower[1] follower_data["username_followed"] = reader["username"] follower_data["id_follower"] = each_follower[0] follower_data["username_follower"] = follower_username result.append(follower_data) return jsonify(result)
def ajaxAddBook(request): reader = Reader.byCurrentUser() if not reader: return HttpResponse("Login or create account to add books") book = fetchCreateByISBN(request.POST["isbn"], invokeSearchByIsbn, True) createReaderBookIfNecessary(reader, book, request.POST["state"]) return HttpResponse("success")
def delete(request): r = Reader.byCurrentUser() if r: list = ReaderBook.all(keys_only=True).ancestor(r).fetch(1000) db.delete(list) r.delete() else: return HttpResponseRedirect('/') return HttpResponse(render('reader_delete_confirm.html', None))
def get(self): reader_key = self.get_str('reader_key') reader = Reader.get_reader(reader_key) current_reader = self.require_current_reader() if current_reader.key() != reader.key(): self.return_forbidden() self.return_ok( { 'reader': reader, 'meters': Meter.gql( "where reader = :1", current_reader).fetch(10)})
def markUnread(article_id): '''Logic to atomically mark an article as being unread by the logged in user''' #TODO: test it new_reader = Reader(user_id=current_user.id) #atomically add current user to readers of given article number_of_items_affected = Article.objects(id=article_id).update_one( add_to_set__readers=new_reader) if number_of_items_affected is 1: return jsonify(dict(status='Success')) else: return jsonify(dict(\ status = 'Error'\ , message = 'No articles matched the given id'\ ))
def index(request, error=None): user = users.get_current_user() loginUrl = users.create_login_url('/reader') if not user: return HttpResponseRedirect(loginUrl) r = Reader.byCurrentUser() if not r: r = Reader() template_values = { "isLoggedIn": True, "isNew": True, "name": "", "username": user.nickname(), "email": user.email() } else: template_values = { "isLoggedIn": True, "isNew": False, "name": r.name, "username": r.username, "email": r.email } template_values["logoutUrl"] = users.create_logout_url("/") if error: template_values["errorMsg"] = error html = render('reader.html', template_values) return HttpResponse(html)
def get_all_readers(): readers = Reader.read_all() result = [] for reader in readers: reader_data = {} reader_data['id'] = reader["id"] reader_data['email'] = reader["email"] reader_data["username"] = reader["username"] reader_data["name"] = reader["name"] reader_data["description"] = reader["description"] result.append(reader_data) return jsonify(result)
def export(request): reader = Reader().byCurrentUser() collection = ReaderBook.finishedBooks(reader) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' writer = csv.writer(response) writer.writerow(['Title', 'ISBN', 'My Rating', 'Date Read', 'Date Added']) for c in collection: title = c.book.title.replace('""', '') writer.writerow( [title, c.book.isbn, c.rating, c.finishedDate, c.created]) return response
def post(self): try: current_reader = self.require_current_reader() reader_key = self.post_str("reader_key") reader = Reader.get_reader(reader_key) if current_reader.key() != reader.key(): self.return_forbidden() if 'remove_email' in self.request.POST: email = self.get_str('email') if email in reader.emails: reader.emails.remove(email) reader.put() fields = self.page_fields(reader) fields['message'] = "Successfully removed email address." self.return_ok(fields) else: raise HTTPBadRequest("""That email isn't associated with the reader.""") elif 'proposed_email' in self.request.POST: proposed_email = self.post_str('proposed_email') reader.proposed_email = proposed_email.strip() reader.put() if len(proposed_email) == 0: message = """Proposed email address successfully set to blank.""" else: message = """Proposed email address set successfully. Now sign out and then sign in using the proposed email address""" self.return_ok(self.page_fields(reader, message)) elif 'delete' in self.request.POST: for meter in Meter.gql("where reader = :1", reader): meter.delete_meter() reader.delete() self.send_found('/welcome') else: name = self.post_str('name') reader.name = name reader.put() self.add_flash('Settings updated successfully.') self.return_see_other( '/view_reader?reader_key=' + str(reader.key())) except HTTPBadRequest as e: self.return_bad_request(self.page_fields(reader, str(e)))
def index(request): reader = Reader().byCurrentUser() fromDate = getPastDate(1) finished = ReaderBook.finishedBooks(reader, fromDate) # 12 months where each is a list to a book months = [[] for i in range(12)] for b in finished: if b.finishedDate: months[b.finishedDate.month - 1].append(b.book.title) tv = {} tv["months"] = months return render(tv)
def index(request, state=None, page=1): reader = Reader().byCurrentUser() user = users.get_current_user() page = int(page) template_values = {} if state: template_values["currentState"] = state else: template_values["currentState"] = "" if user: template_values["isLoggedIn"] = True else: template_values["isLoggedIn"] = False if not reader: template_values["loginUrl"] = users.create_login_url('/reader') else: template_values["hasReader"] = True template_values["books"] = [] template_values["toReadCount"] = reader.toReadCount template_values["inProgressCount"] = reader.inProgressCount template_values["finishedCount"] = reader.finishedCount template_values["totalCount"] = reader.totalCount template_values["showRatings"] = True # paging stuff paging.preparePagingTemplateForBookcase(template_values, reader, state, page) # end paging stuff if state == "unrated": collection = ReaderBook.byReaderUnrated(reader, page - 1) else: collection = ReaderBook.byReaderAndState(reader, state, page - 1) for readerBook in collection: template_values["books"].append( mapping.toReaderBookTemplate(readerBook.book, readerBook)) template_values["navRoot"] = "/bookcase" template_values["viewtype"] = "searchresult.html" return render(template_values)
def auto_login(self): auto = int(self.settings.get('auto_login', 0)) if not auto: return False logging.info("Auto login as user %s" % auto) self.set_secure_cookie("user_id", str(auto)) user = self.session.query(Reader).get(auto) if not user: logging.info("Init default auto login user") user = Reader(id=auto) user.init_default_user() user.save() self.add_msg("success", _("自动登录成功。")) return True
def index(request): reader = Reader().byCurrentUser() user = users.get_current_user() template_values = {} if user: template_values["isLoggedIn"] = True else: template_values["isLoggedIn"] = False if not reader: template_values["loginUrl"] = users.create_login_url('/reader') addedBooks = BookList.getUnread() finishedBooks = BookList.getFinished() inprogressBooks = BookList.getInProgress() template_values["addedBooks"] = [] template_values["finishedBooks"] = [] template_values["inprogressBooks"] = [] def appendBooks(bookList, viewList): if bookList is None: bookList = BookList() if bookList.list is None: bookList.list = () for key in bookList.list[0:5]: bookKey = db.Key(key) if bookKey.app() == "trackmybooks": bookKey = db.Key.from_path(*bookKey.to_path()) book = Book.get(bookKey) if book: viewList.append(mapping.toReaderBookTemplate(book, None)) appendBooks(addedBooks, template_values["addedBooks"]) appendBooks(finishedBooks, template_values["finishedBooks"]) appendBooks(inprogressBooks, template_values["inprogressBooks"]) t = get_template('index.html') html = t.render(Context(template_values)) return HttpResponse(html)
def get_all_reviews(): reviews = Review.read_all() readers = Reader.read_all() result = [] for review in reviews: for reader in readers: if reader["id"] == review["id_reader"]: review_data = {} review_data['id'] = review["id"] review_data['id_reader'] = review["id_reader"] review_data["id_book"] = review["id_book"] review_data["stars"] = review["stars"] review_data["review"] = review["review"] review_data["username"] = reader["username"] result.append(review_data) return jsonify(result)
def get(self): user = users.get_current_user() if user is None: self.return_ok({}) else: current_reader = self.find_current_reader() if current_reader is None: fields = {} proposed_readers = Reader.gql( "where proposed_email = :1", user.email()).fetch(10) if len(proposed_readers) > 0: fields['proposed_readers'] = proposed_readers self.return_ok(fields) else: if 'return_to' in self.request.GET: return_to = self.get_str('return_to') else: return_to = "/" self.return_found(return_to)
def addToReader(request): reader = Reader.byCurrentUser() if not reader: return HttpResponseRedirect('/') bookResult = SearchResult() bookResult.isbn = request.POST["isbn"] bookResult.detailUrl = request.POST["detailUrl"] bookResult.author = request.POST["author"] bookResult.title = request.POST["title"] bookResult.image = request.POST["image"] bookResult.imageSmall = request.POST["imageSmall"] bookResult.imageLarge = request.POST["imageLarge"] bookResult.numberOfPages = int(request.POST["numberOfPages"]) book = fetchCreateByISBN(request.POST["isbn"], bookResult, False) createReaderBookIfNecessary(reader, book, 'unread') return redirectToBook(book)
def layout(request): # get all the books within x amount of time layed out by date # go by each day from the earliest day # output day and the book that is being read on that day # and continue doing that until all the books have been output reader = Reader().byCurrentUser() fromDate = getPastDate(2) finished = ReaderBook.finishedBooks(reader, fromDate) currentDate = fromDate byDate = {} while currentDate <= datetime.date.today() + datetime.timedelta(days=1): list = matchedBookByDate(currentDate, finished) byDate[currentDate] = [] for b in list: byDate[currentDate].append(b.book.title) currentDate = currentDate + datetime.timedelta(days=1) return render_to_response('layout.html', {"data": sorted(byDate.iteritems())})
def viewByIsbn(request, isbn = ""): user = users.get_current_user() reader = None book = None readerBook = None if user: reader = Reader.byCurrentUser() book = fetchCreateByISBN(isbn, invokeSearchByIsbn, True) readerBook = ReaderBook.byReaderAndBook(reader, book) template_values = mapping.toReaderBookTemplate(book, readerBook) if not user: template_values["loginUrlToAdd"] = users.create_login_url('/book/isbn/' + isbn) else: if not reader: template_values["signupUrl"] = '/reader' return render(template_values)
def subscribe(rss_url): '''Logic to add a given rss feed to the db, if required, and subscribe the current user to this feed''' try: feed = Feed.get_or_construct(rss_url) except NotAFeed: return jsonify( dict(status='Error', message='The given url is not an rss feed url')) new_subscription = Subscription(feed_id=feed.id) #atomically add new feed subscription to current user number_of_items_affected = User.objects(id=current_user.id).update_one( add_to_set__subscriptions=new_subscription) new_reader = Reader(user_id=current_user.id) #add current user to readers of all articles in subscribed feed, currently cannot be chained into one statement for article in Article.objects( feed_id=feed.id).order_by("-time_stamp").limit(10): article.update(add_to_set__readers=new_reader) if number_of_items_affected is 1: return jsonify(dict(status='Success')) else: return jsonify(dict(\ status = 'Error'\ , message = 'Unable to subscribe'\ ))
def login(): body = request.get_json() if "x-access-tokens" not in request.headers: if not body or not body["email"] or not body["password"]: return make_response( "El email o la contraseña no son correctas"), 401 reader = Reader.read_by_email(body["email"]) if check_password_hash(reader.password, body["password"]): token = jwt.encode( { 'id': reader.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30) }, app.config['SECRET_KEY']) return jsonify({'token': token.decode('UTF-8')}), 200 return make_response("Error de login", 401) else: return make_response("Token válido", 200)
def viewByIsbn(request, isbn=""): user = users.get_current_user() reader = None book = None readerBook = None if user: reader = Reader.byCurrentUser() book = fetchCreateByISBN(isbn, invokeSearchByIsbn, True) readerBook = ReaderBook.byReaderAndBook(reader, book) template_values = mapping.toReaderBookTemplate(book, readerBook) if not user: template_values["loginUrlToAdd"] = users.create_login_url( '/book/isbn/' + isbn) else: if not reader: template_values["signupUrl"] = '/reader' return render(template_values)
def view(request, identifier): book = db.get(db.Key(identifier)) readerBook = ReaderBook.byReaderAndBook(Reader.byCurrentUser(), book) return render( mapping.toReaderBookTemplate(book, readerBook) )
def find_current_reader(self): user = users.get_current_user() if user is None: return None else: return Reader.gql("where emails = :1", user.email()).get()
# commiting tests db.session.add(book1) db.session.add(book2) db.session.commit() # show one of the tests print(book1,'\n') # show the same test but in json format print(book1.json()) print('='*140,'\n') # creating and commiting the reviewer reader = Reader(name ='Vítor Otto', age = '18', profession = 'Estudante', fav_book = book1) reader2 = Reader(name ='Carlos', age = '20', profession = 'Desempregado') db.session.add(reader) db.session.add(reader2) db.session.commit() print(reader,'\n') print(reader2,'\n') print(reader.json())
def view(request, identifier): book = db.get(db.Key(identifier)) readerBook = ReaderBook.byReaderAndBook(Reader.byCurrentUser(), book) return render(mapping.toReaderBookTemplate(book, readerBook))
def getCurrentUserBook(identifier): return ReaderBook.byReaderAndBook(Reader.byCurrentUser(), db.Key(identifier))
def post(self): if CONF.get("installed", True) != False: return {'err': 'installed', 'msg': _(u'不可重复执行安装操作')} code = self.get_argument("code", "").strip() email = self.get_argument("email", "").strip().lower() title = self.get_argument("title", "").strip() invite = self.get_argument("invite", "").strip() username = self.get_argument("username", "").strip().lower() password = self.get_argument("password", "").strip() if not username or not password or not email or not title: return {'err': 'params.invalid', 'msg': _(u'填写的内容有误')} if not re.match(RE_EMAIL, email): return {'err': 'params.email.invalid', 'msg': _(u'Email无效')} if len(username) < 5 or len(username) > 20 or not re.match( RE_USERNAME, username): return {'err': 'params.username.invalid', 'msg': _(u'用户名无效')} if len(password) < 8 or len(password) > 20 or not re.match( RE_PASSWORD, password): return {'err': 'params.password.invalid', 'msg': _(u'密码无效')} # 避免重复创建 user = self.session.query(Reader).filter( Reader.username == username).first() if not user: user = Reader() user.username = username user.name = username user.email = email user.avatar = "https://www.gravatar.com/avatar/" + hashlib.md5( email).hexdigest() user.create_time = datetime.datetime.now() user.update_time = datetime.datetime.now() user.access_time = datetime.datetime.now() user.active = True user.admin = True user.extra = {"kindle_email": ""} user.set_secure_password(password) try: user.save() except: import traceback logging.error(traceback.format_exc()) return {'err': 'db.error', 'msg': _(u'系统异常,请重试或更换注册信息')} args = loader.SettingsLoader() args.clear() import uuid # set a random secret args['cookie_secret'] = u"%s" % uuid.uuid1() args['site_title'] = title if invite == "true": args['INVITE_MODE'] = True args['INVITE_CODE'] = code else: args['INVITE_MODE'] = False return self.save_extra_settings(args)
def post(self): email = self.get_argument("email", "").strip() nickname = self.get_argument("nickname", "").strip() username = self.get_argument("username", "").strip().lower() password = self.get_argument("password", "").strip() if not nickname or not username or not password: return {'err': 'params.invalid', 'msg': _(u'用户名或密码无效')} if not re.match(RE_EMAIL, email): return {'err': 'params.email.invalid', 'msg': _(u'Email无效')} if len(username) < 5 or len(username) > 20 or not re.match( RE_USERNAME, username): return {'err': 'params.username.invalid', 'msg': _(u'用户名无效')} if len(password) < 8 or len(password) > 20 or not re.match( RE_PASSWORD, password): return {'err': 'params.password.invalid', 'msg': _(u'密码无效')} user = self.session.query(Reader).filter( Reader.username == username).first() if user: return {'err': 'params.username.exist', 'msg': _(u'用户名已被使用')} user = Reader() user.username = username user.name = nickname user.email = email user.avatar = "https://www.gravatar.com/avatar/" + hashlib.md5( email).hexdigest() user.create_time = datetime.datetime.now() user.update_time = datetime.datetime.now() user.access_time = datetime.datetime.now() user.active = False user.extra = {"kindle_email": ""} user.set_secure_password(password) try: user.save() except: import traceback logging.error(traceback.format_exc()) return {'err': 'db.error', 'msg': _(u'系统异常,请重试或更换注册信息')} self.send_active_email(user) return {'err': 'ok'}