36 |
37 |
38 |
179 |
180 |
229 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 📂 qb-rss-manager
2 |
3 | qBittorrent rss订阅 下载规则管理工具
4 |
5 | 1.0版本为基于pyqt5的桌面应用,源代码在这个 [pyqt5分支里](https://github.com/Nriver/qb-rss-manager/tree/pyqt5)
6 |
7 | 后续2.0版本计划改为web应用, 目前正在开发中。
8 |
9 | [](https://GitHub.com/Nriver/qb-rss-manager/releases/)
10 | [](https://github.com/Nriver/qb-rss-manager/blob/master/LICENSE)
11 | [](https://GitHub.com/Nriver/qb-rss-manager/graphs/commit-activity)
12 | [](https://github.com/Nriver/qb-rss-manager/releases/)
13 |
14 | 快速管理qBittorrent的RSS订阅数据. 实时过滤匹配到的数据, 方便管理你的qb订阅.
15 | 可以和 [Episode-ReName](https://github.com/Nriver/Episode-ReName) 联动实现自动改名.
16 |
17 |
18 |
19 |
20 |
21 | * [qb-rss-manager](#qb-rss-manager)
22 | * [qb-rss-manager 懒人包](#qb-rss-manager-懒人包)
23 | * [警告](#警告)
24 | * [懒人包使用方法](#懒人包使用方法)
25 | * [提示](#提示)
26 | * [懒人使用建议](#懒人使用建议)
27 | * [qb订阅管理器 初始化配置](#qb订阅管理器-初始化配置)
28 | * [Windows/Linux桌面环境下的qb使用](#windowslinux桌面环境下的qb使用)
29 | * [通过api连接docker等环境下的qb使用](#通过api连接docker等环境下的qb使用)
30 | * [导入/导出规则进行分享](#导入导出规则进行分享)
31 | * [config.json部分配置参数说明](#configjson部分配置参数说明)
32 | * [自动填充](#自动填充)
33 | * [触发机制](#触发机制)
34 | * [默认关键字模板配置](#默认关键字模板配置)
35 | * [限制解析的 series_name 长度](#限制解析的-series_name-长度)
36 | * [默认订阅地址配置](#默认订阅地址配置)
37 | * [快捷操作/快捷键说明](#快捷操作快捷键说明)
38 | * [声明](#声明)
39 | * [关于图标](#关于图标)
40 | * [Stargazers 数据](#stargazers-数据)
41 | * [捐赠](#捐赠)
42 | * [感谢](#感谢)
43 |
44 |
45 |
46 | # 😴 qb-rss-manager 懒人包
47 |
48 | 填好想要自动下载的文件信息,就能让qb自动下载想要的番剧,自动追番必备,用过都说好!懒人包包含qb订阅管理工具, 自动重命名工具,
49 | qb增强版, 都已经配置完毕, 可以开箱即用.
50 |
51 | ## ⚠️ 警告
52 |
53 | 本工具没有任何售后, 在使用过程中发生的一切后果由使用者自己承担. 对于程序bug, 使用者因操作不当或其它原因导致的数据丢失,
54 | 硬件损坏等问题概不负责.
55 |
56 | ## 📖 懒人包使用方法
57 |
58 | [Release页面](https://github.com/Nriver/qb-rss-manager/releases) 找到懒人包下载下来解压.
59 |
60 | 1. 运行all in one初始化工具 aio_init.exe
61 | 2. 启动 qbittorrent.exe, 设置rss源, 更新数据.
62 | 3. 运行qb管理器 QBRssManager.exe
63 | 4. 修改 '保存路径' 列的存储路径, 注意目录命名会影响自动重命名是否执行
64 | 5. 点击 '保存', 点击 '生成RSS订阅下载规则', 会自动生成qb的rss下载规则并启动qb. (注意qb启动后,
65 | 匹配到rss订阅规则就会开始下载.)
66 | 6. 仿照示例写自己的规则, 重复4-5
67 |
68 | 初始化
69 | 
70 |
71 | 加载RSS数据
72 | 
73 |
74 | 管理RSS订阅, 关键字输入过程中, 匹配到的RSS数据实时过滤显示
75 | 
76 |
77 | 等待自动重命名
78 | 
79 |
80 | ## 💡 提示
81 |
82 | 1. 程序路径可以有中文但是不要有空格
83 | 2. 输入关键字过滤时下方会显示过滤结果
84 | 3. 修改完记得点保存或者备份
85 | 4. 下载完成后 Season XX 目录下的文件会自动重命名, 默认下载完成后15秒自动改名. 有可能删除文件或者覆盖文件, 自己看着办吧.
86 | 5. 需要添加新的rss源请先在qb内添加, 确认qb能加载rss数据, 之后用管理器管理订阅就行了
87 | 6. 不要修改程序的文件名
88 | 7. 程序在右下角托盘里
89 |
90 | ## 🤔 懒人使用建议
91 |
92 | 1. 先填写订阅地址. 如果是qb里没有订阅的地址, 先生成一次订阅规则, 就可以把订阅地址加入到qb里.
93 | 2. 填写保存路径, 使用类似 `Z:\Anime\各位打个赏吧我好饿呜呜呜呜呜\Season 1` 的格式, 程序可以自动解析相关内容.
94 | 3. 在使用api与qb通信的状态下, 编辑关键字可以实时过滤出匹配到的结果.
95 |
96 | # 🚀 qb订阅管理器 初始化配置
97 |
98 | ## 🖥️ Windows/Linux桌面环境下的qb使用
99 |
100 | 1. 从release下载最新对应平台的可执行文件
101 | 2. 首次运行会生成config.json, 请修改`qb_executable`和`rules_path`为你的qb主程序路径, 如果安装在默认路径可以不修改.
102 | 3. 运行程序进行编辑
103 |
104 | 已有的订阅规则可以通过右键导入. 编辑好之后记得先保存再生成规则
105 |
106 | ## 🌐 通过api连接docker等环境下的qb使用
107 |
108 | docker等环境下, 程序可以通过api远程管理qbittorrent
109 |
110 | 打开`QBRssManager.exe`, 保存设置, 桌面右下角托盘里把它完全关掉
111 | 编辑`config.json`
112 | 修改以下内容
113 |
114 | ```
115 | "use_qb_api": 1,
116 | "qb_api_ip": "192.168.1.111",
117 | "qb_api_port": 8080,
118 | "qb_api_username": "admin",
119 | "qb_api_password": "adminadmin"
120 | ```
121 |
122 | 参数说明
123 | `use_qb_api` 启用api通信
124 | `qb_api_ip` qb的ip地址,若填写域名,请附上“http://”
125 | `qb_api_port` qb的端口
126 | `qb_api_username` qb的用户名
127 | `qb_api_password` qb的密码
128 |
129 | 之后打开`QBRssManager.exe`右键即可导入已有规则
130 | (图片看不清可以点击看大图)
131 |
132 | 
133 |
134 | 点击生成规则可以写入到qb里
135 |
136 | 
137 |
138 | # 导入/导出规则进行分享
139 |
140 | 在表格里右键就有导入和导出功能了,快把你的订阅规则和朋友分享吧!
141 |
142 | 
143 |
144 | # config.json部分配置参数说明
145 |
146 | 很多配置里的 1表示开启 0表示关闭, 以下不重复说明
147 |
148 | `close_to_tray` 点击关闭最小化到托盘. 默认开启
149 | `data_auto_zfill` 添加时间列输入的日期自动格式化. 比如 2022.8 2022-8 2022/8 转换成2022年08月, 默认开启
150 |
151 | ## 🤖 自动填充
152 |
153 | ### ⚡️ 触发机制
154 |
155 | 填写`关键字`时会触发自动填充机制, 程序会依据配置尝试自动填充订阅地址. 如果没有配置订阅地址的默认值, 则会自动复制表格上方最近的订阅地址.
156 |
157 | 填写`保存路径`时会触发自动填充机制, 程序会解析保存路径, 尽量解析出所有的数据.
158 | 推荐的保存路径格式为 `Z:\Anime\XXXXX\Season 1`. 程序可以解析出的数据 `XXXXX` 对应模板变量 `{series_name}`.
159 | 特殊格式 `Z:\Anime\XXXXX (2023)\Season 1`, 会忽略掉后面的年份.
160 |
161 | ### 默认关键字模板配置
162 |
163 | 全局配置中的 `keyword_default` 可以配置默认的订阅地址, 默认为 `{series_name}`,
164 | 参考配置值举例 `A组 {series_name} | B组 {series_name}`. 该配置可以被分组数据中的 `keyword_override` 配置给覆盖,
165 | 实现每个分组使用不同的自动填充模板来自动填写关键字.
166 |
167 | ### 限制解析的 series_name 长度
168 |
169 | 全局配置中 `keyword_trim_length` 可以限制解析到的 `{series_name}` 长度.
170 | 比如路径为 `Z:\Anime\各位打个赏吧我好饿呜呜呜呜呜 (2023)\Season 1` 的 `{series_name}`,
171 | 默认会被解析为 `各位打个赏吧我好饿呜呜呜呜呜`. 如果将 `keyword_trim_length` 设置为6, 会被解析为 `各位打个赏吧`.
172 | 对于名字超长的番剧可以通过设置这个值来限制关键字的长度, 因为一般只要前面几个字就足够过滤了.
173 |
174 | ### 默认订阅地址配置
175 |
176 | 全局配置中的 `rss_default` 可以配置默认的订阅地址. 多个订阅地址可以用 `空格`, ',' `|` 符号隔开.
177 | 该配置可以被分组数据中的 `rss_override` 配置给覆盖, 实现每个分组自动填充不同的.
178 |
179 | # ⌨️ 快捷操作/快捷键说明
180 |
181 | - 选中单元格后按 `回车键`, `F2`, `双击` 都能进入编辑模式.
182 | - 在分组上`双击`可以修改分组名称, 修改名称后按 `回车键` 确认修改.
183 | - `Ctrl+s` 保存.
184 | - 用鼠标选中多个单元格, 按下 `Ctrl+c` 可以复制单元格数据, 复制的内容可以粘贴到其它单元格或其它标签里. 另注,
185 | 复制的数据是标准的excel格式, 可以粘贴在excel软件里
186 | - `Ctrl+v` 可以粘贴文本/单元格数据. 另注, 可以从excel里复制过来.
187 | - `Ctrl+f` 可以打开查找/搜索框, 主界面下方文本框会显示共有多少个结果以及当前是第几个结果. 搜索状态下按 `F3` 可以跳到下一个结果.
188 | 按`ESC`键退出搜索.
189 | - `Ctrl+h` 可以打开替换/批量替换框. 基本操作和查找类似.
190 | - `Delete` 可以删除数据, 用鼠标选中多个单元格可以删除多个数据
191 | - `方向键` 上下左右可以切换选中的单元格
192 | - `Alt+1`, `Alt+2` 等 `Alt+数字` 操作可以切换分组
193 |
194 | # 🔔 声明
195 |
196 | qb管理程序来自 https://github.com/Nriver/qb-rss-manager
197 |
198 | 重命名工具来自 https://github.com/Nriver/Episode-ReName
199 |
200 | qb增强版主程序来自 https://github.com/c0re100/qBittorrent-Enhanced-Edition/
201 |
202 | 其它数据来自各rss网站和本工具无关
203 |
204 | 如果觉得对你有点用, 请给以上项目star, 再推荐给你的朋友吧!
205 |
206 | # 关于图标
207 |
208 | 程序使用的图标为 [icon-icons.com](https://icon-icons.com/icon/qbittorrent/93768) 的免费图标
209 |
210 |
211 | ---
212 |
213 | # ⏳ Stargazers 数据
214 |
215 | 统计图使用 [caarlos0/starcharts](https://github.com/caarlos0/starcharts) 项目生成.
216 |
217 | [](https://starchart.cc/Nriver/qb-rss-manager)
218 |
219 | ---
220 |
221 | # 💰 捐赠
222 |
223 | 如果你觉得我做的程序对你有帮助, 欢迎捐赠, 这对我来说是莫大的鼓励!
224 |
225 | 支付宝:
226 | 
227 |
228 | 微信:
229 | 
230 |
231 | ---
232 |
233 | # 🙏 感谢
234 |
235 | 感谢不愿留姓名的某位朋友的大力支持, 对本工具以及懒人包的诞生功不可没.
236 |
237 | 感谢 `J*s` 赞助的50元!
238 |
239 | 感谢 `**莲` 赞助的10元!
240 |
241 | 感谢 `**楷` 赞助的5元!
242 |
243 | 感谢 `*メ` 赞助的200元!
244 |
245 | 感谢Jetbrins公司提供的Pycharm编辑器!
246 |
247 | [](https://jb.gg/OpenSource)
248 |
249 |
--------------------------------------------------------------------------------
/pyqt5-ver/g.py:
--------------------------------------------------------------------------------
1 | # 配置
2 | import json
3 | import os
4 | import sys
5 |
6 | from loguru import logger
7 |
8 | headers = ['添加时间', '剧集名称', '包含关键字', '排除关键字', '集数修正', '保存路径', 'RSS订阅地址', '种子类型']
9 |
10 | # 配置
11 | config = {}
12 | # 屏幕上显示的数据
13 | data_list = []
14 | # 所有的分组数据
15 | data_groups = []
16 | # 记录目前的data_list是第几组数据
17 | current_data_list_index = 0
18 |
19 | new_data_group = {
20 | 'name': '新分组',
21 | 'keyword_override': '',
22 | 'rss_override': '',
23 | 'data': [],
24 | }
25 |
26 |
27 | def get_default_config():
28 | # 默认配置
29 |
30 | default_data_dump = {
31 | 'version': 'v1',
32 | 'data_groups': [
33 | {
34 | 'name': '默认分组',
35 | 'keyword_override': '',
36 | 'rss_override': '',
37 | 'data': [],
38 | }
39 | ]
40 | }
41 |
42 | if os.name == 'nt':
43 | # Windows 系统默认配置
44 | # qb主程序路径
45 | qb_executable = os.path.expandvars(r'%ProgramW6432%\qBittorrent\qbittorrent.exe')
46 | # qb配置文件路径
47 | rules_path = os.path.expandvars(r'%appdata%\qBittorrent\rss\download_rules.json')
48 | feeds_json_path = os.path.expandvars(r'%appdata%\qBittorrent\rss\feeds.json')
49 | rss_article_folder = os.path.expandvars(r'%LOCALAPPDATA%\qBittorrent\rss\articles')
50 | else:
51 | # Linux 桌面系统默认配置
52 | qb_executable = os.path.expanduser(r'qbittorrent')
53 | rules_path = os.path.expanduser(r'~/.config/qBittorrent/rss/download_rules.json')
54 | feeds_json_path = os.path.expanduser(r'~/.config/qBittorrent/rss/feeds.json')
55 | rss_article_folder = os.path.expanduser(r'~/.config/qBittorrent/rss/articles')
56 |
57 | default_config = {
58 | # 自动保存
59 | 'auto_save': 0,
60 | 'column_width_list': [80, 260, 210, 65, 62, 370, 290, 80],
61 | 'center_columns': [0, 3, 4],
62 | 'close_to_tray': 1,
63 | 'data_dump': default_data_dump,
64 | 'date_auto_zfill': 1,
65 | 'full_window_width': 1400,
66 | 'full_window_height': 800,
67 | 'max_row_size': 100,
68 | # 保存后打开qb主程序 1为自动打开 其它值不自动打开
69 | 'open_qb_after_export': 1,
70 | # qb 本机操作
71 | 'qb_executable': qb_executable,
72 | 'feeds_json_path': feeds_json_path,
73 | 'rss_article_folder': rss_article_folder,
74 | 'rules_path': rules_path,
75 | # qb api通信相关
76 | 'use_qb_api': 1,
77 | 'qb_api_ip': '127.0.0.1',
78 | 'qb_api_port': 8080,
79 | 'qb_api_username': 'admin',
80 | 'qb_api_password': 'adminadmin',
81 | 'keyword_default': '{series_name}',
82 | 'rss_default': '',
83 | 'keyword_trim_length': '',
84 | }
85 |
86 | return default_config
87 |
88 |
89 | def init_config():
90 | global config
91 | global data_list
92 | global data_groups
93 | global current_data_list_index
94 |
95 | try:
96 | with open('config.json', 'r', encoding='utf-8') as f:
97 | config = json.loads(f.read())
98 | # 修正配置,补充缺少的默认配置
99 | default_config = get_default_config()
100 | for x in default_config:
101 | if x not in config:
102 | config[x] = default_config[x]
103 |
104 | if 'data_list' in config:
105 | parse_legacy()
106 | elif 'data_dump' in config and config['data_dump']['version'] == 'v1':
107 | # 从config里加载data groups数据,后面的操作不要直接操作config对象,直接操作data_groups
108 | data_groups = config['data_dump']['data_groups']
109 | # 修正配置,补充缺少的默认配置
110 | for i in range(len(data_groups)):
111 | for y in new_data_group:
112 | if y not in data_groups[i]:
113 | data_groups[i][y] = new_data_group[y]
114 |
115 | parse_v1()
116 | else:
117 | exit()
118 | except:
119 | # 配置解析错误
120 | if not os.path.exists('config.json'):
121 | # 不存在配置文件 生成默认配置
122 |
123 | default_config = get_default_config()
124 | config = default_config
125 |
126 | with open('config.json', 'w', encoding='utf-8') as f:
127 | f.write(json.dumps(config, ensure_ascii=False, indent=4))
128 | else:
129 | logger.error('配置解析报错!')
130 | # 直接退出
131 | sys.exit()
132 |
133 | return config, data_list
134 |
135 |
136 | def clean_data_list(tmp_data_list):
137 | """清理空行"""
138 | cleaned_data = []
139 | for x in tmp_data_list:
140 | if all(y == '' for y in x):
141 | continue
142 | cleaned_data.append(x)
143 | return cleaned_data
144 |
145 |
146 | def clean_group_data(tmp_group_data):
147 | """清理v1结构空行"""
148 | cleaned_data = []
149 | for x in tmp_group_data:
150 | if all(x[y] == '' for y in x):
151 | continue
152 | cleaned_data.append(x)
153 | return cleaned_data
154 |
155 |
156 | def save_config(update_data=True):
157 | """保存配置"""
158 | global config
159 | global data_list
160 | global data_groups
161 | global current_data_list_index
162 |
163 | logger.info(f'保存配置 更新数据 {update_data}')
164 |
165 | # 读取原始数据,以防异常报错丢失配置
166 | with open('config.json', 'r', encoding='utf-8') as f:
167 | original_content = f.read()
168 |
169 | with open('config.json', 'w', encoding='utf-8') as f:
170 | try:
171 | if update_data:
172 | config['data_dump'] = dump_v1()
173 | f.write(json.dumps(config, ensure_ascii=False, indent=4))
174 | except:
175 | logger.info('数据解析有问题! 还原数据!')
176 | f.write(original_content)
177 | return '数据解析有问题! 还原数据!'
178 |
179 |
180 | def parse_v1():
181 | global config
182 | global data_list
183 | global data_groups
184 | global current_data_list_index
185 |
186 | data_list = []
187 | for x in data_groups[current_data_list_index]['data']:
188 | data_list.append(convert_v1_line(x))
189 |
190 | # 补到 max_row_size 个数据
191 | fill_up_data_list()
192 |
193 | return config, data_list
194 |
195 |
196 | def parse_v1_line(x):
197 | parsed_line = {
198 | 'release_date': x[0],
199 | 'series_name': x[1],
200 | 'mustContain': x[2],
201 | 'mustNotContain': x[3],
202 | 'rename_offset': x[4],
203 | 'savePath': x[5],
204 | 'affectedFeeds': x[6],
205 | 'assignedCategory': x[7],
206 | }
207 | return parsed_line
208 |
209 |
210 | def parse_v1_data_list(tmp_data_list):
211 | data = []
212 | for x in tmp_data_list:
213 | line = parse_v1_line(x)
214 | data.append(line)
215 | return data
216 |
217 |
218 | def convert_v1_line(x):
219 | converted_list = [
220 | x['release_date'],
221 | x['series_name'],
222 | x['mustContain'],
223 | x['mustNotContain'],
224 | x['rename_offset'],
225 | x['savePath'],
226 | x['affectedFeeds'],
227 | x['assignedCategory'],
228 | ]
229 | return converted_list
230 |
231 |
232 | def dump_v1():
233 | global data_groups
234 |
235 | data_dump = {
236 | 'version': 'v1',
237 | 'data_groups': [],
238 | }
239 |
240 | for data_group in data_groups:
241 | cleaned_group_data = clean_group_data(data_group['data'])
242 | data_dump['data_groups'].append({
243 | 'name': data_group['name'],
244 | 'keyword_override': data_group['keyword_override'],
245 | 'rss_override': data_group['rss_override'],
246 | 'data': cleaned_group_data,
247 | })
248 |
249 | return data_dump
250 |
251 |
252 | def update_data_list(text=None, r=None, c=None):
253 | """更新data_groups里的data_list数据到最新"""
254 | global config
255 | global data_list
256 | global data_groups
257 | global current_data_list_index
258 |
259 | if text and r and c:
260 | data_list[r][c] = text
261 | data_groups[current_data_list_index]['data'] = parse_v1_data_list(data_list)
262 |
263 |
264 | def fill_up_data_list():
265 | global data_list
266 | # 补到 max_row_size 个数据
267 | if len(data_list) < config['max_row_size']:
268 | for _ in range(config['max_row_size'] - len(data_list)):
269 | data_list.append(['' for x in range(len(headers))])
270 |
271 |
272 | def parse_legacy():
273 | """处理旧版数据格式"""
274 | global config
275 | global data_list
276 | global data_groups
277 | global current_data_list_index
278 |
279 | data_list = config['data_list']
280 |
281 | # 补到 max_row_size 个数据
282 | fill_up_data_list()
283 |
284 | data_groups = [
285 | {
286 | 'name': '默认分组',
287 | 'keyword_override': '',
288 | 'rss_override': '',
289 | 'data': [],
290 | }
291 | ]
292 |
293 | data = parse_v1_data_list(data_list)
294 | current_data_list_index = 0
295 | data_groups[current_data_list_index]['data'] = data
296 |
297 | # 去除旧版数据
298 | del config['data_list']
299 |
300 | # 保存新版数据
301 | config['data_dump'] = dump_v1()
302 |
303 | return
304 |
305 |
306 | def data_dump_to_list(data_dump):
307 | pass
308 |
309 |
310 | def data_list_to_dump(data_list):
311 | logger.info('data_list_to_dump()')
312 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/pyqt5-ver/QBRssManager.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import json
3 | import os
4 | import re
5 | import subprocess
6 | import sys
7 | import time
8 | from datetime import datetime
9 | from zipfile import ZipFile
10 |
11 | import qbittorrentapi
12 | from PyQt5 import QtGui, QtCore
13 | from PyQt5.QtCore import pyqtSlot, Qt, QPoint, QByteArray
14 | from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout, QDesktopWidget, \
15 | QStyleFactory, QPushButton, QHBoxLayout, QMessageBox, QMenu, QAction, QSplitter, \
16 | QFileDialog
17 | from loguru import logger
18 |
19 | import g
20 | from g import save_config, clean_data_list, headers
21 | from ui.custom_delegate import CustomDelegate
22 | from ui.custom_qtab_widget import CustomQTabWidget
23 | from ui.custom_qtext_browser import CustomQTextBrowser
24 | from ui.custom_tab_bar import CustomTabBar
25 | from ui.search_window import SearchWindow
26 | from ui.tray_icon import TrayIcon
27 | from utils.path_util import resource_path, format_path_by_system, format_path, get_series_from_season_path
28 | from utils.pyqt_util import catch_exceptions
29 | from utils.qb_util import check_qb_port_open, parse_feed_url, parse_articles_for_type_hint, parse_feeds_url, \
30 | convert_feeds_to_one_level_dict
31 | from utils.string_util import try_split_date_and_name
32 | from utils.time_util import try_convert_time
33 | from utils.windows_util import refresh_tray
34 |
35 | g.config, g.data_list = g.init_config()
36 |
37 | # 初始化qb_api客户端
38 | if g.config['use_qb_api']:
39 | qb_client = qbittorrentapi.Client(
40 | host=g.config['qb_api_ip'],
41 | port=g.config['qb_api_port'],
42 | VERIFY_WEBUI_CERTIFICATE=False,
43 | )
44 |
45 |
46 | class App(QWidget):
47 |
48 | def __init__(self):
49 | super().__init__()
50 | self.title = 'qBittorrent 订阅下载规则管理 v1.2.7 by Nriver'
51 | # 图标
52 | self.setWindowIcon(QtGui.QIcon(resource_path('QBRssManager.ico')))
53 | self.left = 0
54 | self.top = 0
55 | self.width = g.config['full_window_width']
56 | self.height = g.config['full_window_height']
57 | logger.info(f'窗口大小 {self.width} {self.height}')
58 | # 防止初始化时触发header宽度变化事件导致参数被覆盖, 等初始化完毕再设置为False
59 | self.preventHeaderResizeEvent = True
60 | # ctrl+c
61 | self.copied_cells = []
62 | self.initUI()
63 | self.tray_icon = TrayIcon(self)
64 | self.tray_icon.show()
65 | # 记录数据更新时间
66 | self.data_update_timestamp = int(datetime.now().timestamp() * 1000)
67 |
68 | # 防止窗口超出屏幕
69 | pos = self.pos()
70 | if pos.x() < 0:
71 | pos.setX(0)
72 | if pos.y() < 0:
73 | pos.setY(0)
74 | logger.info(f'主窗口位置 {pos.x(), pos.y()}')
75 | self.move(pos)
76 |
77 | # 初始化搜索框
78 | self.search_window = SearchWindow(self)
79 |
80 | def center(self):
81 | # 窗口居中
82 | qr = self.normalGeometry()
83 | cp = QDesktopWidget().availableGeometry().center()
84 | qr.moveCenter(cp)
85 | self.move(qr.topLeft())
86 |
87 | def initUI(self):
88 | self.setWindowTitle(self.title)
89 | self.setGeometry(self.left, self.top, self.width, self.height)
90 |
91 | self.createButton()
92 | self.tableWidget_list = [QTableWidget() for _ in range(len(g.data_groups))]
93 | self.createTable()
94 | self.layout_button = QHBoxLayout()
95 | self.layout_button.addWidget(self.move_up_button)
96 | self.layout_button.addWidget(self.move_down_button)
97 | self.layout_button.addWidget(self.clean_row_button)
98 | self.layout_button.addWidget(self.load_config_button)
99 | self.layout_button.addWidget(self.save_button)
100 | self.layout_button.addWidget(self.backup_button)
101 | self.layout_button.addWidget(self.output_button)
102 |
103 | self.tab = CustomQTabWidget()
104 | self.createTabs()
105 | # 当前点击的tab index
106 | self.clicked_tab = 0
107 |
108 | # 文本框 固定位置方便输出
109 | self.text_browser = CustomQTextBrowser(self)
110 | self.text_browser.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
111 | # self.text_browser.setMaximumHeight(g.config['text_browser_height'])
112 |
113 | # 文本框 去掉右键菜单
114 | self.text_browser.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
115 | self.text_browser.customContextMenuRequested.connect(self.generateTextBrowserMenu)
116 | # 文本框滚动条去掉右键菜单
117 | self.text_browser.verticalScrollBar().setContextMenuPolicy(QtCore.Qt.NoContextMenu)
118 | self.text_browser.horizontalScrollBar().setContextMenuPolicy(QtCore.Qt.NoContextMenu)
119 | self.text_browser.resizeEvent = self.custom_text_browser_resize_event
120 |
121 | self.layout = QVBoxLayout()
122 | self.layout.addLayout(self.layout_button)
123 |
124 | # 增加QSplitter, 让文本框组件直接通过拖拽修改大小
125 | self.splitter = QSplitter(Qt.Vertical)
126 | # self.splitter.addWidget(self.tableWidget)
127 | self.splitter.addWidget(self.tab)
128 | self.splitter.addWidget(self.text_browser)
129 |
130 | try:
131 | self.splitter.restoreState(QByteArray.fromHex(bytes(g.config['splitter_state'], 'ascii')))
132 |
133 | except Exception as e:
134 | logger.info('未发现splitter状态, 使用默认分隔比例')
135 | self.splitter.setStretchFactor(0, 8)
136 | self.splitter.setStretchFactor(1, 1)
137 |
138 | # 实时预览
139 | # self.splitter.setOpaqueResize(False)
140 | self.layout.addWidget(self.splitter)
141 | self.setLayout(self.layout)
142 | # 居中显示
143 | self.center()
144 | self.preventHeaderResizeEvent = False
145 | self.show()
146 |
147 | def custom_text_browser_resize_event(self, event):
148 | # 文本框大小变化时, 记录splitter的状态
149 | logger.info(f"custom_resize_event {self.height, self.tableWidget.height(), self.text_browser.height()}")
150 | # logger.info(f"splitter_state {self.splitter.saveState()}")
151 | g.config['splitter_state'] = bytes(self.splitter.saveState().toHex()).decode('ascii')
152 | save_config(update_data=False)
153 |
154 | def createButton(self):
155 | self.output_button = QPushButton('生成RSS订阅下载规则', self)
156 | self.output_button.setToolTip('生成RSS订阅下载规则')
157 | self.output_button.clicked.connect(self.on_export_click)
158 |
159 | self.move_up_button = QPushButton('向上移动', self)
160 | self.move_up_button.clicked.connect(self.on_move_up_click)
161 | self.move_down_button = QPushButton('向下移动', self)
162 | self.move_down_button.clicked.connect(self.on_move_down_click)
163 |
164 | self.load_config_button = QPushButton('恢复上一次保存的配置', self)
165 | self.load_config_button.clicked.connect(self.on_load_config_click)
166 |
167 | self.save_button = QPushButton('保存配置', self)
168 | self.save_button.clicked.connect(self.on_save_click)
169 |
170 | self.clean_row_button = QPushButton('清理空行', self)
171 | self.clean_row_button.clicked.connect(self.on_clean_row_click)
172 |
173 | self.backup_button = QPushButton('备份配置', self)
174 | self.backup_button.clicked.connect(self.on_backup_click)
175 |
176 | def createTable(self):
177 | self.tableWidget = self.tableWidget_list[g.current_data_list_index]
178 | # 行数
179 | self.tableWidget.setRowCount(len(g.data_list))
180 | # 列数
181 | self.tableWidget.setColumnCount(len(headers))
182 |
183 | # 垂直表头修改
184 | # 文字居中显示
185 | self.tableWidget.verticalHeader().setStyleSheet("QHeaderView { qproperty-defaultAlignment: AlignCenter; }")
186 |
187 | # 渲染表头
188 | self.preventHeaderResizeEvent = True
189 | for i, x in enumerate(headers):
190 | item = QTableWidgetItem(x)
191 | item.setForeground(QtGui.QColor(0, 0, 255))
192 | self.tableWidget.setHorizontalHeaderItem(i, item)
193 | self.tableWidget.horizontalHeader().sectionResized.connect(self.on_header_resized)
194 |
195 | # 渲染数据
196 | # 空数据处理
197 | if not g.data_list:
198 | for x in range(len(headers)):
199 | self.tableWidget.setItem(0, x, QTableWidgetItem(""))
200 | else:
201 | for cx, row in enumerate(g.data_list):
202 | for cy, d in enumerate(row):
203 | item = QTableWidgetItem(d)
204 | if cy in g.config['center_columns']:
205 | item.setTextAlignment(Qt.AlignCenter)
206 | self.tableWidget.setItem(cx, cy, item)
207 |
208 | self.tableWidget.move(0, 0)
209 |
210 | # 宽度自适应 效果不太好
211 | # self.tableWidget.resizeColumnsToContents()
212 | # self.tableWidget.resizeColumnsToContents()
213 | # 拉长
214 | header = self.tableWidget.horizontalHeader()
215 | # header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
216 | # header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
217 | # header.setSectionResizeMode(5, QtWidgets.QHeaderView.Stretch)
218 |
219 | # self.tableWidget.setColumnWidth(0, 80)
220 | # self.tableWidget.setColumnWidth(1, 260)
221 | # self.tableWidget.setColumnWidth(2, 210)
222 | # self.tableWidget.setColumnWidth(3, 65)
223 | # self.tableWidget.setColumnWidth(4, 62)
224 | # self.tableWidget.setColumnWidth(5, 370)
225 | # self.tableWidget.setColumnWidth(6, 290)
226 |
227 | for i in range(len(headers)):
228 | self.tableWidget.setColumnWidth(i, g.config['column_width_list'][i])
229 |
230 | # 双击事件绑定
231 | self.tableWidget.doubleClicked.connect(self.on_double_click)
232 |
233 | # 修改事件绑定
234 | self.tableWidget.cellChanged.connect(self.on_cell_changed)
235 |
236 | self.tableWidget.keyPressEvent = self.handle_key_press
237 |
238 | # 表格 右键菜单
239 | self.tableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
240 | self.tableWidget.customContextMenuRequested.connect(self.generateMenu)
241 | # 表格 滚动条去掉右键菜单
242 | self.tableWidget.verticalScrollBar().setContextMenuPolicy(QtCore.Qt.NoContextMenu)
243 | self.tableWidget.horizontalScrollBar().setContextMenuPolicy(QtCore.Qt.NoContextMenu)
244 |
245 | logger.info('delegate 初始化')
246 | # 自定义处理
247 | self.tableWidget.setItemDelegateForColumn(2, CustomDelegate(self))
248 | self.tableWidget.setItemDelegateForColumn(3, CustomDelegate(self))
249 |
250 | self.tableWidget.setItemDelegateForColumn(5, CustomDelegate(self))
251 | self.tableWidget.setItemDelegateForColumn(6, CustomDelegate(self))
252 |
253 | def createTabs(self):
254 | # 无法共享widget 只好初始化多个widget了
255 | # 自定义tabbar 方便修改
256 | self.tab.setTabBar(CustomTabBar(self))
257 | for i, x in enumerate(self.tableWidget_list):
258 | self.tab.addTab(x, g.data_groups[i]['name'])
259 | self.tab.tabBarClicked.connect(self.on_tab_clicked)
260 | self.tab.currentChanged.connect(self.on_tab_changed)
261 |
262 | # tab的右键菜单
263 | # 注意这里要用tabBar() 否则会影响到这个tab里的组件的右键菜单
264 | self.tab.tabBar().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
265 | self.tab.tabBar().customContextMenuRequested.connect(self.generateTabMenu)
266 |
267 | # 设置可以拖动
268 | # self.tab.tabBar().setMouseTracking(True)
269 | self.tab.tabBar().setMovable(True)
270 |
271 | def generateTextBrowserMenu(self, pos):
272 | """文本框自定义右键菜单"""
273 | time.sleep(0)
274 | logger.info(f"pos: {pos.x(), pos.y()}")
275 | a = QPoint(pos.x(), pos.y())
276 |
277 | self.text_browser_menu = QMenu(self)
278 |
279 | self.copy_text_action = QAction("复制")
280 | self.select_all_action = QAction("全选")
281 |
282 | self.copy_text_action.triggered.connect(self.on_copy_text_click)
283 | self.select_all_action.triggered.connect(self.on_select_all_click)
284 |
285 | self.text_browser_menu.addAction(self.copy_text_action)
286 | self.text_browser_menu.addAction(self.select_all_action)
287 |
288 | self.text_browser_menu.exec_(self.text_browser.mapToGlobal(a))
289 |
290 | def on_copy_text_click(self):
291 | """文本框右键菜单 复制 按钮事件"""
292 | logger.info('on_copy_text_click()')
293 | self.text_browser.copy()
294 |
295 | def on_select_all_click(self):
296 | """文本框右键菜单 全选 按钮事件"""
297 | logger.info('on_select_all_click()')
298 | self.text_browser.selectAll()
299 |
300 | def generateMenu(self, pos):
301 | # 右键弹窗菜单
302 | # 右键弹窗菜单加一个sleep, 防止长按右键导致右键事件被重复触发
303 | time.sleep(0)
304 | # 感觉弹出菜单和实际鼠标点击位置有偏差, 尝试手动修正
305 | logger.info(f"pos {pos.x(), pos.y()}")
306 | a = QPoint(pos.x() + 26, pos.y() + 22)
307 |
308 | self.menu = QMenu(self)
309 | self.up_action = QAction("向上移动")
310 | self.down_action = QAction("向下移动")
311 | # self.group_add_action = QAction("添加分组")
312 | # self.group_delete_action = QAction("删除当前分组")
313 | self.delete_action = QAction("删除整条订阅")
314 | self.delete_all_action = QAction("删除所有订阅")
315 | self.clear_action = QAction("清理空行")
316 | self.load_config_action = QAction("恢复上一次保存的配置")
317 | self.import_exist_qb_rule_action = QAction("从qb导入已有规则")
318 | self.import_from_share_file_action = QAction("从分享文件导入规则")
319 | self.export_to_share_file_action = QAction("导出规则到文件进行分享")
320 |
321 | self.up_action.triggered.connect(self.on_move_up_click)
322 | self.down_action.triggered.connect(self.on_move_down_click)
323 | # self.group_add_action.triggered.connect(self.on_group_add_action)
324 | # self.group_delete_action.triggered.connect(self.on_group_delete_action)
325 | self.delete_action.triggered.connect(self.menu_delete_action)
326 | self.delete_all_action.triggered.connect(self.menu_delete_all_action)
327 | self.clear_action.triggered.connect(self.on_clean_row_click)
328 | self.load_config_action.triggered.connect(self.on_load_config_click)
329 | self.import_exist_qb_rule_action.triggered.connect(self.on_import_exist_qb_rule_action)
330 | self.import_from_share_file_action.triggered.connect(self.on_import_from_share_file_action)
331 | self.export_to_share_file_action.triggered.connect(self.on_export_to_share_file_action)
332 |
333 | self.menu.addAction(self.up_action)
334 | self.menu.addAction(self.down_action)
335 | # self.menu.addSeparator()
336 | # self.menu.addAction(self.group_add_action)
337 | # self.menu.addAction(self.group_delete_action)
338 | self.menu.addSeparator()
339 | self.menu.addAction(self.delete_action)
340 | self.menu.addAction(self.delete_all_action)
341 | self.menu.addAction(self.clear_action)
342 | self.menu.addSeparator()
343 | self.menu.addAction(self.load_config_action)
344 | self.menu.addAction(self.import_exist_qb_rule_action)
345 | self.menu.addSeparator()
346 | self.menu.addAction(self.import_from_share_file_action)
347 | self.menu.addAction(self.export_to_share_file_action)
348 |
349 | # 让弹出菜单在修正后的坐标显示
350 | self.menu.exec_(self.tableWidget.mapToGlobal(a))
351 | # return
352 |
353 | def generateTabMenu(self, pos):
354 |
355 | # tab的右键弹窗菜单
356 | # 右键弹窗菜单加一个sleep, 防止长按右键导致右键事件被重复触发
357 | time.sleep(0)
358 | # 感觉弹出菜单和实际鼠标点击位置有偏差, 尝试手动修正
359 | logger.info(f"pos {pos.x(), pos.y()}")
360 | a = QPoint(pos.x() - 2, pos.y() - 24)
361 |
362 | # 根据点击位置获取tab的index, 注意这里要用事件的pos位置, 不要用修正的坐标
363 | tab_index = self.tab.tabBar().tabAt(pos)
364 | logger.info(f'tab_index {tab_index}')
365 |
366 | self.tabMenu = QMenu(self)
367 | self.group_add_action = QAction("添加分组")
368 | self.group_delete_action_dynamic = QAction("删除分组")
369 |
370 | self.group_add_action.triggered.connect(self.on_group_add_action)
371 |
372 | self.group_delete_action_dynamic.triggered.connect(lambda x: self.on_group_delete_action(tab_index))
373 |
374 | self.tabMenu.addAction(self.group_add_action)
375 | self.tabMenu.addAction(self.group_delete_action_dynamic)
376 |
377 | # 让弹出菜单在修正后的坐标显示
378 | self.tabMenu.exec_(self.tableWidget.mapToGlobal(a))
379 |
380 | def on_header_resized(self):
381 | if self.preventHeaderResizeEvent:
382 | return
383 | logger.info('on_header_resized()')
384 | # 修改列宽写入配置
385 | column_width_list_tmp = []
386 | for i in range(len(headers)):
387 | column_width_list_tmp.append(self.tableWidget.columnWidth(i))
388 | logger.info(column_width_list_tmp)
389 | g.config['column_width_list'] = column_width_list_tmp
390 | save_config(update_data=False)
391 |
392 | def load_type_hints(self, row):
393 | # 输入过程中实时过滤数据
394 | # row 是当前表格的行数, 这里读取对应行的订阅链接来获取feed数据
395 |
396 | self.tableWidget.type_hints = []
397 | self.tableWidget.article_details = []
398 | # 当前行feed路径数据
399 | current_row_feed = g.data_list[row][6]
400 | logger.info(f'current_row_feed {current_row_feed}')
401 |
402 | if not current_row_feed:
403 | self.text_browser.setText('缺少订阅地址')
404 | return
405 |
406 | feed_list = parse_feed_url(current_row_feed)
407 |
408 | if g.config['use_qb_api'] == 1:
409 | if check_qb_port_open(g.config['qb_api_ip'], g.config['qb_api_port']):
410 | # 使用qb的api读取feed
411 | try:
412 | qb_client.auth_log_in(username=g.config['qb_api_username'], password=g.config['qb_api_password'])
413 | self.text_browser.append('通过api获取feed')
414 | rss_feeds = qb_client.rss_items(include_feed_data=True)
415 | article_titles = []
416 | article_details = []
417 | server_rss_feeds = convert_feeds_to_one_level_dict(rss_feeds)
418 |
419 | for x in server_rss_feeds:
420 | if server_rss_feeds[x]['url'] in feed_list:
421 | article_titles_tmp, article_details_tmp = parse_articles_for_type_hint(server_rss_feeds[x]['articles'], x)
422 | article_titles.extend(article_titles_tmp)
423 | article_details.extend(article_details_tmp)
424 |
425 | self.tableWidget.type_hints = article_titles
426 | self.tableWidget.article_details = article_details
427 | # 数据太多可能会导致卡顿 这里尽量不要输出
428 | # logger.info(self.tableWidget.type_hints)
429 | return True
430 |
431 | # except qbittorrentapi.LoginFailed as e:
432 | # self.text_browser.append('api登录失败')
433 | # self.text_browser.append(e)
434 | except Exception as e:
435 | logger.error(e)
436 | self.text_browser.append('通过api连接qb失败')
437 | self.text_browser.append(f'报错信息 {repr(e)}')
438 | else:
439 | self.show_message("通过api连接qb失败, 请检查qb是否开启Web UI. 如不需要通过api连接, 请将use_qb_api设为0",
440 | "错误")
441 |
442 | else:
443 | # 读取本地feed文件
444 | try:
445 | article_titles = []
446 | article_details = []
447 |
448 | # 读取qb feed json数据
449 | feed_uid = None
450 | with open(g.config['feeds_json_path'], 'r', encoding='utf-8') as f:
451 | rss_feeds = json.loads(f.read())
452 | logger.info(f'rss_feeds {rss_feeds}')
453 | server_rss_feeds = convert_feeds_to_one_level_dict(rss_feeds)
454 | for x in server_rss_feeds:
455 | if server_rss_feeds[x]['url'] in feed_list:
456 | feed_uid = server_rss_feeds[x]['uid'].replace('-', '')[1:-1]
457 | logger.info(f'feed_uid {feed_uid}')
458 |
459 | if feed_uid:
460 | # 读取rss feed的标题 写入 type_hints 列表
461 | article_titles = []
462 | article_path = g.config['rss_article_folder'] + '/' + feed_uid + '.json'
463 | logger.info(article_path)
464 | with open(article_path, 'r', encoding='utf-8') as f:
465 | articles = json.loads(f.read())
466 | article_titles_tmp, article_details_tmp = parse_articles_for_type_hint(articles, x)
467 | article_titles.extend(article_titles_tmp)
468 | article_details.extend(article_details_tmp)
469 |
470 | self.tableWidget.type_hints = article_titles
471 | self.tableWidget.article_details = article_details
472 | # logger.info(self.tableWidget.type_hints)
473 | return True
474 | except Exception as e:
475 | logger.info(f'exception {e}')
476 | self.text_browser.setText('没找到RSS数据呀')
477 |
478 | def do_search(self):
479 | """搜索框按钮事件"""
480 | logger.info('do_search()')
481 | # 搜索关键字
482 | # keyword = self.search_window.lineEdit.text()
483 | keyword = self.search_window.text_edit_list[self.search_window.last_tab].text()
484 | logger.info(keyword)
485 | if not keyword:
486 | return
487 |
488 | if self.search_window.last_search_keyword != keyword or self.search_window.last_data_update_timestamp != self.data_update_timestamp:
489 | logger.info('数据有变动, 重新搜索')
490 | self.text_browser.clear()
491 | self.last_search_index = 0
492 | self.search_window.search_result = []
493 | # 目标
494 | selected_columns = list(range(len(headers)))
495 | for r in range(len(g.data_list)):
496 | for c in selected_columns:
497 | cell_data = g.data_list[r][c]
498 | # 忽略大小写
499 | if keyword.lower() in cell_data.lower():
500 | logger.info(f'找到了! {r, c, cell_data}')
501 | self.search_window.search_result.append({'r': r, 'c': c, 'cell_data': cell_data})
502 | self.search_window.last_search_keyword = keyword
503 | # 如果有匹配的结果, 进行跳转
504 | if self.search_window.search_result:
505 | self.search_window.last_data_update_timestamp = self.data_update_timestamp
506 | else:
507 | logger.info('继续遍历上次搜索的结果')
508 | self.last_search_index = (self.last_search_index + 1) % len(self.search_window.search_result)
509 |
510 | if self.search_window.search_result:
511 | logger.info(
512 | f"跳转 {self.search_window.search_result[self.last_search_index]['r'], self.search_window.search_result[self.last_search_index]['c']}")
513 | self.tableWidget.setCurrentCell(self.search_window.search_result[self.last_search_index]['r'],
514 | self.search_window.search_result[self.last_search_index]['c'])
515 | self.text_browser.setText(f'搜索结果: {self.last_search_index + 1}/{len(self.search_window.search_result)}')
516 | self.activateWindow()
517 | else:
518 | self.text_browser.setText('没有找到匹配的数据')
519 |
520 | def search_tab_change(self, index):
521 | logger.info(f'search_tab_change() {index}')
522 | if self.search_window.last_tab != index:
523 | self.search_window.text_edit_list[index].setText(
524 | self.search_window.text_edit_list[self.search_window.last_tab].text())
525 | self.search_window.last_tab = index
526 |
527 | def do_replace(self):
528 | logger.info(f'do_replace() 替换当前单元格内容')
529 | source_text = self.search_window.text_edit_list[self.search_window.last_tab].text()
530 | if not source_text:
531 | return
532 | target_text = self.search_window.lineEditReplaceTarget.text()
533 | logger.info(f'{source_text} 替换为 {target_text}')
534 | pat = re.compile(re.escape(source_text), re.IGNORECASE)
535 | try:
536 | result = pat.sub(target_text, self.tableWidget.currentItem().text())
537 | except:
538 | result = self.tableWidget.currentItem().text().replace(source_text, target_text)
539 | logger.info(result)
540 | g.data_list[self.tableWidget.currentItem().row()][self.tableWidget.currentItem().column()] = result
541 | self.tableWidget.currentItem().setText(result)
542 | self.do_search()
543 |
544 | def do_replace_all(self):
545 | logger.info(f'do_replace_all() 替换全部单元格内容')
546 | source_text = self.search_window.text_edit_list[self.search_window.last_tab].text()
547 | if not source_text:
548 | return
549 | target_text = self.search_window.lineEditReplaceTarget.text()
550 | logger.info(f'{source_text} 替换为 {target_text}')
551 | pat = re.compile(re.escape(source_text), re.IGNORECASE)
552 |
553 | self.tableWidget.blockSignals(True)
554 | g.data_list = clean_data_list(g.data_list)
555 | # 长度补充
556 | if len(g.data_list) < g.config['max_row_size']:
557 | for _ in range(g.config['max_row_size'] - len(g.data_list)):
558 | g.data_list.append(['' for x in range(len(headers))])
559 | # 更新整个列表
560 | for cx, row in enumerate(g.data_list):
561 | for cy, d in enumerate(row):
562 | # 替换数据
563 | try:
564 | d = pat.sub(target_text, d)
565 | except:
566 | d = d.replace(source_text, target_text)
567 | item = QTableWidgetItem(d)
568 | if cy in g.config['center_columns']:
569 | item.setTextAlignment(Qt.AlignCenter)
570 | # 注意这里要更新g.data_list的数据
571 | g.data_list[cx][cy] = d
572 | self.tableWidget.setItem(cx, cy, item)
573 |
574 | # data_groups 数据更新
575 | g.update_data_list()
576 |
577 | self.tableWidget.blockSignals(False)
578 |
579 | def show_message(self, message, title):
580 | """弹出框 消息"""
581 | self.msg = QMessageBox()
582 | # 设置图标
583 | self.msg.setWindowIcon(QtGui.QIcon(resource_path('QBRssManager.ico')))
584 | # 只能通过设置样式来修改宽度, 其它设置没用
585 | logger.info(f'信息字数 {len(message)}')
586 | window_width = max(len(message) * 11, 80)
587 | logger.info(f'窗口宽度 {window_width}')
588 | self.msg.setStyleSheet("QLabel {min-width: " + str(window_width) + "px;}")
589 | # 提示信息
590 | self.msg.setText(message)
591 | # 标题
592 | self.msg.setWindowTitle(title)
593 | self.msg.show()
594 |
595 | def show_yes_no_message(self, message, title, yes_message, no_message):
596 | """
597 | 弹出框 确认是否执行
598 | 封装一个函数,方便自定义提示信息和按钮
599 | """
600 | self.msg = QMessageBox()
601 | # 设置图标
602 | self.msg.setWindowIcon(QtGui.QIcon(resource_path('QBRssManager.ico')))
603 | # 只能通过设置样式来修改宽度, 其它设置没用
604 | logger.info(f'信息字数 {len(message)}')
605 | window_width = max(len(message) * 11, 80)
606 | logger.info(f'窗口宽度 {window_width}')
607 |
608 | self.msg.setStyleSheet("QLabel {min-width: " + str(window_width) + "px;}")
609 | # 提示信息
610 | self.msg.setText(message)
611 | # 标题
612 | self.msg.setWindowTitle(title)
613 | self.msg.addButton(QPushButton(yes_message), QMessageBox.YesRole)
614 | self.msg.addButton(QPushButton(no_message), QMessageBox.RejectRole)
615 | # self.msg.show()
616 | # 这里返回0是yes, 1是no
617 | res = int(self.msg.exec_())
618 | return res
619 |
620 | @pyqtSlot()
621 | def on_double_click(self):
622 | # 防止重复触发
623 | time.sleep(0.001)
624 | # self.tableWidget.blockSignals(True)
625 |
626 | # 双击事件
627 | logger.info("on_double_click()")
628 | for currentQTableWidgetItem in self.tableWidget.selectedItems():
629 | logger.info(
630 | f'{currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text()}')
631 |
632 | # 读取feed数据 用于过滤输入
633 | if (currentQTableWidgetItem.column() in (2, 3)):
634 | self.text_browser.clear()
635 | res = self.load_type_hints(currentQTableWidgetItem.row())
636 | if res:
637 | self.text_browser.filter_type_hint()
638 |
639 | # self.tableWidget.blockSignals(False)
640 |
641 | @pyqtSlot()
642 | def on_move_up_click(self):
643 | logger.info('on_move_up_click()')
644 | # 上移事件
645 | # 防止触发 cellChange 事件导致重复更新
646 | self.tableWidget.blockSignals(True)
647 | r = self.tableWidget.currentRow()
648 | c = self.tableWidget.currentColumn()
649 | logger.info(f'{r, c}')
650 | # 未选中任何单元格时 坐标是 (-1, -1)
651 | if r == 0 or r == -1:
652 | return
653 |
654 | g.data_list[r], g.data_list[r - 1] = g.data_list[r - 1], g.data_list[r]
655 |
656 | for i in range(len(headers)):
657 | item1 = QTableWidgetItem(g.data_list[r][i])
658 | item2 = QTableWidgetItem(g.data_list[r - 1][i])
659 | if i in g.config['center_columns']:
660 | item1.setTextAlignment(Qt.AlignCenter)
661 | item2.setTextAlignment(Qt.AlignCenter)
662 | self.tableWidget.setItem(r, i, item1)
663 | self.tableWidget.setItem(r - 1, i, item2)
664 |
665 | self.tableWidget.setCurrentCell(r - 1, c)
666 |
667 | # 更新数据
668 | g.update_data_list()
669 |
670 | if g.config['auto_save']:
671 | save_config()
672 | self.tableWidget.blockSignals(False)
673 |
674 | @pyqtSlot()
675 | def on_move_down_click(self):
676 | # 下移事件
677 | # 防止触发 cellChange 事件导致重复更新
678 | self.tableWidget.blockSignals(True)
679 | r = self.tableWidget.currentRow()
680 | c = self.tableWidget.currentColumn()
681 | logger.info(f'{r, c}')
682 | if r == len(g.data_list) or r == -1:
683 | return
684 |
685 | g.data_list[r], g.data_list[r + 1] = g.data_list[r + 1], g.data_list[r]
686 |
687 | for i in range(len(headers)):
688 | item1 = QTableWidgetItem(g.data_list[r][i])
689 | item2 = QTableWidgetItem(g.data_list[r + 1][i])
690 | if i in g.config['center_columns']:
691 | item1.setTextAlignment(Qt.AlignCenter)
692 | item2.setTextAlignment(Qt.AlignCenter)
693 | self.tableWidget.setItem(r, i, item1)
694 | self.tableWidget.setItem(r + 1, i, item2)
695 |
696 | self.tableWidget.setCurrentCell(r + 1, c)
697 |
698 | # 更新数据
699 | g.update_data_list()
700 |
701 | if g.config['auto_save']:
702 | save_config()
703 | self.tableWidget.blockSignals(False)
704 |
705 | def on_tab_clicked(self, index):
706 | self.clicked_tab = index
707 | logger.info(f'当前点击的tab index {self.clicked_tab}')
708 |
709 | def on_tab_changed(self, index):
710 | """订阅分组tab切换"""
711 | logger.info(f'当前点击的tab index {self.clicked_tab}')
712 | # logger.info(f'g.current_data_list_index {g.current_data_list_index}')
713 | logger.info(f'on_tab_changed() {index}')
714 | logger.info(f'self.tab.currentIndex() {self.tab.currentIndex()}')
715 |
716 | self.tableWidget.blockSignals(True)
717 |
718 | g.current_data_list_index = index
719 |
720 | # 处理tab拖动过程中数据交换
721 | if index != self.clicked_tab:
722 | logger.info('数据交换')
723 | g.data_groups[index], g.data_groups[self.clicked_tab] = g.data_groups[self.clicked_tab], g.data_groups[
724 | index]
725 | self.tableWidget_list[index], self.tableWidget_list[self.clicked_tab] = self.tableWidget_list[
726 | self.clicked_tab], self.tableWidget_list[index]
727 | # 更新当前点击tab index
728 | self.clicked_tab = index
729 |
730 | # logger.info(f'g.data_groups {g.data_groups}')
731 |
732 | logger.info('切换数据')
733 | g.parse_v1()
734 | # logger.info(g.data_list)
735 | logger.info('刷新表格')
736 |
737 | logger.info('清理表格绑定事件, 防止右键菜单多次触发')
738 | for x in self.tableWidget_list:
739 | try:
740 | # 如果没有绑定事件这里会抛异常,忽略就行
741 | x.customContextMenuRequested.disconnect()
742 | except:
743 | pass
744 | logger.info('切换表格')
745 |
746 | # 销毁当前表格 取消绑定事件
747 | self.tableWidget.horizontalHeader().sectionResized.disconnect()
748 | self.tableWidget.doubleClicked.disconnect()
749 | self.tableWidget.cellChanged.disconnect()
750 | self.tableWidget.keyPressEvent = None
751 | # TODO: 内存没有完全清理 有泄漏
752 | del self.tableWidget
753 | self.tableWidget = self.tableWidget_list[g.current_data_list_index]
754 | logger.info('创建表格 刷新界面')
755 | self.createTable()
756 |
757 | self.tableWidget.blockSignals(False)
758 |
759 | def auto_complete(self, r, c, text):
760 | """表格内容自动填充"""
761 |
762 | def auto_complete_rss_info():
763 | # 自动填充RSS订阅地址
764 | if not g.data_list[r][6]:
765 | auto_complete = ''
766 | if g.data_groups[g.current_data_list_index]['rss_override']:
767 | auto_complete = g.data_groups[g.current_data_list_index]['rss_override']
768 | elif g.config['rss_default']:
769 | auto_complete = g.config['rss_default']
770 | else:
771 | # 获取上面填充过的RSS订阅地址
772 | for x in range(r - 1, -1, -1):
773 | if g.data_list[x][6]:
774 | auto_complete = g.data_list[x][6]
775 | break
776 | if auto_complete:
777 | g.data_list[r][6] = auto_complete
778 | item = QTableWidgetItem(auto_complete)
779 | self.tableWidget.setItem(r, 6, item)
780 |
781 | # 第一列时间进行特殊转换处理
782 | if c == 0:
783 | text = try_convert_time(text, g.config['date_auto_zfill'])
784 | self.tableWidget.currentItem().setText(text)
785 |
786 | # 填写关键字后,对其它字段进行自动填充
787 | if c == 2:
788 | logger.info('尝试自动填充')
789 | auto_complete_rss_info()
790 |
791 | # 填写保存路径后,对其它字段进行自动填充
792 | if c == 5:
793 | logger.info('尝试自动填充')
794 |
795 | # 尝试解析番剧名称
796 | series_name, year = get_series_from_season_path(text)
797 | logger.info(f'解析名称 {series_name} {year}')
798 |
799 | # 自动填充时间
800 | if not g.data_list[r][0]:
801 | # 直接使用当前时间, 忽略解析的时间
802 | auto_complete = f'{datetime.now().year}年{str(datetime.now().month).zfill(2)}月'
803 | g.data_list[r][0] = auto_complete
804 | item = QTableWidgetItem(auto_complete)
805 | # 时间居中显示
806 | item.setTextAlignment(Qt.AlignCenter)
807 | self.tableWidget.setItem(r, 0, item)
808 |
809 | # 自动填充剧集名称
810 | if not g.data_list[r][1]:
811 | auto_complete = f'{series_name}'
812 | g.data_list[r][1] = auto_complete
813 | item = QTableWidgetItem(auto_complete)
814 | self.tableWidget.setItem(r, 1, item)
815 |
816 | # 自动填充关键字
817 | # 这里用到了format 不适合放到函数里去
818 | if not g.data_list[r][2]:
819 | auto_complete = ''
820 |
821 | # 截取名称
822 | if g.config['keyword_trim_length']:
823 | # 留存原始变量
824 | tmp = series_name + ''
825 | series_name = series_name[:min(int(g.config['keyword_trim_length']), len(series_name))]
826 |
827 | if g.data_groups[g.current_data_list_index]['keyword_override']:
828 | auto_complete = g.data_groups[g.current_data_list_index]['keyword_override'].format(**locals())
829 | elif g.config['keyword_default']:
830 | auto_complete = g.config['keyword_default'].format(**locals())
831 | else:
832 | # 获取上面解析的名字
833 | auto_complete = '{series_name}'.format(**locals())
834 |
835 | if auto_complete:
836 | g.data_list[r][2] = auto_complete
837 | item = QTableWidgetItem(auto_complete)
838 | self.tableWidget.setItem(r, 2, item)
839 |
840 | # 还原原始变量
841 | if g.config['keyword_trim_length']:
842 | series_name = tmp
843 |
844 | # 自动填充RSS订阅地址
845 | auto_complete_rss_info()
846 |
847 | @pyqtSlot()
848 | def on_cell_changed(self):
849 | logger.info('on_cell_changed()')
850 |
851 | self.tableWidget.blockSignals(True)
852 |
853 | # 修改事件
854 | r = self.tableWidget.currentRow()
855 | c = self.tableWidget.currentColumn()
856 | current_item = self.tableWidget.currentItem()
857 | if not current_item:
858 | return
859 | text = self.tableWidget.currentItem().text()
860 | logger.info(f'{r, c, text}')
861 |
862 | if text:
863 | # 有输入内容时 自动补全
864 | self.auto_complete(r, c, text)
865 |
866 | g.data_list[r][c] = text
867 | # 更新数据
868 | g.update_data_list()
869 |
870 | logger.info(f'on_cell_changed 结果 {g.data_list}')
871 | if g.config['auto_save']:
872 | save_config()
873 |
874 | # 记录数据修改的时间作为简易版本号, 用来标记搜索结果是否要更新
875 | self.data_update_timestamp = int(datetime.now().timestamp() * 1000)
876 |
877 | self.tableWidget.blockSignals(False)
878 |
879 | @pyqtSlot()
880 | def on_import_exist_qb_rule_action(self):
881 | logger.info('导入qb订阅规则')
882 |
883 | # 尝试通过api读取rss配置
884 | rss_rules = []
885 |
886 | self.text_browser.append('尝试通过api和qb通信')
887 | if g.config['use_qb_api'] == 1 and check_qb_port_open(g.config['qb_api_ip'], g.config['qb_api_port']):
888 | # 使用qb的api, 可以不重启qb
889 | try:
890 | qb_client.auth_log_in(username=g.config['qb_api_username'], password=g.config['qb_api_password'])
891 | self.text_browser.append('通过api获取已有规则')
892 | rss_rules = qb_client.rss_rules()
893 | # except qbittorrentapi.LoginFailed as e:
894 | # self.text_browser.append('api登录失败')
895 | # self.text_browser.append(e)
896 | except Exception as e:
897 | logger.error(e)
898 | self.text_browser.append('通过api连接qb失败')
899 | self.text_browser.append(f'报错信息 {repr(e)}')
900 | else:
901 | self.text_browser.append('无法通过qb的api获取rss数据')
902 |
903 | if not rss_rules:
904 | self.text_browser.append('尝试读取本机rss配置文件')
905 | try:
906 | with open(g.config['rules_path'], 'r', encoding='utf-8') as f:
907 | rss_rules = json.loads(f.read())
908 | except:
909 | return
910 |
911 | self.text_browser.append('规则获取成功')
912 |
913 | # 对比表格内已有数据
914 | exist_data = {}
915 | for x in clean_data_list(g.data_list):
916 | item = {
917 | "enabled": True,
918 | "mustContain": x[2],
919 | "mustNotContain": x[3],
920 | "savePath": format_path_by_system(x[5]),
921 | "affectedFeeds": [x[6], ],
922 | "assignedCategory": x[7]
923 | }
924 | # 这里strip一下, 防止没有添加时间列匹配不到而重复导入
925 | exist_data[(x[0] + ' ' + x[1]).strip()] = item
926 |
927 | new_rules = []
928 | for x in rss_rules:
929 | if x in exist_data:
930 | if rss_rules[x] == exist_data[x]:
931 | # logger.info('重复数据 跳过')
932 | continue
933 | else:
934 | # logger.info('===== 比较数据 begin =====')
935 | # logger.info(f'规则 {rss_rules[x]}')
936 | # logger.info('')
937 | # logger.info(f'现存数据 {exist_data[x]}')
938 | check_fields = ['mustContain', 'mustNotContain', 'savePath', 'affectedFeeds', 'assignedCategory']
939 | for check_field in check_fields:
940 | if rss_rules[x][check_field] != exist_data[x][check_field]:
941 | new_rules.append(x)
942 | continue
943 | # logger.info('===== 比较数据 end =====')
944 | else:
945 | new_rules.append(x)
946 | logger.info(f'新数据 {len(new_rules)}')
947 | logger.info(new_rules)
948 |
949 | if not new_rules:
950 | return
951 |
952 | # 添加新数据 刷新表格
953 | self.tableWidget.blockSignals(True)
954 | g.data_list = clean_data_list(g.data_list)
955 | for x in new_rules:
956 | d = rss_rules[x]
957 |
958 | # 尝试分离日期
959 | release_date, series_name = try_split_date_and_name(x)
960 |
961 | g.data_list.append([
962 | release_date,
963 | series_name,
964 | d['mustContain'],
965 | d['mustNotContain'],
966 | '',
967 | format_path_by_system(d['savePath']),
968 | ','.join(d['affectedFeeds']),
969 | d['assignedCategory'],
970 | ])
971 | # 长度补充
972 | if len(g.data_list) < g.config['max_row_size']:
973 | for _ in range(g.config['max_row_size'] - len(g.data_list)):
974 | g.data_list.append(['' for x in range(len(headers))])
975 | # 更新整个列表
976 | for cx, row in enumerate(g.data_list):
977 | for cy, d in enumerate(row):
978 | item = QTableWidgetItem(d)
979 | if cy in g.config['center_columns']:
980 | item.setTextAlignment(Qt.AlignCenter)
981 | self.tableWidget.setItem(cx, cy, item)
982 | # 更新数据
983 | g.update_data_list()
984 | # 保存结果
985 | if g.config['auto_save']:
986 | save_config()
987 | self.tableWidget.blockSignals(False)
988 |
989 | @pyqtSlot()
990 | def on_import_from_share_file_action(self):
991 | logger.info('从分享文件导入规则')
992 | file_info = QFileDialog.getOpenFileName(self, "选择文件", resource_path('.'), "json 文件(*.json)")
993 | share_file_path = file_info[0]
994 | logger.info(f'导入文件 {share_file_path}')
995 |
996 | if not share_file_path:
997 | # 没有选择文件时的异常处理
998 | return
999 |
1000 | # 添加新数据 刷新表格
1001 | self.tableWidget.blockSignals(True)
1002 |
1003 | with open(share_file_path, 'r', encoding='utf-8') as f:
1004 | share_data = json.loads(f.read())
1005 | # 旧版数据兼容,以后准备删除
1006 | if 'version' not in share_data:
1007 | logger.info('导入旧版共享数据')
1008 | # 对比表格内已有数据
1009 | g.data_list = clean_data_list(g.data_list)
1010 | for x in share_data:
1011 | if x in g.data_list:
1012 | continue
1013 | g.data_list.append(x)
1014 | elif share_data['version'] == 'v1':
1015 | logger.info('导入 v1 数据')
1016 | g.data_list = clean_data_list(g.data_list)
1017 | if 'data_group' in share_data:
1018 | for x in share_data['data_group']['data']:
1019 | line = g.convert_v1_line(x)
1020 | if line in g.data_list:
1021 | continue
1022 | g.data_list.append(line)
1023 | else:
1024 | logger.info('未知格式的数据')
1025 | return
1026 |
1027 | # 长度补充
1028 | if len(g.data_list) < g.config['max_row_size']:
1029 | for _ in range(g.config['max_row_size'] - len(g.data_list)):
1030 | g.data_list.append(['' for x in range(len(headers))])
1031 | # 更新整个列表
1032 | for cx, row in enumerate(g.data_list):
1033 | for cy, d in enumerate(row):
1034 | item = QTableWidgetItem(d)
1035 | if cy in g.config['center_columns']:
1036 | item.setTextAlignment(Qt.AlignCenter)
1037 | self.tableWidget.setItem(cx, cy, item)
1038 |
1039 | # 更新数据
1040 | g.update_data_list()
1041 | # 保存结果
1042 | if g.config['auto_save']:
1043 | save_config()
1044 |
1045 | self.tableWidget.blockSignals(False)
1046 |
1047 | @pyqtSlot()
1048 | def on_export_to_share_file_action(self):
1049 | logger.info('导出规则到文件进行分享')
1050 | # 这里用完整路径可以设置默认名称
1051 | default_file_name = 'rss订阅规则分享.json'
1052 | group_name = g.data_groups[g.current_data_list_index]['name']
1053 | if group_name:
1054 | default_file_name = f"rss订阅规则分享-{group_name}.json"
1055 |
1056 | file_info = QFileDialog.getSaveFileName(self, "选择输出目录文件",
1057 | os.path.join(resource_path('.'), default_file_name),
1058 | "json 文件(*.json)")
1059 | share_file_path = file_info[0]
1060 | logger.info(f'导出文件 {share_file_path}')
1061 | if not share_file_path:
1062 | # 没有选择文件时的异常处理
1063 | return
1064 | with open(share_file_path, 'w', encoding='utf-8') as f:
1065 | # 旧版数据
1066 | # f.write(json.dumps(clean_data_list(g.data_list), ensure_ascii=False, indent=4))
1067 | # v1 结构数据
1068 | output_data = {
1069 | "version": "v1",
1070 | "data_group": {
1071 | 'name': g.data_groups[g.current_data_list_index]['name'],
1072 | 'data': g.clean_group_data(g.data_groups[g.current_data_list_index]['data']),
1073 | # 这个覆盖的配置就不导出了
1074 | # 'rss_override': g.data_groups[g.current_data_list_index]['rss_override'],
1075 | }
1076 | }
1077 | f.write(json.dumps(output_data, ensure_ascii=False, indent=4))
1078 |
1079 | @pyqtSlot()
1080 | def on_export_click(self):
1081 | logger.info('生成qb订阅规则')
1082 |
1083 | # 尝试通过api和qb通信
1084 | if g.config['use_qb_api'] == 1 and check_qb_port_open(g.config['qb_api_ip'], g.config['qb_api_port']):
1085 | # 使用qb的api, 可以不重启qb
1086 | try:
1087 | qb_client.auth_log_in(username=g.config['qb_api_username'], password=g.config['qb_api_password'])
1088 | # 要先加feed
1089 | # qb里已有的feed
1090 | rss_feeds = qb_client.rss_items()
1091 | # feed可能包含文件夹, 这里要处理嵌套的多层feed格式
1092 | rss_urls = parse_feeds_url(rss_feeds)
1093 |
1094 | # 订阅规则里所有的feed
1095 | for x in g.data_groups:
1096 | for y in g.clean_group_data(x['data']):
1097 | feed_url = y['affectedFeeds']
1098 | feed_list = parse_feed_url(feed_url)
1099 | for z in feed_list:
1100 | if not z:
1101 | continue
1102 | if z not in rss_urls:
1103 | # 第一个参数是feed的url地址 第二个是feed的名称, 似乎通过api加会自动变成正确命名
1104 | qb_client.rss_add_feed(z, z)
1105 | rss_urls.append(z)
1106 |
1107 | # 清空已有规则
1108 | rss_rules = qb_client.rss_rules()
1109 | for x in rss_rules:
1110 | qb_client.rss_remove_rule(x)
1111 |
1112 | # 添加新规则
1113 | for x in g.data_groups:
1114 | for y in g.clean_group_data(x['data']):
1115 | qb_client.rss_set_rule(
1116 | rule_name=(y['release_date'] + ' ' + y['series_name']).strip(),
1117 | rule_def={
1118 | "enabled": True,
1119 | "mustContain": y['mustContain'],
1120 | "mustNotContain": y['mustNotContain'],
1121 | "savePath": y['savePath'],
1122 | "affectedFeeds": parse_feed_url(y['affectedFeeds']),
1123 | "assignedCategory": y['assignedCategory']
1124 | }
1125 | )
1126 | # api通信不需要执行qb的exe
1127 | # subprocess.Popen([g.config['qb_executable']])
1128 |
1129 | # 如果api执行成功 就可以直接返回了
1130 | return
1131 |
1132 | # except qbittorrentapi.LoginFailed as e:
1133 | # logger.error(e)
1134 | except Exception as e:
1135 | logger.error(e)
1136 | self.text_browser.append('通过api连接qb失败')
1137 | self.text_browser.append(f'报错信息 {repr(e)}')
1138 |
1139 | else:
1140 | # 不使用qb的api, 需要重启qb
1141 | # 不使用qb的api暂时不方便添加feed
1142 | output_data = {}
1143 |
1144 | for x in g.data_groups:
1145 | for y in g.clean_group_data(x['data']):
1146 | item = {
1147 | "enabled": True,
1148 | "mustContain": y['mustContain'],
1149 | "mustNotContain": y['mustNotContain'],
1150 | "savePath": y['savePath'],
1151 | "affectedFeeds": parse_feed_url(y['affectedFeeds']),
1152 | "assignedCategory": y['assignedCategory']
1153 | }
1154 |
1155 | output_data[(y['release_date'] + ' ' + y['series_name']).strip()] = item
1156 |
1157 | logger.info(g.config['rules_path'])
1158 | with open(g.config['rules_path'], 'w', encoding='utf-8') as f:
1159 | f.write(json.dumps(output_data, ensure_ascii=False))
1160 | logger.info(g.config['open_qb_after_export'])
1161 | if g.config['open_qb_after_export']:
1162 | # 关闭qb
1163 | if os.name == 'nt':
1164 | try:
1165 | qb_executable_name = format_path(g.config['qb_executable']).rsplit('/', 1)[-1]
1166 | os.system(f'taskkill /f /im {qb_executable_name}')
1167 | except:
1168 | pass
1169 | # 启动qb
1170 | subprocess.Popen([g.config['qb_executable']])
1171 | if os.name == 'nt':
1172 | # windows 刷新任务栏托盘图标
1173 | refresh_tray()
1174 |
1175 | @pyqtSlot()
1176 | def on_load_config_click(self):
1177 | self.tableWidget.blockSignals(True)
1178 | self.tab.blockSignals(True)
1179 |
1180 | # 这里要覆盖变量
1181 | # 重置 当前点击的tab index
1182 | self.clicked_tab = 0
1183 | # 重置data list序号 防止因为新建分组再还原导致数组越界
1184 | g.current_data_list_index = 0
1185 |
1186 | g.config, g.data_list = g.init_config()
1187 |
1188 | # tab信息重新加载
1189 | tab_count = len(self.tableWidget_list)
1190 | # 删除tableWidget
1191 | for x in range(tab_count):
1192 | del self.tableWidget_list[0]
1193 | # 修改标记
1194 | g.current_data_list_index = 0
1195 |
1196 | for x in range(tab_count):
1197 | self.tab.removeTab(0)
1198 |
1199 | # 恢复 tableWidget_list
1200 | self.tableWidget_list = [QTableWidget() for _ in range(len(g.data_groups))]
1201 | # 恢复 tab
1202 | self.createTabs()
1203 |
1204 | self.tableWidget.blockSignals(False)
1205 | self.tab.blockSignals(False)
1206 |
1207 | # 切回第一个tab 重新渲染数据
1208 | self.tab.setCurrentIndex(0)
1209 | self.on_tab_changed(0)
1210 |
1211 | @pyqtSlot()
1212 | def on_save_click(self):
1213 | g.config['full_window_width'] = self.normalGeometry().width()
1214 | g.config['full_window_height'] = self.normalGeometry().height()
1215 | column_width_list_tmp = []
1216 | for i in range(len(headers)):
1217 | column_width_list_tmp.append(self.tableWidget.columnWidth(i))
1218 | g.config['column_width_list'] = column_width_list_tmp
1219 | res = save_config()
1220 | if not res:
1221 | # 还是要弹窗,要有点提示,不然容易忘记
1222 | self.show_message("保存成功", "不错不错")
1223 | # 提示信息
1224 | self.text_browser.clear()
1225 | self.text_browser.append(f'保存成功!')
1226 | else:
1227 | self.show_message("保存失败,可能是数据结构异常", "出问题了")
1228 |
1229 | @pyqtSlot()
1230 | def on_clean_row_click(self):
1231 | # 防止触发 cellChange 事件导致重复更新
1232 | self.tableWidget.blockSignals(True)
1233 | g.data_list = clean_data_list(g.data_list)
1234 | # 长度补充
1235 | if len(g.data_list) < g.config['max_row_size']:
1236 | for _ in range(g.config['max_row_size'] - len(g.data_list)):
1237 | g.data_list.append(['' for x in range(len(headers))])
1238 | # 更新整个列表
1239 | for cx, row in enumerate(g.data_list):
1240 | for cy, d in enumerate(row):
1241 | item = QTableWidgetItem(d)
1242 | if cy in g.config['center_columns']:
1243 | item.setTextAlignment(Qt.AlignCenter)
1244 | self.tableWidget.setItem(cx, cy, item)
1245 |
1246 | # 更新数据
1247 | g.update_data_list()
1248 |
1249 | self.tableWidget.blockSignals(False)
1250 |
1251 | @pyqtSlot()
1252 | def on_backup_click(self):
1253 | """备份配置"""
1254 | # 先保存再备份
1255 | save_config()
1256 | logger.info('备份')
1257 | backup_file_name = f'config_{datetime.now()}.json'
1258 | logger.info(backup_file_name)
1259 | zip_obj = ZipFile('backup.zip', 'a')
1260 | zip_obj.write('config.json', backup_file_name)
1261 | logger.info('备份完成')
1262 | self.show_message('备份完成', '不怕手抖')
1263 |
1264 | @pyqtSlot()
1265 | def on_group_add_action(self):
1266 | logger.info('on_group_add_action()')
1267 | # 添加data_group
1268 | g.data_groups.append(copy.deepcopy(g.new_data_group))
1269 | # 添加tableWidget
1270 | self.tableWidget_list.append(QTableWidget())
1271 | # 修改标记
1272 | g.current_data_list_index = len(g.data_groups) - 1
1273 | # 添加tab
1274 | self.tab.addTab(self.tableWidget_list[g.current_data_list_index],
1275 | g.data_groups[g.current_data_list_index]['name'])
1276 | # 修改tab index 记录 防止发生数据交换
1277 | self.clicked_tab = g.current_data_list_index
1278 | # 修改tab焦点
1279 | self.tab.setCurrentIndex(g.current_data_list_index)
1280 |
1281 | @pyqtSlot()
1282 | def on_group_delete_action(self, tab_index=None):
1283 | logger.info(f'on_group_delete_action(), {tab_index}')
1284 |
1285 | # 这里要注意不能写成 if not tab_index, 因为 tab_index 如果是0是合法的
1286 | if tab_index is None:
1287 | tab_index = self.tab.currentIndex()
1288 |
1289 | logger.info(f'准备删除tab {tab_index}')
1290 |
1291 | res = self.show_yes_no_message(f"确认要删除分组 {g.data_groups[tab_index]['name']} 吗?", '警告', '是', '否')
1292 | if res != 0:
1293 | return
1294 |
1295 | if len(self.tableWidget_list) > 1:
1296 | # 删除data_group
1297 | g.data_groups.pop(tab_index)
1298 | # 删除tableWidget
1299 | del self.tableWidget_list[tab_index]
1300 | # 修改标记(不能小于0)
1301 | g.current_data_list_index = max(len(g.data_groups), 0)
1302 | # 修正 tab index
1303 | if tab_index == self.clicked_tab:
1304 | self.clicked_tab -= 1
1305 |
1306 | # 删除tab
1307 | self.tab.removeTab(tab_index)
1308 | else:
1309 | logger.info('只剩最后一个tab')
1310 | # 处理data_group
1311 | g.data_groups.pop(tab_index)
1312 | g.data_groups.append(copy.deepcopy(g.new_data_group))
1313 |
1314 | # 删除tableWidget
1315 | del self.tableWidget_list[tab_index]
1316 | self.tableWidget_list.append(QTableWidget())
1317 |
1318 | # 修改标记
1319 | g.current_data_list_index = 0
1320 | # 修正 tab index
1321 | self.clicked_tab = 0
1322 |
1323 | # 删除tab
1324 | self.tab.removeTab(tab_index)
1325 | self.tab.addTab(self.tableWidget_list[g.current_data_list_index],
1326 | g.data_groups[g.current_data_list_index]['name'])
1327 |
1328 | def handle_key_press(self, event):
1329 | if event.key() in (Qt.Key_Return, Qt.Key_Enter, Qt.Key_F2):
1330 | logger.info('edit cell')
1331 | # PyQt5.QtCore.QModelIndex
1332 | currentQTableWidgetItem = self.tableWidget.currentItem()
1333 | logger.info(
1334 | f'{currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text()}')
1335 | # 读取feed数据 用于过滤输入
1336 | if (currentQTableWidgetItem.column() in (2, 3)):
1337 | self.text_browser.clear()
1338 | res = self.load_type_hints(currentQTableWidgetItem.row())
1339 | if res:
1340 | self.text_browser.filter_type_hint()
1341 |
1342 | self.tableWidget.edit(self.tableWidget.currentIndex())
1343 |
1344 | # 复制粘贴
1345 | elif event.key() == Qt.Key_C and (event.modifiers() & Qt.ControlModifier):
1346 | logger.info('ctrl c')
1347 | self.copied_cells = sorted(self.tableWidget.selectedIndexes())
1348 | logger.info(f'复制了 {len(self.copied_cells)} 个')
1349 |
1350 | # 清空剪贴板
1351 | # app.clipboard().setText('')
1352 |
1353 | # 尝试构造 excel 格式数据
1354 | if len(self.copied_cells) > 0:
1355 | # 找出输出区域坐标
1356 | min_row = self.copied_cells[0].row()
1357 | max_row = self.copied_cells[0].row()
1358 | min_col = self.copied_cells[0].column()
1359 | max_col = self.copied_cells[0].column()
1360 |
1361 | for cell in self.copied_cells:
1362 | min_row = min(min_row, cell.row())
1363 | max_row = max(max_row, cell.row())
1364 | min_col = min(min_col, cell.column())
1365 | max_col = max(max_col, cell.column())
1366 |
1367 | logger.info(f'{min_row} {max_row} {min_col} {max_col}')
1368 |
1369 | tmp_row_count = max_row - min_row + 1
1370 | tmp_col_count = max_col - min_col + 1
1371 |
1372 | # 构造输出文本
1373 | tmp_list = [["" for x in range(tmp_col_count)] for y in range(tmp_row_count)]
1374 |
1375 | for cell in self.copied_cells:
1376 | tmp_list[cell.row() - min_row][cell.column() - min_col] = cell.data()
1377 |
1378 | # excel 列数据以\t分隔 行数据以\n分隔
1379 | lines = []
1380 | for r in tmp_list:
1381 | line = '\t'.join(r)
1382 | lines.append(line)
1383 | excel_text = '\n'.join(lines)
1384 | app.clipboard().setText(excel_text)
1385 |
1386 | elif event.key() == Qt.Key_V and (event.modifiers() & Qt.ControlModifier):
1387 | logger.info('ctrl v')
1388 | self.tableWidget.blockSignals(True)
1389 |
1390 | # 如果剪贴板有内容 优先粘贴剪贴板
1391 | # 可以兼容excel表格的复制粘贴
1392 | if app.clipboard().text():
1393 | r = self.tableWidget.currentRow()
1394 | c = self.tableWidget.currentColumn()
1395 | rows = app.clipboard().text().split('\n')
1396 | if len(rows) > 1 or '\t' in rows[0]:
1397 | logger.info('导入excel')
1398 | for b_r, row in enumerate(rows):
1399 | if not row:
1400 | continue
1401 | cells = row.split('\t')
1402 | logger.info(cells)
1403 |
1404 | for b_c, cell_data in enumerate(cells):
1405 | new_r = b_r + r
1406 | new_c = b_c + c
1407 | if new_c > (len(headers) - 1):
1408 | # 忽略跨行数据 防止数组越界
1409 | continue
1410 | logger.info(f'粘贴数据 {new_r, new_c, cell_data}')
1411 | item = QTableWidgetItem(cell_data)
1412 | if new_c in g.config['center_columns']:
1413 | item.setTextAlignment(Qt.AlignCenter)
1414 |
1415 | self.tableWidget.setItem(new_r, new_c, item)
1416 | g.data_list[new_r][new_c] = cell_data
1417 | # logger.info(f'粘贴结果 {g.data_list}')
1418 | # 更新数据
1419 | g.update_data_list()
1420 | # 保存结果
1421 | if g.config['auto_save']:
1422 | save_config()
1423 | else:
1424 | logger.info(f'粘贴文字 {rows}')
1425 | if isinstance(rows, list):
1426 | text = rows[0]
1427 | item = QTableWidgetItem(text)
1428 | if c in g.config['center_columns']:
1429 | item.setTextAlignment(Qt.AlignCenter)
1430 | self.tableWidget.setItem(r, c, item)
1431 | g.data_list[r][c] = text
1432 | if text:
1433 | # 有输入内容时 自动补全
1434 | self.auto_complete(r, c, text)
1435 |
1436 | # 更新数据
1437 | g.update_data_list()
1438 | # 保存结果
1439 | if g.config['auto_save']:
1440 | save_config()
1441 |
1442 | # app.clipboard().setText('')
1443 | self.tableWidget.blockSignals(False)
1444 | return
1445 | else:
1446 | # 复制增加了剪贴板写入 这个分支可能已经不会触发了 以后考虑删除
1447 | if not self.copied_cells:
1448 | return
1449 | r = self.tableWidget.currentRow() - self.copied_cells[0].row()
1450 | c = self.tableWidget.currentColumn() - self.copied_cells[0].column()
1451 | logger.info(f'准备粘贴 {len(self.copied_cells)} 个')
1452 | for cell in self.copied_cells:
1453 | new_r = cell.row() + r
1454 | new_c = cell.column() + c
1455 | if new_c > (len(headers) - 1):
1456 | # 忽略跨行数据 防止数组越界
1457 | continue
1458 | logger.info(f'粘贴数据 {new_r, new_c, cell.data()}')
1459 | item = QTableWidgetItem(cell.data())
1460 | if new_c in g.config['center_columns']:
1461 | item.setTextAlignment(Qt.AlignCenter)
1462 | self.tableWidget.setItem(new_r, new_c, item)
1463 | g.data_list[new_r][new_c] = cell.data()
1464 | logger.info(f'粘贴结果 {g.data_list}')
1465 | # 更新数据
1466 | g.update_data_list()
1467 | # 保存结果
1468 | if g.config['auto_save']:
1469 | save_config()
1470 | self.tableWidget.blockSignals(False)
1471 |
1472 | # 搜索
1473 | elif event.key() == Qt.Key_F and (event.modifiers() & Qt.ControlModifier):
1474 | logger.info('ctrl f')
1475 | pos = self.search_window.pos()
1476 | logger.info(f'self.search_window {pos.x(), pos.y()}')
1477 | self.search_window.tabs.setCurrentIndex(0)
1478 | self.search_window.show()
1479 | # 获取焦点
1480 | self.search_window.activateWindow()
1481 |
1482 | # 替换
1483 | elif event.key() == Qt.Key_H and (event.modifiers() & Qt.ControlModifier):
1484 | logger.info('ctrl h')
1485 | pos = self.search_window.pos()
1486 | logger.info(f'self.search_window {pos.x(), pos.y()}')
1487 | self.search_window.tabs.setCurrentIndex(1)
1488 | self.search_window.show()
1489 | # 获取焦点
1490 | self.search_window.activateWindow()
1491 |
1492 | # 删除数据
1493 | elif event.key() == Qt.Key_Delete:
1494 | logger.info('delete')
1495 | self.tableWidget.blockSignals(True)
1496 | for x in self.tableWidget.selectedIndexes():
1497 | r = x.row()
1498 | c = x.column()
1499 | self.tableWidget.setItem(r, c, QTableWidgetItem(""))
1500 | g.data_list[r][c] = ""
1501 | # 更新数据
1502 | g.update_data_list()
1503 | if g.config['auto_save']:
1504 | save_config()
1505 | self.tableWidget.blockSignals(False)
1506 |
1507 | # 方向键
1508 | elif event.key() == Qt.Key_Right:
1509 | logger.info('Move right')
1510 | self.tableWidget.setCurrentCell(self.tableWidget.currentRow(),
1511 | min(self.tableWidget.currentColumn() + 1, len(headers) - 1))
1512 | elif event.key() == Qt.Key_Left:
1513 | logger.info('Move left')
1514 | self.tableWidget.setCurrentCell(self.tableWidget.currentRow(),
1515 | max(self.tableWidget.currentColumn() - 1, 0))
1516 | elif event.key() == Qt.Key_Up:
1517 | logger.info('Move up')
1518 | self.tableWidget.setCurrentCell(max(self.tableWidget.currentRow() - 1, 0),
1519 | self.tableWidget.currentColumn())
1520 | elif event.key() == Qt.Key_Down:
1521 | logger.info('Move down')
1522 | self.tableWidget.setCurrentCell(max(self.tableWidget.currentRow() + 1, 0),
1523 | self.tableWidget.currentColumn())
1524 |
1525 | elif event.key() == Qt.Key_I and (event.modifiers() & Qt.ControlModifier):
1526 | # 导入excel数据
1527 | logger.info('ctrl i')
1528 | self.tableWidget.blockSignals(True)
1529 | r = self.tableWidget.currentRow()
1530 | c = self.tableWidget.currentColumn()
1531 | rows = app.clipboard().text().split('\n')
1532 | for b_r, row in enumerate(rows):
1533 | if not row:
1534 | continue
1535 | cells = row.split('\t')
1536 | logger.info(cells)
1537 |
1538 | for b_c, cell_data in enumerate(cells):
1539 | new_r = b_r + r
1540 | new_c = b_c + c
1541 | if new_c > (len(headers) - 1):
1542 | # 忽略跨行数据 防止数组越界
1543 | continue
1544 | logger.info(f'粘贴数据 {new_r, new_c, cell_data}')
1545 | self.tableWidget.setItem(new_r, new_c, QTableWidgetItem(cell_data))
1546 | g.data_list[new_r][new_c] = cell_data
1547 | logger.info(f'粘贴结果 {g.data_list}')
1548 | # 更新数据
1549 | g.update_data_list()
1550 | # 保存结果
1551 | if g.config['auto_save']:
1552 | save_config()
1553 | self.tableWidget.blockSignals(False)
1554 | elif event.key() in (Qt.Key_F3,):
1555 | self.do_search()
1556 |
1557 | elif event.key() in (Qt.Key_Escape,):
1558 | if self.search_window and self.search_window.isVisible():
1559 | self.search_window.close()
1560 |
1561 | elif event.modifiers() & Qt.AltModifier:
1562 | event_dict = {
1563 | Qt.Key_1: 0,
1564 | Qt.Key_2: 1,
1565 | Qt.Key_3: 2,
1566 | Qt.Key_4: 3,
1567 | Qt.Key_5: 4,
1568 | Qt.Key_6: 5,
1569 | Qt.Key_7: 6,
1570 | Qt.Key_8: 7,
1571 | Qt.Key_9: 8,
1572 | Qt.Key_0: 9,
1573 | }
1574 | if event.key() in event_dict:
1575 | i = event_dict[event.key()]
1576 | if i < len(g.data_groups):
1577 | g.current_data_list_index = i
1578 | self.clicked_tab = g.current_data_list_index
1579 | self.tab.setCurrentIndex(g.current_data_list_index)
1580 |
1581 | elif event.key() == Qt.Key_S and (event.modifiers() & Qt.ControlModifier):
1582 | logger.info('ctrl s')
1583 | self.on_save_click()
1584 |
1585 | # return
1586 |
1587 | def menu_delete_action(self):
1588 | # 右键菜单 删除
1589 | self.tableWidget.blockSignals(True)
1590 |
1591 | # 遍历元素找出哪些行有被选中的元素
1592 | r_list = []
1593 | for cx in range(len(g.data_list)):
1594 | delete_flag = False
1595 | for cy in range(len(headers)):
1596 | item = self.tableWidget.item(cx, cy)
1597 | if item.isSelected():
1598 | # logger.info(f'{item.isSelected()} {item.text()}')
1599 | if cx not in r_list:
1600 | r_list.append(cx)
1601 | delete_flag = True
1602 | if delete_flag:
1603 | break
1604 | logger.info(f'删除行 {r_list}')
1605 |
1606 | # r = self.tableWidget.currentRow()
1607 | # logger.info(r)
1608 | # # (临时方案, 已废弃) 修改为只删除当前行, 不清理列表
1609 | # r = self.tableWidget.currentRow()
1610 |
1611 | # 删除所有被选中的行
1612 | for r in r_list:
1613 | g.data_list[r] = ['' for _ in range(len(headers))]
1614 | cx = r
1615 | for cy in range(len(headers)):
1616 | item = QTableWidgetItem('')
1617 | if cy in g.config['center_columns']:
1618 | item.setTextAlignment(Qt.AlignCenter)
1619 | self.tableWidget.setItem(cx, cy, item)
1620 | # 更新数据
1621 | g.update_data_list()
1622 | # 保存结果
1623 | if g.config['auto_save']:
1624 | save_config()
1625 | self.tableWidget.blockSignals(False)
1626 |
1627 | def menu_delete_all_action(self):
1628 | # 右键菜单 删除所有订阅
1629 | logger.info('删除所有订阅')
1630 |
1631 | # 普通写法
1632 | # res = QMessageBox.question(self, '警告', '确认要删除所有订阅吗?', QMessageBox.Yes | QMessageBox.No)
1633 | # if res == QMessageBox.No:
1634 | # return
1635 |
1636 | res = self.show_yes_no_message('确认要删除所有订阅吗?', '警告', '是', '否')
1637 | if res != 0:
1638 | return
1639 |
1640 | self.tableWidget.blockSignals(True)
1641 | for x in range(len(g.data_list)):
1642 | g.data_list[x] = ['' for _ in range(len(headers))]
1643 | for cx in range(len(g.data_list)):
1644 | for cy in range(len(headers)):
1645 | item = QTableWidgetItem('')
1646 | if cy in g.config['center_columns']:
1647 | item.setTextAlignment(Qt.AlignCenter)
1648 | self.tableWidget.setItem(cx, cy, item)
1649 | # 更新数据
1650 | g.update_data_list()
1651 | # 保存结果
1652 | if g.config['auto_save']:
1653 | save_config()
1654 | self.tableWidget.blockSignals(False)
1655 |
1656 | def resizeEvent(self, event):
1657 | logger.info("Window has been resized")
1658 | g.config['full_window_width'] = self.normalGeometry().width()
1659 | g.config['full_window_height'] = self.normalGeometry().height()
1660 | save_config(update_data=False)
1661 |
1662 | def closeEvent(self, event):
1663 | # 主窗口的关闭按钮事件
1664 | if g.config['close_to_tray']:
1665 | logger.info('关闭按钮最小化到任务栏托盘')
1666 | self.hide()
1667 | self.tray_icon.show()
1668 | event.ignore()
1669 | else:
1670 | sys.exit()
1671 |
1672 |
1673 | sys.excepthook = catch_exceptions
1674 |
1675 | if __name__ == '__main__':
1676 | app = QApplication(sys.argv)
1677 | # 加上这个表头才有样式
1678 | app.setStyle(QStyleFactory.create('Fusion'))
1679 | ex = App()
1680 | sys.exit(app.exec_())
1681 |
--------------------------------------------------------------------------------