Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
6720 lines (6113 loc) · 282 KB
/
Copy pathserver.js
File metadata and controls
6720 lines (6113 loc) · 282 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============ 智能考勤系统 API v3.5.1 ============
// 功能:学号登录、考勤密码保存、 自动签到订阅、邮箱VIP(Resend)、卡密系统、管理员后台
// 包含:邀请功能、系统通知配置、邮件宣传信息、时区修复、管理员删除用户、管理员代签到
// 新增:用户留言反馈系统
const express = require('express');
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const cron = require('node-cron');
const rateLimit = require('express-rate-limit');
const { spawn } = require('child_process');
const path = require('path');
const crypto = require('crypto');
const wxpusher = require('./wxpusherService');
const fs = require('fs');
const http = require('http');
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
fs.mkdirSync(uploadsDir, { recursive: true });
}
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
// ============ 微信回调限流(公开接口,防恶意刷库 / 微信轰炸)============
// 按「客户端 IP」限流 + 全局限流兜底;IP 优先取 Cloudflare / 代理头,取不到再退回 socket IP。
function callbackClientIp(req) {
const cf = String(req.headers['cf-connecting-ip'] || '').trim();
if (cf) return cf;
const xff = String(req.headers['x-forwarded-for'] || '').split(',')[0].trim();
if (xff) return xff;
return req.ip || (req.socket && req.socket.remoteAddress) || 'unknown';
}
const WX_CALLBACK_PER_IP_LIMIT = Math.max(1, parseInt(process.env.WX_CALLBACK_RATE_LIMIT || '60', 10) || 60);
const WX_CALLBACK_GLOBAL_LIMIT = Math.max(1, parseInt(process.env.WX_CALLBACK_GLOBAL_LIMIT || '240', 10) || 240);
function callbackLimitHandler(label) {
return (req, res) => {
console.warn(`[wxpusher-callback] 触发限流(${label}) ip=${callbackClientIp(req)}`);
res.status(429).json({ success: false, message: '请求过于频繁,请稍后再试' });
};
}
const wxCallbackIpLimiter = rateLimit({
windowMs: 60 * 1000,
limit: WX_CALLBACK_PER_IP_LIMIT,
standardHeaders: 'draft-7',
legacyHeaders: false,
validate: false,
keyGenerator: callbackClientIp,
handler: callbackLimitHandler('per-ip')
});
const wxCallbackGlobalLimiter = rateLimit({
windowMs: 60 * 1000,
limit: WX_CALLBACK_GLOBAL_LIMIT,
standardHeaders: false,
legacyHeaders: false,
validate: false,
keyGenerator: () => 'global',
handler: callbackLimitHandler('global')
});
const PlantData = require('./PlantData');//zhiwu
const ControlCmd = require('./ControlCmd');
const membership = require('./membership');
const notifyPrefs = require('./notificationPrefs');
const replyService = require('./replyService');
const { isSubscriptionDueToday } = require('./autoSignSchedule');
const { batchTimeoutMs, createRunLock } = require('./autoSignRuntime');
const PYTHON_BIN = process.env.PYTHON_BIN || 'python3';
const AUTO_SIGN_DRY_RUN = process.env.AUTO_SIGN_DRY_RUN === 'true';
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST']
}
});
// ============ WebSocket 用户映射 ============
const userSockets = new Map();
io.on('connection', (socket) => {
console.log('🔌 WebSocket 客户端已连接:', socket.id);
socket.on('bindUser', (userId) => {
if (userId) {
userSockets.set(userId, socket.id);
console.log(`👤 用户 ${userId} 绑定 WebSocket: ${socket.id}`);
}
});
socket.on('disconnect', () => {
for (const [uid, sid] of userSockets.entries()) {
if (sid === socket.id) {
userSockets.delete(uid);
console.log(`👤 用户 ${uid} 断开 WebSocket`);
}
}
});
});
// ============ CORS 配置 ============
const allowedOrigins = [
'https://login.agai.online',
'https://api.agai.online',
'https://attendance-frontend.ag985211ag.workers.dev',
'http://localhost:3000',
'http://127.0.0.1:5500',
'http://localhost:5500'
];
app.use(cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
console.log('❌ CORS 拒绝的域名:', origin);
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
optionsSuccessStatus: 200
}));
app.options('*', (req, res) => {
res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', 'true');
res.sendStatus(200);
});
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
app.use('/uploads', express.static(uploadsDir));
// ============ 数据库连接 ============
const MONGODB_URI = process.env.MONGODB_URI;
let mongoRetryTimer = null;
async function connectMongo() {
if (!MONGODB_URI) {
console.error('❌ MONGODB_URI 未设置!');
return;
}
try {
await mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 15000 });
console.log('✅ MongoDB 连接成功');
} catch (err) {
console.error('❌ MongoDB 连接失败:', err.message);
if (mongoRetryTimer) clearTimeout(mongoRetryTimer);
mongoRetryTimer = setTimeout(connectMongo, 15000);
}
}
connectMongo();
// ============ 时区辅助函数 ============
function getBeijingTime(date = new Date()) {
return date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
}
// ============ 生成邀请码 ============
function generateInviteCode(length = 8) {
return crypto.randomBytes(length).toString('hex').substring(0, length).toUpperCase();
}
// ============ 数据模型 ============
const userSchema = new mongoose.Schema({
studentId: { type: String, required: true, unique: true },
name: { type: String, default: '' },
email: { type: String, default: '' },
emailVerified: { type: Boolean, default: false },
isVip: { type: Boolean, default: false },
vipExpireAt: { type: Date, default: null },
vipTier: { type: String, enum: membership.TIER_VALUES, default: 'FREE' },
vipStartAt: { type: Date, default: null },
signCredits: { type: Number, default: 0 },
signCreditsExpireAt: { type: Date, default: null },
checkinStreak: { type: Number, default: 0 },
lastCheckinDate: { type: String, default: '' },
checkinTotal: { type: Number, default: 0 },
// 新手引导是否已完成/跳过(存在账号上,换设备也不会反复弹)
onboardingDone: { type: Boolean, default: false },
onboardingDoneAt: { type: Date, default: null },
// 考研意向预约(用于后续考研项目统计)
kaoyanIntent: { type: Boolean, default: false },
kaoyanIntentAt: { type: Date, default: null },
lastRenewalReminderDays: { type: Number, default: 0 },
lastRenewalReminderAt: { type: Date, default: null },
// 管理员留下的站内通知:用户下次登录/打开仪表盘时弹一次(不消耗邮件额度)
notices: [{
title: { type: String, default: '' },
content: { type: String, default: '' },
level: { type: String, default: 'warning' },
createdAt: { type: Date, default: Date.now }
}],
role: { type: String, enum: ['user', 'admin'], default: 'user' },
// 微信通知绑定(WxPusher 服务号,无需装 App)
wxpusherUid: { type: String, default: '' },
wxpusherBindTime: { type: Date, default: null },
// 本次绑定会话的开始时间:扫码后靠它识别「刚刚出现的订阅者」
wxpusherBindSession: { type: Date, default: null },
// 签到结果通知偏好(HANDOFF §16)
// notifyChannels 未设置(undefined)= 沿用旧默认;显式数组(含 [])= 用户自己选过
notifyChannels: { type: [String], default: undefined, enum: ['wechat', 'email'] },
notifyLevel: { type: String, enum: ['failure_only', 'always'], default: 'always' },
notifyUpdatedAt: { type: Date, default: null },
isActive: { type: Boolean, default: true },
attendancePassword: { type: String, default: 'Ahgydx@920' },
createdAt: { type: Date, default: Date.now },
lastLogin: Date,
totalSignCount: { type: Number, default: 0 },
successSignCount: { type: Number, default: 0 },
// 邀请功能字段
inviteCode: { type: String, unique: true, sparse: true },
invitedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
inviteCount: { type: Number, default: 0 },
// 二手市场收款码
payQR: {
wechat: { type: String, default: '' },
alipay: { type: String, default: '' }
},
isGuest: { type: Boolean, default: false },
source: { type: String, enum: ['attendance', 'market'], default: 'attendance' }
});
const subscriptionSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
name: { type: String, default: '晚寝签到' },
enabled: { type: Boolean, default: true },
scheduleType: { type: String, enum: ['daily', 'weekdays', 'custom'], default: 'weekdays' },
customDays: { type: [Number], default: [1, 2, 3, 4, 5] },
signTime: { type: String, default: '21:35' },
maxRetries: { type: Number, default: 3 },
notifyOnSuccess: { type: Boolean, default: true },
notifyOnFailure: { type: Boolean, default: true },
// 因会员到期/权益撤销被系统自动关闭(重新有权限时会自动恢复)
autoDisabledBySystem: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
const signLogSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
subscriptionId: { type: mongoose.Schema.Types.ObjectId, ref: 'Subscription' },
subscriptionName: { type: String, default: '手动签到' },
status: { type: String, enum: ['success', 'failed', 'pending'] },
message: { type: String, default: '' },
signTime: { type: Date, default: Date.now },
executedAt: { type: Date, default: Date.now }
});
const emailCodeSchema = new mongoose.Schema({
email: { type: String, required: true },
code: { type: String, required: true },
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
used: { type: Boolean, default: false },
expiresAt: { type: Date, required: true },
createdAt: { type: Date, default: Date.now }
});
const cardSchema = new mongoose.Schema({
code: { type: String, required: true, unique: true },
days: { type: Number, default: 30 },
type: { type: String, default: 'vip_30d' },
vipTier: { type: String, enum: membership.TIER_VALUES, default: 'MONTHLY' },
status: { type: String, enum: ['unused', 'used'], default: 'unused' },
usedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
usedAt: Date,
createdAt: { type: Date, default: Date.now }
});
// 系统配置模型
const systemConfigSchema = new mongoose.Schema({
key: { type: String, required: true, unique: true },
value: mongoose.Schema.Types.Mixed,
updatedAt: { type: Date, default: Date.now }
});
// 邀请记录模型
const inviteLogSchema = new mongoose.Schema({
inviterId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
inviteeId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
rewardDays: { type: Number, default: 10 },
createdAt: { type: Date, default: Date.now }
});
// ============ 二手市场模型 ============
const marketItemSchema = new mongoose.Schema({
productNo: { type: String, unique: true, sparse: true },
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
title: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
category: { type: String, enum: ['book', 'electronic', 'life', 'other'], default: 'other' },
images: { type: [String], default: [] },
paymentQR: { type: String, default: '' },
contact: {
qq: { type: String, default: '' },
wechat: { type: String, default: '' }
},
status: { type: String, enum: ['active', 'reserved', 'sold', 'removed'], default: 'active' },
views: { type: Number, default: 0 },
contactViews: { type: Number, default: 0 },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
marketItemSchema.index({ status: 1, category: 1, createdAt: -1 });
marketItemSchema.index({ title: 'text', description: 'text', productNo: 'text' });
const favoriteSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem', required: true },
createdAt: { type: Date, default: Date.now }
});
favoriteSchema.index({ userId: 1, productId: 1 }, { unique: true });
const chatRoomSchema = new mongoose.Schema({
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem' },
buyerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
sellerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
lastMessage: String,
lastMessageAt: Date,
createdAt: { type: Date, default: Date.now }
});
chatRoomSchema.index({ productId: 1, buyerId: 1 }, { unique: true });
const messageSchema = new mongoose.Schema({
roomId: { type: mongoose.Schema.Types.ObjectId, ref: 'ChatRoom', required: true },
senderId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
content: { type: String, required: true },
createdAt: { type: Date, default: Date.now }
});
const MarketItem = mongoose.models.MarketItem || mongoose.model('MarketItem', marketItemSchema);
const Favorite = mongoose.models.Favorite || mongoose.model('Favorite', favoriteSchema);
const ChatRoom = mongoose.models.ChatRoom || mongoose.model('ChatRoom', chatRoomSchema);
const Message = mongoose.models.Message || mongoose.model('Message', messageSchema);
// ============ 举报和拉黑模型 ============
const reportSchema = new mongoose.Schema({
reporterId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
targetUserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem' },
reason: { type: String, required: true },
status: { type: String, enum: ['pending', 'handled', 'dismissed'], default: 'pending' },
createdAt: { type: Date, default: Date.now }
});
const blockSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
blockedUserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
createdAt: { type: Date, default: Date.now }
});
blockSchema.index({ userId: 1, blockedUserId: 1 }, { unique: true });
const Report = mongoose.models.Report || mongoose.model('Report', reportSchema);
const Block = mongoose.models.Block || mongoose.model('Block', blockSchema);
// ============ 购物车模型 ============
const cartSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem', required: true },
createdAt: { type: Date, default: Date.now }
});
cartSchema.index({ userId: 1, productId: 1 }, { unique: true });
// ============ 二手市场订单模型 ============
const marketOrderSchema = new mongoose.Schema({
orderNo: { type: String, required: true, unique: true },
buyerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
sellerId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'MarketItem', required: true },
productNo: String,
title: String,
price: Number,
address: {
name: { type: String, required: true },
phone: { type: String, required: true },
detail: { type: String, required: true }
},
status: { type: String, enum: ['pending', 'confirmed', 'shipped', 'completed', 'cancelled'], default: 'pending' },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
const Cart = mongoose.models.Cart || mongoose.model('Cart', cartSchema);
const MarketOrder = mongoose.models.MarketOrder || mongoose.model('MarketOrder', marketOrderSchema);
const MARKET_CATEGORIES = ['book', 'electronic', 'life', 'other'];
const MARKET_ORDER_STATUS = ['pending', 'confirmed', 'shipped', 'completed', 'cancelled'];
function escapeRegExp(value = '') {
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function clampNumber(value, min, max, fallback) {
const parsed = Number(value);
if (!Number.isFinite(parsed)) return fallback;
return Math.min(max, Math.max(min, parsed));
}
function normalizeMarketText(value, maxLength) {
return String(value || '').trim().slice(0, maxLength);
}
function normalizeMarketPrice(value) {
const price = Number(value);
if (!Number.isFinite(price) || price < 0 || price > 99999) return null;
return Math.round(price * 100) / 100;
}
function normalizeMarketImages(images) {
if (!Array.isArray(images)) return [];
return images
.filter(img => typeof img === 'string' && img.length <= 2 * 1024 * 1024 && /^data:image\/(png|jpe?g|webp);base64,/i.test(img))
.slice(0, 5);
}
function normalizeMarketContact(contact = {}) {
return {
qq: normalizeMarketText(contact.qq, 40),
wechat: normalizeMarketText(contact.wechat, 80)
};
}
function normalizeQrImage(value) {
if (value === '') return '';
if (typeof value !== 'string') return null;
if (value.length > 1024 * 1024) return null;
return /^data:image\/(png|jpe?g|webp);base64,/i.test(value) ? value : null;
}
async function hasMarketBlockBetween(userA, userB) {
if (!userA || !userB) return false;
return !!(await Block.exists({
$or: [
{ userId: userA, blockedUserId: userB },
{ userId: userB, blockedUserId: userA }
]
}));
}
async function releaseMarketItemIfNoOpenOrders(productId) {
const openOrder = await MarketOrder.exists({
productId,
status: { $in: ['pending', 'confirmed', 'shipped'] }
});
if (!openOrder) {
await MarketItem.updateOne({ _id: productId, status: 'reserved' }, { status: 'active', updatedAt: new Date() });
}
}
// 留言/反馈模型
const feedbackSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
title: { type: String, required: true },
content: { type: String, required: true },
type: { type: String, enum: ['bug', 'suggestion', 'question', 'other'], default: 'other' },
status: { type: String, enum: ['pending', 'read', 'replied', 'closed'], default: 'pending' },
adminReply: { type: String, default: '' },
repliedAt: { type: Date },
repliedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
// ============ 支付订单模型 ============
const paymentOrderSchema = new mongoose.Schema({
orderNo: { type: String, required: true, unique: true },
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
// 下单时冻结的用户快照:用户被物理删除后,后台仍能看到是谁下的单(TD-13,绝不显示空白)
userStudentId: { type: String, default: '' },
userName: { type: String, default: '' },
userEmail: { type: String, default: '' },
packageId: { type: String, default: '' },
planCode: { type: String, default: '' },
packageName: { type: String, default: '' },
durationLabel: { type: String, default: '' },
tier: { type: String, enum: membership.TIER_VALUES.concat(['COUNTS']), default: 'MONTHLY' },
packageType: { type: String, enum: ['days', 'counts'], default: 'days' },
amount: { type: Number, required: true },
couponCode: { type: String, default: '' },
couponDiscount: { type: Number, default: 0 },
originalAmount: { type: Number, default: 0 },
days: { type: Number, default: 0 },
counts: { type: Number, default: 0 },
times: { type: Number, default: 0 },
cardCategory: { type: String, enum: ['days', 'times'], default: 'days' },
payMethod: { type: String, enum: ['wechat', 'alipay'], default: 'wechat' },
status: { type: String, enum: ['pending', 'claimed', 'paid', 'granted', 'expired', 'rejected'], default: 'pending' },
reviewStatus: { type: String, enum: ['unreviewed', 'confirmed', 'rejected'], default: 'unreviewed' },
paymentRef: { type: String, default: '' },
claimNote: { type: String, default: '' },
claimAt: Date,
provider: { type: String, default: '' },
mark: { type: String, default: '' },
payCode: { type: String, default: '' },
cardId: { type: mongoose.Schema.Types.ObjectId, ref: 'Card' },
expireAt: { type: Date },
createdAt: { type: Date, default: Date.now },
paidAt: Date,
grantedAt: Date,
reviewedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
reviewedAt: Date,
reviewNote: { type: String, default: '' },
// 实收金额与订单金额不一致时的记录(按实际支付金额发放)
actualAmount: { type: Number, default: 0 },
amountMismatch: { type: Boolean, default: false },
grantedPlanCode: { type: String, default: '' },
// 实际开通的套餐快照(与下单时的套餐区分,后台表格按这个展示真实天数)
grantedPackageName: { type: String, default: '' },
grantedDays: { type: Number, default: 0 },
grantedDurationLabel: { type: String, default: '' },
revokedAt: Date
});
const PaymentOrder = mongoose.models.PaymentOrder || mongoose.model('PaymentOrder', paymentOrderSchema);
// 优惠码(管理后台可增删改/停用/限时/限次)
const couponSchema = new mongoose.Schema({
code: { type: String, required: true, unique: true, index: true },
discount: { type: Number, required: true, default: 0 },
label: { type: String, default: '' },
active: { type: Boolean, default: true },
validFrom: { type: Date, default: null },
validUntil: { type: Date, default: null },
maxUses: { type: Number, default: 0 },
perUserLimit: { type: Number, default: 0 },
note: { type: String, default: '' },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
const Coupon = mongoose.models.Coupon || mongoose.model('Coupon', couponSchema);
const sponsorPackageSchema = new mongoose.Schema({
packageId: { type: String, required: true, unique: true },
planCode: { type: String, default: '' },
name: { type: String, required: true },
price: { type: Number, required: true },
pricePerYear: { type: Number, default: null },
description: { type: String, default: '' },
badge: { type: String, default: '' },
type: { type: String, enum: ['days', 'counts'], default: 'days' },
kind: { type: String, enum: ['days', 'grade'], default: 'days' },
group: { type: String, enum: ['basic', 'pro', 'grade'], default: 'basic' },
tier: { type: String, default: 'MONTHLY' },
days: { type: Number, default: 0 },
years: { type: Number, default: 0 },
counts: { type: Number, default: 0 },
audience: { type: String, default: '不限' },
customTime: { type: Boolean, default: false },
durationLabel: { type: String, default: '' },
active: { type: Boolean, default: true },
sort: { type: Number, default: 0 },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now }
});
const SponsorPackage = mongoose.models.SponsorPackage || mongoose.model('SponsorPackage', sponsorPackageSchema);
// ============ 访问日志(超级管理终端 · 访客面板)============
// 只记录 API 请求;异步写库,不阻塞响应;密钥/密码类字段绝不记录。
const visitorLogSchema = new mongoose.Schema({
ip: { type: String, default: '' },
method: { type: String, default: '' },
path: { type: String, default: '' }, // 只有路径,不含 query(防 token 泄漏)
status: { type: Number, default: 0 },
durationMs: { type: Number, default: 0 },
studentId: { type: String, default: '' }, // 从 JWT userId → User 表查出,未登录为空
location: { type: String, default: '' }, // IP 属地:省 / 市 / 运营商
userAgent: { type: String, default: '' },
browser: { type: String, default: '' },
os: { type: String, default: '' },
device: { type: String, default: '' },
createdAt: { type: Date, default: Date.now }
}, { versionKey: false });
visitorLogSchema.index({ createdAt: -1 });
visitorLogSchema.index({ ip: 1, createdAt: -1 });
// 30 天自动过期(MongoDB TTL),防止记录无限增长
visitorLogSchema.index({ createdAt: 1 }, { expireAfterSeconds: 30 * 24 * 3600 });
const VisitorLog = mongoose.models.VisitorLog || mongoose.model('VisitorLog', visitorLogSchema);
// 轻量 UA 解析(不引入依赖)
function parseUserAgent(ua) {
if (!ua) return { browser: '未知', os: '未知', device: '未知' };
let browser = '未知', os = '未知', device = '桌面';
if (/edg\//i.test(ua)) browser = 'Edge';
else if (/opr\//i.test(ua) || /opera/i.test(ua)) browser = 'Opera';
else if (/chrome\/|crios\//i.test(ua)) browser = 'Chrome';
else if (/safari\//i.test(ua) && !/chrome/i.test(ua)) browser = 'Safari';
else if (/firefox\//i.test(ua)) browser = 'Firefox';
else if (/microstay|wechat/i.test(ua)) browser = '微信内置';
else if (/android.*applewebkit/i.test(ua)) browser = 'Android 浏览器';
if (/windows/i.test(ua)) os = 'Windows';
else if (/iphone|ipad|ipod/i.test(ua)) os = 'iOS';
else if (/android/i.test(ua)) os = 'Android';
else if (/mac os x|macintosh/i.test(ua)) os = 'macOS';
else if (/linux/i.test(ua)) os = 'Linux';
if (/iphone|ipad|ipod|android|mobile/i.test(ua)) device = /ipad|tablet/i.test(ua) ? '平板' : '手机';
return { browser, os, device };
}
// IP 脱敏:面板显示时可选;库里存完整 IP(TraceId 取不到时才兜底)
function clientIp(req) {
// Cloudflare Tunnel / 直连 / 各种代理头,按可信度依次取
for (const h of ['cf-connecting-ip', 'x-forwarded-for', 'x-real-ip', 'true-client-ip', 'cf-ipcountry']) {
const v = String(req.headers[h] || '').split(',')[0].trim();
if (v && !isPrivateIp(v)) return v;
}
// 隧道场景下如果上面都没有,socket IP 可能是 Docker 网关(172.17.x),不可用
const sock = String(req.ip || req.socket?.remoteAddress || '').replace(/^::ffff:/, '');
return sock;
}
// IP 属地查询(ip-api.com 免费版,国内可访问),带 24h 内存缓存,异步不阻塞
const ipLocationCache = new Map(); // ip -> { location, expiresAt }
function isPrivateIp(ip) {
return /^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|::1|localhost)/i.test(ip || '');
}
async function lookupIpLocation(ip) {
if (!ip || isPrivateIp(ip)) return '';
const hit = ipLocationCache.get(ip);
if (hit && hit.expiresAt > Date.now()) return hit.location;
// 英文省市 → 中文(ip.sb 返回英文)
const zhCity = { Zhejiang:'浙江', Hangzhou:'杭州', Jiaxing:'嘉兴', Beijing:'北京', Shanghai:'上海', Guangdong:'广东', Guangzhou:'广州', Shenzhen:'深圳', Jiangsu:'江苏', Nanjing:'南京', Sichuan:'四川', Chengdu:'成都', Hubei:'湖北', Wuhan:'武汉', Fujian:'福建', Shandong:'山东', Henan:'河南', Anhui:'安徽', Hunan:'湖南', Hebei:'河北', Liaoning:'辽宁', Shaanxi:'陕西', Chongqing:'重庆', Tianjin:'天津', Taiwan:'台湾', Taipei:'台北' };
const translate = (s) => zhCity[s] || s || '';
let location = '';
// 主用 ip.sb(HTTPS,实测 Node fetch 稳定,不受 ip-api 限流影响)
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8000);
const r = await fetch(`https://api.ip.sb/geoip/${encodeURIComponent(ip)}`, { signal: controller.signal });
const j = await r.json();
clearTimeout(timer);
const region = translate(j.region);
const city = translate(j.city);
const isp = String(j.isp || '').split(' ')[0];
location = [region, city && city !== region ? city : '', isp].filter(Boolean).join(' · ');
} catch {}
// 备用 ip-api 单查(中文,作为 ip.sb 失败时的兜底)
if (!location) {
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 8000);
const r = await fetch(`http://ip-api.com/json/${encodeURIComponent(ip)}?lang=zh-CN&fields=status,regionName,city,isp`, { signal: controller.signal });
const j = await r.json();
clearTimeout(timer);
if (j.status === 'success') {
const region = j.regionName || '';
const city = j.city && j.city !== region ? j.city : '';
const isp = String(j.isp || '').split(' ')[0];
location = [region, city, isp].filter(Boolean).join(' · ');
}
} catch {}
}
// 失败只缓存 30 秒(快速重试),成功缓存 24 小时
const ttl = location ? 24 * 3600 * 1000 : 30 * 1000;
ipLocationCache.set(ip, { location, expiresAt: Date.now() + ttl });
// 修复:超过上限时先删过期项,仍超则强制淘汰最旧的,保证硬上限不被突破
if (ipLocationCache.size > 5000) {
for (const [k, v] of ipLocationCache) if (v.expiresAt < Date.now()) ipLocationCache.delete(k);
let excess = ipLocationCache.size - 5000;
if (excess > 0) for (const k of ipLocationCache.keys()) { ipLocationCache.delete(k); if (--excess <= 0) break; }
}
return location;
}
// JWT userId → 用户信息(studentId / role),带 30 分钟缓存
const userIdStudentCache = new Map();
async function resolveUser(userId) {
if (!userId) return { studentId: '', isAdmin: false };
const hit = userIdStudentCache.get(String(userId));
if (hit && hit.expiresAt > Date.now()) return hit.data;
let data = { studentId: '', isAdmin: false };
try {
const u = await User.findById(userId).select('studentId role').lean();
data = { studentId: String(u?.studentId || ''), isAdmin: u?.role === 'admin' || String(u?.studentId || '') === String(process.env.AG_ADMIN_STUDENT_ID || '111') };
} catch {}
userIdStudentCache.set(String(userId), { data, expiresAt: Date.now() + 30 * 60 * 1000 });
return data;
}
async function resolveStudentId(userId) { return (await resolveUser(userId)).studentId; }
const VISITOR_LOG_PATHS = /^\/api\//;
// 管理后台自己的请求不记录(避免自己刷屏、占资源)
const VISITOR_SKIP_PATHS = /^\/api\/admin\//;
const visitorRate = new Map(); // ip -> { windowStart, count }
// 修复:定期清理过期限流桶——原来从不删除,随机伪造 IP 会让 Map 无限增长吃内存
setInterval(() => {
const now = Date.now();
for (const [k, v] of visitorRate) if (now - v.windowStart > 60000) visitorRate.delete(k);
}, 60000).unref();
app.use((req, res, next) => {
if (!VISITOR_LOG_PATHS.test(req.path) || VISITOR_SKIP_PATHS.test(req.path) || req.method === 'OPTIONS') return next();
const start = Date.now();
const ip = clientIp(req);
res.on('finish', () => {
try {
// 同 IP 每 10 秒最多记 20 条,防止刷屏把库写爆
const now = Date.now();
let rec = visitorRate.get(ip);
if (!rec || now - rec.windowStart > 10000) { rec = { windowStart: now, count: 0 }; visitorRate.set(ip, rec); }
rec.count += 1;
if (rec.count > 20) return;
const ua = String(req.headers['user-agent'] || '').slice(0, 300);
const parsed = parseUserAgent(ua);
// 在 finish 回调里异步解析,不阻塞用户响应;解析完一次性写入
(async () => {
let studentId = '';
let isAdmin = false;
// 登录请求:从 body 里的学号判断管理员
if (req.path === '/api/login') {
const bodySid = String(req.body?.studentId || '');
isAdmin = bodySid === String(process.env.AG_ADMIN_STUDENT_ID || '111');
if (isAdmin) return;
}
const auth = String(req.headers.authorization || '');
if (auth.startsWith('Bearer ')) {
try {
const decoded = jwt.verify(auth.slice(7), JWT_SECRET);
const info = await resolveUser(decoded.userId);
studentId = info.studentId;
isAdmin = info.isAdmin;
} catch {}
}
// 管理员自己的所有请求都不记录(不只是 /api/admin/*)
if (isAdmin) return;
const location = await lookupIpLocation(ip);
await VisitorLog.create({
ip, method: req.method, path: req.path.slice(0, 200), status: res.statusCode,
durationMs: Date.now() - start, studentId, location,
userAgent: ua, browser: parsed.browser, os: parsed.os, device: parsed.device
}).catch(() => {});
// 总量封顶:超过 5000 条时删最老的 1000 条(低频执行,避免频繁 count)
if (Math.random() < 0.02) {
const count = await VisitorLog.countDocuments().catch(() => 0);
if (count > 5000) {
const old = await VisitorLog.find({}, { _id: 1 }).sort({ createdAt: 1 }).limit(count - 4000).lean().catch(() => []);
if (old.length) await VisitorLog.deleteMany({ _id: { $in: old.map(x => x._id) } }).catch(() => {});
}
}
})();
} catch {}
});
next();
});
const User = mongoose.models.User || mongoose.model('User', userSchema);
const Subscription = mongoose.models.Subscription || mongoose.model('Subscription', subscriptionSchema);
const SignLog = mongoose.models.SignLog || mongoose.model('SignLog', signLogSchema);
const EmailCode = mongoose.models.EmailCode || mongoose.model('EmailCode', emailCodeSchema);
const Card = mongoose.models.Card || mongoose.model('Card', cardSchema);
const SystemConfig = mongoose.models.SystemConfig || mongoose.model('SystemConfig', systemConfigSchema);
const InviteLog = mongoose.models.InviteLog || mongoose.model('InviteLog', inviteLogSchema);
const Feedback = mongoose.models.Feedback || mongoose.model('Feedback', feedbackSchema);
// 微信上行消息反馈(用户在 WxPusher 公众号里发 "#145060 内容")
const userFeedbackSchema = new mongoose.Schema({
uid: { type: String, default: '', index: true },
studentId: { type: String, default: '', index: true },
content: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
source: { type: String, enum: ['wechat'], default: 'wechat' },
// 管理端回复 / 延迟自动回复
replied: { type: Boolean, default: false },
replyContent: { type: String, default: '' },
repliedAt: { type: Date, default: null },
repliedBy: { type: String, default: '' },
autoReplyDueAt: { type: Date, default: null },
autoReplied: { type: Boolean, default: false },
autoRepliedAt: { type: Date, default: null }
});
const UserFeedback = mongoose.models.UserFeedback || mongoose.model('UserFeedback', userFeedbackSchema);
const AUTO_SIGN_NAME = '自动签到';
const AUTO_SIGN_TIME = '21:35';
const AUTO_SIGN_CRON = '35 21 * * *';
// 学校晚寝签到开放时间:21:20–22:50(北京时间)。手动签到、补签、自定义时间都受这个窗口约束。
const SIGN_WINDOW_START_MIN = 21 * 60 + 20; // 1280
const SIGN_WINDOW_END_MIN = 22 * 60 + 50; // 1370
const SIGN_WINDOW_LABEL = '21:20–22:50';
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'ag985211ag@qq.com';
const WXPUSHER_APP_ID = String(process.env.WXPUSHER_APP_ID || '145060').trim();
const DEFAULT_AUTO_SIGN_DAYS = [0, 1, 2, 3, 4, 5, 6];
const VIP_TIER_RANK = membership.TIER_RANK;
function applyVipTier(user, tier) {
const normalized = membership.normalizeTier(tier);
if (!membership.TIER_VALUES.includes(normalized)) return;
if (membership.tierRank(normalized) >= membership.tierRank(user.vipTier)) {
user.vipTier = normalized;
}
if (!user.vipStartAt) user.vipStartAt = new Date();
}
function addVipDays(user, days) {
const now = new Date();
const base = user.isVip && user.vipExpireAt && user.vipExpireAt > now ? new Date(user.vipExpireAt) : now;
base.setDate(base.getDate() + Number(days || 0));
user.isVip = true;
user.vipExpireAt = base;
if (!user.vipStartAt) user.vipStartAt = now;
user.lastRenewalReminderDays = 0;
user.lastRenewalReminderAt = null;
return base;
}
function getGraduationDate(studentId) {
return membership.graduationDate(studentId);
}
/** 兼容历史订单的套餐解析:优先用订单里快照的天数 */
function planForOrder(order) {
if (!order) return null;
const plan = membership.planForCode(order.packageId) || membership.planForTier(order.tier);
if (!plan) return null;
if (plan.kind === 'days' && Number(order.days) > 0 && Number(order.days) !== Number(plan.days)) {
return { ...plan, days: Number(order.days) };
}
return plan;
}
/** 订单实际开通的套餐(金额不符改过套餐时以 grantedPlanCode 为准) */
function effectivePlanForOrder(order) {
if (!order) return null;
if (order.grantedPlanCode) {
const p = membership.planForCode(order.grantedPlanCode) || membership.planForTier(order.grantedPlanCode);
if (p) return p;
}
return planForOrder(order);
}
/** 该用户其它有效订单的贡献:最晚到期时间 + 最高等级(改套餐/撤销后重算时用作基点) */
async function computeOtherOrdersContribution(user, excludeOrderId) {
const out = { expiry: null, bestTier: '' };
try {
const others = await PaymentOrder.find({
userId: user._id,
_id: { $ne: excludeOrderId },
status: 'granted',
revokedAt: null,
reviewStatus: { $ne: 'rejected' }
}).lean();
for (const o of others) {
const p = effectivePlanForOrder(o);
if (!p) continue;
const g = new Date(o.grantedAt || o.paidAt || o.createdAt || Date.now());
const e = p.kind === 'grade'
? membership.computeExpireAt(p, user, g)
: new Date(g.getTime() + Number(p.days || 0) * membership.DAY_MS);
if (!out.expiry || e.getTime() > out.expiry.getTime()) out.expiry = e;
if (!out.bestTier || membership.tierRank(p.tier) > membership.tierRank(out.bestTier)) out.bestTier = p.tier;
}
} catch (e) { /* ignore */ }
return out;
}
/** 兼容旧调用 */
async function computeOtherOrdersExpiry(user, excludeOrderId) {
const c = await computeOtherOrdersContribution(user, excludeOrderId);
return c.expiry;
}
/**
* 统一发放会员权益。
* planOrTier 可以是套餐对象、套餐 code、或会员等级。
* opts.expireAt 用于管理员自定义到期时间(仅支持自定义时间的套餐使用)。
* opts.stack === false 可强制从当前时间重新计算(默认叠加:未到期会员的剩余天数不清零)。
*/
async function grantMembership(user, planOrTier, opts = {}) {
const now = new Date();
const plan = planOrTier && typeof planOrTier === 'object'
? planOrTier
: (membership.planForCode(planOrTier) || membership.planForTier(planOrTier));
// 体验会员升级/续费:剩余天数保留(叠加),身份标签改为实际购买的套餐
const wasTrial = membership.isTrialMembership(user, now);
const stackBase = (opts.stack === false)
? null
: (user.isVip && user.vipExpireAt && new Date(user.vipExpireAt) > now ? new Date(user.vipExpireAt) : null);
let expireAt;
if (opts.expireAt) {
expireAt = new Date(opts.expireAt);
} else if (plan) {
expireAt = membership.computeExpireAt(plan, user, now, stackBase);
} else {
const days = Number(opts.days || 0);
const origin = stackBase || now;
const grad = membership.graduationDate(user.studentId);
expireAt = days > 0
? new Date(origin.getTime() + days * membership.DAY_MS)
: (grad && grad > origin ? grad : new Date(origin.getTime() + 365 * membership.DAY_MS));
}
user.isVip = true;
user.vipExpireAt = expireAt;
if (!user.vipStartAt || wasTrial) user.vipStartAt = now;
user.lastRenewalReminderDays = 0;
user.lastRenewalReminderAt = null;
if (wasTrial && plan && plan.tier) {
user.vipTier = membership.normalizeTier(plan.tier); // 体验卡(学年卡 Pro 3 天)不再粘着标签
} else {
applyVipTier(user, plan ? plan.tier : planOrTier);
}
await user.save();
await reconcileUserSignAccess(user).catch(() => {});
return expireAt;
}
async function grantSponsorTier(user, tier, days) {
const plan = membership.planForTier(tier);
return grantMembership(user, plan || tier, { days });
}
async function revokeSponsorTier(user) {
user.isVip = false;
user.vipExpireAt = new Date(0);
user.vipTier = 'FREE';
user.lastRenewalReminderDays = 0;
user.lastRenewalReminderAt = null;
await user.save();
await reconcileUserSignAccess(user).catch(() => {});
}
/** 给用户留一条站内通知(不发邮件),下次登录/打开仪表盘时弹出一次 */
function queueUserNotice(user, title, content, level = 'warning') {
if (!user) return;
if (!Array.isArray(user.notices)) user.notices = [];
user.notices.push({
title: String(title || '系统通知').slice(0, 120),
content: String(content || '').slice(0, 800),
level: String(level || 'warning'),
createdAt: new Date()
});
if (user.notices.length > 20) user.notices = user.notices.slice(-20);
}
function userNoticeList(user) {
if (!user || !Array.isArray(user.notices)) return [];
return user.notices.slice(-20).map(n => ({
title: n.title || '系统通知',
content: n.content || '',
level: n.level || 'warning',
createdAt: n.createdAt || new Date()
}));
}
function normalizeAutoSignDays(days) {
const source = Array.isArray(days) && days.length > 0 ? days : DEFAULT_AUTO_SIGN_DAYS;
const normalized = [...new Set(
source
.map(day => Number(day))
.filter(day => Number.isInteger(day) && day >= 0 && day <= 6)
)].sort((a, b) => a - b);
return normalized.length > 0 ? normalized : DEFAULT_AUTO_SIGN_DAYS;
}
function formatAutoSignSetting(setting) {
return {
id: setting?._id || null,
_id: setting?._id || null,
name: AUTO_SIGN_NAME,
enabled: !!setting?.enabled,
scheduleType: 'custom',
customDays: setting ? normalizeAutoSignDays(setting.customDays) : DEFAULT_AUTO_SIGN_DAYS,
signTime: setting?.signTime || AUTO_SIGN_TIME,
maxRetries: 3,
notifyOnSuccess: setting ? setting.notifyOnSuccess !== false : true,
notifyOnFailure: setting ? setting.notifyOnFailure !== false : true,
createdAt: setting?.createdAt || null,
updatedAt: setting?.updatedAt || null
};
}
async function getAutoSignSetting(userId) {
return Subscription.findOne({ userId }).sort({ createdAt: 1 });
}
function isWithinSignWindow(date = new Date()) {
const parts = new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Shanghai', hour: '2-digit', minute: '2-digit', hour12: false }).formatToParts(date);
const hour = Number((parts.find(p => p.type === 'hour') || {}).value);
const minute = Number((parts.find(p => p.type === 'minute') || {}).value);
const mins = hour * 60 + minute;
return mins >= SIGN_WINDOW_START_MIN && mins <= SIGN_WINDOW_END_MIN;
}
function isSignTimeInWindow(value) {
const t = normalizeSignTime(value);
if (!t) return false;
const [hour, minute] = t.split(':').map(Number);
const mins = hour * 60 + minute;
return mins >= SIGN_WINDOW_START_MIN && mins <= SIGN_WINDOW_END_MIN;
}