Commit 9e6c6ba7 authored by Roque's avatar Roque

discussion tool: adding hateoas script in app cache

- controller gadget temporarily uses jio_storage to get html-post form
- controller gadget uses -for test- a manually request to hateoas script
- some code cleanup in hateoas script and still a hardcoded form definition for html post only
parent bd9af427
#return "fake hateoas return!!!"
"""Hello. This will be long because this godly script does almost everything. """Hello. This will be long because this godly script does almost everything.
It **always** return a JSON reponse in HATEOAS format specification. It **always** return a JSON reponse in HATEOAS format specification.
...@@ -66,9 +64,6 @@ from Products.ERP5Type.Utils import UpperCase ...@@ -66,9 +64,6 @@ from Products.ERP5Type.Utils import UpperCase
from Products.ZSQLCatalog.SQLCatalog import Query, ComplexQuery from Products.ZSQLCatalog.SQLCatalog import Query, ComplexQuery
from collections import OrderedDict from collections import OrderedDict
log("################################################################")
log("[DEBUG] ERP5Document_getHateoas script was called!!!!!!")
MARKER = [] MARKER = []
COUNT_LIMIT = 1000 COUNT_LIMIT = 1000
...@@ -770,7 +765,6 @@ def renderField(traversed_document, field, form, value=MARKER, meta_type=None, k ...@@ -770,7 +765,6 @@ def renderField(traversed_document, field, form, value=MARKER, meta_type=None, k
# get embedded form definition # get embedded form definition
embedded_form = getattr(formbox_context, field.get_value('formbox_target_id')) embedded_form = getattr(formbox_context, field.get_value('formbox_target_id'))
# renderForm mutates `embedded_document` therefor no return/assignment # renderForm mutates `embedded_document` therefor no return/assignment
log("[DEBUG] calling renderForm from renderField")
renderForm(formbox_context, embedded_form, embedded_document, key_prefix=key) renderForm(formbox_context, embedded_form, embedded_document, key_prefix=key)
# fix editability which is hard-coded to 0 in `renderForm` implementation # fix editability which is hard-coded to 0 in `renderForm` implementation
embedded_document['form_id']['editable'] = field.get_value("editable") embedded_document['form_id']['editable'] = field.get_value("editable")
...@@ -891,7 +885,6 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti ...@@ -891,7 +885,6 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
'name': form.id 'name': form.id
} }
log("[DEBUG] calling calculateHateoas method from renderForm")
response_dict['_embedded'] = { response_dict['_embedded'] = {
'form_definition': calculateHateoas( 'form_definition': calculateHateoas(
traversed_document=form, traversed_document=form,
...@@ -954,12 +947,7 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti ...@@ -954,12 +947,7 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
# Go through all groups ("left", "bottom", "hidden" etc.) and add fields from # Go through all groups ("left", "bottom", "hidden" etc.) and add fields from
# them into form. # them into form.
group_list = [] for group in form.Form_getGroupTitleAndId():
try:
form_groups = form.Form_getGroupTitleAndId()
except:
form_groups = []
for group in form_groups: #form.Form_getGroupTitleAndId():
# Skipping hidden group could be problematic but see MatrixBox Field above # Skipping hidden group could be problematic but see MatrixBox Field above
if 'hidden' in group['gid']: if 'hidden' in group['gid']:
continue continue
...@@ -1066,7 +1054,6 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti ...@@ -1066,7 +1054,6 @@ def renderForm(traversed_document, form, response_dict, key_prefix=None, selecti
# addressable by the user = have actions (object_view) attached to it # addressable by the user = have actions (object_view) attached to it
# BUT! when Report Section defines `path` that is the new context for # BUT! when Report Section defines `path` that is the new context for
# form rendering and subsequent searches... # form rendering and subsequent searches...
log("[DEBUG] calling renderForm recursively from renderForm")
renderForm(traversed_document if not report_item.path else report_context, renderForm(traversed_document if not report_item.path else report_context,
report_form, report_form,
report_result, report_result,
...@@ -1097,11 +1084,7 @@ def renderFormDefinition(form, response_dict): ...@@ -1097,11 +1084,7 @@ def renderFormDefinition(form, response_dict):
Dialog Form such as dialog_id. Dialog Form such as dialog_id.
""" """
group_list = [] group_list = []
try: for group in form.Form_getGroupTitleAndId():
form_groups = form.Form_getGroupTitleAndId()
except:
form_groups = []
for group in form_groups: #form.Form_getGroupTitleAndId():
if group['gid'].find('hidden') < 0: if group['gid'].find('hidden') < 0:
field_list = [] field_list = []
...@@ -1168,20 +1151,13 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1168,20 +1151,13 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
if extra_param_json is None: if extra_param_json is None:
extra_param_json = {} extra_param_json = {}
is_context_appcache = False
try:
href = traversed_document.Base_getRequestUrl()
except:
is_context_appcache = True
href = "https://softinst112382.host.vifib.net/erp5/web_site_module/officejs_discussion_tool/portal_skins/erp5_officejs_jio_connector/HTMLPost_viewAsJio/ERP5Form_viewAsJio"
result_dict = { result_dict = {
'_debug': mode, '_debug': mode,
'_links': { '_links': {
"self": { "self": {
# XXX Include query parameters # XXX Include query parameters
# FIXME does not work in case of bulk queries # FIXME does not work in case of bulk queries
"href": href #traversed_document.Base_getRequestUrl() "href": traversed_document.Base_getRequestUrl()
}, },
# Always inform about site root # Always inform about site root
"site_root": { "site_root": {
...@@ -1216,7 +1192,10 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1216,7 +1192,10 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
'status': statusLevelToString(portal_status_level) 'status': statusLevelToString(portal_status_level)
} }
if (restricted == 1) and (portal.portal_membership.isAnonymousUser()): if (restricted == 1) and (portal.portal_membership.isAnonymousUser()):
#if False:
#when appcache tries to call this script it fails due unauthorized if not logged in
login_relative_url = site_root.getLayoutProperty("configuration_login", default="") login_relative_url = site_root.getLayoutProperty("configuration_login", default="")
if (login_relative_url): if (login_relative_url):
response.setHeader( response.setHeader(
...@@ -1229,7 +1208,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1229,7 +1208,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
response.setStatus(401) response.setStatus(401)
return "" return ""
elif not is_context_appcache and mime_type != traversed_document.Base_handleAcceptHeader([mime_type]): elif mime_type != traversed_document.Base_handleAcceptHeader([mime_type]):
response.setStatus(406) response.setStatus(406)
return "" return ""
...@@ -1293,37 +1272,20 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1293,37 +1272,20 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
} }
# Find current action URL and extract embedded view # Find current action URL and extract embedded view
try:
erp5_action_dict = portal.Base_filterDuplicateActions( erp5_action_dict = portal.Base_filterDuplicateActions(
portal.portal_actions.listFilteredActionsFor(traversed_document)) portal.portal_actions.listFilteredActionsFor(traversed_document))
except AttributeError as error:
erp5_action_dict = {}
for erp5_action_key in erp5_action_dict.keys(): for erp5_action_key in erp5_action_dict.keys():
for view_action in erp5_action_dict[erp5_action_key]: for view_action in erp5_action_dict[erp5_action_key]:
# Try to embed the form in the result # Try to embed the form in the result
if (view == view_action['id']): if (view == view_action['id']):
current_action = parseActionUrl('%s' % view_action['url']) # current action/view being rendered current_action = parseActionUrl('%s' % view_action['url']) # current action/view being rendered
log("[DEBUG] current_action and view_id stuff with current_action: ")
log(current_action)
#if is_context_appcache:
# current_action['url'] = 'https://softinst112382.host.vifib.net/erp5/web_site_module/officejs_discussion_tool/portal_skins/erp5_officejs_jio_connector/HTMLPost_viewAsJio/ERP5Form_viewAsJio'
# current_action['view_id'] = "ERP5Form_viewAsJio"
# current_action['params'] = {}
if view and (view != 'view') and (current_action.get('view_id', None) is None): if view and (view != 'view') and (current_action.get('view_id', None) is None):
# XXX Allow to directly render a form # XXX Allow to directly render a form
current_action['view_id'] = view current_action['view_id'] = view
current_action['url'] = '%s/%s' % (traversed_document.getRelativeUrl(), view) current_action['url'] = '%s/%s' % (traversed_document.getRelativeUrl(), view)
current_action['params'] = {} current_action['params'] = {}
if current_action.get('view_id', None) is not None:
if is_context_appcache:
current_action['view_id'] = "ERP5Form_viewAsJio"
log("[DEBUG] FINAL current_action['view_id']: " + str(current_action['view_id']))
log("")
# If we have current action definition we are able to render embedded view # If we have current action definition we are able to render embedded view
# which should be a "ERP5 Form" but in reality can be anything # which should be a "ERP5 Form" but in reality can be anything
if current_action.get('view_id', ''): if current_action.get('view_id', ''):
...@@ -1367,7 +1329,6 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -1367,7 +1329,6 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
# REQUEST but expect all (formerly) URL query parameters to appear in their **kw # REQUEST but expect all (formerly) URL query parameters to appear in their **kw
# thus we send extra_param_json (=rjs way of passing parameters to REQUEST) as # thus we send extra_param_json (=rjs way of passing parameters to REQUEST) as
# selection_params so they get into callable's **kw. # selection_params so they get into callable's **kw.
log("[DEBUG] calling renderForm from calculateHateoas -core-")
renderForm(traversed_document, view_instance, embedded_dict, renderForm(traversed_document, view_instance, embedded_dict,
selection_params=extra_param_json, extra_param_json=extra_param_json) selection_params=extra_param_json, extra_param_json=extra_param_json)
...@@ -2031,7 +1992,6 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -2031,7 +1992,6 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
response.setStatus(405) response.setStatus(405)
return "" return ""
log("[DEBUG] calling renderForm from calculateHateoas - mode 'search'")
renderForm(traversed_document, form, result_dict, extra_param_json=extra_param_json) renderForm(traversed_document, form, result_dict, extra_param_json=extra_param_json)
elif mode == 'newContent': elif mode == 'newContent':
...@@ -2127,7 +2087,6 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -2127,7 +2087,6 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
result_dict["_embedded"]["_view"]["my_form_definition"]["default"] = result_dict["_embedded"]["_view"]["_embedded"]["form_definition"].copy() result_dict["_embedded"]["_view"]["my_form_definition"]["default"] = result_dict["_embedded"]["_view"]["_embedded"]["form_definition"].copy()
result_dict["_embedded"]["_view"]["my_form_definition"]["default"]["group_list"] = result_dict["group_list"] result_dict["_embedded"]["_view"]["my_form_definition"]["default"]["group_list"] = result_dict["group_list"]
result_dict["_embedded"]["_view"]["my_form_definition"]["default"]["_actions"] = result_dict["_embedded"]["_view"]["_actions"] result_dict["_embedded"]["_view"]["my_form_definition"]["default"]["_actions"] = result_dict["_embedded"]["_view"]["_actions"]
# [HARDCODED] the form definition must contain a field_info_dict with all the rendered fields # [HARDCODED] the form definition must contain a field_info_dict with all the rendered fields
# for now is hardcoded only for "HTML Post" # for now is hardcoded only for "HTML Post"
# TODO: achieve this iterating the group_list fields and calling renderField # TODO: achieve this iterating the group_list fields and calling renderField
...@@ -2181,6 +2140,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None, ...@@ -2181,6 +2140,7 @@ def calculateHateoas(is_portal=None, is_site_root=None, traversed_document=None,
"title": "form id", "title": "form id",
"default": "Undefined form id", "default": "Undefined form id",
"editable": 0, "editable": 0,
"hidden": 1,
"key": "form_id", "key": "form_id",
"type": "StringField" "type": "StringField"
} }
...@@ -2218,14 +2178,6 @@ temp_is_portal = (temp_traversed_document.getPath() == portal.getPath()) ...@@ -2218,14 +2178,6 @@ temp_is_portal = (temp_traversed_document.getPath() == portal.getPath())
response.setHeader('Content-Type', mime_type) response.setHeader('Content-Type', mime_type)
log(" ")
log("[DEBUG] relative_url: " + str(relative_url))
log("[DEBUG] temp_traversed_document: " + str(temp_traversed_document))
log("[DEBUG] temp_traversed_document.getPath(): " + temp_traversed_document.getPath())
log("[DEBUG] site_root.getPath(): " + site_root.getPath())
log("[DEBUG] portal.getPath(): " + portal.getPath())
log("[DEBUG] calling calculateHateoas method from beggining")
log(" ")
hateoas = calculateHateoas(is_portal=temp_is_portal, is_site_root=temp_is_site_root, hateoas = calculateHateoas(is_portal=temp_is_portal, is_site_root=temp_is_site_root,
traversed_document=temp_traversed_document, traversed_document=temp_traversed_document,
relative_url=relative_url, relative_url=relative_url,
...@@ -2236,10 +2188,6 @@ hateoas = calculateHateoas(is_portal=temp_is_portal, is_site_root=temp_is_site_r ...@@ -2236,10 +2188,6 @@ hateoas = calculateHateoas(is_portal=temp_is_portal, is_site_root=temp_is_site_r
form_relative_url=form_relative_url, form_relative_url=form_relative_url,
extra_param_json=extra_param_json) extra_param_json=extra_param_json)
log(" ")
log("[DEBUG] returning final hateoas dict!!!")
log(" ")
if hateoas == "": if hateoas == "":
return hateoas return hateoas
else: else:
......
/*global document, window, rJS, RSVP, jIO */ /*global document, window, rJS, RSVP, jIO */
/*jslint nomen: true, indent: 2, maxerr: 3 */ /*jslint nomen: true, indent: 2, maxerr: 3 */
(function (document, window, rJS, RSVP, jIO) { (function (document, window, rJS, RSVP, jIO, console, XMLHttpRequest) {
"use strict"; "use strict";
rJS(window) rJS(window)
...@@ -37,36 +37,6 @@ ...@@ -37,36 +37,6 @@
url: setting_list[0], url: setting_list[0],
default_view_reference: setting_list[1] default_view_reference: setting_list[1]
}, },
jio_options_indexdb = {
type: "replicate",
check_remote_deletion: true,
check_local_creation: true,
check_local_deletion: false,
check_local_modification: true,
signature_sub_storage: {
type: "query",
sub_storage: {
type: "indexeddb",
database: "officejs-hash"
}
},
local_sub_storage: {
type: "query",
sub_storage: {
type: "uuid",
sub_storage: {
type: "indexeddb",
database: "ojs_source_code"
}
}
},
remote_sub_storage: {
type: "appcache",
manifest: "gadget_officejs_discussion_tool.appcache",
version: "app/",
take_installer: true
}
},
jio_storage = jIO.createJIO(jio_options), jio_storage = jIO.createJIO(jio_options),
//jio_storage = jIO.createJIO(jio_options_indexdb), //jio_storage = jIO.createJIO(jio_options_indexdb),
form_path = 'portal_skins/erp5_officejs_jio_connector/' + form_path = 'portal_skins/erp5_officejs_jio_connector/' +
...@@ -74,61 +44,24 @@ ...@@ -74,61 +44,24 @@
'_viewAsJio'; '_viewAsJio';
return new RSVP.Queue() return new RSVP.Queue()
.push(function () { .push(function () {
// manual request to hateoas script to test if the script json dict result is correctly cached
var xmlHttp = new XMLHttpRequest(), var xmlHttp = new XMLHttpRequest(),
url = "https://softinst112382.host.vifib.net/erp5/web_site_module/officejs_discussion_tool/app/portal_skins/erp5_hal_json_style/ERP5Document_getHateoas?mode=traverse&relative_url=portal_skins%2Ferp5_officejs_jio_connector%2FHTMLPost_viewAsJio&view=jio_view"; url = "https://softinst112382.host.vifib.net/erp5/web_site_module/officejs_discussion_tool/hateoas/ERP5Document_getHateoas?mode=traverse&relative_url=portal_skins%2Ferp5_officejs_jio_connector%2FHTMLPost_viewAsJio&view=jio_view";
xmlHttp.open("GET", url, false); // false for synchronous request xmlHttp.open("GET", url, false); // false for synchronous request
xmlHttp.send(null); xmlHttp.send(null);
return xmlHttp.responseText; return JSON.parse(xmlHttp.responseText);
}) })
.push(function (result) { .push(function (result) {
console.log("XMLHttpRequest result:"); //return result._embedded._view.my_form_definition["default"];
console.log(result); // jio.get ends up calling hateoas script
return jio_storage.get(form_path) return jio_storage.get(form_path)
.push(function (result) { .push(function (result) {
console.log("jio_storage.get(" + form_path + ") RESULT:"); //console.log("jio_storage.get(" + form_path + ") RESULT:");
console.log(result); //console.log(result);
return result.form_definition; return result.form_definition;
}); });
}); });
}); });
//somehow the form_definition should come from the erp5-doc/form (jio?)
//for now, hardcoded form_definition for POST VIEW
return {
_debug: "traverse",
pt: "form_view",
title: "Post",
group_list: [[
"left",
[["my_title", {meta_type: "StringField"}]]
], [
"bottom",
[["my_text_content", {meta_type: "ProxyField"}]]
]],
//this field_info is totally made up, but somewhere in the definition there must be
//information about the fields. So, foreach field: key->info
field_info_dict: {
"my_title": {
"title": "Title",
"default": "Undefined title",
"editable": 1,
"key": "title",
"type": "StringField"
},
"my_text_content": {
"editable": 1,
"key": "text_content",
"renderjs_extra": '{"editor": "fck_editor",' +
'"maximize": true}',
"type": "GadgetField",
"url": "gadget_editor.html",
"sandbox": "public"
}
},
action: "Base_edit",
update_action: "",
_links: { "type": { name: "" } },
_actions: { "put": true }
};
}) })
.declareMethod("generateJsonRenderForm", function (form_definition, document) { .declareMethod("generateJsonRenderForm", function (form_definition, document) {
...@@ -271,4 +204,4 @@ ...@@ -271,4 +204,4 @@
}); });
}); });
}(document, window, rJS, RSVP, jIO)); }(document, window, rJS, RSVP, jIO, console, XMLHttpRequest));
\ No newline at end of file \ No newline at end of file
...@@ -225,7 +225,7 @@ ...@@ -225,7 +225,7 @@
</item> </item>
<item> <item>
<key> <string>serial</string> </key> <key> <string>serial</string> </key>
<value> <string>973.62473.36343.1126</string> </value> <value> <string>973.64002.24510.31556</string> </value>
</item> </item>
<item> <item>
<key> <string>state</string> </key> <key> <string>state</string> </key>
...@@ -243,7 +243,7 @@ ...@@ -243,7 +243,7 @@
</tuple> </tuple>
<state> <state>
<tuple> <tuple>
<float>1551285840.61</float> <float>1551377466.25</float>
<string>UTC</string> <string>UTC</string>
</tuple> </tuple>
</state> </state>
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment