Crowi.js 6.6 KB

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