Crowi.js 6.3 KB

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