This file is indexed.

/usr/lib/python2.7/dist-packages/djextdirect/provider.py is in python-django-extdirect 0.10-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# -*- coding: utf-8 -*-
# kate: space-indent on; indent-width 4; replace-tabs on;

"""
 *  Copyright (C) 2010, Michael "Svedrin" Ziegler <diese-addy@funzt-halt.net>
 *
 *  djExtDirect is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This package is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
"""

import json
import inspect
import functools
import traceback
from sys import stderr

from django.http import HttpResponse
from django.conf import settings
from django.conf.urls import patterns
from django.core.urlresolvers  import reverse
from django.utils.datastructures import MultiValueDictKeyError
from django.core.serializers.json import DjangoJSONEncoder


def getname( cls_or_name ):
    """ If cls_or_name is not a string, return its __name__. """
    if type(cls_or_name) not in ( str, unicode ):
        return cls_or_name.__name__
    return cls_or_name


class Provider( object ):
    """ Provider for Ext.Direct. This class handles building API information and
        routing requests to the appropriate functions, and serializing their
        response and exceptions - if any.

        Instantiation:

        >>> EXT_JS_PROVIDER = Provider( [name="Ext.app.REMOTING_API", autoadd=True] )

        If autoadd is True, the api.js will include a line like such::

            Ext.Direct.addProvider( Ext.app.REMOTING_API );

        After instantiating the Provider, register functions to it like so:

        >>> @EXT_JS_PROVIDER.register_method("myclass")
        ... def myview( request, possibly, some, other, arguments ):
        ...    " does something with all those args and returns something "
        ...    return 13.37

        Note that those views **MUST NOT** return an HttpResponse but simply
        the plain result, as the Provider will build a response from whatever
        your view returns!

        To be able to access the Provider, include its URLs in an arbitrary
        URL pattern, like so:

        >>> from views import EXT_JS_PROVIDER # import our provider instance
        >>> urlpatterns = patterns(
        ...     # other patterns go here
        ...     ( r'api/', include(EXT_DIRECT_PROVIDER.urls) ),
        ... )

        This way, the Provider will define the URLs "api/api.js" and "api/router".

        If you then access the "api/api.js" URL, you will get a response such as::

            Ext.app.REMOTING_API = { # Ext.app.REMOTING_API is from Provider.name
                "url": "/mumble/api/router",
                "type": "remoting",
                "actions": {"myclass": [{"name": "myview", "len": 4}]}
                }

        You can then use this code in ExtJS to define the Provider there.
    """

    def __init__( self, name="Ext.app.REMOTING_API", autoadd=True ):
        self.name     = name
        self.autoadd  = autoadd
        self.classes  = {}

    def register_method( self, cls_or_name, flags=None ):
        """ Return a function that takes a method as an argument and adds that
            to cls_or_name.

            The flags parameter is for additional information, e.g. formHandler=True.

            Note: This decorator does not replace the method by a new function,
            it returns the original function as-is.
        """
        return functools.partial( self._register_method, cls_or_name, flags=flags )

    def _register_method( self, cls_or_name, method, flags=None ):
        """ Actually registers the given function as a method of cls_or_name. """
        clsname = getname(cls_or_name)
        if clsname not in self.classes:
            self.classes[clsname] = {}
        if flags is None:
            flags = {}
        self.classes[ clsname ][ method.__name__ ] = method
        method.EXT_argnames = inspect.getargspec( method )[0][1:]
        method.EXT_len      = len( method.EXT_argnames )
        method.EXT_flags    = flags
        return method

    def build_api_dict( self ):
        actdict = {}
        for clsname in self.classes:
            actdict[clsname] = []
            for methodname in self.classes[clsname]:
                methinfo = {
                    "name": methodname,
                    "len":  self.classes[clsname][methodname].EXT_len
                    }
                methinfo.update( self.classes[clsname][methodname].EXT_flags )
                actdict[clsname].append( methinfo )

        return actdict

    def get_api_plain( self, request ):
        """ Introspect the methods and get a JSON description of only the API. """
        return HttpResponse( json.dumps({
            "url":     reverse( self.request ),
            "type":    "remoting",
            "actions": self.build_api_dict()
            }, cls=DjangoJSONEncoder), content_type="application/json" )

    def get_api( self, request ):
        """ Introspect the methods and get a javascript description of the API
            that is meant to be embedded directly into the web site.
        """
        request.META["CSRF_COOKIE_USED"] = True
        lines = ["%s = %s;" % ( self.name, json.dumps({
            "url":     reverse( self.request ),
            "type":    "remoting",
            "actions": self.build_api_dict()
            }, cls=DjangoJSONEncoder))]

        if self.autoadd:
            lines.append(
                """Ext.Ajax.on("beforerequest", function(conn, options){"""
                """    if( !options.headers )"""
                """        options.headers = {};"""
                """    options.headers["X-CSRFToken"] = Ext.util.Cookies.get("csrftoken");"""
                """});"""
                )
            lines.append( "Ext.Direct.addProvider( %s );" % self.name )

        return HttpResponse( "\n".join( lines ), content_type="text/javascript" )

    def request( self, request ):
        """ Implements the Router part of the Ext.Direct specification.

            It handles decoding requests, calling the appropriate function (if
            found) and encoding the response / exceptions.
        """
        request.META["CSRF_COOKIE_USED"] = True
        # First try to use request.POST, if that doesn't work check for req.body.
        # The other way round this might make more sense because the case that uses
        # body is way more common, but accessing request.POST after body
        # causes issues with Django's test client while accessing body after
        # request.POST does not.
        try:
            jsoninfo = {
                'action':  request.POST['extAction'],
                'method':  request.POST['extMethod'],
                'type':    request.POST['extType'],
                'upload':  request.POST['extUpload'],
                'tid':     request.POST['extTID'],
            }
        except (MultiValueDictKeyError, KeyError), err:
            try:
                rawjson = json.loads( request.body )
            except getattr( json, "JSONDecodeError", ValueError ):
                return HttpResponse( json.dumps({
                    'type':    'exception',
                    'message': 'malformed request',
                    'where':   err.message,
                    "tid":     None, # dunno
                    }, cls=DjangoJSONEncoder), content_type="application/json" )
            else:
                return self.process_normal_request( request, rawjson )
        else:
            return self.process_form_request( request, jsoninfo )

    def process_normal_request( self, request, rawjson ):
        """ Process standard requests (no form submission or file uploads). """
        if not isinstance( rawjson, list ):
            rawjson = [rawjson]

        responses = []

        for reqinfo in rawjson:
            cls, methname, data, rtype, tid = (reqinfo['action'],
                reqinfo['method'],
                reqinfo['data'],
                reqinfo['type'],
                reqinfo['tid'])

            if cls not in self.classes:
                responses.append({
                    'type':    'exception',
                    'message': 'no such action',
                    'where':   cls,
                    "tid":     tid,
                    })
                continue

            if methname not in self.classes[cls]:
                responses.append({
                    'type':    'exception',
                    'message': 'no such method',
                    'where':   methname,
                    "tid":     tid,
                    })
                continue

            func = self.classes[cls][methname]

            if func.EXT_len and len(data) == 1 and type(data[0]) == dict:
                # data[0] seems to contain a dict with params. check if it does, and if so, unpack
                args = []
                for argname in func.EXT_argnames:
                    if argname in data[0]:
                        args.append( data[0][argname] )
                    else:
                        args = None
                        break
                if args:
                    data = args

            if data is not None:
                datalen = len(data)
            else:
                datalen = 0

            if datalen != len(func.EXT_argnames):
                responses.append({
                    'type': 'exception',
                    'tid':  tid,
                    'message': 'invalid arguments',
                    'where': 'Expected %d, got %d' % ( len(func.EXT_argnames), len(data) )
                    })
                continue

            try:
                if data:
                    result = func( request, *data )
                else:
                    result = func( request )

            except Exception, err:
                errinfo = {
                    'type': 'exception',
                    "tid":  tid,
                    }
                if settings.DEBUG:
                    traceback.print_exc( file=stderr )
                    errinfo['message'] = err.message
                    errinfo['where']   = traceback.format_exc()
                else:
                    errinfo['message'] = 'The socket packet pocket has an error to report.'
                    errinfo['where']   = ''
                responses.append(errinfo)

            else:
                responses.append({
                    "type":   rtype,
                    "tid":    tid,
                    "action": cls,
                    "method": methname,
                    "result": result
                    })

        if len(responses) == 1:
            return HttpResponse( json.dumps( responses[0], cls=DjangoJSONEncoder ), content_type="application/json" )
        else:
            return HttpResponse( json.dumps( responses, cls=DjangoJSONEncoder ),    content_type="application/json" )

    def process_form_request( self, request, reqinfo ):
        """ Router for POST requests that submit form data and/or file uploads. """
        cls, methname, rtype, tid = (reqinfo['action'],
            reqinfo['method'],
            reqinfo['type'],
            reqinfo['tid'])

        if cls not in self.classes:
            response = {
                'type':    'exception',
                'message': 'no such action',
                'where':   cls,
                "tid":     tid,
                }

        elif methname not in self.classes[cls]:
            response = {
                'type':    'exception',
                'message': 'no such method',
                'where':   methname,
                "tid":     tid,
                }

        else:
            func = self.classes[cls][methname]
            try:
                result = func( request )

            except Exception, err:
                errinfo = {
                    'type': 'exception',
                    "tid":  tid,
                    }
                if settings.DEBUG:
                    traceback.print_exc( file=stderr )
                    errinfo['message'] = err.message
                    errinfo['where']   = traceback.format_exc()
                else:
                    errinfo['message'] = 'The socket packet pocket has an error to report.'
                    errinfo['where']   = ''
                response = errinfo

            else:
                response = {
                    "type":   rtype,
                    "tid":    tid,
                    "action": cls,
                    "method": methname,
                    "result": result
                    }

        if reqinfo['upload'] == "true":
            return HttpResponse(
                "<html><body><textarea>%s</textarea></body></html>" % json.dumps(response, cls=DjangoJSONEncoder),
                content_type="application/json"
                )
        else:
            return HttpResponse( json.dumps( response, cls=DjangoJSONEncoder ), content_type="application/json" )

    def get_urls(self):
        """ Return the URL patterns. """
        pat =  patterns('',
            (r'api.json$', self.get_api_plain ),
            (r'api.js$',   self.get_api ),
            (r'router/?',  self.request ),
            )
        return pat

    urls = property(get_urls)