def register(request):
    context = RequestContext(request)

    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)

        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.is_active = False
            user.save()

            profile = Profile.create_profile(user)
            profile.host = "http://cs410.cs.ualberta.ca:41024"
            profile.save()

            registered = True

        else:
            print user_form.errors

    else:
        user_form = UserForm()

    if registered == True:
        return HttpResponse("<script>alert(\"Account Successfully Created!!\"); window.location = \'/login\';</script>")
    else:
        return render_to_response('authors/register.html',
            {'user_form': user_form, 'registered': registered}, context)
def index(request):
    list_of_users = User.objects.filter( Q(username=request.user) | Q(username='******'))
    list_of_profiles = Profile.objects.exclude(id__in=list_of_users)
    list_of_posts = []
    list_of_github = []

        #Checks status of friend requests sent to remote servers
    if request.user.is_authenticated():
        current_profile = Profile.objects.get(user_id = request.user.id)
        follow_qs = Follow.objects.filter(from_profile_id=current_profile.id).filter(status='PENDING')

        for follow in follow_qs:
            #check each follow to_profile to see if they are remote or local
            to_profile_host = follow.to_profile_id.host

            host_port = to_profile_host.strip("http://").split(":")

            port = host_port[1]

            if str(port) != "8000" and str(port) != "41024":
            #if str(port) == '8000' or str(port) == '41024':
                print("not local -- friend response")
                host = Host.objects.filter( Q(host_url__icontains=port) ).first()
                #host = Host.objects.filter( Q(host_url__icontains='41024') ).first()
                friend_response = host.get_friend_response(str(current_profile.uuid), str(follow.to_profile_id.uuid))
                print(friend_response['friends'])
                if friend_response['friends'].upper() == "YES" or friend_response['friends'] == True:
                    current_profile.friends.add(follow.to_profile_id)
                    current_profile.save()
                    follow.delete()

    if request.user.is_authenticated():
        my_profile = Profile.objects.get(user=request.user)

    else:
        my_profile = ''

    if request.user.is_authenticated():
        profile = Profile.objects.get(user_id = request.user.id)
        post_query = Post.objects.filter(Q(privacy=1) | Q(privacy=3) | Q(privacy=4) | Q(privacy=5) | Q(author=profile)).order_by('-date')
        post_query = list(post_query)

        hosts = Host.objects.all().exclude( Q(name='Our own') | Q(name='Test'))
        for host in hosts:
            try:
                host_posts = host.get_public_posts()
                if host.name == "Group3":
                    for post in host_posts['posts']:
                        author = post['author']
                        #Create new remote user
                        try:
                            new_user = User.objects.get(username=author['displayname']+'@Group3')
                        except User.DoesNotExist:
                            new_user = User(username=author['displayname']+'@Group3', password='')
                            new_user.save()

                        #Create new remote profile
                        try:
                            new_profile = Profile.objects.get(user=new_user)
                        except Profile.DoesNotExist:
                            new_profile = Profile(host=author['host'], uuid=author['id'], displayname=author['displayname'], user=new_user)
                            new_profile.save()

                        #Get remote posts
                        title = post['title']
                        uuid = post['guid']
                        description = post['description']
                        content_type = post['content-type']
                        post_text = post['content']
                        date = timezone.make_aware(datetime.datetime.strptime(post['pubdate'], '%Y-%m-%d'), timezone.get_default_timezone())

                        new_post = Post(uuid=uuid, title=title, description="", author=new_profile, date=date,content_type=content_type,post_text=post_text,privacy='1')
                        post_query.append(new_post)
                elif host.name == "Group7":
                    for post in host_posts['posts']:
                        author = post['author']
                        #Create new remote user
                        try:
                            new_user = User.objects.get(username=author['displayname']+'@Group7')
                        except User.DoesNotExist:
                            new_user = User(username=author['displayname']+'@Group7', password='')
                            new_user.save()

                        #Create new remote profile
                        try:
                            new_profile = Profile.objects.get(user=new_user)
                        except Profile.DoesNotExist:
                            new_profile = Profile(host=author['host'], uuid=author['id'], displayname=author['displayname'], user=new_user)
                            new_profile.save()

                        #Get remote posts
                        title = post['title']
                        uuid = post['guid']
                        description = post['description']
                        content_type = post['content-type']
                        post_text = post['content']
                        #Date is set to April 1 because its not given
                        date = timezone.make_aware(datetime.datetime.strptime('2015-04-01', '%Y-%m-%d'), timezone.get_default_timezone())

                        new_post = Post(uuid=uuid, title=title, description="", author=new_profile, date=date,content_type=content_type,post_text=post_text,privacy='1')
                        post_query.append(new_post)
            except:
                pass

        post_query.sort(key=lambda x: x.date,reverse=True)

        following_profiles = Follow.objects.filter(from_profile_id=profile.id)
        friends_list = profile.friends.all()

        for post in post_query:
            if (post.content_type == 'text/x-markdown'):
                post.post_text = markdown2.markdown(post.post_text)

            # Displays your own posts
            if (post.author == profile):
                list_of_posts.append(post)

            elif (post.privacy == '1'):
                # Get posts from local friends
                # Friends means follow. So we also have to get the public posts of all friends
                for friend in friends_list:
                    if post.author == friend:
                        list_of_posts.append(post)

                # Get posts from the people the current user follows.
                for follow in following_profiles:
                    if post.author == follow.to_profile_id:
                        list_of_posts.append(post)

            elif ((post.privacy == '3') or (post.privacy == '4') or (post.privacy == '5')):
                allowed_users = post.allowed.all()
                request_profile = Profile.objects.get(user=request.user.id)
                for allowed_user in allowed_users:
                    if allowed_user.uuid == request_profile.uuid:
                        list_of_posts.append(post)


    return render(request, 'authors/index.html',
        {'list_of_profiles':list_of_profiles, 'list_of_posts':list_of_posts, 'list_of_github':list_of_github, 'my_profile':my_profile})
def ajax_retrieve_latest_post(request):
    list_of_posts = []

    if request.user.is_authenticated():
        profile = Profile.objects.get(user_id = request.user.id)
        post_query = Post.objects.filter(Q(privacy=1) | Q(privacy=3) | Q(privacy=4) | Q(privacy=5) | Q(author=profile)).order_by('-date')
        post_query = list(post_query)

        hosts = Host.objects.all().exclude( Q(name='Our own') | Q(name='Test'))
        for host in hosts:
            try:
                host_posts = host.get_public_posts()
                if host.name == "Group3":
                    for post in host_posts['posts']:
                        author = post['author']
                        #Create new remote user
                        try:
                            new_user = User.objects.get(username=author['displayname']+'@Group3')
                        except User.DoesNotExist:
                            new_user = User(username=author['displayname']+'@Group3', password='')
                            new_user.save()

                        #Create new remote profile
                        try:
                            new_profile = Profile.objects.get(user=new_user)
                        except Profile.DoesNotExist:
                            new_profile = Profile(host=author['host'], uuid=author['id'], displayname=author['displayname'], user=new_user)
                            new_profile.save()

                        #Get remote posts
                        title = post['title']
                        uuid = post['guid']
                        description = post['description']
                        content_type = post['content-type']
                        post_text = post['content']
                        date = timezone.make_aware(datetime.datetime.strptime(post['pubdate'], '%Y-%m-%d'), timezone.get_default_timezone())

                        new_post = Post(uuid=uuid, title=title, description="", author=new_profile, date=date,content_type=content_type,post_text=post_text,privacy='1')
                        post_query.append(new_post)
                elif host.name == "Group7":
                    for post in host_posts['posts']:
                        author = post['author']
                        #Create new remote user
                        try:
                            new_user = User.objects.get(username=author['displayname']+'@Group7')
                        except User.DoesNotExist:
                            new_user = User(username=author['displayname']+'@Group7', password='')
                            new_user.save()

                        #Create new remote profile
                        try:
                            new_profile = Profile.objects.get(user=new_user)
                        except Profile.DoesNotExist:
                            new_profile = Profile(host=author['host'], uuid=author['id'], displayname=author['displayname'], user=new_user)
                            new_profile.save()

                        #Get remote posts
                        title = post['title']
                        uuid = post['guid']
                        description = post['description']
                        content_type = post['content-type']
                        post_text = post['content']
                        #Date is set to April 1 because its not given
                        date = timezone.make_aware(datetime.datetime.strptime('2015-04-01', '%Y-%m-%d'), timezone.get_default_timezone())

                        new_post = Post(uuid=uuid, title=title, description="", author=new_profile, date=date,content_type=content_type,post_text=post_text,privacy='1')
                        post_query.append(new_post)
            except:
                pass


        post_query.sort(key=lambda x: x.date,reverse=True)


        following_profiles = Follow.objects.filter(from_profile_id=profile.id)
        friends_list = profile.friends.all()

        for post in post_query:
            if (post.content_type == 'text/x-markdown'):
                post.post_text = markdown2.markdown(post.post_text)

            # Displays your own posts
            if (post.author == profile):
                list_of_posts.append(post)

            elif (post.privacy == '1'):
                # Get posts from local friends
                # Friends means follow. So we also have to get the public posts of all friends
                for friend in friends_list:
                    if post.author == friend:
                        list_of_posts.append(post)

                # Get posts from the people the current user follows.
                for follow in following_profiles:
                    if post.author == follow.to_profile_id:
                        list_of_posts.append(post)

            elif ((post.privacy == '3') or (post.privacy == '4') or (post.privacy == '5')):
                allowed_users = post.allowed.all()
                print(allowed_users)
                request_profile = Profile.objects.get(user=request.user.id)
                for allowed_user in allowed_users:
                    if allowed_user.uuid == request_profile.uuid:
                        list_of_posts.append(post)

    return render(request, 'post_template.html', {'list_of_posts': list_of_posts})
def ajax_public_posts(request):
    if request.user.is_authenticated():
        my_profile = Profile.objects.get(user=request.user)
    else:
        my_profile = ''

    list_of_posts = list(Post.objects.filter(Q(privacy=1)).order_by('-date'))

    hosts = Host.objects.all()
    for host in hosts:
        try:
            host_posts = host.get_public_posts()
            if host.name == "Group3":
                for post in host_posts['posts']:
                    author = post['author']
                    #Create new remote user
                    try:
                        new_user = User.objects.get(username=author['displayname']+'@Group3')
                    except User.DoesNotExist:
                        new_user = User(username=author['displayname']+'@Group3', password='')
                        new_user.save()

                    #Create new remote profile
                    try:
                        new_profile = Profile.objects.get(user=new_user)
                    except Profile.DoesNotExist:
                        new_profile = Profile(host=author['host'], uuid=author['id'], displayname=author['displayname'], user=new_user)
                        new_profile.save()

                    #Get remote posts
                    title = post['title']
                    uuid = post['guid']
                    description = post['description']
                    content_type = post['content-type']
                    post_text = post['content']
                    date = timezone.make_aware(datetime.datetime.strptime(post['pubdate'], '%Y-%m-%d'), timezone.get_default_timezone())

                    new_post = Post(uuid=uuid, title=title, description="", author=new_profile, date=date,content_type=content_type,post_text=post_text,privacy='1')
                    list_of_posts.append(new_post)
            elif host.name == "Group7":
                for post in host_posts['posts']:
                    author = post['author']
                    #Create new remote user
                    try:
                        new_user = User.objects.get(username=author['displayname']+'@Group7')
                    except User.DoesNotExist:
                        new_user = User(username=author['displayname']+'@Group7', password='')
                        new_user.save()

                    #Create new remote profile
                    try:
                        new_profile = Profile.objects.get(user=new_user)
                    except Profile.DoesNotExist:
                        new_profile = Profile(host=author['host'], uuid=author['id'], displayname=author['displayname'], user=new_user)
                        new_profile.save()

                    #Get remote posts
                    title = post['title']
                    uuid = post['guid']
                    description = post['description']
                    content_type = post['content-type']
                    post_text = post['content']
                    #Date is set to April 1 because its not given
                    date = timezone.make_aware(datetime.datetime.strptime('2015-04-01', '%Y-%m-%d'), timezone.get_default_timezone())

                    new_post = Post(uuid=uuid, title=title, description="", author=new_profile, date=date,content_type=content_type,post_text=post_text,privacy='1')
                    list_of_posts.append(new_post)
        except:
            pass

    for post in list_of_posts:
        if post.content_type == 'text/x-markdown':
            post.post_text = markdown2.markdown(post.post_text)

    list_of_posts.sort(key=lambda x: x.date,reverse=True)

    title = "Viewing All Public Posts"
    return render(request, 'post_template.html', {'list_of_posts':list_of_posts, 'title':title, 'my_profile':my_profile})
def expand_post(request,post_id):
    if request.user.is_authenticated():
        my_profile = Profile.objects.get(user=request.user)
    try:
        post = Post.objects.get(uuid=post_id)
    except:
        hosts = Host.objects.all()
        for host in hosts:
            if host.name == "Group3":
                try:
                    post_json = host.get_postid(post_id)['posts'][0]
                    visibility = post_json['visibility']
                    description = post_json['description']
                    date = timezone.make_aware(datetime.datetime.strptime(post_json['pubdate'], '%Y-%m-%d'), timezone.get_default_timezone())
                    title = post_json['title']
                    content = post_json['content']
                    content_type = post_json['content-type']

                    author_id = post_json['author']['id']
                    author_host = post_json['author']['host']
                    author_displayname = post_json['author']['displayname']
                    try:
                        author_user = User(username=author_displayname+'@Group3',
                                            password="")
                        author_user.save()
                        author_profile = Profile(user=author_user,uuid=author_id,
                        displayname=author_displayname,host=author_host)
                        author_profile.save()
                    except:
                        author_profile = Profile.objects.get(uuid=author_id)

                    post = Post(title=title,post_text=content,author=author_profile,date=date,privacy='1')
                    comments = []
                    comment_form = []
                    return render(request, 'posts/expand_post.html',{'comments':comments, 'comment_form':comment_form, 'post':post, 'my_profile':my_profile})
                except:
                    pass
            elif host.name == "Group7":
                try:
                    post_json = host.get_postid(post_id)['posts'][0]
                    print(post_json)
                    #visibility = post_json['visibility']
                    description = post_json['description']
                    date = date = timezone.make_aware(datetime.datetime.strptime('2015-04-01', '%Y-%m-%d'), timezone.get_default_timezone())
                    title = post_json['title']
                    content = post_json['content']
                    content_type = post_json['content-type']

                    author_id = post_json['author']['id']
                    author_host = post_json['author']['host']
                    author_displayname = post_json['author']['displayname']
                    try:
                        author_user = User(username=author_displayname+'@Group3',
                                            password="")
                        author_user.save()
                        author_profile = Profile(user=author_user,uuid=author_id,
                        displayname=author_displayname,host=author_host)
                        author_profile.save()
                    except:
                        author_profile = Profile.objects.get(uuid=author_id)

                    post = Post(title=title,post_text=content,author=author_profile,date=date,privacy='1')
                    comments = []
                    comment_form = []
                    return render(request, 'posts/expand_post.html',{'comments':comments, 'comment_form':comment_form, 'post':post, 'my_profile':my_profile})
                except:
                    pass

    try:
        if post.content_type == 'text/x-markdown':
            post.post_text = markdown2.markdown(post.post_text)
        current_profile = Profile.objects.get(user_id=request.user.id)
        comments = None
        if request.method == 'POST':
            comment_form = CommentForm(data=request.POST)

            if comment_form.is_valid():
                body = comment_form.cleaned_data['body']
                newComment = Comment(body=body, date=timezone.now(), author=current_profile, post_id=post)
                newComment.save()
            else:
                print comment_form.errors
            return redirect('/posts/'+post_id)
        else:
            comments = Comment.objects.filter(post_id=post).order_by('date')
            comment_form = CommentForm()
        return render(request, 'posts/expand_post.html',{'comments':comments, 'comment_form':comment_form, 'post':post, 'my_profile':my_profile})
    except:
        return HttpResponse("Post not found", status=404)
def posts(request):
    context = RequestContext(request)
    # retrieve form data
    if request.method == 'POST':
        post_form = PostForm(request.user,data=request.POST)
        if post_form.is_valid():
            privacy = post_form.cleaned_data['privacy']
            post_text = post_form.cleaned_data['post_text']
            title = post_form.cleaned_data['title']
            description = post_form.cleaned_data['description']
            content_type = post_form.cleaned_data['content_type']
            date = timezone.now()
            # check if a new photo was uploaded
            try:
                image = request.FILES['image']

            except:
                image=""

            # get current user
            currentUser=request.user

            # if profile for current user already exists, retrieve it
            try:
                author=Profile.objects.get(user=currentUser)

            # create new profile for current user if one doesn't exist
            except:
                userObject = User.objects.get(username=currentUser)
                profile = Profile.create_profile(userObject)
                profile.host = request.get_host()
                profile.save()
                author = profile
            # create a new post given the form submission data
            newPost = Post(post_text=post_text, description=description, title=title, date=date,author=author,privacy=privacy, image=image, content_type=content_type)

            # save the new post in the database
            newPost.save()

            # special privacy settings: friend of a friend
            if privacy=="3":
                all_friends=Profile.objects.get(user=currentUser)
                for friend in all_friends.friends.all():
                    foaf=Profile.objects.get(user=User.objects.get(username=friend.user))
                    for second_friend in foaf.friends.all():
                        try:
                            newPost.allowed.add(Profile.objects.get(user=User.objects.get(username=second_friend.user)))
                        except:
                            continue
                newPost.allowed.add(Profile.objects.get(user=User.objects.get(username=author)))

            # special privacy settings: friends on this server
            elif privacy=="4":
                all_friends=Profile.objects.get(user=currentUser)
                for friend in all_friends.friends.all():
                    f=Profile.objects.get(user=User.objects.get(username=friend.user))
                    if f.host == 'http://cs410.cs.ualberta.ca:41024':
                        newPost.allowed.add(f)
                newPost.allowed.add(Profile.objects.get(user=User.objects.get(username=author)))
	     # special privacy settings: friends
            elif privacy=="5":
                all_friends=Profile.objects.get(user=currentUser)
                for friend in all_friends.friends.all():
                    newPost.allowed.add(Profile.objects.get(user=User.objects.get(username=friend.user)))
                newPost.allowed.add(Profile.objects.get(user=User.objects.get(username=author)))

            # special privacy settings: private
            elif privacy=="2":
                newPost.allowed.add(Profile.objects.get(user=User.objects.get(username=author)))
            # once the new post is added, return to homepage
            return redirect('/')
        # display error if fields aren't filled properly
        else:
            print post_form.errors
    # display the post form
    else:
        post_form = PostForm(request.user)
    my_profile = Profile.objects.get(user=request.user)

    return render(request, 'posts/posts.html', {'post_form':post_form, 'my_profile':my_profile})