def publicPosts(request):

	'''List all public posts on the server'''


	if request.method == 'GET':
		# Default if not given
		page_num = request.GET.get('page', DEFAULT_PAGE_NUM)	
		page_size = request.GET.get('size', DEFAULT_PAGE_SIZE)
		
		# Get all local and global comments, combine and paginate results
		all_posts = Post.objects.filter(visibility='PUBLIC').order_by('-published')

		#for post in all_posts:
		#	print post.comments

		#num_comments = len(all_posts[0]['comments'])

		#print 'Comments: '
		#print num_comments

		# Need this here or else the pagination bitches about it being unicode
		page_num = int(page_num)


		# Get the right page
		pages = Paginator(all_posts, page_size)
		page = pages.page(page_num+1)
		data = page.object_list

		response_obj = {}
		response_obj['query'] = 'posts'
		response_obj['count'] = len(all_posts)
		response_obj['size'] = page_size

		if page.has_next():
			response_obj['next'] = settings.LOCAL_HOST + 'api/posts?page=' + str(page_num + 1) + '&size=' + str(page_size)
		if page.has_previous():
			response_obj['previous'] = settings.LOCAL_HOST + 'api/posts?page=' + str(page_num - 1) + '&size=' + str(page_size)

		serializer = PostSerializer(data, many=True)
		response_obj['posts'] = serializer.data

		return Response(response_obj)


	elif request.method == 'POST':
		'''This method POSTS '''

		
		auth = request.data['author']
		try:
			author = Author.objects.get(author_id = auth)
			print(author)
		except Exception, e:
			print 'No Author!'
			return Response("Not a valid author...", status=status.HTTP_400_BAD_REQUEST)

		try:
			post = Post(author = author)
			

			post.title = request.data['title']
			post.description = request.data['description']
			post.contentType = request.data['contentType']
			post.content  = request.data['content']
			post.visibility = request.data['visibility']
			post.categories = request.data['categories']
			post.set_source()
			post.set_origin()
			post.save()


			#post.set_origin()
			return Response("Post Successfully Added.", status=status.HTTP_201_CREATED)
		except:
			return Response("Post Not Added", status=status.HTTP_400_BAD_REQUEST)
예제 #2
0
    def create_new_post(request):
        # POST to http://service/author/posts
        # Create a post to the currently authenticated user

        # First get the information out of the request body
        size = len(request.body)

        #body = json.load(body)
        # body = dict(x.split("=") for x in body.split("&"))

        #post = body['post']
        post = request.POST

        new_post = Post()

        # Post ID's are created automatically in the database
        # new_post.id = post['id']                  #: "de305d54-75b4-431b-adb2-eb6b9e546013",

        #: "A post title about a post about web dev",
        new_post.title = post['title']

        # Source and origin are the same, and depend on the ID so we wait until after the post gets saved to
        # generate this URLS
        # new_post.source    = post['source']       #: "http://lastplaceigotthisfrom.com/posts/yyyyy"
        # new_post.origin    = post['origin']       #: "http://whereitcamefrom.com/posts/zzzzz"

        new_post.description = post[
            'description']  # : "This post discusses stuff -- brief",

        # If the post is an image, the content would have been provided as a file along with the upload
        if len(request.FILES) > 0:
            file_type = request.FILES['file'].content_type
            allowed_file_type_map = {
                'image/png': Post.TYPE_PNG,
                'image/jpg': Post.TYPE_JPEG
            }

            if file_type not in allowed_file_type_map.keys():
                return JsonResponse({
                    'success':
                    'false',
                    'msg':
                    f'You uploaded an image with content type: {file_type}, but only one of {allowed_file_type_map.keys()} is allowed'
                })

            new_post.contentType = allowed_file_type_map[
                file_type]  # : "text/plain"
            new_post.content = base64.b64encode(
                request.FILES['file'].read()).decode('utf-8')
        else:
            new_post.contentType = post['contentType']  # : "text/plain",
            new_post.content = post['content']  #: "stuffs",

        new_post.author = request.user  # the authenticated user

        # Categories added after new post is saved

        new_post.count = 0  #: 1023, initially the number of comments is zero
        new_post.size = size  #: 50, the actual size of the post in bytes

        # This is not a property that gets stored, but rather a link to the comments of this post that should
        # be generated on the fly.
        # new_post.next        = post['next']         #: "http://service/posts/{post_id}/comments",

        # We do not permit adding comments at the same time a post is created, so this field is not created
        # new_post.comments = post['comments']  #: LIST OF COMMENT,

        current_tz = pytz.timezone('America/Edmonton')
        timezone.activate(current_tz)
        #: "2015-03-09T13:07:04+00:00",
        new_post.published = str(datetime.datetime.now())
        new_post.visibility = post['visibility'].upper()  #: "PUBLIC",

        new_post.unlisted = True if 'unlisted' in post and post[
            'unlisted'] == 'true' else False  #: true

        new_post.save()

        # Now we can set source and origin
        new_post.source = settings.HOSTNAME + "/posts/" + str(new_post.id.hex)
        new_post.origin = settings.HOSTNAME + "/posts/" + str(new_post.id.hex)
        new_post.save()

        # Take the user uid's passed in and convert them into Authors to set as the visibleTo list
        uids = post.getlist('visibleTo')
        visible_authors = Author.objects.filter(uid__in=uids)
        for author in visible_authors:
            new_post.visibleTo.add(author)

        # Categories is commented out because it's not yet in the post data, uncomment once available
        for category in post['categories'].split('\r\n'):
            try:
                # Try connecting to existing categories
                cat_object = Category.objects.get(name=category)
            except Category.DoesNotExist as e:
                cat_object = Category.objects.create(
                    name=category)  # Create one if not
            new_post.categories.add(cat_object)  #: LIST,

        # for key in body.keys():
        #     print(f'{key}: {body[key]}')

        if len(request.FILES) > 0:
            # If they uploaded a file this is an ajax call and we need to return a JSON response
            return JsonResponse({'success': 'true', 'msg': new_post.id.hex})
        else:
            return redirect("/")
예제 #3
0
    def test_author_id_posts_visible_to_auth_user(self):
        author1 = Author(username="******",
                         email="*****@*****.**",
                         password="******",
                         first_name="test",
                         last_name="test",
                         host="testserver",
                         is_active=1)
        author1.uid = "testserver/author/" + str(author1.id)
        author1.save()
        author2 = Author(username="******",
                         email="*****@*****.**",
                         password="******",
                         first_name="post",
                         last_name="post",
                         host="testserver",
                         is_active=1)
        author2.uid = "testserver/author/" + str(author2.id)
        author2.save()
        author3 = Author(username="******",
                         email="post_friend@post_friend.com",
                         password="******",
                         first_name="post_friend",
                         last_name="post_friend",
                         host="testserver",
                         is_active=1)
        author3.uid = "testserver/author/" + str(author3.id)
        author3.save()
        friendship = [
            # author1 and author2 are friends
            Friend(author_id=author1.uid, friend_id=author2.uid),
            Friend(author_id=author2.uid, friend_id=author1.uid),
            # author2 and author3 are friends
            Friend(author_id=author2.uid, friend_id=author3.uid),
            Friend(author_id=author3.uid, friend_id=author2.uid),
        ]
        for friends in friendship:
            friends.save()

        # posts created by author2
        author2_friends = Post(author=author2,
                               content="friends post created by author2",
                               visibility=Post.FRIENDS,
                               title='friends post')
        author2_friends.size = 1
        author2_friends.contentType = 'text/plain'
        author2_friends.save()
        author2_public = Post(author=author2,
                              content="public post created by author2",
                              visibility=Post.PUBLIC,
                              title='public post')
        author2_public.size = 1
        author2_public.contentType = 'text/plain'
        author2_public.save()

        author2_private = Post(
            author=author2,
            content="private post created by author2 not visible to test",
            visibility=Post.PRIVATE,
            title='private post')
        author2_private.visibleTo.set([author1.uid])
        author2_private.size = 1
        author2_private.contentType = 'text/plain'
        author2_private.save()

        # post created by author3
        author3_foaf = Post(author=author3,
                            content="fofa post created by author3",
                            visibility=Post.FOAF,
                            title='foaf post')
        author3_foaf.size = 1
        author3_foaf.contentType = 'text/plain'
        author3_foaf.save()
        author3_private = Post(author=author3,
                               content="private post created by author3",
                               visibility=Post.PRIVATE,
                               title='privage post')
        author3_private.size = 1
        author3_private.contentType = 'text/plain'
        author3_private.save()

        self.client = Client(HTTP_ACCEPT="application/json")
        self.client.force_login(author1)

        viewable_post_for_author3 = [author3_foaf]
        viewable_post_for_author2 = [
            author2_private, author2_public, author2_friends
        ]

        post_id_author3 = []
        post_id_author2 = []

        for post in viewable_post_for_author3:
            post_id_author3.append(str(post.id))

        for post in viewable_post_for_author2:
            post_id_author2.append(str(post.id))

        view_post_of_author2 = reverse(
            'retrieve_posts_of_author_id_visible_to_current_auth_user',
            args=[author2.id])
        view_post_of_author3 = reverse(
            'retrieve_posts_of_author_id_visible_to_current_auth_user',
            args=[author3.id])

        response = self.client.get(view_post_of_author2)

        self.assertEqual(200, response.status_code)

        # getting json
        json_data = response.json()

        self.assertEquals(json_data['query'], 'posts')
        self.assertEquals(json_data['count'], len(viewable_post_for_author2))
        self.assertEquals(json_data['size'], 10)

        returned_post_id = []
        for each_post in json_data['posts']:
            returned_post_id.append(each_post['id'])

        self.assertEqual(post_id_author2, returned_post_id)

        response = self.client.get(view_post_of_author3)

        self.assertEqual(200, response.status_code)

        # getting json
        json_data = response.json()

        self.assertEquals(json_data['query'], 'posts')
        self.assertEquals(json_data['count'], len(viewable_post_for_author3))
        self.assertEquals(json_data['size'], 10)

        returned_post_id = []
        for each_post in json_data['posts']:
            returned_post_id.append(each_post['id'])

        self.assertEqual(post_id_author3, returned_post_id)

        Post.objects.filter(author=author1).delete()
        Post.objects.filter(author=author2).delete()
        Post.objects.filter(author=author3).delete()
        Author.objects.filter(username="******").delete()
        Author.objects.filter(username="******").delete()
        Author.objects.filter(username="******").delete()