Skip to content

Commit

Permalink
Refactor @socket.write and response parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
James Conroy-Finn committed Oct 26, 2011
1 parent f2f12e3 commit 0bf8849
Showing 1 changed file with 20 additions and 21 deletions.
41 changes: 20 additions & 21 deletions lib/net/nntp.rb
Expand Up @@ -10,6 +10,8 @@ class NNTP

include Socket::Constants

attr_reader :response

def initialize(server, port = 119)
@server = server
@port = port
Expand All @@ -24,7 +26,8 @@ def initialize(server, port = 119)
retry
end

response = _response
response = Net::NNTP::Response.parse(@socket.readline)

if response.code == 400 || response.code == 502
raise ServiceUnavailableException.new(response_code.to_s)
end
Expand All @@ -48,16 +51,13 @@ def reconnect
retry
end

response = _response
response = Net::NNTP::Response.parse(@socket.readline)

if response.code == 400 || response.code == 502
raise ServiceUnavailableException.new(response_code.to_s)
end
end

def _response
Net::NNTP::Response.parse(@socket.readline)
end

def read_multiline(limit = nil)
lines, buffer = 0, ""
while true
Expand All @@ -81,13 +81,11 @@ def self.start(server, port = 119)
end

def mode_reader
@socket.write("MODE READER\r\n");
_response
ask('MODE READER')
end

def listgroup(newsgroup = nil, limit = nil)
@socket.write("LISTGROUP #{newsgroup}\r\n")
response = _response
ask("LISTGROUP #{newsgroup}")

if response.code == 211
return read_multiline(limit).split("\n").map {|n| n.strip.to_i}
Expand All @@ -97,8 +95,7 @@ def listgroup(newsgroup = nil, limit = nil)
end

def article(message_id)
@socket.write("ARTICLE #{message_id}\r\n")
response = _response
ask("ARTICLE #{message_id}")

if response.code == 220
return Net::NNTP::Article.parse(read_multiline)
Expand All @@ -108,8 +105,7 @@ def article(message_id)
end

def head(message_id)
@socket.write("HEAD #{message_id}\r\n")
response = _response
ask("HEAD #{message_id}")

if response.code == 221
return Net::NNTP::Article.parse(read_multiline)
Expand All @@ -119,27 +115,30 @@ def head(message_id)
end

def group(newsgroup)
@socket.write("GROUP #{newsgroup}\r\n")
response = _response

ask("GROUP #{newsgroup}")
response.code == 211
end

def auth(username, password)
@socket.write("AUTHINFO USER #{username}\r\n")
response = _response
ask("AUTHINFO USER #{username}")

if response.code == 281
return true
elsif response.code == 381
@socket.write("AUTHINFO PASS #{password}\r\n")
response = _response
ask("AUTHINFO PASS #{password}")
if response.code == 281
return true
end
end

false
end

private

def ask(message)
@socket.write("#{message}\r\n")
@response = Net::NNTP::Response.parse(@socket.readline)
end
end
end

0 comments on commit 0bf8849

Please sign in to comment.