forked from Guovin/iptv-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
275 lines (241 loc) · 8.12 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
try:
import user_config as config
except ImportError:
import config
import aiohttp
import asyncio
import time
import re
import datetime
import os
import urllib.parse
import ipaddress
from urllib.parse import urlparse
def getChannelItems():
"""
Get the channel items from the source file
"""
# Open the source file and read all lines.
try:
user_source_file = (
"user_" + config.source_file
if os.path.exists("user_" + config.source_file)
else getattr(config, "source_file", "demo.txt")
)
with open(user_source_file, "r", encoding="utf-8") as f:
lines = f.readlines()
# Create a dictionary to store the channels.
channels = {}
current_category = ""
pattern = r"^(.*?),(?!#genre#)(.*?)$"
for line in lines:
line = line.strip()
if "#genre#" in line:
# This is a new channel, create a new key in the dictionary.
current_category = line.split(",")[0]
channels[current_category] = {}
else:
# This is a url, add it to the list of urls for the current channel.
match = re.search(pattern, line)
if match:
if match.group(1) not in channels[current_category]:
channels[current_category][match.group(1)] = [match.group(2)]
else:
channels[current_category][match.group(1)].append(
match.group(2)
)
return channels
finally:
f.close()
def updateChannelUrlsTxt(cate, channelUrls):
"""
Update the category and channel urls to the final file
"""
try:
with open("result_new.txt", "a", encoding="utf-8") as f:
f.write(cate + ",#genre#\n")
for name, urls in channelUrls.items():
for url in urls:
if url is not None:
f.write(name + "," + url + "\n")
f.write("\n")
finally:
f.close
def updateFile(final_file, old_file):
"""
Update the file
"""
if os.path.exists(old_file):
os.replace(old_file, final_file)
def getUrlInfo(result):
"""
Get the url, date and resolution
"""
url = date = resolution = None
result_div = [div for div in result.children if div.name == "div"]
if 1 < len(result_div):
channel_text = result_div[1].get_text(strip=True)
url_match = re.search(
r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
channel_text,
)
if url_match:
url = url_match.group()
info_text = result_div[-1].get_text(strip=True)
if info_text:
date, resolution = (
(info_text.partition(" ")[0] if info_text.partition(" ")[0] else None),
(
info_text.partition(" ")[2].partition("•")[2]
if info_text.partition(" ")[2].partition("•")[2]
else None
),
)
return url, date, resolution
async def getSpeed(url, urlTimeout=5):
"""
Get the speed of the url
"""
async with aiohttp.ClientSession() as session:
start = time.time()
try:
async with session.get(url, timeout=urlTimeout) as response:
resStatus = response.status
except:
return float("inf")
end = time.time()
if resStatus == 200:
return int(round((end - start) * 1000))
else:
return float("inf")
async def compareSpeedAndResolution(infoList):
"""
Sort by speed and resolution
"""
response_times = await asyncio.gather(*(getSpeed(url) for url, _, _ in infoList))
valid_responses = [
(info, rt) for info, rt in zip(infoList, response_times) if rt != float("inf")
]
def extract_resolution(resolution_str):
numbers = re.findall(r"\d+x\d+", resolution_str)
if numbers:
width, height = map(int, numbers[0].split("x"))
return width * height
else:
return 0
default_response_time_weight = 0.5
default_resolution_weight = 0.5
response_time_weight = getattr(
config, "response_time_weight", default_response_time_weight
)
resolution_weight = getattr(config, "resolution_weight", default_resolution_weight)
# Check if weights are valid
if not (
0 <= response_time_weight <= 1
and 0 <= resolution_weight <= 1
and response_time_weight + resolution_weight == 1
):
response_time_weight = default_response_time_weight
resolution_weight = default_resolution_weight
def combined_key(item):
(_, _, resolution), response_time = item
resolution_value = extract_resolution(resolution) if resolution else 0
return (
-(response_time_weight * response_time)
+ resolution_weight * resolution_value
)
sorted_res = sorted(valid_responses, key=combined_key, reverse=True)
return sorted_res
def filterByDate(data):
"""
Filter by date and limit
"""
default_recent_days = 60
use_recent_days = getattr(config, "recent_days", 60)
if (
not isinstance(use_recent_days, int)
or use_recent_days <= 0
or use_recent_days > 365
):
use_recent_days = default_recent_days
start_date = datetime.datetime.now() - datetime.timedelta(days=use_recent_days)
recent_data = []
unrecent_data = []
for (url, date, resolution), response_time in data:
if date:
date = datetime.datetime.strptime(date, "%m-%d-%Y")
if date >= start_date:
recent_data.append(((url, date, resolution), response_time))
else:
unrecent_data.append(((url, date, resolution), response_time))
if len(recent_data) < config.urls_limit:
recent_data.extend(unrecent_data[: config.urls_limit - len(recent_data)])
return recent_data[: config.urls_limit]
def getTotalUrls(data):
"""
Get the total urls with filter by date and depulicate
"""
total_urls = []
if len(data) > config.urls_limit:
total_urls = [url for (url, _, _), _ in filterByDate(data)]
else:
total_urls = [url for (url, _, _), _ in data]
return list(dict.fromkeys(total_urls))
def is_ipv6(url):
"""
Check if the url is ipv6
"""
try:
host = urllib.parse.urlparse(url).hostname
ipaddress.IPv6Address(host)
return True
except ValueError:
return False
def checkUrlIPVType(url):
"""
Check if the url is compatible with the ipv type in the config
"""
ipv_type = getattr(config, "ipv_type", "ipv4")
if ipv_type == "ipv4":
return not is_ipv6(url)
elif ipv_type == "ipv6":
return is_ipv6(url)
else:
return True
def checkByDomainBlacklist(url):
"""
Check by domain blacklist
"""
domain_blacklist = [
urlparse(domain).netloc if urlparse(domain).scheme else domain
for domain in getattr(config, "domain_blacklist", [])
]
return urlparse(url).netloc not in domain_blacklist
def checkByURLKeywordsBlacklist(url):
"""
Check by URL blacklist keywords
"""
url_keywords_blacklist = getattr(config, "url_keywords_blacklist", [])
return not any(keyword in url for keyword in url_keywords_blacklist)
def filterUrlsByPatterns(urls):
"""
Filter urls by patterns
"""
urls = [url for url in urls if checkUrlIPVType(url)]
urls = [url for url in urls if checkByDomainBlacklist(url)]
urls = [url for url in urls if checkByURLKeywordsBlacklist(url)]
return urls
async def useAccessibleUrl():
"""
Check if the url is accessible
"""
baseUrl1 = "https://www.foodieguide.com/iptvsearch/"
baseUrl2 = "http://tonkiang.us/"
speed1 = await getSpeed(baseUrl1, 30)
speed2 = await getSpeed(baseUrl2, 30)
if speed1 == float("inf") and speed2 == float("inf"):
return None
if speed1 < speed2:
return baseUrl1
else:
return baseUrl2