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)
97 logging.error('error converting unicode characters')
99 logging.error(traceback.print_exc())
102 tag.text = unicode("".join([c for c in content if c in string.printable]))
104 for k, v in attrs.items():
105 tag.set(k, unicode(v))
109 GOOD_TAG_NAME = re.compile("^\w+$")
111 def make_extra(el, v):
116 if isinstance(v, (int, long, str, unicode, float, bool, dict, list, tuple)):
117 if isinstance(v, tuple):
120 t = v.__class__.__name__
124 value = el.add('value', type=t)
126 if isinstance(v, (list, tuple)):
128 item = value.add('item')
131 elif isinstance(v, dict):
132 for k, i in v.items():
133 item = value.add('item', key=k)
136 value.text = unicode(v)
138 def write_to_file(root, tmp, filename):
139 tree = ET.ElementTree(root)
140 tree.write(os.path.join(tmp, filename), encoding='UTF-8')
142 def create_targz(tmp, files, start_time, options, user, state, set_state, file_format):
143 now = datetime.datetime.now()
144 domain = re.match('[\w-]+\.[\w-]+(\.[\w-]+)*', djsettings.APP_URL)
146 domain = '_'.join(domain.get(0).split('.'))
150 fname = "%s-%s" % (domain, now.strftime('%Y%m%d%H%M'))
151 if file_format == 'zip':
152 full_fname = "%s.zip" % fname
154 full_fname = "%s.tar.gz" % fname
156 if file_format == 'zip':
157 t = zipfile.ZipFile(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), 'w')
159 def add_to_file(f, a):
162 t = tarfile.open(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), mode = 'w:gz')
164 def add_to_file(f, a):
167 state['overall']['status'] = _('Compressing xml files')
171 add_to_file(os.path.join(tmp, f), "/%s" % f)
173 if options.get('uplodaded_files', False):
174 state['overall']['status'] = _('Importing uploaded files')
178 if options.get('import_skins_folder', False):
179 state['overall']['status'] = _('Importing skins folder')
181 export_skinsfolder(t)
183 state['overall']['status'] = _('Writing inf file.')
186 inf = ConfigParser.SafeConfigParser()
188 inf.add_section(DATE_AND_AUTHOR_INF_SECTION)
190 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'file-name', full_fname)
191 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'author', unicode(user.id))
192 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'site', djsettings.APP_URL)
193 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'started', start_time.strftime(DATETIME_FORMAT))
194 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'finished', now.strftime(DATETIME_FORMAT))
196 inf.add_section(OPTIONS_INF_SECTION)
197 inf.set(OPTIONS_INF_SECTION, 'anon-data', str(options.get('anon_data', False)))
198 inf.set(OPTIONS_INF_SECTION, 'with-upfiles', str(options.get('uplodaded_files', False)))
199 inf.set(OPTIONS_INF_SECTION, 'with-skins', str(options.get('import_skins_folder', False)))
201 inf.add_section(META_INF_SECTION)
203 for id, s in state.items():
204 inf.set(META_INF_SECTION, id, str(s['count']))
206 with open(os.path.join(tmp, '%s.backup.inf' % fname), 'wb') as inffile:
209 add_to_file(os.path.join(tmp, '%s.backup.inf' % fname), '/backup.inf')
210 state['overall']['status'] = _('Saving backup file')
216 def export_upfiles(tf):
217 folder = str(settings.UPFILES_FOLDER)
219 if os.path.exists(folder):
220 tf.add(folder, arcname='/upfiles')
223 def export_skinsfolder(tf):
224 folder = djsettings.TEMPLATE_DIRS[0]
226 if os.path.exists(folder):
227 tf.add(folder, arcname='/skins')
230 def export(options, user):
231 original__write = xml.etree.ElementTree.ElementTree._write
232 xml.etree.ElementTree.ElementTree._write = Etree_pretty__write
233 xml.etree.ElementTree._ElementInterface.add = ET_Element_add_tag
235 start_time = datetime.datetime.now()
237 anon_data = options.get('anon_data', False)
239 steps = [s for s in EXPORT_STEPS if not (anon_data and s['fn'].is_user_data())]
241 state = dict([(s['id'], {
242 'status': _('Queued'), 'count': s['fn'].count(start_time), 'parsed': 0
243 }) for s in steps] + [
245 'status': _('Starting'), 'count': sum([s['fn'].count(start_time) for s in steps]), 'parsed': 0
249 full_state = dict(running=True, state=state, time_started="")
252 full_state['time_started'] = diff_date(start_time)
253 cache.set(CACHE_KEY, full_state)
257 def ping_state(name):
258 state[name]['parsed'] += 1
259 state['overall']['parsed'] += 1
266 state['overall']['status'] = _('Exporting %s') % s['name']
267 state[name]['status'] = _('Exporting')
269 root, fname = fn(ping, start_time, anon_data)
271 state[name]['status'] = _('Writing temp file')
272 state['overall']['status'] = _('Writing %s temp file') % s['name']
276 write_to_file(root, tmp, fname)
277 state[name]['status'] = _('Done')
287 dump_files.append(run(s['fn'], s['id']))
289 state['overall']['status'] = _('Compressing files')
292 fname = create_targz(tmp, dump_files, start_time, options, user, state, set_state, options['file_format'])
293 full_state['running'] = False
294 full_state['errors'] = False
295 state['overall']['status'] = _('Done')
296 state['overall']['fname'] = fname
300 full_state['running'] = False
301 full_state['errors'] = "%s: %s" % (e.__class__.__name__, unicode(e))
305 logging.error("Error executing xml backup: \n %s" % (traceback.format_exc()))
307 xml.etree.ElementTree.ElementTree._write = original__write
308 del xml.etree.ElementTree._ElementInterface.add
311 def exporter_step(queryset, root_tag_name, el_tag_name, name, date_lock=None, user_data=False):
316 return queryset.filter(**{"%s__lte" % date_lock: lock})
319 def decorated(ping, lock, anon_data):
320 root = ET.Element(root_tag_name)
322 for item in qs(lock).order_by('id').select_related():
323 el = root.add(el_tag_name)
324 fn(item, el, anon_data)
327 return root, "%s.xml" % root_tag_name
330 return qs(lock).count()
335 decorated.count = count
336 decorated.is_user_data = is_user_data
338 EXPORT_STEPS.append(dict(id=root_tag_name, name=name, fn=decorated))
344 @exporter_step(Tag.objects.all(), 'tags', 'tag', _('Tags'))
345 def export_tags(t, el, anon_data):
346 el.add('name', t.name)
348 el.add('author', t.created_by.id)
349 el.add('used', t.used_count)
352 @exporter_step(User.objects.all(), 'users', 'user', _('Users'), 'date_joined', True)
353 def export_users(u, el, anon_data):
355 el.add('username', u.username)
356 el.add('password', u.password)
357 el.add('email', u.email, validated=u.email_isvalid and 'true' or 'false')
358 el.add('reputation', u.reputation)
359 el.add('badges', bronze=u.bronze, silver=u.silver, gold=u.gold)
360 el.add('joindate', make_date(u.date_joined))
361 el.add('active', u.is_active and 'true' or 'false')
363 el.add('realname', u.real_name)
364 el.add('bio', u.about)
365 el.add('location', u.location)
366 el.add('website', u.website)
367 el.add('birthdate', u.date_of_birth and make_date(u.date_of_birth, with_time=False) or "")
369 roles = el.add('roles')
372 roles.add('role', 'superuser')
375 roles.add('role', 'moderator')
377 auth = el.add('authKeys')
378 for a in u.auth_keys.all():
379 key = auth.add('key')
380 key.add('provider', a.provider)
381 key.add('key', a.key)
384 ss = u.subscription_settings
386 notify = el.add('notifications', enabled=ss.enable_notifications and 'true' or 'false')
388 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']]))
390 notify.add('autoSubscribe', **dict([(t, ss.__dict__.get(t, False) and 'true' or 'false') for t in [
391 'all_questions', 'all_questions_watched_tags', 'questions_asked', 'questions_answered', 'questions_commented', 'questions_viewed']]))
393 notify.add('notifyOnSubscribed', **dict([(t, ss.__dict__.get("notify_%s" % t, False) and 'true' or 'false') for t in [
394 'answers', 'reply_to_comments', 'comments_own_post', 'comments', 'accepted']]))
396 notify.add('digest', ss.send_digest and 'on' or 'off')
398 watched = el.add('watchedTags')
399 rejected = el.add('rejectedTags')
401 for m in u.tag_selections.all():
402 if m.reason == 'good':
403 watched.add('tag', m.tag.name)
405 rejected.add('tag', m.tag.name)
409 @exporter_step(Node.objects.all(), 'nodes', 'node', _('Nodes'), 'added_at')
410 def export_nodes(n, el, anon_data):
412 el.add('type', n.node_type)
415 el.add('author', n.author.id)
416 el.add('date', make_date(n.added_at))
417 el.add('parent', n.parent and n.parent.id or "")
418 el.add('absparent', n.abs_parent and n.abs_parent or "")
420 act = el.add('lastactivity')
421 act.add('by', n.last_activity_by and n.last_activity_by.id or "")
422 act.add('at', n.last_activity_at and make_date(n.last_activity_at) or "")
424 el.add('title', n.title)
425 el.add('body', n.body)
427 el.add('score', n.score)
429 tags = el.add('tags')
431 for t in n.tagname_list():
435 active = n.active_revision and n.active_revision.revision or n.revisions.order_by('revision')[0].revision
439 revs = el.add('revisions', active=active)
441 for r in n.revisions.order_by('revision'):
442 rev = revs.add('revision')
443 rev.add('number', r.revision)
444 rev.add('summary', r.summary)
446 rev.add('author', r.author.id)
447 rev.add('date', make_date(r.revised_at))
449 rev.add('title', r.title)
450 rev.add('body', r.body)
451 rev.add('tags', ", ".join(r.tagname_list()))
453 el.add('marked', n.marked and 'true' or 'false')
454 el.add('extraRef', n.extra_ref and n.extra_ref.id or "")
455 make_extra(el.add('extraData'), n.extra)
456 el.add('extraCount', n.extra_count and n.extra_count or "")
459 @exporter_step(Action.objects.all(), 'actions', 'action', _('Actions'), 'action_date')
460 def export_actions(a, el, anon_data):
462 el.add('type', a.action_type)
463 el.add('date', make_date(a.action_date))
466 el.add('user', a.user.id)
467 el.add('realUser', a.real_user and a.real_user.id or "")
469 el.add('node', a.node and a.node.id or "")
471 make_extra(el.add('extraData'), a.extra)
473 canceled = el.add('canceled', state=a.canceled and 'true' or 'false')
477 canceled.add('user', a.canceled_by.id)
478 canceled.add('ip', a.canceled_ip)
480 canceled.add('date', make_date(a.canceled_at))
483 reputes = el.add('reputes')
485 for r in a.reputes.all():
486 repute = reputes.add('repute', byCanceled=r.by_canceled and 'true' or 'false')
487 repute.add('user', r.user.id)
488 repute.add('value', r.value)
491 #@exporter_step(NodeState.objects.all(), 'states', 'state', _('Node states'), 'action__action_date')
492 #def export_states(s, el, anon_data):
493 # el.add('type', s.state_type)
494 # el.add('node', s.node.id)
495 # el.add('trigger', s.action.id)
498 #@exporter_step(Badge.objects.all(), 'badges', 'badge', _('Badges'), user_data=True)
499 #def export_badges(b, el, anon_data):
500 # el.add('type', ["", 'gold', 'silver', 'bronze'][b.type])
501 # el.add('name', b.cls)
502 # el.add('count', b.awarded_count)
505 @exporter_step(Award.objects.all(), 'awards', 'award', _('Awards'), 'awarded_at', True)
506 def export_awards(a, el, anon_data):
507 el.add('badge', a.badge.cls)
508 el.add('user', a.user.id)
509 el.add('node', a.node and a.node.id or "")
510 el.add('trigger', a.trigger and a.trigger.id or "")
511 el.add('action', a.action.id)
513 @exporter_step(KeyValue.objects.all(), 'settings', 'setting', _('Settings'))
514 def export_settings(s, el, anon_data):
516 make_extra(el.add('value'), s.value)