Skip to content

Instantly share code, notes, and snippets.

@rgaufman
Last active May 17, 2018 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgaufman/bee99b0070f99def3b20551f1dca9b0c to your computer and use it in GitHub Desktop.
Save rgaufman/bee99b0070f99def3b20551f1dca9b0c to your computer and use it in GitHub Desktop.
require 'active_support/all'
def parse_stream(stream)
begin
boundary = stream.readline.strip # Boundary is the first thing in the stream
loop do
fail 'Nothing in stream' unless boundary.present?
header = {}
stream.each_line do |line|
break if line.blank?
key, val = line.split(': ')
header[key] = val&.strip
end
fail 'No Content Length' unless header.key?('Content-Length')
fail 'No Content Type' unless header.key?('Content-Type')
content_length = header['Content-Length'].to_i
data = stream.read(content_length)
yield header, data
# Try to find the next boundary, ignoring blank lines
(1..10).each do
new_boundary = stream.readline.strip
next unless new_boundary.present?
if new_boundary != boundary
fail "Bad boundary: #{new_boundary}, expected: #{boundary}"
else
break
end
end
end
rescue EOFError
puts "End of stream, returning..."
return
ensure
stream.close
end
end
def parse_plate(plate)
parsed = {}
plate.each_line do |line|
keys, val = line.split('=')
keys = keys.split('.')
val = val&.strip
ctx = parsed
keys[1...-1].each do |key| # Exclude initial 'Events[0].'
ctx[key] = {} unless ctx.key?(key)
ctx = ctx[key] # Update context for nested hashes
end
has_array = keys.last.split(/\[(\d)\]/)
if has_array[1] # Deal with keys ending in [0] etc, e.g. BoundingBox[1]
key = has_array[0]
val = val.to_i.zero? ? val : val.to_i # Try to cast to int
ctx[key] ? ctx[key] << val : ctx[key] = [val] # Create or append array
else
ctx[keys.last] = val
end
end
parsed
end
stream = open('snap.cgi', 'r')
parse_stream(stream) do |header, data|
content_type = header['Content-Type']
unless %w[text/plain image/jpeg].include?(content_type)
puts "Unknown content type: #{content_type}"
next
end
if content_type == 'text/plain'
p parse_text(data)
elsif content_type == 'image/jpeg'
puts "Skipping image"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment