base.ts 12 KB

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