forked from learningequality/kolibri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
importchannel.py
247 lines (223 loc) · 8.77 KB
/
importchannel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import logging
import os
from django.core.management.base import CommandError
from le_utils.constants import content_kinds
from ...utils import channel_import
from ...utils import paths
from ...utils import transfer
from ...utils.annotation import update_content_metadata
from kolibri.core.content.models import ContentNode
from kolibri.core.content.utils.importability_annotation import clear_channel_stats
from kolibri.core.errors import KolibriUpgradeError
from kolibri.core.tasks.management.commands.base import AsyncCommand
from kolibri.utils import conf
logger = logging.getLogger(__name__)
# constants to specify the transfer method to be used
DOWNLOAD_METHOD = "download"
COPY_METHOD = "copy"
def import_channel_by_id(channel_id, cancel_check, contentfolder=None):
try:
return channel_import.import_channel_from_local_db(
channel_id, cancel_check=cancel_check, contentfolder=contentfolder
)
except channel_import.InvalidSchemaVersionError:
raise CommandError(
"Database file had an invalid database schema, the file may be corrupted or have been modified."
)
except channel_import.FutureSchemaError:
raise KolibriUpgradeError(
"Database file uses a future database schema that this version of Kolibri does not support."
)
class Command(AsyncCommand):
def add_arguments(self, parser):
# let's save the parser in case we need to print a help statement
self._parser = parser
# see `importcontent` management command for explanation of how we're using subparsers
subparsers = parser.add_subparsers(
dest="command", help="The following subcommands are available."
)
network_subparser = subparsers.add_parser(
name="network",
cmd=self,
help="Download the given channel through the network.",
)
network_subparser.add_argument(
"channel_id",
type=str,
help="Download the database for the given channel_id.",
)
default_studio_url = conf.OPTIONS["Urls"]["CENTRAL_CONTENT_BASE_URL"]
network_subparser.add_argument(
"--baseurl",
type=str,
default=default_studio_url,
help="The host we will download the content from. Defaults to {}".format(
default_studio_url
),
)
network_subparser.add_argument(
"--no_upgrade",
action="store_true",
help="Only download database to an upgrade file path.",
)
network_subparser.add_argument(
"--content_dir",
type=str,
default=paths.get_content_dir_path(),
help="Download the database to the given content dir.",
)
local_subparser = subparsers.add_parser(
name="disk", cmd=self, help="Copy the content from the given folder."
)
local_subparser.add_argument(
"channel_id",
type=str,
help="Import this channel id from the given directory.",
)
local_subparser.add_argument(
"directory", type=str, help="Import content from this directory."
)
local_subparser.add_argument(
"--no_upgrade",
action="store_true",
help="Only download database to an upgrade file path.",
)
local_subparser.add_argument(
"--content_dir",
type=str,
default=paths.get_content_dir_path(),
help="Download the database to the given content dir.",
)
def download_channel(self, channel_id, baseurl, no_upgrade, content_dir):
logger.info("Downloading data for channel id {}".format(channel_id))
self._transfer(
DOWNLOAD_METHOD,
channel_id,
baseurl,
no_upgrade=no_upgrade,
content_dir=content_dir,
)
def copy_channel(self, channel_id, path, no_upgrade, content_dir):
logger.info("Copying in data for channel id {}".format(channel_id))
self._transfer(
COPY_METHOD,
channel_id,
path=path,
no_upgrade=no_upgrade,
content_dir=content_dir,
)
def _transfer(
self,
method,
channel_id,
baseurl=None,
path=None,
no_upgrade=False,
content_dir=None,
):
new_channel_dest = paths.get_upgrade_content_database_file_path(
channel_id, contentfolder=content_dir
)
dest = (
new_channel_dest
if no_upgrade
else paths.get_content_database_file_path(
channel_id, contentfolder=content_dir
)
)
# if new channel version db has previously been downloaded, just copy it over
if os.path.exists(new_channel_dest) and not no_upgrade:
method = COPY_METHOD
# determine where we're downloading/copying from, and create appropriate transfer object
if method == DOWNLOAD_METHOD:
url = paths.get_content_database_file_url(channel_id, baseurl=baseurl)
logger.debug("URL to fetch: {}".format(url))
filetransfer = transfer.FileDownload(
url, dest, cancel_check=self.is_cancelled
)
elif method == COPY_METHOD:
# if there is a new channel version db, set that as source path
srcpath = (
new_channel_dest
if os.path.exists(new_channel_dest)
else paths.get_content_database_file_path(channel_id, datafolder=path)
)
filetransfer = transfer.FileCopy(
srcpath, dest, cancel_check=self.is_cancelled
)
logger.debug("Destination: {}".format(dest))
try:
self._start_file_transfer(
filetransfer,
channel_id,
dest,
no_upgrade=no_upgrade,
contentfolder=content_dir,
)
except transfer.TransferCanceled:
pass
if self.is_cancelled():
try:
os.remove(dest)
except OSError as e:
logger.info(
"Tried to remove {}, but exception {} occurred.".format(dest, e)
)
self.cancel()
# if we are trying to upgrade, remove new channel db
if os.path.exists(new_channel_dest) and not no_upgrade:
os.remove(new_channel_dest)
def _start_file_transfer(
self, filetransfer, channel_id, dest, no_upgrade=False, contentfolder=None
):
progress_extra_data = {"channel_id": channel_id}
with filetransfer, self.start_progress(
total=filetransfer.total_size
) as progress_update:
for chunk in filetransfer:
progress_update(len(chunk), progress_extra_data)
# if upgrading, import the channel
if not no_upgrade:
try:
# evaluate list so we have the current node ids
node_ids = list(
ContentNode.objects.filter(
channel_id=channel_id, available=True
)
.exclude(kind=content_kinds.TOPIC)
.values_list("id", flat=True)
)
import_ran = import_channel_by_id(
channel_id, self.is_cancelled, contentfolder
)
if node_ids and import_ran:
# annotate default channel db based on previously annotated leaf nodes
update_content_metadata(channel_id, node_ids=node_ids)
if import_ran:
# Clear any previously set channel availability stats for this channel
clear_channel_stats(channel_id)
except channel_import.ImportCancelError:
# This will only occur if is_cancelled is True.
pass
def handle_async(self, *args, **options):
if options["command"] == "network":
self.download_channel(
options["channel_id"],
options["baseurl"],
options["no_upgrade"],
options["content_dir"],
)
elif options["command"] == "disk":
self.copy_channel(
options["channel_id"],
options["directory"],
options["no_upgrade"],
options["content_dir"],
)
else:
self._parser.print_help()
raise CommandError(
"Please give a valid subcommand. You gave: {}".format(
options["command"]
)
)