forked from Suwayomi/Suwayomi-WebUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUpdates.tsx
235 lines (211 loc) · 9.27 KB
/
Updates.tsx
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
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import React, {
useContext, useEffect, useState, useRef,
} from 'react';
import { useHistory } from 'react-router-dom';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import IconButton from '@mui/material/IconButton';
import DownloadIcon from '@mui/icons-material/Download';
import Avatar from '@mui/material/Avatar';
import Typography from '@mui/material/Typography';
import NavbarContext from 'components/context/NavbarContext';
import client from 'util/client';
import useLocalStorage from 'util/useLocalStorage';
import EmptyView from 'components/util/EmptyView';
import LoadingPlaceholder from 'components/util/LoadingPlaceholder';
import { Box } from '@mui/system';
function epochToDate(epoch: number) {
const date = new Date(0); // The 0 there is the key, which sets the date to the epoch
date.setUTCSeconds(epoch);
return date;
}
function isTheSameDay(first:Date, second:Date) {
return first.getDate() === second.getDate()
&& first.getMonth() === second.getMonth()
&& first.getFullYear() === second.getFullYear();
}
function getDateString(date: Date) {
const today = new Date();
if (isTheSameDay(today, date)) return 'TODAY';
// calculate yesterday
const yesterday = new Date();
yesterday.setDate(today.getDate() - 1);
if (isTheSameDay(yesterday, date)) return 'YESTERDAY';
return date.toLocaleDateString();
}
function groupByDate(updates: IMangaChapter[]):
[string, { item: IMangaChapter, globalIdx: number }[] ][] {
if (updates.length === 0) return [];
const groups = {};
updates.forEach((item, globalIdx) => {
const key = getDateString(epochToDate(item.chapter.fetchedAt));
// @ts-ignore
if (groups[key] === undefined) groups[key] = [];
// @ts-ignore
groups[key].push({ item, globalIdx });
});
// @ts-ignore
return Object.keys(groups).map((key) => [key, groups[key]]);
}
const baseWebsocketUrl = JSON.parse(window.localStorage.getItem('serverBaseURL')!).replace('http', 'ws');
const initialQueue = {
status: 'Stopped',
queue: [],
} as IQueue;
export default function Updates() {
const history = useHistory();
const { setTitle, setAction } = useContext(NavbarContext);
const [updateEntries, setUpdateEntries] = useState<IMangaChapter[]>([]);
const [hasNextPage, setHasNextPage] = useState(true);
const [fetched, setFetched] = useState(false);
const [lastPageNum, setLastPageNum] = useState(0);
const [serverAddress] = useLocalStorage<String>('serverBaseURL', '');
const [useCache] = useLocalStorage<boolean>('useCache', true);
const [, setWsClient] = useState<WebSocket>();
const [{ queue }, setQueueState] = useState<IQueue>(initialQueue);
useEffect(() => {
const wsc = new WebSocket(`${baseWebsocketUrl}/api/v1/downloads`);
wsc.onmessage = (e) => {
const data = JSON.parse(e.data) as IQueue;
setQueueState(data);
};
setWsClient(wsc);
return () => wsc.close();
}, []);
useEffect(() => {
setTitle('Updates');
setAction(<></>);
}, []);
useEffect(() => {
if (hasNextPage) {
client.get(`/api/v1/update/recentChapters/${lastPageNum}`)
.then((response) => response.data)
.then(({ hasNextPage: fetchedHasNextPage, page }: PaginatedList<IMangaChapter>) => {
setUpdateEntries([
...updateEntries,
...page,
]);
setHasNextPage(fetchedHasNextPage);
setFetched(true);
});
}
}, [lastPageNum]);
const lastEntry = useRef<HTMLDivElement>(null);
const scrollHandler = () => {
if (lastEntry.current) {
const rect = lastEntry.current.getBoundingClientRect();
if (((rect.y + rect.height) / window.innerHeight < 2) && hasNextPage) {
setLastPageNum(lastPageNum + 1);
}
}
};
useEffect(() => {
window.addEventListener('scroll', scrollHandler, true);
return () => {
window.removeEventListener('scroll', scrollHandler, true);
};
}, [hasNextPage, updateEntries]);
if (!fetched) { return <LoadingPlaceholder />; }
if (fetched && updateEntries.length === 0) { return <EmptyView message="You don't have any updates yet." />; }
const downloadStatusStringFor = (chapter: IChapter) => {
let rtn = '';
if (chapter.downloaded) {
rtn = ' • Downloaded';
}
queue.forEach((q) => {
if (chapter.index === q.chapterIndex && chapter.mangaId === q.mangaId) {
rtn = ` • Downloading (${(q.progress * 100).toFixed(2)}%)`;
}
});
return rtn;
};
const downloadChapter = (chapter: IChapter) => {
client.get(`/api/v1/download/${chapter.mangaId}/chapter/${chapter.index}`);
};
return (
<>
{groupByDate(updateEntries).map((dateGroup) => (
<div key={dateGroup[0]}>
<Typography
variant="h5"
sx={{
ml: 3,
my: 2,
fontWeight: 700,
}}
>
{dateGroup[0]}
</Typography>
{dateGroup[1].map(({ item: { chapter, manga }, globalIdx }) => (
<Card
ref={globalIdx === updateEntries.length - 1 ? lastEntry : undefined}
key={globalIdx}
sx={{
margin: '10px',
'&:hover': {
backgroundColor: 'action.hover',
transition: 'background-color 100ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
},
'&:active': {
backgroundColor: 'action.selected',
transition: 'background-color 100ms cubic-bezier(0.4, 0, 0.2, 1) 0ms',
},
}}
onClick={() => history.push({ pathname: `/manga/${chapter.mangaId}/chapter/${chapter.index}`, state: history.location.state })}
>
<CardContent sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: 2,
}}
>
<Box sx={{ display: 'flex' }}>
<Avatar
variant="rounded"
sx={{
width: 56,
height: 56,
flex: '0 0 auto',
marginRight: 2,
imageRendering: 'pixelated',
}}
src={`${serverAddress}${manga.thumbnailUrl}?useCache=${useCache}`}
/>
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
<Typography variant="h5" component="h2">
{manga.title}
</Typography>
<Typography variant="caption" display="block" gutterBottom>
{chapter.name}
{downloadStatusStringFor(chapter)}
</Typography>
</Box>
</Box>
{downloadStatusStringFor(chapter) === ''
&& (
<IconButton
onClick={(e) => {
downloadChapter(chapter);
// prevent parent tags from getting the event
e.stopPropagation();
}}
size="large"
>
<DownloadIcon />
</IconButton>
)}
</CardContent>
</Card>
))}
</div>
))}
</>
);
}