PageRenderTime 24ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/service/fise.js

https://github.com/pivaldi/Aloha-Plugin-Annotations
JavaScript | 322 lines | 145 code | 39 blank | 138 comment | 43 complexity | 9bc8117c1948d989d2492df187f7595e MD5 | raw file
  1. /*!
  2. * Licensed under the MIT (MIT-LICENSE.txt) http://creativecommons.org/licenses/MIT/
  3. *
  4. * Copyright (c) 2010 Gentics Software GmbH, Vienna (http://gentics.com)
  5. * Author Rene Kapusta (http://twitter.com/rene_kapusta)
  6. * Author Haymo Meran (http://twitter.com/draftkraft)
  7. */
  8. /**
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. /**
  28. * Create the Services object. Namespace for Services
  29. * @hide
  30. */
  31. if ( !GENTICS.Aloha.Annotations.Services ) GENTICS.Aloha.Annotations.Services = {};
  32. /**
  33. * register the plugin with unique name
  34. */
  35. GENTICS.Aloha.Annotations.Services.fise = new GENTICS.Aloha.Annotations.Service('com.gentics.aloha.plugins.Annotations.service.fise');
  36. /**
  37. * init IKS Fise Service
  38. */
  39. GENTICS.Aloha.Annotations.Services.fise.init = function() {
  40. var that = this;
  41. this.subscribeEvents();
  42. // REST API Endpoint URL.
  43. //this.ApiEndpoint = "http://fise.demo.nuxeo.com/engines/"; // @todo
  44. this.ApiEndpoint = false;
  45. if (GENTICS.Aloha.Annotations.settings.Services && GENTICS.Aloha.Annotations.settings.Services.fise && GENTICS.Aloha.Annotations.settings.Services.fise.ApiEndpoint) {
  46. this.ApiEndpoint = GENTICS.Aloha.Annotations.settings.Services.fise.ApiEndpoint;
  47. }
  48. if (!this.ApiEndpoint) {
  49. alert('ERROR: GENTICS.Aloha.Annotations.settings.Services.fise.ApiEndpoint not defined. Configure your FISE ApiEndpoint first.');
  50. }
  51. // @todo (due to bug in fise: text/plain == json-ld output); application/json, application/rdf+xml, application/rdf+json, text/turtle or text/rdf+nt
  52. this.ResponseFormat = "text/plain";
  53. if ( this.settings.ApiKey ) {
  54. // set the service name
  55. this.repositoryName = 'fise/' + this.settings.ApiKey;
  56. } else {
  57. // set the service name
  58. this.repositoryName = 'fise/public';
  59. }
  60. };
  61. /**
  62. * Subscribe for events
  63. */
  64. GENTICS.Aloha.Annotations.Services.fise.subscribeEvents = function () {
  65. var that = this;
  66. // add the event handler for smartContentChanged / editableDeactivated
  67. GENTICS.Aloha.EventRegistry.subscribe(GENTICS.Aloha, 'editableDeactivated', function(event, rangeObject) {
  68. //alert('smartContentChanged: ' + rangeObject.triggerType);
  69. /*
  70. $('#aloha_status_value').text('smartContentChanged: ' + rangeObject.triggerType);
  71. $('#aloha_status_value2').text('snapshotContent: ' + rangeObject.snapshotContent);
  72. $('#aloha_status_value3').text('editable content: ' + rangeObject.editable.getContents());
  73. */
  74. //return false;
  75. if (GENTICS.Aloha.activeEditable) {
  76. var url = false;
  77. // @todo use new proxy plugin settings
  78. if (GENTICS.Aloha.settings.proxyUrl) {
  79. // the service url is passed as Query parameter, so it needs to be URLEncoded!
  80. url = GENTICS.Aloha.settings.proxyUrl + that.ApiEndpoint;
  81. } else {
  82. alert('ERROR: GENTICS.Aloha.settings.proxyUrl not defined. Configure your AJAXproxy Plugin.');
  83. }
  84. var data = {
  85. // @todo all or only parts of the content
  86. content: GENTICS.Aloha.activeEditable.getContents(), // send all content
  87. //content: rangeObject.changedDom.outerHTML, // outerText or outerHTML? send currently changed dom
  88. ajax: true,
  89. format: that.ResponseFormat
  90. };
  91. // submit the data to our proxy
  92. jQuery.ajax({
  93. type: "POST",
  94. url: url,
  95. data: data,
  96. //dataType: "html",
  97. contentType: 'text/plain',
  98. cache: false,
  99. beforeSend : function (xhr) {
  100. xhr.setRequestHeader('Accept', that.ResponseFormat);
  101. xhr.setRequestHeader('X-Service-Info', 'Aloha Editor Annotation Service');
  102. },
  103. success: function(result) {
  104. var obj = false;
  105. try {
  106. obj = jQuery.parseJSON(result);
  107. } catch (e) {
  108. // @todo error from fise - it should provide a error message in the same format as expected... json not html
  109. var re = new RegExp('<title>(.*)<\/title>');
  110. var match = re.exec(result);
  111. if (match && match[1]) {
  112. GENTICS.Aloha.Annotations.log('error', 'FISE ERROR: ' + match[1]);
  113. }
  114. return false;
  115. }
  116. var suggestionsContainer = jQuery("input.as-input");
  117. var suggestions = [];
  118. var annotations = [];
  119. var final_annotations = [];
  120. try {
  121. if (obj["@"] == undefined) {
  122. obj["@"] = [];
  123. obj["@"][0] = false;
  124. }
  125. var annotation = {};
  126. for (i = 0; i < obj["@"].length; i++) {
  127. annotation = {
  128. data: obj["@"][i],
  129. urn : obj["@"][i]["@"],
  130. relation : obj["@"][i]["http://purl.org/dc/terms/relation"],
  131. type : obj["@"][i]["http://purl.org/dc/terms/type"],
  132. label : obj["@"][i]["http://fise.iks-project.eu/ontology/entity-label"],
  133. text : obj["@"][i]["http://fise.iks-project.eu/ontology/selected-text"],
  134. confidence : obj["@"][i]["http://fise.iks-project.eu/ontology/confidence"]
  135. }
  136. annotations.push(annotation);
  137. /*
  138. if (annotation.confidence != undefined && annotation.type != undefined && annotation.relation == undefined) {
  139. if (annotation.text) {
  140. var tag = annotation.text;
  141. tag = tag.replace(/ \+ /g, " ");
  142. annotation.text = tag;
  143. } else if (annotation.label) {
  144. var tag = annotation.label;
  145. tag = tag.replace(/ \+ /g, " ");
  146. annotation.label = tag;
  147. }
  148. var re = new RegExp('\"(.*)\"');
  149. var match = re.exec(tag);
  150. // Confidence -- ""0.01657282257080078"^^<http://www.w3.org/2001/XMLSchema#double>"
  151. // @todo -- move to config with min max confidence
  152. var re = new RegExp('\"([0-9]+\.*)\"');
  153. var match_confidence = re.exec(annotation.confidence);
  154. if (match != null && match_confidence != null) {
  155. if (jQuery.inArray(match[1], suggestions) < 0) { // see also autoSuggest plugin
  156. suggestions.push(match[1]);
  157. }
  158. }
  159. }*/
  160. };
  161. var annotations_entities = annotations;
  162. for (i = 0; i < annotations.length; i++) {
  163. if (annotations[i].reference == undefined && annotations[i].type != undefined) {
  164. var tmp_entities = [];
  165. //alert(annotations[i].type);
  166. for(j = 0; j < annotations_entities.length; j++) {
  167. //alert(annotation.urn + ' -- ' + annotations_entities[j]['relation']);
  168. if (annotations[i].urn === annotations_entities[j]['relation'] && annotations_entities[j]['label'] != undefined) {
  169. //alert('relation found');
  170. //alert(annotations_entities[j]['confidence'] + ' -- ' + annotations_entities[j]['label']);
  171. var re = new RegExp('\"([0-9]+\.[0-9]+)\"');
  172. var match_confidence = re.exec(annotations_entities[j]['confidence']);
  173. if (match_confidence != null) {
  174. tmp_entities.push({confidence : match_confidence[1],
  175. data : annotations_entities[j]});
  176. }
  177. }
  178. //alert('end');
  179. }
  180. if (tmp_entities.length < 1) {
  181. tmp_entities.push({confidence : 0,
  182. data : annotations[i]});
  183. }
  184. tmp_entities.sort(compareConfidence);
  185. var final_annotation = tmp_entities.shift();
  186. final_annotations.push(final_annotation);
  187. }
  188. }
  189. var named_entity = false;
  190. for(i = 0; i < final_annotations.length; i++) {
  191. named_entity = final_annotations[i];
  192. named_entity = final_annotations[i];
  193. if (named_entity != undefined && named_entity.data != undefined) {
  194. named_entity = named_entity.data;
  195. if (named_entity.confidence != undefined) {
  196. if (named_entity.text) {
  197. var tag = named_entity.text;
  198. tag = tag.replace(/ \+ /g, " ");
  199. named_entity.text = tag;
  200. } else if (named_entity.label) {
  201. var tag = named_entity.label;
  202. tag = tag.replace(/ \+ /g, " ");
  203. named_entity.label = tag;
  204. }
  205. var re = new RegExp('\"(.*)\"');
  206. var match = re.exec(tag);
  207. // Confidence -- ""0.01657282257080078"^^<http://www.w3.org/2001/XMLSchema#double>"
  208. // @todo -- move to config with min max confidence
  209. var re = new RegExp('\"([0-9]+\.*)\"');
  210. var match_confidence = re.exec(named_entity.confidence);
  211. if (match != null && match_confidence != null) {
  212. if (jQuery.inArray(match[1], suggestions) < 0) { // see also autoSuggest plugin
  213. suggestions.push(match[1]);
  214. }
  215. }
  216. }
  217. }
  218. }
  219. for (i=0; i < suggestions.length; i++) {
  220. suggestionsContainer[0].add_selected_item({name:suggestions[i]+' (f)', value:suggestions[i]+' (f)'});
  221. /* // drupal hack
  222. var term = suggestions[i];
  223. var context = '#edit-field-tags';
  224. var termDiv = jQuery(context);
  225. var termList = termDiv.parent().find('.at-term-list');
  226. var excludedTermList = [];
  227. //excludedTermList =
  228. //alert(term);
  229. // Removing all HTML tags. Need to wrap in tags for text() to work correctly.
  230. //term = $('<div>' + term + '</div>').text();
  231. term = Drupal.checkPlain(term);
  232. term = jQuery.trim(term);
  233. var tags = '';
  234. var tags_array = [];
  235. termList.find('.at-term-text').each(function (i) {
  236. // Get tag and revome quotes to prevent doubling
  237. var tag = jQuery(this).text().replace(/["]/g, '');
  238. // Wrap in quotes if tag contains a comma.
  239. if (tag.search(',') != -1) {
  240. tag = '"' + tag + '"';
  241. }
  242. // Collect tags as a comma seperated list.
  243. tags = (i == 0) ? tag : tags + ', ' + tag;
  244. tags_array.push(tag);
  245. });
  246. //if (term != '') {
  247. if (term != '' && jQuery.inArray(term, tags_array) < 0 && jQuery.inArray(term, excludedTermList) < 0) {
  248. termList.append(Drupal.theme('activeTagsTermRemove', term));
  249. // Wrap in quotes if tag contains a comma.
  250. if (term.search(',') != -1) {
  251. term = '"' + term + '"';
  252. }
  253. tags = tags + ', ' + term;
  254. //tags_array.push(term);
  255. // Attach behaviors to new DOM content.
  256. Drupal.attachBehaviors(termList);
  257. // Set comma seperated tags as value of form field.
  258. termList.parent().find('input.at-terms').val(tags);
  259. termList.parent().find('.at-term-entry').val('');
  260. }
  261. */
  262. }
  263. } catch(m) {
  264. // debug: offline info...
  265. var time = new Date();
  266. time = time.getTime();
  267. suggestionsContainer[0].add_selected_item({name:'fise offline', value:'fise-debug-value-'+time});
  268. }
  269. },
  270. error: function(result) {
  271. GENTICS.Aloha.Annotations.log('error', 'There was an error fetching the contents of the FISE annotation service. Service not available.');
  272. }
  273. });
  274. }
  275. });
  276. };