mirror of https://github.com/Chizi123/Reddit-wallpaper-fetcher.git

Joel Grunbaum
2021-01-11 8f58616b53c56b2a7638f19ca89b78c21e911392
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
#!/bin/bash
 
TESTING=0
 
#Default variables
SUBREDDITS=("Wallpapers")
SORT=new
USER=$(whoami)
SIZE=1920x1080
WRITE_TITLE=1
TITLE_COLOR="white"
TITLE_POSITION="Southeast"
TITLE_SIZE=30
 
#Set directories for testing
if [ $TESTING != 1 ]; then
    CONFDIR="$HOME/.config"
    WALLDIR="$HOME/.wallpaper"
else
    CONFDIR="$(dirname $(realpath "$0"))"
    WALLDIR="$(dirname $(realpath "$0"))"
fi
 
[ ! -d "$WALLDIR" ] && mkdir "$WALLDIR"
[ ! -d "$CONFIR" ] && mkdir "$CONFDIR"
source "$CONFDIR"/reddit-wallpaper-fetcher.conf &>/dev/null
 
#Loud output for testing a changed config
[ -z "$1" ] && LOUD="-s"
 
#Initialise time from last fetch
LATEST_TIME=0
if [ -f "$WALLDIR"/json ]; then
    LATEST=$(cat "$WALLDIR"/json)
    LATEST_TIME=$(echo "$LATEST" | jq ".data.children[-1].data.created_utc")
fi
if [ "$LATEST_TIME" == "null" ]; then
    LATEST_TIME=0
fi
 
#Try subreddits for new images
for i in "${SUBREDDITS[@]}"; do
    temp=$(curl "$LOUD" --user-agent "$USER" "https://www.reddit.com/r/$i.json?sort=$SORT&limit=1")
    time=$(echo "$temp" | jq ".data.children[-1].data.created_utc")
    if [ $(awk -v n1="$time" -v n2="$LATEST_TIME" 'BEGIN {printf (n1>n2?"1":"")}') ]; then
    LATEST="$temp"
    LATEST_TIME="$time"
    fi
done
 
#No Update to do
if [ -f "$WALLDIR"/json ] && [ "$(cat "$WALLDIR"/json)" == "$LATEST" ]; then
    exit
fi
 
#Download image
url=$(echo "$LATEST" | jq ".data.children[-1].data.url" | sed 's/"//g')
if [ -n "$(echo $url | grep gallery)" ]; then
    media_id=$(echo "$LATEST" | jq ".data.children[-1].data.gallery_data.items[0].media_id" | sed 's/"//g')
    url=$(echo "$LATEST" | jq ".data.children[-1].data.media_metadata.$media_id.p[0].u" | sed 's/"//g;s/\?.*//g;s/preview/i/g')
fi
ext="$(echo "$url" | rev | cut -d'.' -f1 | rev)"
curl "$url" "$LOUD" --output "$WALLDIR/temp.$ext"
 
#Save image information
echo "$LATEST" > "$WALLDIR"/json
title=$(echo "$LATEST" | jq ".data.children[-1].data.title")
echo "$title" > "$WALLDIR"/data.txt
echo "$url" >> "$WALLDIR"/data.txt
echo https://reddit.com$(echo "$LATEST" | jq ".data.children[-1].data.permalink" | sed 's/"//g') >> "$WALLDIR"/data.txt
 
#Add image title
convert "$WALLDIR/temp.$ext" -resize "$SIZE^" -gravity center -crop "$SIZE+0+0" -resize "$SIZE!" "$WALLDIR/wallpaper.jpg"
rm "$WALLDIR/temp.$ext"
 
if [ $WRITE_TITLE == 1 ]; then
    convert "$WALLDIR/wallpaper.jpg" -fill "$TITLE_COLOR" -gravity "$TITLE_POSITION" -pointsize "$TITLE_SIZE" -annotate 0 "$title" "$WALLDIR/wallpaper.jpg"
fi