Exemple #1
0
def category(request, category_id):
    '''
    GET: Displays all posts visible to the user which fall under the supplied
         category ID.
    '''
    if not request.user.is_authenticated():
        return redirect('/login/')

    author = Author.objects.get(user=request.user)
    allAllowedPosts = Post.getAllowedPosts(author)

    try:
        category = Category.objects.get(id=int(category_id))
        postIds = PostCategory.objects.filter(post__in=allAllowedPosts,
                        category=category).values_list('post', flat=True)
        postsWithCategory = Post.objects.filter(id__in=postIds)
    except DoesNotExist:
        redirect('author.views.stream')

    if 'application/json' in request.META['HTTP_ACCEPT']:
        return HttpResponse(json.dumps([post.as_dict()
                                        for post in postsWithCategory]),
                            content_type='application/json')
    else:
        return HttpResponse(["%s\n" % obj.content
                                for obj in postsWithCategory],
                            content_type='text/plain')
Exemple #2
0
    def testGetPostsWithCategoryOne(self):
        """
        For all authors, test what they should be getting back when they
        request all viewable posts with category "one".
        """
        cat1 = Category.objects.get(name="one")

        user1 = User.objects.get(username="******")
        user2 = User.objects.get(username="******")
        user3 = User.objects.get(username="******")
        user4 = User.objects.get(username="******")

        author1 = Author.objects.get(user=user1)
        author2 = Author.objects.get(user=user2)
        author3 = Author.objects.get(user=user3)
        author4 = Author.objects.get(user=user4)

        for (u, a) in zip((user1, user2, user3, user4),
                          (author1, author2, author3, author4)):
            self.client.login(username=u, password="******")
            response = self.client.get("/categories/%d/" % cat1.id,
                                       HTTP_ACCEPT="application/json")

            responseContent = json.loads(response.content)
            allAllowedPosts = Post.getAllowedPosts(a)
            postIds = PostCategory.objects.filter(post__in=allAllowedPosts,
                                                  category=cat1).values_list(
                                                    'post', flat=True)
            postsWithCategory = Post.objects.filter(id__in=postIds)

            for post in postsWithCategory:
                self.assertTrue(post.as_dict() in responseContent,
                                "A category one post that was supposed to be " \
                                "viewable was not found")

            self.client.logout()
Exemple #3
0
def stream(request):
    """
    Returns the stream of an author (all posts author can view)
    If calling the function restfully, call by sending a GET request to /author/posts
    """
    if 'application/json' in request.META['HTTP_ACCEPT']:
        return getStream(request)
    elif 'text/html' in request.META['HTTP_ACCEPT']:
        if request.user.is_authenticated():
            context = RequestContext(request)
            author = Author.objects.get(user=request.user)
            comments = []
            authors = []
            categories = []
            visibilityExceptions = []
            images = []
            unlinkedImages = []

            linkedImageIds = ImagePost.objects.all().values_list('image', flat=True)
            unlinkedImageObjs = Image.objects.filter(Q(author=author), ~Q(id__in=linkedImageIds))

            for u in unlinkedImageObjs:
                unlinkedImages.append(u.as_dict())

            githubTemplateItems = cache.get('ge-'.join(author.guid)) or []

            # If cache is empty, force a GET request on GitHub
            if len(githubTemplateItems) == 0:
                githubTemplateItems = __queryGithubForEvents(author, useETag=False)

            rawposts = list(Post.getAllowedPosts(author, checkFollow=True))

            for post in rawposts:
                categoryIds = PostCategory.objects.filter(
                    post=post).values_list('category', flat=True)
                authorIds = PostVisibilityException.objects.filter(
                                post=post).values_list('author', flat=True)
                imageIds = ImagePost.objects.filter(post=post).values_list(
                                'image', flat=True)

                authors.append(AuthorPost.objects.get(post=post).author)
                comments.append(Comment.objects.filter(post_ref=post))
                categories.append(Category.objects.filter(id__in=categoryIds))
                visibilityExceptions.append(Author.objects.filter(
                    guid__in=authorIds))
                images.append(Image.objects.filter(id__in=imageIds))

                # Convert Markdown into HTML for web browser
                # django.contrib.markup is deprecated in 1.6, so, workaround
                if post.contentType == post.MARKDOWN:
                    post.content = markdown.markdown(post.content)

            # Stream payload
            serverPosts = zip(rawposts, authors, comments, categories,
                                   visibilityExceptions, images)

            externalPosts = []
            # Get the other server posts:
            servers = AllowedServer.objects.all()

            for server in servers:
                params = {"id": author.guid}
                headers = {"accept": "application/json"}
                try:
                    # another hack because what the heck is going on with /api/
                    if server.host == 'http://127.0.0.1:80/':
                        url = urljoin(server.host, "api/author/posts")
                        response = requests.get(url, headers=headers, params=params)
                    else:
                        url = urljoin(server.host, "author/posts")
                        response = requests.get(url, headers=headers, params=params)

                    response.raise_for_status()
                    jsonAllPosts = response.json()['posts']
                    # turn into a dummy post
                    for jsonPost in jsonAllPosts:
                        externalPosts.append(jsonPost)
                except Exception as e:
                    # print ("failed to get posts from {1},\n{0}".format(e, server))
                    # may cause IO error, commented out for stability
                    pass

            for externalPost in externalPosts:
                parsedPost = rawPostViewConverter(externalPost)
                if parsedPost != None:
                    serverPosts.append(parsedPost)

            context['posts'] = serverPosts + githubTemplateItems

            # In-place sort the posts by most recent pubDate
            context['posts'].sort(key=lambda x: x[0]['pubDate'], reverse=True)

            # Make a Post payload
            context['visibilities'] = Post.VISIBILITY_CHOICES
            context['contentTypes'] = Post.CONTENT_TYPE_CHOICES
            context['author_id'] = author.guid
            context['unlinked_images'] = unlinkedImages

            if 'text/html' in request.META['HTTP_ACCEPT']:
                return render_to_response('author/stream.html', context)
        else:
            if 'text/html' in request.META['HTTP_ACCEPT']:
                return redirect('/login/')
    else:
        return getStream(request)