Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
2553 lines (2339 loc) · 115 KB
/
Copy pathserver.js
File metadata and controls
2553 lines (2339 loc) · 115 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
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const https = require('https');
const { execFile } = require('child_process');
const { promisify } = require('util');
const { createWorker, OEM } = require('tesseract.js');
const db = require('./db');
const execFileAsync = promisify(execFile);
const app = express();
const PORT = process.env.PORT || 3000;
const LLM_BASE_URL = (process.env.LLM_BASE_URL || 'http://minohlee.mooo.com:8081').replace(/\/$/, '');
const LLM_MODEL = process.env.LLM_MODEL || 'gemma-4-e4b-it-q4km';
const LLM_VISION_MODEL = process.env.LLM_VISION_MODEL || '';
const LLM_TIMEOUT_MS = Math.max(5000, Number(process.env.LLM_TIMEOUT_MS) || 60000);
const KIDSNOTE_SESSION_SECRET = process.env.KIDSNOTE_SESSION_SECRET || '';
const KIDSNOTE_SESSION_COOKIE = 'planner_kidsnote_session';
const KIDSNOTE_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const KIDSNOTE_SESSION_FILE = path.join(__dirname, 'data', 'kidsnote-sessions.json');
const TIMETREE_SESSION_COOKIE = 'planner_timetree_session';
const TIMETREE_SESSION_FILE = path.join(__dirname, 'data', 'timetree-session.json');
const TIMETREE_CALENDAR_ID = process.env.TIMETREE_CALENDAR_ID || 'UvLp28KQRT2D';
const TIMETREE_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const CHROMIUM_EXECUTABLE = process.env.CHROMIUM_EXECUTABLE || '/snap/bin/chromium';
const GOOGLE_CALENDAR_TOKEN_FILE = path.join(__dirname, 'data', 'google-calendar-token.json');
const GOOGLE_CALENDAR_STATE_COOKIE = 'planner_google_calendar_state';
const GOOGLE_CALENDAR_RETURN_COOKIE = 'planner_google_calendar_return';
const GOOGLE_CALENDAR_TIME_ZONE = 'Asia/Seoul';
const GOOGLE_CALENDAR_SCOPE = 'https://www.googleapis.com/auth/calendar';
const GOOGLE_CALENDAR_FALLBACK_NAME = '기본 캘린더';
const SCHEDULE_OCR_CACHE_DIR = path.join(__dirname, 'data', 'tesseract-cache');
const TODO_ATTACHMENT_DIR = path.join(__dirname, 'data', 'todo-attachments');
const TODO_ATTACHMENT_MAX_BYTES = 6 * 1024 * 1024;
const kidsNoteAnalysisJobs = new Map();
let googleCalendarSyncQueue = Promise.resolve();
let timeTreeSyncQueue = Promise.resolve();
let scheduleOcrWorkerPromise;
let scheduleOcrQueue = Promise.resolve();
let koreanHolidayModulePromise;
async function recognizeScheduleImageText(imageBuffer) {
if (!scheduleOcrWorkerPromise) {
fs.mkdirSync(SCHEDULE_OCR_CACHE_DIR, { recursive: true });
scheduleOcrWorkerPromise = createWorker('kor+eng', OEM.LSTM_ONLY, { cachePath: SCHEDULE_OCR_CACHE_DIR }).catch(error => {
scheduleOcrWorkerPromise = null;
throw error;
});
}
const job = scheduleOcrQueue.then(async () => {
const worker = await scheduleOcrWorkerPromise;
const result = await worker.recognize(imageBuffer);
return String(result?.data?.text || '').trim();
});
scheduleOcrQueue = job.catch(() => undefined);
return job;
}
function getGoogleCalendarConfig() {
return {
clientId: process.env.GOOGLE_CLIENT_ID || '',
clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
redirectUri: process.env.GOOGLE_REDIRECT_URI || '',
encryptionKey: process.env.GOOGLE_TOKEN_ENCRYPTION_KEY || ''
};
}
function isGoogleCalendarConfigured() {
const config = getGoogleCalendarConfig();
return Boolean(config.clientId && config.clientSecret && config.redirectUri && config.encryptionKey);
}
function getGoogleCalendarCipherKey() {
return crypto.createHash('sha256').update(getGoogleCalendarConfig().encryptionKey).digest();
}
function encryptGoogleCalendarToken(token) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', getGoogleCalendarCipherKey(), iv);
const encrypted = Buffer.concat([cipher.update(JSON.stringify(token), 'utf8'), cipher.final()]);
return JSON.stringify({
version: 1,
iv: iv.toString('base64'),
tag: cipher.getAuthTag().toString('base64'),
data: encrypted.toString('base64')
}, null, 2);
}
function decryptGoogleCalendarToken(payload) {
const encrypted = JSON.parse(payload);
const decipher = crypto.createDecipheriv('aes-256-gcm', getGoogleCalendarCipherKey(), Buffer.from(encrypted.iv, 'base64'));
decipher.setAuthTag(Buffer.from(encrypted.tag, 'base64'));
const plain = Buffer.concat([decipher.update(Buffer.from(encrypted.data, 'base64')), decipher.final()]);
return JSON.parse(plain.toString('utf8'));
}
function readGoogleCalendarTokenStore() {
if (!isGoogleCalendarConfigured() || !fs.existsSync(GOOGLE_CALENDAR_TOKEN_FILE)) return null;
try {
return decryptGoogleCalendarToken(fs.readFileSync(GOOGLE_CALENDAR_TOKEN_FILE, 'utf8'));
} catch (error) {
console.error('Failed to read Google Calendar connection:', error.message);
return null;
}
}
function writeGoogleCalendarTokenStore(store) {
fs.mkdirSync(path.dirname(GOOGLE_CALENDAR_TOKEN_FILE), { recursive: true });
fs.writeFileSync(GOOGLE_CALENDAR_TOKEN_FILE, encryptGoogleCalendarToken(store), { mode: 0o600 });
}
function parseRequestCookies(req) {
return Object.fromEntries((req.headers.cookie || '').split(';').map(item => {
const index = item.indexOf('=');
return index === -1 ? [] : [item.slice(0, index).trim(), decodeURIComponent(item.slice(index + 1).trim())];
}).filter(item => item.length));
}
function clearGoogleCalendarStateCookie(res) {
res.setHeader('Set-Cookie', [
`${GOOGLE_CALENDAR_STATE_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`,
`${GOOGLE_CALENDAR_RETURN_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`
]);
}
function getGoogleOAuthScopes() {
return ['openid', 'email', 'profile', GOOGLE_CALENDAR_SCOPE];
}
async function getGoogleCalendarAccessToken() {
const store = readGoogleCalendarTokenStore();
if (!store?.refreshToken) throw new Error('Google Calendar is not connected.');
if (store.accessToken && store.expiresAt > Date.now() + 60 * 1000) return { store, accessToken: store.accessToken };
const config = getGoogleCalendarConfig();
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: config.clientId,
client_secret: config.clientSecret,
refresh_token: store.refreshToken,
grant_type: 'refresh_token'
})
});
const token = await response.json();
if (!response.ok) throw new Error(token.error_description || 'Google token refresh failed.');
store.accessToken = token.access_token;
store.expiresAt = Date.now() + Number(token.expires_in || 3600) * 1000;
writeGoogleCalendarTokenStore(store);
return { store, accessToken: store.accessToken };
}
async function googleCalendarRequest(url, options = {}) {
const { accessToken } = await getGoogleCalendarAccessToken();
const response = await fetch(url, {
...options,
headers: {
Authorization: `Bearer ${accessToken}`,
...(options.body ? { 'Content-Type': 'application/json' } : {}),
...(options.headers || {})
}
});
if (response.status === 204) return null;
const result = await response.json().catch(() => ({}));
if (!response.ok) {
const error = new Error(result?.error?.message || 'Google Calendar request failed.');
error.status = response.status;
throw error;
}
return result;
}
async function fetchGoogleUser(accessToken) {
const response = await fetch('https://openidconnect.googleapis.com/v1/userinfo', {
headers: { Authorization: `Bearer ${accessToken}` }
});
const profile = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(profile.error_description || 'Google 계정 정보를 가져오지 못했습니다.');
return { id: profile.sub, email: profile.email || '', name: profile.name || '', picture: profile.picture || '' };
}
function hasGoogleCalendarSharingScope(store) {
return String(store?.scope || '').split(/\s+/).includes(GOOGLE_CALENDAR_SCOPE);
}
function requireSelectedGoogleCalendar(store) {
if (!store?.calendarId) {
const error = new Error('먼저 동기화할 Google 캘린더를 선택해 주세요.');
error.status = 400;
throw error;
}
return store.calendarId;
}
function toGoogleCalendarEvent(todo) {
const event = {
summary: todo.title,
description: todo.content || '',
extendedProperties: { private: { plannerTodoId: String(todo.id), plannerSource: 'neo-planner' } }
};
if (todo.allDay || todo.startDate.slice(0, 10) !== todo.endDate.slice(0, 10)) {
const startDate = todo.startDate.slice(0, 10);
const end = new Date(`${todo.endDate.slice(0, 10)}T00:00:00Z`);
end.setUTCDate(end.getUTCDate() + 1);
event.start = { date: startDate };
event.end = { date: end.toISOString().slice(0, 10) };
} else {
event.start = { dateTime: normalizeGoogleCalendarDateTime(todo.startDate), timeZone: GOOGLE_CALENDAR_TIME_ZONE };
event.end = { dateTime: normalizeGoogleCalendarDateTime(todo.endDate), timeZone: GOOGLE_CALENDAR_TIME_ZONE };
}
return event;
}
function normalizeGoogleCalendarDateTime(value) {
let normalized = String(value || '').trim();
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(normalized)) normalized += ':00';
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(normalized)) normalized += '+09:00';
return normalized;
}
async function syncTodoToGoogleCalendar(todoId) {
const todo = await db.getTodoById(String(todoId));
if (!todo) {
const error = new Error('동기화할 일정을 찾지 못했습니다.');
error.status = 404;
throw error;
}
const { store } = await getGoogleCalendarAccessToken();
const calendarId = requireSelectedGoogleCalendar(store);
store.eventIds = store.eventIds || {};
const rememberedId = store.eventIds[String(todo.id)];
const event = toGoogleCalendarEvent(todo);
let googleEventId = rememberedId || '';
let action = 'created';
if (!googleEventId) {
const params = new URLSearchParams({
maxResults: '10',
singleEvents: 'false',
privateExtendedProperty: `plannerTodoId=${String(todo.id)}`
});
const matches = await googleCalendarRequest(`https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events?${params}`);
googleEventId = (matches.items || []).find(item => item.status !== 'cancelled')?.id || '';
}
if (googleEventId) {
try {
await googleCalendarRequest(`https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events/${encodeURIComponent(googleEventId)}`, {
method: 'PUT', body: JSON.stringify(event)
});
action = 'updated';
} catch (error) {
if (error.status !== 404) throw error;
googleEventId = '';
}
}
if (!googleEventId) {
const created = await googleCalendarRequest(`https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events`, {
method: 'POST', body: JSON.stringify(event)
});
googleEventId = created.id;
action = 'created';
}
store.eventIds[String(todo.id)] = googleEventId;
store.lastSyncedAt = new Date().toISOString();
writeGoogleCalendarTokenStore(store);
return { todoId: String(todo.id), googleEventId, action, calendarId, calendarName: store.calendarName };
}
function getKoreanHolidayModule() {
if (!koreanHolidayModulePromise) {
koreanHolidayModulePromise = import('@hyunbinseo/holidays-kr');
}
return koreanHolidayModulePromise;
}
// Middleware
app.use(cors({ origin: true, credentials: true }));
app.use(morgan('dev'));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
const mobileUserAgentPattern = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
app.get(['/m', '/mobile'], (req, res) => {
res.setHeader('Cache-Control', 'no-store');
res.sendFile(path.join(__dirname, 'public', 'mobile.html'));
});
app.get('/kids_note_gallary', (req, res) => {
res.setHeader('Cache-Control', 'no-store');
res.sendFile(path.join(__dirname, 'public', 'kids-note-gallery.html'));
});
app.get('/', (req, res) => {
res.setHeader('Cache-Control', 'no-store');
const forceDesktop = req.query.desktop === '1';
const useMobileFrontend = !forceDesktop && mobileUserAgentPattern.test(req.get('user-agent') || '');
res.sendFile(path.join(__dirname, 'public', useMobileFrontend ? 'mobile.html' : 'index.html'));
});
// Serve static files. Keep the entry HTML fresh so a normal reload always
// picks up the latest cache-busted frontend assets after a deployment.
app.use(express.static(path.join(__dirname, 'public'), {
setHeaders(res, filePath) {
if (path.extname(filePath) === '.html') {
res.setHeader('Cache-Control', 'no-store');
}
}
}));
app.get('/api/holidays', async (req, res) => {
const year = Number.parseInt(req.query.year, 10);
if (!Number.isInteger(year) || year < 1900 || year > 2200) {
return res.status(400).json({ error: 'A valid year between 1900 and 2200 is required' });
}
try {
const { getHolidayPreset } = await getKoreanHolidayModule();
const preset = await getHolidayPreset(String(year));
const holidays = Object.entries(preset)
.sort(([dateA], [dateB]) => dateA.localeCompare(dateB))
.map(([date, names]) => ({
date,
names,
name: names.join(', ')
}));
res.json({ country: 'KR', year, available: true, holidays });
} catch (err) {
if (err instanceof RangeError) {
return res.json({ country: 'KR', year, available: false, holidays: [] });
}
console.error('Failed to load Korean holidays:', err);
res.status(500).json({ error: 'Failed to load Korean holidays', details: err.message });
}
});
app.get('/api/todos', async (req, res) => {
try {
const todos = await db.getAllTodos();
res.json(todos);
} catch (err) {
res.status(500).json({ error: 'Failed to retrieve tasks', details: err.message });
}
});
app.get('/api/todos/:id', async (req, res) => {
try {
const todo = await db.getTodoById(req.params.id);
if (!todo) {
return res.status(404).json({ error: 'Task not found' });
}
res.json(todo);
} catch (err) {
res.status(500).json({ error: 'Failed to retrieve task', details: err.message });
}
});
app.post('/api/todo-attachments', async (req, res) => {
try {
const match = String(req.body?.imageDataUrl || '').match(/^data:(image\/(?:jpeg|png|webp|gif));base64,([A-Za-z0-9+/=]+)$/);
if (!match) return res.status(400).json({ error: '지원하는 이미지 파일을 선택해 주세요.' });
const buffer = Buffer.from(match[2], 'base64');
if (!buffer.length || buffer.length > TODO_ATTACHMENT_MAX_BYTES) {
return res.status(413).json({ error: '이미지는 한 장당 6MB 이하만 첨부할 수 있습니다.' });
}
const extensions = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif' };
const mimeType = match[1].toLowerCase();
const id = `${crypto.randomBytes(24).toString('hex')}.${extensions[mimeType]}`;
await fs.promises.mkdir(TODO_ATTACHMENT_DIR, { recursive: true });
await fs.promises.writeFile(path.join(TODO_ATTACHMENT_DIR, id), buffer, { flag: 'wx' });
const originalName = path.basename(String(req.body?.fileName || '일정 이미지')).replace(/[\u0000-\u001f]/g, '').slice(0, 200) || '일정 이미지';
res.status(201).json({
id,
name: originalName,
url: `/api/todo-attachments/${id}`,
mimeType,
size: buffer.length
});
} catch (err) {
res.status(500).json({ error: '이미지 첨부를 저장하지 못했습니다.', details: err.message });
}
});
app.get('/api/todo-attachments/:fileName', (req, res) => {
const fileName = String(req.params.fileName || '');
if (!/^[a-f0-9]{48}\.(?:jpg|png|webp|gif)$/.test(fileName)) {
return res.status(404).json({ error: '첨부 이미지를 찾을 수 없습니다.' });
}
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
res.sendFile(fileName, { root: TODO_ATTACHMENT_DIR }, err => {
if (err && !res.headersSent) res.status(err.statusCode || 404).json({ error: '첨부 이미지를 찾을 수 없습니다.' });
});
});
app.post('/api/todos', async (req, res) => {
try {
const { title, startDate } = req.body;
if (!title || !startDate) {
return res.status(400).json({ error: 'Title and startDate are required' });
}
const newTodo = await db.createTodo(req.body);
res.status(201).json(newTodo);
} catch (err) {
res.status(500).json({ error: 'Failed to create task', details: err.message });
}
});
app.put('/api/todos/:id', async (req, res) => {
try {
const updatedTodo = await db.updateTodo(req.params.id, req.body);
if (!updatedTodo) {
return res.status(404).json({ error: 'Task not found' });
}
res.json(updatedTodo);
} catch (err) {
res.status(500).json({ error: 'Failed to update task', details: err.message });
}
});
app.delete('/api/todos/:id', async (req, res) => {
try {
const success = await db.deleteTodo(req.params.id);
if (!success) {
return res.status(404).json({ error: 'Task not found' });
}
res.json({ message: 'Task deleted successfully' });
} catch (err) {
res.status(500).json({ error: 'Failed to delete task', details: err.message });
}
});
const CATEGORY_COLORS = {
work: '#6366f1',
personal: '#06b6d4',
study: '#10b981',
general: '#ec4899'
};
const KOREAN_WEEKDAYS = {
'월요일': 0,
'화요일': 1,
'수요일': 2,
'목요일': 3,
'금요일': 4,
'토요일': 5,
'일요일': 6
};
function formatUtcCalendarDate(date) {
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}-${String(date.getUTCDate()).padStart(2, '0')}`;
}
function addCalendarDays(date, days) {
const result = new Date(date.getTime());
result.setUTCDate(result.getUTCDate() + days);
return result;
}
function formatEpochWithOffset(epochMs, offset) {
const offsetMatch = offset.match(/^([+-])(\d{2}):(\d{2})$/);
const direction = offsetMatch[1] === '+' ? 1 : -1;
const offsetMinutes = direction * (Number(offsetMatch[2]) * 60 + Number(offsetMatch[3]));
const local = new Date(epochMs + offsetMinutes * 60 * 1000);
return `${local.toISOString().slice(0, 19)}${offset}`;
}
function buildNaturalDateHints(text, baseDate) {
const baseMatch = String(baseDate || '').match(/^(\d{4})-(\d{2})-(\d{2})/);
if (!baseMatch) return '';
const anchor = new Date(Date.UTC(Number(baseMatch[1]), Number(baseMatch[2]) - 1, Number(baseMatch[3])));
const hints = [];
const addHint = (expression, date) => {
const hint = `"${expression}"=${formatUtcCalendarDate(date)}`;
if (!hints.includes(hint)) hints.push(hint);
};
for (const [expression, days] of [['오늘', 0], ['내일', 1], ['모레', 2], ['글피', 3]]) {
if (text.includes(expression)) addHint(expression, addCalendarDays(anchor, days));
}
const mondayIndex = (anchor.getUTCDay() + 6) % 7;
const monday = addCalendarDays(anchor, -mondayIndex);
const qualifiedWeekdayRegex = /(이번\s*주|다음\s*주|다다음\s*주)\s*(월요일|화요일|수요일|목요일|금요일|토요일|일요일)/g;
for (const match of text.matchAll(qualifiedWeekdayRegex)) {
const qualifier = match[1].replace(/\s/g, '');
const weekOffset = qualifier === '이번주' ? 0 : qualifier === '다음주' ? 7 : 14;
addHint(match[0], addCalendarDays(monday, weekOffset + KOREAN_WEEKDAYS[match[2]]));
}
return hints.length ? `[DATE_HINT: ${hints.join(', ')}]` : '';
}
function hasNaturalTimeExpression(text) {
return /(?:오전|오후|아침|점심|저녁|밤|새벽)?\s*(?:[01]?\d|2[0-3])\s*(?::\s*[0-5]\d|시(?:\s*[0-5]?\d\s*분)?)/.test(String(text || ''));
}
function isNaturalSchedulePlaceholder(value) {
return /^(?:미정|없음|제목\s*없음|일정|스케줄|unknown|untitled|none|null)$/i.test(String(value || '').trim());
}
function deriveNaturalScheduleTitle(text) {
const title = String(text || '')
.replace(/\s*\[DATE_HINT:[^\]]+\]/g, ' ')
.replace(/(?:이번\s*주|다음\s*주|다다음\s*주)\s*(?:월요일|화요일|수요일|목요일|금요일|토요일|일요일)/g, ' ')
.replace(/(?:오늘|내일|모레|글피|월요일|화요일|수요일|목요일|금요일|토요일|일요일)/g, ' ')
.replace(/(?:(?:\d{4})\s*[년./-]\s*)?\d{1,2}\s*(?:월|[./-])\s*\d{1,2}\s*(?:일)?/g, ' ')
.replace(/(?:오전|오후|아침|점심|저녁|밤|새벽)?\s*(?:[01]?\d|2[0-3])\s*(?::\s*[0-5]\d|시(?:\s*[0-5]?\d\s*분)?)/g, ' ')
.replace(/(?:부터|까지|에)(?=\s|$)/g, ' ')
.replace(/[\s,./~_-]+/g, ' ')
.trim();
return title || '일정';
}
function resolveKidsNoteDateExpressions(text, writtenAt) {
const baseMatch = String(writtenAt || '').match(/^(\d{4})-(\d{2})-(\d{2})/);
if (!baseMatch) return [];
const anchor = new Date(Date.UTC(Number(baseMatch[1]), Number(baseMatch[2]) - 1, Number(baseMatch[3])));
const results = [];
const seen = new Set();
const addResult = (expression, date) => {
const resolvedDate = formatUtcCalendarDate(date);
const key = `${expression}|${resolvedDate}`;
if (!seen.has(key)) {
seen.add(key);
results.push({ expression, date: resolvedDate });
}
};
for (const [expression, days] of [['오늘', 0], ['내일', 1], ['모레', 2], ['글피', 3]]) {
if (text.includes(expression)) addResult(expression, addCalendarDays(anchor, days));
}
const mondayIndex = (anchor.getUTCDay() + 6) % 7;
const monday = addCalendarDays(anchor, -mondayIndex);
const qualifiedWeekdayRegex = /(이번\s*주|다음\s*주|다다음\s*주)\s*(월요일|화요일|수요일|목요일|금요일|토요일|일요일)/g;
for (const match of text.matchAll(qualifiedWeekdayRegex)) {
const qualifier = match[1].replace(/\s/g, '');
const weekOffset = qualifier === '이번주' ? 0 : qualifier === '다음주' ? 7 : 14;
addResult(match[0], addCalendarDays(monday, weekOffset + KOREAN_WEEKDAYS[match[2]]));
}
const explicitDateRegex = /(?:(\d{4})\s*[년./-]\s*)?(\d{1,2})\s*(?:월|[./-])\s*(\d{1,2})\s*(?:일)?/g;
for (const match of text.matchAll(explicitDateRegex)) {
const month = Number(match[2]);
const day = Number(match[3]);
if (month < 1 || month > 12 || day < 1 || day > 31) continue;
let year = match[1] ? Number(match[1]) : anchor.getUTCFullYear();
let date = new Date(Date.UTC(year, month - 1, day));
if (!match[1] && date.getTime() < anchor.getTime() - 31 * 24 * 60 * 60 * 1000) {
year++;
date = new Date(Date.UTC(year, month - 1, day));
}
if (date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) continue;
addResult(match[0], date);
}
return results;
}
function getBaseOffset(baseDate) {
const explicit = String(baseDate || '').match(/([+-]\d{2}:\d{2})$/);
if (explicit) return explicit[1];
const offsetMinutes = -new Date().getTimezoneOffset();
const sign = offsetMinutes >= 0 ? '+' : '-';
const absolute = Math.abs(offsetMinutes);
return `${sign}${String(Math.floor(absolute / 60)).padStart(2, '0')}:${String(absolute % 60).padStart(2, '0')}`;
}
function normalizeEventDate(value, fallbackOffset, defaultTime = '09:00') {
if (typeof value !== 'string') return null;
let normalized = value.trim().replace(' ', 'T');
if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) normalized += `T${defaultTime}`;
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/.test(normalized)) normalized += fallbackOffset;
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?(Z|[+-]\d{2}:\d{2})$/.test(normalized)) return null;
const epochMs = new Date(normalized).getTime();
return Number.isNaN(epochMs) ? null : formatEpochWithOffset(epochMs, fallbackOffset);
}
function normalizeAllDayBoundary(value, fallbackOffset, isEnd = false) {
const date = String(value || '').trim().match(/^(\d{4}-\d{2}-\d{2})/)?.[1];
if (!date) return null;
const normalized = `${date}T${isEnd ? '23:59:59' : '00:00:00'}${fallbackOffset}`;
return Number.isNaN(new Date(normalized).getTime()) ? null : normalized;
}
function normalizeExtractedEvent(event, baseDate, options = {}) {
if (!event || typeof event !== 'object' || typeof event.title !== 'string') return null;
if (event.status !== 'active') return null;
const title = event.title.trim();
if (!title || /^(없음|해당\s*없음|일정\s*없음|이벤트\s*없음|none|null)$/i.test(title)) return null;
const decisionText = `${event.content || ''} ${event.dateReason || ''}`;
if (/(최종(?:적으로)?[^.]{0,20}취소|취소(?:되었|됐|됨)|일정[^.]{0,15}취소|예약[^.]{0,15}취소)/.test(decisionText)) return null;
const fallbackOffset = getBaseOffset(baseDate);
const allDay = options.forceAllDay === true || event.allDay === true;
const startDate = allDay
? normalizeAllDayBoundary(event.startDate, fallbackOffset)
: normalizeEventDate(event.startDate, fallbackOffset);
let endDate = allDay
? normalizeAllDayBoundary(event.endDate || event.startDate, fallbackOffset, true)
: normalizeEventDate(event.endDate, fallbackOffset, '10:00');
if (!startDate) return null;
const startTime = new Date(startDate).getTime();
if (!endDate || new Date(endDate).getTime() <= startTime) {
endDate = allDay
? normalizeAllDayBoundary(event.startDate, fallbackOffset, true)
: formatEpochWithOffset(startTime + 60 * 60 * 1000, fallbackOffset);
}
if (new Date(endDate).getTime() - startTime > 31 * 24 * 60 * 60 * 1000) return null;
const category = Object.hasOwn(CATEGORY_COLORS, event.category) ? event.category : 'general';
const priority = ['low', 'medium', 'high'].includes(event.priority) ? event.priority : 'medium';
const confidence = Math.max(0, Math.min(1, Number(event.confidence) || 0));
if (confidence < 0.65) return null;
return {
title: title.slice(0, 120),
content: String(event.content || '').trim().slice(0, 600),
startDate,
endDate,
allDay,
priority,
category,
color: CATEGORY_COLORS[category],
dateReason: String(event.dateReason || '').trim().slice(0, 500),
evidence: String(event.evidence || '')
.replace(/\s*\[DATE_HINT:[^\]]+\]/g, '')
.replace(/\s*\[EVENT_CANDIDATE:\d+\]/g, '')
.trim()
.slice(0, 500),
confidence
};
}
function deduplicateEvents(events) {
const unique = new Map();
for (const event of events) {
const normalizedTitle = event.title.toLowerCase().replace(/\s+/g, '').replace(/[^\p{L}\p{N}]/gu, '');
const key = `${event.startDate.slice(0, 16)}|${normalizedTitle}`;
const existing = unique.get(key);
if (!existing || event.confidence > existing.confidence) unique.set(key, event);
}
return Array.from(unique.values()).sort((a, b) => new Date(a.startDate) - new Date(b.startDate));
}
function normalizeCandidateText(value) {
return String(value || '').toLowerCase().replace(/키즈노트\s*#\d+\s*:/g, '')
.replace(/[^\p{L}\p{N}]/gu, '');
}
function normalizeKidsNoteEventIdentity(value) {
return normalizeCandidateText(value)
// Remove explicit calendar dates so a period notice and a boundary-day
// reminder share the same identity (e.g. 여름방학 + 7월27일~7월31일).
.replace(/\d{1,2}월\d{1,2}일/g, '')
// These words describe the notice, not the actual calendar event.
.replace(/(일정|기간|안내|공지|알림|운영|실시|예정|관련|안내문|공문|입니다|이에요|입니다)/g, '');
}
function getKidsNoteDateRange(event) {
const start = Date.parse(`${String(event.startDate || '').slice(0, 10)}T00:00:00Z`);
const end = Date.parse(`${String(event.endDate || '').slice(0, 10)}T00:00:00Z`);
return { start, end, days: Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, Math.round((end - start) / 86400000)) : 0 };
}
function getKidsNoteEventType(value) {
const title = String(value || '');
const match = title.match(/방학|개학|휴원|휴관|운동회|발표회|오리엔테이션|설명회|견학|소풍|체험|검진|검사|예방접종|입학|졸업|상담|수업|생일|파티|공연|관람/);
return match ? match[0] : '';
}
function isKidsNoteAssessmentEvent(event) {
return /(?:시험|테스트|평가|\btest\b|\bexam\b)/i.test(`${event?.title || ''} ${event?.content || ''} ${event?.evidence || ''}`);
}
function kidsNoteEventDetailsReferenceTitle(event, title) {
const normalizedTitle = normalizeCandidateText(title);
if (normalizedTitle.length < 4) return false;
return normalizeCandidateText(`${event?.content || ''} ${event?.evidence || ''}`).includes(normalizedTitle);
}
function diceSimilarity(left, right) {
if (left === right) return 1;
if (left.length < 2 || right.length < 2) return 0;
const counts = new Map();
for (let i = 0; i < left.length - 1; i++) {
const pair = left.slice(i, i + 2);
counts.set(pair, (counts.get(pair) || 0) + 1);
}
let overlap = 0;
for (let i = 0; i < right.length - 1; i++) {
const pair = right.slice(i, i + 2);
const count = counts.get(pair) || 0;
if (count > 0) {
overlap++;
counts.set(pair, count - 1);
}
}
return (2 * overlap) / (left.length + right.length - 2);
}
function areSameKidsNoteCandidate(left, right) {
const leftRange = getKidsNoteDateRange(left);
const rightRange = getKidsNoteDateRange(right);
const sameDateRange = left.startDate.slice(0, 10) === right.startDate.slice(0, 10) &&
left.endDate.slice(0, 10) === right.endDate.slice(0, 10);
const leftTitle = normalizeCandidateText(left.title);
const rightTitle = normalizeCandidateText(right.title);
if (!leftTitle || !rightTitle) return false;
const leftIdentity = normalizeKidsNoteEventIdentity(left.title);
const rightIdentity = normalizeKidsNoteEventIdentity(right.title);
const containedRange = (leftRange.days > 0 || rightRange.days > 0) &&
((leftRange.start <= rightRange.start && leftRange.end >= rightRange.end) ||
(rightRange.start <= leftRange.start && rightRange.end >= leftRange.end));
// A notice may repeat a multi-day event on its first or last day. Treat it
// as one candidate only when the normalized event identity is strong and
// the shorter date range is fully contained by the longer one.
if (!sameDateRange) {
if (!containedRange || !leftIdentity || !rightIdentity) return false;
if (leftIdentity === rightIdentity) return true;
const identityShorter = leftIdentity.length <= rightIdentity.length ? leftIdentity : rightIdentity;
const identityLonger = identityShorter === leftIdentity ? rightIdentity : leftIdentity;
return identityShorter.length >= 3 && identityLonger.includes(identityShorter) &&
diceSimilarity(leftIdentity, rightIdentity) >= 0.58;
}
if (leftTitle === rightTitle) return true;
if (leftIdentity && rightIdentity && leftIdentity === rightIdentity) return true;
// A detailed exam notice may use a generic Korean heading while naming the
// canonical English exam title in its body (for example, Quater Test and
// 2분기 시험안내). The cross-reference is stronger than title similarity.
if (isKidsNoteAssessmentEvent(left) && isKidsNoteAssessmentEvent(right) &&
(kidsNoteEventDetailsReferenceTitle(left, right.title) || kidsNoteEventDetailsReferenceTitle(right, left.title))) {
return true;
}
// A shared event type on the exact same period is a duplicate even when one
// notice uses a longer explanatory title (for example, an event and its notice).
const leftEventType = getKidsNoteEventType(left.title);
const rightEventType = getKidsNoteEventType(right.title);
if (leftEventType && leftEventType === rightEventType) return true;
const shorter = leftTitle.length <= rightTitle.length ? leftTitle : rightTitle;
const longer = shorter === leftTitle ? rightTitle : leftTitle;
const containmentRatio = shorter.length / longer.length;
if (shorter.length >= 4 && longer.includes(shorter) && containmentRatio >= 0.5) return true;
if (diceSimilarity(leftTitle, rightTitle) >= 0.66) return true;
if (leftIdentity && rightIdentity) {
const identityShorter = leftIdentity.length <= rightIdentity.length ? leftIdentity : rightIdentity;
const identityLonger = identityShorter === leftIdentity ? rightIdentity : leftIdentity;
if (identityShorter.length >= 3 && identityLonger.includes(identityShorter)) return true;
if (diceSimilarity(leftIdentity, rightIdentity) >= 0.58) return true;
}
const leftEvidence = normalizeCandidateText(left.evidence);
const rightEvidence = normalizeCandidateText(right.evidence);
if (Math.min(leftEvidence.length, rightEvidence.length) < 12) return false;
return diceSimilarity(leftEvidence, rightEvidence) >= 0.82;
}
function chooseKidsNoteCanonicalTitle(left, right) {
const leftReferenced = kidsNoteEventDetailsReferenceTitle(right, left.title);
const rightReferenced = kidsNoteEventDetailsReferenceTitle(left, right.title);
if (leftReferenced !== rightReferenced) return leftReferenced ? left.title : right.title;
const noticePattern = /(안내|공지|알림|안내문|일정|기간|운영|실시|예정)/g;
const score = title => (String(title || '').match(noticePattern) || []).length * 100 + String(title || '').length;
return score(left.title) <= score(right.title) ? left.title : right.title;
}
function mergeKidsNoteTextParts(values, maxLength) {
const parts = [];
for (const value of values) {
const text = String(value || '').trim();
if (!text) continue;
const normalized = normalizeCandidateText(text);
if (!normalized) continue;
const containingIndex = parts.findIndex(part => normalizeCandidateText(part).includes(normalized));
if (containingIndex >= 0) continue;
const containedIndexes = parts
.map((part, index) => normalized.includes(normalizeCandidateText(part)) ? index : -1)
.filter(index => index >= 0);
for (const index of containedIndexes.reverse()) parts.splice(index, 1);
parts.push(text);
}
return parts.join('\n').slice(0, maxLength);
}
function mergeKidsNoteDuplicateEvents(left, right) {
const leftScore = getKidsNoteDateRange(left).days * 5000 + (Number(left.confidence) || 0) * 1000 + String(left.content || '').length + String(left.evidence || '').length;
const rightScore = getKidsNoteDateRange(right).days * 5000 + (Number(right.confidence) || 0) * 1000 + String(right.content || '').length + String(right.evidence || '').length;
const base = rightScore > leftScore ? right : left;
const title = chooseKidsNoteCanonicalTitle(left, right);
const alternateTitles = [left.title, right.title].filter(candidate => candidate !== title);
const priorityRank = { low: 0, medium: 1, high: 2 };
const priority = priorityRank[left.priority] >= priorityRank[right.priority] ? left.priority : right.priority;
return {
...base,
title,
content: mergeKidsNoteTextParts([...alternateTitles, left.content, right.content], 1200),
evidence: mergeKidsNoteTextParts([left.evidence, right.evidence], 1000),
dateReason: String(left.dateReason || '').length >= String(right.dateReason || '').length ? left.dateReason : right.dateReason,
confidence: Math.max(Number(left.confidence) || 0, Number(right.confidence) || 0),
priority
};
}
function deduplicateKidsNoteEvents(events) {
const unique = [];
for (const event of events) {
const duplicateIndex = unique.findIndex(existing => areSameKidsNoteCandidate(existing, event));
if (duplicateIndex === -1) {
unique.push(event);
continue;
}
unique[duplicateIndex] = mergeKidsNoteDuplicateEvents(unique[duplicateIndex], event);
}
return unique.sort((a, b) => new Date(a.startDate) - new Date(b.startDate));
}
function stripHtml(value) {
return String(value || '')
.replace(/<br\s*\/?\s*>/gi, '\n')
.replace(/<\/p\s*>/gi, '\n')
.replace(/<[^>]+>/g, ' ')
.replace(/ /gi, ' ')
.replace(/&/gi, '&')
.replace(/</gi, '<')
.replace(/>/gi, '>')
.replace(/"/gi, '"')
.replace(/'/gi, "'")
.replace(/[ \t]+/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.trim();
}
function getKidsNoteReports(payload) {
if (Array.isArray(payload)) return payload;
if (!payload || typeof payload !== 'object') return [];
if (Array.isArray(payload.results)) return payload.results;
if (payload.data) return getKidsNoteReports(payload.data);
return [];
}
function getKidsNoteNextCollectionUrl(nextValue, endpoint) {
if (!nextValue) return '';
const text = String(nextValue).trim();
if (!text) return '';
if (/^(https?:)?\/\//i.test(text) || text.startsWith('/')) {
try {
const url = new URL(text, endpoint);
if (/^https?:$/.test(url.protocol) && url.pathname.includes('/api/')) return url.href;
} catch {}
}
const url = new URL(endpoint);
if (url.searchParams.has('cursor')) url.searchParams.set('cursor', text);
else if (url.searchParams.has('page')) url.searchParams.set('page', text);
else url.searchParams.set('cursor', text);
return url.href;
}
function parseRequestCookies(req) {
return String(req.headers.cookie || '').split(';').reduce((cookies, part) => {
const separator = part.indexOf('=');
if (separator < 1) return cookies;
cookies[part.slice(0, separator).trim()] = decodeURIComponent(part.slice(separator + 1).trim());
return cookies;
}, {});
}
function mergeSetCookies(existingCookie, setCookieHeaders = []) {
const values = new Map();
String(existingCookie || '').split(';').forEach(part => {
const separator = part.indexOf('=');
if (separator > 0) values.set(part.slice(0, separator).trim(), part.slice(separator + 1).trim());
});
for (const header of setCookieHeaders || []) {
const pair = String(header).split(';', 1)[0];
const separator = pair.indexOf('=');
if (separator > 0) values.set(pair.slice(0, separator).trim(), pair.slice(separator + 1).trim());
}
return Array.from(values, ([name, value]) => `${name}=${value}`).join('; ');
}
function kidsNoteWebRequest({ method = 'GET', requestPath, body = '', cookie = '' }) {
return new Promise((resolve, reject) => {
const request = https.request({
hostname: 'www.kidsnote.com',
port: 443,
path: requestPath,
method,
headers: {
Accept: 'text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8',
'Accept-Language': 'ko-KR,ko;q=0.9',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body),
Origin: 'https://www.kidsnote.com',
Referer: 'https://www.kidsnote.com/login',
Cookie: cookie,
'User-Agent': 'Mozilla/5.0 NEO-Planner-KidsNote-Connector/1.0'
},
timeout: 15000
}, response => {
const chunks = [];
let size = 0;
response.on('data', chunk => {
size += chunk.length;
if (size <= 2 * 1024 * 1024) chunks.push(chunk);
});
response.on('end', () => resolve({
status: response.statusCode || 0,
location: response.headers.location || '',
setCookies: response.headers['set-cookie'] || [],
body: Buffer.concat(chunks).toString('utf8')
}));
});
request.on('timeout', () => request.destroy(new Error('키즈노트 로그인 시간이 초과되었습니다.')));
request.on('error', reject);
if (body) request.write(body);
request.end();
});
}
async function loginToKidsNote(username, password) {
const loginPage = await kidsNoteWebRequest({ requestPath: '/login' });
let cookie = mergeSetCookies('', loginPage.setCookies);
const body = new URLSearchParams({ username, password, remember_me: 'on' }).toString();
const result = await kidsNoteWebRequest({ method: 'POST', requestPath: '/kr/login', body, cookie });
cookie = mergeSetCookies(cookie, result.setCookies);
const redirectedAwayFromLogin = result.status >= 300 && result.status < 400 && result.location && !/\/login(?:\?|$)/.test(result.location);
if (!redirectedAwayFromLogin || !cookie) {
const error = new Error('키즈노트 아이디 또는 비밀번호가 올바르지 않거나 추가 인증이 필요합니다.');
error.status = 401;
throw error;
}
return cookie;
}
async function loginToKidsNoteBrowser(username, password) {
const puppeteer = require('puppeteer-core');
let browser;
try {
browser = await puppeteer.launch({
executablePath: CHROMIUM_EXECUTABLE,
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'],
timeout: 30000
});
const page = await browser.newPage();
let childId = '';
let enrollment = '';
page.on('request', request => {
const match = request.url().match(/\/children\/(\d+)\/reports(?:\/|\?)/);
if (!match) return;
childId = childId || match[1];
const headers = request.headers();
enrollment = enrollment || headers['x-enrollment'] || '';
});
await page.goto('https://www.kidsnote.com/login', { waitUntil: 'domcontentloaded', timeout: 30000 });
await page.waitForSelector('input[name="username"]', { timeout: 15000 });
await page.type('input[name="username"]', username);
await page.type('input[name="password"]', password);
const loginOutcome = Promise.race([
page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: 20000 }).catch(() => null),
page.waitForFunction(() => {
const loginPath = /^\/(?:[a-z]{2}\/)?login\/?$/.test(location.pathname);
const invalidInput = Boolean(document.querySelector('input[aria-invalid="true"]'));
return !loginPath || invalidInput;
}, { timeout: 20000 }).catch(() => null)
]);
await page.click('button[type="submit"]');
await loginOutcome;
if (/\/(?:[a-z]{2}\/)?login(?:\/|\?|$)/.test(page.url())) {
const error = new Error('키즈노트 아이디 또는 비밀번호가 올바르지 않거나 추가 인증이 필요합니다.');
error.status = 401;
throw error;
}