1 import os, tarfile, datetime, logging, re
3 from django.core.cache import cache
4 from django.utils.translation import ugettext as _
5 from forum.models import *
6 from forum.settings import APP_URL
7 from forum.templatetags.extra_tags import diff_date
8 import xml.etree.ElementTree
9 from xml.etree import ElementTree as ET
10 from xml.etree.ElementTree import Comment, _encode, ProcessingInstruction, QName, fixtag, _escape_attrib, _escape_cdata
12 CACHE_KEY = "%s_exporter_state" % APP_URL
15 TMP_FOLDER = os.path.join(os.path.dirname(__file__), 'tmp')
16 LAST_BACKUP = os.path.join(TMP_FOLDER, 'backup.tar.gz')
18 def Etree_pretty__write(self, file, node, encoding, namespaces,
19 level=0, identator=" "):
22 file.write(level * identator + "<!-- %s -->" % _escape_cdata(node.text, encoding))
23 elif tag is ProcessingInstruction:
24 file.write("<?%s?>" % _escape_cdata(node.text, encoding))
27 xmlns_items = [] # new namespaces in this scope
29 if isinstance(tag, QName) or tag[:1] == "{":
30 tag, xmlns = fixtag(tag, namespaces)
31 if xmlns: xmlns_items.append(xmlns)
33 raise #_raise_serialization_error(tag)
34 file.write("\n" + level * identator + "<" + _encode(tag, encoding))
35 if items or xmlns_items:
36 items.sort() # lexical order
39 if isinstance(k, QName) or k[:1] == "{":
40 k, xmlns = fixtag(k, namespaces)
41 if xmlns: xmlns_items.append(xmlns)
43 raise #_raise_serialization_error(k)
45 if isinstance(v, QName):
46 v, xmlns = fixtag(v, namespaces)
47 if xmlns: xmlns_items.append(xmlns)
49 raise #_raise_serialization_error(v)
50 file.write(" %s=\"%s\"" % (_encode(k, encoding),
51 _escape_attrib(v, encoding)))
52 for k, v in xmlns_items:
53 file.write(" %s=\"%s\"" % (_encode(k, encoding),
54 _escape_attrib(v, encoding)))
55 if node.text or len(node):
58 file.write(_escape_cdata(node.text.replace("\n", (level + 1) * identator + "\n"), encoding))
60 self._write(file, n, encoding, namespaces, level + 1, identator)
61 if node.text and len(node.text) < 125:
62 file.write("</" + _encode(tag, encoding) + ">")
64 file.write("\n" + level * identator + "</" + _encode(tag, encoding) + ">")
67 for k, v in xmlns_items:
70 file.write(_escape_cdata(node.tail.replace("\n", level * identator + "\n"), encoding))
72 def _add_tag(el, name, content = None):
73 tag = ET.SubElement(el, name)
78 def ET_Element_add_tag(el, tag_name, content = None, **attrs):
79 tag = ET.SubElement(el, tag_name)
82 tag.text = unicode(content)
84 for k, v in attrs.items():
85 tag.set(k, unicode(v))
89 GOOD_TAG_NAME = re.compile("^\w+$")
91 def make_extra(el, extra):
95 if isinstance(extra, dict):
96 for k, v in extra.items():
97 if GOOD_TAG_NAME.match(k):
98 make_extra(el.add(k), v)
100 make_extra(el.add("key", name=k), v)
102 el.text = unicode(extra)
104 def write_to_file(root, tmp, filename):
105 tree = ET.ElementTree(root)
106 tree.write(os.path.join(tmp, filename), encoding='UTF-8')
108 def create_targz(tmp, files):
109 if os.path.exists(LAST_BACKUP):
110 os.remove(LAST_BACKUP)
112 t = tarfile.open(name=LAST_BACKUP, mode = 'w:gz')
115 t.add(os.path.join(tmp, f), arcname=f)
121 original__write = xml.etree.ElementTree.ElementTree._write
122 xml.etree.ElementTree.ElementTree._write = Etree_pretty__write
123 xml.etree.ElementTree._ElementInterface.add = ET_Element_add_tag
125 start_time = datetime.datetime.now()
127 anon_data = options.get('anon_data', False)
129 steps = [s for s in EXPORT_STEPS if not (anon_data and s['fn'].is_user_data())]
131 state = dict([(s['id'], {
132 'status': _('Queued'), 'count': s['fn'].count(start_time), 'parsed': 0
133 }) for s in steps] + [
135 'status': _('Starting'), 'count': sum([s['fn'].count(start_time) for s in steps]), 'parsed': 0
139 full_state = dict(running=True, state=state, time_started="")
142 full_state['time_started'] = diff_date(start_time)
143 cache.set(CACHE_KEY, full_state)
147 def ping_state(name):
148 state[name]['parsed'] += 1
149 state['overall']['parsed'] += 1
156 state['overall']['status'] = _('Exporting %s') % s['name']
157 state[name]['status'] = _('Exporting')
159 root, fname = fn(ping, start_time, anon_data)
161 state[name]['status'] = _('Writing temp file')
162 state['overall']['status'] = _('Writing %s temp file') % s['name']
166 write_to_file(root, tmp, fname)
167 state[name]['status'] = _('Done')
177 dump_files.append(run(s['fn'], s['id']))
179 state['overall']['status'] = _('Compressing files')
182 create_targz(tmp, dump_files)
183 full_state['running'] = False
184 full_state['errors'] = False
185 state['overall']['status'] = _('Done')
189 full_state['running'] = False
190 full_state['errors'] = "%s: %s" % (e.__class__.__name__, unicode(e))
194 logging.error("Error executing xml backup: \n %s" % (traceback.format_exc()))
196 xml.etree.ElementTree.ElementTree._write = original__write
197 del xml.etree.ElementTree._ElementInterface.add
199 def exporter_step(queryset, root_tag_name, el_tag_name, name, date_lock=None, user_data=False):
204 return queryset.filter(**{"%s__lte" % date_lock: lock})
207 def decorated(ping, lock, anon_data):
208 root = ET.Element(root_tag_name)
210 for item in qs(lock).order_by('id').select_related():
211 el = root.add(el_tag_name)
212 fn(item, el, anon_data)
215 return root, "%s.xml" % root_tag_name
218 return qs(lock).count()
223 decorated.count = count
224 decorated.is_user_data = is_user_data
226 EXPORT_STEPS.append(dict(id=root_tag_name, name=name, fn=decorated))
232 @exporter_step(Tag.objects.all(), 'tags', 'tag', _('Tags'))
233 def export_tags(t, el, anon_data):
234 el.add('name', t.name)
236 el.add('author', t.created_by.id)
237 el.add('used', t.used_count)
240 @exporter_step(User.objects.all(), 'users', 'user', _('Users'), 'date_joined', True)
241 def export_users(u, el, anon_data):
243 el.add('username', u.username)
244 el.add('password', u.password)
245 el.add('email', u.email, validated=u.email_isvalid and 'true' or 'false')
246 el.add('joindate', u.date_joined)
248 el.add('firstname', u.first_name)
249 el.add('lastname', u.last_name)
250 el.add('bio', u.about)
251 el.add('location', u.location)
252 el.add('website', u.website)
253 el.add('birthdate', u.date_of_birth)
255 roles = el.add('roles')
258 roles.add('role', 'superuser')
261 roles.add('role', 'moderator')
263 auth = el.add('authKeys')
264 for a in u.auth_keys.all():
265 key = auth.add('key')
266 key.add('provider', a.provider)
267 key.add('key', a.key)
269 el.add('reputation', u.reputation)
273 @exporter_step(Node.objects.all(), 'nodes', 'node', _('Nodes'), 'added_at')
274 def export_nodes(n, el, anon_data):
276 el.add('type', n.node_type)
279 el.add('author', n.author.id)
280 el.add('date', n.added_at)
281 el.add('parent', n.parent and n.parent.id or "")
283 el.add('title', n.title)
284 el.add('body', n.body)
286 tags = el.add('tags')
288 for t in n.tagname_list():
291 revs = el.add('revisions', active=n.active_revision and n.active_revision or n.revisions.order_by('revision')[0])
293 for r in n.revisions.order_by('revision'):
294 rev = _add_tag(revs, 'revision')
295 rev.add('number', r.revision)
296 rev.add('summary', r.summary)
298 rev.add('author', r.author.id)
299 rev.add('date', r.revised_at)
301 rev.add('title', r.title)
302 rev.add('body', r.body)
303 rev.add('tags', ", ".join(r.tagname_list()))
305 el.add('extraRef', n.extra_ref and n.extra_ref.id or "")
306 make_extra(el.add('exraData'), n.extra)
309 @exporter_step(Action.objects.all(), 'actions', 'action', _('Actions'), 'action_date')
310 def export_actions(a, el, anon_data):
312 el.add('type', a.action_type)
313 el.add('date', a.action_date)
316 el.add('user', a.user.id)
317 el.add('realUser', a.real_user and a.real_user.id or "")
319 el.add('node', a.node and a.node.id or "")
321 make_extra(el.add('extraData'), a.extra)
323 canceled = el.add('canceled', state=a.canceled and 'true' or 'false')
327 canceled.add('user', a.canceled_by.id)
328 canceled.add('ip', a.canceled_ip)
330 canceled.add('date', a.canceled_at)
333 reputes = el.add('reputes')
335 for r in a.reputes.all():
336 repute = reputes.add('repute', byCanceled=r.by_canceled and 'true' or 'false')
337 repute.add('user', r.user.id)
338 repute.add('value', r.value)
341 @exporter_step(NodeState.objects.all(), 'states', 'state', _('Node states'), 'action__action_date')
342 def export_states(s, el, anon_data):
343 el.add('type', s.state_type)
344 el.add('node', s.node.id)
345 el.add('trigger', s.action.id)
348 @exporter_step(Badge.objects.all(), 'badges', 'badge', _('Badges'), user_data=True)
349 def export_badges(b, el, anon_data):
350 el.add('type', ["", 'gold', 'silver', 'bronze'][b.type])
351 el.add('name', b.cls)
352 el.add('count', b.awarded_count)
355 @exporter_step(Award.objects.all(), 'awards', 'award', _('Awards'), 'awarded_at', True)
356 def export_awards(a, el, anon_data):
357 el.add('badge', a.badge.cls)
358 el.add('user', a.user)
359 el.add('node', a.node and a.node.id or "")
360 el.add('trigger', a.trigger and a.trigger.id or "")
361 el.add('action', a.action.id)
363 @exporter_step(KeyValue.objects.all(), 'settings', 'setting', _('Settings'))
364 def export_settings(s, el, anon_data):
366 make_extra(el.add('value'), s.value)