Crowi.js 5.7 KB

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