slack.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. const
  2. WebSocket = require('ws'),
  3. https = require('https'),
  4. sleep = require("sleep").sleep
  5. ,SlackData = require("./slackData.js").SlackData
  6. ,SlackHistory = require("./slackHistory.js").SlackHistory
  7. ,config = require("../config.js")
  8. ,httpsRequest = require('./httpsRequest.js').httpsRequest
  9. ;
  10. const SLACK_ENDPOINT = "https://slack.com/api/"
  11. ,SLACK_HOSTNAME = "slack.com"
  12. ,SLACK_ENDPOINT_PATH = "/api/"
  13. ,GETAPI = {
  14. rtmStart: "rtm.start"
  15. ,oauth: "oauth.access"
  16. ,identityEmail: "users.identity"
  17. ,channelHistory: "channels.history"
  18. ,directHistory: "im.history"
  19. ,groupHistory: "groups.history"
  20. ,starChannel: "stars.add"
  21. ,unstarChannel: "stars.remove"
  22. ,starMsg: "stars.add"
  23. ,unstarMsg: "stars.remove"
  24. ,postMsg: "chat.postMessage"
  25. ,postMeMsg: "chat.meMessage"
  26. ,editMsg: "chat.update"
  27. ,removeMsg: "chat.delete"
  28. ,postFile: "files.upload"
  29. ,setActive: "users.setActive"
  30. ,setPresence: "users.setPresence"
  31. ,emojiList: "emoji.list"
  32. ,slashList: "commands.list"
  33. ,pinMsg: "pins.add"
  34. ,unpinMsg: "pins.remove"
  35. ,listPinned: "pins.list"
  36. ,listMpims: "mpim.list"
  37. ,slashExec: "chat.command"
  38. ,addReaction: "reactions.add"
  39. ,channelList: "users.counts"
  40. ,removeReaction: "reactions.remove"
  41. ,sendAction: "chat.attachmentAction"
  42. ,read: {
  43. group: "groups.mark"
  44. ,im: "im.mark"
  45. ,group: "mpim.mark"
  46. ,channel: "channels.mark"
  47. }
  48. }
  49. ,HISTORY_LENGTH = 35
  50. ,HISTORY_MAX_AGE = 10000// * 60 * 1000
  51. ,UPDATE_LIVE = [
  52. "message"
  53. ,"pin_added"
  54. ,"pin_removed"
  55. ,"reaction_added"
  56. ,"reaction_removed"
  57. ,"star_added"
  58. ,"star_removed"
  59. ] // Message type that affect live history
  60. ;
  61. /**
  62. * @implements {ChatSystem}
  63. **/
  64. function Slack(slackToken, manager) {
  65. this.token = slackToken;
  66. this.manager = manager;
  67. this.rtm = null;
  68. this.rtmId = 1;
  69. this.data = new SlackData(this);
  70. this.history = {};
  71. this.pendingRtm = {};
  72. this.pendingMessages = [];
  73. this.pendingPing = false;
  74. this.connected = false;
  75. this.closing = false;
  76. /** @type {array<String>} */
  77. this.queuedMessages = [];
  78. }
  79. Slack.prototype.getId = function() {
  80. return this.data.team ? this.data.team.id : null;
  81. };
  82. Slack.prototype.onRequest = function() {
  83. if (this.connected === false) {
  84. this.connect();
  85. }
  86. };
  87. Slack.prototype.sendUnsafe = function(msg) {
  88. this.rtm.send(msg);
  89. };
  90. Slack.prototype.send = function(msg, priority) {
  91. try {
  92. this.sendUnsafe(msg);
  93. } catch (e) {
  94. this.connected = false;
  95. console.error("[SLACK] send failed");
  96. if (priority)
  97. this.queuedMessages.push(msg);
  98. this.connect();
  99. return false;
  100. }
  101. return true;
  102. };
  103. Slack.prototype.connect = function(cb) {
  104. var _this = this;
  105. this.connected = undefined;
  106. httpsRequest(SLACK_ENDPOINT +GETAPI.rtmStart +"?token=" +this.token, (status, body) => {
  107. if (!body || !body.ok) {
  108. _this.error = "Slack API error";
  109. _this.connected = false;
  110. _this.pendingPing = false;
  111. console.error("Slack api responded " +status +" with body " +JSON.stringify(body));
  112. cb && cb(_this);
  113. } else if (status !== 200) {
  114. _this.error = body.error;
  115. _this.connected = false;
  116. _this.pendingPing = false;
  117. console.error("Slack api responded " +status);
  118. cb && cb(_this);
  119. } else {
  120. httpsRequest(SLACK_ENDPOINT +GETAPI.channelList +"?mpim_aware=true" /*+"&include_threads=true"*/ +"&token=" +this.token, (status, channels) => {
  121. if (!channels || !channels.ok) {
  122. _this.error = "Slack API error";
  123. _this.connected = false;
  124. _this.pendingPing = false;
  125. console.error("Slack api responded " +status +" with body " +JSON.stringify(body));
  126. cb && cb(_this);
  127. } else if (status !== 200) {
  128. _this.error = body.error;
  129. _this.connected = false;
  130. _this.pendingPing = false;
  131. console.error("Slack api responded " +status);
  132. cb && cb(_this);
  133. } else {
  134. this.data = new SlackData(this);
  135. // Merge body.channels (missing unread stuff) and channels data (missing members)
  136. body["channels"].forEach(function(channelData) {
  137. for (var i =0, nbChans = channels["channels"].length; i < nbChans; i++) {
  138. if (channels["channels"][i]["id"] === channelData["id"]) {
  139. channelData["unread_count"] = channels["channels"][i]["unread_count"];
  140. break;
  141. }
  142. }
  143. });
  144. body["groups"].forEach(function(channelData) {
  145. for (var i =0, nbChans = channels["groups"].length; i < nbChans; i++) {
  146. if (channels["groups"][i]["id"] === channelData["id"]) {
  147. channelData["unread_count"] = channels["groups"][i]["unread_count"];
  148. break;
  149. }
  150. }
  151. });
  152. // TODO deal with channels["threads"]
  153. _this.data.updateStatic({
  154. team: body["team"],
  155. users: body["users"],
  156. bots: body["bots"],
  157. self: body["self"],
  158. channels: body["channels"],
  159. groups: body["groups"],
  160. ims: channels["ims"],
  161. mpims: channels["mpims"]
  162. }, Date.now());
  163. _this.connectRtm(body.url);
  164. }
  165. });
  166. }
  167. });
  168. };
  169. Slack.prototype.sendCommand = function(room, cmd, arg) {
  170. httpsRequest(
  171. SLACK_ENDPOINT
  172. +GETAPI.slashExec
  173. +"?token=" +this.token
  174. +"&command=" +encodeURIComponent(cmd.name)
  175. +"&disp=" +encodeURIComponent(cmd.name)
  176. +"&channel=" +room.remoteId
  177. +"&text=" +arg);
  178. }
  179. Slack.prototype.sendTyping = function(room) {
  180. this.send('{"id":' +this.rtmId++ +',"type":"typing","channel":"' +room.remoteId +'"}');
  181. }
  182. Slack.prototype.getSlashCommands = function(cb) {
  183. httpsRequest(SLACK_ENDPOINT +GETAPI.slashList +"?token=" +this.token, (status, body) => {
  184. if (!status || !body || !body.ok)
  185. cb(null);
  186. else
  187. cb(body.commands || {});
  188. });
  189. };
  190. Slack.prototype.getEmojis = function(cb) {
  191. httpsRequest(SLACK_ENDPOINT +GETAPI.emojiList +"?token=" +this.token, (status, body) => {
  192. if (!status || !body || !body.ok)
  193. cb(null);
  194. else
  195. cb(body.emoji || {});
  196. });
  197. };
  198. Slack.prototype.poll = function(knownVersion, now, withTyping) {
  199. if (this.connected) {
  200. var updatedCtx = this.data.getUpdates(knownVersion)
  201. ,updatedTyping = withTyping ? this.data.getWhoIsTyping(now) : undefined
  202. ,updatedLive = this.getLiveUpdates(knownVersion);
  203. if (updatedCtx || updatedLive || updatedTyping) {
  204. return {
  205. "static": updatedCtx,
  206. "live": updatedLive,
  207. "typing": updatedTyping,
  208. "v": Math.max(this.data.liveV, this.data.staticV)
  209. };
  210. }
  211. }
  212. };
  213. /** @return {Object|undefined} */
  214. Slack.prototype.getLiveUpdates = function(knownVersion) {
  215. var result = {};
  216. for (var roomId in this.history) {
  217. var history = this.history[roomId];
  218. if (history.isNew) {
  219. result[roomId] = history.toStatic(0);
  220. history.isNew = false;
  221. }
  222. else {
  223. var roomData = history.toStatic(knownVersion);
  224. if (roomData.length)
  225. result[roomId] = roomData;
  226. }
  227. }
  228. for (var roomId in result) {
  229. return result;
  230. }
  231. return undefined;
  232. };
  233. Slack.prototype.unstackPendingMessages = function() {
  234. for (var i = this.pendingMessages.length -1; i >= 0; i--) {
  235. this.onMessage(this.pendingMessages[0], Date.now());
  236. this.pendingMessages.shift();
  237. }
  238. while (this.queuedMessages.length) {
  239. if (this.send(this.queuedMessages[0])) {
  240. this.queuedMessages.shift();
  241. } else {
  242. break;
  243. }
  244. }
  245. };
  246. Slack.prototype.resetVersions = function(v) {
  247. this.data.team.version = v;
  248. for (var i in this.data.channels)
  249. this.data.channels[i].version = v;
  250. for (var i in this.data.users)
  251. this.data.users[i].version = v;
  252. if (this.data.self && this.data.self.prefs)
  253. this.data.self.prefs.version = v;
  254. this.data.staticV = v;
  255. };
  256. Slack.prototype.onMessage = function(msg, t) {
  257. if (msg["reply_to"] && this.pendingRtm[msg["reply_to"]]) {
  258. var ts = msg["ts"]
  259. ,rtmId = msg["reply_to"];
  260. msg = this.pendingRtm[rtmId];
  261. msg["ts"] = ts;
  262. delete this.pendingRtm[rtmId];
  263. }
  264. if (msg["type"] === "hello" && msg["start"] && msg["start"]["rtm_start"]) {
  265. var _this = this;
  266. _this.getRawMpims((mpims) => {
  267. _this.getEmojis((emojis) => {
  268. _this.getSlashCommands((commands) => {
  269. var msgContent = msg.start.rtm_start;
  270. var now = Date.now();
  271. msgContent.self = msg.self;
  272. msgContent.emojis = emojis;
  273. msgContent.commands = commands;
  274. msgContent.mpims = mpims;
  275. _this.resetVersions(now);
  276. _this.data.updateStatic(msgContent, now);
  277. _this.connected = true;
  278. _this.unstackPendingMessages();
  279. _this.ping();
  280. });
  281. });
  282. });
  283. } else if (this.connected) {
  284. this.data.onMessage(msg, t);
  285. if ((msg["channel"] || msg["channel_id"] || (msg["item"] && msg["item"]["channel"])) && msg["type"] && UPDATE_LIVE.indexOf(msg["type"]) !== -1) {
  286. var channelId = this.data.team.id +'|' +(msg["channel"] || msg["channel_id"] || msg["item"]["channel"])
  287. ,channel = this.data.channels[channelId]
  288. ,histo = this.lazyHistory(channel);
  289. // FIXME remove typing for user
  290. var lastMsg = histo.push(msg, t);
  291. if (lastMsg)
  292. this.data.liveV = t;
  293. histo.resort();
  294. if (channel)
  295. channel.setLastMsg(lastMsg, t);
  296. }
  297. } else {
  298. this.pendingMessages.push(msg);
  299. }
  300. };
  301. Slack.prototype.getRawMpims = function(cb) {
  302. httpsRequest(SLACK_ENDPOINT +GETAPI.listMpims
  303. +"?token=" +this.token, (status, content) => {
  304. if (status === 200 && content.ok)
  305. cb(content.groups);
  306. else
  307. cb(undefined);
  308. });
  309. };
  310. /**
  311. * @param {SlackChan|SlackGroup|SlackIms} chan
  312. * @param {string} id
  313. * @param {number} ts
  314. **/
  315. Slack.prototype.markRead = function(chan, id, ts) {
  316. var apiURI;
  317. if (chan.remoteId[0] === 'C')
  318. apiURI = SLACK_ENDPOINT+GETAPI.read.channel;
  319. else if (chan.remoteId[0] === 'G')
  320. apiURI = SLACK_ENDPOINT+GETAPI.read.group;
  321. else if (chan.remoteId[0] === 'D')
  322. apiURI = SLACK_ENDPOINT+GETAPI.read.im;
  323. httpsRequest(apiURI
  324. +"?token=" +this.token
  325. +"&channel="+chan.remoteId
  326. +"&ts="+id);
  327. };
  328. Slack.prototype.connectRtm = function(url, cb) {
  329. var _this = this;
  330. this.rtmId = 1;
  331. var protocol = url.substr(0, url.indexOf('://') +3);
  332. url = url.substr(protocol.length);
  333. url = protocol +url.substr(0, url.indexOf('/'))+
  334. "/?flannel=1&token=" +this.token+
  335. "&start_args=" +encodeURIComponent("?simple_latest=true&presence_sub=true&canonical_avatars=true")
  336. this.rtm = new WebSocket(url);
  337. this.rtm.on("message", function(msg) {
  338. if (!_this.connected && cb) {
  339. cb();
  340. }
  341. try {
  342. msg = JSON.parse(msg);
  343. } catch (ex) {
  344. console.error("WTF invalid JSON ", msg);
  345. }
  346. _this.onMessage(msg, Date.now());
  347. });
  348. this.rtm.once("error", function(e) {
  349. _this.connected = false;
  350. _this.pendingPing = false;
  351. console.error(e);
  352. _this.close();
  353. });
  354. this.rtm.once("end", function() {
  355. console.error("RTM hang up");
  356. _this.onClose();
  357. });
  358. };
  359. Slack.prototype.onClose = function() {
  360. this.manager.suicide(this);
  361. };
  362. Slack.prototype.ping = function() {
  363. httpsRequest(SLACK_ENDPOINT+GETAPI.setActive
  364. +"?token=" +this.token);
  365. };
  366. Slack.prototype.rtmPing = function() {
  367. if (this.connected) {
  368. if (this.pendingPing && this.pendingRtm[this.pendingPing]) {
  369. // We could use reconect_url, but we could have missed something important,
  370. // so we restart all over again
  371. this.connected = false;
  372. this.pendingPing = false;
  373. console.error("[SLACK] Ping timeout");
  374. this.connect();
  375. } else {
  376. var rtmId = this.rtmId++;
  377. try {
  378. this.sendUnsafe('{"id":' +rtmId +',"type":"ping"}');
  379. this.pendingRtm[rtmId] = { type: 'ping' };
  380. this.pendingPing = rtmId;
  381. } catch (e) {
  382. this.connected = false;
  383. this.pendingPing = false;
  384. console.error("[SLACK] Ping timeout");
  385. this.connect();
  386. }
  387. }
  388. }
  389. };
  390. Slack.prototype.close = function() {
  391. if (!this.closing) {
  392. this.closing = true;
  393. if (this.rtm)
  394. this.rtm.close();
  395. this.onClose();
  396. }
  397. };
  398. Slack.getUserId = function(code, redirectUri, cb) {
  399. Slack.getOauthToken(code, redirectUri, (teamName, userId, token) => {
  400. httpsRequest(SLACK_ENDPOINT+GETAPI.identityEmail +"?token="+token,
  401. (status, resp) => {
  402. if (status === 200 && resp.ok && resp.user && resp.user.email) {
  403. cb(resp.user.id +'_' +resp.team.id);
  404. } else {
  405. cb(null);
  406. }
  407. });
  408. });
  409. };
  410. Slack.getOauthToken = function(code, redirectUri, cb) {
  411. httpsRequest(SLACK_ENDPOINT+GETAPI.oauth
  412. +"?client_id=" +config.services.Slack.clientId
  413. +"&client_secret=" +config.services.Slack.clientSecret
  414. +"&redirect_uri=" +encodeURIComponent(redirectUri)
  415. +"&code=" +code,
  416. (status, resp) => {
  417. if (status === 200 && resp.ok) {
  418. cb(resp["team_name"], resp["team_id"] +resp["user_id"], resp["access_token"]);
  419. } else {
  420. cb(null);
  421. }
  422. });
  423. };
  424. /**
  425. * @param {SlackChan|SlackGroup|SlackIms} channel
  426. * @param {string} contentType
  427. * @param {function(string|null)} callback
  428. **/
  429. Slack.prototype.openUploadFileStream = function(channel, contentType, callback) {
  430. var req = https.request({
  431. hostname: SLACK_HOSTNAME
  432. ,method: 'POST'
  433. ,path: SLACK_ENDPOINT_PATH +GETAPI.postFile
  434. +"?token=" +this.token
  435. +"&channels=" +channel.remoteId
  436. ,headers: {
  437. "Content-Type": contentType
  438. }
  439. }, (res) => {
  440. var errorJson;
  441. res.on("data", (chunk) => {
  442. errorJson = errorJson ? Buffer.concat([errorJson, chunk], errorJson.length +chunk.length) : Buffer.from(chunk);
  443. });
  444. res.once("end", () => {
  445. if (res.statusCode === 200) {
  446. callback(null);
  447. } else {
  448. try {
  449. errorJson = JSON.parse(errorJson.toString());
  450. } catch(e) {
  451. callback("error");
  452. return;
  453. }
  454. callback(errorJson["error"] || "error");
  455. }
  456. });
  457. });
  458. return req;
  459. };
  460. function findBoundary() {
  461. const prefix = '-'.repeat(15)
  462. ,alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  463. ,doYouKnowWhoManyTheyAre = alphabet.length // 26 letters in da alphabet
  464. ,nbArg = arguments.length;
  465. for (let i =0; i < doYouKnowWhoManyTheyAre; i++)
  466. bLoop: for (let j =0; j < doYouKnowWhoManyTheyAre; j++) {
  467. const boundary = prefix +alphabet[i] +alphabet[j];
  468. for (let argIndex =0; argIndex < nbArg; argIndex++) {
  469. if (arguments[argIndex].indexOf(boundary) >= 0)
  470. continue bLoop;
  471. }
  472. return boundary;
  473. }
  474. }
  475. function encodeWithBoundary(boundary, data) {
  476. var resp = "";
  477. for (var k in data) {
  478. resp += '--' +boundary +'\r\n';
  479. resp += 'Content-Disposition: form-data; name="' +k +'"\r\n\r\n'
  480. +data[k]
  481. +'\r\n';
  482. };
  483. return resp +'--' +boundary +'--\r\n';
  484. }
  485. /**
  486. * @param {string} serviceId
  487. * @param {Object} payload
  488. * @param {function(string|null)=} callback
  489. **/
  490. Slack.prototype.sendAction = function(serviceId, payload, callback) {
  491. var channel = this.data.channels[payload["channel_id"]]
  492. ,service = this.data.users[serviceId];
  493. if (channel && service) {
  494. payload["channel_id"] = channel.remoteId;
  495. var payloadString = JSON.stringify(payload)
  496. ,boundary = findBoundary(service.remoteId, payloadString)
  497. ,body = encodeWithBoundary(boundary, {
  498. "service_id": service.remoteId
  499. ,"payload": payloadString
  500. });
  501. var req = https.request({
  502. hostname: SLACK_HOSTNAME
  503. ,method: 'POST'
  504. ,path: SLACK_ENDPOINT_PATH +GETAPI.sendAction +"?token=" +this.token
  505. ,headers: {
  506. "Content-Type": "multipart/form-data; boundary=" +boundary,
  507. "Content-Length": body.length
  508. }
  509. }, (res) => {
  510. if (callback) {
  511. var resp = [];
  512. res.on("data", (chunk) => { resp.push(chunk); });
  513. res.once("end", () => {
  514. resp = Buffer.concat(resp).toString();
  515. try {
  516. resp = JSON.parse(resp);
  517. } catch (e) {
  518. resp = null;
  519. }
  520. callback(resp && resp.ok ? resp : false);
  521. });
  522. }
  523. });
  524. req.end(body);
  525. return true;
  526. }
  527. return false;
  528. };
  529. /**
  530. * @param {SlackChan|SlackGroup|SlackIms} channel
  531. * @param {string} contentType
  532. * @param {function(string|null)} callback
  533. **/
  534. Slack.prototype.openUploadFileStream = function(channel, contentType, callback) {
  535. var req = https.request({
  536. hostname: SLACK_HOSTNAME
  537. ,method: 'POST'
  538. ,path: SLACK_ENDPOINT_PATH +GETAPI.postFile
  539. +"?token=" +this.token
  540. +"&channels=" +channel.remoteId
  541. ,headers: {
  542. "Content-Type": contentType
  543. }
  544. }, (res) => {
  545. var errorJson;
  546. res.on("data", (chunk) => {
  547. errorJson = errorJson ? Buffer.concat([errorJson, chunk], errorJson.length +chunk.length) : Buffer.from(chunk);
  548. });
  549. res.once("end", () => {
  550. if (res.statusCode === 200) {
  551. callback(null);
  552. } else {
  553. try {
  554. errorJson = JSON.parse(errorJson.toString());
  555. } catch(e) {
  556. callback("error");
  557. return;
  558. }
  559. callback(errorJson["error"] || "error");
  560. }
  561. });
  562. });
  563. return req;
  564. };
  565. /**
  566. * @param {SlackChan|SlackGroup|SlackIms} channel
  567. * @param {string} msgId
  568. * @param {string} reaction
  569. **/
  570. Slack.prototype.addReaction = function(channel, msgId, reaction) {
  571. httpsRequest(SLACK_ENDPOINT +GETAPI.addReaction
  572. +"?token=" +this.token
  573. +"&name=" +reaction
  574. +"&channel="+channel.remoteId
  575. +"&timestamp="+msgId);
  576. }
  577. /**
  578. * @param {SlackChan|SlackGroup|SlackIms} channel
  579. * @param {string} msgId
  580. * @param {string} reaction
  581. **/
  582. Slack.prototype.removeReaction = function(channel, msgId, reaction) {
  583. httpsRequest(SLACK_ENDPOINT +GETAPI.removeReaction
  584. +"?token=" +this.token
  585. +"&name=" +reaction
  586. +"&channel="+channel.remoteId
  587. +"&timestamp="+msgId);
  588. }
  589. /**
  590. * @param {SlackChan|SlackGroup|SlackIms} channel
  591. * @param {Array.<string>} text
  592. * @return {string} sent msg
  593. **/
  594. Slack.prototype.sendMeMsg = function(channel, text) {
  595. var text = idify(this.data, text.join("\n"));
  596. httpsRequest(SLACK_ENDPOINT +GETAPI.postMeMsg
  597. +"?token=" +this.token
  598. +"&channel=" +channel.remoteId
  599. +"&text=" +text
  600. +"&as_user=true");
  601. return text;
  602. };
  603. /**
  604. * @param {SlackChan|SlackGroup|SlackIms} channel
  605. **/
  606. Slack.prototype.starChannel = function(channel) {
  607. httpsRequest(SLACK_ENDPOINT +GETAPI.starChannel
  608. +"?token=" +this.token
  609. +"&channel=" +channel.remoteId);
  610. };
  611. /**
  612. * @param {SlackChan|SlackGroup|SlackIms} channel
  613. **/
  614. Slack.prototype.unstarChannel = function(channel) {
  615. httpsRequest(SLACK_ENDPOINT +GETAPI.unstarChannel
  616. +"?token=" +this.token
  617. +"&channel=" +channel.remoteId);
  618. };
  619. /**
  620. * @param {SlackChan|SlackGroup|SlackIms} channel
  621. * @param {string} msgId
  622. **/
  623. Slack.prototype.starMsg = function(channel, msgId) {
  624. httpsRequest(SLACK_ENDPOINT +GETAPI.starChannel
  625. +"?token=" +this.token
  626. +"&channel=" +channel.remoteId
  627. +"&timestamp=" +msgId);
  628. };
  629. /**
  630. * @param {SlackChan|SlackGroup|SlackIms} channel
  631. * @param {string} msgId
  632. **/
  633. Slack.prototype.unstarMsg = function(channel, msgId) {
  634. httpsRequest(SLACK_ENDPOINT +GETAPI.unstarChannel
  635. +"?token=" +this.token
  636. +"&channel=" +channel.remoteId
  637. +"&timestamp=" +msgId);
  638. };
  639. /**
  640. * @param {SlackChan|SlackGroup|SlackIms} channel
  641. * @param {string} msgId
  642. **/
  643. Slack.prototype.pinMsg = function(channel, msgId) {
  644. httpsRequest(SLACK_ENDPOINT +GETAPI.pinMsg
  645. +"?token=" +this.token
  646. +"&channel=" +channel.remoteId
  647. +"&timestamp=" +msgId);
  648. };
  649. /**
  650. * @param {SlackChan|SlackGroup|SlackIms} channel
  651. * @param {string} msgId
  652. **/
  653. Slack.prototype.unpinMsg = function(channel, msgId) {
  654. httpsRequest(SLACK_ENDPOINT +GETAPI.unpinMsg
  655. +"?token=" +this.token
  656. +"&channel=" +channel.remoteId
  657. +"&timestamp=" +msgId);
  658. };
  659. function idify(data, str) {
  660. return str.replace(/(^|\s)@(\S+)/g, function(match, p1, userName) {
  661. for (var i in data.users) {
  662. if (data.users[i].getName() === userName) {
  663. return p1 +"<@" +data.users[i].remoteId +'|' +userName +'>';
  664. }
  665. }
  666. return match;
  667. }).replace(/(^|\s)#(\S+)/g, function(match, p1, chanName) {
  668. for (var i in data.channels) {
  669. if (data.channels[i].name === chanName) {
  670. return p1 +"<#" +data.channels[i].remoteId +'|' +chanName +'>';
  671. }
  672. }
  673. return match;
  674. });
  675. }
  676. /**
  677. * @param {SlackChan|SlackGroup|SlackIms} channel
  678. * @param {Array.<string>} text
  679. * @param {Array.<Object>=} attachments
  680. * @return {string} sent message
  681. **/
  682. Slack.prototype.sendMsg = function(channel, text, attachments) {
  683. if (attachments) {
  684. attachments.forEach((attachmentObj) => {
  685. if (attachmentObj["ts"])
  686. attachmentObj["ts"] /= 1000;
  687. });
  688. var decodedText = idify(this.data, text.join("\n"));
  689. httpsRequest(SLACK_ENDPOINT +GETAPI.postMsg
  690. +"?token=" +this.token
  691. +"&channel=" +channel.remoteId
  692. +"&text=" +decodedText
  693. +"&link_names=true"
  694. + (attachments ? ("&attachments=" +encodeURIComponent(JSON.stringify(attachments))) : "")
  695. +"&as_user=true");
  696. return fullDecodedText;
  697. } else {
  698. var decodedText = [];
  699. text.forEach(function(i) {
  700. decodedText.push(decodeURIComponent(i));
  701. });
  702. var fullDecodedText = idify(this.data, decodedText.join("\n"));
  703. this.pendingRtm[this.rtmId] = {
  704. type: 'message',
  705. channel: channel.remoteId,
  706. user: this.data.self.remoteId,
  707. text: fullDecodedText
  708. };
  709. this.send('{"id":' +this.rtmId++ +',"type":"message","channel":"' +channel.remoteId +'", "text":' +JSON.stringify(fullDecodedText) +'}', true);
  710. return fullDecodedText;
  711. }
  712. };
  713. /**
  714. * @param {SlackChan|SlackGroup|SlackIms} channel
  715. * @param {string} msgId
  716. **/
  717. Slack.prototype.removeMsg = function(channel, msgId) {
  718. httpsRequest(SLACK_ENDPOINT +GETAPI.removeMsg
  719. +"?token=" +this.token
  720. +"&channel=" +channel.remoteId
  721. +"&ts=" +msgId
  722. +"&as_user=true");
  723. };
  724. /**
  725. * @param {SlackChan|SlackGroup|SlackIms} channel
  726. * @param {string} msgId
  727. * @param {string} text
  728. **/
  729. Slack.prototype.editMsg = function(channel, msgId, text) {
  730. httpsRequest(SLACK_ENDPOINT +GETAPI.editMsg
  731. +"?token=" +this.token
  732. +"&channel=" +channel.remoteId
  733. +"&ts=" +msgId
  734. +"&text=" +text.join("\n")
  735. +"&as_user=true");
  736. };
  737. /**
  738. * @param {SlackChan|SlackGroup|SlackIms} target
  739. **/
  740. Slack.prototype.lazyHistory = function(target) {
  741. var histo = this.history[target.id];
  742. if (!histo) {
  743. histo = this.history[target.id] = new SlackHistory(this, target.remoteId, target.id, this.data.team.id +'|', HISTORY_LENGTH, HISTORY_MAX_AGE);
  744. histo.isNew = true;
  745. }
  746. return histo;
  747. };
  748. /**
  749. * @param {SlackChan|SlackGroup|SlackIms} target
  750. **/
  751. Slack.prototype.fetchPinned = function(target) {
  752. var _this = this;
  753. httpsRequest(SLACK_ENDPOINT +GETAPI.listPinned
  754. +"?token="+this.token
  755. +"&channel=" +target.remoteId,
  756. (status, resp) => {
  757. if (status === 200 && resp && resp.ok) {
  758. var msgs = [],
  759. histo = _this.lazyHistory(target);
  760. now = Date.now();
  761. resp.items.forEach(function(msg) {
  762. msgs.push(histo.messageFactory(msg.message, now));
  763. });
  764. target.pins = msgs;
  765. target.version = Math.max(target.version, now);
  766. _this.data.staticV = Math.max(_this.data.staticV, now);
  767. }
  768. });
  769. };
  770. /**
  771. * @param {SlackChan|SlackGroup|SlackIms} target
  772. **/
  773. Slack.prototype.fetchHistory = function(target, cb, count, firstMsgId) {
  774. var _this = this
  775. ,baseUrl = ""
  776. ,targetId = target.remoteId;
  777. if (targetId[0] === 'D') {
  778. baseUrl = SLACK_ENDPOINT +GETAPI.directHistory;
  779. } else if (targetId[0] === 'C') {
  780. baseUrl = SLACK_ENDPOINT +GETAPI.channelHistory;
  781. } else if (targetId[0] === 'G') {
  782. baseUrl = SLACK_ENDPOINT +GETAPI.groupHistory;
  783. }
  784. httpsRequest(baseUrl
  785. +"?token="+this.token
  786. +"&channel=" +targetId
  787. +"&include_pin_count=true"
  788. +(firstMsgId ? ("&inclusive=true&latest=" +firstMsgId) : "")
  789. +"&count=" +(count || 100),
  790. (status, resp) => {
  791. var history = [];
  792. if (status === 200 && resp && resp.ok) {
  793. var histo = this.lazyHistory(target);
  794. resp.messages.forEach((respMsg) => {
  795. respMsg["id"] = respMsg["ts"];
  796. history.push(histo.messageFactory(histo.prepareMessage(respMsg)));
  797. });
  798. if (!target.pins || target.pins.length !== resp["pin_count"]) {
  799. if (!resp["pin_count"]) {
  800. target.pins = [];
  801. target.version = Math.max(target.version, Date.now());
  802. _this.data.staticV = Math.max(_this.data.staticV, target.version);
  803. } else {
  804. _this.fetchPinned(target);
  805. }
  806. }
  807. }
  808. cb(history);
  809. });
  810. };
  811. Slack.prototype.getChatContext = function() {
  812. return this.data;
  813. };
  814. module.exports.Slack = Slack;