-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebserver.rb
74 lines (54 loc) · 1.56 KB
/
webserver.rb
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
require 'db.rb'
require 'socket'
require 'cgi'
class WebServer
def initialize db, player, port
@db = db
@player = player
puts "Opening webserver at #{port}"
@server = TCPServer.open(port)
port = @server.addr[1]
addrs = @server.addr[2..-1].uniq
puts "*** initing on #{addrs.collect{|a|"#{a}:#{port}"}.join(' ')}"
end
def listen
while connection = @server.accept
headers = []
length = 0
params = nil
while line = connection.gets
headers << line
if line =~ /^Content-Length:\s+(\d+)/i
length = $1.to_i
end
if line =~ /GET \/\?(.+) HTTP/i
params = CGI::parse($1)
end
break if line == "\r\n"
end
body = connection.readpartial(length)
connection.print "HTTP/1.1 200 OK\r\nContent-type: text/html\r\n\r\n"
connection.print "<html><body><form action=\"/\" method=\"get\"><input type=\"text\" name=terms />"
connection.print "<input type=\"submit\" value=\"Search\"/></form><br />\r\n"
if params
if params.include?("order")
sid = params["order"].join(" ").to_i
song = @db.lookup(sid)
if song
@player.queue(song)
end
connection.print"Ordered #{song.to_s}<br />\r\n"
elsif params.include?("terms")
terms = params["terms"].join(" ")
puts "Searching for " + terms
myresults = @db.search(terms)
myresults.each do |song|
connection.print("<a href=\"/?order=#{song.sid.to_s}\">#{song.to_s}</a><br />\r\n")
end
end
end
connection.print "</body></html>\r\n"
connection.close
end
end
end