turniej -> olimpiada
[edumed.git] / catalogue / management / commands / importlessons.py
1 # -*- coding: utf-8 -*-
2 # This file is part of EduMed, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 import os
6 import sys
7 from optparse import make_option
8
9 from django.core.management.base import BaseCommand
10 from django.db import transaction
11
12 from catalogue.models import Lesson, Section
13 from librarian import IOFile
14
15
16 class Command(BaseCommand):
17     option_list = BaseCommand.option_list + (
18         make_option('-q', '--quiet', action='store_false', dest='verbose', default=True,
19                     help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'),
20         make_option('-a', '--attachments', dest='attachments', metavar="PATH", default='materialy',
21                     help='Attachments dir path.'),
22         make_option('--ignore-incomplete', action='store_true', dest='ignore_incomplete', default=False,
23                     help='Attachments dir path.'),
24     )
25     help = 'Imports lessons from the specified directories.'
26     args = 'directory [directory ...]'
27
28     def __init__(self):
29         super(Command, self).__init__()
30         self.options = None
31         self.levels = None
32
33     @staticmethod
34     def all_attachments(path):
35         files = {}
36
37         def read_dir(path):
38             for name in os.listdir(path):
39                 fullname = os.path.join(path, name)
40                 if os.path.isdir(fullname):
41                     read_dir(fullname)
42                 else:
43                     f = IOFile.from_filename(fullname)
44                     files[name.decode('utf-8')] = f
45                     files.setdefault(name.replace(" ", "").decode('utf-8'), f)
46
47         read_dir(path)
48         return files
49
50     @transaction.atomic
51     def handle(self, *directories, **options):
52
53         self.levels = set()
54
55         curdir = os.path.abspath(os.curdir)
56         self.options = options
57
58         files_imported = 0
59         files_skipped = 0
60
61         for dir_name in directories:
62             abs_dir = os.path.join(curdir, dir_name)
63             if not os.path.isdir(abs_dir):
64                 print self.style.ERROR("%s: Not a directory. Skipping." % abs_dir)
65             else:
66                 files_imported_dir, files_skipped_dir = self.import_from_dir(abs_dir)
67                 files_imported += files_imported_dir
68                 files_skipped += files_skipped_dir
69
70         if self.levels:
71             print "Rebuilding level packages:"
72             for level in self.levels:
73                 print level.name
74                 level.build_packages()
75
76         # Print results
77         print
78         print "Results: %d files imported, %d skipped, %d total." % (
79             files_imported, files_skipped, files_imported + files_skipped)
80         print
81
82     def import_from_dir(self, abs_dir):
83         verbose = self.options.get('verbose')
84         files_imported = 0
85         files_skipped = 0
86         att_dir = os.path.join(abs_dir, self.options['attachments'])
87         attachments = self.all_attachments(att_dir)
88         # files queue
89         files = sorted(os.listdir(abs_dir))
90         postponed = {}
91         ignore_incomplete = set()
92         while files:
93             file_name = files.pop(0)
94             file_path = os.path.join(abs_dir, file_name)
95             file_base, ext = os.path.splitext(file_path)
96
97             # Skip files that are not XML files
98             if not ext == '.xml':
99                 continue
100
101             if verbose > 0:
102                 print "Parsing '%s'" % file_path
103             else:
104                 sys.stdout.write('.')
105                 sys.stdout.flush()
106
107             try:
108                 iofile = IOFile.from_filename(file_path)
109                 iofile.attachments = attachments
110                 lesson = Lesson.publish(iofile, file_name in ignore_incomplete)
111             except Section.IncompleteError:
112                 if file_name not in postponed or postponed[file_name] < files_imported:
113                     # Push it back into the queue, maybe the missing lessons will show up.
114                     if verbose > 0:
115                         print self.style.NOTICE('Waiting for missing lessons.')
116                     files.append(file_name)
117                     postponed[file_name] = files_imported
118                 elif self.options['ignore_incomplete'] and file_name not in ignore_incomplete:
119                     files.append(file_name)
120                     ignore_incomplete.add(file_name)
121                     postponed[file_name] = files_imported
122                 else:
123                     # We're in a loop, nothing's being imported - some lesson is really missing.
124                     raise
125             except BaseException:
126                 import traceback
127                 traceback.print_exc()
128                 files_skipped += 1
129             else:
130                 files_imported += 1
131                 if hasattr(lesson, 'level'):
132                     self.levels.add(lesson.level)
133             finally:
134                 if verbose > 0:
135                     print
136         return files_imported, files_skipped