def getNewData(request):
    response = dict()

    userid = request.REQUEST['userid']
    since = request.REQUEST.get('since', None)
    if since:
        since = datetime.strptime(since, MICROSECOND_DATETIME_FORMAT)

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

    newSince = datetime.now().strftime(MICROSECOND_DATETIME_FORMAT)

    pokes = getNewPokesData(userProfile, since)
    chats = getNewChatsData(userProfile, since)
    notifications = getNotificationsJson(userProfile, since)

    response['chats'] = chats
    response['newsince'] = newSince
    response['notifications'] = notifications
    response['success'] = True
    response['pokes'] = pokes

    return HttpResponse(json.dumps(response))
def createTestUser(request):
    numberOfFriends = request.REQUEST['numfriends']
    response = dict()

    name = "test%d" % random.randint(1, 10000000)
    email = "*****@*****.**" % name
    firstName = name
    lastName = name
    user = User(username=email, email=email, first_name=firstName,
                last_name=lastName, password=0)

    user.save()
    userProfile = UserProfile(user=user, device='ios')
    userProfile.save()

    numberOfFriends = int(numberOfFriends)
    friends = UserProfile.objects.all().order_by('-id')[:numberOfFriends]

    blockedFriends = userProfile.blockedFriends.all()
    for friend in friends:
        if friend not in friend.friends.all():
            friend.friends.add(userProfile)
            userProfile.friends.add(friend)

    friends = userProfile.friends.all()
    response['friends'] = list()
    for friend in friends:
        friendData = getUserProfileDetailsJson(friend)
        response['friends'].append(friendData)

    statusesResponse, newSince = getNewStatusesJsonResponse(userProfile, None, None, None)
    myStatusesResponse = getMyStatusesJsonResponse(userProfile)
    groupsData = getMyGroupsJsonResponse(userProfile)

    buddyupSettings = getSettingsData(userProfile)

    newSince = datetime.now().strftime(MICROSECOND_DATETIME_FORMAT)
    notifications = getNotificationsJson(userProfile)
    chatData = getNewChatsData(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'] = buddyupSettings
    response['notifications'] = notifications
    response['favoritesnotifications'] = userProfile.favoritesNotifications

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

    userid = request.REQUEST['userid']
    chatid = request.REQUEST['chatid']
    text = request.REQUEST['text']
    text = str(text)
    since = request.REQUEST.get('since', None)

    if since:
        since = datetime.strptime(since, MICROSECOND_DATETIME_FORMAT)

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

    try:
        convo = Conversation.objects.get(pk=chatid)
    except Conversation.DoesNotExist:
        return errorResponse("Invalid chat id")

    if userProfile not in convo.members.all():
        return errorResponse("User is not a member of this chat")

    message = Message.objects.create(user=userProfile, conversation=convo, text=text)
    convo.save(force_update=True)

    chatData = getNewChatsData(userProfile, since)

    newSince = datetime.now().strftime(MICROSECOND_DATETIME_FORMAT)

    response['chats'] = chatData
    response['newsince'] = newSince
    response['success'] = True

    sendChatNotifications(message)

    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))