Example #1
0
    def index(self, page=1, format='html'):
        """Retrieve a paginated list of uploaded packages.

        Arguments:
          page: The page of packages to get. Each page contains 10 packages.
        """
        if format == 'json':
            pager = QueryPager(int(page), "/packages.json?page=%d",
                               Package.all().order('-updated'),
                               per_page=50)
            return json.dumps({
                "packages": [
                    handlers.request().url(action='show', id=package.name)
                    for package in pager.get_items()
                ],
                "prev": pager.prev_url,
                "next": pager.next_url,
                "pages": pager.page_count
            })
        else:
            pager = QueryPager(int(page), "/packages?page=%d",
                               Package.all().order('-updated'))
            title = 'All Packages'
            if page != 1: title = 'Page %s | %s' % (page, title)
            return handlers.render("packages/index",
                                   packages=pager.get_items(),
                                   pagination=pager.render_pagination(),
                                   layout={'title': title})
Example #2
0
 def show(self, id, format='html'):
     """Retrieve the page describing a specific package."""
     if format == 'json':
         package = handlers.request().package
         cherrypy.response.headers['Content-Type'] = 'application/json'
         versions = [str(version.version) for version in package.version_set]
         return json.dumps({
             "name": package.name,
             "uploaders": [uploader.email() for uploader
                           in package.uploaders],
             "versions": versions
         })
     elif format == 'html':
         package = handlers.request().package
         version_count = package.version_set.count()
         title = package.name
         if package.latest_version:
             title = '%s %s' % (package.name, package.latest_version.version)
         return handlers.render(
             "packages/show", package=package,
             versions=package.version_set.order('-sort_order').fetch(10),
             version_count=version_count,
             show_versions_link=version_count > 10,
             is_uploader=users.get_current_user() in package.uploaders,
             layout={'title': title})
     else:
         raise handlers.http_error(404)
Example #3
0
 def show(self, id, format="html"):
     """Retrieve the page describing a specific package."""
     if format == "json":
         package = handlers.request().package
         versions = [str(version.version) for version in package.version_set]
         return json.dumps(
             {
                 "name": package.name,
                 "uploaders": [uploader.email() for uploader in package.uploaders],
                 "versions": versions,
             }
         )
     elif format == "html":
         package = handlers.request().package
         version_count = package.version_set.count()
         title = package.name
         if package.latest_version:
             title = "%s %s" % (package.name, package.latest_version.version)
         return handlers.render(
             "packages/show",
             package=package,
             versions=package.version_set.order("-sort_order").fetch(10),
             version_count=version_count,
             show_versions_link=version_count > 10,
             is_uploader=users.get_current_user() in package.uploaders,
             layout={"title": title},
         )
     else:
         raise handlers.http_error(404)
    def new(self, package_id, format="html", **kwargs):
        """Retrieve the form for uploading a package version.

        If the user isn't logged in, this presents a login screen. If they are
        logged in but don't have admin priviliges or don't own the package, this
        redirects to /packages/.

        This accepts arbitrary keyword arguments to support OAuth.
        """
        is_json = format == "json"
        user = handlers.get_current_user()

        package = handlers.request().maybe_package
        if not user:
            if is_json:
                handlers.http_error(403, "OAuth authentication failed.")
            else:
                raise cherrypy.HTTPRedirect(users.create_login_url(cherrypy.url()))
        elif package and user not in package.uploaders:
            message = "You aren't an uploader for package '%s'." % package.name
            if is_json:
                handlers.http_error(403, message)
            else:
                handlers.flash(message)
                raise cherrypy.HTTPRedirect("/packages/%s" % package.name)
        elif not handlers.is_current_user_admin():
            message = "Currently only admins may create packages."
            if is_json:
                handlers.http_error(403, message)
            else:
                handlers.flash(message)
                raise cherrypy.HTTPRedirect("/packages")
        elif PrivateKey.get() is None:
            if is_json:
                handlers.http_error(500, "No private key set.")
            else:
                raise cherrypy.HTTPRedirect("/admin#tab-private-key")

        id = str(uuid4())
        redirect_url = handlers.request().url(action="create", id=id)
        upload = cloud_storage.Upload(
            "tmp/" + id, acl="project-private", size_range=(0, Package.MAX_SIZE), success_redirect=redirect_url
        )

        # If the package hasn't been validated and moved out of tmp in five
        # minutes, delete it. This could happen if the user uploads the package
        # to cloud storage, but closes the browser before "create" is run.
        deferred.defer(self._remove_tmp_package, id, _countdown=5 * 60)

        if is_json:
            return upload.to_json()

        if package is not None:
            title = "Upload a new version of %s" % package.name
        else:
            title = "Upload a new package"

            return handlers.render(
                "packages/versions/new", form=upload.to_form(), package=package, layout={"title": title}
            )
Example #5
0
    def show(self, id, format='html'):
        """Retrieve the page describing a specific package."""
        if format == 'json':
            package = handlers.request().package
            versions = [str(version.version) for version in package.version_set]
            return json.dumps({
                "name": package.name,
                "uploaders": [uploader.email() for uploader
                              in package.uploaders],
                "versions": versions
            })
        elif format == 'html':
            package = handlers.request().package
            version_count = package.version_set.count()

            title = package.name
            readme = None
            readme_filename = None
            if package.latest_version:
                title = '%s %s' % (package.name, package.latest_version.version)
                if package.latest_version.readme:
                    readme = package.latest_version.readme.render()
                    readme_filename = package.latest_version.readme.filename;

            return handlers.render(
                "packages/show", package=package,
                versions=package.version_set.order('-sort_order').fetch(10),
                version_count=version_count,
                show_versions_link=version_count > 10,
                readme=readme,
                readme_filename=readme_filename,
                layout={'title': title})
        else:
            raise handlers.http_error(404)
 def index(self, package_id):
     """Retrieve a list of all versions for a given package."""
     package = handlers.request().package
     return handlers.render(
         "packages/versions/index", package=package,
         versions=package.version_set.order('-sort_order').run(),
         layout={'title': 'All versions of %s' % package.name})
Example #7
0
    def index(self, page=1, format='html'):
        """Retrieve a paginated list of uploaded packages.

        Arguments:
          page: The page of packages to get. Each page contains 10 packages.
        """
        if format == 'json':
            pager = Pager(int(page),
                          "/packages.json?page=%d",
                          Package.all().order('-updated'),
                          per_page=50)
            return json.dumps({
                "packages": [
                    handlers.request().url(action='show', id=package.name)
                    for package in pager.get_items()
                ],
                "prev":
                pager.prev_url,
                "next":
                pager.next_url,
                "pages":
                pager.page_count
            })
        else:
            pager = Pager(int(page), "/packages?page=%d",
                          Package.all().order('-updated'))
            title = 'All Packages'
            if page != 1: title = 'Page %s | %s' % (page, title)
            return handlers.render("packages/index",
                                   packages=pager.get_items(),
                                   pagination=pager.render_pagination(),
                                   layout={'title': title})
Example #8
0
def to_markdown(html_string, safe_tags=None, safe_attrs=None):
    """Convert the given HTML text fragment to Markdown.
    """
    # out = StringIO()
    # for f in parse_fragments(html_string, safe_tags=None, safe_attrs=None):
    #     handlers.process_tag_events(f, out)
    # return normalize(out.getvalue())
    return handlers.render(*parse_fragments(html_string, safe_tags))
Example #9
0
 def index(self, package_id):
     """Retrieve a list of all versions for a given package."""
     package = handlers.request().package
     return handlers.render(
         "packages/versions/index",
         package=package,
         versions=package.version_set.order('-sort_order').run(),
         layout={'title': 'All versions of %s' % package.name})
Example #10
0
    def to_form(self):
        """Return the HTML for a form for uploading a file to cloud storage."""

        # Get the fields into a format mustache can iterate over
        fields = [{'key': key, 'value': value}
                  for key, value in self._fields.iteritems()]

        return handlers.render(
            "signed_form", url=self._url, fields=fields, layout=False)
Example #11
0
def _error_page(status, message, traceback, version):
    # Don't show tracebacks to end users.
    if not handlers.is_dev_server() and not users.is_current_user_admin():
        traceback = None

    return str(
        handlers.render(
            "error", status=status, message=message, traceback=traceback, layout={"title": "Error %s" % status}
        )
    )
Example #12
0
    def index(self, page=1):
        """Retrieve a paginated list of uploaded packages.

        Arguments:
          page: The page of packages to get. Each page contains 10 packages.
        """
        pager = Pager(int(page), "/packages?page=%d", Package.all().order("-updated"))
        title = "All Packages"
        if page != 1:
            title = "Page %s | %s" % (page, title)
        return handlers.render(
            "packages/index", packages=pager.get_items(), pagination=pager.render_pagination(), layout={"title": title}
        )
Example #13
0
def _error_page(status, message, traceback, version):
    # Don't show tracebacks to end users.
    if not handlers.is_dev_server() and not users.is_current_user_admin():
        traceback = None

    if handlers.request().is_json:
        handlers.JsonError(status, message).set_response()
        return cherrypy.response.body

    return str(handlers.render('error',
        status=status,
        message=message,
        traceback=traceback,
        layout={'title': 'Error %s' % status}))
Example #14
0
def _error_page(status, message, traceback, version):
    # Don't show tracebacks to end users.
    if not handlers.is_dev_server() and not users.is_current_user_admin():
        traceback = None

    if handlers.request().is_json:
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps({'error': {'message': message}})

    return str(handlers.render('error',
        status=status,
        message=message,
        traceback=traceback,
        layout={'title': 'Error %s' % status}))
Example #15
0
def _error_page(status, message, traceback, version):
    # Don't show tracebacks to end users.
    if not handlers.is_dev_server() and not users.is_current_user_admin():
        traceback = None

    if handlers.request().is_json:
        handlers.JsonError(status, message).set_response()
        return cherrypy.response.body

    return str(
        handlers.render('error',
                        status=status,
                        message=message,
                        traceback=traceback,
                        layout={'title': 'Error %s' % status}))
Example #16
0
    def show(self, id, format='html'):
        """Retrieve the page describing a specific package."""
        if format == 'json':
            package = handlers.request().package
            versions = [
                str(version.version) for version in package.version_set
            ]
            return json.dumps({
                "name":
                package.name,
                "uploaders":
                [uploader.email() for uploader in package.uploaders],
                "versions":
                versions
            })
        elif format == 'html':
            package = handlers.request().package
            version_count = package.version_set.count()

            title = package.name
            readme = None
            readme_filename = None
            changelog = None
            changelog_filename = None
            if package.latest_version:
                title = '%s %s' % (package.name,
                                   package.latest_version.version)
                if package.latest_version.readme:
                    readme = package.latest_version.readme.render()
                    readme_filename = package.latest_version.readme.filename
                if package.latest_version.changelog:
                    changelog = package.latest_version.changelog.render()
                    changelog_filename = \
                            package.latest_version.changelog.filename

            return handlers.render(
                "packages/show",
                package=package,
                versions=package.version_set.order('-sort_order').fetch(10),
                version_count=version_count,
                show_versions_link=version_count > 10,
                readme=readme,
                readme_filename=readme_filename,
                changelog=changelog,
                changelog_filename=changelog_filename,
                layout={'title': title})
        else:
            raise handlers.http_error(404)
Example #17
0
    def index(self, q, page=1):
        """Format and display a list of search results.

        Arguments:
          q: The search query to perform.
          page: The page of results to get. Each page contains 10 results.
        """
        page = int(page)

        results, count = self._query_search(q, page)
        pager = SearchPager(page, q, count)

        return handlers.render("search",
             query=q,
             hasResults=len(results) != 0,
             results=results,
             pagination=pager.render_pagination(),
             layout={'title': 'Search Results for "' + q + '"'})
Example #18
0
    def admin(self):
        """Retrieve a page for performing administrative tasks."""

        if not users.get_current_user():
            raise cherrypy.HTTPRedirect(users.create_login_url(cherrypy.url()))
        elif not users.is_current_user_admin():
            raise handlers.http_error(403)

        reload_status = PackageVersion.get_reload_status()
        if reload_status is not None:
            reload_status['percentage'] = '%d%%' % (
                100.0 * reload_status['count'] / reload_status['total'])

        return handlers.render('admin',
               reload_status=reload_status,
               private_keys_set=PrivateKey.get_oauth() is not None,
               production=handlers.is_production(),
               layout={'title': 'Admin Console'})
Example #19
0
    def admin(self):
        """Retrieve a page for performing administrative tasks."""

        if not users.get_current_user():
            raise cherrypy.HTTPRedirect(users.create_login_url(cherrypy.url()))
        elif not users.is_current_user_admin():
            raise handlers.http_error(403)

        reload_status = PackageVersion.get_reload_status()
        if reload_status is not None:
            reload_status['percentage'] = '%d%%' % (
                100.0 * reload_status['count'] / reload_status['total'])

        return handlers.render('admin',
               reload_status=reload_status,
               private_keys_set=PrivateKey.get_oauth() is not None,
               production=handlers.is_production(),
               layout={'title': 'Admin Console'})
Example #20
0
    def admin(self):
        """Retrieve a page for performing administrative tasks."""

        if not users.get_current_user():
            raise cherrypy.HTTPRedirect(users.create_login_url(cherrypy.url()))
        elif not users.is_current_user_admin():
            raise handlers.http_error(403)

        reload_status = PackageVersion.get_reload_status()
        if reload_status is not None:
            reload_status["percentage"] = "%d%%" % (100.0 * reload_status["count"] / reload_status["total"])

        return handlers.render(
            "admin",
            reload_status=reload_status,
            private_key_set=PrivateKey.get() is not None,
            production=handlers.is_production(),
            layout={"title": "Admin Console"},
        )
Example #21
0
 def render_pagination(self):
     """Return the HTML for the pagination control."""
     return handlers.render("pagination", page_links=self._page_links,
                            layout=False)
Example #22
0
 def site_map(self):
     """Retrieves a map of the site."""
     return handlers.render("site_map", layout={"title": "Site Map"})
Example #23
0
 def site_map(self):
     """Retrieves a map of the site."""
     return handlers.render('site_map', layout={'title': 'Site Map'})
Example #24
0
 def authorized(self):
     """Retrieves the client authorization landing page."""
     return handlers.render(
         'authorized', layout={'title': 'Pub Authorized Successfully'})
Example #25
0
 def index(self):
     """Retrieves the front page of the package server."""
     packages = Package.all().order('-updated').fetch(5)
     return handlers.render('index', recent_packages=packages)
Example #26
0
 def search(self, **kwargs):
     """Exposes an embedded Google search."""
     return handlers.render('search', layout={'title': 'Search Pub'})
Example #27
0
 def render_pagination(self):
     """Return the HTML for the pagination control."""
     return handlers.render("pagination",
                            page_links=self._page_links,
                            layout=False)
Example #28
0
 def site_map(self):
     """Retrieves a map of the site."""
     return handlers.render('site_map', layout={'title': 'Site Map'})
Example #29
0
 def authorized(self):
     """Retrieves the client authorization landing page."""
     return handlers.render(
         'authorized', layout={'title': 'Pub Authorized Successfully'})
Example #30
0
 def index(self):
     """Retrieves the front page of the package server."""
     packages = Package.all().order('-updated').fetch(5)
     return handlers.render('index', recent_packages=packages)
Example #31
0
 def search(self, **kwargs):
     """Exposes an embedded Google search."""
     return handlers.render('search', layout={'title': 'Search Pub'})