summaryrefslogtreecommitdiff
path: root/src/progress.rs
blob: 8822bdb2ce94c92300167b0af1b0a591f8d3c8c2 (plain)
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
use crate::{error::Result, types::TrackInfo};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::path::Path;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MatchedTrack {
    #[serde(rename = "trackId")]
    pub track_id: u64,
    #[serde(rename = "trackTitle")]
    pub track_title: String,
    #[serde(rename = "trackArtist")]
    pub track_artist: String,
    pub album: Option<String>,
    pub confidence: f64,
    #[serde(rename = "csvIndex")]
    pub csv_index: usize,
    #[serde(rename = "csvTrackName")]
    pub csv_track_name: String,
    #[serde(rename = "csvArtistName")]
    pub csv_artist_name: String,
    #[serde(rename = "csvAlbum")]
    pub csv_album: Option<String>,
    #[serde(rename = "playlistName")]
    pub playlist_name: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailedMatch {
    #[serde(rename = "trackName")]
    pub track_name: String,
    pub artist: Option<String>,
    pub album: Option<String>,
    #[serde(rename = "searchAttempts")]
    pub search_attempts: Vec<String>,
    pub attempts: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CsvTrackInfo {
    #[serde(rename = "trackName")]
    pub track_name: String,
    pub artist: Option<String>,
    pub album: Option<String>,
    pub isrc: Option<String>,
    #[serde(rename = "spotifyId")]
    pub spotify_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailedDownload {
    #[serde(rename = "trackId")]
    pub track_id: u64,
    #[serde(rename = "trackTitle")]
    pub track_title: String,
    #[serde(rename = "trackArtist")]
    pub track_artist: String,
    pub album: Option<String>,
    pub error: String,
    pub attempts: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownloadProgress {
    pub source: String,
    pub total: usize,
    pub successful: usize,
    pub failed: Vec<FailedDownload>,
    #[serde(rename = "startedAt")]
    pub started_at: String,
    #[serde(rename = "completedAt")]
    pub completed_at: Option<String>,
    #[serde(rename = "failedMatches")]
    pub failed_matches: Vec<FailedMatch>,
    #[serde(rename = "totalMatched")]
    pub total_matched: usize,
    #[serde(rename = "totalDownloaded")]
    pub total_downloaded: usize,
    #[serde(rename = "completedTrackIds")]
    pub completed_track_ids: Vec<u64>,
    #[serde(rename = "matchedCsvIndices")]
    pub matched_csv_indices: Vec<usize>,
    #[serde(rename = "matchedTracks")]
    pub matched_tracks: Vec<MatchedTrack>,
}

impl DownloadProgress {
    pub fn new(source: &str, total: usize) -> Self {
        Self {
            source: source.to_string(),
            total,
            successful: 0,
            failed: Vec::new(),
            started_at: Utc::now().to_rfc3339(),
            completed_at: None,
            failed_matches: Vec::new(),
            total_matched: 0,
            total_downloaded: 0,
            completed_track_ids: Vec::new(),
            matched_csv_indices: Vec::new(),
            matched_tracks: Vec::new(),
        }
    }

    pub fn mark_completed(&mut self, track_id: u64) {
        if !self
            .completed_track_ids
            .contains(&track_id)
        {
            self.completed_track_ids
                .push(track_id);
        }
    }

    pub fn is_completed(&self, track_id: u64) -> bool {
        self.completed_track_ids
            .contains(&track_id)
    }

    pub fn get_completed_count(&self) -> usize {
        self.completed_track_ids
            .len()
    }

    pub fn mark_csv_matched(&mut self, index: usize) {
        if !self
            .matched_csv_indices
            .contains(&index)
        {
            self.matched_csv_indices
                .push(index);
        }
    }

    pub fn is_csv_matched(&self, index: usize) -> bool {
        self.matched_csv_indices
            .contains(&index)
    }

    pub fn add_matched_track(&mut self, csv_index: usize, track: &TrackInfo, confidence: f64, csv_track_name: &str, csv_artist: &str, csv_album: Option<&str>, playlist: Option<&str>) {
        self.matched_tracks
            .push(
                MatchedTrack {
                    track_id: track.id,
                    track_title: track
                        .title
                        .clone(),
                    track_artist: track
                        .artist
                        .clone(),
                    album: track
                        .album
                        .clone(),
                    confidence,
                    csv_index,
                    csv_track_name: csv_track_name.to_string(),
                    csv_artist_name: csv_artist.to_string(),
                    csv_album: csv_album.map(|s| s.to_string()),
                    playlist_name: playlist.map(|s| s.to_string()),
                },
            );
        self.mark_csv_matched(csv_index);
    }

    pub fn get_matched_track(&self, csv_index: usize) -> Option<&MatchedTrack> {
        self.matched_tracks
            .iter()
            .find(|m| m.csv_index == csv_index)
    }

    pub fn add_success(&mut self) {
        self.successful += 1;
    }

    pub fn add_failure(&mut self, track: &TrackInfo, album: Option<&str>, error: String) {
        self.failed
            .push(
                FailedDownload {
                    track_id: track.id,
                    track_title: track
                        .title
                        .clone(),
                    track_artist: track
                        .artist
                        .clone(),
                    album: album.map(|s| s.to_string()),
                    error,
                    attempts: 1,
                },
            );
    }

    pub fn add_failed_match(&mut self, track_name: &str, artist: Option<&str>, album: Option<&str>) {
        if let Some(existing) = self
            .failed_matches
            .iter_mut()
            .find(
                |m| {
                    m.track_name == track_name
                        && m.artist
                            .as_deref()
                            == artist
                        && m.album
                            .as_deref()
                            == album
                },
            )
        {
            existing.attempts += 1;
        } else {
            self.failed_matches
                .push(
                    FailedMatch {
                        track_name: track_name.to_string(),
                        artist: artist.map(|s| s.to_string()),
                        album: album.map(|s| s.to_string()),
                        search_attempts: Vec::new(),
                        attempts: 1,
                    },
                );
        }
    }

    pub fn get_failed_matches(&self) -> &[FailedMatch] {
        &self.failed_matches
    }

    pub fn total_failed(&self) -> usize {
        self.failed_matches
            .len()
            + self
                .failed
                .len()
    }

    pub fn save_to_file(&self, path: &Path) -> Result<()> {
        let json = serde_json::to_string_pretty(self)?;
        std::fs::write(
            path, json,
        )?;
        Ok(())
    }

    pub fn load_from_file(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let progress: Self = serde_json::from_str(&content)?;
        Ok(progress)
    }

    pub fn has_failures(&self) -> bool {
        !self
            .failed
            .is_empty()
    }

    pub fn retry_count(&self) -> usize {
        self.failed
            .iter()
            .map(|f| f.attempts)
            .sum()
    }
}