Esempio n. 1
0
    def _create_response(self, question, user_profile, response_type):
        comment_response = CommentResponse(user=user_profile, \
                                           comment=question, \
                                           type=response_type) 
        comment_response.save()

        return comment_response
Esempio n. 2
0
 def _flag_as_opinion(self, user_profile, question):
     """Utility method to flag something as opinion."""
     comment_response = CommentResponse(user=user_profile, \
                                        comment=question, \
                                        type="opinion")
     comment_response.save()
Esempio n. 3
0
 def _respond_positively(self, user_profile, question):
     """Utility method to respond positively to a question."""
     comment_response = CommentResponse(user=user_profile, \
                                        comment=question, \
                                        type="concur")
     comment_response.save()
Esempio n. 4
0
def api_comment_responses(request, comment_id, output_format='json',
                          response_id=None):
    """Provide RESTful responses to calls for comment responses.
    
       Example API calls:
       
       Create a new concur response
       Method: POST
       URI: /api/json/comments/1/responses/
       Request paramets:
        type:   "concur"
       Response code: 201 Created
       Response data: {"uri": "/api/json/comments/1/responses/1/"} 
       
    """

    # A user can only respond once during this time period
    # Set these to numbers to make limits take effect,
    # set to None for no limits
    #RESPONSE_WINDOW_HOURS = 0
    #RESPONSE_WINDOW_MINUTES = 5
    RESPONSE_WINDOW_HOURS = None 
    RESPONSE_WINDOW_MINUTES = None 

    # A user can only make this many responses per comment, per type
    MAX_RESPONSES = 1

    data = {}
    status=200 # Be optimistic

    try:
        if request.is_ajax():
            user_id = request.session.get('_auth_user_id', False)

            if user_id: 
                # User is logged in, get the user object
                user = UserProfile.objects.get(user__id = user_id)
            else:
                raise UserNotAuthenticated

            if request.method == 'POST':
                if "type" not in request.POST.keys():
                    raise MissingParameter("You must specify a 'type' " + \
                        "parameter ' + 'to indicate which kind of comment " + \
                        "response is being created")

                response_type = request.POST['type']

                # Try to get the comment object
                comment = Comment.objects.get(id = comment_id)

                # Check to see if the user created the comment.  You can't
                # respond to a comment you created.
                if comment.user.user.id == user.id:
                    # They match!
                    raise UserOwnsItem("You can't vote on an item that you " + \
                                       "created!")

                # Get any previous responses
                responses = CommentResponse.objects.filter(comment=comment, \
                    user__user__id=user_id, \
                    type=response_type).order_by('created')

                if responses.count() < MAX_RESPONSES and \
                   responses.count() > 0:
                    # User hasn't exceeded the maximum number of responses 
                    # allowed
                    
                    if RESPONSE_WINDOW_HOURS is not None and \
                       RESPONSE_WINDOW_MINUTS is not None:
                        # If time limits are enabled check to see
                        # if the user has commented too recently
                    
                        # Get the current time
                        now = datetime.datetime.now()

                        # Get the difference between now and when the user last 
                        # responded
                        time_diff = now - responses[0].created

                        # Calculate the allowable window
                        time_window = datetime.timedelta( \
                            hours=RESPONSE_WINDOW_HOURS, \
                            minutes=RESPONSE_WINDOW_MINUTES);

                        if time_diff < time_window:
                          # User has already commented within the allowable 
                          # window 

                          # Calculate how long the user has to wait
                          wait = time_window - time_diff
                          wait_hours, remainder = divmod(wait.seconds, 3600)
                          wait_minutes, wait_seconds = divmod(remainder, 60)

                          raise RecentlyResponded( \
                            "You must wait %d hours, %d minutes " +
                            "before responding" % (wait_hours, wait_minutes))

                elif responses.count() == 0:
                    pass
                            
                else:
                    raise MaximumExceeded("User has already made maximum " + \
                                          "number of responses")
        
                # Check accept case

                if response_type == 'accept':
                    # This should only be allowed for replies to comments posed by the user

                    # Is the comment a reply at all?
                    try: 
                        reply_relation = CommentRelation.objects.filter(left_comment = comment, relation_type = 'reply')
                    except ObjectDoesNotExist:
                        raise NotUserQuestionReply ("This is not a reply to a question")

                    # It's a reply, but who posed the initial question?

                    if not reply_relation.right_comment.user == user:
                        raise NotUserQuestionReply ("This is a reply to a question posed by another user; user cannot accept it")

                comment_response = CommentResponse(user=user, \
                                                   comment=comment, \
                                                   type=response_type) 
                comment_response.save()

                status = 201
                data['uri'] = "/api/%s/comments/%s/responses/%s/" % \
                              (output_format, comment_id, \
                               comment_response.id)
                    
            elif request.method == 'PUT':
                raise MethodUnsupported("PUT is not supported at this time.")

            elif request.method == 'DELETE':
                raise MethodUnsupported("DELETE is not supported at this time.")
                
            else:
                # GET 
                raise MethodUnsupported("GET is not supported at this time.")

        else:
            # Non-AJAX request.  Disallow for now.
            raise NonAjaxRequest( \
                "Remote API calls aren't allowed right now. " + \
                "This might change some day.")

    except ObjectDoesNotExist, e:
        status = 404 # Not found
        data['error'] = "%s" % e