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