1 import os, tarfile, datetime, logging, re, ConfigParser, shutil, zipfile
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
11 from forum import settings
12 from django.conf import settings as djsettings
13 import settings as selfsettings
15 CACHE_KEY = "%s_exporter_state" % APP_URL
18 TMP_FOLDER = os.path.join(os.path.dirname(__file__), 'tmp')
20 DATE_AND_AUTHOR_INF_SECTION = 'DateAndAuthor'
21 OPTIONS_INF_SECTION = 'Options'
22 META_INF_SECTION = 'Meta'
24 DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
25 DATE_FORMAT = "%Y-%m-%d"
27 def Etree_pretty__write(self, file, node, encoding, namespaces,
28 level=0, identator=" "):
31 file.write(level * identator + "<!-- %s -->" % _escape_cdata(node.text, encoding))
32 elif tag is ProcessingInstruction:
33 file.write("<?%s?>" % _escape_cdata(node.text, encoding))
36 xmlns_items = [] # new namespaces in this scope
38 if isinstance(tag, QName) or tag[:1] == "{":
39 tag, xmlns = fixtag(tag, namespaces)
40 if xmlns: xmlns_items.append(xmlns)
42 raise #_raise_serialization_error(tag)
43 file.write("\n" + level * identator + "<" + _encode(tag, encoding))
44 if items or xmlns_items:
45 items.sort() # lexical order
48 if isinstance(k, QName) or k[:1] == "{":
49 k, xmlns = fixtag(k, namespaces)
50 if xmlns: xmlns_items.append(xmlns)
52 raise #_raise_serialization_error(k)
54 if isinstance(v, QName):
55 v, xmlns = fixtag(v, namespaces)
56 if xmlns: xmlns_items.append(xmlns)
58 raise #_raise_serialization_error(v)
59 file.write(u" %s=\"%s\"" % (_encode(k, encoding),
60 _escape_attrib(v, encoding)))
61 for k, v in xmlns_items:
62 file.write(u" %s=\"%s\"" % (_encode(k, encoding),
63 _escape_attrib(v, encoding)))
64 if node.text or len(node):
67 file.write(_escape_cdata(node.text, encoding))
69 self._write(file, n, encoding, namespaces, level + 1, identator)
70 if node.text and len(node.text) < 125:
71 file.write("</" + _encode(tag, encoding) + ">")
73 file.write("\n" + level * identator + "</" + _encode(tag, encoding) + ">")
76 for k, v in xmlns_items:
79 file.write(_escape_cdata(node.tail.replace("\n", (level * identator )+ "\n"), encoding))
81 def make_date(date, with_time=True):
83 return date.strftime(with_time and DATETIME_FORMAT or DATE_FORMAT)
85 return date.replace(year=1900).strftime(with_time and DATETIME_FORMAT or DATE_FORMAT)
88 def ET_Element_add_tag(el, tag_name, content = None, **attrs):
89 tag = ET.SubElement(el, tag_name)
93 tag.text = unicode(content)
97 for k, v in attrs.items():
98 tag.set(k, unicode(v))
102 GOOD_TAG_NAME = re.compile("^\w+$")
104 def make_extra(el, v):
109 if isinstance(v, (int, long, str, unicode, float, bool, dict, list, tuple)):
110 if isinstance(v, tuple):
113 t = v.__class__.__name__
117 value = el.add('value', type=t)
119 if isinstance(v, (list, tuple)):
121 item = value.add('item')
124 elif isinstance(v, dict):
125 for k, i in v.items():
126 item = value.add('item', key=k)
129 value.text = unicode(v)
131 def write_to_file(root, tmp, filename):
132 tree = ET.ElementTree(root)
133 tree.write(os.path.join(tmp, filename), encoding='UTF-8')
135 def create_targz(tmp, files, start_time, options, user, state, set_state, file_format):
136 now = datetime.datetime.now()
137 domain = re.match('[\w-]+\.[\w-]+(\.[\w-]+)*', djsettings.APP_URL)
139 domain = '_'.join(domain.get(0).split('.'))
143 fname = "%s-%s" % (domain, now.strftime('%Y%m%d%H%M'))
144 if file_format == 'zip':
145 full_fname = "%s.zip" % fname
147 full_fname = "%s.tar.gz" % fname
149 if file_format == 'zip':
150 t = zipfile.ZipFile(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), 'w')
152 def add_to_file(f, a):
155 t = tarfile.open(os.path.join(selfsettings.EXPORTER_BACKUP_STORAGE, full_fname), mode = 'w:gz')
157 def add_to_file(f, a):
160 state['overall']['status'] = _('Compressing xml files')
164 add_to_file(os.path.join(tmp, f), "/%s" % f)
166 if options.get('uplodaded_files', False):
167 state['overall']['status'] = _('Importing uploaded files')
171 if options.get('import_skins_folder', False):
172 state['overall']['status'] = _('Importing skins folder')
174 export_skinsfolder(t)
176 state['overall']['status'] = _('Writing inf file.')
179 inf = ConfigParser.SafeConfigParser()
181 inf.add_section(DATE_AND_AUTHOR_INF_SECTION)
183 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'file-name', full_fname)
184 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'author', unicode(user.id))
185 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'site', djsettings.APP_URL)
186 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'started', start_time.strftime(DATETIME_FORMAT))
187 inf.set(DATE_AND_AUTHOR_INF_SECTION, 'finished', now.strftime(DATETIME_FORMAT))
189 inf.add_section(OPTIONS_INF_SECTION)
190 inf.set(OPTIONS_INF_SECTION, 'anon-data', str(options.get('anon_data', False)))
191 inf.set(OPTIONS_INF_SECTION, 'with-upfiles', str(options.get('uplodaded_files', False)))
192 inf.set(OPTIONS_INF_SECTION, 'with-skins', str(options.get('import_skins_folder', False)))
194 inf.add_section(META_INF_SECTION)
196 for id, s in state.items():
197 inf.set(META_INF_SECTION, id, str(s['count']))
199 with open(os.path.join(tmp, '%s.backup.inf' % fname), 'wb') as inffile:
202 add_to_file(os.path.join(tmp, '%s.backup.inf' % fname), '/backup.inf')
203 state['overall']['status'] = _('Saving backup file')
209 def export_upfiles(tf):
210 folder = str(settings.UPFILES_FOLDER)
212 if os.path.exists(folder):
213 tf.add(folder, arcname='/upfiles')
216 def export_skinsfolder(tf):
217 folder = djsettings.TEMPLATE_DIRS[0]
219 if os.path.exists(folder):
220 tf.add(folder, arcname='/skins')
223 def export(options, user):
224 original__write = xml.etree.ElementTree.ElementTree._write
225 xml.etree.ElementTree.ElementTree._write = Etree_pretty__write
226 xml.etree.ElementTree._ElementInterface.add = ET_Element_add_tag
228 start_time = datetime.datetime.now()
230 anon_data = options.get('anon_data', False)
232 steps = [s for s in EXPORT_STEPS if not (anon_data and s['fn'].is_user_data())]
234 state = dict([(s['id'], {
235 'status': _('Queued'), 'count': s['fn'].count(start_time), 'parsed': 0
236 }) for s in steps] + [
238 'status': _('Starting'), 'count': sum([s['fn'].count(start_time) for s in steps]), 'parsed': 0
242 full_state = dict(running=True, state=state, time_started="")
245 full_state['time_started'] = diff_date(start_time)
246 cache.set(CACHE_KEY, full_state)
250 def ping_state(name):
251 state[name]['parsed'] += 1
252 state['overall']['parsed'] += 1
259 state['overall']['status'] = _('Exporting %s') % s['name']
260 state[name]['status'] = _('Exporting')
262 root, fname = fn(ping, start_time, anon_data)
264 state[name]['status'] = _('Writing temp file')
265 state['overall']['status'] = _('Writing %s temp file') % s['name']
269 write_to_file(root, tmp, fname)
270 state[name]['status'] = _('Done')
280 dump_files.append(run(s['fn'], s['id']))
282 state['overall']['status'] = _('Compressing files')
285 fname = create_targz(tmp, dump_files, start_time, options, user, state, set_state, options['file_format'])
286 full_state['running'] = False
287 full_state['errors'] = False
288 state['overall']['status'] = _('Done')
289 state['overall']['fname'] = fname
293 full_state['running'] = False
294 full_state['errors'] = "%s: %s" % (e.__class__.__name__, unicode(e))
298 logging.error("Error executing xml backup: \n %s" % (traceback.format_exc()))
300 xml.etree.ElementTree.ElementTree._write = original__write
301 del xml.etree.ElementTree._ElementInterface.add
304 def exporter_step(queryset, root_tag_name, el_tag_name, name, date_lock=None, user_data=False):
309 return queryset.filter(**{"%s__lte" % date_lock: lock})
312 def decorated(ping, lock, anon_data):
313 root = ET.Element(root_tag_name)
315 for item in qs(lock).order_by('id').select_related():
316 el = root.add(el_tag_name)
317 fn(item, el, anon_data)
320 return root, "%s.xml" % root_tag_name
323 return qs(lock).count()
328 decorated.count = count
329 decorated.is_user_data = is_user_data
331 EXPORT_STEPS.append(dict(id=root_tag_name, name=name, fn=decorated))
337 @exporter_step(Tag.objects.all(), 'tags', 'tag', _('Tags'))
338 def export_tags(t, el, anon_data):
339 el.add('name', t.name)
341 el.add('author', t.created_by.id)
342 el.add('used', t.used_count)
345 @exporter_step(User.objects.all(), 'users', 'user', _('Users'), 'date_joined', True)
346 def export_users(u, el, anon_data):
348 el.add('username', u.username)
349 el.add('password', u.password)
350 el.add('email', u.email, validated=u.email_isvalid and 'true' or 'false')
351 el.add('reputation', u.reputation)
352 el.add('badges', bronze=u.bronze, silver=u.silver, gold=u.gold)
353 el.add('joindate', make_date(u.date_joined))
354 el.add('active', u.is_active and 'true' or 'false')
356 el.add('realname', u.real_name)
357 el.add('bio', u.about)
358 el.add('location', u.location)
359 el.add('website', u.website)
360 el.add('birthdate', u.date_of_birth and make_date(u.date_of_birth, with_time=False) or "")
362 roles = el.add('roles')
365 roles.add('role', 'superuser')
368 roles.add('role', 'moderator')
370 auth = el.add('authKeys')
371 for a in u.auth_keys.all():
372 key = auth.add('key')
373 key.add('provider', a.provider)
374 key.add('key', a.key)
377 ss = u.subscription_settings
379 notify = el.add('notifications', enabled=ss.enable_notifications and 'true' or 'false')
381 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']]))
383 notify.add('autoSubscribe', **dict([(t, ss.__dict__.get(t, False) and 'true' or 'false') for t in [
384 'all_questions', 'all_questions_watched_tags', 'questions_asked', 'questions_answered', 'questions_commented', 'questions_viewed']]))
386 notify.add('notifyOnSubscribed', **dict([(t, ss.__dict__.get("notify_%s" % t, False) and 'true' or 'false') for t in [
387 'answers', 'reply_to_comments', 'comments_own_post', 'comments', 'accepted']]))
389 notify.add('digest', ss.send_digest and 'on' or 'off')
391 watched = el.add('watchedTags')
392 rejected = el.add('rejectedTags')
394 for m in u.tag_selections.all():
395 if m.reason == 'good':
396 watched.add('tag', m.tag.name)
398 rejected.add('tag', m.tag.name)
402 @exporter_step(Node.objects.all(), 'nodes', 'node', _('Nodes'), 'added_at')
403 def export_nodes(n, el, anon_data):
405 el.add('type', n.node_type)
408 el.add('author', n.author.id)
409 el.add('date', make_date(n.added_at))
410 el.add('parent', n.parent and n.parent.id or "")
411 el.add('absparent', n.abs_parent and n.abs_parent or "")
413 act = el.add('lastactivity')
414 act.add('by', n.last_activity_by and n.last_activity_by.id or "")
415 act.add('at', n.last_activity_at and make_date(n.last_activity_at) or "")
417 el.add('title', n.title)
418 el.add('body', n.body)
420 el.add('score', n.score)
422 tags = el.add('tags')
424 for t in n.tagname_list():
428 active = n.active_revision and n.active_revision.revision or n.revisions.order_by('revision')[0].revision
432 revs = el.add('revisions', active=active)
434 for r in n.revisions.order_by('revision'):
435 rev = revs.add('revision')
436 rev.add('number', r.revision)
437 rev.add('summary', r.summary)
439 rev.add('author', r.author.id)
440 rev.add('date', make_date(r.revised_at))
442 rev.add('title', r.title)
443 rev.add('body', r.body)
444 rev.add('tags', ", ".join(r.tagname_list()))
446 el.add('marked', n.marked and 'true' or 'false')
447 el.add('extraRef', n.extra_ref and n.extra_ref.id or "")
448 make_extra(el.add('extraData'), n.extra)
449 el.add('extraCount', n.extra_count and n.extra_count or "")
452 @exporter_step(Action.objects.all(), 'actions', 'action', _('Actions'), 'action_date')
453 def export_actions(a, el, anon_data):
455 el.add('type', a.action_type)
456 el.add('date', make_date(a.action_date))
459 el.add('user', a.user.id)
460 el.add('realUser', a.real_user and a.real_user.id or "")
462 el.add('node', a.node and a.node.id or "")
464 make_extra(el.add('extraData'), a.extra)
466 canceled = el.add('canceled', state=a.canceled and 'true' or 'false')
470 canceled.add('user', a.canceled_by.id)
471 canceled.add('ip', a.canceled_ip)
473 canceled.add('date', make_date(a.canceled_at))
476 reputes = el.add('reputes')
478 for r in a.reputes.all():
479 repute = reputes.add('repute', byCanceled=r.by_canceled and 'true' or 'false')
480 repute.add('user', r.user.id)
481 repute.add('value', r.value)
484 #@exporter_step(NodeState.objects.all(), 'states', 'state', _('Node states'), 'action__action_date')
485 #def export_states(s, el, anon_data):
486 # el.add('type', s.state_type)
487 # el.add('node', s.node.id)
488 # el.add('trigger', s.action.id)
491 #@exporter_step(Badge.objects.all(), 'badges', 'badge', _('Badges'), user_data=True)
492 #def export_badges(b, el, anon_data):
493 # el.add('type', ["", 'gold', 'silver', 'bronze'][b.type])
494 # el.add('name', b.cls)
495 # el.add('count', b.awarded_count)
498 @exporter_step(Award.objects.all(), 'awards', 'award', _('Awards'), 'awarded_at', True)
499 def export_awards(a, el, anon_data):
500 el.add('badge', a.badge.cls)
501 el.add('user', a.user.id)
502 el.add('node', a.node and a.node.id or "")
503 el.add('trigger', a.trigger and a.trigger.id or "")
504 el.add('action', a.action.id)
506 @exporter_step(KeyValue.objects.all(), 'settings', 'setting', _('Settings'))
507 def export_settings(s, el, anon_data):
509 make_extra(el.add('value'), s.value)