-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackup.py
132 lines (111 loc) · 4.25 KB
/
backup.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
"""
spotify-backup - A simple command line tool to back up your Spotify playlists.
Copyright (C) 2022 Şuayip Üzülmez <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
import argparse
import base64
import csv
import os
import time
from urllib.parse import urlparse
import requests
BASE_URL = "https://api.spotify.com/v1/"
PLAYLIST_URL = BASE_URL + "playlists/%(id)s/"
TRACKS_URL = PLAYLIST_URL + (
"tracks?fields="
"next,items(added_at,track(name,duration_ms,artists.name,album.name)"
)
def _get_authenticated_session(client_id, client_secret):
token = client_id + ":" + client_secret
token = base64.b64encode(token.encode("utf-8"))
token = "Basic %s" % token.decode("utf-8")
session = requests.Session()
session.headers = {"Authorization": token}
response = session.post(
"https://accounts.spotify.com/api/token",
data={"grant_type": "client_credentials"},
)
assert response.status_code == 200, "Check your credentials"
content = response.json()
authorization = "%s %s" % (
content["token_type"],
content["access_token"],
)
session.headers = {"Authorization": authorization}
return session
def _parse_item(item):
track = item["track"]
name = track["name"]
added_at = item["added_at"]
album = track["album"]["name"]
artists = ", ".join(artist["name"] for artist in track["artists"]).strip()
duration = track["duration_ms"]
return name, artists, album, duration, added_at
def _parse_playlist(playlist):
if "spotify" not in playlist:
return playlist
return urlparse(playlist).path.split("/")[-1]
def pull(client_id, client_secret, playlist_id, filename=None):
session = _get_authenticated_session(client_id, client_secret)
response = session.get(PLAYLIST_URL % {"id": playlist_id})
assert response.status_code == 200, "Invalid playlist specified"
playlist = response.json()
filename = filename or "%s_%d" % (playlist["name"], time.time())
csvfile = open("%s.csv" % filename, "w", newline="")
writer = csv.writer(csvfile)
writer.writerow(("name", "artists", "album", "duration", "added_at"))
tracks = session.get(TRACKS_URL % {"id": playlist_id}).json()
while True:
for item in tracks["items"]:
writer.writerow(_parse_item(item))
if not tracks["next"]:
break
tracks = session.get(tracks["next"]).json()
csvfile.close()
session.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Dumps your spotify playlist into a CSV file."
" You may get related credentials here:"
" https://developer.spotify.com/dashboard/applications"
)
parser.add_argument(
"playlist",
type=str,
help="Spotify link or ID of the playlist.",
)
parser.add_argument(
"--client_id",
type=str,
help="Specify client id from Spotify."
" If not specified, looks for 'SPOTIFY_CLIENT_ID'"
" environment variable.",
)
parser.add_argument(
"--client_secret",
type=str,
help="Specify client secret from Spotify."
" If not specified, looks for 'SPOTIFY_CLIENT_SECRET'"
" environment variable.",
)
parser.add_argument(
"--filename",
type=str,
help="Specify a filename for the backup."
" Defaults to playlist name with UTC timestamp.",
)
args = parser.parse_args()
_client_id = args.client_id or os.environ["SPOTIFY_CLIENT_ID"]
_client_secret = args.client_secret or os.environ["SPOTIFY_CLIENT_SECRET"]
_playlist_id = _parse_playlist(args.playlist)
pull(_client_id, _client_secret, _playlist_id, args.filename)