about summary refs log tree commit diff stats
path: root/crates/yt/src/cache/mod.rs
blob: 44a7e72fbeb0a3de75e416d84d25333160f8d9af (plain) (blame)
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
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2024 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// Copyright (C) 2025 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use anyhow::Result;
use log::info;

use crate::{
    app::App,
    storage::db::{
        insert::{Operations, video::Operation},
        video::{Video, VideoStatus, VideoStatusMarker},
    },
};

fn invalidate_video(video: &mut Video, ops: &mut Operations<Operation>) {
    info!("Deleting downloaded path of video: '{}'", video.title);

    assert_eq!(video.status.as_marker(), VideoStatusMarker::Cached);

    video.remove_download_path(ops);
}

pub(crate) async fn invalidate(app: &App) -> Result<()> {
    let mut all_cached_things = Video::in_states(app, &[VideoStatusMarker::Cached]).await?;

    info!("Got videos to invalidate: '{}'", all_cached_things.len());

    let mut ops = Operations::new("Cache: Invalidate cache entries");

    for video in &mut all_cached_things {
        invalidate_video(video, &mut ops);
    }

    ops.commit(app).await?;

    Ok(())
}

/// Remove the cache paths from the db, that no longer exist on the file system.
pub(crate) async fn maintain(app: &App) -> Result<()> {
    let mut cached_videos = Video::in_states(app, &[VideoStatusMarker::Cached]).await?;

    let mut ops = Operations::new("DbMaintain: init");
    for vid in &mut cached_videos {
        if let VideoStatus::Cached { cache_path, .. } = &vid.status {
            if !cache_path.exists() {
                invalidate_video(vid, &mut ops);
            }
        } else {
            unreachable!("We only asked for cached videos.")
        }
    }
    ops.commit(app).await?;

    Ok(())
}