Compare commits

...

107 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
159 changed files with 6175 additions and 10985 deletions

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)

154
README.md

@ -19,97 +19,92 @@
</a> </a>
</p> </p>
在[Obsidian](https://obsidian.md/)使用并导入豆瓣中的 _电影/书籍/音乐/电视剧/日记/游戏_ 甚至是 _你标记过的书影音_ , 包含你的评分/发布日期/演员表等信息. 这是一款[Obsidian](https://obsidian.md/)插件支持在Obsidian中导入[豆瓣]()中的 _电影、书籍、音乐、电视剧、日记、游戏_
甚至是 _你标记过的书影音_ , 包含你的评分、观看日期、评论、阅读状态等信息.
访问[Get Started/指导手册](https://obsidian-douban.wxp.hk/) 获取更多
[//]: # (访问[Get Started/指导手册]&#40;https://obsidian-douban.wanxuping.com/&#41; 获取更多 )
![background](./doc/background.png) ![background](./doc/background.png)
--- ---
关于当前的插件如果有任何疑问, 缺少想要的导入内容或者想要什么功能, 欢迎提issues或加入到开发当中. 关于当前的插件如果有任何疑问, 缺少想要的导入内容或者想要什么功能, 欢迎提issues或加入到开发当中.
如果觉得喜欢或对您有帮助,欢迎一键三连-点亮 ⭐Star 如果觉得喜欢或对您有帮助,欢迎一键三连-点亮 ⭐Star
- [异常, 问题 & 新的想法](https://github.com/Wanxp/obsidian-douban/issues) - [异常, 问题 & 新的想法](https://github.com/Wanxp/obsidian-douban/issues)
- 阅读其它语言的介绍请点击 [English](./doc/README.en.md) | [简体中文](./README.md) - 阅读其它语言的介绍请点击 [English](README.en.md) | 简体中文
## 功能 ## 功能
- ☑️ 同步个人看过的电影 - ☑️ 导入电影、电视剧、书籍、音乐、游戏、日记
- ☑️ 同步个人阅读过的书籍 - ☑️ 同步个人听过/看过的电影、电视剧、书籍、音乐、游戏
- ☑️ 同步个人听过的音乐
- ☑️ 导入电影
- ☑️ 导入电视剧
- ☑️ 导入书籍
- ☑️ 导入音乐
- ☑️ 导入日记
- ☑️ 导入游戏
- ☑️ 导入个人的评论,评论时间,阅读状态,个人评分 - ☑️ 导入个人的评论,评论时间,阅读状态,个人评分
- ☑️ 支持保存封面至本地 - ☑️ 支持保存封面至本地/图床
- ⬜ 支持图床自定义
- ☑️ 支持自定义参数 - ☑️ 支持自定义参数
- ❌ 广播 - ☑️ 支持移动端导入
- ⬜ 支持使用AI大模型ChatGPT、Deepseek、Ollama分析导入
## 拓展 ## 效果
1. 结合Timeline插件 __构建个人观影时间线__,请参照[结合timeline插件实现时间线效果](./doc/Obsidian-Douban-TimeLine.md)) 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. 结合DataView插件__构建个人电子书架书库数据__请参照[结合dateview插件实现个人书架效果](./doc/Obsidian-Douban-DataView.md))-->
2. 结合主题 __构建类豆瓣网页效果__,请参照[结合Blue Topaz实现网页效果](./doc/Obsidian-Douban-BlueTopaz.md)
![](./doc/background.png)
## 如何使用 ## 如何使用
### 同步
- 同步个人的观影、阅读、游戏、音乐记录
从豆瓣同步数据(如何利用Timeline插件构建阅读/观影时间线,请参照[结合timeline插件实现时间线效果](./doc/Obsidian-Douban-TimeLine.md))
![Sync Data From Douban](doc/img/sync_data_from_douban.gif)
### 搜索 ### 搜索
使用方式: 输入<kbd>Ctrl</kbd> + <kbd>P</kbd>输入“豆瓣”或“Douban”选择搜索并使用
- 搜索数据并创建笔记 - 搜索数据并创建笔记
- 通过当前文件名搜索
- 通过输入文本搜索
![search_and_create](doc/img/search_and_create_note.gif) ![search_and_create](doc/img/search_and_create_note.gif)
- 通过当前文件名搜索 ### 同步
![Search Movie By File Name](doc/img/search_by_file_name.gif) - 同步个人的观影、观剧、阅读、游戏、音乐记录
![Sync Data From Douban](doc/img/sync_data_from_douban.gif)
- 通过输入文本搜索
![Search Movie By Input Text](doc/img/search_by_input.gif)
## 设置 ## 设置
- 设置案例1(自定义模板) - 设置豆瓣账号(可选,可使用少部分功能)
![Setting Example1](doc/img/setting_zh.gif) - 设置导入模板(可选,不设置的情况下使用默认模板)
- 设置导入路径(可选,不设置的情况下使用默认路径)
- 设置案例2(其它配置)
![Setting Example2](doc/img/setting_en.gif)
## 支持的字段 ## 支持的字段
(若有缺少想导入的字段, 欢迎提issues反馈) (若有缺少想导入的字段, 欢迎提issues反馈)
| 字段 | 电影 | 电视剧 | 书籍 | 音乐 | 日记 | 游戏 | * | | 字段 | 电影 | 电视剧 | 书籍 | 音乐 | 日记 | 游戏 | 人物 |
|------------------|-------------------|------------------|-------------------|----------------|----------------|---------------|-------| |------------------|------------------|-------------------|-------------------|---------------|----------------|---------------|-------|
| id | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | id | | id | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | 豆瓣ID | id |
| title | 电影名称 | 电视剧名称 | 书名 | 音乐名 | 日记标题 | 游戏名称 | 剧名 | | title | 电影名称 | 电视剧名称 | 书名 | 音乐名 | 日记标题 | 游戏名称 | 姓名 |
| type | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 | | type | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 | 类型 |
| score | 评分 | 评分 | 评分 | 评分 | 评分 | 评分 | 评分 | | score | 评分 | 评分 | 评分 | 评分 | 评分 | 评分 | |
| image | 封面 | 封面 | 封面 | 封面 | 图片 | 封面 | 封面 | | scoreStar | 评分⭐ | 评分⭐ | 评分⭐ | 评分⭐ | 评分⭐ | 评分⭐ | |
| imageData.url | 封面url | 封面url | 封面url | 封面url | 封面url | 封面url | 封面url | | image | 封面 | 封面 | 封面 | 封面 | 图片 | 封面 | 照片 |
| url | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | - | | imageData.url | 封面url | 封面url | 封面url | 封面url | 封面url | 封面url | 照片url |
| desc | 简介 | 简介 | 内容简介 | 简介 | 简介 | 简介 | - | | url | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 | 豆瓣网址 |
| publisher | - | - | 出版社 | 出版者 | 发布者 | 发行商 | - | | desc | 简介 | 简介 | 内容简介 | 简介 | 简介 | 简介 | 简介 |
| datePublished | 上映日期 | 上映日期 | 出版年 | 发行时间 | 发布时间 | 发行日期 | - | | publisher | - | - | 出版社 | 出版者 | 发布者 | 发行商 | - |
| yearPublished | 上映年份 | 上映年份 | 出版年份 | 发行年份 | 发布年份 | 发行年份 | - | | datePublished | 上映日期 | 上映日期 | 出版年 | 发行时间 | 发布时间 | 发行日期 | - |
| genre | 类型 | 类型 | - | 流派 | - | 类型 | - | | yearPublished | 上映年份 | 上映年份 | 出版年份 | 发行年份 | 发布年份 | 发行年份 | - |
| currentDate | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | | | genre | 类型 | 类型 | - | 流派 | - | 类型 | - |
| currentTime | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | | | currentDate | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | 今日日期 | |
| myTags | 我标记的标签 | 我标记的标签 | 我标记的标签 | 我标记的标签 | - | 我标记的标签 | | | currentTime | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | 当前时间 | |
| myRating | 我的评分 | 我的评分 | 我的评分 | 我的评分 | - | 我的评分 | | myTags | 我标记的标签 | 我标记的标签 | 我标记的标签 | 我标记的标签 | - | 我标记的标签 | |
| myState | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想听/在听/听过 | - | 状态:想玩/在玩/玩过 | | | myRating | 我的评分 | 我的评分 | 我的评分 | 我的评分 | - | 我的评分 |
| myComment | 我的评语 | 我的评语 | 我的评语 | 我的评语 | - | 我的评语 | | | myState | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想看/在看/看过 | 状态:想听/在听/听过 | - | 状态:想玩/在玩/玩过 | |
| myCollectionDate | 我标记的时间 | 我标记的时间 | 我标记的时间 | 我标记的时间 | - | 我标记的时间 | | | myComment | 我的评语 | 我的评语 | 我的评语 | 我的评语 | - | 我的评语 | |
| 扩展1 | director:导演 | director:导演 | author:原作者 | actor: 表演者 | author:作者 | aliases:别名 | | | myCollectionDate | 我标记的时间 | 我标记的时间 | 我标记的时间 | 我标记的时间 | - | 我标记的时间 | |
| 扩展2 | author:编剧 | author:编剧 | translator:译者 | albumType:专辑类型 | authorUrl:作者网址 | developer:开发商 | | | 扩展1 | director:导演* | director:导演* | author:原作者 | actor: 表演者 | author:作者 | aliases:别名 | |
| 扩展3 | actor:主演 | actor:主演 | isbn:isbn | medium:介质 | content:日记内容 | platform:平台 | | | 扩展2 | author:编剧* | author:编剧* | translator:译者 | albumType:专辑类型 | authorUrl:作者网址 | developer:开发商 | |
| 扩展4 | originalTitle:原作名 | originalTitle:原作名 | originalTitle:原作名 | records:唱片数 | | | | | 扩展3 | actor:主演* | actor:主演* | isbn:isbn | medium:介质 | content:日记内容 | platform:平台 | |
| 扩展5 | country:国家 | country:国家 | subTitle:副标题 | barcode:条形码 | | | | | 扩展4 | originalTitle:原作名 | originalTitle:原作名 | originalTitle:原作名 | records:唱片数 | | | |
| 扩展6 | language:语言 | language:语言 | totalPage:页数 | | | | | | 扩展5 | country:国家 | country:国家 | subTitle:副标题 | barcode:条形码 | | | |
| 扩展7 | time:片长 | time:片长 | series:丛书 | | | | | | 扩展6 | language:语言 | language:语言 | totalPage:页数 | | | | |
| 扩展8 | aliases:又名 | aliases:又名 | menu:目录 | | | | | | 扩展7 | time:片长 | time:片长 | series:丛书 | | | | |
| 扩展9 | IMDb | IMDb | price:定价 | | | | | | 扩展8 | aliases:又名* | aliases:又名* | menu:目录 | | | | |
| 扩展7 | | episode:集数 | binding:装帧 | | | | | | 扩展9 | IMDb | IMDb | price:定价 | | | | |
| 扩展8 | | | producer: 出品方 | | | | | | 扩展7 | | episode:集数 | binding:装帧 | | | | |
| 扩展8 | | | producer: 出品方 | | | | |
- 注: myTags, myRating, myState, myComment, myCollectionDate 参数均为在插件中登录后可用 - 注: myTags, myRating, myRatingStar:⭐ , myState, myComment, myCollectionDate 参数均为在插件中登录后可用
## 如何安装 ## 如何安装
@ -126,7 +121,7 @@
3. 在obsidian插件中心开启当前插件功能 3. 在obsidian插件中心开启当前插件功能
## 如何开发调试 ## 如何开发调试
### 开发
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`
@ -140,9 +135,20 @@
`npm run dev` `npm run dev`
7. 进入Obsidian插件中心重新加载当前插件 7. 进入Obsidian插件中心重新加载当前插件
8. 享受开发吧 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/obsidian-douban-discord-qr_code.svg" width="300px"> <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"> )
@ -167,6 +173,8 @@
| 同步书影音数据 | 以上所有 | 以上所有 | 以上所有 | | 同步书影音数据 | 以上所有 | 以上所有 | 以上所有 |
| 同步书影音数据 | `替换同名文档`值为勾选 | 已经存在 **同路径同文档名** ,直接覆盖 | 如已经存在在`data/Movie/蝙蝠侠.md`,配置`笔记名称`值为`/data/{{type}}/{{title}}`, 同步书影音记录时勾选 `替换同名文档`, 则`data/Movie/蝙蝠侠.md`会被替换成最新 | | 同步书影音数据 | `替换同名文档`值为勾选 | 已经存在 **同路径同文档名** ,直接覆盖 | 如已经存在在`data/Movie/蝙蝠侠.md`,配置`笔记名称`值为`/data/{{type}}/{{title}}`, 同步书影音记录时勾选 `替换同名文档`, 则`data/Movie/蝙蝠侠.md`会被替换成最新 |
## 鸣谢
### IDE支持
[<image src="doc/img/jb_beam.svg"> </image>](https://www.jetbrains.com/?from=obsidian-douban) [//]: # (### 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)

@ -1,70 +0,0 @@
## 效果如下
![](./img/obsidian-douban-time-preview-example.gif)
## 适用人群
1. 在豆瓣有标记/评论/评分的习惯的人
比如看完电影,会在豆瓣进行评分或评论。或者阅读完的书籍,进行评分或评论。支持包含:电影、书籍、电视剧、音乐、游戏
## 实现步骤
1. 安装[Timeline](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}}
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)

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

@ -1,159 +0,0 @@
# 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>
Import _Movie, Book, Music, Teleplay, Note, Game_ even _Your Personal Movie/Book/Music_ from Douban in [Obsidian](https://obsidian.md/)
![background](./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.en.md) | [简体中文](../README.md)
## Target/功能
- [x] Sync Personal Movie
- [x] Sync Personal Book
- [x] Sync Personal Music
- [x] Import Movie
- [x] Import Teleplay
- [x] Import Book
- [x] Import Music
- [x] Import Note
- [x] Import Game
- [x] Personal Comment
- [x] Attachment Files
- [x] Custom Variables
- [ ] Broadcast
## 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](img/sync_data_from_douban.gif)
### Search
- Search Data And Create Note
![search_and_create]img/search_and_create_note.gif)
- Search Data By File Name
![Search Movie By File Name](img/search_by_file_name.gif)
- Search Movie By Input Text
![Search Movie By Input Text](img/search_by_input.gif)
## Settings
- Setting Example1(Custom Template)
![Setting Example1](img/setting_zh.gif)
- Setting Example2(Other Settings)
![Setting Example2](img/setting_en.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="img/obsidian-douban-discord-qr_code.svg" width="300px"> <img src="img/obsidian-douban-qq-qr_code.svg" width="300px">
## 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)

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 492 KiB

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

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 MiB

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 MiB

BIN
doc/img/support_pay_2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 494 KiB

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

@ -1,7 +1,7 @@
{ {
"id": "obsidian-douban-plugin", "id": "obsidian-douban-plugin",
"name": "Douban", "name": "Douban",
"version": "1.9.8", "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",

9458
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": "1.9.8", "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,13 +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.3", "follow-redirects": "^1.15.6",
"schema-dts": "^1.1.0" "schema-dts": "^1.1.0"
} }
} }

@ -2,6 +2,7 @@ import {i18nHelper} from "../lang/helper";
import DoubanSearchResultSubject from "../douban/data/model/DoubanSearchResultSubject"; import DoubanSearchResultSubject from "../douban/data/model/DoubanSearchResultSubject";
import StringUtil from "../utils/StringUtil"; import StringUtil from "../utils/StringUtil";
import {DoubanPluginOnlineSettings} from "../douban/setting/model/DoubanPluginOnlineSettings"; import {DoubanPluginOnlineSettings} from "../douban/setting/model/DoubanPluginOnlineSettings";
import {DataField} from "../utils/model/DataField";
/** /**
* *
@ -100,15 +101,34 @@ 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', 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 { export enum PropertyName {
//base //base
@ -180,15 +200,15 @@ export enum PropertyName {
/** /**
* *
*/ */
// @ts-ignore
export const SearchTypeRecords: { [key in SupportType]: string } = { export const SearchTypeRecords: { [key in SupportType]: string } = {
[SupportType.ALL]: i18nHelper.getMessage('ALL'), [SupportType.all]: i18nHelper.getMessage('ALL'),
[SupportType.MOVIE]: i18nHelper.getMessage('MOVIE_AND_TELEPLAY'), [SupportType.movie]: i18nHelper.getMessage('MOVIE_AND_TELEPLAY'),
[SupportType.BOOK]: i18nHelper.getMessage('BOOK'), [SupportType.book]: i18nHelper.getMessage('BOOK'),
[SupportType.MUSIC]: i18nHelper.getMessage('MUSIC'), [SupportType.music]: i18nHelper.getMessage('MUSIC'),
[SupportType.NOTE]: i18nHelper.getMessage('NOTE'), [SupportType.note]: i18nHelper.getMessage('NOTE'),
[SupportType.GAME]: i18nHelper.getMessage('GAME'), [SupportType.game]: i18nHelper.getMessage('GAME'),
[SupportType.TELEPLAY]: i18nHelper.getMessage('TELEPLAY'), [SupportType.theater]: i18nHelper.getMessage('THEATER'),
[SupportType.THEATER]: i18nHelper.getMessage('THEATER'),
} }
/** /**
@ -203,6 +223,7 @@ 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',
@ -215,20 +236,23 @@ export const SyncTypeUrlDomain: Map<SyncType, string> = new Map([
[SyncType.broadcast , 'broadcast'], [SyncType.broadcast , 'broadcast'],
[SyncType.note , 'note'], [SyncType.note , 'note'],
[SyncType.music , 'music'], [SyncType.music , 'music'],
[SyncType.teleplay , 'movie']] [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.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'),
} }
/** /**
@ -256,6 +280,7 @@ export enum SyncItemStatus {
replace = 'replace', replace = 'replace',
create = 'create', create = 'create',
fail = 'fail', fail = 'fail',
failByDiffType = 'failByDiffType',
unHandle = 'unHandle', unHandle = 'unHandle',
} }
@ -370,13 +395,13 @@ sec-ch-ua-platform: "Windows"
export const ONLINE_SETTING_DEFAULT: DoubanPluginOnlineSettings = { export const ONLINE_SETTING_DEFAULT: DoubanPluginOnlineSettings = {
properties: [ properties: [
{ {
type: SupportType.BOOK, type: SupportType.book,
name: PropertyName.comment, name: PropertyName.comment,
selectors: ['#interest_sect_level > div > span:nth-child(7)' selectors: ['#interest_sect_level > div > span:nth-child(7)'
] ]
}, },
{ {
type: SupportType.MOVIE, type: SupportType.movie,
name: PropertyName.comment, name: PropertyName.comment,
selectors: ['#interest_sect_level > div > span:nth-child(8)', selectors: ['#interest_sect_level > div > span:nth-child(8)',
'#interest_sect_level > div > span:nth-child(7)', '#interest_sect_level > div > span:nth-child(7)',
@ -395,5 +420,131 @@ export enum SubjectHandledStatus {
syncTypeDiffAbort = 'syncTypeDiffAbort', 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,7 +1,21 @@
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";
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", onlineSettingsFileName: "obsidian_douban_plugin_online_settings.json",
onlineSettingsGistId: "35693f9ece9bd6abba98f94e81afde19", onlineSettingsGistId: "35693f9ece9bd6abba98f94e81afde19",
movieTemplateFile: ``, movieTemplateFile: ``,
@ -24,17 +38,30 @@ export const DEFAULT_SETTINGS: DoubanPluginSetting = {
statusBar: true, statusBar: true,
debugMode: false, 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: '', loginHeadersContent: '',
cacheImage: true, cacheImage: true,
cacheHighQuantityImage: true, cacheHighQuantityImage: true,
attachmentPath: 'assets', attachmentPath: 'assets',
syncHandledDataArray: [] attachmentFileName: "{{title}}",
syncHandledDataArray: [],
// syncLastUpdateTime: new Map<string, string>(),
scoreSetting: {
starFull: '⭐',
starEmpty: '☆',
displayStarEmpty: false,
maxStar: 5,
},
searchDefaultType: SupportType.all,
} }

@ -6,6 +6,7 @@ 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}}
@ -35,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}}
@ -60,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}}
@ -75,6 +78,10 @@ desc: {{desc}}
--- ---
![image]({{image}}) ![image]({{image}})
---
Menu:
{{menu}}
`, `,
noteTemplateFileContent: `--- noteTemplateFileContent: `---
doubanId: {{id}} doubanId: {{id}}
@ -98,6 +105,7 @@ 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}}
@ -116,6 +124,7 @@ 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}}
@ -145,7 +154,9 @@ 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}}
@ -180,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}}
@ -211,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}}
@ -229,8 +244,12 @@ desc: {{desc}}
![image]({{image}}) ![image]({{image}})
Comment:
--- ---
Menu:
{{menu}}
---
Comment:
{{myComment}} {{myComment}}
`, `,
@ -256,7 +275,9 @@ 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}}
@ -280,7 +301,9 @@ 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}}

@ -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',
@ -66,14 +66,14 @@ export const DoubanSubjectStateRecords_THEATER: { [key in DoubanSubjectState]: s
} }
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, [SupportType.theater]:DoubanSubjectStateRecords_THEATER,
} }
@ -106,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'),
} }
@ -123,33 +132,51 @@ 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> ( export const DoubanSubjectStateRecords_KEY_WORD_TYPE: Map<string, SupportType> = new Map<string, SupportType> (
[['我看过这部电视剧', SupportType.TELEPLAY], [['我看过这部电视剧', SupportType.teleplay],
['我最近看过这部电视剧', SupportType.TELEPLAY], ['我最近看过这部电视剧', SupportType.teleplay],
['我想看这部电视剧', SupportType.TELEPLAY], ['我想看这部电视剧', SupportType.teleplay],
['我在看这部电视剧', SupportType.TELEPLAY], ['我在看这部电视剧', SupportType.teleplay],
['我最近在看这部电视剧', SupportType.TELEPLAY], ['我最近在看这部电视剧', SupportType.teleplay],
['我最近看过这部电影', SupportType.MOVIE], ['我最近看过这部电影', SupportType.movie],
['我看过这部电影', SupportType.MOVIE], ['我看过这部电影', SupportType.movie],
['我想看这部电影', SupportType.MOVIE], ['我想看这部电影', SupportType.movie],
['我读过这本书', SupportType.BOOK], ['我读过这本书', SupportType.book],
['我想读这本书', SupportType.BOOK], ['我想读这本书', SupportType.book],
['我在读这本书', SupportType.BOOK], ['我在读这本书', SupportType.book],
['我最近在读这本书', SupportType.BOOK], ['我最近在读这本书', SupportType.book],
['我最近听过这张唱片', SupportType.MUSIC], ['我最近听过这张唱片', SupportType.music],
['我听过这张唱片', SupportType.MUSIC], ['我听过这张唱片', SupportType.music],
['我想听这张唱片', SupportType.MUSIC], ['我想听这张唱片', SupportType.music],
['我在听这张唱片', SupportType.MUSIC], ['我在听这张唱片', SupportType.music],
['我最近在听这张唱片', SupportType.MUSIC], ['我最近在听这张唱片', SupportType.music],
['我最近玩过这个游戏', SupportType.GAME], ['我最近玩过这个游戏', SupportType.game],
['我玩过这个游戏', SupportType.GAME], ['我玩过这个游戏', SupportType.game],
['我想玩这个游戏', SupportType.GAME], ['我想玩这个游戏', 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,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";
import StringUtil from "../../utils/StringUtil"; import StringUtil from "../../utils/StringUtil";
import {Integer} from "schema-dts"; import {Integer} from "schema-dts";

@ -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

@ -1,17 +1,23 @@
import { import {
App, App,
ButtonComponent, ButtonComponent, DropdownComponent,
Modal, SearchComponent, Setting, Modal, SearchComponent, Setting, TextComponent, ValueComponent,
} 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,
SupportType, SyncConditionType,
SyncConditionTypeRecords,
SyncType,
SyncTypeRecords
} from "../../constant/Constsant";
import {
ALL, DoubanSubjectState, DoubanSubjectStateRecords,
DoubanSubjectStateRecords_BOOK_SYNC, DoubanSubjectStateRecords_BOOK_SYNC,
DoubanSubjectStateRecords_BROADCAST_SYNC, DoubanSubjectStateRecords_BROADCAST_SYNC, DoubanSubjectStateRecords_GAME_SYNC,
DoubanSubjectStateRecords_MOVIE_SYNC, DoubanSubjectStateRecords_MOVIE_SYNC,
DoubanSubjectStateRecords_MUSIC_SYNC, DoubanSubjectStateRecords_MUSIC_SYNC,
DoubanSubjectStateRecords_NOTE_SYNC, DoubanSubjectStateRecords_NOTE_SYNC,
@ -25,6 +31,12 @@ import {createFileSelectionSetting} from "../setting/TemplateSettingHelper";
import {FileSuggest} from "../setting/model/FileSuggest"; import {FileSuggest} from "../setting/model/FileSuggest";
import {getDefaultTemplateContent} from "../../constant/DefaultTemplateContent"; import {getDefaultTemplateContent} from "../../constant/DefaultTemplateContent";
import TimeUtil from "../../utils/TimeUtil"; 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;
@ -96,7 +108,16 @@ export class DoubanSyncModal extends Modal {
progress.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() == 0 ? 1:syncStatus.getTotal()}" value="${syncStatus.getHasHandle()}"> </progress> <span> ${syncStatus.getHasHandle()}/${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>
<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); backgroundButton.setDisabled(true);
stopButton.setButtonText(i18nHelper.getMessage('110036')) stopButton.setButtonText(i18nHelper.getMessage('110036'))
return; return;
@ -105,7 +126,16 @@ export class DoubanSyncModal extends Modal {
<label for="file">${i18nHelper.getMessage('110033')}</label> <label for="file">${i18nHelper.getMessage('110033')}</label>
<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()} <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()}
${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + TimeUtil.estimateTimeMsg(syncStatus.getNeedHandled()-syncStatus.getHandle(), syncStatus.getOverSize())} </span> ${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + TimeUtil.estimateTimeMsg(syncStatus.getNeedHandled()-syncStatus.getHandle(), syncStatus.getOverSize())} </span>
</p>`} </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) {
@ -120,8 +150,14 @@ ${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + T
cacheImage: ( settings.cacheImage == null) ? DEFAULT_SETTINGS.cacheImage : settings.cacheImage, cacheImage: ( settings.cacheImage == null) ? DEFAULT_SETTINGS.cacheImage : settings.cacheImage,
cacheHighQuantityImage: ( settings.cacheHighQuantityImage == null) ? DEFAULT_SETTINGS.cacheHighQuantityImage : settings.cacheHighQuantityImage, cacheHighQuantityImage: ( settings.cacheHighQuantityImage == null) ? DEFAULT_SETTINGS.cacheHighQuantityImage : settings.cacheHighQuantityImage,
attachmentPath: (settings.attachmentPath == '' || settings.attachmentPath == null) ? DEFAULT_SETTINGS.attachmentPath : settings.attachmentPath, 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, templateFile: (settings.movieTemplateFile == '' || settings.movieTemplateFile == null) ? DEFAULT_SETTINGS.movieTemplateFile : settings.movieTemplateFile,
incrementalUpdate: true, incrementalUpdate: true,
syncConditionType: SyncConditionType.ALL,
syncConditionDateFromValue: TimeUtil.getLastMonth(),
syncConditionDateToValue: new Date(),
syncConditionCountFromValue: 1,
syncConditionCountToValue: 30
}; };
this.showConfigPan(contentEl.createDiv('config'), syncConfig, false); this.showConfigPan(contentEl.createDiv('config'), syncConfig, false);
const controls = contentEl.createDiv("controls"); const controls = contentEl.createDiv("controls");
@ -160,10 +196,10 @@ ${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + T
private showConfigPan(contentEl: HTMLElement, config:SyncConfig, disable:boolean) { private showConfigPan(contentEl: HTMLElement, config:SyncConfig, disable:boolean) {
new Setting(contentEl); new Setting(contentEl);
this.showTypeDropdown(contentEl, config, disable); this.showTypeDropdown(contentEl, config, disable);
this.showCondition(contentEl, config, disable);
this.showOutputFolderSelections(contentEl, config, disable); // this.showOutputFolderSelections(contentEl, config, disable);
this.showOutiFleName(contentEl, config, disable); // this.showOutiFleName(contentEl, config, disable);
this.showAttachmentsFileConfig(contentEl, config, disable); // this.showAttachmentsFileConfig(contentEl, config, disable);
this.showUpdateAllConfig(contentEl, config, disable); this.showUpdateAllConfig(contentEl, config, disable);
this.showForceUpdateConfig(contentEl, config, disable); this.showForceUpdateConfig(contentEl, config, disable);
} }
@ -196,14 +232,17 @@ ${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + T
case SyncType.teleplay: case SyncType.teleplay:
this.showScopeDropdown(contentEl, DoubanSubjectStateRecords_TELEPLAY_SYNC, config, disable); this.showScopeDropdown(contentEl, DoubanSubjectStateRecords_TELEPLAY_SYNC, config, disable);
break; break;
case SyncType.game:
config.scope = DoubanSubjectState.collect;
this.showScopeDropdown(contentEl, DoubanSubjectStateRecords_GAME_SYNC, config, disable);
break;
} }
} }
private showTypeDropdown(containerEl:HTMLElement, config: SyncConfig, disable:boolean) { private showTypeDropdown(containerEl:HTMLElement, config: SyncConfig, disable:boolean) {
const settings = new Setting(containerEl); const settings = new Setting(containerEl);
const scopeSelections = containerEl.createDiv("scope-selection"); const scopeSelections = containerEl.createDiv("scope-selection");
const templateFile:HTMLDivElement = containerEl.createDiv('template-file-path-selection'); // const templateFile:HTMLDivElement = containerEl.createDiv('template-file-path-selection');
settings settings
.setName(i18nHelper.getMessage('110030')) .setName(i18nHelper.getMessage('110030'))
.addDropdown((dropdown) => { .addDropdown((dropdown) => {
@ -213,11 +252,11 @@ ${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + T
config.syncType = value; config.syncType = value;
config.templateFile = this.getDefaultTemplatePath(value); config.templateFile = this.getDefaultTemplatePath(value);
this.openScopeDropdown(scopeSelections, config, disable); this.openScopeDropdown(scopeSelections, config, disable);
this.showTemplateFileSelectionSetting(templateFile, config, disable); // this.showTemplateFileSelectionSetting(templateFile, config, disable);
}); });
}).setDisabled(disable); }).setDisabled(disable);
this.openScopeDropdown(scopeSelections, config, disable); this.openScopeDropdown(scopeSelections, config, disable);
this.showTemplateFileSelectionSetting(templateFile, config, disable); // this.showTemplateFileSelectionSetting(templateFile, config, disable);
} }
private getDefaultTemplatePath(value: string) { private getDefaultTemplatePath(value: string) {
@ -236,6 +275,9 @@ ${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + T
case SyncType.teleplay: case SyncType.teleplay:
result = (settings.teleplayTemplateFile == '' || settings.teleplayTemplateFile == null) ? DEFAULT_SETTINGS.teleplayTemplateFile : settings.teleplayTemplateFile result = (settings.teleplayTemplateFile == '' || settings.teleplayTemplateFile == null) ? DEFAULT_SETTINGS.teleplayTemplateFile : settings.teleplayTemplateFile
break; break;
case SyncType.game:
result = (settings.gameTemplateFile == '' || settings.gameTemplateFile == null) ? DEFAULT_SETTINGS.gameTemplateFile : settings.gameTemplateFile
break;
} }
return result; return result;
} }
@ -383,6 +425,20 @@ ${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + T
}); });
}) })
.setDisabled(disable); .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) new Setting(containerEl)
.setName(i18nHelper.getMessage('121435')) .setName(i18nHelper.getMessage('121435'))
@ -412,4 +468,128 @@ ${syncStatus.getHandle() == 0? '...' : i18nHelper.getMessage('110042') + ':' + T
.setDisabled(disable); .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,
PersonNameMode, PropertyName, DataValueType,
PersonNameMode,
PropertyName,
SearchHandleMode, SearchHandleMode,
SupportType, SupportType,
TemplateKey, TemplateKey,
@ -19,18 +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 { import {
DoubanSubjectState, DoubanSubjectState,
DoubanSubjectStateRecords, DoubanSubjectStateRecords,
DoubanSubjectStateRecords_KEY_WORD_TYPE DoubanSubjectStateRecords_KEY_WORD_TYPE
} from "../../../constant/DoubanUserState"; } from "../../../constant/DoubanUserState";
import DoubanLoginModel from "../../component/DoubanLoginModel";
import DoubanHumanCheckModel from "../../component/DoubanHumanCheckModel";
import DoubanMovieSubject from "../model/DoubanMovieSubject";
import {Person} from "schema-dts"; import {Person} from "schema-dts";
import HttpUtil from "../../../utils/HttpUtil"; import HttpUtil from "../../../utils/HttpUtil";
import HtmlUtil from "../../../utils/HtmlUtil"; 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> {
@ -43,36 +47,44 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
async parse(extract: T, context: HandleContext): Promise<HandleResult> { async parse(extract: T, context: HandleContext): Promise<HandleResult> {
const 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);
this.parseUserInfo(template, variableMap, extract, context);
this.parseVariable(template, variableMap, extract, context);
await this.saveImage(extract, context, variableMap);
const frontMatterStart: number = template.indexOf(BasicConst.YAML_FRONT_MATTER_SYMBOL, 0); const frontMatterStart: number = template.indexOf(BasicConst.YAML_FRONT_MATTER_SYMBOL, 0);
const frontMatterEnd: number = template.indexOf(BasicConst.YAML_FRONT_MATTER_SYMBOL, frontMatterStart + 1); const frontMatterEnd: number = template.indexOf(BasicConst.YAML_FRONT_MATTER_SYMBOL, frontMatterStart + 1);
let frontMatter: string = ''; let frontMatter = '';
let frontMatterBefore: string = ''; let frontMatterBefore = '';
let frontMatterAfter: string = ''; let frontMatterAfter = '';
let result: string = ''; 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 {
@ -84,63 +96,22 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
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 = this.handleArray(array, context);
}
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;
@ -148,7 +119,7 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
const url:string = this.getSubjectUrl(id); const url:string = this.getSubjectUrl(id);
context.plugin.settingsManager.debug(`开始请求地址:${url}`) context.plugin.settingsManager.debug(`开始请求地址:${url}`)
context.plugin.settingsManager.debug(`(注意:请勿向任何人透露你的Cookie,此处若需要截图请**打码**)请求header:${context.settings.loginHeadersContent}`) context.plugin.settingsManager.debug(`(注意:请勿向任何人透露你的Cookie,此处若需要截图请**打码**)请求header:${context.settings.loginHeadersContent}`)
return await HttpUtil.httpRequestGet(url, context.plugin.settingsManager.getHeaders(), context.plugin.settingsManager) return await DoubanHttpUtil.httpRequestGet(url, context.plugin.settingsManager.getHeaders(), context.plugin.settingsManager)
.then(load) .then(load)
.then(data => this.analysisUserState(data, context)) .then(data => this.analysisUserState(data, context))
.then(({data, userState}) => { .then(({data, userState}) => {
@ -171,7 +142,7 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
}else { }else {
context.syncStatusHolder?context.syncStatusHolder.syncStatus.handled(1):null; context.syncStatusHolder?context.syncStatusHolder.syncStatus.handled(1):null;
} }
return e; return undefined;
}); });
@ -184,9 +155,9 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
*/ */
private getGuessType(data: CheerioAPI):SupportType { private getGuessType(data: CheerioAPI):SupportType {
if (data) { if (data) {
let text = data.html(); const text = data.html();
if (text) { if (text) {
for (let [key, value] of DoubanSubjectStateRecords_KEY_WORD_TYPE) { for (const [key, value] of DoubanSubjectStateRecords_KEY_WORD_TYPE) {
if (text.indexOf(key) >= 0) { if (text.indexOf(key) >= 0) {
return value; return value;
} }
@ -243,7 +214,7 @@ 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,}/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:
@ -253,7 +224,7 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
default: default:
resultName = name; resultName = name;
} }
return resultName; return resultName.trim();
} }
getTitleNameByMode(name: string, personNameMode: string, context: HandleContext): string { getTitleNameByMode(name: string, personNameMode: string, context: HandleContext): string {
@ -294,35 +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(extract.title, textMode))
.replaceAll(DoubanParameter.TYPE, extract.type)
.replaceAll(DoubanParameter.SCORE, this.handleSpecialContent(extract.score))
.replaceAll(DoubanParameter.IMAGE, extract.image)
.replaceAll(DoubanParameter.IMAGE_URL, extract.imageUrl)
.replaceAll(DoubanParameter.URL, extract.url)
.replaceAll(DoubanParameter.DESC, this.handleSpecialContent(extract.desc, textMode))
.replaceAll(DoubanParameter.PUBLISHER, extract.publisher)
.replaceAll(DoubanParameter.YEAR_PUBLISHED, extract.datePublished ? moment(extract.datePublished).format('yyyy') : '')
.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 ||
@ -341,53 +359,77 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
}else { }else {
tags = [extract.type]; tags = [extract.type];
} }
return resultContent.replaceAll(DoubanUserParameter.MY_TAGS, this.handleSpecialContent(tags, textMode, context)) Object.entries(userState).forEach(([key, value]) => {
.replaceAll(DoubanUserParameter.MY_RATING, this.handleSpecialContent(userState.rate, textMode)) if (!value) {
.replaceAll(DoubanUserParameter.MY_STATE, this.getUserStateName(userState.state)) return;
.replaceAll(DoubanUserParameter.MY_COMMENT, this.handleSpecialContent(userState.comment, textMode)) }
.replaceAll(DoubanUserParameter.MY_COLLECTION_DATE, userState.collectionDate?moment(userState.collectionDate).format(context.settings.dateFormat): '') 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.toLowerCase() == SupportType.ALL ||
customProperty.field.toLowerCase() == 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:
@ -421,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 {
@ -465,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;
@ -480,27 +522,44 @@ 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>) {
const {syncConfig} = context; const {syncConfig} = context;
if (!extract.image || (syncConfig && !syncConfig.cacheImage) || !context.settings.cacheImage) { if (!extract.image || (syncConfig && !syncConfig.cacheImage) || !context.settings.cacheImage) {
return; return;
} }
const image = extract.image; const image = extract.image;
const filename = image.split('/').pop();
let folder = syncConfig? syncConfig.attachmentPath : context.settings.attachmentPath; let folder = syncConfig? syncConfig.attachmentPath : context.settings.attachmentPath;
if (!folder) { if (!folder) {
folder = DEFAULT_SETTINGS.attachmentPath; folder = DEFAULT_SETTINGS.attachmentPath;
} }
const referHeaders = {'referer': image}; folder = this.parsePartPath(folder, extract, context, variableMap)
let fileName = syncConfig? syncConfig.attachmentFileName : context.settings.attachmentFileName;
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()) { if ((syncConfig ? syncConfig.cacheHighQuantityImage : context.settings.cacheHighQuantityImage) && context.userComponent.isLogin()) {
try { try {
const fileNameSpilt = filename.split('.'); const highImageFilename = this.getImageFilename(image);
const highFilename = fileNameSpilt.first() + '.jpg'; const highImage = this.getHighQuantityImageUrl(highImageFilename);
const highImageHeaders = HttpUtil.buildImageRequestHeaders(
const highImage = this.getHighQuantityImageUrl(highFilename); context.plugin.settingsManager.getHeaders() as Record<string, any>,
const resultValue = await context.netFileHandler.downloadFile(highImage, folder, highFilename, context, false, referHeaders); imageReferer
);
const resultValue = await this.handleImage(highImage, folder, fileName, context, false, highImageHeaders);
if (resultValue && resultValue.success) { if (resultValue && resultValue.success) {
extract.image = resultValue.filepath; extract.image = resultValue.filepath;
this.initImageVariableMap(extract, context, variableMap);
return; return;
} }
}catch (e) { }catch (e) {
@ -508,24 +567,74 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
console.error('下载高清封面失败,将会使用普通封面') console.error('下载高清封面失败,将会使用普通封面')
} }
} }
const resultValue = await context.netFileHandler.downloadFile(image, folder, filename, context, true, referHeaders); const resultValue = await this.handleImage(image, folder, fileName, context, true, referHeaders);
if (resultValue && resultValue.success) { if (resultValue && resultValue.success) {
extract.image = resultValue.filepath; extract.image = resultValue.filepath;
this.initImageVariableMap(extract, context, variableMap);
} }
} }
private getImageFilename(image: string): string {
if (!image) {
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 {
return await context.netFileHandler.downloadDBFile(image, folder, filename, context, false, headers);
}
}
abstract getHighQuantityImageUrl(fileName:string):string; abstract getHighQuantityImageUrl(fileName:string):string;
abstract getSubjectUrl(id:string):string; abstract getSubjectUrl(id:string):string;
handlePersonNameByMeta(html: CheerioAPI, movie: DoubanSubject, context: HandleContext, handlePersonNameByMeta(html: CheerioAPI, movie: DoubanSubject, context: HandleContext,
metaProperty:string, objectProperty:string) { metaProperty:string, objectProperty:string) {
let metaProperties: string[] = html(`head > meta[property='${metaProperty}']`).get() if (!movie) {
return;
}
const metaProperties: string[] = html(`head > meta[property='${metaProperty}']`).get()
.map((e) => { .map((e) => {
return html(e).attr('content'); return html(e).attr('content');
}); });
// @ts-ignore // @ts-ignore
movie[objectProperty] const currentArray = movie[objectProperty];
if (!Array.isArray(currentArray)) {
return;
}
// @ts-ignore
currentArray
// @ts-ignore // @ts-ignore
.filter((p:Person) => p.name) .filter((p:Person) => p.name)
// @ts-ignore // @ts-ignore
@ -544,10 +653,7 @@ export default abstract class DoubanAbstractLoadHandler<T extends DoubanSubject>
return HtmlUtil.getHtmlText(html, this.doubanPlugin.settingsManager.getSelector(this.getSupportType(), name)); return HtmlUtil.getHtmlText(html, this.doubanPlugin.settingsManager.getSelector(this.getSupportType(), name));
} }
protected handleArray(arr: string[], context: HandleContext): string {
const {settings} = context;
return StringUtil.handleArray(arr, settings);
}
} }

@ -3,11 +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 {PropertyName, 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 {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian"; import {moment} from "obsidian";
import {DataField} from "../../../utils/model/DataField";
export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<DoubanBookSubject> { export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<DoubanBookSubject> {
@ -16,7 +17,7 @@ export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<Dou
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.BOOK; return SupportType.book;
} }
getHighQuantityImageUrl(fileName:string):string{ getHighQuantityImageUrl(fileName:string):string{
@ -27,22 +28,11 @@ export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<Dou
return `https://book.douban.com/subject/${id}/`; return `https://book.douban.com/subject/${id}/`;
} }
parseText(beforeContent: string, extract: DoubanBookSubject, context: HandleContext, textMode: TemplateTextMode): string { parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanBookSubject, context: HandleContext): void {
return beforeContent variableMap.set(DoubanBookParameter.author, new DataField(DoubanBookParameter.author,
.replaceAll(DoubanBookParameter.author, DataValueType.array, extract.author, (extract.author || []).map(this.handleSpecialAuthorName)));
super.handleSpecialContent( variableMap.set(DoubanBookParameter.translator, new DataField(DoubanBookParameter.translator,
extract.author.map(this.handleSpecialAuthorName), textMode, context)) DataValueType.array, extract.translator, (extract.translator || []).map(this.handleSpecialAuthorName)));
.replaceAll(DoubanBookParameter.translator, super.handleSpecialContent(extract.translator, textMode, context))
.replaceAll(DoubanBookParameter.isbn, extract.isbn)
.replaceAll(DoubanBookParameter.originalTitle, super.handleSpecialContent(extract.originalTitle, textMode))
.replaceAll(DoubanBookParameter.subTitle, super.handleSpecialContent(extract.subTitle, textMode))
.replaceAll(DoubanBookParameter.totalPage, super.handleSpecialContent(extract.totalPage, textMode))
.replaceAll(DoubanBookParameter.menu, extract.menu.join('\n'))
.replaceAll(DoubanBookParameter.price, super.handleSpecialContent(extract.price, textMode))
.replaceAll(DoubanBookParameter.series, super.handleSpecialContent(extract.series, textMode))
.replaceAll(DoubanBookParameter.binding, super.handleSpecialContent(extract.binding, textMode))
.replaceAll(DoubanBookParameter.producer, super.handleSpecialContent(extract.producer, textMode))
;
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
@ -83,7 +73,7 @@ export default class DoubanBookLoadHandler extends DoubanAbstractLoadHandler<Dou
const image = html(html("head > meta[property= 'og:image']").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);
const obj = JSON.parse(item.replace(/[\r\n\s+]/g, '')); const obj = JSON.parse(item.replace(/[\r\n\t\s+]/g, ''));
const title = obj.name; const title = obj.name;
const url = obj.url; const url = obj.url;
const author = obj.author.map((a: any) => a.name); const author = obj.author.map((a: any) => a.name);

@ -3,11 +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 {PersonNameMode, SupportType, TemplateKey} from "../../../constant/Constsant"; import {DataValueType, PersonNameMode, SupportType} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject"; import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian"; 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> {
@ -16,7 +18,7 @@ export default class DoubanGameLoadHandler extends DoubanAbstractLoadHandler<Dou
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.GAME; return SupportType.game;
} }
getHighQuantityImageUrl(fileName:string):string{ getHighQuantityImageUrl(fileName:string):string{
return `https://img9.doubanio.com/lpic/${fileName}`; return `https://img9.doubanio.com/lpic/${fileName}`;
@ -26,12 +28,19 @@ export default class DoubanGameLoadHandler extends DoubanAbstractLoadHandler<Dou
return `https://www.douban.com/game/${id}/`; return `https://www.douban.com/game/${id}/`;
} }
parseText(beforeContent: string, extract: DoubanGameSubject, context: HandleContext): string { parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanGameSubject, context: HandleContext): void {
const {settings} = context; // super.parseAliases(beforeContent, variableMap, extract, context);
return beforeContent variableMap.set("aliases", new DataField("aliases", DataValueType.array, extract.aliases,
.replaceAll("{{platform}}", this.handleArray(extract.platform, context)) (extract.aliases || []).map(a=>a
.replaceAll("{{aliases}}", this.handleArray(extract.aliases, context)) .trim()
.replaceAll("{{developer}}", extract.developer ? extract.developer : ""); // .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 {
@ -67,7 +76,7 @@ export default class DoubanGameLoadHandler extends DoubanAbstractLoadHandler<Dou
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();

@ -6,10 +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, PropertyName, SupportType, TemplateKey} from "../../../constant/Constsant"; import {DataValueType, PersonNameMode, PropertyName, SupportType, TemplateKey} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject"; import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian"; import {moment} from "obsidian";
import YamlUtil, {SPECIAL_CHAR_REG, TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil"; 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> {
@ -18,7 +19,7 @@ export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<Do
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.MOVIE; return SupportType.movie;
} }
getHighQuantityImageUrl(fileName:string):string{ getHighQuantityImageUrl(fileName:string):string{
@ -29,20 +30,39 @@ export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<Do
return `https://movie.douban.com/subject/${id}/`; return `https://movie.douban.com/subject/${id}/`;
} }
parseText(beforeContent: string, extract: DoubanMovieSubject, context: HandleContext): string { parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanMovieSubject, context: HandleContext): void {
const {settings} = context; variableMap.set("director", new DataField(
return beforeContent "director",
.replaceAll("{{originalTitle}}", extract.originalTitle ?? "") DataValueType.array,
.replaceAll("{{director}}", this.handleArray(extract.director.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c), context)) extract.director,
.replaceAll("{{actor}}", this.handleArray( extract.actor.map(SchemaOrg.getPersonName).filter(c => c), context)) (extract.director || []).map(SchemaOrg.getPersonName).filter(c => c)
.replaceAll("{{author}}", this.handleArray(extract.author.map(SchemaOrg.getPersonName).filter(c => c), context)) ));
.replaceAll("{{aliases}}", this.handleArray(extract.aliases.map(a=>a.replace(TITLE_ALIASES_SPECIAL_CHAR_REG_G, '_')), context))
.replaceAll("{{country}}", this.handleArray( extract.country, context)) variableMap.set("actor", new DataField(
.replaceAll("{{language}}",this.handleArray( extract.language, context)) "actor",
.replaceAll("{{IMDb}}", extract.IMDb ??"") DataValueType.array,
.replaceAll("{{time}}", extract.time ??"") 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"));
@ -78,18 +98,18 @@ export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<Do
} }
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanMovieSubject { parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanMovieSubject {
const movie:DoubanMovieSubject = html('script') let movie: DoubanMovieSubject | undefined = html('script')
.get() .get()
.filter(scd => "application/ld+json" == html(scd).attr("type")) .filter(scd => "application/ld+json" == html(scd).attr("type"))
.map(i => { .map(i => {
let item = html(i).text(); let item = html(i).text();
item = super.html_decode(item); item = super.html_decode(item);
const obj = JSON.parse(item.replace(/[\r\n+]/g, '')); const obj = JSON.parse(item.replace(/[\r\n\t]+/g, ''));
const idPattern = /(\d){5,10}/g; const idPattern = /(\d){5,10}/g;
const id = idPattern.exec(obj.url); const id = idPattern.exec(obj.url);
const name = obj.name; const name = obj.name;
const title = super.getTitleNameByMode(name, PersonNameMode.CH_NAME, context)??name; const title = super.getTitleNameByMode(name, PersonNameMode.CH_NAME, context) ?? name;
const originalTitle = super.getTitleNameByMode(name, PersonNameMode.EN_NAME, context) ?? 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] : '',
@ -99,14 +119,14 @@ export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<Do
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,
imageUrl: obj.image, imageUrl: obj.image,
genre: obj.genre, genre: obj.genre || [],
publisher: '', publisher: '',
aliases: [""], aliases: [""],
language: [""], language: [""],
@ -116,10 +136,52 @@ export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<Do
} }
return result; return result;
})[0]; })[0];
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(); // 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) { if (desc) {
movie.desc = desc; movie.desc = desc;
} }
@ -136,7 +198,7 @@ export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<Do
// value = html(info.next.next).text().trim(); // value = html(info.next.next).text().trim();
const vas = html(info.next).text().trim(); const vas = html(info.next).text().trim();
value = vas.split("/").map((v) => v.trim()); value = vas.split("/").map((v) => v.trim());
} else if(key.indexOf('片长') >= 0) { } else if (key.indexOf('片长') >= 0) {
value = html(info.next.next).text().trim() value = html(info.next.next).text().trim()
} else { } else {
value = html(info.next).text().trim(); value = html(info.next).text().trim();
@ -144,11 +206,11 @@ export default class DoubanMovieLoadHandler extends DoubanAbstractLoadHandler<Do
valueMap.set(MovieKeyValueMap.get(key), value); valueMap.set(MovieKeyValueMap.get(key), value);
}) })
movie.country = valueMap.has('country') ? valueMap.get('country') : []; movie.country = valueMap.has('country') ? valueMap.get('country') : [];
movie.language = valueMap.has('language') ? valueMap.get('language') : []; movie.language = valueMap.has('language') ? valueMap.get('language') : [];
movie.time = valueMap.has('time') ? valueMap.get('time') : ""; movie.time = valueMap.has('time') ? valueMap.get('time') : "";
movie.aliases = valueMap.has('aliases') ? valueMap.get('aliases') : []; movie.aliases = valueMap.has('aliases') ? valueMap.get('aliases') : [];
movie.IMDb = valueMap.has('IMDb') ? valueMap.get('IMDb') : ""; movie.IMDb = valueMap.has('IMDb') ? valueMap.get('IMDb') : "";
return movie; return movie;
} }

@ -4,9 +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 {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian"; import {moment} from "obsidian";
import {DataField} from "../../../utils/model/DataField";
export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<DoubanMusicSubject> { export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<DoubanMusicSubject> {
@ -15,7 +16,7 @@ export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<Do
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.MUSIC; return SupportType.music;
} }
getHighQuantityImageUrl(fileName:string):string{ getHighQuantityImageUrl(fileName:string):string{
@ -26,15 +27,7 @@ export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<Do
return `https://music.douban.com/subject/${id}/`; return `https://music.douban.com/subject/${id}/`;
} }
parseText(beforeContent: string, extract: DoubanMusicSubject, context: HandleContext): string { parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanMusicSubject, context: HandleContext): void {
const {settings} = context;
return beforeContent
.replaceAll("{{actor}}", this.handleArray(extract.actor, context ))
.replaceAll("{{barcode}}", extract.barcode ? extract.barcode : "")
.replaceAll("{{medium}}", extract.medium ? extract.medium : "")
.replaceAll("{{albumType}}", extract.albumType ? extract.albumType : "")
.replaceAll("{{records}}", extract.records ? extract.records + "" : "")
;
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
@ -83,7 +76,7 @@ export default class DoubanMusicLoadHandler extends DoubanAbstractLoadHandler<Do
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 {
@ -92,8 +85,11 @@ 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,
@ -111,11 +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;
} }

@ -7,6 +7,7 @@ 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 {UserStateSubject} from "../model/UserStateSubject";
import {DataField} from "../../../utils/model/DataField";
export default class DoubanNoteLoadHandler extends DoubanAbstractLoadHandler<DoubanNoteSubject> { export default class DoubanNoteLoadHandler extends DoubanAbstractLoadHandler<DoubanNoteSubject> {
@ -15,7 +16,7 @@ export default class DoubanNoteLoadHandler extends DoubanAbstractLoadHandler<Dou
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.NOTE; return SupportType.note;
} }
getHighQuantityImageUrl(fileName:string):string{ getHighQuantityImageUrl(fileName:string):string{
@ -26,12 +27,7 @@ export default class DoubanNoteLoadHandler extends DoubanAbstractLoadHandler<Dou
return `https://www.douban.com/note/${id}/`; return `https://www.douban.com/note/${id}/`;
} }
parseText(beforeContent: string, extract: DoubanNoteSubject, context: HandleContext): string { parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanNoteSubject, context: HandleContext): void {
return beforeContent
.replaceAll("{{authorUrl}}", extract.authorUrl ? extract.authorUrl : "")
.replaceAll("{{content}}", extract.content ? extract.content : "")
.replaceAll("{{author}}", extract.author ? extract.author : "")
;
} }
support(extract: DoubanSubject): boolean { support(extract: DoubanSubject): boolean {
@ -43,16 +39,16 @@ export default class DoubanNoteLoadHandler extends DoubanAbstractLoadHandler<Dou
} }
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanNoteSubject { parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanNoteSubject {
let title = html(html("head > meta[property= 'og:title']").get(0)).attr("content"); const title = html(html("head > meta[property= 'og:title']").get(0)).attr("content");
let desc = html(html("head > meta[property= 'og:description']").get(0)).attr("content"); const 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"); const 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"); const image = html(html("head > meta[property= 'og:image']").get(0)).attr("content");
let type = html(html("head > meta[property= 'og:type']").get(0)).attr("content"); const type = html(html("head > meta[property= 'og:type']").get(0)).attr("content");
let authorA = html(html("a.note-author").get(0)); const authorA = html(html("a.note-author").get(0));
let timePublished = html(html(".pub-date").get(0)).text(); const timePublished = html(html(".pub-date").get(0)).text();
let content = html(html(".note").get(1)); const content = html(html(".note").get(1));
let idPattern = /(\d){5,10}/g; const idPattern = /(\d){5,10}/g;
let id = idPattern.exec(url); const id = idPattern.exec(url);
const result: DoubanNoteSubject = { const result: DoubanNoteSubject = {
image: image, image: image,

@ -6,18 +6,18 @@ 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 {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 {

@ -5,11 +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 {PersonNameMode, SupportType, TemplateKey} from "../../../constant/Constsant"; import {DataValueType, PersonNameMode, SupportType} from "../../../constant/Constsant";
import {aliases} from "css-select";
import {UserStateSubject} from "../model/UserStateSubject"; import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian"; import {moment} from "obsidian";
import YamlUtil, {SPECIAL_CHAR_REG, TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil"; import {TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil";
import {DataField} from "../../../utils/model/DataField";
/** /**
* teleplay * teleplay
@ -21,23 +21,35 @@ 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 ?? "") "actor",
.replaceAll("{{director}}", this.handleArray( extract.director.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c), context)) DataValueType.array,
.replaceAll("{{actor}}", this.handleArray( extract.actor.map(SchemaOrg.getPersonName).filter(c => c), context)) extract.actor,
.replaceAll("{{author}}", this.handleArray( extract.author.map(SchemaOrg.getPersonName).filter(c => c), context)) (extract.actor || []).map(SchemaOrg.getPersonName).filter(c => c)
.replaceAll("{{aliases}}", this.handleArray( extract.aliases.map(a=>a.replace(TITLE_ALIASES_SPECIAL_CHAR_REG_G, '_')), context)) ));
.replaceAll("{{country}}", this.handleArray( extract.country, context))
.replaceAll("{{language}}", this.handleArray(extract.language, context)) variableMap.set("author", new DataField(
.replaceAll("{{IMDb}}", extract.IMDb?? "") "author",
.replaceAll("{{time}}", extract.time ?? "") DataValueType.array,
.replaceAll("{{episode}}", extract.episode ?? "") 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 {
@ -52,14 +64,14 @@ export class DoubanTeleplayLoadHandler extends DoubanAbstractLoadHandler<DoubanT
} }
analysisUser(html: CheerioAPI, context: HandleContext): {data:CheerioAPI , userState: UserStateSubject} { analysisUser(html: CheerioAPI, context: HandleContext): {data:CheerioAPI , userState: UserStateSubject} {
let rate = html('input#n_rating').val(); const rate = html('input#n_rating').val();
const rating = html('span#rating'); const rating = html('span#rating');
let tagsStr = rating.next().next().text().trim(); const tagsStr = rating.next().next().text().trim();
let tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null; const tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null;
let stateWord = html('div#interest_sect_level > div.a_stars > span.mr10').text().trim(); const 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(); const collectionDateStr = html('div#interest_sect_level > div.a_stars > span.mr10 > span.collection_date').text().trim();
let userState1 = DoubanAbstractLoadHandler.getUserState(stateWord); const userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
let component = rating.next().next().next().next().text().trim(); const component = rating.next().next().next().next().text().trim();
const userState: UserStateSubject = { const userState: UserStateSubject = {
tags: tags, tags: tags,
@ -72,13 +84,13 @@ export class DoubanTeleplayLoadHandler extends DoubanAbstractLoadHandler<DoubanT
} }
parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanTeleplaySubject { parseSubjectFromHtml(html: CheerioAPI, context: HandleContext): DoubanTeleplaySubject {
const teleplay:DoubanTeleplaySubject = html('script') let teleplay: DoubanTeleplaySubject | undefined = html('script')
.get() .get()
.filter(scd => "application/ld+json" == html(scd).attr("type")) .filter(scd => "application/ld+json" == html(scd).attr("type"))
.map(i => { .map(i => {
let item = html(i).text(); let item = html(i).text();
item = super.html_decode(item); item = super.html_decode(item);
const obj = JSON.parse(item.replace(/[\r\n\s+]/g, '')); const obj = JSON.parse(item.replace(/[\r\n\t]+/g, ''));
const idPattern = /(\d){5,10}/g; const idPattern = /(\d){5,10}/g;
const id = idPattern.exec(obj.url); const id = idPattern.exec(obj.url);
const name = obj.name; const name = obj.name;
@ -92,14 +104,14 @@ export class DoubanTeleplayLoadHandler extends DoubanAbstractLoadHandler<DoubanT
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,
imageUrl: obj.image, imageUrl: obj.image,
genre: obj.genre, genre: obj.genre || [],
score: obj.aggregateRating ? obj.aggregateRating.ratingValue : undefined, score: obj.aggregateRating ? obj.aggregateRating.ratingValue : undefined,
publisher: "", publisher: "",
aliases: [""], aliases: [""],
@ -112,6 +124,46 @@ export class DoubanTeleplayLoadHandler extends DoubanAbstractLoadHandler<DoubanT
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:actor', 'actor');
this.handlePersonNameByMeta(html, teleplay, context, 'video:director', 'director'); this.handlePersonNameByMeta(html, teleplay, context, 'video:director', 'director');
const desc:string = html("span[property='v:summary']").text(); const desc:string = html("span[property='v:summary']").text();

@ -4,11 +4,12 @@ import DoubanPlugin from "../../../main";
import SchemaOrg from "src/org/wanxp/utils/SchemaOrg"; import SchemaOrg from "src/org/wanxp/utils/SchemaOrg";
import DoubanSubject from '../model/DoubanSubject'; import DoubanSubject from '../model/DoubanSubject';
import HandleContext from "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import {PropertyName, SupportType} from "../../../constant/Constsant"; import {DataValueType, PropertyName, SupportType} from "../../../constant/Constsant";
import {UserStateSubject} from "../model/UserStateSubject"; import {UserStateSubject} from "../model/UserStateSubject";
import {moment} from "obsidian"; import {moment} from "obsidian";
import {TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil"; import {TITLE_ALIASES_SPECIAL_CHAR_REG_G} from "../../../utils/YamlUtil";
import DoubanTheaterSubject from "../model/DoubanTheaterSubject"; import DoubanTheaterSubject from "../model/DoubanTheaterSubject";
import {DataField} from "../../../utils/model/DataField";
export default class DoubanTheaterLoadHandler extends DoubanAbstractLoadHandler<DoubanTheaterSubject> { export default class DoubanTheaterLoadHandler extends DoubanAbstractLoadHandler<DoubanTheaterSubject> {
constructor(doubanPlugin: DoubanPlugin) { constructor(doubanPlugin: DoubanPlugin) {
@ -16,7 +17,7 @@ export default class DoubanTheaterLoadHandler extends DoubanAbstractLoadHandler<
} }
getSupportType(): SupportType { getSupportType(): SupportType {
return SupportType.THEATER; return SupportType.theater;
} }
getHighQuantityImageUrl(fileName: string): string { getHighQuantityImageUrl(fileName: string): string {
@ -27,15 +28,42 @@ export default class DoubanTheaterLoadHandler extends DoubanAbstractLoadHandler<
return `https://www.douban.com/location/drama/${id}/`; return `https://www.douban.com/location/drama/${id}/`;
} }
parseText(beforeContent: string, extract: DoubanTheaterSubject, context: HandleContext): string { parseVariable(beforeContent: string, variableMap:Map<string, DataField>, extract: DoubanTheaterSubject, context: HandleContext): void {
return beforeContent variableMap.set("director", new DataField(
.replaceAll("{{originalTitle}}", extract.originalTitle ? extract.originalTitle : "") "director",
.replaceAll("{{director}}", this.handleArray(extract.director.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c), context)) DataValueType.array,
.replaceAll("{{actor}}", this.handleArray(extract.actor.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c), context)) extract.director,
.replaceAll("{{author}}", this.handleArray(extract.author.map(SchemaOrg.getPersonName).map(name => super.getPersonName(name, context)).filter(c => c), context)) (extract.director || []).map(SchemaOrg.getPersonName).filter(c => c)
.replaceAll("{{aliases}}", this.handleArray(extract.aliases.map(a => a.replace(TITLE_ALIASES_SPECIAL_CHAR_REG_G, '_')), context)) ));
.replaceAll("{{language}}", this.handleArray(extract.language, context))
; 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 { support(extract: DoubanSubject): boolean {
@ -43,13 +71,13 @@ export default class DoubanTheaterLoadHandler extends DoubanAbstractLoadHandler<
} }
analysisUser(html: CheerioAPI, context: HandleContext): { data: CheerioAPI, userState: UserStateSubject } { analysisUser(html: CheerioAPI, context: HandleContext): { data: CheerioAPI, userState: UserStateSubject } {
let rate = html('input#n_rating').val(); const rate = html('input#n_rating').val();
let tagsStr = html('div#interest_sect_level > div.a_stars > span.color_gray').text().trim(); const tagsStr = html('div#interest_sect_level > div.a_stars > span.color_gray').text().trim();
let tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null; const tags = tagsStr ? tagsStr.replace('标签:', '').trim().split(' ') : null;
let stateWord = html('#interest_sect_level > h2').text().trim(); const stateWord = html('#interest_sect_level > h2').text().trim();
let collectionDateStr = html('div#interest_sect_level > div.a_stars > span.mr10 > span.collection_date').text().trim(); const collectionDateStr = html('div#interest_sect_level > div.a_stars > span.mr10 > span.collection_date').text().trim();
let userState1 = DoubanAbstractLoadHandler.getUserState(stateWord); const userState1 = DoubanAbstractLoadHandler.getUserState(stateWord);
let component = this.getPropertyValue(html, PropertyName.comment); const component = this.getPropertyValue(html, PropertyName.comment);
const userState: UserStateSubject = { const userState: UserStateSubject = {
tags: tags, tags: tags,
rate: rate ? Number(rate) : null, rate: rate ? Number(rate) : null,

@ -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',
} }

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

@ -39,3 +39,23 @@ export const DoubanParameter = {
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',
}

@ -26,5 +26,6 @@ export default interface HandleContext {
syncActive?:boolean; syncActive?:boolean;
searchPage?:SearchPageInfo; 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,
} }

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

@ -56,6 +56,10 @@ export class SearchPageInfo {
return this._total; return this._total;
} }
public set total(total: number) {
this._total = total;
}
get pageSize(): number { get pageSize(): number {
return this._pageSize; return this._pageSize;
} }
@ -73,7 +77,7 @@ export class SearchPageInfo {
return this; return this;
} }
return new SearchPageInfo(this.total, this._pageNum - 1, return new SearchPageInfo(this.total, this._pageNum - 1,
this._pageSize, SupportType.ALL); 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, []);
}
}

@ -2,4 +2,5 @@ export interface SubjectListItem {
id:string; id:string;
url:string; url:string;
title: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',
}

@ -1,9 +1,13 @@
import { import {
DoubanSearchGroupPublishResultSubjectNextPage, DoubanSearchGroupPublishResultSubjectPreviousPage, DoubanSearchGroupPublishResultSubjectNextPage,
DoubanSearchGroupPublishResultSubjectPreviousPage,
DoubanSearchResultSubject_EMPTY, DoubanSearchResultSubject_TIP_EMPTY,
DoubanSearchResultSubjectNextPage, DoubanSearchResultSubjectNextPage,
DoubanSearchResultSubjectNextPageNeedLogin, DoubanSearchResultSubjectNextPageNeedLogin,
DoubanSearchResultSubjectPreviousPage, DoubanSearchResultSubjectPreviousPage,
NavigateType, SEARCH_ITEM_PAGE_SIZE, SupportType NavigateType,
SEARCH_ITEM_PAGE_SIZE,
SupportType
} from "../../../constant/Constsant"; } from "../../../constant/Constsant";
import {FuzzySuggestModal, RequestUrlParam, request} from "obsidian"; import {FuzzySuggestModal, RequestUrlParam, request} from "obsidian";
@ -27,7 +31,7 @@ class DoubanFuzzySuggester extends FuzzySuggestModal<DoubanSearchResultSubject>
private searchItem:string; private searchItem:string;
constructor(plugin: DoubanPlugin, context: HandleContext, searchItem:string) { constructor(plugin: DoubanPlugin, context: HandleContext, searchItem:string) {
super(app); super(plugin.app);
this.plugin = plugin; this.plugin = plugin;
this.context = context; this.context = context;
this.searchItem = searchItem; this.searchItem = searchItem;
@ -106,9 +110,18 @@ class DoubanFuzzySuggester extends FuzzySuggestModal<DoubanSearchResultSubject>
private initItems(searchPage: SearchPage) { private initItems(searchPage: SearchPage) {
const doubanList: DoubanSearchResultSubject[] = searchPage.list; const doubanList: DoubanSearchResultSubject[] = searchPage.list;
if (searchPage.type == SupportType.all && searchPage.pageNum == 1) {
if (doubanList.length == 0) {
// if (searchPage.list.length > 0) {
doubanList.push(DoubanSearchResultSubject_EMPTY);
}else if (searchPage.list.length < SEARCH_ITEM_PAGE_SIZE) {
doubanList.push(DoubanSearchResultSubject_TIP_EMPTY);
}
}
if (searchPage.hasNext) { if (searchPage.hasNext) {
if (this.plugin.userComponent.isLogin()) { if (this.plugin.userComponent.isLogin()) {
if (searchPage.type == SupportType.ALL && searchPage.pageNum == 1) { if (searchPage.type == SupportType.all && searchPage.pageNum == 1) {
doubanList.push(DoubanSearchGroupPublishResultSubjectNextPage) doubanList.push(DoubanSearchGroupPublishResultSubjectNextPage)
}else { }else {
doubanList.push(DoubanSearchResultSubjectNextPage) doubanList.push(DoubanSearchResultSubjectNextPage)
@ -118,7 +131,7 @@ class DoubanFuzzySuggester extends FuzzySuggestModal<DoubanSearchResultSubject>
} }
} }
if (searchPage.hasPrevious) { if (searchPage.hasPrevious) {
if (searchPage.type == SupportType.ALL && searchPage.pageNum == 2) { if (searchPage.type == SupportType.all && searchPage.pageNum == 2) {
doubanList.unshift(DoubanSearchGroupPublishResultSubjectPreviousPage) doubanList.unshift(DoubanSearchGroupPublishResultSubjectPreviousPage)
}else { }else {
doubanList.unshift(DoubanSearchResultSubjectPreviousPage); doubanList.unshift(DoubanSearchResultSubjectPreviousPage);

@ -1,22 +1,26 @@
import {App, DropdownComponent, Modal, TextComponent} from "obsidian"; import {App, ButtonComponent, DropdownComponent, Modal, Setting, TextComponent} 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 "../model/HandleContext"; import HandleContext from "../model/HandleContext";
import {SearchTypeRecords, SupportType} from "../../../constant/Constsant"; import {SearchTypeRecords, SupportType} from "../../../constant/Constsant";
import {sleep} from "../../../utils/TimeUtil";
export class DoubanSearchModal extends Modal { export class DoubanSearchModal extends Modal {
searchTerm: string; searchTerm: string;
searchType: SupportType = SupportType.ALL; searchType: SupportType = SupportType.all;
plugin: DoubanPlugin; plugin: DoubanPlugin;
context: HandleContext context: HandleContext
constructor(app: App, plugin: DoubanPlugin, context: HandleContext) { constructor(app: App, plugin: DoubanPlugin, context: HandleContext, type: SupportType) {
super(app); super(app);
this.plugin = plugin; this.plugin = plugin;
this.context = context; this.context = context;
this.searchType = type??SupportType.all;
} }
onOpen() { onOpen() {
let {contentEl} = this; let {contentEl} = this;
@ -32,6 +36,7 @@ export class DoubanSearchModal extends Modal {
searchInput.inputEl.addEventListener("keydown", (event) => { searchInput.inputEl.addEventListener("keydown", (event) => {
if (event.key === "Enter") { if (event.key === "Enter") {
sleep(1000);
this.close(); this.close();
} }
}); });
@ -40,7 +45,7 @@ export class DoubanSearchModal extends Modal {
const typeSelect = content.createDiv("type-select"); const typeSelect = content.createDiv("type-select");
const typeSelectInput = new DropdownComponent(typeSelect) const typeSelectInput = new DropdownComponent(typeSelect)
.addOptions(SearchTypeRecords) .addOptions(SearchTypeRecords)
.setValue(SupportType.ALL) .setValue(this.searchType)
.onChange((value:SupportType) => { .onChange((value:SupportType) => {
this.searchType = value; this.searchType = value;
}); });
@ -49,21 +54,17 @@ export class DoubanSearchModal extends Modal {
const controls = contentEl.createDiv("controls"); const controls = contentEl.createDiv("controls");
controls.addClass("obsidian_douban_search_controls") controls.addClass("obsidian_douban_search_controls")
const searchButton = controls.createEl("button", { new ButtonComponent(controls)
text: i18nHelper.getMessage('110004'), .setButtonText(i18nHelper.getMessage('110004'))
cls: "mod-cta", .setCta()
attr: { .onClick(() => {
autofocus: true, this.close();
}, }).setClass( "obsidian_douban_search_button");
}); new ButtonComponent(controls)
searchButton.addClass("obsidian_douban_search_button"); .setButtonText(i18nHelper.getMessage('110005'))
.onClick(() => {
searchButton.addEventListener("click", this.close.bind(this)); this.close();
const cancelButton = controls.createEl("button", {text: i18nHelper.getMessage('110005')}); }).setClass( "obsidian_douban_cancel_button");
cancelButton.addEventListener("click", this.close.bind(this));
cancelButton.addClass("obsidian_douban_cancel_button");
searchInput.inputEl.focus();
} }
@ -76,3 +77,4 @@ export class DoubanSearchModal extends Modal {
} }
} }

@ -1,39 +0,0 @@
import {RequestUrlParam, request, requestUrl} from "obsidian";
import {DEFAULT_SETTINGS} from "../../../constant/DefaultSettings";
import {DoubanPluginSetting} from "../../setting/model/DoubanPluginSetting";
import DoubanSearchResultSubject from '../model/DoubanSearchResultSubject';
import {SearchPage} from "../model/SearchPage";
import SearchParserHandler from './SearchParser';
import SettingsManager from "../../setting/SettingsManager";
import User from "../../user/User";
import {i18nHelper} from "../../../lang/helper";
import {load} from 'cheerio';
import {log} from 'src/org/wanxp/utils/Logutil';
import HttpUtil from "../../../utils/HttpUtil";
import {SupportType} from "../../../constant/Constsant";
export default class Searcher {
static search(searchItem: string, type:SupportType, doubanSettings: DoubanPluginSetting, settingsManager:SettingsManager): Promise<DoubanSearchResultSubject[]> {
return HttpUtil.httpRequestGet(DEFAULT_SETTINGS.searchUrl + searchItem, settingsManager.getHeaders(), settingsManager)
.then(load)
.then(SearchParserHandler.parseSearch)
.catch(e => {
throw log.error(i18nHelper.getMessage('130101').replace('{0}', e.toString()), e);
});
};
static loadSearchItem(searchItem: string, type:SupportType, start:number, doubanSettings: DoubanPluginSetting, settingsManager:SettingsManager): Promise<SearchPage> {
const url:string = `https://www.douban.com/j/search?q=${searchItem}&start=${start}&subtype=item`;
log.debug(`请求更多页面:${url}`);
return HttpUtil.httpRequestGet(url, settingsManager.getHeaders(), settingsManager)
.then(e=>SearchParserHandler.parseSearchJson(e, type, start))
.catch(e => {
throw log.error(i18nHelper.getMessage('130101').replace('{0}', e.toString()), e);
});
;
};
}

@ -38,7 +38,7 @@ export default class SearchParserHandler {
}) })
} }
static parseSearchJson(result: string, type:SupportType, start:number): SearchPage { static parseSearchJson(result: string, type:SupportType, pageNum:number): SearchPage {
log.debug("解析给多页面结果"); log.debug("解析给多页面结果");
const data:{total:number, limit:number, more:boolean, items:string[]} = JSON.parse(result); const data:{total:number, limit:number, more:boolean, items:string[]} = JSON.parse(result);
const list:string[] = data.items; const list:string[] = data.items;
@ -46,7 +46,7 @@ export default class SearchParserHandler {
.map(e => load(e)) .map(e => load(e))
.map(e=>this.parseSearch(e)) .map(e=>this.parseSearch(e))
.map(e => e? e[0]:null); .map(e => e? e[0]:null);
return new SearchPage(data.total, start / data.limit, data.limit, type, resultList); return new SearchPage(data.total, pageNum, data.limit, type, resultList);
}; };
} }

@ -1,23 +1,21 @@
import {SupportType} from "../../../../constant/Constsant"; import {
SupportType
} from "../../../../constant/Constsant";
import {SearchResultPageParserInterface} from "./SearchResultPageParserInterface"; import {SearchResultPageParserInterface} from "./SearchResultPageParserInterface";
import {SearchPage} from "../../model/SearchPage"; import {SearchPage} from "../../model/SearchPage";
import SearchParserHandlerV2 from "../SearchParserV2"; import SearchParserHandler from "../SearchParser";
import {log} from "../../../../utils/Logutil";
export class AllFirstPageSearchResultPageParser implements SearchResultPageParserInterface { export class AllFirstPageSearchResultPageParser implements SearchResultPageParserInterface {
support(type:SupportType, pageNum:number):boolean { support(type:SupportType, pageNum:number):boolean {
return pageNum == 1 && type == SupportType.ALL; return pageNum == 1 && type == SupportType.all;
} }
parse(source:string, type:SupportType, pageNum:number, pageSize:number):SearchPage { parse(source:string, type:SupportType, pageNum:number, pageSize:number):SearchPage {
const {subjects} = JSON.parse(source); log.debug("解析给多页面结果");
if (!subjects) { if (!source) {
return SearchPage.empty(type); return new SearchPage(0, 0, 0, type, []);
} }
const {items} = subjects; return SearchParserHandler.parseSearchJson(source, type, pageNum);
if (!items ||items.length == 0) {
return SearchPage.empty(type);
}
const doubanSearchResultSubjects = SearchParserHandlerV2.itemMapToSearchResult(items);
return new SearchPage(2000, pageNum, pageSize, type, doubanSearchResultSubjects);
} }

@ -6,7 +6,7 @@ import SearchParserHandler from "../SearchParser";
export class NotAllPageSearchResultPageParser implements SearchResultPageParserInterface { export class NotAllPageSearchResultPageParser implements SearchResultPageParserInterface {
support(type:SupportType, pageNum:number):boolean { support(type:SupportType, pageNum:number):boolean {
return type != SupportType.ALL && !(pageNum ==1 && type == SupportType.NOTE); return type != SupportType.all && !(pageNum ==1 && type == SupportType.note);
} }
parse(source:string, type:SupportType, pageNum:number, pageSize:number):SearchPage { parse(source:string, type:SupportType, pageNum:number, pageSize:number):SearchPage {
log.debug("解析给多页面结果"); log.debug("解析给多页面结果");

@ -7,7 +7,7 @@ import DoubanSearchResultSubject from "../../model/DoubanSearchResultSubject";
export class NoteFirstPageSearchResultPageParser implements SearchResultPageParserInterface { export class NoteFirstPageSearchResultPageParser implements SearchResultPageParserInterface {
support(type:SupportType, pageNum:number):boolean { support(type:SupportType, pageNum:number):boolean {
return pageNum == 1 && type == SupportType.NOTE; return pageNum == 1 && type == SupportType.note;
} }
parse(source:string, type:SupportType, pageNum:number, pageSize:number):SearchPage { parse(source:string, type:SupportType, pageNum:number, pageSize:number):SearchPage {
const pageData = load(source); const pageData = load(source);

@ -2,21 +2,18 @@ import {SupportType} from "../../../../constant/Constsant";
import {SearchResultPageParserInterface} from "./SearchResultPageParserInterface"; import {SearchResultPageParserInterface} from "./SearchResultPageParserInterface";
import {log} from "../../../../utils/Logutil"; import {log} from "../../../../utils/Logutil";
import {SearchPage} from "../../model/SearchPage"; import {SearchPage} from "../../model/SearchPage";
import SearchParserHandlerV2 from "../SearchParserV2"; import SearchParserHandler from "../SearchParser";
export class OtherAllPageSearchResultPageParser implements SearchResultPageParserInterface { export class OtherAllPageSearchResultPageParser implements SearchResultPageParserInterface {
support(type:SupportType, pageNum:number):boolean { support(type:SupportType, pageNum:number):boolean {
return pageNum > 1 && type == SupportType.ALL; return pageNum > 1 && type == SupportType.all;
} }
parse(source:string, type:SupportType, pageNum:number, pageSize:number):SearchPage { parse(source:string, type:SupportType, pageNum:number, pageSize:number):SearchPage {
log.debug("解析给多页面结果"); log.debug("解析给多页面结果");
const {contents} = JSON.parse(source); if (!source) {
if (!contents) {
return new SearchPage(0, 0, 0, type, []); return new SearchPage(0, 0, 0, type, []);
} }
const data:{total:number, start:number, count:number, items:any[]} = contents; return SearchParserHandler.parseSearchJson(source, type, pageNum);
const doubanSearchResultSubjects = SearchParserHandlerV2.itemMapToSearchResult(data.items);
return new SearchPage(data.total, pageNum, pageSize, type, doubanSearchResultSubjects);
} }
} }

@ -4,6 +4,8 @@ import {SearchPageFetcherInterface} from "./SearchPageFetcherInterface";
import HttpUtil from "../../../../utils/HttpUtil"; import HttpUtil from "../../../../utils/HttpUtil";
import {log} from "../../../../utils/Logutil"; import {log} from "../../../../utils/Logutil";
import {i18nHelper} from "../../../../lang/helper"; import {i18nHelper} from "../../../../lang/helper";
import {DoubanHttpUtil} from "../../../../utils/DoubanHttpUtil";
import {Platform} from "obsidian";
export abstract class AbstractSearchPageFetcher implements SearchPageFetcherInterface { export abstract class AbstractSearchPageFetcher implements SearchPageFetcherInterface {
@ -15,20 +17,30 @@ export abstract class AbstractSearchPageFetcher implements SearchPageFetcherInte
support(type: SupportType, pageNum?:number): boolean { support(type: SupportType, pageNum?:number): boolean {
throw new Error("Method not implemented."); throw new Error("Method not implemented.");
} }
fetch(keyword: string, pageNum: number, pageSize: number): Promise<string> {
const start:number = (pageNum - 1) * pageSize; fetch(keyword: string, pageNum: number, pageSize: number): Promise<string> {
const url:string = this.getUrl(keyword, start, pageSize); const start:number = Math.floor((pageNum - 1) * pageSize);
const url:string = this.getSearchUrl(keyword, start, pageSize);
if (!url) { if (!url) {
return Promise.resolve(""); return Promise.resolve("");
} }
return HttpUtil.httpRequestGet(url, this.settingsManager.getHeaders(), this.settingsManager) return DoubanHttpUtil.httpRequestGet(url, this.settingsManager.getHeaders(), this.settingsManager)
.catch(e => { .catch(e => {
throw log.error(i18nHelper.getMessage('130101').replace('{0}', e.toString()), e); throw log.error(i18nHelper.getMessage('130101').replace('{0}', e.toString()), e);
}); } });
}
getSearchUrl(keyword: string, start: number, pageSize: number):string {
keyword = keyword.trim();
if (keyword.length == 0) {
return "";
}
keyword = HttpUtil.encodeUrl(keyword);
return this.getUrl(keyword, start, pageSize)
}
abstract getUrl(keyword: string, start: number, pageSize: number):string; abstract getUrl(keyword: string, start: number, pageSize: number):string;
} }

@ -2,11 +2,11 @@ import {AbstractSearchPageFetcher} from "./AbstractSearchPageFetcher";
import { SupportType } from "src/org/wanxp/constant/Constsant"; import { SupportType } from "src/org/wanxp/constant/Constsant";
export class AllPageSearchPageFetcher extends AbstractSearchPageFetcher { export class AllPageSearchPageFetcher extends AbstractSearchPageFetcher {
getUrl(keyword: string, pageNum: number, pageSize: number): string { getUrl(keyword: string, start: number, pageSize: number): string {
return `https://m.douban.com/rexxar/api/v2/search?q=${keyword}&start=${pageNum}&count=${pageSize}`; return `https://www.douban.com/j/search?q=${keyword}&start=${start}`;
} }
support(type: SupportType): boolean { support(type: SupportType): boolean {
return type == SupportType.ALL; return type == SupportType.all;
} }

@ -6,7 +6,7 @@ export class BookPageSearchPageFetcher extends AbstractSearchPageFetcher {
return `https://www.douban.com/j/search?q=${keyword}&start=${start}&cat=1001`; return `https://www.douban.com/j/search?q=${keyword}&start=${start}&cat=1001`;
} }
support(type: SupportType): boolean { support(type: SupportType): boolean {
return type == SupportType.BOOK; return type == SupportType.book;
} }

@ -6,7 +6,7 @@ export class GamePageSearchPageFetcher extends AbstractSearchPageFetcher {
return `https://www.douban.com/j/search?q=${keyword}&start=${start}&cat=3114`; return `https://www.douban.com/j/search?q=${keyword}&start=${start}&cat=3114`;
} }
support(type: SupportType): boolean { support(type: SupportType): boolean {
return type == SupportType.GAME; return type == SupportType.game;
} }

@ -6,7 +6,7 @@ export class MoviePageSearchPageFetcher extends AbstractSearchPageFetcher {
return `https://www.douban.com/j/search?q=${keyword}&start=${start}&cat=1002`; return `https://www.douban.com/j/search?q=${keyword}&start=${start}&cat=1002`;
} }
support(type: SupportType): boolean { support(type: SupportType): boolean {
return type == SupportType.MOVIE; return type == SupportType.movie;
} }

@ -6,7 +6,7 @@ export class MusicPageSearchPageFetcher extends AbstractSearchPageFetcher {
return `https://www.douban.com/j/search?q=${keyword}&start=${start}&cat=1003`; return `https://www.douban.com/j/search?q=${keyword}&start=${start}&cat=1003`;
} }
support(type: SupportType): boolean { support(type: SupportType): boolean {
return type == SupportType.MUSIC; return type == SupportType.music;
} }

@ -6,7 +6,7 @@ export class NoteFirstPageSearchPageFetcher extends AbstractSearchPageFetcher {
return `https://www.douban.com/search?cat=1015&q=${keyword}`; return `https://www.douban.com/search?cat=1015&q=${keyword}`;
} }
support(type: SupportType, pageNum:number): boolean { support(type: SupportType, pageNum:number): boolean {
return type == SupportType.NOTE && pageNum == 1; return type == SupportType.note && pageNum == 1;
} }

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