new emails
[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         if not os.path.isdir(path):
37             return files
38
39         def read_dir(path):
40             for name in os.listdir(path):
41                 fullname = os.path.join(path, name)
42                 if os.path.isdir(fullname):
43                     read_dir(fullname)
44                 else:
45                     f = IOFile.from_filename(fullname)
46                     files[name.decode('utf-8')] = f
47                     files.setdefault(name.replace(" ", "").decode('utf-8'), f)
48
49         read_dir(path)
50         return files
51
52     @transaction.atomic
53     def handle(self, *directories, **options):
54
55         self.levels = set()
56
57         curdir = os.path.abspath(os.curdir)
58         self.options = options
59
60         files_imported = 0
61         files_skipped = 0
62
63         for dir_name in directories:
64             abs_dir = os.path.join(curdir, dir_name)
65             if not os.path.isdir(abs_dir):
66                 print self.style.ERROR("%s: Not a directory. Skipping." % abs_dir)
67             else:
68                 files_imported_dir, files_skipped_dir = self.import_from_dir(abs_dir)
69                 files_imported += files_imported_dir
70                 files_skipped += files_skipped_dir
71
72         if self.levels:
73             print "Rebuilding level packages:"
74             for level in self.levels:
75                 print level.name
76                 level.build_packages()
77
78         # Print results
79         print
80         print "Results: %d files imported, %d skipped, %d total." % (
81             files_imported, files_skipped, files_imported + files_skipped)
82         print
83
84     def import_from_dir(self, abs_dir):
85         verbose = self.options.get('verbose')
86         files_imported = 0
87         files_skipped = 0
88         att_dir = os.path.join(abs_dir, self.options['attachments'])
89         attachments = self.all_attachments(att_dir)
90         # files queue
91         files = sorted(os.listdir(abs_dir))
92         postponed = {}
93         ignore_incomplete = set()
94         while files:
95             file_name = files.pop(0)
96             file_path = os.path.join(abs_dir, file_name)
97             file_base, ext = os.path.splitext(file_path)
98
99             if os.path.isdir(file_path):
100                 dir_imported, dir_skipped = self.import_from_dir(file_path)
101                 files_imported += dir_imported
102                 files_skipped += files_skipped
103                 continue
104
105             # Skip files that are not XML files
106             if not ext == '.xml':
107                 continue
108
109             if verbose > 0:
110                 print "Parsing '%s'" % file_path
111             else:
112                 sys.stdout.write('.')
113                 sys.stdout.flush()
114
115             try:
116                 iofile = IOFile.from_filename(file_path)
117                 iofile.attachments = attachments
118                 lesson = Lesson.publish(iofile, file_name in ignore_incomplete)
119             except Section.IncompleteError:
120                 if file_name not in postponed or postponed[file_name] < files_imported:
121                     # Push it back into the queue, maybe the missing lessons will show up.
122                     if verbose > 0:
123                         print self.style.NOTICE('Waiting for missing lessons.')
124                     files.append(file_name)
125                     postponed[file_name] = files_imported
126                 elif self.options['ignore_incomplete'] and file_name not in ignore_incomplete:
127                     files.append(file_name)
128                     ignore_incomplete.add(file_name)
129                     postponed[file_name] = files_imported
130                 else:
131                     # We're in a loop, nothing's being imported - some lesson is really missing.
132                     raise
133             except BaseException:
134                 import traceback
135                 traceback.print_exc()
136                 files_skipped += 1
137             else:
138                 files_imported += 1
139                 if hasattr(lesson, 'level'):
140                     self.levels.add(lesson.level)
141             finally:
142                 if verbose > 0:
143                     print
144         return files_imported, files_skipped