workflow.js 12 KB

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