Compare commits

...

203 Commits

Author SHA1 Message Date
812fc17c5a build: 升级版本为2.3.2
Some checks failed
Release Draft / build (push) Has been cancelled
2026-04-02 16:33:59 +08:00
ChrsiGray
e8a0d8a00c fix: support douban image uploads with referer
- use subject page referer for douban image requests\n- keep PicGo clipboard upload flow and await clipboard writes\n- add webp clipboard fallback for image decoding
2026-04-02 11:26:16 +08:00
ChrsiGray
318aabb21b fix: upload Douban images to PicGo via temp file 2026-04-02 11:26:16 +08:00
a8094d7575
Merge pull request #177
fix: All search type 403, undefined actor crash, and lazy login on startup
2026-03-11 23:27:55 +08:00
YuBai
7ba1a7be0c feat: implement lazy login to eliminate startup network request
Replace eager login verification on startup with assumeLoggedIn(),
which sets login state from saved credentials without any network call.
Real verification is deferred until sync (which needs the actual user ID)
or when the settings page is opened.

- UserComponent: add verified flag, assumeLoggedIn(), isVerified()
- main.ts: replace onLayoutReady(login) with assumeLoggedIn(); fix
  inverted condition bug in checkLogin() (!needLogin -> needLogin)
- DoubanSyncModal: remove redundant login check before checkLogin()
- LoginSettingsHelper: handle assumed-but-unverified state in constructLoginUI()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 20:38:48 +08:00
YuBai
4e8d3f1318 Merge branch 'fix-undefined-actor-error' into fix/search-all-api-and-login-init 2026-03-04 18:25:45 +08:00
YuBai
c375512903 fix: restore All search type and initialize login state on startup
- Switch AllPageSearchPageFetcher from m.douban.com/rexxar/api/v2/search
  (returns 403 need_login) to www.douban.com/j/search (works with cookies)
- Update AllFirstPageSearchResultPageParser and OtherAllPageSearchResultPageParser
  to use SearchParserHandler.parseSearchJson() matching the j/search response format,
  replacing the old Rexxar-specific SearchParserHandlerV2 parsing logic
- Add await this.userComponent.login() in onload() so login state is initialized
  on startup, fixing false isLogin()=false causing "need login for next page" errors

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-04 18:20:58 +08:00
YuBai
99d4170626 fix: 为其他 handler 添加数组空值检查
在 parseVariable 方法中为所有数组字段的 .map() 调用添加 (field || []) 保护,

防止当字段为 undefined 时调用 .map() 报错。
2026-02-02 11:26:47 +08:00
YuBai
297ccd33cf fix: 当 JSON-LD 解析失败时添加回退机制
豆瓣现在对未登录请求返回反爬虫验证页面,导致 JSON-LD 解析返回 undefined。

添加从 OG meta 标签提取基本信息的回退机制,防止代码崩溃。

同时给所有数组字段添加默认值 || []。
2026-02-02 11:25:56 +08:00
YuBai
a0eccf7370 fix: handle() 方法 catch 块返回 undefined 而不是错误对象
当 HTTP 请求失败时,返回错误对象会导致上层代码尝试访问错误对象的属性,

造成 TypeError。改为返回 undefined 让上层代码正确处理空值情况。
2026-02-02 11:24:07 +08:00
572907719b build: 升级版本为2.3.1
Some checks failed
Release Draft / build (push) Has been cancelled
2025-11-09 23:17:43 +08:00
ffc93a4a13 feat: 调整别名的转义 2025-11-09 23:16:34 +08:00
08749116f3 feat: 附件(图片)文件保存本地支持自定义
fix: 修复有些图片无法下问题
fix: 修复同步汇总文件中文件名和真实保存不一致问题
feat: 调整别名的转义
2025-11-09 22:43:17 +08:00
266cfb3901 docs: change home page header
Some checks failed
Deploy Jekyll site to Pages / build (push) Has been cancelled
Deploy Jekyll site to Pages / deploy (push) Has been cancelled
2025-10-10 18:05:36 +08:00
7e57846f32 docs: add documents website 2025-07-24 08:40:42 +08:00
16b9ff581d docs: add documents website
Some checks failed
Deploy Jekyll site to Pages / build (push) Has been cancelled
Deploy Jekyll site to Pages / deploy (push) Has been cancelled
2025-07-24 00:01:09 +08:00
dd1648c20a fix #151 笔记存放位置,无法使用自定义字段 2025-06-05 14:00:28 +08:00
df4c4956f1 upgrade to 2.3.0
Some checks failed
Release Draft / build (push) Has been cancelled
2025-03-11 17:07:09 +08:00
c09f96d3b8 fix #143 #132 #124
1. 增加游戏同步功能
2. 修复自定义参数配置问题
3. 增加搜索默认类型
4. 增加全部搜索为空时的提示
2025-03-11 14:45:14 +08:00
a7b81bd189 upgrade: 升级为2.2.4
Some checks failed
Release Draft / build (push) Has been cancelled
2025-03-10 09:03:46 +08:00
9403fef320 feature: #132 同步游戏 2025-03-10 09:02:54 +08:00
001cb5dc3e 调整说明
Some checks failed
Release Draft / build (push) Waiting to run
Deploy Jekyll site to Pages / build (push) Has been cancelled
Deploy Jekyll site to Pages / deploy (push) Has been cancelled
2025-03-09 16:11:22 +08:00
711744e065 调整说明 2025-03-09 13:48:25 +08:00
836c9c61b3 test 增加提交发布功能 2025-03-09 13:40:30 +08:00
f0b73c7d8b test 增加提交发布功能 2025-03-09 13:16:20 +08:00
8556de0501 test 增加提交发布功能 2025-03-09 13:11:55 +08:00
6481c69d81 test 增加提交发布功能 2025-03-09 13:06:14 +08:00
29322e0869 test 增加提交发布功能 2025-03-09 12:57:10 +08:00
431c1f2564 test 增加提交发布功能 2025-03-09 12:52:20 +08:00
89f43432d2 enhance 增加提交发布功能 2025-03-09 12:50:06 +08:00
20b6daf10e enhance 增加提交发布功能 2025-03-09 12:46:42 +08:00
208e0d2061 enhance 增加提交发布功能 2025-03-09 12:40:31 +08:00
449b96cbd1 enhance 增加提交发布功能 2025-03-09 12:39:49 +08:00
ee514a8c95 enhance 增加提交发布功能 2025-03-09 12:24:08 +08:00
161741b4af Update pages.yml 2025-03-09 12:04:02 +08:00
382e7c87dd
Update pages.yml 2025-03-09 11:58:55 +08:00
671b28f91a feature 游戏同步
Some checks are pending
Deploy Jekyll site to Pages / build (push) Waiting to run
Deploy Jekyll site to Pages / deploy (push) Blocked by required conditions
1. 增加游戏同步页面
2. 增加支持二维码
2025-03-09 00:13:21 +08:00
0aa0c15cc5 fix #139
1. 优化导入配置,增加更多导入时的选项
2. 优化导入结果的显示,现在会在结果文本中显示具体的条件
2025-03-06 18:55:39 +08:00
9fe0d1bfc9 fix #139
1. 优化导入配置,增加更多导入时的选项
2. 优化导入结果的显示,现在会在结果文本中显示具体的条件
2025-03-06 18:54:01 +08:00
ea700e481e fix #139 增加过滤条件:时间或条数限制 2025-03-06 18:54:01 +08:00
dc225f30f1 增加版本为2.2.0 2025-03-06 18:54:01 +08:00
a120e450e9 fix #139 #128
1. 优化配置将配置页面调整为tab
2. 优化文件夹选取方式避免卡顿
3. 优化模板文件选取方式避免卡顿
4. 增加设置的导入导出用以备份
5. 优化加载插件的卡顿问题,现在加载会非常快
6. 优化了配置的文本,简化了文本内容
2025-03-06 18:54:01 +08:00
c866c8be4c
Merge pull request #134 from vran-dev/fix/redundant_space
Fix: remove leading and and trailing whitespace of person name
2025-02-24 14:36:39 +08:00
vran
132e47f2b2 fix: remove leading and and trailing whitespace of person name 2025-01-22 13:36:14 +08:00
wanxuping
eeedf23e7c fix #94 移动端加载失败 2024-12-26 13:47:01 +08:00
wanxuping
8f2c5f2117 fix #94 移动端加载失败 2024-12-26 12:54:37 +08:00
wanxuping
8437aee2e1 fix #94 移动端加载失败 2024-12-26 12:53:28 +08:00
3ff2b8f4db update wechat group qr 2024-08-05 15:27:05 +08:00
8f3bbe99f1 update wechat group qr 2024-08-05 10:10:55 +08:00
5252ce536c update wechat group qr 2024-07-25 10:05:13 +08:00
d98a24545e Fixed clicking the next page has no effect 2024-07-15 23:04:32 +08:00
232439b64c fix search error 2024-07-11 10:19:14 +08:00
d0ed8cf1f3 fix mac os search error 2024-07-10 18:33:55 +08:00
a5747c2f45 add wechat group 2024-06-24 09:12:44 +08:00
59e0f83db3 add wechat group 2024-06-14 12:22:42 +08:00
3df097e861 add wechat group 2024-06-13 17:37:42 +08:00
2ae545c439 update readme wechat group 2024-06-13 17:33:47 +08:00
3b50e801a5 update readme wechat group info 2024-06-13 17:26:16 +08:00
b5d8636352 update wechat group 2024-06-13 17:19:18 +08:00
441345ebb8 fix sync terminate when item wrong 2024-05-16 18:34:50 +08:00
910dbd30d9 fix sync terminate when item wrong 2024-05-16 18:34:38 +08:00
e1ae4cd88c
Merge pull request #113 from ruinshe/add-templated-attachment-support
support variables in attachment
2024-05-16 12:29:34 +08:00
c016bbdc46 fix fetch data error 2024-05-16 02:06:27 +08:00
290eaaa45b fix fetch data error 2024-05-16 01:56:17 +08:00
1d74714e6e fix fetch data error 2024-05-16 01:51:29 +08:00
eb25c5be2b update config description 2024-05-16 00:58:21 +08:00
7480d773ea fix obsidian-douban cookie login 2024-05-16 00:36:57 +08:00
661e8e7e2e add picture bed 2024-05-16 00:09:33 +08:00
Ruins He
6f6943bb09
docs(localization): update attachment folder instruction message
Signed-off-by: Ruins He <lyhypacm@gmail.com>
2024-05-15 19:26:56 +08:00
Ruins He
561e42fe73
feat(attachments): add template support for attachment folder support
Signed-off-by: Ruins He <lyhypacm@gmail.com>
2024-05-15 19:14:30 +08:00
5c5b1b6348
Update README.md 2024-05-11 17:10:38 +08:00
48d8693e5c
Update README.md 2024-05-11 17:10:02 +08:00
4b0580bc87
Merge pull request #111 from Wanxp/add-get-started-info
Update README.md
2024-05-11 17:08:54 +08:00
8e12632afb
Update README.md 2024-05-11 17:07:38 +08:00
08fb988f39 add project wiki github pages 2024-05-11 16:56:03 +08:00
40c8f387c3 add project wiki github pages 2024-05-11 16:54:01 +08:00
cf938779dd add project wiki github pages 2024-05-11 16:04:34 +08:00
663528e09b add project wiki github pages 2024-05-11 13:46:51 +08:00
7505c5520e add project wiki github pages 2024-05-11 13:45:21 +08:00
ba3fcb896c add project wiki github actions 2024-05-11 11:27:35 +08:00
f7562688d8 add project wiki github actions 2024-05-11 11:21:23 +08:00
c6b21e96bb upgrade to 2.0.2 2024-03-21 21:33:35 +08:00
c1bb8cf05a remove search item teleplay 2024-03-21 21:26:32 +08:00
0db96c31f5 move import follow-redirects position 2024-03-21 21:21:48 +08:00
9ccb10c5d4 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	package.json
#	src/org/wanxp/utils/HttpUtil.ts
2024-03-21 21:19:22 +08:00
58ced6cd1f fix game/book/movie import error 2024-03-21 21:18:28 +08:00
01276030ca fix mobile can not login 2024-03-17 21:58:23 +08:00
6a0cf9dab1 fix mobile can not login 2024-03-15 22:43:27 +08:00
6b047b595c custom lib 2024-03-15 20:11:27 +08:00
5c3edc909e fix android can not load plugins 2024-03-14 13:10:17 +08:00
ba5e6a8ee2 add new setting for {{scoreStar}} and {{myRatingStar}} 2023-12-30 20:20:19 +08:00
ba0f75be2a add new setting for {{scoreStar}} and {{myRatingStar}} 2023-12-29 23:37:52 +08:00
f2278b14d9 add new setting for {{scoreStar}} and {{myRatingStar}} 2023-12-29 23:35:32 +08:00
7539134b05 add new setting for {{scoreStar}} and {{myRatingStar}} 2023-12-29 23:09:05 +08:00
b4f41bcae8 add new setting for {{scoreStar}} and {{myRatingStar}} 2023-12-29 18:30:19 +08:00
b39e0a18a3 add new setting for {{scoreStar}} and {{myRatingStar}} 2023-12-29 18:26:53 +08:00
446f405a79 add new setting for {{scoreStar}} and {{myRatingStar}} 2023-12-29 18:25:01 +08:00
232fde720c update readme add example 2023-12-27 09:36:47 +08:00
c2ce0c5e0d fix actor/director's name lost space charactor 2023-12-26 16:40:39 +08:00
68b2a57b80 upgrade to 1.9.9 2023-12-26 15:59:04 +08:00
446a37e03b add array display type
fix write enter to editor when search item
fix desc has "\"     " error
2023-12-26 15:18:11 +08:00
0455b379d6 change README 2023-12-22 14:43:38 +08:00
0a64529a35 change README 2023-12-22 14:16:42 +08:00
e06f998206 change README 2023-12-22 11:45:14 +08:00
52c0202da5 change README 2023-12-22 11:38:33 +08:00
fb25fdc08e fix login notice 2023-12-21 23:51:01 +08:00
ae7c16430d fix name error 2023-12-21 23:31:36 +08:00
de439d2cdc fix note import error 2023-12-21 22:57:46 +08:00
264a91773d fix search by type error 2023-12-21 18:23:08 +08:00
5d288bda14 fix search by type error 2023-12-21 18:18:39 +08:00
ba0014a769 upgrade to 1.9.7 2023-12-21 13:28:30 +08:00
f0c1421f5d fix search error 2023-12-21 13:27:16 +08:00
1b5b9bb0b3 fix search error 2023-12-21 10:25:28 +08:00
96fe6d6771 fix search error 2023-12-18 23:28:14 +08:00
7bd4b6b96f Adjust book descriptions to use more complete data @junjiemao
, upgrade to 1.9.6
2023-11-14 11:15:21 +08:00
5c05bf08a4
Merge pull request #83 from junjiemao/junjiemao-patch-1
Update DoubanBookLoadHandler.ts
2023-11-12 23:04:15 +08:00
HatMatrix
5dd02b1433
Update DoubanBookLoadHandler.ts
Adjust book descriptions to use more complete data
2023-11-11 16:03:05 +08:00
46d61d3e84 Merge remote-tracking branch 'origin/master' 2023-10-30 22:25:03 +08:00
058afa8ebf support sync teleplay , upgrade to 1.9.5 2023-10-30 22:24:39 +08:00
e3fecf03c4
Update issue templates 2023-10-30 22:00:43 +08:00
7395da937c
Update issue templates 2023-10-30 21:44:28 +08:00
37266a3772
Update issue templates 2023-10-30 21:40:09 +08:00
ccabb3e29d
Update issue templates 2023-10-30 21:38:37 +08:00
4eabfea419
Update issue templates 2023-10-30 21:34:53 +08:00
414f078d55
Update issue templates 2023-10-30 20:12:09 +08:00
d02c54b0c9
Update issue templates 2023-10-30 20:11:20 +08:00
6103263c77
Update issue templates 2023-10-30 20:08:43 +08:00
91b44beae2
Update issue templates 2023-10-30 20:05:51 +08:00
405ae66da8 support sync teleplay 2023-10-16 23:18:37 +08:00
331ff38cd9 fix custom variables 2023-10-11 14:14:54 +08:00
4bf64965bb 1. add array spilt , start, end 2023-09-24 00:34:51 +08:00
0dd68ff8cb 1. add array spilt , start, end 2023-09-23 10:12:07 +08:00
230733aa49 1. fix sync movie fetch wrong type
2. fix can not get the comment of book or movie
2023-09-23 09:22:29 +08:00
5c345efa1d 1. fix sync movie fetch wrong type
2. fix can not get the comment of book or movie
2023-09-23 09:21:46 +08:00
21eea367cf version update 2023-09-20 13:44:04 +08:00
9dee83752e fix: douban login 2023-09-20 13:39:38 +08:00
938d7f6658 fix: douban login 2023-09-20 13:37:16 +08:00
01a386dd6b change: the way of request 2023-09-20 13:16:24 +08:00
a97b6a7364
Merge pull request #75 from Wanxp/dev
add https get
2023-09-20 10:48:04 +08:00
wangfei
bcef28c822 add https get 2023-09-20 10:29:32 +08:00
44697ac05a feature: theater
function: HttpUtil
2023-09-20 09:54:29 +08:00
198cffaada add text to headers converter 2023-09-19 15:12:53 +08:00
3def97db92 fix cookie login failed 2023-09-12 15:41:40 +08:00
881f9f36f6 fix cookie login failed 2023-09-12 15:39:17 +08:00
6c52606417 feature: theater
feature: imageData.url
2023-08-30 18:10:37 +08:00
240f71f635 fix: cover image do not show error 2023-07-10 23:06:53 +08:00
3e22d97e52 add thanks 2023-06-20 10:18:49 +08:00
ba0f29ca20 add community qr code 2023-06-20 10:09:12 +08:00
ace218402c add community qr code 2023-06-20 10:02:12 +08:00
32fa165eb8 fix login error 2023-05-25 00:07:41 +08:00
1119b105ba fix login error 2023-05-25 00:06:44 +08:00
fa29664757 fix file dot error 2023-04-27 23:35:25 +08:00
1d17a0afb4 fix file dot error 2023-04-27 23:34:07 +08:00
61860de3cd fix error when the name of file includes dot 2023-04-21 09:26:24 +08:00
d667b4b2a8 fix error when the name of file includes dot 2023-04-21 09:24:50 +08:00
cb9ffb4925 fix login failed problem 2023-04-18 01:03:49 +08:00
9d45746dac fix login failed problem 2023-04-18 01:02:54 +08:00
ab86b3450c Optimization Introduction 2023-04-17 11:30:53 +08:00
814ebaad59 Optimization Introduction 2023-04-17 11:30:25 +08:00
c1bf659deb Optimization Introduction 2023-04-17 11:28:35 +08:00
13a3a15763 Optimization Introduction 2023-04-17 11:23:26 +08:00
2750f29091 Optimization Introduction 2023-04-17 10:29:46 +08:00
8fbcf118a0 feature: search pageable 2023-02-16 11:42:28 +08:00
5c9b37e9e6 feature: search pageable 2023-02-16 11:39:40 +08:00
1d3e30637a feature: search pageable 2023-02-16 11:13:05 +08:00
980fae30ed feature: search pageable 2023-02-16 11:11:44 +08:00
e19fbc648c feature: search next page 2023-02-15 22:38:37 +08:00
29db644ac1 fix: search isbn error 2023-02-13 00:16:28 +08:00
a99e34c367 fix: search isbn error 2023-02-13 00:15:06 +08:00
ec544b12d2 update version to 1.8.1 2023-02-02 01:27:53 +08:00
2b3c310f4c add login by cookie 2023-02-02 01:26:38 +08:00
afecbcdcd0 fix search and create file but open in leftLeaf 2023-01-03 11:55:18 +08:00
a00cdc59ed add variable: yearPublished 2022-12-27 17:27:08 +08:00
7471edea0f add variable: yearPublished 2022-12-26 23:21:34 +08:00
f83a0b4c8e add function: import high quantity image from douban 2022-12-03 18:53:36 +08:00
c9dd998d64 add function: import high quantity image from douban 2022-12-03 18:16:04 +08:00
022b1e347f fix movie/teleplay actor and director name wrong 2022-12-03 17:57:47 +08:00
508e4c9303 Merge remote-tracking branch 'origin/master' 2022-12-03 17:08:37 +08:00
3b7a2fb3a1 fix movie/teleplay actor and director name wrong 2022-12-03 17:08:19 +08:00
c49750b848 fix login and teleplay 2022-12-02 23:00:22 +08:00
037b1f4dbc
Update README.md 2022-12-01 14:03:59 +08:00
ff37584d63
Update README.md 2022-12-01 14:03:41 +08:00
92e30cf97d fix note bug 2022-12-01 00:18:38 +08:00
689a43cf16 upgrade to 1.7.6 2022-11-30 23:59:47 +08:00
36b35db78d add function sync breakpoint resume 2022-11-30 23:58:11 +08:00
594cd3a40b update README.md 2022-11-29 11:33:55 +08:00
2a10100ed0 add function sync breakdown resume 2022-11-29 11:25:37 +08:00
076883aada upgrade to 1.7.4.1 2022-11-26 17:33:37 +08:00
b753f1f244 upgrade to 1.7.4.1 2022-11-26 17:29:39 +08:00
d88a004ed6 add debug mode 2022-11-26 17:28:39 +08:00
b3b9ab2c44 add debug mode 2022-11-26 15:55:41 +08:00
a455baeb41 optimize and fix bug 2022-11-26 14:05:09 +08:00
33e2b76c9f optimize and fix bug 2022-11-26 13:55:13 +08:00
459eca5d61 Merge remote-tracking branch 'origin/master' 2022-11-26 13:54:49 +08:00
86345cdf85 optimize and fix bug 2022-11-26 13:54:29 +08:00
cee6a89bd2
Update README.md 2022-11-24 12:30:21 +08:00
39cc5aeb42
Update README.md 2022-11-24 12:30:02 +08:00
c0d7cf5972 optimize sync config panel 2022-11-21 13:26:51 +08:00
1190dafbd5 optimize sync config panel 2022-11-21 13:19:37 +08:00
23f145f0b0 upgrade to v1.7.2 2022-11-20 12:58:24 +08:00
1adaecfaeb optimize sync config panel 2022-11-20 12:57:01 +08:00
eebe141ef0 upgrade to v1.7.1 2022-11-20 11:26:34 +08:00
c1e25c630c fix #24 show wrong chinese name 2022-11-20 11:25:32 +08:00
198 changed files with 9649 additions and 4790 deletions

@ -0,0 +1,51 @@
---
name: 异常反馈/Bug report
about: 使用遇到问题时反馈问题/Create a report to help us improve
title: "[Bug]:简要描述你的问题"
labels: ''
assignees: Wanxp
---
1. 问题说明
1.1 操作:
比如进行同步电影时,无法获取我自己的评论...
1.2 结果:
截图或者文本...
```text
---
title: 英雄
comment:
---
```
1.3 我想要的效果:
```text
---
title: 英雄
comment: 我的评论
---
```
2. 书影音名称
《英雄》
3. 模板展示
```txt
---
title: {{name}}
comment: {{myComment}}
---
```
4. 其它
如相关的插件设置...
5. 操作系统版本
- [x] windows
- [ ] ubuntu
- [ ] mac
- [ ] android
- [ ] ios
6. obisidian版本
...

@ -0,0 +1,10 @@
---
name: 新功能建议/Feature request
about: Suggest an idea for this project
title: "[Feature]:"
labels: ''
assignees: ''
---

71
.github/workflows/pages.yml vendored Normal file

@ -0,0 +1,71 @@
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
# Sample workflow for building and deploying a Jekyll site to GitHub Pages
name: Deploy Jekyll site to Pages
on:
push:
branches:
- "master"
paths:
- "doc/**"
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow one concurrent deployment
concurrency:
group: "pages"
cancel-in-progress: true
jobs:
# Build job
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: doc
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: '3.3' # Not needed with a .ruby-version file
bundler-cache: true # runs 'bundle install' and caches installed gems automatically
cache-version: 0 # Increment this number if you need to re-download cached gems
working-directory: '${{ github.workspace }}/doc'
- name: Setup Pages
id: pages
uses: actions/configure-pages@v3
- name: Build with Jekyll
# Outputs to the './_site' directory by default
run: bundle exec jekyll build --baseurl "${{ steps.pages.outputs.base_path }}"
env:
JEKYLL_ENV: production
- name: Upload artifact
# Automatically uploads an artifact from the './_site' directory by default
uses: actions/upload-pages-artifact@v3
with:
path: "doc/_site/"
# Deployment job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

97
.github/workflows/release-draft.yml vendored Normal file

@ -0,0 +1,97 @@
name: Release Draft
on:
push:
paths:
- 'manifest.json'
branches:
- "master"
workflow_dispatch:
permissions:
contents: write
pages: write
id-token: write
jobs:
build:
runs-on: ubuntu-latest
environment: node18
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm install
- name: Build project
run: npm run build
- name: Extract version from package.json
id: extract_version
run: echo "VERSION=$(jq -r '.version' package.json)" >> $GITHUB_ENV
- name: Set Git user
run: |
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
- name: Create tag
run: git tag -a "${{ env.VERSION }}" -m "Release version ${{ env.VERSION }}"
- name: Push tag
run: git push origin "${{ env.VERSION }}"
- name: Create GitHub release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: "${{ env.VERSION }}"
release_name: "${{ env.VERSION }}"
draft: true
prerelease: false
generate_release_notes: true
- name: Upload release assets
uses: actions/upload-release-asset@v1
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./main.js
asset_name: main.js
asset_content_type: application/javascript
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ env.VERSION }}
- name: Upload manifest.json
uses: actions/upload-release-asset@v1
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./manifest.json
asset_name: manifest.json
asset_content_type: application/json
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ env.VERSION }}
- name: Upload style.css
uses: actions/upload-release-asset@v1
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./styles.css
asset_name: styles.css
asset_content_type: text/css
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ env.VERSION }}
- name: Output release message
run: echo "发布预发布版本${{ env.VERSION }}正常"

2
.gitignore vendored

@ -20,3 +20,5 @@ data.json
# Exclude macOS Finder (System Explorer) View States # Exclude macOS Finder (System Explorer) View States
.DS_Store .DS_Store
doc/.vitepress/dist
doc/.vitepress/cache

143
README.en.md Normal file

@ -0,0 +1,143 @@
# Obsidian Douban Plugin
<p align="center">
<a href="https://github.com/Wanxp/obsidian-douban/releases/latest">
<img src="https://img.shields.io/github/manifest-json/v/Wanxp/obsidian-douban?color=blue">
</a>
<img src="https://img.shields.io/github/release-date/Wanxp/obsidian-douban">
<a href="https://github.com/Wanxp/obsidian-douban/blob/master/License">
<img src="https://img.shields.io/github/license/Wanxp/obsidian-douban">
</a>
<img src="https://img.shields.io/github/downloads/Wanxp/obsidian-douban/total">
<a href="https://github.com/Wanxp/obsidian-douban/issues">
<img src="https://img.shields.io/github/issues/Wanxp/obsidian-douban">
</a>
<br>
<img src="https://img.shields.io/tokei/lines/github/Wanxp/obsidian-douban">
<a href="https://www.codefactor.io/repository/github/wanxp/obsidian-douban">
<img src="https://www.codefactor.io/repository/github/wanxp/obsidian-douban/badge" alt="CodeFactor" />
</a>
</p>
Bring your data from [Douban]() to Your [Obsidian](https://obsidian.md/)
Including your _Movie, Book, Music, Teleplay, Note, Game_ even your personal State and Comment
![background](doc/background.png)
---
If you want some features or have any questions about this plugin, create issues or join the development is welcome or ⭐Star
- [Bugs, Issues, & Feature Requests](https://github.com/Wanxp/obsidian-douban/issues)
- Read Other Languages: English | [简体中文](README.md)
## Target
- [x] Sync Personal Movie/TV/Book/Music
- [x] Import Movie/Teleplay/Book/Music/Note/Game
- [x] Personal Comment/State/Rate
- [x] Custom Variables
## 效果
1. 结合Timeline插件 __构建个人观影时间线__,请参照[结合timeline插件实现时间线效果](doc/Obsidian-Douban-TimeLine.md)
![](doc/img/obsidian-douban-time-preview-example.gif)
<!--2. 结合DataView插件__构建个人电子书架书库数据__请参照[结合dateview插件实现个人书架效果](./doc/Obsidian-Douban-DataView.md))-->
2. 结合主题 __构建类豆瓣网页效果__,请参照[结合Blue Topaz实现网页效果](doc/Obsidian-Douban-BlueTopaz.md)
![](doc/background.png)
## How to use
### Sync
- Sync Data From Douban
Sync data from Douban (to learn how to use the TimeLine plugin to build a reading/movie watching timeline, please refer to [here](Obsidian-Douban-TimeLine.en.md)).
![Sync Data From Douban](doc/img/sync_data_from_douban.gif)
### Search
Use the following method: Enter <kbd>Ctrl</kbd> + <kbd>P</kbd>, enter "Douban", select search and use
- Search Data And Create Note
- Search Data By File Name
- Search Movie By Input Text
![Search Movie By File Name](doc/img/search_and_create_note.gif)
## Support Field
(若有缺少想导入的字段, 欢迎提issues反馈)
| 字段 | 电影 | 电视剧 | 书籍 | 音乐 | 日记 | 游戏 | 广播 |
|-----------------|-------------------|------------------|-------------------|----------------|----------------|---------------| ---- |
| `id` | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | - |
| `title` | 电影名称 | 电视剧名称 | 书名 | 音乐名 | 日记标题 | 游戏名称 | - |
| `type` | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 | - |
| `score` | 评分 | 评分 | 评分 | 评分 | 评分 | 评分 | - |
| `image` | 封面 | 封面 | 封面 | 封面 | 图片 | 封面 | - |
| `url` | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | - |
| `desc` | 简介 | 简介 | 内容简介 | 简介 | 简介 | 简介 | - |
| `publisher` | - | - | 出版社 | 出版者 | 发布者 | 发行商 | - |
| datePublished | 上映日期 | 上映日期 | 出版年 | 发行时间 | 发布时间 | 发行日期 | - |
| yearPublished | 上映年份 | 上映年份 | 出版年份 | 发行年份 | 发布年份 | 发行年份 | - |
| genre | 类型 | 类型 | - | 流派 | - | 类型 | - |
| currentDate | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | |
| currentTime | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | |
| myTags | 我标记的标签 | 我标记的标签 | 我标记的标签 | 我标记的标签 | - | 我标记的标签 | |
| myRating | 我的评分 | 我的评分 | 我的评分 | 我的评分 | - | 我的评分 |
| myState | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想听/在听/听过 | - | 状态:想玩/在玩/玩过 | |
| myComment | 我的评语 | 我的评语 | 我的评语 | 我的评语 | - | 我的评语 | |
| myCollectionDate | 我标记的时间 | 我标记的时间 | 我标记的时间 | 我标记的时间 | - | 我标记的时间 | |
| 扩展1 | director:导演 | director:导演 | author:原作者 | actor: 表演者 | author:作者 | aliases:别名 | |
| 扩展2 | author:编剧 | author:编剧 | translator:译者 | albumType:专辑类型 | authorUrl:作者网址 | developer:开发商 | |
| 扩展3 | actor:主演 | actor:主演 | isbn:isbn | medium:介质 | content:日记内容 | platform:平台 | |
| 扩展4 | originalTitle:原作名 | originalTitle:原作名 | originalTitle:原作名 | records:唱片数 | | | |
| 扩展5 | country:国家 | country:国家 | subTitle:副标题 | barcode:条形码 | | | |
| 扩展6 | language:语言 | language:语言 | totalPage:页数 | | | | |
| 扩展7 | time:片长 | time:片长 | series:丛书 | | | | |
| 扩展8 | aliases:又名 | aliases:又名 | menu:目录 | | | | |
| 扩展9 | IMDb | IMDb | price:定价 | | | | |
| 扩展7 | | episode:集数 | binding:装帧 | | | | |
| 扩展8 | | | producer: 出品方 | | | | |
- Notice: myTags, myRating, myState, myComment, myCollectionDate. All parameters are available after logging in to the plugin.
## How to install
### From Obsidian
1. Go to Obsidian plugin center
2. Search obsidian-douban
3. Click install
4. Enable plugin
### Manmel
1. Download `main.js`, `manifest.json`, `styles.css` from GitHub release page
2. Copy step1 downloaded file to your vault folder `/.obsidian/plugins/obsidian-douban/`
3. Enable plugin in Obsidian
## How to Develop
1. Enter your test vault folder `/.obsidian/plugins/`
2. Clone Code
`git clone git@github.com:Wanxp/obsidian-douban.git`
3. Enter folder
`cd obsidian-douban`
4. Build
`npm run build`
5. Run and Watch code chang
`npm run dev`
6. Go to your Obsidian plugin center reload this plugin
7. Enjoy your develop
## Community
<img src="doc/img/obsidian-douban-qq-qr_code.svg" width="300px"> <img src="doc/img/wechat_group.png" width="245px">
## Disclaimer
1. This program does not crawl any content such as books and videos, and is only for technical research purposes. It does not violate the copyright of authors of books and videos or the official interests of Douban. If there is any infringement, please contact me to delete it.
2. This program is for learning and communication only, and cannot be used for commercial purposes. Otherwise, the consequences will be at your own risk.
3. Although every effort is made to avoid it, I am not responsible for any losses caused by the plug-in. Please refer to [here](#impact) for the impact of different operations.
## Impact
Note: Except for checking "Replace documents with the same name" when synchronizing book and video data, which may modify notes with the same path and document name, other operations will not modify existing notes.
| Operation | Condition | Impact | Example |
|-----------------|-----------------------|---------------------------|-----------------------------------------------------------------------------------------------|
| Import book and video data | Default condition | Create a note named after the selected item | If you search for "Batman" and select it for import, a note titled "Batman" will be created |
| Import book and video data | Note with the same name already exists | No impact, prompted that there is already a note with the same name, and the existing note will not be modified | If you search for "Batman" and select it for import, but there is already a note with the same path and name, a note will not be created |
| Import book and video data | Configure the `note name` value to include the path | If there is no such path, it will create a file with the corresponding file name | If you search for "Batman" and select it for import, configure the `note name` value to be `/data/{{type}}/{{title}}`, a folder `data/Movie` will be created |
| Import book and video data | Configure the `save image attachment` value to be checked | Save the cover image in the specified location of `attachment storage location` | If you search for "Batman" and select it for import, configure the `attachment storage location` value to be `assets`, the cover file `p462657443.jpg` will be saved in the `assets` folder |
| Synchronize book and video data | All of the above | All of the above | All of the above |
| Synchronize book and video data | Check the value of `replace the same document` | If the file with the same path and name already exists, overwrite it directly | If there is already a `data/Movie/Batman.md` file, configure the `note name` value to be `/data/{{type}}/{{title}}`, and check "Replace documents with the same name" when synchronizing book and video records, then `data/Movie/Batman.md` will be replaced with the latest one |
## Thanks
### IDE support
[<image src="doc/img/jb_beam.svg"> </image>](https://www.jetbrains.com/?from=obsidian-douban)

215
README.md

@ -19,46 +19,71 @@
</a> </a>
</p> </p>
Import _Movie, Book, Music, Teleplay, Note, Game_ even _Your Personal Movie/Book/Music_ from Douban in [Obsidian](https://obsidian.md/) 这是一款[Obsidian](https://obsidian.md/)插件支持在Obsidian中导入[豆瓣]()中的 _电影、书籍、音乐、电视剧、日记、游戏_
在[Obsidian](https://obsidian.md/)使用并导入豆瓣中的 _电影/书籍/音乐/电视剧/日记/游戏_ 甚至是 _你标记过的书影音_ , 包含你的评分/发布日期/演员表等信息. 甚至是 _你标记过的书影音_ , 包含你的评分、观看日期、评论、阅读状态等信息.
访问[Get Started/指导手册](https://obsidian-douban.wxp.hk/) 获取更多
[//]: # (访问[Get Started/指导手册]&#40;https://obsidian-douban.wanxuping.com/&#41; 获取更多 )
![background](./doc/background.png) ![background](./doc/background.png)
--- If you want some features or have any questions about this plugin, create issues or join the development is welcome. ---
关于当前的插件如果有任何疑问, 缺少想要的导入内容或者想要什么功能, 欢迎提issues或加入到开发当中. 关于当前的插件如果有任何疑问, 缺少想要的导入内容或者想要什么功能, 欢迎提issues或加入到开发当中.
如果觉得喜欢或对您有帮助,欢迎一键三连-点亮 ⭐Star
- [Bugs, Issues, & Feature Requests](https://github.com/Wanxp/obsidian-douban/issues) - [异常, 问题 & 新的想法](https://github.com/Wanxp/obsidian-douban/issues)
- [Development Roadmap](https://github.com/users/Wanxp/projects/1) - 阅读其它语言的介绍请点击 [English](README.en.md) | 简体中文
## Target/功能 ## 功能
- [ ] Sync Personal Movie/同步个人看过的电影 - ☑️ 导入电影、电视剧、书籍、音乐、游戏、日记
- [ ] Sync Personal Book/同步个人阅读过的书籍 - ☑️ 同步个人听过/看过的电影、电视剧、书籍、音乐、游戏
- [ ] Sync Personal Music/同步个人听过的音乐 - ☑️ 导入个人的评论,评论时间,阅读状态,个人评分
- [ ] Import Movie/导入电影 - ☑️ 支持保存封面至本地/图床
- [ ] Import Teleplay/导入电视剧 - ⬜ 支持图床自定义
- [ ] Import Book/导入书籍 - ☑️ 支持自定义参数
- [ ] Import Music/导入音乐 - ☑️ 支持移动端导入
- [ ] Import Note/导入日记 - ⬜ 支持使用AI大模型ChatGPT、Deepseek、Ollama分析导入
- [ ] Import Game/导入游戏
- [ ] Personal Comment/导入个人的评论,评论时间,阅读状态,个人评分 ## 效果
- [ ] Attachment Files/支持保存封面至本地 1. 结合Timeline插件 __构建个人观影时间线__,请参照[结合timeline插件实现时间线效果](./doc/Obsidian-Douban-TimeLine.md)
- [ ] Custom Variables/支持自定义参数 ![](./doc/img/obsidian-douban-time-preview-example.gif)
- [x] Broadcast/广播 <!--2. 结合DataView插件__构建个人电子书架书库数据__请参照[结合dateview插件实现个人书架效果](./doc/Obsidian-Douban-DataView.md))-->
2. 结合主题 __构建类豆瓣网页效果__,请参照[结合Blue Topaz实现网页效果](./doc/Obsidian-Douban-BlueTopaz.md)
![](./doc/background.png)
## 如何使用
### 搜索
使用方式: 输入<kbd>Ctrl</kbd> + <kbd>P</kbd>输入“豆瓣”或“Douban”选择搜索并使用
- 搜索数据并创建笔记
- 通过当前文件名搜索
- 通过输入文本搜索
![search_and_create](doc/img/search_and_create_note.gif)
### 同步
- 同步个人的观影、观剧、阅读、游戏、音乐记录
![Sync Data From Douban](doc/img/sync_data_from_douban.gif)
## 设置
- 设置豆瓣账号(可选,可使用少部分功能)
- 设置导入模板(可选,不设置的情况下使用默认模板)
- 设置导入路径(可选,不设置的情况下使用默认路径)
## Support Field/支持的字段 ## 支持的字段
(若有缺少想导入的字段, 欢迎提issues反馈) (若有缺少想导入的字段, 欢迎提issues反馈)
| 字段 | 电影 | 电视剧 | 书籍 | 音乐 | 日记 | 游戏 | 广播 | | 字段 | 电影 | 电视剧 | 书籍 | 音乐 | 日记 | 游戏 | 人物 |
| ---------------- | -------------------- | -------------------- | -------------------- | ------------------- | ------------------ | ------------------- | ---- | |------------------|------------------|-------------------|-------------------|---------------|----------------|---------------|-------|
| id | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | - | | id | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | id |
| title | 电影名称 | 电视剧名称 | 书名 | 音乐名 | 日记标题 | 游戏名称 | - | | title | 电影名称 | 电视剧名称 | 书名 | 音乐名 | 日记标题 | 游戏名称 | 姓名 |
| type | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 | - | | type | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 |
| score | 评分 | 评分 | 评分 | 评分 | 评分 | 评分 | - | | score | 评分 | 评分 | 评分 | 评分 | 评分 | 评分 | |
| image | 封面 | 封面 | 封面 | 封面 | 图片 | 封面 | - | | scoreStar | 评分⭐ | 评分⭐ | 评分⭐ | 评分⭐ | 评分⭐ | 评分⭐ | |
| url | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | - | | image | 封面 | 封面 | 封面 | 封面 | 图片 | 封面 | 照片 |
| desc | 简介 | 简介 | 内容简介 | 简介 | 简介 | 简介 | - | | imageData.url | 封面url | 封面url | 封面url | 封面url | 封面url | 封面url | 照片url |
| url | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 |
| desc | 简介 | 简介 | 内容简介 | 简介 | 简介 | 简介 | 简介 |
| publisher | - | - | 出版社 | 出版者 | 发布者 | 发行商 | - | | publisher | - | - | 出版社 | 出版者 | 发布者 | 发行商 | - |
| datePublished | 上映日期 | 上映日期 | 出版年 | 发行时间 | 发布时间 | 发行日期 | - | | datePublished | 上映日期 | 上映日期 | 出版年 | 发行时间 | 发布时间 | 发行日期 | - |
| yearPublished | 上映年份 | 上映年份 | 出版年份 | 发行年份 | 发布年份 | 发行年份 | - |
| genre | 类型 | 类型 | - | 流派 | - | 类型 | - | | genre | 类型 | 类型 | - | 流派 | - | 类型 | - |
| currentDate | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | | | currentDate | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | |
| currentTime | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | | | currentTime | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | |
@ -67,61 +92,21 @@ Import _Movie, Book, Music, Teleplay, Note, Game_ even _Your Personal Movie/Book
| myState | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想听/在听/听过 | - | 状态:想玩/在玩/玩过 | | | myState | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想听/在听/听过 | - | 状态:想玩/在玩/玩过 | |
| myComment | 我的评语 | 我的评语 | 我的评语 | 我的评语 | - | 我的评语 | | | myComment | 我的评语 | 我的评语 | 我的评语 | 我的评语 | - | 我的评语 | |
| myCollectionDate | 我标记的时间 | 我标记的时间 | 我标记的时间 | 我标记的时间 | - | 我标记的时间 | | | myCollectionDate | 我标记的时间 | 我标记的时间 | 我标记的时间 | 我标记的时间 | - | 我标记的时间 | |
| 扩展1 | director:导演 | director:导演 | author:原作者 | actor: 表演者 | author:作者 | aliases:别名 | | | 扩展1 | director:导演* | director:导演* | author:原作者 | actor: 表演者 | author:作者 | aliases:别名 | |
| 扩展2 | author:编剧 | author:编剧 | translator:译者 | albumType:专辑类型 | authorUrl:作者网址 | developer:开发商 | | | 扩展2 | author:编剧* | author:编剧* | translator:译者 | albumType:专辑类型 | authorUrl:作者网址 | developer:开发商 | |
| 扩展3 | actor:主演 | actor:主演 | isbn:isbn | medium:介质 | content:日记内容 | platform:平台 | | | 扩展3 | actor:主演* | actor:主演* | isbn:isbn | medium:介质 | content:日记内容 | platform:平台 | |
| 扩展4 | originalTitle:原作名 | originalTitle:原作名 | originalTitle:原作名 | records:唱片数 | | | | | 扩展4 | originalTitle:原作名 | originalTitle:原作名 | originalTitle:原作名 | records:唱片数 | | | |
| 扩展5 | | | subTitle:副标题 | barcode:条形码 | | | | | 扩展5 | country:国家 | country:国家 | subTitle:副标题 | barcode:条形码 | | | |
| 扩展6 | | | totalPage:页数 | | | | | | 扩展6 | language:语言 | language:语言 | totalPage:页数 | | | | |
| 扩展7 | | | series:丛书 | | | | | | 扩展7 | time:片长 | time:片长 | series:丛书 | | | | |
| 扩展8 | | | menu:目录 | | | | | | 扩展8 | aliases:又名* | aliases:又名* | menu:目录 | | | | |
| 扩展9 | | | price:定价 | | | | | | 扩展9 | IMDb | IMDb | price:定价 | | | | |
| 扩展7 | | | binding:装帧 | | | | | | 扩展7 | | episode:集数 | binding:装帧 | | | | |
| 扩展8 | | | producer: 出品方 | | | | | | 扩展8 | | | producer: 出品方 | | | | |
- 注: myTags, myRating, myState, myComment, myCollectionDate 参数均为在插件中登录后可用 - 注: myTags, myRating, myRatingStar:⭐ , myState, myComment, myCollectionDate 参数均为在插件中登录后可用
## How to use/如何使用
### Search/搜索
- Search Data And Create Note
搜索数据并创建笔记
![search_and_create](./doc/search_and_create_note.gif)
- Search Data By File Name
通过当前文件名搜索
![Search Movie By File Name](./doc/search_by_file_name.gif)
- Search Movie By Input Text
通过输入文本搜索
![Search Movie By Input Text](./doc/search_by_input.gif)
## Settings/设置
- Setting Example1(Custom Template)
设置案例1(自定义模板)
![Setting Example1](./doc/setting_zh.gif)
- Setting Example2(Other Settings)
设置案例2(其它配置)
![Setting Example2](./doc/setting_en.gif)
## How to install
### From Obsidian
1. Go to Obsidian plugin center
2. Search obsidian-douban
3. Click install
4. Enable plugin
### Manmel
1. Download `main.js`, `manifest.json`, `styles.css` from GitHub release page
2. Copy step1 downloaded file to your vault folder `/.obsidian/plugins/obsidian-douban/`
3. Enable plugin in Obsidian
---
## 如何安装 ## 如何安装
### 从Obsidian插件中心 ### 从Obsidian插件中心
1. 进入Obsidian插件中心 1. 进入Obsidian插件中心
@ -131,39 +116,65 @@ Import _Movie, Book, Music, Teleplay, Note, Game_ even _Your Personal Movie/Book
### 手动安装 ### 手动安装
1. 从Github release 页面下载 `main.js`, `manifest.json`, `styles.css` 1. 从[Github release](https://github.com/Wanxp/obsidian-douban/releases) 页面下载 `main.js`, `manifest.json`, `styles.css`
2. 将下载的文件复制到你的Obsidian文档根目录下的`/.obsidian/plugins/obsidian-douban`路径,若不存在则新建文件夹(注意.obsidian文件夹可能是个隐藏为文件夹) 2. 将下载的文件复制到你的Obsidian文档根目录下的`/.obsidian/plugins/obsidian-douban`路径,若不存在则新建文件夹(注意.obsidian文件夹可能是个隐藏为文件夹)
3. 在obsidian插件中心开启当前插件功能 3. 在obsidian插件中心开启当前插件功能
## How to Develop
1. Enter your test vault folder `/.obsidian/plugins/`
2. Clone Code
`git clone git@github.com:Wanxp/obsidian-douban.git`
3. Enter folder
`cd obsidian-douban`
4. Build
`npm run build`
5. Run and Watch code chang
`npm run dev`
6. Go to your Obsidian plugin center reload this plugin
7. Enjoy your develop
---
## 如何开发调试 ## 如何开发调试
### 开发
1. 进入你的Obsidian测试文档文件夹下的`/.obsidian/plugins/` 1. 进入你的Obsidian测试文档文件夹下的`/.obsidian/plugins/`
2. 克隆代码 2. 克隆代码
`git clone git@github.com:Wanxp/obsidian-douban.git` `git clone git@github.com:Wanxp/obsidian-douban.git`
3. 进入代码文件夹 3. 进入代码文件夹
`cd obsidian-douban` `cd obsidian-douban`
4. 构建 4. install
`npm install`
5. 构建
`npm run build` `npm run build`
5. 运行 6. 运行
`npm run dev` `npm run dev`
6. 进入Obsidian插件中心重新加载当前插件 7. 进入Obsidian插件中心重新加载当前插件
7. 享受开发吧 8. 享受开发吧
#### 文档
```shell
npm run docs:dev
```
## 支持开发者
如果觉得插件对你有帮助,欢迎请我喝杯咖啡,让我有更多的动力去维护和更新插件
![support_pay](./doc/img/support_pay_2.png)
## 交流社群
<img src="doc/img/obsidian-douban-qq-qr_code.svg" width="300px"> <img src="doc/img/wechat_group.png" width="245px">
[//]: # (<img src="doc/img/obsidian-douban-discord-qr_code.svg" width="300px"> )
## 免责声明 ## 免责声明
1. 本程序没有爬取任何书影音等内容,只供技术研究使用。没有侵犯书影音作者版权和豆瓣官方利益。如有任何侵权行为,请联系我删除。 1. 建议使用本插件前,一定要至少有一种方式备份你的数据,以防万一。
## Thanks 2. 本程序没有爬取任何书影音等内容,只供技术研究使用。没有侵犯书影音作者版权和豆瓣官方利益。如有任何侵权行为,请联系我删除。
3. 本程序仅供学习交流使用。
4. 虽然极力避免,但还是有可能纰漏,所以因使用插件造成的损失,由使用者本人承担。不同操作会有何种影响,请参照<a href="#impact">影响</a>
5. 使用或修改本插件,即视为同意上述免责声明。
## <span id="impact" >影响</span>
注意: 除了在同步书影音数据时勾选 `替换同名文档` 有可能会修改同路径同文档名的笔记外,其余操作均不会修改已有笔记。
| 操作 | 条件 | 影响 | 举例 |
|---------|------------------|---------------------------|-----------------------------------------------------------------------------------------------|
| 导入书影音数据 | 默认条件 | 新建一条名为所选条目的笔记 | 如搜索蝙蝠侠并选中导入,则会创建笔记 《蝙蝠侠》 |
| 导入书影音数据 | 已有同名笔记 | 无任何影响,提示已经存在同名笔记,不会修改已有笔记 | 如搜索蝙蝠侠并选中导入,但因存在同路径同名称笔记,则会不会创建笔记 |
| 导入书影音数据 | 配置 `笔记名称`值包含路径 | 若没有此路径则会创建对应文件名 | 如搜索蝙蝠侠并选中导入,配置`笔记名称`值为`/data/{{type}}/{{title}}`,则会创建文件夹`data/电影` |
| 导入书影音数据 | 配置 `保存图片附件`值为勾选 | 则会在`附件存放位置`指定位置保存封面图片 | 如搜索蝙蝠侠并选中导入,配置`附件存放位置`值为`assets`,则会在`assets`文件夹中保存封面文件`p462657443.jpg` |
| 同步书影音数据 | 以上所有 | 以上所有 | 以上所有 |
| 同步书影音数据 | `替换同名文档`值为勾选 | 已经存在 **同路径同文档名** ,直接覆盖 | 如已经存在在`data/Movie/蝙蝠侠.md`,配置`笔记名称`值为`/data/{{type}}/{{title}}`, 同步书影音记录时勾选 `替换同名文档`, 则`data/Movie/蝙蝠侠.md`会被替换成最新 |
[//]: # (### IDE支持)
[//]: # ([<image src="doc/img/jb_beam.svg"> </image>]&#40;https://www.jetbrains.com/?from=obsidian-douban&#41;)

@ -0,0 +1,11 @@
编写github action ,完成以下目标:
1. 当文件mainfest.json文件发生变更时才运行
2. 提供node18 环境
3. 执行npm install
4. 执行npm run build
5. 提取 package.json中的版本
6. 将当前master创建为版本的tag
7. 发布到github release 预发布版本,且版本的名称为当前版本
8. 发布的信息从commit中提取
9. 发布的内容为生成的main.js、mainfest.json、style.css 三个文件
10. 输出内容: 发布预发布版本{版本}正常

15
doc/.gitignore vendored Normal file

@ -0,0 +1,15 @@
# Not sure what a .gitignore is?
# See: https://git-scm.com/docs/gitignore
# These are directly copied from Jekyll's first-party docs on `.gitignore` files:
# https://jekyllrb.com/tutorials/using-jekyll-with-bundler/#commit-to-source-control
# Ignore the default location of the built site, and caches and metadata generated by Jekyll
_site/
.sass-cache/
.jekyll-cache/
.jekyll-metadata
# Ignore folders generated by Bundler
.bundle/
vendor/

56
doc/.vitepress/config.mts Normal file

@ -0,0 +1,56 @@
import { defineConfig } from 'vitepress'
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: "Obsidian Douban",
description: "Plugin for obsidian to manage your douban data",
themeConfig: {
lang: 'zh-CN',
search: {
provider: 'local'
},
// https://vitepress.dev/reference/default-theme-config
logo: '/obsidian-douban-logo.png',
nav: [
{ text: '首页', link: '/' },
{ text: '特殊效果', items: [
{ text: '时间线效果', link: '/Obsidian-Douban-TimeLine' },
{ text: '类网页效果', link: '/Obsidian-Douban-BlueTopaz' },
{ text: '书架效果', link: 'Obsidian-Douban-DataView-Jump' }
] },
{ text: '作者', link: 'https://wxp.hk' },
],
sidebar: [
{
text: '如何安装', link: '/10_install'
},
{ text: '使用说明', link: '/20_howtouse_10_detail' },
{ text: '登录方式', link: '/20_howtouse_25_setting_login_douban_cookie' },
{ text: '图床配置', link: '/20_howtouse_30_picturebed' },
{ text: '功能支持', link: '/30_function_10' },
{ text: '可用参数', link: '/30_function_20_support_variables' },
{ text: '时间线效果', link: '/Obsidian-Douban-TimeLine' },
{ text: '类网页效果', link: '/Obsidian-Douban-BlueTopaz' },
{ text: '书架效果', link: 'Obsidian-Douban-DataView-Jump' },
{ text: '数据影响', link: '/80_others_20_effect' },
{ text: '免责声明', link: '/80_others_disclaimer' },
{ text: '开发调试', link: '/70_develop' },
{ text: '反馈建议', link: '/97_issues' },
{ text: '支持作者', link: '/99_support' },
],
socialLinks: [
{ icon: 'github', link: 'https://github.com/Wanxp/obsidian-douban' },
// { icon: 'blog', link: 'https://github.com/Wanxp/obsidian-douban' }
],
lastUpdated: {
text: '最后更新于',
formatOptions: {
dateStyle: 'full',
timeStyle: 'medium'
}
}
}
})

@ -0,0 +1,15 @@
:root {
--vp-c-brand-1: #646cff;
--vp-c-brand-2: #747bff;
--vp-home-hero-name-color: transparent;
--vp-home-hero-name-background: -webkit-linear-gradient(120deg, #34fe48, #bd34fe);
--vp-home-hero-image-background-image: linear-gradient( 135deg, #34fe48 10%, #bd34fe 100%);
--vp-home-hero-image-filter: blur(80px);
/*--vp-home-hero-image-background-image: linear-gradient(*/
/* -45deg,*/
/* #34fe48 50%,*/
/* #bd34fe 50%*/
/*);*/
/*--vp-home-hero-image-filter: blur(44px);*/
}

@ -0,0 +1,5 @@
import DefaultTheme from 'vitepress/theme'
import './custom.css'
export default DefaultTheme

16
doc/10_install.md Normal file

@ -0,0 +1,16 @@
---
title: 如何安装
nav_order: 200
---
# 如何安装
## 从Obsidian插件中心
1. 进入Obsidian插件中心
2. 搜索obsidian-douban
3. 安装
4. 开启插件
## 手动安装
1. 从[Github release](https://github.com/Wanxp/obsidian-douban/releases) 页面下载 `main.js`, `manifest.json`, `styles.css`
2. 将下载的文件复制到你的Obsidian文档根目录下的`/.obsidian/plugins/obsidian-douban`路径,若不存在则新建文件夹(注意.obsidian文件夹可能是个隐藏为文件夹)
3. 在obsidian插件中心开启当前插件功能

6
doc/20_howtouse.md Normal file

@ -0,0 +1,6 @@
---
title: 如何使用
layout: default
nav_order: 300
has_children: true
---

@ -0,0 +1,17 @@
---
title: 使用说明
nav_order: 300
parent: 如何使用
---
# 如何使用
# 搜索
使用方式: 输入<kbd>Ctrl</kbd> + <kbd>P</kbd>输入“豆瓣”或“Douban”选择搜索并使用
- 搜索数据并创建笔记
- 通过当前文件名搜索
- 通过输入文本搜索
![search_and_create](img/search_and_create_note.gif)
# 同步
- 同步个人的观影、观剧、阅读、游戏、音乐记录
![Sync Data From Douban](img/sync_data_from_douban.gif)

@ -0,0 +1,11 @@
---
title: 设置
nav_order: 350
parent: 如何使用
---
# 设置
- 设置豆瓣账号(可选,可使用少部分功能)
- 设置导入模板(可选,不设置的情况下使用默认模板)
- 设置导入路径(可选,不设置的情况下使用默认路径)

@ -0,0 +1,32 @@
---
title: Cookie登录Douban
nav_order: 350
parent: 如何使用
---
# 登录方式
Obsidian-Douban插件提供了两种登录方式扫码登录和Cookie登录。扫码登录是推荐的方式但如果扫码登录失败可以使用Cookie登录。
## 扫码登录
扫码登录是Obsidian-Douban插件的默认登录方式适用于大多数用户。扫码登录的步骤如下
1. 在Obsidian-Douban插件设置中点击`登录按钮`
2. 弹出扫码登录窗口
3. 使用手机或其他设备的豆瓣APP 扫描二维码
4. 在手机上确认登录
5. 登录成功后Obsidian-Douban插件会自动获取您的豆瓣账号信息
## Cookie登录Douban
此方式仅在Obsidian-Douban中点击`登录按钮`,弹窗后,扫码登录失败的用户
### 操作
1. 打开浏览器(此处默认为您使用的浏览器为Chrome或Chromium衍生浏览器)
2. 访问[豆瓣网站](https://www.douban.com/)
3. 在豆瓣网站中 登录豆瓣
4. 再次访问`https://douban.com`
5. 打开浏览器开发者工具(按键 ctrl + shift +i 或者 F12 或者 右键选择 检查)
6. 选择开发者工具中的`网络`(Network)页签
7. 在出现的页签中选择`全部`(All)
8. 在出现的列表中网上翻找到最上面一条`www.douban.com`, 并点击
9. 点击后出现的`请求头`(Headers) 栏目,找到`请求头`(Request Headers)
10. 找到请求头中的Cookie选中并复制右边的值
![](./img/obsidian-douban-setting-cookie.png)
11. 然后回到Obsidian-Douban插件设置中点击Cookie登录
12. 将浏览器中复制的Cookie值粘贴到弹窗中的输入框中
13. 点击确认

@ -0,0 +1,21 @@
---
title: 图床
nav_order: 380
parent: 如何使用
---
# 图床
## PicGo
### 设置步骤
1. 安装并下载PicGo图床软件
2. 设置PicGo图床
3. 由于Obsidian-Douban是通过剪贴板上传图片的需要在PicGo设置中开启剪贴板上传
4. 需要设置Server开启并设置 端口36677
5. 设置完成之后可以尝试点击PicGo主界面的`剪贴板上传`按钮,验证是否可以上传图片
6. 若在Obsidian-Douban设置中使用PicGo上传图片至图床则每次导入书影音数据前需要保证提前打开了PicGo软件
### 注意事项
Obsidian-Douban插件使用PicGo上传图片至图床仅在Linux系统下测试通过其他系统未测试其它系统有问题欢迎及时反馈
#### Linux
1. x11图形界面下还需要安装xclip软件否则无法使用剪贴板上传图片
2. wayland图形界面下, 还需要安装wl-clipboard软件否则无法使用剪贴板上传图片
3. 若无法上传图片可尝试开启PicGo软件设置中的`使用内置剪贴板上传`选项

6
doc/30_function.md Normal file

@ -0,0 +1,6 @@
---
title: 功能
layout: default
nav_order: 400
has_children: true
---

14
doc/30_function_10.md Normal file

@ -0,0 +1,14 @@
---
title: 基础功能
nav_order: 400
parent: 功能
---
# 功能
- ☑️ 导入电影、电视剧、书籍、音乐、游戏、日记
- ☑️ 同步个人听过/看过的电影、电视剧、书籍、音乐、游戏
- ☑️ 导入个人的评论,评论时间,阅读状态,个人评分
- ☑️ 支持保存封面至本地/图床
- ⬜ 支持图床自定义
- ☑️ 支持自定义参数
- ☑️ 支持移动端导入
- ⬜ 支持使用AI大模型ChatGPT、Deepseek、Ollama分析导入

@ -0,0 +1,42 @@
---
title: 支持的参数
nav_order: 500
parent: 功能
---
# 支持的字段
(若有缺少想导入的字段, 欢迎提issues反馈)
| 字段 | 电影 | 电视剧 | 书籍 | 音乐 | 日记 | 游戏 | 人物 |
|------------------|------------------|-------------------|-------------------|---------------|----------------|---------------|-------|
| id | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | id |
| title | 电影名称 | 电视剧名称 | 书名 | 音乐名 | 日记标题 | 游戏名称 | 姓名 |
| type | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 |
| score | 评分 | 评分 | 评分 | 评分 | 评分 | 评分 | |
| scoreStar | 评分⭐ | 评分⭐ | 评分⭐ | 评分⭐ | 评分⭐ | 评分⭐ | |
| image | 封面 | 封面 | 封面 | 封面 | 图片 | 封面 | 照片 |
| imageData.url | 封面url | 封面url | 封面url | 封面url | 封面url | 封面url | 照片url |
| url | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 |
| desc | 简介 | 简介 | 内容简介 | 简介 | 简介 | 简介 | 简介 |
| publisher | - | - | 出版社 | 出版者 | 发布者 | 发行商 | - |
| datePublished | 上映日期 | 上映日期 | 出版年 | 发行时间 | 发布时间 | 发行日期 | - |
| yearPublished | 上映年份 | 上映年份 | 出版年份 | 发行年份 | 发布年份 | 发行年份 | - |
| genre | 类型 | 类型 | - | 流派 | - | 类型 | - |
| currentDate | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | |
| currentTime | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | |
| myTags | 我标记的标签 | 我标记的标签 | 我标记的标签 | 我标记的标签 | - | 我标记的标签 | |
| myRating | 我的评分 | 我的评分 | 我的评分 | 我的评分 | - | 我的评分 |
| myState | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想听/在听/听过 | - | 状态:想玩/在玩/玩过 | |
| myComment | 我的评语 | 我的评语 | 我的评语 | 我的评语 | - | 我的评语 | |
| myCollectionDate | 我标记的时间 | 我标记的时间 | 我标记的时间 | 我标记的时间 | - | 我标记的时间 | |
| 扩展1 | director:导演* | director:导演* | author:原作者 | actor: 表演者 | author:作者 | aliases:别名 | |
| 扩展2 | author:编剧* | author:编剧* | translator:译者 | albumType:专辑类型 | authorUrl:作者网址 | developer:开发商 | |
| 扩展3 | actor:主演* | actor:主演* | isbn:isbn | medium:介质 | content:日记内容 | platform:平台 | |
| 扩展4 | originalTitle:原作名 | originalTitle:原作名 | originalTitle:原作名 | records:唱片数 | | | |
| 扩展5 | country:国家 | country:国家 | subTitle:副标题 | barcode:条形码 | | | |
| 扩展6 | language:语言 | language:语言 | totalPage:页数 | | | | |
| 扩展7 | time:片长 | time:片长 | series:丛书 | | | | |
| 扩展8 | aliases:又名* | aliases:又名* | menu:目录 | | | | |
| 扩展9 | IMDb | IMDb | price:定价 | | | | |
| 扩展7 | | episode:集数 | binding:装帧 | | | | |
| 扩展8 | | | producer: 出品方 | | | | |

6
doc/60_special_use.md Normal file

@ -0,0 +1,6 @@
---
title: 特殊效果
layout: default
nav_order: 450
has_children: true
---

12
doc/60_special_use_10.md Normal file

@ -0,0 +1,12 @@
---
title: 效果介绍
nav_order: 450
parent: 特殊效果
---
# 效果
1. 结合Timeline插件 __构建个人观影时间线__,请参照[结合timeline插件实现时间线效果](Obsidian-Douban-TimeLine)
![](./img/obsidian-douban-time-preview-example.gif)
<!--2. 结合DataView插件__构建个人电子书架书库数据__请参照[结合dateview插件实现个人书架效果](Obsidian-Douban-DataView.md))-->
2. 结合主题 __构建类豆瓣网页效果__,请参照[结合Blue Topaz实现网页效果](Obsidian-Douban-BlueTopaz)
![](./background.png)

21
doc/70_develop.md Normal file

@ -0,0 +1,21 @@
---
title: 开发
nav_order: 700
---
# 如何开发调试
1. 进入你的Obsidian测试文档文件夹下的`/.obsidian/plugins/`
2. 克隆代码
`git clone git@github.com:Wanxp/obsidian-douban.git`
3. 进入代码文件夹
`cd obsidian-douban`
4. install
`npm install`
5. 构建
`npm run build`
6. 运行
`npm run dev`
7. 进入Obsidian插件中心重新加载当前插件
8. 享受开发吧

7
doc/80_others.md Normal file

@ -0,0 +1,7 @@
---
title: 其它
layout: default
nav_order: 750
has_children: true
---

@ -0,0 +1,17 @@
---
title: 数据影响
nav_order: 800
parent: 其它
---
# 数据影响
注意: 除了在同步书影音数据时勾选 `替换同名文档` 有可能会修改同路径同文档名的笔记外,其余操作均不会修改已有笔记。
| 操作 | 条件 | 影响 | 举例 |
|---------|------------------|---------------------------|-----------------------------------------------------------------------------------------------|
| 导入书影音数据 | 默认条件 | 新建一条名为所选条目的笔记 | 如搜索蝙蝠侠并选中导入,则会创建笔记 《蝙蝠侠》 |
| 导入书影音数据 | 已有同名笔记 | 无任何影响,提示已经存在同名笔记,不会修改已有笔记 | 如搜索蝙蝠侠并选中导入,但因存在同路径同名称笔记,则会不会创建笔记 |
| 导入书影音数据 | 配置 `笔记名称`值包含路径 | 若没有此路径则会创建对应文件名 | 如搜索蝙蝠侠并选中导入,配置`笔记名称`值为`/data/{{type}}/{{title}}`,则会创建文件夹`data/电影` |
| 导入书影音数据 | 配置 `保存图片附件`值为勾选 | 则会在`附件存放位置`指定位置保存封面图片 | 如搜索蝙蝠侠并选中导入,配置`附件存放位置`值为`assets`,则会在`assets`文件夹中保存封面文件`p462657443.jpg` |
| 同步书影音数据 | 以上所有 | 以上所有 | 以上所有 |
| 同步书影音数据 | `替换同名文档`值为勾选 | 已经存在 **同路径同文档名** ,直接覆盖 | 如已经存在在`data/Movie/蝙蝠侠.md`,配置`笔记名称`值为`/data/{{type}}/{{title}}`, 同步书影音记录时勾选 `替换同名文档`, 则`data/Movie/蝙蝠侠.md`会被替换成最新 |

@ -0,0 +1,8 @@
---
title: 鸣谢
nav_order: 810
parent: 其它
---
# 鸣谢
## IDE支持
[<image src="img/jb_beam.svg"> </image>](https://www.jetbrains.com/?from=obsidian-douban)

@ -0,0 +1,12 @@
---
title: 免责声明
nav_order: 820
parent: 其它
---
# 免责声明
1. 建议使用本插件前,一定要至少有一种方式备份你的数据,以防万一。
2. 本程序没有爬取任何书影音等内容,只供技术研究使用。没有侵犯书影音作者版权和豆瓣官方利益。如有任何侵权行为,请联系我删除。
3. 本程序仅供学习交流使用。
4. 虽然极力避免,但还是有可能纰漏,所以因使用插件造成的损失,由使用者本人承担。不同操作会有何种影响,请参照<a href="#impact">影响</a>
5. 使用或修改本插件,即视为同意上述免责声明。

9
doc/97_issues.md Normal file

@ -0,0 +1,9 @@
---
title: 反馈与建议
nav_order: 950
---
# 反馈与建议
如果你有任何问题或建议,欢迎在提交[Issues](https://github.com/Wanxp/obsidian-douban/issues)

17
doc/99_support.md Normal file

@ -0,0 +1,17 @@
---
title: 支持
nav_order: 1000
---
# 支持
愿世界充满爱与和平!
如果觉得喜欢或对您有帮助,欢迎请我喝杯咖啡,让我有更多的动力去维护和更新插件
![support_pay](./img/support_pay_2.png)
## 交流社群
<img src="/img/obsidian-douban-qq-qr_code.svg" width="300px" style="display: inline-block;"><img src="/img/wechat_group.png" width="245px" style="display: inline-block;">
或者[邮件联系我](mailto:977741432@qq.com)

10
doc/Gemfile Normal file

@ -0,0 +1,10 @@
source 'https://rubygems.org'
gem "jekyll" # installed by `gem jekyll`
# gem "webrick" # required when using Ruby >= 3 and Jekyll <= 4.2.2
gem "just-the-docs" # pinned to the current release
# gem "just-the-docs" # always download the latest release
gem 'json'

87
doc/Gemfile.lock Normal file

@ -0,0 +1,87 @@
GEM
remote: https://rubygems.org/
specs:
addressable (2.8.6)
public_suffix (>= 2.0.2, < 6.0)
colorator (1.1.0)
concurrent-ruby (1.2.3)
em-websocket (0.5.3)
eventmachine (>= 0.12.9)
http_parser.rb (~> 0)
eventmachine (1.2.7)
ffi (1.16.3)
forwardable-extended (2.6.0)
google-protobuf (3.25.3-arm64-darwin)
google-protobuf (3.25.3-x86_64-linux)
http_parser.rb (0.8.0)
i18n (1.14.4)
concurrent-ruby (~> 1.0)
jekyll (4.3.3)
addressable (~> 2.4)
colorator (~> 1.0)
em-websocket (~> 0.5)
i18n (~> 1.0)
jekyll-sass-converter (>= 2.0, < 4.0)
jekyll-watch (~> 2.0)
kramdown (~> 2.3, >= 2.3.1)
kramdown-parser-gfm (~> 1.0)
liquid (~> 4.0)
mercenary (>= 0.3.6, < 0.5)
pathutil (~> 0.9)
rouge (>= 3.0, < 5.0)
safe_yaml (~> 1.0)
terminal-table (>= 1.8, < 4.0)
webrick (~> 1.7)
jekyll-include-cache (0.2.1)
jekyll (>= 3.7, < 5.0)
jekyll-sass-converter (3.0.0)
sass-embedded (~> 1.54)
jekyll-seo-tag (2.8.0)
jekyll (>= 3.8, < 5.0)
jekyll-watch (2.2.1)
listen (~> 3.0)
json (2.7.2)
just-the-docs (0.8.2)
jekyll (>= 3.8.5)
jekyll-include-cache
jekyll-seo-tag (>= 2.0)
rake (>= 12.3.1)
kramdown (2.4.0)
rexml
kramdown-parser-gfm (1.1.0)
kramdown (~> 2.0)
liquid (4.0.4)
listen (3.9.0)
rb-fsevent (~> 0.10, >= 0.10.3)
rb-inotify (~> 0.9, >= 0.9.10)
mercenary (0.4.0)
pathutil (0.16.2)
forwardable-extended (~> 2.6)
public_suffix (5.0.5)
rake (13.2.1)
rb-fsevent (0.11.2)
rb-inotify (0.10.1)
ffi (~> 1.0)
rexml (3.2.6)
rouge (4.2.1)
safe_yaml (1.0.5)
sass-embedded (1.69.5-arm64-darwin)
google-protobuf (~> 3.23)
sass-embedded (1.69.5-x86_64-linux-gnu)
google-protobuf (~> 3.23)
terminal-table (3.0.2)
unicode-display_width (>= 1.1.1, < 3)
unicode-display_width (2.5.0)
webrick (1.8.1)
PLATFORMS
arm64-darwin
x86_64-linux-gnu
DEPENDENCIES
jekyll (~> 4.3.3)
json
just-the-docs (= 0.8.2)
BUNDLED WITH
2.5.9

21
doc/LICENSE Normal file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 just-the-docs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -0,0 +1,127 @@
---
title: 类豆瓣网页显示
nav_order: 455
parent: 特殊效果
render_with_liquid: false
---
## 效果如下
![](./background.png)
## 适用人群
1. 在豆瓣有标记/评论/评分的习惯的人
比如看完电影,会在豆瓣进行评分或评论。或者阅读完的书籍,进行评分或评论。支持包含:电影、书籍、电视剧、音乐、游戏
## 实现步骤
1. 安装[Blue Topaz](https://github.com/PKM-er/Blue-Topaz_Obsidian-css)插件, 可在Obsidian主题搜索中找到 `Blue Topaz`
2. 安装[Obsidian-Douban](https://github.com/Wanxp/obsidian-douban)插件(本插件)
3. 在Obsidian-Douban插件配置中登录Douban
4. 配置需要的模板文件, 在模板中 ==增加== 以下内容,如下所示
````markdown
---
# {{title}}
<div style="text-align: center;">{{originalTitle}}</div>
<div style="text-align: center;">{{scoreStar}}</div>
---
> [!bookinfo|noicon]+ 🗒️ **简介**
> ![bookcover|250]( {{image}})
>
| 属性 | 内容 |
|:-------- |:------------------------ |
| 笔记 | [[摘录:{{title}}]] |
| 作者 | {{author(ArrayType1)}} |
| 译者 | {{translator(ArrayType1)}} |
| 来源 | [ {{title}} ]( {{url}} ) |
| 网站评分 | {{score}} |
| 出版发行 | {{publisher}} |
| 原作名 | {{originalTitle}} |
| 出版年份 | {{yearPublished}} |
> [!note]- 书籍简介\
> {{desc}}
---
### 评论
{{myComment}}
````
5. 设置模板为上面的模板
6. 增加数组输出形式
进入插件设置界面,找到[数组输出]
## 模板参考
### 书籍
````markdown
---
doubanId: {{id}}
title: {{title}}
subTitle: {{subTitle}}
originalTitle: {{originalTitle}}
series: {{series}}
type: {{type}}
author: {{author}}
score: {{score}}
scoreStar: {{scoreStar}}
myRating: {{myRating}}
datePublished: {{datePublished}}
translator: {{translator}}
publisher: {{publisher}}
producer: {{producer}}
isbn: {{isbn}}
url: {{url}}
totalPage: {{totalPage}}
price: {{price}}
tags: {{myTags}}
state: {{myState}}
binding: {{binding}}
createTime: {{currentDate}} {{currentTime}}
collectionDate: {{myCollectionDate}}
desc: {{desc}}
---
# {{title}}
<div style="text-align: center;">{{originalTitle}}</div>
<div style="text-align: center;">{{scoreStar}}</div>
---
> [!bookinfo|noicon]+ 🗒️ **简介**
> ![bookcover|250]( {{image}})
>
| 属性 | 内容 |
|:-------- |:------------------------ |
| 笔记 | [[摘录:{{title}}]] |
| 作者 | {{author(ArrayType1)}} |
| 译者 | {{translator(ArrayType1)}} |
| 来源 | [ {{title}} ]( {{url}} ) |
| 网站评分 | {{score}} |
| 出版发行 | {{publisher}} |
| 原作名 | {{originalTitle}} |
| 出版年份 | {{yearPublished}} |
> [!note]- 书籍简介\
> {{desc}}
---
### 评论
{{myComment}}
### 目录
{{menu}}
````
## 电影、电视剧、音乐、游戏
请参照书籍模板
## 更多
此效果来自热心用户的分享,感谢

@ -0,0 +1,3 @@
## 书架效果
点击以下链接跳转至少数派
[使用Obsidian打造个人图书馆](https://sspai.com/post/85574)

@ -0,0 +1,69 @@
## 效果如下
![](./img/obsidian-douban-time-preview-example.gif)
## 适用人群
1. 在豆瓣有标记/评论/评分的习惯的人
比如看完电影,会在豆瓣进行评分或评论。或者阅读完的书籍,进行评分或评论。支持包含:电影、书籍、电视剧、音乐、游戏
## 实现步骤
1. 安装[obsidian-dataview](https://github.com/blacksmithgu/obsidian-dataview)插件
2. 安装[Obsidian-Douban](https://github.com/Wanxp/obsidian-douban)插件(本插件)
3. 在Obsidian-Douban插件配置中登录Douban
4. 配置同步需要的模板 电影/书籍的模板中的frontmatter在frontmatter中 **增加** 特定tags根据自己的需要指定用于需要过滤成为timeline的笔记如增加tags`书籍`
````markdown
---
tags: 书籍
---
````
5. 同时,在电影/书籍... 模板中的 **最后增加** timeline插件需要的html标签如下:
```
```
6. 选择上述模板导入 电影/书籍...操作方式是打开obsidian命令窗口输入豆瓣找到导入功能在导入界面配置 选择模板进行导入
7. 导入需要一定时间每条内容导入需要15-30s左右所有有导入完成后会有导入汇总
8. 导入完成后新建一个笔记笔记内容加入DataView的代码块指定搜索上面指定的tags的内容如`书籍`,代码块如下:
````markdown
```dataview
table file.name
```
````
9. 预览这个笔记就能看出已经出现了时间线
## 模板参考
### 电影
````markdown
---
doubanId: {{id}}
title: {{title}}
type: {{type}}
score: {{score}}
myRate: {{myRate}}
originalTitle: {{originalTitle}}
genre: {{genre}}
datePublished: {{datePublished}}
director: {{director}}
actor: {{actor}}
author: {{author}}
tags: {{type}}, 我看过的电影, {{myTags}}
state: {{myState}}
url: {{url}}
coverUrl: {{imageData.url}}
createTime: {{currentDate}} {{currentTime}}
collectionDate: {{myCollectionDate}}
desc: {{desc}}
---
![image]({{image}})
Comment:
---
{{myComment}}
<span class='ob-timelines' data-date='{{myCollectionDate}}'
data-title='{{title}}' data-img='{{image}}'
data-class = "custom-my-movie-time-line">{{myComment}} |简介: {{desc}}
</span>
````
### 书籍、电视剧、音乐、游戏
请参照电影模板
## 更多
参照讨论 [结合timeline插件的妙用](https://github.com/Wanxp/obsidian-douban/issues/19#issuecomment-1428307130)

@ -0,0 +1,93 @@
---
title: 看剧时间线
nav_order: 456
parent: 特殊效果
render_with_liquid: false
---
## 效果如下
![](./img/obsidian-douban-time-preview-example.gif)
## 适用人群
1. 在豆瓣有标记/评论/评分的习惯的人
比如看完电影,会在豆瓣进行评分或评论。或者阅读完的书籍,进行评分或评论。支持包含:电影、书籍、电视剧、音乐、游戏
## 实现步骤
1. 安装[Timelines](https://github.com/Darakah/obsidian-timelines)插件
2. 安装[Obsidian-Douban](https://github.com/Wanxp/obsidian-douban)插件(本插件)
3. 在Obsidian-Douban插件配置中登录Douban
4. 配置同步需要的模板 电影/书籍的模板中的frontmatter在frontmatter中 **增加** 特定tags根据自己的需要指定用于需要过滤成为timeline的笔记如增加tags`我看过的电影`
````markdown
---
tags: 我看过的电影
---
````
5. 同时,在电影/书籍... 模板中的 **最后增加** timeline插件需要的html标签如下:
```html
<span class='ob-timelines' data-date='{{myCollectionDate}}'
data-title='{{title}}' data-img='{{image}}'
data-class = "custom-my-movie-time-line">{{myComment}} |简介: {{desc}}
</span>
```
6. 选择上述模板导入 电影/书籍...操作方式是打开obsidian命令窗口输入豆瓣找到导入功能在导入界面配置 选择模板进行导入
7. 导入需要一定时间每条内容导入需要15-30s左右所有有导入完成后会有导入汇总
8. 导入完成后新建一个笔记笔记内容加入timeline的代码块代码块的内容就是你上面指定的tags的内容如`我看过的电影`,代码块如下:
````markdown
```timeline
我看过的电影
```
````
9. 预览这个笔记就能看出已经出现了时间线
## 模板参考
### 电影
````markdown
---
doubanId: {{id}}
title: {{title}}
type: {{type}}
score: {{score}}
myRate: {{myRate}}
originalTitle: {{originalTitle}}
genre: {{genre}}
datePublished: {{datePublished}}
director: {{director}}
actor: {{actor}}
author: {{author}}
tags: {{type}}, 我看过的电影, {{myTags}}
state: {{myState}}
url: {{url}}
coverUrl: {{imageData.url}}
createTime: {{currentDate}} {{currentTime}}
collectionDate: {{myCollectionDate}}
desc: {{desc}}
---
![image]({{image}})
Comment:
---
{{myComment}}
<span class='ob-timelines' data-date='{{myCollectionDate}}'
data-title='{{title}}' data-img='{{image}}'
data-class = "custom-my-movie-time-line">{{myComment}} |简介: {{desc}}
</span>
````
## 书籍、电视剧、音乐、游戏
请参照电影模板
## 更多
此效果来自热心用户的分享,感谢[![](https://img.shields.io/badge/GitHub-eryajf-blue)](https://github.com/eryajf)
参照讨论 [结合timeline插件的妙用](https://github.com/Wanxp/obsidian-douban/issues/19#issuecomment-1428307130)

10
doc/_config.yml Normal file

@ -0,0 +1,10 @@
title: Obsidian-Douban
description: This is a plugin that can import movies/books/musics/notes/games info data from Douban for Obsidian .
theme: just-the-docs
url: https://wanxp.github.io/obsidian-douban
aux_links: # remove if you don't want this link to appear on your pages
Obsidian-Douban on Github: https://github.com/Wanxp/obsidian-douban
search:
focus_shortcut_key: 'k'

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 MiB

After

Width:  |  Height:  |  Size: 235 KiB

1
doc/img/jb_beam.svg Normal file

@ -0,0 +1 @@
<svg height="180" viewBox="0 0 180 180" width="180" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><linearGradient id="a" gradientUnits="userSpaceOnUse" x1="32.64" x2="82.77" y1="61.16" y2="85.54"><stop offset=".21" stop-color="#fe2857"/><stop offset="1" stop-color="#293896"/></linearGradient><linearGradient id="b" gradientUnits="userSpaceOnUse" x1="17.38" x2="82.95" y1="69.86" y2="21.23"><stop offset="0" stop-color="#fe2857"/><stop offset=".01" stop-color="#fe2857"/><stop offset=".86" stop-color="#ff318c"/></linearGradient><linearGradient id="c" gradientUnits="userSpaceOnUse" x1="74.17" x2="160.27" y1="21.58" y2="99.76"><stop offset=".02" stop-color="#ff318c"/><stop offset=".21" stop-color="#fe2857"/><stop offset=".86" stop-color="#fdb60d"/></linearGradient><linearGradient id="d" gradientUnits="userSpaceOnUse" x1="155.46" x2="55.07" y1="89.8" y2="158.9"><stop offset=".01" stop-color="#fdb60d"/><stop offset=".86" stop-color="#fcf84a"/></linearGradient><path d="m81.56 83.71-41.35-35a15 15 0 1 0 -14.47 25.7h.15l.39.12 52.16 15.89a3.53 3.53 0 0 0 1.18.21 3.73 3.73 0 0 0 1.93-6.91z" fill="url(#a)"/><path d="m89.85 25.93a10.89 10.89 0 0 0 -16.85-9.18l-50.5 30.66a15 15 0 1 0 17.9 24l45.27-36.89.36-.3a10.93 10.93 0 0 0 3.82-8.29z" fill="url(#b)"/><path d="m163.29 92-76.62-73.79a10.91 10.91 0 1 0 -14.81 16l.14.12 81.4 68.58a7.36 7.36 0 0 0 12.09-5.65 7.39 7.39 0 0 0 -2.2-5.26z" fill="url(#c)"/><path d="m165.5 97.29a7.35 7.35 0 0 0 -11.67-6l-92.71 45.3a15 15 0 1 0 15.48 25.59l85.73-58.84a7.35 7.35 0 0 0 3.17-6.05z" fill="url(#d)"/><path d="m60 60h60v60h-60z"/><g fill="#fff"><path d="m66.53 108.75h22.5v3.75h-22.5z"/><path d="m65.59 75.47 1.67-1.58a1.88 1.88 0 0 0 1.47.87c.64 0 1.06-.45 1.06-1.32v-5.92h2.58v5.94a3.44 3.44 0 0 1 -.92 2.63 3.52 3.52 0 0 1 -2.57 1 3.84 3.84 0 0 1 -3.29-1.62z"/><path d="m73.53 67.52h7.53v2.19h-5v1.43h4.49v2h-4.45v1.49h5v2.2h-7.6z"/><path d="m84.73 69.79h-2.8v-2.27h8.21v2.27h-2.81v7.09h-2.6z"/><path d="m66.63 80.58h4.42a3.47 3.47 0 0 1 2.55.83 2.09 2.09 0 0 1 .61 1.52 2.18 2.18 0 0 1 -1.45 2.09 2.27 2.27 0 0 1 1.86 2.29c0 1.69-1.31 2.69-3.55 2.69h-4.44zm5 2.89c0-.52-.42-.8-1.18-.8h-1.29v1.64h1.25c.78 0 1.24-.27 1.24-.81zm-.9 2.66h-1.57v1.73h1.62c.8 0 1.24-.31 1.24-.86-.02-.53-.4-.87-1.27-.87z"/><path d="m75.45 80.58h4.15a4.14 4.14 0 0 1 3.05 1 2.92 2.92 0 0 1 .83 2.18 3 3 0 0 1 -1.93 2.89l2.24 3.35h-3l-1.89-2.84h-.87v2.84h-2.6zm4 4.5c.87 0 1.4-.43 1.4-1.12 0-.75-.55-1.13-1.41-1.13h-1.39v2.27z"/><path d="m87.09 80.51h2.5l4 9.44h-2.79l-.67-1.69h-3.63l-.67 1.74h-2.71zm2.28 5.73-1.05-2.65-1.06 2.65z"/><path d="m94 80.55h2.6v9.37h-2.6z"/><path d="m97.56 80.55h2.44l3.37 5v-5h2.57v9.37h-2.27l-3.53-5.14v5.14h-2.58z"/><path d="m106.37 88.53 1.44-1.73a4.86 4.86 0 0 0 3 1.13c.71 0 1.08-.25 1.08-.65 0-.41-.3-.61-1.59-.91-2-.46-3.53-1-3.53-2.93 0-1.74 1.38-3 3.63-3a5.88 5.88 0 0 1 3.85 1.25l-1.25 1.78a4.56 4.56 0 0 0 -2.62-.92c-.63 0-.94.25-.94.6 0 .43.32.62 1.63.91 2.15.47 3.48 1.17 3.48 2.92 0 1.91-1.51 3-3.78 3a6.56 6.56 0 0 1 -4.4-1.45z"/></g><path d="m0 0h180v180h-180z" fill="none"/></svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 356 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 492 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 MiB

BIN
doc/img/ps/wechat.psd Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

BIN
doc/img/support_pay_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 494 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

BIN
doc/img/wanxp-logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

BIN
doc/img/wechat_group.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

34
doc/index.md Normal file

@ -0,0 +1,34 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
hero:
name: "Obsidian Douban"
text: "obsidian插件\n同步你的豆瓣书影音"
tagline:
image:
src: /obsidian-douban-logo.png
alt: Obsidian Douban Logo
actions:
- theme: brand
text: 开始使用
link: /20_howtouse_10_detail
- theme: alt
text: 安装
link: /10_install
features:
- title: 搜索导入影音
icon: 📘
details: 搜索豆瓣中您喜欢的电影、电视剧、书籍、音乐、游戏等信息结构化并导入到Obsidian中
link: /20_howtouse_10_detail
- title: 同步个人数据
icon: 🙋
details: 登录后可同步个人的观影、观剧、阅读、游戏、音乐记录到您的Obsidian中
link: /20_howtouse_10_detail
- title: 建立个人书架
icon: 📚
details: 结合DataView生成整合你的书籍建立个人书架统一管理
link: /Obsidian-Douban-DataView-Jump
---

Binary file not shown.

After

Width:  |  Height:  |  Size: 780 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 MiB

@ -35,7 +35,7 @@ esbuild.build({
'@codemirror/panel', '@codemirror/panel',
'@codemirror/rangeset', '@codemirror/rangeset',
'@codemirror/rectangular-selection', '@codemirror/rectangular-selection',
'@codemirror/search', '@codemirror/searcher',
'@codemirror/state', '@codemirror/state',
'@codemirror/stream-parser', '@codemirror/stream-parser',
'@codemirror/text', '@codemirror/text',
@ -46,7 +46,7 @@ esbuild.build({
watch: !prod, watch: !prod,
target: 'es2016', target: 'es2016',
logLevel: "info", logLevel: "info",
sourcemap: prod ? false : 'inline', sourcemap: prod ? false : true,
treeShaking: true, treeShaking: true,
outfile: 'main.js', outfile: 'main.js',
// minify: true // minify: true

@ -1,7 +1,7 @@
{ {
"id": "obsidian-douban-plugin", "id": "obsidian-douban-plugin",
"name": "Douban", "name": "Douban",
"version": "v1.7.0", "version": "2.3.2",
"minAppVersion": "0.12.0", "minAppVersion": "0.12.0",
"description": "This is a plugin that can import movies/books/musics/notes/games info data from Douban for Obsidian .", "description": "This is a plugin that can import movies/books/musics/notes/games info data from Douban for Obsidian .",
"author": "Wanxp", "author": "Wanxp",

3380
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -1,13 +1,16 @@
{ {
"name": "obsidian-douban-plugin", "name": "obsidian-douban-plugin",
"version": "v1.7.7", "version": "2.3.2",
"description": "This is a plugin for Obsidian (https://obsidian.md) that can import data from Douban (https://www.douban.com/).", "description": "This is a plugin for Obsidian (https://obsidian.md) that can import data from Douban (https://www.douban.com/).",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
"dev": "node esbuild.config.mjs", "dev": "node esbuild.config.mjs",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"version": "node version-bump.mjs && git add manifest.json versions.json", "version": "node version-bump.mjs && git add manifest.json versions.json",
"test": "jest" "test": "jest",
"docs:dev": "vitepress dev doc",
"docs:build": "vitepress build doc",
"docs:preview": "vitepress preview doc"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
@ -23,12 +26,14 @@
"obsidian": "latest", "obsidian": "latest",
"ts-jest": "^28.0.5", "ts-jest": "^28.0.5",
"tslib": "2.3.1", "tslib": "2.3.1",
"typescript": "^4.7.2" "typescript": "^4.7.2",
"vitepress": "^1.6.3"
}, },
"dependencies": { "dependencies": {
"@notable/html2markdown": "^1.1.3", "@notable/html2markdown": "^1.1.3",
"@popperjs/core": "^2.11.6", "@popperjs/core": "^2.11.6",
"cheerio": "^1.0.0-rc.11", "cheerio": "^1.0.0-rc.11",
"follow-redirects": "^1.15.6",
"schema-dts": "^1.1.0" "schema-dts": "^1.1.0"
} }
} }

@ -1,15 +1,61 @@
import {i18nHelper} from "../lang/helper"; import {i18nHelper} from "../lang/helper";
import DoubanSearchResultSubject from "../douban/data/model/DoubanSearchResultSubject";
import StringUtil from "../utils/StringUtil";
import {DoubanPluginOnlineSettings} from "../douban/setting/model/DoubanPluginOnlineSettings";
import {DataField} from "../utils/model/DataField";
/** /**
* *
*/ */
export const BasicConst = { export const BasicConst = {
YAML_FRONT_MATTER_SYMBOL: '---', YAML_FRONT_MATTER_SYMBOL: '---',
/**
*
*/
CLEAN_STATUS_BAR_DELAY: 5000, CLEAN_STATUS_BAR_DELAY: 5000,
CALL_DOUBAN_DELAY: 3000, /**
CALL_DOUBAN_DELAY_RANGE: 3000, * ()
*/
CALL_DOUBAN_DELAY: 4000,
/**
* ()
*/
CALL_DOUBAN_DELAY_RANGE: 4000,
/**
* 403
*/
SLOW_SIZE: 200,
/**
* ()
*/
CALL_DOUBAN_DELAY_SLOW: 10000,
/**
* ()
*/
CALL_DOUBAN_DELAY_RANGE_SLOW: 5000,
} }
/**
*
* @private
*/
export const ESTIMATE_TIME_PER: number = 2000;
/**
* +()
* @private
*/
export const ESTIMATE_TIME_PER_WITH_REQUEST_SLOW: number = ESTIMATE_TIME_PER + BasicConst.CALL_DOUBAN_DELAY_SLOW + BasicConst.CALL_DOUBAN_DELAY_RANGE_SLOW / 2;
/**
* +()
* @private
*/
export const ESTIMATE_TIME_PER_WITH_REQUEST: number = ESTIMATE_TIME_PER + BasicConst.CALL_DOUBAN_DELAY + BasicConst.CALL_DOUBAN_DELAY_RANGE / 2;
/** /**
* *
*/ */
@ -55,13 +101,114 @@ export enum TemplateKey {
} }
export enum SupportType { export enum SupportType {
ALL = "ALL", all = "all",
MOVIE = 'MOVIE', movie = 'movie',
BOOK = 'BOOK', book = 'book',
MUSIC = 'MUSIC', music = 'music',
NOTE = 'NOTE', note = 'note',
GAME = 'GAME', game = 'game',
TELEPLAY = 'TELEPLAY', teleplay = 'teleplay',
theater = 'theater',
}
export const SupportTypeMap:object = {
"all": SupportType.all,
"movie": SupportType.movie,
"book": SupportType.book,
"music": SupportType.music,
"note": SupportType.note,
"game": SupportType.game,
"teleplay": SupportType.teleplay,
"theater": SupportType.theater,
"ALL": SupportType.all,
"MOVIE": SupportType.movie,
"BOOK": SupportType.book,
"MUSIC": SupportType.music,
"NOTE": SupportType.note,
"GAME": SupportType.game,
"TELEPLAY": SupportType.teleplay,
"THEATER": SupportType.theater,
}
export enum PropertyName {
//base
id = "id",
title = "title",
type = "type",
score = "score",
image = "image",
imageUrl = "imageUrl",
url = "url",
desc = "desc",
publisher = "publisher",
datePublished = "datePublished",
genre = "genre",
//user
tags = "tags",
rate = "rate",
state = "state",
collectionDate = "collectionDate",
comment = "comment",
//book
author = "author",
translator = "translator",
isbn = "isbn",
originalTitle = "originalTitle",
subTitle = "subTitle",
totalPage = "totalPage",
series = "series",
menu = "menu",
price = "price",
binding = "binding",
producer = "producer",
//movie
director = "director",
actor = "actor",
aggregateRating = "aggregateRating",
aliases = "aliases",
country = "country",
language = "language",
time = "time",
IMDb = "IMDb",
//music
albumType = "albumType",
medium = "medium",
records = "records",
barcode = "barcode",
//game
platform = "platform",
developer = "developer",
//teleplay
episode = "episode",
//theater
//note
authorUrl = "authorUrl",
content = "content",
}
/**
*
*/
// @ts-ignore
export const SearchTypeRecords: { [key in SupportType]: string } = {
[SupportType.all]: i18nHelper.getMessage('ALL'),
[SupportType.movie]: i18nHelper.getMessage('MOVIE_AND_TELEPLAY'),
[SupportType.book]: i18nHelper.getMessage('BOOK'),
[SupportType.music]: i18nHelper.getMessage('MUSIC'),
[SupportType.note]: i18nHelper.getMessage('NOTE'),
[SupportType.game]: i18nHelper.getMessage('GAME'),
[SupportType.theater]: i18nHelper.getMessage('THEATER'),
} }
/** /**
@ -76,26 +223,48 @@ export const PersonNameModeRecords: { [key in PersonNameMode]: string } = {
export enum SyncType { export enum SyncType {
movie = 'movie', movie = 'movie',
book = 'book', book = 'book',
game = 'game',
broadcast = 'broadcast', broadcast = 'broadcast',
note = 'note', note = 'note',
music = 'music', music = 'music',
teleplay = 'teleplay'
} }
export const SyncTypeUrlDomain: Map<SyncType, string> = new Map([
[SyncType.movie , 'movie'],
[SyncType.book , 'book'],
[SyncType.broadcast , 'broadcast'],
[SyncType.note , 'note'],
[SyncType.music , 'music'],
[SyncType.teleplay , 'movie'],
[SyncType.game, 'games'],
]
)
/** /**
* *
*/ */
// @ts-ignore // @ts-ignore
export const SyncTypeRecords: { [key in SyncType]: string } = { export const SyncTypeRecords: { [key in SyncType | string]: string } = {
[SyncType.movie]: i18nHelper.getMessage('504103'), [SyncType.movie]: i18nHelper.getMessage('504103'),
[SyncType.teleplay]: i18nHelper.getMessage('504107'),
[SyncType.book]: i18nHelper.getMessage('504102'), [SyncType.book]: i18nHelper.getMessage('504102'),
// [SyncType.broadcast]: i18nHelper.getMessage('504104'), // [SyncType.broadcast]: i18nHelper.getMessage('504104'),
// [SyncType.note]: i18nHelper.getMessage('504105'), // [SyncType.note]: i18nHelper.getMessage('504105'),
[SyncType.music]: i18nHelper.getMessage('504106'), [SyncType.music]: i18nHelper.getMessage('504106'),
[SyncType.game]: i18nHelper.getMessage('504108'),
} }
/**
*
*/
export const PAGE_SIZE: number = 30; export const PAGE_SIZE: number = 30;
/**
* 403
*/
/** /**
* *
*/ */
@ -111,5 +280,271 @@ export enum SyncItemStatus {
replace = 'replace', replace = 'replace',
create = 'create', create = 'create',
fail = 'fail', fail = 'fail',
failByDiffType = 'failByDiffType',
unHandle = 'unHandle',
} }
export enum NavigateType {
previous = "previous",
next = "next",
nextNeedLogin = "nextNeedLogin"
}
export const DoubanSearchResultSubjectPreviousPage: DoubanSearchResultSubject = {
cast: "",
datePublished: undefined,
desc: "",
genre: [],
id: "",
image: "",
imageUrl: "",
publisher: "",
score: 0,
title: i18nHelper.getMessage("150102"),
type: "navigate",
url: NavigateType.previous
}
export const DoubanSearchGroupPublishResultSubjectPreviousPage: DoubanSearchResultSubject = {
cast: "",
datePublished: undefined,
desc: "",
genre: [],
id: "",
image: "",
imageUrl: "",
publisher: "",
score: 0,
title: i18nHelper.getMessage("150106"),
type: "navigate",
url: NavigateType.previous
}
export const DoubanSearchGroupPublishResultSubjectNextPage: DoubanSearchResultSubject = {
cast: "",
datePublished: undefined,
desc: "",
genre: [],
id: "",
image: "",
imageUrl: "",
publisher: "",
score: 0,
title: i18nHelper.getMessage("150105"),
type: "navigate",
url: NavigateType.next
}
export const DoubanSearchResultSubjectNextPage: DoubanSearchResultSubject = {
cast: "",
datePublished: undefined,
desc: "",
genre: [],
id: "",
image: "",
imageUrl: "",
publisher: "",
score: 0,
title: i18nHelper.getMessage("150103"),
type: "navigate",
url: NavigateType.next
}
export const DoubanSearchResultSubjectNextPageNeedLogin: DoubanSearchResultSubject = {
cast: "",
datePublished: undefined,
desc: "",
genre: [],
id: "",
image: "",
imageUrl: "",
publisher: "",
score: 0,
title: i18nHelper.getMessage("150104"),
type: "navigate",
url: NavigateType.nextNeedLogin
}
export const SEARCH_ITEM_PAGE_SIZE: number = 20;
/**
*
* @type {string}
**/
export const DEFAULT_DOUBAN_HEADERS = StringUtil.parseHeaders(`
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
Accept-Language: zh-CN,zh;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Host: www.douban.com
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36
sec-ch-ua: "Not/A)Brand";v="99", "Google Chrome";v="115", "Chromium";v="115"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
`)
/**
*
*/
export const ONLINE_SETTING_DEFAULT: DoubanPluginOnlineSettings = {
properties: [
{
type: SupportType.book,
name: PropertyName.comment,
selectors: ['#interest_sect_level > div > span:nth-child(7)'
]
},
{
type: SupportType.movie,
name: PropertyName.comment,
selectors: ['#interest_sect_level > div > span:nth-child(8)',
'#interest_sect_level > div > span:nth-child(7)',
'#interest_sect_level > div > span:nth-child(9)'
]
}
]
}
/**
*
*/
export enum SubjectHandledStatus {
init = 'init',
saved = 'saved',
syncTypeDiffAbort = 'syncTypeDiffAbort',
}
export const DEFAULT_SETTINGS_ARRAY_INPUT_SIZE = 2;
export enum DataValueType {
date,
number,
string,
person,
array,
url,
path,
}
export enum DataTargetType {
fileName,
yaml,
content,
}
export const EXAMPLE_RATE = 8.5;
export const EXAMPLE_RATE_MAX = 10;
export const EXAMPLE_SUBJECT_MAP: Map<string, DataField> = new Map([
["id", new DataField("id", DataValueType.string, DataValueType.string, "2253379")],
["title", new DataField("title", DataValueType.string, DataValueType.string, "简爱")],
["type", new DataField("type", DataValueType.string, DataValueType.string, "book")],
["score", new DataField("score", DataValueType.number, DataValueType.number, EXAMPLE_RATE)],
["image", new DataField("image", DataValueType.url, DataValueType.url, "https://img9.doubanio.com/view/subject/s/public/s1070959.jpg")],
["imageUrl", new DataField("imageUrl", DataValueType.url, DataValueType.url, "https://img9.doubanio.com/view/subject/s/public/s1070959.jpg")],
["url", new DataField("url", DataValueType.url, DataValueType.url, "https://book.douban.com/subject/2253379/")],
["desc", new DataField("desc", DataValueType.string, DataValueType.string, "简爱是一部关于爱、关于成长、关于追求自由与尊严的伟大小说。")],
["publisher", new DataField("publisher", DataValueType.string, DataValueType.string, "人民文学出版社")],
["datePublished", new DataField("datePublished", DataValueType.date, DataValueType.date, "2020-1-1")],
["genre", new DataField("genre", DataValueType.array, DataValueType.array, "小说")],
["tags", new DataField("tags", DataValueType.array, DataValueType.array, "小说")],
["rate", new DataField("rate", DataValueType.number, DataValueType.number, 9.0)],
["state", new DataField("state", DataValueType.string, DataValueType.string, "wish")],
["collectionDate", new DataField("collectionDate", DataValueType.date, DataValueType.date, "2020-1-1")],
["comment", new DataField("comment", DataValueType.string, DataValueType.string, "简爱是一部关于爱、关于成长、关于追求自由与尊严的伟大小说。")],
["author", new DataField("author", DataValueType.person, DataValueType.person, "夏洛蒂·勃朗特")],
["translator", new DataField("translator", DataValueType.person, DataValueType.person, "李继宏")],
]);
export const MAX_STAR_NUMBER = 100;
export enum PictureBedType {
PicGo = "PicGo"
}
export const PictureBedSetting_PicGo ={
url: "http://127.0.0.1:36677/upload"
}
export const PictureBedTypeRecords: { [key in PictureBedType]: string } = {
[PictureBedType.PicGo]: PictureBedType.PicGo
}
export enum SyncConditionType {
/**
*
*/
ALL = "all",
// /**
// * 最近新变动
// */
// LAST_UPDATE = "lastUpdate",
/**
* 10
*/
LAST_THIRTY = "lastThirty",
/**
*
*/
CUSTOM_TIME = "customTime",
/**
*
*/
CUSTOM_ITEM = "customItem",
}
/**
*
*/
// @ts-ignore
export const SyncConditionTypeRecords: { [key in SyncConditionType|string]: string } = {
[SyncConditionType.ALL]: i18nHelper.getMessage('110071'),
// [SyncConditionType.LAST_UPDATE]: i18nHelper.getMessage('110072'),
[SyncConditionType.LAST_THIRTY]: i18nHelper.getMessage('110075'),
[SyncConditionType.CUSTOM_ITEM]: i18nHelper.getMessage('110076'),
[SyncConditionType.CUSTOM_TIME]: i18nHelper.getMessage('110074'),
}
export const DoubanSearchResultSubject_EMPTY: DoubanSearchResultSubject = {
id: '',
title: i18nHelper.getMessage('150107'),
score: null,
cast: '',
type: 'navigate',
desc: '-',
url: 'https://www.douban.com',
image: "",
imageUrl: "",
publisher: "",
datePublished: undefined,
genre: []
};
export const DoubanSearchResultSubject_TIP_EMPTY: DoubanSearchResultSubject = {
id: '',
title: i18nHelper.getMessage('150108'),
score: null,
cast: '',
type: 'navigate',
desc: '-',
url: 'https://www.douban.com',
image: "",
imageUrl: "",
publisher: "",
datePublished: undefined,
genre: []
};

@ -1,8 +1,23 @@
import {DoubanPluginSetting} from "../douban/setting/model/DoubanPluginSetting"; import {DoubanPluginSetting} from "../douban/setting/model/DoubanPluginSetting";
import {PersonNameMode, SupportType} from "./Constsant"; import {PersonNameMode, PictureBedSetting_PicGo, PictureBedType, SupportType} from "./Constsant";
import {doubanHeaders} from "./Douban";
export const DEFAULT_SETTINGS: DoubanPluginSetting = { export const DEFAULT_SETTINGS: DoubanPluginSetting = {
pictureBedFlag: false,
pictureBedSetting: PictureBedSetting_PicGo,
pictureBedType: PictureBedType.PicGo,
arraySettings: [
{
"arrayName": "ArrayType1",
"arrayStart": "",
"arrayElementStart": "[[",
"arraySpiltV2": ",",
"arrayElementEnd": "]]",
"arrayEnd": "",
"index": 1
}
],
onlineSettingsFileName: "obsidian_douban_plugin_online_settings.json",
onlineSettingsGistId: "35693f9ece9bd6abba98f94e81afde19",
movieTemplateFile: ``, movieTemplateFile: ``,
bookTemplateFile: ``, bookTemplateFile: ``,
musicTemplateFile: ``, musicTemplateFile: ``,
@ -10,23 +25,43 @@ export const DEFAULT_SETTINGS: DoubanPluginSetting = {
gameTemplateFile: ``, gameTemplateFile: ``,
teleplayTemplateFile: ``, teleplayTemplateFile: ``,
searchUrl: 'https://www.douban.com/search?q=', searchUrl: 'https://www.douban.com/search?q=',
searchHeaders: JSON.stringify(doubanHeaders),
dateFormat: "yyyy-MM-DD", dateFormat: "yyyy-MM-DD",
timeFormat: "HH:mm:ss", timeFormat: "HH:mm:ss",
arraySpilt: ", ", arrayStart: "",
arrayElementStart: "\\n - ",
arraySpiltV2: "",
arrayElementEnd: "",
arrayEnd: "",
personNameMode: PersonNameMode.CH_NAME, personNameMode: PersonNameMode.CH_NAME,
dataFilePath: "", dataFilePath: "",
dataFileNamePath: "/{{type}}/{{title}}", dataFileNamePath: "/{{type}}/{{title}}",
statusBar: true, statusBar: true,
debugMode: false,
customProperties: [ customProperties: [
{name: 'myType', value: 'movie', field: SupportType.MOVIE}, {name: 'myType', value: 'movie', field: SupportType.movie},
{name: 'myType', value: 'book', field: SupportType.BOOK}, {name: 'myType', value: 'book', field: SupportType.book},
{name: 'myType', value: 'music', field: SupportType.MUSIC}, {name: 'myType', value: 'music', field: SupportType.music},
{name: 'myType', value: 'note', field: SupportType.NOTE}, {name: 'myType', value: 'note', field: SupportType.note},
{name: 'myType', value: 'game', field: SupportType.GAME}, {name: 'myType', value: 'game', field: SupportType.game},
{name: 'myType', value: 'teleplay', field: SupportType.TELEPLAY}, {name: 'myType', value: 'teleplay', field: SupportType.teleplay},
{name: 'myType', value: 'theater', field: SupportType.theater},
], ],
loginCookiesContent: '', loginCookiesContent: '',
loginHeadersContent: '',
cacheImage: true, cacheImage: true,
cacheHighQuantityImage: true,
attachmentPath: 'assets', attachmentPath: 'assets',
attachmentFileName: "{{title}}",
syncHandledDataArray: [],
// syncLastUpdateTime: new Map<string, string>(),
scoreSetting: {
starFull: '⭐',
starEmpty: '☆',
displayStarEmpty: false,
maxStar: 5,
},
searchDefaultType: SupportType.all,
} }

@ -6,14 +6,21 @@ doubanId: {{id}}
title: {{title}} title: {{title}}
type: {{type}} type: {{type}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
originalTitle: {{originalTitle}} originalTitle: {{originalTitle}}
genre: {{genre}} genre: {{genre}}
datePublished: {{datePublished}} datePublished: {{datePublished}}
director: {{director}} director: {{director}}
actor: {{actor}} actor: {{actor}}
author: {{author}} author: {{author}}
tags: {{type}} tags:
- {{type}}
url: {{url}} url: {{url}}
aliases: {{aliases}}
country: {{country}}
language: {{language}}
IMDb: {{IMDb}}
time: {{time}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
desc: {{desc}} desc: {{desc}}
--- ---
@ -29,6 +36,7 @@ series: {{series}}
type: {{type}} type: {{type}}
author: {{author}} author: {{author}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
datePublished: {{datePublished}} datePublished: {{datePublished}}
translator: {{translator}} translator: {{translator}}
publisher: {{publisher}} publisher: {{publisher}}
@ -37,13 +45,14 @@ isbn: {{isbn}}
url: {{url}} url: {{url}}
totalPage: {{totalPage}} totalPage: {{totalPage}}
price: {{price}} price: {{price}}
tags: Book tags:
- {{type}}
binding: {{binding}} binding: {{binding}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
desc: {{desc}} desc: {{desc}}
--- ---
![image|150]({{image}}) ![image]({{image}})
{{menu}} {{menu}}
`, `,
@ -53,6 +62,7 @@ title: {{title}}
type: {{type}} type: {{type}}
actor: {{actor}} actor: {{actor}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
genre: {{genre}} genre: {{genre}}
medium: {{medium}} medium: {{medium}}
albumType: {{albumType}} albumType: {{albumType}}
@ -61,12 +71,17 @@ publisher: {{publisher}}
barcode: {{barcode}} barcode: {{barcode}}
url: {{url}} url: {{url}}
records: {{records}} records: {{records}}
tags: Music tags:
- {{type}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
desc: {{desc}} desc: {{desc}}
--- ---
![image|150]({{image}}) ![image]({{image}})
---
Menu:
{{menu}}
`, `,
noteTemplateFileContent: `--- noteTemplateFileContent: `---
doubanId: {{id}} doubanId: {{id}}
@ -76,7 +91,8 @@ author: {{author}}
authorUrl: {{authorUrl}} authorUrl: {{authorUrl}}
dateTimePublished: {{datePublished}} {{timePublished}} dateTimePublished: {{datePublished}} {{timePublished}}
url: {{url}} url: {{url}}
tags: Article tags:
- {{type}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
desc: {{desc}} desc: {{desc}}
--- ---
@ -89,13 +105,15 @@ title: {{title}}
aliases: {{aliases}} aliases: {{aliases}}
type: {{type}} type: {{type}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
dateTimePublished: {{datePublished}} dateTimePublished: {{datePublished}}
publisher: {{publisher}} publisher: {{publisher}}
genre: {{genre}} genre: {{genre}}
developer: {{developer}} developer: {{developer}}
platform: {{platform}} platform: {{platform}}
url: {{url}} url: {{url}}
tags: Game tags:
- {{type}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
desc: {{desc}} desc: {{desc}}
--- ---
@ -106,14 +124,22 @@ doubanId: {{id}}
title: {{title}} title: {{title}}
type: {{type}} type: {{type}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
originalTitle: {{originalTitle}} originalTitle: {{originalTitle}}
genre: {{genre}} genre: {{genre}}
datePublished: {{datePublished}} datePublished: {{datePublished}}
director: {{director}} director: {{director}}
actor: {{actor}} actor: {{actor}}
author: {{author}} author: {{author}}
tags: {{type}} tags:
- {{type}}
url: {{url}} url: {{url}}
aliases: {{aliases}}
country: {{country}}
language: {{language}}
IMDb: {{IMDb}}
time: {{time}}
episode: {{episode}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
desc: {{desc}} desc: {{desc}}
--- ---
@ -128,16 +154,23 @@ doubanId: {{id}}
title: {{title}} title: {{title}}
type: {{type}} type: {{type}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
myRating: {{myRating}} myRating: {{myRating}}
myRatingStar: {{myRatingStar}}
originalTitle: {{originalTitle}} originalTitle: {{originalTitle}}
genre: {{genre}} genre: {{genre}}
datePublished: {{datePublished}} datePublished: {{datePublished}}
director: {{director}} director: {{director}}
actor: {{actor}} actor: {{actor}}
author: {{author}} author: {{author}}
tags: {{type}}, {{myTags}} tags: {{myTags}}
state: {{myState}} state: {{myState}}
url: {{url}} url: {{url}}
aliases: {{aliases}}
country: {{country}}
language: {{language}}
IMDb: {{IMDb}}
time: {{time}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
collectionDate: {{myCollectionDate}} collectionDate: {{myCollectionDate}}
desc: {{desc}} desc: {{desc}}
@ -158,7 +191,9 @@ series: {{series}}
type: {{type}} type: {{type}}
author: {{author}} author: {{author}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
myRating: {{myRating}} myRating: {{myRating}}
myRatingStar: {{myRatingStar}}
datePublished: {{datePublished}} datePublished: {{datePublished}}
translator: {{translator}} translator: {{translator}}
publisher: {{publisher}} publisher: {{publisher}}
@ -167,7 +202,7 @@ isbn: {{isbn}}
url: {{url}} url: {{url}}
totalPage: {{totalPage}} totalPage: {{totalPage}}
price: {{price}} price: {{price}}
tags: Book, {{myTags}} tags: {{myTags}}
state: {{myState}} state: {{myState}}
binding: {{binding}} binding: {{binding}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
@ -175,7 +210,7 @@ collectionDate: {{myCollectionDate}}
desc: {{desc}} desc: {{desc}}
--- ---
![image|150]({{image}}) ![image]({{image}})
Comment: Comment:
--- ---
@ -189,7 +224,9 @@ title: {{title}}
type: {{type}} type: {{type}}
actor: {{actor}} actor: {{actor}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
myRating: {{myRating}} myRating: {{myRating}}
myRatingStar: {{myRatingStar}}
genre: {{genre}} genre: {{genre}}
medium: {{medium}} medium: {{medium}}
albumType: {{albumType}} albumType: {{albumType}}
@ -198,14 +235,23 @@ publisher: {{publisher}}
barcode: {{barcode}} barcode: {{barcode}}
url: {{url}} url: {{url}}
records: {{records}} records: {{records}}
tags: Music, {{myTags}} tags: {{myTags}}
state: {{myState}} state: {{myState}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
collectionDate: {{myCollectionDate}} collectionDate: {{myCollectionDate}}
desc: {{desc}} desc: {{desc}}
--- ---
![image|150]({{image}}) ![image]({{image}})
---
Menu:
{{menu}}
---
Comment:
{{myComment}}
`, `,
noteTemplateFileContent: `--- noteTemplateFileContent: `---
doubanId: {{id}} doubanId: {{id}}
@ -215,7 +261,8 @@ author: {{author}}
authorUrl: {{authorUrl}} authorUrl: {{authorUrl}}
dateTimePublished: {{datePublished}} {{timePublished}} dateTimePublished: {{datePublished}} {{timePublished}}
url: {{url}} url: {{url}}
tags: Article tags:
- {{type}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
desc: {{desc}} desc: {{desc}}
--- ---
@ -228,14 +275,16 @@ title: {{title}}
aliases: {{aliases}} aliases: {{aliases}}
type: {{type}} type: {{type}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
myRating: {{myRating}} myRating: {{myRating}}
myRatingStar: {{myRatingStar}}
dateTimePublished: {{datePublished}} dateTimePublished: {{datePublished}}
publisher: {{publisher}} publisher: {{publisher}}
genre: {{genre}} genre: {{genre}}
developer: {{developer}} developer: {{developer}}
platform: {{platform}} platform: {{platform}}
url: {{url}} url: {{url}}
tags: Game, {{myTags}} tags: {{myTags}}
state: {{myState}} state: {{myState}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
collectionDate: {{myCollectionDate}} collectionDate: {{myCollectionDate}}
@ -252,16 +301,24 @@ doubanId: {{id}}
title: {{title}} title: {{title}}
type: {{type}} type: {{type}}
score: {{score}} score: {{score}}
scoreStar: {{scoreStar}}
myRating: {{myRating}} myRating: {{myRating}}
myRatingStar: {{myRatingStar}}
originalTitle: {{originalTitle}} originalTitle: {{originalTitle}}
genre: {{genre}} genre: {{genre}}
datePublished: {{datePublished}} datePublished: {{datePublished}}
director: {{director}} director: {{director}}
actor: {{actor}} actor: {{actor}}
author: {{author}} author: {{author}}
tags: {{type}}, {{myTags}} tags: {{myTags}}
state: {{myState}} state: {{myState}}
url: {{url}} url: {{url}}
aliases: {{aliases}}
country: {{country}}
language: {{language}}
IMDb: {{IMDb}}
time: {{time}}
episode: {{episode}}
createTime: {{currentDate}} {{currentTime}} createTime: {{currentDate}} {{currentTime}}
collectionDate: {{myCollectionDate}} collectionDate: {{myCollectionDate}}
desc: {{desc}} desc: {{desc}}

@ -10,3 +10,7 @@ export const doubanHeaders = {
export const doubanSubjectSyncListUrl = function(subjectType:string, userId:string, doType:string, start:number):string { export const doubanSubjectSyncListUrl = function(subjectType:string, userId:string, doType:string, start:number):string {
return `https://${subjectType}.douban.com/people/${userId}/${doType}?start=${start}&sort=time&rating=all&filter=all&mode=list`; return `https://${subjectType}.douban.com/people/${userId}/${doType}?start=${start}&sort=time&rating=all&filter=all&mode=list`;
} }
export const doubanGameSubjectSyncListUrl = function(subjectType:string, userId:string, doType:string, start:number):string {
return `https://douban.com/people/${userId}/games?start=${start}&sort=time&rating=all&filter=all&mode=list${doType != 'all' ? '&action='+doType : ''}`;
}

@ -1,5 +1,5 @@
import {i18nHelper} from "../lang/helper"; import {i18nHelper} from "../lang/helper";
import {SupportType} from "./Constsant"; import {SupportType, SyncType} from "./Constsant";
export enum DoubanSubjectState { export enum DoubanSubjectState {
not = 'not', not = 'not',
@ -58,14 +58,22 @@ export const DoubanSubjectStateRecords_TELEPLAY: { [key in DoubanSubjectState]:
[DoubanSubjectState.collect]: i18nHelper.getMessage('500704'), [DoubanSubjectState.collect]: i18nHelper.getMessage('500704'),
} }
export const DoubanSubjectStateRecords_THEATER: { [key in DoubanSubjectState]: string } = {
[DoubanSubjectState.not]: i18nHelper.getMessage('500701'),
[DoubanSubjectState.wish]: i18nHelper.getMessage('500702'),
[DoubanSubjectState.do]: i18nHelper.getMessage('500703'),
[DoubanSubjectState.collect]: i18nHelper.getMessage('500704'),
}
export const DoubanSubjectStateRecords: { [key in SupportType]: Record<DoubanSubjectState, string> } = { export const DoubanSubjectStateRecords: { [key in SupportType]: Record<DoubanSubjectState, string> } = {
[SupportType.ALL]:DoubanSubjectStateRecords_ALL, [SupportType.all]:DoubanSubjectStateRecords_ALL,
[SupportType.MOVIE]:DoubanSubjectStateRecords_MOVIE, [SupportType.movie]:DoubanSubjectStateRecords_MOVIE,
[SupportType.BOOK]:DoubanSubjectStateRecords_BOOK, [SupportType.book]:DoubanSubjectStateRecords_BOOK,
[SupportType.MUSIC]:DoubanSubjectStateRecords_MUSIC, [SupportType.music]:DoubanSubjectStateRecords_MUSIC,
[SupportType.NOTE]:DoubanSubjectStateRecords_NOTE, [SupportType.note]:DoubanSubjectStateRecords_NOTE,
[SupportType.GAME]:DoubanSubjectStateRecords_GAME, [SupportType.game]:DoubanSubjectStateRecords_GAME,
[SupportType.TELEPLAY]:DoubanSubjectStateRecords_TELEPLAY, [SupportType.teleplay]:DoubanSubjectStateRecords_TELEPLAY,
[SupportType.theater]:DoubanSubjectStateRecords_THEATER,
} }
@ -80,6 +88,15 @@ export const DoubanSubjectStateRecords_MOVIE_SYNC: { [key in DoubanSubjectState]
[DoubanSubjectState.collect]: i18nHelper.getMessage('500204'), [DoubanSubjectState.collect]: i18nHelper.getMessage('500204'),
} }
// @ts-ignore
export const DoubanSubjectStateRecords_TELEPLAY_SYNC: { [key in DoubanSubjectState]: string } = {
// @ts-ignore
[ALL]: i18nHelper.getMessage('500004'),
[DoubanSubjectState.wish]: i18nHelper.getMessage('500202'),
[DoubanSubjectState.do]: i18nHelper.getMessage('500203'),
[DoubanSubjectState.collect]: i18nHelper.getMessage('500204'),
}
// @ts-ignore // @ts-ignore
export const DoubanSubjectStateRecords_BOOK_SYNC: { [key in DoubanSubjectState]: string } = { export const DoubanSubjectStateRecords_BOOK_SYNC: { [key in DoubanSubjectState]: string } = {
// @ts-ignore // @ts-ignore
@ -89,6 +106,15 @@ export const DoubanSubjectStateRecords_BOOK_SYNC: { [key in DoubanSubjectState]:
[DoubanSubjectState.collect]: i18nHelper.getMessage('500304'), [DoubanSubjectState.collect]: i18nHelper.getMessage('500304'),
} }
// @ts-ignore
export const DoubanSubjectStateRecords_GAME_SYNC: { [key in DoubanSubjectState]: string } = {
// @ts-ignore
// [ALL]: i18nHelper.getMessage('500004'),
[DoubanSubjectState.wish]: i18nHelper.getMessage('500602'),
[DoubanSubjectState.do]: i18nHelper.getMessage('500603'),
[DoubanSubjectState.collect]: i18nHelper.getMessage('500604'),
}
export const DoubanSubjectStateRecords_BROADCAST_SYNC: { [key :string]: string } = { export const DoubanSubjectStateRecords_BROADCAST_SYNC: { [key :string]: string } = {
[ALL]: i18nHelper.getMessage('500004'), [ALL]: i18nHelper.getMessage('500004'),
} }
@ -106,6 +132,53 @@ export const DoubanSubjectStateRecords_MUSIC_SYNC: { [key in DoubanSubjectState]
[DoubanSubjectState.collect]: i18nHelper.getMessage('500404'), [DoubanSubjectState.collect]: i18nHelper.getMessage('500404'),
} }
// @ts-ignore
export const DoubanSubjectStateRecords_SYNC: { [key in SyncType]: Record<DoubanSubjectState, string> } = {
[SyncType.movie]:DoubanSubjectStateRecords_MOVIE_SYNC,
[SyncType.book]:DoubanSubjectStateRecords_BOOK_SYNC,
[SyncType.music]:DoubanSubjectStateRecords_MUSIC_SYNC,
// [SyncType.note]:DoubanSubjectStateRecords_NOTE_SYNC,
[SyncType.game]:DoubanSubjectStateRecords_GAME_SYNC,
[SyncType.teleplay]:DoubanSubjectStateRecords_TELEPLAY_SYNC,
// [SyncType.theater]:DoubanSubjectStateRecords_THEATER_SYNC,
}
export const DoubanSubjectStateRecords_KEY_WORD_TYPE: Map<string, SupportType> = new Map<string, SupportType> (
[['我看过这部电视剧', SupportType.teleplay],
['我最近看过这部电视剧', SupportType.teleplay],
['我想看这部电视剧', SupportType.teleplay],
['我在看这部电视剧', SupportType.teleplay],
['我最近在看这部电视剧', SupportType.teleplay],
['我最近看过这部电影', SupportType.movie],
['我看过这部电影', SupportType.movie],
['我想看这部电影', SupportType.movie],
['我读过这本书', SupportType.book],
['我想读这本书', SupportType.book],
['我在读这本书', SupportType.book],
['我最近在读这本书', SupportType.book],
['我最近听过这张唱片', SupportType.music],
['我听过这张唱片', SupportType.music],
['我想听这张唱片', SupportType.music],
['我在听这张唱片', SupportType.music],
['我最近在听这张唱片', SupportType.music],
['我最近玩过这个游戏', SupportType.game],
['我玩过这个游戏', SupportType.game],
['我想玩这个游戏', SupportType.game],
['我在玩这个游戏', SupportType.game],
['我最近在玩这个游戏', SupportType.game],
['我最近看过这部电影', SupportType.movie],
['我看过这部电影', SupportType.movie],
['我想看这部电影', SupportType.movie],
]
)

@ -0,0 +1,92 @@
import {CheerioAPI} from 'cheerio';
import DoubanPlugin from "../../../main";
import SchemaOrg from "src/org/wanxp/utils/SchemaOrg";
import {DataValueType, PropertyName, SupportType} from "../../../constant/Constsant";
import {moment} from "obsidian";
import {TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil";
import {DataField} from "../../../utils/model/DataField";
import DoubanAbstractLoadHandler from "../../data/handler/DoubanAbstractLoadHandler";
import DoubanTheaterSubject from "../../data/model/DoubanTheaterSubject";
import HandleContext from "../../data/model/HandleContext";
import DoubanSubject from "../../data/model/DoubanSubject";
import {UserStateSubject} from "../../data/model/UserStateSubject";
export default class DoubanTheaterAiLoadHandler extends DoubanAbstractLoadHandler<DoubanTheaterSubject> {
constructor(doubanPlugin: DoubanPlugin) {
super(doubanPlugin);
}
getSupportType(): SupportType {
return SupportType.theater;
}
getHighQuantityImageUrl(fileName: string): string {
return `https://img9.doubanio.com/view/photo/l/public/${fileName}`;
}
getSubjectUrl(id:string):string{
return `https://www.douban.com/location/drama/${id}/`;
}
parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanTheaterSubject, context: HandleContext): void {
variableMap.set("director", new DataField(
"director",
DataValueType.array,
extract.director,
(extract.director || []).map(SchemaOrg.getPersonName).filter(c => c)
));
variableMap.set("actor", new DataField(
"actor",
DataValueType.array,
extract.actor,
(extract.actor || []).map(SchemaOrg.getPersonName).filter(c => c)
));
variableMap.set("author", new DataField(
"author",
DataValueType.array,
extract.author,
(extract.author || []).map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c)
));
variableMap.set("aliases", new DataField("aliases", DataValueType.array, extract.aliases,
(extract.aliases || []).map(a=>a
.trim()
// .replace(TITLE_ALIASES_SPECIAL_CHAR_REG_G, '_')
// //replase multiple _ to single _
// .replace(/_+/g, '_')
// .replace(/^_/, '')
// .replace(/_$/, '')
.replace(/:\s+/g, ':')
)));
// super.parseAliases(beforeContent, variableMap, extract, context);
}
support(extract: DoubanSubject): boolean {
return extract && extract.type && (extract.type.contains("舞台剧") || extract.type.contains("舞剧") || extract.type.contains("Theater") || extract.type.contains("theater"));
}
analysisUser(html: CheerioAPI, context: HandleContext): { data: CheerioAPI, userState: UserStateSubject } {
const rate = html('input#n_rating').val();
const tagsStr = html('div#interest_sect_level > div.a_stars > span.color_gray').text().trim();
const tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null;
const stateWord = html('#interest_sect_level > h2').text().trim();
const collectionDateStr = html('div#interest_sect_level > div.a_stars > span.mr10 > span.collection_date').text().trim();
const userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
const component = this.getPropertyValue(html, PropertyName.comment);
const userState: UserStateSubject = {
tags: tags,
rate: rate ? Number(rate) : null,
state: userState1,
collectionDate: collectionDateStr ? moment(collectionDateStr, 'YYYY-MM-DD').toDate() : null,
comment: component
}
return {data: html, userState: userState};
}
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanTheaterSubject {
const obj: DoubanTheaterSubject = new DoubanTheaterSubject();
obj.id = this.getPropertyValue(html, PropertyName.id);
return obj;
}
}

@ -0,0 +1,68 @@
import {App, ButtonComponent, Modal} from "obsidian";
import {i18nHelper} from "../../lang/helper";
import {create} from "istanbul-reports";
import DoubanPlugin from "../../main";
import {logger} from "bs-logger";
import {log} from "../../utils/Logutil";
export class ConfirmDialogModal extends Modal {
private promise:Promise<any>;
private message:string;
private doubanPlugin: DoubanPlugin;
constructor(doubanPlugin: DoubanPlugin, message:string, promise: Promise<any>) {
super(doubanPlugin.app);
this.doubanPlugin = doubanPlugin;
this.message = message;
this.promise = promise;
}
onOpen() {
const {contentEl} = this;
contentEl.createEl('h3', {text: i18nHelper.getMessage('110152')});
contentEl.createEl('p', {text: `${this.message}`});
contentEl.createEl('p', {text: i18nHelper.getMessage('125033')});
const controls = contentEl.createDiv("controls");
controls.addClass("obsidian_douban_search_controls")
new ButtonComponent(controls)
.setButtonText(i18nHelper.getMessage('110152'))
.setCta()
.onClick(async () => {
//临时特殊处理导入文件
if (this.message == i18nHelper.getMessage('125046')) {
createFileSelectModal(this.doubanPlugin);
}else {
await this.promise;
}
this.close();
}).setClass( "obsidian_douban_search_button");
new ButtonComponent(controls)
.setButtonText(i18nHelper.getMessage('110005'))
.onClick(() => {
this.close();
}).setClass( "obsidian_douban_cancel_button");
}
}
function createFileSelectModal(doubanPlugin: DoubanPlugin) {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.multiple = false;
input.onchange = async () => {
const file = input.files[0];
const reader = new FileReader();
reader.onload = async () => {
const settings:object = JSON.parse(reader.result as string);
try {
await doubanPlugin.settingsManager.loadAndSaveSettings(settings);
}catch (e) {
log.error(i18nHelper.getMessage('125043'), e);
}
log.notice(i18nHelper.getMessage('125044'))
};
reader.readAsText(file);
};
input.click();}

@ -0,0 +1,18 @@
/**
*
* TextComponent
*/
import {TextComponent} from 'obsidian';
export class DatePickComponent extends TextComponent {
constructor(container: HTMLElement, date: Date = new Date()) {
super(container);
this.inputEl.type = 'date';
this.inputEl.value = date.toISOString().substring(0, 10);
}
getValue(): string {
return this.inputEl.value;
}
}

@ -3,7 +3,7 @@ import { log } from 'src/org/wanxp/utils/Logutil';
import {i18nHelper} from "../../lang/helper"; import {i18nHelper} from "../../lang/helper";
import {DoubanSettingTab} from "../setting/DoubanSettingTab"; import {DoubanSettingTab} from "../setting/DoubanSettingTab";
import SettingsManager from "../setting/SettingsManager"; import SettingsManager from "../setting/SettingsManager";
import {constructDoubanTokenSettingsUI} from "../setting/BasicSettingsHelper"; import {constructDoubanTokenSettingsUI} from "../setting/LoginSettingsHelper";
// Credits go to zhaohongxuan's Weread Plugin : https://github.com/zhaohongxuan/obsidian-weread-plugin // Credits go to zhaohongxuan's Weread Plugin : https://github.com/zhaohongxuan/obsidian-weread-plugin

@ -3,7 +3,9 @@ import { log } from 'src/org/wanxp/utils/Logutil';
import {i18nHelper} from "../../lang/helper"; import {i18nHelper} from "../../lang/helper";
import {DoubanSettingTab} from "../setting/DoubanSettingTab"; import {DoubanSettingTab} from "../setting/DoubanSettingTab";
import SettingsManager from "../setting/SettingsManager"; import SettingsManager from "../setting/SettingsManager";
import {constructDoubanTokenSettingsUI} from "../setting/BasicSettingsHelper"; import {constructDoubanTokenSettingsUI} from "../setting/LoginSettingsHelper";
import StringUtil from "../../utils/StringUtil";
import {Integer} from "schema-dts";
// Credits go to zhaohongxuan's Weread Plugin : https://github.com/zhaohongxuan/obsidian-weread-plugin // Credits go to zhaohongxuan's Weread Plugin : https://github.com/zhaohongxuan/obsidian-weread-plugin
@ -15,8 +17,9 @@ export default class DoubanLoginModel {
constructor(containerEl: HTMLElement, settingsManager: SettingsManager) { constructor(containerEl: HTMLElement, settingsManager: SettingsManager) {
this.containerEl = containerEl; this.containerEl = containerEl;
this.settingsManager = settingsManager; this.settingsManager = settingsManager;
this.settingsManager.debug(`配置界面:初始化登录界面`)
const { remote} = require('electron'); const { remote} = require('electron');
const { BrowserWindow: RemoteBrowserWindow } = remote; const { BrowserWindow: RemoteBrowserWindow } = remote;
this.modal = new RemoteBrowserWindow({ this.modal = new RemoteBrowserWindow({
parent: remote.getCurrentWindow(), parent: remote.getCurrentWindow(),
@ -30,24 +33,49 @@ export default class DoubanLoginModel {
this.modal.show(); this.modal.show();
}); });
this.modal.on('closed', () => { this.modal.on('closed', () => {
this.showCloseMessage();
constructDoubanTokenSettingsUI(this.containerEl, this.settingsManager); constructDoubanTokenSettingsUI(this.containerEl, this.settingsManager);
}); });
this.modal.webContents.on('did-fail-load', (event:Event, errorCode:Integer ) => {
// 例如, 当 Ctrl/Cmd are down 被按下,仅开启应用程序菜单键盘快捷键。
this.settingsManager.debug('加载失败' + errorCode);
})
this.modal.webContents.on('did-fail-load', (event:Event) => {
// 例如, 当 Ctrl/Cmd are down 被按下,仅开启应用程序菜单键盘快捷键。
this.settingsManager.debug('加载成功');
})
this.modal.webContents.on('did-navigate', async (_event: any, _url: string, httpResponseCode: number) => {
if (httpResponseCode == 403) {
// what you want to do
this.settingsManager.debug(`配置界面:登录界面,加载页面失败,HttpStatus:${httpResponseCode},URL:${_url}`);
await this.modal.loadURL('data:text/html;charset=utf-8;base64,55Sx5LqO5aSa5qyh6aKR57mB6K+35rGC5pWw5o2u77yM6LGG55Oj5b2T5YmN5pqC5pe25LiN5Y+v55SoLiDor7fkuo4xMuWwj+aXtuaIljI05bCP5pe25ZCO5YaN6YeN6K+V77yM5oiW6YeN572u5L2g55qE572R57ucKOWmgumHjeaWsOaLqOWPt+aIluabtOaNoue9kee7nCk=');
}else {
this.settingsManager.debug(`配置界面:登录界面,加载页面成功,HttpStatus:${httpResponseCode},URL:${_url}`);
}
});
const session = this.modal.webContents.session; const session = this.modal.webContents.session;
const filter = { const filter = {
urls: ['https://www.douban.com/','https://accounts.douban.com/','https://accounts.douban.com/passport/login'] urls: ['https://www.douban.com/']
}; };
session.webRequest.onSendHeaders(filter, async (details:any) => { session.webRequest.onSendHeaders(filter, async (details:any) => {
const cookies = details.requestHeaders['Cookie']; this.settingsManager.debug(`配置界面:登录界面请求头检测:${details.url}`)
const cookieArr = this.parseCookies(cookies); const headers = details.requestHeaders;
// const wr_name = cookieArr.find((cookie) => cookie.name == 'wr_name').value; if (headers) {
if (cookieArr) { this.settingsManager.debug(`配置界面:登录界面请求检测获取到Cookie`)
let user = await settingsManager.plugin.userComponent.loginCookie(cookieArr); let user = await settingsManager.plugin.userComponent.loginHeaders(headers);
if (user && user.login) { if (user && user.login) {
this.settingsManager.debug(`配置界面:登录界面豆瓣登录成功, 信息:id:${StringUtil.confuse(user.id)}:, 用户名:${StringUtil.confuse(user.name)}`)
session.clearStorageData(() => {
this.settingsManager.debug(`配置界面:登录界面 登录前本地清理缓存成功2`)
});
this.onClose(); this.onClose();
return;
} }
} else { this.settingsManager.debug(`配置界面:登录界面豆瓣登录失败, headers未能成功获取用户信息`)
this.onReload();
} }
}); });
} }
@ -58,6 +86,7 @@ export default class DoubanLoginModel {
async doLogin() { async doLogin() {
try { try {
this.settingsManager.debug(`配置界面:登录界面加载登录页面`)
await this.modal.loadURL('https://accounts.douban.com/passport/login'); await this.modal.loadURL('https://accounts.douban.com/passport/login');
} catch (error) { } catch (error) {
log.error(i18nHelper.getMessage('100101'), error) log.error(i18nHelper.getMessage('100101'), error)
@ -65,10 +94,21 @@ export default class DoubanLoginModel {
} }
onClose() { onClose() {
this.settingsManager.debug(`配置界面:登录界面关闭, 自动退出登录界面`)
// this.modal.destroy();
this.modal.close(); this.modal.close();
} }
onReload() { onReload() {
this.settingsManager.debug(`配置界面:登录界面重新加载`)
this.modal.reload(); this.modal.reload();
} }
private showCloseMessage() {
if(this.settingsManager.plugin.userComponent.isLogin()) {
this.settingsManager.debug(`配置界面:登录界面关闭, 但未检测到登出, 登录失败`)
}else {
this.settingsManager.debug(`配置界面:登录界面关闭, 登录成功`)
}
}
} }

@ -1,7 +1,7 @@
import {DoubanSettingTab} from "../setting/DoubanSettingTab"; import {DoubanSettingTab} from "../setting/DoubanSettingTab";
import {i18nHelper} from "../../lang/helper"; import {i18nHelper} from "../../lang/helper";
import SettingsManager from "../setting/SettingsManager"; import SettingsManager from "../setting/SettingsManager";
import {constructDoubanTokenSettingsUI, constructLoginSettingsUI} from "../setting/BasicSettingsHelper"; import {constructDoubanTokenSettingsUI, constructLoginSettingsUI} from "../setting/LoginSettingsHelper";
import {log} from "../../utils/Logutil"; import {log} from "../../utils/Logutil";
// Credits go to zhaohongxuan's Weread Plugin : https://github.com/zhaohongxuan/obsidian-weread-plugin // Credits go to zhaohongxuan's Weread Plugin : https://github.com/zhaohongxuan/obsidian-weread-plugin
@ -13,6 +13,7 @@ export default class DoubanLogoutModel {
private containerEl: HTMLElement; private containerEl: HTMLElement;
constructor(containerEl: HTMLElement, settingsManager: SettingsManager) { constructor(containerEl: HTMLElement, settingsManager: SettingsManager) {
this.settingsManager = settingsManager; this.settingsManager = settingsManager;
this.settingsManager.debug(`配置界面:初始化登出界面`)
this.containerEl = containerEl; this.containerEl = containerEl;
const { remote } = require('electron'); const { remote } = require('electron');
const { BrowserWindow: RemoteBrowserWindow } = remote; const { BrowserWindow: RemoteBrowserWindow } = remote;
@ -27,6 +28,7 @@ export default class DoubanLogoutModel {
this.modal.show(); this.modal.show();
}); });
this.modal.on('closed', () => { this.modal.on('closed', () => {
this.showCloseMessage();
constructDoubanTokenSettingsUI(this.containerEl, this.settingsManager); constructDoubanTokenSettingsUI(this.containerEl, this.settingsManager);
}); });
const session = this.modal.webContents.session; const session = this.modal.webContents.session;
@ -35,20 +37,34 @@ export default class DoubanLogoutModel {
'https://www.douban.com/accounts/logout'] 'https://www.douban.com/accounts/logout']
}; };
session.webRequest.onSendHeaders(filter, (details:any) => { session.webRequest.onSendHeaders(filter, (details:any) => {
this.settingsManager.debug(`配置界面:登出界面请求头检测:${details.url}`)
const cookies = details.requestHeaders['Cookie']; const cookies = details.requestHeaders['Cookie'];
// const wr_name = cookieArr.find((cookie) => cookie.name == 'wr_name').value; // const wr_name = cookieArr.find((cookie) => cookie.name == 'wr_name').value;
if (cookies && cookies.indexOf('dbcl2') < 0) { // if (cookies && cookies.indexOf('dbcl2') < 0) {
this.settingsManager.debug(`配置界面:登出界面退出登录请求检测成功,准备退出登录`)
this.settingsManager.plugin.userComponent.logout(); this.settingsManager.plugin.userComponent.logout();
this.settingsManager.debug(`配置界面:登出界面退出登录成功`);
this.onClose(); this.onClose();
} // }
}); });
} }
async doLogout() { async doLogout() {
this.settingsManager.debug(`配置界面:登出界面加载登出页面`)
await this.modal.loadURL('https://www.douban.com/accounts/logout?source=main&ck=DfFJ'); await this.modal.loadURL('https://www.douban.com/accounts/logout?source=main&ck=DfFJ');
} }
onClose() { onClose() {
this.settingsManager.debug(`配置界面:登出界面关闭, 自动退出登出界面`);
// this.modal.destroy();
this.modal.close(); this.modal.close();
} }
private showCloseMessage() {
if(this.settingsManager.plugin.userComponent.isLogin()) {
this.settingsManager.debug(`配置界面:登出界面关闭, 但未检测到登出, 退出登录失败`)
}else {
this.settingsManager.debug(`配置界面:登出界面关闭, 退出登录成功`)
}
}
} }

@ -1,28 +1,42 @@
import { import {
App, App,
ButtonComponent, ButtonComponent, DropdownComponent,
DropdownComponent, Modal, SearchComponent, Setting, TextComponent, ValueComponent,
Modal, SearchComponent, Setting,
TextComponent,
ToggleComponent
} from "obsidian"; } from "obsidian";
import DoubanPlugin from "../../main"; import DoubanPlugin from "../../main";
import {i18nHelper} from "src/org/wanxp/lang/helper"; import {i18nHelper} from "src/org/wanxp/lang/helper";
import HandleContext from "../data/model/HandleContext"; import HandleContext from "../data/model/HandleContext";
import {SyncType, SyncTypeRecords} from "../../constant/Constsant";
import { import {
ALL, DEFAULT_SETTINGS_ARRAY_INPUT_SIZE,
DoubanSubjectStateRecords_BOOK_SYNC, DoubanSubjectStateRecords_BROADCAST_SYNC, SupportType, SyncConditionType,
DoubanSubjectStateRecords_MOVIE_SYNC, DoubanSubjectStateRecords_MUSIC_SYNC, DoubanSubjectStateRecords_NOTE_SYNC SyncConditionTypeRecords,
SyncType,
SyncTypeRecords
} from "../../constant/Constsant";
import {
ALL, DoubanSubjectState, DoubanSubjectStateRecords,
DoubanSubjectStateRecords_BOOK_SYNC,
DoubanSubjectStateRecords_BROADCAST_SYNC, DoubanSubjectStateRecords_GAME_SYNC,
DoubanSubjectStateRecords_MOVIE_SYNC,
DoubanSubjectStateRecords_MUSIC_SYNC,
DoubanSubjectStateRecords_NOTE_SYNC,
DoubanSubjectStateRecords_TELEPLAY_SYNC
} from "../../constant/DoubanUserState"; } from "../../constant/DoubanUserState";
import {SyncConfig} from "../sync/model/SyncConfig"; import {SyncConfig} from "../sync/model/SyncConfig";
import {clearInterval} from "timers"; import {clearInterval} from "timers";
import {statSync} from "fs";
import {CreateTemplateSelectParams} from "../setting/model/CreateTemplateSelectParams";
import {FolderSuggest} from "../setting/model/FolderSuggest"; import {FolderSuggest} from "../setting/model/FolderSuggest";
import SettingsManager from "../setting/SettingsManager";
import {DEFAULT_SETTINGS} from "../../constant/DefaultSettings"; import {DEFAULT_SETTINGS} from "../../constant/DefaultSettings";
import {createFileSelectionSetting} from "../setting/TemplateSettingHelper";
import {FileSuggest} from "../setting/model/FileSuggest";
import {getDefaultTemplateContent} from "../../constant/DefaultTemplateContent";
import TimeUtil from "../../utils/TimeUtil";
import SettingsManager from "../setting/SettingsManager";
import {ArraySetting, DEFAULT_SETTINGS_ARRAY_NAME} from "../setting/model/ArraySetting";
import {arraySettingDisplay} from "../setting/ArrayDisplayTypeSettingsHelper";
import {DatePickComponent} from "./DatePickComponent";
import {NumberComponent} from "./NumberComponent";
import {log} from "../../utils/Logutil";
export class DoubanSyncModal extends Modal { export class DoubanSyncModal extends Modal {
plugin: DoubanPlugin; plugin: DoubanPlugin;
@ -54,48 +68,74 @@ export class DoubanSyncModal extends Modal {
const {syncConfig} = syncStatus; const {syncConfig} = syncStatus;
contentEl.createEl("h3", {text: i18nHelper.getMessage('500002')}); contentEl.createEl("h3", {text: i18nHelper.getMessage('500002')});
this.showConfigPan(contentEl, syncConfig, true); this.showConfigPan(contentEl.createDiv('config'), syncConfig, true);
const sliderDiv = contentEl.createEl('div'); const sliderDiv = contentEl.createEl('div');
sliderDiv.addClass('obsidian_douban_sync_slider'); sliderDiv.addClass('obsidian_douban_sync_slider');
const controls = contentEl.createDiv("controls"); const controls = contentEl.createDiv("controls");
const syncButton = new ButtonComponent(controls) const stopButton = new ButtonComponent(controls)
.setButtonText(i18nHelper.getMessage('110009')) .setButtonText(i18nHelper.getMessage('110009'))
.onClick(async () => { .onClick(async () => {
this.close(); this.close();
await this.plugin.statusHolder.stopSync(); await this.plugin.statusHolder.stopSync();
}) })
const cancelButton = new ButtonComponent(controls) const backgroundButton = new ButtonComponent(controls)
.setButtonText(i18nHelper.getMessage('110010')) .setButtonText(i18nHelper.getMessage('110010'))
.onClick(() => { .onClick(() => {
this.close(); this.close();
}); });
cancelButton.setClass("obsidian_douban_search_button");
syncButton.setClass("obsidian_douban_search_button"); this.showProgress(sliderDiv, backgroundButton, stopButton);
this.showProgress(sliderDiv, syncButton);
this.timer = setInterval(() => { this.timer = setInterval(() => {
this.showProgress(sliderDiv,syncButton); this.showProgress(sliderDiv,backgroundButton, stopButton);
}, 1000); }, 1000);
backgroundButton.setClass("obsidian_douban_status_button");
stopButton.setClass("obsidian_douban_status_button");
} }
private showProgress(sliderDiv: HTMLDivElement, button:ButtonComponent) { private showProgress(sliderDiv: HTMLDivElement, backgroundButton:ButtonComponent, stopButton:ButtonComponent) {
sliderDiv.empty();
new Setting(sliderDiv);
let progress = sliderDiv.createDiv('progress');
const {syncStatus} = this.plugin.statusHolder; const {syncStatus} = this.plugin.statusHolder;
if (!this.plugin.statusHolder.syncStarted) { if (!this.plugin.statusHolder.syncStarted) {
sliderDiv.innerHTML = `<p> progress.innerHTML = `<p>
<label for="file">${i18nHelper.getMessage('110033')}</label> <label for="file">${i18nHelper.getMessage('110033')}</label>
<progress class="obsidian_douban_sync_slider" max="${syncStatus.getTotal()}" value="${syncStatus.getHandle()}"> </progress> <span> ${syncStatus.getHandle()}/${syncStatus.getTotal()}:${i18nHelper.getMessage('110036')} </span> <progress class="obsidian_douban_sync_slider" max="${syncStatus.getTotal() == 0 ? 1:syncStatus.getTotal()}" value="${syncStatus.getHasHandle()}"> </progress> <span> ${syncStatus.getHasHandle()}/${syncStatus.getTotal()}:${i18nHelper.getMessage('110036')} </span>
</p>` </p>
button.setDisabled(true); <p>
<label for="file">${i18nHelper.getMessage('110092')}</label>
<span>${i18nHelper.getMessage('110090', syncStatus.getTypeName(), syncStatus.getScopeName(), syncStatus.getAllTotal(), syncStatus.getTotal())}</span>
</p>
<p>
<label for="file">${i18nHelper.getMessage('110091')}</label>
<span>${syncStatus.getMessage()}</span>
</p>
`
backgroundButton.setDisabled(true);
stopButton.setButtonText(i18nHelper.getMessage('110036'))
return; return;
} }
sliderDiv.innerHTML = `<p> progress.innerHTML = `<p>
<label for="file">${i18nHelper.getMessage('110033')}</label> <label for="file">${i18nHelper.getMessage('110033')}</label>
<progress class="obsidian_douban_sync_slider" max="${syncStatus.getTotal()}" value="${syncStatus.getHandle()}"> </progress> <span> ${syncStatus.getHandle()}/${syncStatus.getTotal()} </span> <progress class="obsidian_douban_sync_slider" max="${syncStatus.getTotal() == 0 ? 1:syncStatus.getTotal()}" value="${syncStatus.getHasHandle()}"> </progress> <span> ${syncStatus.getTotal() == 0 ? i18nHelper.getMessage('110043') : syncStatus.getHasHandle() + '/' + syncStatus.getTotal()}
</p>`} ${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + TimeUtil.estimateTimeMsg(syncStatus.getNeedHandled()-syncStatus.getHandle(), syncStatus.getOverSize())} </span>
</p>
<p>
<label for="file">${i18nHelper.getMessage('110092')}</label>
<span>${i18nHelper.getMessage('110090', syncStatus.getTypeName(), syncStatus.getScopeName(), syncStatus.getAllTotal(), syncStatus.getTotal())}</span>
</p>
<p>
<label for="file">${i18nHelper.getMessage('110091')}</label>
<span>${syncStatus.getMessage()}</span>
</p>
`}
private showSyncConfig(contentEl: HTMLElement) { private showSyncConfig(contentEl: HTMLElement) {
if (this.timer != null) { if (this.timer != null) {
@ -105,11 +145,27 @@ export class DoubanSyncModal extends Modal {
const {settings} = this.plugin; const {settings} = this.plugin;
let syncConfig:SyncConfig = {syncType: SyncType.movie, scope: ALL, let syncConfig:SyncConfig = {syncType: SyncType.movie, scope: ALL,
force: false, force: false,
outputFolder: (settings.dataFilePath == '' || settings.dataFilePath == null) ? DEFAULT_SETTINGS.dataFilePath : settings.dataFilePath, dataFilePath: (settings.dataFilePath == '' || settings.dataFilePath == null) ? DEFAULT_SETTINGS.dataFilePath : settings.dataFilePath,
dataFileNamePath: (settings.dataFileNamePath == '' || settings.dataFileNamePath == null) ? DEFAULT_SETTINGS.dataFileNamePath : settings.dataFileNamePath}; dataFileNamePath: (settings.dataFileNamePath == '' || settings.dataFileNamePath == null) ? DEFAULT_SETTINGS.dataFileNamePath : settings.dataFileNamePath,
this.showConfigPan(contentEl, syncConfig, false); cacheImage: ( settings.cacheImage == null) ? DEFAULT_SETTINGS.cacheImage : settings.cacheImage,
cacheHighQuantityImage: ( settings.cacheHighQuantityImage == null) ? DEFAULT_SETTINGS.cacheHighQuantityImage : settings.cacheHighQuantityImage,
attachmentPath: (settings.attachmentPath == '' || settings.attachmentPath == null) ? DEFAULT_SETTINGS.attachmentPath : settings.attachmentPath,
attachmentFileName: (settings.attachmentFileName == '' || settings.attachmentFileName == null) ? DEFAULT_SETTINGS.attachmentFileName : settings.attachmentFileName,
templateFile: (settings.movieTemplateFile == '' || settings.movieTemplateFile == null) ? DEFAULT_SETTINGS.movieTemplateFile : settings.movieTemplateFile,
incrementalUpdate: true,
syncConditionType: SyncConditionType.ALL,
syncConditionDateFromValue: TimeUtil.getLastMonth(),
syncConditionDateToValue: new Date(),
syncConditionCountFromValue: 1,
syncConditionCountToValue: 30
};
this.showConfigPan(contentEl.createDiv('config'), syncConfig, false);
const controls = contentEl.createDiv("controls"); const controls = contentEl.createDiv("controls");
const cancelButton = new ButtonComponent(controls)
.setButtonText(i18nHelper.getMessage('110005'))
.onClick(() => {
this.close();
});
const syncButton = new ButtonComponent(controls) const syncButton = new ButtonComponent(controls)
.setButtonText(i18nHelper.getMessage('110007')) .setButtonText(i18nHelper.getMessage('110007'))
.onClick(async () => { .onClick(async () => {
@ -120,70 +176,32 @@ export class DoubanSyncModal extends Modal {
if(!this.plugin.statusHolder.startSync(syncConfig)) { if(!this.plugin.statusHolder.startSync(syncConfig)) {
return; return;
} }
this.updateContextByConfig(syncConfig);
this.show(contentEl); this.show(contentEl);
await this.plugin.sync(syncConfig, this.context); await this.plugin.sync(this.context);
}) })
const cancelButton = new ButtonComponent(controls)
.setButtonText(i18nHelper.getMessage('110005'))
.onClick(() => {
this.close();
});
cancelButton.setClass("obsidian_douban_search_button");
syncButton.setClass("obsidian_douban_search_button"); syncButton.setClass("obsidian_douban_search_button");
cancelButton.setClass("obsidian_douban_search_button");
}
private updateContextByConfig(syncConfig: SyncConfig) {
const { context} = this;
context.syncConfig = syncConfig;
context.syncActive = true;
} }
private showConfigPan(contentEl: HTMLElement, config:SyncConfig, disable:boolean) { private showConfigPan(contentEl: HTMLElement, config:SyncConfig, disable:boolean) {
const typeSelections = contentEl.createDiv('type-selection'); new Setting(contentEl);
const typeSelectionLabel = typeSelections.createEl('label'); this.showTypeDropdown(contentEl, config, disable);
typeSelectionLabel.setText(i18nHelper.getMessage('110030')) this.showCondition(contentEl, config, disable);
typeSelectionLabel.addClass('obsidian_douban_settings_text') // this.showOutputFolderSelections(contentEl, config, disable);
const syncTypeDropdown = new DropdownComponent(typeSelections); // this.showOutiFleName(contentEl, config, disable);
const scopeSelections = contentEl.createDiv("scope-selection"); // this.showAttachmentsFileConfig(contentEl, config, disable);
syncTypeDropdown.addOptions(SyncTypeRecords) this.showUpdateAllConfig(contentEl, config, disable);
.setValue(config.syncType) this.showForceUpdateConfig(contentEl, config, disable);
.onChange((value) => {
config.syncType = value;
this.openScopeDropdown(scopeSelections, config, disable);
});
this.openScopeDropdown(scopeSelections, config, disable);
const forceSelections = contentEl.createDiv('force-selection');
let forceLabel = forceSelections.createEl('label');
forceLabel.setText(i18nHelper.getMessage('110031'));
forceLabel.addClass('obsidian_douban_settings_text');
forceLabel.addClass('obsidian_douban_sync_config_text');
const toggle:ToggleComponent = new ToggleComponent(forceSelections)
.setTooltip(i18nHelper.getMessage('500110'))
.setValue(config.force)
.onChange((value) => {
config.force = value;
});
if (disable) {
syncTypeDropdown.setDisabled(true);
toggle.setDisabled(true);
}
const folderSelections = contentEl.createDiv('folder-selection');
let folderLabel = folderSelections.createEl('label');
folderLabel.setText(i18nHelper.getMessage('110034'));
folderLabel.addClass('obsidian_douban_settings_text');
folderLabel.addClass('obsidian_douban_sync_config_text');
this.createFolderSetting(folderSelections, config, disable);
const fileName = contentEl.createDiv('fileName-item');
let fileNameLabel = fileName.createEl('label');
fileNameLabel.setText(i18nHelper.getMessage('110035'));
fileNameLabel.addClass('obsidian_douban_settings_text');
fileNameLabel.addClass('obsidian_douban_sync_config_text');
fileNameLabel.addClass('obsidian_douban_sync_config');
this.constructOutiFleName(fileName, config, disable);
fileName.addClass('obsidian_douban_sync_config');
folderSelections.addClass('obsidian_douban_sync_config');
typeSelections.addClass('obsidian_douban_sync_config');
scopeSelections.addClass('obsidian_douban_sync_config');
forceSelections.addClass('obsidian_douban_sync_config');
} }
async onClose() { async onClose() {
@ -195,10 +213,6 @@ export class DoubanSyncModal extends Modal {
} }
private openScopeDropdown(contentEl:HTMLDivElement, config: SyncConfig, disable:boolean) { private openScopeDropdown(contentEl:HTMLDivElement, config: SyncConfig, disable:boolean) {
contentEl.empty();
let scopeLabel = contentEl.createEl('label');
scopeLabel.addClass('obsidian_douban_settings_text');
scopeLabel.setText(i18nHelper.getMessage('110032'));
switch (config.syncType) { switch (config.syncType) {
case SyncType.movie: case SyncType.movie:
this.showScopeDropdown(contentEl, DoubanSubjectStateRecords_MOVIE_SYNC, config, disable); this.showScopeDropdown(contentEl, DoubanSubjectStateRecords_MOVIE_SYNC, config, disable);
@ -215,56 +229,367 @@ export class DoubanSyncModal extends Modal {
case SyncType.music: case SyncType.music:
this.showScopeDropdown(contentEl, DoubanSubjectStateRecords_MUSIC_SYNC, config, disable); this.showScopeDropdown(contentEl, DoubanSubjectStateRecords_MUSIC_SYNC, config, disable);
break; break;
case SyncType.teleplay:
this.showScopeDropdown(contentEl, DoubanSubjectStateRecords_TELEPLAY_SYNC, config, disable);
break;
case SyncType.game:
config.scope = DoubanSubjectState.collect;
this.showScopeDropdown(contentEl, DoubanSubjectStateRecords_GAME_SYNC, config, disable);
break;
} }
} }
private showScopeDropdown(contentEl:HTMLDivElement, scopeSelections: Record<string, string>, config: SyncConfig, disable:boolean) { private showTypeDropdown(containerEl:HTMLElement, config: SyncConfig, disable:boolean) {
const syncScopeTypeDropdown = new DropdownComponent(contentEl) const settings = new Setting(containerEl);
.addOptions(scopeSelections) const scopeSelections = containerEl.createDiv("scope-selection");
.setValue(config.scope) // const templateFile:HTMLDivElement = containerEl.createDiv('template-file-path-selection');
settings
.setName(i18nHelper.getMessage('110030'))
.addDropdown((dropdown) => {
dropdown.addOptions(SyncTypeRecords)
.setValue(config.syncType)
.onChange((value) => { .onChange((value) => {
config.syncType = value;
config.templateFile = this.getDefaultTemplatePath(value);
this.openScopeDropdown(scopeSelections, config, disable);
// this.showTemplateFileSelectionSetting(templateFile, config, disable);
});
}).setDisabled(disable);
this.openScopeDropdown(scopeSelections, config, disable);
// this.showTemplateFileSelectionSetting(templateFile, config, disable);
}
private getDefaultTemplatePath(value: string) {
let result:string = "";
const {settings} = this.plugin;
switch (value) {
case SyncType.movie:
result = (settings.movieTemplateFile == '' || settings.movieTemplateFile == null) ? DEFAULT_SETTINGS.movieTemplateFile : settings.movieTemplateFile
break;
case SyncType.book:
result = (settings.bookTemplateFile == '' || settings.bookTemplateFile == null) ? DEFAULT_SETTINGS.bookTemplateFile : settings.bookTemplateFile
break;
case SyncType.music:
result = (settings.musicTemplateFile == '' || settings.musicTemplateFile == null) ? DEFAULT_SETTINGS.musicTemplateFile : settings.musicTemplateFile
break;
case SyncType.teleplay:
result = (settings.teleplayTemplateFile == '' || settings.teleplayTemplateFile == null) ? DEFAULT_SETTINGS.teleplayTemplateFile : settings.teleplayTemplateFile
break;
case SyncType.game:
result = (settings.gameTemplateFile == '' || settings.gameTemplateFile == null) ? DEFAULT_SETTINGS.gameTemplateFile : settings.gameTemplateFile
break;
}
return result;
}
private showScopeDropdown(containerEl:HTMLDivElement, scopeSelections: Record<string, string>, config: SyncConfig, disable:boolean) {
containerEl.empty();
new Setting(containerEl)
.setName(i18nHelper.getMessage('110032'))
.addDropdown((dropdown) => {
dropdown.addOptions(scopeSelections)
dropdown.setValue(config.scope)
.onChange(async (value: string) => {
config.scope = value; config.scope = value;
}); });
if (disable) { }).setDisabled(disable);
syncScopeTypeDropdown.setDisabled(true);
}
} }
private createFolderSetting(contentEl:HTMLDivElement, config: SyncConfig, disable:boolean) { private showOutiFleName(containerEl: HTMLElement, config: SyncConfig, disable:boolean) {
const {settings} = this.plugin; const dataFilePathSetting = new Setting(containerEl)
const placeHolder = (settings.dataFilePath == '' || settings.dataFilePath == null) ? DEFAULT_SETTINGS.dataFilePath : settings.dataFilePath; .setName(i18nHelper.getMessage('121601'))
let outputFolder = placeHolder; .setDesc(i18nHelper.getMessage('121602'))
if (config.outputFolder) { .addText((textField) => {
outputFolder = config.outputFolder; textField.setPlaceholder(i18nHelper.getMessage('121602'))
} .setValue(config.dataFileNamePath)
const search = new TextComponent(contentEl);
new FolderSuggest(this.plugin.app, search.inputEl);
search.setValue(outputFolder)
.setPlaceholder(placeHolder)
.onChange(async (value:string) => {
config.outputFolder = value;
})
if (disable) {
search.setDisabled(true);
}
}
private constructOutiFleName(containerEl: HTMLElement, config: SyncConfig, disable:boolean) {
const {settings} = this.plugin;
const placeHolder =(settings.dataFileNamePath == '' || settings.dataFileNamePath == null) ? DEFAULT_SETTINGS.dataFileNamePath : settings.dataFileNamePath;
let dataFileNamePath = placeHolder;
if (config.dataFileNamePath) {
dataFileNamePath = config.dataFileNamePath;
}
const textComponent = new TextComponent(containerEl);
textComponent.setPlaceholder(placeHolder)
.setValue(dataFileNamePath)
.onChange(async (value) => { .onChange(async (value) => {
config.dataFileNamePath = value; config.dataFileNamePath = value
}); });
if (disable) { })
textComponent.setDisabled(true); .setDisabled(disable);
}
showOutputFolderSelections(containerEl: HTMLElement, config: SyncConfig, disable:boolean) {
new Setting(containerEl)
.setName( i18nHelper.getMessage('121501'))
.setDesc( i18nHelper.getMessage('121502'))
.addSearch(async (search: SearchComponent) => {
new FolderSuggest(this.app, search.inputEl);
// @ts-ignore
search.setValue(config.dataFilePath)
// @ts-ignore
.setPlaceholder(i18nHelper.getMessage('121503'))
.onChange(async (value: string) => {
config.dataFilePath = value;
});
})
.setDisabled(disable);
}
showTemplateFileSelectionSetting(containerEl: HTMLElement, config: SyncConfig, disable:boolean) {
containerEl.empty();
const key:string = this.getKey(config.syncType);
// @ts-ignore
let setting = new Setting(containerEl)
.setName(i18nHelper.getMessage('121101'))
.setDesc(i18nHelper.getMessage('121102'))
.addSearch(async (search: SearchComponent) => {
new FileSuggest(this.app, search.inputEl);
// @ts-ignore
search.setValue(config.templateFile)
// @ts-ignore
.onChange(async (value: string) => {
config.templateFile = value;
});
})
.setDisabled(disable);
setting.addExtraButton((button) => {
button
.setIcon('copy')
.setTooltip(i18nHelper.getMessage('121903'))
.onClick(async () => {
// @ts-ignore
navigator.clipboard.writeText(getDefaultTemplateContent(key));
});
});
setting.addExtraButton((button) => {
button
.setIcon('document')
.setTooltip(i18nHelper.getMessage('121901'))
.onClick(async () => {
// @ts-ignore
navigator.clipboard.writeText(getDefaultTemplateContent(key, false))
});
});
}
private getKey(supportType: string) {
return supportType + 'TemplateFile';
}
showForceUpdateConfig(containerEl: HTMLElement, config: SyncConfig, disable:boolean) {
new Setting(containerEl)
.setName(i18nHelper.getMessage('110031'))
.setDesc(i18nHelper.getMessage('500110'))
.addToggle((toggleComponent) => {
toggleComponent
// .setTooltip(i18nHelper.getMessage('121403'))
.setValue(config.force)
.onChange(async (value) => {
config.force = value;
});
})
.setDisabled(disable);
}
showAttachmentsFileConfig(containerEl: HTMLElement, config: SyncConfig, disable:boolean) {
const settings = new Setting(containerEl);
let attachmentFileEl = containerEl.createDiv('attachment-file-path-selection');
settings.setName(i18nHelper.getMessage('121430'))
.setDesc(i18nHelper.getMessage('121431'))
.addToggle((toggleComponent) => {
toggleComponent
// .setTooltip(i18nHelper.getMessage('121403'))
.setValue(config.cacheImage)
.onChange(async (value) => {
config.cacheImage = value;
this.showAttachmentPathSelections(value, attachmentFileEl, config, disable);
});
})
.setDisabled(disable);
this.showAttachmentPathSelections(config.cacheImage, attachmentFileEl, config, disable);
}
showAttachmentPathSelections(show:boolean, containerEl: HTMLElement, config: SyncConfig, disable:boolean) {
containerEl.empty();
if (!show) {
return;
}
new Setting(containerEl)
.setName( i18nHelper.getMessage('121432'))
.setDesc( i18nHelper.getMessage('121433'))
.addSearch(async (search: SearchComponent) => {
new FolderSuggest(this.plugin.app, search.inputEl);
// @ts-ignore
search.setValue(config.attachmentPath)
// @ts-ignore
.setPlaceholder(i18nHelper.getMessage('121434'))
.onChange(async (value: string) => {
config.attachmentPath = value;
});
})
.setDisabled(disable);
new Setting(containerEl)
.setName( i18nHelper.getMessage('121452'))
.setDesc( i18nHelper.getMessage('121453'))
.addSearch(async (search: SearchComponent) => {
new FolderSuggest(this.plugin.app, search.inputEl);
// @ts-ignore
search.setValue(config.attachmentFileName)
// @ts-ignore
.setPlaceholder(i18nHelper.getMessage('121454'))
.onChange(async (value: string) => {
config.attachmentFileName = value;
});
})
.setDisabled(disable);
new Setting(containerEl)
.setName(i18nHelper.getMessage('121435'))
.setDesc(i18nHelper.getMessage('121438'))
.addToggle((toggleComponent) => {
toggleComponent
.setValue(config.cacheHighQuantityImage)
.onChange(async (value) => {
config.cacheHighQuantityImage = value;
});
})
.setDisabled(disable);
}
showUpdateAllConfig(containerEl: HTMLElement, config: SyncConfig, disable:boolean) {
new Setting(containerEl)
.setName(i18nHelper.getMessage('110039'))
.setDesc(i18nHelper.getMessage('110040'))
.addToggle((toggleComponent) => {
toggleComponent
.setTooltip(i18nHelper.getMessage('110040'))
.setValue(config.incrementalUpdate)
.onChange(async (value) => {
config.incrementalUpdate = value;
});
})
.setDisabled(disable);
}
private showCondition(contentEl: HTMLElement, config: SyncConfig, disable: boolean) {
showConditionItem(contentEl.createDiv("sync-douban-condition"), this.plugin.settingsManager, config, disable);
} }
} }
function showConditionItem(containerEl: HTMLElement, manager: SettingsManager, config: SyncConfig, disable: boolean) {
containerEl.empty();
const condition = new Setting(containerEl).setName(i18nHelper.getMessage('110070'))
const conditionDesc = condition.descEl.createDiv('sync-douban-condition-desc');
new DropdownComponent(conditionDesc).addOptions(SyncConditionTypeRecords)
.setValue(config.syncConditionType)
.onChange((value) => {
config.syncConditionType = value;
showConditionItem(containerEl, manager, config, disable);
}).setDisabled(disable);
showConditionItemInput(conditionDesc, config, disable);
}
function showConditionItemInput(containerEl: HTMLElement, config: SyncConfig, disable: boolean) {
if (config.syncConditionType == SyncConditionType.CUSTOM_ITEM) {
showCustomInputCount(containerEl, config, disable);
}else if (config.syncConditionType == SyncConditionType.CUSTOM_TIME) {
showCustomInputTime(containerEl, config, disable);
}
}
function showCustomInputCount(containerEl: HTMLElement, config: SyncConfig, disable: boolean) {
containerEl.createEl('span', { text: ' ' })
containerEl.createEl('span', { text: i18nHelper.getMessage('110077') })
containerEl.createEl('span', { text: i18nHelper.getMessage('110078') })
const fromField = new TextComponent(containerEl);
fromField.setPlaceholder(i18nHelper.getMessage('110080'))
.setValue(config.syncConditionCountFromValue + '')
.onChange(async (value) => {
if (!value) {
config.syncConditionCountFromValue = 1;
return;
}
try {
config.syncConditionCountFromValue = parseInt(value);
}catch (e) {
log.notice(i18nHelper.getMessage('112080'))
}
}).setDisabled(disable);
let fromEl = fromField.inputEl;
fromEl.addClass('obsidian_douban_settings_input')
fromEl.style.width ='20%';
containerEl.appendChild(fromEl);
const lang = window.localStorage.getItem('language');
if (lang == 'zh') {
containerEl.createEl('span', {text: i18nHelper.getMessage('110073')})
}
containerEl.createEl('span', { text: i18nHelper.getMessage('110079') })
containerEl.createEl('span', { text: i18nHelper.getMessage('110078') })
const toField = new TextComponent(containerEl);
toField.setPlaceholder(i18nHelper.getMessage('110080'))
.setValue(config.syncConditionCountToValue + '')
.onChange(async (value) => {
if (!value) {
config.syncConditionCountToValue = 30;
return;
}
try {
config.syncConditionCountToValue = parseInt(value);
}catch (e) {
log.notice(i18nHelper.getMessage('112080'))
}
}).setDisabled(disable);
let toEl = toField.inputEl;
toEl.addClass('obsidian_douban_settings_input')
toEl.style.width ='20%';
containerEl.appendChild(toEl);
if (lang == 'zh') {
containerEl.createEl('span', {text: i18nHelper.getMessage('110073')})
}
containerEl.createEl('span', {text: ' '})
const buttopn = new ButtonComponent(containerEl).setIcon('help').setTooltip(i18nHelper.getMessage('110095'))
containerEl.appendChild(buttopn.buttonEl);
}
function showCustomInputTime(containerEl: HTMLElement, config: SyncConfig, disable: boolean) {
containerEl.createEl('span', { text: i18nHelper.getMessage('110077') })
const fromDateField = new TextComponent(containerEl);
const fromDateEl = fromDateField.inputEl;
fromDateEl.type = 'date';
fromDateEl.value = config.syncConditionDateFromValue ? config.syncConditionDateFromValue.toISOString().substring(0, 10) : TimeUtil.getLastMonth().toISOString().substring(0, 10);
fromDateField.setPlaceholder(i18nHelper.getMessage('110075'))
.setValue(config.syncConditionDateFromValue ? config.syncConditionDateFromValue.toISOString().substring(0, 10) : TimeUtil.getLastMonth().toISOString().substring(0, 10))
.onChange(async (value) => {
if (!value) {
return;
}
try {
config.syncConditionDateFromValue = new Date(value);
}catch (e) {
log.notice(i18nHelper.getMessage('110082'))
}
}).setDisabled(disable);
fromDateEl.addClass('obsidian_douban_settings_input')
containerEl.appendChild(fromDateEl);
containerEl.createEl('span', { text: i18nHelper.getMessage('110079') })
const toDateField = new TextComponent(containerEl);
let toDateEl = toDateField.inputEl;
toDateEl.type = 'date';
toDateEl.value = config.syncConditionDateToValue ? config.syncConditionDateToValue.toISOString().substring(0, 10) : new Date().toISOString().substring(0, 10);
toDateField.setPlaceholder(i18nHelper.getMessage('110075'))
.setValue(config.syncConditionDateToValue ? config.syncConditionDateToValue.toISOString().substring(0, 10) : new Date().toISOString().substring(0, 10))
.onChange(async (value) => {
if (!value) {
return;
}
try {
config.syncConditionDateToValue = new Date(value);
}catch (e) {
log.notice(i18nHelper.getMessage('110082'))
}
}).setDisabled(disable);
toDateEl.addClass('obsidian_douban_settings_input')
containerEl.appendChild(toDateEl);
new ButtonComponent(containerEl).setIcon('help').setTooltip(i18nHelper.getMessage('110095'))
} }

@ -0,0 +1,26 @@
/**
*
* TextComponent
*/
import {TextComponent} from 'obsidian';
export class NumberComponent extends TextComponent {
constructor(container: HTMLElement, value: number = 0) {
super(container);
this.inputEl.type = 'date';
this.inputEl.value = value.toString();
}
getValue(): string {
return this.inputEl.value;
}
//当输入框输入的内容不是数字时,则回退到之前的值
// onChanged() {
// if (isNaN(Number(this.inputEl.value))) {
// this.inputEl.value = this.inputEl.value.slice(0, -1);
// }
// }
}

@ -1,14 +1,16 @@
import DoubanPlugin from "../../../main"; import DoubanPlugin from "../../../main";
import DoubanSubject, {DoubanParameter} from '../model/DoubanSubject'; import DoubanSubject, {DoubanParameterName} from '../model/DoubanSubject';
import DoubanSubjectLoadHandler from "./DoubanSubjectLoadHandler"; import DoubanSubjectLoadHandler from "./DoubanSubjectLoadHandler";
import {moment, request, RequestUrlParam, TFile} from "obsidian"; import {moment, Platform, TFile} from "obsidian";
import {i18nHelper} from 'src/org/wanxp/lang/helper'; import {i18nHelper} from 'src/org/wanxp/lang/helper';
import {log} from "src/org/wanxp/utils/Logutil"; import {log} from "src/org/wanxp/utils/Logutil";
import {CheerioAPI, load} from "cheerio"; import {CheerioAPI, load} from "cheerio";
import YamlUtil from "../../../utils/YamlUtil"; import YamlUtil, {TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil";
import { import {
BasicConst, BasicConst,
DataValueType,
PersonNameMode, PersonNameMode,
PropertyName,
SearchHandleMode, SearchHandleMode,
SupportType, SupportType,
TemplateKey, TemplateKey,
@ -19,10 +21,20 @@ import HandleResult from "../model/HandleResult";
import {getDefaultTemplateContent} from "../../../constant/DefaultTemplateContent"; import {getDefaultTemplateContent} from "../../../constant/DefaultTemplateContent";
import StringUtil from "../../../utils/StringUtil"; import StringUtil from "../../../utils/StringUtil";
import {DEFAULT_SETTINGS} from "../../../constant/DefaultSettings"; import {DEFAULT_SETTINGS} from "../../../constant/DefaultSettings";
import {DoubanUserParameter, UserStateSubject} from "../model/UserStateSubject"; import {DoubanUserParameter, DoubanUserParameterName, UserStateSubject} from "../model/UserStateSubject";
import {DoubanSubjectState, DoubanSubjectStateRecords} from "../../../constant/DoubanUserState"; import {
import DoubanLoginModel from "../../component/DoubanLoginModel"; DoubanSubjectState,
import DoubanHumanCheckModel from "../../component/DoubanHumanCheckModel"; DoubanSubjectStateRecords,
DoubanSubjectStateRecords_KEY_WORD_TYPE
} from "../../../constant/DoubanUserState";
import {Person} from "schema-dts";
import HttpUtil from "../../../utils/HttpUtil";
import HtmlUtil from "../../../utils/HtmlUtil";
import {VariableUtil} from "../../../utils/VariableUtil";
import {DataField} from "../../../utils/model/DataField";
import NumberUtil from "../../../utils/NumberUtil";
import {DoubanHttpUtil} from "../../../utils/DoubanHttpUtil";
import {logger} from "bs-logger";
export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject> implements DoubanSubjectLoadHandler<T> { export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject> implements DoubanSubjectLoadHandler<T> {
@ -34,123 +46,90 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
} }
async parse(extract: T, context: HandleContext): Promise<HandleResult> { async parse(extract: T, context: HandleContext): Promise<HandleResult> {
let template: string = await this.getTemplate(extract, context); const template: string = await this.getTemplate(extract, context);
await this.saveImage(extract, context); const variableMap = this.buildVariableMap(extract, context);
let frontMatterStart: number = template.indexOf(BasicConst.YAML_FRONT_MATTER_SYMBOL, 0); this.parseUserInfo(template, variableMap, extract, context);
let frontMatterEnd: number = template.indexOf(BasicConst.YAML_FRONT_MATTER_SYMBOL, frontMatterStart + 1); this.parseVariable(template, variableMap, extract, context);
let frontMatter: string = ''; await this.saveImage(extract, context, variableMap);
let frontMatterBefore: string = '';
let frontMatterAfter: string = ''; const frontMatterStart: number = template.indexOf(BasicConst.YAML_FRONT_MATTER_SYMBOL, 0);
let result: string = ''; const frontMatterEnd: number = template.indexOf(BasicConst.YAML_FRONT_MATTER_SYMBOL, frontMatterStart + 1);
let frontMatter = '';
let frontMatterBefore = '';
let frontMatterAfter = '';
let result = '';
if (frontMatterStart > -1 && frontMatterEnd > -1) { if (frontMatterStart > -1 && frontMatterEnd > -1) {
frontMatterBefore = template.substring(0, frontMatterStart); frontMatterBefore = template.substring(0, frontMatterStart);
frontMatter = template.substring(frontMatterStart, frontMatterEnd + 3); frontMatter = template.substring(frontMatterStart, frontMatterEnd + 3);
frontMatterAfter = template.substring(frontMatterEnd + 3); frontMatterAfter = template.substring(frontMatterEnd + 3);
if (frontMatterBefore.length > 0) { if (frontMatterBefore.length > 0) {
frontMatterBefore = this.parsePartText(frontMatterBefore, extract, context); frontMatterBefore = this.parsePartText(frontMatterBefore, extract, context, variableMap);
} }
if (frontMatterAfter.length > 0) { if (frontMatterAfter.length > 0) {
frontMatterAfter = this.parsePartText(frontMatterAfter, extract, context); frontMatterAfter = this.parsePartText(frontMatterAfter, extract, context, variableMap);
} }
if (frontMatter.length > 0) { if (frontMatter.length > 0) {
frontMatter = this.parsePartText(frontMatter, extract, context, TemplateTextMode.YAML); frontMatter = this.parsePartYml(frontMatter, extract, context, variableMap);
} }
result = frontMatterBefore + frontMatter + frontMatterAfter; result = frontMatterBefore + frontMatter + frontMatterAfter;
} else { } else {
result = this.parsePartText(template, extract, context); result = this.parsePartText(template, extract, context, variableMap);
} }
let fileName: string = ''; let filePath = '';
if (SearchHandleMode.FOR_CREATE == context.mode) { if (SearchHandleMode.FOR_CREATE == context.mode) {
fileName = this.parsePartText(this.getFileName(context), extract, context); filePath = this.parsePartPath(this.getFilePath(context), extract, context, variableMap);
} }
let fileName = '';
return {content: result, fileName: fileName, subject:extract}; if (SearchHandleMode.FOR_CREATE == context.mode) {
fileName = this.parsePartPath(this.getFileName(context), extract, context, variableMap);
}
return {content: result,filePath: filePath, fileName: fileName, subject:extract};
} }
private getFileName(context: HandleContext): string { private getFileName(context: HandleContext): string {
if (context.dataFileNamePath) { const {syncConfig} = context;
return context.dataFileNamePath; if (syncConfig) {
return syncConfig.dataFileNamePath;
} }
const {dataFileNamePath} = context.settings; const {dataFileNamePath} = context.settings;
return dataFileNamePath ? dataFileNamePath : DEFAULT_SETTINGS.dataFileNamePath; return dataFileNamePath ? dataFileNamePath : DEFAULT_SETTINGS.dataFileNamePath;
} }
/** private getFilePath(context: HandleContext): string {
* const {syncConfig} = context;
* @param text if (syncConfig) {
* @param textMode return syncConfig.dataFilePath;
*/
handleSpecialText(text: string, textMode: TemplateTextMode): string {
let result = text;
switch (textMode) {
case TemplateTextMode.YAML:
result = YamlUtil.handleText(text);
break;
} }
return result; const {dataFilePath} = context.settings;
return dataFilePath ? dataFilePath : DEFAULT_SETTINGS.dataFilePath;
} }
/**
*
* @param array
* @param settings
* @param textMode
*/
handleContentArray(array: any[], context: HandleContext, textMode: TemplateTextMode): string {
let result;
switch (textMode) {
case TemplateTextMode.YAML:
result = array.map(YamlUtil.handleText).join(', ');
break;
default:
result = array.join(context.settings.arraySpilt);
}
return result;
}
/**
*
* @param value
* @param textMode
* @param settings
*/
handleSpecialContent(value: any, textMode: TemplateTextMode = TemplateTextMode.NORMAL, context: HandleContext = null): string {
let result;
if (!value) {
return '';
}
if (value instanceof Array) {
result = this.handleContentArray(value, context, textMode);
} else if (value instanceof Number) {
result = value.toString();
} else {
result = this.handleSpecialText(value, textMode);
}
return result;
}
abstract getSupportType(): SupportType; abstract getSupportType(): SupportType;
abstract parseText(beforeContent: string, extract: T, context: HandleContext, textMode: TemplateTextMode): string; abstract parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: T, context: HandleContext): void;
abstract support(extract: DoubanSubject): boolean; abstract support(extract: DoubanSubject): boolean;
handle(url: string, context: HandleContext): void { async handle(id: string, context: HandleContext): Promise<T> {
let headers = JSON.parse(context.settings.searchHeaders); const url:string = this.getSubjectUrl(id);
headers.Cookie = context.settings.loginCookiesContent; context.plugin.settingsManager.debug(`开始请求地址:${url}`)
const requestUrlParam: RequestUrlParam = { context.plugin.settingsManager.debug(`(注意:请勿向任何人透露你的Cookie,此处若需要截图请**打码**)请求header:${context.settings.loginHeadersContent}`)
url: url, return await DoubanHttpUtil.httpRequestGet(url, context.plugin.settingsManager.getHeaders(), context.plugin.settingsManager)
method: "GET",
headers: headers,
throw: true
};
request(requestUrlParam)
.then(s => this.humanCheck(s, url))
.then(load) .then(load)
.then(data => this.analysisUserState(data, context)) .then(data => this.analysisUserState(data, context))
.then(({data, userState}) => { .then(({data, userState}) => {
let sub = this.parseSubjectFromHtml(data); let guessType = this.getSupportType();
if (context.syncActive) {
guessType = this.getGuessType(data);
}
const sub = this.parseSubjectFromHtml(data, context);
sub.userState = userState; sub.userState = userState;
sub.guessType = guessType;
return sub; return sub;
}) })
.then(content => this.toEditor(context, content)) .then(content => this.toEditor(context, content))
@ -158,22 +137,41 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
.catch(e => { .catch(e => {
log.error(i18nHelper.getMessage('130101', e.toString()), e); log.error(i18nHelper.getMessage('130101', e.toString()), e);
if (url) { if (url) {
let id = StringUtil.analyzeIdByUrl(url); const id = StringUtil.analyzeIdByUrl(url);
context.syncStatusHolder?context.syncStatusHolder.fail(id, ''):null; context.syncStatusHolder?context.syncStatusHolder.syncStatus.fail(id, ''):null;
}else { }else {
context.syncStatusHolder?context.syncStatusHolder.handled(1):null; context.syncStatusHolder?context.syncStatusHolder.syncStatus.handled(1):null;
} }
return undefined;
}); });
;
} }
/**
* data中是否包含关键字符串 movie
* @param data
* @private
*/
private getGuessType(data: CheerioAPI):SupportType {
if (data) {
const text = data.html();
if (text) {
for (const [key, value] of DoubanSubjectStateRecords_KEY_WORD_TYPE) {
if (text.indexOf(key) >= 0) {
return value;
}
}
}
}
return null;
}
abstract parseSubjectFromHtml(data: CheerioAPI): T | undefined;
toEditor(context: HandleContext, extract: T): T { abstract parseSubjectFromHtml(data: CheerioAPI, context: HandleContext): T | undefined;
this.doubanPlugin.putToObsidian(context, extract);
async toEditor(context: HandleContext, extract: T): Promise<T> {
await this.doubanPlugin.putToObsidian(context, extract);
return extract; return extract;
} }
@ -181,6 +179,33 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
return this.getPersonNameByMode(name, context.settings.personNameMode); return this.getPersonNameByMode(name, context.settings.personNameMode);
} }
getPersonName2(originalName: string, chineseName: string, context: HandleContext): string {
return this.getPersonNameByMode2(originalName, chineseName, context.settings.personNameMode);
}
getPersonNameByMode2(originalName: string, chineseName: string, personNameMode: string): string {
if (!originalName || !personNameMode) {
return "";
}
let resultName: string;
switch (personNameMode) {
case PersonNameMode.CH_NAME:
resultName = chineseName;
break;
case PersonNameMode.EN_NAME:
resultName = originalName.trim().replace(chineseName, '').trim();
if (!resultName) {
resultName = originalName;
}
break;
default:
resultName = originalName;
}
return resultName;
}
getPersonNameByMode(name: string, personNameMode: string): string { getPersonNameByMode(name: string, personNameMode: string): string {
if (!name || !personNameMode) { if (!name || !personNameMode) {
return ""; return "";
@ -189,17 +214,35 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
let regValue: RegExpExecArray; let regValue: RegExpExecArray;
switch (personNameMode) { switch (personNameMode) {
case PersonNameMode.CH_NAME: case PersonNameMode.CH_NAME:
regValue = /[\u4e00-\u9fa50-9\. \:\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]{2,20}/g.exec(name); regValue = /[\u4e00-\u9fa50-9. ·:\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5()]{2,}/g.exec(name);
resultName = regValue ? regValue[0] : name; resultName = regValue ? regValue[0] : name;
break; break;
case PersonNameMode.EN_NAME: case PersonNameMode.EN_NAME:
regValue = /[0-9a-zA-Z.\s-]{2,50}/g.exec(name); regValue = /[0-9a-zA-Z.\s-:]{2,}/g.exec(name);
resultName = regValue ? regValue[0] : name; resultName = regValue ? regValue[0] : name;
break; break;
default: default:
resultName = name; resultName = name;
} }
return resultName; return resultName.trim();
}
getTitleNameByMode(name: string, personNameMode: string, context: HandleContext): string {
if (!name || !personNameMode) {
return "";
}
if (context.listItem) {
const newName = context.listItem.title.trim().replaceAll(' ', '');
switch (personNameMode) {
case PersonNameMode.CH_NAME:
return newName;
break;
case PersonNameMode.EN_NAME:
return name.trim().replaceAll(' ', '').replaceAll(newName, '');
break;
}
}
return this.getPersonNameByMode(name, personNameMode);
} }
// html_encode(str: string): string { // html_encode(str: string): string {
@ -222,33 +265,82 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
s = s.replace(/&lt;/g, "<"); s = s.replace(/&lt;/g, "<");
s = s.replace(/&gt;/g, ">"); s = s.replace(/&gt;/g, ">");
s = s.replace(/&nbsp;/g, " "); s = s.replace(/&nbsp;/g, " ");
s = s.replace(/&#39;/g, "\'"); s = s.replace(/&#39;/g, "'");
s = s.replace(/&quot;/g, "\""); s = s.replace(/&quot;/g, "\"");
s = s.replace(/<br\/>/g, "\n"); s = s.replace(/<br\/>/g, "\n");
return s; return s;
} }
private parsePartText(template: string, extract: T, context: HandleContext, textMode: TemplateTextMode = TemplateTextMode.NORMAL): string { private parsePartYml(template: string, extract: T, context: HandleContext, variableMap : Map<string, DataField>): string {
let resultContent = this.handleCustomVariable(template, context); return VariableUtil.replaceSubject(variableMap, template, this.getSupportType(), this.doubanPlugin.settingsManager, 'yml_text');
resultContent = resultContent.replaceAll(DoubanParameter.ID, extract.id)
.replaceAll(DoubanParameter.TITLE, this.handleSpecialContent(this.getPersonName(extract.title, context), textMode))
.replaceAll(DoubanParameter.TYPE, extract.type)
.replaceAll(DoubanParameter.SCORE, this.handleSpecialContent(extract.score))
.replaceAll(DoubanParameter.IMAGE, extract.image)
.replaceAll(DoubanParameter.URL, extract.url)
.replaceAll(DoubanParameter.DESC, this.handleSpecialContent(extract.desc, textMode))
.replaceAll(DoubanParameter.PUBLISHER, extract.publisher)
.replaceAll(DoubanParameter.DATE_PUBLISHED, extract.datePublished ? moment(extract.datePublished).format(context.settings.dateFormat) : '')
.replaceAll(DoubanParameter.TIME_PUBLISHED, extract.datePublished ? moment(extract.datePublished).format(context.settings.timeFormat) : '')
.replaceAll(DoubanParameter.CURRENT_DATE, moment(new Date()).format(context.settings.dateFormat))
.replaceAll(DoubanParameter.CURRENT_TIME, moment(new Date()).format(context.settings.timeFormat))
.replaceAll(DoubanParameter.GENRE, this.handleSpecialContent(extract.genre, textMode, context))
;
resultContent = this.parseUserInfo(resultContent, extract, context, textMode);
return this.parseText(resultContent, extract, context, textMode);
} }
private parseUserInfo(resultContent: string, extract: T, context: HandleContext, textMode: TemplateTextMode) { private parsePartText(template: string, extract: T, context: HandleContext, variableMap : Map<string, DataField>): string {
return VariableUtil.replaceSubject(variableMap, template, this.getSupportType(), this.doubanPlugin.settingsManager, 'text');
}
private parsePartPath(template: string, extract: T, context: HandleContext, variableMap : Map<string, DataField>): string {
return VariableUtil.replaceSubject(variableMap, template, this.getSupportType(), this.doubanPlugin.settingsManager, 'path');
}
private buildVariableMap(extract: T, context: HandleContext) {
const variableMap: Map<string, DataField> = new Map();
for (const [key, value] of Object.entries(extract)) {
if (!value) {
continue;
}
const type: DataValueType = VariableUtil.getType(value);
if (key == 'score') {
variableMap.set(DoubanParameterName.SCORE_STAR, new DataField(
DoubanParameterName.SCORE_STAR,
DataValueType.string,
value,
NumberUtil.getRateStar(value, 10, {scoreSetting: context.settings.scoreSetting})
));
}
variableMap.set(key, new DataField(key, type, value, value));
}
variableMap.set(DoubanParameterName.IMAGE_URL, new DataField(
DoubanParameterName.IMAGE_URL,
DataValueType.url,
extract.imageUrl,
extract.imageUrl
));
variableMap.set(DoubanParameterName.YEAR_PUBLISHED, new DataField(
DoubanParameterName.YEAR_PUBLISHED,
DataValueType.date,
extract.datePublished,
extract.datePublished ? moment(extract.datePublished).format('yyyy') : ''
));
variableMap.set(DoubanParameterName.DATE_PUBLISHED, new DataField(
DoubanParameterName.DATE_PUBLISHED,
DataValueType.date,
extract.datePublished,
extract.datePublished ? moment(extract.datePublished).format(context.settings.dateFormat) : ''
));
variableMap.set(DoubanParameterName.TIME_PUBLISHED, new DataField(
DoubanParameterName.TIME_PUBLISHED,
DataValueType.date,
extract.datePublished,
extract.datePublished ? moment(extract.datePublished).format(context.settings.timeFormat) : ''
));
const currentDate = new Date();
variableMap.set(DoubanParameterName.CURRENT_DATE, new DataField(
DoubanParameterName.CURRENT_DATE,
DataValueType.date,
currentDate,
moment(currentDate).format(context.settings.dateFormat)
));
variableMap.set(DoubanParameterName.CURRENT_TIME, new DataField(
DoubanParameterName.CURRENT_TIME,
DataValueType.date,
currentDate,
moment(currentDate).format(context.settings.timeFormat)
));
return variableMap;
}
private parseUserInfo(resultContent: string, variableMap:Map<string, DataField>, extract: T, context: HandleContext) {
const userState = extract.userState; const userState = extract.userState;
if ((resultContent.indexOf(DoubanUserParameter.MY_TAGS) >= 0 || if ((resultContent.indexOf(DoubanUserParameter.MY_TAGS) >= 0 ||
resultContent.indexOf(DoubanUserParameter.MY_RATING) >= 0 || resultContent.indexOf(DoubanUserParameter.MY_RATING) >= 0 ||
@ -258,56 +350,86 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
log.warn(i18nHelper.getMessage('100113')); log.warn(i18nHelper.getMessage('100113'));
return resultContent; return resultContent;
} }
if (!userState || !userState.collectionDate) { if (!userState) {
return resultContent; return resultContent;
} }
return resultContent.replaceAll(DoubanUserParameter.MY_TAGS, this.handleSpecialContent(userState.tags, textMode, context)) let tags: string[] = [];
.replaceAll(DoubanUserParameter.MY_RATING, this.handleSpecialContent(userState.rate, textMode)) if (userState.tags && userState.tags.length > 0 ) {
.replaceAll(DoubanUserParameter.MY_STATE, this.getUserStateName(userState.state)) tags = [extract.type, ...userState.tags.map(tag => tag.trim())];
.replaceAll(DoubanUserParameter.MY_COMMENT, this.handleSpecialContent(userState.comment, textMode)) }else {
.replaceAll(DoubanUserParameter.MY_COLLECTION_DATE, moment(userState.collectionDate).format(context.settings.dateFormat)) tags = [extract.type];
}
Object.entries(userState).forEach(([key, value]) => {
if (!value) {
return;
}
variableMap.set(key, new DataField(key, VariableUtil.getType(value), value, value));
});
if (userState.tags && userState.tags.length > 0 ) {
variableMap.set(DoubanUserParameterName.MY_TAGS, new DataField(DoubanUserParameterName.MY_TAGS, DataValueType.array, tags, tags));
}
if (userState.comment) {
variableMap.set(DoubanUserParameterName.MY_COMMENT, new DataField(
DoubanUserParameterName.MY_COMMENT,
DataValueType.string,
userState.comment,
userState.comment
));
}
if (userState.state) {
variableMap.set(DoubanUserParameterName.MY_STATE, new DataField(
DoubanUserParameterName.MY_STATE,
DataValueType.string,
userState.state,
this.getUserStateName(userState.state)
));
}
if (userState.rate) {
variableMap.set(DoubanUserParameterName.MY_RATING, new DataField(
DoubanUserParameterName.MY_RATING,
DataValueType.number,
userState.rate,
userState.rate)
);
variableMap.set(DoubanUserParameterName.MY_RATING_STAR, new DataField(
DoubanUserParameterName.MY_RATING_STAR,
DataValueType.string,
userState.rate,
NumberUtil.getRateStar(userState.rate, 5, {scoreSetting: context.settings.scoreSetting})
));
}
if (userState.collectionDate) {
variableMap.set(DoubanUserParameterName.MY_COLLECTION_DATE, new DataField(
DoubanUserParameterName.MY_COLLECTION_DATE,
DataValueType.date,
userState.collectionDate,
userState.collectionDate ? moment(userState.collectionDate).format(context.settings.dateFormat) : ''
));
} }
/**
*
* @param template
* @param context
* @private
*/
private handleCustomVariable(template: string, context: HandleContext): string {
let customProperties = context.settings.customProperties;
let resultContent = template;
if (!customProperties) {
return resultContent;
}
customProperties.filter(customProperty => customProperty.name &&
customProperty.field
&& (customProperty.field == SupportType.ALL ||
customProperty.field == this.getSupportType())).forEach(customProperty => {
resultContent = resultContent.replaceAll(`{{${customProperty.name}}}`, customProperty.value);
});
return resultContent;
} }
private getTemplateKey():TemplateKey { private getTemplateKey():TemplateKey {
let templateKey: TemplateKey; let templateKey: TemplateKey;
switch (this.getSupportType()) { switch (this.getSupportType()) {
case SupportType.MOVIE: case SupportType.movie:
templateKey = TemplateKey.movieTemplateFile; templateKey = TemplateKey.movieTemplateFile;
break; break;
case SupportType.BOOK: case SupportType.book:
templateKey = TemplateKey.bookTemplateFile; templateKey = TemplateKey.bookTemplateFile;
break; break;
case SupportType.MUSIC: case SupportType.music:
templateKey = TemplateKey.musicTemplateFile; templateKey = TemplateKey.musicTemplateFile;
break; break;
case SupportType.TELEPLAY: case SupportType.teleplay:
templateKey = TemplateKey.teleplayTemplateFile; templateKey = TemplateKey.teleplayTemplateFile;
break; break;
case SupportType.GAME: case SupportType.game:
templateKey = TemplateKey.gameTemplateFile; templateKey = TemplateKey.gameTemplateFile;
break; break;
case SupportType.NOTE: case SupportType.note:
templateKey = TemplateKey.noteTemplateFile; templateKey = TemplateKey.noteTemplateFile;
break; break;
default: default:
@ -318,6 +440,15 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
} }
private async getTemplate(extract: T, context: HandleContext): Promise<string> { private async getTemplate(extract: T, context: HandleContext): Promise<string> {
const {syncConfig} = context;
if (syncConfig) {
if(syncConfig.templateFile) {
const val = await this.doubanPlugin.fileHandler.getFileContent(syncConfig.templateFile);
if (val) {
return val;
}
}
}
const tempKey: TemplateKey = this.getTemplateKey(); const tempKey: TemplateKey = this.getTemplateKey();
const templatePath: string = context.settings[tempKey]; const templatePath: string = context.settings[tempKey];
let useUserState:boolean = context.userComponent.isLogin() && let useUserState:boolean = context.userComponent.isLogin() &&
@ -332,7 +463,7 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
return getDefaultTemplateContent(tempKey, useUserState); return getDefaultTemplateContent(tempKey, useUserState);
} }
const defaultContent = getDefaultTemplateContent(tempKey, useUserState); const defaultContent = getDefaultTemplateContent(tempKey, useUserState);
let firstLinkpathDest: TFile = this.doubanPlugin.app.metadataCache.getFirstLinkpathDest(templatePath, ''); const firstLinkpathDest: TFile = this.doubanPlugin.app.metadataCache.getFirstLinkpathDest(templatePath, '');
if (!firstLinkpathDest) { if (!firstLinkpathDest) {
return defaultContent; return defaultContent;
} else { } else {
@ -348,25 +479,11 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
if(!html('.nav-user-account')) { if(!html('.nav-user-account')) {
return {data: html, userState: null}; return {data: html, userState: null};
} }
let rate = html(html('input#n_rating').get(0)).val(); return this. analysisUser(html, context);
let tagsStr = html(html('div#interest_sect_level > div.a_stars > span.color_gray').get(0)).text().trim();
let tags = tagsStr.replace('标签:', '').split(' ');
let stateWord = html(html('div#interest_sect_level > div.a_stars > span.mr10').get(0)).text().trim();
let collectionDateStr = html(html('div#interest_sect_level > div.a_stars > span.mr10 > span.collection_date').get(0)).text().trim();
let userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
let component = html(html('div#interest_sect_level > div.a_stars > span.color_gray').get(0)).next().next().text().trim();
const userState: UserStateSubject = {
tags: tags,
rate: rate?Number(rate):null,
state: userState1,
collectionDate: collectionDateStr?moment(collectionDateStr, 'YYYY-MM-DD').toDate():null,
comment: component
}
return {data: html, userState: userState};
} }
abstract analysisUser(html: CheerioAPI, context: HandleContext): {data:CheerioAPI , userState: UserStateSubject};
public static getUserState(stateWord:string):DoubanSubjectState { public static getUserState(stateWord:string):DoubanSubjectState {
let state:DoubanSubjectState; let state:DoubanSubjectState;
@ -390,7 +507,7 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
if (!state) { if (!state) {
return ''; return '';
} }
let v = DoubanSubjectStateRecords[this.getSupportType()]; const v = DoubanSubjectStateRecords[this.getSupportType()];
switch (state) { switch (state) {
case DoubanSubjectState.wish: case DoubanSubjectState.wish:
return v.wish; return v.wish;
@ -405,32 +522,138 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
} }
} }
private async saveImage(extract: T, context: HandleContext) { private async saveImage(extract: T, context: HandleContext, variableMap : Map<string, DataField>) {
if (!extract.image || !context.settings.cacheImage) { const {syncConfig} = context;
if (!extract.image || (syncConfig && !syncConfig.cacheImage) || !context.settings.cacheImage) {
return; return;
} }
let image = extract.image; const image = extract.image;
const filename = image.split('/').pop(); let folder = syncConfig? syncConfig.attachmentPath : context.settings.attachmentPath;
let folder = context.settings.attachmentPath;
if (!folder) { if (!folder) {
folder = DEFAULT_SETTINGS.attachmentPath; folder = DEFAULT_SETTINGS.attachmentPath;
} }
const {success, filepath} = await context.netFileHandler.downloadFile(image, folder, filename); folder = this.parsePartPath(folder, extract, context, variableMap)
if (success) { let fileName = syncConfig? syncConfig.attachmentFileName : context.settings.attachmentFileName;
extract.image = filepath; if (!fileName) {
fileName = DEFAULT_SETTINGS.attachmentFileName;
}
let fileNameSuffix = image ? image.substring(image.lastIndexOf('.')) : '.jpg';
if (fileNameSuffix && fileNameSuffix.length > 10) {
fileNameSuffix = '.jpg';
}
fileName = this.parsePartPath(fileName, extract, context, variableMap)
fileName = fileName + fileNameSuffix;
const imageReferer = (extract.id ? this.getSubjectUrl(extract.id) : '') || extract.url;
const referHeaders = HttpUtil.buildImageRequestHeaders(
context.plugin.settingsManager.getHeaders() as Record<string, any>,
imageReferer
);
if ((syncConfig ? syncConfig.cacheHighQuantityImage : context.settings.cacheHighQuantityImage) && context.userComponent.isLogin()) {
try {
const highImageFilename = this.getImageFilename(image);
const highImage = this.getHighQuantityImageUrl(highImageFilename);
const highImageHeaders = HttpUtil.buildImageRequestHeaders(
context.plugin.settingsManager.getHeaders() as Record<string, any>,
imageReferer
);
const resultValue = await this.handleImage(highImage, folder, fileName, context, false, highImageHeaders);
if (resultValue && resultValue.success) {
extract.image = resultValue.filepath;
this.initImageVariableMap(extract, context, variableMap);
return;
}
}catch (e) {
console.error(e);
console.error('下载高清封面失败,将会使用普通封面')
}
}
const resultValue = await this.handleImage(image, folder, fileName, context, true, referHeaders);
if (resultValue && resultValue.success) {
extract.image = resultValue.filepath;
this.initImageVariableMap(extract, context, variableMap);
} }
} }
private async humanCheck(html:any, url:string):Promise<any> { private getImageFilename(image: string): string {
if (html && html.indexOf("<title>禁止访问</title>") != -1) { if (!image) {
const loginModel = new DoubanHumanCheckModel(url);
await loginModel.load();
return ''; return '';
}
const imageUrl = image.split('?').first() || image;
return imageUrl.substring(imageUrl.lastIndexOf('/') + 1);
}
private initImageVariableMap(extract: T, context: HandleContext, variableMap : Map<string, DataField>) {
variableMap.set(DoubanParameterName.IMAGE_URL, new DataField(
DoubanParameterName.IMAGE_URL,
DataValueType.url,
extract.imageUrl,
extract.imageUrl
));
variableMap.set(DoubanParameterName.IMAGE, new DataField(
DoubanParameterName.IMAGE,
DataValueType.path,
extract.image,
extract.image
));
}
private async handleImage(image: string, folder: string, filename: string, context: HandleContext, showError: boolean, headers?: any) {
//只有在桌面版且开启了图片上传才会使用PicGo并且开启图床功能
if (context.settings.pictureBedFlag && Platform.isDesktopApp) {
//临时限定只支持PicGo
const checked = await context.netFileHandler.downloadDBUploadPicGoByClipboardBefore(context);
if (!checked) {
//TODO 国际化
log.notice('连接PicGo软件失败, 请检查是否已开启PicGo的Server服务 或 检查插件中配置地址是否正确,现使用默认的下载到本地的方式');
return await context.netFileHandler.downloadDBFile(image, folder, filename, context, false, headers);
}
return await context.netFileHandler.downloadDBUploadPicGoByClipboard(image, filename, context, showError, headers);
}else { }else {
return html; return await context.netFileHandler.downloadDBFile(image, folder, filename, context, false, headers);
}
}
abstract getHighQuantityImageUrl(fileName:string):string;
abstract getSubjectUrl(id:string):string;
handlePersonNameByMeta(html: CheerioAPI, movie: DoubanSubject, context: HandleContext,
metaProperty:string, objectProperty:string) {
if (!movie) {
return;
}
const metaProperties: string[] = html(`head > meta[property='${metaProperty}']`).get()
.map((e) => {
return html(e).attr('content');
});
// @ts-ignore
const currentArray = movie[objectProperty];
if (!Array.isArray(currentArray)) {
return;
}
// @ts-ignore
currentArray
// @ts-ignore
.filter((p:Person) => p.name)
// @ts-ignore
.map((p:Person) => {
// @ts-ignore
const persons = metaProperties.filter((a) => p.name.indexOf(a) >= 0);
if (persons) {
// @ts-ignore
p.name = this.getPersonName2(p.name, persons[0], context);
}
})
}
protected getPropertyValue(html: CheerioAPI, name: PropertyName): string {
return HtmlUtil.getHtmlText(html, this.doubanPlugin.settingsManager.getSelector(this.getSupportType(), name));
} }
}
} }

@ -3,9 +3,12 @@ import DoubanAbstractLoadHandler from "./DoubanAbstractLoadHandler";
import DoubanBookSubject, {DoubanBookParameter} from "../model/DoubanBookSubject"; import DoubanBookSubject, {DoubanBookParameter} from "../model/DoubanBookSubject";
import DoubanPlugin from "../../../main"; import DoubanPlugin from "../../../main";
import DoubanSubject from "../model/DoubanSubject"; import DoubanSubject from "../model/DoubanSubject";
import {SupportType, TemplateTextMode} from "../../../constant/Constsant"; import {DataValueType, PropertyName, SupportType, TemplateTextMode} from "../../../constant/Constsant";
import HandleContext from "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import StringUtil from "../../../utils/StringUtil"; import StringUtil from "../../../utils/StringUtil";
import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian";
import {DataField} from "../../../utils/model/DataField";
export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<DoubanBookSubject> { export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<DoubanBookSubject> {
@ -14,29 +17,26 @@ export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<Dou
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.BOOK; return SupportType.book;
} }
parseText(beforeContent: string, extract: DoubanBookSubject, context: HandleContext, textMode: TemplateTextMode): string { getHighQuantityImageUrl(fileName:string):string{
return beforeContent return `https://img9.doubanio.com/view/subject/l/public/${fileName}`;
.replaceAll(DoubanBookParameter.author, }
super.handleSpecialContent(
extract.author.map(this.handleSpecialAuthorName), textMode, context)) getSubjectUrl(id:string):string{
.replaceAll(DoubanBookParameter.translator, super.handleSpecialContent(extract.translator, textMode, context)) return `https://book.douban.com/subject/${id}/`;
.replaceAll(DoubanBookParameter.isbn, extract.isbn) }
.replaceAll(DoubanBookParameter.originalTitle, super.handleSpecialContent(extract.originalTitle, textMode))
.replaceAll(DoubanBookParameter.subTitle, super.handleSpecialContent(extract.subTitle, textMode)) parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanBookSubject, context: HandleContext): void {
.replaceAll(DoubanBookParameter.totalPage, super.handleSpecialContent(extract.totalPage, textMode)) variableMap.set(DoubanBookParameter.author, new DataField(DoubanBookParameter.author,
.replaceAll(DoubanBookParameter.menu, extract.menu.join('\n')) DataValueType.array, extract.author, (extract.author || []).map(this.handleSpecialAuthorName)));
.replaceAll(DoubanBookParameter.price, super.handleSpecialContent(extract.price, textMode)) variableMap.set(DoubanBookParameter.translator, new DataField(DoubanBookParameter.translator,
.replaceAll(DoubanBookParameter.series, super.handleSpecialContent(extract.series, textMode)) DataValueType.array, extract.translator, (extract.translator || []).map(this.handleSpecialAuthorName)));
.replaceAll(DoubanBookParameter.binding, super.handleSpecialContent(extract.binding, textMode))
.replaceAll(DoubanBookParameter.producer, super.handleSpecialContent(extract.producer, textMode))
;
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
return extract && extract.type && (extract.type.contains("书籍") || extract.type.contains("Book") || extract.type.contains("book")); return extract && extract.type && (extract.type.contains("图书") || extract.type.contains("书籍") || extract.type.contains("Book") || extract.type.contains("book"));
} }
handleSpecialAuthorName(authorName: string): string { handleSpecialAuthorName(authorName: string): string {
@ -44,23 +44,47 @@ export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<Dou
.replace(']', '/'); .replace(']', '/');
} }
parseSubjectFromHtml(html: CheerioAPI): DoubanBookSubject { analysisUser(html: CheerioAPI, context: HandleContext): {data:CheerioAPI , userState: UserStateSubject} {
let desc = html(html("head > meta[property= 'og:description']").get(0)).attr("content"); const rate = html('input#n_rating').val();
let image = html(html("head > meta[property= 'og:image']").get(0)).attr("content"); const tagsStr = html('span#rating').next().text().trim();
const tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null;
const stateWord = html('div#interest_sect_level > div.a_stars > span.mr10').text().trim();
const collectionDateStr = html('div#interest_sect_level > div.a_stars > span.mr10').next().text().trim();
const userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
const comment = this.getComment(html);
const userState: UserStateSubject = {
tags: tags,
rate: rate?Number(rate):null,
state: userState1,
collectionDate: collectionDateStr?moment(collectionDateStr, 'YYYY-MM-DD').toDate():null,
comment: comment
}
return {data: html, userState: userState};
}
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanBookSubject {
let desc = html(".intro p").text();
if (!desc) {
desc = html(html("head > meta[property= 'og:description']").get(0)).attr("content");
}
const image = html(html("head > meta[property= 'og:image']").get(0)).attr("content");
let item = html(html("head > script[type='application/ld+json']").get(0)).text(); let item = html(html("head > script[type='application/ld+json']").get(0)).text();
item = super.html_decode(item); item = super.html_decode(item);
let obj = JSON.parse(item.replace(/[\r\n\s+]/g, '')); const obj = JSON.parse(item.replace(/[\r\n\t\s+]/g, ''));
let title = obj.name; const title = obj.name;
let url = obj.url; const url = obj.url;
let author = obj.author.map((a: any) => a.name); const author = obj.author.map((a: any) => a.name);
let isbn = obj.isbn; const isbn = obj.isbn;
let score = html(html("#interest_sectl > div > div.rating_self.clearfix > strong[property= 'v:average']").get(0)).text(); const score = html(html("#interest_sectl > div > div.rating_self.clearfix > strong[property= 'v:average']").get(0)).text();
let detailDom = html(html("#info").get(0)); const detailDom = html(html("#info").get(0));
let publish = detailDom.find("span.pl"); const publish = detailDom.find("span.pl");
let valueMap = new Map<string, any>(); const valueMap = new Map<string, any>();
publish.map((index, info) => { publish.map((index, info) => {
let key = html(info).text().trim(); let key = html(info).text().trim();
@ -85,6 +109,7 @@ export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<Dou
author: author, author: author,
translator: valueMap.has('translator') ? valueMap.get('translator') : [], translator: valueMap.has('translator') ? valueMap.get('translator') : [],
image: image, image: image,
imageUrl: image,
datePublished: valueMap.has('datePublished') ? new Date(valueMap.get('datePublished')) : undefined, datePublished: valueMap.has('datePublished') ? new Date(valueMap.get('datePublished')) : undefined,
isbn: isbn, isbn: isbn,
publisher: valueMap.has('publisher') ? valueMap.get('publisher') : "", publisher: valueMap.has('publisher') ? valueMap.get('publisher') : "",
@ -96,7 +121,7 @@ export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<Dou
menu: menu, menu: menu,
price: valueMap.has('price') ? Number(valueMap.get('price').replace('元', '')) : null, price: valueMap.has('price') ? Number(valueMap.get('price').replace('元', '')) : null,
id: id, id: id,
type: "Book", type: this.getSupportType(),
title: title, title: title,
desc: desc, desc: desc,
url: url, url: url,
@ -107,10 +132,21 @@ export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<Dou
return result; return result;
} }
private getComment(html: CheerioAPI) {
let comment = html('span#rating').next().next().next().text().trim();
if (comment) {
return comment;
}
return this.getPropertyValue(html, PropertyName.comment);
}
} }
const BookKeyValueMap: Map<string, string> = new Map( const BookKeyValueMap: Map<string, string> = new Map(
[['作者', 'author'], [['作者', 'author'],
['出版社:', 'publisher'], ['出版社:', 'publisher'],

@ -3,9 +3,13 @@ import DoubanAbstractLoadHandler from "./DoubanAbstractLoadHandler";
import DoubanPlugin from "../../../main"; import DoubanPlugin from "../../../main";
import DoubanSubject from '../model/DoubanSubject'; import DoubanSubject from '../model/DoubanSubject';
import DoubanGameSubject from '../model/DoubanGameSubject'; import DoubanGameSubject from '../model/DoubanGameSubject';
import StringUtil from "../../../utils/StringUtil";
import HandleContext from "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import {SupportType, TemplateKey} from "../../../constant/Constsant"; import {DataValueType, PersonNameMode, SupportType} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian";
import {TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil";
import {DataField} from "../../../utils/model/DataField";
import {b} from "@shikijs/engine-javascript/dist/shared/engine-javascript.BnuFKbIS";
export default class DoubanGameLoadHandler extends DoubanAbstractLoadHandler<DoubanGameSubject> { export default class DoubanGameLoadHandler extends DoubanAbstractLoadHandler<DoubanGameSubject> {
@ -14,29 +18,65 @@ export default class DoubanGameLoadHandler extends DoubanAbstractLoadHandler<Dou
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.GAME; return SupportType.game;
}
getHighQuantityImageUrl(fileName:string):string{
return `https://img9.doubanio.com/lpic/${fileName}`;
} }
parseText(beforeContent: string, extract: DoubanGameSubject, context: HandleContext): string { getSubjectUrl(id:string):string{
const {settings} = context; return `https://www.douban.com/game/${id}/`;
return beforeContent }
.replaceAll("{{platform}}", extract.platform ? extract.platform.join(settings.arraySpilt) : "")
.replaceAll("{{aliases}}", extract.aliases ? extract.aliases.join(settings.arraySpilt) : "") parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanGameSubject, context: HandleContext): void {
.replaceAll("{{developer}}", extract.developer ? extract.developer : ""); // super.parseAliases(beforeContent, variableMap, extract, context);
variableMap.set("aliases", new DataField("aliases", DataValueType.array, extract.aliases,
(extract.aliases || []).map(a=>a
.trim()
// .replace(TITLE_ALIASES_SPECIAL_CHAR_REG_G, '_')
// //replase multiple _ to single _
// .replace(/_+/g, '_')
// .replace(/^_/, '')
// .replace(/_$/, '')
.replace(/:\s+/g, ':')
)));
// super.parseAliases(beforeContent, variableMap, extract, context);
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
return extract && extract.type && (extract.type.contains("游戏") || extract.type.contains("Game") || extract.type.contains("game")); return extract && extract.type && (extract.type.contains("游戏") || extract.type.contains("Game") || extract.type.contains("game"));
} }
parseSubjectFromHtml(html: CheerioAPI): DoubanGameSubject { analysisUser(html: CheerioAPI, context: HandleContext): {data:CheerioAPI , userState: UserStateSubject} {
let rate = html('input#n_rating').val();
const rating = html('span#rating');
const tagsStr = rating.parent().next().text().trim();
const tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null;
const collected = html('div.collection-section > div.collection-rating-stars > div.collection-collected');
const stateWord = collected.find('span.collection-result').text().trim();
const collectionDateStr = collected.find('span.color_gray').text().trim();
const userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
const component = rating.parent().next().next().text().trim();
const userState: UserStateSubject = {
tags: tags,
rate: rate?Number(rate):null,
state: userState1,
collectionDate: collectionDateStr?moment(collectionDateStr, 'YYYY-MM-DD').toDate():null,
comment: component
}
return {data: html, userState: userState};
}
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanGameSubject {
let title = html(html("#content > h1").get(0)).text(); let title = html(html("#content > h1").get(0)).text();
title = this.getPersonNameByMode(title, PersonNameMode.CH_NAME);
let idContent = html(html("head > meta[name= 'mobile-agent']").get(0)).attr("content"); let idContent = html(html("head > meta[name= 'mobile-agent']").get(0)).attr("content");
let idPattern = /(\d){5,10}/g; let idPattern = /(\d){5,10}/g;
let idP = idPattern.exec(idContent); let idP = idPattern.exec(idContent);
let id = idP ? idP[0] : ""; let id = idP ? idP[0] : "";
let score = html(html("#interest_sectl > div > div.rating_self.clearfix > strong[property= 'v:average']").get(0)).text(); let score = html(html("#interest_sectl > div > div.rating_self.clearfix > strong[property= 'v:average']").get(0)).text();
let detailDom = html(html("dl.game-attr").get(0)); let detailDom = html(html("dl.thing-attr").get(0));
let dt = detailDom.find("dt"); let dt = detailDom.find("dt");
let image = html(html("#content > div > div.article > div.mod.item-subject > div.item-subject-info > div > a > img").get(0)).attr("src"); let image = html(html("#content > div > div.article > div.mod.item-subject > div.item-subject-info > div > a > img").get(0)).attr("src");
let desc = html(html("#link-report > p").get(0)).text(); let desc = html(html("#link-report > p").get(0)).text();
@ -62,12 +102,13 @@ export default class DoubanGameLoadHandler extends DoubanAbstractLoadHandler<Dou
const result: DoubanGameSubject = { const result: DoubanGameSubject = {
id: id, id: id,
type: "Game", type: this.getSupportType(),
title: title, title: title,
desc: desc, desc: desc,
url: url, url: url,
genre: valueMap.has('genre') ? valueMap.get('genre') : [], genre: valueMap.has('genre') ? valueMap.get('genre') : [],
image: image, image: image,
imageUrl: image,
datePublished: valueMap.has('datePublished') ? new Date(valueMap.get('datePublished')) : undefined, datePublished: valueMap.has('datePublished') ? new Date(valueMap.get('datePublished')) : undefined,
publisher: valueMap.has('publisher') ? valueMap.get('publisher') : "", publisher: valueMap.has('publisher') ? valueMap.get('publisher') : "",
score: Number(score), score: Number(score),

@ -6,7 +6,11 @@ import DoubanSubject from '../model/DoubanSubject';
import DoubanMovieSubject from '../model/DoubanMovieSubject'; import DoubanMovieSubject from '../model/DoubanMovieSubject';
import StringUtil from "../../../utils/StringUtil"; import StringUtil from "../../../utils/StringUtil";
import HandleContext from "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import {PersonNameMode, SupportType, TemplateKey} from "../../../constant/Constsant"; import {DataValueType, PersonNameMode, PropertyName, SupportType, TemplateKey} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian";
import YamlUtil, {SPECIAL_CHAR_REG, TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil";
import {DataField} from "../../../utils/model/DataField";
export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<DoubanMovieSubject> { export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<DoubanMovieSubject> {
@ -15,58 +19,209 @@ export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<Do
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.MOVIE; return SupportType.movie;
} }
parseText(beforeContent: string, extract: DoubanMovieSubject, context: HandleContext): string { getHighQuantityImageUrl(fileName:string):string{
const {settings} = context; return `https://img9.doubanio.com/view/photo/l/public/${fileName}`;
return beforeContent }
.replaceAll("{{originalTitle}}", extract.originalTitle ? extract.originalTitle : "")
.replaceAll("{{director}}", extract.director ? extract.director.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c).join(settings.arraySpilt) : "") getSubjectUrl(id:string):string{
.replaceAll("{{actor}}", extract.actor ? extract.actor.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c).join(settings.arraySpilt) : "") return `https://movie.douban.com/subject/${id}/`;
.replaceAll("{{author}}", extract.author ? extract.author.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c).join(settings.arraySpilt) : "") }
;
parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanMovieSubject, context: HandleContext): void {
variableMap.set("director", new DataField(
"director",
DataValueType.array,
extract.director,
(extract.director || []).map(SchemaOrg.getPersonName).filter(c => c)
));
variableMap.set("actor", new DataField(
"actor",
DataValueType.array,
extract.actor,
(extract.actor || []).map(SchemaOrg.getPersonName).filter(c => c)
));
variableMap.set("author", new DataField(
"author",
DataValueType.array,
extract.author,
(extract.author || []).map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c)
));
variableMap.set("aliases", new DataField("aliases", DataValueType.array, extract.aliases,
(extract.aliases || []).map(a=>a
.trim()
// .replace(TITLE_ALIASES_SPECIAL_CHAR_REG_G, '_')
// //replase multiple _ to single _
// .replace(/_+/g, '_')
// .replace(/^_/, '')
// .replace(/_$/, '')
.replace(/:\s+/g, ':')
)));
// super.parseAliases(beforeContent, variableMap, extract, context);
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
return extract && extract.type && (extract.type.contains("电影") || extract.type.contains("Movie") || extract.type.contains("movie")); return extract && extract.type && (extract.type.contains("电影") || extract.type.contains("Movie") || extract.type.contains("movie"));
} }
parseSubjectFromHtml(data: CheerioAPI): DoubanMovieSubject { analysisUser(html: CheerioAPI, context: HandleContext): {data:CheerioAPI , userState: UserStateSubject} {
return data('script') let rate = html('input#n_rating').val();
let tagsStr = html('div#interest_sect_level > div.a_stars > span.color_gray').text().trim();
let tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null;
let stateWord = html('div#interest_sect_level > div.a_stars > span.mr10').text().trim();
let collectionDateStr = html('div#interest_sect_level > div.a_stars > span.mr10 > span.collection_date').text().trim();
let userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
let component = this.getComment(html, context);
const userState: UserStateSubject = {
tags: tags,
rate: rate?Number(rate):null,
state: userState1,
collectionDate: collectionDateStr?moment(collectionDateStr, 'YYYY-MM-DD').toDate():null,
comment: component
}
return {data: html, userState: userState};
}
private getComment(html: CheerioAPI, context: HandleContext) {
const component = html('div#interest_sect_level > div.a_stars > span.color_gray').next().next().text().trim();
if (component) {
return component;
}
return this.getPropertyValue(html, PropertyName.comment);
}
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanMovieSubject {
let movie: DoubanMovieSubject | undefined = html('script')
.get() .get()
.filter(scd => "application/ld+json" == data(scd).attr("type")) .filter(scd => "application/ld+json" == html(scd).attr("type"))
.map(i => { .map(i => {
let item = data(i).text(); let item = html(i).text();
item = super.html_decode(item); item = super.html_decode(item);
let obj = JSON.parse(item.replace(/[\r\n\s+]/g, '')); const obj = JSON.parse(item.replace(/[\r\n\t]+/g, ''));
let idPattern = /(\d){5,10}/g; const idPattern = /(\d){5,10}/g;
let id = idPattern.exec(obj.url); const id = idPattern.exec(obj.url);
let name = obj.name; const name = obj.name;
let title = super.getPersonNameByMode(name, PersonNameMode.CH_NAME)??name; const title = super.getTitleNameByMode(name, PersonNameMode.CH_NAME, context) ?? name;
let originalTitle = super.getPersonNameByMode(name, PersonNameMode.EN_NAME) ?? name; const originalTitle = super.getTitleNameByMode(name, PersonNameMode.EN_NAME, context) ?? name;
const result: DoubanMovieSubject = { const result: DoubanMovieSubject = {
id: id ? id[0] : '', id: id ? id[0] : '',
title: title, title: title,
type: 'Movie', type: this.getSupportType(),
score: obj.aggregateRating ? obj.aggregateRating.ratingValue : undefined, score: obj.aggregateRating ? obj.aggregateRating.ratingValue : undefined,
originalTitle: originalTitle, originalTitle: originalTitle,
desc: obj.description, desc: obj.description,
url: "https://movie.douban.com" + obj.url, url: "https://movie.douban.com" + obj.url,
director: obj.director, director: obj.director || [],
author: obj.author, author: obj.author || [],
actor: obj.actor, actor: obj.actor || [],
aggregateRating: obj.aggregateRating, aggregateRating: obj.aggregateRating,
datePublished: obj.datePublished ? new Date(obj.datePublished) : undefined, datePublished: obj.datePublished ? new Date(obj.datePublished) : undefined,
image: obj.image, image: obj.image,
genre: obj.genre, imageUrl: obj.image,
publisher: '' genre: obj.genre || [],
publisher: '',
aliases: [""],
language: [""],
country: [],
time: null,
IMDb: null,
} }
return result; return result;
})[0]; })[0];
// Fallback: if JSON-LD parsing failed (e.g., anti-bot page), extract from meta tags
if (!movie) {
const title = html(html("head > meta[property='og:title']").get(0)).attr("content") || '';
const image = html(html("head > meta[property='og:image']").get(0)).attr("content") || '';
const urlMeta = html(html("head > meta[property='og:url']").get(0)).attr("content") || '';
const desc = html(html("head > meta[property='og:description']").get(0)).attr("content") || '';
// Extract ID from URL
const idPattern = /(\d){5,10}/g;
const idMatch = idPattern.exec(urlMeta);
const id = idMatch ? idMatch[0] : '';
// Extract score from HTML
const scoreText = html("#interest_sectl strong[property='v:average']").text();
const score = scoreText ? parseFloat(scoreText) : undefined;
movie = {
id,
title,
type: this.getSupportType(),
score,
originalTitle: title,
desc,
url: urlMeta || (id ? `https://movie.douban.com/subject/${id}/` : ''),
director: [],
author: [],
actor: [],
aggregateRating: undefined,
datePublished: undefined,
image,
imageUrl: image,
genre: [],
publisher: '',
aliases: [],
language: [],
country: [],
time: null,
IMDb: null,
};
} }
this.handlePersonNameByMeta(html, movie, context, 'video:actor', 'actor');
this.handlePersonNameByMeta(html, movie, context, 'video:director', 'director');
const desc: string = html("span[property='v:summary']").text();
if (desc) {
movie.desc = desc;
}
const detailDom = html(html("#info").get(0));
const publish = detailDom.find("span.pl");
const valueMap = new Map<string, any>();
publish.map((index, info) => {
const key = html(info).text().trim();
let value;
if (key.indexOf('又名') >= 0 || key.indexOf('语言') >= 0 || key.indexOf('制片国家') >= 0) {
// value = html(info.next.next).text().trim();
const vas = html(info.next).text().trim();
value = vas.split("/").map((v) => v.trim());
} else if (key.indexOf('片长') >= 0) {
value = html(info.next.next).text().trim()
} else {
value = html(info.next).text().trim();
}
valueMap.set(MovieKeyValueMap.get(key), value);
})
movie.country = valueMap.has('country') ? valueMap.get('country') : [];
movie.language = valueMap.has('language') ? valueMap.get('language') : [];
movie.time = valueMap.has('time') ? valueMap.get('time') : "";
movie.aliases = valueMap.has('aliases') ? valueMap.get('aliases') : [];
movie.IMDb = valueMap.has('IMDb') ? valueMap.get('IMDb') : "";
return movie;
} }
}
const MovieKeyValueMap: Map<string, string> = new Map(
[['制片国家/地区:', 'country'],
['语言:', 'language'],
['片长:', 'time'],
['又名:', 'aliases'],
['IMDb:', 'IMDb']
]
);

@ -4,7 +4,10 @@ import DoubanMusicSubject from '../model/DoubanMusicSubject';
import DoubanPlugin from "../../../main"; import DoubanPlugin from "../../../main";
import DoubanSubject from '../model/DoubanSubject'; import DoubanSubject from '../model/DoubanSubject';
import HandleContext from "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import {SupportType, TemplateKey} from "../../../constant/Constsant"; import {SupportType} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian";
import {DataField} from "../../../utils/model/DataField";
export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<DoubanMusicSubject> { export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<DoubanMusicSubject> {
@ -13,41 +16,67 @@ export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<Do
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.MUSIC; return SupportType.music;
} }
parseText(beforeContent: string, extract: DoubanMusicSubject, context: HandleContext): string { getHighQuantityImageUrl(fileName:string):string{
const {settings} = context; return `https://img1.doubanio.com/view/subject/m/public/${fileName}`;
return beforeContent }
.replaceAll("{{actor}}", extract.actor ? extract.actor.join(settings.arraySpilt) : "")
.replaceAll("{{barcode}}", extract.barcode ? extract.barcode : "") getSubjectUrl(id:string):string{
.replaceAll("{{medium}}", extract.medium ? extract.medium : "") return `https://music.douban.com/subject/${id}/`;
.replaceAll("{{albumType}}", extract.albumType ? extract.albumType : "") }
.replaceAll("{{records}}", extract.records ? extract.records + "" : "")
; parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanMusicSubject, context: HandleContext): void {
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
return extract && extract.type && (extract.type.contains("音乐") || extract.type.contains("Music") || extract.type.contains("music")); return extract && extract.type && (extract.type.contains("音乐") || extract.type.contains("Music") || extract.type.contains("music"));
} }
parseSubjectFromHtml(html: CheerioAPI): DoubanMusicSubject { analysisUser(html: CheerioAPI, context: HandleContext): {data:CheerioAPI , userState: UserStateSubject} {
let title = html(html("head > meta[property= 'og:title']").get(0)).attr("content"); const rate = html('input#n_rating').val();
let desc = html(html("head > meta[property= 'og:description']").get(0)).attr("content"); const tagsStr = html('span#rating').next().next().text().trim();
let url = html(html("head > meta[property= 'og:url']").get(0)).attr("content"); const tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null;
let image = html(html("head > meta[property= 'og:image']").get(0)).attr("content"); const stateWord = html('div#interest_sect_level > div.a_stars > span.mr10').text().trim();
let score = html(html("#interest_sectl > div > div.rating_self.clearfix > strong[property= 'v:average']").get(0)).text(); const collectionDateStr = html('div#interest_sect_level > div.a_stars > span.mr10').next().text().trim();
let detailDom = html(html("#info").get(0)); const userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
let publish = detailDom.find("span.pl"); const component = html('span#rating').next().next().next().next().text().trim();
let valueMap = new Map<string, string>(); const userState: UserStateSubject = {
tags: tags,
rate: rate?Number(rate):null,
state: userState1,
collectionDate: collectionDateStr?moment(collectionDateStr, 'YYYY-MM-DD').toDate():null,
comment: component
}
return {data: html, userState: userState};
}
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanMusicSubject {
const title = html(html("head > meta[property= 'og:title']").get(0)).attr("content");
let desc:string = html("span.all.hidden").text();
if (!desc) {
desc = html("span[property='v:summary']").text();
}
if (!desc) {
desc = html(html("head > meta[property= 'og:description']").get(0)).attr("content");
}
const url = html(html("head > meta[property= 'og:url']").get(0)).attr("content");
const image = html(html("head > meta[property= 'og:image']").get(0)).attr("content");
const score = html(html("#interest_sectl > div > div.rating_self.clearfix > strong[property= 'v:average']").get(0)).text();
const detailDom = html(html("#info").get(0));
const publish = detailDom.find("span.pl");
const valueMap = new Map<string, string>();
publish.map((index, info) => { publish.map((index, info) => {
let key = html(info).text().trim(); let key = html(info).text().trim();
let value = ''; let value = '';
if (key.indexOf('表演者') >= 0) { if (key.indexOf('表演者') >= 0) {
// value = html(info.next.next).text().trim(); // value = html(info.next.next).text().trim();
let vas: string[] = key.split("\n \n "); const vas: string[] = key.split("\n \n ");
value = vas && vas.length > 1 ? vas[1] : ""; value = vas && vas.length > 1 ? vas[1] : "";
key = vas && vas.length > 0 ? vas[0] : ""; key = vas && vas.length > 0 ? vas[0] : "";
} else { } else {
@ -56,17 +85,21 @@ export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<Do
valueMap.set(MusicKeyValueMap.get(key), value); valueMap.set(MusicKeyValueMap.get(key), value);
}) })
let idPattern = /(\d){5,10}/g; const idPattern = /(\d){5,10}/g;
let id = idPattern.exec(url); const id = idPattern.exec(url);
const trackItems = html('.track-list .track-items li');
const tracks = Array.from(trackItems).map(item => html(item).text().trim());
const result: DoubanMusicSubject = { const result: DoubanMusicSubject = {
image: image, image: image,
imageUrl: image,
datePublished: valueMap.has('datePublished') ? new Date(valueMap.get('datePublished')) : undefined, datePublished: valueMap.has('datePublished') ? new Date(valueMap.get('datePublished')) : undefined,
publisher: valueMap.has('publisher') ? valueMap.get('publisher') : "", publisher: valueMap.has('publisher') ? valueMap.get('publisher') : "",
score: Number(score), score: Number(score),
records: valueMap.has('records') ? Number(valueMap.get('records')) : null, records: valueMap.has('records') ? Number(valueMap.get('records')) : null,
id: id ? id[0] : "", id: id ? id[0] : "",
type: "Music", type: this.getSupportType(),
title: title, title: title,
desc: desc, desc: desc,
url: url, url: url,
@ -74,8 +107,10 @@ export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<Do
genre: valueMap.has('genre') ? [valueMap.get('genre')] : [""], genre: valueMap.has('genre') ? [valueMap.get('genre')] : [""],
albumType: valueMap.has('albumType') ? valueMap.get('albumType') : "", albumType: valueMap.has('albumType') ? valueMap.get('albumType') : "",
medium: valueMap.has('medium') ? valueMap.get('medium') : "", medium: valueMap.has('medium') ? valueMap.get('medium') : "",
barcode: valueMap.has('barcode') ? valueMap.get('barcode') : "" barcode: valueMap.has('barcode') ? valueMap.get('barcode') : "",
menu: tracks
}; };
return result; return result;
} }

@ -6,6 +6,8 @@ import DoubanSubject from '../model/DoubanSubject';
import html2markdown from '@notable/html2markdown'; import html2markdown from '@notable/html2markdown';
import HandleContext from "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import {SupportType, TemplateKey} from "../../../constant/Constsant"; import {SupportType, TemplateKey} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject";
import {DataField} from "../../../utils/model/DataField";
export default class DoubanNoteLoadHandler extends DoubanAbstractLoadHandler<DoubanNoteSubject> { export default class DoubanNoteLoadHandler extends DoubanAbstractLoadHandler<DoubanNoteSubject> {
@ -14,39 +16,47 @@ export default class DoubanNoteLoadHandler extends DoubanAbstractLoadHandler<Dou
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.NOTE; return SupportType.note;
} }
parseText(beforeContent: string, extract: DoubanNoteSubject, context: HandleContext): string { getHighQuantityImageUrl(fileName:string):string{
return beforeContent return ``;
.replaceAll("{{authorUrl}}", extract.authorUrl ? extract.authorUrl : "") }
.replaceAll("{{content}}", extract.content ? extract.content : "")
.replaceAll("{{author}}", extract.author ? extract.author : "") getSubjectUrl(id:string):string{
; return `https://www.douban.com/note/${id}/`;
}
parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanNoteSubject, context: HandleContext): void {
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
return extract && extract.type && (extract.type.contains("日记") || extract.type.contains("Note") || extract.type.contains("Article")); return extract && extract.type && (extract.type.contains("日记") || extract.type.contains("Note") || extract.type.contains("Article") || extract.type.contains("note") || extract.type.contains("article"));
} }
parseSubjectFromHtml(html: CheerioAPI): DoubanNoteSubject { analysisUser(html: CheerioAPI, context: HandleContext): {data:CheerioAPI , userState: UserStateSubject} {
let title = html(html("head > meta[property= 'og:title']").get(0)).attr("content"); return {data: html, userState: null};
let desc = html(html("head > meta[property= 'og:description']").get(0)).attr("content"); }
let url = html(html("head > meta[property= 'og:url']").get(0)).attr("content");
let image = html(html("head > meta[property= 'og:image']").get(0)).attr("content"); parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanNoteSubject {
let type = html(html("head > meta[property= 'og:type']").get(0)).attr("content"); const title = html(html("head > meta[property= 'og:title']").get(0)).attr("content");
let authorA = html(html("a.note-author").get(0)); const desc = html(html("head > meta[property= 'og:description']").get(0)).attr("content");
let timePublished = html(html(".pub-date").get(0)).text(); const url = html(html("head > meta[property= 'og:url']").get(0)).attr("content");
let content = html(html(".note").get(1)); const image = html(html("head > meta[property= 'og:image']").get(0)).attr("content");
let idPattern = /(\d){5,10}/g; const type = html(html("head > meta[property= 'og:type']").get(0)).attr("content");
let id = idPattern.exec(url); const authorA = html(html("a.note-author").get(0));
const timePublished = html(html(".pub-date").get(0)).text();
const content = html(html(".note").get(1));
const idPattern = /(\d){5,10}/g;
const id = idPattern.exec(url);
const result: DoubanNoteSubject = { const result: DoubanNoteSubject = {
image: image, image: image,
imageUrl: image,
datePublished: timePublished ? new Date(timePublished) : undefined, datePublished: timePublished ? new Date(timePublished) : undefined,
content: content ? html2markdown(content.toString()) : "", content: content ? html2markdown(content.toString()) : "",
id: id ? id[0] : "", id: id ? id[0] : "",
type: "Article", type: this.getSupportType(),
title: title, title: title,
desc: desc, desc: desc,
url: url, url: url,

@ -5,27 +5,42 @@ import {i18nHelper} from "src/org/wanxp/lang/helper";
import {log} from "src/org/wanxp/utils/Logutil"; import {log} from "src/org/wanxp/utils/Logutil";
import HandleContext from "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import {SupportType, TemplateKey} from "../../../constant/Constsant"; import {SupportType, TemplateKey} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject";
import {DataField} from "../../../utils/model/DataField";
/** /**
* *
*/ */
export default class DoubanOtherLoadHandler extends DoubanAbstractLoadHandler<DoubanSubject> { export default class DoubanOtherLoadHandler extends DoubanAbstractLoadHandler<DoubanSubject> {
getSupportType(): SupportType.ALL { getSupportType(): SupportType.all {
return SupportType.ALL; return SupportType.all;
} }
parseText(beforeContent: string, extract: DoubanSubject, context: HandleContext): string { parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanSubject, context: HandleContext): void {
log.warn(i18nHelper.getMessage('140101')); log.warn(i18nHelper.getMessage('140101'));
return "";
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
return false; return false;
} }
parseSubjectFromHtml(data: CheerioAPI): DoubanSubject { getHighQuantityImageUrl(fileName:string):string{
return `https://img9.doubanio.com/view/photo/l/public/${fileName}`;
}
getSubjectUrl(id:string):string{
return `https://book.douban.com/subject/${id}/`;
}
parseSubjectFromHtml(data: CheerioAPI, context: HandleContext): DoubanSubject {
log.notice(i18nHelper.getMessage('140101'));
return undefined; return undefined;
} }
analysisUser(html: CheerioAPI, context: HandleContext): { data: CheerioAPI; userState: UserStateSubject } {
log.notice(i18nHelper.getMessage('140101'));
return {data: undefined, userState: undefined};
}
} }

@ -12,6 +12,7 @@ import {DoubanTeleplayLoadHandler} from "./DoubanTeleplayLoadHandler";
import DoubanGameLoadHandler from "./DoubanGameLoadHandler"; import DoubanGameLoadHandler from "./DoubanGameLoadHandler";
import HandleContext from "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import HandleResult from "../model/HandleResult"; import HandleResult from "../model/HandleResult";
import DoubanTheaterLoadHandler from "./DoubanTheaterLoadHandler";
export class DoubanSearchChooseItemHandler { export class DoubanSearchChooseItemHandler {
@ -30,7 +31,7 @@ export class DoubanSearchChooseItemHandler {
new DoubanMusicLoadHandler(doubanPlugin), new DoubanMusicLoadHandler(doubanPlugin),
new DoubanNoteLoadHandler(doubanPlugin), new DoubanNoteLoadHandler(doubanPlugin),
new DoubanGameLoadHandler(doubanPlugin), new DoubanGameLoadHandler(doubanPlugin),
new DoubanTheaterLoadHandler(doubanPlugin),
this._doubanSubjectHandlerDefault]; this._doubanSubjectHandlerDefault];
} }
@ -41,18 +42,17 @@ export class DoubanSearchChooseItemHandler {
let doubanSubjectHandlers: DoubanSubjectLoadHandler<DoubanSubject>[] = this._doubanSubjectHandlers let doubanSubjectHandlers: DoubanSubjectLoadHandler<DoubanSubject>[] = this._doubanSubjectHandlers
.filter(h => h.support(searchExtract)); .filter(h => h.support(searchExtract));
if (doubanSubjectHandlers && doubanSubjectHandlers.length > 0) { if (doubanSubjectHandlers && doubanSubjectHandlers.length > 0) {
doubanSubjectHandlers[0].handle(searchExtract.url, context); await doubanSubjectHandlers[0].handle(searchExtract.id, context);
} else { } else {
this._doubanSubjectHandlerDefault.handle(searchExtract.url, context); await this._doubanSubjectHandlerDefault.handle(searchExtract.id, context);
} }
} }
public async parseText(extract: DoubanSubject, context: HandleContext): Promise<HandleResult> { public async parseText(extract: DoubanSubject, context: HandleContext): Promise<HandleResult> {
let doubanSubjectHandlers: DoubanSubjectLoadHandler<DoubanSubject>[] = this._doubanSubjectHandlers const doubanSubjectHandlers: DoubanSubjectLoadHandler<DoubanSubject>[] = this._doubanSubjectHandlers
.filter(h => h.support(extract)); .filter(h => h.support(extract));
let result:string='';
if (doubanSubjectHandlers && doubanSubjectHandlers.length > 0) { if (doubanSubjectHandlers && doubanSubjectHandlers.length > 0) {
let result = await doubanSubjectHandlers.map(h => h.parse(extract, context)); const result = await doubanSubjectHandlers.map(h => h.parse(extract, context));
if (result && result.length > 0) { if (result && result.length > 0) {
return result[0]; return result[0];
} else { } else {

@ -8,7 +8,6 @@ export default interface DoubanSubjectLoadHandler<T extends DoubanSubject> {
support(extract: DoubanSubject): boolean; support(extract: DoubanSubject): boolean;
handle(url: string, context: HandleContext): void; handle(id: string, context: HandleContext): Promise<T>;
} }

@ -5,7 +5,11 @@ import DoubanSubject from "../model/DoubanSubject";
import DoubanTeleplaySubject from "../model/DoubanTeleplaySubject"; import DoubanTeleplaySubject from "../model/DoubanTeleplaySubject";
import SchemaOrg from "src/org/wanxp/utils/SchemaOrg"; import SchemaOrg from "src/org/wanxp/utils/SchemaOrg";
import HandleContext from "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import {SupportType, TemplateKey} from "../../../constant/Constsant"; import {DataValueType, PersonNameMode, SupportType} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian";
import {TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil";
import {DataField} from "../../../utils/model/DataField";
/** /**
* teleplay * teleplay
@ -17,59 +21,190 @@ export class DoubanTeleplayLoadHandler extends DoubanAbstractLoadHandler<DoubanT
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.TELEPLAY; return SupportType.teleplay;
} }
parseText(beforeContent: string, extract: DoubanTeleplaySubject, context: HandleContext): string { parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanTeleplaySubject, context: HandleContext): void {
const {settings} = context; variableMap.set("director", new DataField("director", DataValueType.array, extract.director,(extract.director || []).map(SchemaOrg.getPersonName).filter(c => c)));
return beforeContent variableMap.set("actor", new DataField(
.replaceAll("{{originalTitle}}", extract.originalTitle ? extract.originalTitle : "") "actor",
.replaceAll("{{director}}", extract.director ? extract.director.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c).join(settings.arraySpilt) : "") DataValueType.array,
.replaceAll("{{actor}}", extract.actor ? extract.actor.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c).join(settings.arraySpilt) : "") extract.actor,
.replaceAll("{{author}}", extract.author ? extract.author.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c).join(settings.arraySpilt) : "") (extract.actor || []).map(SchemaOrg.getPersonName).filter(c => c)
));
variableMap.set("author", new DataField(
"author",
DataValueType.array,
extract.author,
(extract.author || []).map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c)
));
variableMap.set("aliases", new DataField("aliases", DataValueType.array, extract.aliases,
(extract.aliases || []).map(a=>a
.trim()
// .replace(TITLE_ALIASES_SPECIAL_CHAR_REG_G, '_')
// //replase multiple _ to single _
// .replace(/_+/g, '_')
// .replace(/^_/, '')
// .replace(/_$/, '')
.replace(/:\s+/g, ':')
)));
// super.parseAliases(beforeContent, variableMap, extract, context);
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
return extract && extract.type && (extract.type.contains("电视剧") || extract.type.contains("Teleplay") || extract.type.contains("teleplay")); return extract && extract.type && (extract.type.contains("电视剧") || extract.type.contains("Teleplay") || extract.type.contains("teleplay"));
} }
getHighQuantityImageUrl(fileName:string):string{
return `https://img9.doubanio.com/view/photo/l/public/${fileName}`;
}
getSubjectUrl(id:string):string{
return `https://movie.douban.com/subject/${id}/`;
}
parseSubjectFromHtml(data: CheerioAPI): DoubanTeleplaySubject { analysisUser(html: CheerioAPI, context: HandleContext): {data:CheerioAPI , userState: UserStateSubject} {
return data('script') const rate = html('input#n_rating').val();
const rating = html('span#rating');
const tagsStr = rating.next().next().text().trim();
const tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null;
const stateWord = html('div#interest_sect_level > div.a_stars > span.mr10').text().trim();
const collectionDateStr = html('div#interest_sect_level > div.a_stars > span.mr10 > span.collection_date').text().trim();
const userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
const component = rating.next().next().next().next().text().trim();
const userState: UserStateSubject = {
tags: tags,
rate: rate?Number(rate):null,
state: userState1,
collectionDate: collectionDateStr?moment(collectionDateStr, 'YYYY-MM-DD').toDate():null,
comment: component
}
return {data: html, userState: userState};
}
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanTeleplaySubject {
let teleplay: DoubanTeleplaySubject | undefined = html('script')
.get() .get()
.filter(scd => "application/ld+json" == data(scd).attr("type")) .filter(scd => "application/ld+json" == html(scd).attr("type"))
.map(i => { .map(i => {
let item = data(i).text(); let item = html(i).text();
item = super.html_decode(item); item = super.html_decode(item);
let obj = JSON.parse(item.replace(/[\r\n\s+]/g, '')); const obj = JSON.parse(item.replace(/[\r\n\t]+/g, ''));
let idPattern = /(\d){5,10}/g; const idPattern = /(\d){5,10}/g;
let id = idPattern.exec(obj.url); const id = idPattern.exec(obj.url);
let name = obj.name; const name = obj.name;
let titleExec = /[\u4e00-\u9fa5]{2,20}/g.exec(name); const title = super.getTitleNameByMode(name, PersonNameMode.CH_NAME, context)??name;
let title = titleExec ? titleExec[0] : name; const originalTitle = super.getTitleNameByMode(name, PersonNameMode.EN_NAME, context) ?? name;
let originalTitleExec = /[a-zA-Z.\s\-]{2,50}/g.exec(name);
let originalTitle = originalTitleExec ? originalTitleExec[0] : name;
const result: DoubanTeleplaySubject = { const result: DoubanTeleplaySubject = {
id: id ? id[0] : '', id: id ? id[0] : '',
type: 'Teleplay', type: this.getSupportType(),
title: title, title: title,
originalTitle: originalTitle, originalTitle: originalTitle,
desc: obj.description, desc: obj.description,
url: "https://movie.douban.com" + obj.url, url: "https://movie.douban.com" + obj.url,
director: obj.director, director: obj.director || [],
author: obj.author, author: obj.author || [],
actor: obj.actor, actor: obj.actor || [],
aggregateRating: obj.aggregateRating, aggregateRating: obj.aggregateRating,
datePublished: obj.datePublished ? new Date(obj.datePublished) : undefined, datePublished: obj.datePublished ? new Date(obj.datePublished) : undefined,
image: obj.image, image: obj.image,
genre: obj.genre, imageUrl: obj.image,
genre: obj.genre || [],
score: obj.aggregateRating ? obj.aggregateRating.ratingValue : undefined, score: obj.aggregateRating ? obj.aggregateRating.ratingValue : undefined,
publisher: "" publisher: "",
aliases: [""],
language: [""],
country: [],
episode: null,
time: null,
IMDb: null,
} }
return result; return result;
})[0]; })[0];
// Fallback: if JSON-LD parsing failed, extract from meta tags
if (!teleplay) {
const title = html(html("head > meta[property='og:title']").get(0)).attr("content") || '';
const image = html(html("head > meta[property='og:image']").get(0)).attr("content") || '';
const urlMeta = html(html("head > meta[property='og:url']").get(0)).attr("content") || '';
const desc = html(html("head > meta[property='og:description']").get(0)).attr("content") || '';
const idPattern = /(\d){5,10}/g;
const idMatch = idPattern.exec(urlMeta);
const id = idMatch ? idMatch[0] : '';
const scoreText = html("#interest_sectl strong[property='v:average']").text();
const score = scoreText ? parseFloat(scoreText) : undefined;
teleplay = {
id,
title,
type: this.getSupportType(),
score,
originalTitle: title,
desc,
url: urlMeta || (id ? `https://movie.douban.com/subject/${id}/` : ''),
director: [],
author: [],
actor: [],
aggregateRating: undefined,
datePublished: undefined,
image,
imageUrl: image,
genre: [],
publisher: '',
aliases: [],
language: [],
country: [],
episode: null,
time: null,
IMDb: null,
};
}
this.handlePersonNameByMeta(html, teleplay, context, 'video:actor', 'actor');
this.handlePersonNameByMeta(html, teleplay, context, 'video:director', 'director');
const desc:string = html("span[property='v:summary']").text();
if (desc) {
teleplay.desc = desc;
}
const detailDom = html(html("#info").get(0));
const publish = detailDom.find("span.pl");
const valueMap = new Map<string, any>();
publish.map((index, info) => {
const key = html(info).text().trim();
let value;
if (key.indexOf('又名') >= 0 || key.indexOf('语言') >= 0 || key.indexOf('制片国家') >= 0) {
// value = html(info.next.next).text().trim();
const vas = html(info.next).text().trim();
value = vas.split("/").map((v) => v.trim());
}else {
value = html(info.next).text().trim();
}
valueMap.set(TeleplayKeyValueMap.get(key), value);
})
teleplay.country = valueMap.has('country') ? valueMap.get('country') : [];
teleplay.language = valueMap.has('language') ? valueMap.get('language') : [];
teleplay.episode = valueMap.has('episode') ? valueMap.get('episode') : "";
teleplay.time = valueMap.has('time') ? valueMap.get('time') : "";
teleplay.aliases = valueMap.has('aliases') ? valueMap.get('aliases') : [];
teleplay.IMDb = valueMap.has('IMDb') ? valueMap.get('IMDb') : "";
return teleplay;
} }
} }
const TeleplayKeyValueMap: Map<string, string> = new Map(
[['制片国家/地区:', 'country'],
['语言:', 'language'],
['集数:', 'episode'],
['单集片长:', 'time'],
['又名:', 'aliases'],
['IMDb:', 'IMDb']
]
);

@ -0,0 +1,96 @@
import {CheerioAPI} from 'cheerio';
import DoubanAbstractLoadHandler from "./DoubanAbstractLoadHandler";
import DoubanPlugin from "../../../main";
import SchemaOrg from "src/org/wanxp/utils/SchemaOrg";
import DoubanSubject from '../model/DoubanSubject';
import HandleContext from "../model/HandleContext";
import {DataValueType, PropertyName, SupportType} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian";
import {TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil";
import DoubanTheaterSubject from "../model/DoubanTheaterSubject";
import {DataField} from "../../../utils/model/DataField";
export default class DoubanTheaterLoadHandler extends DoubanAbstractLoadHandler<DoubanTheaterSubject> {
constructor(doubanPlugin: DoubanPlugin) {
super(doubanPlugin);
}
getSupportType(): SupportType {
return SupportType.theater;
}
getHighQuantityImageUrl(fileName: string): string {
return `https://img9.doubanio.com/view/photo/l/public/${fileName}`;
}
getSubjectUrl(id:string):string{
return `https://www.douban.com/location/drama/${id}/`;
}
parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanTheaterSubject, context: HandleContext): void {
variableMap.set("director", new DataField(
"director",
DataValueType.array,
extract.director,
(extract.director || []).map(SchemaOrg.getPersonName).filter(c => c)
));
variableMap.set("actor", new DataField(
"actor",
DataValueType.array,
extract.actor,
(extract.actor || []).map(SchemaOrg.getPersonName).filter(c => c)
));
variableMap.set("author", new DataField(
"author",
DataValueType.array,
extract.author,
(extract.author || []).map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c)
));
variableMap.set("aliases", new DataField(
"aliases",
DataValueType.array,
extract.aliases,
(extract.aliases || []).map(a => a
.trim()
.replace(TITLE_ALIASES_SPECIAL_CHAR_REG_G, '_')
//replace multiple _ to single _
.replace(/_+/g, '_')
.replace(/^_/, '')
.replace(/_$/, '')
)
));
}
support(extract: DoubanSubject): boolean {
return extract && extract.type && (extract.type.contains("舞台剧") || extract.type.contains("舞剧") || extract.type.contains("Theater") || extract.type.contains("theater"));
}
analysisUser(html: CheerioAPI, context: HandleContext): { data: CheerioAPI, userState: UserStateSubject } {
const rate = html('input#n_rating').val();
const tagsStr = html('div#interest_sect_level > div.a_stars > span.color_gray').text().trim();
const tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null;
const stateWord = html('#interest_sect_level > h2').text().trim();
const collectionDateStr = html('div#interest_sect_level > div.a_stars > span.mr10 > span.collection_date').text().trim();
const userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
const component = this.getPropertyValue(html, PropertyName.comment);
const userState: UserStateSubject = {
tags: tags,
rate: rate ? Number(rate) : null,
state: userState1,
collectionDate: collectionDateStr ? moment(collectionDateStr, 'YYYY-MM-DD').toDate() : null,
comment: component
}
return {data: html, userState: userState};
}
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanTheaterSubject {
const obj: DoubanTheaterSubject = new DoubanTheaterSubject();
obj.id = this.getPropertyValue(html, PropertyName.id);
return obj;
}
}

@ -15,15 +15,15 @@ export default class DoubanBookSubject extends DoubanSubject {
} }
export const DoubanBookParameter = { export const DoubanBookParameter = {
author: '{{author}}', author: 'author',
translator: '{{translator}}', translator: 'translator',
isbn: '{{isbn}}', isbn: 'isbn',
originalTitle: '{{originalTitle}}', originalTitle: 'originalTitle',
subTitle: '{{subTitle}}', subTitle: 'subTitle',
totalPage: '{{totalPage}}', totalPage: 'totalPage',
series: '{{series}}', series: 'series',
menu: '{{menu}}', menu: 'menu',
price: '{{price}}', price: 'price',
binding: '{{binding}}', binding: 'binding',
producer: '{{producer}}', producer: 'producer',
} }

@ -8,5 +8,9 @@ export default class DoubanMovieSubject extends DoubanSubject {
actor: Person[]; actor: Person[];
aggregateRating: AggregateRating; aggregateRating: AggregateRating;
originalTitle: string; originalTitle: string;
aliases: string[];
language: string[];
country: string[];
time: string;
IMDb: string;
} }

@ -6,4 +6,5 @@ export default class DoubanMusicSubject extends DoubanSubject {
medium: string; medium: string;
records: number; records: number;
barcode: string; barcode: string;
menu: string[];
} }

@ -1,4 +1,5 @@
import {UserStateSubject} from "./UserStateSubject"; import {UserStateSubject} from "./UserStateSubject";
import {SubjectHandledStatus} from "../../../constant/Constsant";
export default class DoubanSubject { export default class DoubanSubject {
id: string; id: string;
@ -6,12 +7,15 @@ export default class DoubanSubject {
type: string; type: string;
score: number; score: number;
image: string; image: string;
imageUrl: string;
url: string; url: string;
desc: string; desc: string;
publisher: string; publisher: string;
datePublished: Date; datePublished: Date;
genre: string[]; genre: string[];
userState?: UserStateSubject; userState?: UserStateSubject;
guessType?: string;
handledStatus?: SubjectHandledStatus = SubjectHandledStatus.init;
} }
const ParameterMap: Map<string, string> = new Map([ const ParameterMap: Map<string, string> = new Map([
@ -24,12 +28,34 @@ export const DoubanParameter = {
TYPE: '{{type}}', TYPE: '{{type}}',
SCORE: '{{score}}', SCORE: '{{score}}',
IMAGE: '{{image}}', IMAGE: '{{image}}',
IMAGE_URL: '{{imageData.url}}',
URL: '{{url}}', URL: '{{url}}',
DESC: '{{desc}}', DESC: '{{desc}}',
PUBLISHER: '{{publisher}}', PUBLISHER: '{{publisher}}',
DATE_PUBLISHED: '{{datePublished}}', DATE_PUBLISHED: '{{datePublished}}',
TIME_PUBLISHED: '{{timePublished}}', TIME_PUBLISHED: '{{timePublished}}',
YEAR_PUBLISHED: '{{yearPublished}}',
GENRE: '{{genre}}', GENRE: '{{genre}}',
CURRENT_DATE: '{{currentDate}}', CURRENT_DATE: '{{currentDate}}',
CURRENT_TIME: '{{currentTime}}', CURRENT_TIME: '{{currentTime}}',
} }
export const DoubanParameterName = {
ID: 'id',
TITLE: 'title',
TYPE: 'type',
SCORE: 'score',
SCORE_STAR: 'scoreStar',
IMAGE: 'image',
IMAGE_URL: 'imageData.url',
URL: 'url',
DESC: 'desc',
PUBLISHER: 'publisher',
DATE_PUBLISHED: 'datePublished',
TIME_PUBLISHED: 'timePublished',
YEAR_PUBLISHED: 'yearPublished',
GENRE: 'genre',
CURRENT_DATE: 'currentDate',
CURRENT_TIME: 'currentTime',
}

@ -8,4 +8,10 @@ export default class DoubanTeleplaySubject extends DoubanSubject {
actor: Person[]; actor: Person[];
aggregateRating: AggregateRating; aggregateRating: AggregateRating;
originalTitle: string; originalTitle: string;
aliases: string[];
language: string[];
country: string[];
episode: string;
time: string;
IMDb: string;
} }

@ -0,0 +1,13 @@
import {AggregateRating, Person} from 'schema-dts';
import DoubanSubject from "./DoubanSubject";
export default class DoubanTheaterSubject extends DoubanSubject {
director: string[];
author: string[];
actor: string[];
aggregateRating: AggregateRating;
originalTitle: string;
aliases: string[];
language: string[];
}

@ -1,10 +1,15 @@
import {SearchHandleMode} from "../../../constant/Constsant";
import {Editor} from "obsidian";
import { DoubanPluginSetting } from "../../setting/model/DoubanPluginSetting";
import UserComponent from "../../user/UserComponent";
import NetFileHandler from "src/org/wanxp/net/NetFileHandler";
import DoubanPlugin from "../../../main"; import DoubanPlugin from "../../../main";
import { DoubanPluginSetting } from "../../setting/model/DoubanPluginSetting";
import DoubanSubject from "./DoubanSubject";
import {Editor} from "obsidian";
import GlobalStatusHolder from "../../model/GlobalStatusHolder";
import NetFileHandler from "src/org/wanxp/net/NetFileHandler";
import {SearchHandleMode} from "../../../constant/Constsant";
import {SearchPageInfo} from "./SearchPageInfo";
import {SearchResultsPage} from "schema-dts";
import {SyncConfig} from "../../sync/model/SyncConfig";
import SyncStatusHolder from "../../sync/model/SyncStatusHolder"; import SyncStatusHolder from "../../sync/model/SyncStatusHolder";
import UserComponent from "../../user/UserComponent";
export default interface HandleContext { export default interface HandleContext {
plugin:DoubanPlugin; plugin:DoubanPlugin;
@ -14,8 +19,13 @@ export default interface HandleContext {
userComponent: UserComponent; userComponent: UserComponent;
netFileHandler: NetFileHandler; netFileHandler: NetFileHandler;
showAfterCreate?:boolean; showAfterCreate?:boolean;
syncStatusHolder?:SyncStatusHolder; syncStatusHolder?:GlobalStatusHolder;
action:string; action:string;
outputFolder?:string; syncConfig?: SyncConfig;
dataFileNamePath?:string; listItem?:DoubanSubject;
syncActive?:boolean;
searchPage?:SearchPageInfo;
syncOffset?:number;
} }

@ -2,6 +2,7 @@ import DoubanSubject from "./DoubanSubject";
export default interface HandleResult { export default interface HandleResult {
content:string content:string
filePath?:string
fileName?:string fileName?:string
subject?:DoubanSubject, subject?:DoubanSubject,
} }

@ -0,0 +1,14 @@
import { SearchPageInfo } from "./SearchPageInfo";
import { SupportType } from "../../../constant/Constsant";
import {SearchPageTypeOf} from "./SearchPageTypeOf";
export class SearchPage extends SearchPageTypeOf<any> {
public static empty(type: SupportType): SearchPage {
return new SearchPage(0, 1, 0, type, []);
}
static emptyWithNoType() {
return new SearchPage(0, 1, 0, null, []);
}
}

@ -0,0 +1,84 @@
import {SupportType} from "../../../constant/Constsant";
export class SearchPageInfo {
private _total: number;
private _pageSize: number;
private _pageNum: number;
private _hasNext: boolean;
private _type: SupportType;
constructor(total: number, pageNum: number, pageSize: number, type: SupportType) {
this._total = total;
this._pageNum = pageNum;
this._pageSize = pageSize;
this._hasNext = (pageNum * pageSize) < total;
this._type = type;
}
public nextPage(): SearchPageInfo {
if (!this._hasNext) {
return this;
}
return new SearchPageInfo(this.total, this._pageNum + 1,
this._pageSize, this._type);
}
public previousPage(): SearchPageInfo {
if (this._pageNum == 0) {
return this;
}
return new SearchPageInfo(this.total, this._pageNum - 1,
this._pageSize, this._type);
}
public typePage(type: SupportType): SearchPageInfo {
return new SearchPageInfo(this.total, 0,
this._pageSize, this._type);
}
public get hasNext() {
return this._hasNext;
}
public get hasPrevious() {
return this._pageNum > 1;
}
public get start() {
return (this._pageNum - 1) * this._pageSize + 1;
}
public get total() {
return this._total;
}
public set total(total: number) {
this._total = total;
}
get pageSize(): number {
return this._pageSize;
}
get pageNum(): number {
return this._pageNum;
}
get type(): SupportType {
return this._type;
}
allPage() {
if (this._pageNum == 0) {
return this;
}
return new SearchPageInfo(this.total, this._pageNum - 1,
this._pageSize, SupportType.all);
}
}

@ -0,0 +1,29 @@
import { SearchPageInfo } from "./SearchPageInfo";
import { SupportType } from "../../../constant/Constsant";
export class SearchPageTypeOf<T> extends SearchPageInfo {
private _list: T[];
constructor(
total: number,
pageNum: number,
pageSize: number,
type: SupportType,
list: T[],
) {
super(total, pageNum, pageSize, type);
this._list = list;
}
public get list() {
return this._list;
}
public static empty(type: SupportType): SearchPageTypeOf<any> {
return new SearchPageTypeOf(0, 1, 0, type, []);
}
static emptyWithNoType() {
return new SearchPageTypeOf(0, 1, 0, null, []);
}
}

@ -1,4 +1,6 @@
export interface SubjectListItem { export interface SubjectListItem {
id:string; id:string;
url:string; url:string;
title:string;
updateDate: Date | null;
} }

@ -15,3 +15,12 @@ export const DoubanUserParameter = {
MY_COMMENT: '{{myComment}}', MY_COMMENT: '{{myComment}}',
MY_COLLECTION_DATE: '{{myCollectionDate}}', MY_COLLECTION_DATE: '{{myCollectionDate}}',
} }
export const DoubanUserParameterName = {
MY_TAGS: 'myTags',
MY_RATING: 'myRating',
MY_RATING_STAR: 'myRatingStar',
MY_STATE: 'myState',
MY_COMMENT: 'myComment',
MY_COLLECTION_DATE: 'myCollectionDate',
}

Some files were not shown because too many files have changed in this diff Show More