Пример #1
0
    def test_update_username(self):
        before_where = {"username": "******"}
        after_where = {"username": "******"}

        assert len(
            list(self.db.select("bookshelves_books", where=before_where))) == 2
        Bookshelves.update_username("@kilgore_trout", "@anonymous")
        assert len(
            list(self.db.select("bookshelves_books", where=before_where))) == 0
        assert len(list(self.db.select("bookshelves_books",
                                       where=after_where))) == 2

        assert len(list(self.db.select("booknotes", where=before_where))) == 1
        Booknotes.update_username("@kilgore_trout", "@anonymous")
        assert len(list(self.db.select("booknotes", where=before_where))) == 0
        assert len(list(self.db.select("booknotes", where=after_where))) == 1

        assert len(list(self.db.select("ratings", where=before_where))) == 1
        Ratings.update_username("@kilgore_trout", "@anonymous")
        assert len(list(self.db.select("ratings", where=before_where))) == 0
        assert len(list(self.db.select("ratings", where=after_where))) == 1

        assert len(list(self.db.select("observations",
                                       where=before_where))) == 1
        Observations.update_username("@kilgore_trout", "@anonymous")
        assert len(list(self.db.select("observations",
                                       where=before_where))) == 0
        assert len(list(self.db.select("observations",
                                       where=after_where))) == 1
Пример #2
0
    def main(self, test=False):
        params = web.input(key='', test='')

        # Provide an escape hatch to let POST requests preview
        if test is False and params.test:
            test = True

        summary = {'key': params.key, 'redirect_chain': [], 'resolved_key': None}
        if params.key:
            redirect_chain = Work.get_redirect_chain(params.key)
            summary['redirect_chain'] = [
                {
                    "key": thing.key,
                    "occurrences": {},
                    "updates": {}
                } for thing in redirect_chain
            ]
            summary['resolved_key'] = redirect_chain[-1].key

            for r in summary['redirect_chain']:
                olid = r['key'].split('/')[-1][2:-1]
                new_olid = summary['resolved_key'].split('/')[-1][2:-1]

                # count reading log entries
                r['occurrences']['readinglog'] = len(
                    Bookshelves.get_works_shelves(olid))
                r['occurrences']['ratings'] = len(
                    Ratings.get_all_works_ratings(olid))
                r['occurrences']['booknotes'] = len(
                    Booknotes.get_booknotes_for_work(olid))
                r['occurrences']['observations'] = len(
                    Observations.get_observations_for_work(olid))

                # track updates
                r['updates']['readinglog'] = Bookshelves.update_work_id(
                    olid, new_olid, _test=test
                )
                r['updates']['ratings'] = Ratings.update_work_id(
                    olid, new_olid, _test=test
                )
                r['updates']['booknotes'] = Booknotes.update_work_id(
                    olid, new_olid, _test=test
                )
                r['updates']['observations'] = Observations.update_work_id(
                    olid, new_olid, _test=test
                )

        return delegate.RawText(
            json.dumps(summary), content_type="application/json")
Пример #3
0
    def GET(self, work_id):
        from openlibrary.core.ratings import Ratings
        stats = Ratings.get_work_ratings_summary(work_id)

        if stats:
            return json.dumps({
                'summary': {
                    'average': stats['ratings_average'],
                    'count': stats['ratings_count'],
                },
                'counts': {
                    '1': stats['ratings_count_1'],
                    '2': stats['ratings_count_2'],
                    '3': stats['ratings_count_3'],
                    '4': stats['ratings_count_4'],
                    '5': stats['ratings_count_5'],
                },
            })
        else:
            return json.dumps({
                'summary': {
                    'average': None,
                    'count': 0,
                },
                'counts': {
                    '1': 0,
                    '2': 0,
                    '3': 0,
                    '4': 0,
                    '5': 0,
                },
            })
Пример #4
0
    def test_delete_all_by_username(self):
        assert len(list(self.db.select("bookshelves_books"))) == 3
        Bookshelves.delete_all_by_username("@kilgore_trout")
        assert len(list(self.db.select("bookshelves_books"))) == 1

        assert len(list(self.db.select("booknotes"))) == 2
        Booknotes.delete_all_by_username('@kilgore_trout')
        assert len(list(self.db.select("booknotes"))) == 1

        assert len(list(self.db.select("ratings"))) == 2
        Ratings.delete_all_by_username("@kilgore_trout")
        assert len(list(self.db.select("ratings"))) == 1

        assert len(list(self.db.select("observations"))) == 2
        Observations.delete_all_by_username("@kilgore_trout")
        assert len(list(self.db.select("observations"))) == 1
Пример #5
0
 def get_rating_stats(self):
     work_id = extract_numeric_id_from_olid(self.key)
     rating_stats = Ratings.get_rating_stats(work_id)
     if rating_stats and rating_stats['num_ratings'] > 0:
         return {
             'avg_rating': round(rating_stats['avg_rating'], 2),
             'num_ratings': rating_stats['num_ratings']
         }
Пример #6
0
 def get_rating_stats(self):
     work_id = extract_numeric_id_from_olid(self.key)
     rating_stats = Ratings.get_rating_stats(work_id)
     if rating_stats and rating_stats['num_ratings'] > 0:
         return {
         'avg_rating': round(rating_stats['avg_rating'],2),
         'num_ratings': rating_stats['num_ratings']
         }
Пример #7
0
    def resolve_redirect_chain(cls,
                               work_key: str,
                               test: bool = False) -> dict[str, Any]:
        summary: dict[str, Any] = {
            'key': work_key,
            'redirect_chain': [],
            'resolved_key': None,
        }
        redirect_chain = cls.get_redirect_chain(work_key)
        summary['redirect_chain'] = [{
            "key": thing.key,
            "occurrences": {},
            "updates": {}
        } for thing in redirect_chain]
        summary['resolved_key'] = redirect_chain[-1].key

        for r in summary['redirect_chain']:
            olid = r['key'].split('/')[-1][2:-1]  # 'OL1234x' --> '1234'
            new_olid = summary['resolved_key'].split('/')[-1][2:-1]

            # count reading log entries
            r['occurrences']['readinglog'] = len(
                Bookshelves.get_works_shelves(olid))
            r['occurrences']['ratings'] = len(
                Ratings.get_all_works_ratings(olid))
            r['occurrences']['booknotes'] = len(
                Booknotes.get_booknotes_for_work(olid))
            r['occurrences']['observations'] = len(
                Observations.get_observations_for_work(olid))

            # track updates
            r['updates']['readinglog'] = Bookshelves.update_work_id(olid,
                                                                    new_olid,
                                                                    _test=test)
            r['updates']['ratings'] = Ratings.update_work_id(olid,
                                                             new_olid,
                                                             _test=test)
            r['updates']['booknotes'] = Booknotes.update_work_id(olid,
                                                                 new_olid,
                                                                 _test=test)
            r['updates']['observations'] = Observations.update_work_id(
                olid, new_olid, _test=test)
        return summary
Пример #8
0
    def generate_star_ratings(self, username):
        csv = []
        csv.append('Work ID,Edition ID,Rating,Created On')
        ratings = Ratings.select_all_by_username(username)

        for rating in ratings:
            row = [
                f"OL{rating['work_id']}W",
                f"OL{rating['edition_id']}M" if rating['edition_id'] else '',
                f"{rating['rating']}",
                rating['created'].strftime(self.date_format)
            ]
            csv.append(','.join(row))

        return '\n'.join(csv)
Пример #9
0
    def anonymize(self, test=False):
        # Generate new unique username for patron:
        # Note: Cannot test get_activation_link() locally
        uuid = (self.get_activation_link()['code']
                if self.get_activation_link() else generate_uuid())
        new_username = f'anonymous-{uuid}'
        results = {'new_username': new_username}

        # Delete all of the patron's book notes:
        results['booknotes_count'] = Booknotes.delete_all_by_username(
            self.username, _test=test)

        # Anonymize patron's username in OL DB tables:
        results['ratings_count'] = Ratings.update_username(self.username,
                                                           new_username,
                                                           _test=test)
        results['observations_count'] = Observations.update_username(
            self.username, new_username, _test=test)
        results['bookshelves_count'] = Bookshelves.update_username(
            self.username, new_username, _test=test)

        if not test:
            patron = self.get_user()
            email = self.email
            username = self.username

            # Remove patron from all usergroups:
            for grp in patron.usergroups:
                grp.remove_user(patron.key)

            # Set preferences to default:
            patron.save_preferences({'updates': 'no', 'public_readlog': 'no'})

            # Clear patron's profile page:
            data = {'key': patron.key, 'type': '/type/delete'}
            patron.set_data(data)

            # Remove account information from store:
            del web.ctx.site.store[f'account/{username}']
            del web.ctx.site.store[f'account/{username}/verify']
            del web.ctx.site.store[f'account/{username}/password']
            del web.ctx.site.store[f'account-email/{email}']

        return results
Пример #10
0
 def get_users_rating(self, username):
     if not username:
         return None
     work_id = extract_numeric_id_from_olid(self.key)
     rating = Ratings.get_users_rating_for_work(username, work_id)
     return rating
Пример #11
0
 def get_users_rating(self, username):
     if not username:
         return None
     work_id = extract_numeric_id_from_olid(self.key)
     rating = Ratings.get_users_rating_for_work(username, work_id)
     return rating
Пример #12
0
                    yield csv_format.format(**row)

        return "\n".join(lists_as_csv(lists))

    def generate_star_ratings(self, username: str) -> str:
        def format_rating(rating: Mapping) -> dict:
            if edition_id := rating.get("edition_id") or "":
                edition_id = f"OL{edition_id}M"
            return {
                "Work ID": f"OL{rating['work_id']}W",
                "Edition ID": edition_id,
                "Rating": f"{rating['rating']}",
                "Created On": rating['created'].strftime(self.date_format),
            }

        return csv_string(Ratings.select_all_by_username(username),
                          format_rating)


class account_loans(delegate.page):
    path = "/account/loans"

    @require_login
    def GET(self):
        user = accounts.get_current_user()
        user.update_loan_status()
        username = user['key'].split('/')[-1]

        return MyBooksTemplate(username, 'loans').render()