예제 #1
0
 def GET(self):
     return delegate.RawText("[]", content_type="application/json")
예제 #2
0
 def GET(self):
     libraries = inlibrary.get_libraries()
     web.header("Content-Type", "text/plain")
     return delegate.RawText(
         render_template("libraries/locations", libraries))
예제 #3
0
파일: code.py 프로젝트: mheiman/openlibrary
 def GET(self, today):
     json = web.ctx.site._conn.request(
         web.ctx.site.name, '/get', 'GET', {'key': '/admin/stats/' + today}
     )
     return delegate.RawText(json)
예제 #4
0
파일: edits.py 프로젝트: cdrini/openlibrary
 def GET(self):
     i = web.input(type=None, comment='')
     if i.type == 'comment':
         component = render_template('merge_queue/comment', comment_str=i.comment)
         return delegate.RawText(component)
예제 #5
0
def to_json(d):
    web.header('Content-Type', 'application/json')
    return delegate.RawText(simplejson.dumps(d))
예제 #6
0
    def GET(self):
        import guppy

        h = guppy.hpy()
        return delegate.RawText(str(h.heap()))
예제 #7
0
    def GET(self):
        i = web.input(username='', email='', key='')
        if i.key != lending.config_internal_tests_api_key:
            return delegate.RawText(
                json.dumps({'error': 'Authentication failed for private API'}),
                content_type="application/json",
            )
        try:
            if i.username:
                ol_account = OpenLibraryAccount.get(username=i.username)
            elif i.email:
                ol_account = OpenLibraryAccount.get(email=i.email)
        except Exception as e:
            return delegate.RawText(json.dumps({'error': 'bad-account'}),
                                    content_type="application/json")
        if ol_account:
            ol_account.enc_password = '******'
            if ol_account.itemname:
                return delegate.RawText(
                    json.dumps({
                        'status': 'link-exists',
                        'username': ol_account.username,
                        'itemname': ol_account.itemname,
                        'email': ol_account.email.lower(),
                    }),
                    content_type="application/json",
                )
            if not ol_account.itemname:
                ia_account = InternetArchiveAccount.get(
                    email=ol_account.email.lower())
                if ia_account:
                    ol_account.link(ia_account.itemname)
                    return delegate.RawText(
                        json.dumps({
                            'username': ol_account.username,
                            'status': 'link-found',
                            'itemname': ia_account.itemname,
                            'ol-itemname': ol_account.itemname,
                            'email': ol_account.email.lower(),
                            'ia': ia_account,
                        }),
                        content_type="application/json",
                    )

                password = OpenLibraryAccount.generate_random_password(16)
                ia_account = InternetArchiveAccount.create(
                    ol_account.username or ol_account.displayname,
                    ol_account.email,
                    password,
                    verified=True,
                    retries=USERNAME_RETRIES,
                )
                return delegate.RawText(
                    json.dumps({
                        'username': ol_account.username,
                        'email': ol_account.email,
                        'itemname': ia_account.itemname,
                        'password': password,
                        'status': 'link-created',
                    }),
                    content_type="application/json",
                )
예제 #8
0
 def GET(self, key, name, fmt):
     lst = web.ctx.site.get(key)
     if lst is None:
         raise web.notfound()
     text = getattr(self, 'GET_' + name + '_' + fmt)(lst)
     return delegate.RawText(text)
예제 #9
0
 def render_json(self, change):
     return delegate.RawText(simplejson.dumps(change.dict()),
                             content_type="application/json")
예제 #10
0
 def GET(self, key):
     lst = get_list_seeds(key)
     if not lst:
         raise web.notfound()
     return delegate.RawText(formats.dump(lst, self.encoding))
예제 #11
0
 def GET(self):
     web.header('Content-Type', 'application/json')
     output = simplejson.dumps({'success': False, 'error': 'Only POST is supported'})
     return delegate.RawText(output, content_type='application/json')
예제 #12
0
 def GET(self):
     return delegate.RawText(json.dumps(get_observations()),
                             content_type="application/json")
예제 #13
0
파일: edits.py 프로젝트: cdrini/openlibrary
    def POST(self):
        def response(status='ok', **kwargs):
            return {'status': status, **kwargs}

        i = web.input(
            work_ids="",  # Comma-separated OLIDs (OL1W,OL2W,OL3W,...,OL111W)
            rtype="merge-works",
            mrid=None,
            action=None,  # create, approve, decline, comment, unassign
            comment=None,
        )
        user = accounts.get_current_user()
        username = user['key'].split('/')[-1]
        if i.mrid:  # We are updating an existing merge request
            if i.action == 'comment':
                if i.comment:
                    CommunityEditsQueue.comment_request(i.mrid, username, i.comment)
                    return delegate.RawText(
                        json.dumps(response()), content_type="application/json"
                    )
                else:
                    return delegate.RawText(
                        json.dumps(
                            response(
                                status='error', error='No comment sent in request.'
                            )
                        )
                    )
            elif i.action == 'claim':
                result = CommunityEditsQueue.assign_request(i.mrid, username)
                return delegate.RawText(
                    json.dumps(response(**result)), content_type="application/json"
                )
            elif i.action == 'unassign':
                CommunityEditsQueue.unassign_request(i.mrid)
                status = get_status_for_view(CommunityEditsQueue.STATUS['PENDING'])
                return delegate.RawText(json.dumps(response(newStatus=status)))
            else:
                if i.action == "decline":
                    status = CommunityEditsQueue.STATUS['DECLINED']
                elif i.action == 'approve':
                    status = CommunityEditsQueue.STATUS['MERGED']
                CommunityEditsQueue.update_request_status(
                    i.mrid, status, username, comment=i.comment
                )
                return delegate.RawText(
                    json.dumps(response()), content_type="application/json"
                )
        elif i.rtype == "merge-works":
            if i.action == 'create':
                result = create_request(i.work_ids, username, i.comment)
                resp = (
                    response(id=result)
                    if result
                    else response(
                        status='error',
                        error='A request to merge these works has already been submitted.',
                    )
                )
                return delegate.RawText(
                    json.dumps(resp), content_type="application/json"
                )
예제 #14
0
 def GET(self, itemid):
     d = get_borrow_status(itemid,
                           include_resources=False,
                           include_ia=False)
     return delegate.RawText(simplejson.dumps(d),
                             content_type="application/json")
예제 #15
0
 def GET(self):
     user = accounts.get_current_user()
     user.update_loan_status()
     loans = borrow.get_loans(user)
     web.header('Content-Type', 'application/json')
     return delegate.RawText(json.dumps({"loans": loans}))
예제 #16
0
 def POST(self):
     """Internal private API required for testing on vagrant/localhost
     """
     return delegate.RawText(simplejson.dumps({}),
                             content_type="application/json")
예제 #17
0
 def GET(self):
     web.header('Content-Type', 'application/json')
     json = urllib.request.urlopen(
         "http://www.archive.org/download/stats/numUniqueIPsOL.json").read(
         )
     return delegate.RawText(json)
예제 #18
0
class lists_json(delegate.page):
    path = "(/(?:people|books|works|authors|subjects)/[^/]+)/lists"
    encoding = "json"
    content_type = "application/json"

    def GET(self, path):
        if path.startswith("/subjects/"):
            doc = subjects.get_subject(path)
        else:
            doc = web.ctx.site.get(path)
        if not doc:
            raise web.notfound()

        i = web.input(offset=0, limit=50)
        i.offset = h.safeint(i.offset, 0)
        i.limit = h.safeint(i.limit, 50)

        i.limit = min(i.limit, 100)
        i.offset = max(i.offset, 0)

        lists = self.get_lists(doc, limit=i.limit, offset=i.offset)
        return delegate.RawText(self.dumps(lists))

    def get_lists(self, doc, limit=50, offset=0):
        lists = doc.get_lists(limit=limit, offset=offset)
        size = len(lists)

        if offset or len(lists) == limit:
            # There could be more lists than len(lists)
            size = len(doc.get_lists(limit=1000))

        d = {
            "links": {
                "self": web.ctx.path
            },
            "size": size,
            "entries": [lst.preview() for lst in lists]
        }
        if offset + len(lists) < size:
            d['links']['next'] = web.changequery(limit=limit,
                                                 offset=offset + limit)

        if offset:
            offset = max(0, offset - limit)
            d['links']['prev'] = web.changequery(limit=limit, offset=offset)

        return d

    def forbidden(self):
        headers = {"Content-Type": self.get_content_type()}
        data = {"message": "Permission denied."}
        return web.HTTPError("403 Forbidden",
                             data=self.dumps(data),
                             headers=headers)

    def POST(self, user_key):
        # POST is allowed only for /people/foo/lists
        if not user_key.startswith("/people/"):
            raise web.nomethod()

        site = web.ctx.site
        user = site.get(user_key)

        if not user:
            raise web.notfound()

        if not site.can_write(user_key):
            raise self.forbidden()

        data = self.loads(web.data())
        # TODO: validate data

        seeds = self.process_seeds(data.get('seeds', []))

        lst = user.new_list(name=data.get('name', ''),
                            description=data.get('description', ''),
                            tags=data.get('tags', []),
                            seeds=seeds)

        try:
            result = site.save(lst.dict(),
                               comment="Created new list.",
                               action="lists",
                               data={
                                   "list": {
                                       "key": lst.key
                                   },
                                   "seeds": seeds
                               })
        except client.ClientException, e:
            headers = {"Content-Type": self.get_content_type()}
            data = {"message": e.message}
            raise web.HTTPError(e.status,
                                data=self.dumps(data),
                                headers=headers)

        web.header("Content-Type", self.get_content_type())
        return delegate.RawText(self.dumps(result))
예제 #19
0
    def POST(self, work_id):
        """
        Add a work (or a work and an edition) to a bookshelf.

        GET params:
        - edition_id str (optional)
        - action str: e.g. "add", "remove"
        - redir bool: if patron not logged in, redirect back to page after login
        - bookshelf_id int: which bookshelf? e.g. the ID for "want to read"?
        - dont_remove bool: if book exists & action== "add", don't try removal

        :param str work_id: e.g. OL123W
        :rtype: json
        :return: a list of bookshelves_affected
        """
        from openlibrary.core.models import Bookshelves

        user = accounts.get_current_user()
        i = web.input(
            edition_id=None,
            action="add",
            redir=False,
            bookshelf_id=None,
            dont_remove=False,
        )
        key = i.edition_id if i.edition_id else ('/works/OL%sW' % work_id)

        if not user:
            raise web.seeother('/account/login?redirect=%s' % key)

        username = user.key.split('/')[2]
        current_status = Bookshelves.get_users_read_status_of_work(username, work_id)

        try:
            bookshelf_id = int(i.bookshelf_id)
            shelf_ids = Bookshelves.PRESET_BOOKSHELVES.values()
            if bookshelf_id != -1 and bookshelf_id not in shelf_ids:
                raise ValueError
        except (TypeError, ValueError):
            return delegate.RawText(
                json.dumps({'error': 'Invalid bookshelf'}),
                content_type="application/json",
            )

        if (not i.dont_remove) and bookshelf_id == current_status or bookshelf_id == -1:
            work_bookshelf = Bookshelves.remove(
                username=username, work_id=work_id, bookshelf_id=current_status
            )

        else:
            edition_id = int(i.edition_id.split('/')[2][2:-1]) if i.edition_id else None
            work_bookshelf = Bookshelves.add(
                username=username,
                bookshelf_id=bookshelf_id,
                work_id=work_id,
                edition_id=edition_id,
            )

        if i.redir:
            raise web.seeother(key)
        return delegate.RawText(
            json.dumps({'bookshelves_affected': work_bookshelf}),
            content_type="application/json",
        )
예제 #20
0
파일: api.py 프로젝트: user404d/openlibrary
 def response(msg, status="success"):
     return delegate.RawText(simplejson.dumps({status: msg}),
                             content_type="application/json")
예제 #21
0
 def GET(self):
     i = web.input(type='', ids='')
     id_type = i.type
     ids = i.ids.split(',')
     result = self.get_book_availability(id_type, ids)
     return delegate.RawText(json.dumps(result), content_type="application/json")
예제 #22
0
파일: code.py 프로젝트: mheiman/openlibrary
 def POST_remove_tag(self, account, tag):
     account.remove_tag(tag)
     return delegate.RawText('{"ok": "true"}', content_type="application/json")
예제 #23
0
 def GET(self, username, key='want-to-read'):
     i = web.input(page=1, limit=5000)
     page = safeint(i.page, 1)
     limit = safeint(i.limit, 5000)
     # check if user's reading log is public
     user = web.ctx.site.get('/people/%s' % username)
     if not user:
         return delegate.RawText(
             json.dumps({'error': 'User %s not found' % username}),
             content_type="application/json",
         )
     is_public = user.preferences().get('public_readlog', 'no') == 'yes'
     logged_in_user = accounts.get_current_user()
     if (
         is_public
         or logged_in_user
         and logged_in_user.key.split('/')[-1] == username
     ):
         readlog = ReadingLog(user=user)
         books = readlog.get_works(key, page, limit)
         records_json = [
             {
                 'work': {
                     'title': w.get('title'),
                     'key': w.key,
                     'author_keys': [
                         a.author.get("key")
                         for a in w.get('authors', []) if a.author
                     ],
                     'author_names': [
                         str(a.author.name)
                         for a in w.get('authors', [])
                         if type(a.author) is not str
                     ],
                     'first_publish_year': w.first_publish_year or None,
                     'lending_edition_s': (
                         w._solr_data
                         and w._solr_data.get('lending_edition_s')
                         or None
                     ),
                     'edition_key': (
                         w._solr_data and w._solr_data.get('edition_key') or None
                     ),
                     'cover_id': (
                         w._solr_data and w._solr_data.get('cover_id') or None
                     ),
                     'cover_edition_key': (
                         w._solr_data
                         and w._solr_data.get('cover_edition_key')
                         or None
                     ),
                 },
                 'logged_edition': w.get('logged_edition') or None,
                 'logged_date': (
                     w.get('logged_date').strftime("%Y/%m/%d, %H:%M:%S")
                     if w.get('logged_date')
                     else None
                 ),
             }
             for w in books
         ]
         return delegate.RawText(
             json.dumps({'page': page, 'reading_log_entries': records_json}),
             content_type="application/json",
         )
     else:
         return delegate.RawText(
             json.dumps({'error': 'Shelf %s not found or not accessible' % key}),
             content_type="application/json",
         )
예제 #24
0
파일: code.py 프로젝트: mheiman/openlibrary
 def GET(self):
     web.header('Content-Type', 'application/json')
     text = requests.get(
         "http://www.archive.org/download/stats/numUniqueIPsOL.json"
     ).text
     return delegate.RawText(text)
예제 #25
0
 def GET(self, lst_key):
     image_bytes = render_list_preview_image(lst_key)
     web.header("Content-Type", "image/png")
     return delegate.RawText(image_bytes)