src/ldtplatform/management/commands/loadandadddata.py
changeset 69 329b4aa82e22
child 70 6c39cfabefc8
equal deleted inserted replaced
68:19068468fa03 69:329b4aa82e22
       
     1 # -*- coding: utf-8 -*-
       
     2 '''
       
     3 Created on Mar 22, 2013
       
     4 
       
     5 @author: tc
       
     6 '''
       
     7 
       
     8 from ..utils import show_progress
       
     9 from django.contrib.auth.models import User, Group
       
    10 from django.core.management import call_command
       
    11 from django.core.management.base import BaseCommand, CommandError
       
    12 from ldt.ldt_utils.models import Content, Project
       
    13 from optparse import make_option
       
    14 import os.path
       
    15 import json
       
    16 from ldt.security.cache import cached_assign
       
    17 
       
    18 
       
    19 class Command(BaseCommand):
       
    20     '''
       
    21     Load users, medias, contents, project and guardian permissions from json file generated by dumpdata
       
    22     '''
       
    23 
       
    24     args = 'json_file'
       
    25     help = 'Load users, medias, contents, project and guardian permissions from json file generated by dumpdata'
       
    26     
       
    27     option_list = BaseCommand.option_list + (
       
    28         make_option('-u', '--ignore-users',
       
    29             dest= 'ignore_users',
       
    30             default= None,
       
    31             help= 'list of usernames to ignore (separated by comma)'
       
    32         ),
       
    33         make_option('-g', '--ignore-groups',
       
    34             dest= 'ignore_groups',
       
    35             default= None,
       
    36             help= 'list of group names to ignore (separated by comma)'
       
    37         ),
       
    38         make_option('-c', '--ignore-contents',
       
    39             dest= 'ignore_contents',
       
    40             default= None,
       
    41             help= 'list of content iri_id to ignore (separated by comma)'
       
    42         ),
       
    43         make_option('-n', '--new-group',
       
    44             dest= 'new_group',
       
    45             default= None,
       
    46             help= 'The script will create a new group and assign view permission for all new media/contents to all the new users'
       
    47         ),
       
    48     )
       
    49     
       
    50     
       
    51     def __safe_get(self, dict_arg, key, conv = lambda x: x, default= None):
       
    52         val = dict_arg.get(key, default)
       
    53         return conv(val) if val else default
       
    54 
       
    55     def __safe_decode(self, s):
       
    56         if not isinstance(s, basestring):
       
    57             return s
       
    58         try:
       
    59             return s.decode('utf8')
       
    60         except:
       
    61             try:
       
    62                 return s.decode('latin1')
       
    63             except:
       
    64                 return s.decode('utf8','replace')
       
    65 
       
    66     def handle(self, *args, **options):
       
    67         
       
    68         # Test path
       
    69         if len(args) != 1:
       
    70             raise CommandError("The command has no argument or too much arguments. Only one is needed : the json file path.")
       
    71         
       
    72         # Check if temporary files already exist
       
    73         path = os.path.abspath(args[0])
       
    74         dir = os.path.dirname(path)
       
    75         path_file1 = os.path.join(dir, 'temp_data1.json')
       
    76         path_file2 = os.path.join(dir, 'temp_data2.json')
       
    77         do_import = True
       
    78         if os.path.exists(path_file1) or os.path.exists(path_file2):
       
    79             confirm = raw_input(("""
       
    80     The folder %s contains the files temp_data1.json or temp_data2.json. These files will be overwritten.
       
    81     
       
    82     Do you want to continue ?
       
    83 
       
    84     Type 'y' to continue, or 'n' to quit: """) % dir)
       
    85             do_import = (confirm == "y")
       
    86         
       
    87         # Continue
       
    88         if do_import:
       
    89             # Init ignore list
       
    90             user_ignore_list = ["admin","AnonymousUser"]
       
    91             group_ignore_list = ["everyone"]
       
    92             content_ignore_list = []
       
    93             
       
    94             # Update ignore list
       
    95             ignore_users = options.get('ignore_users', None)
       
    96             ignore_groups = options.get('ignore_groups', None)
       
    97             ignore_contents = options.get('ignore_contents', None)
       
    98             if ignore_users:
       
    99                 for u in ignore_users.split(","):
       
   100                     user_ignore_list.append(u)
       
   101             if ignore_groups:
       
   102                 for g in ignore_groups.split(","):
       
   103                     group_ignore_list.append(g)
       
   104             if ignore_contents:
       
   105                 for c in ignore_contents.split(","):
       
   106                     content_ignore_list.append(c)
       
   107             
       
   108             # Begin work...
       
   109             print("Opening file...")
       
   110             json_file = open(path,'rb')
       
   111             print("Loading datas...")
       
   112             data = json.load(json_file)
       
   113             print("%d objects found..." % len(data))
       
   114             content_pk_id = {}
       
   115             project_pk_id = {}
       
   116             # datas for file 1 : users, medias, contents, projects 
       
   117             data_file1 = []
       
   118             # datas for file 2 : guardian permissions
       
   119             data_file2 = []
       
   120             # users
       
   121             usernames = []
       
   122             for obj in data:
       
   123                 if "model" in obj:
       
   124                     m = obj["model"]
       
   125                     if m!="guardian.userobjectpermission" and m!="guardian.groupobjectpermission":
       
   126                         # We remove user admin, user AnonymousUser, group everyone and users and contents in ignore list
       
   127                         # (a bit fuzzy for media and src but good for others)
       
   128                         if not ((m=="auth.user" and "username" in obj["fields"] and obj["fields"]["username"] in user_ignore_list) or \
       
   129                                 (m=="auth.group" and "name" in obj["fields"] and obj["fields"]["name"] in group_ignore_list) or \
       
   130                                 (m=="ldt_utils.media" and "src" in obj["fields"] and any(s in obj["fields"]["src"] for s in content_ignore_list)) or \
       
   131                                 (m=="ldt_utils.content" and "iri_id" in obj["fields"] and obj["fields"]["iri_id"] in content_ignore_list)):
       
   132                             data_file1.append(obj)
       
   133                         #else:
       
   134                         #   print("I don't keep from datas %s, pk = %s" % (m, obj["pk"]))
       
   135                         if "pk" in obj:
       
   136                             # For both contents and projects, we save 2 dicts [id]=pk and [pk]=id
       
   137                             # It will enable to parse and replace easily the old pk by the new ones in the permission datas
       
   138                             if m=="ldt_utils.project":
       
   139                                 pk = str(obj["pk"])
       
   140                                 id = obj["fields"]["ldt_id"]
       
   141                                 project_pk_id[pk] = id
       
   142                             elif m=="ldt_utils.content":
       
   143                                 pk = str(obj["pk"])
       
   144                                 id = obj["fields"]["iri_id"]
       
   145                                 content_pk_id[pk] = id
       
   146                             obj["pk"] = None
       
   147                     else:
       
   148                         obj["pk"] = None
       
   149                         data_file2.append(obj)
       
   150                     # Save usernames except AnonymousUser 
       
   151                     if m=="auth.user" and "username" in obj["fields"] and obj["fields"]["username"]!="AnonymousUser":
       
   152                         usernames.append(obj["fields"]["username"])
       
   153             json_file.close()
       
   154             #data_file1.append(project_pk_id)
       
   155             #data_file1.append(project_id_pk)
       
   156             #data_file1.append(content_pk_id)
       
   157             #data_file1.append(content_id_pk)
       
   158             
       
   159             # We save the datas in a file in order to simply call loaddata
       
   160             print("Writing %s..." % path_file1)
       
   161             file1 =  open(path_file1, 'w')
       
   162             json.dump(data_file1, file1, indent=2)
       
   163             file1.close()
       
   164             print("Updating permissions ids...")
       
   165             # We replace the old pk by the natural keys in the permission datas
       
   166             ignored_project_pks = []
       
   167             ignored_content_pks = []
       
   168             perm_data = []
       
   169             for obj in data_file2:
       
   170                 type = obj["fields"]["content_type"][1]
       
   171                 old_pk = obj["fields"]["object_pk"]
       
   172                 if type=="project":
       
   173                     try:
       
   174                         obj["fields"]["object_pk"] = project_pk_id[old_pk]
       
   175                     except:
       
   176                         # The dumpdata can contain permissions for removed projects
       
   177                         ignored_project_pks.append(old_pk)
       
   178                         continue
       
   179                     # Keeping only valuables objs avoids errors when we we get the new pks
       
   180                     perm_data.append(obj)
       
   181                 elif type == "content":
       
   182                     try:
       
   183                         obj["fields"]["object_pk"] = content_pk_id[old_pk]
       
   184                     except:
       
   185                         # The dumpdata can contain permissions for removed contents
       
   186                         ignored_content_pks.append(old_pk)
       
   187                         continue
       
   188                     # Keeping only valuables objs avoids errors when we we get the new pks
       
   189                     perm_data.append(obj)
       
   190             # We inform the user
       
   191             print("%d project permissions were ignored because projects do not exist in the current datas." % len(ignored_project_pks))
       
   192             print("%d content permissions were ignored because contents do not exist in the current datas." % len(ignored_content_pks))
       
   193             print("Loading datas from temporary file %s ..." % path_file1)
       
   194             # Loaddata from file 1
       
   195             call_command("loaddata", path_file1)
       
   196             
       
   197             # Now users, medias, contents, projects have been saved.
       
   198             # We can get the new pk for contents and projects
       
   199             # Careful: in Python 3, dict.copy().values() will be prefered to list(dict.values())
       
   200             # We use select_related("media_obj") because it will usefull with the new group
       
   201             contents = Content.objects.filter(iri_id__in=list(content_pk_id.values())).select_related("media_obj")#.values('pk', 'iri_id')
       
   202             content_id_pk = {}
       
   203             for c in contents:
       
   204                 content_id_pk[c.iri_id] = str(c.pk)
       
   205             projects = Project.objects.filter(ldt_id__in=list(project_pk_id.values())).values('pk', 'ldt_id')
       
   206             project_id_pk = {}
       
   207             for p in projects:
       
   208                 project_id_pk[p["ldt_id"]] = str(p["pk"])
       
   209             
       
   210             # Now we reparse the perm_data and update with the new pks
       
   211             for obj in perm_data:
       
   212                 type = obj["fields"]["content_type"][1]
       
   213                 obj_id = obj["fields"]["object_pk"]
       
   214                 if type=="project":
       
   215                     obj["fields"]["object_pk"] = project_id_pk[obj_id]
       
   216                 elif type == "content":
       
   217                     obj["fields"]["object_pk"] = content_id_pk[obj_id]
       
   218             
       
   219             
       
   220             # We save the datas in a file in order to simply call loaddata
       
   221             print("Writing %s..." % path_file2)
       
   222             file2 =  open(path_file2, 'w')
       
   223             json.dump(perm_data, file2, indent=2)
       
   224             file2.close()
       
   225             print("Loading permissions from temporary file %s ..." % path_file2)
       
   226             call_command("loaddata", path_file2)
       
   227             
       
   228             # Remove temp files
       
   229             print("Removing temporary files...")
       
   230             try:
       
   231                 os.remove(path_file1)
       
   232             except:
       
   233                 print("Removing temporary files %s failed" % path_file1)
       
   234             try:
       
   235                 os.remove(path_file2)
       
   236             except:
       
   237                 print("Removing temporary files %s failed" % path_file2)
       
   238             
       
   239             # Now that all datas have been imported we can create the new group and assign permissions if asked
       
   240             new_group = options.get('new_group', None)
       
   241             if new_group and len(usernames)>0:
       
   242                 print("Set view permissions for the new group %s ..." % new_group)
       
   243                 # Get or create group
       
   244                 new_grp, _ = Group.objects.get_or_create(name=new_group)
       
   245                 # Add users to the group
       
   246                 users = User.objects.filter(username__in=usernames)
       
   247                 for u in users:
       
   248                     new_grp.user_set.add(u)
       
   249                 # Get all contents and medias
       
   250                 for c in contents:
       
   251                     cached_assign('view_content', new_grp, c)
       
   252                     cached_assign('view_media', new_grp, c.media_obj)
       
   253                 
       
   254             print("Indexing imported projects ...")
       
   255             call_command('reindex', projects=True, no_content=True)
       
   256         
       
   257         # This is the end
       
   258         print("This is the end")
       
   259         
       
   260