aboutsummaryrefslogtreecommitdiff
path: root/pirowatch
blob: 9ac6eaeb406d79fa59419c31c843fdaf1a9eeeba (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/bin/sh

# dir where files are cached
cache_dir="${XDG_CACHE_HOME:-${HOME}/.cache}/pirowatch"
# dir where torrent files are stored
torrent_dir="${DOWNLOADS:-$HOME/Downloads}"
torrent_port=49110
dht_port=49130
menu="wmenu"

note()
{
	# usage: note "message"
	: "${1:?}"

	command -v "notify-send" 1>/dev/null &&
		notify-send "  pirowatch" "$1"
}

die()
{
	# usage: die "reason" [exit_status]
	: "${1:?}"

	note "$1"

	printf "\033[31;1merr: %b\033[0m\n" "$1"
	exit "${2:-1}"
}

dep_check()
{
	# usage: dep_check "dep_1" ...
	: "${1:?}"

	for dep; do
		command -v "$dep" 1>/dev/null ||
			die "$dep not found, please install it" 127
	done

	unset dep
}

stream() {
	# usage: stream "torrent"
	: "${1:?}"

	dep_check "webtorrent" "mpv"

	command -v "notify-send" 1>/dev/null &&
		note "connecting to peers, wait for few seconds"

	if [ -n "$2" ]
	then
		webtorrent --mpv -o "$cache_dir" --torrent-port "$torrent_port" --dht-port "$dht_port" "$1" --select "$2"
	else
		webtorrent --mpv -o "$cache_dir" --torrent-port "$torrent_port" --dht-port "$dht_port" "$1"
	fi

	[ "$?" != 0 ] &&
		die "webtorrent failed to play"
}

set_index() {
	# usage: get_index "torrent"
	: "${1:?}"

	dep_check "webtorrent" "$menu"

	fetch=$(webtorrent -o "$cache_dir" --torrent-port "$torrent_port" --dht-port "$dht_port" "$1" --select |
		grep -Ei "\.(mkv|mp4|webm|avi|mov|flv|flac|opus|ogg|mp3|wav) (.*)$")
	if [ "$(echo "$fetch" | wc -l)" -gt 1 ]
	then
		fetch="$(printf "%s" "$fetch" | "$menu" -p " " -l 25)" ||
			die "empty selection" 66
	fi

	index="${fetch%%[[:space:]]*}"

	unset fetch
}

main()
{
	torrent=
	index="tobeset"

	if [ "$1" = "-s" ]
	then
		index=
		shift
	fi
	[ -z "$WAYLAND_DISPLAY" ] &&
		menu="dmenu"

	dep_check "$menu"

	torrent="${1:-$torrent_dir/$(find "$torrent_dir" -type f -name "*.torrent" | sed 's/.*\///g' | "$menu" -p " " -l 25)}"
	[ -z "${torrent##"${torrent_dir}"/}" ] &&
		die "magnet or torrent file not entered" 66
	[ -d "$cache_dir" ] ||
		mkdir -p "$cache_dir"
	[ "$index" = "tobeset" ] &&
		set_index "$torrent"

	stream "$torrent" "$index"
}

main "$@"