import crypto from 'crypto'
import SparkMD5 from 'spark-md5'
import CryptoJs from 'crypto-js'
import JSEncrypt from 'jsencrypt'
import storage from '@/utils/storage'
import { isEmpty, isArray, remove } from 'lodash-es'
import { chartColor, regexIP, unitOptions } from '@/utils/info'
export const ascSortData = arr => arr.sort((a, b) => a.value - b.value)
export const descSortData = arr => isArray(arr) ? arr.sort((a, b) => b.value - a.value) : arr
export function formatterAddIpData(arr) {
return arr.reduce((item, prev, index) => {
item[index] = `${prev.start || ''}-${prev.end || ''}`
return item
}, [])
}
export const firstUpperCase = str => str.toLowerCase().replace(/^\S/g, s => s.toUpperCase())
export const lowercaseCase = str => str.toLocaleLowerCase()
export function findArrayIndex(arr, key, value) {
return isArray(arr) ? arr.findIndex(item => item[key] === value) : -1
}
let zIndexNum = 20000
export function pMessage(options, callback) {
const { message, duration, type } = options
const zIndex = zIndexNum++
const obj = document.createElement('div')
obj.id = `message${zIndex}`
const className = type || 'success'
obj.innerHTML = `${className
}" style="top: 20px; z-index: ${zIndex};">
${className}">
${message}
`
document.body.appendChild(obj)
setTimeout(() => {
document.body.removeChild(obj)
callback && callback()
}, duration || 2000)
}
export function ipToInt(ip) {
if (!ip) {
throw new Error('E_UNDEFINED_IP')
}
if (!regexIP.test(ip)) {
throw new Error('E_INVALID_IP')
}
return ip
.split('.')
.map((octet, index, array) => {
return parseInt(octet) * Math.pow(256, array.length - index - 1)
})
.reduce((prev, curr) => {
return prev + curr
})
}
export function intToIp(value) {
if (!value) {
throw new Error('E_UNDEFINED_INTEGER')
}
const result = /\d+/.exec(value)
if (!result) {
throw new Error('E_INTEGER_NOT_FOUND')
}
value = result[0]
return [(value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff].join('.')
}
export function intersect(original, arr) {
if (!isArray(original) || !isArray(original)) {
return original
}
const packageData = new Set(arr)
return original.filter(el => packageData.has(el))
}
export function minus(original, arr) {
if (!isArray(original) || !isArray(original)) {
return original
}
const packageData = new Set(arr)
return original.filter(el => !packageData.has(el))
}
export function complement(original, arr) {
if (!isArray(original) || !isArray(original)) {
return original
}
const packageOriginal = minus(original, arr)
const packageData = minus(arr, original)
return [...packageOriginal, ...packageData]
}
export function unionSet(original, arr) {
if (!isArray(original) || !isArray(original)) {
return original
}
return Array.from(new Set([...original, ...arr]))
}
export function dataEmptyFilter(str) {
if (!str && str !== 0) {
return '-'
}
return str
}
export function getMd5(pwd) {
const md5 = crypto.createHash('md5')
md5.update(pwd)
const password = md5.digest('hex')
return password
}
export function getFileMD5(file, onProgress) {
if (!file) return false
const chunkSize = 1024 * 1024 * 2
const { size } = file
const chunks = Math.ceil(size / chunkSize)
let currentChunk = 0
const spark = new SparkMD5.ArrayBuffer()
const fileReader = new FileReader()
function loadNext() {
const start = currentChunk * chunkSize
const end = start + chunkSize >= size ? size : start + chunkSize
fileReader.readAsArrayBuffer(file.slice(start, end))
}
return new Promise((resolve, reject) => {
fileReader.onload = e => {
const sparkObj = spark.append(e.target.result)
currentChunk += 1
if (currentChunk < chunks) {
if (onProgress) {
const percent = parseInt((currentChunk * chunkSize * 100) / size)
onProgress(percent)
}
loadNext()
} else {
onProgress && onProgress(100)
return resolve({
md5: sparkObj.end()
})
}
}
loadNext()
fileReader.onerror = () => {
return reject({
md5: 0
})
}
})
}
export async function getFileSha1(file) {
const reader = new FileReader()
if (!file) {
return ''
}
return new Promise((resolve, reject) => {
reader.onload = function() {
const fileResult = this.result
const fileWordArr = CryptoJs.lib.WordArray.create(fileResult)
const sha1Hash = CryptoJs.SHA1(fileWordArr)
return resolve({
sha1: sha1Hash.toString()
})
}
reader.readAsArrayBuffer(file)
})
}
export const arrayConversion = (value, result) => {
if (isArray(value)) {
value = []
return result
}
}
export const arrayConversionToObject = options =>
options.map(el => el.key).reduce((acc, cur) => ({ ...acc, [cur]: 0 }), {})
export const objectConversionToInitData = options =>
Object.keys(options).reduce((acc, cur) => ({ ...acc, [cur]: 0 }), {})
export let colorData = []
export const serializationDataStyle = (arr, color = 120, parent = false) => {
return arr.map((item, index) => {
chartColor[item.name] && (colorData = chartColor[item.name])
const color = parent ? colorData[0] : colorData[index + 1]
item.itemStyle = {
color
}
item.textStyle = {
color
}
if (item.children && item.children.length) {
serializationDataStyle(item.children, color, false)
}
return item
})
}
export const arrayToHeavy = (data) => Array.from(new Set(data))
export const flattenArray = (data) => data.reduce((flat, toFlat) => flat.concat(Array.isArray(toFlat) ? flattenArray(toFlat) : toFlat), [])
export const updateArrayData = (data, result) => {
remove(result)
data.map((el, index) => result.splice(index, 1, el))
return result
}
export const fillZero = (num) => `${num}`.padStart(2, '0')
export const sum = (arr) => (arr.reduce((acc, cur) => (acc += cur.value), 0))
export const createSizeArr = (size, step = 1) => Array.from(new Array(size), (value, index) => (index * step))
export function getLocalStorage(type = 'unrepaired', name = 'hostLeakFix', result = 0) {
try {
return storage.get(name)[type] || result
} catch (error) {
return result
}
}
export const numberWithCommas = (x) => x.toString().replace(/(\d)(?=(\d{3})+$)/g, '$1,')
export function diffObject(target, source) {
for (const key in target) {
target[key] = source[key] || ''
}
return target
}
export function formatNetworkSpeed(speed, decimals = 2) {
if (!speed) return '0 Bytes'
const num = 1024.00
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const single = Math.floor(Math.log(speed) / Math.log(num))
return `${parseFloat((speed / Math.pow(num, single)).toFixed(decimals))} ${sizes[single]}`
}
export const getPercentWithPrecision = (value, total, precision = 1) => {
if (!value || !total) {
return 0
}
const digits = Math.pow(10, precision)
const result = (isNaN(value) ? 0 : value) / total * digits * 100
return Math.floor(result) / digits
}
export function millionUnitFormat(number, type = 'number') {
if (!`${number}`) {
return 0
}
const len = `${number}`.length
const digits = len > 4 ? 4 : 3
const reg = new RegExp(`(\\d)(?=(?:\\d{${digits}})+$)`)
const regPoint = new RegExp(`(\\d)(?=(?:\\d{${digits}})+$)`, 'g')
const result = `${number}`.replace(reg, digits === 4 ? '$1.' : '$1,')
const point = `${number}`.replace(regPoint, digits === 4 ? '$1.' : '$1,')
const pointLen = point.split('.').length - 1
if (type === 'json') {
return {
name: unitOptions[pointLen],
value: digits === 4 ? Number(result).toFixed(2) / 1 : result,
total: `${digits === 4 ? Number(result).toFixed(2) / 1 : result}${unitOptions[pointLen]}`
}
}
return `${digits === 4 ? Number(result).toFixed(2) / 1 : result}${unitOptions[pointLen]}`
}
export const isObject = function(arg) {
return Object.prototype.toString.call(arg) === '[object Object]'
}
export const isEmptyObject = (data) => {
return !isEmpty(data) && !Object.keys(data).length
}
export const numFormat = (num) => {
var res = num.toString().replace(/\d+/, function(n) {
return n.replace(/(\d)(?=(\d{3})+$)/g, function($1) {
return $1 + ','
})
})
return res
}
export const rsaByPublicKey = (pubKey, value, type = 'encrypt') => {
const encrypt = new JSEncrypt()
encrypt.setPublicKey(pubKey)
return encrypt[type](value)
}