Skip to content

Instantly share code, notes, and snippets.

@hyrious hyrious/AsHttp.rb
Created May 15, 2019

Embed
What would you like to do?
# coding: utf-8
require 'api'
module AsHttp
AsHttp = dll('AsHttp.dll')
%w[ get post head ].each do |meth|
define_singleton_method meth do |url, data=nil, &callback|
Query.new url, meth.upcase do |query|
query.body = data if data
query.start &callback if callback
end
end
end
class Query
Pool = {}
attr_accessor :callback, :loaded, :total, :state, :content
def initialize url, meth
@url, @meth = url, meth
if (@hquery = AsHttp.CreateQueryA url, meth) == 0
puts "AsHttp: failed to CreateQueryA, what's wrong?"
else
self.class.register_auto_dispose self, @hquery
yield self if block_given?
end
@loaded = @total = @state = UNKNOWN
end
def self.register_auto_dispose obj, hquery
Pool[obj.object_id] = hquery
ObjectSpace.define_finalizer obj, proc { |id|
if Pool.key? id
_dispose Pool[id]
Pool.delete id
end
}
end
def self._dispose hquery
if (AsHttp.FinishQuery hquery) == 0
puts "AsHttp: failed to FinishQuery 0x%08x" % hquery
end
end
def dispose
self.class._dispose @hquery
Pool.delete @hquery
@hquery = 0
end
def disposed?
@hquery == 0
end
def inspect
"#<AsHttp::Query:0x%08x #@meth #@url>" % @hquery
end
def body= data
assert!(String === data)
if @started
puts "AsHttp: refused to SetData after StartQuery 0x%08x" % @hquery
elsif (AsHttp.SetData @hquery, data, data.size) == 0
puts "AsHttp: failed to SetData 0x%08x" % @hquery
dispose
end
end
def start &callback
if @started
puts "AsHttp: refused to start a query twice 0x%08x" % @hquery
elsif (AsHttp.StartQuery @hquery) == 0
puts "AsHttp: failed to StartQuery 0x%08x" % @hquery
dispose
else
@started = true
@callback = callback
end
end
UNKNOWN = 0 # 状态未知
READY = 1 # 请求已创建但未开始
SENDING = 2 # 请求已发送
RECEIVING = 3 # 请求已得到回应,正在接收数据
FINISHED = 4 # 请求已完成
FAILED = 5 # 请求已失败
def update
return unless @hquery and @started
return if @state == FAILED or @state == FINISHED
loaded = [].pack 'x4'
total = [].pack 'x4'
@state = AsHttp.GetProgress @hquery, total, loaded
@total = total.unpack('L')[0]
@loaded = loaded.unpack('L')[0]
@callback.call self if @callback
if @state == FINISHED
len = [].pack 'x4'
AsHttp.GetContent @hquery, '', len
@content = [].pack "x#{len.unpack('L')[0]}"
AsHttp.GetContent @hquery, @content, len
dispose
end
end
end
end
begin # test
a = AsHttp.get 'https://example.org' do |a|
puts "[ #{a.state} ] #{a.loaded} / #{a.total}"
end
until a.disposed?
a.update
Graphics.update
end
puts a.content
rescue
puts $!, $!.backtrace
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.