-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1030 lines (886 loc) · 43.4 KB
/
Copy pathscript.js
File metadata and controls
1030 lines (886 loc) · 43.4 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
// -----------------------------------------------------
// 1. 설정 및 공통 함수
// -----------------------------------------------------
const OWNER = "jhjhc1483";
const REPO = "AI_Trend_Analysis_vercel";
const BRANCH = "main";
let adminPassword = ""; // 세션 스토리지 대신 사용할 전역 변수
//Vercel Serverless Function을 호출하는 함수
async function callProxyAPI(endpoint, method = 'GET', body = null) {
try {
const res = await fetch('/api/github', {
method: 'POST', // 프록시에는 항상 POST로 데이터 전달
headers: {
'Content-Type': 'application/json',
'x-admin-password': adminPassword // 세션 대신 전역 변수 사용
},
body: JSON.stringify({
endpoint: endpoint, // 예: repos/owner/repo/...
method: method, // 실제 GitHub에 보낼 method (GET, POST, PUT 등)
body: body // 실제 GitHub에 보낼 데이터
})
});
if (!res.ok) {
const errData = await res.json().catch(() => ({}));
throw new Error(errData.message || `HTTP Error ${res.status}`);
}
// 204 No Content 처리
if (res.status === 204) return null;
return await res.json();
} catch (error) {
throw error;
}
}
// 비밀번호 확인 함수
async function verifyPassword() {
if (adminPassword) return true; // 메모리에 저장된 비밀번호가 있으면 패스
const pw = prompt("관리자 비밀번호를 입력하세요:");
if (!pw) return false;
try {
const res = await fetch('/api/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: pw })
});
const data = await res.json();
if (data.success) {
adminPassword = pw; // 성공 시 전역 변수에 저장 (새로고침 시 초기화)
return true;
} else {
alert("비밀번호가 틀렸습니다.");
return false;
}
} catch (e) {
alert("비밀번호 확인 중 오류가 발생했습니다.");
return false;
}
}
// -----------------------------------------------------
// 2. 기사 업데이트 실행 (runActionBtn)
// -----------------------------------------------------
document.getElementById('runActionBtn').addEventListener('click', async function () {
const message = "⚠️기사 업데이트를 진행하시겠습니까?⚠️\n\n" +
"✅기사는 지정된 시간에 맞춰 자동으로 업데이트 됩니다.\n" +
"✅수동으로 기사 업데이트 시 최소 5분 이상의 시간이 소요 됩니다.";
if (!confirm(message)) return;
if (!(await verifyPassword())) return; // 권한 확인 추가
const WORKFLOW_ID = "main.yml";
const endpoint = `repos/${OWNER}/${REPO}/actions/workflows/${WORKFLOW_ID}/dispatches`;
updateStatus("기사 업데이트 요청 중...");
try {
await callProxyAPI(endpoint, 'POST', { ref: "main" });
alert("✅ 실행 성공! 최소 5분의 시간이 소요 됩니다.\n페이지를 새로고침 하세요.");
updateStatus("기사 업데이트 진행 중... (최소 5분 소요)");
} catch (error) {
console.error('Error:', error);
alert(`❌ 실패: ${error.message}`);
updateStatus("");
}
});
// -----------------------------------------------------
// 3. 파일 불러오기 (loadFileBtn)
// -----------------------------------------------------
// const popup = document.getElementById('popup');
// const overlay = document.getElementById('overlay');
// const contentDiv = document.getElementById('popupContent');
// const PATH = "codes/data.txt";
function base64ToUtf8(base64) {
const binary = atob(base64.replace(/\n/g, ""));
const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
return new TextDecoder("utf-8").decode(bytes);
}
// XSS 방어를 위한 HTML 이스케이프 함수
function escapeHTML(str) {
if (!str) return "";
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// 각 상태 요소에 메시지를 표시하는 공통 함수
function updateStatus(message) {
const ids = ['status-sidebar', 'status-sidebar-bottom', 'status-dashboard'];
ids.forEach(id => {
const el = document.getElementById(id);
if (el) el.textContent = message;
});
}
// document.getElementById('loadFileBtn').addEventListener('click', async () => {
// try {
// const endpoint = `repos/${OWNER}/${REPO}/contents/${PATH}?ref=${BRANCH}`;
// const data = await callProxyAPI(endpoint, 'GET');
// const text = base64ToUtf8(data.content);
// contentDiv.textContent = text;
// popup.style.display = 'block';
// overlay.style.display = 'block';
// console.log(text);
// } catch (error) {
// console.error(error);
// alert("파일을 불러오는 중 오류 발생: " + error.message);
// }
// });
document.getElementById('loadFileBtn').addEventListener('click', async () => {
try {
const response = await fetch('codes/data.txt?t=' + new Date().getTime());
if (!response.ok) throw new Error('파일을 불러오는데 실패했습니다.');
const text = await response.text();
await navigator.clipboard.writeText(text);
alert("복사되었습니다. 이제 메신저로 공유하세요");
window.location.href = 'https://ai-trend-analysis.vercel.app/visualizer.html';
} catch (error) {
console.error(error);
alert("데이터를 처리하는 중 오류가 발생했습니다: " + error.message);
}
});
document.getElementById('closeBtn').addEventListener('click', () => {
popup.style.display = 'none';
overlay.style.display = 'none';
});
document.getElementById('copyBtn2').addEventListener('click', () => {
navigator.clipboard.writeText(contentDiv.textContent)
.then(() => alert("복사 완료!"))
.catch(err => alert("복사 실패: " + err));
});
// -----------------------------------------------------
// 4. 텍스트 만들기 실행 (runActionBtn2)
// -----------------------------------------------------
// document.getElementById('runActionBtn2').addEventListener('click', async function () {
// const WORKFLOW_ID = "json_to_txt.yml";
// const endpoint = `repos/${OWNER}/${REPO}/actions/workflows/${WORKFLOW_ID}/dispatches`;
// try {
// await callProxyAPI(endpoint, 'POST', { ref: "main" });
// alert("✅ 즐겨찾기에 있는 목록을 일일 동향 텍스트로 만듭니다.\n\n약 30초 후 대시보드에서 '텍스트추출'을 누르세요.");
// } catch (error) {
// console.error('Error:', error);
// alert(`❌ 실패: ${error.message}`);
// }
// });
// -----------------------------------------------------
// 5. 전역 변수 및 데이터 로드
// -----------------------------------------------------
let articleData = [];
let publicationData = [];
let allDataLoaded;
let debounceTimeout;
let currentView = 'HOME';
let favoriteArticles = new Map();
let favoritePublications = new Map();
let fewshotExamples = [];
let excludedArticles = new Set(); // 일일동향 제외 블랙리스트 (링크 기준)
let isAdminMode = false; // 관리자 인증 후 true로 변경
const cacheBuster = `?t=${new Date().getTime()}`;
const FILES_TO_LOAD = [
{ url: 'codes/aikorea.json' + cacheBuster, site: 'AIKOREA', isArticle: true, displayName: '국가인공지능전략위원회' },
{ url: 'codes/aitimes.json' + cacheBuster, site: 'AITIMES', isArticle: true, displayName: 'AI Times' },
{ url: 'codes/etnews.json' + cacheBuster, site: 'ETNEWS', isArticle: true, displayName: '전자신문' },
{ url: 'codes/AInews.json' + cacheBuster, site: 'AINEWS', isArticle: true, displayName: '인공지능신문' },
{ url: 'codes/mnd.json' + cacheBuster, site: 'MND', isArticle: true, displayName: '국방부' },
{ url: 'codes/kookbang.json' + cacheBuster, site: 'kookbang', isArticle: true, displayName: '국방일보' },
{ url: 'codes/dapa.json' + cacheBuster, site: 'DAPA', isArticle: true, displayName: '방사청' },
{ url: 'codes/msit.json' + cacheBuster, site: 'MSIT', isArticle: true, displayName: '과기정통부' },
{ url: 'codes/iitp.json' + cacheBuster, site: 'IITP', isArticle: false, displayName: 'IITP' },
{ url: 'codes/nia.json' + cacheBuster, site: 'NIA', isArticle: false, displayName: 'NIA' },
{ url: 'codes/STEPI.json' + cacheBuster, site: 'STEPI', isArticle: false, displayName: 'STEPI' },
{ url: 'codes/NIPA.json' + cacheBuster, site: 'NIPA', isArticle: false, displayName: 'NIPA' },
{ url: 'codes/KISDI.json' + cacheBuster, site: 'KISDI', isArticle: false, displayName: 'KISDI' },
{ url: 'codes/KISTI.json' + cacheBuster, site: 'KISTI', isArticle: false, displayName: 'KISTI' },
{ url: 'codes/KISA.json' + cacheBuster, site: 'KISA', isArticle: false, displayName: 'KISA' },
{ url: 'codes/tta.json' + cacheBuster, site: 'TTA', isArticle: false, displayName: 'TTA' }
];
function loadFewshotExamples() {
return fetch('codes/favorites/fewshot_examples.json' + cacheBuster)
.then(response => {
if (!response.ok) return [];
return response.json();
})
.then(data => {
fewshotExamples = data;
return data;
})
.catch(error => {
console.error("Error loading fewshot examples:", error);
return [];
});
}
function loadExcludedArticles() {
return fetch('codes/favorites/excluded_articles.json' + cacheBuster)
.then(response => {
if (!response.ok) return [];
return response.json();
})
.then(data => {
excludedArticles = new Set(data.map(item => item.link));
return data;
})
.catch(error => {
console.error("Error loading excluded articles:", error);
return [];
});
}
function loadData() {
const favArticlesStr = localStorage.getItem('favoriteArticles');
const favPublicationsStr = localStorage.getItem('favoritePublications');
if (favArticlesStr) {
const parsed = JSON.parse(favArticlesStr);
if (Array.isArray(parsed) && parsed.length > 0 && Array.isArray(parsed[0])) {
favoriteArticles = new Map(parsed);
} else if (Array.isArray(parsed)) {
favoriteArticles = new Map(parsed.map(link => [link, '기타']));
}
}
if (favPublicationsStr) {
const parsed = JSON.parse(favPublicationsStr);
if (Array.isArray(parsed) && parsed.length > 0 && Array.isArray(parsed[0])) {
favoritePublications = new Map(parsed);
} else if (Array.isArray(parsed)) {
favoritePublications = new Map(parsed.map(link => [link, '기타']));
}
}
const promises = [
...FILES_TO_LOAD.map(file => {
// 데이터 파일은 public 접근 가능하므로 기존 fetch 유지
return fetch(file.url)
.then(response => {
if (!response.ok) throw new Error(`Failed to load ${file.url}`);
return response.json();
})
.then(data => {
return data.map(item => ({
...item,
site: file.site,
isArticle: file.isArticle,
displayName: file.displayName,
title: item.기사명 || item.제목 || '제목 없음',
link: item.링크 || item.link || '#',
category: item.분류 || item.category || '',
}));
})
.catch(error => {
console.error(`Error loading ${file.url}:`, error);
return [];
});
}),
loadFewshotExamples(),
loadExcludedArticles()
];
Promise.all(promises)
.then(results => {
// 마지막 2개 결과(fewshotExamples, excludedArticles)는 이미 전역변수에 저장됨
const dataResults = results.slice(0, -2);
dataResults.forEach(siteData => {
if (siteData.length > 0) {
if (siteData[0].isArticle) articleData = articleData.concat(siteData);
else publicationData = publicationData.concat(siteData);
}
});
allDataLoaded = true;
console.log(`Loaded ${articleData.length} articles, ${publicationData.length} publications.`);
showTab('HOME');
})
.catch(error => {
console.error("Critical error:", error);
document.getElementById('no-data').textContent = "데이터 로드 중 치명적인 오류 발생.";
});
}
// -----------------------------------------------------
// 6. UI/UX 렌더링 및 헬퍼 함수들
// -----------------------------------------------------
function sortData(data, sortBy) {
const sortedData = [...data];
sortedData.sort((a, b) => {
const getDateString = (item) => `${item.년 || '0000'}${item.월 || '00'}${item.일 || '00'}${item.시 || '00'}${item.분 || '00'}`;
const dateA = getDateString(a);
const dateB = getDateString(b);
switch (sortBy) {
case 'date_asc': return dateA.localeCompare(dateB);
case 'date_desc': return dateB.localeCompare(dateA);
case 'title_asc': return a.title.localeCompare(b.title);
case 'site_asc': return a.site !== b.site ? a.site.localeCompare(b.site) : dateB.localeCompare(dateA);
case 'category_asc': return a.category !== b.category ? a.category.localeCompare(b.category) : dateB.localeCompare(dateA);
default: return 0;
}
});
return sortedData;
}
function showTab(sourceName) {
currentView = sourceName;
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
const activeTab = document.querySelector(`.tab-button[data-source="${sourceName}"]`);
if (activeTab) activeTab.classList.add('active');
const isHome = sourceName === 'HOME';
const isArticleView = sourceName.includes('ARTICLE') || ['AIKOREA', 'AITIMES', 'ETNEWS', 'AINEWS', 'MND', 'kookbang', 'DAPA', 'MSIT'].includes(sourceName);
const isPublicationView = sourceName.includes('PUBLICATION') || ['NIA', 'IITP', 'STEPI', 'NIPA', 'KISDI', 'KISTI', 'KISA', 'TTA'].includes(sourceName);
document.getElementById('dashboard-view').style.display = isHome ? 'block' : 'none';
document.getElementById('list-view').style.display = isHome ? 'none' : 'block';
document.getElementById('article-controls').style.display = isArticleView ? 'flex' : 'none';
document.getElementById('publication-controls').style.display = isPublicationView ? 'flex' : 'none';
document.getElementById('main-content-title').textContent = activeTab ? activeTab.textContent.replace(/^(🏠|📰|⭐️|📚) /, '') : 'AI 동향 분석';
if (isHome) renderDashboard();
else renderList(sourceName);
}
function renderCurrentView() { showTab(currentView); }
function renderDashboard() {
// Stats removed
const latestArticles = sortData(articleData, 'date_desc').slice(0, 5);
document.getElementById('latest-articles').innerHTML = latestArticles.map(item => `
<li class="latest-item">
<a href="#" onclick="openPopup('${escapeHTML(item.link)}', '${escapeHTML((item.title || '').replace(/'/g, "\\'"))}'); return false;">${escapeHTML(item.title)}</a>
<span>${escapeHTML(item.displayName)} | ${escapeHTML(item.년)}.${escapeHTML(item.월)}.${escapeHTML(item.일)}</span>
</li>
`).join('');
const latestPublications = sortData(publicationData, 'date_desc').slice(0, 5);
document.getElementById('latest-publications').innerHTML = latestPublications.map(item => `
<li class="latest-item">
<a href="#" onclick="openPopup('${escapeHTML(item.link)}', '${escapeHTML((item.title || '').replace(/'/g, "\\'"))}'); return false;">${escapeHTML(item.title)}</a>
<span>${escapeHTML(item.displayName)} | ${escapeHTML(item.년)}.${escapeHTML(item.월)}.${escapeHTML(item.일)}</span>
</li>
`).join('');
}
function renderList(sourceName) {
let data = [];
let sortBy, searchTerm, dataLabel;
const isArticle = sourceName.includes('ARTICLE') || ['AIKOREA', 'AITIMES', 'ETNEWS', 'AINEWS', 'MND', 'kookbang', 'DAPA', 'MSIT'].includes(sourceName);
const isAll = sourceName.includes('_ALL');
const isFav = sourceName.includes('_FAV');
if (isArticle) {
sortBy = document.getElementById('sort-by-article').value;
searchTerm = document.getElementById('search-term-article').value.toLowerCase();
dataLabel = '기사';
if (isFav) data = articleData.filter(a => favoriteArticles.has(a.link));
else if (isAll) data = articleData;
else data = articleData.filter(a => a.site === sourceName);
} else {
sortBy = document.getElementById('sort-by-publication').value;
searchTerm = document.getElementById('search-term-publication').value.toLowerCase();
dataLabel = '간행물';
if (isFav) data = publicationData.filter(p => favoritePublications.has(p.link));
else if (isAll) data = publicationData;
else data = publicationData.filter(p => p.site === sourceName);
}
if (searchTerm) data = data.filter(item => item.title.toLowerCase().includes(searchTerm));
const filteredAndSortedData = sortData(data, sortBy);
const listContainer = document.getElementById('data-list-container');
const noDataMsg = document.getElementById('no-data');
if (filteredAndSortedData.length === 0) {
listContainer.innerHTML = '';
noDataMsg.style.display = 'block';
noDataMsg.textContent = searchTerm ? `검색어 "${searchTerm}" 결과 없음` : `데이터가 없습니다.`;
} else {
listContainer.innerHTML = filteredAndSortedData.map(item => createListItem(item)).join('');
noDataMsg.style.display = 'none';
}
}
function createListItem(item) {
const timeInfo = (item.시 && item.분) ? `${item.시.padStart(2, '0')}:${item.분.padStart(2, '0')}` : '';
const fullDate = `${item.년}.${item.월}.${item.일} ${timeInfo}`;
let isFavorite = item.isArticle ? favoriteArticles.has(item.link) : favoritePublications.has(item.link);
let categoryBadge = '';
let colorClass = 'cat-default';
if (isFavorite) {
const savedCat = item.isArticle ? favoriteArticles.get(item.link) : favoritePublications.get(item.link);
if (item.isArticle) {
if (savedCat === '국방') colorClass = 'cat-defense';
else if (savedCat === '육군') colorClass = 'cat-army';
else if (savedCat === '민간') colorClass = 'cat-civil';
else if (savedCat === '기관') colorClass = 'cat-pub';
else if (savedCat === '해외') colorClass = 'cat-foreign';
else if (savedCat === '기타') colorClass = 'cat-etc';
} else {
colorClass = 'cat-default';
}
categoryBadge = `<span class="category-badge ${colorClass}">${savedCat}</span>`;
}
// 관리자 모드에서만 표시되는 버튼들 (관리자 인증된 경우에만)
let fewshotButtons = '';
if (item.isArticle && isAdminMode) {
const isLearned = fewshotExamples.some(ex => ex.title === item.title && ex.site === item.displayName);
const learnBtn = isLearned
? `<button class="learn-btn" onclick="removeFewshotExample(event, '${item.link}')" title="FewShot 학습에서 제거" style="background:none;border:none;cursor:pointer;font-size:1.1em;padding:0 3px;">🧠✕</button>`
: `<button class="learn-btn" onclick="addFewshotExample(event, '${item.link}')" title="FewShot 학습 데이터로 추가" style="background:none;border:none;cursor:pointer;font-size:1.1em;padding:0 3px;">🧠</button>`;
const isExcluded = excludedArticles.has(item.link);
const excludeBtn = isExcluded
? `<button class="learn-btn" onclick="toggleExcludeArticle(event, '${item.link}')" title="제외 해제 클릭 → 일일동향에 다시 포함" style="background:#e74c3c;color:white;border:none;border-radius:4px;cursor:pointer;font-size:0.9em;padding:2px 6px;font-weight:bold;">🚫</button>`
: `<button class="learn-btn" onclick="toggleExcludeArticle(event, '${item.link}')" title="일일동향에서 제외 (AI가 이 기사를 선택하지 않음)" style="background:none;border:none;cursor:pointer;font-size:1.1em;padding:0 3px;">🚫</button>`;
fewshotButtons = learnBtn + excludeBtn;
}
const isExcluded = excludedArticles.has(item.link);
// 관리자 모드일 때만 음영/뱃지 표시
const excludeStyle = (isExcluded && isAdminMode) ? 'opacity:0.45;' : '';
const excludeBadge = (isExcluded && isAdminMode) ? '<span style="font-size:0.75em;color:#e74c3c;font-weight:bold;margin-left:6px;">[ 일일동향 제외 ]</span>' : '';
return `
<li class="article-item" style="${excludeStyle}">
<div class="article-actions">
<button class="favorite-btn ${isFavorite ? 'is-favorite' : ''}" onclick="toggleFavorite(event, '${escapeHTML(item.link)}', ${item.isArticle})">${isFavorite ? '★' : '☆'}</button>
${fewshotButtons}
</div>
<div class="article-title-group">
<a href="#" class="article-title" onclick="openPopup('${escapeHTML(item.link)}', '${escapeHTML((item.title || '').replace(/'/g, "\\'"))}'); return false;">${escapeHTML(item.title)}</a>
${excludeBadge}
${categoryBadge}
<div class="article-meta">
<span>출처: ${escapeHTML(item.displayName)}</span>
<span>분류: ${escapeHTML(item.category || '-')}</span>
</div>
</div>
<div class="article-date">${escapeHTML(fullDate)}</div>
</li>
`;
}
function toggleFavorite(event, link, isArticle) {
event.stopPropagation();
if (isArticle) {
if (favoriteArticles.has(link)) favoriteArticles.delete(link);
else {
let cat = prompt("카테고리 (국방, 육군, 민간, 기관, 해외, 기타)", "");
if (cat === null) return;
favoriteArticles.set(link, cat.trim() || "기타");
}
localStorage.setItem('favoriteArticles', JSON.stringify(Array.from(favoriteArticles.entries())));
} else {
if (favoritePublications.has(link)) favoritePublications.delete(link);
else favoritePublications.set(link, "간행물");
localStorage.setItem('favoritePublications', JSON.stringify(Array.from(favoritePublications.entries())));
}
renderCurrentView();
// Stats removed
}
function clearFavorites(type) {
if (!confirm("정말 모두 삭제하시겠습니까?")) return;
if (type === 'ARTICLE') {
favoriteArticles.clear();
localStorage.setItem('favoriteArticles', JSON.stringify([]));
} else {
favoritePublications.clear();
localStorage.setItem('favoritePublications', JSON.stringify([]));
}
renderCurrentView();
}
function openPopup(link, title) {
if (link && link !== '#') window.open(link, '_blank');
else alert(`"${title}" 링크가 없습니다.`);
}
async function addFewshotExample(event, link) {
event.stopPropagation();
// Find the item
const item = articleData.find(a => a.link === link);
if (!item) return;
// Prompt user for category
const cat = prompt(`[AI 분류 학습 데이터 추가]\n\n기사 제목: ${item.title}\n출처: ${item.displayName}\n\n이 기사의 올바른 카테고리를 입력하세요.\n(국방, 육군, 민간, 기관, 해외, 기타 중 하나)`, "국방");
if (!cat) return;
const category = cat.trim();
if (!["국방", "육군", "민간", "기관", "해외", "기타"].includes(category)) {
alert("❌ 알맞은 카테고리(국방, 육군, 민간, 기관, 해외, 기타)를 입력해주세요.");
return;
}
// 선택적 이유 입력
const reasonInput = prompt(`[학습 이유 입력 - 선택사항]\n\n카테고리: ${category}\n\nAI가 이 기사를 "${category}"로 분류해야 하는 이유를 간략히 입력하세요.\n(이유를 입력하지 않아도 됩니다. 취소 또는 빈 칸으로 건너뜀)`, "");
const reason = reasonInput !== null ? reasonInput.trim() : '';
const filePath = "codes/favorites/fewshot_examples.json";
const getEndpoint = `repos/${OWNER}/${REPO}/contents/${filePath}`;
let fewshotData = [];
let sha = null;
try {
// Show loading status safely
const originalText = event.target.textContent;
event.target.textContent = "⏳";
// Try to get existing file
try {
const getResData = await callProxyAPI(`${getEndpoint}?ref=${BRANCH}`, 'GET');
if (getResData) {
sha = getResData.sha; // Capture SHA first
if (getResData.content) {
const decodedContent = base64ToUtf8(getResData.content);
fewshotData = JSON.parse(decodedContent);
}
}
} catch (e) {
// File might not exist (404), which is fine
console.log("Few-shot examples file not found or empty. Using empty array.");
}
// Check for duplicates
const exists = fewshotData.some(d => d.title === item.title && d.site === item.site);
if (exists) {
alert("⚠️ 이미 학습 데이터에 존재하는 기사입니다.");
event.target.textContent = originalText;
return;
}
fewshotData.push({
site: item.displayName,
title: item.title,
category: category,
...(reason && { reason }) // 이유가 입력된 경우만 포함
});
const jsonString = JSON.stringify(fewshotData, null, 2);
const encodedContent = btoa(unescape(encodeURIComponent(jsonString)));
const putBody = {
message: `Add few-shot example: ${item.title}`,
content: encodedContent,
branch: BRANCH,
...(sha && { sha })
};
await callProxyAPI(getEndpoint, 'PUT', putBody);
// 로컬 데이터 업데이트 및 UI 갱신
fewshotExamples = fewshotData;
renderCurrentView();
alert("✅ 올바른 카테고리 학습 데이터(Few-Shot)에 성공적으로 추가되었습니다.");
} catch (err) {
console.error("Error saving few-shot example:", err);
alert("❌ 학습 데이터 저장 실패: " + err.message);
} finally {
// Restore button icon
event.target.textContent = "🧠";
}
}
// FewShot 제외 함수 (학습 데이터에서 삭제)
async function removeFewshotExample(event, link) {
event.stopPropagation();
const item = articleData.find(a => a.link === link);
if (!item) return;
if (!confirm(`[FewShot 제외]\n\n기사 제목: ${item.title}\n출처: ${item.displayName}\n\n이 기사를 FewShot 학습 데이터에서 제외하시겠습니까?`)) return;
const filePath = "codes/favorites/fewshot_examples.json";
const getEndpoint = `repos/${OWNER}/${REPO}/contents/${filePath}`;
try {
const originalText = event.target.textContent;
event.target.textContent = "⏳";
const getResData = await callProxyAPI(`${getEndpoint}?ref=${BRANCH}`, 'GET');
if (!getResData || !getResData.content) {
alert("⚠️ FewShot 데이터 파일을 찾을 수 없습니다.");
event.target.textContent = originalText;
return;
}
let fewshotData = JSON.parse(base64ToUtf8(getResData.content));
const sha = getResData.sha;
const prevLen = fewshotData.length;
fewshotData = fewshotData.filter(d => !(d.title === item.title && d.site === item.displayName));
if (fewshotData.length === prevLen) {
alert("⚠️ 해당 기사가 학습 데이터에 없습니다.");
event.target.textContent = originalText;
return;
}
const jsonString = JSON.stringify(fewshotData, null, 2);
const encodedContent = btoa(unescape(encodeURIComponent(jsonString)));
await callProxyAPI(getEndpoint, 'PUT', {
message: `Remove few-shot example: ${item.title}`,
content: encodedContent,
branch: BRANCH,
sha
});
fewshotExamples = fewshotData;
renderCurrentView();
alert("✅ FewShot 학습 데이터에서 제외되었습니다.");
} catch (err) {
console.error("Error removing few-shot example:", err);
alert("❌ 제거 실패: " + err.message);
} finally {
event.target.textContent = "🚫";
}
}
// 일일동향 제외 토글 (excluded_articles.json에 저장)
async function toggleExcludeArticle(event, link) {
event.stopPropagation();
const item = articleData.find(a => a.link === link);
if (!item) return;
const isCurrentlyExcluded = excludedArticles.has(link);
const confirmMsg = isCurrentlyExcluded
? `[제외 해제]\n\n기사 제목: ${item.title}\n출처: ${item.displayName}\n\n이 기사를 일일동향에 다시 포함시키겠습니까?`
: `[일일동향 제외]\n\n기사 제목: ${item.title}\n출처: ${item.displayName}\n\nAI가 이 기사를 일일동향에 절대 포함하지 않도록 설정합니다.\n계속하시겠습니까?`;
if (!confirm(confirmMsg)) return;
const originalText = event.target.textContent;
event.target.textContent = '⏳';
const filePath = 'codes/favorites/excluded_articles.json';
const getEndpoint = `repos/${OWNER}/${REPO}/contents/${filePath}`;
try {
let excludedData = [];
let sha = null;
// sha는 반드시 먼저 추출 (파일 존재 여부 확인)
try {
const getResData = await callProxyAPI(`${getEndpoint}?ref=${BRANCH}`, 'GET');
if (getResData) {
sha = getResData.sha; // 파일이 존재하면 sha 즉시 저장
if (getResData.content) {
try {
excludedData = JSON.parse(base64ToUtf8(getResData.content));
} catch (parseErr) {
console.warn('excluded_articles.json 파싱 실패, 빈 배열로 초기화');
excludedData = [];
}
}
}
} catch (e) {
// 404: 파일이 없음 → sha=null로 새 파일 생성
console.log('excluded_articles.json not found. Creating new one.');
}
if (isCurrentlyExcluded) {
excludedData = excludedData.filter(d => d.link !== link);
excludedArticles.delete(link);
} else {
// 제외 시 선택적 이유 입력
const reasonInput = prompt(`[제외 이유 입력 - 선택사항]\n\n기사 제목: ${item.title}\n\nAI가 이 기사를 일일동향에 절대 포함하지 말아야 하는 이유를 간략히 입력하세요.\n(입력하지 않아도 됩니다. 취소 또는 빈 칸으로 건너뜀)`, '');
const reason = reasonInput !== null ? reasonInput.trim() : '';
excludedData.push({
title: item.title,
link: item.link,
site: item.displayName,
...(reason && { reason })
});
excludedArticles.add(link);
}
const jsonString = JSON.stringify(excludedData, null, 2);
const encodedContent = btoa(unescape(encodeURIComponent(jsonString)));
const putBody = {
message: `${isCurrentlyExcluded ? 'Remove' : 'Add'} excluded article: ${item.title}`,
content: encodedContent,
branch: BRANCH
};
if (sha) putBody.sha = sha; // 파일이 존재하는 경우만 sha 포함
await callProxyAPI(getEndpoint, 'PUT', putBody);
renderCurrentView();
alert(isCurrentlyExcluded
? '✅ 제외가 해제되었습니다. 이 기사는 이제 일일동향 선정 대상에 포함됩니다.'
: '✅ 제외 완료! AI가 이 기사를 일일동향에 포함하지 않습니다.');
} catch (err) {
console.error('Error toggling excluded article:', err);
alert('❌ 실패: ' + err.message);
// 롤백
if (isCurrentlyExcluded) excludedArticles.add(link);
else excludedArticles.delete(link);
} finally {
event.target.textContent = originalText;
}
}
// 관리자 모드 토글 (사이드바 버튼)
async function toggleAdminMode() {
if (isAdminMode) {
// 이미 잠금 해제 상태 → 다시 잠금
isAdminMode = false;
adminPassword = ""; // 로그아웃 시 비밀번호 초기화
document.getElementById('adminModeBtn').style.background = '#555';
document.getElementById('adminModeBtn').innerText = '🔒 Admin';
document.getElementById('adminModeBtn').title = '관리자 모드 (인증 필요)';
renderCurrentView();
return;
}
// 비밀번호 인증
const isVerified = await verifyPassword();
if (!isVerified) return;
isAdminMode = true;
document.getElementById('adminModeBtn').style.background = '#e67e22';
document.getElementById('adminModeBtn').innerText = '🔓 Admin';
document.getElementById('adminModeBtn').title = '관리자 모드 활성화됨 (클릭하여 잠금)';
renderCurrentView();
alert("✅ 관리자 모드가 활성화되었습니다.\n전체 관리자 기능 및 FewShot/제외 관리가 가능합니다.");
}
const debounce = (func, delay) => {
return function (...args) {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => func.apply(this, args), delay);
};
};
const debounceSearchArticles = debounce(renderCurrentView, 300);
const debounceSearchPublications = debounce(renderCurrentView, 300);
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.tab-button').forEach(button => {
button.addEventListener('click', (e) => {
e.preventDefault();
showTab(e.target.getAttribute('data-source'));
});
});
loadData();
});
// -----------------------------------------------------
// 7. AI 자동 선정 (autoSelectFavoritesBtn)
// -----------------------------------------------------
document.getElementById('autoSelectFavoritesBtn').addEventListener('click', async function () {
const message = "🤖 AI(Gemini) 자동 즐겨찾기 생성을 시작하시겠습니까?\n\n" +
"✅ 어제(KST) 기사/간행물을 분석하여 자동 선정하고 분류합니다.\n" +
"✅ 약 4분 이상 소요.(별도 알람❌) 이후 대시보드에서 바로 '텍스트추출'을 눌러 일일동향을 활용하세요.\n" +
"⚠️ 수동 실행하지 않아도 매일 오전 6시경 자동 생성 합니다."
if (!confirm(message)) return;
// 비밀번호 확인 추가
const isVerified = await verifyPassword();
if (!isVerified) return;
updateStatus("AI 자동 선정 요청 중...");
const WORKFLOW_ID = "auto_favorites.yml";
const endpoint = `repos/${OWNER}/${REPO}/actions/workflows/${WORKFLOW_ID}/dispatches`;
try {
await callProxyAPI(endpoint, 'POST', { ref: "main" });
alert("✅ 실행 요청 완료! 약 2분 뒤 데이터가 자동 업데이트됩니다.\n(새로고침 불필요)");
updateStatus("AI 자동 선정이 진행 중입니다... (약 2~4분 소요)");
} catch (error) {
console.error('Error:', error);
alert(`❌ 실행 실패: ${error.message}`);
updateStatus("");
}
});
// -----------------------------------------------------
// 8. 즐겨찾기 JSON 업로드 (uploadFavoritesBtn)
// -----------------------------------------------------
document.getElementById('uploadFavoritesBtn').addEventListener('click', async function () {
if (!(await verifyPassword())) return; // 권한 확인 추가
const files = [
{
type: "ARTICLE",
path: "codes/favorites/favorite_articles.json",
data: articleData.filter(item => favoriteArticles.has(item.link)).map(item => ({
title: item.title, link: item.link, category: favoriteArticles.get(item.link)
}))
},
{
type: "PUBLICATION",
path: "codes/favorites/favorite_publications.json",
data: publicationData.filter(item => favoritePublications.has(item.link)).map(item => ({
title: item.title, link: item.link, category: favoritePublications.get(item.link)
}))
}
];
for (const file of files) {
if (file.data.length === 0) continue;
const jsonString = JSON.stringify(file.data, null, 2);
const encodedContent = btoa(unescape(encodeURIComponent(jsonString)));
try {
let sha = null;
const getEndpoint = `repos/${OWNER}/${REPO}/contents/${file.path}`;
const getResData = await callProxyAPI(getEndpoint, 'GET').catch(() => null);
if (getResData && getResData.sha) sha = getResData.sha;
const putBody = {
message: `update ${file.path}`,
content: encodedContent,
branch: BRANCH,
...(sha && { sha })
};
await callProxyAPI(getEndpoint, 'PUT', putBody);
console.log(`✅ ${file.type} 저장 완료`);
} catch (err) {
console.error(`❌ ${file.type} 실패: ${err.message}`);
alert(`${file.type} 저장 실패`);
}
}
// alert("✅ 모든 데이터 업로드 완료");
updateStatus("데이터 텍스트 변환 요청 중...");
const WORKFLOW_ID = "json_to_txt.yml";
const endpoint = `repos/${OWNER}/${REPO}/actions/workflows/${WORKFLOW_ID}/dispatches`;
try {
await callProxyAPI(endpoint, 'POST', { ref: "main" });
alert("✅ 즐겨찾기에 있는 목록을 일일 동향 텍스트로 만듭니다.\n\n✅️ 약 30초 후 대시보드에서 '텍스트추출'을 누르세요.");
updateStatus("텍스트 변환 작업이 진행 중입니다... (약 30초 소요)");
} catch (error) {
console.error('Error:', error);
alert(`❌ 실패: ${error.message}`);
updateStatus("");
}
});
// 사이드바 토글
document.getElementById('sidebarToggle').addEventListener('click', () => {
const container = document.querySelector('.container');
if (window.innerWidth <= 768) container.classList.toggle('sidebar-open');
else container.classList.toggle('sidebar-collapsed');
});
// -----------------------------------------------------
// 9. 데이터 전체 삭제 (deleteCodesBtn)
// -----------------------------------------------------
document.getElementById('deleteCodesBtn').addEventListener('click', async function () {
const confirmMsg = "⚠️ 경고 ⚠️\n모든 데이터를 삭제합니다.\n이 작업은 되돌릴 수 없습니다.\n정말 삭제하시겠습니까?";
if (!confirm(confirmMsg)) return;
if (!(await verifyPassword())) return; // 권한 확인 추가
try {
const listEndpoint = `repos/${OWNER}/${REPO}/contents/codes`;
const files = await callProxyAPI(listEndpoint, 'GET');
if (!Array.isArray(files)) {
throw new Error("파일 목록을 불러오지 못했습니다.");
}
const targetFiles = files.filter(file =>
file.type === "file" && (file.name.endsWith(".json") || file.name.endsWith(".txt"))
);
if (targetFiles.length === 0) {
alert("삭제할 데이터가 없습니다.");
return;
}
for (const file of targetFiles) {
const deleteBody = {
message: `delete ${file.path}`,
sha: file.sha,
branch: BRANCH
};
const endpoint = `repos/${OWNER}/${REPO}/contents/${file.path}`;
await callProxyAPI(endpoint, 'DELETE', deleteBody);
console.log(`🗑 삭제 완료: ${file.name}`);
}
alert(`✅ 데이터 초기화 완료\n잠시후 페이지를 새로고침하세요.`);
} catch (error) {
console.error(error);
alert("❌ 삭제 중 오류 발생: " + error.message);
}
});
// -----------------------------------------------------
// 10. 오디오 생성 실행 (createAudioBtn) - Vercel Proxy 적용
// -----------------------------------------------------
document.getElementById('createAudioBtn').addEventListener('click', async function () {
// 1. 사용자 확인 (토큰 검사는 Proxy가 처리하므로 제거)
const message = "🎙️ AI 뉴스 브리핑 오디오를 생성하시겠습니까?\n(약 1~2분 소요됩니다)";
if (!confirm(message)) return;
// 비밀번호 확인 추가
const isVerified = await verifyPassword();
if (!isVerified) return;
// 2. API 호출 준비
const WORKFLOW_ID = "audio_gen.yml";
const endpoint = `repos/${OWNER}/${REPO}/actions/workflows/${WORKFLOW_ID}/dispatches`;
updateStatus("AI 오디오 브리핑 생성 요청 중...");
try {
// 3. callProxyAPI를 통해 안전하게 요청 전송
await callProxyAPI(endpoint, 'POST', { ref: "main" });
alert("✅ 브리핑 생성 요청 성공!\nGemini가 대본을 쓰고 녹음 중입니다.\n약 1분 뒤 페이지를 새로고침하여 들어보세요.");
updateStatus("오디오 브리핑 생성 중... (약 1~2분 소요)");
} catch (error) {
console.error('Error:', error);
alert(`❌ 실패: ${error.message}`);
updateStatus("");
}
});
// 11. 최근업데이트 불러오기
async function loadCompletionTime() {
try {
const response = await fetch('public/update_time.json?t=' + new Date().getTime());
if (!response.ok) {
throw new Error('시간 정보를 불러올 수 없습니다.');
}
const data = await response.json();
const timeElement = document.getElementById('workflow-completed-time');
if (timeElement) {
timeElement.innerText = data.completed_at;
}
} catch (error) {
console.error(error);
const timeElement = document.getElementById('workflow-completed-time');
if (timeElement) {
timeElement.innerText = "시간 정보 없음";
}
}
}
document.addEventListener('DOMContentLoaded', () => {
loadCompletionTime();