def read(request): """Render the page for a group.""" if not request.feature('groups'): raise exc.HTTPNotFound() hashid = request.matchdict["hashid"] slug = request.matchdict.get("slug") group_id = hashids.decode(request, 'h.groups', hashid) group = models.Group.get_by_id(group_id) if group is None: raise exc.HTTPNotFound() if slug is None or slug != group.slug: return exc.HTTPMovedPermanently( location=logic.url_for_group(request, group)) if not request.authenticated_userid: return _login_to_join(request, group) else: user = accounts_models.User.get_by_userid(request.domain, request.authenticated_userid) if group in user.groups: return _read_group(request, group) else: return _join(request, group)
def check_slug(group, request): """Redirect if the request slug does not match that of the group.""" slug = request.matchdict.get('slug') if slug is None or slug != group.slug: path = request.route_path('group_read', pubid=group.pubid, slug=group.slug) raise httpexceptions.HTTPMovedPermanently(path)
def redirect_tween(request): for old_path, route_name in redirects: if request.path.startswith(old_path): url = request.route_url(route_name) suffix = request.path.replace(old_path, '', 1) return httpexceptions.HTTPMovedPermanently(location=(url + suffix)) return handler(request)
def short_ref_resolver(request): url_handler = Url(request, short_url=request.matchdict['short_ref']) try: plain_url = url_handler.resolve() except NotExists: raise httpexceptions.HTTPNotFound() raise httpexceptions.HTTPMovedPermanently(plain_url)
def short_ref_resolver(request): access = Access(utctime=datetime.utcnow(), referrer=request.referrer) try: plain_url = request.nurl.resolve(request.matchdict['short_ref'], access=access) except NotExists: raise httpexceptions.HTTPNotFound() from None raise httpexceptions.HTTPMovedPermanently(plain_url)
def submission_(request): username = request.matchdict.get('name') submitid = request.matchdict.get('submitid') form = request.web_input(submitid="", ignore="", anyway="") rating = define.get_rating(request.userid) submitid = define.get_int(submitid) if submitid else define.get_int(form.submitid) extras = { "pdf": True, } if define.user_is_twitterbot(): extras['twitter_card'] = submission.twitter_card(submitid) try: item = submission.select_view( request.userid, submitid, rating, ignore=define.text_bool(form.ignore, True), anyway=form.anyway ) except WeasylError as we: we.errorpage_kwargs = extras if 'twitter_card' in extras: extras['options'] = ['nocache'] if we.value in ("UserIgnored", "TagBlocked"): extras['links'] = [ ("View Submission", "?ignore=false"), ("Return to the Home Page", "/index"), ] raise login = define.get_sysname(item['username']) canonical_path = request.route_path('submission_detail_profile', name=login, submitid=submitid, slug=slug_for(item['title'])) if request.GET.get('anyway'): canonical_path += '?anyway=true' if login != username: raise httpexceptions.HTTPMovedPermanently(location=canonical_path) extras["canonical_url"] = canonical_path extras["title"] = item["title"] page = define.common_page_start(request.userid, **extras) page.append(define.render('detail/submission.html', [ # Myself profile.select_myself(request.userid), # Submission detail item, # Subtypes macro.MACRO_SUBCAT_LIST, # Violations [i for i in macro.MACRO_REPORT_VIOLATION if 2000 <= i[0] < 3000], ])) return Response(define.common_page_end(request.userid, page))
def redirect_legacy_content(request): """Redirect from legacy /content/id/version to new /contents/uuid@version. Handles collection context (book) as well. """ routing_args = request.matchdict objid = routing_args['objid'] objver = routing_args.get('objver') filename = routing_args.get('filename') id, version = _convert_legacy_id(objid, objver) if not id: raise httpexceptions.HTTPNotFound() if filename: with db_connect() as db_connection: with db_connection.cursor() as cursor: args = dict(id=id, version=version, filename=filename) cursor.execute(SQL['get-resourceid-by-filename'], args) try: res = cursor.fetchone() resourceid = res[0] raise httpexceptions.HTTPMovedPermanently( request.route_path('resource', hash=resourceid, ignore=u'/{}'.format(filename))) except TypeError: # None returned raise httpexceptions.HTTPNotFound() ident_hash = join_ident_hash(id, version) params = request.params if params.get('collection'): # page in book objid, objver = split_legacy_hash(params['collection']) book_uuid, book_version = _convert_legacy_id(objid, objver) if book_uuid: id, ident_hash = \ _get_page_in_book(id, version, book_uuid, book_version) raise httpexceptions.HTTPMovedPermanently( request.route_path('content', ident_hash=ident_hash))
def ident_hash_short_id(exc, request): try: uuid_ = get_uuid(exc.id) except httpexceptions.HTTPNotFound as e: return e if not exc.version: return ident_hash_missing_version( IdentHashMissingVersion(uuid_), request) route_name = request.matched_route.name route_args = request.matchdict.copy() route_args['ident_hash'] = join_ident_hash(uuid_, exc.version) return httpexceptions.HTTPMovedPermanently(request.route_path( route_name, _query=request.params, **route_args))
def shorten_redirect(request): url_short = request.matchdict.get('id') if url_short is None: raise exc.HTTPBadRequest('Please provide an id') table = get_table() if url_short == 'toolong': raise exc.HTTPFound(location='http://map.geo.admin.ch') try: url_short = table.get_item(url_short) url = url_short.get('url') except Exception as e: raise exc.HTTPBadRequest( 'This short url doesn\'t exist: s.geo.admin.ch/%s Error is: %s' % (url_short, e)) raise exc.HTTPMovedPermanently(location=url)
def shorten_redirect(request): url_short = request.matchdict.get('id') if url_short == 'toolong': raise exc.HTTPFound(location='http://map.geo.admin.ch') table = get_dynamodb_table(table_name='shorturl') try: url_short = table.get_item(url_short=url_short) url = url_short.get('url') except boto_exc.ItemNotFound as e: raise exc.HTTPNotFound('This short url doesn\'t exist: s.geo.admin.ch/%s Error is: %s' % (url_short, e)) except boto_exc.ProvisionedThroughputExceededException as e: # pragma: no cover raise exc.HTTPInternalServerError('Read units exceeded: %s' % e) except Exception as e: # pragma: no cover raise exc.HTTPInternalServerError('Unexpected internal server error: %s' % e) raise exc.HTTPMovedPermanently(location=url)
def __getitem__(self, identifier): """Get the requested resource from the database.""" try: item = (db.DBSession.query( self.table).filter_by(identifier=identifier).one()) except NoResultFound: # Attempt to redirect redirect = self._redirect(identifier) if redirect is None: raise KeyError else: dummy_request = pyramid.request.Request.blank('/') path = dummy_request.resource_path(redirect.__parent__, redirect.__name__) return httpexc.HTTPMovedPermanently(path, self.redirect_message) else: return item
def read(request): """Render the page for a group.""" pubid = request.matchdict["pubid"] slug = request.matchdict.get("slug") group = models.Group.get_by_pubid(request.db, pubid) if group is None: raise exc.HTTPNotFound() if slug is None or slug != group.slug: url = request.route_url('group_read', pubid=group.pubid, slug=group.slug) return exc.HTTPMovedPermanently(url) if not request.authenticated_userid: return _login_to_join(request, group) else: if group in request.authenticated_user.groups: return _read_group(request, group) else: return _join(request, group)
def redirect_to(url, permanent=False): if not permanent: raise x.HTTPFound(location=url) else: raise x.HTTPMovedPermanently(location=url)
def submission_(request): username = request.matchdict.get('name') submitid = request.matchdict.get('submitid') form = request.web_input(submitid="", ignore="", anyway="") rating = define.get_rating(request.userid) submitid = define.get_int(submitid) if submitid else define.get_int(form.submitid) extras = {} if not request.userid: # Only generate the Twitter/OGP meta headers if not authenticated (the UA viewing is likely automated). twit_card = submission.twitter_card(submitid) if define.user_is_twitterbot(): extras['twitter_card'] = twit_card # The "og:" prefix is specified in page_start.html, and og:image is required by the OGP spec, so something must be in there. extras['ogp'] = { 'title': twit_card['title'], 'site_name': "Weasyl", 'type': "website", 'url': twit_card['url'], 'description': twit_card['description'], # >> BUG AVOIDANCE: https://trello.com/c/mBx51jfZ/1285-any-image-link-with-in-it-wont-preview-up-it-wont-show-up-in-embeds-too # Image URLs with '~' in it will not be displayed by Discord, so replace ~ with the URL encoded char code %7E 'image': twit_card['image:src'].replace('~', '%7E') if 'image:src' in twit_card else define.cdnify_url( '/static/images/logo-mark-light.svg'), } try: item = submission.select_view( request.userid, submitid, rating, ignore=define.text_bool(form.ignore, True), anyway=form.anyway ) except WeasylError as we: we.errorpage_kwargs = extras if we.value in ("UserIgnored", "TagBlocked"): extras['links'] = [ ("View Submission", "?ignore=false"), ("Return to the Home Page", "/index"), ] raise login = define.get_sysname(item['username']) canonical_path = request.route_path('submission_detail_profile', name=login, submitid=submitid, slug=slug_for(item['title'])) if request.GET.get('anyway'): canonical_path += '?anyway=true' if login != username: raise httpexceptions.HTTPMovedPermanently(location=canonical_path) extras["canonical_url"] = canonical_path extras["title"] = item["title"] submission_files = item["sub_media"].get("submission") submission_file = submission_files[0] if submission_files else None extras["pdf"] = bool(submission_file) and submission_file["file_type"] == "pdf" page = define.common_page_start(request.userid, **extras) page.append(define.render('detail/submission.html', [ # Myself profile.select_myself(request.userid), # Submission detail item, # Subtypes macro.MACRO_SUBCAT_LIST, # Violations [i for i in macro.MACRO_REPORT_VIOLATION if 2000 <= i[0] < 3000], ])) return Response(define.common_page_end(request.userid, page))
def redirect(self, url_to, permanent=False): if permanent: raise exc.HTTPMovedPermanently(url_to) raise exc.HTTPFound(url_to)
def redirect(self, to_url, permanent=False): if permanent: raise exc.HTTPMovedPermanently(to_url) raise exc.HTTPFound(to_url)
def redirect_tween(request): url = lookup_redirects(redirects, request) if url is not None: return httpexceptions.HTTPMovedPermanently(location=url) return handler(request)
def slash_redirect(context, request): """Redirect away erroneous trailing slashes.""" return httpexc.HTTPMovedPermanently(request.path.rstrip('/'))