jmcomic 2.7.6__tar.gz → 2.7.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. {jmcomic-2.7.6/src/jmcomic.egg-info → jmcomic-2.7.7}/PKG-INFO +10 -5
  2. {jmcomic-2.7.6 → jmcomic-2.7.7}/README.md +1 -4
  3. {jmcomic-2.7.6 → jmcomic-2.7.7}/pyproject.toml +11 -0
  4. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/__init__.py +1 -1
  5. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_async_client.py +60 -2
  6. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_client_impl.py +143 -2
  7. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_client_interface.py +126 -0
  8. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_config.py +3 -1
  9. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_entity.py +4 -0
  10. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_option.py +37 -1
  11. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_plugin.py +329 -20
  12. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_toolkit.py +29 -1
  13. {jmcomic-2.7.6 → jmcomic-2.7.7/src/jmcomic.egg-info}/PKG-INFO +10 -5
  14. jmcomic-2.7.7/src/jmcomic.egg-info/requires.txt +14 -0
  15. jmcomic-2.7.6/src/jmcomic.egg-info/requires.txt +0 -5
  16. {jmcomic-2.7.6 → jmcomic-2.7.7}/LICENSE +0 -0
  17. {jmcomic-2.7.6 → jmcomic-2.7.7}/setup.cfg +0 -0
  18. {jmcomic-2.7.6 → jmcomic-2.7.7}/setup.py +0 -0
  19. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/api.py +0 -0
  20. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/cli.py +0 -0
  21. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_async_downloader.py +0 -0
  22. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_downloader.py +0 -0
  23. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_exception.py +0 -0
  24. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_feature.py +0 -0
  25. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic/jm_task_context.py +0 -0
  26. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic.egg-info/SOURCES.txt +0 -0
  27. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic.egg-info/dependency_links.txt +0 -0
  28. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic.egg-info/entry_points.txt +0 -0
  29. {jmcomic-2.7.6 → jmcomic-2.7.7}/src/jmcomic.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jmcomic
3
- Version: 2.7.6
3
+ Version: 2.7.7
4
4
  Summary: Python API For JMComic (禁漫天堂)
5
5
  Home-page: https://github.com/hect0x7/JMComic-Crawler-Python
6
6
  Author: hect0x7
@@ -50,6 +50,14 @@ Requires-Dist: curl-cffi
50
50
  Requires-Dist: pillow
51
51
  Requires-Dist: pycryptodome
52
52
  Requires-Dist: pyyaml
53
+ Provides-Extra: plugins
54
+ Requires-Dist: img2pdf; extra == "plugins"
55
+ Requires-Dist: pikepdf; extra == "plugins"
56
+ Requires-Dist: psutil; extra == "plugins"
57
+ Requires-Dist: py7zr; extra == "plugins"
58
+ Requires-Dist: pyzipper; extra == "plugins"
59
+ Requires-Dist: rich; extra == "plugins"
60
+ Requires-Dist: browser_cookie3; extra == "plugins"
53
61
  Dynamic: author
54
62
  Dynamic: home-page
55
63
  Dynamic: license-file
@@ -305,10 +313,7 @@ jmv 350234 -y
305
313
  - 支持自定义本子/章节/图片下载前后事件的回调函数
306
314
  - 支持自定义类:`Downloader(负责调度)` `Option(负责配置)` `Client(负责请求)` `实体类`等
307
315
  - 支持自定义日志、异常监听器
308
- - **支持Plugin插件,可以方便地扩展功能,以及使用别人的插件,目前核心内置插件有**:
309
- - `登录插件`、`只下载新章插件`、`导出收藏夹为csv文件插件`
310
- - `合并所有图片为pdf文件插件`、`合并所有图片为长图png插件`
311
- - `压缩文件插件`、`自动获取浏览器cookies插件`、`订阅更新插件`等
316
+ - **支持 Plugin 扩展,目前内置 21 个实用插件,包括**:`美观下载进度条`、`图片合并 PDF`、`一图流长图拼接`、`生成zip/7z压缩包`、`浏览器 Cookie 获取`、`订阅更新`、`收藏夹导出`、`封面下载`等。
312
317
 
313
318
  ## 使用小说明
314
319
 
@@ -248,10 +248,7 @@ jmv 350234 -y
248
248
  - 支持自定义本子/章节/图片下载前后事件的回调函数
249
249
  - 支持自定义类:`Downloader(负责调度)` `Option(负责配置)` `Client(负责请求)` `实体类`等
250
250
  - 支持自定义日志、异常监听器
251
- - **支持Plugin插件,可以方便地扩展功能,以及使用别人的插件,目前核心内置插件有**:
252
- - `登录插件`、`只下载新章插件`、`导出收藏夹为csv文件插件`
253
- - `合并所有图片为pdf文件插件`、`合并所有图片为长图png插件`
254
- - `压缩文件插件`、`自动获取浏览器cookies插件`、`订阅更新插件`等
251
+ - **支持 Plugin 扩展,目前内置 21 个实用插件,包括**:`美观下载进度条`、`图片合并 PDF`、`一图流长图拼接`、`生成zip/7z压缩包`、`浏览器 Cookie 获取`、`订阅更新`、`收藏夹导出`、`封面下载`等。
255
252
 
256
253
  ## 使用小说明
257
254
 
@@ -32,6 +32,17 @@ dependencies = [
32
32
  ]
33
33
  dynamic = ["version"]
34
34
 
35
+ [project.optional-dependencies]
36
+ plugins = [
37
+ "img2pdf",
38
+ "pikepdf",
39
+ "psutil",
40
+ "py7zr",
41
+ "pyzipper",
42
+ "rich",
43
+ "browser_cookie3",
44
+ ]
45
+
35
46
  [project.urls]
36
47
  Homepage = "https://github.com/hect0x7/JMComic-Crawler-Python"
37
48
  Documentation = "https://jmcomic.readthedocs.io"
@@ -2,7 +2,7 @@
2
2
  # 被依赖方 <--- 使用方
3
3
  # config <--- entity <--- toolkit <--- client <--- option <--- downloader
4
4
 
5
- __version__ = '2.7.6'
5
+ __version__ = '2.7.7'
6
6
 
7
7
  from .jm_task_context import *
8
8
  from .api import *
@@ -14,7 +14,7 @@ from urllib.parse import urlencode
14
14
  from curl_cffi.requests import AsyncSession
15
15
 
16
16
  from .jm_client_interface import (
17
- JmApiResp, JmImageResp, JmAlbumCommentResp,
17
+ JmApiResp, JmImageResp, JmAlbumCommentResp, JmDailyCheckinResp,
18
18
  AsyncJmcomicClient,
19
19
  )
20
20
  from .jm_entity import (
@@ -49,6 +49,8 @@ class AsyncJmApiClient(AsyncJmcomicClient):
49
49
  API_SCRAMBLE = '/chapter_view_template'
50
50
  API_FAVORITE = '/favorite'
51
51
  API_FORUM = '/forum'
52
+ API_DAILY = '/daily'
53
+ API_DAILY_CHK = '/daily_chk'
52
54
 
53
55
  # 缓存未命中标记
54
56
  _SENTINEL = object()
@@ -81,6 +83,7 @@ class AsyncJmApiClient(AsyncJmcomicClient):
81
83
  # 缓存默认关闭,由外部配置决定是否启用。
82
84
  self._cache: dict | None = None
83
85
  self._username: str | None = None
86
+ self._user_id: str | None = None
84
87
 
85
88
  # 接收并保存额外的会话级元数据参数
86
89
  self._meta_kwargs = kwargs
@@ -618,13 +621,15 @@ class AsyncJmApiClient(AsyncJmcomicClient):
618
621
  'username': username,
619
622
  'password': password,
620
623
  })
624
+ res_data = resp.res_data
621
625
  cookies = dict(resp.resp.cookies)
622
- cookies.update({'AVS': resp.res_data['s']})
626
+ cookies.update({'AVS': res_data['s']})
623
627
  # noinspection PyUnresolvedReferences,PyTypeChecker
624
628
  self._session.cookies.update(cookies)
625
629
  # 同步到 Option 配置,确保 cookies 持久化
626
630
  self.option.update_cookies(cookies)
627
631
  self._username = username
632
+ self._user_id = str(res_data['uid']) if 'uid' in res_data else None
628
633
  return resp
629
634
 
630
635
  async def favorite_folder(self,
@@ -720,6 +725,59 @@ class AsyncJmApiClient(AsyncJmcomicClient):
720
725
  """
721
726
  return await self.toggle_favorite_album(album_id, folder_id, expected_type='remove')
722
727
 
728
+ async def get_daily(self, user_id: str | None = None) -> JmApiResp:
729
+ """
730
+ 获取每日签到信息与日历打卡记录
731
+ :param user_id: 用户ID,默认读取当前登录用户的uid
732
+ """
733
+ if user_id is None:
734
+ ExceptionTool.require_true(self._user_id is not None, '签到需要传入 user_id 参数,或者先调用 login 方法')
735
+ user_id = self._user_id
736
+
737
+ return await self.req_api(self.API_DAILY, params={'user_id': user_id})
738
+
739
+ async def daily_checkin(self, daily_id: str | None = None, user_id: str | None = None) -> JmDailyCheckinResp:
740
+ """
741
+ 执行每日打卡签到(异步)。
742
+ 返回 JmDailyCheckinResp 对象:
743
+ - code=0 (或 status=0): 签到成功
744
+ - code=1 (或 status=1): 重复签到(今日已完成打卡)
745
+ - 其余失败情况直接抛出异常
746
+ :param daily_id: 打卡任务ID,未提供时会自动请求 get_daily 获取
747
+ :param user_id: 用户ID,默认读取当前登录用户的uid
748
+ :return: JmDailyCheckinResp
749
+ """
750
+ if user_id is None:
751
+ ExceptionTool.require_true(self._user_id is not None, '签到需要传入 user_id 参数,或者先调用 login 方法')
752
+ user_id = self._user_id
753
+
754
+ if daily_id is None:
755
+ daily_resp = await self.get_daily(user_id)
756
+ if 'daily_id' not in daily_resp.res_data:
757
+ ExceptionTool.raises_resp('签到失败:签到信息缺少 daily_id', daily_resp)
758
+ daily_id = daily_resp.res_data['daily_id']
759
+
760
+ resp: JmApiResp = await self.req_api(
761
+ self.API_DAILY_CHK,
762
+ get=False,
763
+ data={
764
+ 'user_id': user_id,
765
+ 'daily_id': daily_id,
766
+ },
767
+ )
768
+
769
+ res_data = resp.res_data
770
+ msg = str(res_data.get('msg', ''))
771
+
772
+ if any(kw in msg for kw in ('今天已經簽到過了', '已簽到', '簽到過', '已完成', '已签到')):
773
+ code = JmDailyCheckinResp.CODE_ALREADY_CHECKED_IN
774
+ elif 'Jcoin' in msg or 'EXP' in msg or res_data.get('status') == 'ok' or '成功' in msg:
775
+ code = JmDailyCheckinResp.CODE_SUCCESS
776
+ else:
777
+ ExceptionTool.raises_resp(f'签到失败:{msg or res_data}', resp)
778
+
779
+ return JmDailyCheckinResp(resp.resp, code, msg, res_data)
780
+
723
781
  async def album_comment(self,
724
782
  video_id,
725
783
  comment,
@@ -32,6 +32,7 @@ class AbstractJmClient(
32
32
  self.domain_retry_strategy = domain_retry_strategy
33
33
  self.CLIENT_CACHE = None
34
34
  self._username = None # help for favorite_folder method
35
+ self._user_id = None # help for check_in / get_daily method
35
36
  if domain_retry_strategy:
36
37
  domain_retry_strategy(self)
37
38
  self.enable_cache()
@@ -446,7 +447,12 @@ class JmHtmlClient(AbstractJmClient):
446
447
  )
447
448
 
448
449
  if resp.status_code != 200:
449
- ExceptionTool.raises_resp(f'登录失败,状态码为{resp.status_code}', resp)
450
+ self.raise_request_error(resp, f'登录失败,状态码为{resp.status_code}')
451
+
452
+ res = resp.json()
453
+ if res.get('status') != 1:
454
+ errors = res.get('errors') or [res.get('msg', '登录失败')]
455
+ self.raise_request_error(resp, f'登录失败:{errors[0]}')
450
456
 
451
457
  orig_cookies = self.get_meta_data('cookies') or {}
452
458
  new_cookies = dict(resp.cookies)
@@ -488,6 +494,73 @@ class JmHtmlClient(AbstractJmClient):
488
494
  # 解析cookies,可能需要用到 phpserialize,比较麻烦,暂不实现
489
495
  pass
490
496
 
497
+ def get_or_fetch_daily_id(self, daily_id: str | None = None) -> str:
498
+ if daily_id is None:
499
+ resp_home = self.get_jm_html('/')
500
+ daily_id = JmcomicText.parse_daily_id(resp_home.text)
501
+ ExceptionTool.require_true(bool(daily_id), '未能从首页获取到 daily_id,请手动传入 daily_id 参数')
502
+ return str(daily_id)
503
+
504
+ def get_daily(self,
505
+ user_id: str | None = None,
506
+ daily_id: str | None = None
507
+ ) -> JmJsonResp:
508
+ """
509
+ 网页端获取每日签到信息与日历打卡记录。
510
+ 返回值格式参考 JmUserClient.get_daily 文档。
511
+ :param user_id: 兼容参数,网页端不需要
512
+ :param daily_id: 如果外界提前获取了,可直接传递参数,使得本方法内部少一次网络请求查询。
513
+ :return: JmJsonResp
514
+ """
515
+ daily_id = self.get_or_fetch_daily_id(daily_id)
516
+ resp = self.get(
517
+ '/ajax/user_daily_event',
518
+ params={'daily_id': daily_id},
519
+ )
520
+ ret = JmJsonResp(resp)
521
+ ret.require_success()
522
+ return ret
523
+
524
+ def daily_checkin(self,
525
+ daily_id: str | None = None,
526
+ user_id: str | None = None,
527
+ old_step: int = 1
528
+ ) -> JmDailyCheckinResp:
529
+ """
530
+ 网页端每日签到。
531
+ 返回 JmDailyCheckinResp 对象:
532
+ - code=0 (或 status=0): 签到成功
533
+ - code=1 (或 status=1): 重复签到(今日已完成打卡)
534
+ - 其余失败情况直接抛出异常
535
+ :param daily_id: 打卡任务ID,未提供时会自动从首页提取
536
+ :param user_id: 兼容参数,网页端不需要
537
+ :param old_step: 连续签到天数阶段,默认为 1
538
+ :return: JmDailyCheckinResp
539
+ """
540
+ daily_id = self.get_or_fetch_daily_id(daily_id)
541
+ resp = self.post(
542
+ '/ajax/user_daily_sign',
543
+ data={
544
+ 'daily_id': daily_id,
545
+ 'oldStep': str(old_step),
546
+ },
547
+ )
548
+ if resp.status_code != 200:
549
+ self.raise_request_error(resp, f'签到请求失败,HTTP状态码: {resp.status_code}')
550
+
551
+ res = resp.json()
552
+ status = res.get('status')
553
+ msg = str(res.get('msg', ''))
554
+
555
+ if status == 1:
556
+ code = JmDailyCheckinResp.CODE_SUCCESS
557
+ elif status == 0 and any(kw in msg for kw in ('已完成打卡', '今天已经签到', '今日已完成', '已签到', '已打卡')):
558
+ code = JmDailyCheckinResp.CODE_ALREADY_CHECKED_IN
559
+ else:
560
+ self.raise_request_error(resp, f'签到失败:{msg or status}')
561
+
562
+ return JmDailyCheckinResp(resp, code, msg, res)
563
+
491
564
  def get_jm_html(self, url, require_200=True, **kwargs):
492
565
  """
493
566
  请求禁漫网页的入口
@@ -694,6 +767,8 @@ class JmApiClient(AbstractJmClient):
694
767
  API_SCRAMBLE = '/chapter_view_template'
695
768
  API_FAVORITE = '/favorite'
696
769
  API_FORUM = '/forum'
770
+ API_DAILY = '/daily'
771
+ API_DAILY_CHK = '/daily_chk'
697
772
 
698
773
  def search(self,
699
774
  search_query: str,
@@ -917,9 +992,12 @@ class JmApiClient(AbstractJmClient):
917
992
  'password': password,
918
993
  })
919
994
 
995
+ res_data = resp.res_data
920
996
  cookies = dict(resp.resp.cookies)
921
- cookies.update({'AVS': resp.res_data['s']})
997
+ cookies.update({'AVS': res_data['s']})
922
998
  self['cookies'] = cookies
999
+ self._username = username
1000
+ self._user_id = str(res_data['uid']) if 'uid' in res_data else None
923
1001
 
924
1002
  return resp
925
1003
 
@@ -1031,6 +1109,66 @@ class JmApiClient(AbstractJmClient):
1031
1109
  """
1032
1110
  return self.toggle_favorite_album(album_id, folder_id, expected_type='remove')
1033
1111
 
1112
+ def get_daily(self,
1113
+ user_id: str | None = None,
1114
+ ) -> JmApiResp:
1115
+ """
1116
+ 移动端获取每日签到信息与日历打卡记录。
1117
+ 返回值格式参考 JmUserClient.get_daily 文档。
1118
+ :param user_id: 用户ID,默认读取当前登录用户的uid
1119
+ :return: JmApiResp
1120
+ """
1121
+ if user_id is None:
1122
+ ExceptionTool.require_true(self._user_id is not None, '签到需要传入 user_id 参数,或者先调用 login 方法')
1123
+ user_id = self._user_id
1124
+
1125
+ return self.req_api(self.API_DAILY, params={'user_id': user_id})
1126
+
1127
+ def daily_checkin(self,
1128
+ daily_id: str | None = None,
1129
+ user_id: str | None = None,
1130
+ ) -> JmDailyCheckinResp:
1131
+ """
1132
+ 执行每日打卡签到。
1133
+ 返回 JmDailyCheckinResp 对象:
1134
+ - code=0 (或 status=0): 签到成功
1135
+ - code=1 (或 status=1): 重复签到(今日已完成打卡)
1136
+ - 其余失败情况直接抛出异常
1137
+ :param daily_id: 打卡任务ID,未提供时会自动请求 get_daily 获取
1138
+ :param user_id: 用户ID,默认读取当前登录用户的uid
1139
+ :return: JmDailyCheckinResp
1140
+ """
1141
+ if user_id is None:
1142
+ ExceptionTool.require_true(self._user_id is not None, '签到需要传入 user_id 参数,或者先调用 login 方法')
1143
+ user_id = self._user_id
1144
+
1145
+ if daily_id is None:
1146
+ daily_resp = self.get_daily(user_id)
1147
+ if 'daily_id' not in daily_resp.res_data:
1148
+ ExceptionTool.raises_resp('签到失败:签到信息缺少 daily_id', daily_resp)
1149
+ daily_id = daily_resp.res_data['daily_id']
1150
+
1151
+ resp: JmApiResp = self.req_api(
1152
+ self.API_DAILY_CHK,
1153
+ get=False,
1154
+ data={
1155
+ 'user_id': user_id,
1156
+ 'daily_id': daily_id,
1157
+ },
1158
+ )
1159
+
1160
+ res_data = resp.res_data
1161
+ msg = str(res_data.get('msg', ''))
1162
+
1163
+ if any(kw in msg for kw in ('今天已經簽到過了', '已簽到', '簽到過', '已完成', '已签到')):
1164
+ code = JmDailyCheckinResp.CODE_ALREADY_CHECKED_IN
1165
+ elif 'Jcoin' in msg or 'EXP' in msg or res_data.get('status') == 'ok' or '成功' in msg:
1166
+ code = JmDailyCheckinResp.CODE_SUCCESS
1167
+ else:
1168
+ ExceptionTool.raises_resp(f'签到失败:{msg or res_data}', resp)
1169
+
1170
+ return JmDailyCheckinResp(resp.resp, code, msg, res_data)
1171
+
1034
1172
  # noinspection PyMethodMayBeStatic
1035
1173
  def require_resp_status_ok(self, resp: JmApiResp):
1036
1174
  """
@@ -1375,3 +1513,6 @@ class PhotoConcurrentFetcherProxy(JmcomicClient):
1375
1513
  photo.scramble_id = scramble_id
1376
1514
 
1377
1515
  return photo
1516
+
1517
+ def __getattr__(self, item):
1518
+ return getattr(self.client, item)
@@ -96,6 +96,22 @@ class JmJsonResp(JmResp):
96
96
 
97
97
 
98
98
  class JmApiResp(JmJsonResp):
99
+ """
100
+ 移动端 API 响应包装类。
101
+
102
+ 原始响应示例(resp.text):
103
+ {"code": 200, "data": "abc123XYZ..."}
104
+
105
+ 内部数据流动机制:
106
+ 1. encoded_data: 从原始响应 JSON 中提取 resp.json()['data'](服务端经 AES 加密后的 Base64 密文字符串)。
107
+ 示例: "abc123XYZ..."
108
+ 2. decoded_data: 将 encoded_data 经 Base64 解码 + AES-ECB 解密并去除 Padding 后,得到的明文字符串(通常为 JSON 字符串)。
109
+ 示例: '{"msg": "Jcoin:40 EXP:40"}'
110
+ 3. res_data: 通过 json.loads 将 decoded_data 解析为 Python 字典/列表(Any)。
111
+ 示例: {'msg': 'Jcoin:40 EXP:40'}
112
+ 4. model_data: 将 res_data 包装为便于属性访问的 AdvancedDict 字典对象。
113
+ 示例: model_data.msg -> 'Jcoin:40 EXP:40'
114
+ """
99
115
 
100
116
  def __init__(self, resp, ts: str):
101
117
  super().__init__(resp)
@@ -124,6 +140,8 @@ class JmApiResp(JmJsonResp):
124
140
 
125
141
  def require_have_data(self):
126
142
  data = self.encoded_data
143
+ if data is None:
144
+ ExceptionTool.raises_resp(f'响应数据为空: {self.text}', self)
127
145
  if isinstance(data, list) and len(data) == 0 and self.json().get('errorMsg', None):
128
146
  ExceptionTool.raises_resp(f'data返回值异常: {self.text}', self)
129
147
 
@@ -149,6 +167,24 @@ class JmAlbumCommentResp(JmJsonResp):
149
167
  return super().is_success and self.json()['err'] is False
150
168
 
151
169
 
170
+ class JmDailyCheckinResp(JmResp):
171
+ """
172
+ 每日签到打卡响应类
173
+ """
174
+ CODE_SUCCESS = 0 # 签到成功
175
+ CODE_ALREADY_CHECKED_IN = 1 # 重复签到(今日已签)
176
+
177
+ def __init__(self, resp, code: int, msg: str, raw_data: dict = None):
178
+ super().__init__(resp)
179
+ self.code: int = code # 0=签到成功, 1=重复签到
180
+ self.status: int = code # 兼容字段,值等同于 code
181
+ self.msg: str = msg # 透传服务端的提示信息或奖励内容
182
+ self.raw_data: dict = raw_data or {}
183
+
184
+ def __repr__(self):
185
+ return f'<JmDailyCheckinResp code={self.code} msg={self.msg!r}>'
186
+
187
+
152
188
  """
153
189
 
154
190
  Client Interface
@@ -321,6 +357,75 @@ class JmUserClient:
321
357
  """
322
358
  raise NotImplementedError
323
359
 
360
+ def get_daily(self,
361
+ user_id: str | None = None,
362
+ ) -> Union[JmApiResp, JmJsonResp]:
363
+ """
364
+ 获取每日签到信息与日历打卡记录。
365
+ 两端均返回包含活动信息、打卡记录、背景图与打卡状态的完整响应对象:
366
+ - HTML 客户端 (JmJsonResp):明文 JSON,可通过 resp.json() 获取字典,或 resp.model() 属性访问。
367
+ - API 客户端 (JmApiResp):加密响应,可通过 resp.res_data 获取解密字典,或 resp.model_data 属性访问。
368
+
369
+ 两端返回数据结构示例:
370
+
371
+ 1. HTML 客户端 (JmJsonResp.json() / JmJsonResp.model()):
372
+ {
373
+ "dateArray": [11], # 当月已签到的日期数组
374
+ "dateMiss": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], # 当月漏签的日期数组
375
+ "dateEvent": [ # 特殊活动/双倍奖励日期
376
+ "2026-09-05 00:00:00",
377
+ "2026-09-06 00:00:00"
378
+ ],
379
+ "oldStep": 1, # 连续签到天数
380
+ "error": "finished", # 今日打卡状态(若今日已签到则为 "finished")
381
+ "pc_img": "/media/logo/pc/9PC.jpg", # 签到弹窗 PC 背景图
382
+ "mb_img": "/media/logo/phone/9PH.jpg" # 签到弹窗移动端背景图
383
+ }
384
+
385
+ 2. API 客户端 (JmApiResp.res_data / JmApiResp.model_data):
386
+ {
387
+ "daily_id": 72, # 当前签到活动ID
388
+ "event_name": "9月-签到活动", # 活动标题
389
+ "currentProgress": "14.3%", # 连续进度百分比
390
+ "three_days_coin": "150", # 满3天奖励金币
391
+ "three_days_exp": "150", # 满3天奖励经验
392
+ "seven_days_coin": "350", # 满7天奖励金币
393
+ "seven_days_exp": "350", # 满7天奖励经验
394
+ "background_pc": "/media/logo/pc/9PC.jpg", # 背景图路径
395
+ "background_phone": "/media/logo/phone/9PH.jpg",
396
+ "record": [ # 按周划分的完整签到日历矩阵
397
+ [
398
+ {"date": "01", "signed": false, "bonus": false},
399
+ {"date": "02", "signed": false, "bonus": false}
400
+ ],
401
+ [
402
+ {"date": "11", "signed": true, "bonus": false},
403
+ {"date": "12", "signed": null, "bonus": true}
404
+ ]
405
+ ]
406
+ }
407
+
408
+ :param user_id: 用户ID,API 客户端默认读取当前登录用户的uid
409
+ """
410
+ raise NotImplementedError
411
+
412
+ def daily_checkin(self,
413
+ daily_id: str | None = None,
414
+ user_id: str | None = None,
415
+ ) -> JmDailyCheckinResp:
416
+ """
417
+ 执行每日打卡签到。
418
+ 返回 JmDailyCheckinResp 对象:
419
+ - code=0 (或 status=0): 签到成功,msg 包含奖励信息(如金币/经验)
420
+ - code=1 (或 status=1): 重复签到(今日已完成打卡)
421
+ - 其余非预期错误(未登录、网络失败、活动失效等)直接抛出异常
422
+
423
+ :param daily_id: 打卡任务ID,未提供时会自动获取
424
+ :param user_id: 用户ID,API 客户端默认读取当前登录用户的uid
425
+ :return: JmDailyCheckinResp
426
+ """
427
+ raise NotImplementedError
428
+
324
429
 
325
430
  class JmImageClient:
326
431
 
@@ -1061,6 +1166,27 @@ class AsyncJmcomicClient:
1061
1166
  async def delete_favorite_album(self, album_id, folder_id='0'):
1062
1167
  raise NotImplementedError
1063
1168
 
1169
+ async def get_daily(self, user_id: str | None = None) -> JmApiResp:
1170
+ """
1171
+ 获取每日签到信息与日历打卡记录
1172
+ :param user_id: 用户ID,默认读取当前登录用户的uid
1173
+ """
1174
+ raise NotImplementedError
1175
+
1176
+ async def daily_checkin(self, daily_id: str | None = None, user_id: str | None = None) -> JmDailyCheckinResp:
1177
+ """
1178
+ 执行每日打卡签到(异步)。
1179
+ 返回 JmDailyCheckinResp 对象:
1180
+ - code=0 (或 status=0): 签到成功,msg 包含奖励信息(如金币/经验)
1181
+ - code=1 (或 status=1): 重复签到(今日已完成打卡)
1182
+ - 其余非预期错误(未登录、网络失败、活动失效等)直接抛出异常
1183
+
1184
+ :param daily_id: 打卡任务ID,未提供时会自动请求 get_daily 获取
1185
+ :param user_id: 用户ID,默认读取当前登录用户的uid
1186
+ :return: JmDailyCheckinResp
1187
+ """
1188
+ raise NotImplementedError
1189
+
1064
1190
  async def album_comment(self,
1065
1191
  video_id,
1066
1192
  comment,
@@ -146,7 +146,7 @@ class JmMagicConstants:
146
146
  APP_TOKEN_SECRET_2 = '18comicAPPContent'
147
147
  APP_DATA_SECRET = '185Hcomic3PAPP7R'
148
148
  API_DOMAIN_SERVER_SECRET = 'diosfjckwpqpdfjkvnqQjsik'
149
- APP_VERSION = '2.1.6'
149
+ APP_VERSION = '2.1.7'
150
150
 
151
151
 
152
152
  # 模块级别共用配置
@@ -540,6 +540,8 @@ class JmModuleConfig:
540
540
  # 如果插件抛出参数校验异常,只log。(全局配置,可以被插件的局部配置覆盖)
541
541
  # 可选值:ignore(忽略),log(打印日志),raise(抛异常)。
542
542
  'valid': 'log',
543
+ # 插件依赖处理策略。可选值:failed-fast(快速失败),auto-install(自动安装),ignore-only-log(只记录日志不报错)。
544
+ 'dependencies_strategy': 'failed-fast',
543
545
  },
544
546
  }
545
547
 
@@ -481,6 +481,8 @@ class JmAlbumDetail(DetailEntity, Downloadable):
481
481
  tags,
482
482
  related_list=None,
483
483
  description='',
484
+ is_favorite=False,
485
+ liked=False,
484
486
  ):
485
487
  super().__init__()
486
488
  self.album_id: str = str(album_id)
@@ -498,6 +500,8 @@ class JmAlbumDetail(DetailEntity, Downloadable):
498
500
  self.actors: List[str] = actors # 登場人物
499
501
  self.tags: List[str] = tags # 標籤
500
502
  self.authors: List[str] = authors # 作者
503
+ self.is_favorite: bool = bool(is_favorite) # 是否已收藏
504
+ self.liked: bool = bool(liked) # 是否已点赞/喜欢
501
505
 
502
506
  # 有的 album 没有章节,则自成一章。
503
507
  episode_list: List[Tuple[str, str, str]]
@@ -202,6 +202,9 @@ class JmOption:
202
202
  # 需要主线程等待完成的插件
203
203
  self.need_wait_plugins = []
204
204
 
205
+ # 依赖策略预检/处理
206
+ self.check_plugins_dependencies()
207
+
205
208
  if call_after_init_plugin:
206
209
  self.call_all_plugin('after_init', safe=True)
207
210
 
@@ -351,7 +354,9 @@ class JmOption:
351
354
  # 意图聚焦:建议配置中只展示相关的 zip 插件,剔除其他无关插件的干扰
352
355
  advice_plugins = {}
353
356
  for g, plist in plugins.items():
354
- zips = [p for p in plist if p.get('plugin') == 'zip']
357
+ if not isinstance(plist, list):
358
+ continue
359
+ zips = [p for p in plist if isinstance(p, dict) and p.get('plugin') == 'zip']
355
360
  if zips:
356
361
  advice_plugins[g] = zips
357
362
 
@@ -633,6 +638,37 @@ class JmOption:
633
638
 
634
639
  # 下面的方法为调用插件提供支持
635
640
 
641
+ def check_plugins_dependencies(self) -> None:
642
+ """
643
+ 根据 plugins.dependencies_strategy 策略校验或安装已启用插件所需的依赖库。
644
+
645
+ 支持的策略值:
646
+ - failed-fast(默认):缺失依赖时快速失败,抛出带清晰解决方案指引的异常。
647
+ - auto-install:缺失依赖时以插件为维度自动调用 pip 安装缺失包。
648
+ - ignore-only-log:缺失依赖时仅打印 warning 日志,不阻断运行。
649
+
650
+ 具体检查、安装与错误处理逻辑收口于 JmOptionPlugin.check_plugin_dependency。
651
+ """
652
+ # 保证 jm_plugin.py 被加载
653
+ from .jm_plugin import JmOptionPlugin
654
+
655
+ strategy = self.plugins.dependencies_strategy
656
+ plugin_registry = JmModuleConfig.REGISTRY_PLUGIN
657
+
658
+ for group, plist in self.plugins.src_dict.items():
659
+ if not isinstance(plist, list):
660
+ continue
661
+
662
+ for pinfo in plist:
663
+ if not isinstance(pinfo, dict):
664
+ continue
665
+
666
+ pclass: Optional[Type[JmOptionPlugin]] = plugin_registry.get(pinfo.get('plugin'), None)
667
+ if pclass is None:
668
+ continue
669
+
670
+ pclass.check_plugin_dependency(pinfo.get('kwargs') or {}, strategy=strategy)
671
+
636
672
  def call_all_plugin(self, group: str, safe=None, **extra):
637
673
  plugin_list: List[dict] = self.plugins.get(group, [])
638
674
  if plugin_list is None or len(plugin_list) == 0:
@@ -20,6 +20,126 @@ class PluginValidationException(Exception):
20
20
 
21
21
  class JmOptionPlugin:
22
22
  plugin_key: str
23
+ # 插件运行所需的依赖库。
24
+ # 元素可以是 import 模块名(如 'psutil'),或者元组 (import_name, pip_pkg_name)。
25
+ plugin_dependencies: tuple = ()
26
+
27
+ @classmethod
28
+ def required_dependencies_for(cls, kwargs: dict) -> tuple:
29
+ """
30
+ 返回该插件在给定 kwargs 配置下实际需要的依赖库,供依赖策略校验使用。
31
+
32
+ 默认返回类声明的 plugin_dependencies。
33
+ 插件可按配置重写此方法,避免对合法配置误报
34
+ (如未加密的 zip 用标准库 zipfile 即可,无需 pyzipper/py7zr)。
35
+ """
36
+ return cls.plugin_dependencies
37
+
38
+ @classmethod
39
+ def parse_dependency_spec(cls, dep: Union[str, Tuple[str, str]]) -> Tuple[str, str]:
40
+ """
41
+ 解析依赖规格,返回 (import_name, pip_pkg_name)。
42
+ """
43
+ if isinstance(dep, tuple):
44
+ return dep[0], dep[1]
45
+ return dep, dep
46
+
47
+ @classmethod
48
+ def check_plugin_dependency(cls, kwargs: dict, strategy: str = 'failed-fast') -> None:
49
+ """
50
+ 检查当前插件在给定配置下所需的依赖库是否已安装,并按全局策略处理缺失情况。
51
+
52
+ 该方法由 JmOption 初始化(__init__)阶段在执行 after_init 之前统一触发,
53
+ 确保依赖问题在任务启动伊始即被捕获或解决。
54
+
55
+ :param kwargs: 当前插件在 option 中配置的参数字典,用于动态推断依赖
56
+ :param strategy: 依赖处理策略,对应配置 plugins.dependencies_strategy:
57
+ - 'failed-fast': 快速失败(默认),抛出异常并提示具体的解决方案;
58
+ - 'auto-install': 自动通过 pip 安装缺失的依赖包,安装失败严格报错;
59
+ - 'ignore-only-log': 仅输出 warning 日志,不阻断运行。
60
+ """
61
+ import importlib.util
62
+
63
+ # 1. 获取当前插件在特定配置下实际需要的可选依赖列表(如未加密 zip 无需额外库)
64
+ req_deps = cls.required_dependencies_for(kwargs)
65
+ if not req_deps:
66
+ return
67
+
68
+ # 2. 逐项检查依赖模块是否可用,收集所有缺失项 (import_name, pip_pkg_name)
69
+ missing: List[Tuple[str, str]] = []
70
+ for dep in req_deps:
71
+ import_name, pip_name = cls.parse_dependency_spec(dep)
72
+ if importlib.util.find_spec(import_name) is None:
73
+ missing.append((import_name, pip_name))
74
+
75
+ # 全部依赖已就绪,无需后续处理
76
+ if not missing:
77
+ return
78
+
79
+ # 3. 整理缺失模块名与 pip 安装包名,拼接命令与提示文案
80
+ missing_import_names = [m[0] for m in missing]
81
+ missing_pip_names = [m[1] for m in missing]
82
+ import_names_str = ', '.join(missing_import_names)
83
+ pip_install_cmd = 'pip install ' + ' '.join(missing_pip_names)
84
+
85
+ # 4. 根据策略分发处理:
86
+ if strategy == 'auto-install':
87
+ # 策略一:自动安装。以插件为单位排队调用 pip 安装缺失包
88
+ cls.install_missing_dependencies(missing_pip_names)
89
+ elif strategy == 'ignore-only-log':
90
+ # 策略二:仅打日志。记录警告信息,不抛出异常,保持最大容错
91
+ jm_log(
92
+ topic=f'plugin.{cls.plugin_key}.dependency',
93
+ msg=f'插件 [{cls.plugin_key}] 缺少依赖库 [{import_names_str}],'
94
+ f'可能会影响该插件执行。安装命令: [{pip_install_cmd}]'
95
+ )
96
+ else:
97
+ # 策略三:failed-fast(默认)。阻断执行并输出包含3种方案的用户指引
98
+ error_msg = (
99
+ f"插件 [{cls.plugin_key}] 缺少依赖库 [{import_names_str}],无法执行插件。有3种解决方案需要你选择一种手动执行:\n"
100
+ f"1. 仅安装该库,手动执行: {pip_install_cmd}\n"
101
+ f"2. 一键安装jmcomic插件依赖全家桶,手动执行: pip install jmcomic[plugins]\n"
102
+ f"3. 修改option,让jmcomic自动安装或不要报错\n"
103
+ f"plugins:\n"
104
+ f" dependencies_strategy: failed-fast # 👈当前默认配置,可配置为以下值\n"
105
+ f" # auto-install # 缺失时自动安装依赖\n"
106
+ f" # ignore-only-log # 缺失时仅打印失败日志不报错"
107
+ )
108
+ ExceptionTool.raises(error_msg)
109
+
110
+ @classmethod
111
+ def install_missing_dependencies(cls, pip_packages: List[str]) -> None:
112
+ """
113
+ 通过 pip 自动安装缺失的依赖包。如果安装失败则严格抛出异常。
114
+ """
115
+ import sys
116
+ import subprocess
117
+ import importlib
118
+
119
+ cmd = [sys.executable, '-m', 'pip', 'install'] + pip_packages
120
+ jm_log(
121
+ topic=f'plugin.{cls.plugin_key}.dependency',
122
+ msg=f'检测到插件 [{cls.plugin_key}] 缺少依赖,auto-install 策略正在自动安装: {" ".join(cmd)}'
123
+ )
124
+
125
+ try:
126
+ res = subprocess.run(cmd, capture_output=True, text=True, check=True)
127
+ if res.stdout:
128
+ jm_log(topic=f'plugin.{cls.plugin_key}.dependency', msg=res.stdout.strip())
129
+ # 刷新导入缓存,保证后续 import 能够正常找到新装的包
130
+ importlib.invalidate_caches()
131
+ jm_log(
132
+ topic=f'plugin.{cls.plugin_key}.dependency',
133
+ msg=f'插件 [{cls.plugin_key}] 依赖安装成功: {" ".join(pip_packages)}'
134
+ )
135
+ except Exception as e:
136
+ err_output = getattr(e, 'stderr', '') or str(e)
137
+ ExceptionTool.raises(
138
+ f'插件 [{cls.plugin_key}] 自动安装依赖 [{" ".join(pip_packages)}] 失败。\n'
139
+ f'执行命令: {" ".join(cmd)}\n'
140
+ f'错误详情: {err_output}\n'
141
+ f'请排查网络/权限问题,或手动执行: pip install {" ".join(pip_packages)}'
142
+ )
23
143
 
24
144
  def __init__(self, option: JmOption):
25
145
  self.option = option
@@ -175,6 +295,7 @@ class JmLoginPlugin(JmOptionPlugin):
175
295
 
176
296
  class UsageLogPlugin(JmOptionPlugin):
177
297
  plugin_key = 'usage_log'
298
+ plugin_dependencies = ('psutil',)
178
299
 
179
300
  def invoke(self, **kwargs) -> None:
180
301
  import threading
@@ -324,6 +445,35 @@ class ZipPlugin(JmOptionPlugin):
324
445
  """
325
446
 
326
447
  plugin_key = 'zip'
448
+ # zip 依赖取决于加密配置:未加密用标准库 zipfile,加密 zip 用 pyzipper,7z 用 py7zr
449
+ plugin_dependencies = ()
450
+
451
+ @classmethod
452
+ def required_dependencies_for(cls, kwargs: dict) -> tuple:
453
+ encrypt = cls.check_encrypt_param(kwargs.get('encrypt'))
454
+ if not encrypt:
455
+ return ()
456
+ if encrypt.get('impl', '') == '7z':
457
+ return ('py7zr',)
458
+ return ('pyzipper',)
459
+
460
+ @staticmethod
461
+ def check_encrypt_param(encrypt):
462
+ """
463
+ 校验 encrypt 配置的类型,返回规范化后的值(未配置时返回 None)。
464
+
465
+ encrypt 必须是映射(如 {type: sha256, password: xxx}),
466
+ 写成真值标量(encrypt: enabled)时后续的 encrypt.get(...) 会抛
467
+ AttributeError,绕过了配置校验机制、报错也难以理解,这里统一拦掉。
468
+ """
469
+ if encrypt is None:
470
+ return None
471
+ if not isinstance(encrypt, dict):
472
+ ExceptionTool.raises(
473
+ f'zip插件的encrypt参数类型有误,预期为映射(如 {{type: sha256, password: xxx}}),'
474
+ f'实际类型为{type(encrypt)}'
475
+ )
476
+ return encrypt
327
477
 
328
478
  # noinspection PyAttributeOutsideInit
329
479
  def invoke(self,
@@ -347,6 +497,8 @@ class ZipPlugin(JmOptionPlugin):
347
497
  level = 'album' if album is not None else 'photo'
348
498
  self.level = level
349
499
  self.delete_original_file = delete_original_file
500
+ # 未开启 strict_dependencies 时也拦掉非法的 encrypt 类型
501
+ encrypt = self.check_encrypt_param(encrypt)
350
502
 
351
503
  # 确保压缩文件所在文件夹存在
352
504
  zip_dir = JmcomicText.parse_to_abspath(zip_dir)
@@ -927,6 +1079,7 @@ class AsyncProgressDownloader(JmAsyncDownloader):
927
1079
 
928
1080
  class DownloadProgressPlugin(JmOptionPlugin):
929
1081
  plugin_key = 'download_progress'
1082
+ plugin_dependencies = ('rich',)
930
1083
  log_file = 'jmcomic-download.log'
931
1084
 
932
1085
  @staticmethod
@@ -1036,6 +1189,7 @@ class DownloadProgressPlugin(JmOptionPlugin):
1036
1189
 
1037
1190
  class AutoSetBrowserCookiesPlugin(JmOptionPlugin):
1038
1191
  plugin_key = 'auto_set_browser_cookies'
1192
+ plugin_dependencies = ('browser_cookie3',)
1039
1193
 
1040
1194
  accepted_cookies_keys = str_to_set('''
1041
1195
  yuo1
@@ -1097,13 +1251,18 @@ class FavoriteFolderExportPlugin(JmOptionPlugin):
1097
1251
  zip_filepath=None,
1098
1252
  zip_password=None,
1099
1253
  delete_original_file=False,
1254
+ max_retry=2,
1100
1255
  ):
1101
1256
  self.save_dir = os.path.abspath(save_dir if save_dir is not None else (os.getcwd() + '/export/'))
1102
1257
  self.zip_enable = zip_enable
1103
1258
  self.zip_filepath = os.path.abspath(zip_filepath)
1104
1259
  self.zip_password = zip_password
1105
1260
  self.delete_original_file = delete_original_file
1261
+ # max_retry 表示「首次失败后的重试次数」,所以总尝试次数是 max_retry + 1。
1262
+ # 允许配 0 表示不重试(只尝试一次),不要把它强行抬成 1。
1263
+ self.max_retry = max(0, int(max_retry))
1106
1264
  self.files = []
1265
+ self.failed_folders = []
1107
1266
 
1108
1267
  mkdir_if_not_exists(self.save_dir)
1109
1268
  mkdir_if_not_exists(of_dir_path(self.zip_filepath))
@@ -1127,34 +1286,81 @@ class FavoriteFolderExportPlugin(JmOptionPlugin):
1127
1286
  apply_each_obj_func=bind_jm_task_context(self.handle_folder),
1128
1287
  )
1129
1288
 
1130
- if not self.zip_enable:
1131
- return
1289
+ # 压缩导出的文件(放在失败检查之前:即便有收藏夹失败,
1290
+ # 已经成功抓下来的那部分也应该照常打包,不能因为一个收藏夹失败就丢掉整批数据)
1291
+ if self.zip_enable:
1292
+ self.require_param(self.zip_filepath, '如果开启zip,请指定zip_filepath参数(压缩文件保存路径)')
1132
1293
 
1133
- # 压缩导出的文件
1134
- self.require_param(self.zip_filepath, '如果开启zip,请指定zip_filepath参数(压缩文件保存路径)')
1294
+ if self.zip_password is None:
1295
+ self.zip_folder_without_password(self.files, self.zip_filepath)
1296
+ else:
1297
+ self.zip_with_password(self.files, self.zip_filepath)
1135
1298
 
1136
- if self.zip_password is None:
1137
- self.zip_folder_without_password(self.files, self.zip_filepath)
1138
- else:
1139
- self.zip_with_password()
1299
+ self.execute_deletion(self.files)
1140
1300
 
1141
- self.execute_deletion(self.files)
1301
+ # 汇总导出失败的收藏夹,避免数据静默缺失
1302
+ self.raise_if_failed_folders()
1142
1303
 
1143
1304
  def handle_folder(self, fid: str, fname: str):
1144
1305
  self.log(f'【收藏夹: {fname}, fid: {fid}】开始获取数据')
1145
1306
 
1146
- # 获取收藏夹数据
1147
- page_data = self.fetch_folder_page_data(fid)
1307
+ # 第 0 次是首次尝试,之后每次都是重试;总共 1 + max_retry 次
1308
+ for attempt in range(self.max_retry + 1):
1309
+ try:
1310
+ # 获取收藏夹数据
1311
+ page_data = self.fetch_folder_page_data(fid)
1312
+
1313
+ # 序列化到文件
1314
+ filepath = self.save_folder_page_data_to_file(page_data, fid, fname)
1315
+ except Exception as e:
1316
+ # 单个收藏夹失败不应该中断其他收藏夹,
1317
+ # 但也不能无声无息地丢掉这份数据,这里记录并在结束后统一汇报
1318
+ self.log(f'【收藏夹: {fname}, fid: {fid}】第 {attempt + 1}/{self.max_retry + 1} 次获取失败: [{e}]')
1319
+
1320
+ if attempt >= self.max_retry:
1321
+ self.failed_folders.append((fid, fname, e))
1322
+ return
1323
+
1324
+ self.retry_backoff(attempt + 1)
1325
+ continue
1326
+
1327
+ if filepath is None:
1328
+ self.log(f'【收藏夹: {fname}, fid: {fid}】收藏夹无数据')
1329
+ return
1330
+
1331
+ self.log(f'【收藏夹: {fname}, fid: {fid}】保存文件成功 → [{filepath}]')
1332
+ self.files.append(filepath)
1333
+ return
1334
+
1335
+ # noinspection PyMethodMayBeStatic
1336
+ def retry_backoff(self, attempt: int):
1337
+ """
1338
+ 重试前的等待,避免短时间内反复请求加剧服务端限流。
1339
+
1340
+ :param attempt: 当前是第几次尝试(从 1 开始)
1341
+ """
1342
+ import time
1148
1343
 
1149
- # 序列化到文件
1150
- filepath = self.save_folder_page_data_to_file(page_data, fid, fname)
1344
+ # attempt 从 1 开始,首次重试等 2s,之后 4s、8s,上限 10s
1345
+ time.sleep(min(2 ** attempt, 10))
1151
1346
 
1152
- if filepath is None:
1153
- self.log(f'【收藏夹: {fname}, fid: {fid}】收藏夹无数据')
1347
+ def raise_if_failed_folders(self):
1348
+ """
1349
+ 导出结束后统一检查失败的收藏夹。
1350
+
1351
+ 收藏夹数据量大、耗时长时,登录态可能在服务端被提前过期,
1352
+ 导致个别收藏夹抓取失败;这类失败此前会被静默吞掉,导出的结果看起来
1353
+ 是成功的、实际却缺了数据。这里抛出运行时异常,交由 option 的 safe
1354
+ 策略决定记录后继续或向外抛出,不走参数校验的 valid 策略。
1355
+ """
1356
+ if not self.failed_folders:
1154
1357
  return
1155
1358
 
1156
- self.log(f'【收藏夹: {fname}, fid: {fid}】保存文件成功 → [{filepath}]')
1157
- self.files.append(filepath)
1359
+ detail = '、'.join(f'【{fname}】(fid={fid})' for fid, fname, _ in self.failed_folders)
1360
+ msg = (f'以下 {len(self.failed_folders)} 个收藏夹导出失败(已重试 {self.max_retry} 次): {detail}。'
1361
+ f'可稍后重新执行导出以补全这部分数据。')
1362
+ self.log(msg)
1363
+ ExceptionTool.raises(msg)
1158
1364
 
1159
1365
  def fetch_folder_page_data(self, fid):
1160
1366
  # 一页一页获取,不使用并行
@@ -1196,11 +1402,31 @@ class FavoriteFolderExportPlugin(JmOptionPlugin):
1196
1402
  for file in files:
1197
1403
  zipf.write(file, arcname=of_file_name(file))
1198
1404
 
1199
- def zip_with_password(self):
1200
- # 构造shell命令
1405
+ def zip_with_password(self, files, zip_path):
1406
+ """
1407
+ 用 7z 打包指定文件并加密。
1408
+
1409
+ 只打包传入的 files,不打包整个 save_dir:否则会连上一轮遗留的旧导出、
1410
+ 以及失败收藏夹写了一半的 csv 一起塞进包里,而这些文件并不在
1411
+ execute_deletion 的删除范围内,等于往产物里混入无关数据。
1412
+
1413
+ :param files: 要压缩的文件的绝对路径的列表
1414
+ :param zip_path: 压缩文件的保存路径
1415
+ """
1416
+ # 未指定输入文件时,7z 会默认打包整个目录。
1417
+ if not files:
1418
+ return
1419
+
1420
+ import shlex
1421
+
1422
+ # 在 save_dir 中逐个列举本次成功导出的文件。
1423
+ file_args = ' '.join(
1424
+ shlex.quote(of_file_name(f)) for f in files
1425
+ )
1426
+
1201
1427
  cmd_list = f'''
1202
1428
  cd {self.save_dir}
1203
- 7z a "{self.zip_filepath}" "./" -p{self.zip_password} -mhe=on > "../7z_output.txt"
1429
+ 7z a "{zip_path}" {file_args} -p{self.zip_password} -mhe=on > "../7z_output.txt"
1204
1430
 
1205
1431
  '''
1206
1432
  self.log(f'运行命令: {cmd_list}')
@@ -1211,6 +1437,14 @@ class FavoriteFolderExportPlugin(JmOptionPlugin):
1211
1437
 
1212
1438
  class Img2pdfPlugin(JmOptionPlugin):
1213
1439
  plugin_key = 'img2pdf'
1440
+ # img2pdf 总是需要;pikepdf 仅在加密 pdf 时需要
1441
+ plugin_dependencies = ('img2pdf',)
1442
+
1443
+ @classmethod
1444
+ def required_dependencies_for(cls, kwargs: dict) -> tuple:
1445
+ if kwargs.get('encrypt'):
1446
+ return cls.plugin_dependencies + ('pikepdf',)
1447
+ return cls.plugin_dependencies
1214
1448
 
1215
1449
  def invoke(self,
1216
1450
  photo: JmPhotoDetail = None,
@@ -1846,3 +2080,78 @@ class DownloadCoverPlugin(JmOptionPlugin):
1846
2080
  self.log(f'album-{album_id}的封面已存在,跳过下载: [{save_path}]', 'skip')
1847
2081
  return
1848
2082
  downloader.client.download_album_cover(album_id, save_path, size)
2083
+
2084
+
2085
+ class CalibreMetadataPlugin(JmOptionPlugin):
2086
+ """
2087
+ 功能:为本子生成 Calibre 可识别的元数据文件 metadata.opf。
2088
+
2089
+ 通常挂在 after_album 上,每个本子在其目录下生成一份 metadata.opf,
2090
+ Calibre 导入(从 OPF 读元数据)时可以自动带上书名、作者、标签、简介和封面。
2091
+
2092
+ OPF 的生成逻辑由 jmcomic-calibre 提供,
2093
+ 避免同一份 XML 拼接逻辑在两处各维护一份。
2094
+
2095
+ 配置示例:
2096
+
2097
+ ```yml
2098
+ plugins:
2099
+ after_album:
2100
+ - plugin: calibre_metadata
2101
+ kwargs:
2102
+ dir_rule:
2103
+ rule: "Bd/Aid/metadata.opf"
2104
+ base_dir: "./"
2105
+ include_cover: true
2106
+ fields: # 追加静态字段
2107
+ language: "zh"
2108
+ ```
2109
+
2110
+ 说明:
2111
+ - identifier 固定写为 jmcomic:{album_id},可在 Calibre 中反查回禁漫的 album_id
2112
+ - fields 中的 title/author 可覆盖默认取值,其余键值对须为 Dublin Core 元素名(如 language/publisher/date),按 dc:{key} 写入,不支持的键会忽略并告警
2113
+ - include_cover 依赖 downloader(after_album 阶段自动传入)
2114
+ """
2115
+ plugin_key = 'calibre_metadata'
2116
+ plugin_dependencies = (('jmcomic_calibre', 'jmcomic-calibre'),)
2117
+
2118
+ def invoke(self,
2119
+ dir_rule: dict,
2120
+ album: JmAlbumDetail = None,
2121
+ photo: JmPhotoDetail = None,
2122
+ downloader=None,
2123
+ include_cover=False,
2124
+ fields=None,
2125
+ **kwargs) -> None:
2126
+ self.require_param(album, '本插件需在after_album阶段使用,需要album参数')
2127
+
2128
+ try:
2129
+ import jmcomic_calibre
2130
+ except ImportError:
2131
+ self.warning_lib_not_install('jmcomic-calibre')
2132
+ return
2133
+
2134
+ opf_path = self.decide_filepath(album, photo, None, None, None, dir_rule)
2135
+
2136
+ # 处理封面下载
2137
+ if include_cover:
2138
+ cover_path = os.path.join(os.path.dirname(opf_path), 'cover.jpg')
2139
+ self.download_cover_if_needed(album.id, cover_path, downloader)
2140
+
2141
+ jmcomic_calibre.export_opf(
2142
+ album=album,
2143
+ opf_path=opf_path,
2144
+ fields=fields,
2145
+ include_cover=include_cover,
2146
+ on_ignored=lambda key, allowed: self.log(
2147
+ f'calibre_metadata: 忽略不支持的fields字段 [{key}],'
2148
+ f'仅支持Dublin Core元素: {", ".join(sorted(allowed))}', 'warning'),
2149
+ )
2150
+ self.log(f'已生成Calibre元数据文件 → [{opf_path}]')
2151
+
2152
+ def download_cover_if_needed(self, album_id: str, cover_path: str, downloader):
2153
+ if self.option.download.cache and os.path.exists(cover_path):
2154
+ self.log(f'album-{album_id}的封面已存在,跳过下载: [{cover_path}]', 'skip')
2155
+ return
2156
+ self.require_param(downloader, 'include_cover=true时需要downloader参数(after_album阶段会自动传入)')
2157
+ downloader.client.download_album_cover(album_id, cover_path, '')
@@ -1,3 +1,4 @@
1
+ from datetime import datetime
1
2
  from html.parser import HTMLParser
2
3
  from urllib.parse import unquote, urlparse
3
4
 
@@ -61,6 +62,13 @@ class JmcomicText:
61
62
  pattern_html_album_views = compile(r'<span>(.*?)</span>\n *<span>(次觀看|观看次数|次观看次数)</span>')
62
63
  # 評論(div)
63
64
  pattern_html_album_comment_count = compile(r'<div class="badge"[^>]*?id="total_video_comments">(\d+)</div>'), 0
65
+ # 是否已收藏 (HTML端通过主本子收藏按钮带有 btn-primary 判定)
66
+ pattern_html_album_is_favorite = compile(
67
+ r'<a\s+[^>]*?(id="album_favorite_\d+"[^>]*?class="[^"]*?'
68
+ r'\bbtn-primary\b|class="[^"]*?\bbtn-primary\b[^>]*?id="album_favorite_\d+)[^>]*?>'), False
69
+ # 是否已点赞/喜欢 (HTML端通过顶栏爱心按钮带有 style="color:red" 判定)
70
+ pattern_html_album_liked = compile(
71
+ r'id=[\'"]love_likes_\d+[\'"][^>]*>\s*<i[^>]+style=[\'"][^\'"]*color:\s*(red)[^\'"]*[\'"]'), False
64
72
 
65
73
  # 提取接口返回值信息
66
74
  pattern_ajax_favorite_msg = compile(r'</button>(.*?)</div>')
@@ -68,6 +76,8 @@ class JmcomicText:
68
76
  pattern_api_response_json_object = compile(r'\{[\s\S]*?}')
69
77
 
70
78
  pattern_html_comment_next_page = compile(r'id=["\']p_album_comments_\d+_(\d+)["\']')
79
+ # 网页端签到活动ID (data-dailyid)
80
+ pattern_html_daily_id = compile(r'data-dailyid="(\d+)"')
71
81
 
72
82
  @classmethod
73
83
  def parse_to_jm_domain(cls, text: str):
@@ -140,6 +150,19 @@ class JmcomicText:
140
150
  JmModuleConfig.album_class()
141
151
  )
142
152
 
153
+ @classmethod
154
+ def parse_daily_id(cls, html: str, default=None) -> Optional[str]:
155
+ """
156
+ 从网页文本(如禁漫首页)中提取每日签到活动 ID(data-dailyid)
157
+ """
158
+ return PatternTool.match_or_default(
159
+ html,
160
+ cls.pattern_html_daily_id,
161
+ default,
162
+ )
163
+
164
+ parse_html_daily_id = parse_daily_id
165
+
143
166
  @classmethod
144
167
  def reflect_new_instance(cls, html: str, cls_field_prefix: str, clazz: type):
145
168
 
@@ -948,6 +971,8 @@ class JmApiAdaptTool:
948
971
  'related_list',
949
972
  'name',
950
973
  'description',
974
+ 'is_favorite',
975
+ 'liked',
951
976
  ('id', 'album_id'),
952
977
  ('author', 'authors'),
953
978
  ('total_views', 'views'),
@@ -1003,7 +1028,10 @@ class JmApiAdaptTool:
1003
1028
  (chapter.id, chapter.sort, chapter.name)
1004
1029
  )
1005
1030
  fields['episode_list'] = episode_list
1006
- for it in 'scramble_id', 'page_count', 'pub_date', 'update_date':
1031
+ fields['page_count'] = int(data['total_photos'])
1032
+ fields['pub_date'] = datetime.fromtimestamp(int(data['addtime'])).strftime('%Y-%m-%d')
1033
+
1034
+ for it in 'scramble_id', 'update_date':
1007
1035
  fields[it] = '0'
1008
1036
 
1009
1037
  @classmethod
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: jmcomic
3
- Version: 2.7.6
3
+ Version: 2.7.7
4
4
  Summary: Python API For JMComic (禁漫天堂)
5
5
  Home-page: https://github.com/hect0x7/JMComic-Crawler-Python
6
6
  Author: hect0x7
@@ -50,6 +50,14 @@ Requires-Dist: curl-cffi
50
50
  Requires-Dist: pillow
51
51
  Requires-Dist: pycryptodome
52
52
  Requires-Dist: pyyaml
53
+ Provides-Extra: plugins
54
+ Requires-Dist: img2pdf; extra == "plugins"
55
+ Requires-Dist: pikepdf; extra == "plugins"
56
+ Requires-Dist: psutil; extra == "plugins"
57
+ Requires-Dist: py7zr; extra == "plugins"
58
+ Requires-Dist: pyzipper; extra == "plugins"
59
+ Requires-Dist: rich; extra == "plugins"
60
+ Requires-Dist: browser_cookie3; extra == "plugins"
53
61
  Dynamic: author
54
62
  Dynamic: home-page
55
63
  Dynamic: license-file
@@ -305,10 +313,7 @@ jmv 350234 -y
305
313
  - 支持自定义本子/章节/图片下载前后事件的回调函数
306
314
  - 支持自定义类:`Downloader(负责调度)` `Option(负责配置)` `Client(负责请求)` `实体类`等
307
315
  - 支持自定义日志、异常监听器
308
- - **支持Plugin插件,可以方便地扩展功能,以及使用别人的插件,目前核心内置插件有**:
309
- - `登录插件`、`只下载新章插件`、`导出收藏夹为csv文件插件`
310
- - `合并所有图片为pdf文件插件`、`合并所有图片为长图png插件`
311
- - `压缩文件插件`、`自动获取浏览器cookies插件`、`订阅更新插件`等
316
+ - **支持 Plugin 扩展,目前内置 21 个实用插件,包括**:`美观下载进度条`、`图片合并 PDF`、`一图流长图拼接`、`生成zip/7z压缩包`、`浏览器 Cookie 获取`、`订阅更新`、`收藏夹导出`、`封面下载`等。
312
317
 
313
318
  ## 使用小说明
314
319
 
@@ -0,0 +1,14 @@
1
+ commonx>=0.6.38
2
+ curl-cffi
3
+ pillow
4
+ pycryptodome
5
+ pyyaml
6
+
7
+ [plugins]
8
+ img2pdf
9
+ pikepdf
10
+ psutil
11
+ py7zr
12
+ pyzipper
13
+ rich
14
+ browser_cookie3
@@ -1,5 +0,0 @@
1
- commonx>=0.6.38
2
- curl-cffi
3
- pillow
4
- pycryptodome
5
- pyyaml
File without changes
File without changes
File without changes
File without changes
File without changes