1
0

workflow.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. document.getElementById(R.id.stylesheet).innerHTML = CONFIG.compileCSS();
  91. }
  92. function poll(callback) {
  93. if (!IS_LOCAL) {
  94. HttpRequestWrapper("api?v=" +DATA.lastServerVersion)
  95. .callback(function(statusCode, statusText, resp) {
  96. var success = Math.floor(statusCode / 100) === 2;
  97. if (success) {
  98. if (NEXT_RETRY) {
  99. NEXT_RETRY = 0;
  100. onNetworkStateUpdated(true);
  101. }
  102. } else {
  103. if (NEXT_RETRY) {
  104. NEXT_RETRY += Math.floor((NEXT_RETRY || 5)/2);
  105. NEXT_RETRY = Math.min(60, NEXT_RETRY);
  106. } else {
  107. NEXT_RETRY = 5;
  108. onNetworkStateUpdated(false);
  109. }
  110. }
  111. callback(success, resp);
  112. })
  113. .setResponseType(HttpRequestResponseType.JSON)
  114. .setTimeout(1000 * 60 * 1)
  115. .send();
  116. }
  117. }
  118. function outOfSync() {
  119. DATA.lastServerVersion = 0;
  120. }
  121. /**
  122. * @param {Room} room
  123. **/
  124. function sendTyping(room) {
  125. HttpRequestWrapper(HttpRequestMethod.POST, "api/typing?room=" +HttpRequestWrapper.encode(room.id)).send();
  126. }
  127. /**
  128. * @param {boolean} success
  129. * @param {*} response
  130. **/
  131. function onPollResponse(success, response) {
  132. if (success) {
  133. if (response) {
  134. DATA.update(response);
  135. }
  136. startPolling();
  137. } else {
  138. setTimeout(startPolling, NEXT_RETRY * 1000);
  139. }
  140. }
  141. function startPolling() {
  142. poll(onPollResponse);
  143. }
  144. function setNativeTitle(title) {
  145. if (isNative()) {
  146. var enabled = !!(SELECTED_CONTEXT && SELECTED_CONTEXT.getChatContext().capacities["starChannel"]);
  147. __native.setTitle(title, enabled, enabled ? SELECTED_ROOM.starred : false);
  148. }
  149. }
  150. /**
  151. * @param {Room} room
  152. **/
  153. function selectRoom(room) {
  154. if (SELECTED_ROOM)
  155. unselectRoom();
  156. document.getElementById("room_" +room.id).classList.add(R.klass.selected);
  157. document.body.classList.remove(R.klass.noRoomSelected);
  158. SELECTED_ROOM = room;
  159. SELECTED_CONTEXT = /** @type {SimpleChatSystem} */ (DATA.context.getChannelContext(room.id));
  160. SELECTED_ROOM_UNREAD = room.lastRead;
  161. if (isNative())
  162. __native.setCurrentChannel(room.id);
  163. onRoomSelected();
  164. roomInfo.hide();
  165. createContextBackground(SELECTED_CONTEXT.getChatContext().team.id, SELECTED_CONTEXT.getChatContext().users, function(imgData) {
  166. document.getElementById(R.id.context).style.backgroundImage = 'url(' +imgData +')';
  167. });
  168. if (!DATA.history[SELECTED_ROOM.id] || DATA.history[SELECTED_ROOM.id].messages.length < KEEP_MESSAGES)
  169. fetchHistory(SELECTED_ROOM, function(success) {});
  170. document.getElementById(R.id.mainSection).classList.remove(R.klass.noRoomSelected);
  171. document.getElementById(R.id.context).classList.remove(R.klass.opened);
  172. }
  173. function setRoomFromHashBang() {
  174. var hashId = document.location.hash.substr(1),
  175. room = DATA.context.getChannel(hashId);
  176. if (room && room !== SELECTED_ROOM) {
  177. selectRoom(room);
  178. return true;
  179. } else {
  180. var user = DATA.context.getUser(hashId);
  181. if (user && user.privateRoom) {
  182. selectRoom(user.privateRoom);
  183. return true;
  184. }
  185. }
  186. return false;
  187. }
  188. /**
  189. * @param {Room} room
  190. **/
  191. function starChannel(room) {
  192. HttpRequestWrapper(HttpRequestMethod.POST, "api/starChannel?room=" +HttpRequestWrapper.encode(room.id)).send();
  193. }
  194. /**
  195. * @param {Room} room
  196. **/
  197. function unstarChannel(room) {
  198. HttpRequestWrapper(HttpRequestMethod.POST, "api/unstarChannel?room=" +HttpRequestWrapper.encode(room.id)).send();
  199. }
  200. function unselectRoom() {
  201. document.getElementById("room_" +SELECTED_ROOM.id).classList.remove(R.klass.selected);
  202. document.getElementById(R.id.mainSection).classList.add(R.klass.noRoomSelected);
  203. }
  204. /**
  205. * @param {Room} chan
  206. * @param {string} filename
  207. * @param {File} file
  208. * @param {function(string?)} callback
  209. **/
  210. function uploadFile(chan, filename, file, callback) {
  211. var fileReader = new FileReader(),
  212. formData = new FormData();
  213. // FIXME NATIVE !
  214. formData.append("file", file);
  215. formData.append("filename", filename);
  216. HttpRequestWrapper(HttpRequestMethod.POST, "api/file?room=" +HttpRequestWrapper.encode(chan.id))
  217. .callbackSuccess(function() { callback(null); })
  218. .callbackError(function(sCode, sText, resp) { callback(sText); })
  219. .send(formData);
  220. }
  221. /**
  222. * @param {string} payload
  223. * @param {string} serviceId
  224. * @param {(function((string|null)))=} callback
  225. **/
  226. function sendCommand(payload, serviceId, callback) {
  227. var xhr = HttpRequestWrapper(HttpRequestMethod.POST, "api/attachmentAction?serviceId=" +HttpRequestWrapper.encode(serviceId));
  228. if (callback)
  229. xhr.callbackSuccess(function() {
  230. callback(null);
  231. }).callbackError(function(code, head, resp) {
  232. callback(head);
  233. });
  234. xhr.send(JSON.stringify(payload));
  235. }
  236. function getActionPayload(channelId, msg, attachment, action) {
  237. var payload = {
  238. "actions": [ action ],
  239. "attachment_id": attachment["id"],
  240. "callback_id": attachment["callback_id"],
  241. "channel_id": channelId,
  242. "is_ephemeral": msg instanceof NoticeMessage,
  243. "message_ts": msg["id"]
  244. };
  245. return payload;
  246. }
  247. /**
  248. * @param {Room} chan
  249. * @param {Command!} cmd
  250. * @param {string} args
  251. **/
  252. function doCommand(chan, cmd, args) {
  253. HttpRequestWrapper(HttpRequestMethod.POST, "api/cmd?room=" +HttpRequestWrapper.encode(chan.id) +"&cmd=" +HttpRequestWrapper.encode(cmd.name.substr(1)) +"&args=" +HttpRequestWrapper.encode(args)).send();
  254. }
  255. /**
  256. * @param {Room} chan
  257. * @param {string} msg
  258. * @param {Object=} pendingObj
  259. * @param {Message|null=} replyTo
  260. **/
  261. function sendMsg(chan, msg, pendingObj, replyTo) {
  262. var url = 'api/msg?room=' +HttpRequestWrapper.encode(chan.id) +"&text=" +HttpRequestWrapper.encode(msg);
  263. if (replyTo) {
  264. var sender = DATA.context.getUser(replyTo.userId),
  265. footer = chan.isPrivate ? locale.message : chan.name;
  266. var attachment = {
  267. "fallback": replyTo.text,
  268. "author_name": sender.getName(),
  269. "text": replyTo.text,
  270. "footer": footer,
  271. "ts": replyTo.ts
  272. };
  273. url += "&attachments=" +HttpRequestWrapper.encode(JSON.stringify([attachment]));
  274. }
  275. SELECTED_ROOM_UNREAD = -1;
  276. HttpRequestWrapper(HttpRequestMethod.POST, url).setResponseType(HttpRequestResponseType.JSON).callbackSuccess(function(code, text, resp) {
  277. if (resp && resp["pendingId"] !== undefined) {
  278. pendingObj.pendingId = resp["pendingId"];
  279. }
  280. }).send();
  281. }
  282. /**
  283. * @param {Room} chan
  284. * @param {string} text
  285. * @param {Message} msg
  286. **/
  287. function editMsg(chan, text, msg) {
  288. HttpRequestWrapper(HttpRequestMethod.PUT, "api/msg?room=" +HttpRequestWrapper.encode(chan.id) +"&ts=" +msg.id +"&text=" +HttpRequestWrapper.encode(text)).send();
  289. }
  290. /**
  291. * @param {Room} chan
  292. * @param {Message} msg
  293. **/
  294. function removeMsg(chan, msg) {
  295. HttpRequestWrapper(HttpRequestMethod.DELETE, "api/msg?room=" +HttpRequestWrapper.encode(chan.id) +"&ts=" +msg.id).send();
  296. }
  297. /**
  298. * @param {Room} chan
  299. * @param {Message} msg
  300. **/
  301. function pinMsg(chan, msg) {
  302. HttpRequestWrapper(HttpRequestMethod.POST, "api/pinMsg?room=" +HttpRequestWrapper.encode(chan.id) +"&msgId=" +msg.id).send();
  303. }
  304. /**
  305. * @param {Room} chan
  306. * @param {Message} msg
  307. **/
  308. function starMsg(chan, msg) {
  309. HttpRequestWrapper(HttpRequestMethod.POST, "api/starMsg?room=" +HttpRequestWrapper.encode(chan.id) +"&msgId=" +msg.id).send();
  310. }
  311. /**
  312. * @param {Room} chan
  313. * @param {Message} msg
  314. **/
  315. function unpinMsg(chan, msg) {
  316. HttpRequestWrapper(HttpRequestMethod.DELETE, "api/pinMsg?room=" +HttpRequestWrapper.encode(chan.id) +"&msgId=" +msg.id).send();
  317. }
  318. /**
  319. * @param {Room} chan
  320. * @param {Message} msg
  321. **/
  322. function unstarMsg(chan, msg) {
  323. HttpRequestWrapper(HttpRequestMethod.DELETE, "api/starMsg?room=" +HttpRequestWrapper.encode(chan.id) +"&msgId=" +msg.id).send();
  324. }
  325. /**
  326. * @param {Room} chan
  327. * @param {string} id
  328. * @param {number} ts
  329. **/
  330. function sendReadMarker(chan, id, ts) {
  331. HttpRequestWrapper(HttpRequestMethod.POST, "api/markread?room=" +HttpRequestWrapper.encode(chan.id) +"&id=" +id +"&ts=" +ts).send();
  332. }
  333. /**
  334. * @param {string} channelId
  335. * @param {string} msgId
  336. * @param {string} reaction
  337. **/
  338. function addReaction(channelId, msgId, reaction) {
  339. HttpRequestWrapper(HttpRequestMethod.POST, "api/reaction?room=" +HttpRequestWrapper.encode(channelId) +"&msg=" +msgId +"&reaction=" +HttpRequestWrapper.encode(reaction)).send();
  340. }
  341. /**
  342. * @param {string} channelId
  343. * @param {string} msgId
  344. * @param {string} reaction
  345. **/
  346. function removeReaction(channelId, msgId, reaction) {
  347. HttpRequestWrapper(HttpRequestMethod.DELETE, "api/reaction?room=" +HttpRequestWrapper.encode(channelId) +"&msg=" +msgId +"&reaction=" +HttpRequestWrapper.encode(reaction)).send();
  348. }
  349. function logout() {
  350. HttpRequestWrapper(HttpRequestMethod.POST, "api/logout").send();
  351. document.cookie = "sessID=;Path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
  352. document.location.reload();
  353. if (isNative())
  354. __native.logout();
  355. }
  356. /**
  357. * @this {Element}
  358. **/
  359. function filterChanList() {
  360. var chans = {},
  361. matchingChans = [],
  362. val = this.value;
  363. DATA.context.foreachChannels(function(chan) {
  364. chans[chan.id] = chan.matchString(val, Utils);
  365. });
  366. for (var chanId in chans) {
  367. var chanDom = document.getElementById("room_" +chanId);
  368. if (chanDom) {
  369. if (chans[chanId].name + chans[chanId].members + chans[chanId].topic +chans[chanId].purpose) {
  370. chanDom.classList.remove(R.klass.hidden);
  371. matchingChans.push(chanId);
  372. } else {
  373. chanDom.classList.add(R.klass.hidden);
  374. }
  375. }
  376. }
  377. //TODO sort
  378. }