import re from django.http import HttpResponse, HttpResponseForbidden from django.conf import settings from django.core import urlresolvers from flashticle.remoting import to_remoting, from_remoting from flashticle.util import StringIO class AMFMiddleware(object): CONTENT_TYPE = 'application/x-amf' def __init__(self): self.gateway_path = getattr(settings, 'GATEWAY_PATH', '/gateway/') self.path_matcher = re.compile(r'^%s.+' % self.gateway_path) def process_request(self, request): if self.path_matcher.match(request.path): return HttpResponseForbidden() elif request.method == "POST" and request.path == self.gateway_path and request.META.get('CONTENT_TYPE') == AMFMiddleware.CONTENT_TYPE: request_message = from_remoting(StringIO(request.raw_post_data)) headers, body = self.processAMF(request, request_message) io = StringIO() to_remoting(headers, body, io) response = HttpResponse(io.getvalue(), AMFMiddleware.CONTENT_TYPE) response['Content-Length'] = str(io.tell()) return response def processAMF(self, request, request_message): headers = request_message.raw_headers if not 'DescribeService' in request_message.headers: body = [self.processBody(request, *elem) for elem in request_message.raw_body] print headers print body return headers, body def processBody(self, request, target, response, params): targetPath = target.encode('utf8').replace('.', '/') path = request.path.rsplit('/', 1)[0] + '/' + targetPath callback, _, _ = urlresolvers.resolve(path) result = callback(request, *params) response += '/onResult' return response, 'null', result