提交 4950eb8f 编写于 作者: 张磊's avatar 张磊

Merge branch 'feat/zl' into 'release'

Feat/zl

See merge request !263
......@@ -316,4 +316,4 @@ export const savePCDayCount = async (data) => {
data: data,
method: 'post',
});
};
\ No newline at end of file
};
......@@ -649,7 +649,6 @@
that.memberList &&
that.memberList.length > 0
) {
that.memberList.map((i) => {
console.log('res==---', l, i.id, l.includes(i.id));
if (l.includes(i.id)) {
......@@ -666,14 +665,12 @@
}
}
});
}else {
if( that.memberList &&
that.memberList.length > 0) {
that.memberList.map( i => {
} else {
if (that.memberList && that.memberList.length > 0) {
that.memberList.map((i) => {
that.removeMember(i.liveUserId);
});
}
}
});
}, 2000);
......
......@@ -295,7 +295,7 @@
font-weight: 400;
color: #666666;
border-radius: 9px;
border: 1px solid #D9D9D9;
border: 1px solid #d9d9d9;
margin-right: 8px;
}
.info-phone {
......
/* eslint-disable */
class RtcClient {
constructor(options) {
this.sdkAppId_ = options.sdkAppId;
......@@ -25,7 +26,7 @@ class RtcClient {
mode: 'live',
sdkAppId: this.sdkAppId_,
userId: this.userId_,
userSig: this.userSig_
userSig: this.userSig_,
});
this.handleEvents();
} catch (error) {
......@@ -43,7 +44,7 @@ class RtcClient {
try {
await this.client_.join({
roomId: this.roomId_,
role: this.role
role: this.role,
});
console.log('加入房间trtc成功');
this.isJoined_ = true;
......@@ -52,7 +53,7 @@ class RtcClient {
audio: true,
video: false,
userId: this.userId_,
mirror: true
mirror: true,
});
this.startRTC();
} catch (e) {
......@@ -69,7 +70,7 @@ class RtcClient {
width: this.vueInstance.viedoParams.webVideoWidth,
height: this.vueInstance.viedoParams.webVideoHeight,
frameRate: this.vueInstance.viedoParams.webVideoFramerate,
bitrate: this.vueInstance.viedoParams.webVideoBitrate /* kpbs */
bitrate: this.vueInstance.viedoParams.webVideoBitrate /* kpbs */,
});
// 避免重复开摄像头
this.stopPush();
......@@ -86,29 +87,32 @@ class RtcClient {
return;
}
try {
this.localStream_.initialize().catch(error => {
this.vueInstance.$message({
message: '打开设备失败,请检查您的设备!',
type: 'error'
});
console.error('failed initialize localStream ' + error);
}).then(() => {
// 本地流在主播放器上播放,并且插入到一个关联的box中
var localVideoWrapEl = document.getElementById('ask');
this.localStream_.play(localVideoWrapEl, {
muted: true
});
// 主播直接推流
if (this.role == 'anchor') {
this.publish();
}
}).catch(() => {
this.vueInstance.$message({
message: '麦克风打开失败!',
type: 'error'
this.localStream_
.initialize()
.catch((error) => {
this.vueInstance.$message({
message: '打开设备失败,请检查您的设备!',
type: 'error',
});
console.error('failed initialize localStream ' + error);
})
.then(() => {
// 本地流在主播放器上播放,并且插入到一个关联的box中
var localVideoWrapEl = document.getElementById('ask');
this.localStream_.play(localVideoWrapEl, {
muted: true,
});
// 主播直接推流
if (this.role == 'anchor') {
this.publish();
}
})
.catch(() => {
this.vueInstance.$message({
message: '麦克风打开失败!',
type: 'error',
});
});
});
} catch (e) {
this.isPublished_ = false;
}
......@@ -117,16 +121,20 @@ class RtcClient {
// 发布本地流
async publish() {
this.client_ && this.client_.publish(this.localStream_).then(() => {
console.log('本地流发布成功');
this.isPublished_ = true;
// 手动将麦克风打开
this.unmuteLocalAudio();
}).catch(error => {
console.log('本地流发布失败');
this.isPublished_ = false;
this.vueInstance.reloadfn();
});
this.client_ &&
this.client_
.publish(this.localStream_)
.then(() => {
console.log('本地流发布成功');
this.isPublished_ = true;
// 手动将麦克风打开
this.unmuteLocalAudio();
})
.catch((error) => {
console.log('本地流发布失败');
this.isPublished_ = false;
this.vueInstance.reloadfn();
});
}
/**
......@@ -134,11 +142,11 @@ class RtcClient {
*/
async stopPush() {
if (this.localStream_ && this.isPublished_ && this.isJoined_) {
this.client_.unpublish(this.localStream_).then(() => {
this.isPublished_ = false;
this.localStream_.stop();
this.setLocalVideo();
});
this.client_.unpublish(this.localStream_).then(() => {
this.isPublished_ = false;
this.localStream_.stop();
this.setLocalVideo();
});
} else {
this.setLocalVideo();
}
......@@ -189,12 +197,12 @@ class RtcClient {
roomID: this.roomId_, // 房间id
viewslist: this.viewslist, // 当前房间用户列表
TRTCType: 'mute', // trtc 实时通讯状态数据类型 1. error , 2.network-quality 3. AudioStats
TRTCData: {muteLocalAudio: '静音' }, // trtc 实时通讯状态数据
TRTCData: { muteLocalAudio: '静音' }, // trtc 实时通讯状态数据
};
_VM.$sendBuriedData({
action: 'TRTC',
component_tag: 'TRTC#0',
web_data: params
web_data: params,
});
this.localStream_.muteAudio();
}
......@@ -207,12 +215,12 @@ class RtcClient {
roomID: this.roomId_, // 房间id
viewslist: this.viewslist, // 当前房间用户列表
TRTCType: 'unmute', // trtc 实时通讯状态数据类型 1. error , 2.network-quality 3. AudioStats
TRTCData: {muteLocalAudio: '取消静音' }, // trtc 实时通讯状态数据
TRTCData: { muteLocalAudio: '取消静音' }, // trtc 实时通讯状态数据
};
_VM.$sendBuriedData({
action: 'TRTC',
component_tag: 'TRTC#0',
web_data: params
web_data: params,
});
this.localStream_.unmuteAudio();
}
......@@ -239,15 +247,17 @@ class RtcClient {
// client的一些事件监听
handleEvents() {
// 报错
this.client_.on('error', err => {
console.log('client 报错了--------------------------------------------------------------');
this.client_.on('error', (err) => {
console.log(
'client 报错了--------------------------------------------------------------'
);
console.log(err);
// alert(err);
window.onbeforeunload = null;
location.reload();
});
this.client_.on('network-quality', event => {
this.client_.on('network-quality', (event) => {
console.log('--network-quality', event);
const params = {
roomID: this.roomId_, // 房间id
......@@ -258,9 +268,9 @@ class RtcClient {
_VM.$sendBuriedData({
action: 'TRTC',
component_tag: 'TRTC#0',
web_data: params
web_data: params,
});
this.client_.getLocalAudioStats().then(stats => {
this.client_.getLocalAudioStats().then((stats) => {
const params = {
roomID: this.roomId_, // 房间id
viewslist: this.viewslist, // 当前房间用户列表
......@@ -270,10 +280,10 @@ class RtcClient {
_VM.$sendBuriedData({
action: 'TRTC',
component_tag: 'TRTC#0',
web_data: params
web_data: params,
});
});
this.client_.getRemoteAudioStats().then(stats => {
this.client_.getRemoteAudioStats().then((stats) => {
const params = {
roomID: this.roomId_, // 房间id
viewslist: this.viewslist, // 当前房间用户列表
......@@ -284,10 +294,9 @@ class RtcClient {
_VM.$sendBuriedData({
action: 'TRTC',
component_tag: 'TRTC#0',
web_data: params
web_data: params,
});
});
});
// 房间被解散了
......@@ -296,20 +305,20 @@ class RtcClient {
});
// 当一个远程同伴(必须推流)进入房间时触发
this.client_.on('peer-join', evt => {
this.client_.on('peer-join', (evt) => {
const userId = evt.userId;
console.log('有远程同伴进入房间:', userId);
});
// 当远处的同伴离开房间时触发(删减好友列表)
this.client_.on('peer-leave', evt => {
this.client_.on('peer-leave', (evt) => {
const userId = evt.userId;
console.log('有远程同伴离开房间:' + userId);
this.removeUserList(userId);
});
// 在添加远程流时触发
this.client_.on('stream-added', evt => {
this.client_.on('stream-added', (evt) => {
const remoteStream = evt.stream;
// 获取流的StreamId
const id = remoteStream.getId();
......@@ -317,19 +326,21 @@ class RtcClient {
const userId = remoteStream.getUserId();
this.members_.set(userId, remoteStream);
this.inmembers_.set(userId, remoteStream);
console.log(`remote stream added: [${userId}] ID: ${id} type: ${remoteStream.getType()}`);
console.log(
`remote stream added: [${userId}] ID: ${id} type: ${remoteStream.getType()}`
);
// 我们订阅远端的流
console.log('subscribe to this remote stream');
this.client_.subscribe(remoteStream);
});
// 在订阅远程流时触发
this.client_.on('stream-subscribed', evt => {
this.client_.on('stream-subscribed', (evt) => {
const remoteStream = evt.stream;
const id = remoteStream.getId();
const uid = remoteStream.userId_;
this.remoteStreams_.push(remoteStream);
remoteStream.on('player-state-changed', event => {
remoteStream.on('player-state-changed', (event) => {
console.log(`${event.type} player is ${event.state}`);
// 远端流是播放还是暂停状态(显示按钮等画面不同)
if (event.type == 'video' && event.state == 'STOPPED') {
......@@ -346,46 +357,44 @@ class RtcClient {
}
});
// 避免重复加载
for (let i = 0; i < this.viewslist.length; i++) {
if (this.viewslist[i] && uid == this.viewslist[i].userId) {
return;
}
// 避免重复加载
for (let i = 0; i < this.viewslist.length; i++) {
if (this.viewslist[i] && uid == this.viewslist[i].userId) {
return;
}
const isMask = false;
// this.viewslist.push({ id: id, userId: uid, nick: uid, mask: isMask, vioce: true })
this.add(id, uid, isMask);
this.vueInstance.addNewMember(uid);
setTimeout(() => {
// 避免其他乱入视频
const index = this.viewslist.findIndex((item => {
if (item && item.userId) {
return item.userId == uid;
} else {
return -1;
}
}));
if (index < 0) {
return;
}
// 播放视频
remoteStream.play(id);
if (!remoteStream.hasVideo()) {
this.changeView(id, 'mask', true);
}
if (!remoteStream.hasAudio()) {
this.changeView(id, 'vioce', false);
}
const isMask = false;
// this.viewslist.push({ id: id, userId: uid, nick: uid, mask: isMask, vioce: true })
this.add(id, uid, isMask);
this.vueInstance.addNewMember(uid);
setTimeout(() => {
// 避免其他乱入视频
const index = this.viewslist.findIndex((item) => {
if (item && item.userId) {
return item.userId == uid;
} else {
return -1;
}
}, 1000);
});
if (index < 0) {
return;
}
// 播放视频
remoteStream.play(id);
if (!remoteStream.hasVideo()) {
this.changeView(id, 'mask', true);
}
if (!remoteStream.hasAudio()) {
this.changeView(id, 'vioce', false);
}
}, 1000);
});
// 当远程流被移除时触发
this.client_.on('stream-removed', evt => {
this.client_.on('stream-removed', (evt) => {
const remoteStream = evt.stream;
const id = remoteStream.getId();
const uid = remoteStream.userId_;
......@@ -393,14 +402,14 @@ class RtcClient {
// 停止播放并删除相应<video>标签
remoteStream.stop();
this.inmembers_.delete(uid);
this.remoteStreams_ = this.remoteStreams_.filter(stream => {
this.remoteStreams_ = this.remoteStreams_.filter((stream) => {
return stream.getId() !== id;
});
this.removeUserList(uid);
});
// 流更新
this.client_.on('stream-updated', evt => {
this.client_.on('stream-updated', (evt) => {
console.log('=========流更新========stream-updated===================');
console.log(evt);
const remoteStream = evt.stream;
......@@ -408,37 +417,52 @@ class RtcClient {
// remoteStream.hasVideo() // 是否有视频轨道
// remoteStream.hasAudio() //是否有音轨道
// remoteStream.getType() // 主要用于判断一个远端流是主音视频流还是辅路视频流,辅路视频流通常是一个屏幕分享流。
console.log('remoteStream ID: ' + remoteStream.getId() + ' was updated hasAudio: ' +
remoteStream.hasAudio() + ' hasVideo: ' + remoteStream.hasVideo());
console.log(
'remoteStream ID: ' +
remoteStream.getId() +
' was updated hasAudio: ' +
remoteStream.hasAudio() +
' hasVideo: ' +
remoteStream.hasVideo()
);
});
// 关闭音轨道
this.client_.on('mute-audio', evt => {
this.client_.on('mute-audio', (evt) => {
this.changeView(evt.userId, 'vioce', false);
console.log(evt.userId + '关闭麦克风============================================');
console.log(
evt.userId + '关闭麦克风============================================'
);
});
// 打开音轨道
this.client_.on('unmute-audio', evt => {
this.client_.on('unmute-audio', (evt) => {
this.changeView(evt.userId, 'vioce', true);
if (evt.type == 'audio' && evt.state == 'PLAYING' && this.vueInstance.type == 1) {
if (
evt.type == 'audio' &&
evt.state == 'PLAYING' &&
this.vueInstance.type == 1
) {
this.changeView(evt.userId, 'mask', true);
}
});
// 关闭视频轨道
this.client_.on('mute-video', evt => {
console.log(evt.userId + '关闭 video==============================================');
this.client_.on('mute-video', (evt) => {
console.log(
evt.userId + '关闭 video=============================================='
);
this.changeView(evt.userId, 'mask', true);
});
// 打开视频轨道
this.client_.on('unmute-video', evt => {
console.log(evt.userId + '打开 video=============================================');
this.client_.on('unmute-video', (evt) => {
console.log(
evt.userId + '打开 video============================================='
);
if (this.members_.get(evt.userId)) {
this.changeView(evt.userId, 'mask', false);
}
});
}
......@@ -452,7 +476,7 @@ class RtcClient {
// 移除视频数组
removeUserList(userId) {
for(let i = 0; i < this.viewslist.length; i++) {
for (let i = 0; i < this.viewslist.length; i++) {
if (this.viewslist[i] && this.viewslist[i].userId == userId) {
this.viewslist[i] = null;
}
......@@ -462,7 +486,10 @@ class RtcClient {
// 改变视频数组属性
changeView(id, attr, val) {
for (let i = 0; i < this.viewslist.length; i++) {
if (this.viewslist[i] && (this.viewslist[i].userId == id || this.viewslist[i].id == id)) {
if (
this.viewslist[i] &&
(this.viewslist[i].userId == id || this.viewslist[i].id == id)
) {
this.viewslist[i][attr] = val;
}
}
......@@ -471,7 +498,13 @@ class RtcClient {
add(id, uid, isMask) {
this.vueInstance.memberList.forEach((ele, index) => {
if (ele.liveUserId == uid) {
this.viewslist[index] = { id: id, userId: uid, nick: uid, mask: isMask, vioce: true };
this.viewslist[index] = {
id: id,
userId: uid,
nick: uid,
mask: isMask,
vioce: true,
};
}
});
}
......
// api路径
import {isNotEmptyUtils} from './utils';
/* eslint-disable */
import { isNotEmptyUtils } from './utils';
export default async(url = '', data = {}, type = 'POST', method = 'fetch') => {
type = type.toUpperCase();
export default async (url = '', data = {}, type = 'POST', method = 'fetch') => {
type = type.toUpperCase();
// url = (server==='WECHAT'?wechatUrl:baseUrl) + url;
if (url.match('^http') == null) {
url = localStorage.getItem('Url') + url;
}
// url = (server==='WECHAT'?wechatUrl:baseUrl) + url;
if (url.match('^http') == null) {
url = localStorage.getItem('Url') + url;
}
console.log('完整url:', url);
if (type == 'GET' && data) {
let dataStr = ''; // 数据拼接字符串
Object.keys(data).forEach(key => {
dataStr += key + '=' + data[key] + '&';
});
console.log('完整url:', url);
if (type == 'GET' && data) {
let dataStr = ''; // 数据拼接字符串
Object.keys(data).forEach((key) => {
dataStr += key + '=' + data[key] + '&';
});
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
url = url + '?' + dataStr;
// url = encodeURI(url + '?' + dataStr, true);
}
}
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
url = url + '?' + dataStr;
// url = encodeURI(url + '?' + dataStr, true);
}
}
if (window.fetch && method == 'fetch') {
const requestConfig = {
credentials: 'include',
method: type,
// mode: "cors",
headers: {
// 'Access-Control-Allow-Origin': '*',
'Accept': '*',
'Content-Type': 'application/json',
'sysCode':'2'
// 'token': localStorage.getItem('token') || null, //固定传header:
// 'system_code': 'todo' //固定传header:系统编号
},
};
if (window.fetch && method == 'fetch') {
const requestConfig = {
credentials: 'include',
method: type,
// mode: "cors",
headers: {
// 'Access-Control-Allow-Origin': '*',
Accept: '*',
'Content-Type': 'application/json',
sysCode: '2',
// 'token': localStorage.getItem('token') || null, //固定传header:
// 'system_code': 'todo' //固定传header:系统编号
},
};
if (type == 'POST' || type === 'PUT' || type === 'PATCH' || type === 'DELETE' && data) {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data)
});
}
try {
const response = await fetch(url, requestConfig);
const responseJson = await response.json();
if (
type == 'POST' ||
type === 'PUT' ||
type === 'PATCH' ||
(type === 'DELETE' && data)
) {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data),
});
}
try {
const response = await fetch(url, requestConfig);
const responseJson = await response.json();
return responseJson;
} catch (error) {
throw new Error(error);
}
} else {
return new Promise((resolve, reject) => {
let requestObj;
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest();
} else {
requestObj = new ActiveXObject();
}
return responseJson;
} catch (error) {
throw new Error(error);
}
} else {
return new Promise((resolve, reject) => {
let requestObj;
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest();
} else {
requestObj = new ActiveXObject();
}
let sendData = '';
if (type == 'POST' || type == 'DELETE' || type == 'PUT') {
sendData = JSON.stringify(data);
}
let sendData = '';
if (type == 'POST' || type == 'DELETE' || type == 'PUT') {
sendData = JSON.stringify(data);
}
requestObj.open(type, url, true);
requestObj.setRequestHeader('Content-Type', 'application/json');
requestObj.send(sendData);
requestObj.open(type, url, true);
requestObj.setRequestHeader('Content-Type', 'application/json');
requestObj.send(sendData);
requestObj.onreadystatechange = () => {
if (requestObj.readyState == 4) {
if (requestObj.status == 200) {
let obj = requestObj.response;
if (typeof obj !== 'object' && isNotEmptyUtils(obj)) {
obj = JSON.parse(obj);
}
resolve(obj);
} else {
reject(requestObj);
}
}
};
});
}
requestObj.onreadystatechange = () => {
if (requestObj.readyState == 4) {
if (requestObj.status == 200) {
let obj = requestObj.response;
if (typeof obj !== 'object' && isNotEmptyUtils(obj)) {
obj = JSON.parse(obj);
}
resolve(obj);
} else {
reject(requestObj);
}
}
};
});
}
};
import axios from 'axios';
import store from '../store';
// import { getHostnameAndPort } from '../utils'
// axios.defaults.withCredentials = true
......@@ -7,48 +6,45 @@ import store from '../store';
const service = axios.create({
// baseURL: process.env.BASE_API
timeout: 600000,
withCredentials: false
withCredentials: false,
});
// request拦截器
service.interceptors.request.use(config => {
config.headers['sysCode'] = 26;
config.headers['token'] = localStorage.getItem('token');
config.headers['deviceInfo'] = JSON.stringify({ 'app_channel': '', 'app_mac': '', 'app_uuid': '', 'app_version': '', 'device_brand': '', 'device_ip': '', 'device_model': '', 'device_net': '', 'device_ops': '', 'resolution_wh': '', 'system_level': '', 'device_type': '10' });
Object.assign(config.headers, config.changeHeader);
if (config.fileHeader) {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
service.interceptors.request.use(
(config) => {
config.headers['sysCode'] = 26;
config.headers['token'] = localStorage.getItem('token');
config.headers['deviceInfo'] = JSON.stringify({
app_channel: '',
app_mac: '',
app_uuid: '',
app_version: '',
device_brand: '',
device_ip: '',
device_model: '',
device_net: '',
device_ops: '',
resolution_wh: '',
system_level: '',
device_type: '10',
});
Object.assign(config.headers, config.changeHeader);
if (config.fileHeader) {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
return config;
},
(error) => {
Promise.reject(error);
}
// if (config.data && config.data.setEntry) {
// config.headers['sysCode'] = config.data.sysCode || 10
// if(config.data.token){
// config.headers['token'] = config.data.token || '63C3FA92AF8A45A48B31EB7FD97B95EB'
// }
// config.headers['deviceInfo'] = JSON.stringify({ "app_channel": "", "app_mac": "", "app_uuid": "", "app_version": "", "device_brand": "", "device_ip": "", "device_model": "", "device_net": "", "device_ops": "", "resolution_wh": "", "system_level": "", "device_type": '10' })
// }
return config;
}, error => {
Promise.reject(error);
});
);
// respone拦截器
service.interceptors.response.use(
response => {
const res = response.data;
/*
baseUrl时,返回000000为成功
apiUrl时,返回200为成功
*/
// if (res.code !== '000000') {
// return Promise.reject(response.data)
// } else {
return response.data;
// }
(response) => {
return response.data;
},
error => {
(error) => {
return Promise.reject(error);
}
);
......
/**
* Created by Anndy Yang on 18/09/18.
*/
/* eslint-disable */
import { envConfig } from '@/utils/env-config';
export function setEventByModuleCode(itemData) {
const modeCode = itemData.appModuleInfo.code || '';
let paramList = itemData.appModuleInfo.paramList ? itemData.appModuleInfo.paramList : '';
if (modeCode === 'M001' || modeCode === 'M002' || modeCode === 'M003') {
paramList = '';
} else if (modeCode === 'M100' || modeCode === 'M300') {
const urlPara = getUrlParmByCode(paramList);
paramList[0] && (paramList[0].value += urlPara);
} else if (modeCode === 'M400') {
}
if (typeof paramList === 'string' && !paramList) {
paramList = [];
}
return paramList;
const modeCode = itemData.appModuleInfo.code || '';
let paramList = itemData.appModuleInfo.paramList
? itemData.appModuleInfo.paramList
: '';
if (modeCode === 'M001' || modeCode === 'M002' || modeCode === 'M003') {
paramList = '';
} else if (modeCode === 'M100' || modeCode === 'M300') {
const urlPara = getUrlParmByCode(paramList);
paramList[0] && (paramList[0].value += urlPara);
} else if (modeCode === 'M400') {
}
if (typeof paramList === 'string' && !paramList) {
paramList = [];
}
return paramList;
}
function getUrlParmByCode(paramList) {
if (paramList.length <= 1) {
return '';
}
let dataStr = '';
const list = [];
for (let i = 1; i < paramList.length; i++) {
list.push(paramList[i].key + '=' + paramList[i].value);
}
dataStr = list.join('&');
if (dataStr !== '') {
return '?' + dataStr;
}
if (paramList.length <= 1) {
return '';
}
let dataStr = '';
const list = [];
for (let i = 1; i < paramList.length; i++) {
list.push(paramList[i].key + '=' + paramList[i].value);
}
dataStr = list.join('&');
if (dataStr !== '') {
return '?' + dataStr;
}
return '';
}
export function p_getElm(elmId) {
return document.getElementById(elmId);
return document.getElementById(elmId);
}
export function deepCopy(obj) {
var result = Array.isArray(obj) ? [] : {};
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (typeof obj[key] === 'object') {
result[key] = deepCopy(obj[key]); // 递归复制
} else {
result[key] = obj[key];
}
}
var result = Array.isArray(obj) ? [] : {};
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (typeof obj[key] === 'object') {
result[key] = deepCopy(obj[key]); // 递归复制
} else {
result[key] = obj[key];
}
}
return result;
}
return result;
}
/**
*
*
* @param {Array} originData 初始数据
* @param {Boolean} isUp true: 升序 false: 降序
* @param {String} sortField 排序字段,如果没有,则直接排序
* @param {Function} converFun 字段对应的数值转换函数
*/
export function arraySort(originData, isUp = true, sortedField, converFun) {
// debugger
const sortedData = originData.slice();
let swap, sourceA, sourceB;
for (let i = 0; i < sortedData.length - 1; i++) {
for (let j = 0; j < sortedData.length - i - 1; j++) {
sourceA = sortedData[j];
sourceB = sortedData[j + 1];
if (sortedField && !converFun) {
sourceA = sourceA[sortedField];
sourceB = sourceB[sortedField];
} else if (sortedField && converFun && typeof converFun === 'function') {
if (!sourceA[sortedField] || !sourceB[sortedField]) {
sourceA = 0;
sourceB = 0;
} else {
sourceA = converFun(sourceA[sortedField]);
sourceB = converFun(sourceB[sortedField]);
}
}
// if(!sourceA || !sourceB) {
// sourceA = 0
// sourceB = 0
// }
if (isUp) {
if ((sourceA - 0) > (sourceB - 0)) {
swap = sortedData[j];
sortedData[j] = sortedData[j + 1];
sortedData[j + 1] = swap;
}
} else {
if ((sourceA - 0) < (sourceB - 0)) {
swap = sortedData[j];
sortedData[j] = sortedData[j + 1];
sortedData[j + 1] = swap;
}
}
// debugger
const sortedData = originData.slice();
let swap, sourceA, sourceB;
for (let i = 0; i < sortedData.length - 1; i++) {
for (let j = 0; j < sortedData.length - i - 1; j++) {
sourceA = sortedData[j];
sourceB = sortedData[j + 1];
if (sortedField && !converFun) {
sourceA = sourceA[sortedField];
sourceB = sourceB[sortedField];
} else if (sortedField && converFun && typeof converFun === 'function') {
if (!sourceA[sortedField] || !sourceB[sortedField]) {
sourceA = 0;
sourceB = 0;
} else {
sourceA = converFun(sourceA[sortedField]);
sourceB = converFun(sourceB[sortedField]);
}
}
if (isUp) {
if (sourceA - 0 > sourceB - 0) {
swap = sortedData[j];
sortedData[j] = sortedData[j + 1];
sortedData[j + 1] = swap;
}
} else {
if (sourceA - 0 < sourceB - 0) {
swap = sortedData[j];
sortedData[j] = sortedData[j + 1];
sortedData[j + 1] = swap;
}
}
}
return sortedData;
}
return sortedData;
}
export function sortParmData(originData, orderCol) {
return originData.sort((a, b) => {
return (a[orderCol] - b[orderCol]) * -1;
});
return originData.sort((a, b) => {
return (a[orderCol] - b[orderCol]) * -1;
});
}
// 获取SC服务器域名地址
export function getBaseUrl(url) {
return getConfigByEnvType('baseUrl') + url;
return getConfigByEnvType('baseUrl') + url;
}
// 获取七牛token
export function getQiniuToken1() {
return getConfigByEnvType('qiniuFileUrl');
return getConfigByEnvType('qiniuFileUrl');
}
// 登录URL
export function getLoginUrl() {
return getConfigByEnvType('loginUrl');
return getConfigByEnvType('loginUrl');
}
export function getInnerLoginUrl() {
return getConfigByEnvType('innerLoginUrl');
return getConfigByEnvType('innerLoginUrl');
}
// 云鹊医首页
export function getYunQueYiUrl() {
return getConfigByEnvType('yuequeyiIndexUrl');
return getConfigByEnvType('yuequeyiIndexUrl');
}
// 七牛上传视频和图片
export function uploadVideo() {
return getConfigByEnvType('qiniuResourceUrl');
return getConfigByEnvType('qiniuResourceUrl');
}
export function uploadImg() {
return getConfigByEnvType('qiniuImgUrl');
return getConfigByEnvType('qiniuImgUrl');
}
// 根据不同环境,生成URL
function getConfigByEnvType(urlType) {
return envConfig[process.env.VUE_APP_ENV][urlType];
return envConfig[process.env.VUE_APP_ENV][urlType];
}
// 获取客服的云信ID
export function getPicaKFAccid() {
return getConfigByEnvType('picakfAccId');
return getConfigByEnvType('picakfAccId');
}
// 获取客服的云信ID
export function getPhomeDemain() {
return getConfigByEnvType('phomeDemain');
return getConfigByEnvType('phomeDemain');
}
// 根据身份证获取生日
export function getBirth(idCard) {
let birthday = '';
if (idCard != null && idCard != '') {
if (idCard.length == 15) {
birthday = '19' + idCard.slice(6, 12);
} else if (idCard.length == 18) {
birthday = idCard.slice(6, 14);
}
birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');
// 通过正则表达式来指定输出格式为:1990-01-01
let birthday = '';
if (idCard != null && idCard != '') {
if (idCard.length == 15) {
birthday = '19' + idCard.slice(6, 12);
} else if (idCard.length == 18) {
birthday = idCard.slice(6, 14);
}
return birthday;
}
\ No newline at end of file
birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');
// 通过正则表达式来指定输出格式为:1990-01-01
}
return birthday;
}
/* eslint-disable */
class RtcClient {
constructor(options) {
this.sdkAppId_ = options.sdkAppId;
......@@ -25,7 +26,7 @@ class RtcClient {
mode: 'live',
sdkAppId: this.sdkAppId_,
userId: this.userId_,
userSig: this.userSig_
userSig: this.userSig_,
});
this.handleEvents();
} catch (error) {
......@@ -43,7 +44,7 @@ class RtcClient {
try {
await this.client_.join({
roomId: this.roomId_,
role: this.role
role: this.role,
});
console.log('加入房间trtc成功');
this.isJoined_ = true;
......@@ -52,7 +53,7 @@ class RtcClient {
audio: true,
video: false,
userId: this.userId_,
mirror: true
mirror: true,
});
this.startRTC();
} catch (e) {
......@@ -69,7 +70,7 @@ class RtcClient {
width: this.vueInstance.viedoParams.webVideoWidth,
height: this.vueInstance.viedoParams.webVideoHeight,
frameRate: this.vueInstance.viedoParams.webVideoFramerate,
bitrate: this.vueInstance.viedoParams.webVideoBitrate /* kpbs */
bitrate: this.vueInstance.viedoParams.webVideoBitrate /* kpbs */,
});
// 避免重复开摄像头
this.stopPush();
......@@ -86,29 +87,32 @@ class RtcClient {
return;
}
try {
this.localStream_.initialize().catch(error => {
this.vueInstance.$message({
message: '打开设备失败,请检查您的设备!',
type: 'error'
});
console.error('failed initialize localStream ' + error);
}).then(() => {
// 本地流在主播放器上播放,并且插入到一个关联的box中
// var localVideoWrapEl = document.getElementById('ask');
// this.localStream_.play(localVideoWrapEl, {
// muted: true
// });
// 主播直接推流
if (this.role == 'anchor') {
this.publish();
}
}).catch(error => {
this.vueInstance.$message({
message: '麦克风打开失败!',
type: 'error'
this.localStream_
.initialize()
.catch((error) => {
this.vueInstance.$message({
message: '打开设备失败,请检查您的设备!',
type: 'error',
});
console.error('failed initialize localStream ' + error);
})
.then(() => {
// 本地流在主播放器上播放,并且插入到一个关联的box中
// var localVideoWrapEl = document.getElementById('ask');
// this.localStream_.play(localVideoWrapEl, {
// muted: true
// });
// 主播直接推流
if (this.role == 'anchor') {
this.publish();
}
})
.catch((error) => {
this.vueInstance.$message({
message: '麦克风打开失败!',
type: 'error',
});
});
});
} catch (e) {
this.isPublished_ = false;
}
......@@ -117,17 +121,21 @@ class RtcClient {
// 发布本地流
async publish() {
this.client_ && this.client_.publish(this.localStream_).then(() => {
console.log('本地流发布成功');
this.isPublished_ = true;
// 手动将麦克风打开
this.unmuteLocalAudio();
this.vueInstance.isMicOn = true;
}).catch(error => {
console.log('本地流发布失败');
this.isPublished_ = false;
this.vueInstance.reloadfn();
});
this.client_ &&
this.client_
.publish(this.localStream_)
.then(() => {
console.log('本地流发布成功');
this.isPublished_ = true;
// 手动将麦克风打开
this.unmuteLocalAudio();
this.vueInstance.isMicOn = true;
})
.catch((error) => {
console.log('本地流发布失败');
this.isPublished_ = false;
this.vueInstance.reloadfn();
});
}
/**
......@@ -135,11 +143,11 @@ class RtcClient {
*/
async stopPush() {
if (this.localStream_ && this.isPublished_ && this.isJoined_) {
this.client_.unpublish(this.localStream_).then(() => {
this.isPublished_ = false;
this.localStream_.stop();
this.setLocalVideo();
});
this.client_.unpublish(this.localStream_).then(() => {
this.isPublished_ = false;
this.localStream_.stop();
this.setLocalVideo();
});
} else {
this.setLocalVideo();
}
......@@ -217,8 +225,10 @@ class RtcClient {
// client的一些事件监听
handleEvents() {
// 报错
this.client_.on('error', err => {
console.log('client 报错了--------------------------------------------------------------');
this.client_.on('error', (err) => {
console.log(
'client 报错了--------------------------------------------------------------'
);
console.log(err);
const params = {
roomID: this.roomId_, // 房间id
......@@ -229,14 +239,14 @@ class RtcClient {
this.$sendBuriedData({
action: 'TRTC',
component_tag: 'TRTC#0',
web_data: params
web_data: params,
});
// alert(err);
window.onbeforeunload = null;
location.reload();
});
this.client_.on('network-quality', event => {
this.client_.on('network-quality', (event) => {
console.log('--network-quality', event);
const params = {
roomID: this.roomId_, // 房间id
......@@ -247,9 +257,9 @@ class RtcClient {
this.$sendBuriedData({
action: 'TRTC',
component_tag: 'TRTC#0',
web_data: params
web_data: params,
});
this.client_.getLocalAudioStats().then(stats => {
this.client_.getLocalAudioStats().then((stats) => {
const params = {
roomID: this.roomId_, // 房间id
viewslist: this.viewslist, // 当前房间用户列表
......@@ -259,10 +269,10 @@ class RtcClient {
this.$sendBuriedData({
action: 'TRTC',
component_tag: 'TRTC#0',
web_data: params
web_data: params,
});
});
this.client_.getRemoteAudioStats().then(stats => {
this.client_.getRemoteAudioStats().then((stats) => {
const params = {
roomID: this.roomId_, // 房间id
viewslist: this.viewslist, // 当前房间用户列表
......@@ -272,32 +282,31 @@ class RtcClient {
this.$sendBuriedData({
action: 'TRTC',
component_tag: 'TRTC#0',
web_data: params
web_data: params,
});
});
});
// 房间被解散了
this.client_.on('client-banned', err => {
this.client_.on('client-banned', (err) => {
console.log('房间被解散了');
});
// 当一个远程同伴(必须推流)进入房间时触发
this.client_.on('peer-join', evt => {
this.client_.on('peer-join', (evt) => {
const userId = evt.userId;
console.log('有远程同伴进入房间:', userId);
});
// 当远处的同伴离开房间时触发(删减好友列表)
this.client_.on('peer-leave', evt => {
this.client_.on('peer-leave', (evt) => {
const userId = evt.userId;
console.log('有远程同伴离开房间:' + userId);
this.remove(userId);
});
// 在添加远程流时触发
this.client_.on('stream-added', evt => {
this.client_.on('stream-added', (evt) => {
const remoteStream = evt.stream;
// 获取流的StreamId
const id = remoteStream.getId();
......@@ -305,19 +314,21 @@ class RtcClient {
const userId = remoteStream.getUserId();
this.members_.set(userId, remoteStream);
this.inmembers_.set(userId, remoteStream);
console.log(`remote stream added: [${userId}] ID: ${id} type: ${remoteStream.getType()}`);
console.log(
`remote stream added: [${userId}] ID: ${id} type: ${remoteStream.getType()}`
);
// 我们订阅远端的流
console.log('subscribe to this remote stream');
this.client_.subscribe(remoteStream);
});
// 在订阅远程流时触发
this.client_.on('stream-subscribed', evt => {
this.client_.on('stream-subscribed', (evt) => {
const remoteStream = evt.stream;
const id = remoteStream.getId();
const uid = remoteStream.userId_;
this.remoteStreams_.push(remoteStream);
remoteStream.on('player-state-changed', event => {
remoteStream.on('player-state-changed', (event) => {
console.log(`${event.type} player is ${event.state}`);
// 远端流是播放还是暂停状态(显示按钮等画面不同)
if (event.type == 'video' && event.state == 'STOPPED') {
......@@ -334,46 +345,44 @@ class RtcClient {
}
});
// 避免重复加载
for (let i = 0; i < this.viewslist.length; i++) {
if (this.viewslist[i] && uid == this.viewslist[i].userId) {
return;
}
// 避免重复加载
for (let i = 0; i < this.viewslist.length; i++) {
if (this.viewslist[i] && uid == this.viewslist[i].userId) {
return;
}
const isMask = false;
// this.viewslist.push({ id: id, userId: uid, nick: uid, mask: isMask, vioce: true })
this.add(id, uid, isMask);
this.vueInstance.addNewMember(uid);
setTimeout(() => {
// 避免其他乱入视频
const index = this.viewslist.findIndex((item => {
if (item && item.userId) {
return item.userId == uid;
} else {
return -1;
}
}));
if (index < 0) {
return;
}
// 播放视频
remoteStream.play(id);
if (!remoteStream.hasVideo()) {
this.changeView(id, 'mask', true);
}
if (!remoteStream.hasAudio()) {
this.changeView(id, 'vioce', false);
}
const isMask = false;
// this.viewslist.push({ id: id, userId: uid, nick: uid, mask: isMask, vioce: true })
this.add(id, uid, isMask);
this.vueInstance.addNewMember(uid);
setTimeout(() => {
// 避免其他乱入视频
const index = this.viewslist.findIndex((item) => {
if (item && item.userId) {
return item.userId == uid;
} else {
return -1;
}
}, 1000);
});
if (index < 0) {
return;
}
// 播放视频
remoteStream.play(id);
if (!remoteStream.hasVideo()) {
this.changeView(id, 'mask', true);
}
if (!remoteStream.hasAudio()) {
this.changeView(id, 'vioce', false);
}
}, 1000);
});
// 当远程流被移除时触发
this.client_.on('stream-removed', evt => {
this.client_.on('stream-removed', (evt) => {
const remoteStream = evt.stream;
const id = remoteStream.getId();
const uid = remoteStream.userId_;
......@@ -381,14 +390,14 @@ class RtcClient {
// 停止播放并删除相应<video>标签
remoteStream.stop();
this.inmembers_.delete(uid);
this.remoteStreams_ = this.remoteStreams_.filter(stream => {
this.remoteStreams_ = this.remoteStreams_.filter((stream) => {
return stream.getId() !== id;
});
this.remove(uid);
});
// 流更新
this.client_.on('stream-updated', evt => {
this.client_.on('stream-updated', (evt) => {
console.log('=========流更新========stream-updated===================');
console.log(evt);
const remoteStream = evt.stream;
......@@ -396,37 +405,52 @@ class RtcClient {
// remoteStream.hasVideo() // 是否有视频轨道
// remoteStream.hasAudio() //是否有音轨道
// remoteStream.getType() // 主要用于判断一个远端流是主音视频流还是辅路视频流,辅路视频流通常是一个屏幕分享流。
console.log('remoteStream ID: ' + remoteStream.getId() + ' was updated hasAudio: ' +
remoteStream.hasAudio() + ' hasVideo: ' + remoteStream.hasVideo());
console.log(
'remoteStream ID: ' +
remoteStream.getId() +
' was updated hasAudio: ' +
remoteStream.hasAudio() +
' hasVideo: ' +
remoteStream.hasVideo()
);
});
// 关闭音轨道
this.client_.on('mute-audio', evt => {
this.client_.on('mute-audio', (evt) => {
this.changeView(evt.userId, 'vioce', false);
console.log(evt.userId + '关闭麦克风============================================');
console.log(
evt.userId + '关闭麦克风============================================'
);
});
// 打开音轨道
this.client_.on('unmute-audio', evt => {
this.client_.on('unmute-audio', (evt) => {
this.changeView(evt.userId, 'vioce', true);
if (evt.type == 'audio' && evt.state == 'PLAYING' && this.vueInstance.type == 1) {
if (
evt.type == 'audio' &&
evt.state == 'PLAYING' &&
this.vueInstance.type == 1
) {
this.changeView(evt.userId, 'mask', true);
}
});
// 关闭视频轨道
this.client_.on('mute-video', evt => {
console.log(evt.userId + '关闭 video==============================================');
this.client_.on('mute-video', (evt) => {
console.log(
evt.userId + '关闭 video=============================================='
);
this.changeView(evt.userId, 'mask', true);
});
// 打开视频轨道
this.client_.on('unmute-video', evt => {
console.log(evt.userId + '打开 video=============================================');
this.client_.on('unmute-video', (evt) => {
console.log(
evt.userId + '打开 video============================================='
);
if (this.members_.get(evt.userId)) {
this.changeView(evt.userId, 'mask', false);
}
});
}
......@@ -440,7 +464,7 @@ class RtcClient {
// 移除视频数组
remove(userId) {
for(let i = 0; i < this.viewslist.length; i++) {
for (let i = 0; i < this.viewslist.length; i++) {
if (this.viewslist[i] && this.viewslist[i].userId == userId) {
this.viewslist[i] = null;
}
......@@ -450,7 +474,10 @@ class RtcClient {
// 改变视频数组属性
changeView(id, attr, val) {
for (let i = 0; i < this.viewslist.length; i++) {
if (this.viewslist[i] && (this.viewslist[i].userId == id || this.viewslist[i].id == id)) {
if (
this.viewslist[i] &&
(this.viewslist[i].userId == id || this.viewslist[i].id == id)
) {
this.viewslist[i][attr] = val;
}
}
......@@ -459,7 +486,13 @@ class RtcClient {
add(id, uid, isMask) {
this.vueInstance.memberList.forEach((ele, index) => {
if (ele.liveUserId == uid) {
this.viewslist[index] = { id: id, userId: uid, nick: uid, mask: isMask, vioce: true };
this.viewslist[index] = {
id: id,
userId: uid,
nick: uid,
mask: isMask,
vioce: true,
};
}
});
}
......
/* eslint-disable */
/* 浏览器兼容提示 */
export const CHECK_BROWSER_TIPS = {
BROWSER_NOT_COMPATIBLE: '您的浏览器不支持直播功能!',
BROWSER_NOT_SUPPORT_SCREEN_SHARE: '您的浏览器不支持直播功能!'
BROWSER_NOT_SUPPORT_SCREEN_SHARE: '您的浏览器不支持直播功能!',
};
export const setLgTenText = time => {
export const setLgTenText = (time) => {
return time < 10 ? `0${time}` : time;
};
......@@ -21,11 +22,13 @@ export const countDown = (endtime) => {
const nowtime = new Date(); // 获取当前时间
const time = endtime - nowtime.getTime(); // 距离结束时间的毫秒数
if (time > 0) {
const lefth = Math.floor(time / (1000 * 60 * 60) % 24); // 计算小时数
const leftm = Math.floor(time / (1000 * 60) % 60); // 计算分钟数
const lefts = Math.floor(time / 1000 % 60); // 计算秒数
// 返回倒计时的字符串
return `${setLgTenText(lefth)}:${setLgTenText(leftm)}:${setLgTenText(lefts)}`;
const lefth = Math.floor((time / (1000 * 60 * 60)) % 24); // 计算小时数
const leftm = Math.floor((time / (1000 * 60)) % 60); // 计算分钟数
const lefts = Math.floor((time / 1000) % 60); // 计算秒数
// 返回倒计时的字符串
return `${setLgTenText(lefth)}:${setLgTenText(leftm)}:${setLgTenText(
lefts
)}`;
} else {
return '时间已到';
}
......@@ -34,20 +37,20 @@ export const countDown = (endtime) => {
export const laseTime = (endtime) => {
const nowtime = new Date(); // 获取当前时间
const time = endtime - nowtime.getTime(); // 距离结束时间的毫秒数
const lefth = Math.floor(time / (1000 * 60 * 60) % 24); // 计算小时数
const leftm = Math.floor(time / (1000 * 60) % 60); // 计算分钟数
const lefts = Math.floor(time / 1000 % 60); // 计算秒数
const lefth = Math.floor((time / (1000 * 60 * 60)) % 24); // 计算小时数
const leftm = Math.floor((time / (1000 * 60)) % 60); // 计算分钟数
const lefts = Math.floor((time / 1000) % 60); // 计算秒数
return {
lefth,
leftm,
lefts
lefts,
};
};
export const lastm = (startTime, endTime) => {
const time = endTime - startTime; // 距离结束时间的毫秒数
const lefth = Math.floor(time / (1000 * 60 * 60) % 24); // 计算小时数
const leftm = Math.floor(time / (1000 * 60) % 60); // 计算分钟数
const lefth = Math.floor((time / (1000 * 60 * 60)) % 24); // 计算小时数
const leftm = Math.floor((time / (1000 * 60)) % 60); // 计算分钟数
return lefth * 60 + leftm;
};
......@@ -69,10 +72,10 @@ export const listSort = (one, two, three, four, arr) => {
const a = h.sort(listCompare(three));
const b = a.sort(listCompare(two));
newList = b.sort(listCompare(one, 1));
newList.forEach(item => {
newList.forEach((item) => {
if (item.isCalling) {
callArr.push(item);
}
}
if (item.inviteCall) {
inviteArr.push(item);
}
......@@ -80,7 +83,7 @@ export const listSort = (one, two, three, four, arr) => {
return {
newList,
callArr,
inviteArr
inviteArr,
};
};
......@@ -93,13 +96,21 @@ export const getBroswer = () => {
const sys = {};
const ua = navigator.userAgent.toLowerCase();
let s;
(s = ua.match(/edge\/([\d.]+)/)) ? sys.edge = s[1] :
(s = ua.match(/rv:([\d.]+)\) like gecko/)) ? sys.ie = s[1] :
(s = ua.match(/msie ([\d.]+)/)) ? sys.ie = s[1] :
(s = ua.match(/firefox\/([\d.]+)/)) ? sys.firefox = s[1] :
(s = ua.match(/chrome\/([\d.]+)/)) ? sys.chrome = s[1] :
(s = ua.match(/opera.([\d.]+)/)) ? sys.opera = s[1] :
(s = ua.match(/version\/([\d.]+).*safari/)) ? sys.safari = s[1] : 0;
(s = ua.match(/edge\/([\d.]+)/))
? (sys.edge = s[1])
: (s = ua.match(/rv:([\d.]+)\) like gecko/))
? (sys.ie = s[1])
: (s = ua.match(/msie ([\d.]+)/))
? (sys.ie = s[1])
: (s = ua.match(/firefox\/([\d.]+)/))
? (sys.firefox = s[1])
: (s = ua.match(/chrome\/([\d.]+)/))
? (sys.chrome = s[1])
: (s = ua.match(/opera.([\d.]+)/))
? (sys.opera = s[1])
: (s = ua.match(/version\/([\d.]+).*safari/))
? (sys.safari = s[1])
: 0;
if (sys.edge) return { broswer: 'Edge', version: sys.edge };
if (sys.ie) return { broswer: 'IE', version: sys.ie };
......@@ -109,4 +120,4 @@ export const getBroswer = () => {
if (sys.safari) return { broswer: 'Safari', version: sys.safari };
return { broswer: '', version: '0' };
};
\ No newline at end of file
};
import {isEmptyUtils, isNotEmptyUtils, subString} from './utils';
/* eslint-disable */
import { isEmptyUtils, isNotEmptyUtils, subString } from './utils';
import fetchQiniu from './fetch-qiniu.js';
import { getQiniuToken1, uploadVideo, uploadImg } from './index';
const qiniu = require('qiniu-js');
......@@ -9,12 +10,12 @@ let subscription = null;
// 上传返回结果
const result = {
key: null, // 文件保存在空间中的资源名
path: null, // 保存到db的路径(不带域名)
fullPath: null, // 文件网络路径(文件url)
size: null, // 资源尺寸,单位为字节
name: null, // 原始文件名
ext: null// 上传资源的后缀名,通过自动检测的mimeType 或者原文件的后缀来获取
key: null, // 文件保存在空间中的资源名
path: null, // 保存到db的路径(不带域名)
fullPath: null, // 文件网络路径(文件url)
size: null, // 资源尺寸,单位为字节
name: null, // 原始文件名
ext: null, // 上传资源的后缀名,通过自动检测的mimeType 或者原文件的后缀来获取
};
// 上传状态
......@@ -26,57 +27,58 @@ const domain = uploadVideo(); // 视频
const domain1 = uploadImg(); // 图片
const errorCode = new Map([
[298, '部分操作执行成功'],
[400, '请求报文格式错误'],
[401, '认证授权失败'],
[403, '权限不足,拒绝访问。'],
[404, '资源不存在'],
[405, '请求方式错误'],
[406, '上传的数据 CRC32 校验错误'],
[413, '请求资源大小大于指定的最大值'],
[419, '用户账号被冻结'],
[478, '镜像回源失败'],
[502, '错误网关'],
[503, '服务端不可用'],
[504, '服务端操作超时'],
[573, '单个资源访问频率过高'],
[579, '上传成功但是回调失败'],
[599, '服务端操作失败'],
[608, '资源内容被修改'],
[612, '指定资源不存在或已被删除'],
[614, '目标资源已存在'],
[630, '已创建的空间数量达到上限,无法创建新空间。'],
[631, '指定空间不存在'],
[640, '调用列举资源(list)接口时,指定非法的marker参数。'],
[701, '在断点续上传过程中,后续上传接收地址不正确或ctx信息已过期。']
[298, '部分操作执行成功'],
[400, '请求报文格式错误'],
[401, '认证授权失败'],
[403, '权限不足,拒绝访问。'],
[404, '资源不存在'],
[405, '请求方式错误'],
[406, '上传的数据 CRC32 校验错误'],
[413, '请求资源大小大于指定的最大值'],
[419, '用户账号被冻结'],
[478, '镜像回源失败'],
[502, '错误网关'],
[503, '服务端不可用'],
[504, '服务端操作超时'],
[573, '单个资源访问频率过高'],
[579, '上传成功但是回调失败'],
[599, '服务端操作失败'],
[608, '资源内容被修改'],
[612, '指定资源不存在或已被删除'],
[614, '目标资源已存在'],
[630, '已创建的空间数量达到上限,无法创建新空间。'],
[631, '指定空间不存在'],
[640, '调用列举资源(list)接口时,指定非法的marker参数。'],
[701, '在断点续上传过程中,后续上传接收地址不正确或ctx信息已过期。'],
]);
const qiniuErrorCheck = function (code) {
errorCode.forEach(function (value, key, map) {
if (code === key) {
console.error(key + ':' + value);
}
});
errorCode.forEach(function (value, key, map) {
if (code === key) {
console.error(key + ':' + value);
}
});
};
// 用来限制上传文件类型,为 null 时表示不对文件类型限制;限制类型放到数组里: ["image/png", "image/jpeg", "image/gif"]
const mimeTypeArray = null;
export const createFilePath = (file, fileName) => {
if (isEmptyUtils(file)) {
return null;
}
const arr = fileName.split('_');
if(arr.length != 4) {
alert('上传视频文件名格式不正确');
return null;
}
const arr4 = arr[3].split('.');
// 文件全路径(文件路径 + 文件名) 扩展名​/年/月/日/
const filePath = arr[0] + '/' + arr[1] + '/' + arr[2] + '_' + arr4[0] + '.' + arr4[1];
console.log(filePath);
return filePath;
if (isEmptyUtils(file)) {
return null;
}
const arr = fileName.split('_');
if (arr.length != 4) {
alert('上传视频文件名格式不正确');
return null;
}
const arr4 = arr[3].split('.');
// 文件全路径(文件路径 + 文件名) 扩展名​/年/月/日/
const filePath =
arr[0] + '/' + arr[1] + '/' + arr[2] + '_' + arr4[0] + '.' + arr4[1];
console.log(filePath);
return filePath;
};
/**
......@@ -85,29 +87,31 @@ export const createFilePath = (file, fileName) => {
* @return {Promise} token 七牛上传凭证
* */
const doQiniuAction1 = (fileType) => {
console.log('send---' + fileApiUrl);
return new Promise(function (resolve, reject) {
// if(isEmptyUtils(localStorage.getItem('qiniuToken'))){
fetchQiniu(fileApiUrl, {'fileType': fileType}, 'GET').then(function (result) {
let token = null;
if (isNotEmptyUtils(result) && result.code == '000000') {
token = result.data.qiniuToken;
resolve(token);
console.log('七牛临时授权成功');
localStorage.setItem('qiniuToken', token);
} else {
reject(result);
console.error('七牛临时授权失败:', result);
}
}).catch(function (error) {
reject();
console.error('七牛临时授权失败:', error);
});
// }else{
// console.log('从localStorage获取token:'+localStorage.getItem('qiniuToken'))
// resolve(localStorage.getItem('qiniuToken'));
// }
});
console.log('send---' + fileApiUrl);
return new Promise(function (resolve, reject) {
// if(isEmptyUtils(localStorage.getItem('qiniuToken'))){
fetchQiniu(fileApiUrl, { fileType: fileType }, 'GET')
.then(function (result) {
let token = null;
if (isNotEmptyUtils(result) && result.code == '000000') {
token = result.data.qiniuToken;
resolve(token);
console.log('七牛临时授权成功');
localStorage.setItem('qiniuToken', token);
} else {
reject(result);
console.error('七牛临时授权失败:', result);
}
})
.catch(function (error) {
reject();
console.error('七牛临时授权失败:', error);
});
// }else{
// console.log('从localStorage获取token:'+localStorage.getItem('qiniuToken'))
// resolve(localStorage.getItem('qiniuToken'));
// }
});
};
/**
......@@ -120,124 +124,121 @@ const doQiniuAction1 = (fileType) => {
* @returns {Promise}
*/
export const qiniuUpload = (self, file, filePath, previewId, progressId) => {
// var deferred = $q.defer();
// var deferred = $q.defer();
return new Promise(function (resolve, reject) {
return new Promise(function (resolve, reject) {
if (isEmptyUtils(file) || isEmptyUtils(filePath)) {
console.error('七牛上传失败:非法参数');
reject();
}
if (isEmptyUtils(file) || isEmptyUtils(filePath)) {
console.error('七牛上传失败:非法参数');
reject();
const key = filePath ? filePath : getFilePath(file);
// 修改状态为上传
self.qiniuUploadStatus = true;
// let token = "BRVB4TpxVFA5Wo6lIpfltmWKOltzGar46tvC3BlR:UHn0LDElwjP4jEZTXdq_1qV6_hw=:eyJzY29wZSI6InBpY2EtdGVzdCIsInJldHVybkJvZHkiOiJ7XCJrZXlcIjpcIiQoa2V5KVwiLFwiaGFzaFwiOlwiJChldGFnKVwiLFwiYnVja2V0XCI6XCIkKGJ1Y2tldClcIixcImZzaXplXCI6JChmc2l6ZSksXCJmbmFtZVwiOiQoZm5hbWUpLFwiZXh0XCI6JChleHQpfSIsImRlYWRsaW5lIjoxNTI5NDk0MTc1fQ==";
doQiniuAction().then(function (token) {
const putExtra = {
fname: file.name, // 原文件名
params: {}, // 用来放置自定义变量
mimeType: mimeTypeArray || null, // null || array,用来限制上传文件类型,为 null 时表示不对文件类型限制;限制类型放到数组里: ["image/png", "image/jpeg", "image/gif"]
};
const config = {
useCdnDomain: true, // 表示是否使用 cdn 加速域名,为布尔值,true 表示使用,默认为 false。
region: null, // 选择上传域名区域;当为 null 或 undefined 时,自动分析上传域名区域
};
/*
* qiniu.upload 返回一个 observable 对象用来控制上传行为,observable 对像通过 subscribe 方法可以被 observer 所订阅,
* 订阅同时会开始触发上传,同时返回一个 subscription 对象,该对象有一个 unsubscribe 方法取消订阅,同时终止上传行为。
* */
const observable = qiniu.upload(file, key, token, putExtra, config);
/**
* 接收上传进度信息,res 参数是一个带有 total 字段的 object,包含loaded、total、percent三个属性,提供上传进
* total.loaded: number,已上传大小,单位为字节。
* total.total: number,本次上传的总量控制信息,单位为字节,注意这里的 total 跟文件大小并不一致。
* total.percent: number,当前上传进度,范围:0~100
* */
const next = function (res) {
// res值{"total":{"loaded":18184,"size":18185,"percent":99.99450096233159}}
// 获取百分比进度
const progress = res.total.percent.toFixed(2);
self.uploadProgress = Number(progress);
console.log('Progress1: ' + progress);
};
/**
* 接收上传完成后的后端返回信息,res 参数为一个 object, 为上传成功后后端返回的信息
* ,具体返回结构取决于后端sdk的配置,可参考上传策略(https://developer.qiniu.com/kodo/manual/1206/put-policy)
* */
const complete = function (res) {
console.log('七牛上传完成');
setTimeout(function () {
result.key = res.key;
result.path = '/' + res.key;
result.fullPath =
domain + '/' + res.key + '?v=' + new Date().getTime();
result.size = res.fsize;
result.name = res.fname;
result.ext = res.ext;
resolve(result);
self.qiniuUploadStatus = false;
if (isNotEmptyUtils(previewId)) {
const address = domain + result.path;
console.log('文件路径: ' + address);
// 显示图片
const $img = $('<img>').attr('src', address);
const obj = $('#' + previewId);
obj.empty().append($img);
obj.css('max-width', '100%');
}
}, 2000);
};
/**
* 上传错误后触发,当不是 xhr 请求错误时,会把当前错误产生原因直接抛出,诸如 JSON 解析异常等;当产生 xhr 请求错误时,参数 err 为一个包含 code、message、isRequestError 三个属性的 object:
* err.isRequestError: 用于区分是否 xhr 请求错误;当 xhr 请求出现错误并且后端通过 HTTP 状态码返回了错误信息时,该参数为 true;否则为 undefined 。
* err.reqId: string,xhr请求错误的 X-Reqid。
* err.code: number,请求错误状态码,只有在 err.isRequestError 为 true 的时候才有效,可查阅码值对应说明。
* err.message: string,错误信息,包含错误码,当后端返回提示信息时也会有相应的错误信息。
* */
const error = function (err) {
// 修改状态为非上传
// status = false;
self.qiniuUploadStatus = false;
localStorage.removeItem('qiniuToken');
console.log(
'七牛上传失败,详细信息请参考:https://developer.qiniu.com/kodo/api/3928/error-responses'
);
// 输出简略错误信息
if (err.isRequestError) {
qiniuErrorCheck(err.code);
} else {
console.error(err);
}
const key = filePath ? filePath : getFilePath(file);
// 修改状态为上传
self.qiniuUploadStatus = true;
// let token = "BRVB4TpxVFA5Wo6lIpfltmWKOltzGar46tvC3BlR:UHn0LDElwjP4jEZTXdq_1qV6_hw=:eyJzY29wZSI6InBpY2EtdGVzdCIsInJldHVybkJvZHkiOiJ7XCJrZXlcIjpcIiQoa2V5KVwiLFwiaGFzaFwiOlwiJChldGFnKVwiLFwiYnVja2V0XCI6XCIkKGJ1Y2tldClcIixcImZzaXplXCI6JChmc2l6ZSksXCJmbmFtZVwiOiQoZm5hbWUpLFwiZXh0XCI6JChleHQpfSIsImRlYWRsaW5lIjoxNTI5NDk0MTc1fQ==";
doQiniuAction().then(function (token) {
const putExtra = {
fname: file.name, // 原文件名
params: {}, // 用来放置自定义变量
mimeType: mimeTypeArray || null // null || array,用来限制上传文件类型,为 null 时表示不对文件类型限制;限制类型放到数组里: ["image/png", "image/jpeg", "image/gif"]
};
const config = {
useCdnDomain: true, // 表示是否使用 cdn 加速域名,为布尔值,true 表示使用,默认为 false。
region: null // 选择上传域名区域;当为 null 或 undefined 时,自动分析上传域名区域
};
/*
* qiniu.upload 返回一个 observable 对象用来控制上传行为,observable 对像通过 subscribe 方法可以被 observer 所订阅,
* 订阅同时会开始触发上传,同时返回一个 subscription 对象,该对象有一个 unsubscribe 方法取消订阅,同时终止上传行为。
* */
const observable = qiniu.upload(file, key, token, putExtra, config);
/**
* 接收上传进度信息,res 参数是一个带有 total 字段的 object,包含loaded、total、percent三个属性,提供上传进
* total.loaded: number,已上传大小,单位为字节。
* total.total: number,本次上传的总量控制信息,单位为字节,注意这里的 total 跟文件大小并不一致。
* total.percent: number,当前上传进度,范围:0~100
* */
const next = function (res) {
// res值{"total":{"loaded":18184,"size":18185,"percent":99.99450096233159}}
// 获取百分比进度
const progress = res.total.percent.toFixed(2);
self.uploadProgress = Number(progress);
console.log('Progress1: ' + progress);
};
/**
* 接收上传完成后的后端返回信息,res 参数为一个 object, 为上传成功后后端返回的信息
* ,具体返回结构取决于后端sdk的配置,可参考上传策略(https://developer.qiniu.com/kodo/manual/1206/put-policy)
* */
const complete = function (res) {
console.log('七牛上传完成');
setTimeout(function() {
result.key = res.key;
result.path = '/' + res.key;
result.fullPath = domain + '/' + res.key + '?v=' + new Date().getTime();
result.size = res.fsize;
result.name = res.fname;
result.ext = res.ext;
resolve(result);
self.qiniuUploadStatus = false;
if (isNotEmptyUtils(previewId)) {
const address = domain + result.path;
console.log('文件路径: ' + address);
// 显示图片
const $img = $('<img>').attr('src', address);
const obj = $('#' + previewId);
obj.empty().append($img);
obj.css('max-width', '100%');
}
}, 2000);
};
/**
* 上传错误后触发,当不是 xhr 请求错误时,会把当前错误产生原因直接抛出,诸如 JSON 解析异常等;当产生 xhr 请求错误时,参数 err 为一个包含 code、message、isRequestError 三个属性的 object:
* err.isRequestError: 用于区分是否 xhr 请求错误;当 xhr 请求出现错误并且后端通过 HTTP 状态码返回了错误信息时,该参数为 true;否则为 undefined 。
* err.reqId: string,xhr请求错误的 X-Reqid。
* err.code: number,请求错误状态码,只有在 err.isRequestError 为 true 的时候才有效,可查阅码值对应说明。
* err.message: string,错误信息,包含错误码,当后端返回提示信息时也会有相应的错误信息。
* */
const error = function (err) {
// 修改状态为非上传
// status = false;
self.qiniuUploadStatus = false;
localStorage.removeItem('qiniuToken');
console.log('七牛上传失败,详细信息请参考:https://developer.qiniu.com/kodo/api/3928/error-responses');
// 输出简略错误信息
if (err.isRequestError) {
qiniuErrorCheck(err.code);
}else {
console.error(err);
}
/* modalClick("提示", "上传失败!", "确定", function () {
/* modalClick("提示", "上传失败!", "确定", function () {
$('#model-modify').modal('hide');
}, "", null);*/
// deferred.reject(new Error('七牛上传失败'));
// return deferred.promise;
return reject(new Error('七牛上传失败'));
};
// 上传开始
subscription = observable.subscribe(next, error, complete);
});
// deferred.reject(new Error('七牛上传失败'));
// return deferred.promise;
return reject(new Error('七牛上传失败'));
};
// 上传开始
subscription = observable.subscribe(next, error, complete);
});
// return deferred.promise;
});
};
/**
......@@ -246,25 +247,38 @@ export const qiniuUpload = (self, file, filePath, previewId, progressId) => {
* @return {String} timeStamp时间戳 格式:yyyyMMddhhmmssS
*/
const timeStamp = (date) => {
if (isEmptyUtils(date)) {
return new Date().format('yyyyMMddhhmmssS');
}
if (isEmptyUtils(date)) {
return new Date().format('yyyyMMddhhmmssS');
}
return date.format('yyyyMMddhhmmssS');
return date.format('yyyyMMddhhmmssS');
};
/**
* 获取全局唯一标识符(GUID,Globally Unique Identifier)
* @return {String} guid
*/
const guid = () => {
/**
* @return {String}
*/
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4());
/**
* @return {String}
*/
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (
S4() +
S4() +
'-' +
S4() +
'-' +
S4() +
'-' +
S4() +
'-' +
S4() +
S4() +
S4()
);
};
/**
* 文件重命名--七牛图片 2018 11
......@@ -274,31 +288,30 @@ const guid = () => {
* @return {String} fileName
*/
export const getFilePath = (file, fileName, folder) => {
if (isEmptyUtils(file)) {
return null;
}
// 文件类型
var ext = file.type;
// 后缀名
var suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
// 若为空则从name中获取---对wps格式的文件获取不到file.type
if (isEmptyUtils(ext)) {
ext = suffix;
}
// 获取当前日期对象
var date = new Date();
if (isEmptyUtils(fileName)) {
// 重命名后的文件名
fileName = timeStamp(date) + '-' + subString(guid(), 8) + '.' + suffix;
}
// 文件全路径(文件路径 + 文件名) 扩展名​/年/月/日/
// var filePath = ext + "/" + date.format('yyyy/MM/dd') + "/" + (isEmptyUtils(folder) ? "" : (folder + "/")) + fileName;
// var filePath = ext + "/" + "common/" + file.name.split('.')[0] + '-' + timeStamp(date) + "." + suffix;
var filePath = ext + '/' + 'admin/im/' + timeStamp(date) + '.' + suffix;
console.log('filePath==============', filePath);
return filePath;
if (isEmptyUtils(file)) {
return null;
}
// 文件类型
var ext = file.type;
// 后缀名
var suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
// 若为空则从name中获取---对wps格式的文件获取不到file.type
if (isEmptyUtils(ext)) {
ext = suffix;
}
// 获取当前日期对象
var date = new Date();
if (isEmptyUtils(fileName)) {
// 重命名后的文件名
fileName = timeStamp(date) + '-' + subString(guid(), 8) + '.' + suffix;
}
// 文件全路径(文件路径 + 文件名) 扩展名​/年/月/日/
// var filePath = ext + "/" + date.format('yyyy/MM/dd') + "/" + (isEmptyUtils(folder) ? "" : (folder + "/")) + fileName;
// var filePath = ext + "/" + "common/" + file.name.split('.')[0] + '-' + timeStamp(date) + "." + suffix;
var filePath = ext + '/' + 'admin/im/' + timeStamp(date) + '.' + suffix;
console.log('filePath==============', filePath);
return filePath;
};
/**
......@@ -311,109 +324,119 @@ export const getFilePath = (file, fileName, folder) => {
* @param fileType 1--图片和文件 空为视频
* @returns {Promise}
*/
export const doUpload = (self, file, filePath, previewId, progressId, fileType) => {
return new Promise(function (resolve, reject) {
if (isEmptyUtils(file) || isEmptyUtils(filePath)) {
console.error('七牛上传失败:非法参数');
reject();
export const doUpload = (
self,
file,
filePath,
previewId,
progressId,
fileType
) => {
return new Promise(function (resolve, reject) {
if (isEmptyUtils(file) || isEmptyUtils(filePath)) {
console.error('七牛上传失败:非法参数');
reject();
}
const key = filePath ? filePath : getFilePath(file);
// 修改状态为上传
self.qiniuUploadStatus = true;
doQiniuAction1(fileType).then(function (token) {
const putExtra = {
fname: file.name, // 原文件名
params: {}, // 用来放置自定义变量
mimeType: mimeTypeArray || null, // null || array,用来限制上传文件类型,为 null 时表示不对文件类型限制;限制类型放到数组里: ["image/png", "image/jpeg", "image/gif"]
};
const config = {
useCdnDomain: true, // 表示是否使用 cdn 加速域名,为布尔值,true 表示使用,默认为 false。
region: null, // 选择上传域名区域;当为 null 或 undefined 时,自动分析上传域名区域
};
/*
* qiniu.upload 返回一个 observable 对象用来控制上传行为,observable 对像通过 subscribe 方法可以被 observer 所订阅,
* 订阅同时会开始触发上传,同时返回一个 subscription 对象,该对象有一个 unsubscribe 方法取消订阅,同时终止上传行为。
* */
const observable = qiniu.upload(file, key, token, putExtra, config);
/**
* 接收上传进度信息,res 参数是一个带有 total 字段的 object,包含loaded、total、percent三个属性,提供上传进
* total.loaded: number,已上传大小,单位为字节。
* total.total: number,本次上传的总量控制信息,单位为字节,注意这里的 total 跟文件大小并不一致。
* total.percent: number,当前上传进度,范围:0~100
* */
const next = function (res) {
// res值{"total":{"loaded":18184,"size":18185,"percent":99.99450096233159}}
// 获取百分比进度
const progress = res.total.percent.toFixed(2);
self.uploadProgress = Number(progress);
if (progressId == 'uploadProgress1') {
self.uploadProgress1 = Number(progress);
}
const key = filePath ? filePath : getFilePath(file);
// 修改状态为上传
self.qiniuUploadStatus = true;
doQiniuAction1(fileType).then(function (token) {
const putExtra = {
fname: file.name, // 原文件名
params: {}, // 用来放置自定义变量
mimeType: mimeTypeArray || null // null || array,用来限制上传文件类型,为 null 时表示不对文件类型限制;限制类型放到数组里: ["image/png", "image/jpeg", "image/gif"]
};
const config = {
useCdnDomain: true, // 表示是否使用 cdn 加速域名,为布尔值,true 表示使用,默认为 false。
region: null // 选择上传域名区域;当为 null 或 undefined 时,自动分析上传域名区域
};
/*
* qiniu.upload 返回一个 observable 对象用来控制上传行为,observable 对像通过 subscribe 方法可以被 observer 所订阅,
* 订阅同时会开始触发上传,同时返回一个 subscription 对象,该对象有一个 unsubscribe 方法取消订阅,同时终止上传行为。
* */
const observable = qiniu.upload(file, key, token, putExtra, config);
/**
* 接收上传进度信息,res 参数是一个带有 total 字段的 object,包含loaded、total、percent三个属性,提供上传进
* total.loaded: number,已上传大小,单位为字节。
* total.total: number,本次上传的总量控制信息,单位为字节,注意这里的 total 跟文件大小并不一致。
* total.percent: number,当前上传进度,范围:0~100
* */
const next = function (res) {
// res值{"total":{"loaded":18184,"size":18185,"percent":99.99450096233159}}
// 获取百分比进度
const progress = res.total.percent.toFixed(2);
self.uploadProgress = Number(progress);
if(progressId == 'uploadProgress1') {
self.uploadProgress1 = Number(progress);
}
if(progressId == 'uploadProgress2') {
self.uploadProgress2 = Number(progress);
}
console.log('Progress2: ' + progress);
};
/**
* 接收上传完成后的后端返回信息,res 参数为一个 object, 为上传成功后后端返回的信息
* ,具体返回结构取决于后端sdk的配置,可参考上传策略(https://developer.qiniu.com/kodo/manual/1206/put-policy)
* */
const complete = function (res) {
console.log('七牛上传完成');
setTimeout(function() {
result.key = res.key;
result.path = '/' + res.key;
if(!fileType) { // 图片 文件
console.log('---domain-------', domain);
result.fullPath = domain + '/' + res.key;
}else{ // 视频
console.log('----domain1------', domain1);
result.fullPath = domain1 + '/' + res.key;
}
result.size = res.fsize;
result.name = res.fname;
result.ext = res.ext;
resolve(result);
self.qiniuUploadStatus = false;
}, 500);
};
/**
* 上传错误后触发,当不是 xhr 请求错误时,会把当前错误产生原因直接抛出,诸如 JSON 解析异常等;当产生 xhr 请求错误时,参数 err 为一个包含 code、message、isRequestError 三个属性的 object:
* err.isRequestError: 用于区分是否 xhr 请求错误;当 xhr 请求出现错误并且后端通过 HTTP 状态码返回了错误信息时,该参数为 true;否则为 undefined 。
* err.reqId: string,xhr请求错误的 X-Reqid。
* err.code: number,请求错误状态码,只有在 err.isRequestError 为 true 的时候才有效,可查阅码值对应说明。
* err.message: string,错误信息,包含错误码,当后端返回提示信息时也会有相应的错误信息。
* */
const error = function (err) {
// 修改状态为非上传
// status = false;
self.qiniuUploadStatus = false;
localStorage.removeItem('qiniuToken');
console.log('七牛上传失败,详细信息请参考:https://developer.qiniu.com/kodo/api/3928/error-responses');
// 输出简略错误信息
if (err.isRequestError) {
qiniuErrorCheck(err.code);
}else {
console.error(err);
}
return reject(new Error('七牛上传失败'));
};
// 上传开始
subscription = observable.subscribe(next, error, complete);
});
// 保存到全局对象
window.QNSubscription = subscription;
if (progressId == 'uploadProgress2') {
self.uploadProgress2 = Number(progress);
}
console.log('Progress2: ' + progress);
};
/**
* 接收上传完成后的后端返回信息,res 参数为一个 object, 为上传成功后后端返回的信息
* ,具体返回结构取决于后端sdk的配置,可参考上传策略(https://developer.qiniu.com/kodo/manual/1206/put-policy)
* */
const complete = function (res) {
console.log('七牛上传完成');
setTimeout(function () {
result.key = res.key;
result.path = '/' + res.key;
if (!fileType) {
// 图片 文件
console.log('---domain-------', domain);
result.fullPath = domain + '/' + res.key;
} else {
// 视频
console.log('----domain1------', domain1);
result.fullPath = domain1 + '/' + res.key;
}
result.size = res.fsize;
result.name = res.fname;
result.ext = res.ext;
resolve(result);
self.qiniuUploadStatus = false;
}, 500);
};
/**
* 上传错误后触发,当不是 xhr 请求错误时,会把当前错误产生原因直接抛出,诸如 JSON 解析异常等;当产生 xhr 请求错误时,参数 err 为一个包含 code、message、isRequestError 三个属性的 object:
* err.isRequestError: 用于区分是否 xhr 请求错误;当 xhr 请求出现错误并且后端通过 HTTP 状态码返回了错误信息时,该参数为 true;否则为 undefined 。
* err.reqId: string,xhr请求错误的 X-Reqid。
* err.code: number,请求错误状态码,只有在 err.isRequestError 为 true 的时候才有效,可查阅码值对应说明。
* err.message: string,错误信息,包含错误码,当后端返回提示信息时也会有相应的错误信息。
* */
const error = function (err) {
// 修改状态为非上传
// status = false;
self.qiniuUploadStatus = false;
localStorage.removeItem('qiniuToken');
console.log(
'七牛上传失败,详细信息请参考:https://developer.qiniu.com/kodo/api/3928/error-responses'
);
// 输出简略错误信息
if (err.isRequestError) {
qiniuErrorCheck(err.code);
} else {
console.error(err);
}
return reject(new Error('七牛上传失败'));
};
// 上传开始
subscription = observable.subscribe(next, error, complete);
});
// 保存到全局对象
window.QNSubscription = subscription;
});
};
// 取消上传
export const unsubscribe = () => {
......
/* eslint-disable */
import axios from 'axios';
// 对象的合并
export const containObject = function(...obj1) {
const obj = Object.assign(...obj1);
return obj;
export const containObject = function (...obj1) {
const obj = Object.assign(...obj1);
return obj;
};
// 获取页面自适应高度
export function resizeHeight(cMinusHeight = 152, iMinuxHeight = 210, refHeightId = 'slidebar-container',
containerHeightId = 'screenSet') {
// let containerHeight = p_getElm(refHeightId).getBoundingClientRect().height - 15;
let containerHeight = document.body.clientHeight - 80;
p_getElm(containerHeightId).style.height = containerHeight - cMinusHeight + 'px';
window.onresize = function() {
if(p_getElm(refHeightId) && p_getElm(containerHeightId)) {
containerHeight = p_getElm(refHeightId).getBoundingClientRect().height - 15;
p_getElm(containerHeightId).style.height = containerHeight - cMinusHeight + 'px';
}
};
export function resizeHeight(
cMinusHeight = 152,
iMinuxHeight = 210,
refHeightId = 'slidebar-container',
containerHeightId = 'screenSet'
) {
// let containerHeight = p_getElm(refHeightId).getBoundingClientRect().height - 15;
let containerHeight = document.body.clientHeight - 80;
p_getElm(containerHeightId).style.height =
containerHeight - cMinusHeight + 'px';
window.onresize = function () {
if (p_getElm(refHeightId) && p_getElm(containerHeightId)) {
containerHeight =
p_getElm(refHeightId).getBoundingClientRect().height - 15;
p_getElm(containerHeightId).style.height =
containerHeight - cMinusHeight + 'px';
}
};
}
function p_getElm(elmId) {
return document.getElementById(elmId);
return document.getElementById(elmId);
}
// 共通函数
Array.prototype.contains = function (obj) {
if (this.length > 0) {
for (let i = 0; i < this.length; i++) {
if (obj === this[i]) {
return true;
}
}
if (this.length > 0) {
for (let i = 0; i < this.length; i++) {
if (obj === this[i]) {
return true;
}
}
return false;
}
return false;
};
Array.prototype.remove = function (obj) {
if (this.contains(obj)) {
for (let i = 0; i < this.length; i++) {
if (obj === this[i]) {
this.splice(i, 1);
break;
}
}
if (this.contains(obj)) {
for (let i = 0; i < this.length; i++) {
if (obj === this[i]) {
this.splice(i, 1);
break;
}
}
return this;
}
return this;
};
// 时间处理
Date.prototype.format = function (fmt) { // author: meizz
const o = {
'M+': this.getMonth() + 1, // 月份
'd+': this.getDate(), // 日
'h+': this.getHours(), // 小时
'm+': this.getMinutes(), // 分
's+': this.getSeconds(), // 秒
'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
'S': this.getMilliseconds()
// 毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '')
.substr(4 - RegExp.$1.length));
for (const k in o)
if (new RegExp('(' + k + ')').test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
return fmt;
Date.prototype.format = function (fmt) {
// author: meizz
const o = {
'M+': this.getMonth() + 1, // 月份
'd+': this.getDate(), // 日
'h+': this.getHours(), // 小时
'm+': this.getMinutes(), // 分
's+': this.getSeconds(), // 秒
'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
S: this.getMilliseconds(),
// 毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(
RegExp.$1,
(this.getFullYear() + '').substr(4 - RegExp.$1.length)
);
for (const k in o)
if (new RegExp('(' + k + ')').test(fmt))
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
);
return fmt;
};
/**
......@@ -71,87 +85,207 @@ Date.prototype.format = function (fmt) { // author: meizz
* @param {Object} str
*/
export const base64encode = (str) => {
const base64EncodeChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
let out, i, len;
let c1, c2, c3;
len = str.length;
i = 0;
out = '';
while (i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt((c1 & 0x3) << 4);
out += '==';
break;
}
c2 = str.charCodeAt(i++);
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt((c2 & 0xF) << 2);
out += '=';
break;
}
c3 = str.charCodeAt(i++);
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
out += base64EncodeChars.charAt(c3 & 0x3F);
const base64EncodeChars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
let out, i, len;
let c1, c2, c3;
len = str.length;
i = 0;
out = '';
while (i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt((c1 & 0x3) << 4);
out += '==';
break;
}
return out;
c2 = str.charCodeAt(i++);
if (i == len) {
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4));
out += base64EncodeChars.charAt((c2 & 0xf) << 2);
out += '=';
break;
}
c3 = str.charCodeAt(i++);
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xf0) >> 4));
out += base64EncodeChars.charAt(((c2 & 0xf) << 2) | ((c3 & 0xc0) >> 6));
out += base64EncodeChars.charAt(c3 & 0x3f);
}
return out;
};
/**
* base64解码
* @param {Object} str
*/
export const base64decode = (str) => {
const base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1);
let c1, c2, c3, c4;
let i, len, out;
len = str.length;
i = 0;
out = '';
while (i < len) {
/* c1 */
do {
c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
}
while (i < len && c1 == -1);
if (c1 == -1)
break;
/* c2 */
do {
c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
}
while (i < len && c2 == -1);
if (c2 == -1)
break;
out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
/* c3 */
do {
c3 = str.charCodeAt(i++) & 0xff;
if (c3 == 61)
return out;
c3 = base64DecodeChars[c3];
}
while (i < len && c3 == -1);
if (c3 == -1)
break;
out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
/* c4 */
do {
c4 = str.charCodeAt(i++) & 0xff;
if (c4 == 61)
return out;
c4 = base64DecodeChars[c4];
}
while (i < len && c4 == -1);
if (c4 == -1)
break;
out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
}
return out;
const base64DecodeChars = new Array(
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
62,
-1,
-1,
-1,
63,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
-1,
-1,
-1,
-1,
-1,
-1,
-1,
0,
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,
-1,
-1,
-1,
-1,
-1,
-1,
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,
-1,
-1,
-1,
-1,
-1
);
let c1, c2, c3, c4;
let i, len, out;
len = str.length;
i = 0;
out = '';
while (i < len) {
/* c1 */
do {
c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while (i < len && c1 == -1);
if (c1 == -1) break;
/* c2 */
do {
c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while (i < len && c2 == -1);
if (c2 == -1) break;
out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
/* c3 */
do {
c3 = str.charCodeAt(i++) & 0xff;
if (c3 == 61) return out;
c3 = base64DecodeChars[c3];
} while (i < len && c3 == -1);
if (c3 == -1) break;
out += String.fromCharCode(((c2 & 0xf) << 4) | ((c3 & 0x3c) >> 2));
/* c4 */
do {
c4 = str.charCodeAt(i++) & 0xff;
if (c4 == 61) return out;
c4 = base64DecodeChars[c4];
} while (i < len && c4 == -1);
if (c4 == -1) break;
out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
}
return out;
};
/**
......@@ -160,58 +294,58 @@ export const base64decode = (str) => {
* @returns {*} 格式化后的时分秒
*/
export const secToTime = (s) => {
let t = '';
if (s > -1) {
// let hour = Math.floor(s/3600);
const min = Math.floor(s / 60) % 60;
const sec = s % 60;
// if(hour < 10) {
// t = '0'+ hour + ":";
// } else {
// t = hour + ":";
// }
if (min < 10) {
t += '0';
}
t += min + ':';
if (sec < 10) {
t += '0';
}
t += sec.toFixed(0);
let t = '';
if (s > -1) {
// let hour = Math.floor(s/3600);
const min = Math.floor(s / 60) % 60;
const sec = s % 60;
// if(hour < 10) {
// t = '0'+ hour + ":";
// } else {
// t = hour + ":";
// }
if (min < 10) {
t += '0';
}
t += min + ':';
if (sec < 10) {
t += '0';
}
return t;
t += sec.toFixed(0);
}
return t;
};
/**
* 校验对象是否为空
* */
export const isNotEmptyUtils = (obj) => {
if ('' == obj || null == obj || undefined == obj || 'null' == obj) {
return false;
}
return true;
if ('' == obj || null == obj || undefined == obj || 'null' == obj) {
return false;
}
return true;
};
/**
* 校验对象是否为空
* */
export const isEmptyUtils = (obj) => {
return !isNotEmptyUtils(obj);
return !isNotEmptyUtils(obj);
};
/**
* 校验数组是否为空
* */
export const isEmptyList = (list) => {
return (isEmptyUtils(list) || !(list instanceof Array) || list.length === 0);
return isEmptyUtils(list) || !(list instanceof Array) || list.length === 0;
};
/**
* 校验数组是否为空
* */
export const isNotEmptyList = (list) => {
return !isEmptyList(list);
return !isEmptyList(list);
};
/**
......@@ -219,153 +353,157 @@ export const isNotEmptyList = (list) => {
* * @param {String} [obj] 校验对象
* */
export const isNumber = (obj) => {
return (obj != null && obj.toString().match('^[0-9]*$') != null);
return obj != null && obj.toString().match('^[0-9]*$') != null;
};
// 获取用户系统信息start
const detectOS = () => {
const sUserAgent = navigator.userAgent;
const isWin = (navigator.platform == 'Win32')
|| (navigator.platform == 'Windows');
const isMac = (navigator.platform == 'Mac68K')
|| (navigator.platform == 'MacPPC')
|| (navigator.platform == 'Macintosh')
|| (navigator.platform == 'MacIntel');
if (isMac)
return 'Mac';
const isUnix = (navigator.platform == 'X11') && !isWin && !isMac;
if (isUnix)
return 'Unix';
const isLinux = (String(navigator.platform).indexOf('Linux') > -1);
if (isLinux)
return 'Linux';
const isIos = (sUserAgent.indexOf('Mac OS X') > -1);
if (isIos)
return 'Mac';
if (isWin) {
const isWinXP = sUserAgent.indexOf('Windows NT 5.1') > -1
|| sUserAgent.indexOf('Windows XP') > -1;
if (isWinXP)
return 'WinXP';
const isWinVista = sUserAgent.indexOf('Windows NT 6.0') > -1
|| sUserAgent.indexOf('Windows Vista') > -1;
if (isWinVista)
return 'WinVista';
const isWin7 = sUserAgent.indexOf('Windows NT 6.1') > -1
|| sUserAgent.indexOf('Windows 7') > -1;
if (isWin7)
return 'Win7';
const isWin8_1 = sUserAgent.indexOf('Windows NT 6.2') > -1
|| sUserAgent.indexOf('Windows 8') > -1;
const isWin8_2 = sUserAgent.indexOf('Windows NT 6.3') > -1
|| sUserAgent.indexOf('Windows 8.1') > -1;
if (isWin8_1 || isWin8_2)
return 'Win8';
const isWin10_1 = sUserAgent.indexOf('Windows NT 6.4') > -1
|| sUserAgent.indexOf('Windows 10') > -1;
const isWin10_2 = sUserAgent.indexOf('Windows NT 10.0') > -1
|| sUserAgent.indexOf('Windows 10') > -1;
if (isWin10_1 || isWin10_2)
return 'Win10';
}
return 'other';
const sUserAgent = navigator.userAgent;
const isWin =
navigator.platform == 'Win32' || navigator.platform == 'Windows';
const isMac =
navigator.platform == 'Mac68K' ||
navigator.platform == 'MacPPC' ||
navigator.platform == 'Macintosh' ||
navigator.platform == 'MacIntel';
if (isMac) return 'Mac';
const isUnix = navigator.platform == 'X11' && !isWin && !isMac;
if (isUnix) return 'Unix';
const isLinux = String(navigator.platform).indexOf('Linux') > -1;
if (isLinux) return 'Linux';
const isIos = sUserAgent.indexOf('Mac OS X') > -1;
if (isIos) return 'Mac';
if (isWin) {
const isWinXP =
sUserAgent.indexOf('Windows NT 5.1') > -1 ||
sUserAgent.indexOf('Windows XP') > -1;
if (isWinXP) return 'WinXP';
const isWinVista =
sUserAgent.indexOf('Windows NT 6.0') > -1 ||
sUserAgent.indexOf('Windows Vista') > -1;
if (isWinVista) return 'WinVista';
const isWin7 =
sUserAgent.indexOf('Windows NT 6.1') > -1 ||
sUserAgent.indexOf('Windows 7') > -1;
if (isWin7) return 'Win7';
const isWin8_1 =
sUserAgent.indexOf('Windows NT 6.2') > -1 ||
sUserAgent.indexOf('Windows 8') > -1;
const isWin8_2 =
sUserAgent.indexOf('Windows NT 6.3') > -1 ||
sUserAgent.indexOf('Windows 8.1') > -1;
if (isWin8_1 || isWin8_2) return 'Win8';
const isWin10_1 =
sUserAgent.indexOf('Windows NT 6.4') > -1 ||
sUserAgent.indexOf('Windows 10') > -1;
const isWin10_2 =
sUserAgent.indexOf('Windows NT 10.0') > -1 ||
sUserAgent.indexOf('Windows 10') > -1;
if (isWin10_1 || isWin10_2) return 'Win10';
}
return 'other';
};
// 获取用户浏览器信息
const getBrowser = () => {
// let OsObject = "未知";
// if (navigator.userAgent.indexOf("MSIE") > 0) {
// return "IE";
// }
// if (navigator.userAgent.indexOf("Firefox") > 0) {
// return "Firefox";
// }
// if (navigator.userAgent.indexOf("Chrome") > 0) {
// return "Chrome";
// }
// if (navigator.userAgent.indexOf("Safari") > 0) {
// return "Safari";
// }
// if (navigator.userAgent.indexOf("Gecko") > 0) {
// return "Gecko";
// }
return navigator.userAgent;
// let OsObject = "未知";
// if (navigator.userAgent.indexOf("MSIE") > 0) {
// return "IE";
// }
// if (navigator.userAgent.indexOf("Firefox") > 0) {
// return "Firefox";
// }
// if (navigator.userAgent.indexOf("Chrome") > 0) {
// return "Chrome";
// }
// if (navigator.userAgent.indexOf("Safari") > 0) {
// return "Safari";
// }
// if (navigator.userAgent.indexOf("Gecko") > 0) {
// return "Gecko";
// }
return navigator.userAgent;
};
const GetLocalIPAddress = () => {
// let url ='http://counter.sina.com.cn/ip/';
// let url ='http://chaxun.1616.net/s.php?type=ip&output=json&callback=?&_='+Math.random();
// let ip = "";
// $.getJSON(url, function(data){
// localStorage.setItem("ipAddress",data.Ip);
// // check();
// });
// $.getScript('http://pv.sohu.com/cityjson?ie=utf-8', function () {
return returnCitySN['cip'];
// });
// return ip;
// let url ='http://counter.sina.com.cn/ip/';
// let url ='http://chaxun.1616.net/s.php?type=ip&output=json&callback=?&_='+Math.random();
// let ip = "";
// $.getJSON(url, function(data){
// localStorage.setItem("ipAddress",data.Ip);
// // check();
// });
// $.getScript('http://pv.sohu.com/cityjson?ie=utf-8', function () {
return returnCitySN['cip'];
// });
// return ip;
};
// 获取用户终端信息
const getTerminalType = () => {
let brow = '未知';
// alert(navigator.userAgent);
if (navigator.userAgent.indexOf('iPad') > -1) {
// alert("iPad");
return brow = 'iPad';
}
if (navigator.userAgent.indexOf('Android') > -1
|| navigator.userAgent.indexOf('Linux') > -1) {
// alert("Android");
return brow = 'android手机';
}
if (navigator.userAgent.indexOf('iPhone') > -1
let brow = '未知';
// alert(navigator.userAgent);
if (navigator.userAgent.indexOf('iPad') > -1) {
// alert("iPad");
return (brow = 'iPad');
}
if (
navigator.userAgent.indexOf('Android') > -1 ||
navigator.userAgent.indexOf('Linux') > -1
) {
// alert("Android");
return (brow = 'android手机');
}
if (
navigator.userAgent.indexOf('iPhone') > -1
// || navigator.userAgent.indexOf('Mac') > -1
) {
// alert("iPhone");
return brow = 'iPhone手机';
}
if (navigator.userAgent.indexOf('Trident') > -1) {
// alert("Trident");
return brow = '电脑';
}
if (navigator.userAgent.indexOf('Presto') > -1) {
// alert("Presto");
return brow = '电脑';
}
if (navigator.userAgent.indexOf('Chrome') > -1) {
// alert("Chrome");
return brow = '电脑';
}
if (navigator.userAgent.indexOf('AppleWebKit') > -1) {
// alert("AppleWebKit");
return brow = 'iPad';
}
if (navigator.userAgent.indexOf('Gecko') > -1
&& navigator.userAgent.indexOf('KHTML') == -1) {
// alert("Gecko");
return brow = '电脑';
}
if (navigator.userAgent.indexOf('Mac OS X') > -1) {
// alert("ios");
return brow = 'ios';
}
if (navigator.userAgent.indexOf('Safari') == -1) {
// alert("Safari");
return brow = '电脑';
}
return brow;
) {
// alert("iPhone");
return (brow = 'iPhone手机');
}
if (navigator.userAgent.indexOf('Trident') > -1) {
// alert("Trident");
return (brow = '电脑');
}
if (navigator.userAgent.indexOf('Presto') > -1) {
// alert("Presto");
return (brow = '电脑');
}
if (navigator.userAgent.indexOf('Chrome') > -1) {
// alert("Chrome");
return (brow = '电脑');
}
if (navigator.userAgent.indexOf('AppleWebKit') > -1) {
// alert("AppleWebKit");
return (brow = 'iPad');
}
if (
navigator.userAgent.indexOf('Gecko') > -1 &&
navigator.userAgent.indexOf('KHTML') == -1
) {
// alert("Gecko");
return (brow = '电脑');
}
if (navigator.userAgent.indexOf('Mac OS X') > -1) {
// alert("ios");
return (brow = 'ios');
}
if (navigator.userAgent.indexOf('Safari') == -1) {
// alert("Safari");
return (brow = '电脑');
}
return brow;
};
const initEnvironment = () => {
const OS = detectOS();
const browser = getBrowser();
const ip = GetLocalIPAddress();
const terminalType = getTerminalType();
localStorage.setItem('OS', OS);
localStorage.setItem('browser', browser);
localStorage.setItem('ipAddress', ip);
localStorage.setItem('terminalType', terminalType);
const OS = detectOS();
const browser = getBrowser();
const ip = GetLocalIPAddress();
const terminalType = getTerminalType();
localStorage.setItem('OS', OS);
localStorage.setItem('browser', browser);
localStorage.setItem('ipAddress', ip);
localStorage.setItem('terminalType', terminalType);
};
/**
......@@ -375,11 +513,11 @@ const initEnvironment = () => {
* @return{Array} [array]
* */
export const stringToArr = (str, split) => {
if (isEmptyUtils(str) || isEmptyUtils(split) || str.indexOf(split) === -1) {
return [str];
} else {
return str.split(split);
}
if (isEmptyUtils(str) || isEmptyUtils(split) || str.indexOf(split) === -1) {
return [str];
} else {
return str.split(split);
}
};
// 单点登录--start
......@@ -390,23 +528,23 @@ export const stringToArr = (str, split) => {
* @return{Array} [parArr] 返回键值对list
* */
const getUrlParams = (str, split) => {
const parArr = [];
if (isEmptyUtils(str) || isEmptyUtils(split) || str.indexOf(split) === -1) {
return parArr;
} else {
const parMapArray = str.split(split);
if (parMapArray.length > 0) {
for (let i = 0; i < parMapArray.length; i++) {
if (parMapArray[i].indexOf('=') > -1) {
const item = parMapArray[i].split('=');
const par = {};
par[item[0]] = item[1];
parArr.push(par);
}
}
const parArr = [];
if (isEmptyUtils(str) || isEmptyUtils(split) || str.indexOf(split) === -1) {
return parArr;
} else {
const parMapArray = str.split(split);
if (parMapArray.length > 0) {
for (let i = 0; i < parMapArray.length; i++) {
if (parMapArray[i].indexOf('=') > -1) {
const item = parMapArray[i].split('=');
const par = {};
par[item[0]] = item[1];
parArr.push(par);
}
return parArr;
}
}
return parArr;
}
};
/**
......@@ -416,65 +554,65 @@ const getUrlParams = (str, split) => {
* @return{Map} [parMap] 返回键值对Map
* */
export const getUrlParamsMap = (str, split) => {
const parMap = new Map();
if (isEmptyUtils(str) || isEmptyUtils(split) || str.indexOf(split) === -1) {
return parMap;
} else {
const parMapArray = str.split(split);
if (parMapArray.length > 0) {
for (let i = 0; i < parMapArray.length; i++) {
if (parMapArray[i].indexOf('=') > -1) {
const item = parMapArray[i].split('=');
parMap[item[0]] = item[1];
}
}
const parMap = new Map();
if (isEmptyUtils(str) || isEmptyUtils(split) || str.indexOf(split) === -1) {
return parMap;
} else {
const parMapArray = str.split(split);
if (parMapArray.length > 0) {
for (let i = 0; i < parMapArray.length; i++) {
if (parMapArray[i].indexOf('=') > -1) {
const item = parMapArray[i].split('=');
parMap[item[0]] = item[1];
}
return parMap;
}
}
return parMap;
}
};
export const ssoLogin = (href, paramMap) => {
console.log('ssoLogin开始');
console.log('ssoLogin开始');
if (isNotEmptyUtils(paramMap)) {
if (isNotEmptyUtils(paramMap)) {
if (isNotEmptyUtils(paramMap)) {
for (var param in paramMap) {
localStorage.setItem(param, paramMap[param]);
}
}
// 获取用户系统信息
// initEnvironment();
for (var param in paramMap) {
localStorage.setItem(param, paramMap[param]);
}
}
// 获取用户系统信息
// initEnvironment();
}
};
// 单点登录--end
// 退出登录,跳转到登录页面
export const logout = () => {
const url = localStorage.getItem('Url');
const logoutUrl = localStorage.getItem('logoutUrl');
const ssoLoginUrl = localStorage.getItem('ssoLogin');
const ssoOriginUrl = localStorage.getItem('ssoOrigin');
console.log('logoutUrl:' + logoutUrl);
/* alert("ssoLogin Url:"+ ssoLoginUrl)
const url = localStorage.getItem('Url');
const logoutUrl = localStorage.getItem('logoutUrl');
const ssoLoginUrl = localStorage.getItem('ssoLogin');
const ssoOriginUrl = localStorage.getItem('ssoOrigin');
console.log('logoutUrl:' + logoutUrl);
/* alert("ssoLogin Url:"+ ssoLoginUrl)
alert("logOut url:" + logoutUrl)
alert("ssoOrigin url:" + ssoOriginUrl);*/
localStorage.clear();
localStorage.setItem('Url', url);
localStorage.setItem('logoutUrl', logoutUrl);
localStorage.setItem('ssoLogin', ssoLoginUrl);
localStorage.setItem('ssoOrigin', ssoOriginUrl);
if (isEmptyUtils(logoutUrl)) {
if(isEmptyUtils(ssoLoginUrl)) {
window.location.href = localStorage.getItem('ssoOrigin')
+ '/PICA_SSO_FE/html/pica_login.html';
}else{
window.location.href = localStorage.getItem('ssoLogin');
}
localStorage.clear();
localStorage.setItem('Url', url);
localStorage.setItem('logoutUrl', logoutUrl);
localStorage.setItem('ssoLogin', ssoLoginUrl);
localStorage.setItem('ssoOrigin', ssoOriginUrl);
if (isEmptyUtils(logoutUrl)) {
if (isEmptyUtils(ssoLoginUrl)) {
window.location.href =
localStorage.getItem('ssoOrigin') + '/PICA_SSO_FE/html/pica_login.html';
} else {
// window.location.href = logoutUrl;
window.location.href = localStorage.getItem('ssoOrigin')
+ '/PICA_SSO_FE/html/pica_login.html';
window.location.href = localStorage.getItem('ssoLogin');
}
} else {
// window.location.href = logoutUrl;
window.location.href =
localStorage.getItem('ssoOrigin') + '/PICA_SSO_FE/html/pica_login.html';
}
};
/**
......@@ -488,53 +626,65 @@ export const logout = () => {
* @param {Function} [cancelFunction] 按取消按钮认时,执行的函数
* @param {String} [messageType] 消息类型 success,info,warning,error
* */
export const messageBox = (self, title, content, confirmButton, confirmFunction, cancelButton, cancelFunction, messageType) => {
const titleText = title ? title : '提示';
const contentText = content ? content : '';
const confirmButtonText = confirmButton ? confirmButton : '确定';
let type = messageType ? messageType : 'info';
const typeArray = ['error', 'warning', 'info', 'success'];
if (!typeArray.contains(type)) {
type = 'info';
}
export const messageBox = (
self,
title,
content,
confirmButton,
confirmFunction,
cancelButton,
cancelFunction,
messageType
) => {
const titleText = title ? title : '提示';
const contentText = content ? content : '';
const confirmButtonText = confirmButton ? confirmButton : '确定';
let type = messageType ? messageType : 'info';
const typeArray = ['error', 'warning', 'info', 'success'];
if (!typeArray.contains(type)) {
type = 'info';
}
if (isNotEmptyUtils(cancelButton)) {
self.$confirm(contentText, titleText, {
confirmButtonText: confirmButtonText,
cancelButtonText: cancelButton,
type: type
}).then(() => {
// self.$message({
// type: 'success',
// message: '删除成功!'
// });
if (confirmFunction instanceof Function) {
confirmFunction();
}
}).catch(() => {
// self.$message({
// type: 'info',
// message: '已取消删除'
// });
if (cancelFunction instanceof Function) {
cancelFunction();
}
});
} else {
self.$alert(contentText, titleText, {
confirmButtonText: confirmButtonText,
type: type,
callback: action => {
// self.$message({
// type: 'info',
// message: `action: ${ action }`
// });
if (confirmFunction instanceof Function) {
confirmFunction();
}
}
});
}
if (isNotEmptyUtils(cancelButton)) {
self
.$confirm(contentText, titleText, {
confirmButtonText: confirmButtonText,
cancelButtonText: cancelButton,
type: type,
})
.then(() => {
// self.$message({
// type: 'success',
// message: '删除成功!'
// });
if (confirmFunction instanceof Function) {
confirmFunction();
}
})
.catch(() => {
// self.$message({
// type: 'info',
// message: '已取消删除'
// });
if (cancelFunction instanceof Function) {
cancelFunction();
}
});
} else {
self.$alert(contentText, titleText, {
confirmButtonText: confirmButtonText,
type: type,
callback: (action) => {
// self.$message({
// type: 'info',
// message: `action: ${ action }`
// });
if (confirmFunction instanceof Function) {
confirmFunction();
}
},
});
}
};
/**
......@@ -548,48 +698,60 @@ export const messageBox = (self, title, content, confirmButton, confirmFunction,
* @param {Function} [cancelFunction] 按取消按钮认时,执行的函数
* @param {String} [messageType] 消息类型 success,info,warning,error
* */
export const htmlMessageBox = (self, title, content, confirmButton, confirmFunction, cancelButton, cancelFunction, messageType) => {
const titleText = title ? title : '提示';
const contentText = content ? content : '';
const confirmButtonText = confirmButton ? confirmButton : '确定';
let type = messageType ? messageType : 'info';
const typeArray = ['error', 'warning', 'info', 'success'];
if (!typeArray.contains(type)) {
type = 'info';
}
export const htmlMessageBox = (
self,
title,
content,
confirmButton,
confirmFunction,
cancelButton,
cancelFunction,
messageType
) => {
const titleText = title ? title : '提示';
const contentText = content ? content : '';
const confirmButtonText = confirmButton ? confirmButton : '确定';
let type = messageType ? messageType : 'info';
const typeArray = ['error', 'warning', 'info', 'success'];
if (!typeArray.contains(type)) {
type = 'info';
}
// debugger
if (isNotEmptyUtils(cancelButton)) {
self.$confirm(contentText, titleText, {
confirmButtonText: confirmButtonText,
cancelButtonText: cancelButton,
dangerouslyUseHTMLString: true, // 是否将 message 属性作为 HTML 片段处理
type: type
}).then(() => {
if (confirmFunction instanceof Function) {
confirmFunction();
}
}).catch(() => {
if (cancelFunction instanceof Function) {
cancelFunction();
}
});
} else {
self.$alert(contentText, titleText, {
confirmButtonText: confirmButtonText,
dangerouslyUseHTMLString: true, // 是否将 message 属性作为 HTML 片段处理
type: type,
callback: action => {
// self.$message({
// type: 'info',
// message: `action: ${ action }`
// });
if (confirmFunction instanceof Function) {
confirmFunction();
}
}
});
}
// debugger
if (isNotEmptyUtils(cancelButton)) {
self
.$confirm(contentText, titleText, {
confirmButtonText: confirmButtonText,
cancelButtonText: cancelButton,
dangerouslyUseHTMLString: true, // 是否将 message 属性作为 HTML 片段处理
type: type,
})
.then(() => {
if (confirmFunction instanceof Function) {
confirmFunction();
}
})
.catch(() => {
if (cancelFunction instanceof Function) {
cancelFunction();
}
});
} else {
self.$alert(contentText, titleText, {
confirmButtonText: confirmButtonText,
dangerouslyUseHTMLString: true, // 是否将 message 属性作为 HTML 片段处理
type: type,
callback: (action) => {
// self.$message({
// type: 'info',
// message: `action: ${ action }`
// });
if (confirmFunction instanceof Function) {
confirmFunction();
}
},
});
}
};
/**
......@@ -599,48 +761,61 @@ export const htmlMessageBox = (self, title, content, confirmButton, confirmFunct
* @param {Object} [self] 当前vue对象
* */
export const errorResponseCheck = (error, self) => {
closeLoading(self);
console.log(error);
setTimeout(function () {
const code = error ? (error.response ? error.response.data : 0) : 0;
// console.log("请求失败:%s", code);
if (code == '40011') {
messageBox(self, '登录', '登录失效,请重新登录!', '是', function () {
logout();
}, '', null);
setTimeout(function () {
logout();
}, 2000);
} else if (code == '40013') {
messageBox(self, '提示', '刷新太过频繁,休息一下!', '是', function () {
}, '', null);
// setTimeout(function () {
//
// }, 2000);
} else {
// sendErrorReport(code);
// messageBox(self, "提示", "操作失败!", "确定", function () {
//
// }, "", null, "error");
self.$message.error('操作失败');
}
}, 100);
closeLoading(self);
console.log(error);
setTimeout(function () {
const code = error ? (error.response ? error.response.data : 0) : 0;
// console.log("请求失败:%s", code);
if (code == '40011') {
messageBox(
self,
'登录',
'登录失效,请重新登录!',
'是',
function () {
logout();
},
'',
null
);
setTimeout(function () {
logout();
}, 2000);
} else if (code == '40013') {
messageBox(
self,
'提示',
'刷新太过频繁,休息一下!',
'是',
function () {},
'',
null
);
// setTimeout(function () {
//
// }, 2000);
} else {
// sendErrorReport(code);
// messageBox(self, "提示", "操作失败!", "确定", function () {
//
// }, "", null, "error");
self.$message.error('操作失败');
}
}, 100);
};
// 截位
export const subString = (obj, int) => {
if (isEmptyUtils(obj) || isEmptyUtils(int)) {
return '';
}
if (obj.length <= int) {
return obj;
} else {
obj = obj.substring(0, int);
}
if (isEmptyUtils(obj) || isEmptyUtils(int)) {
return '';
}
if (obj.length <= int) {
return obj;
} else {
obj = obj.substring(0, int);
}
return obj;
};
/**
......@@ -649,15 +824,15 @@ export const subString = (obj, int) => {
* @return 当前loading对象
* */
export const openLoading = (self) => {
const options = {
lock: true,
text: 'Loading',
// target:'#bodyContent',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
};
self.elLoadingId = self.$loading(options);
return self.elLoadingId;
const options = {
lock: true,
text: 'Loading',
// target:'#bodyContent',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)',
};
self.elLoadingId = self.$loading(options);
return self.elLoadingId;
};
/**
......@@ -666,9 +841,9 @@ export const openLoading = (self) => {
* @return 当前loading对象
* */
export const closeLoading = (self) => {
if (self.elLoadingId) {
self.elLoadingId.close();
}
if (self.elLoadingId) {
self.elLoadingId.close();
}
};
/**
......@@ -679,136 +854,160 @@ export const closeLoading = (self) => {
* @param {Object} [codeObject] 例如:codeObject={list1:"P097",list2:"P097"}
* */
export const getConstantList = (self, codeObject) => {
if (!codeObject instanceof Object) {
return;
}
const req = {
params: {
numMap: JSON.stringify(codeObject)
}
};
self.$axios.get(
localStorage.getItem('msUrl') + 'constants'
, req
).then(function (res) {
const map = JSON.parse(JSON.stringify(res.data.data));// 通过这个实现深拷贝
for (const key in map) {
self[key] = map[key];
}
if (!codeObject instanceof Object) {
return;
}
const req = {
params: {
numMap: JSON.stringify(codeObject),
},
};
self.$axios
.get(localStorage.getItem('msUrl') + 'constants', req)
.then(function (res) {
const map = JSON.parse(JSON.stringify(res.data.data)); // 通过这个实现深拷贝
for (const key in map) {
self[key] = map[key];
}
});
};
export const initDepartment = (self, obj, type) => {
if (!obj instanceof Object) {
return;
}
var num = {
id: obj,
type: type
};
axios.create().post(
localStorage.getItem('kfUrl') + 'PICAAddressHospitalServiceImpl/postDepartmentList',
num
).then(function (res) {
const list = JSON.parse(JSON.stringify(res.data.departmentList));// 通过这个实现深拷贝
if (obj == -1) {
self.departmentListP = list;
} else {
self.departmentList = list;
}
if (!obj instanceof Object) {
return;
}
var num = {
id: obj,
type: type,
};
axios
.create()
.post(
localStorage.getItem('kfUrl') +
'PICAAddressHospitalServiceImpl/postDepartmentList',
num
)
.then(function (res) {
const list = JSON.parse(JSON.stringify(res.data.departmentList)); // 通过这个实现深拷贝
if (obj == -1) {
self.departmentListP = list;
} else {
self.departmentList = list;
}
if (type == 'childGetChildList') {
self.departmentPid = getPdepartmentId(self, 'model', 'departmentId');
}
if (type == 'childGetChildList') {
self.departmentPid = getPdepartmentId(self, 'model', 'departmentId');
}
});
};
export const getPdepartmentId = (self) => {
if(isNotEmptyList(self.model.departmentId)
|| !self.departmentList instanceof Array) {
return null;
}
if(self.departmentList.length > 0) {
return self.departmentList[0].parent_id;
}else{
return -1;
}
if (
isNotEmptyList(self.model.departmentId) ||
!self.departmentList instanceof Array
) {
return null;
}
if (self.departmentList.length > 0) {
return self.departmentList[0].parent_id;
} else {
return -1;
}
};
export const getObjectIdsStr = (list, key) => {
if (isEmptyUtils(list)) {
return '';
}
let strRet = '';
for (const temp of list) {
strRet = strRet + temp[key] + ',';
}
return strRet;
if (isEmptyUtils(list)) {
return '';
}
let strRet = '';
for (const temp of list) {
strRet = strRet + temp[key] + ',';
}
return strRet;
};
export const getPositionList = (provinceId, cityId, countyId, townId) => {
return new Promise(function (resolve, reject) {
var num = {
provinceId,
cityId,
countyId,
townId
};
axios.create().post(
localStorage.getItem('kfUrl') + 'combineHospital/getPositionList',
num
).then(function (res) {
resolve(res);
}).then(function (res) {
reject(res);
});
});
return new Promise(function (resolve, reject) {
var num = {
provinceId,
cityId,
countyId,
townId,
};
axios
.create()
.post(
localStorage.getItem('kfUrl') + 'combineHospital/getPositionList',
num
)
.then(function (res) {
resolve(res);
})
.then(function (res) {
reject(res);
});
});
};
export const setOptionLabel = (self, selfModel, selfEId, selfEName, list, listEId, listEName) => {
if (isEmptyList(list) || isEmptyUtils(listEId) || isEmptyUtils(listEName)) {
return;
}
for (let i = 0; i < list.length; i++) {
if(list[i][listEId] == self[selfModel][selfEId]) {
self[selfModel][selfEName] = list[i][listEName];
break;
}
}
export const setOptionLabel = (
self,
selfModel,
selfEId,
selfEName,
list,
listEId,
listEName
) => {
if (isEmptyList(list) || isEmptyUtils(listEId) || isEmptyUtils(listEName)) {
return;
}
for (let i = 0; i < list.length; i++) {
if (list[i][listEId] == self[selfModel][selfEId]) {
self[selfModel][selfEName] = list[i][listEName];
break;
}
}
return;
};
// 将文件大小B转为MB
export const betaHandle = (limit) => {
var size = '';
if(limit < 1024) { // 小于0.1KB,则转化成B
size = limit + 'B';
}else if(limit < (1024 * 1024)) { // 小于0.1MB,则转化成KB
size = (limit / 1024).toFixed(0) + 'KB';
}else if(limit < (1024 * 1024 * 1024)) { // 小于0.1GB,则转化成MB
size = (limit / (1024 * 1024)).toFixed(1) + 'MB';
}else{ // 其他转化成GB
size = (limit / (1024 * 1024 * 1024)).toFixed(1) + 'GB';
}
return size;
var size = '';
if (limit < 1024) {
// 小于0.1KB,则转化成B
size = limit + 'B';
} else if (limit < 1024 * 1024) {
// 小于0.1MB,则转化成KB
size = (limit / 1024).toFixed(0) + 'KB';
} else if (limit < 1024 * 1024 * 1024) {
// 小于0.1GB,则转化成MB
size = (limit / (1024 * 1024)).toFixed(1) + 'MB';
} else {
// 其他转化成GB
size = (limit / (1024 * 1024 * 1024)).toFixed(1) + 'GB';
}
return size;
};
// 转换年月日方法
export const timeHandle = (str) => {
const date = new Date(str * 1);
const Y = date.getFullYear() + '-';
const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
const D = change(date.getDate()) + ' ';
const h = change(date.getHours()) + ':';
const m = change(date.getMinutes());
return Y + M + D + h + m;
const date = new Date(str * 1);
const Y = date.getFullYear() + '-';
const M =
(date.getMonth() + 1 < 10
? '0' + (date.getMonth() + 1)
: date.getMonth() + 1) + '-';
const D = change(date.getDate()) + ' ';
const h = change(date.getHours()) + ':';
const m = change(date.getMinutes());
return Y + M + D + h + m;
};
// 补0操作
const change = (num) => {
if(parseInt(num) < 10) {
num = '0' + num;
}
return num;
if (parseInt(num) < 10) {
num = '0' + num;
}
return num;
};
// 拖拽
export const bindDragHeader = (classname, content) => {
......@@ -829,12 +1028,12 @@ export const bindDragHeader = (classname, content) => {
const t = e.clientY - disY;
let x, y, tran;
if(contranslate.length > 1) {
x = (l + Number(contranslate[0])) + 'px';
y = (t + Number(contranslate[1])) + 'px';
}else{
x = (l) + 'px';
y = (t ) + 'px';
if (contranslate.length > 1) {
x = l + Number(contranslate[0]) + 'px';
y = t + Number(contranslate[1]) + 'px';
} else {
x = l + 'px';
y = t + 'px';
}
tran = `translate(${x},${y})`;
......
......@@ -124,9 +124,9 @@
.show-work-set {
margin-top: 100px;
}
.maxNum-first-show{
.maxNum-first-show {
margin-top: 20px;
.show-sep-num{
.show-sep-num {
color: red;
}
}
......
......@@ -138,7 +138,7 @@
:total-rows="searchParam.totalRows"
:loading="loading"
:create-list="newCreateList"
:center-dialog-visible="centerDialogVisible"
:center-dialog-visible="centerDialogVisible"
@sortfunc="sortfunc"
@getServiceOpen="getServiceOpen"
@getWorkStatus="getWorkStatus"
......@@ -197,7 +197,7 @@
workInStep,
getLevel,
} from '@/api/serviceSchedule';
import { departmentAll, savePCDayCount} from '@/api/diagnosis';
import { departmentAll, savePCDayCount } from '@/api/diagnosis';
import TableServiceSchedule from '@/components/list/table-serviceSchedule';
export default {
components: {
......@@ -259,9 +259,9 @@
newCreateList: [],
allTilst: [],
allList: {},
centerDialogVisible:false,
doctorInfo:{},
maxNumValue:''
centerDialogVisible: false,
doctorInfo: {},
maxNumValue: '',
};
},
watch: {},
......@@ -444,7 +444,7 @@
target.setAttribute('href', u);
target.click();
},
setMaxNumValue(value) {
setMaxNumValue(value) {
this.doctorInfo = value;
this.maxNumValue = value.preNum;
this.centerDialogVisible = true;
......@@ -455,16 +455,16 @@
},
submitSetData() {
const params = {
doctorId:this.doctorInfo.doctorId,
preNum:this.maxNumValue
doctorId: this.doctorInfo.doctorId,
preNum: this.maxNumValue,
};
savePCDayCount(params).then(res => {
savePCDayCount(params).then((res) => {
if (res.code == '000000') {
this.centerDialogVisible = false;
this.search();
}
});
}
},
},
};
</script>
......@@ -610,9 +610,9 @@
}
}
}
}
}
}
}
</style>
<style lang="scss">
.serviceSchedule-cascader {
......
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册