-
-
Notifications
You must be signed in to change notification settings - Fork 512
Expand file tree
/
Copy pathsource.ts
More file actions
537 lines (501 loc) · 15.1 KB
/
source.ts
File metadata and controls
537 lines (501 loc) · 15.1 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
import intl from "react-intl-universal"
import * as db from "../db"
import lf from "lovefield"
import {
fetchFavicon,
ActionStatus,
AppThunk,
parseRSS,
MyParserItem,
} from "../utils"
import {
RSSItem,
insertItems,
ItemActionTypes,
FETCH_ITEMS,
MARK_READ,
MARK_UNREAD,
MARK_ALL_READ,
} from "./item"
import { saveSettings } from "./app"
import { SourceRule } from "./rule"
import { fixBrokenGroups } from "./group"
export const enum SourceOpenTarget {
Local,
Webpage,
External,
FullContent,
}
export const enum SourceTextDirection {
LTR,
RTL,
Vertical,
}
export class RSSSource {
sid: number
url: string
originUrl?: string
iconurl?: string
name: string
openTarget: SourceOpenTarget
unreadCount: number
lastFetched: Date
serviceRef?: string
fetchFrequency: number // in minutes
rules?: SourceRule[]
textDir: SourceTextDirection
hidden: boolean
constructor(url: string, name: string = null) {
this.url = url
this.name = name
this.openTarget = SourceOpenTarget.Local
this.lastFetched = new Date()
this.fetchFrequency = 0
this.textDir = SourceTextDirection.LTR
this.hidden = false
}
static async fetchMetaData(source: RSSSource) {
let feed = await parseRSS(source.url)
source.originUrl = feed.link
if (!source.name) {
if (feed.title) source.name = feed.title.trim()
source.name = source.name || intl.get("sources.untitled")
}
return feed
}
private static async checkItem(
source: RSSSource,
item: MyParserItem
): Promise<RSSItem> {
let i = new RSSItem(item, source)
const items = (await db.itemsDB
.select()
.from(db.items)
.where(
lf.op.and(
db.items.source.eq(i.source),
db.items.title.eq(i.title),
db.items.date.eq(i.date)
)
)
.limit(1)
.exec()) as RSSItem[]
if (items.length === 0) {
RSSItem.parseContent(i, item)
if (source.rules) SourceRule.applyAll(source.rules, i)
return i
} else {
return null
}
}
static checkItems(
source: RSSSource,
items: MyParserItem[]
): Promise<RSSItem[]> {
return new Promise<RSSItem[]>((resolve, reject) => {
let p = new Array<Promise<RSSItem>>()
for (let item of items) {
p.push(this.checkItem(source, item))
}
Promise.all(p)
.then(values => {
resolve(values.filter(v => v != null))
})
.catch(e => {
reject(e)
})
})
}
static async fetchItems(source: RSSSource) {
let feed = await parseRSS(source.url)
return await this.checkItems(source, feed.items)
}
}
export type SourceState = {
[sid: number]: RSSSource
}
export const INIT_SOURCES = "INIT_SOURCES"
export const ADD_SOURCE = "ADD_SOURCE"
export const UPDATE_SOURCE = "UPDATE_SOURCE"
export const UPDATE_UNREAD_COUNTS = "UPDATE_UNREAD_COUNTS"
export const DELETE_SOURCE = "DELETE_SOURCE"
export const HIDE_SOURCE = "HIDE_SOURCE"
export const UNHIDE_SOURCE = "UNHIDE_SOURCE"
interface InitSourcesAction {
type: typeof INIT_SOURCES
status: ActionStatus
sources?: SourceState
err?
}
interface AddSourceAction {
type: typeof ADD_SOURCE
status: ActionStatus
batch: boolean
source?: RSSSource
err?
}
interface UpdateSourceAction {
type: typeof UPDATE_SOURCE
source: RSSSource
}
interface UpdateUnreadCountsAction {
type: typeof UPDATE_UNREAD_COUNTS
sources: SourceState
}
interface DeleteSourceAction {
type: typeof DELETE_SOURCE
source: RSSSource
}
interface ToggleSourceHiddenAction {
type: typeof HIDE_SOURCE | typeof UNHIDE_SOURCE
status: ActionStatus
source: RSSSource
}
export type SourceActionTypes =
| InitSourcesAction
| AddSourceAction
| UpdateSourceAction
| UpdateUnreadCountsAction
| DeleteSourceAction
| ToggleSourceHiddenAction
export function initSourcesRequest(): SourceActionTypes {
return {
type: INIT_SOURCES,
status: ActionStatus.Request,
}
}
export function initSourcesSuccess(sources: SourceState): SourceActionTypes {
return {
type: INIT_SOURCES,
status: ActionStatus.Success,
sources: sources,
}
}
export function initSourcesFailure(err): SourceActionTypes {
return {
type: INIT_SOURCES,
status: ActionStatus.Failure,
err: err,
}
}
async function unreadCount(sources: SourceState): Promise<SourceState> {
const rows = await db.itemsDB
.select(db.items.source, lf.fn.count(db.items._id))
.from(db.items)
.where(db.items.hasRead.eq(false))
.groupBy(db.items.source)
.exec()
for (let row of rows) {
sources[row["source"]].unreadCount = row["COUNT(_id)"]
}
return sources
}
export function updateUnreadCounts(): AppThunk<Promise<void>> {
return async (dispatch, getState) => {
const sources: SourceState = {}
for (let source of Object.values(getState().sources)) {
sources[source.sid] = {
...source,
unreadCount: 0,
}
}
dispatch({
type: UPDATE_UNREAD_COUNTS,
sources: await unreadCount(sources),
})
}
}
export function initSources(): AppThunk<Promise<void>> {
return async dispatch => {
dispatch(initSourcesRequest())
await db.init()
const sources = (await db.sourcesDB
.select()
.from(db.sources)
.exec()) as RSSSource[]
const state: SourceState = {}
for (let source of sources) {
source.unreadCount = 0
state[source.sid] = source
}
await unreadCount(state)
dispatch(fixBrokenGroups(state))
dispatch(initSourcesSuccess(state))
}
}
export function addSourceRequest(batch: boolean): SourceActionTypes {
return {
type: ADD_SOURCE,
batch: batch,
status: ActionStatus.Request,
}
}
export function addSourceSuccess(
source: RSSSource,
batch: boolean
): SourceActionTypes {
return {
type: ADD_SOURCE,
batch: batch,
status: ActionStatus.Success,
source: source,
}
}
export function addSourceFailure(err, batch: boolean): SourceActionTypes {
return {
type: ADD_SOURCE,
batch: batch,
status: ActionStatus.Failure,
err: err,
}
}
let insertPromises = Promise.resolve()
export function insertSource(source: RSSSource): AppThunk<Promise<RSSSource>> {
return (_, getState) => {
return new Promise((resolve, reject) => {
insertPromises = insertPromises.then(async () => {
let sids = Object.values(getState().sources).map(s => s.sid)
source.sid = Math.max(...sids, -1) + 1
const row = db.sources.createRow(source)
try {
const inserted = (await db.sourcesDB
.insert()
.into(db.sources)
.values([row])
.exec()) as RSSSource[]
resolve(inserted[0])
} catch (err) {
if (err.code === 201) reject(intl.get("sources.exist"))
else reject(err)
}
})
})
}
}
export function addSource(
url: string,
name: string = null,
batch = false
): AppThunk<Promise<number>> {
return async (dispatch, getState) => {
const app = getState().app
if (app.sourceInit) {
dispatch(addSourceRequest(batch))
const source = new RSSSource(url, name)
try {
const feed = await RSSSource.fetchMetaData(source)
const inserted = await dispatch(insertSource(source))
inserted.unreadCount = feed.items.length
dispatch(addSourceSuccess(inserted, batch))
window.settings.saveGroups(getState().groups)
dispatch(updateFavicon([inserted.sid]))
const items = await RSSSource.checkItems(inserted, feed.items)
await insertItems(items)
return inserted.sid
} catch (e) {
dispatch(addSourceFailure(e, batch))
if (!batch) {
window.utils.showErrorBox(
intl.get("sources.errorAdd"),
String(e),
intl.get("context.copy")
)
}
throw e
}
}
throw new Error("Sources not initialized.")
}
}
export function updateSourceDone(source: RSSSource): SourceActionTypes {
return {
type: UPDATE_SOURCE,
source: source,
}
}
export function updateSource(source: RSSSource): AppThunk<Promise<void>> {
return async dispatch => {
let sourceCopy = { ...source }
delete sourceCopy.unreadCount
const row = db.sources.createRow(sourceCopy)
await db.sourcesDB
.insertOrReplace()
.into(db.sources)
.values([row])
.exec()
dispatch(updateSourceDone(source))
}
}
export function deleteSourceDone(source: RSSSource): SourceActionTypes {
return {
type: DELETE_SOURCE,
source: source,
}
}
export function deleteSource(
source: RSSSource,
batch = false
): AppThunk<Promise<void>> {
return async (dispatch, getState) => {
if (!batch) dispatch(saveSettings())
try {
await db.itemsDB
.delete()
.from(db.items)
.where(db.items.source.eq(source.sid))
.exec()
await db.sourcesDB
.delete()
.from(db.sources)
.where(db.sources.sid.eq(source.sid))
.exec()
dispatch(deleteSourceDone(source))
window.settings.saveGroups(getState().groups)
} catch (err) {
console.log(err)
} finally {
if (!batch) dispatch(saveSettings())
}
}
}
export function deleteSources(sources: RSSSource[]): AppThunk<Promise<void>> {
return async dispatch => {
dispatch(saveSettings())
for (let source of sources) {
await dispatch(deleteSource(source, true))
}
dispatch(saveSettings())
}
}
export function toggleSourceHidden(source: RSSSource): AppThunk<Promise<void>> {
return async (dispatch, getState) => {
const sourceCopy: RSSSource = { ...getState().sources[source.sid] }
sourceCopy.hidden = !sourceCopy.hidden
dispatch({
type: sourceCopy.hidden ? HIDE_SOURCE : UNHIDE_SOURCE,
status: ActionStatus.Success,
source: sourceCopy,
})
await dispatch(updateSource(sourceCopy))
}
}
export function updateFavicon(
sids?: number[],
force = false
): AppThunk<Promise<void>> {
return async (dispatch, getState) => {
const initSources = getState().sources
if (!sids) {
sids = Object.values(initSources)
.filter(s => s.iconurl === undefined)
.map(s => s.sid)
} else {
sids = sids.filter(sid => sid in initSources)
}
const promises = sids.map(async sid => {
const { originUrl, url }= initSources[sid]
let favicon = (await fetchFavicon(originUrl || url)) || ""
const source = getState().sources[sid]
if (
source &&
source.url === url &&
(force || source.iconurl === undefined)
) {
source.iconurl = favicon
await dispatch(updateSource(source))
}
})
await Promise.all(promises)
}
}
export function sourceReducer(
state: SourceState = {},
action: SourceActionTypes | ItemActionTypes
): SourceState {
switch (action.type) {
case INIT_SOURCES:
switch (action.status) {
case ActionStatus.Success:
return action.sources
default:
return state
}
case UPDATE_UNREAD_COUNTS:
return action.sources
case ADD_SOURCE:
switch (action.status) {
case ActionStatus.Success:
return {
...state,
[action.source.sid]: action.source,
}
default:
return state
}
case UPDATE_SOURCE:
return {
...state,
[action.source.sid]: action.source,
}
case DELETE_SOURCE: {
delete state[action.source.sid]
return { ...state }
}
case FETCH_ITEMS: {
switch (action.status) {
case ActionStatus.Success: {
let updateMap = new Map<number, number>()
for (let item of action.items) {
if (!item.hasRead) {
updateMap.set(
item.source,
updateMap.has(item.source)
? updateMap.get(item.source) + 1
: 1
)
}
}
let nextState = {} as SourceState
for (let [s, source] of Object.entries(state)) {
let sid = parseInt(s)
if (updateMap.has(sid)) {
nextState[sid] = {
...source,
unreadCount:
source.unreadCount + updateMap.get(sid),
} as RSSSource
} else {
nextState[sid] = source
}
}
return nextState
}
default:
return state
}
}
case MARK_UNREAD:
case MARK_READ:
return {
...state,
[action.item.source]: {
...state[action.item.source],
unreadCount:
state[action.item.source].unreadCount +
(action.type === MARK_UNREAD ? 1 : -1),
} as RSSSource,
}
case MARK_ALL_READ: {
let nextState = { ...state }
action.sids.forEach(sid => {
nextState[sid] = {
...state[sid],
unreadCount: action.time ? state[sid].unreadCount : 0,
}
})
return nextState
}
default:
return state
}
}