1
0

workflow.js 13 KB

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