-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpctl
executable file
·393 lines (330 loc) · 10.8 KB
/
pctl
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#!/usr/bin/env python3
import sys
import os
import sqlite3
import random
import subprocess
import signal
from datetime import date
from urllib.parse import quote_plus
from urllib.request import Request, urlopen
import argparse
DB_PATH = os.getenv("PLAYLIST_DB_PATH")
def signal_handler(signal, frame):
sys.exit(0)
def get_db_connection():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def get_youtube_url(query):
url = f"https://www.youtube.com/results?search_query={quote_plus(query)}"
req = Request(url, headers={"User-Agent": "Mozilla/5.0"})
response = urlopen(req).read().decode("utf-8")
start_index = response.find("/watch?v=")
if start_index != -1:
end_index = response.find('"', start_index)
video_id = response[start_index:end_index]
return f"https://www.youtube.com{video_id}"
return ""
def create_playlist_if_not_exists(conn, playlist_name):
cursor = conn.cursor()
cursor.execute(
"INSERT OR IGNORE INTO playlists (title) VALUES (?)", (playlist_name,)
)
conn.commit()
return cursor.execute(
"SELECT id FROM playlists WHERE title = ?", (playlist_name,)
).fetchone()[0]
def save_track(artist, title, playlist):
"""
Saves a track and a youtube url for it to a playlist.
The playlist is created if it doesn't already exist.
:param artist: The artist of the track
:param title: The title of the track
:param playlist: The name of the playlist to add the track to
"""
conn = get_db_connection()
youtube_url = get_youtube_url(f"{artist} - {title}")
today = date.today().isoformat()
try:
cursor = conn.cursor()
# Insert track
cursor.execute(
"""
INSERT INTO tracks (date, artist, title, url)
VALUES (?, ?, ?, ?)
""",
(today, artist, title, youtube_url),
)
track_id = cursor.lastrowid
# Get or create playlist
playlist_id = create_playlist_if_not_exists(conn, playlist)
# Associate track with playlist
cursor.execute(
"""
INSERT INTO playlist_tracks (playlist_id, track_id)
VALUES (?, ?)
""",
(playlist_id, track_id),
)
conn.commit()
print(f"Track saved to playlist '{playlist}'")
except sqlite3.Error as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def list_playlists():
conn = get_db_connection()
try:
cursor = conn.cursor()
cursor.execute("SELECT title FROM playlists")
playlists = cursor.fetchall()
if not playlists:
print("No playlists found.")
else:
print("Available playlists:")
for playlist in playlists:
print(f"- {playlist['title']}")
except sqlite3.Error as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def cat_playlist(playlist):
conn = get_db_connection()
try:
cursor = conn.cursor()
cursor.execute(
"""
SELECT t.id, t.date, t.artist, t.title, t.url
FROM tracks t
JOIN playlist_tracks pt ON t.id = pt.track_id
JOIN playlists p ON p.id = pt.playlist_id
WHERE p.title = ?
""",
(playlist,),
)
tracks = cursor.fetchall()
if not tracks:
print(f"Playlist '{playlist}' not found or is empty.")
else:
print(f"Contents of '{playlist}' playlist:\n")
for track in tracks:
print(
f"ID: {track['id']}, {track['date']}, {track['artist']} - {track['title']}\nURL: {track['url']}\n"
)
except sqlite3.Error as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def remove_track(playlist, track_id):
conn = get_db_connection()
try:
cursor = conn.cursor()
# Check if the track exists in the specified playlist
cursor.execute(
"""
SELECT t.artist, t.title
FROM tracks t
JOIN playlist_tracks pt ON t.id = pt.track_id
JOIN playlists p ON p.id = pt.playlist_id
WHERE p.title = ? AND t.id = ?
""",
(playlist, track_id),
)
track = cursor.fetchone()
if not track:
print(f"Track with ID {track_id} not found in playlist '{playlist}'.")
return
# Ask for confirmation
confirm = input(
f"Are you sure you want to remove '{track['artist']} - {track['title']}' from '{playlist}'? (y/n): "
)
if confirm.lower() != "y":
print("Track removal cancelled.")
return
# Remove the track from the playlist
cursor.execute(
"""
DELETE FROM playlist_tracks
WHERE track_id = ? AND playlist_id = (SELECT id FROM playlists WHERE title = ?)
""",
(track_id, playlist),
)
# Remove the track from the tracks table if it's not in any other playlist
cursor.execute(
"""
DELETE FROM tracks
WHERE id = ? AND NOT EXISTS (
SELECT 1 FROM playlist_tracks WHERE track_id = ?
)
""",
(track_id, track_id),
)
conn.commit()
print(f"Track removed from playlist '{playlist}'")
except sqlite3.Error as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def create_playlist(playlist_name):
conn = get_db_connection()
try:
cursor = conn.cursor()
cursor.execute("INSERT INTO playlists (title) VALUES (?)", (playlist_name,))
conn.commit()
print(f"Playlist '{playlist_name}' created successfully.")
except sqlite3.IntegrityError:
print(f"Playlist '{playlist_name}' already exists.")
except sqlite3.Error as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def remove_playlist(playlist_name):
conn = get_db_connection()
try:
cursor = conn.cursor()
# Check if the playlist exists and is empty
cursor.execute(
"""
SELECT COUNT(*) as track_count
FROM playlist_tracks pt
JOIN playlists p ON p.id = pt.playlist_id
WHERE p.title = ?
""",
(playlist_name,),
)
result = cursor.fetchone()
if result is None:
print(f"Playlist '{playlist_name}' not found.")
return
if result["track_count"] > 0:
print(f"Cannot remove playlist '{playlist_name}'. It is not empty.")
return
# Ask for confirmation
confirm = input(
f"Are you sure you want to remove the playlist '{playlist_name}'? (y/n): "
)
if confirm.lower() != "y":
print("Playlist removal cancelled.")
return
# Remove the playlist
cursor.execute("DELETE FROM playlists WHERE title = ?", (playlist_name,))
conn.commit()
print(f"Playlist '{playlist_name}' removed successfully.")
except sqlite3.Error as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def get_mpv_command(urls, shuffle=True):
if shuffle:
random.shuffle(urls)
mpv_command = [
"mpv",
"--no-video",
"--osd-level=3",
"--force-window=no",
"--osd-duration=99999",
"--term-osd-bar",
"--term-osd=force",
"--term-playing-msg=${playlist-pos-1}/${playlist-count} - ${media-title}",
]
mpv_command.extend(urls)
return mpv_command
def play_playlist(playlist_name, shuffle=True):
conn = get_db_connection()
try:
cursor = conn.cursor()
cursor.execute(
"""
SELECT t.url
FROM tracks t
JOIN playlist_tracks pt ON t.id = pt.track_id
JOIN playlists p ON p.id = pt.playlist_id
WHERE p.title = ?
""",
(playlist_name,),
)
tracks = cursor.fetchall()
if not tracks:
print(f"Playlist '{playlist_name}' not found or is empty.")
return
urls = [track["url"] for track in tracks]
mpv_command = get_mpv_command(urls, shuffle)
subprocess.run(mpv_command)
except sqlite3.Error as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def play_radio():
conn = get_db_connection()
try:
cursor = conn.cursor()
cursor.execute("SELECT radio_name, url FROM radios")
radios = cursor.fetchall()
if not radios:
print("No radios found in the database.")
return
urls = [radio["url"] for radio in radios]
mpv_command = get_mpv_command(urls, shuffle=False)
subprocess.run(mpv_command)
except sqlite3.Error as e:
print(f"An error occurred: {e}")
finally:
conn.close()
def main():
# Handle CNTRL-C gracefully
signal.signal(signal.SIGINT, signal_handler)
parser = argparse.ArgumentParser(description="Playlist control utility")
parser.add_argument(
"command",
choices=[
"ls",
"l",
"cat",
"save",
"s",
"rm",
"create",
"rmpl",
"rmplaylist",
"play",
"p",
"radio",
],
help="Command to execute",
)
parser.add_argument("args", nargs="*", help="Additional arguments")
parser.add_argument(
"--no-shuffle", action="store_false", help="Don't shuffle playlist when playing"
)
args = parser.parse_args()
if args.command in ["ls", "l"]:
list_playlists()
elif args.command == "cat" and len(args.args) == 1:
cat_playlist(args.args[0])
elif args.command in ["save", "s"] and len(args.args) == 3:
artist, title, playlist = args.args
save_track(artist, title, playlist)
elif args.command == "rm" and len(args.args) == 2:
playlist, track_id = args.args
remove_track(playlist, int(track_id))
elif args.command == "create" and len(args.args) == 1:
create_playlist(args.args[0])
elif args.command in ["rmpl", "rmplaylist"] and len(args.args) == 1:
remove_playlist(args.args[0])
elif args.command in ["play", "p"] and len(args.args) == 1:
play_playlist(args.args[0], shuffle=args.no_shuffle)
elif args.command == "radio":
play_radio()
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
try:
if not DB_PATH:
print("PLAYLIST_DB_PATH environment variable not set.")
sys.exit(1)
main()
except Exception as e:
print(f"An unexpected error occurred: {e}")
sys.exit(1)