Repository: OCHA-DAP/hdx-ckan

Issue:
Related Item: change redirect on saving an edit
After editing and saving (or canceling) on a related item, the user is redirected to (for example) https://test-data.hdx.rwlabs.org/dataset/proportion_of_the_population_using_improved_sanitation_facilities/related?__no_cache__=True

Change it to redirect to the indicator page.



Discussion:

Resolving patch:
diff --git a/ckan/controllers/related.py b/ckan/controllers/related.py
--- a/ckan/controllers/related.py
+++ b/ckan/controllers/related.py
@@ -185,8 +185,10 @@ def _edit_or_new(self, id, related_id, is_edit):
                 else:
                     h.flash_success(_("Related item was successfully updated"))
 
+                #h.redirect_to(
+                #    controller='related', action='list', id=c.pkg_dict['name'])
                 h.redirect_to(
-                    controller='related', action='list', id=c.pkg_dict['name'])
+                    controller='ckanext.hdx_package.controllers.dataset_controller:DatasetController', action='read', id=c.pkg_dict['name'])
             except df.DataError:
                 base.abort(400, _(u'Integrity Error'))
             except logic.ValidationError, e:
diff --git a/ckanext-hdx_package/ckanext/hdx_package/controllers/storage_controller.py b/ckanext-hdx_package/ckanext/hdx_package/controllers/storage_controller.py
--- a/ckanext-hdx_package/ckanext/hdx_package/controllers/storage_controller.py
+++ b/ckanext-hdx_package/ckanext/hdx_package/controllers/storage_controller.py
@@ -19,13 +19,13 @@
 import ckan.logic as logic
 
 try:
-	from cStringIO import StringIO
+    from cStringIO import StringIO
 except ImportError:
-	from StringIO import StringIO
+    from StringIO import StringIO
 try:
-	import json
+    import json
 except:
-	import simplejson as json
+    import simplejson as json
 
 from logging import getLogger
 log = getLogger(__name__)
@@ -38,38 +38,60 @@
 
 
 class FileDownloadController(storage.StorageController):
-	_ofs_impl = None
-
-	@property
-	def ofs(self):
-		if not FileDownloadController._ofs_impl:
-			FileDownloadController._ofs_impl = get_ofs()
-		return FileDownloadController._ofs_impl
-
-	def file(self, label):
-		exists = self.ofs.exists(BUCKET, label)
-		if not exists:
-			# handle erroneous trailing slash by redirecting to url w/o slash
-			if label.endswith('/'):
-				label = label[:-1]
-				# This may be best being cached_url until we have moved it into
-				# permanent storage
-				file_url = h.url_for('storage_file', label=label)
-				h.redirect_to(file_url)
-			else:
-				abort(404)
-
-		file_url = self.ofs.get_url(BUCKET, label)
-		if file_url.startswith("file://") or file_url.endswith('xlsx'):
-			metadata = self.ofs.get_metadata(BUCKET, label)
-			filepath = file_url[len("file://"):]
-			headers = {
-				# 'Content-Disposition':'attachment; filename="%s"' % label,
-				'Content-Type': metadata.get('_format', 'text/plain')}
-			fapp = FileApp(filepath, headers=None, **headers)
-			return fapp(request.environ, self.start_response)
-		else:
-			h.redirect_to(file_url.encode('ascii', 'ignore'))
+    _ofs_impl = None
+
+    @property
+    def ofs(self):
+        if not FileDownloadController._ofs_impl:
+            FileDownloadController._ofs_impl = get_ofs()
+        return FileDownloadController._ofs_impl
+
+    def file(self, label):
+        from sqlalchemy.engine import create_engine
+        #from label find resource id
+        url = config.get('ckan.site_url', '') +'/storage/f/'+ urllib.quote(label)
+        engine = create_engine(config.get('sqlalchemy.url', ''), echo=True)
+        connection = engine.connect()
+        query = connection.execute("""SELECT * from resource where url= %s""", (url,))
+        res = query.fetchone()
+        if not res:
+            raise logic.NotFound
+        
+        # We need this as a resource object to check access so create a dummy obj and trick CKAN
+        resource = model.Resource()
+        for k in res.keys():
+            setattr(resource,k,res[k])
+        
+        context = {'model': model, 'session': model.Session,
+                   'user': c.user or c.author, 'for_view': True,
+                   'auth_user_obj': c.userobj, 'resource':resource}
+        data_dict = {'id': resource.id}
+
+        logic.check_access('resource_show', context, data_dict)
+
+        exists = self.ofs.exists(BUCKET, label)
+        if not exists:
+            # handle erroneous trailing slash by redirecting to url w/o slash
+            if label.endswith('/'):
+                label = label[:-1]
+                # This may be best being cached_url until we have moved it into
+                # permanent storage
+                file_url = h.url_for('storage_file', label=label)
+                h.redirect_to(file_url)
+            else:
+                abort(404)
+
+        file_url = self.ofs.get_url(BUCKET, label)
+        if file_url.startswith("file://") or file_url.endswith('xlsx'):
+            metadata = self.ofs.get_metadata(BUCKET, label)
+            filepath = file_url[len("file://"):]
+            headers = {
+                # 'Content-Disposition':'attachment; filename="%s"' % label,
+                'Content-Type': metadata.get('_format', 'text/plain')}
+            fapp = FileApp(filepath, headers=None, **headers)
+            return fapp(request.environ, self.start_response)
+        else:
+            h.redirect_to(file_url.encode('ascii', 'ignore'))
 
 
 
@@ -90,18 +112,18 @@ def create_pairtree_marker(folder):
 
 
 def get_ofs():
-		"""Return a configured instance of the appropriate OFS driver.
-		"""
-		storage_backend = config['ofs.impl']
-		kw = {}
-		for k, v in config.items():
-			if not k.startswith('ofs.') or k == 'ofs.impl':
-				continue
-			kw[k[4:]] = v
-
-		# Make sure we have created the marker file to avoid pairtree issues
-		if storage_backend == 'pairtree' and 'storage_dir' in kw:
-			create_pairtree_marker(kw['storage_dir'])
-
-		ofs = get_impl(storage_backend)(**kw)
-		return ofs
\ No newline at end of file
+        """Return a configured instance of the appropriate OFS driver.
+        """
+        storage_backend = config['ofs.impl']
+        kw = {}
+        for k, v in config.items():
+            if not k.startswith('ofs.') or k == 'ofs.impl':
+                continue
+            kw[k[4:]] = v
+
+        # Make sure we have created the marker file to avoid pairtree issues
+        if storage_backend == 'pairtree' and 'storage_dir' in kw:
+            create_pairtree_marker(kw['storage_dir'])
+
+        ofs = get_impl(storage_backend)(**kw)
+        return ofs
\ No newline at end of file


Test patch: