protocols.js 11.7 KB
Newer Older
1
import {
2 3
  isPlainObject,
  hasOwn
4
} from 'uni-shared'
fxy060608's avatar
fxy060608 已提交
5
import navigateTo from 'uni-helpers/navigate-to'
6
import redirectTo from '../../../mp-weixin/helpers/redirect-to'
7
import getSystemInfo from '../../helpers/system-info'
8

X
xiaoyucoding 已提交
9
// 不支持的 API 列表
fxy060608's avatar
fxy060608 已提交
10 11 12
const todos = [
  'preloadPage',
  'unPreloadPage',
fxy060608's avatar
fxy060608 已提交
13
  'loadSubPackage'
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
  // 'getRecorderManager',
  // 'getBackgroundAudioManager',
  // 'createInnerAudioContext',
  // 'createCameraContext',
  // 'createLivePlayerContext',
  // 'startAccelerometer',
  // 'startCompass',
  // 'authorize',
  // 'chooseInvoiceTitle',
  // 'addTemplate',
  // 'deleteTemplate',
  // 'getTemplateLibraryById',
  // 'getTemplateLibraryList',
  // 'getTemplateList',
  // 'sendTemplateMessage',
  // 'setEnableDebug',
  // 'getExtConfig',
  // 'getExtConfigSync',
  // 'onWindowResize',
  // 'offWindowResize'
fxy060608's avatar
fxy060608 已提交
34 35
]

36 37
// 存在兼容性的 API 列表
const canIUses = [
38 39 40 41 42 43 44 45
  'startPullDownRefresh',
  'setTabBarItem',
  'setTabBarStyle',
  'hideTabBar',
  'showTabBar',
  'setTabBarBadge',
  'removeTabBarBadge',
  'showTabBarRedDot',
W
wangyaqi 已提交
46 47 48 49
  'hideTabBarRedDot',
  'openSetting',
  'getSetting',
  'createIntersectionObserver',
W
wangyaqi 已提交
50 51
  'getUpdateManager',
  'setBackgroundColor',
雪洛's avatar
雪洛 已提交
52 53 54 55
  'setBackgroundTextStyle',
  'checkIsSupportSoterAuthentication',
  'startSoterAuthentication',
  'checkIsSoterEnrolledInDevice',
56 57 58 59
  'openDocument',
  'createVideoContext',
  'onMemoryWarning',
  'addPhoneContact'
60 61
]

X
xiaoyucoding 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74
function _handleNetworkInfo (result) {
  switch (result.networkType) {
    case 'NOTREACHABLE':
      result.networkType = 'none'
      break
    case 'WWAN':
      // TODO ?
      result.networkType = '3g'
      break
    default:
      result.networkType = result.networkType.toLowerCase()
      break
  }
X
xiaoyucoding 已提交
75
  return {}
X
xiaoyucoding 已提交
76 77 78
}

const protocols = { // 需要做转换的 API 列表
fxy060608's avatar
fxy060608 已提交
79
  navigateTo,
80
  redirectTo,
fxy060608's avatar
fxy060608 已提交
81
  returnValue (methodName, res = {}) { // 通用 returnValue 解析
X
xiaoyucoding 已提交
82 83 84 85
    if (res.error || res.errorMessage) {
      res.errMsg = `${methodName}:fail ${res.errorMessage || res.error}`
      delete res.error
      delete res.errorMessage
X
xiaoyucoding 已提交
86 87
    } else {
      res.errMsg = `${methodName}:ok`
X
xiaoyucoding 已提交
88 89 90 91
    }
    return res
  },
  request: {
92
    name: my.canIUse('request') ? 'request' : 'httpRequest',
X
xiaoyucoding 已提交
93
    args (fromArgs) {
94
      const method = fromArgs.method || 'GET'
X
xiaoyucoding 已提交
95 96 97
      if (!fromArgs.header) { // 默认增加 header 参数,方便格式化 content-type
        fromArgs.header = {}
      }
98 99 100 101 102 103
      const headers = {
        'content-type': 'application/json'
      }
      Object.keys(fromArgs.header).forEach(key => {
        headers[key.toLocaleLowerCase()] = fromArgs.header[key]
      })
X
xiaoyucoding 已提交
104 105 106 107 108 109 110
      return {
        header (header = {}, toArgs) {
          return {
            name: 'headers',
            value: headers
          }
        },
111
        data (data) {
112
          // 钉钉小程序在content-type为application/json时需上传字符串形式data,使用my.dd在真机运行钉钉小程序时不能正确判断
113 114
          if (my.canIUse('saveFileToDingTalk') && method.toUpperCase() === 'POST' && headers['content-type'].indexOf(
            'application/json') === 0 && isPlainObject(data)) {
115 116 117 118 119 120 121 122 123 124
            return {
              name: 'data',
              value: JSON.stringify(data)
            }
          }
          return {
            name: 'data',
            value: data
          }
        },
X
xiaoyucoding 已提交
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
        method: 'method', // TODO 支付宝小程序仅支持 get,post
        responseType: false
      }
    },
    returnValue: {
      status: 'statusCode',
      headers: 'header'
    }
  },
  setNavigationBarColor: {
    name: 'setNavigationBar',
    args: {
      frontColor: false,
      animation: false
    }
  },
  setNavigationBarTitle: {
    name: 'setNavigationBar'
  },
  showModal ({
    showCancel = true
  } = {}) {
    if (showCancel) {
      return {
        name: 'confirm',
        args: {
          cancelColor: false,
          confirmColor: false,
          cancelText: 'cancelButtonText',
          confirmText: 'confirmButtonText'
        },
        returnValue (fromRes, toRes) {
          toRes.confirm = fromRes.confirm
          toRes.cancel = !fromRes.confirm
        }
      }
    }
    return {
      name: 'alert',
      args: {
        confirmColor: false,
        confirmText: 'buttonText'
      },
      returnValue (fromRes, toRes) {
        toRes.confirm = true
        toRes.cancel = false
      }
    }
  },
  showToast ({
    icon = 'success'
  } = {}) {
    const args = {
      title: 'content',
      icon: 'type',
      duration: false,
      image: false,
      mask: false
    }
    if (icon === 'loading') {
      return {
        name: 'showLoading',
        args
      }
    }
    return {
      name: 'showToast',
      args
    }
  },
  showActionSheet: {
    name: 'showActionSheet',
    args: {
      itemList: 'items',
      itemColor: false
    },
    returnValue: {
      index: 'tapIndex'
    }
  },
X
xiaoyucoding 已提交
205 206 207 208 209 210
  showLoading: {
    args: {
      title: 'content',
      mask: false
    }
  },
X
xiaoyucoding 已提交
211 212 213 214 215 216 217 218
  uploadFile: {
    args: {
      name: 'fileName'
    }
    // 从测试结果看,是有返回对象的,文档上没有说明。
  },
  downloadFile: {
    returnValue: {
X
xiaoyucoding 已提交
219
      apFilePath: 'tempFilePath'
X
xiaoyucoding 已提交
220
    }
221 222 223 224 225
  },
  getFileInfo: {
    args: {
      filePath: 'apFilePath'
    }
雪洛's avatar
雪洛 已提交
226
  },
227 228 229 230 231 232 233 234 235 236 237 238 239 240
  compressImage: {
    args (fromArgs) {
      fromArgs.compressLevel = 4
      if (fromArgs && fromArgs.quality) {
        fromArgs.compressLevel = Math.floor(fromArgs.quality / 26)
      }
      fromArgs.apFilePaths = [fromArgs.src]
    },
    returnValue (result) {
      if (result.apFilePaths && result.apFilePaths.length) {
        result.tempFilePath = result.apFilePaths[0]
      }
    }
  },
雪洛's avatar
雪洛 已提交
241 242 243 244 245
  chooseVideo: {
    // 支付宝小程序文档中未找到(仅在getSetting处提及),但实际可用
    returnValue: {
      apFilePath: 'tempFilePath'
    }
X
xiaoyucoding 已提交
246 247 248 249 250 251 252 253 254
  },
  connectSocket: {
    args: {
      method: false,
      protocols: false
    }
    // TODO 有没有返回值还需要测试下
  },
  chooseImage: {
255 256 257 258 259 260 261 262 263 264 265
    returnValue (result) {
      const hasTempFilePaths = hasOwn(result,'tempFilePaths') && result.tempFilePaths
      if (hasOwn(result,'apFilePaths') && !hasTempFilePaths) {
        result.tempFilePaths = result.apFilePaths
        delete result.apFilePaths
      }
      if (!hasOwn(result,'tempFiles') && hasTempFilePaths) {
        result.tempFiles = []
        result.tempFilePaths.forEach(tempFilePath => result.tempFiles.push({path: tempFilePath}))
      }
      return {}
X
xiaoyucoding 已提交
266 267 268 269
    }
  },
  previewImage: {
    args (fromArgs) {
X
xiaoyucoding 已提交
270
      // 支付宝小程序的 current 是索引值,而非图片地址。
271 272 273 274 275 276 277 278
      const currentIndex = Number(fromArgs.current)
      if (isNaN(currentIndex)) {
        if (fromArgs.current && Array.isArray(fromArgs.urls)) {
          const index = fromArgs.urls.indexOf(fromArgs.current)
          fromArgs.current = ~index ? index : 0
        }
      } else {
        fromArgs.current = currentIndex
X
xiaoyucoding 已提交
279
      }
X
xiaoyucoding 已提交
280
      return {
X
xiaoyucoding 已提交
281 282
        indicator: false,
        loop: false
X
xiaoyucoding 已提交
283
      }
X
xiaoyucoding 已提交
284 285 286 287 288 289 290
    }
  },
  saveFile: {
    args: {
      tempFilePath: 'apFilePath'
    },
    returnValue: {
X
xiaoyucoding 已提交
291
      apFilePath: 'savedFilePath'
X
xiaoyucoding 已提交
292 293 294 295 296 297
    }
  },
  getSavedFileInfo: {
    args: {
      filePath: 'apFilePath'
    }
298 299 300 301 302 303 304 305 306 307 308
  },
  getSavedFileList: {
    returnValue (result) {
      if (result.fileList && result.fileList.length) {
        result.fileList.forEach(file => {
          file.filePath = file.apFilePath
          delete file.apFilePath
        })
      }
      return {}
    }
X
xiaoyucoding 已提交
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
  },
  removeSavedFile: {
    args: {
      filePath: 'apFilePath'
    }
  },
  getLocation: {
    args: {
      type: false,
      altitude: false
    }
  },
  openLocation: {
    args: {
      // TODO address 参数在阿里上是必传的
    }
  },
  getNetworkType: {
    returnValue: _handleNetworkInfo
  },
  onNetworkStatusChange: {
    returnValue: _handleNetworkInfo
  },
  stopAccelerometer: {
    name: 'offAccelerometerChange'
  },
  stopCompass: {
    name: 'offCompassChange'
  },
  scanCode: {
    name: 'scan',
雪洛's avatar
雪洛 已提交
340
    args (fromArgs) {
341 342 343 344 345 346 347 348
      if (fromArgs.scanType) {
        switch (fromArgs.scanType[0]) {
          case 'qrCode':
            fromArgs.type = 'qr'
            break
          case 'barCode':
            fromArgs.type = 'bar'
            break
雪洛's avatar
雪洛 已提交
349
        }
350
      }
351 352 353
      return {
        onlyFromCamera: 'hideAlbum'
      }
X
xiaoyucoding 已提交
354 355 356
    },
    returnValue: {
      code: 'result'
X
xiaoyucoding 已提交
357 358 359 360 361 362 363 364 365 366 367
    }
  },
  setClipboardData: {
    name: 'setClipboard',
    args: {
      data: 'text'
    }
  },
  getClipboardData: {
    name: 'getClipboard',
    returnValue: {
X
xiaoyucoding 已提交
368
      text: 'data'
X
xiaoyucoding 已提交
369 370
    }
  },
X
xiaoyucoding 已提交
371 372 373 374 375 376 377
  login: {
    name: 'getAuthCode',
    returnValue (result) {
      result.code = result.authCode
    }
  },
  getUserInfo: {
雪洛's avatar
雪洛 已提交
378
    name: my.canIUse('getOpenUserInfo') ? 'getOpenUserInfo' : 'getAuthUserInfo',
雪洛's avatar
雪洛 已提交
379 380 381 382 383 384 385
    returnValue (result) {
      if (my.canIUse('getOpenUserInfo')) {
        let response = {}
        try {
          response = JSON.parse(result.response).response
        } catch (e) {}
        result.nickName = response.nickName
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
        result.avatar = response.avatar
      }
      result.userInfo = {
        nickName: result.nickName,
        avatarUrl: result.avatar
      }
    }
  },
  getUserProfile: {
    name: my.canIUse('getOpenUserInfo') ? 'getOpenUserInfo' : 'getAuthUserInfo',
    returnValue (result) {
      if (my.canIUse('getOpenUserInfo')) {
        let response = {}
        try {
          response = JSON.parse(result.response).response
        } catch (e) {}
        result.nickName = response.nickName
雪洛's avatar
雪洛 已提交
403
        result.avatar = response.avatar
雪洛's avatar
雪洛 已提交
404
      }
X
xiaoyucoding 已提交
405 406 407 408 409 410 411 412 413
      result.userInfo = {
        nickName: result.nickName,
        avatarUrl: result.avatar
      }
    }
  },
  requestPayment: {
    name: 'tradePay',
    args: {
414
      orderInfo: 'tradeNO'
X
xiaoyucoding 已提交
415
    }
X
xiaoyucoding 已提交
416 417 418 419 420 421 422
  },
  getBLEDeviceServices: {
    returnValue (result) {
      result.services.forEach((item) => {
        item.uuid = item.serviceId
      })
    }
雪洛's avatar
雪洛 已提交
423 424 425 426 427 428 429 430 431 432 433 434
  },
  createBLEConnection: {
    name: 'connectBLEDevice',
    args: {
      timeout: false
    }
  },
  closeBLEConnection: {
    name: 'disconnectBLEDevice'
  },
  onBLEConnectionStateChange: {
    name: 'onBLEConnectionStateChanged'
X
xiaoyucoding 已提交
435 436 437 438 439
  },
  makePhoneCall: {
    args: {
      phoneNumber: 'number'
    }
X
xiaoyucoding 已提交
440 441 442
  },
  stopGyroscope: {
    name: 'offGyroscopeChange'
X
xiaoyucoding 已提交
443
  },
444 445
  getSystemInfo: getSystemInfo,
  getSystemInfoSync: getSystemInfo,
446 447 448 449 450 451
  // 文档没提到,但是实测可用。
  canvasToTempFilePath: {
    returnValue (result) {
      // 真机的情况下会有 tempFilePath 这个值,因此需要主动修改。
      result.tempFilePath = result.apFilePath
    }
X
xiaoyucoding 已提交
452 453 454 455 456 457 458 459 460 461
  },
  setScreenBrightness: {
    args: {
      value: 'brightness'
    }
  },
  getScreenBrightness: {
    returnValue: {
      brightness: 'value'
    }
雪洛's avatar
雪洛 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
  },
  showShareMenu: {
    name: 'showSharePanel'
  },
  hideHomeButton: {
    name: 'hideBackHome'
  },
  saveImageToPhotosAlbum: {
    name: 'saveImage',
    args: {
      filePath: 'url'
    }
  },
  saveVideoToPhotosAlbum: {
    args: {
      filePath: 'src'
    }
  },
  chooseAddress: {
    name: 'getAddress',
    returnValue (result) {
fxy060608's avatar
fxy060608 已提交
483
      const info = result.result || {}
雪洛's avatar
雪洛 已提交
484 485 486
      result.userName = info.fullname
      result.provinceName = info.prov
      result.cityName = info.city
487
      result.countyName = info.area
雪洛's avatar
雪洛 已提交
488 489 490 491
      result.detailInfo = info.address
      result.telNumber = info.mobilePhone
      result.errMsg = result.resultStatus
    }
492
  }
fxy060608's avatar
fxy060608 已提交
493 494
}

495 496 497 498
export {
  protocols,
  todos,
  canIUses
499
}