12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273(*
* Copyright (c) 2014, OCaml.org project
* Copyright (c) 2015 KC Sivaramakrishnan <sk826@cl.cam.ac.uk>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)(* Download urls and cache them — especially during development, it slows down
the rendering to download over and over again the same URL. *)openPrintfopenLwtopenCohttpopenCohttp.ResponseopenCohttp.CodeexceptionStatus_unhandledofstringexceptionTimeoutletmax_num_redirects=5letget_location_exnheaders=matchHeader.getheaders"location"with|Somex->x|None->raise@@Status_unhandled"Location HTTP header not found"letrecget_uriuri=function|0->raise(Status_unhandled"Too many redirects")|n->letmain=Cohttp_lwt_unix.Client.geturi>>=fun(resp,body)->matchresp.statuswith|`OK->Cohttp_lwt.Body.to_stringbody|`Found|`See_other|`Moved_permanently|`Temporary_redirect|`Permanent_redirect->(letl=Uri.of_string@@get_location_exnresp.headersinmatchUri.hostlwith|Some_->get_uril(n-1)|None->lethost=Uri.hosturiinletscheme=Uri.schemeuriinletnew_uri=Uri.with_scheme(Uri.with_hostlhost)schemeinget_urinew_uri(n-1))|_->raise@@Status_unhandled(string_of_statusresp.status)inlettimeout=Lwt_unix.sleep(float_of_int3)>>=fun()->Lwt.failTimeoutinLwt.pick[main;timeout]letgeturl=eprintf"Downloading %s ... %!"url;tryletdata=Lwt_main.run@@get_uri(Uri.of_stringurl)max_num_redirectsineprintf"done %!\n";datawith|(Status_unhandleds|Failures)ase->eprintf"Failed: %s\n"s;raisee|Timeoutase->eprintf"Failed: Timeout\n";raisee