summaryrefslogtreecommitdiff
path: root/odin/strm/cleanup_youtube
blob: 0df15d0b7638adb27c4104e50bdb6e38ac7e7daa (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
#!@zsh@/bin/zsh

function notmuch {
    while true; do 
        result=$($_env NOTMUCH_CONFIG=${HOME}/.notmuch-rss-config @notmuch@/bin/notmuch "$@" 2>&1)
        if ! [[ $result =~ "already locked" ]]; then
            echo -nE $result
            return
        fi
        sleep 2
    done
}

tagFile=""

function cleanup {
    [[ -n "${tagFile}" ]] && rm -fv ${tagFile}
}

dir=/srv/media/youtube
maxsize=$((1024 * 1024 * 1024 * 50))

while [[ $(du -bs $dir | awk '{ print $1; }') -gt $maxsize ]]; do
    find $dir -type f -not -path $dir/CACHEDIR.TAG -print0 | \
        xargs -0 -- $_stat --printf '%W %Y %Z %X %n\0' | \
        sort -t '\0' -z | \
        awk -F '\0' '{ gsub("^\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+", "", $1); printf "%s\0", $1; }' | \
        xargs -0 -- rm -v
done

find $dir -xtype l -delete
find $dir -type d -empty -delete

notmuch search --output=messages --format=text 'is:cached' | \
    while read id; do 
        untag=false
        url=$(notmuch show --format=raw "$id" | grep 'http://odin.asgard.yggdrasil/youtube' | sed -r 's|^.*href="http://odin.asgard.yggdrasil/youtube/([^"]+)".*$|\1|' | sed -f /usr/lib/url_unescape.sed)

        printf "%s\n  ‘%s’\n" ${id} ${dir}/${url}
        
        if [[ -z "${url}" ]]; then
            printf "  Could not extract filename.\n"
            untag=true
        fi

        if [[ -n "${url}" && ! -e "${dir}/${url}" ]]; then
            printf "  File vanished\n"
            untag=true
        fi

        if ${untag}; then
            if [[ -z "${tagFile}" ]]; then
                tagFile=$(mktemp --tmpdir $$.tags.XXXXXXXXXX)
                printf "Using %s\n" ${tagFile}
            fi
            
            { printf "-cached -- %s\n" ${id} >> ${tagFile} } && printf "  Tagging ‘-cached’...\n"
        fi
    done

[[ -n "${tagFile}" ]] && notmuch tag --batch --input=${tagFile}