Skip to content

Instantly share code, notes, and snippets.

@ReiFan49
Last active June 1, 2018 07:19
Show Gist options
  • Save ReiFan49/4330ea58837eac2e24c1c9bee6270903 to your computer and use it in GitHub Desktop.
Save ReiFan49/4330ea58837eac2e24c1c9bee6270903 to your computer and use it in GitHub Desktop.
simple yet lazy multipart handler on ruby
# MIT License
#
# Copyright (c) 2018 Rei Hakurei
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Source: https://gist.github.com/ReiFan49/4330ea58837eac2e24c1c9bee6270903
class Multipart
# RFC 1341
BCHAR = "[0-9A-Za-z#{Regexp.escape("'()+_-./:=?")}]"
BCHARS = "(?:#{BCHAR}|\x20)"
BOUND = /(#{BCHARS}{0,69}#{BCHAR})$/
BOUNDX = Regexp.compile(BOUND.source.chop,BOUND.options)
def initialize(bound=nil,*content)
init_bound(bound)
init_content(*content)
end
def boundary
@boundary
end
def <<(contents)
case contents
when Hash
body = contents.delete('body')
@content.push(Content.new(body,contents))
when Array
contents.each { |content|
self[@content.length] = content
}
else
self << [contents]
end
end
def [](index)
@content.fetch(index,nil)
end
def []=(index,value)
case value
when NilClass
if index >= @content.size
@content.pop
elsif index < 0
@content.shift
else
@content.delete_at(index)
end
nil
when Content,String
content = Content.parse(value)
if index >= @content.size
@content.push content
elsif index < 0
@content.unshift content
else
@content[index] = content
end
content
else
fail TypeError, "Unsupported operation to convert `#{content.class}' into Content"
end
end
def boundary=(new_bound)
case new_bound
when NilClass, ''
rg = BCHAR[1...-1].scan(/.(?:[-].)?/).map{|x|
a,b = x[0],x[-1]
(a.ord).upto(b.ord).to_a.map(&:chr)
}.flatten.uniq
@boundary.replace(rand(32..70).times.to_a.map{rg.shuffle.first}*'')
else
md = BOUND.match(new_bound.to_s)
if md then
@boundary.replace(md.captures.join(''))
else
@boundary
end
end
end
def each(&block)
@content.each(&block)
end
def inspect
proc { |*args|
fail TypeError unless args.all?{|x|self.instance_variable_defined?(x)}
head = "%s:%%#0%dx"%[self.class.name,0.size<<1]%[__id__ << 1]
inst = args || self.instance_variables
sprintf("#<%s%s>",
head,
inst.size > 0 ? " %s" % ( inst.map{ |sym|"%s=%s" % [ sym,instance_variable_get(sym).inspect ] } * ', ') : ''
)
}.call(:@boundary)
end
def to_s
double = "-" * 2
border = double + @boundary
separt = border + $/
sprintf("%s%s%s",separt,@content.map{ |c|
"#{c}#{$/}"
} * separt,border + double);
end
class << self
def parse(raw)
return raw if raw.is_a?(Multipart)
md = /[-]{2}#{BOUND}/.match(raw)
return nil unless md
b = md[1]
md = /[-]{2}#{BOUNDX}
(.+)
[-]{2}\1[-]{2}/mx.match(raw)
return new(b) unless md
b = md[1]
c = md[2].split(/(?:\r\n?|\n)/).slice(1..-1) * ($/)
return new(b,*(c.split('-' * 2 + b)))
end
end
class Content
def initialize(body,head)
# Assertions
fail ArgumentError, 'Expected Content-Disposition header to be present' unless head.keys.include?('Content-Disposition')
@head = head || {}
@body = body || ''
@clones={}
end
def body
@clones[:body] ||= @body.dup.freeze
end
def body=(new_body)
@clones.delete :body
@body.replace(new_body)
end
def head
@clones[:head] ||= @head.dup.freeze
end
def [](key)
head.fetch(key,nil)
end
def []=(key,value)
@clones.delete :head
@head[k.to_s] = v.to_s
end
def each(&block)
@head.each(&block)
end
def inspect
proc { |*args|
fail TypeError unless args.all?{|x|self.instance_variable_defined?(x)}
head = "%s:%%#0%dx"%[self.class.name,0.size<<1]%[__id__ << 1]
inst = args || self.instance_variables
sprintf("#<%s%s>",
head,
inst.size > 0 ? " %s" % ( inst.map{ |sym|"%s=%s" % [ sym,instance_variable_get(sym).inspect ] } * ', ') : ''
)
}.call()
end
def to_s
sprintf("%s%s%s",@head.map{|k,d|
d.map { |v| sprintf("%s: %s",k,v) } * $/
} * $/,$/*2,@body);
end
class << self
def parse(raw)
return raw if raw.is_a?(Content)
#'-----------------------------14013246541315956113474900849'
#'Content-Disposition: form-data; name="dir[]" '
#' '
#'/public_html/api '
#'-----------------------------14013246541315956113474900849--'
head, body = raw.split(/(?:\r\n?|\n){2}/,2)
hdr = Hash.new { |h,k| h[k] = [] }
head.each_line { |line|
line.chomp!
k,v = line.split(': ',2)
hdr[k].push(v) unless k.nil? || v.nil?
}
body.chomp!
new(body,hdr)
end
end
protected
private
end
protected
private
def init_bound(b)
@boundary=String.new()
@boundary.define_singleton_method(:to_s) {
c = to_str
c = "\"#{c}\"" if /\x20/.match(c)
"boundary=#{c}"
}
self.boundary=b
end
def init_content(*c)
@content=(c.is_a?(Array)&& c.all?{|x|[Content,String].any?{|y|x.is_a?(y)}} && c) || []
@content.map! { |x| x.is_a?(String) ? Content.parse(x) : x }
end
end
@ReiFan49
Copy link
Author

ReiFan49 commented Jun 1, 2018

The snippet is made around 2016 July. That's why i don't really remember the flow.

@ReiFan49
Copy link
Author

ReiFan49 commented Jun 1, 2018

Revision Note: make it to work with imgur example.

Just throw me some good multipart raw if it has some errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment