dongsik22 Claude Opus 4.7 (1M context) commited on
Commit
2bf344b
·
1 Parent(s): 6f8fa15

feat: 현재 시청 시리즈 정렬 최상단 + 디바이스 간 활성 동기화

Browse files

증상 ① 카드 클릭만 해선 clickedAt 갱신/서버 PUT 없어 정렬에 반영 안 됨.
selectFav에 clickedAt + saveFavs 추가 (silent 부팅 자동선택은 제외).

증상 ② HF·로컬 등 디바이스 간 lastFavId 동기화는 부팅 시에만 일어남.
syncFavsFromOtherDevices 추가 — 15분 폴링/visibility 복귀 시 pullFavs +
lastFavId 변경 시 활성 시리즈 자동 따라감 (단 현재 시청 중이면 안 따라감).

충돌 방지: _pendingPut 플래그로 디바운스 큐 대기 중인 PUT이 있으면
pull 보류 — 내 로컬 변경이 서버 응답으로 덮어쓰여지지 않게.

정렬: 모든 정렬 모드(기본/recent/added/title)에서 activeId 시리즈를
무조건 최상단 고정.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

Files changed (1) hide show
  1. index.html +38 -4
index.html CHANGED
@@ -950,16 +950,18 @@ function save(k, v) { localStorage.setItem(k, JSON.stringify(v)); }
950
 
951
  // 서버 동기화: saveFavs는 항상 로컬+서버 양쪽에. 빈번한 PUT 방지를 위해 디바운스.
952
  let _saveTimer = null;
 
953
  function saveFavs() {
954
  save(LS_FAV(), favs);
955
  // 디바운스 1초
956
  clearTimeout(_saveTimer);
 
957
  _saveTimer = setTimeout(() => {
958
  fetch('/api/favs?profile=' + currentProfile, {
959
  method: 'PUT',
960
  headers: { 'Content-Type': 'application/json' },
961
  body: JSON.stringify({ favs, lastFavId }),
962
- }).catch(() => {});
963
  }, 1000);
964
  }
965
 
@@ -1061,6 +1063,8 @@ function renderProfileTabs() {
1061
  }
1062
 
1063
  async function pullFavsFromServer() {
 
 
1064
  try {
1065
  const r = await fetch('/api/favs?profile=' + currentProfile, { cache: 'no-store' });
1066
  if (!r.ok) return;
@@ -1222,6 +1226,14 @@ function renderFavs() {
1222
  return (a.title || '').localeCompare(b.title || '', 'ko');
1223
  });
1224
  }
 
 
 
 
 
 
 
 
1225
  for (const [host, filter] of [[$('#favListMob'), filterMob], [$('#favListDt'), filterDt]]) {
1226
  if (!host) continue;
1227
  host.innerHTML = '';
@@ -1368,6 +1380,14 @@ async function selectFav(id, opts = {}) {
1368
  currentFavId = id;
1369
  lastFavId = String(id);
1370
  localStorage.setItem(LS_LAST(), lastFavId);
 
 
 
 
 
 
 
 
1371
  renderFavs();
1372
 
1373
  await loadEpisodes(f);
@@ -2406,11 +2426,24 @@ async function refreshLatestLabels() {
2406
  }
2407
  }
2408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2409
  // 15분마다 주기 폴링 — 페이지가 visible일 때만 (hidden 탭에선 불필요한 호출 절약)
2410
  setInterval(() => {
2411
- if (document.visibilityState === 'visible') {
2412
- refreshLatestLabels().catch(() => {});
2413
- }
2414
  }, LATEST_LABELS_POLL_INTERVAL);
2415
 
2416
  // 탭 전환·앱 백그라운드 복귀 시 즉시 검사 (단 마지막 호출 후 5분 이상 지났을 때만)
@@ -2418,6 +2451,7 @@ document.addEventListener('visibilitychange', () => {
2418
  if (document.visibilityState !== 'visible') return;
2419
  if (Date.now() - _lastLatestLabelsAt < LATEST_LABELS_MIN_INTERVAL) return;
2420
  refreshLatestLabels().catch(() => {});
 
2421
  });
2422
 
2423
  // E-4: ↻ 클릭 — 알림 점이 있으면 첫 NEW 카드로 스크롤. 없으면 새 회차 확인.
 
950
 
951
  // 서버 동기화: saveFavs는 항상 로컬+서버 양쪽에. 빈번한 PUT 방지를 위해 디바운스.
952
  let _saveTimer = null;
953
+ let _pendingPut = false; // 디바운스 큐에 들어가 아직 서버로 안 간 변경 있음을 표시 (pull과 충돌 방지)
954
  function saveFavs() {
955
  save(LS_FAV(), favs);
956
  // 디바운스 1초
957
  clearTimeout(_saveTimer);
958
+ _pendingPut = true;
959
  _saveTimer = setTimeout(() => {
960
  fetch('/api/favs?profile=' + currentProfile, {
961
  method: 'PUT',
962
  headers: { 'Content-Type': 'application/json' },
963
  body: JSON.stringify({ favs, lastFavId }),
964
+ }).catch(() => {}).finally(() => { _pendingPut = false; });
965
  }, 1000);
966
  }
967
 
 
1063
  }
1064
 
1065
  async function pullFavsFromServer() {
1066
+ // 디바운스 큐에 push 대기 중이면 pull 보류 — 내 로컬 변경이 덮어쓰여지지 않게
1067
+ if (_pendingPut) return;
1068
  try {
1069
  const r = await fetch('/api/favs?profile=' + currentProfile, { cache: 'no-store' });
1070
  if (!r.ok) return;
 
1226
  return (a.title || '').localeCompare(b.title || '', 'ko');
1227
  });
1228
  }
1229
+ // 활성(현재 시청 중) 시리즈는 모든 정렬 모드에서 무조건 맨 위
1230
+ if (activeId != null) {
1231
+ const activeIdx = sorted.findIndex(f => f.id == activeId);
1232
+ if (activeIdx > 0) {
1233
+ const [active] = sorted.splice(activeIdx, 1);
1234
+ sorted.unshift(active);
1235
+ }
1236
+ }
1237
  for (const [host, filter] of [[$('#favListMob'), filterMob], [$('#favListDt'), filterDt]]) {
1238
  if (!host) continue;
1239
  host.innerHTML = '';
 
1380
  currentFavId = id;
1381
  lastFavId = String(id);
1382
  localStorage.setItem(LS_LAST(), lastFavId);
1383
+ // 카드 클릭(=현재 보고 있는 시리즈)을 모든 디바이스에 즉시 알림.
1384
+ // - clickedAt 갱신: 정렬에서 "최근 본 것" 위로 올라옴
1385
+ // - saveFavs: 디바운스 큐에 들어가 1초 뒤 서버 PUT (lastFavId 포함) → 다른 디바이스가 다음 pull/부팅 때 동기화
1386
+ // silent 모드(부팅 시 자동 선택)에선 갱신하지 않음 — 실제 사용자 액션만 기록
1387
+ if (!opts.silent) {
1388
+ f.clickedAt = Date.now();
1389
+ saveFavs();
1390
+ }
1391
  renderFavs();
1392
 
1393
  await loadEpisodes(f);
 
2426
  }
2427
  }
2428
 
2429
+ // 다른 디바이스의 변경(clickedAt, lastFavId 등)을 받아 정렬·활성표시 동기화.
2430
+ // pull 후 lastFavId가 바뀌었으면 활성 시리즈로 자동 선택(시청 화면은 유지하지 않고 목록 강조만).
2431
+ async function syncFavsFromOtherDevices() {
2432
+ const prevLast = lastFavId;
2433
+ await pullFavsFromServer();
2434
+ renderFavs();
2435
+ // 다른 디바이스가 활성 시리즈를 바꿨을 때 — 현재 시청 중인 시리즈가 따로 없을 때만 자동 따라감
2436
+ // (이미 다른 걸 보고 있는데 강제로 화면 갈아치우는 것 방지)
2437
+ if (lastFavId && lastFavId !== prevLast && !currentFavId && favs.find(f => f.id == lastFavId)) {
2438
+ selectFav(+lastFavId, { silent: true }).catch(() => {});
2439
+ }
2440
+ }
2441
+
2442
  // 15분마다 주기 폴링 — 페이지가 visible일 때만 (hidden 탭에선 불필요한 호출 절약)
2443
  setInterval(() => {
2444
+ if (document.visibilityState !== 'visible') return;
2445
+ refreshLatestLabels().catch(() => {});
2446
+ syncFavsFromOtherDevices().catch(() => {});
2447
  }, LATEST_LABELS_POLL_INTERVAL);
2448
 
2449
  // 탭 전환·앱 백그라운드 복귀 시 즉시 검사 (단 마지막 호출 후 5분 이상 지났을 때만)
 
2451
  if (document.visibilityState !== 'visible') return;
2452
  if (Date.now() - _lastLatestLabelsAt < LATEST_LABELS_MIN_INTERVAL) return;
2453
  refreshLatestLabels().catch(() => {});
2454
+ syncFavsFromOtherDevices().catch(() => {});
2455
  });
2456
 
2457
  // E-4: ↻ 클릭 — 알림 점이 있으면 첫 NEW 카드로 스크롤. 없으면 새 회차 확인.