MobileBlur

Diff
Login

Differences From Artifact [bbbb0c1942]:

To Artifact [0c846c8b37]:


1
2
3
4
5
6
7
8
9

10
11
12
13
14
15
16
1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
16








-
+







"""
Extract client information from http user agent
The module does not try to detect all capabilities of browser in current form (it can easily be extended though).
Aim is
    * fast
    * very easy to extend
    * reliable enough for practical purposes
    * and assist python web apps to detect clients.
    

Taken from http://pypi.python.org/pypi/httpagentparser (MIT license)
Modified my Ross Peoples for web2py to better support iPhone and iPad.
"""
import sys
from storage import Storage

class DetectorsHub(dict):
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
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







+












+
+
+
+



+







-
+







    name = "" # "to perform match in DetectorsHub object"
    info_type = "override me"
    result_key = "override me"
    order = 10 # 0 is highest
    look_for = "string to look for"
    skip_if_found = [] # strings if present stop processin
    can_register = False
    is_mobile = False
    prefs = Storage() # dict(info_type = [name1, name2], ..)
    version_splitters = ["/", " "]
    _suggested_detectors = None

    def __init__(self):
        if not self.name:
            self.name = self.__class__.__name__
        self.can_register = (self.__class__.__dict__.get('can_register', True))

    def detect(self, agent, result):
        if agent and self.checkWords(agent):
            result[self.info_type] = Storage(name=self.name)
            result[self.info_type].is_mobile = self.is_mobile
            if not result.is_mobile:
                result.is_mobile = result[self.info_type].is_mobile
                
            version = self.getVersion(agent)
            if version:
                result[self.info_type].version = version
            
            return True
        return False

    def checkWords(self, agent):
        for w in self.skip_if_found:
            if w in agent:
                return False
        if self.look_for:
        if self.look_for in agent:
            return True
        return False

    def getVersion(self, agent):
        # -> version string /None
        vs = self.version_splitters
        return agent.split(self.look_for + vs[0])[-1].split(vs[1])[0].strip()
159
160
161
162
163
164
165
166

167
168
169
170
171

172
173
174
175
176
177
178
165
166
167
168
169
170
171

172
173
174
175
176

177
178
179
180
181
182
183
184







-
+




-
+







            return True

    def getVersion(self, agent):
        if "Version/" in agent:
            return agent.split('Version/')[-1].split(' ')[0].strip()
        else:
            # Mobile Safari
            return agent.split('Safari ')[-1].split(' ')[0].strip() 
            return agent.split('Safari ')[-1].split(' ')[0].strip()


class Linux(OS):
    look_for = 'Linux'
    prefs = Storage(browser=["Firefox"], 
    prefs = Storage(browser=["Firefox"],
                    dist=["Ubuntu", "Android"], flavor=None)

    def getVersion(self, agent):
        pass


class Macintosh(OS):
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
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







+







+









-
+


+







    prefs = Storage(browser=['Chrome'])
    def getVersion(self, agent):
        vs = self.version_splitters
        return agent.split(self.look_for+vs[0])[-1].split(vs[1])[1].strip()[:-1]

class Android(Dist):
    look_for = 'Android'
    is_mobile = True

    def getVersion(self, agent):
        return agent.split('Android')[-1].split(';')[0].strip()


class iPhone(Dist):
    look_for = 'iPhone'
    is_mobile = True

    def getVersion(self, agent):
        version_end_chars = ['like', ';', ')']
        part = agent.split('CPU OS')[-1].strip()
        for c in version_end_chars:
            if c in part:
                version = 'iOS ' + part.split(c)[0].strip()
                break
        return version.replace('_', '.')
        

class iPad(Dist):
    look_for = 'iPad'
    is_mobile = True

    def getVersion(self, agent):
        version_end_chars = ['like', ';', ')']
        part = agent.split('CPU OS')[-1].strip()
        for c in version_end_chars:
            if c in part:
                version = 'iOS ' + part.split(c)[0].strip()
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
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







-
+











+
+














-
+



-
+








-
-
-
+
+
+








+
-
+







            _d_prefs = prefs.get(info_type, [])
            detectors = detectorshub.reorderByPrefs(detectors, _d_prefs)
            if "detector" in locals():
                detector._suggested_detectors = detectors
        else:
            detectors = _suggested_detectors
        for detector in detectors:
            print "detector name: ", detector.name
            # print "detector name: ", detector.name
            if detector.detect(agent, result):
                prefs = detector.prefs
                _suggested_detectors = detector._suggested_detectors
                break
    return result


class Result(Storage):
    def __missing__(self, k):
        return ""

"""
THIS VERSION OF DETECT CAUSES IndexErrors.

def detect(agent):
    result = Result()
    _suggested_detectors = []
    for info_type in detectorshub:
        detectors = _suggested_detectors or detectorshub[info_type]
        for detector in detectors:
            if detector.detect(agent, result):
                if detector.prefs and not detector._suggested_detectors:
                    _suggested_detectors = detectorshub.reorderByPrefs(
                        detectors, detector.prefs.get(info_type))
                    detector._suggested_detectors = _suggested_detectors
                    break
    return result

"""

def simple_detect(agent):
    """
    -> (os, browser) # tuple of strings
    -> (os, browser, is_mobile) # tuple of strings
    """
    result = detect(agent)
    os_list = []
    if 'flavor' in result: os_list.append(result['flavor']['name'])
    if 'dist' in result: os_list.append(result['dist']['name'])
    if 'os' in result: os_list.append(result['os']['name'])

    os = os_list and " ".join(os_list) or "Unknown OS"
    os_version = os_list and (result['flavor'] and result['flavor'].get(
            'version')) or (result['dist'] and result['dist'].get('version')) \
            or (result['os'] and result['os'].get('version')) or ""
    os_version = os_list and ('flavor' in result and result['flavor'] and result['flavor'].get(
            'version')) or ('dist' in result and result['dist'] and result['dist'].get('version')) \
            or ('os' in result and result['os'] and result['os'].get('version')) or ""
    browser = 'browser' in result and result['browser']['name'] \
        or 'Unknown Browser'
    browser_version = 'browser' in result \
        and result['browser'].get('version') or ""
    if browser_version:
        browser = " ".join((browser, browser_version))
    if os_version:
        os = " ".join((os, os_version))
    #is_mobile = ('dist' in result and result.dist.is_mobile) or ('os' in result and result.os.is_mobile) or False
    return os, browser
    return os, browser, result.is_mobile


if __name__ == '__main__':
    import time
    import unittest

    data = (
361
362
363
364
365
366
367
368

369
370
371
372
373
374
375
373
374
375
376
377
378
379

380
381
382
383
384
385
386
387







-
+







        ("Opera/9.80 (X11; Linux i686; U; en) Presto/2.9.168 Version/11.50",
         ("Linux", "Opera 9.80"),
         {"os": {"name": "Linux"}, "browser": {"name": "Opera", "version": "9.80"}},),
        ("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20060127 Netscape/8.1",
         ("Windows NT 5.1", "Netscape 8.1"),
         {'os': {'name': 'Windows', 'version': 'NT 5.1'}, 'browser': {'name': 'Netscape', 'version': '8.1'}},),
        )
    

    class TestHAP(unittest.TestCase):
        def setUp(self):
            self.harass_repeat = 1000
            self.data = data

        def test_simple_detect(self):
            for agent, simple_res, res in data:
388
389
390
391
392
393
394














400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420







+
+
+
+
+
+
+
+
+
+
+
+
+
+
            print "\nTime taken for %s detecttions: %s" \
                % (no_of_tests, time_taken)
            print "Time taken for single detecttion: ", \
                time_taken / (len(self.data) * self.harass_repeat)

    unittest.main()


class mobilize(object): 

    def __init__(self, func): 
        self.func = func 

    def __call__(self):
        from gluon import current 
        user_agent = current.request.user_agent()
        if user_agent.is_mobile: 
            items = current.response.view.split('.')
            items.insert(-1,'mobile')
            current.response.view = '.'.join(items)
        return self.func()