def publish(self, message):
        if not self.backlog_length:
            raise Exception("Cannot publish to a RealtimeChannel without a backlog_length set.")

        id = self.msg_id.incr()
        self.msg_backlog.zadd(util.client_dumps(message), id)
        self.pubsub.publish(util.client_dumps({'id': id, 'payload': message}))
        self.msg_backlog.zremrangebyscore('-inf', id - self.backlog_length)
        if self.ttl:
            self.msg_id.expire(self.ttl)
            self.msg_backlog.expire(self.ttl)
Пример #2
0
    def publish(self, message):
        if not self.backlog_length:
            raise Exception(
                "Cannot publish to a RealtimeChannel without a backlog_length set."
            )

        id = self.msg_id.incr()
        self.msg_backlog.zadd(util.client_dumps(message), id)
        self.pubsub.publish(util.client_dumps({'id': id, 'payload': message}))
        self.msg_backlog.zremrangebyscore('-inf', id - self.backlog_length)
        if self.ttl:
            self.msg_id.expire(self.ttl)
            self.msg_backlog.expire(self.ttl)
Пример #3
0
def to_json(things):
    """ 
    If the model/object defines a "to_client" then call it first.
    This way objects can implement the "to_client" interface to return a dictionary
    representation of themselves to be serialized as json.
    """
    return util.js_safety(util.client_dumps(things))
def to_json(things):
    """ 
    If the model/object defines a "to_client" then call it first.
    This way objects can implement the "to_client" interface to return a dictionary
    representation of themselves to be serialized as json.
    """
    return util.js_safety(util.client_dumps(things))
Пример #5
0
def JSONPResponse(request, response, **kwargs):
    callback = request.GET.get('callback', 'callback')
    if not callback.replace('_', '').isalnum():
        raise ServiceError()
    return HttpResponse(
        '%s(%s);' % (callback, client_dumps(response, viewer=request.user)),
        mimetype='application/javascript',
        **kwargs)
Пример #6
0
def daily_sticker_activity_json(user):
    activity = None
    if user.kv.has_unseen_daily_free_stickers.get():
        user.kv.has_unseen_daily_free_stickers.delete()
        activity = DailyFreeStickersActivity({
            'reward_stickers': knobs.DAILY_FREE_STICKERS,
        }, actor=user)
        activity = activity_stream_item(activity, user)
    return util.js_safety(util.client_dumps(activity))
Пример #7
0
    def process_response(self, request, response):
        if response.status_code == 403 and request.META.get('HTTP_X_SESSIONID'):
            import traceback
            import sys
            stack = str(request.path_info) + '\n'

            #stack += request.body + '\n'

            if request.user.is_authenticated():
                stack += request.user.username + '\n'

            import time
            stack += str(time.time()) + '\n'

            import re
            regex_http_          = re.compile(r'^HTTP_.+$')
            regex_content_type   = re.compile(r'^CONTENT_TYPE$')
            regex_content_length = re.compile(r'^CONTENT_LENGTH$')

            request_headers = {}
            for header in request.META:
                if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header):
                    request_headers[header] = request.META[header]

            stack += '\n'.join('{}: {}'.format(k,v) for k,v in request_headers.items()) + '\n'

            import traceback
            tb = traceback.format_exc()
            stack += unicode(tb)

            stack += '\n'.join('{}: {}'.format(k,v) for k,v in request.COOKIES.items()) + '\n'
            stack += '\n' + unicode(response.content)

            stack += '\n'.join(traceback.format_exception(*sys.exc_info()))

            stk = traceback.extract_stack()
            for mod, lineno, fun_name, call_code_text in stk:
                stack += "[%s:%i] in %s" % (mod, lineno, fun_name)

            from django.core.mail import send_mail
            send_mail('403 stack trace', stack, '*****@*****.**',
                      ['*****@*****.**'], fail_silently=False)

            user_agent = request.META.get('HTTP_USER_AGENT')
            version = AppVersionMiddleware.get_version_from_user_agent(user_agent)
            if version is None or version in ['1.0.1', '1.0.2']:
                return response

            response = {'success': False, 'error_type': 'ServiceError', 'reason': 'Sorry! To fix your app, please sign-out and sign-in again: tap Profile, tap the gear icon in the top right, then tap Sign Out. Please contact us if you need more help: [email protected]'}

            #if 'activities' in request.META['PATH_INFO']:
            #    response = {'success': True, 'activities': []}
            #else:
            #    response = {'success': False, 'error_type': 'ServiceError', 'reason': 'Error code 403, please try again.'}
            return HttpResponse(util.client_dumps(response), mimetype='application/json')
        return response
Пример #8
0
def ServiceResponse(request, response, **kwargs):
    """
    Serializes the response to primarily JSON, but you can force it to produce YAML by sending a format=yaml request
    variable.
    """
    formatted_response = client_dumps(response)
    if request.POST.get("format") == "yaml":
        formatted_response = yaml.safe_dump(loads(formatted_response), default_flow_style=False)
    # Allows us to force a mimetype in a request arg.
    mimetype = request.POST.get("force_mimetype", 'application/json')
    return HttpResponse(formatted_response, mimetype, **kwargs)
def ServiceResponse(request, response, **kwargs):
    """
    Serializes the response to primarily JSON, but you can force it to produce YAML by sending a format=yaml request
    variable.
    """
    formatted_response = client_dumps(response, viewer=request.user)
    def get_yaml():
        return yaml.safe_dump(loads(formatted_response), default_flow_style=False)
    if request.POST.get('format') == 'yaml':
        formatted_response = get_yaml()
    elif request.POST.get('format') == 'html':
        return r2r_jinja('api_response.html', {'yaml': get_yaml()})
    # Allows us to force a mimetype in a request arg.
    mimetype = request.POST.get('force_mimetype', 'application/json')
    return HttpResponse(formatted_response, mimetype, **kwargs)
Пример #10
0
 def process_request(self, request):
     if request.user.is_authenticated():
         if 'sandbox' in request.user_kv:
             if request.META['PATH_INFO'].startswith('/api'):
                 # Deactivated users cannot access anything outside of the sandbox. 403 Forbidden any other
                 # request.
                 if not request.user.is_active:
                     return HttpResponseForbidden(util.client_dumps({'reason': 'deactivated'}))
                 # Otherwise fall though and serve API requests, user is just warned.
             elif not request.META['PATH_INFO'].startswith(request.user_kv['sandbox']):
                 # Request for a page outside of the sandbox, redirect to the sandbox.
                 return HttpResponseRedirect(request.user_kv['sandbox'])
         elif not request.user.is_active:
             # Deactivated user with no sandbox, log them out, boot them to /
             logout(request)
             return HttpResponseRedirect('/')
Пример #11
0
def ServiceResponse(request, response, **kwargs):
    """
    Serializes the response to primarily JSON, but you can force it to produce YAML by sending a format=yaml request
    variable.
    """
    formatted_response = client_dumps(response, viewer=request.user)

    def get_yaml():
        return yaml.safe_dump(loads(formatted_response),
                              default_flow_style=False)

    if request.POST.get('format') == 'yaml':
        formatted_response = get_yaml()
    elif request.POST.get('format') == 'html':
        return r2r_jinja('api_response.html', {'yaml': get_yaml()})
    # Allows us to force a mimetype in a request arg.
    mimetype = request.POST.get('force_mimetype', 'application/json')
    return HttpResponse(formatted_response, mimetype, **kwargs)
Пример #12
0
 def process_request(self, request):
     if request.user.is_authenticated():
         if 'sandbox' in request.user_kv:
             if request.META['PATH_INFO'].startswith('/api'):
                 # Deactivated users cannot access anything outside of the sandbox. 403 Forbidden any other
                 # request.
                 if not request.user.is_active:
                     return HttpResponseForbidden(
                         util.client_dumps({'reason': 'deactivated'}))
                 # Otherwise fall though and serve API requests, user is just warned.
             elif not request.META['PATH_INFO'].startswith(
                     request.user_kv['sandbox']):
                 # Request for a page outside of the sandbox, redirect to the sandbox.
                 return HttpResponseRedirect(request.user_kv['sandbox'])
         elif not request.user.is_active:
             # Deactivated user with no sandbox, log them out, boot them to /
             logout(request)
             return HttpResponseRedirect('/')
Пример #13
0
 def response_wrapper(ret):
     ret = loads(ret)
     ret['success'] = True
     ret = client_dumps(ret)
     return HttpResponse(ret, 'application/json')
Пример #14
0
 def test_client_dumps(self):
     self.assertEqual('{}', util.client_dumps({}))
Пример #15
0
 def test_sticker_details(self):
     util.client_dumps(stickers.all_details())
Пример #16
0
 def process_request(self, request):
     if (request.META['PATH_INFO'].startswith('/staff')
             and not (request.user.is_authenticated()
                      and request.user.is_staff)):
         return HttpResponseForbidden(util.client_dumps({'reason': 'staff_only'}))
def JSONPResponse(request, response, **kwargs):
    callback = request.GET.get('callback', 'callback')
    if not callback.replace('_', '').isalnum():
        raise ServiceError()
    return HttpResponse('%s(%s);' % (callback, client_dumps(response, viewer=request.user)), mimetype='application/javascript', **kwargs)
Пример #18
0
 def process_request(self, request):
     if request.META["PATH_INFO"].startswith("/staff") and not (
         request.user.is_authenticated() and request.user.is_staff
     ):
         return HttpResponseForbidden(util.client_dumps({"reason": "staff_only"}))
Пример #19
0
def to_escaped_json(things):
    return util.js_safety(util.client_dumps(things), django=False, escape_html=True)
Пример #20
0
 def test_sticker_details(self):
     util.client_dumps(stickers.all_details())
Пример #21
0
 def test_client_dumps(self):
     self.assertEqual('{}', util.client_dumps({}))
Пример #22
0
 def process_request(self, request):
     if (request.META['PATH_INFO'].startswith('/staff')
             and not (request.user.is_authenticated()
                      and request.user.is_staff)):
         return HttpResponseForbidden(
             util.client_dumps({'reason': 'staff_only'}))
Пример #23
0
 def response_wrapper(ret):
     ret = loads(ret)
     ret['success'] = True
     ret = client_dumps(ret)
     return HttpResponse(ret, 'application/json')
Пример #24
0
    def process_response(self, request, response):
        if response.status_code == 403 and request.META.get(
                'HTTP_X_SESSIONID'):
            import traceback
            import sys
            stack = str(request.path_info) + '\n'

            #stack += request.body + '\n'

            if request.user.is_authenticated():
                stack += request.user.username + '\n'

            import time
            stack += str(time.time()) + '\n'

            import re
            regex_http_ = re.compile(r'^HTTP_.+$')
            regex_content_type = re.compile(r'^CONTENT_TYPE$')
            regex_content_length = re.compile(r'^CONTENT_LENGTH$')

            request_headers = {}
            for header in request.META:
                if regex_http_.match(header) or regex_content_type.match(
                        header) or regex_content_length.match(header):
                    request_headers[header] = request.META[header]

            stack += '\n'.join('{}: {}'.format(k, v)
                               for k, v in request_headers.items()) + '\n'

            import traceback
            tb = traceback.format_exc()
            stack += unicode(tb)

            stack += '\n'.join('{}: {}'.format(k, v)
                               for k, v in request.COOKIES.items()) + '\n'
            stack += '\n' + unicode(response.content)

            stack += '\n'.join(traceback.format_exception(*sys.exc_info()))

            stk = traceback.extract_stack()
            for mod, lineno, fun_name, call_code_text in stk:
                stack += "[%s:%i] in %s" % (mod, lineno, fun_name)

            from django.core.mail import send_mail
            send_mail('403 stack trace',
                      stack,
                      '*****@*****.**', ['*****@*****.**'],
                      fail_silently=False)

            user_agent = request.META.get('HTTP_USER_AGENT')
            version = AppVersionMiddleware.get_version_from_user_agent(
                user_agent)
            if version is None or version in ['1.0.1', '1.0.2']:
                return response

            response = {
                'success':
                False,
                'error_type':
                'ServiceError',
                'reason':
                'Sorry! To fix your app, please sign-out and sign-in again: tap Profile, tap the gear icon in the top right, then tap Sign Out. Please contact us if you need more help: [email protected]'
            }

            #if 'activities' in request.META['PATH_INFO']:
            #    response = {'success': True, 'activities': []}
            #else:
            #    response = {'success': False, 'error_type': 'ServiceError', 'reason': 'Error code 403, please try again.'}
            return HttpResponse(util.client_dumps(response),
                                mimetype='application/json')
        return response