1 from __future__ import with_statement
3 import os, tarfile, datetime, logging, re, ConfigParser, shutil, zipfile
5 from django.core.cache import cache
6 from django.utils.translation import ugettext as _
7 from forum.models import *
8 from forum.settings import APP_URL
9 from forum.templatetags.extra_tags import diff_date
10 import xml.etree.ElementTree
11 from xml.etree import ElementTree as ET
12 from xml.etree.ElementTree import Comment, _encode, ProcessingInstruction, QName, fixtag, _escape_attrib, _escape_cdata
13 from forum import settings
14 from django.conf import settings as djsettings
15 import settings as selfsettings
17 CACHE_KEY = "%s_exporter_state" % APP_URL
20 TMP_FOLDER = os.path.join(os.path.dirname(__file__), 'tmp')
22 DATE_AND_AUTHOR_INF_SECTION = 'DateAndAuthor'
23 OPTIONS_INF_SECTION = 'Options'
24 META_INF_SECTION = 'Meta'
26 DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
27 DATE_FORMAT = "%Y-%m-%d"
29 def Etree_pretty__write(self, file, node, encoding, namespaces,
30 level=0, identator=" "):
33 file.write(level * identator + "<!-- %s -->" % _escape_cdata(node.text, encoding))
34 elif tag is ProcessingInstruction:
35 file.write("<?%s?>" % _escape_cdata(node.text, encoding))
38 xmlns_items = [] # new namespaces in this scope
40 if isinstance(tag, QName) or tag[:1] == "{":
41 tag, xmlns = fixtag(tag, namespaces)
42 if xmlns: xmlns_items.append(xmlns)
44 raise #_raise_serialization_error(tag)
45 file.write("\n" + level * identator + "<" + _encode(tag, encoding))
46 if items or xmlns_items:
47 items.sort() # lexical order
50 if isinstance(k, QName) or k[:1] == "{":
51 k, xmlns = fixtag(k, namespaces)
52 if xmlns: xmlns_items.append(xmlns)
54 raise #_raise_serialization_error(k)
56 if isinstance(v, QName):
57 v, xmlns = fixtag(v, namespaces)
58 if xmlns: xmlns_items.append(xmlns)
60 raise #_raise_serialization_error(v)
61 file.write(u" %s=\"%s\"" % (_encode(k, encoding),
62 _escape_attrib(v, encoding)))
63 for k, v in xmlns_items:
64 file.write(u" %s=\"%s\"" % (_encode(k, encoding),
65 _escape_attrib(v, encoding)))
66 if node.text or len(node):
69 file.write(_escape_cdata(node.text, encoding))
71 self._write(file, n, encoding, namespaces, level + 1, identator)
72 if node.text and len(node.text) < 125:
73 file.write("</" + _encode(tag, encoding) + ">")
75 file.write("\n" + level * identator + "</" + _encode(tag, encoding) + ">")
78 for k, v in xmlns_items:
81 file.write(_escape_cdata(node.tail.replace("\n", (level * identator )+ "\n"), encoding))
83 def make_date(date, with_time=True):
85 return date.strftime(with_time and DATETIME_FORMAT or DATE_FORMAT)
87 return date.replace(year=1900).strftime(with_time and DATETIME_FORMAT or DATE_FORMAT)
90 def ET_Element_add_tag(el, tag_name, content = None, **attrs):
91 tag = ET.SubElement(el, tag_name)
95 tag.text = unicode(content)
99 for k, v in attrs.items():
100 tag.set(k, unicode(v))
104 GOOD_TAG_NAME = re.compile("^\w+$")
106 def make_extra(el, v):
111 if isinstance(v, (int, long, str, unicode, float, bool, dict, list, tuple)):
112 if isinstance(v, tuple):
115 t = v.__class__.__name__
119 value = el.add('value', type=t)
121 if isinstance(v, (list, tuple)):
123 item = value.add('item')
126 elif isinstance(v, dict):
127 for k, i in v.items():
128 item = value.add('item', key=k)
131 value.text = unicode(v)
133 def write_to_file(root, tmp, filename):
134 tree = ET.ElementTree(root)
135 tree.write(os.path.join(tmp, filename), encoding='UTF-8')
137 def create_targz(tmp, files, start_time, options, user, state, set_state, file_format):
138 now = datetime.datetime.now()
139 domain = re.match('[\w-]+\.[\w-]+(\.[\w-]+)*', djsettings.APP_URL)
141 domain = '_'.join(domain.get(0).split('.'))
145 fname = "%s-%s" % (domain, now.strftime('%Y%m%d%H%M'))
146 if file_format == 'zip':
147 full_fname = "%s.zip" % fname
149 full_fname = "%s.tar.gz" % fname
151 if file_format == 'zip':
152 t = zipfile.ZipFile(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), 'w')
154 def add_to_file(f, a):
157 t = tarfile.open(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), mode = 'w:gz')
159 def add_to_file(f, a):
162 state['overall']['status'] = _('Compressing xml files')
166 add_to_file(os.path.join(tmp, f), "/%s" % f)
168 if options.get('uplodaded_files', False):
169 state['overall']['status'] = _('Importing uploaded files')
173 if options.get('import_skins_folder', False):
174 state['overall']['status'] = _('Importing skins folder')
176 export_skinsfolder(t)
178 state['overall']['status'] = _('Writing inf file.')
181 inf = ConfigParser.SafeConfigParser()
183 inf.add_section(DATE_AND_AUTHOR_INF_SECTION)
185 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'file-name', full_fname)
186 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'author', unicode(user.id))
187 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'site', djsettings.APP_URL)
188 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'started', start_time.strftime(DATETIME_FORMAT))
189 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'finished', now.strftime(DATETIME_FORMAT))
191 inf.add_section(OPTIONS_INF_SECTION)
192 inf.set(OPTIONS_INF_SECTION, 'anon-data', str(options.get('anon_data', False)))
193 inf.set(OPTIONS_INF_SECTION, 'with-upfiles', str(options.get('uplodaded_files', False)))
194 inf.set(OPTIONS_INF_SECTION, 'with-skins', str(options.get('import_skins_folder', False)))
196 inf.add_section(META_INF_SECTION)
198 for id, s in state.items():
199 inf.set(META_INF_SECTION, id, str(s['count']))
201 with open(os.path.join(tmp, '%s.backup.inf' % fname), 'wb') as inffile:
204 add_to_file(os.path.join(tmp, '%s.backup.inf' % fname), '/backup.inf')
205 state['overall']['status'] = _('Saving backup file')
211 def export_upfiles(tf):
212 folder = str(settings.UPFILES_FOLDER)
214 if os.path.exists(folder):
215 tf.add(folder, arcname='/upfiles')
218 def export_skinsfolder(tf):
219 folder = djsettings.TEMPLATE_DIRS[0]
221 if os.path.exists(folder):
222 tf.add(folder, arcname='/skins')
225 def export(options, user):
226 original__write = xml.etree.ElementTree.ElementTree._write
227 xml.etree.ElementTree.ElementTree._write = Etree_pretty__write
228 xml.etree.ElementTree._ElementInterface.add = ET_Element_add_tag
230 start_time = datetime.datetime.now()
232 anon_data = options.get('anon_data', False)
234 steps = [s for s in EXPORT_STEPS if not (anon_data and s['fn'].is_user_data())]
236 state = dict([(s['id'], {
237 'status': _('Queued'), 'count': s['fn'].count(start_time), 'parsed': 0
238 }) for s in steps] + [
240 'status': _('Starting'), 'count': sum([s['fn'].count(start_time) for s in steps]), 'parsed': 0
244 full_state = dict(running=True, state=state, time_started="")
247 full_state['time_started'] = diff_date(start_time)
248 cache.set(CACHE_KEY, full_state)
252 def ping_state(name):
253 state[name]['parsed'] += 1
254 state['overall']['parsed'] += 1
261 state['overall']['status'] = _('Exporting %s') % s['name']
262 state[name]['status'] = _('Exporting')
264 root, fname = fn(ping, start_time, anon_data)
266 state[name]['status'] = _('Writing temp file')
267 state['overall']['status'] = _('Writing %s temp file') % s['name']
271 write_to_file(root, tmp, fname)
272 state[name]['status'] = _('Done')
282 dump_files.append(run(s['fn'], s['id']))
284 state['overall']['status'] = _('Compressing files')
287 fname = create_targz(tmp, dump_files, start_time, options, user, state, set_state, options['file_format'])
288 full_state['running'] = False
289 full_state['errors'] = False
290 state['overall']['status'] = _('Done')
291 state['overall']['fname'] = fname
295 full_state['running'] = False
296 full_state['errors'] = "%s: %s" % (e.__class__.__name__, unicode(e))
300 logging.error("Error executing xml backup: \n %s" % (traceback.format_exc()))
302 xml.etree.ElementTree.ElementTree._write = original__write
303 del xml.etree.ElementTree._ElementInterface.add
306 def exporter_step(queryset, root_tag_name, el_tag_name, name, date_lock=None, user_data=False):
311 return queryset.filter(**{"%s__lte" % date_lock: lock})
314 def decorated(ping, lock, anon_data):
315 root = ET.Element(root_tag_name)
317 for item in qs(lock).order_by('id').select_related():
318 el = root.add(el_tag_name)
319 fn(item, el, anon_data)
322 return root, "%s.xml" % root_tag_name
325 return qs(lock).count()
330 decorated.count = count
331 decorated.is_user_data = is_user_data
333 EXPORT_STEPS.append(dict(id=root_tag_name, name=name, fn=decorated))
339 @exporter_step(Tag.objects.all(), 'tags', 'tag', _('Tags'))
340 def export_tags(t, el, anon_data):
341 el.add('name', t.name)
343 el.add('author', t.created_by.id)
344 el.add('used', t.used_count)
347 @exporter_step(User.objects.all(), 'users', 'user', _('Users'), 'date_joined', True)
348 def export_users(u, el, anon_data):
350 el.add('username', u.username)
351 el.add('password', u.password)
352 el.add('email', u.email, validated=u.email_isvalid and 'true' or 'false')
353 el.add('reputation', u.reputation)
354 el.add('badges', bronze=u.bronze, silver=u.silver, gold=u.gold)
355 el.add('joindate', make_date(u.date_joined))
356 el.add('active', u.is_active and 'true' or 'false')
358 el.add('realname', u.real_name)
359 el.add('bio', u.about)
360 el.add('location', u.location)
361 el.add('website', u.website)
362 el.add('birthdate', u.date_of_birth and make_date(u.date_of_birth, with_time=False) or "")
364 roles = el.add('roles')
367 roles.add('role', 'superuser')
370 roles.add('role', 'moderator')
372 auth = el.add('authKeys')
373 for a in u.auth_keys.all():
374 key = auth.add('key')
375 key.add('provider', a.provider)
376 key.add('key', a.key)
379 ss = u.subscription_settings
381 notify = el.add('notifications', enabled=ss.enable_notifications and 'true' or 'false')
383 notify.add('notify', **dict([(t, ss.__dict__.get(t, 'n') == 'i' and 'true' or 'false') for t in ['member_joins', 'new_question', 'new_question_watched_tags', 'subscribed_questions']]))
385 notify.add('autoSubscribe', **dict([(t, ss.__dict__.get(t, False) and 'true' or 'false') for t in [
386 'all_questions', 'all_questions_watched_tags', 'questions_asked', 'questions_answered', 'questions_commented', 'questions_viewed']]))
388 notify.add('notifyOnSubscribed', **dict([(t, ss.__dict__.get("notify_%s" % t, False) and 'true' or 'false') for t in [
389 'answers', 'reply_to_comments', 'comments_own_post', 'comments', 'accepted']]))
391 notify.add('digest', ss.send_digest and 'on' or 'off')
393 watched = el.add('watchedTags')
394 rejected = el.add('rejectedTags')
396 for m in u.tag_selections.all():
397 if m.reason == 'good':
398 watched.add('tag', m.tag.name)
400 rejected.add('tag', m.tag.name)
404 @exporter_step(Node.objects.all(), 'nodes', 'node', _('Nodes'), 'added_at')
405 def export_nodes(n, el, anon_data):
407 el.add('type', n.node_type)
410 el.add('author', n.author.id)
411 el.add('date', make_date(n.added_at))
412 el.add('parent', n.parent and n.parent.id or "")
413 el.add('absparent', n.abs_parent and n.abs_parent or "")
415 act = el.add('lastactivity')
416 act.add('by', n.last_activity_by and n.last_activity_by.id or "")
417 act.add('at', n.last_activity_at and make_date(n.last_activity_at) or "")
419 el.add('title', n.title)
420 el.add('body', n.body)
422 el.add('score', n.score)
424 tags = el.add('tags')
426 for t in n.tagname_list():
430 active = n.active_revision and n.active_revision.revision or n.revisions.order_by('revision')[0].revision
434 revs = el.add('revisions', active=active)
436 for r in n.revisions.order_by('revision'):
437 rev = revs.add('revision')
438 rev.add('number', r.revision)
439 rev.add('summary', r.summary)
441 rev.add('author', r.author.id)
442 rev.add('date', make_date(r.revised_at))
444 rev.add('title', r.title)
445 rev.add('body', r.body)
446 rev.add('tags', ", ".join(r.tagname_list()))
448 el.add('marked', n.marked and 'true' or 'false')
449 el.add('extraRef', n.extra_ref and n.extra_ref.id or "")
450 make_extra(el.add('extraData'), n.extra)
451 el.add('extraCount', n.extra_count and n.extra_count or "")
454 @exporter_step(Action.objects.all(), 'actions', 'action', _('Actions'), 'action_date')
455 def export_actions(a, el, anon_data):
457 el.add('type', a.action_type)
458 el.add('date', make_date(a.action_date))
461 el.add('user', a.user.id)
462 el.add('realUser', a.real_user and a.real_user.id or "")
464 el.add('node', a.node and a.node.id or "")
466 make_extra(el.add('extraData'), a.extra)
468 canceled = el.add('canceled', state=a.canceled and 'true' or 'false')
472 canceled.add('user', a.canceled_by.id)
473 canceled.add('ip', a.canceled_ip)
475 canceled.add('date', make_date(a.canceled_at))
478 reputes = el.add('reputes')
480 for r in a.reputes.all():
481 repute = reputes.add('repute', byCanceled=r.by_canceled and 'true' or 'false')
482 repute.add('user', r.user.id)
483 repute.add('value', r.value)
486 #@exporter_step(NodeState.objects.all(), 'states', 'state', _('Node states'), 'action__action_date')
487 #def export_states(s, el, anon_data):
488 # el.add('type', s.state_type)
489 # el.add('node', s.node.id)
490 # el.add('trigger', s.action.id)
493 #@exporter_step(Badge.objects.all(), 'badges', 'badge', _('Badges'), user_data=True)
494 #def export_badges(b, el, anon_data):
495 # el.add('type', ["", 'gold', 'silver', 'bronze'][b.type])
496 # el.add('name', b.cls)
497 # el.add('count', b.awarded_count)
500 @exporter_step(Award.objects.all(), 'awards', 'award', _('Awards'), 'awarded_at', True)
501 def export_awards(a, el, anon_data):
502 el.add('badge', a.badge.cls)
503 el.add('user', a.user.id)
504 el.add('node', a.node and a.node.id or "")
505 el.add('trigger', a.trigger and a.trigger.id or "")
506 el.add('action', a.action.id)
508 @exporter_step(KeyValue.objects.all(), 'settings', 'setting', _('Settings'))
509 def export_settings(s, el, anon_data):
511 make_extra(el.add('value'), s.value)