xg-project-library/js/common.js
2024-11-25 18:37:12 +08:00

208 lines
7.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const projectBaseURL = "https://project.gter.net"
if (["localhost", "127.0.0.1"].includes(location.hostname)) {
axios.defaults.headers = {
Authorization: "97d1c7b2fe6dec05aaf52c0f3b9130e8",
}
}
function $ajax(url) {
var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}
url = url.indexOf("https://") > -1 ? url : projectBaseURL + url
if (["localhost", "127.0.0.1"].includes(location.hostname)) data["authorization"] = "97d1c7b2fe6dec05aaf52c0f3b9130e8"
return new Promise(function (resolve, reject) {
axios
.post(url, data, {
emulateJSON: true,
withCredentials: true,
})
.then(function (res) {
var data = typeof res.data == "string" ? JSON.parse(res.data) : res.data
if (data.code == 401) {
openShowWindow()
reject()
}
if (data.code == 201) creationAlertBox("error", data.message || data.msg)
resolve(data)
})
.catch(err => {
if (err.response?.status == 401) openShowWindow()
})
})
}
function $ajaxget(url, data) {
if (!data) data = {}
// data["authorization"] = "97d1c7b2fe6dec05aaf52c0f3b9130e8"
if (["localhost", "127.0.0.1"].includes(location.hostname)) data["authorization"] = "97d1c7b2fe6dec05aaf52c0f3b9130e8"
url = url.indexOf("https://") > -1 ? url : projectBaseURL + url
url += objectToQueryString(data)
return new Promise(function (resolve, reject) {
axios
.get(
url,
{},
{
emulateJSON: true,
withCredentials: true,
}
)
.then(function (res) {
var data = typeof res.data == "string" ? JSON.parse(res.data) : res.data
if (data.code == 401) {
openShowWindow()
reject()
}
if (data.code == 201) creationAlertBox("error", data.message || data.msg)
resolve(data)
})
.catch(error => {
if (error.response?.status == 401) openShowWindow()
reject(error)
})
})
}
function randomString(n) {
let str = "abcdefghijklmnopqrstuvwxyz9876543210"
let tmp = "",
i = 0,
l = str.length
for (i = 0; i < n; i++) {
tmp += str.charAt(Math.floor(Math.random() * l))
}
return tmp
}
function formatNumberWithSpaces(number) {
if (typeof number != "string") number = ""
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
// 将一个JavaScript对象转换为路由参数的形式将键值对转换为key=value的形式
function objectToQueryString(obj = {}) {
const queryString = Object.keys(obj)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]))
.join("&")
return queryString ? "?" + queryString : ""
}
function decodeKey(encrypted, key) {
return new Promise((resolve, reject) => {
try {
const storedData = localStorage.getItem("basicData")
const basicData = JSON.parse(storedData)
if (!key) key = basicData.encodekey
const encryptedData = CryptoJS.enc.Base64.parse(encrypted)
const decrypted = CryptoJS.AES.decrypt(
{
ciphertext: encryptedData,
},
CryptoJS.enc.Utf8.parse(key),
{
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}
)
const text = JSON.parse(decrypted.toString(CryptoJS.enc.Utf8))
resolve(text)
} catch (error) {
reject()
}
})
}
function getBaseData() {
return new Promise((resolve, reject) => {
const storedTime = localStorage.getItem("dataTimestamp")
const storedData = localStorage.getItem("basicData")
const currentTime = new Date().getTime()
const timeDiff = currentTime - parseInt(storedTime)
console.log(storedTime && storedData && timeDiff <= 5 * 60 * 1000)
if (storedTime && storedData && timeDiff <= 5 * 60 * 1000) {
// 在5分钟内使用本地存储的数据
const basicData = JSON.parse(storedData)
// 处理数据
resolve(basicData)
return
}
console.log("222");
$ajaxget("/api/home/basicData").then(res => {
if (res.code != 200) return
const data = res.data
const user = data.user
const basicData = {
contrastcount: data.contrastcount || 0,
university: data.university,
discipline: data.discipline,
rankings: data.rankings,
encodekey: data.encodekey,
user,
}
if (user.uin > 0) {
localStorage.setItem("dataTimestamp", new Date().getTime())
localStorage.setItem("basicData", JSON.stringify(basicData))
} else {
localStorage.removeItem("basicData")
localStorage.removeItem("dataTimestamp")
}
resolve(basicData)
})
})
}
function openShowWindow() {
showWindow("login", "https://passport.gter.net/login/ajax", "get", -1, { cover: true })
}
function strtimeago(dateStr) {
dateStr = dateStr + "" // 反之传入的不是字符串
dateStr = dateStr.replaceAll("-", "/") // 修改格式
var minute = 1000 * 60 //把分,时,天,周,半个月,一个月用毫秒表示
var hour = minute * 60
var day = hour * 24
var now = new Date().getTime() //获取当前时间毫秒
let objectTime = new Date(dateStr).getTime()
var diffValue = now - objectTime //时间差
if (diffValue < 0) return "刚刚"
var minC = diffValue / minute //计算时间差的分,时,天,周,月
var hourC = diffValue / hour
var dayC = diffValue / day
const diffInMilliseconds = now - objectTime
const diffInYears = diffInMilliseconds / (1000 * 60 * 60 * 24 * 365)
const diffInMonths = diffInYears * 12
let result = ""
if (dayC >= 7) {
var datetime = new Date(dateStr)
var Nyear = datetime.getFullYear()
var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1
var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate()
var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours()
var Nmin = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes()
if (diffInYears >= 1) result = Math.floor(diffInYears) + "年前"
else if (diffInMonths >= 1) result = Math.floor(diffInMonths) + "个月前"
} else if (dayC >= 1) result = parseInt(dayC) + "天前"
else if (hourC >= 1 && hourC <= 24) result = parseInt(hourC) + "小时前"
else if (minC >= 1 && minC <= 60) result = parseInt(minC) + "分钟前"
else result = "刚刚"
return result
}