-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathkavita.js
More file actions
672 lines (627 loc) · 22.6 KB
/
Copy pathkavita.js
File metadata and controls
672 lines (627 loc) · 22.6 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
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
670
671
672
/** @type {import('./_venera_.js')} */
class Kavita extends ComicSource {
name = "Kavita"
key = "kavita"
version = "1.0.0"
minAppVersion = "1.4.0"
url = "https://cdn.jsdelivr.net/gh/venera-app/venera-configs@main/kavita.js"
settings = {
base_url: {
title: "服务器地址",
type: "input",
default: "https://demo.kavita.org",
validator: "^(https?:\\/\\/).+$"
},
}
get baseUrl() {
let raw = this.loadSetting('base_url')
if (typeof raw !== 'string' || !raw.trim()) {
raw = this.settings.base_url.default
}
let value = raw.trim()
if (!/^https?:\/\//i.test(value)) {
value = `https://${value}`
}
return value.replace(/\/$/, '')
}
get headers() {
const headers = { "Accept": "application/json" }
const token = this.loadData('token')
if (token) headers["Authorization"] = `Bearer ${token}`
return headers
}
async init() {
try {
await this.refreshReferenceData(false)
} catch (_) {
}
}
FilterComparison = {
Equals: 0,
GreaterThan: 1,
GreaterThanEqual: 2,
LessThan: 3,
LessThanEqual: 4,
Contains: 5,
MustContains: 6,
Matches: 7,
NotContains: 8,
NotEqual: 9,
BeginsWith: 10,
EndsWith: 11,
IsBefore: 12,
IsAfter: 13,
IsInLast: 14,
IsNotInLast: 15,
IsEmpty: 16
}
FilterField = {
Summary: 0,
SeriesName: 1,
PublicationStatus: 2,
Languages: 3,
AgeRating: 4,
UserRating: 5,
Tags: 6,
CollectionTags: 7,
Translators: 8,
Publisher: 10,
Editor: 11,
CoverArtist: 12,
Letterer: 13,
Colorist: 14,
Inker: 15,
Penciller: 16,
Writers: 17,
Genres: 18,
Libraries: 19,
ReadProgress: 20,
Formats: 21,
ReleaseYear: 22,
ReadTime: 23,
Path: 24,
FilePath: 25,
WantToRead: 26,
ReadingDate: 27,
AverageRating: 28,
Imprint: 29,
Team: 30,
Location: 31,
ReadLast: 32,
FileSize: 33
};
// [Optional] account related
account = {
/**
* [Optional] login with account and password, return any value to indicate success
* @param account {string}
* @param pwd {string}
* @returns {Promise<any>}
*/
login: async (account, pwd) => {
if (!account || !pwd) {
throw '账号或密码不能为空'
}
const res = await Network.post(
this.buildUrl('/api/Account/login'),
this.headers,
{
username: account,
password: pwd
}
)
if (res.status === 401) {
throw '账号或密码错误'
}
if (res.status !== 200) {
throw `登录失败: ${res.status}`
}
if (res.status === 200) {
this.saveData('token', JSON.parse(res.body).token)
this.saveData('apiKey', JSON.parse(res.body).apiKey)
await this.refreshReferenceData(true)
return account
}
},
/**
* logout function, clear account related data
*/
logout: () => {
this.deleteData('token')
this.deleteData('apiKey')
this.deleteData('kavita_libraries')
this.deleteData('kavita_genres')
this.deleteData('kavita_authors')
this.deleteData('kavita_meta_ts')
},
// {string?} - register url
registerWebsite: null
}
// explore page list
explore = [
{
title: "Kavita",
type: "singlePageWithMultiPart",
load: async () => {
await this.refreshReferenceData(false)
const feeds = {}
const data = {
id: 0,
name: "",
statements: [],
combination: 0,
sortOptions: {
sortField: 4,
isAscending: false
},
limitTo: 0
}
const latest = await this.fetchSeriesList(`/api/Series/v2`, { PageNumber: 0, PageSize: 12 }, data)
if (latest.comics.length) feeds["最新上架"] = latest.comics
return feeds
},
}
]
// categories
category = {
/// title of the category page, used to identify the page, it should be unique
title: "Kavita",
parts: [
{
name: "常用",
type: "dynamic",
loader: () => (
[
{
label: "全部",
target: {
page: 'category',
attributes: {
category: '全部',
param: 'all',
},
},
}
]
)
},
{
name: "书库",
type: "dynamic",
loader: () => {
const libraries = this.loadData('kavita_libraries')
if (!Array.isArray(libraries) || !libraries.length) {
return []
}
return libraries.map((library) => ({
label: library.name,
target: {
page: 'category',
attributes: {
category: library.name,
param: `library:${library.id}`,
},
},
}))
}
},
{
name: "作者",
type: "dynamic",
loader: () => {
const authors = this.loadData('kavita_authors')
if (!Array.isArray(authors) || !authors.length) {
return []
}
return authors.map((author) => ({
label: author.name,
target: {
page: 'category',
attributes: {
category: author.name,
param: `author:${author.id}`,
},
},
}))
}
},
{
name: "题材",
type: "dynamic",
loader: () => {
const genres = this.loadData('kavita_genres')
if (!Array.isArray(genres) || !genres.length) {
return []
}
return genres.map((genre) => ({
label: genre.title,
target: {
page: 'category',
attributes: {
category: genre.title,
param: `genre:${genre.id}`,
},
},
}))
}
},
],
// enable ranking page
enableRankingPage: false,
}
/// category comic loading related
categoryComics = {
/**
* load comics of a category
* @param category {string} - category name
* @param param {string?} - category param
* @param options {string[]} - options from optionList
* @param page {number} - page number
* @returns {Promise<{comics: Comic[], maxPage: number}>}
*/
load: async (category, param, options, page) => {
await this.refreshReferenceData(false)
const pageSize = 30
const data = {
statements: [],
combination: 0,
sortOptions: {
sortField: 4,
isAscending: false
},
limitTo: 0
}
/*
* sortField : 排序枚举类型:
* 1 按系列名称排序,2 创建时间,3 最后修改时间,4 最近添加章节时间,5 阅读时长,6 发布年份,7 阅读进度,8 平均评分,9 随机,10 用户评分
*/
if (options && options.length) {
const [sortField, isAscending] = options[0].split(',')
data.sortOptions.sortField = parseInt(sortField)
data.sortOptions.isAscending = isAscending === 'true'
}
const params = param.split(":")
if (params[0] === 'library' && params[1]) {
const libraryId = params[1]
data.statements.push({
comparison: this.FilterComparison.Equals,
field: this.FilterField.Libraries,
value: libraryId
})
}
if (params[0] === 'genre' && params[1]) {
const genreId = params[1]
data.statements.push({
comparison: this.FilterComparison.Equals,
field: this.FilterField.Genres,
value: genreId
})
}
if (params[0] === 'author' && params[1]) {
const authorId = params[1]
data.statements.push({
comparison: this.FilterComparison.Equals,
field: this.FilterField.Writers,
value: authorId
})
}
const allowedCategories = ['all', 'library', 'genre', 'author']
if (allowedCategories.includes(params[0])) {
const { comics, totalPages } = await this.fetchSeriesList(`/api/Series/v2`, { PageNumber: page, PageSize: pageSize }, data)
return {
comics: comics,
maxPage: totalPages
}
}
},
optionList: [
{
options: [
"4,false-最近添加",
"1,true-名称[升序]",
"1,false-名称[降序]",
"2,false-创建时间[降序]",
"2,true-创建时间[升序]",
"3,false-修改时间[降序]",
"3,true-修改时间[升序]",
],
notShowWhen: null,
showWhen: null
}
],
}
/// search related
search = {
/**
* load search result
* @param keyword {string}
* @param options {(string | null)[]} - options from optionList
* @param page {number}
* @returns {Promise<{comics: Comic[], maxPage: number}>}
*/
load: async (keyword, options, page) => {
const pageSize = 30
const data = {
statements: [],
combination: 0,
sortOptions: {
sortField: 4,
isAscending: false
},
limitTo: 0
}
if (options && options.length) {
const type = options[0]
if (type === 'FilePath') {
data.statements.push({
comparison: this.FilterComparison.Matches,
field: this.FilterField.FilePath,
value: keyword
})
} else if (type === 'SeriesName') {
data.statements.push({
comparison: this.FilterComparison.Matches,
field: this.FilterField.SeriesName,
value: keyword
})
} else { // all
data.statements.push({
comparison: this.FilterComparison.Matches,
field: this.FilterField.SeriesName,
value: keyword
}, {
comparison: this.FilterComparison.Matches,
field: this.FilterField.Summary,
value: keyword
}, {
comparison: this.FilterComparison.Matches,
field: this.FilterField.FilePath,
value: keyword
})
}
}
const { comics, totalPages } = await this.fetchSeriesList(`/api/Series/v2`, { PageNumber: page, PageSize: pageSize }, data)
return {
comics: comics,
maxPage: totalPages
}
/*
const data = await this.getJson('/api/Search/search', { queryString: keyword, includeChapterAndFiles: false })
const series = Array.isArray(data?.series) ? data.series : []
const token = this.loadData('token')
const comics = series.map((item) => this.parseSeries(item, token)).filter(Boolean)
return { comics: comics, maxPage: 1 }
*/
},
// provide options for search
optionList: [
{
type: 'select',
options: [
'All-全部',
'SeriesName-名称',
'FilePath-文件名',
],
label: '搜索选项'
}
],
enableTagsSuggestions: false,
// [Optional] handle tag suggestion click
onTagSuggestionSelected: (namespace, tag) => {
// return the text to insert into search box
return `${namespace}:${tag}`
},
}
/// single comic related
comic = {
/**
* load comic info
* @param id {string}
* @returns {Promise<ComicDetails>}
*/
loadInfo: async (id) => {
const data = await this.getJson(`/api/Series/${id}`)
const metadata = await this.getJson(`/api/Series/metadata`, { seriesId: id })
const volume = await this.getJson(`/api/Series/volumes`, { seriesId: id })
const chapters = volume
.flatMap(item => item.chapters || [])
.reduce((map, { id, titleName, files }) => {
let title = titleName
if (!title) {
title = files[0].filePath.split('/').pop()
}
map[id] = title;
return map;
}, {});
const authors = metadata.writers.map(item => item.name)
const apiKey = this.loadData('apiKey')
const tagSections = {}
const isReadable = this.isReadable(data.format)
console.log(data)
if (authors.length) tagSections['作者'] = authors
if (metadata.genres.length) tagSections['类型'] = metadata.genres.map(item => item.title)
if (metadata.tags.length) tagSections['标签'] = metadata.tags.map(item => item.title)
if (!isReadable) tagSections['提示'] = ['该系列包含的项目暂不支持阅读']
const info = new ComicDetails({
title: data.name,
subtitle: authors.join(', '),
cover: this.buildUrl(`/api/Image/series-cover`, { seriesId: id, apiKey: apiKey }),
description: metadata.summary || '暂无简介',
tags: tagSections,
chapters,
updateTime: data.lastChapterAdded,
uploadTime: data.created,
url: this.buildUrl(`/api/Series/${id}`)
})
return info
},
/**
* rate a comic
* @param id
* @param rating {number} - [0-10] app use 5 stars, 1 rating = 0.5 stars,
* @returns {Promise<any>} - return any value to indicate success
*/
starRating: async (id, rating) => {
},
/**
* load images of a chapter
* @param comicId {string}
* @param epId {string?}
* @returns {Promise<{images: string[]}>}
*/
loadEp: async (comicId, epId) => {
const data = await this.getJson(`/api/Series/chapter`, { chapterId: epId })
const page = data.pages
const isReadable = this.isReadable(data.format)
if (!isReadable) {
throw '该项目暂不支持阅读'
}
const apiKey = this.loadData('apiKey')
const extractPdf = data.format === 4
return { images: Array.from({ length: page }, (_, i) => this.buildUrl(`/api/Reader/image`, { chapterId: epId, page: i, apiKey: apiKey, extractPdf })) }
},
/**
* [Optional] Handle tag click event
* @param namespace {string}
* @param tag {string}
* @returns {{action: string, keyword: string, param: string?}}
*/
onClickTag: (namespace, tag) => {
if (namespace === '类型') {
const genres = this.loadData('kavita_genres')
const genreId = genres.find(item => item.title === tag)?.id
if (genreId) {
return {
action: 'category',
keyword: tag,
param: `genre:${genreId}`
}
}
}
if (namespace === '作者') {
const authors = this.loadData('kavita_authors')
const authorId = authors.find(item => item.name === tag)?.id
if (authorId) {
return {
action: 'category',
keyword: tag,
param: `author:${authorId}`
}
}
}
UI.showMessage(`不支持的标签类型: ${namespace}:${tag}`)
},
// enable tags translate
enableTagsTranslate: false,
}
async refreshReferenceData(force) {
const token = this.loadData('token')
if (!token) {
this.saveData('kavita_libraries', [])
this.saveData('kavita_genres', [])
this.saveData('kavita_authors', [])
return
}
const now = Date.now()
const last = this.loadData('kavita_meta_ts')
if (!force && last && now - last < 5 * 60 * 1000) return
try {
const [libraries, genres, authors] = await Promise.all([
this.getJson('/api/Library/libraries'),
this.getJson('/api/Metadata/genres'),
this.getJson('/api/metadata/people-by-role?role=3')
])
const libraryList = Array.isArray(libraries) ? libraries.filter((library) => library && library.id) : []
this.saveData('kavita_libraries', libraryList.map(item => ({ id: item.id, name: item.name })))
this.saveData('kavita_genres', Array.isArray(genres) ? genres : [])
this.saveData('kavita_authors', Array.isArray(authors) ? authors.map(item => ({ id: item.id, name: item.name })) : [])
this.saveData('kavita_meta_ts', now)
} catch (error) {
this.saveData('kavita_libraries', [])
this.saveData('kavita_genres', [])
this.saveData('kavita_authors', [])
if (String(error) === 'Login expired') throw error
}
}
async fetchSeriesList(path, query, data) {
const { content, page } = await this.postJson(path, query, data)
const series = Array.isArray(content) ? content : []
const apiKey = this.loadData('apiKey')
const comics = series.map((item) => this.parseSeries(item, apiKey)).filter(Boolean)
return {
comics,
totalPages: page.totalPages
}
}
parseSeries(series, apiKey) {
if (!series) return null
const id = series.id || series.seriesId
const title = series.name
return new Comic({
id: `${id}`,
title,
cover: this.buildUrl(`/api/Image/series-cover`, { seriesId: id, apiKey: apiKey }),
})
}
isReadable(format) {
const readableFormats = [0, 1, 4] // 0 图片, 1 档案, 2 Epub, 4 PDF
return readableFormats.includes(format)
}
async getJson(path, query) {
const res = await Network.get(this.buildUrl(path, query), this.headers)
this.ensureOk(res)
const text = res.body
if (!text) return null
return JSON.parse(text)
}
async postJson(path, query, data) {
const res = await Network.post(this.buildUrl(path, query), this.headers, data)
this.ensureOk(res)
const text = res.body
if (!text) return null
return {
content: JSON.parse(text),
page: JSON.parse(res.headers.pagination)
}
}
ensureOk(res) {
if (!res) throw '请求失败'
if (res.status === 401 || res.status === 403) throw 'Login expired'
if (res.status < 200 || res.status >= 300) throw `请求失败: ${res.status}`
}
buildUrl(path, query) {
let url = path
if (!/^https?:\/\//i.test(path)) {
url = `${this.baseUrl}${path.startsWith('/') ? '' : '/'}${path}`
}
const qs = this.buildQuery(query)
return qs ? `${url}?${qs}` : url
}
buildQuery(query) {
if (!query) return ''
const parts = []
for (const key of Object.keys(query)) {
const value = query[key]
if (value === undefined || value === null) continue
if (Array.isArray(value)) {
for (const item of value) {
if (item === undefined || item === null) continue
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(item))}`)
}
} else {
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
}
}
return parts.join('&')
}
formatDate(value) {
if (!value) return null
try {
const date = new Date(value)
if (Number.isNaN(date.getTime())) return null
return date.toISOString().split('T')[0]
} catch (_) {
return null
}
}
}