01 // vim: set ft=cpp:
02 
03 #include "::/Adam/Net/Http"
04 
05 I64 UrlGet(U8* url, U8** data_out = NULL, I64* size_out = NULL) {
06   CUrl curl;
07   UrlInit(&curl);
08 
09   I64 error = 0;
10 
11   if (UrlParse(url, &curl)) {
12     if (!StrCmp(curl.protocol, "http"))
13       error = HttpGet(curl.host, curl.port, curl.path, data_out, size_out);
14     else
15       error = URL_EPROTOCOL;
16   }
17   else
18     error = URL_EPARSE;
19 
20   UrlFree(&curl);
21   return error;
22 }
23 
24 I64 UrlGetWithProgress(U8* url, U8** data_out, I64* size_out) {
25   CUrl curl;
26   UrlInit(&curl);
27 
28   I64 error = 0;
29   I64 size = 0;
30 
31   if (UrlParse(url, &curl)) {
32     if (!StrCmp(curl.protocol, "http")) {
33       I64 sock = HttpOpenGet(curl.host, curl.port, curl.path, &size);
34 
35       if (sock > 0) {
36         if (size >= 0) {
37           U8* data = MAlloc(1 + size);
38           I64 total = 0;
39           I64 progress = 0;
40           "[";
41 
42           while (total < size) {
43             I64 step = size - total;
44 
45             if (step > 1024)
46               step = 1024;
47 
48             I64 got = recv(sock, data + total, step, 0);
49 
50             if (got <= 0) {
51               error = HTTP_EEOF;
52               break;
53             }
54 
55             total += got;
56 
57             I64 new_progress = (20 * total + size - 1) / size;
58             while (progress < new_progress) {
59               '' 0xfe;
60               progress++;
61             }
62           }
63         }
64         else
65           error = HTTP_ECONTENTLENGTH;
66 
67         close(sock);
68 
69         if (error) {
70           "x\n";
71           Free(data);
72         }
73         else {
74           "]\n";
75           data[total] = 0;
76           *data_out = data;
77           *size_out = total;
78         }
79       }
80       else
81         error = sock;
82     }
83     else
84       error = URL_EPROTOCOL;
85   }
86   else
87     error = URL_EPARSE;
88 
89   UrlFree(&curl);
90   return error;
91 }