adhoc-commands.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import "./autocomplete.js"
  2. import { __ } from '@converse/headless/i18n';
  3. import { CustomElement } from './element.js';
  4. import { api } from "@converse/headless/converse-core";
  5. import { html } from "lit-html";
  6. import { unsafeHTML } from 'lit-html/directives/unsafe-html.js';
  7. import log from "@converse/headless/log";
  8. import sizzle from "sizzle";
  9. const { Strophe, $iq } = window.converse.env;
  10. const u = window.converse.env.utils;
  11. const i18n_hide = __('Hide');
  12. const i18n_choose_service = __('On which entity do you want to run commands?');
  13. const i18n_choose_service_instructions = __(
  14. 'Certain XMPP services and entities allow privileged users to execute ad-hoc commands on them.');
  15. const i18n_commands_found = __('Commands found');
  16. const i18n_fetch_commands = __('List available commands');
  17. const i18n_jid_placeholder = __('XMPP Address');
  18. const i18n_no_commands_found = __('No commands found');
  19. const i18n_run = __('Execute');
  20. const tpl_command_form = (o, command) => html`
  21. <form @submit=${o.runCommand}>
  22. ${ command.alert ? html`<div class="alert alert-${command.alert_type}" role="alert">${command.alert}</div>` : '' }
  23. <fieldset class="form-group">
  24. <input type="hidden" name="command_node" value="${command.node}"/>
  25. <input type="hidden" name="command_jid" value="${command.jid}"/>
  26. <p class="form-help">${command.instructions}</p>
  27. <!-- Fields are generated internally, with xForm2webForm -->
  28. ${ command.fields.map(field => unsafeHTML(field)) }
  29. </fieldset>
  30. <fieldset>
  31. <input type="submit" class="btn btn-primary" value="${i18n_run}">
  32. <input type="button" class="btn btn-secondary button-cancel" value="${i18n_hide}" @click=${o.hideCommandForm}>
  33. </fieldset>
  34. </form>
  35. `;
  36. const tpl_command = (o, command) => html`
  37. <li class="room-item list-group-item">
  38. <div class="available-chatroom d-flex flex-row">
  39. <a class="open-room available-room w-100"
  40. @click=${o.toggleCommandForm}
  41. data-command-node="${command.node}"
  42. data-command-jid="${command.jid}"
  43. data-command-name="${command.name}"
  44. title="${command.name}"
  45. href="#">${command.name || command.jid}</a>
  46. </div>
  47. ${ command.node === o.showform ? tpl_command_form(o, command) : '' }
  48. </li>
  49. `;
  50. async function getAutoCompleteList () {
  51. const models = [...(await api.rooms.get()), ...(await api.contacts.get())];
  52. const jids = [...new Set(models.map(o => Strophe.getDomainFromJid(o.get('jid'))))];
  53. return jids;
  54. }
  55. const tpl_adhoc = (o) => html`
  56. <form class="converse-form" @submit=${o.fetchCommands}>
  57. <fieldset class="form-group">
  58. <label>
  59. ${i18n_choose_service}
  60. <p class="form-help">${i18n_choose_service_instructions}</p>
  61. <converse-autocomplete
  62. .getAutoCompleteList="${getAutoCompleteList}"
  63. placeholder="${i18n_jid_placeholder}"
  64. name="jid"/>
  65. </label>
  66. </fieldset>
  67. <fieldset class="form-group">
  68. <input type="submit" class="btn btn-primary" value="${i18n_fetch_commands}">
  69. </fieldset>
  70. ${ o.view === 'list-commands' ? html`
  71. <fieldset class="form-group">
  72. <ul class="list-group">
  73. <li class="list-group-item active">${ o.commands.length ? i18n_commands_found : i18n_no_commands_found }:</li>
  74. ${ o.commands.map(cmd => tpl_command(o, cmd)) }
  75. </ul>
  76. </fieldset>`
  77. : '' }
  78. </form>
  79. `;
  80. async function fetchCommandForm (command) {
  81. const node = command.node;
  82. const jid = command.jid;
  83. const stanza = $iq({
  84. 'type': 'set',
  85. 'to': jid
  86. }).c('command', {
  87. 'xmlns': Strophe.NS.ADHOC,
  88. 'node': node,
  89. 'action': 'execute'
  90. });
  91. try {
  92. const iq = await api.sendIQ(stanza);
  93. const cmd_el = sizzle(`command[xmlns="${Strophe.NS.ADHOC}"]`, iq).pop();
  94. command.sessionid = cmd_el.getAttribute('sessionid');
  95. command.instructions = sizzle('x[type="form"][xmlns="jabber:x:data"] instructions', cmd_el).pop()?.textContent;
  96. command.fields = sizzle('x[type="form"][xmlns="jabber:x:data"] field', cmd_el)
  97. .map(f => u.xForm2webForm(f, cmd_el));
  98. } catch (e) {
  99. if (e === null) {
  100. log.error(`Error: timeout while trying to execute command for ${jid}`);
  101. } else {
  102. log.error(`Error while trying to execute command for ${jid}`);
  103. log.error(e);
  104. }
  105. command.fields = [];
  106. }
  107. }
  108. export class AdHocCommands extends CustomElement {
  109. static get properties () {
  110. return {
  111. 'view': { type: String },
  112. 'showform': { type: String },
  113. 'nonce': { type: String } // Used to force re-rendering
  114. }
  115. }
  116. constructor () {
  117. super();
  118. this.view = 'choose-service';
  119. this.showform = '';
  120. this.commands = [];
  121. }
  122. render () {
  123. return tpl_adhoc({
  124. 'commands': this.commands,
  125. 'fetchCommands': ev => this.fetchCommands(ev),
  126. 'hideCommandForm': ev => this.hideCommandForm(ev),
  127. 'runCommand': ev => this.runCommand(ev),
  128. 'showform': this.showform,
  129. 'toggleCommandForm': ev => this.toggleCommandForm(ev),
  130. 'view': this.view,
  131. });
  132. }
  133. async fetchCommands (ev) {
  134. ev.preventDefault();
  135. const form_data = new FormData(ev.target);
  136. const jid = form_data.get('jid').trim();
  137. if (await api.disco.supports(Strophe.NS.ADHOC, jid)) {
  138. this.commands = await api.adhoc.getCommands(jid);
  139. this.view = 'list-commands';
  140. }
  141. }
  142. async toggleCommandForm (ev) {
  143. ev.preventDefault();
  144. const node = ev.target.getAttribute('data-command-node');
  145. const cmd = this.commands.filter(c => c.node === node)[0];
  146. this.showform !== node && await fetchCommandForm(cmd);
  147. this.showform = node;
  148. }
  149. hideCommandForm (ev) {
  150. ev.preventDefault();
  151. this.showform = ''
  152. }
  153. async runCommand (ev) {
  154. ev.preventDefault();
  155. const form_data = new FormData(ev.target);
  156. const jid = form_data.get('command_jid').trim();
  157. const node = form_data.get('command_node').trim();
  158. const cmd = this.commands.filter(c => c.node === node)[0];
  159. const inputs = sizzle(':input:not([type=button]):not([type=submit])', ev.target);
  160. const configArray = inputs
  161. .filter(i => !['command_jid', 'command_node'].includes(i.getAttribute('name')))
  162. .map(u.webForm2xForm);
  163. const iq = $iq({to: jid, type: "set"})
  164. .c("command", {
  165. 'sessionid': cmd.session,
  166. 'node': cmd.node,
  167. 'xmlns': Strophe.NS.ADHOC
  168. }).c("x", {xmlns: Strophe.NS.XFORM, type: "submit"});
  169. configArray.forEach(node => iq.cnode(node).up());
  170. let result;
  171. try {
  172. result = await api.sendIQ(iq);
  173. } catch (e) {
  174. cmd.alert_type = 'danger';
  175. cmd.alert = __('Sorry, an error occurred while trying to execute the command. See the developer console for details');
  176. log.error('Error while trying to execute an ad-hoc command');
  177. log.error(e);
  178. }
  179. if (result) {
  180. cmd.alert = result.querySelector('note')?.textContent;
  181. } else {
  182. cmd.alert = 'Done';
  183. }
  184. cmd.alert_type = 'primary';
  185. this.nonce = u.getUniqueId();
  186. }
  187. }
  188. window.customElements.define('converse-adhoc-commands', AdHocCommands);