AppContextContainer.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import { Container } from 'unstated';
  2. import axios from 'axios';
  3. import io from 'socket.io-client';
  4. import InterceptorManager from '@commons/service/interceptor-manager';
  5. import emojiStrategy from '../util/emojione/emoji_strategy_shrinked.json';
  6. import {
  7. DetachCodeBlockInterceptor,
  8. RestoreCodeBlockInterceptor,
  9. } from '../util/interceptor/detach-code-blocks';
  10. /**
  11. * Service container related to options for Application
  12. * @extends {Container} unstated Container
  13. */
  14. export default class AppContextContainer extends Container {
  15. constructor() {
  16. super();
  17. const body = document.querySelector('body');
  18. this.me = body.dataset.currentUsername;
  19. this.isAdmin = body.dataset.isAdmin;
  20. this.csrfToken = body.dataset.csrftoken;
  21. this.config = JSON.parse(document.getElementById('crowi-context-hydrate').textContent || '{}');
  22. const userAgent = window.navigator.userAgent.toLowerCase();
  23. this.isMobile = /iphone|ipad|android/.test(userAgent);
  24. this.socketClientId = Math.floor(Math.random() * 100000);
  25. this.page = undefined;
  26. this.pageEditor = undefined;
  27. this.isDocSaved = true;
  28. this.fetchUsers = this.fetchUsers.bind(this);
  29. this.apiGet = this.apiGet.bind(this);
  30. this.apiPost = this.apiPost.bind(this);
  31. this.apiRequest = this.apiRequest.bind(this);
  32. this.interceptorManager = new InterceptorManager();
  33. this.interceptorManager.addInterceptor(new DetachCodeBlockInterceptor(this), 10); // process as soon as possible
  34. this.interceptorManager.addInterceptor(new RestoreCodeBlockInterceptor(this), 900); // process as late as possible
  35. this.users = [];
  36. this.userByName = {};
  37. this.userById = {};
  38. this.draft = {};
  39. this.editorOptions = {};
  40. this.recoverData();
  41. this.socket = io();
  42. }
  43. /**
  44. * @return {Object} window.Crowi (js/legacy/crowi.js)
  45. */
  46. getCrowiForJquery() {
  47. return window.Crowi;
  48. }
  49. getConfig() {
  50. return this.config;
  51. }
  52. setPage(page) {
  53. this.page = page;
  54. }
  55. setPageEditor(pageEditor) {
  56. this.pageEditor = pageEditor;
  57. }
  58. setIsDocSaved(isSaved) {
  59. this.isDocSaved = isSaved;
  60. }
  61. getIsDocSaved() {
  62. return this.isDocSaved;
  63. }
  64. getWebSocket() {
  65. return this.socket;
  66. }
  67. getSocketClientId() {
  68. return this.socketClientId;
  69. }
  70. getEmojiStrategy() {
  71. return emojiStrategy;
  72. }
  73. recoverData() {
  74. const keys = [
  75. 'userByName',
  76. 'userById',
  77. 'users',
  78. 'draft',
  79. ];
  80. keys.forEach((key) => {
  81. const keyContent = window.localStorage[key];
  82. if (keyContent) {
  83. try {
  84. this[key] = JSON.parse(keyContent);
  85. }
  86. catch (e) {
  87. window.localStorage.removeItem(key);
  88. }
  89. }
  90. });
  91. }
  92. fetchUsers() {
  93. const interval = 1000 * 60 * 15; // 15min
  94. const currentTime = new Date();
  95. if (window.localStorage.lastFetched && interval > currentTime - new Date(window.localStorage.lastFetched)) {
  96. return;
  97. }
  98. this.apiGet('/users.list', {})
  99. .then((data) => {
  100. this.users = data.users;
  101. window.localStorage.users = JSON.stringify(data.users);
  102. const userByName = {};
  103. const userById = {};
  104. for (let i = 0; i < data.users.length; i++) {
  105. const user = data.users[i];
  106. userByName[user.username] = user;
  107. userById[user._id] = user;
  108. }
  109. this.userByName = userByName;
  110. window.localStorage.userByName = JSON.stringify(userByName);
  111. this.userById = userById;
  112. window.localStorage.userById = JSON.stringify(userById);
  113. window.localStorage.lastFetched = new Date();
  114. })
  115. .catch((err) => {
  116. window.localStorage.removeItem('lastFetched');
  117. // ignore errors
  118. });
  119. }
  120. setCaretLine(line) {
  121. if (this.pageEditor != null) {
  122. this.pageEditor.setCaretLine(line);
  123. }
  124. }
  125. focusToEditor() {
  126. if (this.pageEditor != null) {
  127. this.pageEditor.focusToEditor();
  128. }
  129. }
  130. clearDraft(path) {
  131. delete this.draft[path];
  132. window.localStorage.setItem('draft', JSON.stringify(this.draft));
  133. }
  134. clearAllDrafts() {
  135. window.localStorage.removeItem('draft');
  136. }
  137. saveDraft(path, body) {
  138. this.draft[path] = body;
  139. window.localStorage.setItem('draft', JSON.stringify(this.draft));
  140. }
  141. findDraft(path) {
  142. if (this.draft && this.draft[path]) {
  143. return this.draft[path];
  144. }
  145. return null;
  146. }
  147. findUserById(userId) {
  148. if (this.userById && this.userById[userId]) {
  149. return this.userById[userId];
  150. }
  151. return null;
  152. }
  153. findUserByIds(userIds) {
  154. const users = [];
  155. for (const userId of userIds) {
  156. const user = this.findUserById(userId);
  157. if (user) {
  158. users.push(user);
  159. }
  160. }
  161. return users;
  162. }
  163. findUser(username) {
  164. if (this.userByName && this.userByName[username]) {
  165. return this.userByName[username];
  166. }
  167. return null;
  168. }
  169. createPage(pagePath, markdown, additionalParams = {}) {
  170. const params = Object.assign(additionalParams, {
  171. path: pagePath,
  172. body: markdown,
  173. });
  174. return this.apiPost('/pages.create', params)
  175. .then((res) => {
  176. if (!res.ok) {
  177. throw new Error(res.error);
  178. }
  179. return res.page;
  180. });
  181. }
  182. updatePage(pageId, revisionId, markdown, additionalParams = {}) {
  183. const params = Object.assign(additionalParams, {
  184. page_id: pageId,
  185. revision_id: revisionId,
  186. body: markdown,
  187. });
  188. return this.apiPost('/pages.update', params)
  189. .then((res) => {
  190. if (!res.ok) {
  191. throw new Error(res.error);
  192. }
  193. return res.page;
  194. });
  195. }
  196. launchHandsontableModal(componentKind, beginLineNumber, endLineNumber) {
  197. let targetComponent;
  198. switch (componentKind) {
  199. case 'page':
  200. targetComponent = this.page;
  201. break;
  202. }
  203. targetComponent.launchHandsontableModal(beginLineNumber, endLineNumber);
  204. }
  205. apiGet(path, params) {
  206. return this.apiRequest('get', path, { params });
  207. }
  208. apiPost(path, params) {
  209. if (!params._csrf) {
  210. params._csrf = this.csrfToken;
  211. }
  212. return this.apiRequest('post', path, params);
  213. }
  214. apiRequest(method, path, params) {
  215. return new Promise((resolve, reject) => {
  216. axios[method](`/_api${path}`, params)
  217. .then((res) => {
  218. if (res.data.ok) {
  219. resolve(res.data);
  220. }
  221. else {
  222. reject(new Error(res.data.error));
  223. }
  224. })
  225. .catch((res) => {
  226. reject(res);
  227. });
  228. });
  229. }
  230. }