new format of cwiczenie wybor
[edumed.git] / wtem / management / commands / wtem_send_keys.py
1 # -*- coding: utf-8 -*-
2
3 from optparse import make_option
4
5 from django.core.management.base import BaseCommand
6 from django.conf import settings
7 from wtem.management.commands import send_mail
8 from django.template.loader import render_to_string
9
10 from wtem.models import Submission, DEBUG_KEY
11
12
13 class Command(BaseCommand):
14     help = 'Sends personalized links to WTEM contestants'
15     args = '<email_address1>, <email_address2>, ...'
16
17     option_list = BaseCommand.option_list + (
18         make_option(
19             '--all',
20             action='store_true',
21             dest='all',
22             default=False,
23             help='Use all available submissions'),
24         make_option(
25             '--force',
26             action='store_true',
27             dest='force',
28             default=False,
29             help='Force sending key even if one was already sent')
30         )
31
32     def handle(self, *args, **options):
33         if len(args) or options['all']:
34             return self.send_keys(*args, **options)
35         self.stdout.write('No submissions selected')
36
37     def send_keys(self, *args, **options):
38         sent = 0
39         skipped = 0
40         failed = 0
41
42         submissions = Submission.objects.all()
43         if not options['force']:
44             submissions = submissions.filter(key_sent=False)
45         if len(args):
46             submissions = submissions.filter(email__in=args)
47
48         for submission in submissions:
49             assert len(submission.key) == 30 or (settings.DEBUG and submission.key == DEBUG_KEY)
50
51             try:
52                 self.send_key(submission)
53             except Exception as e:
54                 failed += 1
55                 self.stdout.write('failed sending to: ' + submission.email + ' - ' + str(e))
56             else:
57                 submission.key_sent = True
58                 submission.save()
59                 sent += 1
60                 self.stdout.write('key sent to: ' + submission.email)
61
62         self.stdout.write('sent: ' + str(sent))
63
64     def send_key(self, submission):
65         self.stdout.write('>>> sending to ' + submission.email)
66         send_mail(
67             subject="WLEM - Twój link do egzaminu",
68             body=render_to_string('wtem/email_key.txt', dict(submission=submission)),
69             to=[submission.email])