예제 #1
0
def DeleteStaticContent(urls):
    TAG = Const.Tags.Events.PRUNE_STATIC_CONTENT
    
    try:
        if(settings.PRUNE_STATIC_CONTENT):
            s3 = boto3.resource('s3')
            bucket = s3.Bucket(settings.AWS_BUCKET_NAME)
        
            objectsToDelete = []
                   
        
            # build up the list of objects to delete to we can pass to the delete
            for url in urls:
                object = { 'Key': url}
                objectsToDelete.append(object)
            
            delete = {'Objects': objectsToDelete,
                      'Quiet': False }
            
            # Delete the objects from the bucket
            # TODO: parse this response object and do stuff with it 
            response = bucket.delete_objects(Delete=delete)
            
            DataCollector.logServerEvent(TAG, { 
                Const.DataCollection.ParamNames.MESSAGE_CODE: Const.DataCollection.MessageCodes.Events.PruneStaticContent.SUCCESS,
                Const.DataCollection.ParamNames.NUM_RECEIVED: len(urls),
                Const.DataCollection.ParamNames.NUM_DELETED: len(urls) }) # note: we need to get this info from response object later
            
    except Exception as e:
        DataCollector.logServerError(e)
예제 #2
0
def UploadLive(requestData):
    TAG = Const.Tags.Urls.UPLOAD_LIVE

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:       
        clientUser = securityProperties.userObject
        clientSession = securityProperties.userSession
        clientThreadText= securityProperties.jsonRequestData[Const.Views.UploadThread.JsonRequestKey.THREAD_TEXT]
        clientThreadKey = securityProperties.jsonRequestData[Const.Views.UploadThread.JsonRequestKey.THREAD_URL]
        clientThreadARN = securityProperties.jsonRequestData[Const.Views.UploadThread.JsonRequestKey.THREAD_ARN]
 
        # check if this user is posting too fast
        if (settings.RATE_LIMIT_LIVE and RateLimiter.UserLiveRateLimitExceeded(clientUser.id)): 
                  
            # log the warning and return if too many threads
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS, 
                                       messageCode=Const.DataCollection.MessageCodes.UploadLive.RATE_LIMIT_EXCEEDED)

            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS, 
                                                        Const.DataCollection.MessageCodes.UploadLive.RATE_LIMIT_EXCEEDED) 

        # Save the live thread in the DB
        # Save title as an empty string if it is empty
        if (Utils.StringIsEmpty(clientThreadText)):
            clientThreadText = ''
               
        Thread.objects.create(fromUser=clientUser,
                              fromSession=clientSession,
                              contentType=Const.Tags.ContentTypes.THREAD,
                              text=clientThreadText,
                              key=clientThreadKey,
                              arn=clientThreadARN)
                     

        QueryManager.CheckAndPruneThreads()           
       
        # FOR RELEASE 1.1
        # return the list of threads after a successful thread upload    
        jsonString = GetThreadListJsonString()

        # log and return on success   
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                    messageCode=Const.DataCollection.MessageCodes.UploadLive.POST_SUCCESSFUL)         
       
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                                    jsonString, 'application/json')
        
    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                    messageCode=Const.DataCollection.MessageCodes.UploadLive.POST_FAILED_SERVER_ERROR)  

        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.UploadLive.POST_FAILED_SERVER_ERROR)
예제 #3
0
def GetLive(requestData):
    TAG = Const.Tags.Urls.GET_LIVE
        
    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:        
        # Get the list of threads
        jsonString = GetThreadListJsonString()

        # log and return on success          
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                   messageCode=Const.DataCollection.MessageCodes.GetLive.REQUEST_SUCCESSFUL)
                       
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                                    jsonString, 'application/json')
    
    except Exception as e:
        # log and return on error
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR,
                                   messageCode=Const.DataCollection.MessageCodes.GetLive.REQUEST_FAILED_SERVER_ERROR)
 
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.GetLive.REQUEST_FAILED_SERVER_ERROR)
예제 #4
0
def CreateUser(requestData):
    TAG = Const.Tags.Urls.SECURITY_CREATE

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse

    try:
        # Create the new user identity in the db
        with transaction.atomic():
            newUser = User.objects.create()
            newUserID = Utils.BinaryToUUID(newUser.id)
            identityID = ''

            # Create a new identity on Cognito with the new uuid
            # Only when in not in DEBUG. I don't want to get charged ;)
            if (not settings.DEBUG):
                identityID = AuthManager.CreateNewCognitoIdentity(newUserID)

            jsonDict = _CreateUserClientObject(newUserID,
                                               identityID).getOrderedDict()
            jsonString = json.dumps(jsonDict)
            logger.info(jsonString)

            # Update the URL hit and return
            DataCollector.UpdateURLHit(
                hitID=securityProperties.hitID,
                responseCode=Const.HttpResponseFactory.ResponseCodes.Success.
                CODE_OK,
                messageCode=Const.DataCollection.MessageCodes.SecurityCreate.
                CREATE_SUCCESSFUL)

            return HttpResponseFactory.MakeHttpResponse(
                Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                jsonString, 'application/json')

    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(
            hitID=securityProperties.hitID,
            responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR,
            messageCode=Const.DataCollection.MessageCodes.SecurityCreate.
            CREATE_FAILED_SERVER_ERROR)

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR, Const.DataCollection.MessageCodes.
            SecurityCreate.CREATE_FAILED_SERVER_ERROR)
예제 #5
0
def Login(requestData):
    TAG = Const.Tags.Urls.SECURITY_LOGIN

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse

    try:
        currentTime = int(time.time())
        timeSessionExpires = currentTime + settings.AWS_COGNITO_TOKEN_DURATION

        # Get the client user
        clientUser = securityProperties.userObject

        # Login to Cognito and retrieve the access token for this client
        # We login with our uuid
        token = AuthManager.LoginWithCognitoIdentity(securityProperties.userID)

        # Create a new user session in the DB
        Session.objects.create(fromUser=securityProperties.userObject,
                               timeExpires=timeSessionExpires,
                               token=token)

        jsonString = json.dumps(_LoginClientObject(token).getOrderedDict())

        DataCollector.UpdateURLHit(
            hitID=securityProperties.hitID,
            responseCode=Const.HttpResponseFactory.ResponseCodes.Success.
            CODE_OK,
            messageCode=Const.DataCollection.MessageCodes.SecurityLogin.
            REQUEST_SUCCESSFUL)

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
            jsonString, 'application/json')

    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(
            hitID=securityProperties.hitID,
            responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR,
            messageCode=Const.DataCollection.MessageCodes.SecurityLogin.
            REQUEST_FAILED_SERVER_ERROR)

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR, Const.DataCollection.MessageCodes.
            SecurityCreate.CREATE_FAILED_SERVER_ERROR)
예제 #6
0
def RunThroughSecurityLayer(urlTag, urlRequestData):
    currentTime = time.time()

    # Get all security info on this request
    securityProperties = SecurityProperties()
    securityProperties = GetData(securityProperties, urlTag, urlRequestData,
                                 currentTime)
    securityProperties = CheckData(securityProperties, urlTag)
    securityProperties = CheckUserIdentity(securityProperties, urlTag,
                                           currentTime)

    # Once all checks are done, set is isSecure flag
    if (securityProperties.errorsList):
        securityProperties.isSecure = False
    else:
        securityProperties.isSecure = True

    # Attach an appropriate Http response that we can use, if there was an error
    if (not securityProperties.isSecure):
        securityProperties.httpResponse = MakeSecurityErrorHttpResponse(
            securityProperties)

    # Log the request
    # This also logs security errors if there are any
    # and returns the hitID for the hit so we can use it later
    securityProperties.hitID = DataCollector.LogURLHit(securityProperties)

    return securityProperties
예제 #7
0
def AnalyticsFeedback(requestData):
    TAG = Const.Tags.Urls.ANALYTICS_FEEDBACK

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse

    try:
        clientFeedbackText = securityProperties.jsonRequestData[
            Const.Views.AnalyticsFeedback.JsonRequestKey.TEXT]

        # Save the feedback in the DB
        Feedback.objects.create(fromUser=securityProperties.userObject,
                                text=clientFeedbackText)

        # Update the URL hit and return
        DataCollector.UpdateURLHit(
            hitID=securityProperties.hitID,
            responseCode=Const.HttpResponseFactory.ResponseCodes.Success.
            CODE_OK,
            messageCode=Const.DataCollection.MessageCodes.AnalyticsFeedback.
            REQUEST_SUCCESSFUL)

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, Const.
            DataCollection.MessageCodes.AnalyticsFeedback.REQUEST_SUCCESSFUL)

    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(
            hitID=securityProperties.hitID,
            responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR,
            messageCode=Const.DataCollection.MessageCodes.AnalyticsFeedback.
            REQUEST_FAILED_SERVER_ERROR)

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR, Const.DataCollection.MessageCodes.
            AnalyticsFeedback.REQUEST_FAILED_SERVER_ERROR)
예제 #8
0
def Report(requestData):
    
    TAG = Const.Tags.Urls.MODERATION_REPORT
    
    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:
        clientUser = securityProperties.userObject
        clientContentId = securityProperties.jsonRequestData[Const.Views.Report.JsonRequestKey.CONTENT_ID]
        
        # check that the content exists in the database
        clientContent = QueryManager.GetObjectByID(OnlineContent, clientContentId)
        if (not clientContent):
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, 
                                       messageCode=Const.DataCollection.MessageCodes.ModerationReport.CONTENT_NOT_FOUND)  
            
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, 
                                                        Const.DataCollection.MessageCodes.ModerationReport.CONTENT_NOT_FOUND)
        
        # get the content type that the user is reporting
        contentType = clientContent.contentType
        
        # check if this user has already tried to create this report
        userDupeReports = ReportModel.objects.filter(fromUser=clientUser,
                                                contentID=clientContentId)
        
        # If so, log the hit and return an error to client
        if (userDupeReports):
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_CONFLICT, 
                                       messageCode=Const.DataCollection.MessageCodes.ModerationReport.REPORT_EXISTS) 
             
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_CONFLICT, 
                                                        Const.DataCollection.MessageCodes.ModerationReport.REPORT_EXISTS) 
        
        # Create the report
        ReportModel.objects.create(fromUser=clientUser,
                                   contentID=Utils.UUIDToBinary(clientContentId),
                                   contentType=contentType)  
        
        # Log the hit and return
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                   messageCode=Const.DataCollection.MessageCodes.ModerationReport.REQUEST_SUCCESSFUL) 
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                                    Const.DataCollection.MessageCodes.ModerationReport.REQUEST_SUCCESSFUL)    
                
    except Exception as e:
        # log and return on error
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                    messageCode=Const.DataCollection.MessageCodes.ModerationReport.REQUEST_FAILED_SERVER_ERROR) 
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.ModerationReport.REQUEST_FAILED_SERVER_ERROR)
예제 #9
0
    def handle(self, *args, **options):
        numberToDisplay = int(options['num'])

        # Get the most recent errors
        recentErrors = Error.objects.order_by('-timeCreated')[:numberToDisplay]

        Utils.ClearConsole()
        errors = DataCollector.ServerErrorsToString(recentErrors)

        # Print each one, in reversed list order
        # (Console printing stops at the last thing printed)
        for error in reversed(errors):
            print(error)
예제 #10
0
def CheckAndPruneThreads():
    import JokrBackend.DataCollection.ContentManager as ContentManager
    import JokrBackend.DataCollection.DataCollector as DataCollector

    # get the thread count
    numOfCurrentThreads = Thread.objects.count()

    # If the board is full already, prune a thread
    if numOfCurrentThreads > settings.BOARD_THREAD_LIMIT:
        numThreadsToPrune = numOfCurrentThreads - settings.BOARD_THREAD_LIMIT

        # Get the lowest bump order threads to be pruned
        threadsToPrune = GetLiveThreadsByTimeLastActive(
            ascending=True, limit=numThreadsToPrune)

        for thread in threadsToPrune:

            # log info about the pruned thread
            DataCollector.logServerEvent(
                Const.Tags.Events.PRUNE_THREAD,
                {Const.DataCollection.ParamNames.THREAD_ID: thread.id})

            ContentManager.DeleteContent(thread.id)
예제 #11
0
    def handle(self, *args, **options):
        TAG = Const.Tags.Events.PRUNE_LOCALPOSTS

        try:
            # Only run the pruning if the setting is set
            if (settings.PRUNE_OLD_LOCALPOSTS):

                currentTime = time.time()
                oldestTimeAllowed = currentTime - (
                    Const.Pruning.LOCALPOST_MAX_AGE_HOURS *
                    Const.SECONDS_IN_HOUR)
                numPostsDeleted = 0

                # Get all localposts where timeCreated < oldestTimeAllowed
                localPostsToDelete = LocalPost.objects.filter(
                    timeCreated__lt=oldestTimeAllowed)

                # remove static content if enabled
                if (settings.PRUNE_STATIC_CONTENT):
                    localPostUrls = []
                    for lp in localPostsToDelete:
                        localPostUrls.append(lp.url)

                    StaticContentUtils.DeleteStaticContent(
                        localPostUrls, 'local')

                # Remove each local post
                for lp in localPostsToDelete:
                    lp.delete()
                    numPostsDeleted += 1

            # log info on success
            DataCollector.logServerEvent(
                TAG, {
                    Const.DataCollection.ParamNames.MESSAGE_CODE:
                    Const.DataCollection.MessageCodes.Events.PruneLocalPosts.
                    SUCCESS,
                    Const.DataCollection.ParamNames.NUM_RECEIVED:
                    len(list(localPostsToDelete)),
                    Const.DataCollection.ParamNames.NUM_DELETED:
                    numPostsDeleted
                })

        except Exception as e:
            # log error and info on error
            DataCollector.logServerError(e)
            DataCollector.logServerEvent(
                TAG, {
                    Const.DataCollection.ParamNames.MESSAGE_CODE:
                    Const.DataCollection.MessageCodes.Events.PruneLocalPosts.
                    SERVER_ERROR,
                    Const.DataCollection.ParamNames.NUM_RECEIVED:
                    len(list(localPostsToDelete)),
                    Const.DataCollection.ParamNames.NUM_DELETED:
                    numPostsDeleted
                })
예제 #12
0
    def handle(self, *args, **options):
        TAG = Const.Tags.Events.PRUNE_MESSAGES

        try:
            if (settings.PRUNE_OLD_MESSAGES):
                currentTime = time.time()
                oldestTimeAllowed = currentTime - (
                    Const.Pruning.MESSAGE_MAX_AGE_HOURS *
                    Const.SECONDS_IN_HOUR)
                numMessagesDeleted = 0

                # Get all messages where timeCreated < oldestTimeAllowed
                messagesToDelete = Message.objects.filter(
                    timeCreated__lt=oldestTimeAllowed)

                # remove static content if enabled
                if (settings.PRUNE_STATIC_CONTENT):
                    messageUrls = []
                    for m in messagesToDelete:
                        messageUrls.append(m.url)

                    StaticContentUtils.DeleteStaticContent(
                        messageUrls, 'message')

                # Remove each one
                for m in messagesToDelete:
                    m.delete()
                    numMessagesDeleted += 1

            # log info on success
            DataCollector.logServerEvent(
                TAG, {
                    Const.DataCollection.ParamNames.MESSAGE_CODE:
                    Const.DataCollection.MessageCodes.Events.PruneLocalPosts.
                    SUCCESS,
                    Const.DataCollection.ParamNames.NUM_RECEIVED:
                    len(list(messagesToDelete)),
                    Const.DataCollection.ParamNames.NUM_DELETED:
                    numMessagesDeleted
                })

        except Exception as e:
            # log error and info on error
            DataCollector.logServerError(e)
            DataCollector.logServerEvent(
                TAG, {
                    Const.DataCollection.ParamNames.MESSAGE_CODE:
                    Const.DataCollection.MessageCodes.Events.PruneLocalPosts.
                    SERVER_ERROR,
                    Const.DataCollection.ParamNames.NUM_RECEIVED:
                    len(list(messagesToDelete)),
                    Const.DataCollection.ParamNames.NUM_DELETED:
                    numMessagesDeleted
                })
예제 #13
0
def SubscribeLive(requestData):
    TAG = Const.Tags.Urls.SUBSCRIBE_LIVE
        
    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:        
        instanceID = securityProperties.jsonRequestData[Const.Views.SubscribeLive.JsonRequestKey.INSTANCE_ID]
        threadID = securityProperties.jsonRequestData[Const.Views.SubscribeLive.JsonRequestKey.THREAD_ID]

        # Check that the thread exists
        if (not QueryManager.ContentIsOnline(threadID)):
            # If not, return 404
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND,
                                   messageCode=Const.DataCollection.MessageCodes.SubscribeLive.THREAD_NOT_FOUND)
                       
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND,
                                                        Const.DataCollection.MessageCodes.SubscribeLive.THREAD_NOT_FOUND)
        
        # try to subscribe to the thread
        googleResponseCode = GCMManager.SubscribeUserToThread(instanceID, threadID)
        
        # check the response. If it was not successful, return an error
        if (googleResponseCode != Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK):
                DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_BAD_REQUEST,
                                   messageCode=Const.DataCollection.MessageCodes.SubscribeLive.GCM_SUBSCRIBE_FAILED)
                       
                return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_BAD_REQUEST,
                                                            Const.DataCollection.MessageCodes.SubscribeLive.GCM_SUBSCRIBE_FAILED)
            

        # log and return on success          
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                   messageCode=Const.DataCollection.MessageCodes.SubscribeLive.REQUEST_SUCCESSFUL)
                       
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                                    Const.DataCollection.MessageCodes.SubscribeLive.REQUEST_SUCCESSFUL)
    
    except Exception as e:
        # log and return on error
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR,
                                   messageCode=Const.DataCollection.MessageCodes.SubscribeLive.REQUEST_FAILED_SERVER_ERROR)
 
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.SubscribeLive.REQUEST_FAILED_SERVER_ERROR)
예제 #14
0
def UploadMessage(requestData):
    TAG = Const.Tags.Urls.UPLOAD_MESSAGE

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse

    try:
        clientUser = securityProperties.clientUserObject
        clientRecipientUserUUID = securityProperties.jsonRequestData[
            Const.Views.UploadMessage.JsonRequestKey.TO_USER_ID]
        clientMessageText = securityProperties.jsonRequestData[
            Const.Views.UploadMessage.JsonRequestKey.TEXT]
        clientMessageURL = securityProperties.jsonRequestData[
            Const.Views.UploadMessage.JsonRequestKey.URL]

        # Find the recipient user in the DB
        try:
            recipientUser = User.objects.get(
                uuid=Utils.ConvertUUIDToBinary(clientRecipientUserUUID))
        except ObjectDoesNotExist:
            DataCollector.logURL(
                TAG, {
                    Const.DataCollection.ParamNames.RESPONSE_CODE:
                    Const.HttpResponseFactory.ResponseCodes.ClientError.
                    CODE_UNPROCESSABLE_ENTITY,
                    Const.DataCollection.ParamNames.MESSAGE_CODE:
                    Const.DataCollection.MessageCodes.UploadMessage.
                    RECIPIENT_NOT_FOUND,
                    Const.DataCollection.ParamNames.FROM_USER:
                    Utils.ConvertBinaryToUUID(clientUser.uuid),
                    Const.DataCollection.ParamNames.TO_USER:
                    Utils.ConvertBinaryToUUID(recipientUser.uuid),
                    Const.DataCollection.ParamNames.HAS_TEXT:
                    (not Utils.StringIsEmpty(clientMessageText))
                })

            return HttpResponseFactory.MakeHttpResponse(
                Const.HttpResponseFactory.ResponseCodes.ClientError.
                CODE_UNPROCESSABLE_ENTITY, Const.DataCollection.MessageCodes.
                UploadMessage.RECIPIENT_NOT_FOUND)

        # Save the message in the DB
        newMessage = Message(toUser=recipientUser,
                             fromUser=clientUser,
                             text=clientMessageText,
                             url=clientMessageURL,
                             contentType=Const.Tags.ContentTypes.MESSAGE)

        # If there is an exception, roll back this db transaction
        with transaction.atomic():
            newMessage.save()

        # log and return on success
        DataCollector.logURL(
            TAG, {
                Const.DataCollection.ParamNames.RESPONSE_CODE:
                Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                Const.DataCollection.ParamNames.MESSAGE_CODE:
                Const.DataCollection.MessageCodes.UploadMessage.
                POST_SUCCESSFUL,
                Const.DataCollection.ParamNames.FROM_USER:
                Utils.ConvertBinaryToUUID(clientUser.uuid),
                Const.DataCollection.ParamNames.TO_USER:
                Utils.ConvertBinaryToUUID(recipientUser.uuid),
                Const.DataCollection.ParamNames.HAS_TEXT:
                (not Utils.StringIsEmpty(clientMessageText))
            })

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
            Const.DataCollection.MessageCodes.UploadMessage.POST_SUCCESSFUL)

    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.logURL(
            TAG, {
                Const.DataCollection.ParamNames.RESPONSE_CODE:
                Const.HttpResponseFactory.ResponseCodes.ServerError.
                CODE_INTERNAL_SERVER_ERROR,
                Const.DataCollection.ParamNames.MESSAGE_CODE:
                Const.DataCollection.MessageCodes.UploadMessage.
                POST_FAILED_SERVER_ERROR,
                Const.DataCollection.ParamNames.FROM_USER:
                Utils.ConvertBinaryToUUID(clientUser.uuid),
                Const.DataCollection.ParamNames.TO_USER:
                Utils.ConvertBinaryToUUID(recipientUser.uuid),
                Const.DataCollection.ParamNames.HAS_TEXT:
                (not Utils.StringIsEmpty(clientMessageText))
            })

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR, Const.DataCollection.MessageCodes.
            UploadMessage.POST_FAILED_SERVER_ERROR)
예제 #15
0
def GetMessage(requestData):
    TAG = Const.Tags.Urls.GET_MESSAGE

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse

    try:

        clientUser = securityProperties.clientUserObject

        # Retrieve all this user's messages from the DB
        messages = Message.objects.filter(toUser=clientUser)
        clientMessageListToReturn = []
        for lm in messages:
            clientMessageToReturn = _GetMessageClientObject(
                id=lm.id,
                time=lm.timeCreated,
                fromUserId=str(ConvertBinaryToUUID(lm.fromUser.uuid)),
                text=lm.text,
                url=lm.url)
            clientMessageListToReturn.append(
                clientMessageToReturn.getOrderedDict())

        jsonString = json.dumps(clientMessageListToReturn)

        # Delete all this user's messages from the DB, since we are about to give
        # them their messages (this is temporary)
        for m in messages:
            m.delete()

        # log and return on success
        DataCollector.logURL(
            TAG, {
                Const.DataCollection.ParamNames.RESPONSE_CODE:
                Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                Const.DataCollection.ParamNames.MESSAGE_CODE:
                Const.DataCollection.MessageCodes.GetMessage.
                REQUEST_SUCCESSFUL,
                Const.DataCollection.ParamNames.FROM_USER:
                Utils.ConvertBinaryToUUID(clientUser.uuid),
                Const.DataCollection.ParamNames.NUM_MESSAGES_RECEIVED:
                len(list(messages))
            })

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
            jsonString, 'application/json')

    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.logURL(
            TAG, {
                Const.DataCollection.ParamNames.RESPONSE_CODE:
                Const.HttpResponseFactory.ResponseCodes.ServerError.
                CODE_INTERNAL_SERVER_ERROR,
                Const.DataCollection.ParamNames.MESSAGE_CODE:
                Const.DataCollection.MessageCodes.GetMessage.
                REQUEST_FAILED_SERVER_ERROR,
                Const.DataCollection.ParamNames.FROM_USER:
                Utils.ConvertBinaryToUUID(clientUser.uuid),
                Const.DataCollection.ParamNames.NUM_MESSAGES_RECEIVED:
                len(list(messages))
            })

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR, Const.DataCollection.MessageCodes.
            GetMessage.REQUEST_FAILED_SERVER_ERROR)
예제 #16
0
def GetReply(requestData):
    TAG = Const.Tags.Urls.GET_REPLY

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse

    try:

        clientUser = securityProperties.userObject
        clientThreadID = securityProperties.jsonRequestData[
            Const.Views.GetReply.JsonRequestKey.THREAD_ID]

        # Retrieve the thread and replies from the database
        thread = QueryManager.GetObjectByID(Thread, clientThreadID)
        threadReplies = Reply.objects.filter(parentThread=thread)

        if (not thread):
            DataCollector.UpdateURLHit(
                hitID=securityProperties.hitID,
                responseCode=Const.HttpResponseFactory.ResponseCodes.
                ClientError.CODE_NOT_FOUND,
                messageCode=Const.DataCollection.MessageCodes.GetReply.
                THREAD_NOT_FOUND)

            return HttpResponseFactory.MakeHttpResponse(
                Const.HttpResponseFactory.ResponseCodes.ClientError.
                CODE_NOT_FOUND,
                Const.DataCollection.MessageCodes.GetReply.THREAD_NOT_FOUND)

        # Package the thread replies and return
        clientReplyListToReturn = []
        for reply in threadReplies:
            replyClientObject = GetReplyClientObject(text=reply.text,
                                                     time=reply.timeCreated,
                                                     id=Utils.BinaryToUUID(
                                                         reply.id),
                                                     key=reply.key)
            clientReplyListToReturn.append(replyClientObject.getDict())

        jsonString = json.dumps(clientReplyListToReturn)

        # log and return on success
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                   responseCode=Const.HttpResponseFactory.
                                   ResponseCodes.Success.CODE_OK,
                                   messageCode=Const.DataCollection.
                                   MessageCodes.GetReply.REQUEST_SUCCESSFUL)

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
            jsonString, 'application/json')

    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(
            hitID=securityProperties.hitID,
            responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR,
            messageCode=Const.DataCollection.MessageCodes.GetReply.
            REQUEST_FAILED_SERVER_ERROR)

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR, Const.DataCollection.MessageCodes.
            GetReply.REQUEST_FAILED_SERVER_ERROR)
예제 #17
0
def GetBanInfo(requestData):
    TAG = Const.Tags.Urls.SECURITY_GETBANINFO

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse

    try:
        clientUser = securityProperties.clientUserObject
        banLength = ''
        banTimeCreated = ''

        # Check if the user has any bans
        userBan = Ban.objects.filter(
            bannedUser=clientUser).order_by('-timeCreated')[:1]

        # If there is a ban, check to make sure it is still active
        if (userBan):
            userBan = userBan[0]
            banExpires = userBan.timeCreated + (userBan.banLengthHours *
                                                Const.SECONDS_IN_HOUR)

            # If the ban expir. time is past the current time, then the user is
            # still currently under a ban
            if (banExpires > time.time()):
                banTimeCreated = userBan.timeCreated
                banLength = userBan.banLengthHours

        clientObject = _BanInfoClientObject(
            banStartTime=banTimeCreated,
            banEndTime=(banTimeCreated + (banLength * Const.SECONDS_IN_HOUR)))
        jsonString = json.dumps(clientObject.getOrderedDict())

        DataCollector.logURL(
            TAG, {
                Const.DataCollection.ParamNames.RESPONSE_CODE:
                Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                Const.DataCollection.ParamNames.MESSAGE_CODE:
                Const.DataCollection.MessageCodes.SecurityGetBanInfo.
                REQUEST_SUCCESSFUL,
                Const.DataCollection.ParamNames.FROM_USER:
                Utils.ConvertBinaryToUUID(clientUser.uuid)
            })

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
            jsonString, 'application/json')

    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.logURL(
            TAG, {
                Const.DataCollection.ParamNames.RESPONSE_CODE:
                Const.HttpResponseFactory.ResponseCodes.ServerError.
                CODE_INTERNAL_SERVER_ERROR,
                Const.DataCollection.ParamNames.MESSAGE_CODE:
                Const.DataCollection.MessageCodes.SecurityGetBanInfo.
                REQUEST_FAILED_SERVER_ERROR,
                Const.DataCollection.ParamNames.NEW_USER:
                ''
            })

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR, Const.DataCollection.MessageCodes.
            SecurityGetBanInfo.REQUEST_FAILED_SERVER_ERROR)
예제 #18
0
def UploadReply(requestData):
    TAG = Const.Tags.Urls.UPLOAD_REPLY
     
    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:
        clientUser = securityProperties.userObject
        clientSession = securityProperties.userSession
        clientThreadID = securityProperties.jsonRequestData[Const.Views.UploadReply.JsonRequestKey.THREAD_ID]
        clientReplyText= securityProperties.jsonRequestData[Const.Views.UploadReply.JsonRequestKey.REPLY_TEXT]
        clientReplyKey = securityProperties.jsonRequestData[Const.Views.UploadReply.JsonRequestKey.REPLY_URL]

        # Moderation - check if this user is posting replies too fast
        if (settings.RATE_LIMIT_LIVE and RateLimiter.UserReplyRateLimitExceeded(clientUser.id)):
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS, 
                                       messageCode=Const.DataCollection.MessageCodes.UploadReply.RATE_LIMIT_EXCEEDED)  
            
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS, 
                                                        Const.DataCollection.MessageCodes.UploadReply.RATE_LIMIT_EXCEEDED)
        
        # Find the parent thread to reply to in the DB  
        threadToReplyTo = QueryManager.GetObjectByID(Thread, clientThreadID)
        
        if (not threadToReplyTo):
            DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                       responseCode=Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, 
                                       messageCode=Const.DataCollection.MessageCodes.UploadReply.THREAD_NOT_FOUND) 
            
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_NOT_FOUND, 
                                                        Const.DataCollection.MessageCodes.UploadReply.THREAD_NOT_FOUND)

        # These fields are optional. Make sure that they go into the DB
        # as an empty string if they are not present 
        if (Utils.StringIsEmpty(clientReplyText)):
            clientReplyText = ''
        if (Utils.StringIsEmpty(clientReplyKey)):
            clientReplyKey = ''

        # Save the reply in the DB
        newReply = Reply.objects.create(fromUser=clientUser,
                             fromSession=clientSession,
                             contentType=Const.Tags.ContentTypes.REPLY,
                             parentThread=threadToReplyTo,
                             text=clientReplyText,
                             key=clientReplyKey)
        
        # Broadcast the reply out to this thread's subscribers using GCM
        # Create the client reply object
        newReplyClientObject = GetReplyClientObject(text=newReply.text, 
                                                    time=newReply.timeCreated, 
                                                    id=Utils.BinaryToUUID(newReply.id), 
                                                    key=newReply.key) 
        
        # Turn it into JSON and send it off
        googleResponseCode = GCMManager.BroadcastReplyToSubscribers(parentThreadID=clientThreadID,
                                               newReplyJSON=newReplyClientObject.getDict()) 
        
        # Check the response code from google
        # If it is not successful, return and log a warning, but still
        # return a 200 code to the client (since the reply saved ok)
        if (googleResponseCode != Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK):
                DataCollector.UpdateURLHit(hitID=securityProperties.hitID, 
                                   responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                   messageCode=Const.DataCollection.MessageCodes.UploadReply.GCM_BROADCAST_FAILED)
                       
                return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                                                            Const.DataCollection.MessageCodes.UploadReply.GCM_BROADCAST_FAILED)
        
        
        # log and return on success
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                    messageCode=Const.DataCollection.MessageCodes.UploadReply.POST_SUCCESSFUL) 
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                                    Const.DataCollection.MessageCodes.UploadReply.POST_SUCCESSFUL)
    
    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.UpdateURLHit(hitID=securityProperties.hitID,
                                    responseCode=Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                    messageCode=Const.DataCollection.MessageCodes.UploadReply.POST_FAILED_SERVER_ERROR)  
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.UploadReply.POST_FAILED_SERVER_ERROR)
예제 #19
0
def UploadLocalPost(requestData):
    
    TAG = Const.Tags.Urls.UPLOAD_LOCAL
    
    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:
           
        clientUser = securityProperties.clientUserObject
        clientLatitude = securityProperties.jsonRequestData[Const.Views.UploadLocalPost.JsonRequestKey.LATITUDE]
        clientLongitude = securityProperties.jsonRequestData[Const.Views.UploadLocalPost.JsonRequestKey.LONGITUDE]  
        clientPostText = securityProperties.jsonRequestData[Const.Views.UploadLocalPost.JsonRequestKey.TEXT]
        clientPostURL = securityProperties.jsonRequestData[Const.Views.UploadLocalPost.JsonRequestKey.URL]
        clientARN = securityProperties.jsonRequestData[Const.Views.UploadLocalPost.JsonRequestKey.ARN]
    
 
        # Moderation - check if this user is posting too fast
        if (settings.RATE_LIMIT_LOCAL and _UserLocalRateLimitExceeded(clientUser.id)):         
            DataCollector.logURL(TAG, { 
                Const.DataCollection.ParamNames.RESPONSE_CODE: Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS,
                Const.DataCollection.ParamNames.MESSAGE_CODE: Const.DataCollection.MessageCodes.UploadLocal.RATE_LIMIT_EXCEEDED,
                Const.DataCollection.ParamNames.FROM_USER: Utils.ConvertBinaryToUUID(clientUser.uuid),
                Const.DataCollection.ParamNames.LATITUDE: clientLatitude,
                Const.DataCollection.ParamNames.LONGITUDE: clientLongitude,
                Const.DataCollection.ParamNames.HAS_TEXT: (not Utils.StringIsEmpty(clientPostText)) })
    
            return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ClientError.CODE_TOO_MANY_REQUESTS, 
                                                        Const.DataCollection.MessageCodes.UploadLocal.RATE_LIMIT_EXCEEDED)
            
    
        # Creating a localPost and saving it in the DB       
        # Create a new LocalPost and populate the fields from the Json
        newPost = LocalPost(fromUser=clientUser,
                            latitude=clientLatitude,
                            longitude=clientLongitude,
                            text=clientPostText,
                            url=clientPostURL,
                            contentType=Const.Tags.ContentTypes.LOCALPOST,
                            arn=clientARN)
        
        # If there is an exception, roll back this db transaction
        # Save the post in the database
        with transaction.atomic():
            newPost.save()
                
        # log and return on success
        DataCollector.logURL(TAG, { 
            Const.DataCollection.ParamNames.RESPONSE_CODE: Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
            Const.DataCollection.ParamNames.MESSAGE_CODE: Const.DataCollection.MessageCodes.UploadLocal.POST_SUCCESSFUL,
            Const.DataCollection.ParamNames.FROM_USER: Utils.ConvertBinaryToUUID(clientUser.uuid),
            Const.DataCollection.ParamNames.LATITUDE: clientLatitude,
            Const.DataCollection.ParamNames.LONGITUDE: clientLongitude,
            Const.DataCollection.ParamNames.HAS_TEXT: (not Utils.StringIsEmpty(clientPostText)) })   
           
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                                    Const.DataCollection.MessageCodes.UploadLocal.POST_SUCCESSFUL)
        
    except Exception as e:
        # log and return on error
        DataCollector.logServerError(e)
        DataCollector.logURL(TAG, { 
            Const.DataCollection.ParamNames.RESPONSE_CODE: Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR,
            Const.DataCollection.ParamNames.MESSAGE_CODE: Const.DataCollection.MessageCodes.UploadLocal.POST_FAILED_SERVER_ERROR,
            Const.DataCollection.ParamNames.FROM_USER: Utils.ConvertBinaryToUUID(clientUser.uuid),
            Const.DataCollection.ParamNames.LATITUDE: clientLatitude,
            Const.DataCollection.ParamNames.LONGITUDE: clientLongitude,
            Const.DataCollection.ParamNames.HAS_TEXT: (not Utils.StringIsEmpty(clientPostText)) })
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.UploadLocal.POST_FAILED_SERVER_ERROR)
예제 #20
0
def Block(requestData):

    TAG = Const.Tags.Urls.MODERATION_BLOCK

    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse

    try:

        clientUser = securityProperties.clientUserObject
        clientBlockUser = securityProperties.jsonRequestData[
            Const.Views.Block.JsonRequestKey.USER_TO_BLOCK_ID]

        # Try to find the user to block in the Db
        try:
            blockedUser = User.objects.get(
                uuid=Utils.ConvertUUIDToBinary(clientBlockUser))
        except ObjectDoesNotExist:
            DataCollector.logURL(
                TAG, {
                    Const.DataCollection.ParamNames.RESPONSE_CODE:
                    Const.HttpResponseFactory.ResponseCodes.ClientError.
                    CODE_UNPROCESSABLE_ENTITY,
                    Const.DataCollection.ParamNames.MESSAGE_CODE:
                    Const.DataCollection.MessageCodes.ModerationBlock.
                    TARGET_USER_NOT_FOUND,
                    Const.DataCollection.ParamNames.BLOCKED_USER:
                    clientBlockUser,
                    Const.DataCollection.ParamNames.BLOCKER_USER:
                    Utils.ConvertBinaryToUUID(clientUser.uuid)
                })

            return HttpResponseFactory.MakeHttpResponse(
                Const.HttpResponseFactory.ResponseCodes.ClientError.
                CODE_UNPROCESSABLE_ENTITY, Const.DataCollection.MessageCodes.
                ModerationBlock.TARGET_USER_NOT_FOUND)

        # Make sure that this block does not already exist
        block = Block.objects.filter(blockerUser=clientUser,
                                     blockedUser=blockedUser)
        if block:
            DataCollector.logURL(
                TAG, {
                    Const.DataCollection.ParamNames.RESPONSE_CODE:
                    Const.HttpResponseFactory.ResponseCodes.ClientError.
                    CODE_CONFLICT,
                    Const.DataCollection.ParamNames.MESSAGE_CODE:
                    Const.DataCollection.MessageCodes.ModerationBlock.
                    BLOCK_EXISTS,
                    Const.DataCollection.ParamNames.BLOCKED_USER:
                    clientBlockUser,
                    Const.DataCollection.ParamNames.BLOCKER_USER:
                    Utils.ConvertBinaryToUUID(clientUser.uuid)
                })

            return HttpResponseFactory.MakeHttpResponse(
                Const.HttpResponseFactory.ResponseCodes.ClientError.
                CODE_CONFLICT,
                Const.DataCollection.MessageCodes.ModerationBlock.BLOCK_EXISTS)

        # Save the block in the DB
        # If there is an exception, roll back this db transaction
        with transaction.atomic():
            Block.objects.create(blockerUser=clientUser,
                                 blockedUser=blockedUser)

        # log and return on success
        DataCollector.logURL(
            TAG, {
                Const.DataCollection.ParamNames.RESPONSE_CODE:
                Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
                Const.DataCollection.ParamNames.MESSAGE_CODE:
                Const.DataCollection.MessageCodes.ModerationBlock.
                REQUEST_SUCCESSFUL,
                Const.DataCollection.ParamNames.BLOCKED_USER:
                clientBlockUser,
                Const.DataCollection.ParamNames.BLOCKER_USER:
                Utils.ConvertBinaryToUUID(clientUser.uuid)
            })

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, Const.
            DataCollection.MessageCodes.ModerationBlock.REQUEST_SUCCESSFUL)

    except Exception as e:
        DataCollector.logServerError(e)
        DataCollector.logURL(
            TAG, {
                Const.DataCollection.ParamNames.RESPONSE_CODE:
                Const.HttpResponseFactory.ResponseCodes.ServerError.
                CODE_INTERNAL_SERVER_ERROR,
                Const.DataCollection.ParamNames.MESSAGE_CODE:
                Const.DataCollection.MessageCodes.ModerationBlock.
                REQUEST_FAILED_SERVER_ERROR,
                Const.DataCollection.ParamNames.BLOCKED_USER:
                clientBlockUser,
                Const.DataCollection.ParamNames.BLOCKER_USER:
                Utils.ConvertBinaryToUUID(clientUser.uuid)
            })

        return HttpResponseFactory.MakeHttpResponse(
            Const.HttpResponseFactory.ResponseCodes.ServerError.
            CODE_INTERNAL_SERVER_ERROR, Const.DataCollection.MessageCodes.
            ModerationBlock.REQUEST_FAILED_SERVER_ERROR)
예제 #21
0
def TakeSecurityAction(securityProperties):

    # simply log the error
    DataCollector.logSecurityError(securityProperties)
예제 #22
0
def GetLocalPost(requestData):
    TAG = Const.Tags.Urls.GET_LOCAL
    
    securityProperties = RunThroughSecurityLayer(TAG, requestData)
    if (not securityProperties.isSecure):
        return securityProperties.httpResponse
    
    try:      
        clientUser = securityProperties.clientUserObject
        clientNumPostsRequested = securityProperties.jsonRequestData[Const.Views.GetLocalPost.JsonRequestKey.COUNT]
        clientSeenPosts = securityProperties.jsonRequestData[Const.Views.GetLocalPost.JsonRequestKey.SEEN]
        clientLatitude = securityProperties.jsonRequestData[Const.Views.GetLocalPost.JsonRequestKey.LATITUDE]
        clientLongitude = securityProperties.jsonRequestData[Const.Views.GetLocalPost.JsonRequestKey.LONGITUDE]
        
        localPosts = None
    
        # If the list images the client has seen is empty,
        # set the list to be non-empty with a dummy value of 0.
        # This prevents the query from breaking.
        if not clientSeenPosts:
            clientSeenPosts = [0]
        
        # Get a list of users that this user has blocked on local
        blockedUserList = _GetBlockedUsersList(clientUser)
                    
        # Run the local algo.
        localPosts = _RunLocalAlgorithm(clientID=clientUser.id, 
                                        latitude=clientLatitude, 
                                        longitude=clientLongitude, 
                                        numOfPostsRequested=clientNumPostsRequested, 
                                        postsToExclude=clientSeenPosts, 
                                        blockedUsers=blockedUserList)
        
        
        # Package the localPosts  
        # Iterate over the results set. Make 'LocalPostClientObject' out of each result
        # Add these objects to a list as a dictionary. Json stringify the whole list,
        # using simplejson.
        
        clientPostListToReturn = []
        for lp in localPosts:
            clientPostToReturn = _GetLocalPostClientObject(postID=lp.id, 
                                                          fromUser=str(ConvertBinaryToUUID(lp.fromUser_uuid)), 
                                                          timeCreated=lp.timeCreated, 
                                                          latitude=lp.latitude, 
                                                          longitude=lp.longitude, 
                                                          weight=lp.weight,
                                                          text=lp.text,
                                                          url=lp.url,
                                                          arn=lp.arn)
            clientPostListToReturn.append(clientPostToReturn.getOrderedDict())
                
        jsonString = json.dumps(clientPostListToReturn)
            
        # log and return on success   
        DataCollector.logURL(TAG, { 
            Const.DataCollection.ParamNames.RESPONSE_CODE: Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK,
            Const.DataCollection.ParamNames.MESSAGE_CODE: Const.DataCollection.MessageCodes.GetLocal.REQUEST_SUCCESSFUL,
            Const.DataCollection.ParamNames.FROM_USER: Utils.ConvertBinaryToUUID(clientUser.uuid),
            Const.DataCollection.ParamNames.LATITUDE: clientLatitude,
            Const.DataCollection.ParamNames.LONGITUDE: clientLongitude,
            Const.DataCollection.ParamNames.NUM_IMAGES_REQUESTED: clientNumPostsRequested,
            Const.DataCollection.ParamNames.NUM_IMAGES_SERVED: len(list(localPosts)) })  
                           
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.Success.CODE_OK, 
                                                    jsonString, 'application/json')
    
    except Exception as e:
        # log and return on error
        DataCollector.logServerError(e)
        DataCollector.logURL(TAG, { 
            Const.DataCollection.ParamNames.RESPONSE_CODE: Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR,
            Const.DataCollection.ParamNames.MESSAGE_CODE: Const.DataCollection.MessageCodes.GetLocal.REQUEST_FAILED_SERVER_ERROR,
            Const.DataCollection.ParamNames.FROM_USER: Utils.ConvertBinaryToUUID(clientUser.uuid),
            Const.DataCollection.ParamNames.LATITUDE: clientLatitude,
            Const.DataCollection.ParamNames.LONGITUDE: clientLongitude,
            Const.DataCollection.ParamNames.NUM_IMAGES_REQUESTED: clientNumPostsRequested,
            Const.DataCollection.ParamNames.NUM_IMAGES_SERVED: 0 })  
        
        return HttpResponseFactory.MakeHttpResponse(Const.HttpResponseFactory.ResponseCodes.ServerError.CODE_INTERNAL_SERVER_ERROR, 
                                                    Const.DataCollection.MessageCodes.GetLocal.REQUEST_FAILED_SERVER_ERROR)