-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhtml2canvasproxy.ashx
325 lines (270 loc) · 12.2 KB
/
html2canvasproxy.ashx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
<%@ WebHandler Language="C#" Debug="true" Class="Html2CanvasProxy" %>
/*
* html2canvas-csharp-proxy 0.0.6
* Copyright (c) 2014 Guilherme Nascimento (brcontainer@yahoo.com.br)
*
* Released under the MIT license
*/
using System;
using System.IO;
using System.Web;
using System.Net;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
public class Html2CanvasProxy : IHttpHandler {
//Setup
private string defaultCallback = "console.log"; //Set default callback
private string PATH = "images"; //Path relative
private int CCACHE = 60 * 5 * 1000; //Limit access-control and cache
private bool CROSSDOMAIN = false; //Enable cross-domain for use proxy with a sub-domain
private static string JsonEncodeString (string s, bool onlyEncode) {
string[] vetor = new string[127];
vetor[0] = "\\0";
vetor[8] = "\\b";
vetor[9] = "\\t";
vetor[10] = "\\n";
vetor[12] = "\\f";
vetor[13] = "\\r";
vetor[34] = "\\\"";
vetor[47] = "\\/";
vetor[92] = "\\";
int i = 0;
int c;
string d;
string[] e = new string[s.Length];
foreach (string j in e) {
e[i] = s.Substring(i, 1);
c = (int) Convert.ToChar(e[i]);
if (c > 126) {
d = "000" + c.ToString("X");
e[i] = "\\u" + d.Substring(d.Length - 4);
} else {
if (!String.IsNullOrEmpty(vetor[c])) {
e[i] = vetor[c];
} else if (!(c > 31)) {
d = "000" + c.ToString("X");
e[i] = "\\u" + d.Substring(d.Length - 4);
}
}
i++;
}
if (onlyEncode) {
return String.Join("", e);
} else {
return "\"" + String.Join("", e) + "\"";
}
}
private static string Ascii2Inline (string str) {
string[] x = {
"\n",
"\r",
" ",
"\"",
"#",
"&",
"/",
"\\",
":",
"?",
"\0",
"\b",
"\t"
};
string[] y = {
"%0A",
"%0D",
"%20",
"%22",
"%23",
"%26",
"%2F",
"%5C",
"%3A",
"%3F",
"%00",
"",
"%09"
};
int i = 0;
foreach (string j in x) {
str = str.Replace(j, y[i]);
i++;
}
return str;
}
private static string ReadFileEnconding (string file, bool base64) {
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] filebytes = new byte[fs.Length];
fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
fs.Close();
if (base64) {
return Convert.ToBase64String(filebytes);
}
return Html2CanvasProxy.Ascii2Inline(System.Text.Encoding.Default.GetString(filebytes));
}
public void ProcessRequest (HttpContext context) {
string GMDATECACHE = DateTime.UtcNow.ToString();
string ERR = "";
string MIME = "";
string CHARSET = "";
string[] tmp;
string[] makeAdress;
string username = "";
string password = "";
string httpType = "http";
string basicAuth = "";
HttpResponse HS = context.Response;
//set access-control
HS.AddHeader("Access-Control-Max-Age", CCACHE.ToString());
HS.AddHeader("Access-Control-Allow-Origin", "*");
HS.AddHeader("Access-Control-Request-Method", "*");
HS.AddHeader("Access-Control-Allow-Methods", "OPTIONS, GET");
HS.AddHeader("Access-Control-Allow-Headers", "*");
//mime
HS.ContentType = "application/javascript";
//GET
string geturl = context.Request.QueryString["url"];
string getcallback = context.Request.QueryString["callback"];
if (getcallback == "" || getcallback == null) {
ERR = "get param callback is undefined";
getcallback = defaultCallback;
} else if (geturl == "" || geturl == null) {
ERR = "get param url is undefined";
} else {
string realpath = HttpContext.Current.Server.MapPath("./" + PATH);
bool isExists = System.IO.Directory.Exists(realpath);
if (!isExists) {
System.IO.Directory.CreateDirectory(realpath);
isExists = System.IO.Directory.Exists(realpath);
if (!isExists) {
ERR = "\"" + realpath + "\" folder can not be created.";
}
}
if (geturl.IndexOf("https") == 0) {
httpType = "https";
}
geturl = Regex.Replace(geturl, "^(https|http)[:]//", "");
if (ERR == "") {
tmp = geturl.Split('/');
if (tmp[0].IndexOf("@") != -1) {
makeAdress = tmp[0].Split('@');
makeAdress = makeAdress[0].Split(':');
if (makeAdress.Length > 1) {
username = makeAdress[0];
password = makeAdress[1];
} else {
username = makeAdress[0];
}
//Basic authentication
basicAuth = Convert.ToBase64String(
System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)
);
}
WebRequest request = WebRequest.Create(httpType + "://" + geturl);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
//Set same user agent
((HttpWebRequest) request).UserAgent = context.Request.UserAgent;
//Auth basic
request.Headers["Authorization"] = "Basic " + basicAuth;
try {
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK) {
ERR = response.StatusCode.ToString();
} else if (response.Headers["Content-Length"] == "0") {
ERR = "source is blank (Content-length: 0)";
} else {
MIME = response.ContentType.ToLower().Trim();
if (MIME.IndexOf(";") != -1) {
tmp = MIME.Split(';');
MIME = tmp[0].Trim();
tmp[0] = "";
CHARSET = string.Join(" ", tmp).Remove(0, 1).Trim();
}
//Some servers use image/svg-xml (minus signal) instead of image/svg+xml (plus signal)
if ("|image/jpeg|image/jpg|image/png|image/gif|image/svg+xml|image/svg-xml|text/html|application/xhtml|application/xhtml+xml|".IndexOf("|" + MIME + "|")== - 1) {
ERR = MIME + " mime is invalid";
} else {
HashAlgorithm sha = SHA1.Create();
byte[] shafilebyte = sha.ComputeHash(Encoding.UTF8.GetBytes(geturl));
string shafile = BitConverter.ToString(shafilebyte).Replace("-", "").ToLowerInvariant();
string extesionFile = MIME.Replace("image/", "")
.Replace("text/", "")
.Replace("application/", "")
.Replace("x-", "")
.Replace("jpeg", "jpg")
.Replace("xhtml+xml", "xhtml")
.Replace("svg+xml", "svg").Replace("svg-xml", "svg");
shafile = shafile + "." + extesionFile;
Stream receiveStream = response.GetResponseStream();
using (System.IO.FileStream fs = System.IO.File.Create(realpath + "\\" + shafile)) {
int bytesRead;
long sizeBytes = response.ContentLength;
if (!(sizeBytes > 1)) {
sizeBytes = Int32.MaxValue / 2;
}
byte[] buffer = new byte[sizeBytes];
while((bytesRead = receiveStream.Read(buffer, 0, buffer.Length)) != 0) {
fs.Write(buffer, 0, bytesRead);
}
}
if (System.IO.File.Exists(realpath + "\\" + shafile)) {
HS.AddHeader("Last-Modified", DateTime.UtcNow.ToString("R"));
HS.AddHeader("Cache-Control", "max-age=" + (CCACHE - 1));
HS.AddHeader("Pragma", "max-age=" + (CCACHE - 1));
HS.AddHeader("Expires", new DateTime(DateTime.UtcNow.Ticks).AddSeconds(CCACHE - 1).ToString("R"));
if (CROSSDOMAIN) {
bool isBase64 = MIME.IndexOf("image/svg") == -1 && MIME.IndexOf("text/") == -1;
string dataURI = "data:" + Html2CanvasProxy.JsonEncodeString(MIME, true);
if (CHARSET != "" && CHARSET != null) {
dataURI += ";" + Html2CanvasProxy.JsonEncodeString(CHARSET, true);
}
if (isBase64) {
dataURI += ";base64";
}
HS.Write(
getcallback + "(\"" +
dataURI + "," +
Html2CanvasProxy.ReadFileEnconding(realpath + "\\" + shafile, isBase64) +
"\")"
);
} else {
string fullurl = "http://";
if (context.Request.Url.Port == 443) {
fullurl = "https://";
}
fullurl += context.Request.Url.Host;
if (context.Request.Url.Port != 80 && context.Request.Url.Port != 443) {
fullurl += ":" + context.Request.Url.Port.ToString();
}
string[] uri = context.Request.Url.Segments;
uri[uri.Length - 1]="";
fullurl += String.Join("/", uri).Replace("//","/");
fullurl += PATH + "/" + shafile;
HS.Write(getcallback + "(" + Html2CanvasProxy.JsonEncodeString(fullurl, false) + ")");
}
return;
} else {
ERR = "no such file";
}
}
}
} catch (WebException e) {
ERR = e.ToString();
}
}
}
HS.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HS.Cache.SetValidUntilExpires(false);
HS.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HS.Cache.SetCacheability(HttpCacheability.NoCache);
HS.Cache.SetNoStore();
HS.Write(getcallback + "(" + Html2CanvasProxy.JsonEncodeString("error:" + ERR, false) + ")");
}
public bool IsReusable {
get {
return false;
}
}
}