1 /**
2  * ae.sys.net implementation using ae.net
3  * Note: ae.net requires an SSL provider for HTTPS links.
4  *
5  * License:
6  *   This Source Code Form is subject to the terms of
7  *   the Mozilla Public License, v. 2.0. If a copy of
8  *   the MPL was not distributed with this file, You
9  *   can obtain one at http://mozilla.org/MPL/2.0/.
10  *
11  * Authors:
12  *   Vladimir Panteleev <vladimir@thecybershadow.net>
13  */
14 
15 module ae.sys.net.ae;
16 
17 import ae.net.asockets;
18 import ae.net.http.client;
19 import ae.net.ietf.url;
20 import ae.sys.net;
21 
22 static import std.file;
23 
24 class AENetwork : Network
25 {
26 	private Data getData(string url)
27 	{
28 		Data result;
29 		bool got;
30 
31 		httpGet(url,
32 			(Data data) { result = data; got = true; },
33 			(string error) { throw new Exception(error); }
34 		);
35 
36 		socketManager.loop();
37 		assert(got);
38 		return result;
39 	}
40 
41 	override void downloadFile(string url, string target)
42 	{
43 		Data data = getData(url);
44 		std.file.write(target, data.contents);
45 	}
46 
47 	override void[] getFile(string url)
48 	{
49 		return getData(url).toHeap;
50 	}
51 
52 	override bool urlOK(string url)
53 	{
54 		bool got, result;
55 
56 		auto request = new HttpRequest;
57 		request.method = "HEAD";
58 		request.resource = url;
59 		try
60 		{
61 			httpRequest(request,
62 				(HttpResponse response, string disconnectReason)
63 				{
64 					got = true;
65 					if (!response)
66 						result = false;
67 					else
68 						result = response.status == HttpStatusCode.OK;
69 				}
70 			);
71 
72 			socketManager.loop();
73 		}
74 		catch (Exception e)
75 			return false;
76 
77 		assert(got);
78 		return result;
79 	}
80 
81 	override string resolveRedirect(string url)
82 	{
83 		string result; bool got;
84 
85 		auto request = new HttpRequest;
86 		request.method = "HEAD";
87 		request.resource = url;
88 		httpRequest(request,
89 			(HttpResponse response, string disconnectReason)
90 			{
91 				if (!response)
92 					throw new Exception(disconnectReason);
93 				else
94 				{
95 					got = true;
96 					result = response.headers.get("Location", null);
97 					if (result)
98 						result = url.applyRelativeURL(result);
99 				}
100 			}
101 		);
102 
103 		socketManager.loop();
104 		assert(got);
105 		return result;
106 	}
107 }
108 
109 static this()
110 {
111 	net = new AENetwork();
112 }