uploader.js 21.1 KB
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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
import { getOssToken } from '@/utils/ossUploadFile/uploadFile.js'
import Queue from '@/utils/Queue.js'
import { Command } from '../ws/constants'
import { isInteger, serializeIfObject } from '@/utils/utils.js'
import dayjs from 'dayjs'
export default {
  onLoad() {},
  data() {
    return {
      wv: null,
      snapshot: null,
      interval: 60 * 5,
      timer: null,
      _isUploading: false
    }
  },
  mounted() {
    this.init()
    this.subscribe()
  },
  methods: {
    /**
     * 初始化函数
     * 这个函数在对象创建时被调用,它执行一系列的初始化任务
     *
     * @async
     * @returns {Promise<void>} 当初始化完成时,Promise 将解析为 undefined
     * @throws {Error} 如果初始化过程中出现错误,将抛出错误
     */
    async init() {
      this.wv = await this.initWebview()
      this.startPolling()
      // uni.$logger.local.error({ extra : { key: 'data', value: {'abc':123,'sss':456,'GDF':888}  }, msg:'test', tag : { key: 'tag', value: 'tagtest' } })
      // uni.$logger.local.getFiles('20240905','2024-09/05')
      // uni.$logger.local.removeOverDays(1)
    },
    subscribe() {
      uni.$on(Command.StopPolling, this.stopPolling)
      uni.$on(Command.StartPolling, this.startPolling)
      uni.$on(Command.SetPollingInterval, this.setInterval)
    },
    /**
     * 处理消息函数
     * 此函数用于处理接收到的消息
     * 它解构参数对象,获取代码、文件名、数据、记录 ID、文件路径和客户端文件路径等信息
     * 根据代码值决定下一步操作:若为 0,则上传成功,调用 uploadSuccess 函数;否则,开始轮询,调用 polling 函数
     *
     * @param {Object} result - 包含消息详情的对象
     * @throws {Error} 如果解构对象时缺少关键属性,将抛出错误
     */
    async handlerMessage(result) {
      const { code, fileName, data, recordId, filePath, filePathOnClient = filePath + fileName } = result.detail.data[0]
      try {
        if (code == 0) {
          const filePathOnServer = data.oss.res.requestUrls[0].split('?')[0]
          await this.uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName)
        } else {
          this.reportError(recordId, fileName, data)
        }
      } catch (e) {
        this.reportError(recordId, fileName, e)
      } finally {
        uni.$logger.local.info('本次任务完成,开启下一次上传任务!')
        this.polling()
      }
    },
    /**
     * 上报文件上传失败日志
     */
    async reportError(recordId, filePath, res, message = '上传文件失败!!') {
      try {
        const record = uni.$recordManager.getRecordById(recordId) || {}
        const userInfo = uni.$storage.get('userInfo')
        const { customerName, phoneNumber, carModel, salesName } = record || {}
        const { name } = userInfo || {}
        const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
        uni.$logger.error({
          msg: `${now}-${message},员工: ${name}, 客户: ${customerName}`,
          extra: {
            '手机号: ': phoneNumber,
            '姓名: ': customerName,
            '销售: ': salesName,
            '车型: ': carModel,
            '原因: ': serializeIfObject(res),
            '文件路径: ': filePath
          }
        })
      } catch (error) {
        uni.$logger.error(`报告错误时发生异常: ${error.message}`)
      }
    },
    /**
     * 初始化 WebView 的异步函数
     * 这个函数返回一个 Promise,当初始化 WebView 完成时,它将解析为 WebView 对象。
     * 在页面初始化调用时,这个函数会延迟 1 秒,以确保 WebView 对象已经创建。
     *
     * @async
     * @returns {Promise<any>} 当初始化完成时,Promise 将解析为 WebView 对象。
     */
    initWebview() {
      return new Promise((resolve, reject) => {
        var currentWebview = this.$parent.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
        let i = setInterval(() => {
          var wv = currentWebview.children()[0]
          if (wv) {
            clearInterval(i)
            wv.setStyle({ top: '100%', height: 300 })
            resolve(wv)
          }
        }, 100)
        // setTimeout(function () {
        //   var wv = currentWebview.children()[0]
        //   wv.setStyle({ top: '100%', height: 300 })
        //   resolve(wv)
        // }, 1000) //如果是页面初始化调用时,需要延时一下
      })
    },
    /**
     * 入列操作
     * 这个函数异步执行,目的是获取记录的快照并将其扁平化,以形成一个队列
     * 通过调用 getRecordsSnapshotFlatten 获取快照数据
     * 当所有数据准备好后,创建一个新的 Queue 实例,并将扁平化后的数据作为参数传入
     * 这样,队列就被创建并且最初是满的,其中包含了已经获取到的记录快照
     *
     * @async
     * @returns {Promise<void>} 一个 Promise,当初始化队列完成时解析,没有返回值
     * @throws {Error} 如果获取快照失败或扁平化数据失败,将抛出错误
     */
    async enQueue() {
      // uni.$logger.remote.error({ extra : { key: 'data', value: {test:'test'} }, msg:'test', tag : { key: 'test', value: 'test' } })
      // uni.$logger.local.info('开始创建上传文件快照.')
      const _snapshot = await this.getRecordsSnapshotFlatten()
      this.snapshot = new Queue(_snapshot)
      uni.$logger.local.info('创建快照成功! 文件个数:' + this.snapshot.size)
      // console.log('创建任务快照.下一轮快照文件个数:', this.snapshot.size)
    },
    /**
     * 获取记录快照并展平数据
     * 此函数异步获取记录快照,然后使用flattenData函数将这些记录转换为一个文件对象列表
     * 每个文件对象都包含一个额外的recordId属性,用于指示它所属的记录
     *
     * @async
     * @returns {Promise<Array>} 一个Promise,当获取并处理完记录时,返回一个文件对象列表
     * @throws {Error} 如果在获取记录快照或展平数据的过程中出现错误,将抛出错误
     */
    async getRecordsSnapshotFlatten() {
      const _records = await this.getRecordsSnapshot()
      const _snapshot = this.flattenData(_records || [])
      return _snapshot
    },
    /**
     * 将指定记录上传到服务器
     * 此函数使用 WebView 的 evalJS 方法,将 OSS 令牌信息和记录详情传递给 UniApp 应用,以便进行文件上传
     *
     * @async
     * @param {Object} record - 要上传的记录对象,包含 fileName 和 filePath 属性
     * @returns {void} - 此函数不返回任何值
     * @throws {Error} - 如果获取 OSS 令牌的过程中出现错误,将抛出错误
     */
    async uploadRecord(record) {
      if (record.filePath) {
        const { lsaccessKeySecret, securityToken, lsaccessKeyId } = await getOssToken()
        console.log('获取Token成功!!', `lsaccessKeySecret: ${lsaccessKeySecret},   lsaccessKeyId:  ${lsaccessKeyId}`)
        this.wv.evalJS(`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${record.fileName}','${record.filePath}','${record.recordId}')`)
      } else {
        this._saveOrUpdateFail(record.recordId)
      }
    },
    /**
     * 文件上传成功后的处理逻辑
     * 这个函数在文件上传成功后执行,它接受四个参数:recordId、filePathOnServer、filePathOnClient 和 fileName
     * 函数首先获取记录锁,然后尝试获取对应的记录。如果记录存在,它将客户端路径的文件记录更新为服务器路径,并移除 client 文件。
     * 接着,它调用一个名为 _saveOrUpdate 的私有方法,这个方法可能会上传记录。
     * 无论是尝试获取记录失败,还是在处理过程中出现任何其他错误,都会被捕获并作为 error 参数传递给 Promise.reject 方法,表明发生错误。
     * 无论成功或失败,最终都会执行 finally 块中的代码。这里首先释放记录锁,然后调用 polling 方法,可能是为了继续下一次文件上传。
     *
     * @async
     * @param {string} recordId - 要更新的记录的 ID
     * @param {string} filePathOnServer - 文件在服务器上的新路径
     * @param {string} filePathOnClient - 文件在客户端的旧路径
     * @param {string} fileName - 文件的原始名称
     * @throws {Error} 如果获取记录失败或发生任何其他错误,将抛出错误
     */
    async uploadSuccess(recordId, filePathOnServer, filePathOnClient, fileName) {
      const unlock = await uni.$recordManager.lock()
      try {
        uni.$logger.local.info(`文件上传完成回调(uploadSuccess)!!', filePathOnServer-> ${filePathOnServer},   filePathOnClient->  ${filePathOnClient} , fileName-> ${fileName}`)
        const record = uni.$recordManager.getRecordById(recordId)
        if (!record) return uni.$logger.local.info(`未找到接待记录!!`)
        this._changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName)
        await this._saveOrUpdate(record)
      } catch (err) {
        throw new Error(err)
      } finally {
        unlock()
      }
    },
    /**
     * 将记录中的文件路径更改为服务器路径
     * 此函数遍历记录中的每个文件信息对象
     * 将文件信息对象中的 file 属性值与 filePathOnClient 或 fileName 进行比较
     * 如果匹配,则将 file 属性更新为 filePathOnServer,并删除 status 属性
     *
     * @param {Object} record - 包含文件信息列表的记录对象
     * @param {string} filePathOnClient - 需要替换的客户端文件路径
     * @param {string} filePathOnServer - 需要更新的服务器文件路径
     * @param {string} fileName - 需要替换的文件名
     * @throws {Error} 如果 record 参数无效或 recordFileList 属性不存在,将抛出错误
     */
    _changeFilePathToServer(record, filePathOnClient, filePathOnServer, fileName) {
      uni.$logger.local.info(`开始将接待记录的文件路径改成服务器路径!! record.recordUrlList-> ${JSON.stringify(record.recordUrlList)}`)
      record.recordUrlList?.forEach(fileInfo => {
        if (fileInfo.file === filePathOnClient || fileInfo.file.endsWith(fileName)) {
          fileInfo.file = filePathOnServer
          fileInfo.filePathOnClient = filePathOnClient
          delete fileInfo.status
          uni.$logger.local.info(`修改文件路径完成并删除文件status属性!! fileInfo.file-> ${fileInfo.file} fileInfo.status-> ${fileInfo.status}`)
        }
      })
      uni.$logger.local.info(`替换完成!! record.recordUrlList-> ${JSON.stringify(record.recordUrlList)}`)
    },
    /**
     * 从客户端移除文件
     * 此函数使用 uni.removeSavedFile 方法删除指定路径的文件。该方法是一个异步操作,完成时会调用传入的 complete 回调函数。
     *
     * @param {string} filePathOnClient - 要删除的文件在客户端的文件路径
     * @param {Object} complete - (可选) uni.removeSavedFile 完成时调用的回调函数。函数参数是一个包含 statusCode 和 errMsg 的对象。
     * @throws {Error} 如果 filePathOnClient 参数无效或文件删除过程中发生错误,将抛出错误
     */
    _removeFileOnClient(filePathOnClient) {
      uni.$logger.local.info(`开始删除客户端的文件!! 路径-> ${filePathOnClient}`)
      return new Promise((resolve, reject) => {
        uni.removeSavedFile({
          filePath: filePathOnClient,
          complete: function (res) {
            uni.$logger.local.info(`${filePathOnClient}->删除成功!!`)
            resolve(res)
          }
        })
      })
    },
    /**
     * 保存或更新记录
     * 这个函数检查记录中的文件列表,以确定是保存还是更新记录
     * 如果所有文件记录条目状态都为未定义,函数将创建一个新的记录对象,调用保存 API,并在成功时移除记录
     * 如果文件记录条目状态不全为未定义,函数将更新记录
     *
     * @async
     * @param {Object} record - 要保存或更新的记录对象
     * @throws {Error} 如果在保存或更新记录时发生错误,将抛出错误
     */
    async _saveOrUpdate(record) {
      uni.$logger.local.info(`开始保存或更新接待记录!! record-> ${JSON.stringify(record)}`)
      if (record.recordUrlList?.every(i => i.status == undefined)) {
        const pathArr = record.recordUrlList.map(i => i.file)
        const originalFileArr = record.recordUrlList.map(i => i.filePathOnClient)
        const params = { ...record, recordUrlList: pathArr }
        uni.$logger.local.info(`记录中的文件已全部上传,开始向服务器保存接待记录!!`)
        if (!params.receptionEndTime) {
          const endTime = await uni.$api.commonApi.searchRecordingEndTime({ recordUrlList: pathArr, receptionStartTime: params.receptionStartTime.replace(/\//g, '-') })
          params.receptionEndTime = endTime.replace(/\-/g, '/')
        }
        console.log(params, 'params')
        const res = await uni.$api.commonApi.saveRecCustomer(params)
        uni.$logger.local.info(`服务器返回结果: ${res}`)
        if (res) {
          uni.$logger.local.info(`保存接待记录成功,开始删除本地接待记录!!`)
          uni.$recordManager.removeRecord(record.id)
          while (originalFileArr.length > 0) {
            const file = originalFileArr.shift()
            await this._removeFileOnClient(file)
          }
          // await this._removeFileOnClient(filePathOnClient)
        }
      } else {
        uni.$logger.local.info(`记录中有未上传文件,开始更新记录!!`)
        uni.$recordManager.updateRecord(record)
        // await this._removeFileOnClient(filePathOnClient)
      }
    },
    async _saveOrUpdateFail(recordId) {
      const unlock = await uni.$recordManager.lock()
      try {
        const record = uni.$recordManager.getRecordById(recordId)
        const params = { ...record, recordUrlList: [] }
        if (!params.receptionEndTime) {
          params.receptionEndTime = params.receptionStartTime
        }
        const res = await uni.$api.commonApi.saveRecCustomer(params)
        if (res) {
          uni.$recordManager.removeRecord(record.id)
        }
      } catch (e) {
        this.reportError(recordId, '无文件', e)
      } finally {
        unlock()
        this.polling()
      }
    },
    /**
     * 获取记录快照的异步函数
     * 此函数获取当前记录列表的快照,并返回这些记录
     *
     * @async
     * @returns {Promise<Array>} 解析为包含记录列表的 Promise
     */
    async getRecordsSnapshot() {
      const unlock = await uni.$recordManager.lock()
      const records = uni.$recordManager.getRecords()
      unlock()
      return records
    },
    /**
     * 展开数据
     * 将嵌套的记录列表转换为平面的文件对象列表,其中每个文件对象都包含一个 recordId 属性
     *
     * @param {Array} records - 要展开的记录列表
     * @returns {Array} - 展开后包含文件对象的列表,每个文件对象都包含一个 recordId 属性
     */
    async flattenData(records) {
      const result = []
      for (const cur of records) {
        cur.recordUrlList = cur.recordUrlList || []
        // 如果记录没有文件,添加一个空记录
        if (cur.recordUrlList.length == 0) {
          result.push({ recordId: cur.id })
          this.reportError(cur.id, '', cur, '记录中不存在接待语音文件') //记录中不存在接待语音文件
          continue
        }
        // 处理每个记录的文件列表
        for (const file of cur.recordUrlList) {
          if (!file.status) continue
          const aFullPath = file.file.split('/')
          const fileName = aFullPath.pop()
          const filePath = aFullPath.join('/') + '/'
          // 检查文件是否存在
          const fileExists = await this.checkFileExists(file.file)
          if (!fileExists) {
            this.reportError(cur.id, fileName, cur, '记录中有语音文件地址,但是文件不存在') //记录中语音文件不存在
            continue
          }
          result.push({ ...file, recordId: cur.id, fileName, filePath })
        }
      }
      return result
    },
    /**
     * 检查文件是否存在
     * 此函数检查指定路径的文件是否存在
     *
     * @param {string} filePath - 要检查的文件路径
     * @returns {Promise<boolean>} - 返回一个 Promise,当文件存在时解析为 true,否则解析为 false
     */
    async checkFileExists(filePath) {
      return new Promise(resolve => {
        if (!filePath) {
          resolve(false)
          return
        }
        uni.getFileInfo({
          filePath: filePath,
          success: function (info) {
            resolve(true)
          },
          fail: function (error) {
            resolve(false)
          }
        })
      })
    },
    /**
     * 轮询函数
     * 这个函数用于检查一个队列的大小,并在需要时执行文件上传操作
     * 如果队列大小为 0,则调用 enQueue() 函数来获取新的文件进行上传,并延迟一段时间后再次轮询
     * 如果队列不为 0,则从队列中取出一个记录并调用 uploadRecord(record) 函数进行上传
     * 如果在获取网络状态或上传过程中出现错误,它将捕获错误并在指定的时间间隔后重新开始轮询
     *
     * @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling
     */
    polling() {
      // uni.$logger.local.info(`当前待上传文件快照数量-> ${this.snapshot.size}`)
      // console.log(this.snapshot.size, '当前待上传文件快照数量')
      if (this.snapshot === null) return
      // prettier-ignore
      uni.$isNetWork().then(this.upload).catch(e => {
        this.reportError('', '异常', e)
        this.pollingLater(this.interval)
      })
    },
    /**
     * 上传文件或执行队列操作
     * 检查队列大小,以确定是上传单个文件还是通过 enQueue() 函数获取新的文件进行上传
     *
     * @throws {Error} 如果在上传过程中发生错误,将抛出错误,延迟 interval 后继续 polling
     */
    async upload() {
      if (this._isUploading) return
      try {
        this._isUploading = true
        if (this.snapshot.size == 0) {
          await this.enQueue()
          this.pollingLater(this.interval)
        } else {
          let record = this.snapshot.dequeue()
          await this.uploadRecord(record)
        }
      } finally {
        this._isUploading = false
      }
    },
    /**
     * 停止轮询并清除队列
     * 这个函数用于停止轮询操作,并清除队列中的所有记录
     * 首先,它调用 snapshot.clear() 方法清除队列
     * 然后,它将 snapshot 对象设置为 null,以释放资源并停止轮询
     */
    stopPolling() {
      if (this.snapshot) {
        this.snapshot.clear()
        this.snapshot = null
      }
      this.clearTimer()
      uni.$logger.local.info(`停止文件上传轮询并清除队列`)
    },
    setInterval(interval, isForce = false) {
      if (!isInteger(interval)) {
        const error = `参数错误!interval 必需为数字!  interval -> ${interval} `
        uni.$logger.local.error(error)
        return
      }
      this.interval = interval
      if (isForce) {
        this.startPolling(isForce)
      }
      uni.$logger.local.info(`轮询间隔已设置为 ${interval} 秒`)
    },
    async startPolling(isForce = false) {
      if (this.timer) {
        if (!isForce) {
          uni.$logger.local.info(`非强制模式下,timer正在运行,不强制重启轮询`)
          return
        } else {
          uni.$logger.local.info(`强制模式下,timer正在运行,强制重启轮询`)
          this.clearTimer()
        }
      }
      await this.enQueue()
      this.polling()
      uni.$logger.local.info(`=========开始轮询========`)
    },
    clearTimer() {
      if (this.timer) {
        clearTimeout(this.timer)
        this.timer = null
      }
    },
    /**
     * 在指定的时间间隔后启动轮询
     * 这个函数用于在指定的时间间隔后执行轮询操作
     * @param {number} [interval=60*10] - 轮询间隔(默认为10分钟)
     * @returns {void} - 此函数不返回任何值
     */
    pollingLater(interval = 60 * 10) {
      this.clearTimer()
      this.timer = setTimeout(() => {
        this.polling()
      }, interval * 1000)
      console.log(interval + 's后开始下一轮上传!')
    }
  },
  /**
   * 在组件销毁之前执行的生命周期函数
   * 这个函数在组件被销毁之前被调用,可以在这里进行一些清理工作
   * 在这个例子中,使用 console.log 输出 'topPolling',并调用 this.stopPolling() 方法
   *
   * @private
   * @returns {void} 没有返回值
   * @throws {Error} 调用 this.stopPolling() 时可能出现的错误
   */
  beforeDestroy() {
    this.stopPolling()
    uni.$off(Command.StopPolling, this.stopPolling)
    uni.$off(Command.StartPolling, this.startPolling)
    uni.$off(Command.SetPollingInterval, this.setInterval)
    uni.$logger.local.info(`组件销毁前执行的生命周期函数`)
  }
}