Skip to content

Instantly share code, notes, and snippets.

@zeehio
Created October 16, 2015 10:09
Show Gist options
  • Save zeehio/39cc4b231f28e8dcf90a to your computer and use it in GitHub Desktop.
Save zeehio/39cc4b231f28e8dcf90a to your computer and use it in GitHub Desktop.
Copy files from moodle mbz into an ordered directory tree.
#!/usr/bin/env python3
"""
Moodle provides a backup system for courses offering an mbz file. This is a zip file with
all the resources and files included and the needed metadata about the files encoded in XML.
This script gets an unzipped mbz directory and copies all the files from the course into
a directory tree with the same layout than the original moodle course.
unzip my_moodle_backup.zip
extract_moodle_files.py --source my_moodle_backup_FILES --destination sorted_course
"""
# ChangeLog:
#
# [2015-10-16] Sergio Oller
# - Ported to python-3.4
# - Added command line arguments
#
# [2012-11-29] Jon Reades
# - Script hosted at: http://www.reades.com/2012/11/29/mb-archives/
#
import xml.etree.ElementTree as etree
import fnmatch
import shutil
import os
import re
import argparse
def parse_arguments():
parser = argparse.ArgumentParser(description='Sort files from moodle backup.',
usage='extract_moodle_files.py --source my_moodle_backup_FILES --destination sorted_course')
parser.add_argument('--source', dest='source', type=str,
help='path to extracted backup files')
parser.add_argument('--destination', dest='destination', type=str,
help='path to destination directory')
args = parser.parse_args()
if args.source is None:
raise ValueError("Path to extracted backup files not given. Use --source /path/to/extracted_mbz_FILES/")
if args.destination is None:
raise ValueError("Path to destination files not given. Use --destination /path/to/a/directory")
return args
def locate(pattern, root=os.curdir):
'''Locate all files matching supplied filename pattern in and below
supplied root directory.'''
for path, dirs, files in os.walk(os.path.abspath(root)):
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
def main(destination, source, pattern):
tree = etree.parse(source + 'files.xml')
root = tree.getroot()
os.makedirs(destination, exist_ok=True)
print("Root: ", root)
print(destination)
for rsrc in root:
# print "Child id: ", rsrc.attrib
fhash = rsrc.find('contenthash').text
filepath = rsrc.find('filepath').text
if filepath.startswith("/"):
filepath = filepath[1:]
fname = rsrc.find('filename').text
os.makedirs(os.path.join(destination, filepath), exist_ok=True)
# If file name is just a directory, skip it:
if fname == ".":
continue
if pattern is not None:
hit = pattern.search(fname)
else:
hit = True
if hit:
# print "\tMatch: ", hit.group(1)
files = locate(fhash, source)
# print "\tFiles: ", files
for x in files:
print("Copying: ", x)
shutil.copyfile(x, os.path.join(destination, filepath, fname))
else:
print("File excluded by pattern: '", fname, "'", sep="")
if __name__ == "__main__":
args = parse_arguments()
#pattern = re.compile('^\s*(.+\.(?:pdf|png|zip|rtf|sav|mp3|mht|por|xlsx?|docx?|pptx?))\s*$', flags=re.IGNORECASE)
pattern = None
main(args.destination, args.source, pattern)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment