mod/lti/amd/src/external_registration.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * Encapsules the behavior for creating a tool type and tool proxy from a
  17. * registration url in Moodle.
  18. *
  19. * Manages the UI while operations are occuring, including rendering external
  20. * registration page within the iframe.
  21. *
  22. * See template: mod_lti/external_registration
  23. *
  24. * @module mod_lti/external_registration
  25. * @copyright 2015 Ryan Wyllie <ryan@moodle.com>
  26. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  27. * @since 3.1
  28. */
  29. define(['jquery', 'core/ajax', 'core/notification', 'core/templates', 'mod_lti/events',
  30. 'mod_lti/tool_proxy', 'mod_lti/tool_type', 'mod_lti/keys', 'core/str'],
  31. function($, ajax, notification, templates, ltiEvents, toolProxy, toolType, KEYS, str) {
  32. var SELECTORS = {
  33. EXTERNAL_REGISTRATION_CONTAINER: '#external-registration-page-container',
  34. EXTERNAL_REGISTRATION_TEMPLATE_CONTAINER: '#external-registration-template-container',
  35. EXTERNAL_REGISTRATION_CANCEL_BUTTON: '#cancel-external-registration',
  36. TOOL_TYPE_CAPABILITIES_CONTAINER: '#tool-type-capabilities-container',
  37. TOOL_TYPE_CAPABILITIES_TEMPLATE_CONTAINER: '#tool-type-capabilities-template-container',
  38. CAPABILITIES_AGREE_CONTAINER: '.capabilities-container',
  39. };
  40. /**
  41. * Return the external registration cancel button element. This button is
  42. * the cancel button that appears while the iframe is rendered.
  43. *
  44. * @method getExternalRegistrationCancelButton
  45. * @private
  46. * @return {JQuery} jQuery object
  47. */
  48. var getExternalRegistrationCancelButton = function() {
  49. return $(SELECTORS.EXTERNAL_REGISTRATION_CANCEL_BUTTON);
  50. };
  51. /**
  52. * Return the container that holds all elements for the external registration, including
  53. * the cancel button and the iframe.
  54. *
  55. * @method getExternalRegistrationContainer
  56. * @private
  57. * @return {JQuery} jQuery object
  58. */
  59. var getExternalRegistrationContainer = function() {
  60. return $(SELECTORS.EXTERNAL_REGISTRATION_CONTAINER);
  61. };
  62. /**
  63. * Return the container that holds the external registration page template. It should
  64. * be the iframe.
  65. *
  66. * @method getExternalRegistrationTemplateContainer
  67. * @private
  68. * @return {JQuery} jQuery object
  69. */
  70. var getExternalRegistrationTemplateContainer = function() {
  71. return $(SELECTORS.EXTERNAL_REGISTRATION_TEMPLATE_CONTAINER);
  72. };
  73. /**
  74. * Return the container that holds the elements for displaying the list of capabilities
  75. * that this tool type requires. This container wraps the loading indicator and the template
  76. * container.
  77. *
  78. * @method getToolTypeCapabilitiesContainer
  79. * @private
  80. * @return {JQuery} jQuery object
  81. */
  82. var getToolTypeCapabilitiesContainer = function() {
  83. return $(SELECTORS.TOOL_TYPE_CAPABILITIES_CONTAINER);
  84. };
  85. /**
  86. * Return the container that holds the template that lists the capabilities that the
  87. * tool type will require.
  88. *
  89. * @method getToolTypeCapabilitiesTemplateContainer
  90. * @private
  91. * @return {JQuery} jQuery object
  92. */
  93. var getToolTypeCapabilitiesTemplateContainer = function() {
  94. return $(SELECTORS.TOOL_TYPE_CAPABILITIES_TEMPLATE_CONTAINER);
  95. };
  96. /**
  97. * Triggers a visual indicator to show that the capabilities section is loading.
  98. *
  99. * @method startLoadingCapabilitiesContainer
  100. * @private
  101. */
  102. var startLoadingCapabilitiesContainer = function() {
  103. getToolTypeCapabilitiesContainer().addClass('loading');
  104. };
  105. /**
  106. * Removes the visual indicator that shows the capabilities section is loading.
  107. *
  108. * @method stopLoadingCapabilitiesContainer
  109. * @private
  110. */
  111. var stopLoadingCapabilitiesContainer = function() {
  112. getToolTypeCapabilitiesContainer().removeClass('loading');
  113. };
  114. /**
  115. * Adds a visual indicator that shows the cancel button is loading.
  116. *
  117. * @method startLoadingCancel
  118. * @private
  119. */
  120. var startLoadingCancel = function() {
  121. getExternalRegistrationCancelButton().addClass('loading');
  122. };
  123. /**
  124. * Adds a visual indicator that shows the cancel button is loading.
  125. *
  126. * @method startLoadingCancel
  127. * @private
  128. */
  129. var stopLoadingCancel = function() {
  130. getExternalRegistrationCancelButton().removeClass('loading');
  131. };
  132. /**
  133. * Stops displaying the tool type capabilities container.
  134. *
  135. * @method hideToolTypeCapabilitiesContainer
  136. * @private
  137. */
  138. var hideToolTypeCapabilitiesContainer = function() {
  139. getToolTypeCapabilitiesContainer().addClass('hidden');
  140. };
  141. /**
  142. * Displays the tool type capabilities container.
  143. *
  144. * @method showToolTypeCapabilitiesContainer
  145. * @private
  146. */
  147. var showToolTypeCapabilitiesContainer = function() {
  148. getToolTypeCapabilitiesContainer().removeClass('hidden');
  149. };
  150. /**
  151. * Stops displaying the external registration content.
  152. *
  153. * @method hideExternalRegistrationContent
  154. * @private
  155. */
  156. var hideExternalRegistrationContent = function() {
  157. getExternalRegistrationContainer().addClass('hidden');
  158. };
  159. /**
  160. * Displays the external registration content.
  161. *
  162. * @method showExternalRegistrationContent
  163. * @private
  164. */
  165. var showExternalRegistrationContent = function() {
  166. getExternalRegistrationContainer().removeClass('hidden');
  167. };
  168. /**
  169. * Save the given tool proxy id on the DOM.
  170. *
  171. * @method setToolProxyId
  172. * @private
  173. * @param {Integer} id Tool proxy ID
  174. */
  175. var setToolProxyId = function(id) {
  176. var button = getExternalRegistrationCancelButton();
  177. button.attr('data-tool-proxy-id', id);
  178. };
  179. /**
  180. * Return the saved tool proxy id.
  181. *
  182. * @method getToolProxyId
  183. * @private
  184. * @return {String} Tool proxy ID
  185. */
  186. var getToolProxyId = function() {
  187. var button = getExternalRegistrationCancelButton();
  188. return button.attr('data-tool-proxy-id');
  189. };
  190. /**
  191. * Remove the saved tool proxy id.
  192. *
  193. * @method clearToolProxyId
  194. * @private
  195. */
  196. var clearToolProxyId = function() {
  197. var button = getExternalRegistrationCancelButton();
  198. button.removeAttr('data-tool-proxy-id');
  199. };
  200. /**
  201. * Returns true if a tool proxy id has been recorded.
  202. *
  203. * @method hasToolProxyId
  204. * @private
  205. * @return {Boolean}
  206. */
  207. var hasToolProxyId = function() {
  208. return getToolProxyId() ? true : false;
  209. };
  210. /**
  211. * Checks if this process has created a tool proxy within
  212. * Moodle yet.
  213. *
  214. * @method hasCreatedToolProxy
  215. * @private
  216. * @return {Boolean}
  217. */
  218. var hasCreatedToolProxy = function() {
  219. var button = getExternalRegistrationCancelButton();
  220. return button.attr('data-tool-proxy-new') && hasToolProxyId();
  221. };
  222. /**
  223. * Records that this process has created a tool proxy.
  224. *
  225. * @method setProxyAsNew
  226. * @private
  227. * @return {Boolean}
  228. */
  229. var setProxyAsNew = function() {
  230. var button = getExternalRegistrationCancelButton();
  231. return button.attr('data-tool-proxy-new', "new");
  232. };
  233. /**
  234. * Records that this process has not created a tool proxy.
  235. *
  236. * @method setProxyAsOld
  237. * @private
  238. * @return {Boolean}
  239. */
  240. var setProxyAsOld = function() {
  241. var button = getExternalRegistrationCancelButton();
  242. return button.removeAttr('data-tool-proxy-new');
  243. };
  244. /**
  245. * Gets the external registration request required to be sent to the external
  246. * registration page using a form.
  247. *
  248. * See mod_lti/tool_proxy_registration_form template.
  249. *
  250. * @method getRegistrationRequest
  251. * @private
  252. * @param {Integer} id Tool Proxy ID
  253. * @return {Promise} jQuery Deferred object
  254. */
  255. var getRegistrationRequest = function(id) {
  256. var request = {
  257. methodname: 'mod_lti_get_tool_proxy_registration_request',
  258. args: {
  259. id: id
  260. }
  261. };
  262. return ajax.call([request])[0];
  263. };
  264. /**
  265. * Cancel an in progress external registration. This will perform any necessary
  266. * clean up of tool proxies and return the page section back to the home section.
  267. *
  268. * @method cancelRegistration
  269. * @private
  270. * @return {Promise} jQuery Deferred object
  271. */
  272. var cancelRegistration = function() {
  273. startLoadingCancel();
  274. var promise = $.Deferred();
  275. // If we've created a proxy as part of this process then
  276. // we need to delete it to clean up the data in the back end.
  277. if (hasCreatedToolProxy()) {
  278. var id = getToolProxyId();
  279. toolProxy.delete(id).done(function() {
  280. promise.resolve();
  281. }).fail(function(failure) {
  282. promise.reject(failure);
  283. });
  284. } else {
  285. promise.resolve();
  286. }
  287. promise.done(function() {
  288. // Return to the original page.
  289. finishExternalRegistration();
  290. stopLoadingCancel();
  291. }).fail(function(failure) {
  292. notification.exception(failure);
  293. finishExternalRegistration();
  294. stopLoadingCancel();
  295. str.get_string('failedtodeletetoolproxy', 'mod_lti').done(function(s) {
  296. var feedback = {
  297. message: s,
  298. error: true
  299. };
  300. $(document).trigger(ltiEvents.REGISTRATION_FEEDBACK, feedback);
  301. }).fail(notification.exception);
  302. });
  303. return promise;
  304. };
  305. /**
  306. * Load the external registration template and render it in the DOM and display it.
  307. *
  308. * @method renderExternalRegistrationWindow
  309. * @private
  310. * @param {Object} registrationRequest
  311. * @return {Promise} jQuery Deferred object
  312. */
  313. var renderExternalRegistrationWindow = function(registrationRequest) {
  314. var promise = templates.render('mod_lti/tool_proxy_registration_form', registrationRequest);
  315. promise.done(function(html, js) {
  316. // Show the external registration page in an iframe.
  317. var container = getExternalRegistrationTemplateContainer();
  318. container.append(html);
  319. templates.runTemplateJS(js);
  320. container.find('form').submit();
  321. showExternalRegistrationContent();
  322. }).fail(notification.exception);
  323. return promise;
  324. };
  325. /**
  326. * Send a request to Moodle server to set the state of the tool type to configured (active).
  327. *
  328. * @method setTypeStatusActive
  329. * @private
  330. * @param {Object} typeData A set of data representing a type, as returned by a request to get a type
  331. * from the Moodle server.
  332. * @return {Promise} jQuery Deferred object
  333. */
  334. var setTypeStatusActive = function(typeData) {
  335. return toolType.update({
  336. id: typeData.id,
  337. state: toolType.constants.state.configured
  338. });
  339. };
  340. /**
  341. * Render and display an agreement page for the user to acknowledge the list of capabilities
  342. * (groups of data) that the external tool requires in order to work. If the user agrees then
  343. * we will activate the tool so that it is immediately available. If they don't agree then
  344. * the tool remains in a pending state within Moodle until agreement is given.
  345. *
  346. * @method promptForToolTypeCapabilitiesAgreement
  347. * @private
  348. * @param {Object} typeData A set of data representing a type, as returned by a request to get a type
  349. * from the Moodle server.
  350. * @return {Promise} jQuery Deferred object
  351. */
  352. var promptForToolTypeCapabilitiesAgreement = function(typeData) {
  353. var promise = $.Deferred();
  354. templates.render('mod_lti/tool_type_capabilities_agree', typeData).done(function(html, js) {
  355. var container = getToolTypeCapabilitiesTemplateContainer();
  356. hideExternalRegistrationContent();
  357. showToolTypeCapabilitiesContainer();
  358. templates.replaceNodeContents(container, html, js);
  359. var choiceContainer = container.find(SELECTORS.CAPABILITIES_AGREE_CONTAINER);
  360. // The user agrees to allow the tool to use the groups of data so we can go
  361. // ahead and activate it for them so that it can be used straight away.
  362. choiceContainer.on(ltiEvents.CAPABILITIES_AGREE, function() {
  363. startLoadingCapabilitiesContainer();
  364. setTypeStatusActive(typeData).always(function() {
  365. stopLoadingCapabilitiesContainer();
  366. container.empty();
  367. promise.resolve();
  368. });
  369. });
  370. // The user declines to let the tool use the data. In this case we leave
  371. // the tool as pending and they can delete it using the main screen if they
  372. // wish.
  373. choiceContainer.on(ltiEvents.CAPABILITIES_DECLINE, function() {
  374. container.empty();
  375. promise.resolve();
  376. });
  377. }).fail(promise.reject);
  378. promise.done(function() {
  379. hideToolTypeCapabilitiesContainer();
  380. }).fail(notification.exception);
  381. return promise;
  382. };
  383. /**
  384. * Send a request to the Moodle server to create a tool proxy using the registration URL the user
  385. * has provided. The proxy is required for the external registration page to work correctly.
  386. *
  387. * After the proxy is created the external registration page is rendered within an iframe for the user
  388. * to complete the registration in the external page.
  389. *
  390. * If the tool proxy creation fails then we redirect the page section back to the home section and
  391. * display the error, rather than rendering the external registration page.
  392. *
  393. * @method createAndRegisterToolProxy
  394. * @private
  395. * @param {String} url Tool registration URL to register
  396. * @return {Promise} jQuery Deferred object
  397. */
  398. var createAndRegisterToolProxy = function(url) {
  399. var promise = $.Deferred();
  400. if (!url || url === "") {
  401. // No URL has been input so do nothing.
  402. promise.resolve();
  403. } else {
  404. // A tool proxy needs to exist before the external page is rendered because
  405. // the external page sends requests back to Moodle for information that is stored
  406. // in the proxy.
  407. toolProxy.create({regurl: url})
  408. .done(function(result) {
  409. // Note that it's a new proxy so we will always clean it up.
  410. setProxyAsNew();
  411. promise = registerProxy(result.id);
  412. })
  413. .fail(function(exception) {
  414. // Clean up.
  415. cancelRegistration();
  416. // Let the user know what the error is.
  417. var feedback = {
  418. message: exception.message,
  419. error: true
  420. };
  421. $(document).trigger(ltiEvents.REGISTRATION_FEEDBACK, feedback);
  422. promise.reject(exception);
  423. });
  424. }
  425. return promise;
  426. };
  427. /**
  428. * Loads the window to register a proxy, given an ID.
  429. *
  430. * @method registerProxy
  431. * @private
  432. * @param {Integer} id Proxy id to register
  433. * @return {Promise} jQuery Deferred object to fail or resolve
  434. */
  435. var registerProxy = function(id) {
  436. var promise = $.Deferred();
  437. // Save the id on the DOM to cleanup later.
  438. setToolProxyId(id);
  439. // There is a specific set of data needed to send to the external registration page
  440. // in a form, so let's get it from our server.
  441. getRegistrationRequest(id)
  442. .done(function(registrationRequest) {
  443. renderExternalRegistrationWindow(registrationRequest)
  444. .done(function() {
  445. promise.resolve();
  446. })
  447. .fail(promise.fail);
  448. })
  449. .fail(promise.fail);
  450. return promise;
  451. };
  452. /**
  453. * Complete the registration process, clean up any left over data and
  454. * trigger the appropriate events.
  455. *
  456. * @method finishExternalRegistration
  457. * @private
  458. */
  459. var finishExternalRegistration = function() {
  460. if (hasToolProxyId()) {
  461. clearToolProxyId();
  462. }
  463. setProxyAsOld(false);
  464. hideExternalRegistrationContent();
  465. var container = getExternalRegistrationTemplateContainer();
  466. container.empty();
  467. $(document).trigger(ltiEvents.STOP_EXTERNAL_REGISTRATION);
  468. };
  469. /**
  470. * Sets up the listeners for user interaction on the page.
  471. *
  472. * @method registerEventListeners
  473. * @private
  474. */
  475. var registerEventListeners = function() {
  476. $(document).on(ltiEvents.START_EXTERNAL_REGISTRATION, function(event, data) {
  477. if (!data) {
  478. return;
  479. }
  480. if (data.url) {
  481. createAndRegisterToolProxy(data.url);
  482. }
  483. if (data.proxyid) {
  484. registerProxy(data.proxyid);
  485. }
  486. });
  487. var cancelExternalRegistrationButton = getExternalRegistrationCancelButton();
  488. cancelExternalRegistrationButton.click(function(e) {
  489. e.preventDefault();
  490. cancelRegistration();
  491. });
  492. cancelExternalRegistrationButton.keypress(function(e) {
  493. if (!e.metaKey && !e.shiftKey && !e.altKey && !e.ctrlKey) {
  494. if (e.keyCode == KEYS.ENTER || e.keyCode == KEYS.SPACE) {
  495. e.preventDefault();
  496. cancelRegistration();
  497. }
  498. }
  499. });
  500. // This is gross but necessary due to isolated jQuery scopes between
  501. // child iframe and parent windows. There is no other way to communicate.
  502. //
  503. // This function gets called by the moodle page that received the redirect
  504. // from the external registration page and handles the external page's returned
  505. // parameters.
  506. //
  507. // See AMD module mod_lti/external_registration_return.
  508. window.triggerExternalRegistrationComplete = function(data) {
  509. var promise = $.Deferred();
  510. var feedback = {
  511. message: "",
  512. error: false
  513. };
  514. if (data.status == "success") {
  515. str.get_string('successfullycreatedtooltype', 'mod_lti').done(function(s) {
  516. feedback.message = s;
  517. }).fail(notification.exception);
  518. // Trigger appropriate events when we've completed the necessary requests.
  519. promise.done(function() {
  520. finishExternalRegistration();
  521. $(document).trigger(ltiEvents.REGISTRATION_FEEDBACK, feedback);
  522. $(document).trigger(ltiEvents.NEW_TOOL_TYPE);
  523. }).fail(notification.exception);
  524. // We should have created a tool proxy by this point.
  525. if (hasCreatedToolProxy()) {
  526. var proxyId = getToolProxyId();
  527. // We need the list of types that are linked to this proxy. We're assuming it'll
  528. // only be one because this process creates a one-to-one type->proxy.
  529. toolType.getFromToolProxyId(proxyId).done(function(types) {
  530. if (types && types.length) {
  531. // There should only be one result.
  532. var typeData = types[0];
  533. // Check if the external tool required access to any Moodle data (users, courses etc).
  534. if (typeData.hascapabilitygroups) {
  535. // If it did then we ask the user to agree to those groups before the type is
  536. // activated (i.e. can be used in Moodle).
  537. promptForToolTypeCapabilitiesAgreement(typeData).always(function() {
  538. promise.resolve();
  539. });
  540. } else {
  541. promise.resolve();
  542. }
  543. } else {
  544. promise.resolve();
  545. }
  546. }).fail(function() {
  547. promise.resolve();
  548. });
  549. }
  550. } else {
  551. // Anything other than success is failure.
  552. feedback.message = data.error;
  553. feedback.error = true;
  554. // Cancel registration to clean up any proxies and tools that were
  555. // created.
  556. promise.done(function() {
  557. cancelRegistration().always(function() {
  558. $(document).trigger(ltiEvents.REGISTRATION_FEEDBACK, feedback);
  559. });
  560. }).fail(notification.exception);
  561. promise.resolve();
  562. }
  563. return promise;
  564. };
  565. };
  566. return {
  567. /**
  568. * Initialise this module.
  569. */
  570. init: function() {
  571. registerEventListeners();
  572. }
  573. };
  574. });