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