Skip to content

Commit

Permalink
refactor: 保证 isBanned 总为 Boolean
Browse files Browse the repository at this point in the history
  • Loading branch information
SALTWOOD committed Sep 7, 2024
1 parent 430ae13 commit d65225c
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 26 deletions.
34 changes: 32 additions & 2 deletions src/database/cluster.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Ignore, Table, PrimaryKey } from '../sqlite';
import { StatsStorage } from '../statistics/cluster-stats';
import { Utilities } from '../utilities';
import { File } from './file';

@Table('clusters', `
clusterId TEXT PRIMARY KEY UNIQUE,
Expand Down Expand Up @@ -74,8 +76,36 @@ export class ClusterEntity {
this.interval && clearInterval(this.interval);
}

public doOnline(): void {
public doOnline(files: File[]): void {
this.isOnline = true;
this.interval = setInterval(() => {});
this.interval = setInterval(() => {
const file = Utilities.getRandomElement(files);
if (file) {
Utilities.checkSpecfiedFiles([file], this, -5)
.then(result => {
if (!result) {
this.doOffline(`Warden failed: ${file.hash}, ${result}`);
}
})
.catch(error => {
this.doOffline(`Warden failed: ${file.hash}, ${error}`);
});
}
});
}

public getJson(removeSecret: boolean = false, removeSensitive: boolean = false): any {
const convertBanned = ({ isBanned, ...rest }: ClusterEntity) => {
return {
isBanned: Boolean(isBanned),
...rest
};
};
const removeSensitiveInfo = ({ clusterSecret, endpoint, bandwidth, measureBandwidth, port, downReason, ...rest }: {clusterSecret: string, endpoint: string, bandwidth: number, measureBandwidth: number, port: number, downReason: string, [key: string]: any}) => rest;
const removeSecretInfo = ({ clusterSecret, ...rest }: {clusterSecret: string, [key: string]: any}) => rest;
let json: any = convertBanned(this);
if (removeSensitive) json = removeSensitiveInfo(json);
if (removeSecret) json = removeSecretInfo(json);
return json;
}
}
48 changes: 25 additions & 23 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ const logAccess = (req: Request, res: Response) => {
console.log(`${req.method} ${req.originalUrl} ${req.protocol} <${res.statusCode}> - [${ip}] ${userAgent}`);
};

// 使用对象解构来移除敏感信息
const removeSensitiveInfo = ({ clusterSecret, ...rest }: ClusterEntity) => rest;

export class Server {
private app;
private io: SocketIOServer;
Expand Down Expand Up @@ -162,7 +159,7 @@ export class Server {
this.app.get('/93AtHome/list_clusters', (req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(this.db.getEntities<ClusterEntity>(ClusterEntity).map(removeSensitiveInfo)));
res.end(JSON.stringify(this.db.getEntities<ClusterEntity>(ClusterEntity).map(c => c.getJson(true, true))));
});
this.app.get('/93AtHome/list_files', (req, res) => {
res.statusCode = 200;
Expand Down Expand Up @@ -438,18 +435,18 @@ export class Server {

const onlineClustersSorted = onlineClusters
.sort((a, b) => b.traffic - a.traffic)
.map(removeSensitiveInfo);
.map(c => c.getJson(true, true));

const offlineClustersSorted = offlineClusters
.sort((a, b) => b.traffic - a.traffic)
.map(removeSensitiveInfo);
.map(c => c.getJson(true, true));

// 添加 ownerName 并返回 JSON 响应
const result = [
...onlineClustersSorted,
...offlineClustersSorted
].map(c => ({
...c,
...(c as ClusterEntity).getJson(true, true),
ownerName: this.db.getEntity<UserEntity>(UserEntity, c.owner)?.username || ''
}));

Expand Down Expand Up @@ -498,7 +495,7 @@ export class Server {
c.owner = user.id;
this.db.update(c);
});
res.status(200).json(matches.map(c => removeSensitiveInfo(c)));
res.status(200).json(matches.map(c => c.getJson(true, false)));
});
this.app.post('/93AtHome/dashboard/user/unbindCluster', (req: Request, res: Response) => {
const token = req.cookies.token;
Expand All @@ -522,7 +519,7 @@ export class Server {
c.owner = 0;
this.db.update(c);
});
res.status(200).json(matches.map(c => removeSensitiveInfo(c)));
res.status(200).json(matches.map(c => c.getJson(true, false)));
});
this.app.get('/93AtHome/dashboard/user/clusters', (req: Request, res: Response) => {
const token = req.cookies.token;
Expand All @@ -539,14 +536,14 @@ export class Server {
res.setHeader('Content-Type', 'application/json');
if (!clusterId) {
const clusters = this.clusters.filter(c => c.owner === user.id);
res.status(200).json(clusters.map(c => removeSensitiveInfo(c)));
res.status(200).json(clusters.map(c => c.getJson(true, false)));
} else {
const cluster = this.clusters.find(c => c.clusterId === clusterId && c.owner === user.id);
if (!cluster) {
res.status(404).send(); // 集群不存在
return;
}
res.status(200).json(removeSensitiveInfo(cluster));
res.status(200).json(cluster.getJson(true, false));
}
});
this.app.post('/93AtHome/dashboard/user/cluster/profile', (req: Request, res: Response) => {
Expand Down Expand Up @@ -590,7 +587,7 @@ export class Server {
}

this.db.update(cluster);
res.status(200).json(removeSensitiveInfo(cluster));
res.status(200).json(cluster.getJson(true, false));
});

this.app.get('/93AtHome/dashboard/user/cluster/reset_secret', (req: Request, res: Response) => {
Expand Down Expand Up @@ -649,7 +646,7 @@ export class Server {
this.db.insert(cluster);
this.clusters.push(cluster);
res.setHeader('Content-Type', 'application/json');
res.status(200).json(cluster);
res.status(200).json(cluster.getJson(false, false));
});
this.app.post('/93AtHome/super/cluster/remove', (req: Request, res: Response) => {
if (!Utilities.verifyAdmin(req, res, this.db)) return;
Expand Down Expand Up @@ -683,7 +680,7 @@ export class Server {
cluster.isBanned = Number(data.ban);
this.db.update(cluster);
res.setHeader('Content-Type', 'application/json');
res.status(200).json(removeSensitiveInfo(cluster));
res.status(200).json(cluster.getJson(true, false));
});
this.app.post('/93AtHome/super/cluster/profile', (req: Request, res: Response) => {
if (!Utilities.verifyAdmin(req, res, this.db)) return;
Expand All @@ -707,7 +704,7 @@ export class Server {

this.db.update(cluster);
res.setHeader('Content-Type', 'application/json');
res.status(200).json(removeSensitiveInfo(cluster));
res.status(200).json(cluster.getJson(true, false));
});
}

Expand Down Expand Up @@ -752,7 +749,8 @@ export class Server {
this.io.on('connection', (socket) => {
console.log(`SOCKET ${socket.handshake.url} socket.io <CONNECTED> - [${socket.handshake.headers["x-real-ip"] || socket.handshake.address}] ${socket.handshake.headers['user-agent']}`);

socket.on('enable', (data, ack: Function) => {
socket.on('enable', (data, callback: Function) => {
const ack = callback ? callback : (...rest: any[]) => {};
const enableData = data as {
host: string,
port: number,
Expand Down Expand Up @@ -789,15 +787,19 @@ export class Server {
ack({ message: message });
return;
} else {
cluster.isOnline = true;
cluster.downReason = "null";
cluster.doOnline(this.files);
this.db.update(cluster);
ack([null, true]);
}
})
.catch(err => {
ack({ message: err.message });
console.error(err);
});
});

socket.on('keep-alive', (data, ack: Function) => {
socket.on('keep-alive', (data, callback: Function) => {
const ack = callback ? callback : (...rest: any[]) => {};
const keepAliveData = data as {
time: string,
hits: number,
Expand Down Expand Up @@ -828,17 +830,17 @@ export class Server {
}
});

socket.on('disable', (data, ack: Function) => {
socket.on('disable', (data, callback: Function) => {
const ack = callback ? callback : (...rest: any[]) => {};
const cluster = this.sessionToClusterMap.get(socket.id);

if (!cluster || !cluster.isOnline) {
ack([null, false]);
}
else {
console.log(`SOCKET ${socket.handshake.url} socket.io <DISABLE> - [${socket.handshake.headers["x-real-ip"] || socket.handshake.address}] ${socket.handshake.headers['user-agent']}`);
cluster.isOnline = false;
cluster.doOffline("Client disabled");
socket.send('Bye. Have a good day!');
cluster.downReason = "Client disabled";
cluster.downTime = Math.floor(Date.now() / 1000);
ack([null, true]);
this.db.update(cluster);
Expand All @@ -853,7 +855,7 @@ export class Server {
if (cluster.isOnline) {
cluster.downReason = "Client disconnected";
cluster.downTime = Math.floor(Date.now() / 1000);
cluster.isOnline = false;
cluster.doOffline("Client disconnected")
this.db.update(cluster);
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ export class Utilities {
return array[randomIndex];
}

public static getUrl(file: File, cluster: ClusterEntity): string { return `http://${cluster.endpoint}:${cluster.port}/download/${file.hash}?${Utilities.getSign(file.hash, cluster.clusterSecret)}` }

public static async checkUrl(url: string): Promise<{ url: string; hash: string }> {
try {
const response = await axios.get(url, { responseType: 'arraybuffer' });
Expand Down Expand Up @@ -197,7 +199,7 @@ export class Utilities {
let result: string | null = "Error: This value should never be returned. if you see this message, please contact to the administrator.";

try {
const urls = files.map(f => `http://${cluster.endpoint}:${cluster.port}/download/${f.hash}?${Utilities.getSign(f.hash, cluster.clusterSecret)}`);
const urls = files.map(f => Utilities.getUrl(f, cluster));
for (const [url, file] of Utilities.zip(urls, files)) {
const realHash = file.hash;
const remote = await Utilities.checkUrl(url);
Expand Down

0 comments on commit d65225c

Please sign in to comment.