| 193 | |
| 194 | # ===================== 频道分类核心 ===================== |
| 195 | class ChannelClassifier: |
| 196 | def __init__(self, main_dict: dict, local_dict: dict, blacklist: set): |
| 197 | self.main_dict = main_dict |
| 198 | self.local_dict = local_dict |
| 199 | self.blacklist = blacklist |
| 200 | self.channel_data = {} |
| 201 | self.other_lines = [] |
| 202 | self.other_urls = set() |
| 203 | self.all_urls = {} |
| 204 | # === 全局单频道限流 新增:单频道计数字典 === |
| 205 | self.single_chn_count = {} # key: 频道名(如CCTV1), value: 已添加源数量 |
| 206 | # 初始化分类数据 |
| 207 | for chn_type in list(main_dict.keys()) + list(local_dict.keys()): |
| 208 | self.channel_data[chn_type] = [] |
| 209 | self.all_urls[chn_type] = set() |
| 210 | |
| 211 | def check_url_exist(self, chn_type: str, url: str) -> bool: |
| 212 | if url in self.all_urls.get(chn_type, set()) or "127.0.0.1" in url: |
| 213 | return True |
| 214 | return False |
| 215 | |
| 216 | # === 全局单频道限流 === |
| 217 | def is_single_chn_limit(self, channel_name: str) -> bool: |
| 218 | if SINGLE_CHANNEL_MAX_COUNT == -1: |
| 219 | return False # -1表示无限制 |
| 220 | # 获取该频道已添加数量,默认0 |
| 221 | current_count = self.single_chn_count.get(channel_name, 0) |
| 222 | # 达到上限返回True,否则False |
| 223 | if current_count >= SINGLE_CHANNEL_MAX_COUNT: |
| 224 | return True |
| 225 | return False |
| 226 | |
| 227 | def add_channel_line(self, chn_type: str, line: str, url: str): |
| 228 | self.channel_data[chn_type].append(line) |
| 229 | self.all_urls[chn_type].add(url) |
| 230 | # === 全局单频道限流 新增:更新单频道计数 === |
| 231 | channel_name = line.split(',')[0].strip() |
| 232 | self.single_chn_count[channel_name] = self.single_chn_count.get(channel_name, 0) + 1 |
| 233 | |
| 234 | def add_other_line(self, line: str, url: str): |
| 235 | if url not in self.other_urls and url not in self.blacklist: |
| 236 | self.other_urls.add(url) |
| 237 | self.other_lines.append(line) |
| 238 | |
| 239 | # === 全局单频道限流 === |
| 240 | def classify(self, channel_name: str, channel_url: str, line: str): |
| 241 | # 先判断:黑名单/空URL → 跳过;单频道达上限 → 跳过 |
| 242 | if channel_url in self.blacklist or not channel_url or self.is_single_chn_limit(channel_name): |
| 243 | return |
| 244 | # 原有分类逻辑不变 |
| 245 | for chn_type, chn_names in self.main_dict.items(): |
| 246 | if channel_name in chn_names and not self.check_url_exist(chn_type, channel_url): |
| 247 | self.add_channel_line(chn_type, line, channel_url) |
| 248 | return |
| 249 | for chn_type, chn_names in self.local_dict.items(): |
| 250 | if channel_name in chn_names and not self.check_url_exist(chn_type, channel_url): |
| 251 | self.add_channel_line(chn_type, line, channel_url) |
| 252 | return |