-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
283 lines (244 loc) · 10.8 KB
/
Copy pathapp.py
File metadata and controls
283 lines (244 loc) · 10.8 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
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
import tempfile
import sentry_sdk
from flask import Flask, request, redirect, session, Response
from helpers.config import *
from helpers import spotify, git, files, database, time
sentry_sdk.init(
# Read SENTRY_DSN from environment
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for tracing.
traces_sample_rate=1.0,
_experiments={
# Set continuous_profiling_auto_start to True
# to automatically start the profiler on when
# possible.
"continuous_profiling_auto_start": True,
},
)
app = Flask(__name__)
app.secret_key = os.urandom(24)
# Helper functions
def login_redirect(redirect_url=None):
session['previous_page'] = redirect_url or request.url
auth_url = spotify.spotify_oauth().get_authorize_url()
return redirect(auth_url)
def run_export(sp, config):
"""
Executes the main export process for Spotify playlists.
This function performs the following steps:
1. Fetches all playlists from the user's Spotify account.
2. Sets up the archive directory and initializes/updates the Git repository.
3. Writes metadata for all playlists to a JSON file.
4. Writes individual JSON files for each playlist's tracks.
5. Commits all changes to the Git repository.
6. Pushes changes to the remote repository if configured.
Args:
sp (spotipy.Spotify): An authenticated Spotify client object.
config (dict): A dictionary containing configuration settings.
Note:
This function may take a while to complete, especially for users with many playlists.
Returns:
A generator of status messages.
"""
try:
repo = git.setup_archive(config)
playlists = yield from spotify.fetch_playlists(sp, config)
yield from files.write_playlists_metadata(playlists, config)
yield from files.write_playlist_tracks(playlists, config)
yield from git.commit_and_push_changes(repo, config)
except Exception as e:
yield f"Error: {str(e)}"
raise e
# Routes
@app.route('/health', methods=['GET'])
def health_check():
return {"status": "healthy"}, 200
@app.route('/error')
def error():
raise Exception("Test error")
@app.route('/login')
def login():
return login_redirect('/')
@app.route('/authorize')
def authorize():
sp_oauth = spotify.spotify_oauth()
sp_oauth.get_access_token(request.args['code'])
sp = spotify.spotify_client(sp_oauth)
if sp:
user_info = sp.me()
session['user_id'] = user_info['id']
return redirect(session.pop('previous_page', '/'))
return {"error": "Failed to get access token"}, 400
@app.route('/export', methods=['GET'])
def export():
sp = spotify.spotify_client()
if not sp:
return login_redirect()
# Record backup start time
database.update_user_last_export(session['user_id'])
# Create temporary directory for this export
export_dir = tempfile.mkdtemp()
archive_dir = os.path.join(export_dir, 'spotify-archive')
config = {
**config_for_user(session['user_id']),
ARCHIVE_DIR_KEY: archive_dir
}
# Return initial response with progress indicator
def generate():
yield from map(lambda msg: msg + '\n', run_export(sp, config))
yield "Export complete! Close this tab and view your archive on GitHub."
return Response(generate(), mimetype='text/plain')
@app.route('/last-backup')
def last_backup():
if 'user_id' not in session:
return {"error": "Not logged in"}, 401
last_export = database.get_user_last_export(session['user_id'])
return {
"last_backup": time.format_time_since(last_export) if last_export else None
}
@app.route('/config', methods=['GET', 'POST'])
def config():
if 'user_id' not in session:
return login_redirect()
current_config = config_for_user(session['user_id'])
if request.method == 'POST':
new_config = {
**current_config,
INCLUDE_LIKED_SONGS_KEY: INCLUDE_LIKED_SONGS_KEY in request.form,
EXCLUDE_PLAYLISTS_KEY: [p.strip() for p in request.form.get(EXCLUDE_PLAYLISTS_KEY, '').split('\n') if p.strip()],
GITHUB_VIEWERS_KEY: [u.strip() for u in request.form.get(GITHUB_VIEWERS_KEY, '').split('\n') if u.strip()],
}
if new_config != current_config:
database.update_user_config(session['user_id'], new_config)
if new_config[GITHUB_VIEWERS_KEY] != current_config[GITHUB_VIEWERS_KEY]:
error_messages = git.update_repository_access(new_config)
# TODO: Add flash message with error messages
return redirect('/')
html = f"""
<html>
<head>
<title>Spogitify - Configuration</title>
<style>
.form-group {{ margin: 20px 0; }}
label {{ display: block; margin-bottom: 5px; }}
textarea {{ width: 100%; height: 100px; }}
.button-group {{ display: flex; gap: 10px; }}
.button-group button {{ flex: 1; }}
.secondary {{ background: #6c757d !important; }}
</style>
<script>
let formChanged = false;
function trackChanges() {{
formChanged = true;
}}
function confirmDiscard() {{
if (formChanged) {{
return confirm('You have unsaved changes. Are you sure you want to go back?');
}}
return true;
}}
</script>
</head>
<body style="max-width: 800px; margin: 40px auto; padding: 0 20px; font-family: system-ui, sans-serif;">
<h1>Configuration</h1>
<form method="POST" onchange="trackChanges()">
<div class="form-group">
<label>
<input type="checkbox" name="{INCLUDE_LIKED_SONGS_KEY}" id="{INCLUDE_LIKED_SONGS_KEY}"
{' checked' if current_config.get(INCLUDE_LIKED_SONGS_KEY) else ''}>
Include Liked Songs
</label>
</div>
<div class="form-group">
<label for="{EXCLUDE_PLAYLISTS_KEY}">Exclude these playlists (one per line):</label>
<textarea name="{EXCLUDE_PLAYLISTS_KEY}" id="{EXCLUDE_PLAYLISTS_KEY}">{chr(10).join(current_config.get(EXCLUDE_PLAYLISTS_KEY, []))}</textarea>
</div>
<div class="form-group">
<label for="{GITHUB_VIEWERS_KEY}">Share with GitHub users (one username per line):<br>
<small style="color: #666;">Leave empty to make the repository public, or add GitHub usernames to make it private and shared with specific users.</small></label>
<textarea name="{GITHUB_VIEWERS_KEY}" id="{GITHUB_VIEWERS_KEY}">{chr(10).join(current_config.get(GITHUB_VIEWERS_KEY, []))}</textarea>
</div>
<div class="button-group" style="margin-top: 30px;">
<button type="submit" style="background: #1DB954; color: white; border: none; padding: 10px 20px; border-radius: 20px; cursor: pointer; font-size: 16px;">
Save Changes
</button>
<a href="/" onclick="return confirmDiscard()">
<button type="button" style="background: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 20px; cursor: pointer; font-size: 16px; width: 100%;">
Cancel
</button>
</a>
</div>
</form>
</body>
</html>
"""
return html
@app.route('/')
def home():
sp = spotify.spotify_client()
# Common button style
button_style = 'background: #1DB954; color: white; border: none; padding: 10px 20px; border-radius: 20px; cursor: pointer; font-size: 16px;'
# Common HTML header and description
html = f"""
<html>
<head><title>Spogitify - Spotify Playlist Backup</title></head>
<body style="max-width: 800px; margin: 40px auto; padding: 0 20px; font-family: system-ui, sans-serif;">
<div style="display: flex; justify-content: space-between; align-items: center;">
<h1>Spogitify</h1>
{f'<div>Logged in with Spotify as {sp.me()["display_name"]}</div>' if sp else ''}
</div>
<p>Spogitify backs up your Spotify playlists to a GitHub repository, allowing you to track how your playlists change over time.</p>
<p>NOTE: Spogitify is currently in beta, and users must be allowlisted. <a href="https://arizerner.com/contact" target="_blank">Contact</a> Ari Zerner for access.</p>
"""
if not sp:
# Login button for logged-out users
html += f"""
<form action="/login" method="get">
<button type="submit" style="{button_style}">
Login with Spotify
</button>
</form>
</body>
</html>
"""
return html
# Additional content for logged-in users
config = config_for_user(session['user_id'])
repo_url = git.get_remote_url(config)
last_export = database.get_user_last_export(session['user_id'])
last_export_text = time.format_time_since(last_export) if last_export else "Never"
html += f"""
{'''<div style="background: #fff3cd; padding: 15px; border-radius: 4px; margin: 20px 0;">
<strong>⚠️ Warning:</strong> Your playlist archive will be stored in a public GitHub repository that anyone can view. You can change this in configuration.
</div>''' if not config.get(GITHUB_VIEWERS_KEY) else ''}
<form action="/export" method="get" target="_blank" onsubmit="setTimeout(updateLastBackupTime, 1000)">
<button type="submit" style="{button_style}">
Start Backup
</button>
</form>
<div id="last-backup" style="margin: 10px 0; color: #666;">
Last backup: <span id="last-backup-time">{last_export_text}</span>
</div>
<script>
function updateLastBackupTime() {{
fetch('/last-backup')
.then(response => response.json())
.then(data => {{
document.getElementById('last-backup-time').textContent = data.last_backup || 'Never';
}});
}}
</script>
{f'''<form action="{repo_url}" method="get" target="_blank" style="margin-bottom: 10px;">
<button type="submit" style="{button_style}">
View on GitHub
</button>
</form>''' if repo_url else ''}
<a href="/config" style="text-decoration: none;">
<button style="{button_style}">Configure</button>
</a>
</body>
</html>
"""
return html
if __name__ == '__main__':
app.run(debug=True)