about summary refs log tree commit diff stats
path: root/bonus/magnet.cgi
blob: 085d252b7fbc21e49ac1c2193a845107f35e1ff0 (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
#!/bin/sh
# Add magnet: links to transmission using transmission-remote.
#
# Usage: place magnet.cgi in your cgi-bin directory (don't forget to set
# the executable bit, e.g. chmod +x magnet.cgi), then add the following line
# to your urimethodmap:
#
# magnet: /cgi-bin/magnet.cgi?%s
#
# Then, set the remote transmission session's address using the
# CHA_TRANSMISSION_ADDRESS environment variable, and if needed, the
# authentication data using CHA_TRANSMISSION_AUTH. Alternatively, uncomment
# the following lines and set them there:

#CHA_TRANSMISSION_ADDRESS=localhost:9091
#CHA_TRANSMISSION_AUTH=username:password

#TODO: add a way to authenticate without exposing the credentials as an
# environment variable

die() {
	printf "Content-Type: text/plain\n\n%s" "$1"
	exit 1
}

decode() {
	# URL-decode the string passed as the first parameter
	printf '%s\n' "$1" | \
		sed 's/+/ /g;s/%/\\x/g' | \
		xargs -0 printf "%b"
}

html_quote() {
	sed 's/&/&amp;/g;s/</&lt;/g;s/>/&gt;/g;s/'\''/&apos;/g;s/"/&quot;/g'
}


test -n "$QUERY_STRING" || die "URL expected"
type transmission-remote >/dev/null || die "transmission-remote not found"

case "$REQUEST_METHOD" in
GET)	URL_HTML_QUOTED="$(printf '%s' "$QUERY_STRING" | html_quote)"
	printf 'Content-Type: text/html\n\n
<!DOCTYPE HTML>
<HEAD>
<TITLE>Add magnet URL</TITLE>
</HEAD>
<H1>Add magnet URL</H1>
<P>
Add the following magnet URL to transmission?
<PRE>%s</PRE>
<FORM METHOD=POST>
<INPUT TYPE=SUBMIT NAME=ADD_URL VALUE=OK>
<INPUT type=HIDDEN NAME=URL VALUE='%s'>
</FORM>
' "$URL_HTML_QUOTED" "$URL_HTML_QUOTED"
	;;
POST)	read line
	case $line in
	'ADD_URL=OK&'*) line="${line#*&}" ;;
	*) die 'Invalid POST 1; this is probably a bug in the magnet script.' ;;
	esac
	case $line in
	URL=*) line="${line#*=}" ;;
	*) die 'Invalid POST 2; this is probably a bug in the magnet script.'"$line" ;;
	esac
	line="$(decode "$line")"
	if test -n "$CHA_TRANSMISSION_AUTH"
	then	authparam="--auth=$CHA_TRANSMISSION_AUTH"
	fi
	if test -n "$authparam"
	then	output="$(transmission-remote "${CHA_TRANSMISSION_ADDRESS:-localhost:9091}" "$authparam" -a "$line" 2>&1)"
	else	output="$(transmission-remote "${CHA_TRANSMISSION_ADDRESS:-localhost:9091}" -a "$line" 2>&1)"
	fi
	printf 'Content-Type: text/plain\n\n%s' "$output"
	;;
*)	die "Unrecognized HTTP method $HTTP_METHOD" ;;
esac