about summary refs log tree commit diff stats
path: root/src/cache/mod.rs
blob: a3e08c9a156f42fd905203deb62a2420319848fe (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2024 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::{Context, Result};
use log::info;
use tokio::fs;

use crate::{
    app::App,
    storage::video_database::{
        downloader::set_video_cache_path, getters::get_videos, setters::set_state_change, Video,
        VideoStatus,
    },
};

async fn invalidate_video(app: &App, video: &Video, hard: bool) -> Result<()> {
    info!("Invalidating cache of video: '{}'", video.title);

    if hard {
        if let Some(path) = &video.cache_path {
            info!("Removing cached video at: '{}'", path.display());
            fs::remove_file(path).await.with_context(|| {
                format!(
                    "Failed to delete video ('{}') cache path: '{}'.",
                    video.title,
                    path.display()
                )
            })?;
        }
    }

    set_video_cache_path(app, &video.extractor_hash, None).await?;

    Ok(())
}

pub async fn invalidate(app: &App, hard: bool) -> Result<()> {
    let all_cached_things = get_videos(app, &[VideoStatus::Cached], None).await?;

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

    for video in all_cached_things {
        invalidate_video(app, &video, hard).await?
    }

    Ok(())
}

pub async fn maintain(app: &App, all: bool) -> Result<()> {
    let domain = if all {
        vec![
            VideoStatus::Pick,
            //
            VideoStatus::Watch,
            VideoStatus::Cached,
            VideoStatus::Watched,
            //
            VideoStatus::Drop,
            VideoStatus::Dropped,
        ]
    } else {
        vec![VideoStatus::Watch, VideoStatus::Cached]
    };

    let cached_videos = get_videos(app, domain.as_slice(), None).await?;

    for vid in cached_videos {
        if let Some(path) = vid.cache_path.as_ref() {
            info!("Checking if path ('{}') exists", path.display());
            if !path.exists() {
                invalidate_video(app, &vid, false).await?;
            }
        }
        if vid.status_change {
            info!("Video '{}' has it's changing bit set. This is probably the result of an unexpectet exit. Clearing it", vid.title);
            set_state_change(app, &vid.extractor_hash, false).await?;
        }
    }

    Ok(())
}