asciinema.org/app/models/asciicast_params.rb

90 lines
2.4 KiB
Ruby
Raw Normal View History

class AsciicastParams
2015-03-23 16:40:11 +00:00
FormatError = Class.new(StandardError)
def self.build(asciicast_params, user, user_agent)
attributes = if asciicast_params.try(:respond_to?, :read)
from_format_1_request(asciicast_params, user, user_agent)
else
from_format_0_request(asciicast_params, user, user_agent)
end
attributes.merge(private: user.new_asciicast_private?)
end
def self.from_format_0_request(params, user, user_agent)
meta = params.delete(:meta)
attributes = {
2014-02-09 13:58:17 +00:00
command: meta['command'],
2014-02-11 16:49:22 +00:00
duration: meta['duration'],
2014-02-09 13:58:17 +00:00
shell: meta['shell'],
2014-02-11 16:49:22 +00:00
stdin_data: params[:stdin],
stdin_timing: params[:stdin_timing],
stdout_data: params[:stdout],
stdout_timing: params[:stdout_timing],
2014-02-09 13:58:17 +00:00
terminal_columns: meta['term']['columns'],
2014-02-11 16:49:22 +00:00
terminal_lines: meta['term']['lines'],
2014-02-09 13:58:17 +00:00
terminal_type: meta['term']['type'],
2014-02-11 16:49:22 +00:00
title: meta['title'],
user: user,
version: 0,
}
2015-02-27 13:58:04 +00:00
if meta['uname'] # old client, with useless user_agent
attributes[:uname] = meta['uname']
else
attributes[:user_agent] = user_agent
end
attributes
end
def self.from_format_1_request(asciicast_file, user, user_agent)
2015-03-23 16:40:11 +00:00
begin
asciicast = Oj.sc_parse(AsciicastHandler.new, asciicast_file)
rescue Oj::ParseError
end
if asciicast.nil?
2015-03-23 16:40:11 +00:00
raise FormatError, "This doesn't look like a valid asciicast file"
end
version = asciicast['version']
if version != 1
2015-03-23 16:40:11 +00:00
raise FormatError, "Unsupported asciicast format version: #{version}"
end
2015-02-27 13:58:04 +00:00
env = asciicast['env']
{
command: asciicast['command'],
duration: asciicast['duration'],
file: asciicast_file,
2015-02-27 13:58:04 +00:00
shell: env && env['SHELL'],
terminal_columns: asciicast['width'],
terminal_lines: asciicast['height'],
2015-02-27 13:58:04 +00:00
terminal_type: env && env['TERM'],
title: asciicast['title'],
user: user,
2015-02-27 13:58:04 +00:00
user_agent: user_agent,
version: version,
2015-02-27 13:58:04 +00:00
}
end
class AsciicastHandler < ::Oj::ScHandler
META_ATTRIBUTES = %w[version width height duration command title env SHELL TERM]
2015-02-27 13:58:04 +00:00
def hash_start
{}
end
def hash_set(h, k, v)
if META_ATTRIBUTES.include?(k)
h[k] = v
end
end
end
end