Crowi.js 5.8 KB

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