nextcloud-talk.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /**
  2. * @node nextcloud-talk
  3. * @name Nextcloud Talk
  4. * @category integration
  5. * @version 1.0.0
  6. * @description Post a message to a Nextcloud Talk conversation, or read the recent messages in one
  7. * @icon message-square
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. baseUrl: {
  13. type: 'string',
  14. title: 'Nextcloud URL',
  15. description: 'Address of the Nextcloud instance, e.g. https://cloud.example.com'
  16. },
  17. credentialId: {
  18. type: 'string',
  19. title: 'Credential',
  20. description: 'A basic credential holding the username and an app password. Not needed for a bot webhook.',
  21. dynamicOptions: {
  22. source: 'credentials',
  23. filter: { type: 'basic' }
  24. }
  25. },
  26. action: {
  27. type: 'string',
  28. title: 'Action',
  29. enum: ['send', 'read'],
  30. default: 'send',
  31. description: 'Post a message, or read the recent ones'
  32. },
  33. token: {
  34. type: 'string',
  35. title: 'Conversation Token',
  36. description: 'The token in the conversation URL, e.g. the a1b2c3d4 in /call/a1b2c3d4'
  37. },
  38. message: {
  39. type: 'string',
  40. title: 'Message',
  41. description: 'What to post. Supports {{variable}} interpolation.'
  42. },
  43. replyTo: {
  44. type: 'string',
  45. title: 'Reply To',
  46. description: 'Post as a reply to this message id'
  47. },
  48. silent: {
  49. type: 'boolean',
  50. title: 'Send Silently',
  51. description: 'Post without notifying participants',
  52. default: false
  53. },
  54. limit: {
  55. type: 'integer',
  56. title: 'Limit',
  57. description: 'How many messages to read',
  58. default: 20,
  59. minimum: 1,
  60. maximum: 200
  61. },
  62. timeoutMs: {
  63. type: 'number',
  64. title: 'Timeout (ms)',
  65. default: 30000
  66. }
  67. },
  68. required: ['baseUrl', 'credentialId', 'token']
  69. };
  70. const inputSchema = {
  71. type: 'object',
  72. properties: {
  73. token: { type: 'string', description: 'Overrides the configured conversation' },
  74. message: { type: 'string', description: 'Overrides the configured message' }
  75. }
  76. };
  77. const outputSchema = {
  78. type: 'object',
  79. properties: {
  80. success: { type: 'boolean' },
  81. messageId: { type: 'integer', description: 'The id Talk gave the posted message' },
  82. token: { type: 'string', description: 'The conversation it was posted to' },
  83. messages: {
  84. type: 'array',
  85. description: 'Recent messages, when reading',
  86. items: {
  87. type: 'object',
  88. properties: {
  89. id: { type: 'integer' },
  90. actorId: { type: 'string' },
  91. actorDisplayName: { type: 'string' },
  92. message: { type: 'string' },
  93. timestamp: { type: 'integer' }
  94. }
  95. }
  96. },
  97. count: { type: 'integer', description: 'How many messages were read' }
  98. }
  99. };
  100. const outputs = [
  101. { name: 'main', displayName: 'Result', type: 'object', color: '#3b82f6' }
  102. ];
  103. // A connection hands the previous node's whole output over as input.data, and
  104. // some nodes wrap their own return in a result object on top of that. Rather
  105. // than guess which shape arrived, the layers are flattened with the innermost
  106. // winning, so a field set anywhere in the chain is found.
  107. function incoming(input) {
  108. const isPlain = (v) => v && typeof v === 'object' && !Array.isArray(v);
  109. const merged = {};
  110. for (const layer of [input, input && input.data, input && input.data && input.data.result]) {
  111. if (!isPlain(layer)) continue;
  112. for (const key of Object.keys(layer)) {
  113. merged[key] = layer[key];
  114. }
  115. }
  116. return merged;
  117. }
  118. // Talk is reached through the OCS API, which refuses any request that does not
  119. // declare itself as an API call with this header, and returns XML unless asked
  120. // for JSON.
  121. function ocsHeaders(credential) {
  122. const headers = {
  123. 'OCS-APIRequest': 'true',
  124. 'Accept': 'application/json',
  125. 'Content-Type': 'application/json'
  126. };
  127. if (credential && credential.headerName) {
  128. headers[credential.headerName] = credential.headerValue;
  129. }
  130. return headers;
  131. }
  132. function readCredential(credentialId) {
  133. const credential = smartbotic.credentials.get(credentialId);
  134. if (!credential || !credential.success) {
  135. throw new Error('Could not read the Nextcloud credential: ' +
  136. ((credential && credential.error) || 'unknown error'));
  137. }
  138. return credential;
  139. }
  140. // A Nextcloud that is unhappy answers with XML, or with the HTML of a login
  141. // page, and parsing that as JSON throws a bare syntax error that says nothing
  142. // about which request failed. The body is reported instead.
  143. function parseJsonResponse(response, what) {
  144. if (typeof response.data !== 'string') {
  145. return response.data;
  146. }
  147. try {
  148. return JSON.parse(response.data);
  149. } catch (e) {
  150. const snippet = response.data.substring(0, 200).replace(/\s+/g, ' ');
  151. throw new Error('Nextcloud Talk ' + what + ' failed: HTTP ' + response.status +
  152. ' returned ' + (response.headers && response.headers['content-type'] || 'an unreadable body') +
  153. ' instead of JSON: ' + snippet);
  154. }
  155. }
  156. // OCS wraps everything in ocs.meta plus ocs.data, and reports failure in the
  157. // meta rather than always in the status code.
  158. function unwrapOcs(response, what) {
  159. const body = parseJsonResponse(response, what);
  160. const ocs = body && body.ocs;
  161. if (!ocs) {
  162. throw new Error('Nextcloud Talk ' + what + ' failed: HTTP ' + response.status +
  163. ' returned no OCS envelope: ' + JSON.stringify(body).substring(0, 200));
  164. }
  165. const status = ocs.meta && ocs.meta.statuscode;
  166. if (status && (status < 200 || status >= 300)) {
  167. throw new Error('Nextcloud Talk ' + what + ' failed: ' +
  168. ((ocs.meta && ocs.meta.message) || ('OCS ' + status)));
  169. }
  170. return ocs.data;
  171. }
  172. module.exports = {
  173. configSchema,
  174. inputSchema,
  175. outputSchema,
  176. outputs,
  177. async execute(config, input, context) {
  178. const from = incoming(input);
  179. const base = String(config.baseUrl || '').replace(/\/+$/, '');
  180. if (!base) {
  181. throw new Error('The Nextcloud URL is required');
  182. }
  183. const token = String(from.token || config.token || '').trim();
  184. if (!token) {
  185. throw new Error('A conversation token is required');
  186. }
  187. const credential = readCredential(config.credentialId);
  188. const headers = ocsHeaders(credential);
  189. const timeout = Number(config.timeoutMs) || 30000;
  190. const chatUrl = base + '/ocs/v2.php/apps/spreed/api/v1/chat/' + token;
  191. if ((config.action || 'send') === 'read') {
  192. const limit = Number(config.limit) || 20;
  193. // lookIntoFuture=0 asks for the messages already there rather than
  194. // holding the connection open waiting for the next one.
  195. const response = smartbotic.http.request({
  196. method: 'GET',
  197. url: chatUrl + '?format=json&lookIntoFuture=0&limit=' + limit,
  198. headers: headers,
  199. timeout: timeout
  200. });
  201. const data = unwrapOcs(response, 'read') || [];
  202. const messages = data.map(function (entry) {
  203. return {
  204. id: entry.id,
  205. actorId: entry.actorId,
  206. actorDisplayName: entry.actorDisplayName,
  207. message: entry.message,
  208. timestamp: entry.timestamp
  209. };
  210. });
  211. return {
  212. success: true,
  213. token: token,
  214. messages: messages,
  215. count: messages.length
  216. };
  217. }
  218. const message = from.message || config.message || '';
  219. if (!message) {
  220. throw new Error('A message is required');
  221. }
  222. const payload = { message: message };
  223. if (config.replyTo) {
  224. payload.replyTo = Number(config.replyTo);
  225. }
  226. if (config.silent === true) {
  227. payload.silent = true;
  228. }
  229. const response = smartbotic.http.request({
  230. method: 'POST',
  231. url: chatUrl + '?format=json',
  232. headers: headers,
  233. body: JSON.stringify(payload),
  234. timeout: timeout
  235. });
  236. const data = unwrapOcs(response, 'send') || {};
  237. smartbotic.log.info('Nextcloud Talk: posted to conversation ' + token);
  238. return {
  239. success: true,
  240. messageId: data.id,
  241. token: token
  242. };
  243. }
  244. };