-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplaylistChecker.py
88 lines (68 loc) · 2.81 KB
/
playlistChecker.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
import time
import json
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
def fetchPage(session, url):
try:
response = session.get(url, timeout=30)
response.raise_for_status()
return response
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}. Retrying in 10 seconds...")
time.sleep(10)
return(fetchPage(session, url))
class Playlist:
def __init__(self, playlistId):
self.playlistId = playlistId
print(playlistId)
def getPlaylistData(self):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
session = requests.Session()
session.headers.update(headers)
response = fetchPage(session, self.playlistId)
if response.status_code != 200:
print(f"Failed to retrieve the page. Status code: {response.status_code}")
soup = BeautifulSoup(response.text, 'html.parser')
scriptTag = soup.find('script', id='urlSchemeConfig')
if not scriptTag:
return(soup) #< no redirect URL found, assuming it's the correct page
config = json.loads(scriptTag.string)
redirectUrl = config.get('redirectUrl')
if not redirectUrl:
print("Redirect URL not found in the JSON data.")
return(-2)
redirectResponse = session.get(redirectUrl, headers=headers)
if redirectResponse.status_code != 200:
print(f"Failed to retrieve the redirected page. Status code: {redirectResponse.status_code}")
return(-3)
soup = BeautifulSoup(redirectResponse.text, 'html.parser')
return(soup)
def convertToFullUrl(self, url):
urljoin(self.playlistId, url)
class PlaylistChangeListener(Playlist):
def __init__(self, playlistId):
self.playlistId = playlistId
super().__init__(playlistId)
self.prevTrackCount = self.getPlaylistTracksCount()
def getPlaylistTracksCount(self):
"""Fetch current tracks count from the playlist."""
soup = self.getPlaylistData()
songCount = soup.find_all('meta', attrs={"name": "music:song_count"})[-1]
if not songCount:
return(-4)
return(int(songCount["content"]))
def isChange(self):
trackCount = self.getPlaylistTracksCount()
if trackCount < 0:
print("failed to fetch track count")
return(False)
# Find changes (added or removed tracks)
addedTracks = trackCount - self.prevTrackCount
removedTracks = self.prevTrackCount - trackCount
if addedTracks or removedTracks:
self.prevTrackCount = trackCount
return(True)
return(False)