Repository navigation
Expand file tree
/
Copy pathofflinesonic.py
More file actions
98 lines (80 loc) · 2.84 KB
/
Copy pathofflinesonic.py
File metadata and controls
98 lines (80 loc) · 2.84 KB
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
import sqlite3
import asyncio
import aiohttp
import datetime
import json
import yt_dlp
from ytmusicapi import YTMusic
def my_hook(d):
if d['status'] == 'finished':
print(d['filename'])
def download(url,artist,title):
ydl_opts = {
'format': "bestaudio[ext=m4a]",
'outtmpl': f'/vids/lolmusic/sonic/{artist} - {title}.m4a',
'progress_hooks': [my_hook]}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
ytmusic = YTMusic()
loop = asyncio.get_event_loop()
session = aiohttp.ClientSession(loop=loop)
conn = sqlite3.connect("sonic.sqlite")
c = conn.cursor()
q = "SELECT name FROM sqlite_master WHERE type='table' AND name='songs';"
result = c.execute(q).fetchone()
if not result:
q = '''CREATE TABLE 'songs' (
"artist" text,
"title" text,
"album" text,
"spotify" text,
"firstseen" integer,
"count" integer default '1'
);'''
c.execute(q)
c.execute("CREATE INDEX songid ON songs (artist, title);")
conn.commit()
url = 'https://player.rogersradio.ca/chdi/widget/recently_played?page=0&num_per_page=10'
async def update():
lastseen = 1631153871 #TODO - keep this number for restarts?
while True:
dt = datetime.datetime.now()
print(f'running at {dt}')
async with session.get(url) as resp:
data = await resp.json()
lastsong = ""
for song in reversed(data):
if song['updated_at'] > lastseen:
if f"{song['artist']} {song['song_title']}" == lastsong:
# they occasionally dupe them
print(f"Duplicate song {song['artist']} {song['song_title']}")
continue
await dbcheck(song)
lastseen = song['updated_at']
lastsong = f"{song['artist']} {song['song_title']}"
await asyncio.sleep(30 * 60)
async def dbcheck(song):
artist = song['artist']
title = song['song_title']
q = "SELECT count FROM songs WHERE artist=(?) AND title=(?)"
res = c.execute(q, (artist, title)).fetchone()
if res:
q = "UPDATE songs SET count=count+1 WHERE artist=(?) AND title=(?)"
c.execute(q, (artist, title))
else:
q = "INSERT INTO songs(artist, title, album, spotify, firstseen, count) VALUES (?, ?, ?, ?, ?, 1)"
c.execute(q, (artist, title, song['album'], song['spotify'], song['updated_at']))
res = ytmusic.search(f"{artist} {title}", filter="songs")
yturl = f"https://music.youtube.com/watch?v={res[0]['videoId']}"
print(artist, title, yturl)
download(yturl, artist, title)
conn.commit()
try:
task = asyncio.ensure_future(update())
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
print("Closing Loop")
session.close()
loop.close()