forked from WeblateOrg/website
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathviews.py
705 lines (602 loc) · 22.7 KB
/
views.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
#
# Copyright © 2012–2020 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
import django.views.defaults
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.models import User
from django.core.exceptions import SuspiciousOperation, ValidationError
from django.core.mail import mail_admins, send_mail
from django.core.signing import BadSignature, SignatureExpired, loads
from django.db import transaction
from django.db.models import Q
from django.http import Http404, HttpResponse, HttpResponseBadRequest, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.translation import gettext, override
from django.views.decorators.cache import cache_control
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.views.generic.dates import ArchiveIndexView
from django.views.generic.detail import DetailView, SingleObjectMixin
from django.views.generic.edit import FormView, UpdateView
from payments.backends import get_backend, list_backends
from payments.forms import CustomerForm
from payments.models import Customer, Payment
from payments.validators import cache_vies_data, validate_vatin
from weblate_web.forms import (
DonateForm,
EditImageForm,
EditLinkForm,
EditNameForm,
MethodForm,
SubscribeForm,
)
from weblate_web.models import (
PAYMENTS_ORIGIN,
TOPIC_DICT,
Donation,
Package,
Post,
Service,
Subscription,
process_donation,
process_subscription,
)
from weblate_web.remote import get_activity
def get_customer(request):
return Customer.objects.get_or_create(
origin=PAYMENTS_ORIGIN,
user_id=request.user.id,
defaults={"email": request.user.email},
)[0]
def show_form_errors(request, form):
"""Show all form errors as a message."""
for error in form.non_field_errors():
messages.error(request, error)
for field in form:
for error in field.errors:
messages.error(
request,
gettext("Error in parameter %(field)s: %(error)s")
% {"field": field.name, "error": error},
)
@require_POST
@csrf_exempt
def api_user(request):
try:
payload = loads(
request.POST.get("payload", ""),
key=settings.PAYMENT_SECRET,
max_age=300,
salt="weblate.user",
)
except (BadSignature, SignatureExpired) as error:
return HttpResponseBadRequest(str(error))
try:
user = User.objects.get(username=payload["username"])
except User.DoesNotExist:
return JsonResponse({"status": "User not found"})
# Cycle unused passwords to invalidate existing sessions
if not user.has_usable_password():
user.set_unusable_password()
# Update attributes
for key, value in payload.get("changes", {}).items():
if key not in ("username", "email", "last_name"):
continue
setattr(user, key, value)
# Save to the database
user.save()
return JsonResponse({"status": "User updated"})
@require_POST
@csrf_exempt
def api_hosted(request):
try:
payload = loads(
request.POST.get("payload", ""),
key=settings.PAYMENT_SECRET,
max_age=300,
salt="weblate.hosted",
)
except (BadSignature, SignatureExpired) as error:
return HttpResponseBadRequest(str(error))
# Get/create service for this billing
service = Service.objects.get_or_create(hosted_billing=payload["billing"])[0]
# TODO: This is temporary hack for payments migration period
payments = []
for payment in Payment.objects.order_by("end").iterator():
if payment.extra.get("billing", -1) == payload["billing"]:
payments.append(payment.pk)
if payments:
# Create/update subscription
subscription = Subscription.objects.get_or_create(
service=service,
package=payload["package"],
defaults={"payment": payments[-1]},
)[0]
if subscription.payment != payments[-1]:
subscription.payment = payments[-1]
subscription.save(update_fields=["payment"])
# Link past payments
for payment in payments[:-1]:
subscription.pastpayment_set.get_or_create(payment=payment)
# Link users which are supposed to have access
for user in payload["users"]:
service.users.add(User.objects.get_or_create(username=user)[0])
# Collect stats
service.report_set.create(
site_url="https://hosted.weblate.org/",
site_title="Hosted Weblate",
projects=payload["projects"],
components=payload["components"],
languages=payload["languages"],
source_strings=payload["source_strings"],
version=request.headers["User-Agent"].split("/", 1)[1],
)
service.update_status()
return JsonResponse(
data={
"name": service.status,
"expiry": service.expires,
"backup_repository": service.backup_repository,
"in_limits": service.check_in_limits(),
}
)
@require_POST
@csrf_exempt
def api_support(request):
service = get_object_or_404(Service, secret=request.POST.get("secret", ""))
service.report_set.create(
site_url=request.POST.get("site_url", ""),
site_title=request.POST.get("site_title", ""),
ssh_key=request.POST.get("ssh_key", ""),
users=request.POST.get("users", 0),
projects=request.POST.get("projects", 0),
components=request.POST.get("components", 0),
languages=request.POST.get("languages", 0),
source_strings=request.POST.get("source_strings", 0),
version=request.headers["User-Agent"].split("/", 1)[1],
)
service.update_status()
service.create_backup()
return JsonResponse(
data={
"name": service.status,
"expiry": service.expires,
"backup_repository": service.backup_repository,
"in_limits": service.check_in_limits(),
}
)
@require_POST
def fetch_vat(request):
if "payment" not in request.POST or "vat" not in request.POST:
raise SuspiciousOperation("Missing needed parameters")
payment = Payment.objects.filter(pk=request.POST["payment"], state=Payment.NEW)
if not payment.exists():
raise SuspiciousOperation("Already processed payment")
vat = cache_vies_data(request.POST["vat"])
return JsonResponse(data=getattr(vat, "vies_data", {"valid": False}))
class PaymentView(FormView, SingleObjectMixin):
model = Payment
form_class = MethodForm
template_name = "payment/payment.html"
check_customer = True
def redirect_origin(self):
return redirect(
"{}?payment={}".format(self.object.customer.origin, self.object.pk)
)
def get_context_data(self, **kwargs):
kwargs = super().get_context_data(**kwargs)
kwargs["can_pay"] = self.can_pay
kwargs["backends"] = [x(self.object) for x in list_backends()]
return kwargs
def validate_customer(self, customer):
if not self.check_customer:
return None
if customer.is_empty:
messages.info(
self.request,
gettext(
"Please provide your billing information to "
"complete the payment."
),
)
return redirect("payment-customer", pk=self.object.pk)
# This should not happen, but apparently validation service is
# often broken, so whitelist repeating payments
if customer.vat and not self.object.repeat:
try:
validate_vatin(customer.vat)
except ValidationError:
messages.warning(
self.request,
gettext("The VAT ID is no longer valid, please update it."),
)
return redirect("payment-customer", pk=self.object.pk)
return None
def dispatch(self, request, *args, **kwargs):
with transaction.atomic(using="payments_db"):
self.object = self.get_object()
customer = self.object.customer
self.can_pay = not customer.is_empty
# Redirect already processed payments to origin in case
# the web redirect was aborted
if self.object.state != Payment.NEW:
return self.redirect_origin()
result = self.validate_customer(customer)
if result is not None:
return result
return super().dispatch(request, *args, **kwargs)
def form_invalid(self, form):
if self.form_class == MethodForm:
messages.error(self.request, gettext("Please choose a payment method."))
else:
messages.error(
self.request,
gettext(
"Please provide your billing information to "
"complete the payment."
),
)
return super().form_invalid(form)
def form_valid(self, form):
if not self.can_pay:
return redirect("payment", pk=self.object.pk)
# Actualy call the payment backend
method = form.cleaned_data["method"]
backend = get_backend(method)(self.object)
result = backend.initiate(
self.request,
self.request.build_absolute_uri(
reverse("payment", kwargs={"pk": self.object.pk})
),
self.request.build_absolute_uri(
reverse("payment-complete", kwargs={"pk": self.object.pk})
),
)
if result is not None:
return result
backend.complete(self.request)
return self.redirect_origin()
class CustomerView(PaymentView):
form_class = CustomerForm
template_name = "payment/customer.html"
check_customer = False
def form_valid(self, form):
form.save()
return redirect("payment", pk=self.object.pk)
def get_form_kwargs(self):
"""Return the keyword arguments for instantiating the form."""
kwargs = super().get_form_kwargs()
kwargs["instance"] = self.object.customer
return kwargs
class CompleteView(PaymentView):
def dispatch(self, request, *args, **kwargs):
with transaction.atomic(using="payments_db"):
self.object = self.get_object()
# User should choose method for new payment
if self.object.state == Payment.NEW:
return redirect("payment", pk=self.object.pk)
# Get backend and refetch payment from the database
backend = get_backend(self.object.backend)(self.object)
# Allow reprocessing of rejected payments. User might choose
# to retry in the payment gateway and previously rejected payment
# can be now completed.
if backend.payment.state not in (Payment.PENDING, Payment.REJECTED):
return self.redirect_origin()
backend.complete(self.request)
# If payment is still pending, display info page
if backend.payment.state == Payment.PENDING:
return render(
request,
"payment/pending.html",
{"object": backend.payment, "backend": backend},
)
return self.redirect_origin()
@method_decorator(login_required, name="dispatch")
class DonateView(FormView):
form_class = DonateForm
template_name = "donate/form.html"
def get_form_kwargs(self):
result = super().get_form_kwargs()
result["initial"] = self.request.GET
return result
def redirect_payment(self, **kwargs):
kwargs["customer"] = get_customer(self.request)
payment = Payment.objects.create(**kwargs)
return redirect(payment.get_payment_url())
def form_invalid(self, form):
show_form_errors(self.request, form)
return super().form_invalid(form)
def form_valid(self, form):
data = form.cleaned_data
tmp = Donation(reward=int(data["reward"]))
with override("en"):
description = tmp.get_payment_description()
return self.redirect_payment(
amount=data["amount"],
amount_fixed=True,
description=description,
recurring=data["recurring"],
extra={"reward": data["reward"]},
)
@login_required
def process_payment(request):
try:
payment = Payment.objects.get(
pk=request.GET["payment"],
customer__origin=PAYMENTS_ORIGIN,
customer__user_id=request.user.id,
)
except (KeyError, Payment.DoesNotExist):
return redirect(reverse("user"))
# Create donation
if payment.state in (Payment.NEW, Payment.PENDING):
messages.error(request, gettext("Payment not yet processed, please retry."))
elif payment.state == Payment.REJECTED:
messages.error(
request,
gettext("The payment was rejected: {}").format(
payment.details.get("reject_reason", gettext("Unknown reason"))
),
)
elif payment.state == Payment.ACCEPTED:
if "subscription" in payment.extra:
messages.success(request, gettext("Thank you for your subscription."))
process_subscription(payment)
else:
messages.success(request, gettext("Thank you for your donation."))
donation = process_donation(payment)
if donation.reward:
return redirect(donation)
return redirect(reverse("user"))
@login_required
def download_invoice(request, pk):
# Allow downloading own invoices of pending ones (for proforma invoices)
payment = get_object_or_404(
Payment,
(Q(customer__origin=PAYMENTS_ORIGIN) & Q(customer__user_id=request.user.id))
| Q(state=Payment.PENDING),
pk=pk,
)
if not payment.invoice_filename_valid:
raise Http404("File {0} does not exist!".format(payment.invoice_filename))
with open(payment.invoice_full_filename, "rb") as handle:
data = handle.read()
response = HttpResponse(data, content_type="application/pdf")
response["Content-Disposition"] = "attachment; filename={0}".format(
payment.invoice_filename
)
response["Content-Length"] = len(data)
return response
@require_POST
@login_required
def disable_repeat(request, pk):
donation = get_object_or_404(Donation, pk=pk, user=request.user)
payment = donation.payment_obj
payment.recurring = ""
payment.save()
return redirect(reverse("user"))
@method_decorator(login_required, name="dispatch")
class EditLinkView(UpdateView):
template_name = "donate/edit.html"
success_url = "/user/"
def get_form_class(self):
reward = self.object.reward
if reward == 2:
return EditLinkForm
if reward == 3:
return EditImageForm
return EditNameForm
def get_queryset(self):
return Donation.objects.filter(user=self.request.user, reward__gt=0)
def form_valid(self, form):
"""If the form is valid, save the associated model."""
mail_admins(
"Weblate: link changed",
"New link: {link_url}\nNew text: {link_text}\n".format(
link_url=form.cleaned_data.get("link_url", "N/A"),
link_text=form.cleaned_data.get("link_text", "N/A"),
),
)
return super().form_valid(form)
@require_POST
def subscribe(request, name):
addresses = {
"hosted": "[email protected]",
"users": "[email protected]",
}
form = SubscribeForm(request.POST)
if form.is_valid():
send_mail(
"subscribe",
"subscribe",
form.cleaned_data["email"],
[addresses[name]],
fail_silently=True,
)
messages.success(
request,
gettext(
"Subscription requested, " "all you have to do is confirm the email."
),
)
else:
messages.error(request, gettext("Could not process subscription request."))
return redirect("support")
class NewsArchiveView(ArchiveIndexView):
model = Post
date_field = "timestamp"
paginate_by = 10
ordering = ("-timestamp",)
class NewsView(NewsArchiveView):
paginate_by = 5
template_name = "news.html"
class TopicArchiveView(NewsArchiveView):
def get_queryset(self):
return super().get_queryset().filter(topic=self.kwargs["slug"])
# pylint: disable=arguments-differ
def get_context_data(self, **kwargs):
result = super().get_context_data(**kwargs)
result["topic"] = TOPIC_DICT[self.kwargs["slug"]]
return result
class MilestoneArchiveView(NewsArchiveView):
def get_queryset(self):
return super().get_queryset().filter(milestone=True)
# pylint: disable=arguments-differ
def get_context_data(self, **kwargs):
result = super().get_context_data(**kwargs)
result["topic"] = gettext("Milestones")
return result
class PostView(DetailView):
model = Post
def get_object(self, queryset=None):
result = super().get_object(queryset)
if not self.request.user.is_staff and result.timestamp >= timezone.now():
raise Http404("Future entry")
return result
def get_context_data(self, **kwargs):
kwargs["related"] = (
Post.objects.filter(topic=self.object.topic)
.exclude(pk=self.object.pk)
.order_by("-timestamp")[:3]
)
return kwargs
# pylint: disable=unused-argument
def not_found(request, exception=None):
"""Error handler showing list of available projects."""
return render(request, "404.html", status=404)
def server_error(request):
# pylint: disable=broad-except
"""Error handler for server errors."""
try:
return render(request, "500.html", status=500)
except Exception:
return django.views.defaults.server_error(request)
@cache_control(max_age=3600)
def activity_svg(request):
bars = []
opacities = {0: ".1", 1: ".3", 2: ".5", 3: ".7"}
data = get_activity()
top_count = max(data) if data else 0
for i, count in enumerate(data):
height = int(76 * count / top_count)
item = {
"rx": 2,
"width": 6,
"height": height,
"id": "b{}".format(i),
"x": 10 * i,
"y": 86 - height,
}
if height < 20:
item["fill"] = "#f6664c"
elif height < 45:
item["fill"] = "#38f"
else:
item["fill"] = "#2eccaa"
if i in opacities:
item["opacity"] = opacities[i]
bars.append(item)
return render(
request,
"svg/activity.svg",
{"bars": bars},
content_type="image/svg+xml; charset=utf-8",
)
@require_POST
@login_required
def subscription_disable_repeat(request, pk):
subscription = get_object_or_404(Subscription, pk=pk, service__users=request.user)
payment = subscription.payment_obj
payment.recurring = ""
payment.save()
return redirect(reverse("user"))
@require_POST
@login_required
def service_token(request, pk):
service = get_object_or_404(Service, pk=pk, users=request.user)
service.regenerate()
return redirect(reverse("user"))
@require_POST
@login_required
def service_user(request, pk):
service = get_object_or_404(Service, pk=pk, users=request.user)
try:
user = User.objects.get(email__iexact=request.POST.get("email"))
if "remove" in request.POST:
service.users.remove(user)
else:
service.users.add(user)
except User.DoesNotExist:
messages.error(request, gettext("User not found!"))
return redirect(reverse("user"))
@login_required
@user_passes_test(lambda u: u.is_superuser)
def subscription_view(request, pk):
service = get_object_or_404(Service, pk=pk)
return render(request, "service.html", {"service": service})
@require_POST
@login_required
def subscription_pay(request, pk):
subscription = get_object_or_404(Subscription, pk=pk, service__users=request.user)
if "switch_yearly" in request.POST and subscription.yearly_package:
subscription.package = subscription.yearly_package
subscription.save(update_fields=["package"])
with override("en"):
payment = Payment.objects.create(
amount=subscription.get_amount(),
# pylint: disable=no-member
description="Weblate: {}".format(subscription.get_package_display()),
recurring=subscription.get_repeat(),
extra={"subscription": subscription.pk},
customer=get_customer(request),
)
return redirect(payment.get_payment_url())
@require_POST
@login_required
def donate_pay(request, pk):
donation = get_object_or_404(Donation, pk=pk, user=request.user)
with override("en"):
payment = Payment.objects.create(
amount=donation.get_amount(),
description=donation.get_payment_description(),
recurring=donation.payment_obj.recurring,
extra={"donation": donation.pk},
customer=get_customer(request),
)
return redirect(payment.get_payment_url())
@login_required
def subscription_new(request):
plan = request.GET.get("plan")
if not Package.objects.filter(name=plan).exists():
return redirect("support")
subscription = Subscription(package=plan)
with override("en"):
payment = Payment.objects.create(
amount=subscription.get_amount(),
# pylint: disable=no-member
description="Weblate: {}".format(subscription.get_package_display()),
recurring=subscription.get_repeat(),
extra={"subscription": plan, "service": request.GET.get("service")},
customer=get_customer(request),
)
return redirect(payment.get_payment_url())