def get_book_by_id(id): books_query = Book.Book()\ .query('BOOKS.ID', 'BOOKS.GOODREADSID', 'BOOKS.ISBN', 'BOOKS.TITLE', 'BOOKS.GENRE', 'BOOKS.EXPIRES', 'BOOKS.AUTHORID', 'BOOKS.COVER', 'BOOKS.DELETED', 'AUTHORS.NAME', 'USERBOOKS.USERID')\ .join('AUTHORS', 'AUTHORID', 'ID')\ .join('USERBOOKS', 'ID', 'BOOKID')\ .where('BOOKS.ID', '=', id).get() if books_query: books_query = books_query[0] else: return {} user = User.User().query('*').where( 'ID', '=', books_query['USERBOOKS.USERID']).get()[0] book = {} book['user_id'] = user['ID'] book['username'] = user['USERNAME'] book['title'] = books_query['BOOKS.TITLE'].decode('cp1252') book['goodreads_id'] = books_query['BOOKS.GOODREADSID'] book['id'] = books_query['BOOKS.ID'] book['isbn'] = books_query['BOOKS.ISBN'].decode('cp1252') book['genre'] = books_query['BOOKS.GENRE'].decode('cp1252') book['expires'] = books_query['BOOKS.EXPIRES'].strftime('%d-%m-%Y') book['author'] = books_query['AUTHORS.NAME'].decode('cp1252') if books_query['BOOKS.COVER']: book['cover'] = books_query['BOOKS.COVER'].decode('cp1252') else: book['cover'] = '' return book
def match_book(variables={}, request={}): status = 'success' message = '' token = request.params['token'] receiver_id = request.params['receiverid'] book_id1 = request.params['bookid1'] book_id2 = request.params['bookid2'] user_dict = Token.Token().query("USERID").where("TOKEN", "=", token).get() book1_dict = Book.Book().query("TITLE").where("ID", "=", book_id1).get() book2_dict = Book.Book().query("TITLE").where("ID", "=", book_id2).get() if not book1_dict or not book2_dict: status = 'error' message = 'one of the books does not exist' else: exchange_dict = Exchange.Exchange().query("*").where("OWNERID", "=", user_dict[0]['USERID']). \ condition("AND", "BOOKID1", "=", book_id1). \ condition("AND", "RECEIVERID", "=", receiver_id).get() if not exchange_dict: status = 'error' message = 'the exchange does not exist' else: if exchange_dict[0]['ISFINISHED'] == 1: status = 'error' message = 'the exchange has already been approved/denied' else: if exchange_dict[0]['BOOKID2'] != None: status = 'error' message = 'you cannot respond to this exchange' else: Exchange.Exchange().update({ 'BOOKID2' : book_id2 }). \ where("OWNERID", "=", user_dict[0]['USERID']). \ condition("AND", "BOOKID1", "=", book_id1). \ condition("AND", "RECEIVERID", "=", receiver_id).execute() status = 'success' message = 'user responded to the exchange' result = {'status': status, 'message': message} return Controller.response_json(result)
def user_info(variables={}, request={}): id = request.params['id'] ok, error_message = Validator.validate([(id, r'^[0-9]|[1-9][0-9]+$', 'id value is invalid')]) user = {} try: if not ok: raise UserWaning(error_message) found_user = User.User().query('*').where('ID', '=', id).get() if not found_user: raise UserWarning('no such user') found_user = found_user[0] book_count = UserBook.UserBook().count().where( 'USERID', '=', found_user['ID']).get()[0] books_query = Book.Book()\ .query('BOOKS.ID')\ .join('USERBOOKS', 'ID', 'BOOKID')\ .where('USERBOOKS.USERID', '=', found_user['ID']).get() books = [] for book_result in books_query: book = BookController.get_book_by_id(book_result['BOOKS.ID']) books.append(book) location = Location.Location().query('*').where( 'USERID', '=', found_user['ID']).get() if location: location = location[0] else: location = dict() prefs = Preference.Preference().query('*').where( 'USERID', '=', found_user['ID']).get() if prefs: prefs = prefs[0] else: prefs = dict() user = { 'id': found_user['ID'], 'username': found_user['USERNAME'], 'first_name': found_user['FIRSTNAME'], 'last_name': found_user['LASTNAME'], 'country': location.get('COUNTRY', ''), 'city': location.get('CITY', ''), 'street': location.get('STREET', ''), 'email': found_user['EMAIL'], 'book_count': book_count['count'], 'books': books, 'title_preference': prefs.get('PREFERENCE', '') } except UserWarning, e: logging.exception('User warning') return Controller.response_json({'status': 'error', 'message': str(e)})
def recommended(variables={}, request={}): result = [] try: search_results = Book.Book().query('ID').get() logging.debug(search_results) for search_result in search_results[:10]: book = BookController.get_book_by_id(search_result['ID']) result.append(book) except UserWarning, e: logging.exception('User warning') return Controller.response_json({'status': 'error', 'message': str(e)})
def search(variables={}, request={}): keywords = request.params.get('keywords', '.*') authors = request.params.get('authors', '.*') genres = request.params.get('genres', '.*') before = request.params.get('before', '-') after = request.params.get('after', '-') location = request.params.get('location', '-') ok, error_message = Validator.validate([ (keywords, r'^\.\*|[a-zA-Z0-9,. \'"+-=;?]+$', 'keywords value is invalid'), (authors, r'^\.\*|[\w\'-, ]+$', 'authors value is invalid'), (genres, r'^\.\*|(%s)$' % ('|'.join(BookController.genres)), 'genres value is invalid'), (before, r'^\-|([1-9]|([012][0-9])|(3[01]))\-([0]{0,1}[1-9]|1[012])\-\d\d\d\d$', 'before value is invalid'), (after, r'^\-|([1-9]|([012][0-9])|(3[01]))\-([0]{0,1}[1-9]|1[012])\-\d\d\d\d$', 'after value is invalid'), ]) result = [] try: if not ok: raise UserWarning(error_message) search_results = Book.Book().query('BOOKS.ID', 'BOOKS.GOODREADSID', 'BOOKS.ISBN', 'BOOKS.TITLE', 'BOOKS.GENRE', 'BOOKS.EXPIRES', 'BOOKS.AUTHORID', 'BOOKS.COVER', 'AUTHORS.NAME')\ .join('AUTHORS', 'AUTHORID', 'ID')\ .where('BOOKS.title', 'REGEXP', '|'.join(keywords.split(',')))\ .condition('AND', 'BOOKS.GENRE', 'REGEXP', '|'.join(genres.split(',')))\ .condition('AND', 'AUTHORS.NAME', 'REGEXP', '|'.join(authors.split(','))) if before != '-': before = datetime.strptime(before, '%d-%m-%Y').strftime('%Y-%m-%d') search_results = search_results.condition('AND', 'BOOKS.EXPIRES', '<', before) if after != '-': after = datetime.strptime(after, '%d-%m-%Y').strftime('%Y-%m-%d') search_results = search_results.condition('AND', 'BOOKS.EXPIRES', '>', after) search_results = search_results.get() for search_result in search_results: book = BookController.get_book_by_id(search_result['BOOKS.ID']) result.append(book) except UserWarning, e: logging.exception('User warning') return Controller.response_json({'status': 'error', 'message': str(e)})
def propose_exchange(variables={}, request={}): status = 'success' message = '' token = request.params['token'] book_id = request.params['bookid'] dict_book = Book.Book().query("DELETED").where("ID", "=", book_id).get() if not dict_book: status = 'error' message = 'the book does not exist' elif (dict_book[0]['DELETED'] == 1): status = 'error' message = 'the book is not available for exchange' else: dict_receiver = Token.Token().query("USERID").where( "TOKEN", "=", token).get() dict_owner = UserBook.UserBook().query("USERID").where( "BOOKID", "=", book_id).get() logging.debug(dict_owner) if (dict_receiver[0]['USERID'] == dict_owner[0]['USERID']): status = 'error' message = 'users cannot send requests to themselves' else: dict_exchange = Exchange.Exchange().query('ID').where("OWNERID", "=", dict_owner[0]['USERID']). \ condition("AND", "RECEIVERID", "=", dict_receiver[0]['USERID']). \ condition("AND", "BOOKID1", "=", book_id).get() if (dict_exchange): status = 'error' message = 'the exchange already exists' else: date = datetime.datetime.now().strftime("%Y-%m-%d") insert_dict = { 'OWNERID': dict_owner[0]['USERID'], 'RECEIVERID': dict_receiver[0]['USERID'], 'BOOKID1': book_id, 'EXCHANGEDATE': date, 'ISFINISHED': 0, 'HASSUCCEEDED': 0 } message = 'the request has been registered' Exchange.Exchange().insert(insert_dict) result = {'status': status, 'message': message} return Controller.response_json(result)
def general_info(variables={}, request={}): users = 0 connections = 0 locations = 0 books = 0 authors = 0 genres = 0 try: users = User.User().count().get()[0]['count'] connections = Exchange.Exchange().count().get()[0]['count'] locations = Location.Location().count().get()[0]['count'] books = Book.Book().count().get()[0]['count'] authors = Author.Author().count().get()[0]['count'] genres = len(BookController.genres) except Exception, e: print str(e) pass
def get_user_books(variables={}, request={}): status = 'success' message = '' user_id = request.params.get('user', '') exchange_id = request.params.get('exchange_id', '') token = request.params.get('token', '') result = None try: books_query = Book.Book().query('ID').join('USERBOOKS', 'ID', 'BOOKID').where( 'USERBOOKS.USERID', '=', user_id).get() books = [ BookController.get_book_by_id(book['ID']) for book in books_query ] result = books except UserWarning, e: logging.exception('User warning') return Controller.response_json({'status': 'error', 'message': str(e)})
def add_book(variables={}, request={}): status = 'success' message = '' values = {} #title = request.params['title'] #author = request.params['author'] expires = request.params['expires'] genre = request.params['genre'] goodreads_id = request.params['goodreads_id'] ok, error_message = Validator.validate([ #(title, r'^[A-Za-z0-9\s\-_,\.;:()]+$', 'title value is invalid'), #(author, r'^[a-zA-Z0-9 ,.\'-]+$', 'author value is invalid'), (genre, r'^(%s)$' % ('|'.join(genres)), 'genre value is invalid'), (expires, r'^([1-9]|([012][0-9])|(3[01]))\-([0]{0,1}[1-9]|1[012])\-\d\d\d\d$', 'expires value is invalid'), (goodreads_id, r'^[0-9]|[1-9][0-9]+$', 'goodreads_id value is invalid'), ]) try: if not ok: raise UserWarning(error_message) book = Goodreads.find_book_by_id(int(goodreads_id)) if not book: raise UserWarning('no book with such id was found') current_user_id = Token.Token().query('USERID').where( 'TOKEN', '=', request.params['token']).get()[0]['USERID'] if not current_user_id or current_user_id == 0: raise UserWarning('invalid user connected to token') created_author = Author.Author().update_or_create( {'NAME': book['author']}, {'NAME': book['author']}) if not created_author: raise UserWarning('unable to create or update the book author') datetime_object = datetime.strptime(expires, '%d-%m-%Y') created_book = Book.Book().insert({ 'ISBN': book['isbn'], 'GOODREADSID': int(goodreads_id), 'TITLE': book['title'], 'GENRE': genre, 'COVER': book['image_url'], 'EXPIRES': datetime_object.strftime('%Y-%m-%d'), 'AUTHORID': created_author['ID'] }) if not created_book: raise UserWarning('unable to add book to the database') created_user_book = UserBook.UserBook().insert({ 'BOOKID': created_book['ID'], 'USERID': current_user_id }) if not created_user_book: raise UserWarning('unable to connect user to book') message = 'the book has been added' values['book_id'] = created_book['ID'] values['user_id'] = current_user_id values['author_id'] = created_author['ID'] except UserWarning, e: logging.exception('User Warning') return Controller.response_json({'status': 'error', 'message': str(e)})