2020-03-23 13:56:04 +00:00
|
|
|
module Pigeon
|
|
|
|
class Parser
|
2020-04-02 12:38:00 +00:00
|
|
|
class DuplicateKeyError < StandardError; end
|
|
|
|
|
2020-04-17 13:55:18 +00:00
|
|
|
def self.parse(db, tokens)
|
2020-04-18 14:37:43 +00:00
|
|
|
raise "NO!" unless db.is_a?(Pigeon::Database)
|
2020-04-25 15:11:25 +00:00
|
|
|
|
|
|
|
new(db, tokens).parse
|
2020-03-24 12:39:32 +00:00
|
|
|
end
|
|
|
|
|
2020-04-17 13:55:18 +00:00
|
|
|
def initialize(db, tokens)
|
|
|
|
reset_scratchpad
|
2020-04-18 14:37:43 +00:00
|
|
|
@db = db
|
2020-03-24 12:39:32 +00:00
|
|
|
@tokens = tokens
|
|
|
|
@results = []
|
|
|
|
end
|
|
|
|
|
2020-04-25 15:11:25 +00:00
|
|
|
def parse
|
|
|
|
@tokens.each_with_index do |token, _i|
|
2020-03-24 13:00:00 +00:00
|
|
|
case token.first
|
|
|
|
when :AUTHOR then set(:author, token.last)
|
|
|
|
when :KIND then set(:kind, token.last)
|
|
|
|
when :DEPTH then set(:depth, token.last)
|
|
|
|
when :PREV then set(:prev, token.last)
|
2020-04-11 14:53:22 +00:00
|
|
|
when :LIPMAA then set(:lipmaa, token.last)
|
2020-03-24 13:00:00 +00:00
|
|
|
when :HEADER_END then set(:body, {})
|
|
|
|
when :BODY_ENTRY then set(token[1], token[2], @scratchpad[:body])
|
|
|
|
when :BODY_END then nil
|
|
|
|
when :SIGNATURE then set(:signature, token.last)
|
|
|
|
when :MESSAGE_END then finish_this_message!
|
|
|
|
end
|
|
|
|
end
|
|
|
|
@results
|
2020-03-24 12:39:32 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2020-04-17 13:55:18 +00:00
|
|
|
def reset_scratchpad
|
2020-04-18 14:37:43 +00:00
|
|
|
@scratchpad = {}
|
2020-04-17 13:55:18 +00:00
|
|
|
end
|
|
|
|
|
2020-03-24 13:00:00 +00:00
|
|
|
def finish_this_message!
|
2020-03-24 13:12:35 +00:00
|
|
|
@scratchpad.freeze
|
2020-04-20 02:32:37 +00:00
|
|
|
unless @db.peer_blocked?(@scratchpad.fetch(:author))
|
2020-04-23 12:21:00 +00:00
|
|
|
@results.push(@db._ingest_message(**@scratchpad))
|
2020-04-20 02:32:37 +00:00
|
|
|
end
|
2020-04-17 13:55:18 +00:00
|
|
|
reset_scratchpad
|
2020-03-24 12:39:32 +00:00
|
|
|
end
|
|
|
|
|
2020-03-24 13:00:00 +00:00
|
|
|
def set(key, value, hash = @scratchpad)
|
|
|
|
if hash[key]
|
2020-04-02 12:38:00 +00:00
|
|
|
raise DuplicateKeyError, "Found duplicate keys: #{key}"
|
2020-03-24 13:00:00 +00:00
|
|
|
else
|
|
|
|
hash[key] = value
|
|
|
|
end
|
2020-03-23 13:56:04 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|