UsageStatsView.dispatch()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
1
# coding: utf8
2
3
"""
4
This software is licensed under the Apache 2 license, quoted below.
5
6
Copyright 2014 Crystalnix Limited
7
8
Licensed under the Apache License, Version 2.0 (the "License"); you may not
9
use this file except in compliance with the License. You may obtain a copy of
10
the License at
11
12
    http://www.apache.org/licenses/LICENSE-2.0
13
14
Unless required by applicable law or agreed to in writing, software
15
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17
License for the specific language governing permissions and limitations under
18
the License.
19
"""
20
21
import logging
22
23
from django.views.generic import View
24
from django.views.decorators.csrf import csrf_exempt
25
from django.http import HttpResponse, JsonResponse
26
from django.conf import settings
27
28
from django_select2.views import AutoResponseView
29
from lxml.etree import XMLSyntaxError
30
from raven import Client
31
32
from omaha.builder import build_response
33
from omaha_server.utils import get_client_ip
34
from omaha.models import Request
35
36
logger = logging.getLogger(__name__)
37
client = Client(getattr(settings, 'RAVEN_DSN_STACKTRACE', None), name=getattr(settings, 'HOST_NAME', None),
38
                release=getattr(settings, 'APP_VERSION', None))
39
40
41
class UpdateView(View):
42
    http_method_names = ['post']
43
44
    @csrf_exempt
45
    def dispatch(self, *args, **kwargs):
46
        return super(UpdateView, self).dispatch(*args, **kwargs)
47
48
    def post(self, request):
49
        try:
50
            response = build_response(request.body, ip=get_client_ip(request))
51
        except XMLSyntaxError:
52
            logger.error('UpdateView', exc_info=True, extra=dict(request=request))
53
            msg = b"""<?xml version="1.0" encoding="utf-8"?>
54
<data>
55
    <message>
56
        Bad Request
57
    </message>
58
</data>"""
59
            return HttpResponse(msg, status=400, content_type="text/html; charset=utf-8")
60
        return HttpResponse(response, content_type="text/xml; charset=utf-8")
61
62
63
class FilterByUserIDResponseView(AutoResponseView):
64
    max_results = 10
65
66
    def get(self, request, *args, **kwargs):
67
        term = request.GET.get('term', '')
68
        app = request.GET.get('app_id', '')
69
70
        if not term.startswith('{'):
71
            term = '{' + term
72
        term = term.upper()
73
74
        requests = Request.objects.filter(apprequest__appid=app, userid__startswith=term)
75
        requests = requests.distinct('userid').values_list('userid', flat=True)[:self.max_results]
76
        return JsonResponse({
77
            'results': [
78
                {
79
                    'text': userid,
80
                    'id': userid,
81
                }
82
                for userid in requests
83
                ],
84
            'more': False
85
        })
86
87
88
class UsageStatsView(View):
89
    http_method_names = ['post', 'get']
90
91
    @csrf_exempt
92
    def dispatch(self, *args, **kwargs):
93
        return super(UsageStatsView, self).dispatch(*args, **kwargs)
94
95
    def post(self, request):
96
        client.captureMessage('Omaha Clients Usage Statistics: {0}'.format(request.body), tags=request.GET,
97
                              data={'level': 20, 'logger': 'usagestats'})
98
        return HttpResponse('ok')
99