1
0

workflow.js 13 KB

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