]> git.openstreetmap.org Git - osqa.git/blobdiff - forum_modules/sximporter/importer.py
#SPLUNK-91, modifying the permanent link tool, adding an option to copy to the clipbo...
[osqa.git] / forum_modules / sximporter / importer.py
index 0f7f812626e23968ff072493092218a5d984a383..98c9dbd64872a63fdc73ee9d9d8407b7539c4a36 100644 (file)
@@ -1,15 +1,11 @@
 # -*- coding: utf-8 -*-
 
 # -*- coding: utf-8 -*-
 
-from xml.dom import minidom
-from datetime import datetime, timedelta
+from datetime import datetime
 import time
 import re
 import os
 import gc
 from django.utils.translation import ugettext as _
 import time
 import re
 import os
 import gc
 from django.utils.translation import ugettext as _
-from django.template.defaultfilters import slugify
-from forum.models.utils import dbsafe_encode
-from orm import orm
 
 from django.utils.encoding import force_unicode
 
 
 from django.utils.encoding import force_unicode
 
@@ -25,6 +21,33 @@ from zlib import compress, decompress
 from xml.sax import make_parser
 from xml.sax.handler import ContentHandler
 
 from xml.sax import make_parser
 from xml.sax.handler import ContentHandler
 
+def create_orm():
+    from django.conf import settings
+    from south.orm import FakeORM
+
+    get_migration_number_re = re.compile(r'^((\d+)_.*)\.py$')
+
+    migrations_folder = os.path.join(settings.SITE_SRC_ROOT, 'forum/migrations')
+
+    highest_number = 0
+    highest_file = None
+
+    for f in os.listdir(migrations_folder):
+        if os.path.isfile(os.path.join(migrations_folder, f)):
+            m = get_migration_number_re.match(f)
+
+            if m:
+                found = int(m.group(2))
+
+                if found > highest_number:
+                    highest_number = found
+                    highest_file = m.group(1)
+
+    mod = __import__('forum.migrations.%s' % highest_file, globals(), locals(), ['forum.migrations'])
+    return FakeORM(getattr(mod, 'Migration'), "forum")
+
+orm = create_orm()
+
 class SXTableHandler(ContentHandler):
     def __init__(self, fname, callback):
         self.in_row = False
 class SXTableHandler(ContentHandler):
     def __init__(self, fname, callback):
         self.in_row = False
@@ -151,9 +174,13 @@ class UnknownYahooUser(UnknownUser):
 
 
 class IdMapper(dict):
 
 
 class IdMapper(dict):
+
+    def __init__(self):
+        self.default = 1
+
     def __getitem__(self, key):
         key = int(key)
     def __getitem__(self, key):
         key = int(key)
-        return super(IdMapper, self).get(key, 1)
+        return super(IdMapper, self).get(key, self.default)
 
     def __setitem__(self, key, value):
         super(IdMapper, self).__setitem__(int(key), int(value))
 
     def __setitem__(self, key, value):
         super(IdMapper, self).__setitem__(int(key), int(value))
@@ -167,32 +194,48 @@ class IdIncrementer():
 
 openidre = re.compile('^https?\:\/\/')
 def userimport(path, options):
 
 openidre = re.compile('^https?\:\/\/')
 def userimport(path, options):
-#users = readTable(dump, "Users")
 
     usernames = []
     openids = set()
     uidmapper = IdMapper()
 
     usernames = []
     openids = set()
     uidmapper = IdMapper()
-    #merged_users = []
 
 
+    authenticated_user = options.get('authenticated_user', None)
     owneruid = options.get('owneruid', None)
     #check for empty values
     if not owneruid:
         owneruid = None
     owneruid = options.get('owneruid', None)
     #check for empty values
     if not owneruid:
         owneruid = None
+    else:
+        owneruid = int(owneruid)
 
     def callback(sxu):
         create = True
 
     def callback(sxu):
         create = True
+        set_mapper_defaults = False
 
         if sxu.get('id') == '-1':
             return
         #print "\n".join(["%s : %s" % i for i in sxu.items()])
 
         if sxu.get('id') == '-1':
             return
         #print "\n".join(["%s : %s" % i for i in sxu.items()])
-        if int(sxu.get('id')) == int(owneruid):
-            osqau = orm.User.objects.get(id=1)
-            for assoc in orm.AuthKeyUserAssociation.objects.filter(user=osqau):
-                openids.add(assoc.key)
-            uidmapper[owneruid] = 1
-            uidmapper[-1] = 1
-            create = False
-        else:
+
+        if (owneruid and (int(sxu.get('id')) == owneruid)) or (
+            (not owneruid) and len(uidmapper)):
+
+            set_mapper_defaults = True
+
+            if authenticated_user:
+                osqau = orm.User.objects.get(id=authenticated_user.id)
+
+                for assoc in orm.AuthKeyUserAssociation.objects.filter(user=osqau):
+                    openids.add(assoc.key)
+
+                uidmapper[owneruid] = osqau.id
+                create = False
+
+        sxbadges = sxu.get('badgesummary', None)
+        badges = {'1':'0', '2':'0', '3':'0'}
+
+        if sxbadges:
+            badges.update(dict([b.split('=') for b in sxbadges.split()]))
+
+        if create:
             username = unicode(sxu.get('displayname',
                                sxu.get('displaynamecleaned', sxu.get('realname', final_username_attempt(sxu)))))[:30]
 
             username = unicode(sxu.get('displayname',
                                sxu.get('displaynamecleaned', sxu.get('realname', final_username_attempt(sxu)))))[:30]
 
@@ -210,15 +253,8 @@ def userimport(path, options):
 
                     if not totest in usernames:
                         username = totest
 
                     if not totest in usernames:
                         username = totest
-                        break          
-
-        sxbadges = sxu.get('badgesummary', None)
-        badges = {'1':'0', '2':'0', '3':'0'}
-
-        if sxbadges:
-            badges.update(dict([b.split('=') for b in sxbadges.split()]))
+                        break
 
 
-        if create:
             osqau = orm.User(
                     id           = sxu.get('id'),
                     username     = username,
             osqau = orm.User(
                     id           = sxu.get('id'),
                     username     = username,
@@ -290,6 +326,10 @@ def userimport(path, options):
             #merged_users.append(osqau.id)
             osqau.save()
 
             #merged_users.append(osqau.id)
             osqau.save()
 
+        if set_mapper_defaults:
+            uidmapper[-1] = osqau.id
+            uidmapper.default = osqau.id
+
         usernames.append(osqau.username)
 
         openid = sxu.get('openid', None)
         usernames.append(osqau.username)
 
         openid = sxu.get('openid', None)
@@ -306,13 +346,12 @@ def userimport(path, options):
 
     readTable(path, "Users", callback)
 
 
     readTable(path, "Users", callback)
 
-    if uidmapper[-1] == -1:
-        uidmapper[-1] = 1
+    #if uidmapper[-1] == -1:
+    #    uidmapper[-1] = 1
 
     return uidmapper
 
 def tagsimport(dump, uidmap):
 
     return uidmapper
 
 def tagsimport(dump, uidmap):
-#tags = readTable(dump, "Tags")
 
     tagmap = {}
 
 
     tagmap = {}
 
@@ -354,18 +393,8 @@ def remove_post_state(name, post):
     post.state_string = "".join("(%s)" % s for s in re.findall('\w+', post.state_string) if s != name)
 
 def postimport(dump, uidmap, tagmap):
     post.state_string = "".join("(%s)" % s for s in re.findall('\w+', post.state_string) if s != name)
 
 def postimport(dump, uidmap, tagmap):
-#history = {}
-#accepted = {}
     all = []
 
     all = []
 
-    #for h in readTable(dump, "PostHistory"):
-    #    if not history.get(h.get('postid'), None):
-    #        history[h.get('postid')] = []
-    #
-    #    history[h.get('postid')].append(h)
-
-    #posts = readTable(dump, "Posts")
-
     def callback(sxpost):
         nodetype = (sxpost.get('posttypeid') == '1') and "nodetype" or "answer"
 
     def callback(sxpost):
         nodetype = (sxpost.get('posttypeid') == '1') and "nodetype" or "answer"
 
@@ -441,7 +470,6 @@ def postimport(dump, uidmap, tagmap):
     return all
 
 def comment_import(dump, uidmap, posts):
     return all
 
 def comment_import(dump, uidmap, posts):
-#comments = readTable(dump, "PostComments")
     currid = IdIncrementer(max(posts))
     mapping = {}
 
     currid = IdIncrementer(max(posts))
     mapping = {}
 
@@ -516,7 +544,6 @@ def create_and_activate_revision(post):
     post.save()
 
 def post_vote_import(dump, uidmap, posts):
     post.save()
 
 def post_vote_import(dump, uidmap, posts):
-#votes = readTable(dump, "Posts2Votes")
     close_reasons = {}
 
     def close_callback(r):
     close_reasons = {}
 
     def close_callback(r):
@@ -646,7 +673,6 @@ def post_vote_import(dump, uidmap, posts):
 
 
 def comment_vote_import(dump, uidmap, comments):
 
 
 def comment_vote_import(dump, uidmap, comments):
-#votes = readTable(dump, "Comments2Votes")
     user2vote = []
     comments2score = {}
 
     user2vote = []
     comments2score = {}
 
@@ -688,7 +714,6 @@ def comment_vote_import(dump, uidmap, comments):
 
 
 def badges_import(dump, uidmap, post_list):
 
 
 def badges_import(dump, uidmap, post_list):
-#node_ctype = orm['contenttypes.contenttype'].objects.get(name='node')
 
     sxbadges = {}
 
 
     sxbadges = {}
 
@@ -743,6 +768,7 @@ def badges_import(dump, uidmap, post_list):
 
         osqaa.save()
         badge.awarded_count += 1
 
         osqaa.save()
         badge.awarded_count += 1
+
         user_badge_count[user_id] += 1
 
     readTable(dump, "Users2Badges", callback)
         user_badge_count[user_id] += 1
 
     readTable(dump, "Users2Badges", callback)
@@ -750,10 +776,19 @@ def badges_import(dump, uidmap, post_list):
     for badge in obadges.values():
         badge.save()
 
     for badge in obadges.values():
         badge.save()
 
+def save_setting(k, v):
+    try:
+        kv = orm.KeyValue.objects.get(key=k)
+        kv.value = v
+    except:
+        kv = orm.KeyValue(key = k, value = v)
+
+    kv.save()
+
+
 def pages_import(dump, currid):
     currid = IdIncrementer(currid)
     registry = {}
 def pages_import(dump, currid):
     currid = IdIncrementer(currid)
     registry = {}
-    #sx_pages = readTable(dump, "FlatPages")
 
     def callback(sxp):
         currid.inc()
 
     def callback(sxp):
         currid.inc()
@@ -800,8 +835,7 @@ def pages_import(dump, currid):
 
     readTable(dump, "FlatPages", callback)
 
 
     readTable(dump, "FlatPages", callback)
 
-    kv = orm.KeyValue(key='STATIC_PAGE_REGISTRY', value=dbsafe_encode(registry))
-    kv.save()
+    save_setting('STATIC_PAGE_REGISTRY', dbsafe_encode(registry))
 
 sx2osqa_set_map = {
 u'theme.html.name': 'APP_TITLE',
 
 sx2osqa_set_map = {
 u'theme.html.name': 'APP_TITLE',
@@ -832,28 +866,17 @@ def html_decode(html):
 
 
 def static_import(dump):
 
 
 def static_import(dump):
-#sx_sets = readTable(dump, "ThemeTextResources")
     sx_unknown = {}
 
     def callback(set):
         if unicode(set['name']) in sx2osqa_set_map:
     sx_unknown = {}
 
     def callback(set):
         if unicode(set['name']) in sx2osqa_set_map:
-            try:
-                kv = orm.KeyValue.objects.get(key=sx2osqa_set_map[set['name']])
-                kv.value = dbsafe_encode(html_decode(set['value']))
-            except:
-                kv = orm.KeyValue(
-                        key = sx2osqa_set_map[set['name']],
-                        value = dbsafe_encode(html_decode(set['value']))
-                        )
-
-            kv.save()
+            save_setting(sx2osqa_set_map[set['name']], dbsafe_encode(html_decode(set['value'])))
         else:
             sx_unknown[set['name']] = html_decode(set['value'])
 
     readTable(dump, "ThemeTextResources", callback)
 
         else:
             sx_unknown[set['name']] = html_decode(set['value'])
 
     readTable(dump, "ThemeTextResources", callback)
 
-    unknown = orm.KeyValue(key='SXIMPORT_UNKNOWN_SETS', value=dbsafe_encode(sx_unknown))
-    unknown.save()
+    save_setting('SXIMPORT_UNKNOWN_SETS', dbsafe_encode(sx_unknown))
 
 def disable_triggers():
     from south.db import db
 
 def disable_triggers():
     from south.db import db