workflow.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /* jshint sub: true */
  2. var
  3. /**
  4. * @type {number} next period to wait before next retry in case of failure, in seconds
  5. **/
  6. NEXT_RETRY = 0,
  7. /**
  8. * @type {Room|null}
  9. **/
  10. SELECTED_ROOM = null,
  11. /**
  12. * @type {SimpleChatSystem|null}
  13. **/
  14. SELECTED_CONTEXT = null,
  15. /** @type {Message|null} */
  16. REPLYING_TO = null,
  17. /** @type {Message|null} */
  18. EDITING = null,
  19. /** @const @type {number} */
  20. KEEP_MESSAGES = 100,
  21. /** @type {Array<{channel: string, text: string, isMe: boolean, pendingId: (string|undefined), dom: Element}>} */
  22. PENDING_MESSAGES = []
  23. ;
  24. function initHljs() {
  25. new HttpRequest("highlight.pack.js")
  26. .callbackSuccess(function(code, head, resp) {
  27. var script = document.createElement("script"),
  28. link = document.createElement("link");
  29. script.innerHTML = resp;
  30. script.language = "text/javascript";
  31. link.href = "hljs-androidstudio.css";
  32. link.rel = "stylesheet";
  33. document.head.appendChild(link);
  34. document.body.appendChild(script);
  35. })
  36. .callbackError(function() {
  37. console.error("Failure loading hljs required files");
  38. })
  39. .setTimeout(1000 * 60 * 1) // 1 min timeout
  40. .send();
  41. }
  42. /**
  43. * @param {Room} room
  44. * @param {function(boolean)} cb
  45. **/
  46. function fetchHistory(room, cb) {
  47. new HttpRequest("api/hist?room=" +room.id)
  48. .setResponseType(HttpRequestResponseType.JSON)
  49. .callbackSuccess(function(code, status, resp) {
  50. if (resp) {
  51. var history = DATA.history[room.id],
  52. updated,
  53. now = Date.now();
  54. if (!history) {
  55. history = DATA.history[room.id] = new UiRoomHistory(room, KEEP_MESSAGES, /** @type {Array} */ (resp), now);
  56. updated = true;
  57. } else {
  58. updated = !!history.pushAll(/** @type {Array} */ (resp), now);
  59. }
  60. if (updated) {
  61. if (history.messages.length)
  62. room.setLastMsg(history.lastMessage().ts, now);
  63. onMsgReceived(DATA.context.getChannelContext(room.id).getChatContext(), room, /** @type {Array} */ (resp));
  64. if (room === SELECTED_ROOM)
  65. onRoomUpdated();
  66. }
  67. }
  68. }, this)
  69. .callback(function() {
  70. // TODO ui stop loading
  71. })
  72. .send();
  73. }
  74. function onConfigUpdated() {
  75. if (isObjectEmpty(CONFIG.services)) {
  76. Settings.setClosable(false).display(Settings.pages.services);
  77. }
  78. loadEmojiProvider(CONFIG.getEmojiProvider());
  79. document.getElementById(R.id.stylesheet).innerHTML = CONFIG.compileCSS();
  80. }
  81. function poll(callback) {
  82. if (!IS_LOCAL) {
  83. new HttpRequest("api?v=" +DATA.lastServerVersion)
  84. .callback(function(statusCode, statusText, resp) {
  85. var success = Math.floor(statusCode / 100) === 2;
  86. if (success) {
  87. if (NEXT_RETRY) {
  88. NEXT_RETRY = 0;
  89. onNetworkStateUpdated(true);
  90. }
  91. } else {
  92. if (NEXT_RETRY) {
  93. NEXT_RETRY += Math.floor((NEXT_RETRY || 5)/2);
  94. NEXT_RETRY = Math.min(60, NEXT_RETRY);
  95. } else {
  96. NEXT_RETRY = 5;
  97. onNetworkStateUpdated(false);
  98. }
  99. }
  100. callback(success, resp);
  101. })
  102. .setResponseType(HttpRequestResponseType.JSON)
  103. .setTimeout(1000 * 60 * 1)
  104. .send();
  105. }
  106. }
  107. function outOfSync() {
  108. DATA.lastServerVersion = 0;
  109. }
  110. /**
  111. * @param {Room} room
  112. **/
  113. function sendTyping(room) {
  114. new HttpRequest(HttpRequestMethod.POST, "api/typing?room=" +room.id).send();
  115. }
  116. /**
  117. * @param {boolean} success
  118. * @param {*} response
  119. **/
  120. function onPollResponse(success, response) {
  121. if (success) {
  122. if (response) {
  123. DATA.update(response);
  124. }
  125. startPolling();
  126. } else {
  127. setTimeout(startPolling, NEXT_RETRY * 1000);
  128. }
  129. }
  130. function startPolling() {
  131. poll(onPollResponse);
  132. }
  133. function setNativeTitle(title) {
  134. if (isNative()) {
  135. var enabled = !!(SELECTED_CONTEXT && SELECTED_CONTEXT.getChatContext().capacities["starChannel"]);
  136. __native.setTitle(title, enabled, enabled ? SELECTED_ROOM.starred : false);
  137. }
  138. }
  139. /**
  140. * @param {Room} room
  141. **/
  142. function selectRoom(room) {
  143. if (SELECTED_ROOM)
  144. unselectRoom();
  145. document.getElementById("room_" +room.id).classList.add(R.klass.selected);
  146. document.body.classList.remove(R.klass.noRoomSelected);
  147. SELECTED_ROOM = room;
  148. SELECTED_CONTEXT = /** @type {SimpleChatSystem} */ (DATA.context.getChannelContext(room.id));
  149. if (isNative)
  150. __native.setCurrentChannel(room.id);
  151. onRoomSelected();
  152. roomInfo.hide();
  153. createContextBackground(SELECTED_CONTEXT.getChatContext().team.id, SELECTED_CONTEXT.getChatContext().users, function(imgData) {
  154. document.getElementById(R.id.context).style.backgroundImage = 'url(' +imgData +')';
  155. });
  156. if (!DATA.history[SELECTED_ROOM.id] || DATA.history[SELECTED_ROOM.id].messages.length < KEEP_MESSAGES)
  157. fetchHistory(SELECTED_ROOM, function(success) {});
  158. document.getElementById(R.id.mainSection).classList.remove(R.klass.noRoomSelected);
  159. document.getElementById(R.id.context).classList.remove(R.klass.opened);
  160. }
  161. function setRoomFromHashBang() {
  162. var hashId = document.location.hash.substr(1),
  163. room = DATA.context.getChannel(hashId);
  164. if (room && room !== SELECTED_ROOM)
  165. selectRoom(room);
  166. else {
  167. var user = DATA.context.getUser(hashId);
  168. if (user && user.privateRoom)
  169. selectRoom(user.privateRoom);
  170. }
  171. }
  172. /**
  173. * @param {Room} room
  174. **/
  175. function starChannel(room) {
  176. new HttpRequest(HttpRequestMethod.POST, "api/starChannel?room=" +room.id).send();
  177. }
  178. /**
  179. * @param {Room} room
  180. **/
  181. function unstarChannel(room) {
  182. new HttpRequest(HttpRequestMethod.POST, "api/unstarChannel?room=" +room.id).send();
  183. }
  184. function unselectRoom() {
  185. document.getElementById("room_" +SELECTED_ROOM.id).classList.remove(R.klass.selected);
  186. document.getElementById(R.id.mainSection).classList.add(R.klass.noRoomSelected);
  187. }
  188. /**
  189. * @param {Room} chan
  190. * @param {string} filename
  191. * @param {File} file
  192. * @param {function(string?)} callback
  193. **/
  194. function uploadFile(chan, filename, file, callback) {
  195. var fileReader = new FileReader(),
  196. formData = new FormData();
  197. formData.append("file", file);
  198. formData.append("filename", filename);
  199. new HttpRequest(HttpRequestMethod.POST, "api/file?room=" +chan.id)
  200. .callbackSuccess(function() { callback(null); })
  201. .callbackError(function(sCode, sText, resp) { callback(sText); })
  202. .send(formData);
  203. }
  204. /**
  205. * @param {string} payload
  206. * @param {string} serviceId
  207. * @param {(function((string|null)))=} callback
  208. **/
  209. function sendCommand(payload, serviceId, callback) {
  210. var xhr = new HttpRequest(HttpRequestMethod.POST, "api/attachmentAction?serviceId=" +serviceId);
  211. if (callback)
  212. xhr.callbackSuccess(function() {
  213. callback(null);
  214. }).callbackError(function(code, head, resp) {
  215. callback(head);
  216. });
  217. xhr.send(JSON.stringify(payload));
  218. }
  219. function getActionPayload(channelId, msg, attachment, action) {
  220. var payload = {
  221. "actions": [ action ],
  222. "attachment_id": attachment["id"],
  223. "callback_id": attachment["callback_id"],
  224. "channel_id": channelId,
  225. "is_ephemeral": msg instanceof NoticeMessage,
  226. "message_ts": msg["id"]
  227. };
  228. return payload;
  229. }
  230. /**
  231. * @param {Room} chan
  232. * @param {Command!} cmd
  233. * @param {string} args
  234. **/
  235. function doCommand(chan, cmd, args) {
  236. new HttpRequest(HttpRequestMethod.POST, "api/cmd?room=" +chan.id +"&cmd=" +encodeURIComponent(cmd.name.substr(1)) +"&args=" +encodeURIComponent(args)).send();
  237. }
  238. /**
  239. * @param {Room} chan
  240. * @param {string} msg
  241. * @param {Object=} pendingObj
  242. * @param {Message|null=} replyTo
  243. **/
  244. function sendMsg(chan, msg, pendingObj, replyTo) {
  245. var url = 'api/msg?room=' +chan.id +"&text=" +encodeURIComponent(msg);
  246. if (replyTo) {
  247. var sender = DATA.context.getUser(replyTo.userId),
  248. footer = chan.isPrivate ? locale.message : chan.name;
  249. var attachment = {
  250. "fallback": replyTo.text,
  251. "author_name": sender.getName(),
  252. "text": replyTo.text,
  253. "footer": footer,
  254. "ts": replyTo.ts
  255. };
  256. url += "&attachments=" +encodeURIComponent(JSON.stringify([attachment]));
  257. }
  258. new HttpRequest(HttpRequestMethod.POST, url).setResponseType(HttpRequestResponseType.JSON).callbackSuccess(function(code, text, resp) {
  259. if (resp && resp["pendingId"] !== undefined) {
  260. pendingObj.pendingId = resp["pendingId"];
  261. }
  262. }).send();
  263. }
  264. /**
  265. * @param {Room} chan
  266. * @param {string} text
  267. * @param {Message} msg
  268. **/
  269. function editMsg(chan, text, msg) {
  270. new HttpRequest(HttpRequestMethod.PUT, "api/msg?room=" +chan.id +"&ts=" +msg.id +"&text=" +encodeURIComponent(text)).send();
  271. }
  272. /**
  273. * @param {Room} chan
  274. * @param {Message} msg
  275. **/
  276. function removeMsg(chan, msg) {
  277. new HttpRequest(HttpRequestMethod.DELETE, "api/msg?room=" +chan.id +"&ts=" +msg.id).send();
  278. }
  279. /**
  280. * @param {Room} chan
  281. * @param {Message} msg
  282. **/
  283. function pinMsg(chan, msg) {
  284. new HttpRequest(HttpRequestMethod.POST, "api/pinMsg?room=" +chan.id +"&msgId=" +msg.id).send();
  285. }
  286. /**
  287. * @param {Room} chan
  288. * @param {Message} msg
  289. **/
  290. function starMsg(chan, msg) {
  291. new HttpRequest(HttpRequestMethod.POST, "api/starMsg?room=" +chan.id +"&msgId=" +msg.id).send();
  292. }
  293. /**
  294. * @param {Room} chan
  295. * @param {Message} msg
  296. **/
  297. function unpinMsg(chan, msg) {
  298. new HttpRequest(HttpRequestMethod.DELETE, "api/pinMsg?room=" +chan.id +"&msgId=" +msg.id).send();
  299. }
  300. /**
  301. * @param {Room} chan
  302. * @param {Message} msg
  303. **/
  304. function unstarMsg(chan, msg) {
  305. new HttpRequest(HttpRequestMethod.DELETE, "api/starMsg?room=" +chan.id +"&msgId=" +msg.id).send();
  306. }
  307. /**
  308. * @param {Room} chan
  309. * @param {string} id
  310. * @param {number} ts
  311. **/
  312. function sendReadMarker(chan, id, ts) {
  313. new HttpRequest(HttpRequestMethod.POST, "api/markread?room=" +chan.id +"&id=" +id +"&ts=" +ts).send();
  314. }
  315. /**
  316. * @param {string} channelId
  317. * @param {string} msgId
  318. * @param {string} reaction
  319. **/
  320. function addReaction(channelId, msgId, reaction) {
  321. new HttpRequest(HttpRequestMethod.POST, "api/reaction?room=" +channelId +"&msg=" +msgId +"&reaction=" +encodeURIComponent(reaction)).send();
  322. }
  323. /**
  324. * @param {string} channelId
  325. * @param {string} msgId
  326. * @param {string} reaction
  327. **/
  328. function removeReaction(channelId, msgId, reaction) {
  329. new HttpRequest(HttpRequestMethod.DELETE, "api/reaction?room=" +channelId +"&msg=" +msgId +"&reaction=" +encodeURIComponent(reaction)).send();
  330. }
  331. function logout() {
  332. new HttpRequest(HttpRequestMethod.POST, "api/logout").send();
  333. document.cookie = "sessID=;Path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
  334. document.location.reload();
  335. if (isNative())
  336. __native.logout();
  337. }
  338. /**
  339. * @this {Element}
  340. **/
  341. function filterChanList() {
  342. var chans = {},
  343. matchingChans = [],
  344. val = this.value;
  345. DATA.context.foreachChannels(function(chan) {
  346. chans[chan.id] = chan.matchString(val, Utils);
  347. });
  348. for (var chanId in chans) {
  349. var chanDom = document.getElementById("room_" +chanId);
  350. if (chanDom) {
  351. if (chans[chanId].name + chans[chanId].members + chans[chanId].topic +chans[chanId].purpose) {
  352. chanDom.classList.remove(R.klass.hidden);
  353. matchingChans.push(chanId);
  354. } else {
  355. chanDom.classList.add(R.klass.hidden);
  356. }
  357. }
  358. }
  359. //TODO sort
  360. }