summaryrefslogtreecommitdiffstats
path: root/store/api.py
blob: 9bb8dc2baa2900fee2b5a4e2693d28bcb518286c (plain)
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
#############################################################################
##
## Copyright (C) 2016 Pelagicore AG
## Contact: https://www.qt.io/licensing/
##
## This file is part of the Neptune Deployment Server
##
## $QT_BEGIN_LICENSE:GPL-QTAS$
## Commercial License Usage
## Licensees holding valid commercial Qt Automotive Suite licenses may use
## this file in accordance with the commercial license agreement provided
## with the Software or, alternatively, in accordance with the terms
## contained in a written agreement between you and The Qt Company.  For
## licensing terms and conditions see https://www.qt.io/terms-conditions.
## For further information use the contact form at https://www.qt.io/contact-us.
##
## GNU General Public License Usage
## Alternatively, this file may be used under the terms of the GNU
## General Public License version 3 or (at your option) any later version
## approved by the KDE Free Qt Foundation. The licenses are as published by
## the Free Software Foundation and appearing in the file LICENSE.GPL3
## included in the packaging of this file. Please review the following
## information to ensure the GNU General Public License requirements will
## be met: https://www.gnu.org/licenses/gpl-3.0.html.
##
## $QT_END_LICENSE$
##
## SPDX-License-Identifier: GPL-3.0
##
#############################################################################

import os
import tempfile
import datetime
import shutil
import json

from django.conf import settings
from django.db.models import Q
from django.http import HttpResponse, HttpResponseForbidden, Http404, JsonResponse
from django.contrib import auth
from django.template import Context, loader

from models import App, Category, Vendor
from utilities import parsePackageMetadata, packagePath, iconPath, downloadPath, addSignatureToPackage, validateTag


def hello(request):
    status = 'ok'

    if settings.APPSTORE_MAINTENANCE:
        status = 'maintenance'
    elif request.REQUEST.get("platform", "") != str(settings.APPSTORE_PLATFORM_ID):
        status = 'incompatible-platform'
    elif request.REQUEST.get("version", "") != str(settings.APPSTORE_PLATFORM_VERSION):
        status = 'incompatible-version'

    for j in ("require_tag", "conflicts_tag",):
        if j in request.REQUEST: #Tags are coma-separated,
            taglist = [i.lower() for i in request.REQUEST[j].split(',') if i]
            for i in taglist:
                if not validateTag(i): #Tags must be alphanumeric (or, even better - limited to ASCII alphanumeric)
                    status = 'malformed-tag'
                    break
            request.session[j] = taglist
    return JsonResponse({'status': status})


def login(request):
    status = 'ok'

    try:
        try:
            username = request.REQUEST["username"]
            password = request.REQUEST["password"]
        except KeyError:
            raise Exception('missing-credentials')

        user = auth.authenticate(username = username, password = password)
        if user is None:
            raise Exception('authentication-failed')

        if not user.is_active:
            raise Exception('account-disabled')

        auth.login(request, user)

    except Exception as error:
        status = str(error)

    return JsonResponse({'status': status})


def logout(request):
    status = 'ok'

    if not request.user.is_authenticated():
        status = 'failed'
    logout(request)

    return JsonResponse({'status': status})


def appList(request):
    apps = App.objects.all()
    if 'filter' in request.REQUEST:
        apps = apps.filter(name__contains = request.REQUEST['filter'])
    if 'category_id' in request.REQUEST:
        catId = request.REQUEST['category_id']
        if catId != -1: # All metacategory
            apps = apps.filter(category__exact = catId)

    #Tag filtering
    #"require_tag", "conflicts_tag"
    # Tags are combined by logical AND (for require) and logical OR for conflicts
    if 'require_tag' in request.session:
        for i in request.session['require_tag']:
            regex = '(^|,)%s(,|$)' % (i,)
            apps = apps.filter(Q(tags__regex = regex))
    if 'conflicts_tag' in request.session:
        for i in request.session['conflicts_tag']:
            regex = '(^|,)%s(,|$)' % (i,)
            apps = apps.filter(~Q(tags__regex = regex))

    appList = list(apps.values('id', 'name', 'vendor__name', 'briefDescription', 'category', 'tags').order_by('id'))
    for app in appList:
        app['category_id'] = app['category']
        app['category'] = Category.objects.all().filter(id__exact = app['category_id'])[0].name
        app['vendor'] = app['vendor__name']
        if app['tags'] != "":
            app['tags'] = app['tags'].split(',')
        else:
            app['tags'] = []
        del app['vendor__name']

    # this is not valid JSON, since we are returning a list!
    return JsonResponse(appList, safe = False)


def appDescription(request):
    try:
        app = App.objects.get(id__exact = request.REQUEST['id'])
        return HttpResponse(app.description)
    except:
        raise Http404('no such application: %s' % request.REQUEST['id'])


def appIcon(request):
    try:
        app = App.objects.get(id__exact = request.REQUEST['id'])
        with open(iconPath(app.id), 'rb') as iconPng:
            response = HttpResponse(content_type = 'image/png')
            response.write(iconPng.read())
            return response
    except:
        raise Http404('no such application: %s' % request.REQUEST['id'])


def appPurchase(request):
    if not request.user.is_authenticated():
        return HttpResponseForbidden('no login')

    try:
        deviceId = str(request.REQUEST.get("device_id", ""))
        if settings.APPSTORE_BIND_TO_DEVICE_ID:
            if not deviceId:
                return JsonResponse({'status': 'failed', 'error': 'device_id required'})
        else:
            deviceId = ''

        app = App.objects.get(id__exact = request.REQUEST['id'])
        fromFilePath = packagePath(app.id)

        # we should not use obvious names here, but just hash the string.
        # this would be a nightmare to debug though and this is a development server :)
        toFile = str(app.id) + '_' + str(request.user.id) + '_' + str(deviceId) + '.appkg'
        toPath = downloadPath()
        if not os.path.exists(toPath):
            os.makedirs(toPath)

        if not settings.APPSTORE_NO_SECURITY:
            with open(fromFilePath, 'rb') as package:
                pkgdata = parsePackageMetadata(package)
                addSignatureToPackage(fromFilePath, toPath + toFile, pkgdata['rawDigest'], deviceId)
        else:
            shutil.copyfile(fromFilePath, toPath + toFile)

        return JsonResponse({'status': 'ok',
                             'url': request.build_absolute_uri('/app/download/' + toFile),
                             'expiresIn': int(settings.APPSTORE_DOWNLOAD_EXPIRY) * 60})

        # a cronjob runing "manage.py expiredownloads" every settings.APPSTORE_DOWNLOAD_EXPIRY/2
        # minutes will take care of removing these temporary download files.
    except Exception as error:
        return JsonResponse({ 'status': 'failed', 'error': str(error)})


def appDownload(request, path):
    try:
        response = HttpResponse(content_type = 'application/octetstream')
        with open(downloadPath() + path, 'rb') as pkg:
            response.write(pkg.read())
            response['Content-Length'] = pkg.tell()
        return response
    except:
        raise Http404


def categoryList(request):
    # this is not valid JSON, since we are returning a list!
    allmeta = [{'id': -1, 'name': 'All'}, ] #All metacategory
    categoryobject = Category.objects.all().order_by('rank').values('id', 'name')
    categoryobject=allmeta + list(categoryobject)
    return JsonResponse(categoryobject, safe = False)


def categoryIcon(request):
    response = HttpResponse(content_type = 'image/png')

    # there are no category icons (yet), so we just return the icon of the first app in this category
    try:
        app = App.objects.filter(category__exact = request.REQUEST['id']).order_by('-dateModified')[0] #FIXME - the category icon is unimplemented
        with open(iconPath(app.id), 'rb') as iconPng:
            response.write(iconPng.read())
    except:
        emptyPng = '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x01\x03\x00\x00\x00%\xdbV\xca\x00\x00\x00\x03PLTE\x00\x00\x00\xa7z=\xda\x00\x00\x00\x01tRNS\x00@\xe6\xd8f\x00\x00\x00\nIDAT\x08\xd7c`\x00\x00\x00\x02\x00\x01\xe2!\xbc3\x00\x00\x00\x00IEND\xaeB`\x82'
        response.write(emptyPng)

    return response