Exemple #1
0
def setProfilePic(request, type_requested):
    """
    Retrieves uploaded image, creates an ImageHolder object to save the image
    and then points the logged in user's profile pic to it
    """
    response = None
    #Make sure user is logged in
    if not request.user.is_authenticated():
        response = { 'success' : 0, 'error' : 'You are not logged in.' }
    
    if not response:
        if request.method == 'POST':
            form = ImageUploadForm(request.POST, request.FILES)
            if form.is_valid():
                #Handle the uploaded file
                new_image = helper_functions.handleUploadedImage(request.FILES['image'], request.user.get_profile())
                request.user.get_profile().profile_pic = new_image
                request.user.get_profile().save()
                response = { 'success' : 1 }
            else:
                response = { 'success' : 0, 'error' : 'Invalid/No file given.' }
        else:
            response = { 'success' : 0, 'error' : 'No file given.' }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #2
0
def getActivity(request, type_requested, user_id, offset=0):
    """Displays activity for the specified user"""
    try:
        offset = int(offset)  #Make sure offset is an integer
    except ValueError:
        #Default it to 0
        offset = 0

    response = None  #Sentinel value to trigger early render
    try:
        user = auth.models.User.objects.get(pk=user_id)
    except auth.models.User.DoesNotExist:
        response = {'success': 0, 'error': 'User does not exist.'}

    #Get logged in user if there is one
    if request.user.is_authenticated():
        requesting_user = request.user
    else:
        requesting_user = None

    if not response:
        response = user.get_profile().getUserActivity(requesting_user, offset)

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
    elif type_requested == 'desktop':
        return render_to_response('profile.html',
                                  response,
                                  context_instance=RequestContext(request))
    else:
        return render_to_response('profile.html',
                                  response,
                                  context_instance=RequestContext(request))
Exemple #3
0
def search(request, type_requested, term=None, offset=0):
    """
    Searches for a user given a term containing potentially multiple words
    """

    #Get terms from term by splitting string on whitespace
    if term == None:
        response = { 'success' : 0, 'error' : 'No search term given.' }
    else:
        terms = escape(term).split()

        length = len(terms)
        if length == 0:
            response = { 'success' : 0, 'error' : 'No search term given.' }
        elif length == 1:
            #Only one word term
            results = [ result.get_profile().getInfo() for result in auth.models.User.objects.filter(Q(first_name__icontains=terms[0]) | Q(last_name__icontains=terms[0])) ]
            response = { 'success' : 1, 'matches' : results }
        else:
            #Just consider first two terms for now
            results = [ result.get_profile().getInfo() for result in auth.models.User.objects.filter(Q(first_name__icontains=terms[0], last_name__icontains=terms[1]) | Q(first_name__icontains=terms[1], last_name__icontains=terms[0])) ]
            response = { 'success' : 1, 'matches' : results }
            
    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #4
0
def getComments(request, type_requested, post_id, offset=0):
    """
    Gets a list of comments for given post
    """
    try:
        offset = int(offset) #Make sure its an integer
    except ValueError:
        #Default it to 0
        offset = 0

    response = None
    try:
        post = Post.objects.get(pk=post_id)
    except Post.DoesNotExist:
        response = { 'success' : 0, 'error' : 'Post does not exist.' }

    #TODO maybe check if user has permission to view this

    if not response:
        #Get comments according to offset
        if len(post.comment_set.all()) >= offset + 10:
            comments = [ comment.getDetail() for comment in post.comment_set.all()[len(post.comment_set.all())-1*(offset+10):len(post.comment_set.all())-1*offset] ]
        else:
            comments = [ comment.getDetail() for comment in post.comment_set.all()[0:len(post.comment_set.all())-1*offset] ]
        response = { 'success' : 1, 'comments' : comments, 'post' : post.getDetail() }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
    elif type_requested == 'desktop':
        return render_to_response('comments.html', response, context_instance=RequestContext(request))
Exemple #5
0
def getActivity(request, type_requested, user_id, offset=0):
    """Displays activity for the specified user"""
    try:
        offset = int(offset) #Make sure offset is an integer
    except ValueError:
        #Default it to 0
        offset = 0
    
    response = None #Sentinel value to trigger early render
    try:
        user = auth.models.User.objects.get(pk=user_id)
    except auth.models.User.DoesNotExist:
        response = { 'success' : 0, 'error' : 'User does not exist.' }

    #Get logged in user if there is one
    if request.user.is_authenticated():
        requesting_user = request.user
    else:
        requesting_user = None

    if not response:
        response = user.get_profile().getUserActivity(requesting_user, offset)

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
    elif type_requested == 'desktop':
        return render_to_response('profile.html', response, context_instance=RequestContext(request))
    else:
        return render_to_response('profile.html', response, context_instance=RequestContext(request))
Exemple #6
0
def logout(request, type_requested):
    """Logs out user and redirects depending on type"""
    auth.logout(request)

    response = { 'success' : 1 }
    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
    elif type_requested == 'desktop':
        return HttpResponseRedirect('/')
Exemple #7
0
def getExtraInfo(request, type_requested, user_id):
    """
    Returns all of the extra info for specified user, including interests, living locations, schools, and workplaces
    """
    response = None
    try:
        user_pro = auth.models.User.objects.get(pk=user_id).get_profile()
    except UserProfile.DoesNotExist:
        response = { 'success' : 0, 'error' : 'User does not exist.' }

    if not response:
        response = { 'success' : 1, 'extra_info' : user_pro.getInterests() + user_pro.getSchools() + user_pro.getLivingLocs() + user_pro.getWorkplaces() }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #8
0
def getProfile(request, type_requested, user_id):
    """Returns info about specified user"""
    #Get data from model
    response = None
    try:
        user = auth.models.User.objects.get(pk=user_id)
    except auth.models.User.DoesNotExist:
        response = { 'success' : 0, 'error' : 'User does not exist' }

    if not response:
        if request.user.is_authenticated():
            response = { 'success' : 1, 'info' : user.get_profile().getProfile(request.user.id) }
        else:
            response = { 'success' : 1, 'info' : user.get_profile().getProfile() }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #9
0
def myBlock(request, type_requested='desktop', offset=0, num_results=10):
    """
    Returns activity for user's current block
    """
    #Make sure user is logged in
    response = None
    if not request.user.is_authenticated():
        response = { 'success' : 0 }
    
    if not response:
        response = request.user.get_profile().getBlockActivity(offset=offset)

    #Switch rendering based on type
    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
    elif type_requested == 'desktop':
        return render_to_response('block_page.html', response, context_instance=RequestContext(request))
Exemple #10
0
def getFriends(request, type_requested, user_id):
    """Defines view for getting a list of user's friends along with the details for each user"""
    
    #Get data from model
    response = None
    try:
        user = auth.models.User.objects.get(pk=user_id)
    except auth.models.User.DoesNotExist:
        response = { 'success' : 0, 'error' : 'User does not exist' }

    if (not response):
        if request.user.is_authenticated():
            response = { 'success' : 1, 'friends' : user.get_profile().getFriendDetails(request.user.id) }
        else:
            response = { 'success' : 1, 'friends' : user.get_profile().getFriendDetails() }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #11
0
def eventPage(request, type_requested, event_id, offset=0):
    """
    Gets info on event for given event_id
    """
    try:
        event = BlockEvent.objects.get(pk=event_id)
        if request.user.is_authenticated():
            response = event.getComments(offset=offset, user=request.user.get_profile())
        else:
            response = event.getComments(offset=offset)

    except BlockEvent.DoesNotExist:
        response = { 'success' : 0, 'error' : 'Event does not exist.' }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
    elif type_requested == 'desktop':
        return render_to_response('block_event.html', response, context_instance=RequestContext(request))
Exemple #12
0
def currentBlock(request, type_requested, offset=0, num_results=10):
    """
    Gets the Block feed for the posted latitude and longitude
    To be used as a preview pane
    """
    request_dict = helper_functions.get_request_dict(request, type_requested)

    try:
        #Get Block corresponding to POSTed lat/long
        (x, y) = helper_functions.computeXY(request_dict['latitude'], request_dict['longitude'])
        current_block = BlockPage.objects.get(x_coordinate=x, y_coordinate=y)
        response = current_block.getActivity(offset=offset)
    except KeyError:
        response = { 'success' : 0, 'error' : 'Latitude and longitude were not passed in' }
    except BlockPage.DoesNotExist:
        response = { 'success' : 0, 'error' : 'There is nothing posted for the current block' }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #13
0
def getFriendFeed(request, type_requested, offset=0):
    """Displays the aggregate activity of all the logged in user's friends"""
    try:
        offset = int(offset) #Make sure offset is an integer
    except ValueError:
        #Default it to 0
        offset = 0

    #Get logged in user if there is one
    response = None
    if request.user.is_authenticated():
        requesting_user = request.user
    else:
        response = { 'success' : 0, 'error' : 'You must be logged in to view this page.' }

    if not response:
        response = requesting_user.get_profile().getFriendFeed(offset)

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #14
0
def getProfile(request, type_requested, user_id):
    """Returns info about specified user"""
    #Get data from model
    response = None
    try:
        user = auth.models.User.objects.get(pk=user_id)
    except auth.models.User.DoesNotExist:
        response = {'success': 0, 'error': 'User does not exist'}

    if not response:
        if request.user.is_authenticated():
            response = {
                'success': 1,
                'info': user.get_profile().getProfile(request.user.id)
            }
        else:
            response = {'success': 1, 'info': user.get_profile().getProfile()}

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #15
0
def searchExtraInfo(request, type_requested, extra_info_type, term):
    """
    Searches specified extra infos' entries, returning top 5 matches
    """
    term = escape(term)
    if extra_info_type == 'interests':
        results = [ interest.title for interest in SpecialInfoApp.models.Interest.objects.filter(title__icontains=term) ][0:5]
    elif extra_info_type == 'living_locs':
        results = [ living_loc.title for living_loc in SpecialInfoApp.models.LivingLoc.objects.filter(title__icontains=term) ][0:5]
    elif extra_info_type == 'schools':
        results = [ school.title for school in SpecialInfoApp.models.School.objects.filter(title__icontains=term) ][0:5]
    elif extra_info_type == 'workplaces':
        results = [ workplace.title for workplace in SpecialInfoApp.models.Workplace.objects.filter(title__icontains=term) ][0:5]

    response = None
    if len(results) == 0:
        response = { 'success' : 0, 'error' : 'No results match your term.' }
    else:
        response = { 'success' : 1, 'results' : results }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #16
0
def getFriendFeed(request, type_requested, offset=0):
    """Displays the aggregate activity of all the logged in user's friends"""
    try:
        offset = int(offset)  #Make sure offset is an integer
    except ValueError:
        #Default it to 0
        offset = 0

    #Get logged in user if there is one
    response = None
    if request.user.is_authenticated():
        requesting_user = request.user
    else:
        response = {
            'success': 0,
            'error': 'You must be logged in to view this page.'
        }

    if not response:
        response = requesting_user.get_profile().getFriendFeed(offset)

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #17
0
def search(request, type_requested, term=None, offset=0):
    """
    Searches for a user given a term containing potentially multiple words
    """

    #Get terms from term by splitting string on whitespace
    if term == None:
        response = {'success': 0, 'error': 'No search term given.'}
    else:
        terms = escape(term).split()

        length = len(terms)
        if length == 0:
            response = {'success': 0, 'error': 'No search term given.'}
        elif length == 1:
            #Only one word term
            results = [
                result.get_profile().getInfo()
                for result in auth.models.User.objects.filter(
                    Q(first_name__icontains=terms[0])
                    | Q(last_name__icontains=terms[0]))
            ]
            response = {'success': 1, 'matches': results}
        else:
            #Just consider first two terms for now
            results = [
                result.get_profile().getInfo()
                for result in auth.models.User.objects.filter(
                    Q(first_name__icontains=terms[0],
                      last_name__icontains=terms[1])
                    | Q(first_name__icontains=terms[1],
                        last_name__icontains=terms[0]))
            ]
            response = {'success': 1, 'matches': results}

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #18
0
def getFriends(request, type_requested, user_id):
    """Defines view for getting a list of user's friends along with the details for each user"""

    #Get data from model
    response = None
    try:
        user = auth.models.User.objects.get(pk=user_id)
    except auth.models.User.DoesNotExist:
        response = {'success': 0, 'error': 'User does not exist'}

    if (not response):
        if request.user.is_authenticated():
            response = {
                'success': 1,
                'friends': user.get_profile().getFriendDetails(request.user.id)
            }
        else:
            response = {
                'success': 1,
                'friends': user.get_profile().getFriendDetails()
            }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
Exemple #19
0
def createEvent(request, type_requested='desktop'):
    """
    Creates a block event if user is logged in and post is not empty
    """
    #Check if they actually tried to create an event
    if request.method != 'POST':
        #They are just viewing page for the first time, display empty form
        return render_to_response('create_event.html', context_instance=RequestContext(request))

    request_dict = helper_functions.get_request_dict(request, type_requested)

    response = None
    if not request.user.is_authenticated():
        response = { 'success' : 0, 'error' : 'You are not logged in.' }
    else:
        title = ''
        description = ''
        duration = ''
        location = ''
        try:
            title = request_dict['title']
            description = request_dict['description'] if 'description' in request_dict else ''
            duration = request_dict['duration']
            location = request_dict['location']
        except KeyError:
            error = ''
            if 'title' not in request_dict:
                error += 'No title entered. '
            if 'description' not in request_dict:
                error += 'No description entered. '
            if 'duration' not in request_dict:
                error += 'No duration given. '
            if 'location' not in request_dict:
                error += 'No location given. '
            response = { 'success' : 0, 'error' : error, 'title' : title, 
                    'description' : description, 'duration' : duration, 
                    'location' : location }

        if not response:
            if title == '' or duration == '' or location == '':
                error = ''
                if title == '':
                    error += 'No title entered. '
                if description == '':
                    error += 'No description entered. '
                if duration == '':
                    error += 'No duration given. '
                if location == '':
                    error += 'No location given. '
                response = { 'success' : 0, 'error' : error, 'title' : title, 
                        'description' : description, 'duration' : duration, 
                        'location' : location }

        if not response:
            #Check if there was an image uploaded
            form = ImageUploadForm(request.POST, request.FILES)
            if form.is_valid():
                try:
                    new_image = helper_functions.handleUploadedImage(request.FILES['image'], request.user.get_profile())
                    new_event = BlockEvent(block_page=request.user.get_profile().current_block, author=request.user.get_profile(), duration=duration, event_title=title, description=description, location=location, image=new_image)
                except KeyError:
                    #Create new block event
                    new_event = BlockEvent(block_page=request.user.get_profile().current_block, author=request.user.get_profile(), duration=duration, event_title=title, description=description, location=location)

            else:
                #Create new block event
                new_event = BlockEvent(block_page=request.user.get_profile().current_block, author=request.user.get_profile(), duration=duration, event_title=title, description=description, location=location)

            #Save new event
            new_event.save()

            #Set user as attending event
            request.user.get_profile().events.add(new_event)
            request.user.get_profile().save()

            response = { 'success' : 1 }

    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
    elif type_requested == 'desktop':
        if response['success'] == 0:
            #There's an error; redisplay create block page with error text
            return render_to_response('create_event.html', response, context_instance=RequestContext(request))
        else:
            #It was successful, redirect back to Block page
            return HttpResponseRedirect('/desktop/block/')
Exemple #20
0
def signup(request, type_requested):
    """Creates a new user (and user profile) if the data is valid (i.e. email/username not already taken)"""
    request_dict = helper_functions.get_request_dict(request, type_requested)
    
    #Make sure data is set
    response = None
    email = ''
    username = ''
    password_1 = ''
    password_2 = ''
    first_name = ''
    last_name = ''

    #Sanity checking to make sure this wasn't a get
    if request_dict == None:
        response = { 'success' : 0 }
    else:
        try:
            email = request_dict['email']
            username = email if 'username' not in request_dict else request_dict['username']
            password_1 = request_dict['password']
            password_2 = request_dict['password']
            names = request_dict['name'].split()
            if (len(names) > 1):
                first_name = names[0]
                last_name = names[1]
            elif len(names) == 1:
                first_name = names[0]
                last_name = ''
            else:
                first_name = ''
                last_name = ''
        except KeyError:
            error = ''
            if 'email' not in request_dict:
                error += 'Email not entered. '
            if 'password' not in request_dict:
                error += 'Password not entered. '
            if 'first_name' not in request_dict:
                error += 'Name not entered.\n'
            response = { 'success' : 0, 'error' : error,
                    'email' : email, 'username' : username, 'password_1' : password_1, 
                    'password_2' : password_2, 'name' : first_name + last_name}

    if not response:
        if email == u'' or username == u'' or first_name == u'':
                error = ''
                if email == '':
                    error += 'Email not entered. '
                if password_1 == '':
                    error += 'Password not entered. '
                if first_name == '':
                    error += 'Name not entered.'
                response = { 'success' : 0, 'error' : error,
                        'email' : email, 'username' : username, 'password_1' : password_1, 
                        'password_2' : password_2, 'first_name' : first_name, 'last_name' : last_name }

    #Check if email is valid
    if not response and not helper_functions.validate_email(email):
        response = { 'success' : 0, 'error' : 'Invalid email address.' }

    if not response:
        if password_1 != password_2:
            response = { 'success' : 0, 'error' : 'Passwords do not match.' }

    #Check if username or email is taken
    if not response:
        if auth.models.User.objects.filter(username=username).exists():
            response = { 'success' : 0, 'error' : 'Username already taken.' }
    if not response:
        if auth.models.User.objects.filter(email=email).exists():
            response = { 'success' : 0, 'error' : 'Email already in use.' }

    if not response:
        new_user = auth.models.User.objects.create_user(username=username, email=email, password=password_1)
        new_user.first_name = first_name
        new_user.last_name = last_name
        new_user.is_active = True
        new_user.save()

        #Send user e-mail containing key which is their username salted & hashed
        #key = hashlib.md5('bailey' + username).hexdigest()
        #send_mail('The Block registration', 'Hi ' + str(first_name) + ' ' + str(last_name) + 
        #        ',\n\nWelcome to The Block! ' +
        #        'Click the following link to finish signing up: http://inmyblock.com/users/' + 
        #        str(new_user.id) + '/register/' + str(key) + 
        #        '\n\n-The Block', '*****@*****.**'
        #        , [email], fail_silently=False)

        #Create profile for this user
        user_account = UserProfile(user=new_user)
        user_account.save()

        user = auth.authenticate(username=username, password=password_1)
        if (user is not None and user.is_active):
            #Correct password, so we can log them in
            auth.login(request, user)

        response = { 'success' : 1 }
    
    if type_requested == 'rest':
        return helper_functions.dict_to_json_response(response)
    elif type_requested == 'desktop':
        if response['success'] == 0:
            #Theres an error, so redisplay signup page with error text
            return render_to_response('block_page.html', response, context_instance=RequestContext(request))
        else:
            return HttpResponseRedirect('/desktop/block/')