-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
320 lines (265 loc) · 11 KB
/
server.js
File metadata and controls
320 lines (265 loc) · 11 KB
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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
const fs = require('fs');
const path = require('path');
// コメントログファイルのパス
const LOG_DIR = path.join(__dirname, 'public', 'chatlogs');
// ログディレクトリが存在しない場合は作成
if (!fs.existsSync(LOG_DIR)) {
fs.mkdirSync(LOG_DIR, { recursive: true });
console.log('Created log directory:', LOG_DIR);
}
// ファイル名として安全な文字列に変換する関数
function sanitizeFilename(str) {
// 英数字、ハイフン、アンダースコア以外を置換
return str.replace(/[^a-zA-Z0-9_-]/g, '_');
}
// コメントをログファイルに追記する関数
function saveCommentLog(data, room) {
try {
if (!room) {
console.warn('Room name is empty, skipping log save');
return;
}
// room名をファイル名として安全な形式に変換
const safeRoomName = sanitizeFilename(room);
const logFile = path.join(LOG_DIR, `${safeRoomName}.log`);
const timestamp = new Date().toISOString();
const logEntry = JSON.stringify({
timestamp,
room,
username: data.my_name || 'Anonymous',
comment: data.comment,
emoji: data.flg_emoji || false,
sound: data.flg_sound || false,
socketid: data.socketid
});
// ログファイルに追記(1行ずつ)
fs.appendFileSync(logFile, logEntry + '\n', 'utf8');
} catch (error) {
console.error('Error saving comment log:', error);
}
}
// ローカル開発環境では3000番ポート、本番環境では80番ポート
var port = process.env.PORT || (process.env.NODE_ENV === 'production' ? 80 : 3000);
var express = require('express');
var app = express();
// JSONボディパーサーを追加(ダッシュボードAPI用)
app.use(express.json());
// CORS設定
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
// ダッシュボードAPIルーターを読み込み
const dashboardRouter = require('./dashboard-api');
app.use(dashboardRouter);
var server = app.listen(port, () => console.log('listening on', port));
app.use(express.static('./public'));
let broadcaster;
var socket = require('socket.io');
const options = {
serveClient: true,
cors: {
origin: "*",
methods: ["GET", "POST"],
credentials: false
},
pingInterval: 15000, // サーバからのping間隔(ミリ秒)
pingTimeout: 10000 // pongが返らなければ切断(ミリ秒)
//pingTimeout: 25000,
//pingInterval: 5000,
//transports: ['polling']
//transports: ['websockets']
}
var io = socket(server, options);
// ルームごとの状態を保持するためのメタデータ格納オブジェクト
// roomState[roomName] = { deactivate_comment_control: boolean }
const roomState = {};
function getRoomUserCount(roomName) {
const roomRef = io.sockets.adapter.rooms.get(roomName);
return roomRef ? roomRef.size : 0;
}
io.on('connection', (socket) => {
console.log('connection', socket.id);
var room = "";
var room_master = "-master";
// ルームの制御フラグは roomState に集約(ソケット毎に保持しない)
// 接続者に対してコネクションを作ったことを知らせるメッセージ
socket.emit('you_are_connected');
socket.on("join", (room_to_join) => {
if (room_to_join == "") room_to_join = "undefined-room"
socket.join(room_to_join);
console.log(socket.id, " joined to ", room_to_join);
room = room_to_join;
// ルーム状態初期化
if (!roomState[room]) {
roomState[room] = { deactivate_comment_control: false };
}
const number_of_users = getRoomUserCount(room);
console.log('user count (join):', number_of_users);
// we store the username in the socket session for this client
socket.username = socket.id; //username;
socket.emit('login', {
numUsers: number_of_users,
deactivate_comment_control: roomState[room].deactivate_comment_control
});
// echo globally (all clients) that a person has connected
socket.to(room).emit('user joined', {
username: socket.username,
numUsers: number_of_users
});
});
socket.on("join-as-master", (room_to_join) => {
if (room_to_join == "") room_to_join = "undefined-room"
socket.join(room_to_join);
//console.log(socket.id, "joined master to ", room_to_join);
room_master = room_to_join;
});
// when the client emits 'new message', this listens and executes
socket.on('new message', (data) => {
// we tell the client to execute 'new message'
socket.to(room).emit('new message', {
username: socket.username,
message: data
});
});
// when the client emits 'new message', this listens and executes
socket.on('comment', (data) => {
// we tell the client to execute 'new message'
data.socketid = socket.id;
// コメントをログファイルに保存
saveCommentLog(data, room);
// 全員に送信
socket.to(room).emit('comment', data);
});
socket.on('delete comment', (data) => {
socket.to(room).emit('delete comment', data);
});
socket.on('letter', (data) => {
socket.to(room_master).emit('letter', data);
});
socket.on('deactivate_comment_control', (data) => {
if (room === "") {
return; // join 前は無視
}
if (!roomState[room]) {
roomState[room] = { deactivate_comment_control: false };
}
roomState[room].deactivate_comment_control = data.control;
socket.to(room).emit('deactivate_comment_control', data);
});
// when the user disconnects.. perform this
socket.on('disconnect', () => {
// disconnect イベント時点ではアダプタから既に除去されているので再計算
const number_of_users = getRoomUserCount(room);
socket.to(room).emit('user left', {
username: socket.username,
numUsers: number_of_users
});
socket.to(broadcaster).emit("disconnectPeer", socket.id, number_of_users);
// 明示的 leave は不要(Socket.IO が処理)
});
});
// チャットログの自動削除設定
// ログの保持期間(古いログを削除する基準)
const LOG_RETENTION_DAYS = 21; // 日数で指定(例: 21 = 3週間)
// const LOG_RETENTION_HOURS = 1; // テスト用: 時間で指定する場合はこちらを使用
// const LOG_RETENTION_MINUTES = 2; // テスト用: 分で指定する場合はこちらを使用
// クリーンアップチェック間隔(どのくらいの頻度で古いログをチェックするか)
const CLEANUP_CHECK_INTERVAL_HOURS = 24; // 時間で指定(例: 24 = 1日1回)
// const CLEANUP_CHECK_INTERVAL_MINUTES = 1; // テスト用: 分で指定する場合はこちらを使用
// 保持期間の計算(優先順位: MINUTES > HOURS > DAYS)
const getRetentionPeriodMs = () => {
if (typeof LOG_RETENTION_MINUTES !== 'undefined') {
return LOG_RETENTION_MINUTES * 60 * 1000;
} else if (typeof LOG_RETENTION_HOURS !== 'undefined') {
return LOG_RETENTION_HOURS * 60 * 60 * 1000;
} else {
return LOG_RETENTION_DAYS * 24 * 60 * 60 * 1000;
}
};
// チェック間隔の計算(優先順位: MINUTES > HOURS)
const getCheckIntervalMs = () => {
if (typeof CLEANUP_CHECK_INTERVAL_MINUTES !== 'undefined') {
return CLEANUP_CHECK_INTERVAL_MINUTES * 60 * 1000;
} else {
return CLEANUP_CHECK_INTERVAL_HOURS * 60 * 60 * 1000;
}
};
// 設定の表示用テキスト生成
const getRetentionPeriodText = () => {
if (typeof LOG_RETENTION_MINUTES !== 'undefined') {
return `${LOG_RETENTION_MINUTES} minutes`;
} else if (typeof LOG_RETENTION_HOURS !== 'undefined') {
return `${LOG_RETENTION_HOURS} hours`;
} else {
return `${LOG_RETENTION_DAYS} days`;
}
};
const getCheckIntervalText = () => {
if (typeof CLEANUP_CHECK_INTERVAL_MINUTES !== 'undefined') {
return `every ${CLEANUP_CHECK_INTERVAL_MINUTES} minutes`;
} else {
return `every ${CLEANUP_CHECK_INTERVAL_HOURS} hours`;
}
};
// 古いチャットログを削除する関数
function cleanupOldChatLogs() {
try {
const files = fs.readdirSync(LOG_DIR);
const now = Date.now();
const retentionPeriodMs = getRetentionPeriodMs();
let deletedCount = 0;
files.forEach(file => {
const filePath = path.join(LOG_DIR, file);
// .logファイルのみ対象
if (path.extname(file) !== '.log') {
return;
}
try {
const stats = fs.statSync(filePath);
const lastModified = stats.mtime.getTime();
const ageInMs = now - lastModified;
// 保持期間を超えた場合は削除
if (ageInMs > retentionPeriodMs) {
fs.unlinkSync(filePath);
deletedCount++;
const ageInMinutes = Math.floor(ageInMs / (60 * 1000));
const ageInHours = Math.floor(ageInMs / (60 * 60 * 1000));
const ageInDays = Math.floor(ageInMs / (24 * 60 * 60 * 1000));
let ageText;
if (ageInDays > 0) {
ageText = `${ageInDays} days old`;
} else if (ageInHours > 0) {
ageText = `${ageInHours} hours old`;
} else {
ageText = `${ageInMinutes} minutes old`;
}
console.log(`Deleted old chat log: ${file} (${ageText}, last modified: ${stats.mtime.toISOString()})`);
}
} catch (error) {
console.error(`Error processing file ${file}:`, error);
}
});
if (deletedCount > 0) {
console.log(`Cleanup completed: ${deletedCount} old chat log(s) deleted`);
} else {
console.log('Cleanup completed: No old chat logs to delete');
}
} catch (error) {
console.error('Error during chat log cleanup:', error);
}
}
// 定期的にチャットログをクリーンアップ
const CLEANUP_INTERVAL_MS = getCheckIntervalMs();
setInterval(cleanupOldChatLogs, CLEANUP_INTERVAL_MS);
// サーバー起動時にも一度実行
cleanupOldChatLogs();
console.log(`Chat log cleanup scheduled:`);
console.log(` - Check interval: ${getCheckIntervalText()}`);
console.log(` - Retention period: ${getRetentionPeriodText()}`);