def refreshFacebookFriends(request):
    response = dict()

    userid = request.REQUEST.get('userid', None)
    accessToken = request.REQUEST.get('accesstoken')

    try:
        userProfile = UserProfile.getUser(userid)
    except UserProfile.DoesNotExist:
        return errorResponse("Invalid user id")

    facebookProfile = FacebookProfile(userProfile, accessToken)
    friends = facebookProfile.getFacebookFriends()

    response['users'] = []
    for friend in friends:
        response['users'].append(getUserProfileDetailsJson(friend))

    response['success'] = True

    return HttpResponse(json.dumps(response))
def postStatus(request):
    response = dict()

    text = request.REQUEST['text']
    userid = request.REQUEST['userid']
    groupids = request.REQUEST.get('groupids', '[]')
    expires = request.REQUEST.get('expires', None)
    starts = request.REQUEST.get('starts', None)
    locationData = request.REQUEST.get('location', '{}')
    statusid = request.REQUEST.get('statusid', 0)
    accessToken = request.REQUEST.get('accesstoken', None)
    shareOnFacebook = request.REQUEST.get('facebookshare', False)
    statusType = request.REQUEST.get('type', 'other')
    visibility = request.REQUEST.get('visibility', 'friends')
    visibilityFriends = request.REQUEST.get('visibilityfriends', '[]')
    imageUrl = request.REQUEST.get('imageurl', None)
    imageOrientation = request.REQUEST.get('imageorientation', None)

    groupids = json.loads(groupids)
    locationData = json.loads(locationData)

    if starts:
        starts = datetime.strptime(starts, DATETIME_FORMAT).replace(tzinfo=pytz.utc)
    else:
        starts = datetime.utcnow()

    if expires:
        expires = datetime.strptime(expires, DATETIME_FORMAT).replace(tzinfo=pytz.utc)
    else:
        expires = starts + timedelta(hours=8)

    try:
        userprofile = UserProfile.getUser(userid)
    except UserProfile.DoesNotExist:
        return errorResponse("User Id not valid")

    if statusid:
        try:
            status = Status.getStatus(statusid)
            createStatusChangedNotification(status)
            shouldPostNotification = False
        except Status.DoesNotExist:
            return errorResponse('status does not exist with that id')
    else:
        status = Status(user=userprofile)
        shouldPostNotification = True

    status.expires = expires
    status.text = text
    status.starts = starts
    status.statusType = statusType
    status.visibility = visibility
    status.imageOrientation = imageOrientation

    if imageUrl:
        status.imageUrl = imageUrl

    if locationData:
        location = getLocationObjectFromJson(locationData)
        status.location = location

    status.save()
    status.attending.add(userprofile)

    if status.visibility == 'custom':
        visibilityFriends = json.loads(visibilityFriends)

        for friendId in visibilityFriends:

            if str(friendId)[:2] == 'fb':
                friendId = str(friendId)[2:]
                try:
                    friendProfile = UserProfile.objects.get(facebookUID=friendId)
                    status.friendsVisible.add(friendProfile)
                except UserProfile.DoesNotExist:
                    try:
                        facebookUser = FacebookUser.objects.get(facebookUID=friendId)
                    except FacebookUser.DoesNotExist:
                        facebookUser = FacebookUser.objects.create(facebookUID=friendId)

                    status.fbFriendsVisible.add(facebookUser)
            else:
                try:
                    friendProfile = UserProfile.getUser(friendId)
                    status.friendsVisible.add(friendProfile)
                except UserProfile.DoesNotExist:
                    pass

    if groupids:
        groups = Group.objects.filter(id__in=groupids)
        status.groups.add(*groups)
    else:
        status.groups.clear()

    status.save()

    if shareOnFacebook:
        if accessToken is not None:
            fbProfile = FacebookProfile(userprofile, accessToken)
            fbProfile.shareStatus(status, request)

    if shouldPostNotification:
        sendFavoritesStatusPushNotification(status)
    else:
        sendEditStatusNotification(status)

    response['success'] = True
    response['statusid'] = status.id

    cacheKey = status.getCacheKeyNoneStatic()

    statusDuration = status.getStatusDuration()

    cache.set(cacheKey, status, statusDuration)


    return HttpResponse(json.dumps(response))
def facebookLogin(request):
    """

    :param request:
    :return:
    """
    response = dict()

    device = request.REQUEST['device']
    facebookAuthKey = request.REQUEST['fbauthkey']
    lat = request.REQUEST.get('lat', None)
    lng = request.REQUEST.get('lng', None)

    if device != 'ios' and device != 'android':
        return errorResponse('Invalid device: ' + device)

    try:
        facebookProfile, newUser = FacebookProfile.getFacebookUserFromAuthKey(facebookAuthKey, device)
        userProfile = facebookProfile.userProfile
    except facebook.GraphAPIError:
        return errorResponse("Invalid Facebook AUTH Key")

    response['friends'] = []

    facebookFriends = facebookProfile.getFacebookFriends()

    blockedFriends = userProfile.blockedFriends.all()
    for friend in facebookFriends:
        blocked = False
        if friend in blockedFriends:
            blocked = True

        friendData = getUserProfileDetailsJson(friend)
        response['friends'].append(friendData)

    # Check all buddyup friends and add them if they weren't already included in facebook friends check
    friends = userProfile.friends.all()
    for friend in friends:
        if friend not in facebookFriends:
            blocked = False
            if friend in blockedFriends:
                blocked = True

            friendData = getUserProfileDetailsJson(friend)
            response['friends'].append(friendData)

    statusesResponse, newSince = getNewStatusesJsonResponse(userProfile, None, lat, lng)
    myStatusesResponse = getMyStatusesJsonResponse(userProfile)

    settings = getSettingsData(userProfile)

    newSince = datetime.now().strftime(MICROSECOND_DATETIME_FORMAT)
    notifications = getNotificationsJson(userProfile)
    chatData = getNewChatsData(userProfile)

    if newUser:
        createFriendJoinedNotification(userProfile)
        Group.objects.create(name="Favorites", user=userProfile)

    groupsData = getMyGroupsJsonResponse(userProfile)


    response['success'] = True
    response['firstname'] = userProfile.user.first_name
    response['lastname'] = userProfile.user.last_name
    response['userid'] = userProfile.id
    response['facebookid'] = userProfile.facebookUID
    response['statuses'] = statusesResponse
    response['groups'] = groupsData
    response['mystatuses'] = myStatusesResponse
    response['chats'] = chatData
    response['newsince'] = newSince
    response['settings'] = settings
    response['notifications'] = notifications
    response['favoritesnotifications'] = userProfile.favoritesNotifications

    return HttpResponse(json.dumps(response))