sunox 0.0.10

Generate AI music from your terminal via direct Suno web workflows
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use serde_json::Value;

use super::SunoClient;
use super::types::{
    CreatePlaylistRequest, PlaylistInfo, PlaylistListResponse, PlaylistReaction,
    PlaylistReorderRequest, PlaylistTrackMutationFailure, PlaylistTrackMutationReport,
    PlaylistTracksRequest, SetPlaylistCoverRequest, SetPlaylistMetadataRequest,
    SetPlaylistReactionRequest, SetPlaylistVisibilityRequest, TrashPlaylistRequest,
};
use crate::core::CliError;

impl SunoClient {
    /// List the authenticated user's playlists.
    /// GET /api/playlist/me?page={page}
    pub async fn list_playlists(&self, page: u32) -> Result<PlaylistListResponse, CliError> {
        self.with_auth_retry(|| async {
            let resp = self
                .get("/api/playlist/me")
                .query(&[("page", page)])
                .send()
                .await?;
            let resp = self.check_response(resp).await?;
            Ok(resp.json().await?)
        })
        .await
    }

    /// Fetch playlist details.
    /// GET /api/playlist/v2/{playlist_id}
    pub async fn get_playlist(&self, playlist_id: &str) -> Result<PlaylistInfo, CliError> {
        self.with_auth_retry(|| async {
            let resp = self
                .get(&format!("/api/playlist/v2/{playlist_id}"))
                .send()
                .await?;
            let resp = self.check_response(resp).await?;
            decode_playlist(resp.json().await?)
        })
        .await
    }

    /// Create a playlist. Suno Web's create route only sends the name; when a
    /// description is supplied we follow with the metadata route.
    pub async fn create_playlist(
        &self,
        name: &str,
        description: Option<&str>,
        image_url: Option<&str>,
    ) -> Result<PlaylistInfo, CliError> {
        let mut playlist = self
            .with_auth_retry(|| async {
                let resp = self
                    .post("/api/playlist/create/")
                    .json(&CreatePlaylistRequest {
                        name: name.to_string(),
                    })
                    .send()
                    .await?;
                let resp = self.check_response(resp).await?;
                decode_playlist(resp.json().await?)
            })
            .await?;

        if description.is_some() || image_url.is_some() {
            playlist = self
                .set_playlist_metadata(&playlist.id, None, description, image_url)
                .await?;
        }

        Ok(playlist)
    }

    /// Update playlist metadata.
    /// POST /api/playlist/set_metadata
    pub async fn set_playlist_metadata(
        &self,
        playlist_id: &str,
        name: Option<&str>,
        description: Option<&str>,
        image_url: Option<&str>,
    ) -> Result<PlaylistInfo, CliError> {
        if let Some(upload_id) = image_url.and_then(upload_id_from_suno_image_url) {
            if name.is_some() || description.is_some() {
                self.post_playlist_metadata(playlist_id, name, description, None)
                    .await?;
            }
            return self
                .set_playlist_uploaded_cover(playlist_id, &upload_id)
                .await;
        }

        self.post_playlist_metadata(playlist_id, name, description, image_url)
            .await?;

        self.get_playlist(playlist_id).await
    }

    async fn post_playlist_metadata(
        &self,
        playlist_id: &str,
        name: Option<&str>,
        description: Option<&str>,
        image_url: Option<&str>,
    ) -> Result<(), CliError> {
        let req = SetPlaylistMetadataRequest {
            playlist_id: playlist_id.to_string(),
            name: name.map(str::to_string),
            description: description.map(str::to_string),
            image_url: image_url.map(str::to_string),
        };

        self.with_auth_retry(|| async {
            let resp = self
                .post("/api/playlist/set_metadata")
                .json(&req)
                .send()
                .await?;
            let resp = self.check_response(resp).await?;
            let text = resp.text().await.unwrap_or_default();
            if !text.trim().is_empty() {
                let body: Value = serde_json::from_str(&text)?;
                reject_playlist_moderation_error(&body)?;
            }
            Ok(())
        })
        .await
    }

    /// Set playlist cover to an image previously uploaded through Suno's image
    /// upload flow.
    /// PATCH /api/playlist/v2/{playlist_id}
    pub async fn set_playlist_uploaded_cover(
        &self,
        playlist_id: &str,
        upload_id: &str,
    ) -> Result<PlaylistInfo, CliError> {
        let req = SetPlaylistCoverRequest::from_upload_id(upload_id);
        self.with_auth_retry(|| async {
            let resp = self
                .patch(&format!("/api/playlist/v2/{playlist_id}"))
                .json(&req)
                .send()
                .await?;
            self.check_response(resp).await?;
            Ok(())
        })
        .await?;

        self.get_playlist(playlist_id).await
    }

    /// Set or clear playlist like/dislike reaction.
    /// POST /api/playlist_reaction/{playlist_id}/update_reaction_type/
    pub async fn set_playlist_reaction(
        &self,
        playlist_id: &str,
        reaction: Option<PlaylistReaction>,
    ) -> Result<(), CliError> {
        self.with_auth_retry(|| async {
            let resp = self
                .post(&format!(
                    "/api/playlist_reaction/{playlist_id}/update_reaction_type/"
                ))
                .json(&SetPlaylistReactionRequest::new(reaction))
                .send()
                .await?;
            self.check_response(resp).await?;
            Ok(())
        })
        .await
    }

    /// Add clips to a playlist.
    /// POST /api/playlist/v2/{playlist_id}/tracks/add
    pub async fn add_clips_to_playlist(
        &self,
        playlist_id: &str,
        clip_ids: &[String],
    ) -> Result<(), CliError> {
        self.update_playlist_tracks(playlist_id, "add", clip_ids)
            .await
    }

    /// Remove clips from a playlist.
    /// POST /api/playlist/v2/{playlist_id}/tracks/remove
    pub async fn remove_clips_from_playlist(
        &self,
        playlist_id: &str,
        clip_ids: &[String],
    ) -> Result<PlaylistTrackMutationReport, CliError> {
        let mut succeeded_clip_ids = Vec::new();
        let mut failed = Vec::new();
        let mut not_attempted_clip_ids = Vec::new();

        for (index, clip_id) in clip_ids.iter().enumerate() {
            match self
                .update_playlist_tracks(playlist_id, "remove", std::slice::from_ref(clip_id))
                .await
            {
                Ok(()) => succeeded_clip_ids.push(clip_id.clone()),
                Err(error) => {
                    if succeeded_clip_ids.is_empty() {
                        return Err(error);
                    }
                    failed.push(PlaylistTrackMutationFailure::from_error(clip_id, &error));
                    not_attempted_clip_ids.extend_from_slice(&clip_ids[index + 1..]);
                    break;
                }
            }
        }

        Ok(PlaylistTrackMutationReport::new(
            playlist_id,
            "remove",
            clip_ids,
            succeeded_clip_ids,
            failed,
            not_attempted_clip_ids,
        ))
    }

    /// Set playlist visibility.
    /// PATCH /api/playlist/v2/{playlist_id}
    pub async fn set_playlist_visibility(
        &self,
        playlist_id: &str,
        is_public: bool,
    ) -> Result<(), CliError> {
        self.with_auth_retry(|| async {
            let resp = self
                .patch(&format!("/api/playlist/v2/{playlist_id}"))
                .json(&SetPlaylistVisibilityRequest::new(is_public))
                .send()
                .await?;
            self.check_response(resp).await?;
            Ok(())
        })
        .await
    }

    /// Save a playlist to the user's library.
    /// POST /api/playlist/v2/{playlist_id}/save
    pub async fn save_playlist(&self, playlist_id: &str) -> Result<(), CliError> {
        self.with_auth_retry(|| async {
            let resp = self
                .post(&format!("/api/playlist/v2/{playlist_id}/save"))
                .send()
                .await?;
            self.check_response(resp).await?;
            Ok(())
        })
        .await
    }

    /// Remove a saved playlist from the user's library.
    /// DELETE /api/playlist/v2/{playlist_id}/save
    pub async fn unsave_playlist(&self, playlist_id: &str) -> Result<(), CliError> {
        self.with_auth_retry(|| async {
            let resp = self
                .delete(&format!("/api/playlist/v2/{playlist_id}/save"))
                .send()
                .await?;
            self.check_response(resp).await?;
            Ok(())
        })
        .await
    }

    /// Move a playlist clip to a zero-based index.
    /// POST /api/playlist/v2/{playlist_id}/tracks/reorder-by-index
    pub async fn reorder_playlist_clip(
        &self,
        playlist_id: &str,
        clip_id: &str,
        index: u32,
    ) -> Result<(), CliError> {
        self.with_auth_retry(|| async {
            let resp = self
                .post(&format!(
                    "/api/playlist/v2/{playlist_id}/tracks/reorder-by-index"
                ))
                .json(&PlaylistReorderRequest::single(clip_id, index))
                .send()
                .await?;
            self.check_response(resp).await?;
            Ok(())
        })
        .await
    }

    async fn update_playlist_tracks(
        &self,
        playlist_id: &str,
        action: &str,
        clip_ids: &[String],
    ) -> Result<(), CliError> {
        self.with_auth_retry(|| async {
            let resp = self
                .post(&format!("/api/playlist/v2/{playlist_id}/tracks/{action}"))
                .json(&PlaylistTracksRequest {
                    clip_ids: clip_ids.to_vec(),
                })
                .send()
                .await?;
            self.check_response(resp).await?;
            Ok(())
        })
        .await
    }

    /// Trash a playlist. The route supports undo, but the CLI exposes delete.
    /// POST /api/playlist/v2/{playlist_id}/trash
    pub async fn trash_playlist(&self, playlist_id: &str) -> Result<(), CliError> {
        self.set_playlist_trash_state(playlist_id, false).await
    }

    /// Restore a trashed playlist.
    /// POST /api/playlist/v2/{playlist_id}/trash
    pub async fn restore_playlist(&self, playlist_id: &str) -> Result<(), CliError> {
        self.set_playlist_trash_state(playlist_id, true).await
    }

    async fn set_playlist_trash_state(
        &self,
        playlist_id: &str,
        undo: bool,
    ) -> Result<(), CliError> {
        self.with_auth_retry(|| async {
            let resp = self
                .post(&format!("/api/playlist/v2/{playlist_id}/trash"))
                .json(&TrashPlaylistRequest { undo })
                .send()
                .await?;
            self.check_response(resp).await?;
            Ok(())
        })
        .await
    }
}

fn reject_playlist_moderation_error(body: &Value) -> Result<(), CliError> {
    if let Some(message) = body
        .get("moderation_error_message")
        .and_then(serde_json::Value::as_str)
    {
        return Err(CliError::Api {
            code: "moderation_error",
            message: message.to_string(),
        });
    }
    Ok(())
}

fn decode_playlist(body: Value) -> Result<PlaylistInfo, CliError> {
    let candidates = [
        body.get("playlist").cloned(),
        body.get("data").cloned(),
        Some(body.clone()),
    ];

    for candidate in candidates.into_iter().flatten() {
        if let Ok(playlist) = serde_json::from_value::<PlaylistInfo>(candidate) {
            return Ok(playlist);
        }
    }

    Err(CliError::Api {
        code: "schema_drift",
        message: format!("playlist response did not match known Suno schema: {body}"),
    })
}

fn upload_id_from_suno_image_url(url: &str) -> Option<String> {
    let url = url.trim().split(['?', '#']).next().unwrap_or_default();
    if !url.starts_with("https://cdn1.suno.ai/") && !url.starts_with("https://cdn2.suno.ai/") {
        return None;
    }
    let file = url
        .trim_end_matches('/')
        .rsplit('/')
        .next()
        .unwrap_or_default();
    let id = file
        .strip_prefix("image_")?
        .strip_suffix(".jpeg")
        .or_else(|| file.strip_prefix("image_")?.strip_suffix(".jpg"))?;
    if id.is_empty() {
        None
    } else {
        Some(id.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::upload_id_from_suno_image_url;

    #[test]
    fn suno_image_url_extracts_upload_id() {
        assert_eq!(
            upload_id_from_suno_image_url("https://cdn2.suno.ai/image_upload-1.jpeg"),
            Some("upload-1".to_string())
        );
        assert_eq!(
            upload_id_from_suno_image_url("https://cdn1.suno.ai/image_upload-2.jpg?x=1"),
            Some("upload-2".to_string())
        );
        assert_eq!(
            upload_id_from_suno_image_url("https://example.com/image_upload-1.jpeg"),
            None
        );
    }
}