From 4114c692dbb5163885eb0d3c6d48ca3c3eeb14e7 Mon Sep 17 00:00:00 2001
From: juanf <juanf>
Date: Thu, 21 Sep 2017 12:04:16 +0000
Subject: [PATCH] SSDM-4223 : Jupyter integration - reopening past notebooks +
 updating correct parents to children datasets

SVN: 38743
---
 .../eln-lims/html/js/config/Profile.js        |  6 +-
 .../eln-lims/html/js/util/JupyterUtil.js      | 87 ++++++++++++++++---
 .../widgets/JupyterCopyNotebookController.js  |  4 +-
 .../widgets/JupyterCopyNotebookView.js        |  2 +-
 4 files changed, 81 insertions(+), 18 deletions(-)

diff --git a/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/config/Profile.js b/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/config/Profile.js
index d2a6a4ad378..60cc1dac5d7 100644
--- a/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/config/Profile.js
+++ b/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/config/Profile.js
@@ -124,9 +124,9 @@ $.extend(DefaultProfile.prototype, {
 //		jupyterhub -f jupyterhub_config.py --no-ssl
 		
 //		Jupyter integration config
-//		this.jupyterOpenbisEndpoint = "http://10.0.2.2:8888"; //Should not end with slash
-//		this.jupyterIntegrationServerEndpoint = "https://127.0.0.1:8123";
-//		this.jupyterEndpoint = "http://127.0.0.1:8000/";
+		this.jupyterOpenbisEndpoint = "http://10.0.2.2:8888"; //Should not end with slash
+		this.jupyterIntegrationServerEndpoint = "https://127.0.0.1:8123";
+		this.jupyterEndpoint = "http://127.0.0.1:8000/";
 		
 		this.forcedDisableRTF = ["FREEFORM_TABLE_STATE","NAME", "SEQUENCE"];
 		this.forceMonospaceFont = ["SEQUENCE"];
diff --git a/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/util/JupyterUtil.js b/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/util/JupyterUtil.js
index 9734331cfc9..6b3235ec958 100644
--- a/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/util/JupyterUtil.js
+++ b/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/util/JupyterUtil.js
@@ -21,19 +21,49 @@ var JupyterUtil = new function() {
 		jupyterNotebook.init();
 	}
 	
-	this.openJupyterNotebookFromTemplate = function(folder, fileName, template) {
+	this.openJupyterNotebookFromTemplate = function(folder, fileName, template, dataSetId) {
 		fileName = fileName + ".ipynb";
 		var jupyterURL = profile.jupyterIntegrationServerEndpoint + "?token=" + mainController.serverFacade.openbisServer.getSession() + "&folder=" + folder + "&filename=" + fileName;
 		var jupyterNotebookURL = profile.jupyterEndpoint + "user/" + mainController.serverFacade.getUserId() + "/notebooks/" + folder + "/";
 		
 		$.ajax({
-            url : jupyterURL,
+            url : jupyterURL + "&test=True",
             type : 'POST',
             crossDomain: true,
-            data : template,
+            data : "TEST",
             success : function(result) {
-            	var win = window.open(jupyterNotebookURL + result.fileName, '_blank');
-				win.focus(); 
+            	fileName =  result.fileName;
+            	var jupyterNotebookJson = JSON.parse(template);
+        		
+        		var autogeneratedWithOpenBIS = false;
+        		for(var cIdx = 0; cIdx < jupyterNotebookJson.cells.length; cIdx++) {
+        			//If was autogenerated with openBIS
+        			if(jupyterNotebookJson.cells[cIdx].source[0] === "# Mark : Autogenerated with openBIS-ELN/LIMS (System Cell, Don't delete!)") {
+        				autogeneratedWithOpenBIS = true;
+        			}
+        			//Fix Name
+        			if(autogeneratedWithOpenBIS && jupyterNotebookJson.cells[cIdx].source[0] === "# Variable - File Name (System Cell, Don't delete!)\n") {
+        				jupyterNotebookJson.cells[cIdx].source[1] = "fileName='" + fileName + "'";
+        			}
+        			//Fix Parents
+        			if(autogeneratedWithOpenBIS && jupyterNotebookJson.cells[cIdx].source[0] === "# Variable : Parents used by the automaticaly generated result dataset (System Cell, Don't delete!)\n") {
+        				jupyterNotebookJson.cells[cIdx].source[1] = "resultDatasetParents=" + JSON.stringify([dataSetId]);
+        			}
+        		}
+        		
+            	$.ajax({
+                    url : jupyterURL + "&test=False",
+                    type : 'POST',
+                    crossDomain: true,
+                    data : JSON.stringify(jupyterNotebookJson),
+                    success : function(result) {
+                    	var win = window.open(jupyterNotebookURL + result.fileName, '_blank');
+        				win.focus(); 
+                    },
+                    error : function(result) {
+                    	alert("error: " + JSON.stringify(result));
+                    }
+        		});
             },
             error : function(result) {
             	alert("error: " + JSON.stringify(result));
@@ -82,10 +112,43 @@ var JupyterUtil = new function() {
 				   "cell_type": "markdown",
 				   "metadata": {},
 				   "source": [
-				    "# Jupyter notebook autogenerated from openBIS-ELN"
+				    "# Jupyter notebook title, modify me!"
 				   ]
 		}
 		content.push(mainTitle);
+		var openbisCell = {
+			      "cell_type": "code",
+			      "execution_count": null,
+			      "metadata": {
+			        "collapsed": true
+			      },
+			      "outputs": [],
+			      "source": ["# Mark : Autogenerated with openBIS-ELN/LIMS (System Cell, Don't delete!)"]
+		};
+		content.push(openbisCell);
+		var fileNameCell = {
+			      "cell_type": "code",
+			      "execution_count": null,
+			      "metadata": {
+			        "collapsed": true
+			      },
+			      "outputs": [],
+			      "source": ["# Variable - File Name (System Cell, Don't delete!)\n",
+			                 "fileName='" + fileName + "'"]
+		};
+		content.push(fileNameCell);
+		var parentsCell = {
+			      "cell_type": "code",
+			      "execution_count": null,
+			      "metadata": {
+			        "collapsed": true
+			      },
+			      "outputs": [],
+			      "source": ["# Variable : Parents used by the automaticaly generated result dataset (System Cell, Don't delete!)\n",
+			                 "resultDatasetParents=" + JSON.stringify(dataSetIds)]
+		};
+		content.push(parentsCell);
+		
 		var connectTitle = {
 				   "cell_type": "markdown",
 				   "metadata": {},
@@ -178,18 +241,19 @@ var JupyterUtil = new function() {
 				   "cell_type": "markdown",
 				   "metadata": {},
 				   "source": [
-				    "### Create Result Dataset with current notebook and HTML version with the output (save the notebook first!)"
+				    "### Result Dataset, it will hold the current notebook and HTML version with the output (press save before executing this!)"
 				   ]
 		}
 		content.push(saveTitle);
+		
 		var createHTML = [
 					        "from nbconvert import HTMLExporter\n",
 					        "import codecs\n",
 					        "import nbformat\n",
 					        "exporter = HTMLExporter()\n",
-					        "output_notebook = nbformat.read('" + fileName + "', as_version=4)\n",
+					        "output_notebook = nbformat.read(fileName, as_version=4)\n",
 					        "output, resources = exporter.from_notebook_node(output_notebook)\n",
-					        "codecs.open('" + fileName + ".html', 'w', encoding='utf-8').write(output)\n",
+					        "codecs.open(fileName + '.html', 'w', encoding='utf-8').write(output)\n",
 					        "\n"
 		];
 		
@@ -204,14 +268,13 @@ var JupyterUtil = new function() {
 				break;
 		}
 		
-		var parents = JSON.stringify(dataSetIds);
 		
 		var createDataset = [
 		                     "ds_new = o.new_dataset(\n",
 		                     "type='ANALYZED_DATA',\n",
 		                     ownerSettings,
-		                     "parents=" + parents + ",\n",
-		                     "files = ['" + fileName + "', '" + fileName + ".html'],\n",
+		                     "parents=resultDatasetParents,\n",
+		                     "files = [fileName, fileName + '.html'],\n",
 		                     "props={'name': 'Name your dataset!', 'notes': 'Write some notes or delete this property!'}\n",
 		                     ")\n",
 		                     "ds_new.save()"
diff --git a/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/views/DataSetForm/widgets/JupyterCopyNotebookController.js b/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/views/DataSetForm/widgets/JupyterCopyNotebookController.js
index 2b096a86d09..5895631461c 100644
--- a/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/views/DataSetForm/widgets/JupyterCopyNotebookController.js
+++ b/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/views/DataSetForm/widgets/JupyterCopyNotebookController.js
@@ -22,8 +22,8 @@ function JupyterCopyNotebookController(datasetCode, existingNotebookURL) {
 		this._jupyterNotebookView.repaint();
 	}
 	
-	this.create = function(workspace, notebook, existingNotebookURL) {
-		JupyterUtil.openJupyterNotebookFromTemplate(workspace, notebook, existingNotebookURL);
+	this.create = function(workspace, notebook, existingNotebookURL, datasetCode) {
+		JupyterUtil.openJupyterNotebookFromTemplate(workspace, notebook, existingNotebookURL, datasetCode);
 		Util.unblockUI();
 	}
 }
\ No newline at end of file
diff --git a/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/views/DataSetForm/widgets/JupyterCopyNotebookView.js b/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/views/DataSetForm/widgets/JupyterCopyNotebookView.js
index b55edfbc0e6..81de70bb1ce 100644
--- a/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/views/DataSetForm/widgets/JupyterCopyNotebookView.js
+++ b/openbis_standard_technologies/dist/core-plugins/eln-lims/1/as/webapps/eln-lims/html/js/views/DataSetForm/widgets/JupyterCopyNotebookView.js
@@ -32,7 +32,7 @@ function JupyterCopyNotebookView(jupyterNotebookController, jupyterNotebookModel
 		var $btnAccept = $('<input>', { 'type': 'submit', 'class' : 'btn btn-primary', 'value' : 'Accept' });
 		$window.submit(function() {
 			$.get(_this._jupyterNotebookModel.existingNotebookURL, function( data ) {
-				_this._jupyterNotebookController.create($workspace.val(), $notebookName.val(), data);
+				_this._jupyterNotebookController.create($workspace.val(), $notebookName.val(), data, _this._jupyterNotebookModel.datasetCode);
 			});
 		});
 		var $btnCancel = $('<a>', { 'class' : 'btn btn-default' }).append('Cancel');
-- 
GitLab