Crowi.js 4.6 KB

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