|
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 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 and block then |
|
47 server.setquitting(true); |
|
48 end |
|
49 end |
|
50 end); |
|
51 end |
|
52 batch.download_count = count; |
|
53 batch.downloading_count = count; |
|
54 if block then |
|
55 server.loop(); |
|
56 server.setquitting(false); |
|
57 end |
|
58 return count; |
|
59 end |
|
60 |
|
61 function progress(batch) |
|
62 local progress = {}; |
|
63 for url, request in pairs(batch.urls) do |
|
64 local p = {}; |
|
65 p.bytes_downloaded = request.havebodylength; |
|
66 p.bytes_total = request.bodylength; |
|
67 if p.bytes_total then |
|
68 p.percent = 100/(p.bytes_total/p.bytes_downloaded); |
|
69 end |
|
70 progress[url] = p; |
|
71 end |
|
72 return progress; |
|
73 end |
|
74 |
|
75 function new(callback, urls) |
|
76 local batch = { callback = callback, urls = {} }; |
|
77 if type(urls) == "table" then |
|
78 for _, url in ipairs(urls) do |
|
79 batch.urls[url] = true; |
|
80 end |
|
81 end |
|
82 return setmetatable(batch, _M); |
|
83 end |
|
84 |
|
85 return _M; |