funread 1.0.1__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.
funread-1.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2023] [niuliangtao]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
funread-1.0.1/PKG-INFO ADDED
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.1
2
+ Name: funread
3
+ Version: 1.0.1
4
+ Summary:
5
+ Author: farfun
6
+ Author-email: 1007530194@qq.com
7
+ Requires-Python: >=3.8,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.8
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Description-Content-Type: text/markdown
15
+
16
+ # 阅读
17
+
18
+ [源仓库](http://www.yckceo1.com/)
19
+
20
+ [规则说明](https://alanskycn.gitee.io/teachme/)
21
+
22
+ [app端](https://github.com/gedoor/legado)
23
+
24
+ [服务端](https://github.com/hectorqin/reader)
25
+
@@ -0,0 +1,9 @@
1
+ # 阅读
2
+
3
+ [源仓库](http://www.yckceo1.com/)
4
+
5
+ [规则说明](https://alanskycn.gitee.io/teachme/)
6
+
7
+ [app端](https://github.com/gedoor/legado)
8
+
9
+ [服务端](https://github.com/hectorqin/reader)
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = [ "poetry-core",]
3
+ build-backend = "poetry.core.masonry.api"
4
+
5
+ [tool.poetry]
6
+ name = "funread"
7
+ version = "1.0.1"
8
+ description = ""
9
+ authors = [ "farfun <1007530194@qq.com>",]
10
+ readme = "README.md"
11
+ [[tool.poetry.packages]]
12
+ from = "src"
13
+ include = "*"
14
+
15
+ [tool.poetry.dependencies]
16
+ python = "^3.8"
File without changes
File without changes
File without changes
@@ -0,0 +1,4 @@
1
+ from .base import DownloadSource
2
+ from .book import BookSourceFormat,BookSourceDownload
3
+ from.generate import GenerateSourceTask
4
+ from .rss import RSSSourceDownload
@@ -0,0 +1,178 @@
1
+ import json
2
+ import os
3
+ from datetime import datetime
4
+ import traceback
5
+ import pandas as pd
6
+ import requests
7
+ from funfile import pickle, funos
8
+ from funfile.compress import tarfile
9
+ from funread.legado.manage.utils import url_to_hostname
10
+ from funsecret import get_md5_str
11
+ from tqdm import tqdm
12
+
13
+
14
+ class DownloadSource(object):
15
+ def __init__(self, path="./funread-hub", cate1="rss", *args, **kwargs):
16
+ self.cate1 = cate1
17
+ self.path_rot = f"{path}/{cate1}"
18
+ self.path_bak = f"{path}/{cate1}/bak"
19
+ self.path_pkl = f"{path}/{cate1}/pkl"
20
+ self.path_bok = f"{path}/{cate1}/source"
21
+ self.pkl_url = f"{self.path_pkl}/url_info.pkl.bz2"
22
+ self.pkl_md5 = f"{self.path_pkl}/source_info.pkl.bz2"
23
+
24
+ self.url_map = {}
25
+ self.md5_set = {}
26
+ self.current_id = 1
27
+
28
+ funos.makedirs(self.path_bak)
29
+ funos.makedirs(self.path_bok)
30
+ funos.makedirs(self.path_pkl)
31
+
32
+ def loads(self):
33
+ print("loads")
34
+ if os.path.exists(self.pkl_url):
35
+ df = pd.read_pickle(self.pkl_url, compression="infer")
36
+ self.url_map = {k: v for k, v in df.values}
37
+ else:
38
+ self.url_map = {"https://farfarfun.github.com": 100000}
39
+ self.current_id = max(self.url_map.values())
40
+ if os.path.exists(self.pkl_md5):
41
+ df = pd.read_pickle(self.pkl_md5, compression="infer")
42
+ self.md5_set = {info["md5"]: info for info in df.to_dict(orient="records")}
43
+
44
+ def dumps(self):
45
+ print("dumps")
46
+
47
+ df = pd.DataFrame([{"url": k, "url_id": v} for k, v in self.url_map.items()])
48
+ df.to_pickle(self.pkl_url, compression="infer")
49
+
50
+ df = pd.DataFrame(self.md5_set.values())
51
+ df.to_pickle(self.pkl_md5, compression="infer")
52
+
53
+ def url_index(self, url):
54
+ if url in self.url_map:
55
+ return self.url_map[url]
56
+ else:
57
+ self.current_id += 1
58
+ self.url_map[url] = self.current_id
59
+ return self.current_id
60
+
61
+ def source_format(self, source):
62
+ pass
63
+
64
+ def add_source(self, source, *args, **kwargs):
65
+ md5 = get_md5_str(json.dumps(source))
66
+ source = self.source_format(source)
67
+ hostname = url_to_hostname(source["sourceUrl"])
68
+ if hostname is None:
69
+ return
70
+ url_id = self.url_index(hostname)
71
+
72
+ cate1 = (url_id // 100) * 100
73
+ fdir = f"{self.path_bok}/{cate1}-{cate1 + 100}/"
74
+ if not os.path.exists(fdir):
75
+ os.makedirs(fdir)
76
+ fpath = f"{fdir}/{url_id}.json"
77
+
78
+ url_info = {"url_id": url_id, "hostname": hostname, "cate1": cate1}
79
+ self.add_source_to_candidate(md5, fpath, source, url_info=url_info)
80
+
81
+ self.md5_set[md5] = {
82
+ "md5": md5,
83
+ "url_id": url_id,
84
+ "hostname": hostname,
85
+ "cate1": cate1,
86
+ }
87
+
88
+ def add_sources(self, data, *args, **kwargs):
89
+ """"""
90
+ if isinstance(data, str):
91
+ if data.startswith("http"):
92
+ data = requests.get(data).json()
93
+ elif os.path.exists(data):
94
+ data = pickle.load(data)
95
+ elif data[0] == "[" or data[0] == "{":
96
+ data = json.loads(data)
97
+
98
+ for source in tqdm(data):
99
+ try:
100
+ self.add_source(source, *args, **kwargs)
101
+ except Exception as e:
102
+ # traceback.print_exc()
103
+ # print(e)
104
+ pass
105
+
106
+ def add_source_to_candidate(self, md5, fpath, source, url_info=None):
107
+ url_info = url_info or {}
108
+ if os.path.exists(fpath):
109
+ data = json.loads(open(fpath, "r").read())
110
+ else:
111
+ data = {
112
+ "available": True,
113
+ "merged": [],
114
+ "candidate": [],
115
+ "url_id": url_info["url_id"],
116
+ "hostname": url_info["hostname"],
117
+ }
118
+ md5_list = []
119
+ [
120
+ [md5_list.extend(md5["md5_list"]) for md5 in data[key]]
121
+ for key in ("merged", "candidate")
122
+ if key in data
123
+ ]
124
+ if md5 not in md5_list:
125
+ data["candidate"].append({"md5_list": [md5], "source": source})
126
+
127
+ with open(fpath, "w") as fw:
128
+ fw.write(json.dumps(data, sort_keys=True, indent=4))
129
+
130
+ def export_sources(self, size=1000):
131
+ file_list = []
132
+ for root, dirs, files in os.walk(self.path_bok):
133
+ for file in files:
134
+ if file.endswith(".json"):
135
+ file_list.append(os.path.join(root, file))
136
+ dd = []
137
+ for file in tqdm(file_list):
138
+ data = open(file, "r").read()
139
+ data = json.loads(data)
140
+ if not data.get("available", True):
141
+ continue
142
+ for key in ("candidate", "merged"):
143
+ for item in data[key][:3]:
144
+ source = item["source"]
145
+ source["sourceUrl"] = (
146
+ f"{source['sourceUrl']}#{item['md5_list'][0][:10]}"
147
+ )
148
+ dd.append(source)
149
+ if len(dd) >= size:
150
+ yield dd
151
+ dd = []
152
+ yield dd
153
+
154
+ def loads_zip(self, zip_file=None):
155
+ funos.delete(self.path_pkl)
156
+ funos.delete(self.path_bok)
157
+ if zip_file is None:
158
+ files = os.listdir(self.path_bak)
159
+ files.sort(key=lambda x: x)
160
+ zip_file = os.path.join(self.path_bak, files[-1])
161
+ print(f"load zip file from {zip_file}")
162
+ with tarfile.open(zip_file, "r") as tar:
163
+ tar.extractall(self.path_rot)
164
+ self.loads()
165
+
166
+ def dumps_zip(self):
167
+ self.dumps()
168
+ zip_file = f"{self.path_bak}/{self.cate1}-{datetime.now().strftime('%Y%m%d-%H%M%S')}.tar.xz"
169
+ with tarfile.open(zip_file, "w|xz") as tar:
170
+ tar.add(self.path_pkl, arcname=os.path.basename(self.path_pkl))
171
+ tar.add(self.path_bok, arcname=os.path.basename(self.path_bok))
172
+
173
+ def __enter__(self):
174
+ self.loads()
175
+ return self
176
+
177
+ def __exit__(self, exc_type, exc_val, exc_tb):
178
+ self.dumps()
@@ -0,0 +1,121 @@
1
+ import re
2
+
3
+ from funread.legado.manage.download.base import DownloadSource
4
+
5
+
6
+ def retain_zh_ch_dig(text):
7
+ return re.sub("[^\u4e00-\u9fa5a-zA-Z0-9\[\]]+", "", text)
8
+
9
+
10
+ class BookSourceFormat:
11
+ def __init__(self, source):
12
+
13
+ self.source = source
14
+ self.source["bookSourceComment"] = ""
15
+ self.source["bookSourceUrl"] = self.source["bookSourceUrl"].rstrip("/|#")
16
+ if "httpUserAgent" in self.source.keys():
17
+ self.source["header"] = self.source.pop("httpUserAgent")
18
+
19
+ for key in ["bookSourceGroup", "bookSourceName"]:
20
+ self.source[key] = retain_zh_ch_dig(self.source.get(key, ""))
21
+
22
+ def run(self):
23
+ self.format_book_info()
24
+ self.format_content()
25
+ self.format_search()
26
+ self.format_explore()
27
+ self.format_toc()
28
+ keys = [key for key in self.source.keys() if not self.source[key]]
29
+ for key in keys:
30
+ self.source.pop(key)
31
+
32
+ for key in ['customOrder','respondTime','lastUpdateTime']:
33
+ self.source.pop(key)
34
+
35
+ for key in ['searchUrl','exploreUrl']:
36
+ if key in self.source.keys():
37
+ self.source[key]=self.source[key].replace(self.source['bookSourceUrl'],'')
38
+ return self.source
39
+
40
+ def __format_base(self, group, map):
41
+ book_info = self.source.get(group, {})
42
+
43
+ for key, name in map.items():
44
+ if key not in self.source:
45
+ continue
46
+ value = self.source.pop(key)
47
+ if value:
48
+ book_info[name] = value
49
+ if len(book_info) > 0:
50
+ self.source[group] = book_info
51
+
52
+ def format_book_info(self):
53
+ map = {
54
+ "ruleBookAuthor": "author",
55
+ "ruleBookContent": "content",
56
+ "ruleBookContentReplace": "contentReplace",
57
+ "ruleBookInfoInit": "init",
58
+ "ruleBookKind": "kind",
59
+ "ruleBookLastChapter": "lastChapter",
60
+ "ruleBookName": "name",
61
+ "ruleBookUrlPattern": "urlPattern",
62
+ "ruleBookWordCount": "wordCount",
63
+ }
64
+ self.__format_base("ruleBookInfo", map)
65
+
66
+ def format_content(self):
67
+ map = {
68
+ "ruleContentUrl": "url",
69
+ "ruleContentUrlNext": "urlNext",
70
+ "ruleBookContentReplaceRegex": "replaceRegex",
71
+ "ruleBookContentSourceRegex": "sourceRegex",
72
+ "ruleBookContentWebJs": "webJs",
73
+ }
74
+ self.__format_base("ruleContent", map)
75
+
76
+ def format_search(self):
77
+ map = {
78
+ "ruleSearchUrl": "url",
79
+ "ruleSearchName": "name",
80
+ "ruleSearchAuthor": "author",
81
+ "ruleSearchList": "bookList",
82
+ "ruleSearchCoverUrl": "coverUrl",
83
+ "ruleSearchIntroduce": "intro",
84
+ "ruleSearchKind": "kind",
85
+ "ruleSearchLastChapter": "lastChapter",
86
+ "ruleSearchNoteUrl": "noteUrl",
87
+ "ruleSearchWordCount": "wordCount",
88
+ }
89
+ self.__format_base("ruleSearch", map)
90
+
91
+ def format_explore(self):
92
+ map = {
93
+ "ruleFindUrl": "url",
94
+ "ruleFindName": "name",
95
+ "ruleFindAuthor": "author",
96
+ "ruleFindList": "bookList",
97
+ "ruleFindCoverUrl": "coverUrl",
98
+ "ruleFindIntroduce": "intro",
99
+ "ruleFindKind": "kind",
100
+ "ruleFindLastChapter": "lastChapter",
101
+ "ruleFindNoteUrl": "noteUrl",
102
+ }
103
+ self.__format_base("ruleExplore", map)
104
+
105
+ def format_toc(self):
106
+ map = {
107
+ "ruleChapterList": "chapterList",
108
+ "ruleChapterName": "chapterName",
109
+ "ruleChapterUpdateTime": "updateTime",
110
+ "ruleChapterUrl": "chapterUrl",
111
+ "ruleChapterUrlNext": "nextTocUrl",
112
+ }
113
+ self.__format_base("ruleToc", map)
114
+
115
+
116
+ class BookSourceDownload(DownloadSource):
117
+ def __init__(self, *args, **kwargs):
118
+ super().__init__(*args, **kwargs)
119
+
120
+ def source_format(self, source):
121
+ return BookSourceFormat(source).run()
@@ -0,0 +1,187 @@
1
+ from datetime import datetime
2
+
3
+ from dominate.tags import *
4
+ from fundrive import GithubDrive
5
+ from funfile import funos
6
+ from funread.legado.manage.download.rss import RSSSourceDownload
7
+ from funsecret import read_secret
8
+ from funtask import Task
9
+
10
+ """
11
+ dominate example: https://blog.csdn.net/wumingxiaoyao/article/details/122894671
12
+ """
13
+
14
+
15
+ class GenerateCommon:
16
+ def generate_build_repo(self, category, repo):
17
+ with li(category + ":"):
18
+ a("github", href=f"https://github.com/{repo}")
19
+ a("gitee", href=f"https://gitee.com/{repo}")
20
+ a("gitlink", href=f"https://gitlink.org.cn/{repo}")
21
+
22
+ def generate_org(self):
23
+ build_type_div = div()
24
+ build_type_fond = b()
25
+ build_type_fond += font("farfarfun")
26
+ build_type_div += build_type_fond
27
+ with ul():
28
+ self.generate_build_repo("funsecret", "farfarfun/funsecret")
29
+ self.generate_build_repo("fundrive", "farfarfun/fundrive")
30
+ self.generate_build_repo("funread", "farfarfun/funread")
31
+ with li("订阅源:"):
32
+ a("github",
33
+ href="yuedu://rssSource/importonline?src=https://github.com/farfarfun/funread-cache/raw/master/funread/legado/rss/rss-main.json")
34
+ a("gitee",
35
+ href="yuedu://rssSource/importonline?src=https://gitee.com/farfarfun/funread-cache/raw/master/funread/legado/rss/rss-main.json")
36
+ a("gitlink",
37
+ href="yuedu://rssSource/importonline?src=https://gitlink.org.cn/farfarfun/funread-cache/raw/master/funread/legado/rss/rss-main.json")
38
+
39
+ def generate(self):
40
+ br()
41
+ div(b(font("Build Information", color="#0B610B")))
42
+ div(hr(size=2, alignment="center", width="100%"))
43
+ div((b(font("Cause: Started by upstream pipeline job "))))
44
+ self.generate_org()
45
+ img(src="https://profile-avatar.csdnimg.cn/2e9aaf5666c044d7aa273e086f9878d0_n1007530194.jpg")
46
+ br()
47
+ p("** This is an automatically generated email by jenkins job. **")
48
+ p("Feel free to connect 1007530194@qq.com if you have any question.")
49
+ p(f'update time: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
50
+
51
+
52
+ class GenerateSourceType:
53
+ style_applied = """
54
+ body{
55
+ font-family: verdana,arial,sans-serif;
56
+ font-size:11px;
57
+ }
58
+ table.gridtable {
59
+ color: #333333;
60
+ border-width: 1px;
61
+ border-color: #666666;
62
+ border-collapse: collapse;
63
+ font-size:11px;
64
+ }
65
+ table.gridtable th {
66
+ border-width: 1px;
67
+ padding: 8px;
68
+ border-style: solid;
69
+ border-color: #666666;
70
+ background-color: #DDEBF7;
71
+ }
72
+ table.gridtable td {
73
+ border-width: 1px;
74
+ padding: 8px;
75
+ border-style: solid;
76
+ border-color: #666666;
77
+ background-color: #ffffff;
78
+ text-align:center;
79
+ }
80
+ table.gridtable td.failed {
81
+ color:#ED5F5F;
82
+ }
83
+ table.gridtable td.passrate {
84
+ font-weight:bold;
85
+ color:green;
86
+ }
87
+ li {
88
+ margin-top:5px;
89
+ }
90
+ div{
91
+ margin-top:10px;
92
+ }
93
+ """
94
+
95
+ def __init__(self, dir_path="funread/legado/book/snapshot/20231011", source_type="booksource"):
96
+ self.repo_str = "farfarfun/funread-cache"
97
+ self.dir_path = dir_path
98
+ self.source_type = source_type
99
+ self.drive = GithubDrive()
100
+ self.drive.login(repo_str=self.repo_str)
101
+
102
+ def set_table_head(self):
103
+ with tr():
104
+ th("文件")
105
+ th("大小")
106
+ th("github")
107
+ th("gitee")
108
+
109
+ def fill_table_data(self, file):
110
+ data_tr = tr()
111
+ data_tr += td(file["name"])
112
+ data_tr += td(file["size"])
113
+ link_td = td()
114
+ link_td += a(
115
+ "github",
116
+ href=f"yuedu://{self.source_type}/importonline?src=https://github.com/{self.repo_str}/raw/master/{file['path']}",
117
+ )
118
+ data_tr += link_td
119
+ link_td = td()
120
+ link_td += a(
121
+ "gitee",
122
+ href=f"yuedu://{self.source_type}/importonline?src=https://gitee.com/{self.repo_str}/raw/master/{file['path']}",
123
+ )
124
+ data_tr += link_td
125
+
126
+ def generate_table(self):
127
+ result_div = div(id="test case result")
128
+ with result_div.add(table(cls="gridtable")).add(tbody()):
129
+ self.set_table_head()
130
+
131
+ files = self.drive.get_file_list(self.dir_path)
132
+ for file in files:
133
+ if file["name"].endswith(".json"):
134
+ self.fill_table_data(file)
135
+
136
+ def generate_html_report(self):
137
+ html_root = html()
138
+ # html head
139
+ with html_root.add(head()):
140
+ style(self.style_applied, type="text/css")
141
+
142
+ # html body
143
+ with html_root.add(body()):
144
+ hello_div = div(id="hello")
145
+ hello_div.add(p("Hi All,"))
146
+ hello_div.add(p("This is today's " " API Test Report in "))
147
+ self.generate_table()
148
+ GenerateCommon().generate()
149
+
150
+ return html_root.render()
151
+
152
+ def split_and_upload(self):
153
+ path = read_secret(cate1='funread', cate2='cache', cate3='path', cate4='root')
154
+ with RSSSourceDownload(path=path, cate1="rss") as runner:
155
+ funos.delete(runner.path_pkl)
156
+ funos.delete(runner.path_bok)
157
+ runner.loads_zip()
158
+ i = 1000
159
+ for data in runner.export_sources(size=3000):
160
+ if len(data) > 0:
161
+ self.drive.upload_file(content=data, git_path=f"{self.dir_path}/progress-{i}.json")
162
+ i += 1
163
+
164
+ def update_rss(self):
165
+ print("update source rss")
166
+ self.drive.upload_file(git_path=f"{self.dir_path}/index.html", content=self.generate_html_report())
167
+ print(len(self.generate_html_report()))
168
+
169
+
170
+ class GenerateSourceTask(Task):
171
+ def __init__(self, dir_path=f"funread/legado/snapshot/lasted", source_type="booksource", *args, **kwargs):
172
+ self.repo_str = "farfarfun/funread-cache"
173
+ self.dir_path = dir_path
174
+ self.source_type = source_type
175
+ self.drive = GithubDrive()
176
+ self.drive.login(repo_str=self.repo_str)
177
+ super(GenerateSourceTask, self).__init__(*args, **kwargs)
178
+
179
+ def run_book(self, *args, **kwargs):
180
+ generate_source = GenerateSourceType(source_type="booksource", dir_path=f"{self.dir_path}/book")
181
+ generate_source.split_and_upload()
182
+ generate_source.update_rss()
183
+
184
+ def run_rss(self, *args, **kwargs):
185
+ generate_source = GenerateSourceType(source_type="rsssource", dir_path=f"{self.dir_path}/rss")
186
+ generate_source.split_and_upload()
187
+ generate_source.update_rss()
@@ -0,0 +1,56 @@
1
+ import re
2
+
3
+ from funread.legado.manage.download.base import DownloadSource
4
+
5
+
6
+ def retain_zh_ch_dig(text):
7
+ return re.sub("[^\u4e00-\u9fa5a-zA-Z0-9\[\]]+", "", text)
8
+
9
+
10
+ class RSSSourceFormat:
11
+ def __init__(self, source):
12
+ self.source = source
13
+ self.source["sourceComment"] = ""
14
+ self.source["sourceUrl"] = self.source["sourceUrl"].rstrip("/|#")
15
+ if "httpUserAgent" in self.source.keys():
16
+ self.source["header"] = self.source.pop("httpUserAgent")
17
+
18
+ for key in ["sourceGroup", "sourceName"]:
19
+ self.source[key] = retain_zh_ch_dig(self.source.get(key, ""))
20
+
21
+ def run(self):
22
+ keys = [key for key in self.source.keys() if not self.source[key]]
23
+ for key in keys:
24
+
25
+ self.source.pop(key)
26
+
27
+ for key in ['customOrder', 'respondTime', 'lastUpdateTime']:
28
+ if key in self.source.keys():
29
+ self.source.pop(key)
30
+
31
+ for key in ['searchUrl', 'exploreUrl']:
32
+ if key in self.source.keys():
33
+ self.source[key] = self.source[key].replace(self.source['bookSourceUrl'], '')
34
+ return self.source
35
+
36
+ def __format_base(self, group, map):
37
+ book_info = self.source.get(group, {})
38
+
39
+ for key, name in map.items():
40
+ if key not in self.source:
41
+ continue
42
+ value = self.source.pop(key)
43
+ if value:
44
+ book_info[name] = value
45
+ if len(book_info) > 0:
46
+ self.source[group] = book_info
47
+
48
+
49
+ class RSSSourceDownload(DownloadSource):
50
+ def __init__(self, *args, **kwargs):
51
+ super().__init__(*args, **kwargs)
52
+
53
+ def source_format(self, source):
54
+ return RSSSourceFormat(source).run()
55
+
56
+
@@ -0,0 +1 @@
1
+ from .core import url_to_hostname
@@ -0,0 +1,4 @@
1
+ from urllib.parse import urlparse
2
+
3
+ def url_to_hostname(url):
4
+ return urlparse(url).hostname
File without changes
@@ -0,0 +1,37 @@
1
+ # import argparse
2
+
3
+ # from funread.legado.task import GenerateSourceTask
4
+ # from funread.legado.task import ReadODSProgressDataTask
5
+ # from funread.legado.task import ReadODSSourceDataTask
6
+ # from funread.legado.task import ReadODSUrlDataTask
7
+ # from funread.legado.task import UpdateRssTask
8
+
9
+
10
+ # def funbuild():
11
+ # parser = argparse.ArgumentParser(prog="PROG")
12
+ # subparsers = parser.add_subparsers(help="sub-command help")
13
+
14
+ # # 添加子命令
15
+ # build_parser = subparsers.add_parser("url", help="format the source url")
16
+ # build_parser.set_defaults(func=ReadODSUrlDataTask().run)
17
+
18
+ # # 添加子命令
19
+ # clean_history_parser = subparsers.add_parser("source", help="load the source")
20
+ # clean_history_parser.set_defaults(func=ReadODSSourceDataTask().run)
21
+
22
+ # # 添加子命令
23
+ # pull_parser = subparsers.add_parser("progress", help="progress the source data.")
24
+ # pull_parser.add_argument("--quiet", default=True, help="quiet")
25
+ # pull_parser.set_defaults(func=ReadODSProgressDataTask().run)
26
+
27
+ # # 添加子命令
28
+ # push_parser = subparsers.add_parser("generate", help="git push")
29
+ # push_parser.add_argument("--quiet", default=True, help="quiet")
30
+ # push_parser.set_defaults(func=GenerateSourceTask().run)
31
+
32
+ # # 添加子命令
33
+ # tag_parser = subparsers.add_parser("update", help="git build tag")
34
+ # tag_parser.set_defaults(func=UpdateRssTask().run)
35
+
36
+ # args = parser.parse_args()
37
+ # args.func(args)
File without changes
File without changes
@@ -0,0 +1,12 @@
1
+ from funread.web.parse.video import VideoInfo
2
+
3
+ from nicegui import ui
4
+
5
+
6
+ def video_page(video_info: VideoInfo = None):
7
+ @ui.page("/media/video/")
8
+ def video_play():
9
+ v = ui.video(src=video_info.video_url)
10
+ v.on("ended", lambda _: ui.notify("Video playback completed"))
11
+
12
+ return video_play
@@ -0,0 +1,67 @@
1
+ from funread.web.parse.video import ParseVideo
2
+
3
+ from nicegui import ui
4
+ from nicegui.events import ValueChangeEventArguments
5
+ from .video import video_page, VideoInfo
6
+
7
+
8
+ def show(event: ValueChangeEventArguments):
9
+ name = type(event.sender).__name__
10
+ ui.notify(f"{name}: {event.value}")
11
+
12
+
13
+ def card(video: VideoInfo):
14
+ with ui.card():
15
+ ui.image(video.pic_url)
16
+ with ui.row():
17
+ ui.link(video.text, video_page(video))
18
+
19
+
20
+ def video_list_page(parse: ParseVideo, tab_id=0):
21
+ @ui.page("/videos")
22
+ def video_list_play(rows=10, cols=2):
23
+ ui.button("Button", on_click=lambda: ui.notify("Click"))
24
+ videos = parse.parse_video_list()
25
+
26
+ index = 0
27
+ for i in range(rows):
28
+ with ui.row():
29
+ for j in range(cols):
30
+ if index >= len(videos.video_list):
31
+ break
32
+ card(videos.video_list[index])
33
+
34
+ return video_list_play
35
+
36
+
37
+ def video_list_play(parse: ParseVideo, tab_id=0, rows=10, cols=2):
38
+ ui.button("Button", on_click=lambda: ui.notify("Click"))
39
+ videos = parse.parse_video_list()
40
+ print(videos)
41
+ index = 0
42
+ for i in range(rows):
43
+ with ui.row():
44
+ for j in range(cols):
45
+ if index >= len(videos.video_list):
46
+ break
47
+ card(videos.video_list[index])
48
+
49
+
50
+ def video_list_tabs_page(parse: ParseVideo, tab_id=0):
51
+ @ui.page("/videosssss")
52
+ def video_list_tabs_play(rows=10, cols=2):
53
+ parse_tabs = parse.tabs()
54
+ if len(parse_tabs) == 0:
55
+ video_list_play(parse, tab_id=tab_id)
56
+ else:
57
+ with ui.tabs().classes("w-full") as tabs:
58
+ for name in parse_tabs.keys():
59
+ tab = ui.tab(name)
60
+ with ui.tab_panels(tabs, value=tab).classes("w-full"):
61
+ with ui.tab_panel(tab):
62
+ video_list_play(parse, tab_id=tab_id)
63
+
64
+ return video_list_tabs_play
65
+
66
+
67
+ ui.run()
File without changes
@@ -0,0 +1,9 @@
1
+ class BaseParse:
2
+ def __init__(self, source=None, *args, **kwargs):
3
+ self.source = source
4
+
5
+ def parse_list(self, page_no, page_size=10, *args, **kwargs):
6
+ pass
7
+
8
+ def parse_detail(self, path):
9
+ pass
@@ -0,0 +1,29 @@
1
+ from typing import List
2
+
3
+ from pydantic import BaseModel
4
+
5
+ from .base import BaseParse
6
+
7
+
8
+ class VideoInfo(BaseModel):
9
+ text: str = ""
10
+ pic_url: str = ""
11
+ video_url: str = ""
12
+ description: str = None
13
+
14
+
15
+ class VideoListInfo(BaseModel):
16
+ page_no: int = 1
17
+ page_size = 10
18
+ video_list: List[VideoInfo] = []
19
+
20
+
21
+ class ParseVideo(BaseParse):
22
+ def __init__(self, *args, **kwargs):
23
+ super().__init__(*args, **kwargs)
24
+
25
+ def parse_video_detail(self) -> VideoInfo:
26
+ pass
27
+
28
+ def parse_video_list(self) -> VideoListInfo:
29
+ pass