You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
uptime-kuma/src/mixins/socket.js

350 lines
10 KiB

import dayjs from "dayjs";
3 years ago
import { io } from "socket.io-client";
import { useToast } from "vue-toastification";
3 years ago
const toast = useToast()
let socket;
export default {
data() {
return {
info: { },
3 years ago
socket: {
token: null,
firstConnect: true,
connected: false,
3 years ago
connectCount: 0,
3 years ago
},
remember: (localStorage.remember !== "0"),
userTimezone: localStorage.timezone || "auto",
3 years ago
allowLoginDialog: false, // Allowed to show login dialog, but "loggedIn" have to be true too. This exists because prevent the login dialog show 0.1s in first before the socket server auth-ed.
loggedIn: false,
3 years ago
monitorList: { },
heartbeatList: { },
importantHeartbeatList: { },
avgPingList: { },
uptimeList: { },
certInfoList: {},
notificationList: [],
windowWidth: window.innerWidth,
showListMobile: false,
connectionErrorMsg: "Cannot connect to the socket server. Reconnecting..."
3 years ago
}
},
created() {
3 years ago
window.addEventListener("resize", this.onResize);
let wsHost;
const env = process.env.NODE_ENV || "production";
if (env === "development" || localStorage.dev === "dev") {
wsHost = ":3001"
} else {
wsHost = ""
}
socket = io(wsHost, {
3 years ago
transports: ["websocket"],
3 years ago
});
3 years ago
socket.on("info", (info) => {
this.info = info;
});
3 years ago
socket.on("setup", (monitorID, data) => {
3 years ago
this.$router.push("/setup")
});
socket.on("autoLogin", (monitorID, data) => {
this.loggedIn = true;
this.storage().token = "autoLogin";
this.allowLoginDialog = false;
});
socket.on("monitorList", (data) => {
// Add Helper function
Object.entries(data).forEach(([monitorID, monitor]) => {
monitor.getUrl = () => {
try {
return new URL(monitor.url);
} catch (_) {
return null;
}
};
});
3 years ago
this.monitorList = data;
});
3 years ago
socket.on("notificationList", (data) => {
this.notificationList = data;
});
3 years ago
socket.on("heartbeat", (data) => {
3 years ago
if (! (data.monitorID in this.heartbeatList)) {
this.heartbeatList[data.monitorID] = [];
}
this.heartbeatList[data.monitorID].push(data)
// Add to important list if it is important
// Also toast
if (data.important) {
if (data.status === 0) {
toast.error(`[${this.monitorList[data.monitorID].name}] [DOWN] ${data.msg}`, {
timeout: false,
});
} else if (data.status === 1) {
toast.success(`[${this.monitorList[data.monitorID].name}] [Up] ${data.msg}`, {
timeout: 20000,
});
} else {
toast(`[${this.monitorList[data.monitorID].name}] ${data.msg}`);
}
if (! (data.monitorID in this.importantHeartbeatList)) {
this.importantHeartbeatList[data.monitorID] = [];
}
this.importantHeartbeatList[data.monitorID].unshift(data)
}
3 years ago
});
3 years ago
socket.on("heartbeatList", (monitorID, data) => {
3 years ago
if (! (monitorID in this.heartbeatList)) {
this.heartbeatList[monitorID] = data;
} else {
this.heartbeatList[monitorID] = data.concat(this.heartbeatList[monitorID])
}
});
3 years ago
socket.on("avgPing", (monitorID, data) => {
this.avgPingList[monitorID] = data
});
3 years ago
socket.on("uptime", (monitorID, type, data) => {
3 years ago
this.uptimeList[`${monitorID}_${type}`] = data
});
3 years ago
socket.on("certInfo", (monitorID, data) => {
this.certInfoList[monitorID] = JSON.parse(data)
});
3 years ago
socket.on("importantHeartbeatList", (monitorID, data) => {
if (! (monitorID in this.importantHeartbeatList)) {
this.importantHeartbeatList[monitorID] = data;
} else {
this.importantHeartbeatList[monitorID] = data.concat(this.importantHeartbeatList[monitorID])
}
});
3 years ago
socket.on("connect_error", (err) => {
console.error(`Failed to connect to the backend. Socket.io connect_error: ${err.message}`);
this.connectionErrorMsg = `Cannot connect to the socket server. [${err}] Reconnecting...`;
this.socket.connected = false;
this.socket.firstConnect = false;
});
3 years ago
socket.on("disconnect", () => {
3 years ago
console.log("disconnect")
this.connectionErrorMsg = "Lost connection to the socket server. Reconnecting...";
3 years ago
this.socket.connected = false;
});
3 years ago
socket.on("connect", () => {
3 years ago
console.log("connect")
this.socket.connectCount++;
3 years ago
this.socket.connected = true;
3 years ago
// Reset Heartbeat list if it is re-connect
if (this.socket.connectCount >= 2) {
this.clearData()
3 years ago
}
3 years ago
let token = this.storage().token;
if (token) {
if (token !== "autoLogin") {
this.loginByToken(token)
} else {
// Timeout if it is not actually auto login
setTimeout(() => {
if (! this.loggedIn) {
this.allowLoginDialog = true;
this.$root.storage().removeItem("token");
}
}, 5000);
}
3 years ago
} else {
this.allowLoginDialog = true;
}
3 years ago
this.socket.firstConnect = false;
3 years ago
});
},
methods: {
3 years ago
cancelActiveList() {
this.$root.showListMobile = false;
},
onResize() {
this.windowWidth = window.innerWidth;
},
storage() {
return (this.remember) ? localStorage : sessionStorage;
},
3 years ago
getSocket() {
3 years ago
return socket;
3 years ago
},
3 years ago
3 years ago
toastRes(res) {
if (res.ok) {
toast.success(res.msg);
} else {
toast.error(res.msg);
}
},
3 years ago
3 years ago
login(username, password, callback) {
socket.emit("login", {
username,
password,
}, (res) => {
if (res.ok) {
this.storage().token = res.token;
3 years ago
this.socket.token = res.token;
this.loggedIn = true;
// Trigger Chrome Save Password
3 years ago
history.pushState({}, "")
3 years ago
}
callback(res)
})
},
3 years ago
3 years ago
loginByToken(token) {
socket.emit("loginByToken", token, (res) => {
this.allowLoginDialog = true;
if (! res.ok) {
this.logout()
} else {
this.loggedIn = true;
}
})
},
3 years ago
3 years ago
logout() {
this.storage().removeItem("token");
3 years ago
this.socket.token = null;
this.loggedIn = false;
3 years ago
this.clearData()
3 years ago
},
3 years ago
3 years ago
add(monitor, callback) {
socket.emit("add", monitor, callback)
},
3 years ago
3 years ago
deleteMonitor(monitorID, callback) {
socket.emit("deleteMonitor", monitorID, callback)
},
clearData() {
console.log("reset heartbeat list")
this.heartbeatList = {}
this.importantHeartbeatList = {}
},
3 years ago
},
computed: {
isMobile() {
return this.windowWidth <= 767.98;
},
timezone() {
if (this.userTimezone === "auto") {
return dayjs.tz.guess()
}
3 years ago
return this.userTimezone
},
3 years ago
lastHeartbeatList() {
let result = {}
for (let monitorID in this.heartbeatList) {
let index = this.heartbeatList[monitorID].length - 1;
result[monitorID] = this.heartbeatList[monitorID][index];
}
return result;
},
statusList() {
let result = {}
3 years ago
3 years ago
let unknown = {
text: "Unknown",
3 years ago
color: "secondary",
3 years ago
}
for (let monitorID in this.lastHeartbeatList) {
let lastHeartBeat = this.lastHeartbeatList[monitorID]
if (! lastHeartBeat) {
result[monitorID] = unknown;
} else if (lastHeartBeat.status === 1) {
result[monitorID] = {
text: "Up",
3 years ago
color: "primary",
3 years ago
};
} else if (lastHeartBeat.status === 0) {
result[monitorID] = {
text: "Down",
3 years ago
color: "danger",
3 years ago
};
} else if (lastHeartBeat.status === 2) {
result[monitorID] = {
text: "Pending",
3 years ago
color: "warning",
};
3 years ago
} else {
result[monitorID] = unknown;
}
}
return result;
3 years ago
},
},
watch: {
// Reload the SPA if the server version is changed.
"info.version"(to, from) {
3 years ago
if (from && from !== to) {
window.location.reload()
}
},
remember() {
localStorage.remember = (this.remember) ? "1" : "0"
3 years ago
},
3 years ago
},
3 years ago
}