state.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /**
  2. * This file is part of Threema Web.
  3. *
  4. * Threema Web is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU Affero General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. import {AsyncEvent} from 'ts-events';
  18. import {Logger} from 'ts-log';
  19. import {LogService} from './log';
  20. import TaskConnectionState = threema.TaskConnectionState;
  21. import GlobalConnectionState = threema.GlobalConnectionState;
  22. import ChosenTask = threema.ChosenTask;
  23. const enum Stage {
  24. Signaling,
  25. Task,
  26. }
  27. export class StateService {
  28. // Angular services
  29. private $interval: ng.IIntervalService;
  30. // Logging
  31. private readonly log: Logger;
  32. // Events
  33. public evtConnectionBuildupStateChange = new AsyncEvent<threema.ConnectionBuildupStateChange>();
  34. public evtGlobalConnectionStateChange = new AsyncEvent<threema.GlobalConnectionStateChange>();
  35. public evtUnreadCountChange = new AsyncEvent<number>();
  36. // Connection states
  37. public signalingConnectionState: saltyrtc.SignalingState;
  38. public taskConnectionState: TaskConnectionState;
  39. // Connection buildup state
  40. public connectionBuildupState: threema.ConnectionBuildupState;
  41. public progress = 0;
  42. private progressInterval: ng.IPromise<any> = null;
  43. public slowConnect = false;
  44. // Global connection state
  45. private stage: Stage;
  46. private _state: threema.GlobalConnectionState;
  47. public attempt: number = 0;
  48. // Unread messages
  49. private _unreadCount: number = 0;
  50. public static $inject = ['$interval', 'LogService'];
  51. constructor($interval: ng.IIntervalService, logService: LogService) {
  52. this.$interval = $interval;
  53. this.log = logService.getLogger('State-S', 'color: #fff; background-color: #cc9900');
  54. this.reset();
  55. }
  56. /**
  57. * Getters and setters for global connection state.
  58. */
  59. public get state(): threema.GlobalConnectionState {
  60. return this._state;
  61. }
  62. public set state(state: threema.GlobalConnectionState) {
  63. const prevState = this._state;
  64. if (prevState === state) {
  65. // No need to dispatch any events
  66. return;
  67. }
  68. this._state = state;
  69. this.evtGlobalConnectionStateChange.post({state: state, prevState: prevState});
  70. }
  71. /**
  72. * Signaling connection state.
  73. */
  74. public updateSignalingConnectionState(
  75. state: saltyrtc.SignalingState, chosenTask: ChosenTask, handoverDone: boolean,
  76. ): void {
  77. const prevState = this.signalingConnectionState;
  78. this.signalingConnectionState = state;
  79. if (!handoverDone) {
  80. this.log.debug('Signaling connection state:', prevState, '=>', state);
  81. switch (state) {
  82. case 'new':
  83. case 'ws-connecting':
  84. case 'server-handshake':
  85. case 'peer-handshake':
  86. this.state = GlobalConnectionState.Warning;
  87. break;
  88. case 'task':
  89. this.stage = Stage.Task;
  90. if (chosenTask === ChosenTask.RelayedData) {
  91. this.updateTaskConnectionState(TaskConnectionState.Connected);
  92. } else {
  93. this.state = GlobalConnectionState.Warning;
  94. }
  95. break;
  96. case 'closing':
  97. case 'closed':
  98. this.state = GlobalConnectionState.Error;
  99. break;
  100. default:
  101. this.log.warn(`Unknown signaling connection state: ${state}`);
  102. }
  103. } else {
  104. this.log.debug('Ignored signaling connection state to "' + state + '"');
  105. }
  106. }
  107. /**
  108. * Task connection state.
  109. */
  110. public updateTaskConnectionState(state: TaskConnectionState): void {
  111. const prevState = this.taskConnectionState;
  112. this.taskConnectionState = state;
  113. if (this.stage === Stage.Task) {
  114. this.log.debug('Task connection state:', prevState, '=>', state);
  115. switch (state) {
  116. case TaskConnectionState.New:
  117. case TaskConnectionState.Connecting:
  118. case TaskConnectionState.Reconnecting:
  119. this.state = GlobalConnectionState.Warning;
  120. break;
  121. case TaskConnectionState.Connected:
  122. this.state = GlobalConnectionState.Ok;
  123. this.attempt = 0;
  124. break;
  125. case TaskConnectionState.Disconnected:
  126. this.state = GlobalConnectionState.Error;
  127. break;
  128. default:
  129. this.log.warn('Ignored task connection state change to "' + state + '"');
  130. }
  131. } else {
  132. this.log.debug('Ignored task connection state change to "' + state + '"');
  133. }
  134. }
  135. /**
  136. * Connection buildup state.
  137. */
  138. public updateConnectionBuildupState(state: threema.ConnectionBuildupState): void {
  139. if (this.connectionBuildupState === state) {
  140. return;
  141. }
  142. const prevState = this.connectionBuildupState;
  143. this.log.debug('Connection buildup state:', prevState, '=>', state);
  144. // Update state
  145. this.connectionBuildupState = state;
  146. this.evtConnectionBuildupStateChange.post({state: state, prevState: prevState});
  147. // Cancel progress interval if present
  148. if (this.progressInterval !== null) {
  149. this.$interval.cancel(this.progressInterval);
  150. this.progressInterval = null;
  151. }
  152. // Reset slow connect state
  153. this.slowConnect = false;
  154. // Update progress
  155. switch (state) {
  156. case 'new':
  157. this.progress = 0;
  158. break;
  159. case 'push':
  160. this.progress = 0;
  161. this.progressInterval = this.$interval(() => {
  162. if (this.progress < 12) {
  163. this.progress += 1;
  164. } else {
  165. this.slowConnect = true;
  166. }
  167. }, 800);
  168. break;
  169. case 'manual_start':
  170. this.progress = 0;
  171. break;
  172. case 'connecting':
  173. this.progress = 13;
  174. break;
  175. case 'waiting':
  176. this.progress = 14;
  177. break;
  178. case 'peer_handshake':
  179. this.progress = 15;
  180. this.progressInterval = this.$interval(() => {
  181. if (this.progress < 40) {
  182. this.progress += 5;
  183. } else if (this.progress < 55) {
  184. this.progress += 3;
  185. } else if (this.progress < 60) {
  186. this.progress += 1;
  187. } else {
  188. this.slowConnect = true;
  189. }
  190. }, 500);
  191. break;
  192. case 'loading':
  193. this.progress = 60;
  194. this.progressInterval = this.$interval(() => {
  195. if (this.progress < 80) {
  196. this.progress += 4;
  197. } else if (this.progress < 90) {
  198. this.progress += 2;
  199. } else if (this.progress < 99) {
  200. this.progress += 1;
  201. } else {
  202. this.slowConnect = true;
  203. }
  204. }, 600);
  205. break;
  206. case 'done':
  207. this.progress = 100;
  208. break;
  209. default:
  210. this.progress = 0;
  211. break;
  212. }
  213. }
  214. /**
  215. * Return whether messages can be submitted to the outgoing queue.
  216. *
  217. * The `startupDone` flag indicates, whether the initial data in the
  218. * webclient service has been loaded or not.
  219. */
  220. public readyToSubmit(chosenTask: ChosenTask, startupDone: boolean): boolean {
  221. switch (chosenTask) {
  222. case ChosenTask.RelayedData:
  223. return true;
  224. case ChosenTask.WebRTC:
  225. default:
  226. return this.state === GlobalConnectionState.Ok && startupDone;
  227. }
  228. }
  229. /**
  230. * Getters and setters for unread messages count.
  231. */
  232. public get unreadCount(): number {
  233. return this._unreadCount;
  234. }
  235. public set unreadCount(count: number) {
  236. if (this._unreadCount === count) {
  237. // No need to dispatch any events
  238. return;
  239. }
  240. this._unreadCount = count;
  241. this.evtUnreadCountChange.post(count);
  242. }
  243. /**
  244. * Reset all states.
  245. */
  246. public reset(connectionBuildupState: threema.ConnectionBuildupState = 'new'): void {
  247. this.log.debug('Reset states');
  248. // Reset state
  249. this.signalingConnectionState = 'new';
  250. this.taskConnectionState = TaskConnectionState.New;
  251. this.stage = Stage.Signaling;
  252. this.state = GlobalConnectionState.Error;
  253. this.connectionBuildupState = connectionBuildupState;
  254. this.progress = 0;
  255. this.unreadCount = 0;
  256. }
  257. }