aboutsummaryrefslogtreecommitdiff
path: root/http.go
blob: 4c0c8bebae807a70898390e5b5192f71458cc61c (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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main

import (
	"encoding/json"
	"expvar"
	"fmt"
	"net/http"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Header().Set("Cache-Control", "no-cache")
	w.WriteHeader(200)
	w.Write(html)
}

func statsHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Cache-Control", "public")
	w.WriteHeader(200)
	fmt.Fprintf(w, "{")
	first := true
	expvar.Do(func(kv expvar.KeyValue) {
		if kv.Key == "cmdline" || kv.Key == "memstats" {
			return
		}
		if !first {
			fmt.Fprintf(w, ",")
		}
		first = false
		fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
	})
	fmt.Fprintf(w, "}")
}

func searchHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Cache-Control", "no-cache")
	if q := r.URL.Query().Get("q"); q != "" {
		torrents, err := torrentsByName(q)
		if err != nil {
			w.WriteHeader(500)
			fmt.Printf("Error: %q\n", err)
			return
		}
		w.WriteHeader(200)
		json.NewEncoder(w).Encode(torrents)
		return
	}

	if tag := r.URL.Query().Get("tag"); tag != "" {
		torrents, err := torrentsByTag(tag)
		if err != nil {
			w.WriteHeader(500)
			fmt.Printf("Error: %q\n", err)
			return
		}
		w.WriteHeader(200)
		json.NewEncoder(w).Encode(torrents)
		return
	}

	w.WriteHeader(406)
	json.NewEncoder(w).Encode("Query required")
}

var html = []byte(`
<!doctype html>
<html>
	<head>
		<title>DHT search</title>
		<meta charset="UTF-8">
		<style>
		body { padding:0;margin:0;color:#666;line-height:1.5;font-size:16px; }
		.header { padding:1em;border-bottom:1px solid #555; }
		input { padding:2px; }
		.page { padding:1em 2em; }
		ul { list-style:none;padding:0;margin:0; }
		.torrent { margin-bottom:1em; }
		.torrent__name { display:block; }
		.torrent__magnet { display:block; }
		.torrent__size, .torrent__file-count, .torrent__seen, .torrent__tags { padding-right:1em; }
		.tag { display:inline;text-decoration:none; }
		.files { padding-left:2em;font-family:monospace;font-size:.75em; }
		.files { display:none; }
		.files--active { display:block; }
		.file__size { margin-left:.5em;font-size:.875em; }
		.stats { display:block;margin:0;margin-top:1em; }
		.stats__key, .stats__value { display:inline-block;font-size:.75em;padding:0;margin:0; }
		.stats__key { margin-right:.25em;color:#222; }
		.stats__key:after { content:':'; }
		.stats__value { margin-right:.5em;color:#888; }
		</style>
	</head>
	<body id="body">
		<div class="header">
		<input id="search" type="text" name="search" placeholder="Search" />
		<button id="go">Go</button>
		<dl id="stats" class="stats"></dl>
		</div>
		<div id="page" class="page">
		</div>
		<script>
var humanSize = function (bytes) {
	if (bytes === 0) {
		return '0 Bytes'
	}
	var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
	var sizeIndex = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10)
	if (sizeIndex >= sizes.length) {
		sizeIndex = sizes.length - 1
	}
	return (bytes / Math.pow(1024, sizeIndex)).toFixed(0) + sizes[sizeIndex]
}
var processResponse = function (resp) {
	if (resp.status === 200 || resp.status === 0) {
		return resp.json()
	} else {
		return new Error(resp.statusText)
	}
}
var search = function (term) {
	var oldButton = bEl.innerHTML
	bEl.innerHTML = 'Searching'
	var query = ''
	var tIdx = term.indexOf('tag:')
	if (tIdx >= 0) {
		query = 'tag=' + term.slice(tIdx+4).trim()
	} else {
		query = 'q=' + term.trim()
    }
	fetch('/search?' + query)
	.then(processResponse)
	.then(function (data) {
		var pre = [
		'<p>Displaying ', data.length, ' torrents.</p>',
		'<ul id="results">'
		].join('')
		var torrents = data.map(function (t) {
			var magnet = 'magnet:?xt=urn:btih:' + t.infohash
			var pre = [
			'<li class="torrent">',
			'<a class="torrent__name" href="', magnet, '">', t.name, '</a>',
			'<span class="torrent__magnet">', magnet, '</span>',
			'<span class="torrent__size">Size:&nbsp;', humanSize(t.size), '</span>',
			'<span class="torrent__seen">Last&nbsp;seen:&nbsp;<time datetime="', t.seen, '">', new Date(t.seen).toLocaleString(), '</time></span>'
			].join('')
			var tags = ''
			if (t.tags.length) {
				tags = [
				'<span class="torrent__tags">Tags: ',
				t.tags.map(function (g) { return '<a class="tag" href="/tags/' + g + '">' + g + '</a>' }).join(',&nbsp;'),
				'</span>'
				].join('')
			}
			var files = ''
			if (t.files.length) {
				var fHtml = t.files.map(function (f) {
					return [
					'<li class="files__file file">',
					'<span class="file__path">', f.path, '</span>',
					'<span class="file__size">[', humanSize(f.size), ']</span>',
					'</li>'
					].join('')
				})
				files = [
				'<span class="torrent__file-count">Files:&nbsp;', t.files.length, '</span>',
				'<a class="toggler" href="#">toggle files</a><ul class="files">',
				fHtml.join(''),
				'</ul>'].join('')
			}
			var post = [
			'</li>'
			].join('')
			return pre + tags + files + post
		}).join('')
		var post = '</ul>'
		bEl.innerHTML = oldButton
		pEl.innerHTML = pre + torrents + post
		var togglers = document.getElementsByClassName('toggler')
		for (var i = 0; i < togglers.length; i += 1) {
			var el = togglers[i]
			el.addEventListener('click', function (e) {
				e.preventDefault()
				e.target.nextElementSibling.classList.toggle('files--active')
			})
		}
	})
}
var pEl = document.getElementById('page')
var sEl = document.getElementById('search')
var bEl = document.getElementById('go')
bEl.addEventListener('click', function () {
	var term = sEl.value
	if (term.length > 2) {
		console.log('Search term: ', term)
		search(term)
	}
})
sEl.addEventListener('keyup', function (e) {
	if (e.keyCode === 13) {
		bEl.click()
	}
})
var statsEl = document.getElementById('stats')
var getStats = function () {
	fetch('/stats')
	.then(processResponse)
	.then(function (data) {
		statsEl.innerHTML = Object.keys(data).map(function (k) {
			return [
			'<dt class="stats__key">',
			k.replace(/_/g,'&nbsp;'),
			'</dt><dd class="stats__value">',
			k.indexOf('bytes') === -1 ? data[k] : humanSize(data[k]),
			'</dd>'
			].join('')
		}).join('')
		setTimeout(getStats, 5000)
	})
}
getStats()
		</script>
	</body>
</html>
`)