<commit_before>import json

from django.http import Http404
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

from api.serializers import PostSerializer, CommentSerializer, AuthorSerializer, AllAuthorSerializer
from feed.models import Post, Author, Comment, Friend, CommentAuthor, ForeignHost

import requests
import urllib2
import base64


class public_posts(APIView):
    """
    List all posts.
    """

    def get(self, request, format=None):
        posts = Post.objects.filter(visibility="PUBLIC")
        serializer = PostSerializer(posts, many=True)
        return Response({"query": "posts", "count": len(posts), "size": "", "next": "",
                         "previous": "http://previouspageurlhere", "posts": serializer.data})


class post_detail(APIView):
    """
    Retrieve a single post.
    """
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

    def get_object(self, pk):
        try:
            return Post.objects.get(pk=pk)
        except Post.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        post = self.get_object(pk)
        serializer = PostSerializer(post)
        return Response(serializer.data)


class post_comments(APIView):
    """
    List all comments for a single post.
    """
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

    def get(self, request, pk, format=None):
        post_object = Post.objects.get(id=pk)
        comments = Comment.objects.filter(id=post_object)
        serializer = CommentSerializer(comments, many=True)
        return Response({"query": "comments", "count": len(comments), "size": "10", "next": "http://nextpageurlhere",
                         "previous": "http://previouspageurlhere", "comments": serializer.data})

    def post(self, request, pk, format=None):
        comment = request.data.get('comment')
        author_object = request.data.get('author')
        author_name = author_object['displayName']

        published = request.data.get('published')
        contentType = request.data.get('contentType')
        post_object = Post.objects.get(id=pk)
        new_comment_author = CommentAuthor(id=author_object['id'], host=author_object['host'], displayName=author_name,
                                   url=author_object['url'], github=author_object['github'])
        new_comment_author.save()
        new_comment = Comment(author=new_comment_author, post_id=post_object,
                              comment=comment, published=published,
                              author_name=author_name, contentType=contentType)
        new_comment.save()

        return Response({})


class author_posts(APIView):
    """
    List all posts.
    """

    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

    def get(self, request, pk, format=None):
        author_object = Author.objects.get(id=pk)

        asker_host = request.META.get("HTTP_HOST")

        try:
            asker_object = Author.objects.get(email=request.user)
            asker_id = str(asker_object.id)
        except:
            asker_id = request.GET.get('id', default=None)
            print asker_id
            if asker_id == None:
                return Response({"details": "give and ?id=xxxx"}, status=status.HTTP_400_BAD_REQUEST)
            else:
                asker_id = str(asker_id)


        public_posts = Post.objects.filter(author=author_object, visibility="PUBLIC")
        return_posts = public_posts

        # the asker is the user itself, return everything
        if (pk == asker_id):
            all_posts = Post.objects.filter(author=author_object)
            return_posts = all_posts

            serializer = PostSerializer(return_posts, many=True)

            return Response({"query": "posts", "count": len(return_posts), "size": "10", "next": "http://nextpageurlhere",
                         "previous": "http://previouspageurlhere", "posts": serializer.data})
      
        # if the asker is a friend
        friend_to_author = Friend.objects.filter(follower_id=pk, followed_id=asker_id)
        author_to_friend = Friend.objects.filter(follower_id=asker_id, followed_id=pk)

        if (len(friend_to_author) == 1) and (len(author_to_friend) == 1):
            #then they are friends, because the relationship is mutual
            friend_posts = Post.objects.filter(author=author_object, visibility="FRIENDS")
            return_posts = return_posts | friend_posts

        # if the asker is on our server, and a friend
        if (len(Author.objects.filter(id=asker_id)) > 0) and (len(friend_to_author) == 1) and (len(author_to_friend) == 1):
            server_friends_posts = Post.objects.filter(author=author_object, visibility="SERVERONLY")
            return_posts = return_posts | server_friends_posts

        # TODO: Look at FOAF stuff
        # asker_id is person A
        # as ditto, we need to ask person A's host who A is friends with

        # fetch list of A's friends
        print " do I still work here?"
        url = "http://" + asker_host + "/api/friends/" + asker_id
        print url

        req = urllib2.Request(url)
        # assume we are sending to ourselves to begin with, if we are getting this from
        # another host then we will update after
        base64string = base64.encodestring('%s:%s' % ("admin", "pass")).replace('\n', '')
        req.add_header("Authorization", "Basic %s" % base64string)

        foreign_hosts = ForeignHost.objects.filter()
        for host in foreign_hosts:
            # if the sender host, which is a clipped version of the full host path, is part of it, then that host
            # is the correct one we're looking for
            if asker_host in host.url:
                base64string = base64.encodestring('%s:%s' % (host.username, host.password)).replace('\n', '')
                req.add_header("Authorization", "Basic %s" % base64string)

        print "how about now"
        response = urllib2.urlopen(req).read()
        print "i would think this one fails"
        loaded = json.loads(response)

        print loaded['authors']

        # we now have a list of authors who are friends with the asker
        # if we are friends with any of them then we can give them our FOAF marked posts
        # or if we were friends to begin with they can also see FOAF marked posts

        for author in loaded['authors']:
            # if we are directly friends lets just give it to them
            if (len(friend_to_author) == 1) and (len(author_to_friend) == 1):
                foaf_posts = Post.objects.filter(author=author_object, visibility="FOAF")
                return_posts = return_posts | foaf_posts
                break
            else:
                # we should check if we are friends of any of A's friends
                #author is a string of a uuid
                a_to_b = Friend.objects.filter(follower_id=pk, followed_id=author)
                b_to_a = Friend.objects.filter(follower_id=author, followed_id=pk)
                if (len(a_to_b) == 1) and (len(b_to_a) == 1):
                    # we are friends with one of their friends
                    foaf_posts = Post.objects.filter(author=author_object, visibility="FOAF")
                    return_posts = return_posts | foaf_posts<commit_msg>ahhh commit spams34<commit_after>import json

from django.http import Http404
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

from api.serializers import PostSerializer, CommentSerializer, AuthorSerializer, AllAuthorSerializer
from feed.models import Post, Author, Comment, Friend, CommentAuthor, ForeignHost

import requests
import urllib2
import base64


class public_posts(APIView):
    """
    List all posts.
    """

    def get(self, request, format=None):
        posts = Post.objects.filter(visibility="PUBLIC")
        serializer = PostSerializer(posts, many=True)
        return Response({"query": "posts", "count": len(posts), "size": "", "next": "",
                         "previous": "http://previouspageurlhere", "posts": serializer.data})


class post_detail(APIView):
    """
    Retrieve a single post.
    """
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

    def get_object(self, pk):
        try:
            return Post.objects.get(pk=pk)
        except Post.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        post = self.get_object(pk)
        serializer = PostSerializer(post)
        return Response(serializer.data)


class post_comments(APIView):
    """
    List all comments for a single post.
    """
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

    def get(self, request, pk, format=None):
        post_object = Post.objects.get(id=pk)
        comments = Comment.objects.filter(id=post_object)
        serializer = CommentSerializer(comments, many=True)
        return Response({"query": "comments", "count": len(comments), "size": "10", "next": "http://nextpageurlhere",
                         "previous": "http://previouspageurlhere", "comments": serializer.data})

    def post(self, request, pk, format=None):
        comment = request.data.get('comment')
        author_object = request.data.get('author')
        author_name = author_object['displayName']

        published = request.data.get('published')
        contentType = request.data.get('contentType')
        post_object = Post.objects.get(id=pk)
        new_comment_author = CommentAuthor(id=author_object['id'], host=author_object['host'], displayName=author_name,
                                   url=author_object['url'], github=author_object['github'])
        new_comment_author.save()
        new_comment = Comment(author=new_comment_author, post_id=post_object,
                              comment=comment, published=published,
                              author_name=author_name, contentType=contentType)
        new_comment.save()

        return Response({})


class author_posts(APIView):
    """
    List all posts.
    """

    authentication_classes = (SessionAuthentication, BasicAuthentication)
    permission_classes = (IsAuthenticated,)

    def get(self, request, pk, format=None):
        author_object = Author.objects.get(id=pk)

        asker_host = request.META.get("HTTP_HOST")

        try:
            asker_object = Author.objects.get(email=request.user)
            asker_id = str(asker_object.id)
        except:
            asker_id = request.GET.get('id', default=None)
            print asker_id
            if asker_id == None:
                return Response({"details": "give and ?id=xxxx"}, status=status.HTTP_400_BAD_REQUEST)
            else:
                asker_id = str(asker_id)


        public_posts = Post.objects.filter(author=author_object, visibility="PUBLIC")
        return_posts = public_posts

        # the asker is the user itself, return everything
        if (pk == asker_id):
            all_posts = Post.objects.filter(author=author_object)
            return_posts = all_posts

            serializer = PostSerializer(return_posts, many=True)

            return Response({"query": "posts", "count": len(return_posts), "size": "10", "next": "http://nextpageurlhere",
                         "previous": "http://previouspageurlhere", "posts": serializer.data})
      
        # if the asker is a friend
        friend_to_author = Friend.objects.filter(follower_id=pk, followed_id=asker_id)
        author_to_friend = Friend.objects.filter(follower_id=asker_id, followed_id=pk)

        if (len(friend_to_author) == 1) and (len(author_to_friend) == 1):
            #then they are friends, because the relationship is mutual
            friend_posts = Post.objects.filter(author=author_object, visibility="FRIENDS")
            return_posts = return_posts | friend_posts

        # if the asker is on our server, and a friend
        if (len(Author.objects.filter(id=asker_id)) > 0) and (len(friend_to_author) == 1) and (len(author_to_friend) == 1):
            server_friends_posts = Post.objects.filter(author=author_object, visibility="SERVERONLY")
            return_posts = return_posts | server_friends_posts

        # TODO: Look at FOAF stuff
        # asker_id is person A
        # as ditto, we need to ask person A's host who A is friends with

        # fetch list of A's friends
        print " do I still work here?"
        url = "http://" + asker_host + "/api/friends/" + asker_id
        print url

                
        #req = urllib2.Request(url)


        # assume we are sending to ourselves to begin with, if we are getting this from
        # another host then we will update after
        #base64string = base64.encodestring('%s:%s' % ("admin", "pass")).replace('\n', '')
        #req.add_header("Authorization", "Basic %s" % base64string)

        r = requests.get(url, auth=("admin", "pass"))


        foreign_hosts = ForeignHost.objects.filter()
        for host in foreign_hosts:
            # if the sender host, which is a clipped version of the full host path, is part of it, then that host
            # is the correct one we're looking for
            if asker_host in host.url:
                #base64string = base64.encodestring('%s:%s' % (host.username, host.password)).replace('\n', '')
                #req.add_header("Authorization", "Basic %s" % base64string)
                r = requests.get(url, auth=(host.username, host.password))

        print "how about now"


        #response = urllib2.urlopen(req).read()
        print "i would think this one fails"
        #loaded = json.loads(response)
        loaded = json.loads(r.text)

        print loaded['authors']

        # we now have a list of authors who are friends with the asker
        # if we are friends with any of them then we can give them our FOAF marked posts
        # or if we were friends to begin with they can also see FOAF marked posts

        for author in loaded['authors']:
            # if we are directly friends lets just give it to them
            if (len(friend_to_author) == 1) and (len(author_to_friend) == 1):
                foaf_posts = Post.objects.filter(author=author_object, visibility="FOAF")
                return_posts = return_posts | foaf_posts
                break
            else:
                # we should check if we are friends of any of A's friends
                #author is a string of a uuid
                a_to_b = Friend.objects.filter(follower_id=pk, followed_id=author)
                b_to_a = Friend.objects.filter(follower_id=author, followed_id=pk)
                if (len(a_to_b) == 1) and (len(b_to_a) == 1):
                    # we are friends with one of their friends
                    foaf_posts = Post.objects.filter(author=author_object, visibility="FOAF")
                    return_posts = return_posts | foaf_posts
{'fraction_non_alphanumeric': 0.10161633073604225, 'fraction_numerical': 0.005151651748341812, 'mean_word_length': 2.6446843463975593, 'pattern_counts': {'":': 38, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6456476', 'n_tokens_mistral': 4419, 'n_tokens_neox': 4235, 'n_words': 1151}