-
Notifications
You must be signed in to change notification settings - Fork 0
/
gopher.rb
73 lines (56 loc) · 1.36 KB
/
gopher.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
73
require "socket"
# Example usage
# z = Gopher.new("gopher.quux.org")
# puts z.list "/"
class Gopher
def initialize(server, port = 70)
@server = server
@port = port
end
# Returns the raw output from a Gopher request
def list_raw(path, query = "")
socket = Socket.tcp(@server, @port, connect_timeout: 3)
if query.empty? then
socket.print(path + "\n")
else
socket.print(path + "\t" + query + "\n")
end
response = socket.read
return response
end
# Get the parsed file list
def list(path, query = "")
response = list_raw(path, query)
lines = response.split "\n"
# Handle the final dot if it is there
if lines[-1].strip == "." then
lines = lines[0..-2]
end
result = Array.new lines.size
lines.each.with_index do |line, i|
type = line[0]
splitted = line.split "\t"
splitted[0] = splitted[0][1..-1] # Remove the item type character
result[i] = {
:type => type,
:description => splitted[0],
:path => splitted[1],
:host => splitted[2],
:port => splitted[3].to_i
}
end
return result
end
# Get a file
def get(path)
socket = TCPSocket.open(@server, @port)
socket.print(path + "\n")
response = socket.read
return response
end
# Download to disk
def download(path, destination)
data = get(path)
File.open(destination, "wb") { |file| file.write(data) }
end
end