Crowi.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /**
  2. * Crowi context class for client
  3. */
  4. import axios from 'axios'
  5. import InterceptorManager from '../../../lib/util/interceptor-manager';
  6. import {
  7. DetachCodeBlockInterceptor,
  8. RestoreCodeBlockInterceptor,
  9. } from './interceptor/detach-code-blocks';
  10. export default class Crowi {
  11. constructor(context, window) {
  12. this.context = context;
  13. this.config = {};
  14. this.csrfToken = context.csrfToken;
  15. this.window = window;
  16. this.location = window.location || {};
  17. this.document = window.document || {};
  18. this.localStorage = window.localStorage || {};
  19. this.fetchUsers = this.fetchUsers.bind(this);
  20. this.apiGet = this.apiGet.bind(this);
  21. this.apiPost = this.apiPost.bind(this);
  22. this.apiRequest = this.apiRequest.bind(this);
  23. this.interceptorManager = new InterceptorManager();
  24. this.interceptorManager.addInterceptors([
  25. new DetachCodeBlockInterceptor(this),
  26. new RestoreCodeBlockInterceptor(this),
  27. ]);
  28. // FIXME
  29. this.me = context.me;
  30. this.users = [];
  31. this.userByName = {};
  32. this.userById = {};
  33. this.draft = {};
  34. this.recoverData();
  35. }
  36. /**
  37. * @return {Object} window.Crowi (/resource/js/crowi.js)
  38. */
  39. getCrowiForJquery() {
  40. return window.Crowi;
  41. }
  42. getContext() {
  43. return context;
  44. }
  45. setConfig(config) {
  46. this.config = config;
  47. }
  48. getConfig() {
  49. return this.config;
  50. }
  51. recoverData() {
  52. const keys = [
  53. 'userByName',
  54. 'userById',
  55. 'users',
  56. 'draft',
  57. ];
  58. keys.forEach(key => {
  59. if (this.localStorage[key]) {
  60. try {
  61. this[key] = JSON.parse(this.localStorage[key]);
  62. } catch (e) {
  63. this.localStorage.removeItem(key);
  64. }
  65. }
  66. });
  67. }
  68. fetchUsers () {
  69. const interval = 1000*60*15; // 15min
  70. const currentTime = new Date();
  71. if (this.localStorage.lastFetched && interval > currentTime - new Date(this.localStorage.lastFetched)) {
  72. return ;
  73. }
  74. this.apiGet('/users.list', {})
  75. .then(data => {
  76. this.users = data.users;
  77. this.localStorage.users = JSON.stringify(data.users);
  78. let userByName = {};
  79. let userById = {};
  80. for (let i = 0; i < data.users.length; i++) {
  81. const user = data.users[i];
  82. userByName[user.username] = user;
  83. userById[user._id] = user;
  84. }
  85. this.userByName = userByName;
  86. this.localStorage.userByName = JSON.stringify(userByName);
  87. this.userById = userById;
  88. this.localStorage.userById = JSON.stringify(userById);
  89. this.localStorage.lastFetched = new Date();
  90. }).catch(err => {
  91. this.localStorage.removeItem('lastFetched');
  92. // ignore errors
  93. });
  94. }
  95. clearDraft(path) {
  96. delete this.draft[path];
  97. this.localStorage.draft = JSON.stringify(this.draft);
  98. }
  99. saveDraft(path, body) {
  100. this.draft[path] = body;
  101. this.localStorage.draft = JSON.stringify(this.draft);
  102. }
  103. findDraft(path) {
  104. if (this.draft && this.draft[path]) {
  105. return this.draft[path];
  106. }
  107. return null;
  108. }
  109. findUserById(userId) {
  110. if (this.userById && this.userById[userId]) {
  111. return this.userById[userId];
  112. }
  113. return null;
  114. }
  115. findUserByIds(userIds) {
  116. let users = [];
  117. for (let userId of userIds) {
  118. let user = this.findUserById(userId);
  119. if (user) {
  120. users.push(user);
  121. }
  122. }
  123. return users;
  124. }
  125. findUser(username) {
  126. if (this.userByName && this.userByName[username]) {
  127. return this.userByName[username];
  128. }
  129. return null;
  130. }
  131. apiGet(path, params) {
  132. return this.apiRequest('get', path, {params: params});
  133. }
  134. apiPost(path, params) {
  135. if (!params._csrf) {
  136. params._csrf = this.csrfToken;
  137. }
  138. return this.apiRequest('post', path, params);
  139. }
  140. apiRequest(method, path, params) {
  141. return new Promise((resolve, reject) => {
  142. axios[method](`/_api${path}`, params)
  143. .then(res => {
  144. if (res.data.ok) {
  145. resolve(res.data);
  146. } else {
  147. reject(new Error(res.data.error));
  148. }
  149. })
  150. .catch(res => {
  151. reject(res);
  152. });
  153. });
  154. }
  155. static escape (html, encode) {
  156. return html
  157. .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
  158. .replace(/</g, '&lt;')
  159. .replace(/>/g, '&gt;')
  160. .replace(/"/g, '&quot;')
  161. .replace(/'/g, '&#39;');
  162. }
  163. static unescape(html) {
  164. return html.replace(/&([#\w]+);/g, function(_, n) {
  165. n = n.toLowerCase();
  166. if (n === 'colon') return ':';
  167. if (n.charAt(0) === '#') {
  168. return n.charAt(1) === 'x'
  169. ? String.fromCharCode(parseInt(n.substring(2), 16))
  170. : String.fromCharCode(+n.substring(1));
  171. }
  172. return '';
  173. });
  174. }
  175. }