mtl-js-sdk
Version:
ynf-fw-mtl-api
1,163 lines (1,120 loc) • 38.1 kB
JavaScript
/*
* @Author: wangyingliang@yonyou.com
* @Date: 2024-07-22 15:47:03
* @LastEditors: wangyingliang wangyingliang@yonyou.com
* @LastEditTime: 2025-09-02 17:45:32
* @FilePath: /mtl-api-project/src/common/unique.js
* @Description: h5 wx 兼容友空间,处理api
* Copyright (c) 2024 by Yonyou, All Rights Reserved.
*/
import xaxios from 'axios'
const FAIL_CODE = 1
const SUCCESS_CODE = 200
const setUserYHTInfoKey = "mtl$setUserYHTInfoKey"
const saveExpandParams = "mtl$saveExpandParams"
const KEY_DOMAIN = "key_domain"
const KEY_USERINFO = "key_userInfo"
const KEY_YHTTOKEN = "key_yht_token"
const axios = xaxios?.default || xaxios
const unsupportFailRes = {
code: FAIL_CODE,
message: "The current platform does not support",
}
function unsupportMethod(object = {}) {
object.fail && object.fail(unsupportFailRes)
object.complete && object.complete(unsupportFailRes)
}
function supportMethod(object = {}) {
object.success && object.success({})
object.complete && object.complete({})
}
const unsupportMethods = [
"blueToothConnectState",
"blueToothConnect",
"blueToothPrint",
"blueToothDisConnect",
"blueToothScan",
"blueToothStopScan",
"getBlueToothState",
"executeDBOperate",
"rfidConnect",
"rfidDisconnect",
"setAppletCapsuleStyle",
"getAppletCapsuleParams",
"setStatusBarStyle",
"getAuthorizationStatus",
"downloadFile",
"chooseVideoToServer",
"chooseLocalFileToServer",
]
const supportMethods = [
"registerCommonCallback",
"mdfCustomScanQRCode",
"mdfChangeCustomScanMode",
"mdfChangeFlashLightStatus",
"settingNavBar",
"voiceToText",
"openChatWindow",
"chooseContacts",
"chooseDocFiles",
"sendTodoReceipt",
"getAppInfomation",
"backToHome",
]
// 是否手机号
function isMobileNumber(phone, callback) {
let flag = false
let message = ""
// let myreg = /^1[3|4|5|6|7|8]\d{9}$/;
if (!phone) {
flag = false
message = "mobile number is null!"
} else {
flag = true
}
if (message) {
callback && callback(message)
}
return flag
}
const upesn = {
dail(obj) {
let _object = obj || {}
let number = _object.number
if (
isMobileNumber(number, (message) => {
let err = {
code: FAIL_CODE,
message,
}
_object.fail && _object.fail(err)
_object.complete && _object.complete(err)
})
) {
window.location.href = `tel://${number}`
}
},
//H5\wx上传图片
chooseImageToServer(obj = {}) {
let { url = "", sourceType = ["album", "camera"] } = obj
if (!url && url == "") {
obj.fail && obj.fail({ code: FAIL_CODE, message: "url is null!" })
return
}
mtl.chooseImage({
count: 1,
sourceType: sourceType,
success: function (res) {
var localIds = res.localIds
mtl.getLocalImgData({
localId: localIds[0],
success: function (res) {
var localData = res.localData
if (localData && localData != "") {
var param = {
type: "image",
}
axios({
headers: { "Content-Type": "application/json;" },
method: "post",
url: `${url}/rest/v1/mobile/upload/uploadBase64`,
params: param,
data: [localData],
})
.then((res) => {
let { status: code, statusText: message, data } = res
if (code === 200) {
if (data && data.code == 0) {
obj.success && obj.success({ pictures: data.data.files })
} else {
obj.fail && obj.fail(data)
}
} else {
obj.fail && obj.fail({ code, message, data })
}
})
.catch((err) => {
obj.fail && obj.fail(err)
})
} else {
obj.fail && obj.fail({ code: FAIL_CODE, message: "Error converting base64" })
}
},
fail: function (err) {
obj.fail && obj.fail(err)
},
})
},
fail: function (err) {
obj.fail && obj.fail(err)
},
})
},
setUserYHTInfo(obj = {}) {
mtl.setStorage({
key: setUserYHTInfoKey,
data: JSON.stringify(obj),
success: function (res) {
obj.success && obj.success(res)
},
fail: function (err) {
obj.fail && obj.fail(err)
},
})
},
getUserYHTInfo(obj = {}) {
mtl.getStorage({
key: setUserYHTInfoKey,
success: function (res) {
var userInfo = res.data
obj.success && obj.success(JSON.parse(userInfo))
},
fail: function (err) {
obj.fail && obj.fail(err)
},
})
},
getToken(obj = {}) {
mtl.getStorage({
key: setUserYHTInfoKey,
success: function (res) {
var userInfo = res.data
const obj = JSON.parse(userInfo) || {}
obj.success && obj.success({ token: obj.yhtToken })
},
fail: function (err) {
obj.fail && obj.fail(err)
},
})
},
gainUserInfo(obj = {}) {
mtl.getStorage({
key: setUserYHTInfoKey,
success: function (res) {
var userInfo = res.data
const obj = JSON.parse(userInfo) || {}
obj.success &&
obj.success({
userId: obj.yht_userid,
name: obj.userName,
qzId: obj.tenant_id,
loginName: obj.userName,
qzName: obj.tenant_name,
avatar: obj.userAvatar,
})
},
fail: function (err) {
obj.fail && obj.fail(err)
},
})
},
/** 文件预览 */
wpsPreview(obj = {}) {
const { fileUrl, fileId } = obj
if (fileId) {
loadFileSercice(obj)
} else if (fileUrl) {
mtl.navigateTo({ ...obj, url: fileUrl })
} else {
let err = {
message: "fileId、fileUrl is null",
}
obj.fail && obj.fail(err)
}
},
previewDoc(obj = {}) {
const { downloadUrl, fileId } = obj
if (fileId) {
loadFileSercice(obj)
} else if (downloadUrl) {
mtl.navigateTo({ ...obj, url: downloadUrl })
} else {
let err = {
message: "fileId、downloadUrl is null",
}
obj.fail && obj.fail(err)
}
},
previewFile(obj = {}) {
const { fid } = obj
if (fid) {
if (!fid.startsWith("http")) {
loadFileSercice({ ...obj, fileId: fid })
} else {
mtl.navigateTo({ ...obj, url: fid })
}
} else {
let err = {
message: "fid is null",
}
obj.fail && obj.fail(err)
}
},
/** 获取应用信息 */
getAppData(obj = {}) {
getData(obj, function (data) {
let params = data.ykj || {}
params.app_type = params.appType
params.name = data.serviceName
params.url = params.appUrl
obj.success && obj.success(params)
obj.complete && obj.complete(params)
})
},
}
unsupportMethods.forEach((pop) => {
upesn[pop] = unsupportMethod
})
supportMethods.forEach((pop) => {
upesn[pop] = supportMethod
})
// 内部方法,图片水印、压缩
function selectedImages(object = {}) {
const { index = 0, originLOcalIds = {}, sizeFiles } = object
const localIds = object?.localIds || object?.localData || []
if (index == localIds?.length) {
let res = {
pictures: object?.pictures,
localIds: localIds,
sizeFiles: object?.sizeFiles
}
object.success && object.success(res)
object.complete && object.complete(res)
} else {
watermarkImage({
...object,
image: localIds[index],
success: function (res) {
let newLocalIds = localIds.concat()
newLocalIds[index] = res.newBase64
// 重新处理 form-data
if (object?.pictures) {
let fileData = object.pictures[index]
var file = base64ToFile(res.newBase64, fileData.name);
object.pictures[index].file = file
}
selectedImages({ ...object, localIds: newLocalIds, index: index + 1 })
},
fail: function (err) {
console.log("watermark func error message:", err.message)
object.success && object.success(object)
object.complete && object.complete(object)
},
})
}
}
function watermarkImage(object) {
let { image } = object
new Promise((resolve, reject) => {
mtl.getLocalImgData({
localId: image,
success: resolve,
fail: reject,
})
}).then((res) => {
const { watermark = {}, returnThumbnail = false } = object
const { text, position = 0, font = 0, color = "#FFFFFF", alpha = 0.5 } = watermark
let imgBase64 = res.localData
let index = imgBase64.indexOf("base64,")
if (index === -1) {
imgBase64 = "data:image/png;base64," + imgBase64
}
if (!text) {
object.success && object.success({ newBase64: imgBase64 })
return
}
let newImage = new Image()
let quality = returnThumbnail ? 0.3 : 1 //压缩系数0-1之间,压缩到0.9以上会有bug,注意!(可以自行设置)
newImage.src = imgBase64
newImage.setAttribute("crossOrigin", "Anonymous") //url为外域时需要
let imgWidth = 800,
imgHeight
newImage.onload = function () {
imgHeight = (imgWidth / this.width) * this.height
//准备在画布上绘制图片
let canvas = document.createElement("canvas")
let ctx = canvas.getContext("2d")
let fontQuality = 1 // 文字比例
if (this.width > imgWidth) {
canvas.width = imgWidth
canvas.height = imgHeight
} else {
fontQuality = this.width / imgWidth
canvas.width = this.width
canvas.height = this.height
}
//清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height)
//开始绘制图片到画布上
ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
// 绘制水印
let steps = 36 * fontQuality
if (font == 1) {
steps = 48 * fontQuality
} else if (font == 2) {
steps = 24 * fontQuality
}
ctx.font = `${steps}px microsoft yahei`
ctx.fillStyle = color
ctx.globalAlpha = alpha
if (position == 0 || position == 1) {
ctx.textAlign = "center"
} else if (position == 2 || position == 4 || position == 5) {
ctx.textAlign = "left"
} else {
ctx.textAlign = "right"
}
if (position == 0) {
toFormateStr(ctx, text, canvas.width - 60, 5, canvas.width / 2, canvas.height - 10 - 40 * fontQuality, true, steps)
} else if (position == 1) {
toFormateStr(ctx, text, canvas.width - 60, 5, canvas.width / 2, 10 + 40 * fontQuality, false, steps)
} else if (position == 2) {
toFormateStr(ctx, text, canvas.width - 60, 5, 30, canvas.height / 2, false, steps)
} else if (position == 3) {
toFormateStr(ctx, text, canvas.width - 60, 5, canvas.width - 15 - 15 * fontQuality, canvas.height / 2, false, steps)
} else if (position == 4) {
toFormateStr(ctx, text, canvas.width - 60, 5, 10 + 20 * fontQuality, 10 + 40 * fontQuality, false, steps)
} else if (position == 5) {
// 下
toFormateStr(ctx, text, canvas.width - 60, 5, 10 + 20 * fontQuality, canvas.height - 10 - 40 * fontQuality, true, steps)
} else if (position == 6) {
toFormateStr(ctx, text, canvas.width - 60, 5, canvas.width - 15 - 15 * fontQuality, 10 + 40 * fontQuality, false, steps)
} else if (position == 7) {
// 下
toFormateStr(ctx, text, canvas.width - 60, 5, canvas.width - 15 - 15 * fontQuality, canvas.height - 10 - 40 * fontQuality, true, steps)
}
var newBase64 = canvas.toDataURL("image/png", quality) //压缩图片大小(关键代码)
if (newBase64.indexOf("\n") != -1 || newBase64.indexOf("\r") != -1 || newBase64.indexOf(" ") != -1) {
// 包含\n,可以直接替换, 解决android机器base64编码后带有\n问题
newBase64 = newBase64.replace(/(\r\n)|(\n)|(\s)/g, "")
}
object.success && object.success({ newBase64: newBase64 })
}
}).catch((err) => {
let result = { code: FAIL_CODE, message: err.toString() }
object.fail && object.fail(result)
object.complete && object.complete(result)
})
}
// 使用示例
function base64ToFile(base64Data, filename) {
// 将base64的数据部分提取出来
const parts = base64Data.split(';base64,');
const contentType = parts[0].split(':')[1];
const raw = window.atob(parts[1]);
// 将原始数据转换为Uint8Array
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
// 使用Blob对象创建File对象
const blob = new Blob([uInt8Array], { type: contentType });
blob.lastModifiedDate = new Date();
blob.name = filename;
return new File([blob], filename, { type: contentType });
}
function isBase64File(str) {
const base64Pattern = /^[A-Za-z0-9+/=]*$/;
return base64Pattern.test(str);
}
function isBase64Image(dataString) {
const regex = /^data:image\/([a-z]+);base64,/;
return regex.test(dataString);
}
/** 文本换行 */
function toFormateStr(ctx, str, drow_width, lineNum, startX, startY, isMoveUp, steps) {
var strWidth = ctx.measureText(str).width
var startPoint = startY,
keyStr = "",
sreLn = strWidth / drow_width
var liner = Math.ceil(sreLn)
let strlen = parseInt(str.length / sreLn)
if (strWidth < drow_width) {
ctx.fillText(str, startX, startPoint)
} else {
if (isMoveUp) {
startPoint = startPoint - steps * (Math.min(liner, lineNum) - 1)
}
for (var i = 1; i < liner + 1; i++) {
let strPoint = strlen * (i - 1)
if (i < lineNum || lineNum == -1 || liner <= lineNum) {
keyStr = str.substr(strPoint, strlen)
ctx.fillText(keyStr, startX, startPoint)
} else {
keyStr = str.substr(strPoint, strlen - 5) + "..."
ctx.fillText(keyStr, startX, startPoint)
break
}
startPoint = startPoint + steps
}
}
}
/** 给图片添加水印 */
function addImageWaterMark(object = {}) {
const { image } = object
watermarkImage({
...object,
image: image,
success: function (res) {
object.success && object.success({ image: res.newBase64 })
object.complete && object.complete({ image: res.newBase64 })
},
fail: function (err) {
console.log("watermark func error message:", err.message)
object.file && object.file(err)
object.complete && object.complete(err)
},
})
}
/**
* 参数为空判断
*/
function isEmpty(key, value, obj) {
if (!!!value) {
let res = {
code: -1,
message: `${key} is null`,
}
obj.fail && obj.fail(res)
obj.complete && obj.complete(res)
return true
}
return false
}
/**
* 网络状态
*/
function onNetworkStatusChange(obj = {}) {
var el = document.body
if (el.addEventListener) {
window.addEventListener(
"online",
function () {
networkChangeCallback(obj, true)
},
true
)
window.addEventListener(
"offline",
function () {
networkChangeCallback(obj, false)
},
true
)
} else if (el.attachEvent) {
window.attachEvent("ononline", function () {
networkChangeCallback(obj, true)
})
window.attachEvent("onoffline", function () {
networkChangeCallback(obj, false)
})
} else {
window.ononline = function () {
networkChangeCallback(obj, true)
}
window.onoffline = function () {
networkChangeCallback(obj, false)
}
}
supportMethod(obj)
}
function networkChangeCallback(obj, isConnected) {
const platform = mtl.platform
if (isConnected && (platform === "wx" || platform === "tt" || platform === "dingtalk")) {
mtl.getNetworkType({
success: function (res) {
let data = { isConnected: isConnected, networkType: isConnected ? res.networkType : "none" }
obj.callback && obj.callback(data)
obj.complete && obj.complete({ data, code: SUCCESS_CODE })
},
fail: function () {
let data = { isConnected: false, networkType: "none" }
obj.callback && obj.callback(data)
obj.complete && obj.complete({ data, code: FAIL_CODE })
},
})
} else {
let data = { isConnected: isConnected, networkType: isConnected ? "wifi" : "none" }
obj.callback && obj.callback(data)
obj.complete && obj.complete({ data, code: SUCCESS_CODE })
}
}
/* 启动应用 */
function openAppWithParams(obj = {}) {
const { expandParams } = obj
if (expandParams && typeof expandParams === "string") {
mtl.setStorage({
key: saveExpandParams,
data: expandParams,
})
}
getData(obj, function (data) {
let params = data.ykj || {}
params.app_type = params.appType
params.serviceIcon = data.serviceIcon
params.serviceName = data.serviceName
params.tenantId = data.tenantId
params.serviceId = data.serviceId
mtl.openExclusiveApp({
...params,
success: function (openRes) {
obj.success && obj.success(openRes)
obj.complete && obj.complete(openRes)
},
fail: function (openErr) {
obj.fail && obj.fail(openErr)
obj.complete && obj.complete(openErr)
},
})
})
}
/* 获取透传参数 */
function getAppletShareParams(obj = {}) {
mtl.getStorage({
key: saveExpandParams,
success: function (res) {
var value = res.data
obj.success && obj.success({ expandParams: value })
obj.complete && obj.complete({ expandParams: value })
},
fail: function (err) {
obj.fail && obj.fail(err)
obj.complete && obj.complete(err)
},
})
}
/* 选择附件 */
function chooseLocalFiles(obj = {}) {
let elementById = "mtlChooseFiles"
let input = document.getElementById(obj?.targetId || elementById)
if (!input) {
input = document.createElement("input")
}
input.type = "file"
input.id = "mtlChooseFiles"
input.name = "mtlChooseFiles"
input.style.display = "none"
input.accept = obj?.accept || "*/*"
try {
input.removeAttribute("capture")
} catch (error) {
console.log("input.removeAttribute fail, err = ", error)
}
var targetElement = document.getElementById(obj?.targetId)
if (targetElement) {
targetElement && targetElement.appendChild(input)
} else {
document.body && document.body.appendChild(input)
}
input.dispatchEvent(new MouseEvent("click"))
input.onchange = function (e) {
const files = [...this.files]
const retureFile = {}
if (files && files.length > 0) {
const file = files[0]
retureFile.fileName = file.name
retureFile.fileSize = file.size
retureFile.filePath = file
}
let resData = { localfiles: [retureFile] }
obj.success && obj.success(resData)
e.target.value = ""
}
}
/* 系统信息 */
function getSystemInfo(obj = {}) {
mtl.getExclusiveLanguage({
success: function (res) {
obj.language = res.language
systemInfo(obj)
},
fail: function (err) {
systemInfo(obj)
},
})
}
function systemInfo(obj = {}) {
let data = {
YZLanguage: obj.language,
platform: mtl.platform,
pixelRatio: window.devicePixelRatio,
screenWidth: window.screen.width,
screenHeight: window.screen.height,
systemLanguage: window.navigator.language,
}
obj.success && obj.success(data)
obj.complete && obj.complete(data)
}
/* 获取剪切板内容 */
function getClipboardData(obj = {}) {
navigator.permissions?.query({ name: "clipboard-read" }).then((result) => {
navigator.clipboard
?.readText()
.then((clipText) => {
obj.success && obj.success({ data: clipText })
obj.complete && obj.complete({ data: clipText })
})
.catch((err) => {
obj.fail && obj.fail(err)
obj.complete && obj.complete(err)
})
})
}
/* 设置剪切板内容 */
function setClipboardData(obj = {}) {
navigator.permissions?.query({ name: "clipboard-write" }).then((result) => {
navigator.clipboard
?.writeText(obj.data || "")
.then(() => {
obj.success && obj.success({ code: SUCCESS_CODE })
obj.complete && obj.complete({ code: SUCCESS_CODE })
})
.catch((err) => {
obj.fail && obj.fail(err)
obj.complete && obj.complete(err)
})
})
}
/** 监听摇一摇 */
function watchShake(obj = {}) {
const ua = navigator.userAgent
let isAndroid = ua.indexOf("Android") > -1 || ua.indexOf("Adr") > -1
if (window.DeviceMotionEvent) {
if (isAndroid || typeof DeviceOrientationEvent.requestPermission != "function") {
deviceHandler(obj)
} else {
DeviceOrientationEvent.requestPermission()
.then((response) => {
if (response == "granted") {
deviceHandler(obj)
} else {
let data = {
code: FAIL_CODE,
message: "The current platform does not have permissions enabled",
}
obj.fail && obj.fail(data)
obj.complete && obj.complete(data)
}
})
.catch((err) => {
obj.fail && obj.fail(err)
obj.complete && obj.complete(err)
})
}
} else {
supportMethod(obj)
}
}
function deviceHandler(obj) {
let last_update = 0
let x = 0
let y = 0
let z = 0
let last_x = 0
let last_y = 0
let last_z = 0
window.addEventListener(
"devicemotion",
function (eventData) {
var acceleration = eventData.accelerationIncludingGravity
var curTime = new Date().getTime()
if (curTime - last_update > 200) {
var diffTime = curTime - last_update
last_update = curTime
x = acceleration.x
y = acceleration.y
z = acceleration.z
var speed = (Math.abs(x + y + z - last_x - last_y - last_z) / diffTime) * 10000
if (speed > 1000) {
console.log("shaked")
obj.callback && obj.callback({})
}
last_x = x
last_y = y
last_z = z
}
},
false
)
}
/** 震动 */
function vibrateOnce(obj = {}) {
const ua = navigator.userAgent
let isAndroid = ua.indexOf("Android") > -1 || ua.indexOf("Adr") > -1
if (isAndroid && navigator.vibrate) {
navigator.vibrate(400)
setTimeout(() => {
supportMethod(obj)
}, 400)
} else {
supportMethod(obj)
}
}
/** 文件预览 */
function loadFileSercice(obj) {
if (!window.YYCooperationBridge) {
const { url } = obj
window.mtl &&
window.mtl.loadMtlCDNJs({
url: url || "/iuap-apcom-file/ucf-wh/fileservice/web/fileservice-web.min.js",
type: "all",
success: function (res) {
previewUrl(obj)
},
fail: obj.fail,
})
} else {
previewUrl(obj)
}
}
function previewUrl(obj) {
const { fileId, serviceCode, extraParams = {} } = obj
extraParams.authId = serviceCode
window.YYCooperationBridge &&
window.YYCooperationBridge.ready(() => {
window.YYCooperationBridge.YYPreviewFileByIdV2({ ...obj, fileId, extraParams })
.then((res) => {
if (typeof res === "string") {
mtl.navigateTo({ ...obj, url: res })
} else if (typeof res === "object") {
obj.fail && obj.fail(res)
}
})
.catch((err) => {
obj.fail && obj.fail(err)
})
})
}
/** 调用接口,获取应用信息 */
function getData(obj, onSuccess) {
const { serviceCode, url, fail } = obj
var objStr = localStorage.getItem(KEY_DOMAIN)
if (objStr) {
try {
objStr = JSON.parse(objStr)
} catch (error) {
console.log("getData json parse error")
}
}
var data = objStr?.data
var domain = null
if (data && data.mobileAppUrl) {
domain = data.mobileAppUrl
}
const appUrl = mtl.getStorageSync({ key: "key_mobile_app_url" }) || domain || `${window.location.origin}/iuap-yonbuilder-mobile`
let path = `${appUrl}/rest/v1/mobile/app/getServiceDetail`
if (url) {
path = url
}
mtl.request({
url: path,
params: { serviceCode },
success: function (res) {
let resData = res.data
if (resData && typeof resData === "string") {
resData = JSON.parse(resData)
}
if (resData && resData.success) {
const data = resData.data || {}
onSuccess && onSuccess(data)
} else {
fail && fail(resData)
}
},
fail: function (err) {
fail && fail(err)
},
})
}
// 保存接口域名信息
function saveExclusiveDomain(obj = {}) {
localStorage.setItem(KEY_DOMAIN, JSON.stringify(obj))
supportMethod(obj)
}
// 保存用户基本信息
function saveExclusiveUserInfo(obj = {}) {
const { userId, tenantId } = obj
if (isEmpty("userId", userId, obj) || isEmpty("tenantId", tenantId, obj)) {
return
}
localStorage.setItem(KEY_USERINFO, JSON.stringify(obj))
supportMethod(obj)
}
// 保存友户通信息
function saveExclusiveYhtInfo(obj = {}) {
const { yht_access_token, wb_at } = obj
if (isEmpty("yht_access_token", yht_access_token, obj) || isEmpty("wb_at", wb_at, obj)) {
return
}
// 写入userAgent
changeUseragent("yht_access_token", yht_access_token)
changeUseragent("wb_at", wb_at)
localStorage.setItem(KEY_YHTTOKEN, JSON.stringify(obj))
supportMethod(obj)
}
// 获取认证code
function getExclusiveCode(obj = {}) {
let domain = localStorage.getItem(KEY_DOMAIN)
try {
domain = JSON.parse(domain).domain
} catch (error) {
console.log("getExclusiveCode json parse error: domain")
}
let userInfo = JSON.parse(localStorage.getItem(KEY_USERINFO))
let yhtToken = JSON.parse(localStorage.getItem(KEY_YHTTOKEN))
if (isEmpty("domain", domain, obj) || isEmpty("userInfo", userInfo, obj) || isEmpty("yhtToken", yhtToken, obj)) {
return
}
let url = `${domain}/rest/v1/mobile/user/yht/auth/code?wb_at=${yhtToken.wb_at}&yhtAccessToken=${yhtToken.yht_access_token}&tenantId=${userInfo.tenantId}`
let axionObj = {
url,
method: "GET",
timeout: 10 * 1000,
}
axios(axionObj)
.then((response) => {
let { status: code, statusText: message, data } = response
if (code === 200) {
obj.success && obj.success(response)
} else {
obj.fail && obj.fail({ code, message, data })
}
obj.complete && obj.complete({ code, message, data })
})
.catch((err) => {
const result = { code: FAIL_CODE, message: err.message }
obj.fail && obj.fail(result)
obj.complete && obj.complete(result)
})
}
// 设置当前语言
function setExclusiveLanguage(obj = {}) {
const { language = 0 } = obj
let uaLanguage = "zh"
let lang = "zhs"
if (obj?.languageCode) {
let locallang = obj?.languageCode
uaLanguage = obj?.languageCode
mtl.setStorage({ key: "key_local_lang", data: locallang })
changeUseragent("YouZoneLocalLanguage", uaLanguage)
}
if (language == 1) {
uaLanguage = "en"
lang = "en"
} else if (language == 3) {
uaLanguage = "tw"
lang = "zht"
}
mtl.setStorage({ key: "key_lang", data: lang })
changeUseragent("youZoneLanguage", uaLanguage)
supportMethod(obj)
}
// 获取上下文信息
function mtlContext(obj = {}) {
let storageDomain = localStorage.getItem(KEY_DOMAIN)
try {
storageDomain = JSON.parse(storageDomain).domain
} catch (error) {
console.log("getExclusiveCode json parse error: domain")
}
if (window.location.href.includes("https")) {
storageDomain = window.location.origin
}
const { domain = storageDomain } = obj
if (domain && domain.length > 0) {
const url = `${domain}/me?onlyShayat=false`
let mtlResult = mtl.getStorageSync({ key: url })
if (mtlResult) {
try {
mtlResult = JSON.parse(mtlResult)
} catch (error) { }
obj.success && obj.success(mtlResult)
obj.complete && obj.complete({ code: SUCCESS_CODE, data: mtlResult })
return
} else {
window.mtl.request({
url,
success: function (res) {
let { data } = res
if (data) {
if (typeof data === "string") {
data = JSON.parse(res.data)
}
if (data.data) {
mtl.setStorage({
key: url,
data: JSON.stringify(data.data),
})
obj.success && obj.success(data.data)
} else {
mtl.setStorage({
key: url,
data: JSON.stringify(data),
})
obj.success && obj.success(data)
}
} else {
mtl.setStorage({
key: url,
data: JSON.stringify(res),
})
obj.success && obj.success(res)
}
obj.complete && obj.complete({ code: SUCCESS_CODE, data: res })
},
fail: function (err) {
obj.fail && obj.fail(err)
obj.complete && obj.complete({ code: FAIL_CODE, data: err })
},
})
}
} else {
obj.complete && obj.complete({ code: FAIL_CODE, message: "mtlContext domain is null" })
obj.complete && obj.complete({ code: FAIL_CODE, data: { message: "mtlContext domain is null" } })
}
}
// 内部方法
// 替换useragent参数
function changeUseragent(arg, val) {
let useragent = window.navigator.userAgent
let newUseragent
if (useragent.includes(arg)) {
newUseragent = changeUrlArg(useragent, arg, val)
} else {
newUseragent = `${useragent} ${arg}=${val}`
}
Object.defineProperty(navigator, "userAgent", {
value: newUseragent,
writable: true,
})
}
function changeUrlArg(url, arg, val) {
var replaceText = arg + "=" + val
return url.replace(eval("/(" + arg + "=)([^ ]*)/gi"), replaceText)
}
/**
* 检查 bridge 是否存在.
* @param {string} bridgeName
*/
function checkBridgeNameExist(obj = {}) {
var bridgeName = obj.bridgeName
var isExist = mtl[bridgeName] ? "1" : "0"
obj.success &&
obj.success({
isExist: isExist,
})
}
/**
* 检查 bridge 是否在友空间公有云执行.
*/
function canExecUpesnBridge() {
var _window$mtl = window.mtl,
_window$mtl$upesnVers = _window$mtl.upesnVersion,
upesnVersion = _window$mtl$upesnVers === void 0 ? 0 : _window$mtl$upesnVers,
platform = _window$mtl.platform
if (platform == "upesn" && upesnVersion > 0) {
return true
}
return false
}
/**
* url 上获取 appCode 字段
* @param {string} url 指定url
* @param {function} success 成功的回调
* @param {function} fail 失败的回调
*/
function getAppCode(obj) {
let urlSuffix = obj?.url || window.location.search
if (urlSuffix) {
let query = window.location.search.substring(1)
let vars = query.split("&")
let result = vars.find((element) => {
return element.indexOf("appCode") != -1
})
if (result) {
let data = {
code: 200,
message: "getAppCode success ",
data: {
appCode: result.substring(result.lastIndexOf("=") + 1),
},
appCode: result.substring(result.lastIndexOf("=") + 1),
}
obj.success && obj.success(data)
} else {
let data = {
code: -1,
message: "appCode acquisition failed",
}
obj.fail && obj.fail(data)
}
} else {
throw "appCode is null"
}
}
/**
* url 上获取 authCode 字段
* @param {string} url 指定url
* @param {function} success 成功的回调
* @param {function} fail 失败的回调
*/
function getAuthCode(obj) {
let urlSuffix = obj?.url || window.location.search
if (urlSuffix) {
let query = window.location.search.substring(1)
let vars = query.split("&")
let result = vars.find((element) => {
return element.indexOf("authCode") != -1
})
if (result) {
let data = {
code: 200,
message: "getAuthCode success",
data: {
authCode: result.substring(result.lastIndexOf("=") + 1),
},
authCode: result.substring(result.lastIndexOf("=") + 1),
}
obj.success && obj.success(data)
} else {
let data = {
code: -1,
message: "appCode acquisition failed",
}
obj.fail && obj.fail(data)
}
return
} else {
throw "authCode is null"
}
}
let exports = {
upesn,
selectedImages,
isEmpty,
onNetworkStatusChange,
openAppWithParams,
getAppletShareParams,
chooseLocalFiles,
getSystemInfo,
getClipboardData,
setClipboardData,
watchShake,
vibrateOnce,
saveExclusiveDomain,
saveExclusiveYhtInfo,
saveExclusiveUserInfo,
getExclusiveCode,
setExclusiveLanguage,
addImageWaterMark,
mtlContext,
checkBridgeNameExist,
canExecUpesnBridge,
getAppCode,
getAuthCode,
base64ToFile,
isBase64File,
isBase64Image
}
export default exports