workflow.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. var
  2. /**
  3. * @type {number} next period to wait before next retry in case of failure, in seconds
  4. **/
  5. NEXT_RETRY = 5
  6. /**
  7. * @type {SlackChan|SlackIms|SlackGroup}
  8. **/
  9. ,SELECTED_ROOM = null
  10. ;
  11. function poll(callback) {
  12. var xhr = new XMLHttpRequest();
  13. xhr.timeout = 1000 * 60 * 1; // 3 min timeout
  14. xhr.onreadystatechange = function(e) {
  15. if (xhr.readyState === 4) {
  16. if (xhr.status === 0) {
  17. poll(callback); // retry on timeout
  18. NEXT_RETRY = 5;
  19. return;
  20. }
  21. var resp = null
  22. ,success = Math.floor(xhr.status / 100) === 2;
  23. if (success) {
  24. NEXT_RETRY = 5;
  25. resp = xhr.response;
  26. try {
  27. resp = JSON.parse(/** @type {string} */ (resp));
  28. } catch (e) {
  29. resp = null;
  30. }
  31. } else {
  32. NEXT_RETRY += Math.floor(NEXT_RETRY /2);
  33. NEXT_RETRY = Math.min(60, NEXT_RETRY);
  34. }
  35. callback(success, resp);
  36. }
  37. };
  38. xhr.open('GET', 'api?v=' +SLACK.lastServerVersion, true);
  39. xhr.send(null);
  40. }
  41. /**
  42. * @param {boolean} success
  43. * @param {*} response
  44. **/
  45. function onPollResponse(success, response) {
  46. if (success) {
  47. if (response) {
  48. SLACK.update(response);
  49. }
  50. startPolling();
  51. } else {
  52. setTimeout(startPolling, NEXT_RETRY * 1000);
  53. }
  54. }
  55. function startPolling() {
  56. poll(onPollResponse);
  57. }
  58. /**
  59. * @param {SlackChan|SlackIms|SlackGroup} room
  60. **/
  61. function selectRoom(room) {
  62. if (SELECTED_ROOM)
  63. unselectRoom();
  64. document.getElementById(room.id).classList.add(R.klass.selected);
  65. document.body.classList.remove(R.klass.noRoomSelected);
  66. SELECTED_ROOM = room;
  67. onRoomSelected();
  68. }
  69. function unselectRoom() {
  70. document.getElementById(SELECTED_ROOM.id).classList.remove(R.klass.selected);
  71. }