enforce valid package url
enforce valid package url


Former-commit-id: 26accf46eff2958223ffae9a1234d4291379bce4

--- a/documents/datagov-export.py
+++ b/documents/datagov-export.py
@@ -91,9 +91,10 @@
     name = re.sub('__', '_', name).lower()
     return name
 
-
+#todo "{'name': [u'Url must be purely lowercase alphanumeric (ascii) characters and these symbols: -_']}"
+# http://data.gov.au/dataset/australian-domestic-regional-and-international-airline-activity-%E2%80%93-time-series/
 def name_munge(input_name):
-    return munge(input_name.replace(' ', '').replace('.', '_').replace('&', 'and'))
+    return  munge(input_name.replace(' ', '').replace('.', '_').replace('&', 'and'))
     #[:100]
     #return input_name.replace(' ', '').replace('.', '_').replace('&', 'and')
 
@@ -124,7 +125,7 @@
         print doc.id
         if doc.value['url'] != "http://data.gov.au/data/" and doc.value['agencyID'] != "qld":
             # Collect the package metadata.
-            pkg_name = doc.value['url'].replace("http://data.gov.au/dataset/",'').replace('/','')[:100];
+            pkg_name = filter( lambda x: x in '0123456789abcdefghijklmnopqrstuvwxyz-_',doc.value['url'].replace("http://data.gov.au/dataset/",'').replace('/','')[:100]);
             tags = []
             if doc.value['agencyID'] == "AGIMO":
                 if len(doc.value['metadata']["Keywords / Tags"]) > 0:
@@ -166,71 +167,73 @@
 
             #add to group
 
-            # group_name = name_munge(doc.value['metadata']["Agency"][:100])
+            group_name = name_munge(doc.value['metadata']["Agency"][:100])
+            try:
+                print ckan.group_entity_get(group_name)
+
+                # Update the group details
+                group_entity = ckan.last_message
+                print "group exists"
+                if 'packages' in group_entity.keys():
+                    group_entity['packages'] = list(set(group_entity['packages'] + [pkg_name]))
+                else:
+                    group_entity['packages'] = [pkg_name]
+                ckan.group_entity_put(group_entity)
+            except CkanApiError, e:
+                if ckan.last_status == 404:
+                    print "group does not exist, creating"
+                    group_entity = {
+                        'name': group_name,
+                        'title': doc.value['metadata']["Agency"],
+                        'description': doc.value['metadata']["Agency"],
+                        'packages': [pkg_name],
+                        # 'type': "organization" # not allowed via API, use database query
+                        # update "group" set type = 'organization';
+                        }
+                    print group_entity
+                    ckan.group_register_post(group_entity)
+                elif ckan.last_status == 409:
+		    print "group already exists"
+                else:
+                    raise LoaderError('Unexpected status %s adding to group under \'%s\': %r' % (
+                        ckan.last_status, pkg_name, e.args))
+
+            # #add to or create organization using direct API
+            # org_name = name_munge(doc.value['metadata']["Agency"][:100])
+            # if org_name not in orgs_list:
+            #     orgs_list = ckandirect.action.organization_list()['result']
+            #     print orgs_list
+            #     if org_name not in orgs_list:
+            #         try:
+            #             print "org not found, creating "+org_name
+            #             ckandirect.action.organization_create(name = org_name,   title= doc.value['metadata']["Agency"],
+            #                                                           description= doc.value['metadata']["Agency"])
+            #             orgs_list.append(org_name)
+            #         except ckanapi.ValidationError, e:
+            #             print e
+            #             raise LoaderError('Unexpected status')
+            #
             # try:
-             #    print ckan.group_entity_get(group_name)
-            #
-             #    # Update the group details
-             #    group_entity = ckan.last_message
-             #    print "group exists"
-             #    if 'packages' in group_entity.keys():
-             #        group_entity['packages'] = list(set(group_entity['packages'] + [pkg_name]))
-             #    else:
-             #        group_entity['packages'] = [pkg_name]
-             #    ckan.group_entity_put(group_entity)
-            # except CkanApiError, e:
-             #    if ckan.last_status == 404:
-             #        print "group does not exist, creating"
-             #        group_entity = {
-             #            'name': group_name,
-             #            'title': doc.value['metadata']["Agency"],
-             #            'description': doc.value['metadata']["Agency"],
-             #            'packages': [pkg_name],
-             #            # 'type': "organization" # not allowed via API, use database query
-             #            # update "group" set type = 'organization';
-             #            }
-             #        print group_entity
-             #        ckan.group_register_post(group_entity)
-             #    elif ckan.last_status == 409:
-		    # print "group already exists"
-             #    else:
-             #        raise LoaderError('Unexpected status %s adding to group under \'%s\': %r' % (
-             #            ckan.last_status, pkg_name, e.args))
-
-            #add to or create organization using direct API
-            org_name = name_munge(doc.value['metadata']["Agency"][:100])
-            if org_name not in orgs_list:
-                orgs_list = ckandirect.action.organization_list()['result']
-                print orgs_list
-                if org_name not in orgs_list:
-                    try:
-                        print "org not found, creating "+org_name
-                        ckandirect.action.organization_create(name = org_name,   title= doc.value['metadata']["Agency"],
-                                                                      description= doc.value['metadata']["Agency"])
-                        orgs_list.append(org_name)
-                    except ckanapi.ValidationError, e:
-                        print e
-                        raise LoaderError('Unexpected status')
-
-            try:
-                print "linking package to "+org_name
-
-               #brute force
-                org = ckandirect.action.organization_show(id=org_name)
-                #print org["result"]["packages"]
-                #print pkg
-                org["result"]["packages"].append({"id":pkg['id'], "name": pkg_name})
-                #print org["result"]
-                ckandirect.call_action(action="organization_update", data_dict=org["result"])
-
-                # if only this worked
-                #print ckandirect.action.package_owner_org_update(id=pkg['id'],organization_id=org["result"]["id"])
-
-            except ckanapi.ValidationError, e:
-                print e
-                raise LoaderError('Unexpected status')
-            #except ckanapi.CKANAPIError, e:
-            #    print "lol"
+            #     print "linking package to "+org_name
+            #
+            #    #brute force
+            #     org = ckandirect.action.organization_show(id=org_name)
+            #     #print org["result"]["packages"]
+            #     #print pkg
+            #     org["result"]["packages"].append({"id":pkg['id'], "name": pkg_name})
+            #     #print org["result"]
+            #     ckandirect.call_action(action="organization_update", data_dict=org["result"])
+            #
+            #     # if only this worked
+            #     print ckandirect.action.package_owner_org_update(id=pkg['id'],organization_id=org["result"]["id"])
+            #
+            # except ckanapi.ValidationError, e:
+            #     print e
+            #     raise LoaderError('Unexpected status')
+            # except ckanapi.CKANAPIError, e:
+            #     print "lol"
+
+
 
             if 'Download' in doc.value['metadata'].keys():
                 try: