base.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import { API_PREFIX, PUBLIC_API_PREFIX, IS_CE_EDITION } from '@/config'
  2. import Toast from '@/app/components/base/toast'
  3. const TIME_OUT = 100000
  4. const ContentType = {
  5. json: 'application/json',
  6. stream: 'text/event-stream',
  7. form: 'application/x-www-form-urlencoded; charset=UTF-8',
  8. download: 'application/octet-stream', // for download
  9. upload: 'multipart/form-data', // for upload
  10. }
  11. const baseOptions = {
  12. method: 'GET',
  13. mode: 'cors',
  14. credentials: 'include', // always send cookies、HTTP Basic authentication.
  15. headers: new Headers({
  16. 'Content-Type': ContentType.json,
  17. }),
  18. redirect: 'follow',
  19. }
  20. export type IOnDataMoreInfo = {
  21. conversationId: string | undefined
  22. messageId: string
  23. errorMessage?: string
  24. }
  25. export type IOnData = (message: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => void
  26. export type IOnCompleted = (hasError?: boolean) => void
  27. export type IOnError = (msg: string) => void
  28. type IOtherOptions = {
  29. isPublicAPI?: boolean
  30. needAllResponseContent?: boolean
  31. onData?: IOnData // for stream
  32. onError?: IOnError
  33. onCompleted?: IOnCompleted // for stream
  34. getAbortController?: (abortController: AbortController) => void
  35. }
  36. function unicodeToChar(text: string) {
  37. return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
  38. return String.fromCharCode(parseInt(p1, 16))
  39. })
  40. }
  41. export function format(text: string) {
  42. let res = text.trim()
  43. if (res.startsWith('\n')) {
  44. res = res.replace('\n', '')
  45. }
  46. return res.replaceAll('\n', '<br/>').replaceAll('```', '')
  47. }
  48. const handleStream = (response: any, onData: IOnData, onCompleted?: IOnCompleted) => {
  49. if (!response.ok)
  50. throw new Error('Network response was not ok')
  51. const reader = response.body.getReader()
  52. const decoder = new TextDecoder('utf-8')
  53. let buffer = ''
  54. let bufferObj: any
  55. let isFirstMessage = true
  56. function read() {
  57. let hasError = false
  58. reader.read().then((result: any) => {
  59. if (result.done) {
  60. onCompleted && onCompleted()
  61. return
  62. }
  63. buffer += decoder.decode(result.value, { stream: true })
  64. const lines = buffer.split('\n')
  65. try {
  66. lines.forEach((message) => {
  67. if (message.startsWith('data: ')) { // check if it starts with data:
  68. // console.log(message);
  69. bufferObj = JSON.parse(message.substring(6)) // remove data: and parse as json
  70. if (bufferObj.status === 400 || !bufferObj.event) {
  71. onData('', false, {
  72. conversationId: undefined,
  73. messageId: '',
  74. errorMessage: bufferObj.message
  75. })
  76. hasError = true
  77. onCompleted && onCompleted(true)
  78. return
  79. }
  80. // can not use format here. Because message is splited.
  81. onData(unicodeToChar(bufferObj.answer), isFirstMessage, {
  82. conversationId: bufferObj.conversation_id,
  83. messageId: bufferObj.id,
  84. })
  85. isFirstMessage = false
  86. }
  87. })
  88. buffer = lines[lines.length - 1]
  89. } catch (e) {
  90. onData('', false, {
  91. conversationId: undefined,
  92. messageId: '',
  93. errorMessage: e + ''
  94. })
  95. hasError = true
  96. onCompleted && onCompleted(true)
  97. return
  98. }
  99. if (!hasError) {
  100. read()
  101. }
  102. })
  103. }
  104. read()
  105. }
  106. const baseFetch = (
  107. url: string,
  108. fetchOptions: any,
  109. {
  110. isPublicAPI = false,
  111. needAllResponseContent
  112. }: IOtherOptions
  113. ) => {
  114. const options = Object.assign({}, baseOptions, fetchOptions)
  115. if (isPublicAPI) {
  116. const sharedToken = globalThis.location.pathname.split('/').slice(-1)[0]
  117. options.headers.set('Authorization', `bearer ${sharedToken}`)
  118. }
  119. let urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  120. let urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
  121. const { method, params, body } = options
  122. // handle query
  123. if (method === 'GET' && params) {
  124. const paramsArray: string[] = []
  125. Object.keys(params).forEach(key =>
  126. paramsArray.push(`${key}=${encodeURIComponent(params[key])}`),
  127. )
  128. if (urlWithPrefix.search(/\?/) === -1)
  129. urlWithPrefix += `?${paramsArray.join('&')}`
  130. else
  131. urlWithPrefix += `&${paramsArray.join('&')}`
  132. delete options.params
  133. }
  134. if (body)
  135. options.body = JSON.stringify(body)
  136. // Handle timeout
  137. return Promise.race([
  138. new Promise((resolve, reject) => {
  139. setTimeout(() => {
  140. reject(new Error('request timeout'))
  141. }, TIME_OUT)
  142. }),
  143. new Promise((resolve, reject) => {
  144. globalThis.fetch(urlWithPrefix, options)
  145. .then((res: any) => {
  146. const resClone = res.clone()
  147. // Error handler
  148. if (!/^(2|3)\d{2}$/.test(res.status)) {
  149. const bodyJson = res.json()
  150. switch (res.status) {
  151. case 401: {
  152. if (isPublicAPI) {
  153. Toast.notify({ type: 'error', message: 'Invalid token' })
  154. return
  155. }
  156. const loginUrl = `${globalThis.location.origin}/signin`
  157. if (IS_CE_EDITION) {
  158. bodyJson.then((data: any) => {
  159. if (data.code === 'not_setup') {
  160. globalThis.location.href = `${globalThis.location.origin}/install`
  161. } else {
  162. if (location.pathname === '/signin') {
  163. bodyJson.then((data: any) => {
  164. Toast.notify({ type: 'error', message: data.message })
  165. })
  166. } else {
  167. globalThis.location.href = loginUrl
  168. }
  169. }
  170. })
  171. return Promise.reject()
  172. }
  173. globalThis.location.href = loginUrl
  174. break
  175. }
  176. case 403:
  177. new Promise(() => {
  178. bodyJson.then((data: any) => {
  179. Toast.notify({ type: 'error', message: data.message })
  180. if (data.code === 'already_setup') {
  181. globalThis.location.href = `${globalThis.location.origin}/signin`
  182. }
  183. })
  184. })
  185. break
  186. // fall through
  187. default:
  188. // eslint-disable-next-line no-new
  189. new Promise(() => {
  190. bodyJson.then((data: any) => {
  191. Toast.notify({ type: 'error', message: data.message })
  192. })
  193. })
  194. }
  195. return Promise.reject(resClone)
  196. }
  197. // handle delete api. Delete api not return content.
  198. if (res.status === 204) {
  199. resolve({ result: "success" })
  200. return
  201. }
  202. // return data
  203. const data = options.headers.get('Content-type') === ContentType.download ? res.blob() : res.json()
  204. resolve(needAllResponseContent ? resClone : data)
  205. })
  206. .catch((err) => {
  207. Toast.notify({ type: 'error', message: err })
  208. reject(err)
  209. })
  210. }),
  211. ])
  212. }
  213. export const upload = (options: any): Promise<any> => {
  214. const defaultOptions = {
  215. method: 'POST',
  216. url: `${API_PREFIX}/files/upload`,
  217. headers: {},
  218. data: {},
  219. }
  220. options = {
  221. ...defaultOptions,
  222. ...options,
  223. headers: { ...defaultOptions.headers, ...options.headers },
  224. };
  225. return new Promise(function (resolve, reject) {
  226. const xhr = options.xhr
  227. xhr.open(options.method, options.url);
  228. for (const key in options.headers) {
  229. xhr.setRequestHeader(key, options.headers[key]);
  230. }
  231. xhr.withCredentials = true
  232. xhr.responseType = 'json'
  233. xhr.onreadystatechange = function () {
  234. if (xhr.readyState === 4) {
  235. if (xhr.status === 201) {
  236. resolve(xhr.response)
  237. } else {
  238. reject(xhr)
  239. }
  240. }
  241. }
  242. xhr.upload.onprogress = options.onprogress
  243. xhr.send(options.data)
  244. })
  245. }
  246. export const ssePost = (url: string, fetchOptions: any, { isPublicAPI = false, onData, onCompleted, onError, getAbortController }: IOtherOptions) => {
  247. const abortController = new AbortController()
  248. const options = Object.assign({}, baseOptions, {
  249. method: 'POST',
  250. signal: abortController.signal,
  251. }, fetchOptions)
  252. getAbortController?.(abortController)
  253. const urlPrefix = isPublicAPI ? PUBLIC_API_PREFIX : API_PREFIX
  254. const urlWithPrefix = `${urlPrefix}${url.startsWith('/') ? url : `/${url}`}`
  255. const { body } = options
  256. if (body)
  257. options.body = JSON.stringify(body)
  258. globalThis.fetch(urlWithPrefix, options)
  259. .then((res: any) => {
  260. // debugger
  261. if (!/^(2|3)\d{2}$/.test(res.status)) {
  262. // eslint-disable-next-line no-new
  263. new Promise(() => {
  264. res.json().then((data: any) => {
  265. Toast.notify({ type: 'error', message: data.message || 'Server Error' })
  266. })
  267. })
  268. onError?.('Server Error')
  269. return
  270. }
  271. return handleStream(res, (str: string, isFirstMessage: boolean, moreInfo: IOnDataMoreInfo) => {
  272. if (moreInfo.errorMessage) {
  273. Toast.notify({ type: 'error', message: moreInfo.errorMessage })
  274. return
  275. }
  276. onData?.(str, isFirstMessage, moreInfo)
  277. }, onCompleted)
  278. }).catch((e) => {
  279. // debugger
  280. Toast.notify({ type: 'error', message: e })
  281. onError?.(e)
  282. })
  283. }
  284. export const request = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  285. return baseFetch(url, options, otherOptions || {})
  286. }
  287. export const get = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  288. return request(url, Object.assign({}, options, { method: 'GET' }), otherOptions)
  289. }
  290. // For public API
  291. export const getPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  292. return get(url, options, { ...otherOptions, isPublicAPI: true })
  293. }
  294. export const post = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  295. return request(url, Object.assign({}, options, { method: 'POST' }), otherOptions)
  296. }
  297. export const postPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  298. return post(url, options, { ...otherOptions, isPublicAPI: true })
  299. }
  300. export const put = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  301. return request(url, Object.assign({}, options, { method: 'PUT' }), otherOptions)
  302. }
  303. export const putPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  304. return put(url, options, { ...otherOptions, isPublicAPI: true })
  305. }
  306. export const del = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  307. return request(url, Object.assign({}, options, { method: 'DELETE' }), otherOptions)
  308. }
  309. export const delPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  310. return del(url, options, { ...otherOptions, isPublicAPI: true })
  311. }
  312. export const patch = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  313. return request(url, Object.assign({}, options, { method: 'PATCH' }), otherOptions)
  314. }
  315. export const patchPublic = (url: string, options = {}, otherOptions?: IOtherOptions) => {
  316. return patch(url, options, { ...otherOptions, isPublicAPI: true })
  317. }