| 1 | local http = require "net.http"; |
| 2 | local server = require "net.server"; |
| 3 | local timer = require "util.timer"; |
| 4 | |
| 5 | local pairs, ipairs, type, setmetatable = |
| 6 | pairs, ipairs, type, setmetatable; |
| 7 | |
| 8 | module "multihttp" |
| 9 | __index = _M; |
| 10 | |
| 11 | function set_callback(batch, callback) |
| 12 | batch.callback = callback; |
| 13 | end |
| 14 | |
| 15 | function set_progress_callback(batch, callback, delay) |
| 16 | delay = delay or 1; |
| 17 | batch.progress_callback = callback; |
| 18 | timer.add_task(delay, function () |
| 19 | if batch.progress_callback then |
| 20 | batch.progress_callback(batch); |
| 21 | if batch.progress_callback and batch.status ~= "complete" then |
| 22 | return delay; |
| 23 | end |
| 24 | end |
| 25 | end); |
| 26 | end |
| 27 | |
| 28 | function add_url(batch, url) |
| 29 | batch.urls[url] = true; |
| 30 | end |
| 31 | |
| 32 | function remove_url(batch, url) |
| 33 | batch.urls[url] = nil; |
| 34 | end |
| 35 | |
| 36 | function download(batch, block) |
| 37 | batch.status = "downloading"; |
| 38 | local count = 0; |
| 39 | for url in pairs(batch.urls) do |
| 40 | count = count + 1; |
| 41 | batch.urls[url] = |
| 42 | http.request(url, nil, function (data, status, request) |
| 43 | if batch.callback then |
| 44 | batch.downloading_count = batch.downloading_count - 1; |
| 45 | batch.callback(url, status, data, request); |
| 46 | if batch.downloading_count == 0 then |
| 47 | if block then |
| 48 | server.setquitting(true); |
| 49 | end |
| 50 | batch.status = "complete"; |
| 51 | end |
| 52 | end |
| 53 | end); |
| 54 | end |
| 55 | batch.download_count = count; |
| 56 | batch.downloading_count = count; |
| 57 | if block then |
| 58 | server.loop(); |
| 59 | server.setquitting(false); |
| 60 | end |
| 61 | return count; |
| 62 | end |
| 63 | |
| 64 | function progress(batch) |
| 65 | local progress = {}; |
| 66 | for url, request in pairs(batch.urls) do |
| 67 | if request ~= true then |
| 68 | local p = {}; |
| 69 | p.bytes_downloaded = request.havebodylength; |
| 70 | p.bytes_total = request.bodylength; |
| 71 | if p.bytes_total then |
| 72 | p.percent = 100/(p.bytes_total/p.bytes_downloaded); |
| 73 | end |
| 74 | progress[url] = p; |
| 75 | end |
| 76 | end |
| 77 | return progress; |
| 78 | end |
| 79 | |
| 80 | function new(callback, urls) |
| 81 | local batch = { callback = callback, urls = {} }; |
| 82 | if type(urls) == "table" then |
| 83 | for _, url in ipairs(urls) do |
| 84 | batch.urls[url] = true; |
| 85 | end |
| 86 | end |
| 87 | return setmetatable(batch, _M); |
| 88 | end |
| 89 | |
| 90 | return _M; |