--!parent
--!encoding=utf-8
--****************************************************************************
-- @file Partial file download based on Range HTTP header
-- @author Valentin Schmidt
-- @version 0.1
--****************************************************************************
global $
-- public
property range -- useful for reporting/debugging in target callback
-- private
property _fp
property _startByte
property _cbHandler
property _cbTarget
property _pos
property _ch
----------------------------------------
-- @constructor
----------------------------------------
on new (me, tUrl, fp, startByte, numBytes, cbHandler, cbTarget)
if voidP(cbTarget) then cbTarget = _movie
me._fp = fp
me._startByte = startByte
me._cbHandler = cbHandler
me._cbTarget = cbTarget
me._pos = 0
me.range = (startByte)&"-"&(startByte+numBytes-1)
me._ch = $.curl.init()
me._ch.setOption($.curl.CURLOPT.URL, tUrl)
me._ch.setOption($.curl.CURLOPT.RANGE, me.range) -- adds range header, e.g. "Range: bytes=0-999" (=1000 bytes)
-- uncomment to show progress info
-- me._ch.setOption($.curl.CURLOPT.NOPROGRESS, 0)
-- me._ch.setProgressCallback(#slotCurlProgress, me)
-- returnMode: 0=return error code (=default), 1=return data, 2=return chunks immediately
$.curl.execAsyncDetached(me._ch, #slotDataReceived, me, 2)
return me
end
----------------------------------------
-- @callback
----------------------------------------
on slotDataReceived (me, res)
if ilk(res)=#bytearray then
$.file.fseek(me._fp, me._startByte + me._pos)
$.file.fwritebytes(me._fp, res)
me._pos = me._pos + res.length
else
if res<>0 then put "ERROR:" && curl_error(res)
call(me._cbHandler, me._cbTarget, me, res=0)
end if
end
----------------------------------------
-- @callback
----------------------------------------
on slotCurlProgress (me, dltotal, dlnow, ultotal, ulnow)
if dltotal>0 then
prog = dlnow*100/dltotal
if prog<>me.progess then
put "DOWNLOAD PROGRESS OF RANGE"&& me.range ":" && (dlnow*100/dltotal) && "%"
me.progress = prog
end if
end if
end