File size: 11,247 Bytes
4e1096a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useEnv } from '@/context/EnvContext';
import { useSettingsStore } from '@/store/settingsStore';
import { useReaderStore } from '@/store/readerStore';
import { useBookDataStore } from '@/store/bookDataStore';
import { useTranslation } from '@/hooks/useTranslation';
import { KOSyncClient, KoSyncProgress } from '@/services/sync/KOSyncClient';
import { Book, BookProgress, FIXED_LAYOUT_FORMATS } from '@/types/book';
import { BookDoc } from '@/libs/document';
import { debounce } from '@/utils/debounce';
import { eventDispatcher } from '@/utils/event';
import { getCFIFromXPointer, normalizeProgressXPointer, XCFI } from '@/utils/xcfi';

type SyncState = 'idle' | 'checking' | 'conflict' | 'synced' | 'error';

export interface SyncDetails {
  book: Book;
  bookDoc: BookDoc;
  local: {
    cfi?: string;
    preview: string;
  };
  remote: KoSyncProgress & {
    preview: string;
    percentage?: number;
  };
}

export const useKOSync = (bookKey: string) => {
  const _ = useTranslation();
  const { appService } = useEnv();
  const { settings } = useSettingsStore();
  const { getProgress, getView } = useReaderStore();
  const { getBookData } = useBookDataStore();

  const [kosyncClient, setKOSyncClient] = useState<KOSyncClient | null>(null);
  const [syncState, setSyncState] = useState<SyncState>('idle');
  const [conflictDetails, setConflictDetails] = useState<SyncDetails | null>(null);
  const [errorMessage] = useState<string | null>(null);
  const hasPulledOnce = useRef(false);

  const progress = getProgress(bookKey);

  useEffect(() => {
    if (!settings.kosync.username || !settings.kosync.userkey) {
      setKOSyncClient(null);
      return;
    }
    const client = new KOSyncClient(settings.kosync);
    setKOSyncClient(client);
  }, [settings]);

  const generateKOProgress = useCallback(() => {
    const progress = getProgress(bookKey);
    const book = getBookData(bookKey)?.book;
    if (!progress || !book) return null;

    let koProgress = '';
    let percentage: number;
    if (FIXED_LAYOUT_FORMATS.has(book.format)) {
      const page = progress.section?.current ?? 0;
      const totalPages = progress.section?.total ?? 0;
      koProgress = page.toString();
      percentage = totalPages > 0 ? (page + 1) / totalPages : 0;
    } else {
      const view = getView(bookKey);
      const cfi = progress.location;
      if (!view || !cfi) return null;
      try {
        const content = view.renderer.getContents()[0];
        if (content) {
          const { doc, index: spineIndex } = content;
          const converter = new XCFI(doc, spineIndex || 0);
          const xpointerResult = converter.cfiToXPointer(cfi);
          koProgress = normalizeProgressXPointer(xpointerResult.xpointer);
        }
      } catch (error) {
        console.error('Failed to convert CFI to XPointer', error);
      }

      const page = progress.pageinfo?.current ?? 0;
      const totalPages = progress.pageinfo?.total ?? 0;
      percentage = totalPages > 0 ? (page + 1) / totalPages : 0;
    }

    return { koProgress, percentage };
  }, [bookKey, getProgress, getBookData, getView]);

  const applyRemoteProgress = async (book: Book, bookDoc: BookDoc, remote: KoSyncProgress) => {
    const view = getView(bookKey);
    if (FIXED_LAYOUT_FORMATS.has(book.format)) {
      const pageToGo = parseInt(remote.progress!, 10);
      if (isNaN(pageToGo)) return;
      view?.select(pageToGo - 1);
    } else {
      if (!remote.progress?.startsWith('/body')) return;
      try {
        const content = view?.renderer.getContents()[0];
        const koProgress = normalizeProgressXPointer(remote.progress);
        const cfi = await getCFIFromXPointer(koProgress, content?.doc, content?.index, bookDoc);
        view?.goTo(cfi);
      } catch (error) {
        console.error('Failed to convert XPointer to CFI', error);
        return;
      }
    }
    eventDispatcher.dispatch('toast', { message: _('Reading Progress Synced'), type: 'info' });
  };

  const promptedSync = async (
    book: Book,
    bookDoc: BookDoc,
    local: BookProgress,
    remote: KoSyncProgress,
  ) => {
    let localPreview = '';
    let remotePreview = '';
    const remotePercentage = remote.percentage || 0;
    const conflictProgressDiffThreshold = 0.0001;
    let showConflictDetails = false;

    if (FIXED_LAYOUT_FORMATS.has(book.format)) {
      const localPageInfo = local.section;
      const localPercentage =
        localPageInfo && localPageInfo.total > 0
          ? (localPageInfo.current + 1) / localPageInfo.total
          : 0;
      localPreview = localPageInfo
        ? _('Page {{page}} of {{total}} ({{percentage}}%)', {
            page: localPageInfo.current + 1,
            total: localPageInfo.total,
            percentage: Math.round(localPercentage * 100),
          })
        : _('Current position');

      const remotePage = parseInt(remote.progress!, 10);
      if (!isNaN(remotePage) && remotePercentage > 0) {
        const localTotalPages = localPageInfo?.total ?? 0;
        const remoteTotalPages = Math.round(remotePage / remotePercentage);
        const pagesMatch = Math.abs(localTotalPages - remoteTotalPages) <= 1;

        if (pagesMatch) {
          remotePreview = _('Page {{page}} of {{total}} ({{percentage}}%)', {
            page: remotePage,
            total: remoteTotalPages,
            percentage: Math.round(remotePercentage * 100),
          });
        } else {
          remotePreview = _('Approximately page {{page}} of {{total}} ({{percentage}}%)', {
            page: remotePage,
            total: remoteTotalPages,
            percentage: Math.round(remotePercentage * 100),
          });
        }
        showConflictDetails =
          Math.abs(localPercentage - remotePercentage) > conflictProgressDiffThreshold;
      } else {
        remotePreview = _('Approximately {{percentage}}%', {
          percentage: Math.round(remotePercentage * 100),
        });
      }
    } else {
      const localPageInfo = local.pageinfo;
      const localPercentage =
        localPageInfo && localPageInfo.total > 0
          ? (localPageInfo.current + 1) / localPageInfo.total
          : 0;
      localPreview = `${local.sectionLabel} (${Math.round(localPercentage * 100)}%)`;

      remotePreview = _('Approximately {{percentage}}%', {
        percentage: Math.round(remotePercentage * 100),
      });
      showConflictDetails =
        Math.abs(localPercentage - remotePercentage) > conflictProgressDiffThreshold;
    }

    if (showConflictDetails) {
      setConflictDetails({
        book,
        bookDoc,
        local: { cfi: local.location, preview: localPreview },
        remote: { ...remote, preview: remotePreview },
      });
    }
  };

  const pushProgress = useMemo(
    () =>
      debounce(async () => {
        if (!bookKey || !appService || !kosyncClient || !hasPulledOnce.current) return;
        const { settings } = useSettingsStore.getState();
        if (['receive', 'disable'].includes(settings.kosync.strategy)) return;

        const currentBook = getBookData(bookKey)?.book;
        const progress = generateKOProgress();
        if (!currentBook || !progress || !progress.koProgress) return;

        await kosyncClient.updateProgress(currentBook, progress.koProgress, progress.percentage);
      }, 5000),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [bookKey, appService, kosyncClient],
  );

  const pullProgress = useCallback(
    async () => {
      if (!progress?.location || !appService || !kosyncClient) return;

      const bookData = getBookData(bookKey);
      const book = bookData?.book;
      const bookDoc = bookData?.bookDoc;
      if (!book || !bookDoc) return;

      const { strategy, enabled } = settings.kosync;
      if (!enabled) return;

      hasPulledOnce.current = true;
      if (strategy === 'send') {
        setSyncState('synced');
        return;
      }

      setSyncState('checking');
      const remoteProgress = await kosyncClient.getProgress(book);
      if (!remoteProgress || !remoteProgress.progress) {
        setSyncState('synced');
        return;
      }

      const localTimestamp = bookData?.config?.updatedAt || book.updatedAt;
      const remoteTimestamp = remoteProgress.timestamp
        ? remoteProgress.timestamp * 1000
        : Date.now();
      const remoteIsNewer = remoteTimestamp > localTimestamp;
      if (strategy === 'receive' || (strategy === 'silent' && remoteIsNewer)) {
        applyRemoteProgress(book, bookDoc, remoteProgress);
        setSyncState('synced');
      } else if (strategy === 'prompt') {
        promptedSync(book, bookDoc, progress, remoteProgress);
        setSyncState('conflict');
      } else {
        setSyncState('synced');
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [bookKey, appService, kosyncClient, settings.kosync, progress],
  );

  useEffect(() => {
    const handlePushProgress = (event: CustomEvent) => {
      if (event.detail.bookKey !== bookKey) return;
      pushProgress();
      pushProgress.flush();
    };
    const handleFlush = (event: CustomEvent) => {
      if (event.detail.bookKey !== bookKey) return;
      pushProgress.flush();
    };
    eventDispatcher.on('push-kosync', handlePushProgress);
    eventDispatcher.on('flush-kosync', handleFlush);
    return () => {
      eventDispatcher.off('push-kosync', handlePushProgress);
      eventDispatcher.off('flush-kosync', handleFlush);
      pushProgress.flush();
    };
  }, [bookKey, pushProgress]);

  useEffect(() => {
    const handlePullProgress = (event: CustomEvent) => {
      if (event.detail.bookKey !== bookKey) return;
      pullProgress();
    };
    eventDispatcher.on('pull-kosync', handlePullProgress);
    return () => {
      eventDispatcher.off('pull-kosync', handlePullProgress);
    };
  }, [bookKey, pullProgress]);

  // Pull: pull progress once when the book is opened
  useEffect(() => {
    if (!appService || !kosyncClient || !progress?.location) return;
    if (hasPulledOnce.current) return;

    pullProgress();
  }, [appService, kosyncClient, progress?.location, pushProgress, pullProgress]);

  // Push: auto-push progress when progress changes with a debounce
  useEffect(() => {
    if (syncState === 'synced' && progress) {
      const { strategy, enabled } = settings.kosync;
      if (strategy !== 'receive' && enabled) {
        pushProgress();
      }
    }
  }, [progress, syncState, settings.kosync, pushProgress]);

  const resolveWithLocal = () => {
    pushProgress();
    pushProgress.flush();
    setSyncState('synced');
    setConflictDetails(null);
  };

  const resolveWithRemote = async () => {
    const view = getView(bookKey);
    const remote = conflictDetails?.remote;
    const book = conflictDetails?.book;
    const bookDoc = conflictDetails?.bookDoc;

    if (!book || !bookDoc || !remote || !remote.progress || !view) return;

    applyRemoteProgress(book, bookDoc, remote);
    setSyncState('synced');
    setConflictDetails(null);
  };

  return {
    syncState,
    conflictDetails,
    errorMessage,
    pushProgress,
    pullProgress,
    resolveWithLocal,
    resolveWithRemote,
  };
};