1. --!parent
  2. --!encoding=utf-8
  3.  
  4. --****************************************************************************
  5. -- @file Partial file download based on Range HTTP header
  6. -- @author Valentin Schmidt
  7. -- @version 0.1
  8. --****************************************************************************
  9.  
  10. global $
  11.  
  12. -- public
  13. property range -- useful for reporting/debugging in target callback
  14.  
  15. -- private
  16. property _fp
  17. property _startByte
  18. property _cbHandler
  19. property _cbTarget
  20. property _pos
  21. property _ch
  22.  
  23. ----------------------------------------
  24. -- @constructor
  25. ----------------------------------------
  26. on new (me, tUrl, fp, startByte, numBytes, cbHandler, cbTarget)
  27.     if voidP(cbTarget) then cbTarget = _movie
  28.  
  29.     me._fp = fp
  30.     me._startByte = startByte
  31.     me._cbHandler = cbHandler
  32.     me._cbTarget = cbTarget
  33.     me._pos = 0
  34.  
  35.     me.range = (startByte)&"-"&(startByte+numBytes-1)
  36.  
  37.     me._ch = $.curl.init()
  38.     me._ch.setOption($.curl.CURLOPT.URL, tUrl)
  39.     me._ch.setOption($.curl.CURLOPT.RANGE, me.range) -- adds range header, e.g. "Range: bytes=0-999" (=1000 bytes)
  40.  
  41.     -- uncomment to show progress info
  42.     -- me._ch.setOption($.curl.CURLOPT.NOPROGRESS, 0)
  43.     -- me._ch.setProgressCallback(#slotCurlProgress, me)
  44.  
  45.     -- returnMode: 0=return error code (=default), 1=return data, 2=return chunks immediately
  46.     $.curl.execAsyncDetached(me._ch, #slotDataReceived, me, 2)
  47.     return me
  48. end
  49.  
  50. ----------------------------------------
  51. -- @callback
  52. ----------------------------------------
  53. on slotDataReceived (me, res)
  54.     if ilk(res)=#bytearray then
  55.         $.file.fseek(me._fp, me._startByte + me._pos)
  56.         $.file.fwritebytes(me._fp, res)
  57.         me._pos = me._pos + res.length
  58.     else
  59.         if res<>0 then put "ERROR:" && curl_error(res)
  60.         call(me._cbHandler, me._cbTarget, me, res=0)
  61.     end if
  62. end
  63.  
  64. ----------------------------------------
  65. -- @callback
  66. ----------------------------------------
  67. on slotCurlProgress (me, dltotal, dlnow, ultotal, ulnow)
  68.     if dltotal>0 then
  69.         prog = dlnow*100/dltotal
  70.         if prog<>me.progess then
  71.             put "DOWNLOAD PROGRESS OF RANGE"&& me.range ":" && (dlnow*100/dltotal) && "%"
  72.             me.progress = prog
  73.         end if
  74.     end if
  75. end
  76.  
[raw code]