All files / client/util Crowi.ts

0% Statements 0/96
0% Branches 0/46
0% Functions 0/27
0% Lines 0/95

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * Crowi context class for client
 */
 
import axios from 'axios'
import io from 'socket.io-client'
import { User } from 'client/types/crowi'
 
interface Me {
  id?: string
  name?: string
}
 
interface Context {
  user: Me
  csrfToken: string
}
 
export default class Crowi {
  public context: Context
 
  public config: {
    crowi?: {}
    upload?: {
      image: boolean
      file: boolean
    }
    env?: {
      PLANTUML_URI: string | null
      MATHJAX: string | null
    }
  }
 
  public csrfToken: string
 
  public window: Window
 
  public location: Location
 
  public document: Document
 
  public localStorage: Storage
 
  public user?: Me
 
  public users: User[]
 
  public userByName: { [name: string]: User }
 
  public userById: { [id: string]: User }
 
  public draft: { [path: string]: string }
 
  public socket: any
 
  constructor(context: Context, window: Window) {
    this.context = context
    this.config = {}
    this.csrfToken = context.csrfToken
    this.setUser(context.user)
 
    this.window = window
    this.location = window.location || {}
    this.document = window.document || {}
    this.localStorage = window.localStorage || {}
 
    this.fetchUsers = this.fetchUsers.bind(this)
    this.apiGet = this.apiGet.bind(this)
    this.apiPost = this.apiPost.bind(this)
    this.apiRequest = this.apiRequest.bind(this)
 
    this.users = []
    this.userByName = {}
    this.userById = {}
    this.draft = {}
 
    this.recoverData()
 
    this.socket = io({
      transports: ['websocket'],
    })
  }
 
  getContext() {
    return this.context
  }
 
  setConfig(config: {}) {
    this.config = config
  }
 
  getConfig() {
    return this.config
  }
 
  setUser(user?: Me) {
    const { id = '', name = '' } = user || {}
    this.user = { id, name }
  }
 
  getUser() {
    return this.user
  }
 
  getWebSocket() {
    return this.socket
  }
 
  recoverData() {
    type keys = ['userByName', 'userById', 'users', 'draft']
    const keys: keys = ['userByName', 'userById', 'users', 'draft']
 
    keys.forEach(key => {
      const keyContent = this.localStorage[key]
      if (keyContent) {
        try {
          this[key] = JSON.parse(keyContent)
        } catch (e) {
          this.localStorage.removeItem(key)
        }
      }
    })
  }
 
  fetchUsers() {
    const interval = 1000 * 60 * 15 // 15min
    const currentTime = new Date().getTime()
    const lastFetched = new Date(this.localStorage.lastFetched || 0).getTime()
    if (interval > currentTime - lastFetched) {
      return
    }
 
    this.apiGet('/users.list', {})
      .then(data => {
        this.users = data.users
        this.localStorage.users = JSON.stringify(data.users)
 
        const userByName: { [name: string]: User } = {}
        const userById: { [id: string]: User } = {}
        data.users.forEach((user: User) => {
          const { username, _id } = user
          userByName[username] = user
          userById[_id] = user
        })
        this.userByName = userByName
        this.localStorage.userByName = JSON.stringify(userByName)
 
        this.userById = userById
        this.localStorage.userById = JSON.stringify(userById)
 
        this.localStorage.lastFetched = new Date()
      })
      .catch(err => {
        this.localStorage.removeItem('lastFetched')
        // ignore errors
      })
  }
 
  clearDraft(path: string) {
    delete this.draft[path]
    this.localStorage.draft = JSON.stringify(this.draft)
  }
 
  saveDraft(path: string, body: string) {
    this.draft[path] = body
    this.localStorage.draft = JSON.stringify(this.draft)
  }
 
  findDraft(path: string) {
    if (this.draft && this.draft[path]) {
      return this.draft[path]
    }
 
    return null
  }
 
  findUserById(userId: string) {
    if (this.userById && this.userById[userId]) {
      return this.userById[userId]
    }
 
    return null
  }
 
  findUserByIds(userIds: string[]) {
    const users: User[] = []
    for (const userId of userIds) {
      const user = this.findUserById(userId)
      if (user) {
        users.push(user)
      }
    }
 
    return users
  }
 
  findUser(username: string) {
    if (this.userByName && this.userByName[username]) {
      return this.userByName[username]
    }
 
    return null
  }
 
  async apiGet(path: string, params = {}) {
    return this.apiRequest('get', path, { params })
  }
 
  async apiPost(path: string, data: { _csrf?: string; [key: string]: any } = {}) {
    if (!data._csrf) {
      data._csrf = this.csrfToken
    }
 
    return this.apiRequest('post', path, { data })
  }
 
  async apiRequest(method: 'get' | 'post', path: string, payload: { params?: any; data?: any }) {
    const createError = (message: string, info = {}) => {
      const error = new Error(message)
      error.info = info
      return error
    }
    const url = `/_api${path}`
    const { data } = await axios({ method, url, ...payload }).catch(function() {
      throw createError('Error')
    })
    const { ok, error, info } = data
    if (ok) {
      return data
    }
    throw createError(error, info)
  }
 
  static escape = (html: string, encode = false) =>
    html
      .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')
 
  static unescape = (html: string) =>
    html.replace(/&([#\w]+);/g, (_, n) => {
      n = n.toLowerCase()
      if (n === 'colon') return ':'
      if (n.charAt(0) === '#') {
        return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1))
      }
      return ''
    })
}