def browse(request, viewer, key=None, type_='file'): form = forms.FileCompareForm(request.POST or None, addon=viewer.addon, initial={'left': viewer.file}) response = check_compare_form(request, form) if response: return response data = setup_viewer(request, viewer.file) data['viewer'] = viewer data['poll_url'] = reverse('mkt.files.poll', args=[viewer.file.id]) data['form'] = form if not viewer.is_extracted(): extract_file(viewer.file.id) if viewer.is_extracted(): data.update({'status': True, 'files': viewer.get_files()}) key = viewer.get_default(key) if key not in data['files']: raise http.Http404 viewer.select(key) data['key'] = key binary = viewer.is_binary() if (not viewer.is_directory() and (not binary or binary != 'image')): data['content'] = viewer.read_file() else: extract_file.delay(viewer.file.id) tmpl = 'content' if type_ == 'fragment' else 'viewer' return render(request, 'fileviewer/%s.html' % tmpl, data)
def payments(request, addon_id, addon, webapp=False): premium_form = forms_payments.PremiumForm( request.POST or None, request=request, addon=addon, user=request.user) region_form = forms.RegionForm( request.POST or None, product=addon, request=request) if request.method == 'POST': if region_form.is_valid() and premium_form.is_valid(): region_form.save() premium_form.save() messages.success(request, _('Changes successfully saved.')) return redirect(addon.get_dev_url('payments')) return render(request, 'developers/payments/premium.html', {'addon': addon, 'webapp': webapp, 'region_form': region_form, 'is_paid': (addon.premium_type in mkt.ADDON_PREMIUMS or addon.premium_type == mkt.ADDON_FREE_INAPP), 'form': premium_form, 'is_fxos': DEVICE_GAIA.id in ( addon.addondevicetype_set.values_list('device_type', flat=True)), 'PLATFORMS_NAMES': PLATFORMS_NAMES})
def website_abuse(request, website): reports = AbuseReport.objects.filter(website=website).order_by('-created') total = reports.count() reports = paginate(request, reports, count=total) return render(request, 'reviewers/abuse.html', context(request, item=website, reports=reports, total=total))
def transaction_search(request): tx_form = TransactionSearchForm(request.GET) if tx_form.is_valid(): return redirect(reverse('lookup.transaction_summary', args=[tx_form.cleaned_data['q']])) else: return render(request, 'lookup/home.html', {'tx_form': tx_form})
def logs(request): data = request.GET.copy() if not data.get('start') and not data.get('end'): today = datetime.date.today() data['start'] = today - datetime.timedelta(days=30) form = forms.ReviewLogForm(data) approvals = ActivityLog.objects.review_queue(webapp=True) if form.is_valid(): data = form.cleaned_data if data.get('start'): approvals = approvals.filter(created__gte=data['start']) if data.get('end'): approvals = approvals.filter(created__lt=data['end']) if data.get('search'): term = data['search'] approvals = approvals.filter( Q(commentlog__comments__icontains=term) | Q(applog__addon__name__localized_string__icontains=term) | Q(applog__addon__app_slug__icontains=term) | Q(user__display_name__icontains=term) | Q(user__email__icontains=term)).distinct() pager = paginate(request, approvals, 50) data = context(request, form=form, pager=pager, ACTION_DICT=mkt.LOG_BY_ID, tab='logs') return render(request, 'reviewers/logs.html', data)
def monitor(request, format=None): # For each check, a boolean pass/fail status to show in the template status_summary = {} results = {} checks = ['memcache', 'libraries', 'elastic', 'package_signer', 'path', 'receipt_signer', 'settings_check', 'solitude'] for check in checks: with statsd.timer('monitor.%s' % check) as timer: status, result = getattr(monitors, check)() # state is a string. If it is empty, that means everything is fine. status_summary[check] = {'state': not status, 'status': status} results['%s_results' % check] = result results['%s_timer' % check] = timer.ms # If anything broke, send HTTP 500. status_code = 200 if all(a['state'] for a in status_summary.values()) else 500 if format == '.json': return HttpResponse(json.dumps(status_summary), status=status_code) ctx = {} ctx.update(results) ctx['status_summary'] = status_summary return render(request, 'services/monitor.html', ctx, status=status_code)
def api(request): roles = request.user.groups.filter(name="Admins").exists() form = APIConsumerForm() if roles: messages.error(request, _("Users with the admin role cannot use the API.")) elif request.method == "POST": if "delete" in request.POST: try: consumer = Access.objects.get(pk=request.POST.get("consumer"), user=request.user) consumer.delete() except Access.DoesNotExist: messages.error(request, _("No such API key.")) else: access = Access.create_for_user(request.user) form = APIConsumerForm(request.POST, instance=access) if form.is_valid(): form.save() messages.success(request, _("New API key generated.")) else: access.delete() consumers = list(Access.objects.filter(user=request.user)) return render( request, "developers/api.html", { "consumers": consumers, "roles": roles, "form": form, "domain": settings.DOMAIN, "site_url": settings.SITE_URL, }, )
def authorize(request): if request.method == 'GET' and 'oauth_token' in request.GET: try: t = Token.objects.get(token_type=REQUEST_TOKEN, key=request.GET['oauth_token']) except Token.DoesNotExist: log.error('Invalid OAuth request for obtaining user authorization') return HttpResponse(status=401) return render( request, 'developers/oauth_authorize.html', { 'app_name': t.creds.app_name, 'oauth_token': request.GET['oauth_token'] }) elif request.method == 'POST': token = request.POST.get('oauth_token') try: t = Token.objects.get(token_type=REQUEST_TOKEN, key=token) except Token.DoesNotExist: return HttpResponse(status=401) if 'grant' in request.POST: t.user = request.user t.save() return HttpResponseRedirect( urlparams(t.creds.redirect_uri, oauth_token=token, oauth_verifier=t.verifier)) elif 'deny' in request.POST: t.delete() return HttpResponse(status=200) else: log.error('Invalid OAuth request for user access authorization') return HttpResponse(status=401)
def monitor(request, format=None): # For each check, a boolean pass/fail status to show in the template status_summary = {} results = {} checks = [ 'memcache', 'libraries', 'elastic', 'package_signer', 'path', 'receipt_signer', 'settings_check' ] for check in checks: with statsd.timer('monitor.%s' % check) as timer: status, result = getattr(monitors, check)() # state is a string. If it is empty, that means everything is fine. status_summary[check] = {'state': not status, 'status': status} results['%s_results' % check] = result results['%s_timer' % check] = timer.ms # If anything broke, send HTTP 500. status_code = 200 if all(a['state'] for a in status_summary.values()) else 500 if format == '.json': return HttpResponse(json.dumps(status_summary), status=status_code) ctx = {} ctx.update(results) ctx['status_summary'] = status_summary return render(request, 'services/monitor.html', ctx, status=status_code)
def moderatelog_detail(request, eventlog_id): log = get_object_or_404(ActivityLog.objects.editor_events(), pk=eventlog_id) review = None if len(log.arguments) > 1 and isinstance(log.arguments[1], Review): review = log.arguments[1] form = ModerateLogDetailForm(request.POST or None) is_admin = acl.action_allowed(request, 'ReviewerAdminTools', 'View') can_undelete = review and review.deleted and (is_admin or request.user.pk == log.user.pk) if (request.method == 'POST' and form.is_valid() and form.cleaned_data['action'] == 'undelete'): if not can_undelete: if not review: raise RuntimeError('Review doesn`t exist.') elif not review.deleted: raise RuntimeError('Review isn`t deleted.') else: raise PermissionDenied ReviewerScore.award_moderation_points(log.user, review.addon, review.id, undo=True) review.undelete() return redirect('reviewers.apps.moderatelog.detail', eventlog_id) data = context(request, log=log, form=form, review=review, can_undelete=can_undelete) return render(request, 'reviewers/moderatelog_detail.html', data)
def _queue(request, apps, tab, pager_processor=None, date_sort='created', template='reviewers/queue.html', data=None, use_es=False): per_page = request.GET.get('per_page', QUEUE_PER_PAGE) pager = paginate(request, apps, per_page) ctx = { 'addons': pager.object_list, 'pager': pager, 'tab': tab, 'search_form': _get_search_form(request), 'date_sort': date_sort, 'use_es': use_es, } # Additional context variables. if data is not None: ctx.update(data) return render(request, template, context(request, **ctx))
def in_app_products(request, addon_id, addon, webapp=True, account=None): owner = acl.check_addon_ownership(request, addon) products = addon.inappproduct_set.all() new_product = InAppProduct(webapp=addon) form = InAppProductForm() if addon.origin: inapp_origin = addon.origin elif addon.guid: # Derive a marketplace specific origin out of the GUID. # This is for apps that do not specify a custom origin. inapp_origin = 'marketplace:{}'.format(addon.guid) else: # Theoretically this is highly unlikely. A hosted app will # always have a domain and a packaged app will always have # a generated GUID. raise TypeError( 'Cannot derive origin: no declared origin, no GUID') list_url = _fix_origin_link(reverse('in-app-products-list', kwargs={'origin': inapp_origin})) detail_url = _fix_origin_link(reverse('in-app-products-detail', # {guid} is replaced in JS. kwargs={'origin': inapp_origin, 'guid': "{guid}"})) return render(request, 'developers/payments/in-app-products.html', {'addon': addon, 'form': form, 'new_product': new_product, 'owner': owner, 'products': products, 'form': form, 'list_url': list_url, 'detail_url': detail_url, 'active_lang': request.LANG.lower()})
def validate_app(request): return render(request, 'developers/validate_app.html', { 'upload_hosted_url': reverse('mkt.developers.standalone_hosted_upload'), 'upload_packaged_url': reverse('mkt.developers.standalone_packaged_upload'), })
def app_abuse(request, addon): reports = AbuseReport.objects.filter(addon=addon).order_by('-created') total = reports.count() reports = paginate(request, reports, count=total) return render(request, 'reviewers/abuse.html', context(request, item=addon, reports=reports, total=total))
def authorize(request): if request.method == 'GET' and 'oauth_token' in request.GET: try: t = Token.objects.get(token_type=REQUEST_TOKEN, key=request.GET['oauth_token']) except Token.DoesNotExist: log.error('Invalid OAuth request for obtaining user authorization') return HttpResponse(status=401) return render(request, 'developers/oauth_authorize.html', {'app_name': t.creds.app_name, 'oauth_token': request.GET['oauth_token']}) elif request.method == 'POST': token = request.POST.get('oauth_token') try: t = Token.objects.get(token_type=REQUEST_TOKEN, key=token) except Token.DoesNotExist: return HttpResponse(status=401) if 'grant' in request.POST: t.user = request.user t.save() return HttpResponseRedirect( urlparams(t.creds.redirect_uri, oauth_token=token, oauth_verifier=t.verifier)) elif 'deny' in request.POST: t.delete() return HttpResponse(status=200) else: log.error('Invalid OAuth request for user access authorization') return HttpResponse(status=401)
def moderatelog_detail(request, eventlog_id): log = get_object_or_404( ActivityLog.objects.editor_events(), pk=eventlog_id) review = None if len(log.arguments) > 1 and isinstance(log.arguments[1], Review): review = log.arguments[1] form = ModerateLogDetailForm(request.POST or None) is_admin = acl.action_allowed(request, 'ReviewerAdminTools', 'View') can_undelete = review and review.deleted and ( is_admin or request.user.pk == log.user.pk) if (request.method == 'POST' and form.is_valid() and form.cleaned_data['action'] == 'undelete'): if not can_undelete: if not review: raise RuntimeError('Review doesn`t exist.') elif not review.deleted: raise RuntimeError('Review isn`t deleted.') else: raise PermissionDenied ReviewerScore.award_moderation_points( log.user, review.addon, review.id, undo=True) review.undelete() return redirect('reviewers.apps.moderatelog.detail', eventlog_id) data = context(request, log=log, form=form, review=review, can_undelete=can_undelete) return render(request, 'reviewers/moderatelog_detail.html', data)
def transactions(request): form, transactions = _get_transactions(request) return render( request, 'developers/transactions.html', {'form': form, 'CONTRIB_TYPES': mkt.CONTRIB_TYPES, 'count': transactions.count(), 'transactions': paginate(request, transactions, per_page=50)})
def api(request): roles = request.user.groups.filter(name='Admins').exists() form = APIConsumerForm() if roles: messages.error(request, _('Users with the admin role cannot use the API.')) elif request.method == 'POST': if 'delete' in request.POST: try: consumer = Access.objects.get(pk=request.POST.get('consumer'), user=request.user) consumer.delete() except Access.DoesNotExist: messages.error(request, _('No such API key.')) else: access = Access.create_for_user(request.user) form = APIConsumerForm(request.POST, instance=access) if form.is_valid(): form.save() messages.success(request, _('New API key generated.')) else: access.delete() consumers = list(Access.objects.filter(user=request.user)) return render(request, 'developers/api.html', {'consumers': consumers, 'roles': roles, 'form': form, 'domain': settings.DOMAIN, 'site_url': settings.SITE_URL})
def user_summary(request, user_id): user = get_object_or_404(UserProfile, pk=user_id) is_admin = acl.action_allowed(request, 'Users', 'Edit') app_summary = _app_summary(user.pk) # All refunds that this user has requested (probably as a consumer). req = Refund.objects.filter(contribution__user=user) # All instantly-approved refunds that this user has requested. appr = req.filter(status=mkt.REFUND_APPROVED_INSTANT) refund_summary = {'approved': appr.count(), 'requested': req.count()} user_addons = user.addons.order_by('-created') user_addons = paginate(request, user_addons, per_page=15) payment_data = (AddonPaymentData.objects.filter(addon__authors=user) .values(*AddonPaymentData.address_fields()) .distinct()) # If the user is deleted, get the log detailing the delete. try: delete_log = ActivityLog.objects.for_user(user).filter( action=mkt.LOG.DELETE_USER_LOOKUP.id)[0] except IndexError: delete_log = None group_membership_formset = APIGroupMembershipFormSet() provider_portals = get_payment_provider_portals(user=user) return render(request, 'lookup/user_summary.html', {'account': user, 'app_summary': app_summary, 'delete_form': DeleteUserForm(), 'delete_log': delete_log, 'is_admin': is_admin, 'refund_summary': refund_summary, 'user_addons': user_addons, 'payment_data': payment_data, 'provider_portals': provider_portals, 'group_membership_formset': group_membership_formset})
def content_ratings(request, addon_id, addon): if not addon.is_rated(): return redirect(addon.get_dev_url('ratings_edit')) # Use _ratings_success_msg to display success message. session = request.session app_id = str(addon.id) ratings = sorted(addon.content_ratings.all(), key=lambda r: r.get_body().name) if 'ratings_edit' in session and app_id in session['ratings_edit']: prev_state = session['ratings_edit'][app_id] msg = _ratings_success_msg( addon, prev_state['app_status'], prev_state['rating_modified']) messages.success(request, msg) if msg else None del session['ratings_edit'][app_id] # Clear msg so not shown again. request.session.modified = True ctx = { 'addon': addon, 'cert': None, 'ratings': ratings, 'rating_descriptors': addon.rating_descriptors, 'rating_interactives': addon.rating_interactives, } if waffle.switch_is_active('iarc-upgrade-v2'): # If there is a cert attached, we show it to the developer. try: ctx['cert'] = addon.iarc_cert except IARCCert.DoesNotExist: pass return render(request, 'developers/apps/ratings/ratings_summary.html', ctx)
def file_validation(request, addon_id, addon, file_id): file = get_object_or_404(File, id=file_id) v = addon.get_dev_url('json_file_validation', args=[file.id]) return render(request, 'developers/validation.html', dict(validate_url=v, filename=file.filename, timestamp=file.created, addon=addon))
def app_summary(request, addon_id): if unicode(addon_id).isdigit(): query = {'pk': addon_id} else: query = {'app_slug': addon_id} app = get_object_or_404(Webapp.with_deleted, **query) if request.FILES: promo_img_form = PromoImgForm(request.POST, request.FILES) else: promo_img_form = PromoImgForm() if 'promo_img' in request.FILES and promo_img_form.is_valid(): promo_img_form.save(app) messages.success( request, 'Promo image successfully uploaded.' ' You may have to refresh the page again to see it below.') return redirect(reverse('lookup.app_summary', args=[app.pk])) if 'prioritize' in request.POST and not app.priority_review: prioritize_app(app, request.user) authors = (app.authors.filter(addonuser__role__in=(mkt.AUTHOR_ROLE_DEV, mkt.AUTHOR_ROLE_OWNER)) .order_by('display_name')) if app.premium and app.premium.price: price = app.premium.price else: price = None purchases, refunds = _app_purchases_and_refunds(app) provider_portals = get_payment_provider_portals(app=app) versions = None status_form = APIStatusForm(initial={ 'status': mkt.STATUS_CHOICES_API[app.status] }) version_status_forms = {} if app.is_packaged: versions = app.versions.all().order_by('-created') for v in versions: version_status_forms[v.pk] = APIFileStatusForm(initial={ 'status': mkt.STATUS_CHOICES_API[v.all_files[0].status] }) permissions = {} if app.latest_version: permissions = app.latest_version.manifest.get('permissions', {}) return render(request, 'lookup/app_summary.html', { 'abuse_reports': app.abuse_reports.count(), 'app': app, 'authors': authors, 'purchases': purchases, 'refunds': refunds, 'price': price, 'provider_portals': provider_portals, 'status_form': status_form, 'versions': versions, 'is_tarako': app.tags.filter(tag_text=QUEUE_TARAKO).exists(), 'version_status_forms': version_status_forms, 'permissions': permissions, 'promo_img_form': promo_img_form, })
def motd(request): message = unmemoized_get_config("mkt_developers_motd") form = MOTDForm(request.POST or None, initial={"motd": message}) if request.method == "POST" and form and form.is_valid(): set_config("mkt_developers_motd", form.cleaned_data["motd"]) messages.success(request, _("Changes successfully saved.")) return redirect(reverse("mkt.developers.motd")) return render(request, "developers/motd.html", {"form": form})
def transaction_search(request): tx_form = TransactionSearchForm(request.GET) if tx_form.is_valid(): return redirect( reverse('lookup.transaction_summary', args=[tx_form.cleaned_data['q']])) else: return render(request, 'lookup/home.html', {'tx_form': tx_form})
def user_purchases(request, user_id): """Shows the purchase page for another user.""" user = get_object_or_404(UserProfile, pk=user_id) is_admin = acl.action_allowed(request, 'Users', 'Edit') products = purchase_list(request, user) return render(request, 'lookup/user_purchases.html', {'pager': products, 'account': user, 'is_admin': is_admin, 'single': bool(None), 'show_link': False})
def motd(request): message = unmemoized_get_config('mkt_developers_motd') form = MOTDForm(request.POST or None, initial={'motd': message}) if request.method == 'POST' and form and form.is_valid(): set_config('mkt_developers_motd', form.cleaned_data['motd']) messages.success(request, _('Changes successfully saved.')) return redirect(reverse('mkt.developers.motd')) return render(request, 'developers/motd.html', {'form': form})
def price_tiers(request): output = [] form = PriceTiersForm(request.POST or None, request.FILES) if request.method == 'POST' and form.is_valid(): output = update_from_csv(form.cleaned_data['prices']) return render(request, 'zadmin/update-prices.html', {'result': output, 'form': form})
def apps_reviewing(request): return render( request, 'reviewers/apps_reviewing.html', context( request, **{ 'tab': 'reviewing', 'apps': AppsReviewing(request).get_apps() }))
def login(request, template=None): if "to" in request.GET: request = _clean_next_url(request) data = {"to": request.GET.get("to")} if request.user.is_authenticated(): return http.HttpResponseRedirect(request.GET.get("to", settings.LOGIN_REDIRECT_URL)) return render(request, "developers/login.html", data)
def content_ratings_edit(request, addon_id, addon): if settings.DEBUG: messages.debug(request, "DEBUG mode on; you may use IARC id 0 with any code") initial = {} data = request.POST if request.method == "POST" else None if waffle.switch_is_active("iarc-upgrade-v2"): form_class = IARCV2ExistingCertificateForm else: try: app_info = addon.iarc_info initial["submission_id"] = app_info.submission_id initial["security_code"] = app_info.security_code except IARCInfo.DoesNotExist: pass form_class = IARCGetAppInfoForm form = form_class(data=data, initial=initial, app=addon) if request.method == "POST" and form.is_valid(): try: form.save() return redirect(addon.get_dev_url("ratings")) except django_forms.ValidationError: pass # Fall through to show the form error. # Save some information for _ratings_success_msg. if "ratings_edit" not in request.session: request.session["ratings_edit"] = {} last_rated = addon.last_rated_time() request.session["ratings_edit"][str(addon.id)] = { "app_status": addon.status, "rating_modified": last_rated.isoformat() if last_rated else None, } request.session.modified = True ctx = { "addon": addon, "app_name": get_iarc_app_title(addon), "form": form, "company": addon.latest_version.developer_name, "now": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), } if waffle.switch_is_active("iarc-upgrade-v2"): try: iarc_request = addon.iarc_request outdated = datetime.now() - iarc_request.created > timedelta(hours=1) if outdated: # IARC request outdated. Re-create. iarc_request.delete() iarc_request = IARCRequest.objects.create(app=addon, uuid=uuid.uuid4()) except IARCRequest.DoesNotExist: # No IARC request exists. Create. iarc_request = IARCRequest.objects.create(app=addon, uuid=uuid.uuid4()) ctx["iarc_request_id"] = unicode(uuid.UUID(iarc_request.uuid)) return render(request, "developers/apps/ratings/ratings_edit.html", ctx)
def validate_app(request): return render( request, "developers/validate_app.html", { "upload_hosted_url": reverse("mkt.developers.standalone_hosted_upload"), "upload_packaged_url": reverse("mkt.developers.standalone_packaged_upload"), }, )
def email_devs(request): form = DevMailerForm(request.POST or None) preview = EmailPreviewTopic(topic='email-devs') if preview.filter().count(): preview_csv = reverse('zadmin.email_preview_csv', args=[preview.topic]) else: preview_csv = None if request.method == 'POST' and form.is_valid(): data = form.cleaned_data qs = (AddonUser.objects.filter( role__in=(mkt.AUTHOR_ROLE_DEV, mkt.AUTHOR_ROLE_OWNER)).exclude(user__email=None)) if data['recipients'] in ('payments', 'desktop_apps'): qs = qs.exclude(addon__status=mkt.STATUS_DELETED) else: qs = qs.filter(addon__status__in=mkt.LISTED_STATUSES) if data['recipients'] in ('payments', 'payments_region_enabled', 'payments_region_disabled'): qs = qs.exclude(addon__premium_type__in=(mkt.ADDON_FREE, mkt.ADDON_OTHER_INAPP)) if data['recipients'] == 'payments_region_enabled': qs = qs.filter(addon__enable_new_regions=True) elif data['recipients'] == 'payments_region_disabled': qs = qs.filter(addon__enable_new_regions=False) elif data['recipients'] in ('apps', 'free_apps_region_enabled', 'free_apps_region_disabled'): if data['recipients'] == 'free_apps_region_enabled': qs = qs.filter(addon__enable_new_regions=True) elif data['recipients'] == 'free_apps_region_disabled': qs = qs.filter(addon__enable_new_regions=False) elif data['recipients'] == 'desktop_apps': qs = (qs.filter( addon__addondevicetype__device_type=mkt.DEVICE_DESKTOP.id)) else: raise NotImplementedError('If you want to support emailing other ' 'types of developers, do it here!') if data['preview_only']: # Clear out the last batch of previewed emails. preview.filter().delete() total = 0 for emails in chunked(set(qs.values_list('user__email', flat=True)), 100): total += len(emails) tasks.admin_email.delay(emails, data['subject'], data['message'], preview_only=data['preview_only'], preview_topic=preview.topic) msg = 'Emails queued for delivery: %s' % total if data['preview_only']: msg = '%s (for preview only, emails not sent!)' % msg messages.success(request, msg) return redirect('zadmin.email_devs') return render(request, 'zadmin/email-devs.html', dict(form=form, preview_csv=preview_csv))
def dashboard(request): addons, sorting = addon_listing(request) addons = paginate(request, addons, per_page=10) data = { 'addons': addons, 'sorting': sorting, 'motd': unmemoized_get_config('mkt_developers_motd') } return render(request, 'developers/apps/dashboard.html', data)
def email_devs(request): form = DevMailerForm(request.POST or None) preview = EmailPreviewTopic(topic='email-devs') if preview.filter().count(): preview_csv = reverse('zadmin.email_preview_csv', args=[preview.topic]) else: preview_csv = None if request.method == 'POST' and form.is_valid(): data = form.cleaned_data qs = (AddonUser.objects.filter(role__in=(mkt.AUTHOR_ROLE_DEV, mkt.AUTHOR_ROLE_OWNER)) .exclude(user__email=None)) if data['recipients'] in ('payments', 'desktop_apps'): qs = qs.exclude(addon__status=mkt.STATUS_DELETED) else: qs = qs.filter(addon__status__in=mkt.LISTED_STATUSES) if data['recipients'] in ('payments', 'payments_region_enabled', 'payments_region_disabled'): qs = qs.exclude(addon__premium_type__in=(mkt.ADDON_FREE, mkt.ADDON_OTHER_INAPP)) if data['recipients'] == 'payments_region_enabled': qs = qs.filter(addon__enable_new_regions=True) elif data['recipients'] == 'payments_region_disabled': qs = qs.filter(addon__enable_new_regions=False) elif data['recipients'] in ('apps', 'free_apps_region_enabled', 'free_apps_region_disabled'): if data['recipients'] == 'free_apps_region_enabled': qs = qs.filter(addon__enable_new_regions=True) elif data['recipients'] == 'free_apps_region_disabled': qs = qs.filter(addon__enable_new_regions=False) elif data['recipients'] == 'desktop_apps': qs = (qs.filter( addon__addondevicetype__device_type=mkt.DEVICE_DESKTOP.id)) else: raise NotImplementedError('If you want to support emailing other ' 'types of developers, do it here!') if data['preview_only']: # Clear out the last batch of previewed emails. preview.filter().delete() total = 0 for emails in chunked(set(qs.values_list('user__email', flat=True)), 100): total += len(emails) tasks.admin_email.delay(emails, data['subject'], data['message'], preview_only=data['preview_only'], preview_topic=preview.topic) msg = 'Emails queued for delivery: %s' % total if data['preview_only']: msg = '%s (for preview only, emails not sent!)' % msg messages.success(request, msg) return redirect('zadmin.email_devs') return render(request, 'zadmin/email-devs.html', dict(form=form, preview_csv=preview_csv))
def price_tiers(request): output = [] form = PriceTiersForm(request.POST or None, request.FILES) if request.method == 'POST' and form.is_valid(): output = update_from_csv(form.cleaned_data['prices']) return render(request, 'zadmin/update-prices.html', { 'result': output, 'form': form })
def show_settings(request): settings_dict = debug.get_safe_settings() for i in ['GOOGLE_ANALYTICS_CREDENTIALS']: settings_dict[i] = debug.cleanse_setting(i, getattr(settings, i, {})) settings_dict['WEBAPPS_RECEIPT_KEY'] = '********************' return render(request, 'zadmin/settings.html', {'settings_dict': settings_dict})
def terms(request): form = forms.DevAgreementForm({"read_dev_agreement": True}, instance=request.user) if request.POST and form.is_valid(): form.save() log.info("Dev agreement agreed for user: %s" % request.user.pk) if request.GET.get("to") and request.GET["to"].startswith("/"): return redirect(request.GET["to"]) messages.success(request, _("Terms of service accepted.")) return render( request, "developers/terms.html", {"accepted": request.user.read_dev_agreement, "agreement_form": form} )
def upload_detail(request, uuid, format='html'): upload = get_object_or_404(FileUpload, uuid=uuid) if format == 'json' or request.is_ajax(): return json_upload_detail(request, upload) validate_url = reverse('mkt.developers.standalone_upload_detail', args=['hosted', upload.uuid]) return render(request, 'developers/validation.html', dict(validate_url=validate_url, filename=upload.name, timestamp=upload.created))
def motd(request): form = None motd = unmemoized_get_config('mkt_reviewers_motd') if acl.action_allowed(request, 'AppReviewerMOTD', 'Edit'): form = MOTDForm(request.POST or None, initial={'motd': motd}) if form and request.method == 'POST' and form.is_valid(): set_config(u'mkt_reviewers_motd', form.cleaned_data['motd']) messages.success(request, _('Changes successfully saved.')) return redirect(reverse('reviewers.apps.motd')) data = context(request, form=form) return render(request, 'reviewers/motd.html', data)
def proceed(request): """ This is a fake "Terms" view that we overlay the login. We link here from the Developer Hub landing page. """ if request.user.is_authenticated(): return submit(request) agreement_form = forms.DevAgreementForm({'read_dev_agreement': True}, instance=None, request=request) return render(request, 'submit/terms.html', {'step': 'terms', 'agreement_form': agreement_form, 'proceed': True})
def login(request, template=None): if 'to' in request.GET: request = _clean_next_url(request) data = { 'to': request.GET.get('to') } if request.user.is_authenticated(): return http.HttpResponseRedirect( request.GET.get('to', settings.LOGIN_REDIRECT_URL)) return render(request, 'developers/login.html', data)
def terms(request): form = forms.DevAgreementForm({'read_dev_agreement': True}, instance=request.user) if request.POST and form.is_valid(): form.save() log.info('Dev agreement agreed for user: %s' % request.user.pk) if request.GET.get('to') and request.GET['to'].startswith('/'): return redirect(request.GET['to']) messages.success(request, _('Terms of service accepted.')) return render(request, 'developers/terms.html', {'accepted': request.user.read_dev_agreement, 'agreement_form': form})
def website_edit(request, addon_id): website = get_object_or_404(Website, pk=addon_id) form = WebsiteForm(request.POST or None, request=request, instance=website) if request.method == 'POST' and form.is_valid(): form.save() messages.success(request, _('Website saved.')) return redirect(reverse('lookup.website_summary', args=[website.pk])) return render(request, 'lookup/website_edit.html', { 'website': website, 'form': form, })
def user_purchases(request, user_id): """Shows the purchase page for another user.""" user = get_object_or_404(UserProfile, pk=user_id) is_admin = acl.action_allowed(request, 'Users', 'Edit') products = purchase_list(request, user) return render( request, 'lookup/user_purchases.html', { 'pager': products, 'account': user, 'is_admin': is_admin, 'single': bool(None), 'show_link': False })
def manifest(request): form = forms.NewWebappForm(request.POST or None, request=request) features_form = forms.AppFeaturesForm(request.POST or None) features_form_valid = features_form.is_valid() if (request.method == 'POST' and form.is_valid() and features_form_valid): upload = form.cleaned_data['upload'] addon = Webapp.from_upload(upload, is_packaged=form.is_packaged()) file_obj = addon.latest_version.all_files[0] if form.is_packaged(): validation = json.loads(upload.validation) escalate_prerelease_permissions( addon, validation, addon.latest_version) # Set the device type. for device in form.get_devices(): addon.addondevicetype_set.get_or_create( device_type=device.id) # Set the premium type, only bother if it's not free. premium = form.get_paid() if premium: addon.update(premium_type=premium) if addon.has_icon_in_manifest(file_obj): # Fetch the icon, do polling. addon.update(icon_type='image/png') else: # In this case there is no need to do any polling. addon.update(icon_type='') AddonUser(addon=addon, user=request.user).save() # Checking it once. Checking it twice. AppSubmissionChecklist.objects.create(addon=addon, terms=True, manifest=True, details=False) # Create feature profile. addon.latest_version.features.update(**features_form.cleaned_data) tasks.fetch_icon.delay(addon.pk, file_obj.pk) return redirect('submit.app.details', addon.app_slug) return render(request, 'submit/manifest.html', {'step': 'manifest', 'features_form': features_form, 'form': form, 'PLATFORMS_NAMES': PLATFORMS_NAMES})
def terms(request): # If dev has already agreed, continue to next step. if request.user.is_authenticated() and request.user.read_dev_agreement: return manifest(request) agreement_form = forms.DevAgreementForm( request.POST or {'read_dev_agreement': True}, instance=request.user, request=request) if request.POST and agreement_form.is_valid(): agreement_form.save() return redirect('submit.app') return render(request, 'submit/terms.html', {'step': 'terms', 'agreement_form': agreement_form})
def manifest_revalidation(request): if request.method == 'POST': # Collect the apps to revalidate. qs = Q(is_packaged=False, status=mkt.STATUS_PUBLIC, disabled_by_user=False) webapp_pks = Webapp.objects.filter(qs).values_list('pk', flat=True) for pks in chunked(webapp_pks, 100): update_manifests.delay(list(pks), check_hash=False) messages.success(request, 'Manifest revalidation queued') return render(request, 'zadmin/manifest.html')
def payment_accounts_form(request): webapp = get_object_or_404(Webapp, app_slug=request.GET.get('app_slug')) provider = get_provider(name=request.GET.get('provider')) account_list_formset = forms_payments.AccountListFormSet( provider_data=[{ 'user': request.user, 'addon': webapp, 'provider': p } for p in get_providers()]) account_list_form = next(form for form in account_list_formset.forms if form.provider.name == provider.name) return render(request, 'developers/payments/includes/bango_accounts_form.html', {'account_list_form': account_list_form})
def moderatelog(request): form = ModerateLogForm(request.GET) modlog = ActivityLog.objects.editor_events() if form.is_valid(): if form.cleaned_data['start']: modlog = modlog.filter(created__gte=form.cleaned_data['start']) if form.cleaned_data['end']: modlog = modlog.filter(created__lt=form.cleaned_data['end']) if form.cleaned_data['search']: modlog = modlog.filter(action=form.cleaned_data['search'].id) pager = paginate(request, modlog, 50) data = context(request, form=form, pager=pager, tab='moderatelog') return render(request, 'reviewers/moderatelog.html', data)