This repository has been archived by the owner on Mar 15, 2018. It is now read-only.
/
models.py
1501 lines (1257 loc) · 55.2 KB
/
models.py
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import datetime
import json
import os
import time
import urlparse
import uuid
from operator import attrgetter
from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.storage import default_storage as storage
from django.core.urlresolvers import NoReverseMatch
from django.db import models
from django.db.models import signals as dbsignals
from django.dispatch import receiver
from django.utils.http import urlquote
import commonware.log
import waffle
from elasticutils.contrib.django import F, Indexable, MappingType
from tower import ugettext as _
import amo
import amo.models
from access.acl import action_allowed, check_reviewer
from addons import query
from addons.models import (Addon, AddonDeviceType, attach_categories,
attach_devices, attach_prices, attach_translations,
Category,
update_search_index as amo_update_search_index)
from addons.signals import version_changed
from amo.decorators import skip_cache
from amo.helpers import absolutify
from amo.search import TempS
from amo.storage_utils import copy_stored_file
from amo.urlresolvers import reverse
from amo.utils import JSONEncoder, memoize, memoize_key, smart_path
from constants.applications import DEVICE_TYPES
from files.models import File, nfd_str, Platform
from files.utils import parse_addon, WebAppParser
from lib.crypto import packaged
from market.models import AddonPremium
from stats.models import ClientData
from translations.fields import save_signal
from versions.models import Version
import mkt
from mkt.constants import APP_FEATURES, APP_IMAGE_SIZES, apps
from mkt.search.utils import S
from mkt.webapps.utils import get_locale_properties, get_supported_locales
from mkt.zadmin.models import FeaturedApp
log = commonware.log.getLogger('z.addons')
class WebappManager(amo.models.ManagerBase):
def __init__(self, include_deleted=False):
amo.models.ManagerBase.__init__(self)
self.include_deleted = include_deleted
def get_query_set(self):
qs = super(WebappManager, self).get_query_set()
qs = qs._clone(klass=query.IndexQuerySet).filter(
type=amo.ADDON_WEBAPP)
if not self.include_deleted:
qs = qs.exclude(status=amo.STATUS_DELETED)
return qs.transform(Webapp.transformer)
def valid(self):
return self.filter(status__in=amo.LISTED_STATUSES,
disabled_by_user=False)
def reviewed(self):
return self.filter(status__in=amo.REVIEWED_STATUSES)
def visible(self):
return self.filter(status=amo.STATUS_PUBLIC, disabled_by_user=False)
def top_free(self, listed=True):
qs = self.visible() if listed else self
return (qs.filter(premium_type__in=amo.ADDON_FREES)
.order_by('-weekly_downloads')
.with_index(addons='downloads_type_idx'))
def top_paid(self, listed=True):
qs = self.visible() if listed else self
return (qs.filter(premium_type__in=amo.ADDON_PREMIUMS)
.order_by('-weekly_downloads')
.with_index(addons='downloads_type_idx'))
@skip_cache
def pending(self):
# - Holding
# ** Approved -- PUBLIC
# ** Unapproved -- PENDING
# - Open
# ** Reviewed -- PUBLIC
# ** Unreviewed -- LITE
# ** Rejected -- REJECTED
return self.filter(status=amo.WEBAPPS_UNREVIEWED_STATUS)
def by_identifier(self, identifier):
"""
Look up a single app by its `id` or `app_slug`.
If the identifier is coercable into an integer, we first check for an
ID match, falling back to a slug check (probably not necessary, as
there is validation preventing numeric slugs). Otherwise, we only look
for a slug match.
"""
try:
return self.get(id=identifier)
except (ObjectDoesNotExist, ValueError):
return self.get(app_slug=identifier)
# We use super(Addon, self) on purpose to override expectations in Addon that
# are not true for Webapp. Webapp is just inheriting so it can share the db
# table.
class Webapp(Addon):
objects = WebappManager()
with_deleted = WebappManager(include_deleted=True)
class Meta:
proxy = True
def save(self, **kw):
# Make sure we have the right type.
self.type = amo.ADDON_WEBAPP
self.clean_slug(slug_field='app_slug')
self.assign_uuid()
creating = not self.id
super(Addon, self).save(**kw)
if creating:
# Set the slug once we have an id to keep things in order.
self.update(slug='app-%s' % self.id)
@staticmethod
def transformer(apps):
# I think we can do less than the Addon transformer, so at some point
# we'll want to copy that over.
apps_dict = Addon.transformer(apps)
if not apps_dict:
return
for adt in AddonDeviceType.objects.filter(addon__in=apps_dict):
if not getattr(apps_dict[adt.addon_id], '_device_types', None):
apps_dict[adt.addon_id]._device_types = []
apps_dict[adt.addon_id]._device_types.append(
DEVICE_TYPES[adt.device_type])
@staticmethod
def version_and_file_transformer(apps):
"""Attach all the versions and files to the apps."""
if not apps:
return []
ids = set(app.id for app in apps)
versions = (Version.uncached.filter(addon__in=ids)
.select_related('addon'))
vids = [v.id for v in versions]
files = (File.uncached.filter(version__in=vids)
.select_related('version'))
# Attach the files to the versions.
f_dict = dict((k, list(vs)) for k, vs in
amo.utils.sorted_groupby(files, 'version_id'))
for version in versions:
version.all_files = f_dict.get(version.id, [])
# Attach the versions to the apps.
v_dict = dict((k, list(vs)) for k, vs in
amo.utils.sorted_groupby(versions, 'addon_id'))
for app in apps:
app.all_versions = v_dict.get(app.id, [])
return apps
@staticmethod
def indexing_transformer(apps):
"""Attach everything we need to index apps."""
transforms = (attach_categories, attach_devices, attach_prices,
attach_translations)
for t in transforms:
qs = apps.transform(t)
return qs
def get_api_url(self, action=None, api=None, resource=None, pk=False):
"""Reverse a URL for the API."""
kwargs = {'api_name': api or 'apps',
'resource_name': resource or 'app'}
if pk:
kwargs['pk'] = self.pk
else:
kwargs['app_slug'] = self.app_slug
return reverse('api_dispatch_%s' % (action or 'detail'), kwargs=kwargs)
def get_url_path(self, more=False, add_prefix=True):
# We won't have to do this when Marketplace absorbs all apps views,
# but for now pretend you didn't see this.
try:
return reverse('detail', args=[self.app_slug],
add_prefix=add_prefix)
except NoReverseMatch:
# Fall back to old details page until the views get ported.
return super(Webapp, self).get_url_path(more=more,
add_prefix=add_prefix)
def get_detail_url(self, action=None):
"""Reverse URLs for 'detail', 'details.record', etc."""
return reverse(('detail.%s' % action) if action else 'detail',
args=[self.app_slug])
def get_purchase_url(self, action=None, args=None):
"""Reverse URLs for 'purchase', 'purchase.done', etc."""
return reverse(('purchase.%s' % action) if action else 'purchase',
args=[self.app_slug] + (args or []))
def get_dev_url(self, action='edit', args=None, prefix_only=False):
# Either link to the "new" Marketplace Developer Hub or the old one.
args = args or []
prefix = ('mkt.developers' if getattr(settings, 'MARKETPLACE', False)
else 'devhub')
view_name = ('%s.%s' if prefix_only else '%s.apps.%s')
return reverse(view_name % (prefix, action),
args=[self.app_slug] + args)
def get_ratings_url(self, action='list', args=None, add_prefix=True):
"""Reverse URLs for 'ratings.list', 'ratings.add', etc."""
return reverse(('ratings.%s' % action),
args=[self.app_slug] + (args or []),
add_prefix=add_prefix)
def get_stats_url(self, action='overview', inapp='', args=None):
"""Reverse URLs for 'stats', 'stats.overview', etc."""
# Simplifies the templates to not have to choose whether to call
# get_stats_url or get_stats_inapp_url.
if inapp:
stats_url = self.get_stats_inapp_url(action=action,
inapp=inapp, args=args)
return stats_url
if action.endswith('_inapp'):
action = action.replace('_inapp', '')
return reverse(('mkt.stats.%s' % action),
args=[self.app_slug] + (args or []))
def get_stats_inapp_url(self, action='revenue', inapp='', args=None):
"""
Inapp reverse URLs for stats.
"""
if not action.endswith('_inapp'):
action += '_inapp'
try:
url = reverse(('mkt.stats.%s' % action),
args=[self.app_slug, urlquote(inapp)])
except NoReverseMatch:
url = reverse(('mkt.stats.%s' % 'revenue_inapp'),
args=[self.app_slug, urlquote(inapp)])
return url
def get_image_asset_url(self, slug, default=64):
"""
Returns the URL for an app's image asset that uses the slug specified
by `slug`.
"""
if not any(slug == x['slug'] for x in APP_IMAGE_SIZES):
raise Exception(
"Requesting image asset for size that doesn't exist.")
try:
return ImageAsset.objects.get(addon=self, slug=slug).image_url
except ImageAsset.DoesNotExist:
return settings.MEDIA_URL + 'img/hub/default-%s.png' % str(default)
def get_image_asset_hue(self, slug):
"""
Returns the URL for an app's image asset that uses the slug specified
by `slug`.
"""
if not any(slug == x['slug'] for x in APP_IMAGE_SIZES):
raise Exception(
"Requesting image asset for size that doesn't exist.")
try:
return ImageAsset.objects.get(addon=self, slug=slug).hue
except ImageAsset.DoesNotExist:
return 0
@staticmethod
def domain_from_url(url):
if not url:
raise ValueError('URL was empty')
pieces = urlparse.urlparse(url)
return '%s://%s' % (pieces.scheme, pieces.netloc.lower())
@property
def parsed_app_domain(self):
if self.is_packaged:
raise ValueError('Packaged apps do not have a domain')
return urlparse.urlparse(self.app_domain)
@property
def device_types(self):
# If the transformer attached something, use it.
if hasattr(self, '_device_types'):
return self._device_types
return [DEVICE_TYPES[d.device_type] for d in
self.addondevicetype_set.order_by('device_type')]
@property
def origin(self):
if self.is_packaged:
return self.app_domain
parsed = urlparse.urlparse(self.get_manifest_url())
return '%s://%s' % (parsed.scheme, parsed.netloc)
def get_manifest_url(self, reviewer=False):
"""
Hosted apps: a URI to an external manifest.
Packaged apps: a URI to a mini manifest on m.m.o. If reviewer, the
mini-manifest behind reviewer auth pointing to the reviewer-signed
package.
"""
if self.is_packaged:
if reviewer:
# Get latest version and return reviewer manifest URL.
version = self.versions.latest()
return absolutify(reverse('reviewers.mini_manifest',
args=[self.id, version.id]))
elif self.current_version:
return absolutify(reverse('detail.manifest', args=[self.guid]))
else:
return '' # No valid version.
else:
return self.manifest_url
def has_icon_in_manifest(self):
data = self.get_manifest_json()
return 'icons' in data
def get_manifest_json(self, file_obj=None):
file_ = file_obj or self.get_latest_file()
if not file_:
return
if self.status == amo.STATUS_REJECTED:
file_path = file_.guarded_file_path
else:
file_path = file_.file_path
return WebAppParser().get_json_data(file_path)
def share_url(self):
return reverse('apps.share', args=[self.app_slug])
def manifest_updated(self, manifest, upload):
"""The manifest has updated, update the version and file.
This is intended to be used for hosted apps only, which have only a
single version and a single file.
"""
data = parse_addon(upload, self)
version = self.versions.latest()
max_ = Version._meta.get_field_by_name('_developer_name')[0].max_length
version.update(version=data['version'],
_developer_name=data['developer_name'][:max_])
path = smart_path(nfd_str(upload.path))
file = version.files.latest()
file.filename = file.generate_filename(extension='.webapp')
file.size = storage.size(path)
file.hash = file.generate_hash(path)
log.info('Updated file hash to %s' % file.hash)
file.save()
# Move the uploaded file from the temp location.
copy_stored_file(path, os.path.join(version.path_prefix,
nfd_str(file.filename)))
log.info('[Webapp:%s] Copied updated manifest to %s' % (
self, version.path_prefix))
amo.log(amo.LOG.MANIFEST_UPDATED, self)
def is_complete(self):
"""See if the app is complete. If not, return why. This function does
not consider or include payments-related information.
"""
reasons = []
if not self.support_email:
reasons.append(_('You must provide a support email.'))
if not self.name:
reasons.append(_('You must provide an app name.'))
if not self.device_types:
reasons.append(_('You must provide at least one device type.'))
if not self.categories.count():
reasons.append(_('You must provide at least one category.'))
if not self.previews.count():
reasons.append(_('You must upload at least one screenshot or '
'video.'))
return not bool(reasons), reasons
def mark_done(self):
"""When the submission process is done, update status accordingly."""
self.update(status=amo.WEBAPPS_UNREVIEWED_STATUS)
def update_status(self, using=None):
if (self.is_deleted or self.is_disabled or
self.status == amo.STATUS_BLOCKED):
return
def _log(reason, old=self.status):
log.info(u'Update app status [%s]: %s => %s (%s).' % (
self.id, old, self.status, reason))
amo.log(amo.LOG.CHANGE_STATUS, self.get_status_display(), self)
# Handle the case of no versions.
if not self.versions.exists():
self.update(status=amo.STATUS_NULL)
_log('no versions')
return
# Handle the case of versions with no files.
if not self.versions.filter(files__isnull=False).exists():
self.update(status=amo.STATUS_NULL)
_log('no versions with files')
return
# If there are no public versions and at least one pending, set status
# to pending.
has_public = (
self.versions.filter(files__status=amo.STATUS_PUBLIC).exists())
has_pending = (
self.versions.filter(files__status=amo.STATUS_PENDING).exists())
if not has_public and has_pending:
self.update(status=amo.STATUS_PENDING)
_log('has pending but no public files')
return
def authors_other_addons(self, app=None):
"""Return other apps by the same author."""
return (self.__class__.objects.visible()
.filter(type=amo.ADDON_WEBAPP)
.exclude(id=self.id).distinct()
.filter(addonuser__listed=True,
authors__in=self.listed_authors))
def can_purchase(self):
return self.is_premium() and self.premium and self.is_public()
def is_purchased(self, user):
return user and self.id in user.purchase_ids()
def is_pending(self):
return self.status == amo.STATUS_PENDING
def is_visible(self, request):
"""Returns whether the app has a visible search result listing. Its
detail page will always be there.
This does not consider whether an app is excluded in the current region
by the developer.
"""
region = getattr(request, 'REGION', mkt.regions.WORLDWIDE)
# See if it's a game without a content rating.
if (region == mkt.regions.BR and self.listed_in(category='games') and
not self.content_ratings_in(mkt.regions.BR, 'games')):
unrated_brazil_game = True
else:
unrated_brazil_game = False
# Let developers see it always.
can_see = (self.has_author(request.amo_user) or
action_allowed(request, 'Apps', 'Edit'))
# Let app reviewers see it only when it's pending.
if check_reviewer(request, only='app') and self.is_pending():
can_see = True
visible = False
if can_see:
# Developers and reviewers should see it always.
visible = True
elif self.is_public() and not unrated_brazil_game:
# Everyone else can see it only if it's public -
# and if it's a game, it must have a content rating.
visible = True
return visible
def has_premium(self):
"""If the app is premium status and has a premium object."""
return bool(self.is_premium() and self.premium)
def get_price(self, carrier=None, region=None, provider=None):
"""
A shortcut to get the price as decimal. Returns None if their is no
price for the app.
:param optional carrier: an int for the carrier.
:param optional region: an int for the region. Defaults to worldwide.
:param optional provider: an int for the provider. Defaults to bango.
"""
if self.has_premium() and self.premium.price:
return self.premium.price.get_price(carrier=carrier,
region=region, provider=provider)
def get_price_locale(self, carrier=None, region=None, provider=None):
"""
A shortcut to get the localised price with currency. Returns None if
their is no price for the app.
:param optional carrier: an int for the carrier.
:param optional region: an int for the region. Defaults to worldwide.
:param optional provider: an int for the provider. Defaults to bango.
"""
if self.has_premium() and self.premium.price:
return self.premium.price.get_price_locale(carrier=carrier,
region=region, provider=provider)
def get_tier(self):
"""
Returns the price tier object.
"""
if self.has_premium():
return self.premium.price
def get_tier_name(self):
"""
Returns the price tier for showing prices in the reviewer
tools and developer hub.
"""
tier = self.get_tier()
if tier:
return tier.tier_locale()
@amo.cached_property
def promo(self):
return self.get_promo()
def get_promo(self):
try:
return self.previews.filter(position=-1)[0]
except IndexError:
pass
def get_region_ids(self, worldwide=False, excluded=None):
"""
Return IDs of regions in which this app is listed.
If `excluded` is provided we'll use that instead of doing our own
excluded lookup.
"""
if worldwide:
all_ids = mkt.regions.ALL_REGION_IDS
else:
all_ids = mkt.regions.REGION_IDS
if excluded is None:
excluded = list(self.addonexcludedregion
.values_list('region', flat=True))
return sorted(list(set(all_ids) - set(excluded)))
def get_possible_price_region_ids(self):
if self.premium:
ids = [p['region'] for p in self.premium.price.prices()]
return sorted(set(ids))
return set()
def get_regions(self):
"""
Return regions, e.g.:
[<class 'mkt.constants.regions.BR'>,
<class 'mkt.constants.regions.CA'>,
<class 'mkt.constants.regions.UK'>,
<class 'mkt.constants.regions.US'>,
<class 'mkt.constants.regions.WORLDWIDE'>]
"""
_regions = map(mkt.regions.REGIONS_CHOICES_ID_DICT.get,
self.get_region_ids(worldwide=True))
return sorted(_regions, key=lambda x: x.slug)
def listed_in(self, region=None, category=None):
listed = []
if region:
listed.append(region.id in self.get_region_ids(worldwide=True))
if category:
if isinstance(category, basestring):
filters = {'slug': category}
else:
filters = {'id': category.id}
listed.append(self.category_set.filter(**filters).exists())
return all(listed or [False])
def content_ratings_in(self, region, category=None):
"""Give me the content ratings for a game listed in Brazil."""
# If we want to find games in Brazil with content ratings, then
# make sure it's actually listed in Brazil and it's a game.
if category and not self.listed_in(region, category):
return []
rb = [x.id for x in region.ratingsbodies]
return list(self.content_ratings.filter(ratings_body__in=rb)
.order_by('rating'))
@classmethod
def now(cls):
return datetime.date.today()
@classmethod
def featured(cls, cat=None, region=None, limit=9, mobile=False,
gaia=False, tablet=False, profile=None):
apps = (FeaturedApp.objects
.featured(cat, region, limit, mobile, gaia, tablet, profile)
.values_list('app_id', flat=True))
# Get a list of ids, then get all those objects in one query
# which will get cache-machined.
return list(cls.objects.filter(pk__in=list(apps)))
@classmethod
def from_search(cls, request, cat=None, region=None, gaia=False,
mobile=False, tablet=False, filter_overrides=None,
new_idx=False):
filters = {
'type': amo.ADDON_WEBAPP,
'status': amo.STATUS_PUBLIC,
'is_disabled': False,
}
# Special handling if status is 'any' to remove status filter.
if filter_overrides and 'status' in filter_overrides:
if filter_overrides['status'] is 'any':
del filters['status']
del filter_overrides['status']
if filter_overrides:
filters.update(filter_overrides)
if cat:
filters.update(category=cat.id)
if new_idx and waffle.switch_is_active('search-api-es'):
srch = S(WebappIndexer).filter(**filters)
else:
srch = TempS(cls).filter(**filters)
if region:
if new_idx and waffle.switch_is_active('search-api-es'):
srch = srch.filter(~F(region_exclusions=region.id))
else:
excluded = get_excluded_in(region.id)
if excluded:
log.info(
'Excluding the following IDs based on region %s: %s'
% (region.slug, excluded))
srch = srch.filter(~F(id__in=excluded))
if mobile or gaia:
srch = srch.filter(uses_flash=False)
exclude_paid = True
if waffle.flag_is_active(request, 'allow-paid-app-search'):
exclude_paid = (mobile or tablet) and not gaia
if exclude_paid:
srch = srch.filter(~F(premium_type__in=amo.ADDON_PREMIUMS))
return srch
@classmethod
def popular(cls, request, cat=None, region=None, gaia=False):
"""Elastically grab the most popular apps."""
return cls.from_search(request, cat, region,
gaia=gaia).order_by('-popularity')
@classmethod
def latest(cls, request, cat=None, region=None, gaia=False):
"""Elastically grab the most recent apps."""
return cls.from_search(request, cat, region,
gaia=gaia).order_by('-created')
@classmethod
def category(cls, slug):
try:
return (Category.objects
.filter(type=amo.ADDON_WEBAPP, slug=slug))[0]
except IndexError:
return None
def in_rereview_queue(self):
return self.rereviewqueue_set.exists()
def get_cached_manifest(self, force=False):
"""
Creates the "mini" manifest for packaged apps and caches it.
Call this with `force=True` whenever we need to update the cached
version of this manifest, e.g., when a new version of the packaged app
is approved.
If the addon is not a packaged app, this will not cache anything.
"""
if not self.is_packaged:
return
key = 'webapp:{0}:manifest'.format(self.pk)
if not force:
data = cache.get(key)
if data:
return data
version = self.current_version
if not version:
data = {}
else:
file_obj = version.all_files[0]
manifest = self.get_manifest_json(file_obj)
package_path = absolutify(
os.path.join(reverse('downloads.file', args=[file_obj.id]),
file_obj.filename))
data = {
'name': manifest['name'],
'version': version.version,
'size': storage.size(file_obj.signed_file_path),
'release_notes': version.releasenotes,
'package_path': package_path,
}
for key in ['developer', 'icons', 'locales']:
if key in manifest:
data[key] = manifest[key]
data = json.dumps(data, cls=JSONEncoder)
cache.set(key, data, 0)
return data
def sign_if_packaged(self, version_pk, reviewer=False):
if not self.is_packaged:
return
return packaged.sign(version_pk, reviewer=reviewer)
def assign_uuid(self):
"""Generates a UUID if self.guid is not already set."""
if not self.guid:
max_tries = 10
tried = 1
guid = str(uuid.uuid4())
while tried <= max_tries:
if not Webapp.objects.filter(guid=guid).exists():
self.guid = guid
break
else:
guid = str(uuid.uuid4())
tried += 1
else:
raise ValueError('Could not auto-generate a unique UUID')
def is_premium_type_upgrade(self, premium_type):
"""
Returns True if changing self.premium_type from current value to passed
in value is considered an upgrade that should trigger a re-review.
"""
ALL = set(amo.ADDON_FREES + amo.ADDON_PREMIUMS)
free_upgrade = ALL - set([amo.ADDON_FREE])
free_inapp_upgrade = ALL - set([amo.ADDON_FREE, amo.ADDON_FREE_INAPP])
if (self.premium_type == amo.ADDON_FREE and
premium_type in free_upgrade):
return True
if (self.premium_type == amo.ADDON_FREE_INAPP and
premium_type in free_inapp_upgrade):
return True
return False
def create_blocklisted_version(self):
"""
Creates a new version who's file is the blocklisted app found in /media
and sets status to STATUS_BLOCKLISTED.
"""
blocklisted_path = os.path.join(settings.MEDIA_ROOT, 'packaged-apps',
'blocklisted.zip')
last_version = self.current_version.version
v = Version.objects.create(
addon=self, version='blocklisted-%s' % last_version)
f = File(version=v, status=amo.STATUS_BLOCKED,
platform=Platform.objects.get(id=amo.PLATFORM_ALL.id))
f.filename = f.generate_filename()
copy_stored_file(blocklisted_path, f.file_path)
log.info(u'[Webapp:%s] Copied blocklisted app from %s to %s' % (
self.id, blocklisted_path, f.file_path))
f.size = storage.size(f.file_path)
f.hash = f.generate_hash(f.file_path)
f.save()
self.sign_if_packaged(v.pk)
self.status = amo.STATUS_BLOCKED
self._current_version = v
self.save()
def update_name_from_package_manifest(self):
"""
Looks at the manifest.webapp inside the current version's file and
updates the app's name and translated names.
Note: Make sure the correct version is in place before calling this.
"""
if not self.is_packaged:
return None
file_ = self.versions.latest().all_files[0]
mf = self.get_manifest_json(file_)
# Get names in "locales" as {locale: name}.
locale_names = get_locale_properties(mf, 'name', self.default_locale)
# Check changes to default_locale.
locale_changed = self.update_default_locale(mf.get('default_locale'))
if locale_changed:
log.info(u'[Webapp:%s] Default locale changed from "%s" to "%s".'
% (self.pk, locale_changed[0], locale_changed[1]))
# Update names
crud = self.update_names(locale_names)
if any(crud.values()):
self.save()
def update_supported_locales(self, latest=False, manifest=None):
"""
Loads the manifest (for either hosted or packaged) and updates
Version.supported_locales for the current version or latest version if
latest=True.
"""
version = self.versions.latest() if latest else self.current_version
file_ = version.all_files[0]
if not manifest:
manifest = self.get_manifest_json(file_)
updated = False
supported_locales = ','.join(get_supported_locales(manifest))
if version.supported_locales != supported_locales:
updated = True
version.update(supported_locales=supported_locales, _signal=False)
return updated
@property
def app_type(self):
# Returns string of 'hosted' or 'packaged'. Used in the API.
key = (amo.ADDON_WEBAPP_PACKAGED if self.is_packaged else
amo.ADDON_WEBAPP_HOSTED)
return amo.ADDON_WEBAPP_TYPES[key]
@property
def supported_locales(self):
"""
Returns a tuple of the form:
(localized default_locale, list of localized supported locales)
for the current public version.
"""
languages = []
version = self.current_version
if version:
for locale in version.supported_locales.split(','):
if locale:
language = settings.LANGUAGES.get(locale.lower())
if language:
languages.append(language)
return (
settings.LANGUAGES.get(self.default_locale.lower()),
sorted(languages)
)
class WebappIndexer(MappingType, Indexable):
"""
Mapping type for Webapp models.
By default we will return these objects rather than hit the database so
include here all the things we need to avoid hitting the database.
"""
@classmethod
def get_mapping_type_name(cls):
"""
Returns mapping type name which is used as the key in ES_INDEXES to
determine which index to use.
We override this because Webapp is a proxy model to
Addon.
"""
return 'webapp'
@classmethod
def get_index(cls):
return settings.ES_INDEXES[cls.get_mapping_type_name()]
@classmethod
def get_model(cls):
return Webapp
@classmethod
def setup_mapping(cls):
"""Creates the ES index/mapping."""
cls.get_es().create_index(cls.get_index(),
{'mappings': cls.get_mapping()})
@classmethod
def get_mapping(cls):
doc_type = cls.get_mapping_type_name()
def _locale_field_mapping(field, analyzer):
return {'name_%s' % analyzer: {'type': 'string',
'analyzer': analyzer}}
mapping = {
doc_type: {
# Disable _all field to reduce index size.
'_all': {'enabled': False},
# Add a boost field to enhance relevancy of a document.
'_boost': {'name': '_boost', 'null_value': 1.0},
'properties': {
'id': {'type': 'long'},
'app_slug': {'type': 'string'},
'app_type': {'type': 'byte'},
'authors': {'type': 'string'},
'average_daily_users': {'type': 'long'},
'bayesian_rating': {'type': 'float'},
'category': {'type': 'integer'},
'content_ratings': {
'type': 'object',
'dynamic': 'true',
},
'created': {'format': 'dateOptionalTime', 'type': 'date'},
'current_version': {
'type': 'object',
'properties': {
'version': {'type': 'string',
'index': 'not_analyzed'},
'release_notes': {'type': 'string',
'index': 'not_analyzed'},
'developer_name': {'type': 'string',
'index': 'not_analyzed'},
}
},
'default_locale': {'type': 'string',
'index': 'not_analyzed'},
'description': {'type': 'string', 'analyzer': 'snowball'},
'device': {'type': 'byte'},
'features': {
'type': 'object',
'properties': dict(
('has_%s' % f.lower(), {'type': 'boolean'})
for f in APP_FEATURES)
},
'has_public_stats': {'type': 'boolean'},
'homepage': {'type': 'string', 'index': 'not_analyzed'},
'icons': {
'type': 'object',
'properties': {
'size': {'type': 'short'},
'url': {'type': 'string', 'index': 'not_analyzed'},
}
},
'is_disabled': {'type': 'boolean'},
'last_updated': {'format': 'dateOptionalTime',
'type': 'date'},
'latest_version': {
'type': 'object',
'properties': {
'status': {'type': 'byte'},
'is_privileged': {'type': 'boolean'},
},
},
'manifest_url': {'type': 'string',
'index': 'not_analyzed'},
'name': {'type': 'string',