nextcloud-talk.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. retries: {
  63. type: 'number', title: 'Retries', default: 1,
  64. description: 'Extra attempts when Nextcloud times out or answers 429, 500, 502, 503 or 504. Posting a message is safe to repeat'
  65. },
  66. skipOnError: {
  67. type: 'boolean', title: 'Skip On Error', default: false,
  68. description: 'Return success false instead of failing the workflow. A notification that could not be sent is rarely worth ending a run over - least of all when the run is already reporting a problem'
  69. },
  70. timeoutMs: {
  71. type: 'number',
  72. title: 'Timeout (ms)',
  73. default: 30000
  74. }
  75. },
  76. required: ['baseUrl', 'credentialId', 'token']
  77. };
  78. const inputSchema = {
  79. type: 'object',
  80. properties: {
  81. token: { type: 'string', description: 'Overrides the configured conversation' },
  82. message: { type: 'string', description: 'Overrides the configured message' }
  83. }
  84. };
  85. const outputSchema = {
  86. type: 'object',
  87. properties: {
  88. error: { type: 'string', description: 'Why the send failed, when Skip On Error let the run carry on' },
  89. success: { type: 'boolean' },
  90. messageId: { type: 'integer', description: 'The id Talk gave the posted message' },
  91. token: { type: 'string', description: 'The conversation it was posted to' },
  92. messages: {
  93. type: 'array',
  94. description: 'Recent messages, when reading',
  95. items: {
  96. type: 'object',
  97. properties: {
  98. id: { type: 'integer' },
  99. actorId: { type: 'string' },
  100. actorDisplayName: { type: 'string' },
  101. message: { type: 'string' },
  102. timestamp: { type: 'integer' }
  103. }
  104. }
  105. },
  106. count: { type: 'integer', description: 'How many messages were read' }
  107. }
  108. };
  109. const outputs = [
  110. { name: 'main', displayName: 'Result', type: 'object', color: '#3b82f6' }
  111. ];
  112. // A connection hands the previous node's whole output over as input.data, and
  113. // some nodes wrap their own return in a result object on top of that. Rather
  114. // than guess which shape arrived, the layers are flattened with the innermost
  115. // winning, so a field set anywhere in the chain is found.
  116. function incoming(input) {
  117. const isPlain = (v) => v && typeof v === 'object' && !Array.isArray(v);
  118. const merged = {};
  119. for (const layer of [input, input && input.data, input && input.data && input.data.result]) {
  120. if (!isPlain(layer)) continue;
  121. for (const key of Object.keys(layer)) {
  122. merged[key] = layer[key];
  123. }
  124. }
  125. return merged;
  126. }
  127. // Talk is reached through the OCS API, which refuses any request that does not
  128. // declare itself as an API call with this header, and returns XML unless asked
  129. // for JSON.
  130. function ocsHeaders(credential) {
  131. const headers = {
  132. 'OCS-APIRequest': 'true',
  133. 'Accept': 'application/json',
  134. 'Content-Type': 'application/json'
  135. };
  136. if (credential && credential.headerName) {
  137. headers[credential.headerName] = credential.headerValue;
  138. }
  139. return headers;
  140. }
  141. function readCredential(credentialId) {
  142. const credential = smartbotic.credentials.get(credentialId);
  143. if (!credential || !credential.success) {
  144. throw new Error('Could not read the Nextcloud credential: ' +
  145. ((credential && credential.error) || 'unknown error'));
  146. }
  147. return credential;
  148. }
  149. // A Nextcloud that is unhappy answers with XML, or with the HTML of a login
  150. // page, and parsing that as JSON throws a bare syntax error that says nothing
  151. // about which request failed. The body is reported instead.
  152. function parseJsonResponse(response, what) {
  153. if (typeof response.data !== 'string') {
  154. return response.data;
  155. }
  156. try {
  157. return JSON.parse(response.data);
  158. } catch (e) {
  159. const snippet = response.data.substring(0, 200).replace(/\s+/g, ' ');
  160. throw new Error('Nextcloud Talk ' + what + ' failed: HTTP ' + response.status +
  161. ' returned ' + (response.headers && response.headers['content-type'] || 'an unreadable body') +
  162. ' instead of JSON: ' + snippet);
  163. }
  164. }
  165. // OCS wraps everything in ocs.meta plus ocs.data, and reports failure in the
  166. // meta rather than always in the status code.
  167. function unwrapOcs(response, what) {
  168. const body = parseJsonResponse(response, what);
  169. const ocs = body && body.ocs;
  170. if (!ocs) {
  171. throw new Error('Nextcloud Talk ' + what + ' failed: HTTP ' + response.status +
  172. ' returned no OCS envelope: ' + JSON.stringify(body).substring(0, 200));
  173. }
  174. const status = ocs.meta && ocs.meta.statuscode;
  175. if (status && (status < 200 || status >= 300)) {
  176. throw new Error('Nextcloud Talk ' + what + ' failed: ' +
  177. ((ocs.meta && ocs.meta.message) || ('OCS ' + status)));
  178. }
  179. return ocs.data;
  180. }
  181. async function talk(config, input, context) {
  182. {
  183. const from = incoming(input);
  184. const base = String(config.baseUrl || '').replace(/\/+$/, '');
  185. if (!base) {
  186. throw new Error('The Nextcloud URL is required');
  187. }
  188. const token = String(from.token || config.token || '').trim();
  189. if (!token) {
  190. throw new Error('A conversation token is required');
  191. }
  192. const credential = readCredential(config.credentialId);
  193. const headers = ocsHeaders(credential);
  194. const timeout = Number(config.timeoutMs) || 30000;
  195. const chatUrl = base + '/ocs/v2.php/apps/spreed/api/v1/chat/' + token;
  196. if ((config.action || 'send') === 'read') {
  197. const limit = Number(config.limit) || 20;
  198. // lookIntoFuture=0 asks for the messages already there rather than
  199. // holding the connection open waiting for the next one.
  200. const response = smartbotic.http.request({
  201. method: 'GET',
  202. url: chatUrl + '?format=json&lookIntoFuture=0&limit=' + limit,
  203. headers: headers,
  204. timeout: timeout,
  205. retries: Number(config.retries) >= 0 ? Number(config.retries) : 1,
  206. retryDelayMs: 2000
  207. });
  208. const data = unwrapOcs(response, 'read') || [];
  209. const messages = data.map(function (entry) {
  210. return {
  211. id: entry.id,
  212. actorId: entry.actorId,
  213. actorDisplayName: entry.actorDisplayName,
  214. message: entry.message,
  215. timestamp: entry.timestamp
  216. };
  217. });
  218. return {
  219. success: true,
  220. token: token,
  221. messages: messages,
  222. count: messages.length
  223. };
  224. }
  225. const message = from.message || config.message || '';
  226. if (!message) {
  227. throw new Error('A message is required');
  228. }
  229. const payload = { message: message };
  230. if (config.replyTo) {
  231. payload.replyTo = Number(config.replyTo);
  232. }
  233. if (config.silent === true) {
  234. payload.silent = true;
  235. }
  236. const response = smartbotic.http.request({
  237. method: 'POST',
  238. url: chatUrl + '?format=json',
  239. headers: headers,
  240. body: JSON.stringify(payload),
  241. timeout: timeout,
  242. retries: Number(config.retries) >= 0 ? Number(config.retries) : 1,
  243. retryDelayMs: 2000
  244. });
  245. const data = unwrapOcs(response, 'send') || {};
  246. smartbotic.log.info('Nextcloud Talk: posted to conversation ' + token);
  247. return {
  248. success: true,
  249. messageId: data.id,
  250. token: token
  251. };
  252. }
  253. }
  254. module.exports = {
  255. configSchema,
  256. inputSchema,
  257. outputSchema,
  258. outputs,
  259. async execute(config, input, context) {
  260. try {
  261. return await talk(config, input, context);
  262. } catch (err) {
  263. if (config.skipOnError !== true) {
  264. throw err;
  265. }
  266. // A notification that could not be sent is rarely worth ending a run
  267. // over - least of all when the run is already reporting a problem,
  268. // where failing here would put back the very failure it replaced.
  269. const message = (err && err.message) ? err.message : String(err);
  270. smartbotic.log.warn('Nextcloud Talk: skipping after ' + message);
  271. return { success: false, error: message, messageId: null, token: config.token || '' };
  272. }
  273. }
  274. };