Ejemplo n.º 1
0
 def thing_attr(self, thing, attr):
     if attr == "_fullname":
         return "LiveUpdateEvent_" + thing._id
     elif attr == "viewer_count":
         if thing.state == "live":
             return thing.active_visitors
         else:
             return None
     elif attr == "viewer_count_fuzzed":
         if thing.state == "live":
             return thing.active_visitors_fuzzed
         else:
             return None
     elif attr == "description_html":
         return filters.spaceCompress(
             filters.safemarkdown(thing.description, nofollow=True) or "")
     elif attr == "resources_html":
         return filters.spaceCompress(
             filters.safemarkdown(thing.resources, nofollow=True) or "")
     elif attr == "websocket_url":
         if thing.state == "live":
             return websockets.make_url(
                 "/live/" + c.liveupdate_event._id, max_age=24 * 60 * 60)
         else:
             return None
     else:
         return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 2
0
 def thing_attr(self, thing, attr):
     if attr == "_fullname":
         return "LiveUpdateEvent_" + thing._id
     elif attr == "viewer_count":
         if thing.state == "live":
             return thing.active_visitors
         else:
             return None
     elif attr == "viewer_count_fuzzed":
         if thing.state == "live":
             return thing.active_visitors_fuzzed
         else:
             return None
     elif attr == "total_views":
         # this requires an extra query, so we'll only show it in places
         # where we're just getting one event.
         if not hasattr(thing, "total_views"):
             return None
         return thing.total_views
     elif attr == "description_html":
         return filters.spaceCompress(
             filters.safemarkdown(thing.description, nofollow=True) or "")
     elif attr == "resources_html":
         return filters.spaceCompress(
             filters.safemarkdown(thing.resources, nofollow=True) or "")
     elif attr == "websocket_url":
         if thing.state == "live":
             return websockets.make_url(
                 "/live/" + thing._id, max_age=24 * 60 * 60)
         else:
             return None
     else:
         return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 3
0
 def thing_attr(self, thing, attr):
     if attr == "_fullname":
         return "LiveUpdateEvent_" + thing._id
     elif attr == "viewer_count":
         if thing.state == "live":
             return thing.active_visitors
         else:
             return None
     elif attr == "viewer_count_fuzzed":
         if thing.state == "live":
             return thing.active_visitors_fuzzed
         else:
             return None
     elif attr == "description_html":
         return filters.spaceCompress(
             filters.safemarkdown(thing.description, nofollow=True) or "")
     elif attr == "resources_html":
         return filters.spaceCompress(
             filters.safemarkdown(thing.resources, nofollow=True) or "")
     elif attr == "websocket_url":
         if thing.state == "live":
             return websockets.make_url(
                 "/live/" + thing._id, max_age=24 * 60 * 60)
         else:
             return None
     else:
         return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 4
0
 def thing_attr(self, thing, attr):
     if attr == "_fullname":
         return "LiveUpdateEvent_" + thing._id
     elif attr == "viewer_count":
         if thing.state == "live":
             return thing.active_visitors
         else:
             return None
     elif attr == "viewer_count_fuzzed":
         if thing.state == "live":
             return thing.active_visitors_fuzzed
         else:
             return None
     elif attr == "total_views":
         # this requires an extra query, so we'll only show it in places
         # where we're just getting one event.
         if not hasattr(thing, "total_views"):
             return None
         return thing.total_views
     elif attr == "description_html":
         return filters.spaceCompress(
             filters.safemarkdown(thing.description, nofollow=True) or "")
     elif attr == "resources_html":
         return filters.spaceCompress(
             filters.safemarkdown(thing.resources, nofollow=True) or "")
     elif attr == "websocket_url":
         if thing.state == "live":
             return websockets.make_url("/live/" + thing._id,
                                        max_age=24 * 60 * 60)
         else:
             return None
     else:
         return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 5
0
    def GET_tb(self, link):
        from r2.lib.media import thumbnail_url

        "/tb/$id36, show a given link with the toolbar"
        if not link:
            return self.abort404()
        elif link.is_self:
            return self.redirect(link.url)

        # if the domain is shame-banned, bail out.
        if is_shamed_domain(link.url, request.ip)[0]:
            self.abort404()

        if not link.subreddit_slow.can_view(c.user):
            self.abort403()

        if link.has_thumbnail:
            thumbnail = thumbnail_url(link)
        else:
            thumbnail = None

        res = Frame(title=link.title,
                    url=link.url,
                    thumbnail=thumbnail,
                    fullname=link._fullname)
        return spaceCompress(res.render())
Ejemplo n.º 6
0
    def thing_attr(self, thing, attr):
        from r2.models import Comment, Link, Subreddit
        if attr == 'link_id':
            return make_fullname(Link, thing.link_id)
        elif attr == "controversiality":
            return 1 if thing.is_controversial else 0
        elif attr == "editted" and not isinstance(thing.editted, bool):
            return (time.mktime(thing.editted.astimezone(pytz.UTC).timetuple())
                    - time.timezone)
        elif attr == 'subreddit':
            return thing.subreddit.name
        elif attr == 'subreddit_id':
            return thing.subreddit._fullname
        elif attr == "parent_id":
            if getattr(thing, "parent_id", None):
                return make_fullname(Comment, thing.parent_id)
            else:
                return make_fullname(Link, thing.link_id)
        elif attr == "body_html":
            return spaceCompress(safemarkdown(thing.body))
        elif attr == "gilded":
            return thing.gildings
        elif attr == "archived":
            return not thing.votable

        return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 7
0
 def cells(self, thing):
     cells = []
     for cell in thing.cells:
         thing.name = cell
         r = thing.part_render('cell_type', style = "html")
         cells.append(spaceCompress(r))
     return cells
Ejemplo n.º 8
0
    def GET_toolbar(self, link, url):
        """The visible toolbar, with voting buttons and all"""
        if url:
            url = demangle_url(url)

        if link:
            wrapped = wrap_links(link, wrapper=FrameToolbar, num=1)
        elif url:
            listing = hot_links_by_url_listing(url, sr=c.site, num=1, skip=True)
            if listing.things:
                wrapped = listing.things[0]
            else:
                wrapped = None
        else:
            return self.abort404()

        res = None
        if wrapped:
            res = wrapped
        elif url:
            res = FrameToolbar(link=None, title=None, url=url, expanded=False)

        if res:
            return spaceCompress(res.render())
        else:
            return self.abort404()
Ejemplo n.º 9
0
    def thing_attr(self, thing, attr):
        from r2.models import Comment, Link, Subreddit
        if attr == 'link_id':
            return make_fullname(Link, thing.link_id)
        elif attr == "controversiality":
            return 1 if thing.is_controversial else 0
        elif attr == "editted" and not isinstance(thing.editted, bool):
            return (
                time.mktime(thing.editted.astimezone(pytz.UTC).timetuple()) -
                time.timezone)
        elif attr == 'subreddit':
            return thing.subreddit.name
        elif attr == 'subreddit_id':
            return thing.subreddit._fullname
        elif attr == "parent_id":
            if getattr(thing, "parent_id", None):
                return make_fullname(Comment, thing.parent_id)
            else:
                return make_fullname(Link, thing.link_id)
        elif attr == "body_html":
            return spaceCompress(safemarkdown(thing.body))
        elif attr == "gilded":
            return thing.gildings

        return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 10
0
    def GET_tb(self, link):
        '''/tb/$id36, show a given link with the toolbar
        If the user doesn't have the toolbar enabled, redirect to comments
        page.
        
        '''
        from r2.lib.media import thumbnail_url
        if not link:
            return self.abort404()
        elif link.is_self:
            return self.redirect(link.url)
        elif not (c.user_is_loggedin and c.user.pref_frame):
            return self.redirect(link.make_permalink_slow(force_domain=True))
        
        # if the domain is shame-banned, bail out.
        if is_shamed_domain(link.url)[0]:
            self.abort404()
        
        if not link.subreddit_slow.can_view(c.user):
            self.abort403()

        if link.has_thumbnail:
            thumbnail = thumbnail_url(link)
        else:
            thumbnail = None

        res = Frame(
            title=link.title,
            url=match_current_reddit_subdomain(link.url),
            thumbnail=thumbnail,
            fullname=link._fullname,
        )
        return spaceCompress(res.render())
Ejemplo n.º 11
0
    def GET_button_content(self, url, title, css, vote, newwindow, width, link):
            
        
        # no buttons on domain listings
        if isinstance(c.site, DomainSR):
            c.site = Default
            return self.redirect(request.path + query_string(request.GET))

        #disable css hack 
        if (css != 'http://blog.wired.com/css/diggsocial.css' and
            css != 'http://www.wired.com/css/diggsocial.css'): 
            css = None 

        if link:
            url = link.url
        wrapper = make_wrapper(Button if vote else ButtonNoBody,
                               url = url, 
                               target = "_new" if newwindow else "_parent",
                               title = title, vote = vote, bgcolor = c.bgcolor,
                               width = width, css = css,
                               button = self.buttontype())

        l = self.get_wrapped_link(url, link, wrapper)
        res = l.render()
        c.response.content = spaceCompress(res)
        return c.response
Ejemplo n.º 12
0
    def GET_tb(self, link):
        '''/tb/$id36, show a given link with the toolbar
        If the user doesn't have the toolbar enabled, redirect to comments
        page.
        
        '''
        from r2.lib.media import thumbnail_url
        if not link:
            return self.abort404()
        elif not link.subreddit_slow.can_view(c.user):
            # don't disclose the subreddit/title of a post via the redirect url
            self.abort403()
        elif link.is_self:
            return self.redirect(link.url)
        elif not (c.user_is_loggedin and c.user.pref_frame):
            return self.redirect(link.make_permalink_slow(force_domain=True))
        
        # if the domain is shame-banned, bail out.
        if is_shamed_domain(link.url)[0]:
            self.abort404()

        if link.has_thumbnail:
            thumbnail = thumbnail_url(link)
        else:
            thumbnail = None

        res = Frame(
            title=link.title,
            url=match_current_reddit_subdomain(link.url),
            thumbnail=thumbnail,
            fullname=link._fullname,
        )
        return spaceCompress(res.render())
    def POST_request_promo(self, srnames):
        if not srnames:
            return

        srnames = srnames.split('+')

        # request multiple ads in case some are hidden by the builder due
        # to the user's hides/preferences
        response = adzerk_request(srnames)

        if not response:
            g.stats.simple_event('adzerk.request.no_promo')
            return

        res_by_campaign = {r.campaign: r for r in response}
        tuples = [promote.PromoTuple(r.link, 1., r.campaign) for r in response]
        builder = CampaignBuilder(tuples, wrap=default_thing_wrapper(),
                                  keep_fn=promote.is_promoted,
                                  num=1,
                                  skip=True)
        listing = LinkListing(builder, nextprev=False).listing()
        if listing.things:
            g.stats.simple_event('adzerk.request.valid_promo')
            w = listing.things[0]
            r = res_by_campaign[w.campaign]
            w.adserver_imp_pixel = r.imp_pixel
            w.adserver_click_url = r.click_url
            return spaceCompress(w.render())
        else:
            g.stats.simple_event('adzerk.request.skip_promo')
Ejemplo n.º 14
0
 def cells(self, thing):
     cells = []
     for cell in thing.cells:
         thing.name = cell
         r = thing.part_render('cell_type', style = "html")
         cells.append(spaceCompress(r))
     return cells
Ejemplo n.º 15
0
    def GET_tb(self, link):
        from r2.lib.media import thumbnail_url

        "/tb/$id36, show a given link with the toolbar"
        if not link:
            return self.abort404()
        elif link.is_self:
            return self.redirect(link.url)
        
        # if the domain is shame-banned, bail out.
        if is_shamed_domain(link.url, request.ip)[0]:
            self.abort404()
        
        if not link.subreddit_slow.can_view(c.user):
            self.abort403()

        if link.has_thumbnail:
            thumbnail = thumbnail_url(link)
        else:
            thumbnail = None

        res = Frame(title = link.title,
                    url = link.url,
                    thumbnail = thumbnail,
                    fullname = link._fullname)
        return spaceCompress(res.render())
Ejemplo n.º 16
0
    def GET_inner(self, link):
        """The intermediate frame that displays the comments side-bar
           on one side and the link on the other"""
        if not link:
            return self.abort404()

        res = InnerToolbarFrame(link = link, expanded = auto_expand_panel(link))
        return spaceCompress(res.render())
Ejemplo n.º 17
0
    def GET_inner(self, link):
        """The intermediate frame that displays the comments side-bar
           on one side and the link on the other"""
        if not link:
            return self.abort404()

        res = InnerToolbarFrame(link=link, expanded=auto_expand_panel(link))
        return spaceCompress(res.render())
Ejemplo n.º 18
0
Archivo: pages.py Proyecto: vin/reddit
 def ajax_render(self, style="html"):
     """Generates a 'rendering' of this item suitable for
     processing by JS for insert or removal from an existing
     UserList"""
     cells = []
     for cell in self.cells:
         r = Wrapped.part_render(self, 'cell_type', cell)
         cells.append(spaceCompress(r))
     return dict(cells=cells, id=self.type, name=self.name)
Ejemplo n.º 19
0
 def ajax_render(self, style="html"):
     """Generates a 'rendering' of this item suitable for
     processing by JS for insert or removal from an existing
     UserList"""
     cells = []
     for cell in self.cells:
         r = Wrapped.part_render(self, 'cell_type', cell)
         cells.append(spaceCompress(r))
     return dict(cells=cells, id=self.type, name=self.name)
Ejemplo n.º 20
0
 def rendered_data(self, thing):
     from r2.lib.filters import spaceCompress
     from r2.lib.template_helpers import replace_render
     from pylons import c
     listing = thing.listing if hasattr(thing, "listing") else None
     return dict(id = thing._fullname,
                 vl = self.points(thing),
                 content = spaceCompress(replace_render(listing, thing,
                                                        style=get_api_subtype())))
Ejemplo n.º 21
0
    def GET_tb(self, link):
        "/tb/$id36, show a given link with the toolbar"
        if not link:
            return self.abort404()

        res = Frame(title = link.title,
                    url = link.url,
                    fullname = link._fullname)
        return spaceCompress(res.render())
Ejemplo n.º 22
0
    def GET_tb(self, link):
        "/tb/$id36, show a given link with the toolbar"
        if not link:
            return self.abort404()
        elif link.is_self or not link.subreddit_slow.can_view(c.user):
            return self.redirect(link.url)

        res = Frame(title=link.title, url=link.url, fullname=link._fullname)
        return spaceCompress(res.render())
Ejemplo n.º 23
0
 def rendered_data(self, thing):
     from r2.lib.filters import spaceCompress
     from r2.lib.template_helpers import replace_render
     from pylons import c
     listing = thing.listing if hasattr(thing, "listing") else None
     return dict(id=thing._fullname,
                 vl=self.points(thing),
                 content=spaceCompress(
                     replace_render(listing, thing,
                                    style=get_api_subtype())))
Ejemplo n.º 24
0
    def GET_tb(self, link):
        "/tb/$id36, show a given link with the toolbar"
        if not link:
            return self.abort404()
        elif link.is_self or not link.subreddit_slow.can_view(c.user):
            return self.redirect(link.url)

        res = Frame(title = link.title,
                    url = link.url,
                    fullname = link._fullname)
        return spaceCompress(res.render())
Ejemplo n.º 25
0
    def GET_toolbar(self, link, url):
        """The visible toolbar, with voting buttons and all"""
        if url:
            url = demangle_url(url)

        if link:
            wrapped = wrap_links(link, wrapper=FrameToolbar, num=1)
        else:
            return self.abort404()

        return spaceCompress(wrapped.render())
Ejemplo n.º 26
0
    def GET_s(self, rest):
        """/s/http://..., show a given URL with the toolbar. if it's
           submitted, redirect to /tb/$id36"""
        force_html()
        path = demangle_url(request.fullpath)

        if not path:
            # it was malformed
            self.abort404()

        # if the domain is shame-banned, bail out.
        if is_shamed_domain(path)[0]:
            self.abort404()

        listing = hot_links_by_url_listing(path, sr=c.site, num=1)
        link = listing.things[0] if listing.things else None

        if c.cname and not c.authorized_cname:
            # In this case, we make some bad guesses caused by the
            # cname frame on unauthorised cnames. 
            # 1. User types http://foo.com/http://myurl?cheese=brie
            #    (where foo.com is an unauthorised cname)
            # 2. We generate a frame that points to
            #    http://www.reddit.com/r/foo/http://myurl?cnameframe=0.12345&cheese=brie
            # 3. Because we accept everything after the /r/foo/, and
            #    we've now parsed, modified, and reconstituted that
            #    URL to add cnameframe, we really can't make any good
            #    assumptions about what we've done to a potentially
            #    already broken URL, and we can't assume that we've
            #    rebuilt it in the way that it was originally
            #    submitted (if it was)
            # We could try to work around this with more guesses (by
            # having demangle_url try to remove that param, hoping
            # that it's not already a malformed URL, and that we
            # haven't re-ordered the GET params, removed
            # double-slashes, etc), but for now, we'll just refuse to
            # do this operation
            return self.abort404()

        if link:
            # we were able to find it, let's send them to the
            # link-id-based URL so that their URL is reusable
            return self.redirect(add_sr("/tb/" + link._id36))

        title = utils.domain(path)
        res = Frame(
            title=title,
            url=match_current_reddit_subdomain(path),
        )

        # we don't want clients to think that this URL is actually a
        # valid URL for search-indexing or the like
        request.environ['usable_error_content'] = spaceCompress(res.render())
        abort(404)
Ejemplo n.º 27
0
 def thing_attr(self, thing, attr):
     if attr == "_fullname":
         return "LiveUpdateEvent_" + thing._id
     elif attr == "viewer_count":
         return thing.active_visitors
     elif attr == "viewer_count_fuzzed":
         return thing.active_visitors_fuzzed
     elif attr == "description_html":
         return filters.spaceCompress(
             filters.safemarkdown(thing.description) or "")
     else:
         return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 28
0
    def GET_s(self, rest):
        """/s/http://..., show a given URL with the toolbar. if it's
           submitted, redirect to /tb/$id36"""
        force_html()
        path = demangle_url(request.fullpath)

        if not path:
            # it was malformed
            self.abort404()

        # if the domain is shame-banned, bail out.
        if is_shamed_domain(path)[0]:
            self.abort404()

        link = utils.link_from_url(path, multiple=False)

        if c.cname and not c.authorized_cname:
            # In this case, we make some bad guesses caused by the
            # cname frame on unauthorised cnames.
            # 1. User types http://foo.com/http://myurl?cheese=brie
            #    (where foo.com is an unauthorised cname)
            # 2. We generate a frame that points to
            #    http://www.reddit.com/r/foo/http://myurl?cnameframe=0.12345&cheese=brie
            # 3. Because we accept everything after the /r/foo/, and
            #    we've now parsed, modified, and reconstituted that
            #    URL to add cnameframe, we really can't make any good
            #    assumptions about what we've done to a potentially
            #    already broken URL, and we can't assume that we've
            #    rebuilt it in the way that it was originally
            #    submitted (if it was)
            # We could try to work around this with more guesses (by
            # having demangle_url try to remove that param, hoping
            # that it's not already a malformed URL, and that we
            # haven't re-ordered the GET params, removed
            # double-slashes, etc), but for now, we'll just refuse to
            # do this operation
            return self.abort404()

        if link:
            # we were able to find it, let's send them to the
            # link-id-based URL so that their URL is reusable
            return self.redirect(add_sr("/tb/" + link._id36))

        title = utils.domain(path)
        res = Frame(
            title=title,
            url=match_current_reddit_subdomain(path),
        )

        # we don't want clients to think that this URL is actually a
        # valid URL for search-indexing or the like
        request.environ['usable_error_content'] = spaceCompress(res.render())
        abort(404)
Ejemplo n.º 29
0
    def rendered_data(self, thing):
        from r2.lib.filters import spaceCompress
        from r2.lib.template_helpers import replace_render

        res = []
        for a in thing.things:
            a.listing = thing
            r = replace_render(thing, a, style='api')
            if isinstance(r, str):
                r = spaceCompress(r)
            res.append(r)
        return res
Ejemplo n.º 30
0
    def rendered_data(self, thing):
        from r2.lib.filters import spaceCompress
        from r2.lib.template_helpers import replace_render

        res = []
        for a in thing.things:
            a.listing = thing
            r = replace_render(thing, a, style = 'api')
            if isinstance(r, str):
                r = spaceCompress(r)
            res.append(r)
        return res
Ejemplo n.º 31
0
 def thing_attr(self, thing, attr):
     if attr == "_id":
         return str(thing._id)
     elif attr == "body_html":
         return filters.spaceCompress(filters.safemarkdown(thing.body, nofollow=True))
     elif attr == "author":
         if not thing.author.deleted:
             return thing.author.name
         else:
             return None
     elif attr == "stricken":
         return bool(thing.stricken)
     return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 32
0
 def thing_attr(self, thing, attr):
     if attr == "_id":
         return str(thing._id)
     elif attr == "body_html":
         return filters.spaceCompress(filters.safemarkdown(thing.body, nofollow=True))
     elif attr == "author":
         if not thing.author.deleted:
             return thing.author.name
         else:
             return None
     elif attr == "stricken":
         return bool(thing.stricken)
     return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 33
0
    def GET_toolbar(self, link, url):
        """The visible toolbar, with voting buttons and all"""
        if not link:
            link = utils.link_from_url(url, multiple=False)

        if link:
            link = list(wrap_links(link, wrapper=FrameToolbar))
        if link:
            res = link[0]
        elif url:
            res = FrameToolbar(link=None, title=None, url=url, expanded=False)
        else:
            self.abort404()
        return spaceCompress(res.render())
Ejemplo n.º 34
0
 def _update(obj):
     if isinstance(obj, (str, unicode)):
         return StringTemplate(obj).finalize(kw)
     elif isinstance(obj, dict):
         return dict((k, _update(v)) for k, v in obj.iteritems())
     elif isinstance(obj, (list, tuple)):
         return map(_update, obj)
     elif isinstance(obj, CacheStub) and kw.has_key(obj.name):
         r = kw[obj.name]
         if isinstance(r, (str, unicode)):
             r = spaceCompress(r)
         return r    
     else:
         return obj
Ejemplo n.º 35
0
Archivo: pages.py Proyecto: cmak/reddit
 def render(self, *a, **kw):
     """Overrides default Wrapped.render with two additions
        * support for rendering API requests with proper wrapping
        * support for space compression of the result
     In adition, unlike Wrapped.render, the result is in the form of a pylons
     Response object with it's content set.
     """
     res = Wrapped.render(self, *a, **kw)
     if is_api():
         res = json_respond(res)
     elif self.space_compress:
         res = spaceCompress(res)
     c.response.content = res
     return c.response
Ejemplo n.º 36
0
 def thing_attr(self, thing, attr):
     from r2.models import Comment, Link, Subreddit
     if attr == 'link_id':
         return make_fullname(Link, thing.link_id)
     elif attr == 'subreddit':
         return thing.subreddit.name
     elif attr == 'subreddit_id':
         return thing.subreddit._fullname
     elif attr == "parent_id":
         if getattr(thing, "parent_id", None):
             return make_fullname(Comment, thing.parent_id)
         else:
             return make_fullname(Link, thing.link_id)
     elif attr == "body_html":
         return spaceCompress(safemarkdown(thing.body))
     return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 37
0
 def thing_attr(self, thing, attr):
     from r2.models import Comment, Link, Subreddit
     if attr == 'link_id':
         return make_fullname(Link, thing.link_id)
     elif attr == 'subreddit':
         return thing.subreddit.name
     elif attr == 'subreddit_id':
         return thing.subreddit._fullname
     elif attr == "parent_id":
         if getattr(thing, "parent_id", None):
             return make_fullname(Comment, thing.parent_id)
         else:
             return make_fullname(Link, thing.link_id)
     elif attr == "body_html":
         return spaceCompress(safemarkdown(thing.body))
     return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 38
0
 def thing_attr(self, thing, attr):
     from r2.models import Comment, Link, Subreddit
     if attr == 'link_id':
         return make_fullname(Link, thing.link_id)
     elif attr == 'sr_id':
         if hasattr(thing, attr):
             return make_fullname(Subreddit, thing.sr_id)
         return None
     elif attr == "parent_id":
         try:
             return make_fullname(Comment, thing.parent_id)
         except AttributeError:
             return make_fullname(Link, thing.link_id)
     elif attr == "body_html":
         return spaceCompress(safemarkdown(thing.body))
     return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 39
0
    def GET_toolbar(self, link, url):
        """The visible toolbar, with voting buttons and all"""
        if not link:
            link = utils.link_from_url(url, multiple = False)

        if link:
            link = list(wrap_links(link, wrapper = FrameToolbar))
        if link:
            res = link[0]
        elif url:
            res = FrameToolbar(link = None,
                               title = None,
                               url = url,
                               expanded = False)
        else:
            self.abort404()
        return spaceCompress(res.render())
Ejemplo n.º 40
0
    def GET_tb(self, link):
        from r2.lib.media import thumbnail_url

        "/tb/$id36, show a given link with the toolbar"
        if not link:
            return self.abort404()
        elif link.is_self or not link.subreddit_slow.can_view(c.user):
            return self.redirect(link.url)

        if link.has_thumbnail:
            thumbnail = thumbnail_url(link)
        else:
            thumbnail = None

        res = Frame(title=link.title,
                    url=link.url,
                    thumbnail=thumbnail,
                    fullname=link._fullname)
        return spaceCompress(res.render())
Ejemplo n.º 41
0
    def thing_attr(self, thing, attr):
        from r2.models import Comment, Link, Subreddit

        if attr == "link_id":
            return make_fullname(Link, thing.link_id)
        elif attr == "editted" and not isinstance(thing.editted, bool):
            return time.mktime(thing.editted.astimezone(pytz.UTC).timetuple()) - time.timezone
        elif attr == "subreddit":
            return thing.subreddit.name
        elif attr == "subreddit_id":
            return thing.subreddit._fullname
        elif attr == "parent_id":
            if getattr(thing, "parent_id", None):
                return make_fullname(Comment, thing.parent_id)
            else:
                return make_fullname(Link, thing.link_id)
        elif attr == "body_html":
            return spaceCompress(safemarkdown(thing.body))
        return ThingJsonTemplate.thing_attr(self, thing, attr)
Ejemplo n.º 42
0
    def GET_tb(self, link):
        from r2.lib.media import thumbnail_url

        "/tb/$id36, show a given link with the toolbar"
        if not link:
            return self.abort404()
        elif link.is_self or not link.subsciteit_slow.can_view(c.user):
            return self.redirect(link.url)

        if link.has_thumbnail:
            thumbnail = thumbnail_url(link)
        else:
            thumbnail = None

        res = Frame(title = link.title,
                    url = link.url,
                    thumbnail = thumbnail,
                    fullname = link._fullname)
        return spaceCompress(res.render())
Ejemplo n.º 43
0
    def GET_tb(self, link):
        '''/tb/$id36, show a given link with the toolbar
        If the user doesn't have the toolbar enabled, redirect to comments
        page.
        
        '''
        from r2.lib.media import thumbnail_url
        redirect_url = None
        query_params = dict(request.GET)
        if not link:
            return self.abort404()
        elif not link.subreddit_slow.can_view(c.user):
            # don't disclose the subreddit/title of a post via the redirect url
            self.abort403()
        elif link.is_self:
            redirect_url = link.url
        elif not (c.user_is_loggedin and c.user.uses_toolbar):
            redirect_url = link.make_permalink_slow(force_domain=True)
        
        if redirect_url:
            if query_params:
                url = UrlParser(redirect_url)
                url.update_query(**query_params)
                redirect_url =  url.unparse()
            return self.redirect(redirect_url)

        # if the domain is shame-banned, bail out.
        if is_shamed_domain(link.url)[0]:
            self.abort404()

        if link.has_thumbnail:
            thumbnail = thumbnail_url(link)
        else:
            thumbnail = None

        res = Frame(
            title=link.title,
            url=match_current_reddit_subdomain(link.url),
            thumbnail=thumbnail,
            fullname=link._fullname,
        )
        return spaceCompress(res.render())
Ejemplo n.º 44
0
 def render(self, *a, **kw):
     """Overrides default Wrapped.render with two additions
        * support for rendering API requests with proper wrapping
        * support for space compression of the result
     In adition, unlike Wrapped.render, the result is in the form of a pylons
     Response object with it's content set.
     """
     try:
         res = Wrapped.render(self, *a, **kw)
         if is_api():
             res = json_respond(res)
         elif self.space_compress:
             res = spaceCompress(res)
         c.response.content = res
     except NoTemplateFound, e:
         # re-raise the error -- development environment
         if g.debug:
             s = sys.exc_info()
             raise s[1], None, s[2]
         # die gracefully -- production environment
         else:
             abort(404, "not found")
Ejemplo n.º 45
0
Archivo: pages.py Proyecto: vin/reddit
 def render(self, *a, **kw):
     """Overrides default Wrapped.render with two additions
        * support for rendering API requests with proper wrapping
        * support for space compression of the result
     In adition, unlike Wrapped.render, the result is in the form of a pylons
     Response object with it's content set.
     """
     try:
         res = Wrapped.render(self, *a, **kw)
         if is_api():
             res = json_respond(res)
         elif self.space_compress:
             res = spaceCompress(res)
         c.response.content = res
     except NoTemplateFound, e:
         # re-raise the error -- development environment
         if g.debug:
             s = sys.exc_info()
             raise s[1], None, s[2]
         # die gracefully -- production environment
         else:
             abort(404, "not found")
Ejemplo n.º 46
0
def responsive(res, space_compress=None):
    """
    Use in places where the template is returned as the result of the
    controller so that it becomes compatible with the page cache.
    """
    if space_compress is None:
        space_compress = not g.template_debug

    if is_api():
        res = res or u''
        if not c.allowed_callback and request.environ.get("WANT_RAW_JSON"):
            res = scriptsafe_dumps(res)
        else:
            res = websafe_json(simplejson.dumps(res))

        if c.allowed_callback:
            # Add a comment to the beginning to prevent the "Rosetta Flash"
            # XSS when an attacker controls the beginning of a resource
            res = "/**/%s(%s)" % (websafe_json(c.allowed_callback), res)
    elif space_compress:
        res = spaceCompress(res)
    return res
Ejemplo n.º 47
0
    def POST_request_promo(self):
        if not (c.site and c.site.name in g.cpm_beta_srs):
            return super(AdzerkApiController, self).POST_request_promo()

        srids = promote.srids_with_live_promos(c.user, c.site)
        if not srids:
            return

        if '' in srids:
            srnames = [Frontpage.name]
            srids.remove('')
        else:
            srnames = []

        srs = Subreddit._byID(srids, data=True, return_dict=False)
        srnames.extend(sr.name for sr in srs)

        # request multiple ads in case some are hidden by the builder due
        # to the user's hides/preferences
        response = adzerk_request(srnames, num_placements=g.az_selfserve_num_request)

        if not response:
            return

        res_by_campaign = {r.campaign: r for r in response}
        tuples = [promote.PromoTuple(r.link, 1., r.campaign) for r in response]
        builder = CampaignBuilder(tuples, wrap=default_thing_wrapper(),
                                  keep_fn=promote.is_promoted,
                                  num=1,
                                  skip=True)
        listing = LinkListing(builder, nextprev=False).listing()
        if listing.things:
            w = listing.things[0]
            r = res_by_campaign[w.campaign]
            w.adserver_imp_pixel = r.imp_pixel
            w.adserver_click_url = r.click_url
            return spaceCompress(w.render())
Ejemplo n.º 48
0
def test_spaceCompress():
    html = '   \t  test  \n    <br>  <br>  \v     foo    bar  \v\n\t  '
    shrunk = spaceCompress(html)
    assert len(shrunk) < len(html)
    assert re.match(r'test\s*<br>\s+<br>\s*foo\s+bar\s*', shrunk)
Ejemplo n.º 49
0
 def render(self, *a, **kw):
     res = Wrapped.render(self, *a, **kw)
     res = spaceCompress(res)
     return res
Ejemplo n.º 50
0
def mass_part_render(thing, **kw):
    from r2.lib.filters import spaceCompress
    return dict([(k, spaceCompress(thing.part_render(v)).strip(' ')) \
                 for k, v in kw.iteritems()])
Ejemplo n.º 51
0
 def process_rendered(self, res):
     if 'data' in res:
         if 'content' in res['data']:
             res['data']['content'] = spaceCompress(res['data']['content'])
     return res
Ejemplo n.º 52
0
 def GET_toolbar(self, link):
     if not link: return self.abort404()
     link_builder = IDBuilder((link._fullname, ))
     link_listing = LinkListing(link_builder, nextprev=False).listing()
     res = FrameToolbar(link=link_listing.things[0]).render()
     return spaceCompress(res)
Ejemplo n.º 53
0
def test_spaceCompress_bad_utf8():
    baddata = '\x80 ; \xbf ; \x80\xbf\x80\xbf\x80 ; \xc0 ; \xe0 ; \xf7\xf0'
    spaceCompress(baddata)