cuiqian2004
10 天以前 f57571f987f3d25730123f488fccdfa3158ec5b1
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
488
import {
    Base64
} from 'js-base64';
import {
    wxDecryptData
} from '@/common/WXBizDataCrypt.js'
 
import {
 
    login as loginOrg,
    loginWeChat,
    loginDingTalk,
    getDingToken,
    getWeChatToken,
    getFileSvrInfo
 
} from "./org.js"
import {
    httpRequest,
} from "./gungho/index.js"
import {
    token as tokenFeishu,
    accesstoken as accesstokenFeishu,
    getCode as getCodeFeishu,
    getUserInfo as getUserInfoFeishu,
 
} from "./request/feishu.js"
import {
    getAuthCode as getDingAuthCode,
 
} from "./request/ding.js"
 
import {
    getCode as getCodeWxQy,
    checkSession as checkSessionWxQy,
    getMobile as getMobileWxQy,
 
} from "./request/wxqy.js"
 
import {
    getUploadUrl,
    putFile,
    uploadTask,
    callback,
    getDownloadUrl
 
} from "./request/minio.js"
 
 
export const getDingAutoLoginInfo = () => {
    return new Promise(async (resolve, reject) => {
        try {
            const app = getApp()
 
            const code = await getDingAuthCode() || ""
            const tokenRes = await getDingToken()
            const access_token = tokenRes.token || ""
            if (!access_token) {
                return reject("服务端没有配置钉钉应用相关信息,请联系管理员配置!")
            }
            app.globalData.dingding = {
                access_token: access_token,
                authCode: code,
            }
            let sUrl =
                `https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token=${access_token}`
            let dataStr = `code=${code}`
 
            let res = await httpRequest(sUrl, "POST", dataStr)
            const userId = res.userid || ""
 
            dataStr = `userid=${userId}`
            sUrl = `https://oapi.dingtalk.com/topapi/v2/user/get?access_token=${access_token}`
            const user = await httpRequest(sUrl, "POST", dataStr) || {}
            if (user.mobile) {
                let sMobile = user.mobile
                let nFind = user.mobile.indexOf("+86");
                if (nFind == 0) {
                    sMobile = user.mobile.substr(3)
                }
                resolve({
                    user_id: user.userid,
                    mobile: sMobile
                })
 
            } else {
                reject("你没有获取用户ID和手机号权限,请联系管理员开通!")
            }
 
        } catch (ex) {
            reject(ex)
        }
    })
}
 
/**
 * 钉钉用户自动登录
 * @returns 
 */
 
export const autoLoginDing = () => {
    return new Promise(async (resolve, reject) => {
        try {
            let info = await getDingAutoLoginInfo()
            let res = await loginDingTalk(info.user_id, info.mobile)
            res.mobile = info.mobile
            res.user_id = info.user_id
            resolve(res)
        } catch (ex) {
            reject(ex)
        }
    })
}
/**
 * 飞书用户自动登录
 * @returns 
 */
export const autoLoginFeiShu = () => {
    return new Promise(async (resolve, reject) => {
        try {
            const app = getApp()
            const code = await getCodeFeishu()
            const token = await tokenFeishu()
            if (!token) {
                return reject("访问飞书失败,请联系小程序开发商!")
            }
            const access_token = await accesstokenFeishu(code, token) || ""
            if (!access_token) {
                return reject("访问飞书失败,请联系小程序开发商!")
            }
            const user = await getUserInfoFeishu(access_token)
            if (user.mobile) {
                let sMobile = user.mobile
                let nFind = user.mobile.indexOf("+86");
                if (nFind == 0) {
                    sMobile = user.mobile.substr(3)
                }
                const res3 = await loginWeChat(user.user_id, sMobile)
                res3.mobile = sMobile
                res3.user_id = user.user_id
                resolve(res3)
            } else {
                return reject("你没有获取用户ID和手机号权限,请联系管理员开通!")
            }
 
        } catch (ex) {
            reject(ex)
        }
    })
}
 
/**
 * 企业微信用户自动登录
 * @returns 
 */
export const loginWxQy = () => {
    return new Promise(async (resolve, reject) => {
        try {
            const app = getApp()
            const code = await getCodeWxQy()
            const tokenRes = await getWeChatToken()
            const token = tokenRes.token || ""
            if (!token) {
                return reject("服务端没有配置企业微信应用相关信息,请联系管理员配置!")
            }
            let sUrl =
                'https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token=' +
                token + '&js_code=' + code + '&grant_type=authorization_code'
            let dataStr = `code=${code}`
            const resWx = await httpRequest(sUrl) || {}
            app.globalData.qyWx.userid = resWx.userid
            app.globalData.qyWx.session_key = resWx.session_key
            resolve(resWx)
        } catch (ex) {
            reject(ex)
        }
    })
}
 
 
/**
 * 企业微信用户自动登录
 * @returns 
 */
export const autoLoginWxQy = () => {
    return new Promise(async (resolve, reject) => {
        try {
            const app = getApp()
            const bRet = await checkSessionWxQy()
            if (!bRet) {
                await loginWxQy()
            }
            const res = await getMobileWxQy()
            const res2 = await wxDecryptData(app.globalData.appid, app.globalData.qyWx
                .session_key, res
                .encryptedData, res.iv)
            const res3 = await loginWeChat(app.globalData.qyWx.userid, res2.mobile)
            res3.mobile = res2.mobile
            res3.user_id = user.user_id
            resolve(res3)
        } catch (ex) {
            reject(ex)
        }
    })
}
 
 
/**
 * 上传文件至minio
 * @param {*} file 
 */
export const uploadFile3 = (file) => {
    return new Promise(async (resolve, reject) => {
        try {
            // 准备用户信息
            const app = getApp()
            const userInfo = app.globalData.userdata
            // 得到文件服务器信息
            let fileSFlag = app.globalData.files_flag || userInfo.files_info?.flag
            const fileSvrInfo = await getFileSvrInfo(fileSFlag)
            // 准备文件信息
            let md5 = file.md5
            // 得到接口地址
            let ip = fileSvrInfo.exter_ip || fileSvrInfo?.inter_ip
            let port = fileSvrInfo.exter_port || fileSvrInfo?.inter_port
            let isSSL = fileSvrInfo?.is_ssl || false
            let svrUrl = `${isSSL?'https':'http'}://${ip}:${port}`
 
            if (!ip) throw new Error(`文件服务器“${fileSFlag}”配置不正确,exter_ip为空`)
            if (!port) throw new Error(`文件服务器“${fileSFlag}”配置不正确,exter_port为空`)
            // 得到文件上传地址
 
 
            let uploadUrlInfo = await getUploadUrl(svrUrl, Base64.encode(JSON.stringify(fileSvrInfo
                    .minio)), file
                .name)
            // 上传文件
 
            await putFile(uploadUrlInfo.uldurl, file)
 
            let res = await callback(
                svrUrl,
                uploadUrlInfo.savepath,
                file.size,
                file.name,
                md5,
                userInfo.user_login,
                userInfo.user_name,
                fileSvrInfo.minio.access,
                fileSvrInfo.minio.secret
            )
            // 文件id
            let {
                id,
                createtime
            } = res
            let downloadUrlInfo = await getDownloadUrl(svrUrl, Base64.encode(JSON
                    .stringify(fileSvrInfo.minio)),
                id, file.name)
            let url = downloadUrlInfo.dldurl
            resolve({
                id,
                filesflag: fileSFlag,
                name: file.name,
                url: url,
                size: file.size,
                md5,
                createtime
            })
        } catch (ex) {
            let tip = typeof ex == 'string' ? ex : ex.message
            console.log(ex)
            throw new Error(`上传文件至minio服务器失败:${tip}`)
        }
    })
}
 
 
export const uploadFile = async (file, cbSuccess, cbProgress, cbFail) => {
    try {
        // 准备用户信息
        const app = getApp()
        const userInfo = app.globalData.userdata
 
        // 得到文件服务器信息
        let fileSFlag = app.globalData.files_flag || userInfo.files_info?.flag
        if (!fileSFlag) {
            return cbFail({
                errMsg: `未设置文件服务标识`,
                path: file.path
            })
        }
        const fileSvrInfo = await getFileSvrInfo(fileSFlag)
 
        // 准备文件信息
        let md5 = file.md5
        // 得到接口地址
        let ip = fileSvrInfo.exter_ip || fileSvrInfo?.inter_ip
        let port = fileSvrInfo.exter_port || fileSvrInfo?.inter_port
    let isSSL = fileSvrInfo?.is_ssl || false
    let svrUrl = `${isSSL?'https':'http'}://${ip}:${port}`
        if (!ip) {
            return cbFail({
                errMsg: `文件服务器“${fileSFlag}”配置不正确,exter_ip为空`,
                path: file.path
            })
        }
        if (!port) {
            return cbFail({
                errMsg: `文件服务器“${fileSFlag}”配置不正确,exter_port为空`,
                path: file.path
            })
        }
        if (fileSvrInfo?.is_ssl)
            fileSvrInfo.minio.is_ssl = true
        // 得到文件上传地址
        let uploadUrlInfo = await getUploadUrl(svrUrl, Base64.encode(JSON.stringify(fileSvrInfo.minio)), file
            .name, file.public)
 
        // 上传文件
        const task = uploadTask(uploadUrlInfo.uldurl, file, uploadUrlInfo.formdata, async (param) => {
            // 写数据库
            let res = await callback(
                svrUrl,
                uploadUrlInfo.savepath,
                file.size,
                file.name,
                md5,
                userInfo.user_login,
                userInfo.user_name,
                fileSvrInfo.minio.access,
                fileSvrInfo.minio.secret
            )
 
            // 文件id
            let {
                id,
                createtime
            } = res
 
            // let downloadUrlInfo = await getDownloadUrl(svrUrl, Base64.encode(JSON.stringify(
            //         fileSvrInfo.minio)),
            //     id, file.name)
            let url = file.path // downloadUrlInfo.dldurl
            if (file.public) {
                url = `/${uploadUrlInfo.bucketname}/${uploadUrlInfo.savepath}`
            }
 
            if (typeof cbSuccess == "function") {
                console.log(url)
                cbSuccess({
                    id,
                    filesflag: fileSFlag,
                    name: file.name,
                    url,
                    size: file.size,
                    md5,
                    createtime,
                    savepath: uploadUrlInfo.savepath,
                })
 
            }
 
        }, (param1, param2) => {
            if (typeof cbProgress == "function") {
                cbProgress(param1, param2)
            }
        }, (param) => {
            console.log(cbFail)
            if (typeof cbFail == "function") {
                cbFail(param)
            }
        })
        return task
 
    } catch (ex) {
        let tip = typeof ex == 'string' ? ex : ex.message
        console.log(ex)
        cbFail({
            errMsg: `上传文件至minio服务器失败:${tip}`,
            path: file.path
        })
    }
}
/**
 * minio public文件访问地址
 * @returns 
 */
export const publicFileUrl = async (fileSFlag, subUrl) => {
    try {
 
        if (!fileSFlag) return subUrl
        // 得到文件服务器信息
        const fileSvrInfo = await getFileSvrInfo(fileSFlag)
         console.log("publicFileUrl",fileSvrInfo)
        // 得到接口地址
        let ip = fileSvrInfo?.minio?.exter_ip || fileSvrInfo?.minio?.inter_ip
        let port = fileSvrInfo?.minio?.exter_port || fileSvrInfo?.minio?.inter_port
        let isSSL = fileSvrInfo?.is_ssl || false
        let svrUrl = `${isSSL?'https':'http'}://${ip}:${port}`
        if (!ip) return subUrl
        if (!port) return subUrl
        let url = `${svrUrl}${subUrl}`
        return url
    } catch (ex) {
        return subUrl
    }
}
/**
 * minio下载文件
 * @param {*} fileId 
 * @param {*} fileName 
 * @param {*} fileServer 
 * @returns 
 */
export const downloadFileUrl = async (fileId, fileName, fileSFlag) => {
    try {
        if (!fileSFlag) throw new Error('未指定文件服务器标识')
        // 得到文件服务器信息
        const fileSvrInfo = await getFileSvrInfo(fileSFlag)
         console.log("downloadFileUrl",fileSvrInfo)
        // 得到接口地址
        let ip = fileSvrInfo.exter_ip || fileSvrInfo?.inter_ip
        let port = fileSvrInfo.exter_port || fileSvrInfo?.inter_port
        let isSSL = fileSvrInfo?.is_ssl || false
        let svrUrl = `${isSSL?'https':'http'}://${ip}:${port}`
        if (!ip) throw new Error(`文件服务器“${fileSFlag}”配置不正确,exter_ip为空`)
        if (!port) throw new Error(`文件服务器“${fileSFlag}”配置不正确,exter_port为空`)
        if (fileSvrInfo?.is_ssl)
            fileSvrInfo.minio.is_ssl = true
        fileId = fileId.replace("{", "").replace("}", "");
        // 得到文件下载地址
        let downloadUrlInfo = await getDownloadUrl(svrUrl, Base64.encode(JSON.stringify(fileSvrInfo.minio)),
            fileId, fileName)
        let url = downloadUrlInfo.dldurl
        return url
    } catch (ex) {
        let tip = typeof ex === 'string' ? ex : ex.errMsg ||  ex.message  
        throw new Error(`minio下载文件失败:${tip}`)
    }
}
 
export const downloadFileTask = (url, cbSuccess, cbProgress, cbFail) => {
    const app = getApp()
    const downloadTask = uni.downloadFile({
        url,
        success: (result) => {
            //#ifdef MP-MP-WEIXIN || MP-LARK
            if (result.statusCode === 200) {
                console.log("downloadTaskFile success", result)
                var res = {}
                res.url = url;
                res.path = result.tempFilePath
                cbSuccess(res)
            } else {
                console.log("downloadTaskFile err", result)
                var res = {}
                res.errMsg = result.data || '下载未知错误!';
                res.url = url;
                cbFail(res);
            }
            return
            // #endif
            console.log("downloadTaskFile success", result)
            var res = {}
            res.url = url;
            res.path = result.tempFilePath
            cbSuccess(res)
        },
        fail: (result) => {
            console.log("downloadTaskFile fail", result)
            var res = {}
            res.url = url;
            res.errMsg = '下载文件失败!';
            cbFail(res);
        }
    })
    downloadTask.onProgressUpdate((res) => {
        if (res.progress != null) {
            console.log('下载进度', res.progress);
            console.log('已经下载的数据长度', res.totalBytesWritten);
            console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite);
            res.url = url;
            cbProgress(res, downloadTask)
        }
 
    });
}