Ejemplo n.º 1
0
    def respond_to_edit_request(self, message):
        """ Responds to an edit request. The bot will parse the body of the message, looking for verse
        quotations. These will replace the quotations that were placed in the original response to the
        user. Once the comment has been successfully edited, the bot then sends a message to the user
        letting them know that their verse quotations have been updated. """

        try:
            comment_url = message.body[1:message.body.find("}")]
            comment = self.r.get_submission(comment_url)
        except:
            try:
                message.reply("An error occurred while processing your edit request. "
                    "Please make sure that you do not modify the subject line of your message to %s."
                    % REDDIT_USERNAME)
            except requests.exceptions.ConnectionError:
                pass
            return

        if message.author == comment.author and comment:
            verses = find_verses(message.body)
            if verses is not None:
                for reply in comment.comments[0].replies:
                    if str(reply.author) == REDDIT_USERNAME:
                        try:
                            self.log.info("%s has requested a comment edit..." % comment.author)
                            link = reply.permalink[24:comment.permalink.find("/", 24)]
                            response = Response(message, self.parser, comment_url)
                            for verse in verses:
                                book_name = books.get_book(verse[0])
                                if book_name is not None:
                                    v = Verse(book_name,  # Book
                                        verse[1],  # Chapter
                                        verse[3],  # Translation
                                        message.author,  # User
                                        link,  # Subreddit
                                        verse[2])  # Verse
                                    if not response.is_duplicate_verse(v):
                                        response.add_verse(v)
                            if len(response.verse_list) != 0:
                                message_response = ("*^This ^comment ^has ^been ^edited ^by ^%s.*\n\n" % message.author)
                                message_response += response.construct_message()
                                if message_response is not None:
                                    self.log.info("Editing %s's comment with updated verse quotations..." % message.author)
                                    database.remove_invalid_statistics(reply.body, link)
                                    reply.edit(message_response)
                                    database.update_db_stats(response.verse_list)
                                    try:
                                        message.reply("[Your triggered %s response](%s) has been successfully edited to reflect"
                                            " your updated quotations." % (REDDIT_USERNAME, comment_url))
                                    except requests.exceptions.ConnectionError:
                                        pass
                                    break
                        except:
                            raise
                            self.log.warning("Comment edit failed. Will try again later...")
                            break
Ejemplo n.º 2
0
def index_books(index_path, ids):
    connection = indexer_connection(index_path)
    try:
        for bookid in ids:
            book = books.get_book(bookid)
            doc = BookIndexer(book).document()
            connection.replace(doc)
            print 'indexed book:', bookid
    finally:
        connection.flush()
        connection.close()
Ejemplo n.º 3
0
def index_all(bookid, index_path):
    connection = indexer_connection(index_path)
    try:
        book = books.get_book(bookid)
        for obj in book.walk():
            indexer = Indexer.get(obj)
            doc = indexer(obj).document()
            connection.replace(doc)
    finally:
        connection.flush()
        connection.close()
Ejemplo n.º 4
0
def index_all(bookid, index_path):
    connection = indexer_connection(index_path)
    try:
        book = books.get_book(bookid)    
        for obj in book.walk():
            indexer = Indexer.get(obj)
            doc = indexer(obj).document()
            connection.replace(doc)
    finally:
        connection.flush()
        connection.close()
Ejemplo n.º 5
0
def index_books(index_path, ids):
    connection = indexer_connection(index_path)
    try:
        for bookid in ids:
            book = books.get_book(bookid)
            doc = BookIndexer(book).document()
            connection.replace(doc)
            print "indexed book:", bookid
    finally:
        connection.flush()
        connection.close()
Ejemplo n.º 6
0
    def respond_to_username_mention(self, msg):
        """ Responds to a username mention. This could either contain one or
        more valid Bible verse quotation requests, or it could simply be a
        username mention without any valid Bible verses. If there are valid
        Bible verses, VerseBot generates a response that contains the text
        from these quotations. Otherwise, the message is forwarded to the
        VerseBot admin for review.

        :param msg: The message that contains the username mention
        """
        verses = find_verses(msg.body)
        if verses is not None:
            response = Response(msg, self.parser)
            for verse in verses:
                book_name = books.get_book(verse[0])
                if book_name is not None:
                    v = Verse(
                        book_name,  # Book
                        verse[1],  # Chapter
                        verse[3],  # Translation
                        msg.author,  # User
                        msg.subreddit.display_name,  # Subreddit
                        verse[2])  # Verse
                    if not response.is_duplicate_verse(v):
                        response.add_verse(v)
            if len(response.verse_list) != 0:
                message_response = response.construct_message()
                if message_response is not None:
                    self.log.info("Replying to %s with verse quotations..." %
                                  msg.author)
                    try:
                        msg.reply(message_response)
                        database.update_db_stats(response.verse_list)
                        database.increment_comment_count()
                    except praw.errors.Forbidden:
                        # This message is unreachable.
                        pass
                    except praw.errors.APIException as err:
                        if err.error_type in ("TOO_OLD", "DELETED_LINK",
                                              "DELETED_COMMENT"):
                            self.log.warning("An error occurred while replying"
                                             " with error_type %s." %
                                             err.error_type)
        else:
            self.log.info("No verses found in this message. "
                          "Forwarding to /u/%s..." % VERSEBOT_ADMIN)
            try:
                self.r.send_message(
                    VERSEBOT_ADMIN, "Forwarded VerseBot Message",
                    "%s\n\n[[Link to Original Message](%s)]" %
                    (msg.body, msg.permalink))
            except requests.ConnectionError:
                pass
Ejemplo n.º 7
0
    def respond_to_username_mention(self, msg):
        """ Responds to a username mention. This could either contain one or
        more valid Bible verse quotation requests, or it could simply be a
        username mention without any valid Bible verses. If there are valid
        Bible verses, VerseBot generates a response that contains the text
        from these quotations. Otherwise, the message is forwarded to the
        VerseBot admin for review.

        :param msg: The message that contains the username mention
        """
        verses = find_verses(msg.body)
        if verses is not None:
            response = Response(msg, self.parser)
            for verse in verses:
                book_name = books.get_book(verse[0])
                if book_name is not None:
                    v = Verse(book_name,                   # Book
                              verse[1],                    # Chapter
                              verse[3],                    # Translation
                              msg.author,                  # User
                              msg.subreddit.display_name,  # Subreddit
                              verse[2])                    # Verse
                    if not response.is_duplicate_verse(v):
                        response.add_verse(v)
            if len(response.verse_list) != 0:
                message_response = response.construct_message()
                if message_response is not None:
                    self.log.info("Replying to %s with verse quotations..."
                                  % msg.author)
                    try:
                        msg.reply(message_response)
                        database.update_db_stats(response.verse_list)
                        database.increment_comment_count()
                    except praw.errors.Forbidden:
                        # This message is unreachable.
                        pass
                    except praw.errors.APIException as err:
                        if err.error_type in ("TOO_OLD", "DELETED_LINK",
                                              "DELETED_COMMENT"):
                            self.log.warning("An error occurred while replying"
                                             " with error_type %s."
                                             % err.error_type)
        else:
            self.log.info("No verses found in this message. "
                          "Forwarding to /u/%s..." % VERSEBOT_ADMIN)
            try:
                self.r.send_message(VERSEBOT_ADMIN,
                                    "Forwarded VerseBot Message",
                                    "%s\n\n[[Link to Original Message](%s)]"
                                    % (msg.body, msg.permalink))
            except requests.ConnectionError:
                pass
Ejemplo n.º 8
0
def get_reviews_by_book(cur, start, amount, bid, current_user_id):

    total_pages = get_total_pages(cur, QUERIES['reviews_by_book_count'] % bid)
    query = QUERIES['select_reviews_where'] % ('WHERE review.book_id = %s', '%s', '%s')
    book_info = books.get_book(cur,bid,current_user_id)

    cur.execute(query, (bid, amount, start))

    review_info = {'book_info': book_info, 'reviews': []}
    for  review_id, core_id, book_id, book_title, reviewer, login_name, date_reviewed, review_text in cur:
        review_info['reviews'].append({'core_id':core_id, 'id':review_id, 'book_id': book_id, 'book_title':book_title.decode('utf8', 'xmlcharrefreplace'), 'reviewer':reviewer, 'reviewer_name': login_name, 'date_reviewed': date_reviewed, 'review_text':review_text})

    return total_pages, review_info
Ejemplo n.º 9
0
def book(id):
    book = books.get_book(id)
    admin = users.is_admin()
    return render_template("book.html",
                           name=book[0],
                           genre=book[1],
                           author=book[2],
                           id=id,
                           admin=admin,
                           publisher=book[3],
                           published_in=book[4],
                           year=book[5],
                           isbn=book[6])
Ejemplo n.º 10
0
def reviewsit(id):
    book = books.get_book(id)
    name = book[0]
    reviewsit = reviews.get_reviews(id)
    count = reviews.get_count(id)
    if count == None:
        count = 0
    else:
        count = count[0]
    return render_template("reviews.html",
                           reviews=reviewsit,
                           id=id,
                           count=count,
                           name=name)
Ejemplo n.º 11
0
def get_review(cur,review_id):
    cur.execute('''
        SELECT review_id, core_id, book_id, book_title, reviewer, login_name, to_char(date_reviewed,'Mon. DD, YYYY'), review_text
        FROM review
        JOIN book USING (book_id)
        JOIN book_core USING (core_id)
        JOIN booknet_user ON reviewer = user_id
        WHERE review_id = %s
    ''', (review_id,))
    review_info = {}
    for  review_id, core_id, book_id, book_title, reviewer, login_name, date_reviewed, review_text in cur:
        review_info = {'core_id':core_id, 'id':review_id, 'book_id': book_id, 'book_title':book_title.decode('utf8', 'xmlcharrefreplace'),
                       'user_id':reviewer, 'reviewer': login_name, 'date_reviewed': date_reviewed, 'review_text':review_text}

    review_info['book'] = books.get_book(cur, review_info['book_id'])
    return review_info
Ejemplo n.º 12
0
def remove_book_from_list(cur, book_id, list_id):
    print "Book id for removing rating: %s" % book_id
    book_info = books.get_book(cur, book_id)
    # try:
    cur.execute('''
        DELETE FROM book_list
        WHERE book_id = %s AND list_id = %s
    ''', (book_id, list_id))
    # first two queries should be able to be combined
    if cur.rowcount == 1:
        message = "Book removed from list %s!" % (book_info['title'], list_id)
    else:
        message = "Unknown error!"
    # except Exception, e:
    #     message = errorcodes.lookup(e.pgcode[:2])


    # else:
    #     message = "User not currently authenticated!"

    return message
Ejemplo n.º 13
0
 async def send_verses(self, body, verses, user, channel, websocket):
     if verses is not None:
         response = Response(body, self.parser)
         for verse in verses:
             book_name = books.get_book(verse[0])
             if book_name is not None:
                 v = Verse(book_name,
                           verse[1],
                           verse[3],
                           user,
                           channel,
                           verse[2])
                 if not response.is_duplicate_verse(v):
                     response.add_verse(v)
         if len(response.verse_list) != 0:
             message_response = response.construct_message()
             if message_response is not None:
                 await self.send_message(message_response, channel,
                                         websocket)
     else:
         pass
Ejemplo n.º 14
0
def add_book_to_list(cur, user_id, form):
    create_status = True
    message = []
    book_id = form['book_id']

    if form['listRadioGroup'] == 'new':
        create_status, message, list_id = create_list(cur, form['newInputListName'], form['newInputListDesc'], user_id)
        if not create_status:
            return create_status, message, list_id
    else:
        list_id = form['inputListID']

    print "Book id for adding list: %s" % book_id
    book_info = books.get_book(cur, book_id)
    # try:
    cur.execute('''
        SELECT booklist_id
        FROM book_list
        WHERE book_id = %s AND list_id = %s
    ''', (book_id, list_id))
    # first two queries should be able to be combined
    if cur.rowcount == 1:
        message.append("%s already in list %s!" % (book_info['title'], list_id))
    else:
        cur.execute('''
          INSERT INTO book_list (book_id, list_id, date_added)
          VALUES(%s, %s, current_timestamp)
          RETURNING booklist_id
        ''', (book_info['core_id'], list_id))
        if cur.rowcount == 1:
            message.append("%s added to list %s!" % (book_info['title'], list_id))
        else:
            message.append("Unknown error!")

    # else:
    #     message = "User not currently authenticated!"

    return create_status, message, list_id
Ejemplo n.º 15
0
def get_log(cur,log_id):
    cur.execute('''
        SELECT log_id, core_id, book_id, book_title, reader, login_name, log_text, status, pages_read, to_char(date_started,'Mon. DD, YYYY') as date_started, to_char(date_completed,'Mon. DD, YYYY') as date_completed
        FROM user_log
        JOIN book USING (book_id)
        JOIN book_core USING (core_id)
        JOIN booknet_user ON reader = user_id
        WHERE log_id = %s
    ''', (log_id,))
    log_info = {}
    for  id, core_id, book_id, book_title, reader, login_name, log_text, status, pages_read, date_started, date_completed  in cur:
        if status == 1:
            status_text = "In-progress"
        elif status == 2:
            status_text = "Completed"
        else:
            status_text = "Unknown"
        log_info = {'core_id':core_id, 'id':id, 'book_id': book_id, 'book_title':book_title.decode('utf8', 'xmlcharrefreplace'),
                       'user_id':reader, 'reader': login_name, 'log_text': log_text, 'status': status, 'pages_read': pages_read,
                       'status_text': status_text, 'date_started': date_started, 'date_completed':date_completed}

    log_info['book'] = books.get_book(cur, log_info['book_id'])
    return log_info
Ejemplo n.º 16
0
def kirjantiedot(id):
    list = books.get_book(id)
    return render_template("book.html", id=id, book=list)
Ejemplo n.º 17
0
    def respond_to_edit_request(self, msg):
        """ Responds to an edit request. The bot will parse the body of the
        message, looking for verse quotations. These will replace the
        quotations that were placed in the original response to the user.
        Once the comment has been successfully edited, the bot then sends a
        message to the user letting them know that their verse quotations
        have been updated.

        :param msg: The message that contains the edit request
        """
        try:
            comment_url = re.search("\{(.*?)\}", msg.body).group(1)
            comment = self.r.get_submission(comment_url)
        except:
            try:
                msg.reply("An error occurred while processing your edit "
                          "request. Please make sure that you do not modify "
                          "the subject line of your message to %s."
                          % REDDIT_USERNAME)
            except requests.ConnectionError:
                pass
            return

        if msg.author == comment.author and comment:
            verses = find_verses(msg.body)
            if verses is not None:
                for reply in comment.comments[0].replies:
                    if str(reply.author) == REDDIT_USERNAME:
                        try:
                            self.log.info("%s has requested a comment edit..."
                                          % comment.author)
                            sub = re.search("/r/(.*?)/", comment_url).group(1)
                            response = Response(msg, self.parser, comment_url)
                            for verse in verses:
                                book_name = books.get_book(verse[0])
                                if book_name is not None:
                                    v = Verse(book_name,      # Book
                                              verse[1],       # Chapter
                                              verse[3],       # Translation
                                              msg.author,     # User
                                              sub,            # Subreddit
                                              verse[2])       # Verse
                                    if not response.is_duplicate_verse(v):
                                        response.add_verse(v)
                            if len(response.verse_list) != 0:
                                msg_response = ("*^This ^comment ^has ^been "
                                                "^edited ^by ^%s.*\n\n"
                                                % msg.author)
                                msg_response += response.construct_message()
                                if msg_response is not None:
                                    self.log.info("Editing %s's comment with "
                                                  "updated verse quotations..."
                                                  % msg.author)
                                    database.remove_invalid_stats(reply.body,
                                                                  sub)
                                    reply.edit(msg_response)
                                    database.update_db_stats(
                                        response.verse_list)
                                    try:
                                        msg.reply("[Your triggered %s "
                                                  "response](%s) has been "
                                                  "successfully edited to "
                                                  "reflect your updated "
                                                  "quotations."
                                                  % (REDDIT_USERNAME,
                                                     comment_url))
                                    except requests.ConnectionError:
                                        pass
                                    break
                        except:
                            self.log.warning("Comment edit failed. "
                                             "Will try again later...")
Ejemplo n.º 18
0
    def respond_to_edit_request(self, msg):
        """ Responds to an edit request. The bot will parse the body of the
        message, looking for verse quotations. These will replace the
        quotations that were placed in the original response to the user.
        Once the comment has been successfully edited, the bot then sends a
        message to the user letting them know that their verse quotations
        have been updated.

        :param msg: The message that contains the edit request
        """
        try:
            comment_url = re.search("\{(.*?)\}", msg.body).group(1)
            comment = self.r.get_submission(comment_url)
        except:
            try:
                msg.reply("An error occurred while processing your edit "
                          "request. Please make sure that you do not modify "
                          "the subject line of your message to %s." %
                          REDDIT_USERNAME)
            except requests.ConnectionError:
                pass
            return

        if msg.author == comment.author and comment:
            verses = find_verses(msg.body)
            if verses is not None:
                for reply in comment.comments[0].replies:
                    if str(reply.author) == REDDIT_USERNAME:
                        try:
                            self.log.info(
                                "%s has requested a comment edit..." %
                                comment.author)
                            sub = re.search("/r/(.*?)/", comment_url).group(1)
                            response = Response(msg, self.parser, comment_url)
                            for verse in verses:
                                book_name = books.get_book(verse[0])
                                if book_name is not None:
                                    v = Verse(
                                        book_name,  # Book
                                        verse[1],  # Chapter
                                        verse[3],  # Translation
                                        msg.author,  # User
                                        sub,  # Subreddit
                                        verse[2])  # Verse
                                    if not response.is_duplicate_verse(v):
                                        response.add_verse(v)
                            if len(response.verse_list) != 0:
                                msg_response = ("*^This ^comment ^has ^been "
                                                "^edited ^by ^%s.*\n\n" %
                                                msg.author)
                                msg_response += response.construct_message()
                                if msg_response is not None:
                                    self.log.info(
                                        "Editing %s's comment with "
                                        "updated verse quotations..." %
                                        msg.author)
                                    database.remove_invalid_stats(
                                        reply.body, sub)
                                    reply.edit(msg_response)
                                    database.update_db_stats(
                                        response.verse_list)
                                    try:
                                        msg.reply(
                                            "[Your triggered %s "
                                            "response](%s) has been "
                                            "successfully edited to "
                                            "reflect your updated "
                                            "quotations." %
                                            (REDDIT_USERNAME, comment_url))
                                    except requests.ConnectionError:
                                        pass
                                    break
                        except:
                            self.log.warning("Comment edit failed. "
                                             "Will try again later...")
Ejemplo n.º 19
0
    def respond_to_edit_request(self, message):
        """ Responds to an edit request. The bot will parse the body of the message, looking for verse
        quotations. These will replace the quotations that were placed in the original response to the
        user. Once the comment has been successfully edited, the bot then sends a message to the user
        letting them know that their verse quotations have been updated. """

        try:
            comment_url = message.body[1:message.body.find("}")]
            comment = self.r.get_submission(comment_url)
        except:
            try:
                message.reply(
                    "An error occurred while processing your edit request. "
                    "Please make sure that you do not modify the subject line of your message to %s."
                    % REDDIT_USERNAME)
            except requests.exceptions.ConnectionError:
                pass
            return

        if message.author == comment.author and comment:
            verses = find_verses(message.body)
            if verses is not None:
                for reply in comment.comments[0].replies:
                    if str(reply.author) == REDDIT_USERNAME:
                        try:
                            self.log.info(
                                "%s has requested a comment edit..." %
                                comment.author)
                            link = reply.permalink[24:comment.permalink.
                                                   find("/", 24)]
                            response = Response(message, self.parser,
                                                comment_url)
                            for verse in verses:
                                book_name = books.get_book(verse[0])
                                if book_name is not None:
                                    v = Verse(
                                        book_name,  # Book
                                        verse[1],  # Chapter
                                        verse[3],  # Translation
                                        message.author,  # User
                                        link,  # Subreddit
                                        verse[2])  # Verse
                                    if not response.is_duplicate_verse(v):
                                        response.add_verse(v)
                            if len(response.verse_list) != 0:
                                message_response = (
                                    "*^This ^comment ^has ^been ^edited ^by ^%s.*\n\n"
                                    % message.author)
                                message_response += response.construct_message(
                                )
                                if message_response is not None:
                                    self.log.info(
                                        "Editing %s's comment with updated verse quotations..."
                                        % message.author)
                                    database.remove_invalid_statistics(
                                        reply.body, link)
                                    reply.edit(message_response)
                                    database.update_db_stats(
                                        response.verse_list)
                                    try:
                                        message.reply(
                                            "[Your triggered %s response](%s) has been successfully edited to reflect"
                                            " your updated quotations." %
                                            (REDDIT_USERNAME, comment_url))
                                    except requests.exceptions.ConnectionError:
                                        pass
                                    break
                        except:
                            raise
                            self.log.warning(
                                "Comment edit failed. Will try again later...")
                            break
Ejemplo n.º 20
0
 def test_book_standardization(self):
     """ Tests book conversion to standardized book names. """
     self.assertTrue(books.get_book("1 Jn") == "1 John")
     self.assertTrue(books.get_book("ti") == "Titus")
     self.assertTrue(books.get_book("thisisntabook") == False)
Ejemplo n.º 21
0
    def test_book_standardization(self):
        """ Tests book conversion to standardized book names. """

        self.assertTrue(books.get_book("1 Jn") == "1 John")
        self.assertTrue(books.get_book("ti") == "Titus")
        self.assertTrue(books.get_book("thisisntabook") is None)