summaryrefslogtreecommitdiff
path: root/layouts/recordings/recordings-plain.html
blob: d3c273ef70c41b77a510e3d83ec5280f19674fc1 (plain)
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
<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>{{ .Title }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style>
      body {
        font-family:
          system-ui,
          Segoe UI,
          Roboto,
          Apple SD Gothic Neo,
          AppleGothic,
          sans-serif;
        max-width: 900px;
        margin: 32px auto;
        padding: 0 16px;
      }
      h1 {
        margin-bottom: 12px;
      }
      ul {
        line-height: 1.9;
        padding-left: 1.1rem;
      }
      a {
        text-decoration: none;
      }
      a:hover {
        text-decoration: underline;
      }
      .meta {
        color: #666;
        margin-top: 4px;
      }
      video {
        width: 100%;
        height: auto;
        margin: 12px 0;
      }
      img.preview {
        width: 100%;
        height: auto;
        margin: 12px 0;
      }
      .badge {
        font-size: 0.8rem;
        border: 1px solid #ccc;
        border-radius: 6px;
        padding: 2px 6px;
        margin-left: 6px;
      }
      .folder-section {
        margin: 16px 0;
        border: 1px solid #ddd;
        border-radius: 8px;
        background: #f9f9f9;
      }
      .folder-header {
        padding: 8px 12px;
        cursor: pointer;
        font-weight: 600;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .folder-header:hover {
        background: #f0f0f0;
      }
      .folder-name {
        color: #333;
      }
      .folder-count {
        color: #666;
        font-size: 0.9rem;
        font-weight: normal;
      }
      .folder-content {
        padding: 0 12px 12px;
        margin: 0;
        border-top: 1px solid #eee;
        background: white;
      }
      .folder-content li {
        margin: 8px 0;
        padding: 4px 0;
        border-bottom: 1px solid #f0f0f0;
      }
      .folder-content li:last-child {
        border-bottom: none;
      }
      /* 제한된 폴더는 기본적으로 숨김 (si 사용자만 표시) */
      li.folder-section[data-restricted="true"] {
        display: none;
      }
      li.folder-section[data-restricted="true"].allowed {
        display: block;
      }
    </style>
    <script>
      // 즉시 실행: 제한된 폴더 숨기기 (FOUC 방지)
      (function() {
        let isSiUser = false;
        
        // 쿠키에서 사용자 확인
        const cookies = document.cookie.split(';').reduce((acc, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        isSiUser = cookies.user === 'si' || cookies.authUser === 'si';
        
        // DOM이 준비되면 즉시 처리
        function applyRestrictions() {
          const restrictedFolders = document.querySelectorAll('li.folder-section[data-restricted="true"]');
          if (isSiUser) {
            restrictedFolders.forEach(folder => {
              folder.classList.add('allowed');
            });
          }
        }
        
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', applyRestrictions);
        } else {
          applyRestrictions();
        }
        
        // 쿠키가 없으면 재확인 (쿠키는 nginx에서 설정됨)
        if (!isSiUser) {
          setTimeout(() => {
            const cookies2 = document.cookie.split(';').reduce((acc, cookie) => {
              const [key, value] = cookie.trim().split('=');
              acc[key] = value;
              return acc;
            }, {});
            if (cookies2.user === 'si' || cookies2.authUser === 'si') {
              isSiUser = true;
              applyRestrictions();
            }
          }, 100);
        }
        
        // API로 최종 확인
        fetch('/api/whoami.php', { credentials: 'include' })
          .then(r => r.ok ? r.json() : null)
          .then(data => {
            if (data && data.user === 'si') {
              isSiUser = true;
              applyRestrictions();
            }
          })
          .catch(() => {});
      })();
    </script>
  </head>
  <body>
    <h1>{{ .Title }}</h1>

    <!-- 섹션 소개 글 -->
    <div class="content">{{ .Content }}</div>

    <!-- 인라인 플레이어 -->
    <div id="player" style="display: none">
      <video id="video" controls preload="metadata"></video>
      <img id="image" class="preview" alt="" style="display:none" />
      <div id="meta" class="meta"></div>
    </div>

    {{/* 섹션 레벨 배경음악 (recordings/ 루트에 오디오 파일이 있는 경우) */}}
    {{ $secAudio := .Resources.Match "*.{mp3,m4a,ogg,wav,opus,OPUS,OGG,WAV,MP3,M4A}" }}
    {{ with (index $secAudio 0) }}
    <audio id="bgm" src="{{ .RelPermalink }}" preload="auto" loop style="display:none"></audio>
    <div style="position:fixed;right:16px;bottom:16px;z-index:10">
      <button id="bgm-toggle" class="badge" style="opacity:.8;cursor:pointer;border:none;background:#666;color:white">BGM ▷</button>
    </div>
    {{ end }}

    <ul id="list">
      <!-- 페이지 폴더명 -> 페이지 객체 매핑 제거 (노트는 아래에서 일괄 정렬 출력) -->
      <!-- 1) 섹션 폴더 바로 아래 mp4/mov (섹션 리소스) -->
      {{ $secVids := .Resources.Match "*.{mp4,mov}" }}
      {{ range $v := $secVids }}
      <li>
        <a href="{{ $v.RelPermalink }}" data-name="{{ $v.Name }}" class="vid"
          >{{ $v.Name }}</a
        >
        <span class="badge">video</span>
      </li>
      {{ end }}

      <!-- 1-3) 섹션 폴더 바로 아래 HEIC (다운로드/새 탭 열기 전용) -->
      {{ $secHeic := .Resources.Match "*.{heic,HEIC}" }}
      {{ range $h := $secHeic }}
      <li>
        <a href="{{ $h.RelPermalink }}" data-name="{{ $h.Name }}" class="heic"
          >{{ $h.Name }}</a
        >
        <span class="badge">heic</span>
      </li>
      {{ end }}

      <!-- 1-2) 섹션 폴더 바로 아래 이미지/GIF (섹션 리소스) -->
      {{ $secImgs := .Resources.Match "*.{jpg,jpeg,png,gif,webp,svg}" }}
      {{ range $i := $secImgs }}
      <li>
        <a href="{{ $i.RelPermalink }}" data-name="{{ $i.Name }}" class="img"
          >{{ $i.Name }}</a
        >
        <span class="badge">image</span>
      </li>
      {{ end }}

      <!-- 1-4) 하위 폴더별 트리 구조 -->
      {{ $subfolderFiles := .Resources.Match "**/*.{mp4,mov,jpg,jpeg,png,gif,webp,svg,heic,HEIC}" }}
      {{ $.Scratch.Set "folderGroups" (dict) }}
      {{ range $f := $subfolderFiles }}
        {{ $dir := path.Dir $f.RelPermalink }}
        {{ if ne $dir "." }}
          {{ $folderName := path.Base $dir }}
          {{ $currentGroups := $.Scratch.Get "folderGroups" }}
          {{ $folderFiles := index $currentGroups $folderName }}
          {{ if $folderFiles }}
            {{ $.Scratch.Add (printf "folder_%s" $folderName) (slice $f) }}
          {{ else }}
            {{ $.Scratch.Set (printf "folder_%s" $folderName) (slice $f) }}
            {{ $newGroups := merge $currentGroups (dict $folderName true) }}
            {{ $.Scratch.Set "folderGroups" $newGroups }}
          {{ end }}
        {{ end }}
      {{ end }}

      {{ $folderGroups := $.Scratch.Get "folderGroups" }}
      {{/* Leak 폴더가 없으면 강제로 추가 (파일이 없어도 표시) */}}
      {{ $leakLower := "leak" }}
      {{ $hasLeak := false }}
      {{ range $folderName, $exists := $folderGroups }}
        {{ if eq (lower $folderName) $leakLower }}
          {{ $hasLeak = true }}
        {{ end }}
      {{ end }}
      {{ if not $hasLeak }}
        {{ $folderGroups = merge $folderGroups (dict "Leak" true) }}
        {{ $.Scratch.Set "folderGroups" $folderGroups }}
        {{ $.Scratch.Set "folder_Leak" (slice) }}
      {{ end }}
      {{ $folderGroups = $.Scratch.Get "folderGroups" }}
      {{ range $folderName, $exists := $folderGroups }}
      {{ $files := $.Scratch.Get (printf "folder_%s" $folderName) }}
      {{ $isRestricted := or (eq $folderName "hidden") (eq (lower $folderName) "leak") }}
      <li class="folder-section" {{ if $isRestricted }}data-restricted="true"{{ end }}>
        <details>
          <summary class="folder-header">
            <span class="folder-name" data-encoded="{{ $folderName }}">{{ $folderName }}/</span>
            <span class="folder-count">({{ len $files }} items)</span>
          </summary>
          <ul class="folder-content">
            {{ range $f := $files }}
            {{ $ext := path.Ext $f.Name | lower }}
            <li>
              <a href="{{ $f.RelPermalink }}" data-name="{{ $f.Name }}"
                {{ if or (eq $folderName "hidden") (eq (lower $folderName) "leak") }}class="hidden-file"{{ else }}{{ if in (slice ".mp4" ".mov") $ext }}class="vid"{{ else if in (slice ".jpg" ".jpeg" ".png" ".gif" ".webp" ".svg") $ext }}class="img"{{ else if in (slice ".heic") $ext }}class="heic"{{ end }}{{ end }}
                >{{ $f.Name }}</a
              >
              <span class="badge">
                {{ if in (slice ".mp4" ".mov") $ext }}video{{ else if in (slice ".jpg" ".jpeg" ".png" ".gif" ".webp" ".svg") $ext }}image{{ else if in (slice ".heic") $ext }}heic{{ end }}
              </span>
            </li>
            {{ end }}
          </ul>
        </details>
      </li>
      {{ end }}

      <!-- 2) 자식 페이지들 (노트/동영상 페이지) - 월별 그룹: 현재 달은 평면, 과거 달은 접기 -->
      {{ $nowMonth := now.Format "2006-01" }}
      {{ $.Scratch.Set "monthKeys" (slice) }}
      {{ $.Scratch.Set "monthSeen" (dict) }}
      {{ range $p := .Pages.ByDate.Reverse }}
        {{ if eq $p.File.BaseFileName "whoareyou" }}{{ continue }}{{ end }}
        {{ $dstr := $p.Date.Format "2006-01-02" }}
        {{ $m := cond (eq $dstr "0001-01-01") "etc" ($p.Date.Format "2006-01") }}
        {{ $seen := $.Scratch.Get "monthSeen" }}
        {{ if not (index $seen $m) }}
          {{ $.Scratch.Set "monthSeen" (merge $seen (dict $m true)) }}
          {{ $.Scratch.Add "monthKeys" (slice $m) }}
        {{ end }}
        {{ $key := printf "month_%s" $m }}
        {{ if $.Scratch.Get $key }}
          {{ $.Scratch.Add $key (slice $p) }}
        {{ else }}
          {{ $.Scratch.Set $key (slice $p) }}
        {{ end }}
      {{ end }}

      {{ $monthKeys := $.Scratch.Get "monthKeys" }}

      {{ range $m := $monthKeys }}
        {{ $key := printf "month_%s" $m }}
        {{ $pages := $.Scratch.Get $key }}
        {{ if eq $m $nowMonth }}
          {{ range $p := $pages }}
          {{ $vid := $p.Resources.GetMatch "*.{mp4,mov}" }}
          {{ $img := $p.Resources.GetMatch "*.{jpg,jpeg,png,gif,webp,svg}" }}
          {{ $heic := $p.Resources.GetMatch "*.{heic,HEIC}" }}
          {{ $folderBase := path.Base $p.File.Dir }}
          {{ $dateKey := $p.Date.Format "2006-01-02" }}
          <li data-date="{{ $dateKey }}" data-folder="{{ $folderBase }}">
            {{ if $vid }}
            <a href="{{ $vid.RelPermalink }}" data-name="{{ or $p.Title $vid.Name }}" class="vid">
              {{ with $p.Title }}{{ . }}{{ else }}{{ $vid.Name }}{{ end }}
            </a>
            <span class="badge">video</span>
            {{ $d := $p.Date.Format "2006-01-02" }}{{ if ne $d "0001-01-01" }}<div class="meta">{{ $d }}</div>{{ end }}
            {{ else if $img }}
            <a href="{{ $img.RelPermalink }}" data-name="{{ or $p.Title $img.Name }}" class="img">
              {{ with $p.Title }}{{ . }}{{ else }}{{ $img.Name }}{{ end }}
            </a>
            <span class="badge">image</span>
            {{ $d := $p.Date.Format "2006-01-02" }}{{ if ne $d "0001-01-01" }}<div class="meta">{{ $d }}</div>{{ end }}
            {{ else if $heic }}
            <a href="{{ $heic.RelPermalink }}" data-name="{{ or $p.Title $heic.Name }}" class="heic">
              {{ with $p.Title }}{{ . }}{{ else }}{{ $heic.Name }}{{ end }}
            </a>
            <span class="badge">heic</span>
            {{ $d := $p.Date.Format "2006-01-02" }}{{ if ne $d "0001-01-01" }}<div class="meta">{{ $d }}</div>{{ end }}
            {{ else }}
            {{ $d := $p.Date.Format "2006-01-02" }}
            <a href="{{ $p.RelPermalink }}">{{ if ne $d "0001-01-01" }}{{ $d }} {{ end }}{{ $p.Title }}</a>
            <span class="badge">note</span>
            {{ end }}
          </li>
          {{ end }}
        {{ else }}
        <li class="folder-section">
          <details>
            <summary class="folder-header">
              <span class="folder-name">{{ $m }}/</span>
              <span class="folder-count">({{ len $pages }} items)</span>
            </summary>
            <ul class="folder-content">
              {{ range $p := $pages }}
              {{ $vid := $p.Resources.GetMatch "*.{mp4,mov}" }}
              {{ $img := $p.Resources.GetMatch "*.{jpg,jpeg,png,gif,webp,svg}" }}
              {{ $heic := $p.Resources.GetMatch "*.{heic,HEIC}" }}
              <li>
                {{ if $vid }}
                <a href="{{ $vid.RelPermalink }}" data-name="{{ or $p.Title $vid.Name }}" class="vid">
                  {{ with $p.Title }}{{ . }}{{ else }}{{ $vid.Name }}{{ end }}
                </a>
                <span class="badge">video</span>
                {{ $d := $p.Date.Format "2006-01-02" }}{{ if ne $d "0001-01-01" }}<div class="meta">{{ $d }}</div>{{ end }}
                {{ else if $img }}
                <a href="{{ $img.RelPermalink }}" data-name="{{ or $p.Title $img.Name }}" class="img">
                  {{ with $p.Title }}{{ . }}{{ else }}{{ $img.Name }}{{ end }}
                </a>
                <span class="badge">image</span>
                {{ $d := $p.Date.Format "2006-01-02" }}{{ if ne $d "0001-01-01" }}<div class="meta">{{ $d }}</div>{{ end }}
                {{ else if $heic }}
                <a href="{{ $heic.RelPermalink }}" data-name="{{ or $p.Title $heic.Name }}" class="heic">
                  {{ with $p.Title }}{{ . }}{{ else }}{{ $heic.Name }}{{ end }}
                </a>
                <span class="badge">heic</span>
                {{ $d := $p.Date.Format "2006-01-02" }}{{ if ne $d "0001-01-01" }}<div class="meta">{{ $d }}</div>{{ end }}
                {{ else }}
                {{ $d := $p.Date.Format "2006-01-02" }}
                <a href="{{ $p.RelPermalink }}">{{ if ne $d "0001-01-01" }}{{ $d }} {{ end }}{{ $p.Title }}</a>
                <span class="badge">note</span>
                {{ end }}
              </li>
              {{ end }}
            </ul>
          </details>
        </li>
        {{ end }}
      {{ end }}

      {{ if and (eq (len $secVids) 0) (eq (len .Pages) 0) }}
      <li>No items yet.</li>
      {{ end }}
    </ul>

    <script>
      document.addEventListener("DOMContentLoaded", () => {
        // 사용자별 제한된 폴더 필터링 (API로 최종 확인)
        const checkUserAccess = async () => {
          const restrictedFolders = document.querySelectorAll('li.folder-section[data-restricted="true"]');
          
          // 이미 allowed 클래스가 있으면 스킵 (head의 스크립트에서 처리됨)
          if (restrictedFolders.length > 0 && restrictedFolders[0].classList.contains('allowed')) {
            return;
          }
          
          // API로 사용자 정보 확인 (nginx에서 헤더 읽기)
          let isSiUser = false;
          try {
            const response = await fetch('/api/whoami.php', {
              credentials: 'include'
            });
            if (response.ok) {
              const data = await response.json();
              isSiUser = data.user === 'si';
            }
          } catch (e) {
            // API 실패 시 쿠키 확인
            const cookies = document.cookie.split(';').reduce((acc, cookie) => {
              const [key, value] = cookie.trim().split('=');
              acc[key] = value;
              return acc;
            }, {});
            isSiUser = cookies.user === 'si' || cookies.authUser === 'si';
          }
          
          if (isSiUser) {
            // si 사용자는 allowed 클래스 추가하여 표시
            restrictedFolders.forEach(folder => {
              folder.classList.add('allowed');
            });
          }
          // si 사용자가 아니면 CSS에서 이미 숨김 처리됨
        };
        checkUserAccess();

        // Decode URL-encoded folder names
        document.querySelectorAll('.folder-name[data-encoded]').forEach(el => {
          const encoded = el.getAttribute('data-encoded');
          try {
            const decoded = decodeURIComponent(encoded);
            if (decoded !== encoded) {
              el.textContent = decoded + '/';
            }
          } catch (e) {
            // Keep original if decoding fails
          }
        });

        // Leak 폴더의 동영상 파일 목록 자동 로드 (에러 발생해도 다른 기능에 영향 없음)
        (function() {
          const loadLeakFiles = async () => {
            try {
              // si 사용자인지 확인
              let isSiUser = false;
              try {
                const cookies = document.cookie.split(';').reduce((acc, cookie) => {
                  const [key, value] = cookie.trim().split('=');
                  acc[key] = value;
                  return acc;
                }, {});
                isSiUser = cookies.user === 'si' || cookies.authUser === 'si';
                
                if (!isSiUser) {
                  const response = await fetch('/api/whoami.php', { credentials: 'include' });
                  if (response.ok) {
                    const data = await response.json();
                    isSiUser = data && data.user === 'si';
                  }
                }
              } catch (e) {
                // whoami 실패해도 무시
                return;
              }
              
              if (!isSiUser) return; // si 사용자가 아니면 Leak 파일 로드 안 함
              
              // Leak 섹션 찾기 (allowed 클래스가 있는 것만)
              const findLeakSection = () => {
                try {
                  return Array.from(document.querySelectorAll('li.folder-section[data-restricted="true"].allowed'))
                    .find(li => {
                      const folderName = li.querySelector('.folder-name');
                      if (!folderName) return false;
                      const name = folderName.textContent.toLowerCase();
                      return name.includes('leak');
                    });
                } catch (e) {
                  return null;
                }
              };
              
              // allowed 클래스가 추가될 때까지 대기
              let leakSection = findLeakSection();
              if (!leakSection) {
                setTimeout(() => {
                  try {
                    leakSection = findLeakSection();
                    if (leakSection) {
                      loadFilesIntoSection(leakSection);
                    }
                  } catch (e) {
                    // 에러 무시
                  }
                }, 500);
                return;
              }
              
              loadFilesIntoSection(leakSection);
              
              async function loadFilesIntoSection(leakSection) {
                try {
                  const folderContent = leakSection.querySelector('.folder-content');
                  if (!folderContent) return;
                  
                  const response = await fetch('/api/leak-files.php', { credentials: 'include' });
                  if (!response.ok) return; // 404 등 에러는 무시
                  
                  const data = await response.json();
                  if (!data || !data.files || !Array.isArray(data.files)) return;
                  
                  const existingFiles = new Set(Array.from(folderContent.querySelectorAll('a')).map(a => a.textContent.trim()));
                  
                  let addedCount = 0;
                  data.files.forEach(file => {
                    if (file && file.name && !existingFiles.has(file.name)) {
                      try {
                        const li = document.createElement('li');
                        const a = document.createElement('a');
                        a.href = file.url || ('/recordings/Leak/' + encodeURIComponent(file.name));
                        a.textContent = file.name;
                        a.className = 'hidden-file';
                        a.setAttribute('data-name', file.name);
                        
                        const badge = document.createElement('span');
                        badge.className = 'badge';
                        badge.textContent = 'video';
                        
                        li.appendChild(a);
                        li.appendChild(badge);
                        folderContent.appendChild(li);
                        addedCount++;
                      } catch (e) {
                        // 개별 파일 추가 실패해도 무시
                      }
                    }
                  });
                  
                  // 폴더 카운트 업데이트
                  if (addedCount > 0) {
                    const countEl = leakSection.querySelector('.folder-count');
                    if (countEl) {
                      const currentCount = parseInt(countEl.textContent.match(/\d+/)?.[0] || '0');
                      countEl.textContent = `(${currentCount + addedCount} items)`;
                    }
                  }
                } catch (e) {
                  // API 에러 무시
                }
              }
            } catch (e) {
              // 모든 에러 무시 (다른 기능에 영향 없음)
            }
          };
          
          // 사용자 확인 후 Leak 파일 로드 (약간 지연)
          setTimeout(() => {
            try {
              loadLeakFiles();
            } catch (e) {
              // 에러 무시
            }
          }, 1000);
        })();

        // 같은 날짜 내에서 폴더명 역순 정렬
        const listEl = document.getElementById('list');
        if (listEl) {
          const items = Array.from(listEl.querySelectorAll('li[data-date][data-folder]'));
          const groupedByDate = {};
          
          items.forEach(item => {
            const date = item.getAttribute('data-date');
            if (!groupedByDate[date]) {
              groupedByDate[date] = [];
            }
            groupedByDate[date].push(item);
          });
          
          // 날짜별로 그룹을 처리하되, 원래 순서를 유지하면서 같은 날짜 내에서만 재정렬
          const dateKeys = Object.keys(groupedByDate).sort().reverse();
          dateKeys.forEach(date => {
            const group = groupedByDate[date];
            // 폴더명 역순 정렬
            group.sort((a, b) => {
              const folderA = a.getAttribute('data-folder') || '';
              const folderB = b.getAttribute('data-folder') || '';
              return folderB.localeCompare(folderA);
            });
            
            // 그룹 내 첫 항목의 다음 형제를 기준점으로 사용
            if (group.length > 1) {
              const firstItem = group[0];
              const parent = firstItem.parentNode;
              const insertBefore = firstItem.nextSibling;
              
              // 모든 항목을 fragment에 추가
              const fragment = document.createDocumentFragment();
              group.forEach(item => {
                if (item.parentNode) {
                  parent.removeChild(item);
                }
                fragment.appendChild(item);
              });
              
              // 정렬된 항목들을 원래 위치에 삽입
              if (insertBefore) {
                parent.insertBefore(fragment, insertBefore);
              } else {
                parent.appendChild(fragment);
              }
            }
          });
        }

        // BGM 토글 버튼 및 자동재생 시도
        const bgm = document.getElementById('bgm');
        const toggle = document.getElementById('bgm-toggle');
        if (bgm && toggle) {
          const tryPlay = () => bgm.play().then(() => { toggle.textContent = 'BGM ❚❚'; }).catch(() => {});
          // 자동재생 시도
          tryPlay();
          // 첫 사용자 클릭 시 재생 시도
          const onFirst = () => { tryPlay(); document.removeEventListener('click', onFirst); };
          document.addEventListener('click', onFirst, { once: true });
          
          toggle.addEventListener('click', (e) => {
            e.preventDefault();
            if (bgm.paused) {
              tryPlay();
            } else {
              bgm.pause();
              bgm.currentTime = 0;
              toggle.textContent = 'BGM ▷';
            }
          });
        }

        const list = document.getElementById("list");
        const wrap = document.getElementById("player");
        const video = document.getElementById("video");
        const image = document.getElementById("image");
        const meta = document.getElementById("meta");
        list.addEventListener("click", (e) => {
          const vid = e.target.closest("a.vid");
          const img = e.target.closest("a.img");
          const hiddenFile = e.target.closest("a.hidden-file");
          if (hiddenFile) return; // hidden 파일은 URL로 이동
          if (!vid && !img) return; // note는 링크로 이동
          e.preventDefault(); // 미디어는 인라인 표시
          wrap.style.display = "";
          meta.textContent = (vid || img).dataset.name || (vid || img).textContent.trim();
          if (vid) {
            image.style.display = "none";
            image.removeAttribute("src");
            video.style.display = "";
            video.src = vid.getAttribute("href");
            video.play().catch(() => {});
          } else if (img) {
            video.pause();
            video.removeAttribute("src");
            video.style.display = "none";
            image.style.display = "";
            image.src = img.getAttribute("href");
          }
          wrap.scrollIntoView({ behavior: "smooth", block: "nearest" });
        });
      });
    </script>
  </body>
</html>