mirror of
https://github.com/electron/electron.git
synced 2026-02-19 03:14:51 -05:00
Compare commits
1017 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
959e80cc53 | ||
|
|
97010bf947 | ||
|
|
372c5b9518 | ||
|
|
4dc2c2800c | ||
|
|
ba1b75c218 | ||
|
|
5dac4531ca | ||
|
|
3cb788a030 | ||
|
|
9984dd9017 | ||
|
|
7efa4ccfb3 | ||
|
|
3bf5ad22f4 | ||
|
|
6e94fb3f9f | ||
|
|
9c92d87e2f | ||
|
|
8dcf7fc0b9 | ||
|
|
c7fd17a723 | ||
|
|
b68f8999ca | ||
|
|
35cb95b3d8 | ||
|
|
3b3cc0215a | ||
|
|
3cb2484184 | ||
|
|
bafcac7913 | ||
|
|
6a0c701a43 | ||
|
|
5ed3bd8724 | ||
|
|
779e3250c0 | ||
|
|
4c5197fe6e | ||
|
|
72a75889de | ||
|
|
242658102a | ||
|
|
7586295378 | ||
|
|
e7fce15152 | ||
|
|
456c9f09a2 | ||
|
|
f229d12056 | ||
|
|
4a2d94d031 | ||
|
|
df09e278a1 | ||
|
|
10f65979ff | ||
|
|
cac3884d75 | ||
|
|
b9734edfd1 | ||
|
|
ace3216392 | ||
|
|
12cb11f99b | ||
|
|
c16c4c25ed | ||
|
|
8e30e21ee6 | ||
|
|
a80f7fc81f | ||
|
|
83e7b00e7c | ||
|
|
eabb872345 | ||
|
|
b12090a129 | ||
|
|
0bf12e4e76 | ||
|
|
411b9f2ae7 | ||
|
|
a632f1f1b7 | ||
|
|
2543517443 | ||
|
|
5736df41c8 | ||
|
|
fbbe8afc3e | ||
|
|
6fdd055642 | ||
|
|
0f082ecd5c | ||
|
|
f29a600fd8 | ||
|
|
1bde50636f | ||
|
|
7d739a3608 | ||
|
|
8d3f0f47c1 | ||
|
|
dfd338d8bf | ||
|
|
dd242f4b28 | ||
|
|
4c61f62149 | ||
|
|
fd654afae9 | ||
|
|
cadddfec23 | ||
|
|
0e8aa5c252 | ||
|
|
edac24c9be | ||
|
|
0251f5aa93 | ||
|
|
cccd3778f8 | ||
|
|
680f3432ae | ||
|
|
420fb46121 | ||
|
|
6ef605eaa2 | ||
|
|
d7247bc77d | ||
|
|
5e6e118595 | ||
|
|
b1f19970e7 | ||
|
|
c30ecc38d0 | ||
|
|
14d9b8a8b4 | ||
|
|
f0d872947d | ||
|
|
40a212e132 | ||
|
|
cb9b3b29af | ||
|
|
da65c881e2 | ||
|
|
aa5e51dbe0 | ||
|
|
b5d38bfff0 | ||
|
|
a3054443f4 | ||
|
|
1f631ca337 | ||
|
|
e7576019e9 | ||
|
|
77448c75c6 | ||
|
|
538ebabf7e | ||
|
|
d17dfabfcb | ||
|
|
b6cb396893 | ||
|
|
4da56797c3 | ||
|
|
570e4f6a34 | ||
|
|
8c5a2c0a4a | ||
|
|
1c1e9fc7a7 | ||
|
|
0a3a0def25 | ||
|
|
ae9ee76e56 | ||
|
|
7908013a49 | ||
|
|
c7bb1d0300 | ||
|
|
4cf67fea52 | ||
|
|
2c29a4e93d | ||
|
|
04234f41f2 | ||
|
|
0799c8721c | ||
|
|
442174da0f | ||
|
|
ef94a79cac | ||
|
|
38afcff63a | ||
|
|
7ddfffb723 | ||
|
|
f8e601adaf | ||
|
|
dd27520637 | ||
|
|
85c07d0715 | ||
|
|
4dac36d111 | ||
|
|
ae27218296 | ||
|
|
c92efa4ec5 | ||
|
|
cbf499b18a | ||
|
|
7b1117e186 | ||
|
|
3bd3d9440a | ||
|
|
704cdd3a2b | ||
|
|
c56e5abd8c | ||
|
|
ec61041d41 | ||
|
|
32b51bce75 | ||
|
|
e0576ef11a | ||
|
|
a889ec7957 | ||
|
|
bef0dd868b | ||
|
|
3d74cacefe | ||
|
|
0b1248c8e6 | ||
|
|
0569c929a1 | ||
|
|
2dc42971ce | ||
|
|
577d0483e9 | ||
|
|
a3fde67056 | ||
|
|
79aebdffb7 | ||
|
|
fc800837bd | ||
|
|
58469efd1c | ||
|
|
80c36602fd | ||
|
|
f910704838 | ||
|
|
f17dc63c16 | ||
|
|
04b0d61323 | ||
|
|
544b4c5209 | ||
|
|
b35f37ea5a | ||
|
|
7f0bbd27b1 | ||
|
|
3b557bcf2e | ||
|
|
ef2f0580d9 | ||
|
|
425d2fa6f1 | ||
|
|
1409056baf | ||
|
|
72cb493023 | ||
|
|
1e7f26e5fd | ||
|
|
383e75796a | ||
|
|
1edfffae25 | ||
|
|
96e7b443fc | ||
|
|
8f728af13a | ||
|
|
281b0741f7 | ||
|
|
38c43ab48f | ||
|
|
d1d3d1bd1f | ||
|
|
89a7bdb566 | ||
|
|
09d59f2b83 | ||
|
|
ebec22045d | ||
|
|
a2c4000b84 | ||
|
|
9010838f21 | ||
|
|
6fe40ca797 | ||
|
|
101b971f36 | ||
|
|
6156254886 | ||
|
|
d0e4bd3fc9 | ||
|
|
3e5213b4e9 | ||
|
|
7ba8855ac1 | ||
|
|
c3e0ae9646 | ||
|
|
4b456bf3cb | ||
|
|
2a4bdfff98 | ||
|
|
c4baee0dab | ||
|
|
15688c6d6e | ||
|
|
aa4d7f1799 | ||
|
|
0476eb67ab | ||
|
|
69aebc05e5 | ||
|
|
98d06f6e5c | ||
|
|
7d321a90aa | ||
|
|
cfddc0a125 | ||
|
|
ade70463c1 | ||
|
|
4cb983ed40 | ||
|
|
79b3fcb2ab | ||
|
|
4cfa7be79d | ||
|
|
67bcc2a972 | ||
|
|
449bdcfda2 | ||
|
|
e70adc8f83 | ||
|
|
a6ae1ca755 | ||
|
|
b6fb8d3a63 | ||
|
|
5462a2c197 | ||
|
|
de428e9a7a | ||
|
|
fbe36e2365 | ||
|
|
5ac12c9e44 | ||
|
|
8d11391cb4 | ||
|
|
e82f453f71 | ||
|
|
abc187d651 | ||
|
|
913ef7890f | ||
|
|
bcb24bcdd1 | ||
|
|
d7ce600503 | ||
|
|
d16f29f7fc | ||
|
|
3b77af7ac3 | ||
|
|
0a241479cb | ||
|
|
1c8177c542 | ||
|
|
3f148fc3aa | ||
|
|
dd2310df48 | ||
|
|
9bc81be9d0 | ||
|
|
dc90c1153e | ||
|
|
7beb7b9a12 | ||
|
|
b6198b1648 | ||
|
|
16ff7b17a0 | ||
|
|
0d8be47c0f | ||
|
|
c4ab79e7ae | ||
|
|
49d91c7fc8 | ||
|
|
2b84b1ea43 | ||
|
|
4bb6f57657 | ||
|
|
db47a846da | ||
|
|
a3c951b14b | ||
|
|
c5abb17569 | ||
|
|
1b0ba71973 | ||
|
|
8dd004235b | ||
|
|
55955c3d79 | ||
|
|
5b33e9d9b7 | ||
|
|
6871b448ad | ||
|
|
7a1b3c5f2d | ||
|
|
2e8349c520 | ||
|
|
d63150502b | ||
|
|
daa61688b1 | ||
|
|
0a3b0391f4 | ||
|
|
1b66c03e41 | ||
|
|
92362da082 | ||
|
|
16e468137f | ||
|
|
b27a34eb91 | ||
|
|
18176b48b4 | ||
|
|
317f0cec68 | ||
|
|
49009236d9 | ||
|
|
976c7d122a | ||
|
|
ef548b6592 | ||
|
|
37c1df6ce1 | ||
|
|
d9068b7175 | ||
|
|
cac0a4fe3c | ||
|
|
e6807b387c | ||
|
|
f6f73a5a78 | ||
|
|
7bad919bee | ||
|
|
667db6fa67 | ||
|
|
022ee3793b | ||
|
|
5c0e8c5fd3 | ||
|
|
961436f300 | ||
|
|
e2c7e4b1ad | ||
|
|
d12b0eefe0 | ||
|
|
8dfb8c5589 | ||
|
|
57bb08e084 | ||
|
|
03e0905519 | ||
|
|
b6717a6644 | ||
|
|
41b32cf5d9 | ||
|
|
176f4728d7 | ||
|
|
0de78019c8 | ||
|
|
1926169c91 | ||
|
|
25b3ee29cf | ||
|
|
2228e5ac65 | ||
|
|
92cace3998 | ||
|
|
7dc858be02 | ||
|
|
7ffa127f0f | ||
|
|
f423312090 | ||
|
|
4cacd15730 | ||
|
|
37eeaf32ad | ||
|
|
b97c3aca2d | ||
|
|
2e07877c28 | ||
|
|
d8bd7654c6 | ||
|
|
f979e0cfbc | ||
|
|
1582824d33 | ||
|
|
71009fd61e | ||
|
|
055b5d274e | ||
|
|
1841742586 | ||
|
|
3841ac9b6d | ||
|
|
ed1c2a47f1 | ||
|
|
bcc4f67784 | ||
|
|
771d4dc374 | ||
|
|
b1fb7c7bfb | ||
|
|
725dac35ab | ||
|
|
6e32da3798 | ||
|
|
32ac551ca5 | ||
|
|
b90ac55d2d | ||
|
|
e797639d6d | ||
|
|
a31d041f03 | ||
|
|
6b70f0e8e6 | ||
|
|
b1357ab12b | ||
|
|
ffdec7a661 | ||
|
|
50822bc8d4 | ||
|
|
85164223cb | ||
|
|
5cb6ba2883 | ||
|
|
e23030b69e | ||
|
|
d417bbdcfd | ||
|
|
e6f92f3f30 | ||
|
|
3b59f12495 | ||
|
|
3083693e67 | ||
|
|
2a2f7e7090 | ||
|
|
f4c697d7a1 | ||
|
|
944690e79b | ||
|
|
ae303ade7d | ||
|
|
19162f4bac | ||
|
|
ee53f8cef6 | ||
|
|
4463715714 | ||
|
|
f6894da715 | ||
|
|
1657908fa8 | ||
|
|
26d059b3ea | ||
|
|
49aaa2fe96 | ||
|
|
0a9b201c34 | ||
|
|
e17cd837ef | ||
|
|
981208b66c | ||
|
|
77af675511 | ||
|
|
a92ee9443d | ||
|
|
23a52c02a3 | ||
|
|
8536f62826 | ||
|
|
312f14ee88 | ||
|
|
1f660c67c6 | ||
|
|
325bdfaf23 | ||
|
|
e3dcdba2db | ||
|
|
6b5a2c550a | ||
|
|
21e702a563 | ||
|
|
f79cfae3c2 | ||
|
|
51ffe25f45 | ||
|
|
0a0d7a8202 | ||
|
|
421490c6b3 | ||
|
|
068e12d909 | ||
|
|
d251642c83 | ||
|
|
27ceeb5e94 | ||
|
|
4ac616b681 | ||
|
|
fc677b7cf6 | ||
|
|
d25e511fc0 | ||
|
|
b4ba2f6d55 | ||
|
|
f967d73a13 | ||
|
|
c923aa2fde | ||
|
|
dec2078e54 | ||
|
|
2d16034854 | ||
|
|
4ce431829f | ||
|
|
430b355258 | ||
|
|
638ca05702 | ||
|
|
9e7cce3d2b | ||
|
|
c7a3142bab | ||
|
|
b6f5e26eab | ||
|
|
3330647834 | ||
|
|
bb8c7dfc7e | ||
|
|
4dea193854 | ||
|
|
080c2c9218 | ||
|
|
182f63d3a3 | ||
|
|
d3e0c461f6 | ||
|
|
b09a1c7607 | ||
|
|
7cc1efd2e6 | ||
|
|
324096aa37 | ||
|
|
d780a16d78 | ||
|
|
005ef96ac0 | ||
|
|
4f74be084a | ||
|
|
b7c2188d09 | ||
|
|
192326c7c5 | ||
|
|
1af064a144 | ||
|
|
6061fcce40 | ||
|
|
e68a9486da | ||
|
|
dd8bcb67ba | ||
|
|
27661d8e7b | ||
|
|
94ddcc4742 | ||
|
|
2515087322 | ||
|
|
36a5ba0d4d | ||
|
|
241b2a98af | ||
|
|
9b2e3d1d0b | ||
|
|
67cb05b435 | ||
|
|
3f5222b047 | ||
|
|
28e7e6492d | ||
|
|
23f7f63405 | ||
|
|
99eaa0d1bb | ||
|
|
543dbaf412 | ||
|
|
5901293628 | ||
|
|
30543cec74 | ||
|
|
66aeeac8df | ||
|
|
b03bc4de83 | ||
|
|
601c3f97ea | ||
|
|
d01a8eaa39 | ||
|
|
54e1c11b2b | ||
|
|
c1ad66b104 | ||
|
|
a905259646 | ||
|
|
356045ff57 | ||
|
|
a9f69bf732 | ||
|
|
3e181b8efc | ||
|
|
171c76e3cb | ||
|
|
0299f69fd1 | ||
|
|
0bdb7b164c | ||
|
|
ea9cfc127c | ||
|
|
0afb1a8188 | ||
|
|
f154dbda40 | ||
|
|
c3013d2e9f | ||
|
|
3272564eac | ||
|
|
a0f4632461 | ||
|
|
8ddf837d49 | ||
|
|
9822953d31 | ||
|
|
c6061cce41 | ||
|
|
a9602682c5 | ||
|
|
b7e5213afc | ||
|
|
9b70d9aa68 | ||
|
|
d9bfac32e3 | ||
|
|
9e815afc02 | ||
|
|
47a38daee2 | ||
|
|
cde79501e3 | ||
|
|
51ce3e5a83 | ||
|
|
d6605193a1 | ||
|
|
69646f4258 | ||
|
|
e74daf2d19 | ||
|
|
af3316707f | ||
|
|
6e367dab9a | ||
|
|
38c918ed5c | ||
|
|
9ab3ec080f | ||
|
|
42a483ad27 | ||
|
|
c06007175f | ||
|
|
aaca9011ae | ||
|
|
33d1e87163 | ||
|
|
71b1b69339 | ||
|
|
ceb64b3b1b | ||
|
|
9da1251dbc | ||
|
|
c1d7d60ca2 | ||
|
|
8a33118e36 | ||
|
|
4838bd7834 | ||
|
|
5e930bf940 | ||
|
|
2983701c75 | ||
|
|
0732da1b4a | ||
|
|
4e0e615406 | ||
|
|
c9a455ea49 | ||
|
|
00a1f4395b | ||
|
|
6c9d40ec33 | ||
|
|
50c7eb58a1 | ||
|
|
c6bcf49acc | ||
|
|
5aa1385cfc | ||
|
|
db3cf52add | ||
|
|
12bbbef688 | ||
|
|
48f2807473 | ||
|
|
504407c5df | ||
|
|
4d23b9e031 | ||
|
|
dc5574cbde | ||
|
|
636dd38164 | ||
|
|
d50298ed96 | ||
|
|
2a5d40617a | ||
|
|
16011cacef | ||
|
|
4639c68a7b | ||
|
|
44efaea6d5 | ||
|
|
bdd626f57a | ||
|
|
477661d0e4 | ||
|
|
8028c57b42 | ||
|
|
0f5cb7995f | ||
|
|
e58f8a79ee | ||
|
|
6b7c66aa04 | ||
|
|
49096c2359 | ||
|
|
65648756b5 | ||
|
|
f6fb877de9 | ||
|
|
539078f281 | ||
|
|
86c2ea1cb8 | ||
|
|
95977291f7 | ||
|
|
bd526f97a5 | ||
|
|
6d83eaaf4b | ||
|
|
a46e459595 | ||
|
|
2132fdfa28 | ||
|
|
60821c8ab0 | ||
|
|
cf2103d6e9 | ||
|
|
1d06f67672 | ||
|
|
637cfdd9a0 | ||
|
|
62e6957f68 | ||
|
|
9dfc4eb2ff | ||
|
|
898adbce5c | ||
|
|
a25b15bc2a | ||
|
|
d11d222da2 | ||
|
|
9910507bc4 | ||
|
|
358f4eebae | ||
|
|
9a7276dffc | ||
|
|
b7f554f1dc | ||
|
|
bb90a36701 | ||
|
|
ad6fb20486 | ||
|
|
b3fb7497c2 | ||
|
|
103b38650f | ||
|
|
2c383b51c1 | ||
|
|
2e3d757f46 | ||
|
|
38507974d6 | ||
|
|
5dcac23aea | ||
|
|
384ba8da64 | ||
|
|
13c152717f | ||
|
|
eb6660f534 | ||
|
|
d45694dcb0 | ||
|
|
6ff2d69842 | ||
|
|
3395a1d4db | ||
|
|
0490189531 | ||
|
|
526f9d442d | ||
|
|
6e55b81c56 | ||
|
|
0c0197a0ef | ||
|
|
1f2f1fb82d | ||
|
|
42d4c579c3 | ||
|
|
e389fa75ea | ||
|
|
dc30b86377 | ||
|
|
1edbd30987 | ||
|
|
8fc38ed549 | ||
|
|
6fc648cd25 | ||
|
|
2467350180 | ||
|
|
9711fc895e | ||
|
|
d82e7af9be | ||
|
|
90684bd5b1 | ||
|
|
3ee95cf0e8 | ||
|
|
e510816cf6 | ||
|
|
afa5266c7e | ||
|
|
fbcbdb051b | ||
|
|
478360f317 | ||
|
|
c79613b037 | ||
|
|
134d76dcdd | ||
|
|
7b69730e82 | ||
|
|
8452a7ffa5 | ||
|
|
d1c9f5e309 | ||
|
|
b57e623c11 | ||
|
|
70857e9a5d | ||
|
|
42f283c281 | ||
|
|
3ded946686 | ||
|
|
c5e249b85c | ||
|
|
b5f69e0b9f | ||
|
|
355b307618 | ||
|
|
3d2eb8360a | ||
|
|
9a7426dc25 | ||
|
|
4d547bdd3a | ||
|
|
27599a851f | ||
|
|
7249b25868 | ||
|
|
aa211c6c50 | ||
|
|
da672a3b5c | ||
|
|
4439249617 | ||
|
|
50f4977048 | ||
|
|
f6a29707b6 | ||
|
|
0db6789210 | ||
|
|
bd50115bfe | ||
|
|
b49ca7ba2e | ||
|
|
6d5e494782 | ||
|
|
d0ece2bc93 | ||
|
|
2ce68df27a | ||
|
|
c9bc4aeb90 | ||
|
|
f101c72cbe | ||
|
|
a4cffd29b7 | ||
|
|
1ff2704445 | ||
|
|
8a57fe5466 | ||
|
|
3957a791b7 | ||
|
|
4d8a05568b | ||
|
|
ab8b940151 | ||
|
|
079a173a72 | ||
|
|
e6e94fc59d | ||
|
|
32fec3e8f9 | ||
|
|
150a92d093 | ||
|
|
beb996b847 | ||
|
|
9a42ddd2b8 | ||
|
|
35294891ae | ||
|
|
e26f366405 | ||
|
|
75a020e0ac | ||
|
|
c756b955b3 | ||
|
|
79114ff40a | ||
|
|
6d34314457 | ||
|
|
0dbeb49ee0 | ||
|
|
1f70dfbffd | ||
|
|
06d48514c6 | ||
|
|
692df804cf | ||
|
|
8b31953d40 | ||
|
|
faa2710485 | ||
|
|
015e1348e0 | ||
|
|
e3440f1975 | ||
|
|
62a3666773 | ||
|
|
fdbb97e876 | ||
|
|
b32bee5d84 | ||
|
|
436d5c9ac1 | ||
|
|
d79e6bbffe | ||
|
|
a90306876e | ||
|
|
419ce494e9 | ||
|
|
c3ae476deb | ||
|
|
a04a458156 | ||
|
|
550b2269be | ||
|
|
69369cf365 | ||
|
|
949f8685d2 | ||
|
|
09c3277b42 | ||
|
|
e6a7a84834 | ||
|
|
106cc6189c | ||
|
|
269a93177d | ||
|
|
731edbe2b6 | ||
|
|
acdb290469 | ||
|
|
87b1dab497 | ||
|
|
c933d19a1b | ||
|
|
2a3793485f | ||
|
|
4b674c1daf | ||
|
|
5a1b661f42 | ||
|
|
e6108740c0 | ||
|
|
da64fae690 | ||
|
|
43b4a3ae6a | ||
|
|
d362be5cd9 | ||
|
|
ae01a48fca | ||
|
|
d1292833e9 | ||
|
|
8782d06ed6 | ||
|
|
de072c6ef5 | ||
|
|
69ea0b4ebf | ||
|
|
50b9c7051e | ||
|
|
9bef48216f | ||
|
|
616856552f | ||
|
|
c2d78deeca | ||
|
|
39c4a5411d | ||
|
|
9a4e551c8b | ||
|
|
dee331519c | ||
|
|
4e2990d3aa | ||
|
|
21d04ed3f4 | ||
|
|
5154b95447 | ||
|
|
5a3073128c | ||
|
|
c7da54e82a | ||
|
|
3173b66d00 | ||
|
|
3038846f5d | ||
|
|
3859244a79 | ||
|
|
cc223d7cd2 | ||
|
|
f62d9f1411 | ||
|
|
0348b60a34 | ||
|
|
684d1838f9 | ||
|
|
6ece477779 | ||
|
|
e03a40026a | ||
|
|
6eed4a98ce | ||
|
|
1d8e16bc6e | ||
|
|
23b8c9c917 | ||
|
|
769dcce9d7 | ||
|
|
a4f61565c3 | ||
|
|
e44bb8474b | ||
|
|
0a9438dbba | ||
|
|
127d617db5 | ||
|
|
1a6a16e346 | ||
|
|
ec8697bcdc | ||
|
|
fdb2502a19 | ||
|
|
e8e360a902 | ||
|
|
819cebff5d | ||
|
|
c1ad0725d8 | ||
|
|
6243dba068 | ||
|
|
d643921313 | ||
|
|
5298358b72 | ||
|
|
2b3a256647 | ||
|
|
c87394ee25 | ||
|
|
ab5ec0af33 | ||
|
|
dc2cd8e780 | ||
|
|
24ffc3cfb0 | ||
|
|
99e3de56df | ||
|
|
1304f259cc | ||
|
|
ed5c624b08 | ||
|
|
764be844ec | ||
|
|
fb01c94511 | ||
|
|
5686a0713e | ||
|
|
1cd7c21f38 | ||
|
|
a084093d73 | ||
|
|
79ac99c09b | ||
|
|
e8c8328081 | ||
|
|
792f6b246c | ||
|
|
bef9610f6a | ||
|
|
81497c7f2e | ||
|
|
236d552d6a | ||
|
|
57c099d8b8 | ||
|
|
7e5ea179a1 | ||
|
|
536327151d | ||
|
|
e95d2129be | ||
|
|
c27231ce5c | ||
|
|
6251a6d307 | ||
|
|
f3f2990b9e | ||
|
|
23286fe557 | ||
|
|
dca583a77f | ||
|
|
34c4c8d508 | ||
|
|
8c4496a9c9 | ||
|
|
56930338e8 | ||
|
|
2160c1fcc9 | ||
|
|
d7f07e8a80 | ||
|
|
4575a4aae3 | ||
|
|
257fd2c0df | ||
|
|
aa522731a2 | ||
|
|
5247fe6038 | ||
|
|
5cb25c27b0 | ||
|
|
f8f0540487 | ||
|
|
ee01810395 | ||
|
|
79f0c444fd | ||
|
|
7201845894 | ||
|
|
504edf2cf6 | ||
|
|
0146cc0eb5 | ||
|
|
00d18917d0 | ||
|
|
ae49aa4a03 | ||
|
|
98bc0ae7ee | ||
|
|
edb56500c7 | ||
|
|
450aa33775 | ||
|
|
a0b2810640 | ||
|
|
a42ed950ca | ||
|
|
c720803413 | ||
|
|
b98c1d0472 | ||
|
|
d5811607eb | ||
|
|
3f7cce6d8c | ||
|
|
1aac7ac9d0 | ||
|
|
ccd15fc12e | ||
|
|
0af3548b55 | ||
|
|
4dc38d39e9 | ||
|
|
c9bca78a7a | ||
|
|
5a08522b98 | ||
|
|
deebde66f9 | ||
|
|
632bbf948d | ||
|
|
77d5e0c1ef | ||
|
|
8959c98251 | ||
|
|
1d6e5e6e70 | ||
|
|
7d0a93858d | ||
|
|
d59689b170 | ||
|
|
d77159a19e | ||
|
|
370e9522b4 | ||
|
|
4ef8de69ef | ||
|
|
3309005325 | ||
|
|
441857c6e7 | ||
|
|
0a9df1e37d | ||
|
|
7b26048d9e | ||
|
|
45f5f2ba1a | ||
|
|
d9215dd4ce | ||
|
|
0bdc05bf24 | ||
|
|
83c3f71980 | ||
|
|
44ea7ab093 | ||
|
|
bfcce8aa27 | ||
|
|
ffb53405fb | ||
|
|
6e327184bd | ||
|
|
da58ac7c20 | ||
|
|
29decbdd4d | ||
|
|
390e7f5719 | ||
|
|
5e320291b4 | ||
|
|
9856e5df3b | ||
|
|
ac02ab9fde | ||
|
|
7c76d0e34a | ||
|
|
f98454e5dd | ||
|
|
ddec3c0e78 | ||
|
|
ba96cdb7dc | ||
|
|
ec10fd3044 | ||
|
|
292a240e1b | ||
|
|
5317211b0b | ||
|
|
0bf83b7183 | ||
|
|
0e3ab7c128 | ||
|
|
e5d1e7b4da | ||
|
|
81ad355355 | ||
|
|
3a1d6d2ce1 | ||
|
|
c6dc7d5b79 | ||
|
|
af108764c7 | ||
|
|
4321df13f2 | ||
|
|
64f7974252 | ||
|
|
605cd9bec9 | ||
|
|
54449d044d | ||
|
|
ad54d38678 | ||
|
|
bb19142389 | ||
|
|
a9f601612f | ||
|
|
b10c946564 | ||
|
|
abab90f563 | ||
|
|
b30484d3a9 | ||
|
|
8da17ffe37 | ||
|
|
8330507efd | ||
|
|
eec12b399a | ||
|
|
4b9da4dd0e | ||
|
|
a45afddb75 | ||
|
|
0fc172fcaf | ||
|
|
7d326f6bc5 | ||
|
|
291ee2dafc | ||
|
|
bd80e68698 | ||
|
|
796d2636e6 | ||
|
|
aa030f9fd5 | ||
|
|
a0b1f4fe0b | ||
|
|
164cc43440 | ||
|
|
9e8bd433df | ||
|
|
ed5fb4a720 | ||
|
|
f80601da16 | ||
|
|
69e32ad9ce | ||
|
|
74825e4df7 | ||
|
|
d008d217f9 | ||
|
|
641e1d6587 | ||
|
|
d1371c5dd0 | ||
|
|
24b3d66767 | ||
|
|
901cdb22e3 | ||
|
|
cf628d9287 | ||
|
|
3c8acf3687 | ||
|
|
b4276835d8 | ||
|
|
cec61d010b | ||
|
|
cb4579fe28 | ||
|
|
8b5473c170 | ||
|
|
4feb769378 | ||
|
|
fd9e031f0d | ||
|
|
0ee2f8a64a | ||
|
|
477b09db3e | ||
|
|
911cdd809a | ||
|
|
7f369c3292 | ||
|
|
eedbdedef9 | ||
|
|
0b25176893 | ||
|
|
52c76d737a | ||
|
|
4cb6be453a | ||
|
|
18acda7888 | ||
|
|
449d2752f2 | ||
|
|
bc527f6b51 | ||
|
|
a19e55a902 | ||
|
|
9187759460 | ||
|
|
04dd52e4dc | ||
|
|
90caedb552 | ||
|
|
87ae9324ac | ||
|
|
26155c8a00 | ||
|
|
81366b5bfb | ||
|
|
c436997840 | ||
|
|
b180fb376c | ||
|
|
ab70e854f8 | ||
|
|
a31faaae61 | ||
|
|
1e3e5a6619 | ||
|
|
ac35f41e8d | ||
|
|
554ee92b39 | ||
|
|
02dc1b266c | ||
|
|
81ba491e53 | ||
|
|
09d544f6ad | ||
|
|
a1226d75ff | ||
|
|
2dbd2c07e4 | ||
|
|
f4c792d014 | ||
|
|
babe2b68fb | ||
|
|
9af5072115 | ||
|
|
96371b6d75 | ||
|
|
3d8db573d9 | ||
|
|
f5b3d00b47 | ||
|
|
471d457576 | ||
|
|
03a02b8d6c | ||
|
|
93b8dc2362 | ||
|
|
815b9d7707 | ||
|
|
1a609f0caf | ||
|
|
2923ae8b03 | ||
|
|
0e2dedaf4e | ||
|
|
96b32a814c | ||
|
|
c621615112 | ||
|
|
1688ebdd40 | ||
|
|
01cd6e7a06 | ||
|
|
43f8a7ef00 | ||
|
|
af8d4e1bc5 | ||
|
|
00964b98b9 | ||
|
|
c0c5ebb271 | ||
|
|
ac002b3c3c | ||
|
|
4ed989587b | ||
|
|
cfd4eace42 | ||
|
|
723625c065 | ||
|
|
a6637fbce9 | ||
|
|
cbc177708e | ||
|
|
54cbe5f749 | ||
|
|
646f572b77 | ||
|
|
d57df5a4a1 | ||
|
|
c4147aed3f | ||
|
|
4604985b2e | ||
|
|
842830d709 | ||
|
|
53954494a9 | ||
|
|
e32cf5c418 | ||
|
|
f8ab48adac | ||
|
|
68dbef48da | ||
|
|
b48dd6a11c | ||
|
|
05e986816e | ||
|
|
72b1c01836 | ||
|
|
8f200595ba | ||
|
|
aea042cc83 | ||
|
|
87a337a536 | ||
|
|
9e9d0c3435 | ||
|
|
2fcb785d3e | ||
|
|
4f6d24026d | ||
|
|
7d212b17f8 | ||
|
|
e56adafc1f | ||
|
|
ec3a4cea6a | ||
|
|
da98beac54 | ||
|
|
e1a2cc7f36 | ||
|
|
287345c778 | ||
|
|
12f95429bf | ||
|
|
a5e6e957cf | ||
|
|
5b507cc562 | ||
|
|
e96f9c06f0 | ||
|
|
79f62cc1aa | ||
|
|
ca283c74c9 | ||
|
|
446944c677 | ||
|
|
75609f784c | ||
|
|
a8ff6899d4 | ||
|
|
1941a46825 | ||
|
|
e39c76bfe1 | ||
|
|
1a2ab11c90 | ||
|
|
c832533f5f | ||
|
|
e73a0e6cc6 | ||
|
|
d1207e9d8f | ||
|
|
b7357d5750 | ||
|
|
f106ea0029 | ||
|
|
286fdaa53c | ||
|
|
204e3808d2 | ||
|
|
e81afed66d | ||
|
|
cac50608d6 | ||
|
|
340014a9d3 | ||
|
|
c1cccfc082 | ||
|
|
9c21c66b97 | ||
|
|
5a7b56b042 | ||
|
|
dbb8617214 | ||
|
|
623ea9b0f1 | ||
|
|
89105e7e57 | ||
|
|
24d06c4725 | ||
|
|
7e2cbf528e | ||
|
|
af0ad4454e | ||
|
|
0af06a3136 | ||
|
|
2b4ad2cb09 | ||
|
|
cf5224140b | ||
|
|
aa00b19c92 | ||
|
|
e38127323f | ||
|
|
7a0058fbdb | ||
|
|
8a7de89b97 | ||
|
|
2d14a0e90d | ||
|
|
18d70e6e57 | ||
|
|
03ee12d13e | ||
|
|
cae2f1f537 | ||
|
|
0580a2fb3e | ||
|
|
941851b3eb | ||
|
|
1fa5bf0140 | ||
|
|
19550bd444 | ||
|
|
6f0524d87f | ||
|
|
6c6555c13c | ||
|
|
e794260d89 | ||
|
|
f14eb32758 | ||
|
|
111baba29c | ||
|
|
c7d93c7579 | ||
|
|
76783e2a90 | ||
|
|
2a08bfbcc6 | ||
|
|
2ad62cedc3 | ||
|
|
fde3137b90 | ||
|
|
d027be05a6 | ||
|
|
6609138959 | ||
|
|
23b0487e9b | ||
|
|
367868613f | ||
|
|
78d45a17c8 | ||
|
|
3a5e6f2551 | ||
|
|
326215e1f1 | ||
|
|
85c24c0b47 | ||
|
|
8de9ba6df6 | ||
|
|
019b31d084 | ||
|
|
96e19f1cc4 | ||
|
|
be484ee8a4 | ||
|
|
b3fcc080d5 | ||
|
|
8759e30f04 | ||
|
|
6e29611788 | ||
|
|
6770a8c64a | ||
|
|
e63f527e76 | ||
|
|
0ab3d7a0be | ||
|
|
d79dc056bc | ||
|
|
02710ef574 | ||
|
|
cfb6e847a0 | ||
|
|
91e3421525 | ||
|
|
175fae722a | ||
|
|
237f74a01f | ||
|
|
a96b6e2c96 | ||
|
|
9ec59cbc6c | ||
|
|
636273b6cb | ||
|
|
99d4537075 | ||
|
|
cb13d7a0a8 | ||
|
|
6d96f30ed3 | ||
|
|
0755857a0c | ||
|
|
c25c31e018 | ||
|
|
a59dc56fa6 | ||
|
|
0a6eb8afca | ||
|
|
cc00fa8874 | ||
|
|
4808f30538 | ||
|
|
c278043511 | ||
|
|
5f28f89c9c | ||
|
|
55a7f92297 | ||
|
|
2dd108e9c9 | ||
|
|
9585818a90 | ||
|
|
8785e9007c | ||
|
|
d507ba68a7 | ||
|
|
d4f5ebefe6 | ||
|
|
649d7c0d9e | ||
|
|
3949f0bd50 | ||
|
|
493af7f84c | ||
|
|
e736d04e7f | ||
|
|
f316c8470c | ||
|
|
61effac72a | ||
|
|
dd3913fada | ||
|
|
913bd4c832 | ||
|
|
496d796833 | ||
|
|
1abe658ef4 | ||
|
|
d2cebc62d1 | ||
|
|
b333ce2628 | ||
|
|
5ed11aa1f3 | ||
|
|
6f5c850d60 | ||
|
|
aebad6fd21 | ||
|
|
2616911f7a | ||
|
|
00358545a9 | ||
|
|
67b3fbca89 | ||
|
|
4e5a0946c7 | ||
|
|
24bf2c29e4 | ||
|
|
98c51dd660 | ||
|
|
8d83518f9a | ||
|
|
f2d41b7812 | ||
|
|
fcf0af15de | ||
|
|
d87b3ead76 | ||
|
|
fdf5f838f4 | ||
|
|
e9d88e965e | ||
|
|
277f93653e | ||
|
|
7b55ee9d36 | ||
|
|
4ee201c56e | ||
|
|
4a3771ff7f | ||
|
|
cc1e8ecef6 | ||
|
|
2fd3029040 | ||
|
|
77a4946069 | ||
|
|
8b79776b5e | ||
|
|
9714a91392 | ||
|
|
7574f91f31 | ||
|
|
18b77a4de6 | ||
|
|
6f83977f47 | ||
|
|
fe618631f1 | ||
|
|
72baff1c88 | ||
|
|
e7ef374899 | ||
|
|
68f448ee73 | ||
|
|
84212b8e8b | ||
|
|
d673865881 | ||
|
|
2e7ad1a527 | ||
|
|
a4fcc32799 | ||
|
|
e1acfffaf8 | ||
|
|
075b818a8e | ||
|
|
6530c99cfa | ||
|
|
2108044bdb | ||
|
|
c2c3a04628 | ||
|
|
2ad942323c | ||
|
|
a2e5cb82fc | ||
|
|
3142d5ca00 | ||
|
|
93d9dafacc | ||
|
|
02c7b92095 | ||
|
|
aed0b1ee54 | ||
|
|
4588fc2232 | ||
|
|
f7a38ec72a | ||
|
|
4556433f3b | ||
|
|
253d049ac9 | ||
|
|
9b779657fb | ||
|
|
e1e055a837 | ||
|
|
53c453567f | ||
|
|
132137081a | ||
|
|
341592119f | ||
|
|
bb9e92a5d9 | ||
|
|
0b0f677432 | ||
|
|
316abe21f9 | ||
|
|
e9114b3c00 | ||
|
|
df269ecb24 | ||
|
|
0c24ac9ae7 | ||
|
|
716cb28430 |
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,3 @@
|
||||
*
|
||||
!tools/xvfb-init.sh
|
||||
!tools/run-electron.sh
|
||||
!build/install-build-deps.sh
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# These env vars are only necessary for creating Electron releases.
|
||||
# See docs/development/releasing.md
|
||||
|
||||
APPVEYOR_TOKEN=
|
||||
APPVEYOR_CLOUD_TOKEN=
|
||||
CIRCLE_TOKEN=
|
||||
ELECTRON_GITHUB_TOKEN=
|
||||
VSTS_TOKEN=
|
||||
@@ -6,9 +6,11 @@
|
||||
"browser": true
|
||||
},
|
||||
"rules": {
|
||||
"semi": ["error", "always"],
|
||||
"no-var": "error",
|
||||
"no-unused-vars": 0,
|
||||
"no-global-assign": 0,
|
||||
"guard-for-in": 2,
|
||||
"@typescript-eslint/no-unused-vars": ["error", {
|
||||
"vars": "all",
|
||||
"args": "after-used",
|
||||
@@ -16,7 +18,8 @@
|
||||
}],
|
||||
"prefer-const": ["error", {
|
||||
"destructuring": "all"
|
||||
}]
|
||||
}],
|
||||
"node/no-deprecated-api": 0
|
||||
},
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 6,
|
||||
|
||||
1
.gitattributes
vendored
1
.gitattributes
vendored
@@ -1,3 +1,4 @@
|
||||
# `git apply` and friends don't understand CRLF, even on windows. Force those
|
||||
# files to be checked out with LF endings even if core.autocrlf is true.
|
||||
*.patch text eol=lf
|
||||
patches/**/.patches merge=union
|
||||
|
||||
12
.github/CODEOWNERS
vendored
12
.github/CODEOWNERS
vendored
@@ -4,17 +4,19 @@
|
||||
# https://git-scm.com/docs/gitignore
|
||||
|
||||
# Most stuff in here is owned by the Community & Safety WG...
|
||||
/.github/* @electron/wg-community
|
||||
/.github/* @electron/wg-community
|
||||
|
||||
# ...except the Admin WG maintains this file.
|
||||
/.github/CODEOWNERS @electron/wg-admin
|
||||
/.github/CODEOWNERS @electron/wg-admin
|
||||
|
||||
# Upgrades WG
|
||||
/patches/ @electron/wg-upgrades
|
||||
/patches/ @electron/wg-upgrades
|
||||
DEPS @electron/wg-upgrades
|
||||
|
||||
# Docs & Tooling WG
|
||||
/default_app/ @electron/wg-docs-tools
|
||||
/docs/ @electron/wg-docs-tools
|
||||
/docs/ @electron/wg-docs-tools
|
||||
|
||||
# Releases WG
|
||||
/npm/ @electron/wg-releases
|
||||
/npm/ @electron/wg-releases
|
||||
/script/release @electron/wg-releases
|
||||
10
.github/ISSUE_TEMPLATE/Bug_report.md
vendored
10
.github/ISSUE_TEMPLATE/Bug_report.md
vendored
@@ -20,7 +20,7 @@ about: Create a report to help us improve Electron
|
||||
* <!-- (output of `node_modules/.bin/electron --version`) e.g. 4.0.3 -->
|
||||
* **Operating System:**
|
||||
* <!-- (Platform and Version) e.g. macOS 10.13.6 / Windows 10 (1803) / Ubuntu 18.04 x64 -->
|
||||
* **Last Known Working Electron version:**:
|
||||
* **Last Known Working Electron version:**
|
||||
* <!-- (if applicable) e.g. 3.1.0 -->
|
||||
|
||||
### Expected Behavior
|
||||
@@ -31,11 +31,15 @@ about: Create a report to help us improve Electron
|
||||
|
||||
### To Reproduce
|
||||
<!--
|
||||
Your best chance of getting this bug looked at quickly is to provide a REPOSITORY that can be cloned and run.
|
||||
Your best chance of getting this bug looked at quickly is to provide an example.
|
||||
-->
|
||||
|
||||
<!--
|
||||
You can fork electron-quick-start (https://github.com/electron/electron-quick-start) and include a link to the branch with your changes.
|
||||
For bugs that can be encapsulated in a small experiment, you can use Electron Fiddle (https://github.com/electron/fiddle) to publish your example to a GitHub Gist and link it your bug report.
|
||||
-->
|
||||
|
||||
<!--
|
||||
If Fiddle is insufficient to produce an example, please provide an example REPOSITORY that can be cloned and run. You can fork electron-quick-start (https://github.com/electron/electron-quick-start) and include a link to the branch with your changes.
|
||||
-->
|
||||
|
||||
<!--
|
||||
|
||||
10
.github/main.workflow
vendored
Normal file
10
.github/main.workflow
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
workflow "Clerk" {
|
||||
#TODO(codebytere): make this work properly on pull_request
|
||||
on = "repository_dispatch"
|
||||
resolves = "Check release notes"
|
||||
}
|
||||
|
||||
action "Check release notes" {
|
||||
uses = "electron/clerk@master"
|
||||
secrets = [ "GITHUB_TOKEN" ]
|
||||
}
|
||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -37,7 +37,7 @@
|
||||
/vendor/pyyaml
|
||||
node_modules/
|
||||
SHASUMS256.txt
|
||||
**/yarn.lock
|
||||
**/package-lock.json
|
||||
compile_commands.json
|
||||
.envrc
|
||||
|
||||
@@ -62,3 +62,6 @@ spec/.hash
|
||||
|
||||
# If someone runs tsc this is where stuff will end up
|
||||
ts-gen
|
||||
|
||||
# Used to accelerate CI builds
|
||||
.depshash
|
||||
|
||||
@@ -28,6 +28,18 @@ the issue will be closed.
|
||||
* If an issue has been closed and you still feel it's relevant, feel free to
|
||||
ping a maintainer or add a comment!
|
||||
|
||||
### Languages
|
||||
|
||||
We accept issues in *any* language.
|
||||
When an issue is posted in a language besides English, it is acceptable and encouraged to post an English-translated copy as a reply.
|
||||
Anyone may post the translated reply.
|
||||
In most cases, a quick pass through translation software is sufficient.
|
||||
Having the original text _as well as_ the translation can help mitigate translation errors.
|
||||
|
||||
Responses to posted issues may or may not be in the original language.
|
||||
|
||||
**Please note** that using non-English as an attempt to circumvent our [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) will be an immediate, and possibly indefinite, ban from the project.
|
||||
|
||||
## [Pull Requests](https://electronjs.org/docs/development/pull-requests)
|
||||
|
||||
Pull Requests are the way concrete changes are made to the code, documentation,
|
||||
@@ -57,4 +69,4 @@ See [Coding Style](https://electronjs.org/docs/development/coding-style) for inf
|
||||
## Further Reading
|
||||
|
||||
For more in-depth guides on developing Electron, see
|
||||
[/docs/development](/docs/development/README.md)
|
||||
[/docs/development](/docs/development/README.md)
|
||||
|
||||
49
DEPS
49
DEPS
@@ -5,14 +5,17 @@ gclient_gn_args = [
|
||||
'checkout_android_native_support',
|
||||
'checkout_libaom',
|
||||
'checkout_nacl',
|
||||
'checkout_oculus_sdk'
|
||||
'checkout_oculus_sdk',
|
||||
'checkout_openxr'
|
||||
]
|
||||
|
||||
vars = {
|
||||
'chromium_version':
|
||||
'75.0.3740.3',
|
||||
'78.0.3904.130',
|
||||
'node_version':
|
||||
'2dc0f8811b2b295c08d797b8a11b030234c98502',
|
||||
'v12.8.1',
|
||||
'nan_version':
|
||||
'2ee313aaca52e2b478965ac50eb5082520380d1b',
|
||||
|
||||
'boto_version': 'f7574aa6cc2c819430c1f05e9a1a1a666ef8169b',
|
||||
'pyyaml_version': '3.12',
|
||||
@@ -21,9 +24,13 @@ vars = {
|
||||
'boto_git': 'https://github.com/boto',
|
||||
'chromium_git': 'https://chromium.googlesource.com',
|
||||
'electron_git': 'https://github.com/electron',
|
||||
'nodejs_git': 'https://github.com/nodejs',
|
||||
'requests_git': 'https://github.com/kennethreitz',
|
||||
'yaml_git': 'https://github.com/yaml',
|
||||
|
||||
# KEEP IN SYNC WITH utils.js FILE
|
||||
'yarn_version': '1.15.2',
|
||||
|
||||
# To be able to build clean Chromium from sources.
|
||||
'apply_patches': True,
|
||||
|
||||
@@ -33,6 +40,7 @@ vars = {
|
||||
# To allow in-house builds to checkout those manually.
|
||||
'checkout_chromium': True,
|
||||
'checkout_node': True,
|
||||
'checkout_nan': True,
|
||||
|
||||
# It's only needed to parse the native tests configurations.
|
||||
'checkout_pyyaml': False,
|
||||
@@ -40,6 +48,9 @@ vars = {
|
||||
# Python "requests" module is used for releases only.
|
||||
'checkout_requests': False,
|
||||
|
||||
# To allow running hooks without parsing the DEPS tree
|
||||
'process_deps': True,
|
||||
|
||||
# It is always needed for normal Electron builds,
|
||||
# but might be impossible for custom in-house builds.
|
||||
'download_external_binaries': True,
|
||||
@@ -50,6 +61,8 @@ vars = {
|
||||
True,
|
||||
'checkout_oculus_sdk':
|
||||
False,
|
||||
'checkout_openxr':
|
||||
False,
|
||||
'build_with_chromium':
|
||||
True,
|
||||
'checkout_android':
|
||||
@@ -61,35 +74,39 @@ vars = {
|
||||
deps = {
|
||||
'src': {
|
||||
'url': (Var("chromium_git")) + '/chromium/src.git@' + (Var("chromium_version")),
|
||||
'condition': 'checkout_chromium',
|
||||
'condition': 'checkout_chromium and process_deps',
|
||||
},
|
||||
'src/third_party/nan': {
|
||||
'url': (Var("nodejs_git")) + '/nan.git@' + (Var("nan_version")),
|
||||
'condition': 'checkout_nan and process_deps',
|
||||
},
|
||||
'src/third_party/electron_node': {
|
||||
'url': (Var("electron_git")) + '/node.git@' + (Var("node_version")),
|
||||
'condition': 'checkout_node',
|
||||
'url': (Var("nodejs_git")) + '/node.git@' + (Var("node_version")),
|
||||
'condition': 'checkout_node and process_deps',
|
||||
},
|
||||
'src/electron/vendor/pyyaml': {
|
||||
'url': (Var("yaml_git")) + '/pyyaml.git@' + (Var("pyyaml_version")),
|
||||
'condition': 'checkout_pyyaml',
|
||||
'condition': 'checkout_pyyaml and process_deps',
|
||||
},
|
||||
'src/electron/vendor/boto': {
|
||||
'url': Var('boto_git') + '/boto.git' + '@' + Var('boto_version'),
|
||||
'condition': 'checkout_boto',
|
||||
'condition': 'checkout_boto and process_deps',
|
||||
},
|
||||
'src/electron/vendor/requests': {
|
||||
'url': Var('requests_git') + '/requests.git' + '@' + Var('requests_version'),
|
||||
'condition': 'checkout_requests',
|
||||
'condition': 'checkout_requests and process_deps',
|
||||
},
|
||||
}
|
||||
|
||||
hooks = [
|
||||
{
|
||||
'name': 'patch_chromium',
|
||||
'condition': 'checkout_chromium and apply_patches',
|
||||
'condition': '(checkout_chromium and apply_patches) and process_deps',
|
||||
'pattern': 'src/electron',
|
||||
'action': [
|
||||
'python',
|
||||
'src/electron/script/apply_all_patches.py',
|
||||
'src/electron/patches/common/config.json',
|
||||
'src/electron/patches/config.json',
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -97,7 +114,7 @@ hooks = [
|
||||
'pattern': 'src/electron/script/update-external-binaries.py',
|
||||
'condition': 'download_external_binaries',
|
||||
'action': [
|
||||
'python',
|
||||
'python3',
|
||||
'src/electron/script/update-external-binaries.py',
|
||||
],
|
||||
},
|
||||
@@ -107,13 +124,13 @@ hooks = [
|
||||
'action': [
|
||||
'python',
|
||||
'-c',
|
||||
'import os, subprocess; os.chdir(os.path.join("src", "electron")); subprocess.check_call(["python", "script/lib/npm.py", "install"]);',
|
||||
'import os, subprocess; os.chdir(os.path.join("src", "electron")); subprocess.check_call(["python", "script/lib/npx.py", "yarn@' + (Var("yarn_version")) + '", "install", "--frozen-lockfile"]);',
|
||||
],
|
||||
},
|
||||
{
|
||||
'name': 'setup_boto',
|
||||
'pattern': 'src/electron',
|
||||
'condition': 'checkout_boto',
|
||||
'condition': 'checkout_boto and process_deps',
|
||||
'action': [
|
||||
'python',
|
||||
'-c',
|
||||
@@ -123,7 +140,7 @@ hooks = [
|
||||
{
|
||||
'name': 'setup_requests',
|
||||
'pattern': 'src/electron',
|
||||
'condition': 'checkout_requests',
|
||||
'condition': 'checkout_requests and process_deps',
|
||||
'action': [
|
||||
'python',
|
||||
'-c',
|
||||
@@ -135,3 +152,5 @@ hooks = [
|
||||
recursedeps = [
|
||||
'src',
|
||||
]
|
||||
|
||||
# Touch DEPS to bust cache
|
||||
|
||||
@@ -10,18 +10,21 @@ RUN chmod a+rwx /tmp
|
||||
# Install Linux packages
|
||||
ADD build/install-build-deps.sh /setup/install-build-deps.sh
|
||||
RUN echo ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true | debconf-set-selections
|
||||
RUN dpkg --add-architecture i386
|
||||
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
|
||||
curl \
|
||||
libnotify-bin \
|
||||
locales \
|
||||
lsb-release \
|
||||
nano \
|
||||
python-dbusmock \
|
||||
python-dbus \
|
||||
python-pip \
|
||||
python-setuptools \
|
||||
sudo \
|
||||
vim-nox \
|
||||
wget \
|
||||
g++-multilib \
|
||||
libgl1:i386 \
|
||||
&& /setup/install-build-deps.sh --syms --no-prompt --no-chromeos-fonts --lib32 --arm \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
@@ -33,6 +36,9 @@ RUN curl -sL https://deb.nodesource.com/setup_10.x | bash - \
|
||||
# crcmod is required by gsutil, which is used for filling the gclient git cache
|
||||
RUN pip install -U crcmod
|
||||
|
||||
# dbusmock is needed for Electron tests
|
||||
RUN pip install python-dbusmock
|
||||
|
||||
RUN mkdir /tmp/workspace
|
||||
RUN chown builduser:builduser /tmp/workspace
|
||||
|
||||
|
||||
@@ -19,8 +19,6 @@ RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
|
||||
libcap-dev \
|
||||
libcups2-dev \
|
||||
libdbus-1-dev \
|
||||
libgconf-2-4 \
|
||||
libgconf2-dev \
|
||||
libgnome-keyring-dev \
|
||||
libgtk2.0-0 \
|
||||
libgtk2.0-dev \
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM arm64v8/ubuntu:16.04
|
||||
FROM arm64v8/ubuntu:18.04
|
||||
|
||||
RUN groupadd --gid 1000 builduser \
|
||||
&& useradd --uid 1000 --gid builduser --shell /bin/bash --create-home builduser
|
||||
@@ -22,8 +22,6 @@ RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
|
||||
libcap-dev \
|
||||
libcups2-dev \
|
||||
libdbus-1-dev \
|
||||
libgconf-2-4 \
|
||||
libgconf2-dev \
|
||||
libgnome-keyring-dev \
|
||||
libgtk2.0-0 \
|
||||
libgtk2.0-dev \
|
||||
@@ -41,7 +39,6 @@ RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
|
||||
nano \
|
||||
python-setuptools \
|
||||
python-pip \
|
||||
python-dbusmock \
|
||||
sudo \
|
||||
unzip \
|
||||
wget \
|
||||
@@ -56,6 +53,9 @@ RUN curl -sL https://deb.nodesource.com/setup_10.x | bash - \
|
||||
# crcmod is required by gsutil, which is used for filling the gclient git cache
|
||||
RUN pip install -U crcmod
|
||||
|
||||
# dbusmock is needed for Electron tests
|
||||
RUN pip install python-dbusmock
|
||||
|
||||
ADD tools/xvfb-init.sh /etc/init.d/xvfb
|
||||
RUN chmod a+x /etc/init.d/xvfb
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
6.0.0-nightly.20190404
|
||||
7.2.2
|
||||
@@ -2,10 +2,8 @@
|
||||
|
||||
|
||||
[](https://circleci.com/gh/electron/electron/tree/master)
|
||||
[](https://windows-ci.electronjs.org/project/AppVeyor/electron/branch/master)
|
||||
[](https://github.visualstudio.com/electron/_build/latest?definitionId=36)
|
||||
[](https://ci.appveyor.com/project/electron-bot/electron-ljo26/branch/master)
|
||||
[](https://david-dm.org/electron/electron?type=dev)
|
||||
[](https://atom-slack.herokuapp.com/)
|
||||
|
||||
:memo: Available Translations: 🇨🇳 🇹🇼 🇧🇷 🇪🇸 🇰🇷 🇯🇵 🇷🇺 🇫🇷 🇹🇭 🇳🇱 🇹🇷 🇮🇩 🇺🇦 🇨🇿 🇮🇹 🇵🇱.
|
||||
View these docs in other languages at [electron/i18n](https://github.com/electron/i18n/tree/master/content/).
|
||||
@@ -93,6 +91,10 @@ const child = proc.spawn(electron)
|
||||
|
||||
Find documentation translations in [electron/i18n](https://github.com/electron/i18n).
|
||||
|
||||
## Contributing
|
||||
|
||||
If you are interested in reporting/fixing issues and contributing directly to the code base, please see [CONTRIBUTING.md](CONTRIBUTING.md) for more information on what we're looking for and how to get started.
|
||||
|
||||
## Community
|
||||
|
||||
Info on reporting bugs, getting help, finding third-party tools and sample apps,
|
||||
|
||||
51
appveyor.yml
51
appveyor.yml
@@ -23,13 +23,29 @@
|
||||
# https://www.appveyor.com/docs/build-configuration/#secure-variables
|
||||
# https://www.appveyor.com/docs/build-configuration/#custom-environment-variables
|
||||
|
||||
# Uncomment these lines to enable RDP
|
||||
#on_finish:
|
||||
# - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
|
||||
|
||||
version: 1.0.{build}
|
||||
build_cloud: libcc-20
|
||||
image: libcc-20-vs2017-15.7.4
|
||||
image: vs2017-15.9-10.0.18362
|
||||
environment:
|
||||
GIT_CACHE_PATH: C:\Users\electron\libcc_cache
|
||||
DISABLE_CRASH_REPORTER_TESTS: true
|
||||
ELECTRON_OUT_DIR: Default
|
||||
ELECTRON_ENABLE_STACK_DUMPING: 1
|
||||
MOCHA_REPORTER: mocha-multi-reporters
|
||||
MOCHA_MULTI_REPORTERS: mocha-appveyor-reporter, tap
|
||||
notifications:
|
||||
- provider: Webhook
|
||||
url: https://electron-mission-control.herokuapp.com/rest/appveyor-hook
|
||||
method: POST
|
||||
headers:
|
||||
x-mission-control-secret:
|
||||
secure: 90BLVPcqhJPG7d24v0q/RRray6W3wDQ8uVQlQjOHaBWkw1i8FoA1lsjr2C/v1dVok+tS2Pi6KxDctPUkwIb4T27u4RhvmcPzQhVpfwVJAG9oNtq+yKN7vzHfg7k/pojEzVdJpQLzeJGcSrZu7VY39Q==
|
||||
on_build_success: false
|
||||
on_build_failure: true
|
||||
on_build_status_changed: false
|
||||
build_script:
|
||||
- ps: >-
|
||||
if(($env:APPVEYOR_PULL_REQUEST_HEAD_REPO_NAME -split "/")[0] -eq ($env:APPVEYOR_REPO_NAME -split "/")[0]) {
|
||||
@@ -38,13 +54,15 @@ build_script:
|
||||
- echo "Building $env:GN_CONFIG build"
|
||||
- git config --global core.longpaths true
|
||||
- cd ..
|
||||
- md src
|
||||
- mkdir src
|
||||
- ps: Move-Item $env:APPVEYOR_BUILD_FOLDER -Destination src\electron
|
||||
- ps: $env:CHROMIUM_BUILDTOOLS_PATH="$pwd\src\buildtools"
|
||||
- ps: $env:SCCACHE_PATH="$pwd\src\electron\external_binaries\sccache.exe"
|
||||
- ps: >-
|
||||
if ($env:GN_CONFIG -eq 'release') {
|
||||
$env:GCLIENT_EXTRA_ARGS="--custom-var=checkout_boto=True --custom-var=checkout_requests=True"
|
||||
$env:GCLIENT_EXTRA_ARGS="$env:GCLIENT_EXTRA_ARGS --custom-var=checkout_boto=True --custom-var=checkout_requests=True"
|
||||
} else {
|
||||
$env:NINJA_STATUS="[%r processes, %f/%t @ %o/s : %es] "
|
||||
}
|
||||
- >-
|
||||
gclient config
|
||||
@@ -52,15 +70,16 @@ build_script:
|
||||
--unmanaged
|
||||
%GCLIENT_EXTRA_ARGS%
|
||||
"https://github.com/electron/electron"
|
||||
- gclient sync --with_branch_heads --with_tags
|
||||
- gclient sync --with_branch_heads --with_tags --reset
|
||||
- cd src
|
||||
- ps: $env:BUILD_CONFIG_PATH="//electron/build/args/%GN_CONFIG%.gn"
|
||||
- gn gen out/Default "--args=import(\"%BUILD_CONFIG_PATH%\") %GN_EXTRA_ARGS%"
|
||||
- gn check out/Default //electron:electron_lib
|
||||
- gn check out/Default //electron:electron_app
|
||||
- gn check out/Default //electron:manifests
|
||||
- gn check out/Default //electron/atom/common/api:mojo
|
||||
- gn check out/Default //electron/shell/common/api:mojo
|
||||
- ninja -C out/Default electron:electron_app
|
||||
- if "%GN_CONFIG%"=="testing" ( python C:\Users\electron\depot_tools\post_build_ninja_summary.py -C out\Default )
|
||||
- gn gen out/ffmpeg "--args=import(\"//electron/build/args/ffmpeg.gn\") %GN_EXTRA_ARGS%"
|
||||
- ninja -C out/ffmpeg electron:electron_ffmpeg_zip
|
||||
- ninja -C out/Default electron:electron_dist_zip
|
||||
@@ -70,21 +89,27 @@ build_script:
|
||||
- appveyor PushArtifact out/Default/dist.zip
|
||||
- appveyor PushArtifact out/Default/chromedriver.zip
|
||||
- appveyor PushArtifact out/ffmpeg/ffmpeg.zip
|
||||
- 7z a node_headers.zip out\Default\gen\node_headers
|
||||
- appveyor PushArtifact node_headers.zip
|
||||
- appveyor PushArtifact out/Default/mksnapshot.zip
|
||||
- appveyor PushArtifact out/Default/electron.lib
|
||||
- ps: >-
|
||||
if ($env:GN_CONFIG -eq 'release') {
|
||||
ninja -C out/Default third_party/breakpad:dump_syms
|
||||
# Needed for msdia140.dll on 64-bit windows
|
||||
$env:Path += ";$pwd\third_party\llvm-build\Release+Asserts\bin"
|
||||
ninja -C out/Default electron:electron_symbols
|
||||
}
|
||||
- if "%GN_CONFIG%"=="release" ( python electron\script\dump-symbols.py -d %cd%\out\Default\breakpad_symbols -v)
|
||||
- ps: >-
|
||||
if ($env:GN_CONFIG -eq 'release') {
|
||||
python electron\script\zip-symbols.py
|
||||
appveyor PushArtifact out/Default/symbols.zip
|
||||
}
|
||||
- python electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.win.%TARGET_ARCH%.manifest
|
||||
test_script:
|
||||
# Workaround for https://github.com/appveyor/ci/issues/2420
|
||||
- set "PATH=%PATH%;C:\Program Files\Git\mingw64\libexec\git-core"
|
||||
- ps: >-
|
||||
if ((-Not (Test-Path Env:\ELECTRON_RELEASE)) -And ($env:GN_CONFIG -in "testing", "release")) {
|
||||
if ((-Not (Test-Path Env:\TEST_WOA)) -And (-Not (Test-Path Env:\ELECTRON_RELEASE)) -And ($env:GN_CONFIG -in "testing", "release")) {
|
||||
$env:RUN_TESTS="true"
|
||||
}
|
||||
- ps: >-
|
||||
@@ -95,7 +120,7 @@ test_script:
|
||||
echo "Skipping tests for $env:GN_CONFIG build"
|
||||
}
|
||||
- cd electron
|
||||
- if "%RUN_TESTS%"=="true" ( echo Running test suite & npm run test -- --ci --enable-logging)
|
||||
- if "%RUN_TESTS%"=="true" ( echo Running test suite & node script/yarn test -- --ci --enable-logging)
|
||||
- cd ..
|
||||
- if "%RUN_TESTS%"=="true" ( echo Verifying non proprietary ffmpeg & python electron\script\verify-ffmpeg.py --build-dir out\Default --source-root %cd% --ffmpeg-path out\ffmpeg )
|
||||
- echo "About to verify mksnapshot"
|
||||
@@ -107,9 +132,11 @@ deploy_script:
|
||||
if (Test-Path Env:\ELECTRON_RELEASE) {
|
||||
if (Test-Path Env:\UPLOAD_TO_S3) {
|
||||
Write-Output "Uploading Electron release distribution to s3"
|
||||
& python script\upload.py --upload_to_s3
|
||||
& python script\release\uploaders\upload.py --upload_to_s3
|
||||
} else {
|
||||
Write-Output "Uploading Electron release distribution to github releases"
|
||||
& python script\upload.py
|
||||
& python script\release\uploaders\upload.py
|
||||
}
|
||||
} elseif (Test-Path Env:\TEST_WOA) {
|
||||
node script/release/ci-release-build.js --job=electron-woa-testing --ci=VSTS --armTest --appveyorJobId=$env:APPVEYOR_JOB_ID $env:APPVEYOR_REPO_BRANCH
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright (c) 2019 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/app/manifests.h"
|
||||
|
||||
#include "base/no_destructor.h"
|
||||
#include "electron/atom/common/api/api.mojom.h"
|
||||
#include "printing/buildflags/buildflags.h"
|
||||
#include "services/proxy_resolver/public/cpp/manifest.h"
|
||||
#include "services/service_manager/public/cpp/manifest_builder.h"
|
||||
|
||||
#if BUILDFLAG(ENABLE_PRINTING)
|
||||
#include "components/services/pdf_compositor/public/cpp/manifest.h"
|
||||
#endif
|
||||
|
||||
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
|
||||
#include "chrome/services/printing/public/cpp/manifest.h"
|
||||
#endif
|
||||
|
||||
const service_manager::Manifest& GetElectronContentBrowserOverlayManifest() {
|
||||
static base::NoDestructor<service_manager::Manifest> manifest{
|
||||
service_manager::ManifestBuilder()
|
||||
.WithDisplayName("Electron (browser process)")
|
||||
.RequireCapability("device", "device:geolocation_control")
|
||||
.RequireCapability("proxy_resolver", "factory")
|
||||
.RequireCapability("chrome_printing", "converter")
|
||||
.RequireCapability("pdf_compositor", "compositor")
|
||||
.ExposeInterfaceFilterCapability_Deprecated(
|
||||
"navigation:frame", "renderer",
|
||||
service_manager::Manifest::InterfaceList<
|
||||
atom::mojom::ElectronBrowser>())
|
||||
.Build()};
|
||||
return *manifest;
|
||||
}
|
||||
|
||||
const std::vector<service_manager::Manifest>&
|
||||
GetElectronPackagedServicesOverlayManifest() {
|
||||
static base::NoDestructor<std::vector<service_manager::Manifest>> manifests{{
|
||||
proxy_resolver::GetManifest(),
|
||||
#if BUILDFLAG(ENABLE_PRINTING)
|
||||
printing::GetPdfCompositorManifest(),
|
||||
#endif
|
||||
#if BUILDFLAG(ENABLE_PRINT_PREVIEW)
|
||||
GetChromePrintingManifest(),
|
||||
#endif
|
||||
}};
|
||||
return *manifests;
|
||||
}
|
||||
@@ -1,407 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/api/atom_api_cookies.h"
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "atom/browser/cookie_change_notifier.h"
|
||||
#include "atom/common/native_mate_converters/callback.h"
|
||||
#include "atom/common/native_mate_converters/gurl_converter.h"
|
||||
#include "atom/common/native_mate_converters/value_converter.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "base/time/time.h"
|
||||
#include "base/values.h"
|
||||
#include "content/public/browser/browser_context.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
#include "native_mate/object_template_builder.h"
|
||||
#include "net/cookies/canonical_cookie.h"
|
||||
#include "net/cookies/cookie_store.h"
|
||||
#include "net/cookies/cookie_util.h"
|
||||
#include "net/url_request/url_request_context.h"
|
||||
#include "net/url_request/url_request_context_getter.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace mate {
|
||||
|
||||
template <>
|
||||
struct Converter<atom::api::Cookies::Error> {
|
||||
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
|
||||
atom::api::Cookies::Error val) {
|
||||
if (val == atom::api::Cookies::SUCCESS)
|
||||
return v8::Null(isolate);
|
||||
else
|
||||
return v8::Exception::Error(StringToV8(isolate, "Setting cookie failed"));
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct Converter<net::CanonicalCookie> {
|
||||
static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
|
||||
const net::CanonicalCookie& val) {
|
||||
mate::Dictionary dict(isolate, v8::Object::New(isolate));
|
||||
dict.Set("name", val.Name());
|
||||
dict.Set("value", val.Value());
|
||||
dict.Set("domain", val.Domain());
|
||||
dict.Set("hostOnly", net::cookie_util::DomainIsHostOnly(val.Domain()));
|
||||
dict.Set("path", val.Path());
|
||||
dict.Set("secure", val.IsSecure());
|
||||
dict.Set("httpOnly", val.IsHttpOnly());
|
||||
dict.Set("session", !val.IsPersistent());
|
||||
if (val.IsPersistent())
|
||||
dict.Set("expirationDate", val.ExpiryDate().ToDoubleT());
|
||||
return dict.GetHandle();
|
||||
}
|
||||
};
|
||||
|
||||
template <>
|
||||
struct Converter<network::mojom::CookieChangeCause> {
|
||||
static v8::Local<v8::Value> ToV8(
|
||||
v8::Isolate* isolate,
|
||||
const network::mojom::CookieChangeCause& val) {
|
||||
switch (val) {
|
||||
case network::mojom::CookieChangeCause::INSERTED:
|
||||
case network::mojom::CookieChangeCause::EXPLICIT:
|
||||
return mate::StringToV8(isolate, "explicit");
|
||||
case network::mojom::CookieChangeCause::OVERWRITE:
|
||||
return mate::StringToV8(isolate, "overwrite");
|
||||
case network::mojom::CookieChangeCause::EXPIRED:
|
||||
return mate::StringToV8(isolate, "expired");
|
||||
case network::mojom::CookieChangeCause::EVICTED:
|
||||
return mate::StringToV8(isolate, "evicted");
|
||||
case network::mojom::CookieChangeCause::EXPIRED_OVERWRITE:
|
||||
return mate::StringToV8(isolate, "expired-overwrite");
|
||||
default:
|
||||
return mate::StringToV8(isolate, "unknown");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mate
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace api {
|
||||
|
||||
namespace {
|
||||
|
||||
// Returns whether |domain| matches |filter|.
|
||||
bool MatchesDomain(std::string filter, const std::string& domain) {
|
||||
// Add a leading '.' character to the filter domain if it doesn't exist.
|
||||
if (net::cookie_util::DomainIsHostOnly(filter))
|
||||
filter.insert(0, ".");
|
||||
|
||||
std::string sub_domain(domain);
|
||||
// Strip any leading '.' character from the input cookie domain.
|
||||
if (!net::cookie_util::DomainIsHostOnly(sub_domain))
|
||||
sub_domain = sub_domain.substr(1);
|
||||
|
||||
// Now check whether the domain argument is a subdomain of the filter domain.
|
||||
for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) {
|
||||
if (sub_domain == filter)
|
||||
return true;
|
||||
const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot.
|
||||
sub_domain.erase(0, next_dot);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Returns whether |cookie| matches |filter|.
|
||||
bool MatchesCookie(const base::DictionaryValue* filter,
|
||||
const net::CanonicalCookie& cookie) {
|
||||
std::string str;
|
||||
bool b;
|
||||
if (filter->GetString("name", &str) && str != cookie.Name())
|
||||
return false;
|
||||
if (filter->GetString("path", &str) && str != cookie.Path())
|
||||
return false;
|
||||
if (filter->GetString("domain", &str) && !MatchesDomain(str, cookie.Domain()))
|
||||
return false;
|
||||
if (filter->GetBoolean("secure", &b) && b != cookie.IsSecure())
|
||||
return false;
|
||||
if (filter->GetBoolean("session", &b) && b != !cookie.IsPersistent())
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Helper to returns the CookieStore.
|
||||
inline net::CookieStore* GetCookieStore(
|
||||
scoped_refptr<net::URLRequestContextGetter> getter) {
|
||||
return getter->GetURLRequestContext()->cookie_store();
|
||||
}
|
||||
|
||||
// Remove cookies from |list| not matching |filter|, and pass it to |callback|.
|
||||
void FilterCookies(std::unique_ptr<base::DictionaryValue> filter,
|
||||
util::Promise promise,
|
||||
const net::CookieList& list,
|
||||
const net::CookieStatusList& excluded_list) {
|
||||
net::CookieList result;
|
||||
for (const auto& cookie : list) {
|
||||
if (MatchesCookie(filter.get(), cookie))
|
||||
result.push_back(cookie);
|
||||
}
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::UI},
|
||||
base::BindOnce(util::Promise::ResolvePromise<const net::CookieList&>,
|
||||
std::move(promise), std::move(result)));
|
||||
}
|
||||
|
||||
// Receives cookies matching |filter| in IO thread.
|
||||
void GetCookiesOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
|
||||
std::unique_ptr<base::DictionaryValue> filter,
|
||||
util::Promise promise) {
|
||||
std::string url;
|
||||
filter->GetString("url", &url);
|
||||
|
||||
auto filtered_callback =
|
||||
base::BindOnce(FilterCookies, std::move(filter), std::move(promise));
|
||||
|
||||
// Empty url will match all url cookies.
|
||||
if (url.empty())
|
||||
GetCookieStore(getter)->GetAllCookiesAsync(std::move(filtered_callback));
|
||||
else
|
||||
GetCookieStore(getter)->GetAllCookiesForURLAsync(
|
||||
GURL(url), std::move(filtered_callback));
|
||||
}
|
||||
|
||||
// Removes cookie with |url| and |name| in IO thread.
|
||||
void RemoveCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
|
||||
const GURL& url,
|
||||
const std::string& name,
|
||||
util::Promise promise) {
|
||||
net::CookieDeletionInfo cookie_info;
|
||||
cookie_info.url = url;
|
||||
cookie_info.name = name;
|
||||
GetCookieStore(getter)->DeleteAllMatchingInfoAsync(
|
||||
std::move(cookie_info),
|
||||
base::BindOnce(
|
||||
[](util::Promise promise, uint32_t num_deleted) {
|
||||
util::Promise::ResolveEmptyPromise(std::move(promise));
|
||||
},
|
||||
std::move(promise)));
|
||||
}
|
||||
|
||||
// Callback of SetCookie.
|
||||
void OnSetCookie(util::Promise promise,
|
||||
net::CanonicalCookie::CookieInclusionStatus status) {
|
||||
std::string errmsg;
|
||||
switch (status) {
|
||||
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_HTTP_ONLY:
|
||||
errmsg = "Failed to create httponly cookie";
|
||||
break;
|
||||
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_SECURE_ONLY:
|
||||
errmsg = "Cannot create a secure cookie from an insecure URL";
|
||||
break;
|
||||
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE:
|
||||
errmsg = "Failed to parse cookie";
|
||||
break;
|
||||
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN:
|
||||
errmsg = "Failed to get cookie domain";
|
||||
break;
|
||||
case net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX:
|
||||
errmsg = "Failed because the cookie violated prefix rules.";
|
||||
break;
|
||||
case net::CanonicalCookie::CookieInclusionStatus::
|
||||
EXCLUDE_NONCOOKIEABLE_SCHEME:
|
||||
errmsg = "Cannot set cookie for current scheme";
|
||||
break;
|
||||
case net::CanonicalCookie::CookieInclusionStatus::INCLUDE:
|
||||
errmsg = "";
|
||||
break;
|
||||
default:
|
||||
errmsg = "Setting cookie failed";
|
||||
break;
|
||||
}
|
||||
if (errmsg.empty()) {
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::UI},
|
||||
base::BindOnce(util::Promise::ResolveEmptyPromise, std::move(promise)));
|
||||
} else {
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::UI},
|
||||
base::BindOnce(util::Promise::RejectPromise, std::move(promise),
|
||||
std::move(errmsg)));
|
||||
}
|
||||
}
|
||||
|
||||
// Flushes cookie store in IO thread.
|
||||
void FlushCookieStoreOnIOThread(
|
||||
scoped_refptr<net::URLRequestContextGetter> getter,
|
||||
util::Promise promise) {
|
||||
GetCookieStore(getter)->FlushStore(
|
||||
base::BindOnce(util::Promise::ResolveEmptyPromise, std::move(promise)));
|
||||
}
|
||||
|
||||
// Sets cookie with |details| in IO thread.
|
||||
void SetCookieOnIO(scoped_refptr<net::URLRequestContextGetter> getter,
|
||||
std::unique_ptr<base::DictionaryValue> details,
|
||||
util::Promise promise) {
|
||||
std::string url_string, name, value, domain, path;
|
||||
bool secure = false;
|
||||
bool http_only = false;
|
||||
double creation_date;
|
||||
double expiration_date;
|
||||
double last_access_date;
|
||||
details->GetString("url", &url_string);
|
||||
details->GetString("name", &name);
|
||||
details->GetString("value", &value);
|
||||
details->GetString("domain", &domain);
|
||||
details->GetString("path", &path);
|
||||
details->GetBoolean("secure", &secure);
|
||||
details->GetBoolean("httpOnly", &http_only);
|
||||
|
||||
base::Time creation_time;
|
||||
if (details->GetDouble("creationDate", &creation_date)) {
|
||||
creation_time = (creation_date == 0)
|
||||
? base::Time::UnixEpoch()
|
||||
: base::Time::FromDoubleT(creation_date);
|
||||
}
|
||||
|
||||
base::Time expiration_time;
|
||||
if (details->GetDouble("expirationDate", &expiration_date)) {
|
||||
expiration_time = (expiration_date == 0)
|
||||
? base::Time::UnixEpoch()
|
||||
: base::Time::FromDoubleT(expiration_date);
|
||||
}
|
||||
|
||||
base::Time last_access_time;
|
||||
if (details->GetDouble("lastAccessDate", &last_access_date)) {
|
||||
last_access_time = (last_access_date == 0)
|
||||
? base::Time::UnixEpoch()
|
||||
: base::Time::FromDoubleT(last_access_date);
|
||||
}
|
||||
|
||||
GURL url(url_string);
|
||||
std::unique_ptr<net::CanonicalCookie> canonical_cookie(
|
||||
net::CanonicalCookie::CreateSanitizedCookie(
|
||||
url, name, value, domain, path, creation_time, expiration_time,
|
||||
last_access_time, secure, http_only,
|
||||
net::CookieSameSite::DEFAULT_MODE, net::COOKIE_PRIORITY_DEFAULT));
|
||||
auto completion_callback = base::BindOnce(OnSetCookie, std::move(promise));
|
||||
if (!canonical_cookie || !canonical_cookie->IsCanonical()) {
|
||||
std::move(completion_callback)
|
||||
.Run(net::CanonicalCookie::CookieInclusionStatus::
|
||||
EXCLUDE_FAILURE_TO_STORE);
|
||||
return;
|
||||
}
|
||||
if (url.is_empty()) {
|
||||
std::move(completion_callback)
|
||||
.Run(net::CanonicalCookie::CookieInclusionStatus::
|
||||
EXCLUDE_INVALID_DOMAIN);
|
||||
return;
|
||||
}
|
||||
if (name.empty()) {
|
||||
std::move(completion_callback)
|
||||
.Run(net::CanonicalCookie::CookieInclusionStatus::
|
||||
EXCLUDE_FAILURE_TO_STORE);
|
||||
return;
|
||||
}
|
||||
net::CookieOptions options;
|
||||
if (http_only) {
|
||||
options.set_include_httponly();
|
||||
}
|
||||
GetCookieStore(getter)->SetCanonicalCookieAsync(
|
||||
std::move(canonical_cookie), url.scheme(), options,
|
||||
std::move(completion_callback));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Cookies::Cookies(v8::Isolate* isolate, AtomBrowserContext* browser_context)
|
||||
: browser_context_(browser_context) {
|
||||
Init(isolate);
|
||||
cookie_change_subscription_ =
|
||||
browser_context_->cookie_change_notifier()->RegisterCookieChangeCallback(
|
||||
base::Bind(&Cookies::OnCookieChanged, base::Unretained(this)));
|
||||
}
|
||||
|
||||
Cookies::~Cookies() {}
|
||||
|
||||
v8::Local<v8::Promise> Cookies::Get(const base::DictionaryValue& filter) {
|
||||
util::Promise promise(isolate());
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
|
||||
auto copy = base::DictionaryValue::From(
|
||||
base::Value::ToUniquePtrValue(filter.Clone()));
|
||||
auto* getter = browser_context_->GetRequestContext();
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(GetCookiesOnIO, base::RetainedRef(getter), std::move(copy),
|
||||
std::move(promise)));
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> Cookies::Remove(const GURL& url,
|
||||
const std::string& name) {
|
||||
util::Promise promise(isolate());
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
|
||||
auto* getter = browser_context_->GetRequestContext();
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(RemoveCookieOnIO, base::RetainedRef(getter), url, name,
|
||||
std::move(promise)));
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> Cookies::Set(const base::DictionaryValue& details) {
|
||||
util::Promise promise(isolate());
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
|
||||
auto copy = base::DictionaryValue::From(
|
||||
base::Value::ToUniquePtrValue(details.Clone()));
|
||||
auto* getter = browser_context_->GetRequestContext();
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(SetCookieOnIO, base::RetainedRef(getter), std::move(copy),
|
||||
std::move(promise)));
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> Cookies::FlushStore() {
|
||||
util::Promise promise(isolate());
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
|
||||
auto* getter = browser_context_->GetRequestContext();
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(FlushCookieStoreOnIOThread, base::RetainedRef(getter),
|
||||
std::move(promise)));
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
void Cookies::OnCookieChanged(const CookieDetails* details) {
|
||||
Emit("changed", *(details->cookie), details->cause, details->removed);
|
||||
}
|
||||
|
||||
// static
|
||||
mate::Handle<Cookies> Cookies::Create(v8::Isolate* isolate,
|
||||
AtomBrowserContext* browser_context) {
|
||||
return mate::CreateHandle(isolate, new Cookies(isolate, browser_context));
|
||||
}
|
||||
|
||||
// static
|
||||
void Cookies::BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype) {
|
||||
prototype->SetClassName(mate::StringToV8(isolate, "Cookies"));
|
||||
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
|
||||
.SetMethod("get", &Cookies::Get)
|
||||
.SetMethod("remove", &Cookies::Remove)
|
||||
.SetMethod("set", &Cookies::Set)
|
||||
.SetMethod("flushStore", &Cookies::FlushStore);
|
||||
}
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,132 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "atom/browser/api/atom_api_browser_window.h"
|
||||
#include "atom/browser/native_window.h"
|
||||
#include "atom/browser/ui/certificate_trust.h"
|
||||
#include "atom/browser/ui/file_dialog.h"
|
||||
#include "atom/browser/ui/message_box.h"
|
||||
#include "atom/common/native_mate_converters/callback.h"
|
||||
#include "atom/common/native_mate_converters/file_dialog_converter.h"
|
||||
#include "atom/common/native_mate_converters/file_path_converter.h"
|
||||
#include "atom/common/native_mate_converters/image_converter.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "atom/common/node_includes.h"
|
||||
#include "atom/common/promise_util.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
|
||||
namespace {
|
||||
|
||||
int ShowMessageBoxSync(int type,
|
||||
const std::vector<std::string>& buttons,
|
||||
int default_id,
|
||||
int cancel_id,
|
||||
int options,
|
||||
const std::string& title,
|
||||
const std::string& message,
|
||||
const std::string& detail,
|
||||
const std::string& checkbox_label,
|
||||
bool checkbox_checked,
|
||||
const gfx::ImageSkia& icon,
|
||||
atom::NativeWindow* window) {
|
||||
return atom::ShowMessageBoxSync(
|
||||
window, static_cast<atom::MessageBoxType>(type), buttons, default_id,
|
||||
cancel_id, options, title, message, detail, icon);
|
||||
}
|
||||
|
||||
void ResolvePromiseObject(atom::util::Promise promise,
|
||||
int result,
|
||||
bool checkbox_checked) {
|
||||
mate::Dictionary dict = mate::Dictionary::CreateEmpty(promise.isolate());
|
||||
|
||||
dict.Set("response", result);
|
||||
dict.Set("checkboxChecked", checkbox_checked);
|
||||
|
||||
promise.Resolve(dict.GetHandle());
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> ShowMessageBox(int type,
|
||||
const std::vector<std::string>& buttons,
|
||||
int default_id,
|
||||
int cancel_id,
|
||||
int options,
|
||||
const std::string& title,
|
||||
const std::string& message,
|
||||
const std::string& detail,
|
||||
const std::string& checkbox_label,
|
||||
bool checkbox_checked,
|
||||
const gfx::ImageSkia& icon,
|
||||
atom::NativeWindow* window,
|
||||
mate::Arguments* args) {
|
||||
v8::Isolate* isolate = args->isolate();
|
||||
atom::util::Promise promise(isolate);
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
|
||||
atom::ShowMessageBox(
|
||||
window, static_cast<atom::MessageBoxType>(type), buttons, default_id,
|
||||
cancel_id, options, title, message, detail, checkbox_label,
|
||||
checkbox_checked, icon,
|
||||
base::BindOnce(&ResolvePromiseObject, std::move(promise)));
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
void ShowOpenDialogSync(const file_dialog::DialogSettings& settings,
|
||||
mate::Arguments* args) {
|
||||
std::vector<base::FilePath> paths;
|
||||
if (file_dialog::ShowOpenDialogSync(settings, &paths))
|
||||
args->Return(paths);
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> ShowOpenDialog(
|
||||
const file_dialog::DialogSettings& settings,
|
||||
mate::Arguments* args) {
|
||||
atom::util::Promise promise(args->isolate());
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
file_dialog::ShowOpenDialog(settings, std::move(promise));
|
||||
return handle;
|
||||
}
|
||||
|
||||
void ShowSaveDialogSync(const file_dialog::DialogSettings& settings,
|
||||
mate::Arguments* args) {
|
||||
base::FilePath path;
|
||||
if (file_dialog::ShowSaveDialogSync(settings, &path))
|
||||
args->Return(path);
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> ShowSaveDialog(
|
||||
const file_dialog::DialogSettings& settings,
|
||||
mate::Arguments* args) {
|
||||
atom::util::Promise promise(args->isolate());
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
|
||||
file_dialog::ShowSaveDialog(settings, std::move(promise));
|
||||
return handle;
|
||||
}
|
||||
|
||||
void Initialize(v8::Local<v8::Object> exports,
|
||||
v8::Local<v8::Value> unused,
|
||||
v8::Local<v8::Context> context,
|
||||
void* priv) {
|
||||
mate::Dictionary dict(context->GetIsolate(), exports);
|
||||
dict.SetMethod("showMessageBoxSync", &ShowMessageBoxSync);
|
||||
dict.SetMethod("showMessageBox", &ShowMessageBox);
|
||||
dict.SetMethod("showErrorBox", &atom::ShowErrorBox);
|
||||
dict.SetMethod("showOpenDialogSync", &ShowOpenDialogSync);
|
||||
dict.SetMethod("showOpenDialog", &ShowOpenDialog);
|
||||
dict.SetMethod("showSaveDialogSync", &ShowSaveDialogSync);
|
||||
dict.SetMethod("showSaveDialog", &ShowSaveDialog);
|
||||
#if defined(OS_MACOSX) || defined(OS_WIN)
|
||||
dict.SetMethod("showCertificateTrustDialog",
|
||||
&certificate_trust::ShowCertificateTrust);
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_dialog, Initialize)
|
||||
@@ -1,140 +0,0 @@
|
||||
// Copyright (c) 2018 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/api/atom_api_net_log.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "atom/browser/net/system_network_context_manager.h"
|
||||
#include "atom/common/native_mate_converters/callback.h"
|
||||
#include "atom/common/native_mate_converters/file_path_converter.h"
|
||||
#include "atom/common/node_includes.h"
|
||||
#include "base/command_line.h"
|
||||
#include "chrome/browser/browser_process.h"
|
||||
#include "components/net_log/chrome_net_log.h"
|
||||
#include "content/public/browser/storage_partition.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
#include "native_mate/handle.h"
|
||||
#include "net/url_request/url_request_context_getter.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace api {
|
||||
|
||||
NetLog::NetLog(v8::Isolate* isolate, AtomBrowserContext* browser_context)
|
||||
: browser_context_(browser_context) {
|
||||
Init(isolate);
|
||||
|
||||
net_log_writer_ = g_browser_process->system_network_context_manager()
|
||||
->GetNetExportFileWriter();
|
||||
net_log_writer_->AddObserver(this);
|
||||
}
|
||||
|
||||
NetLog::~NetLog() {
|
||||
net_log_writer_->RemoveObserver(this);
|
||||
}
|
||||
|
||||
void NetLog::StartLogging(mate::Arguments* args) {
|
||||
base::FilePath log_path;
|
||||
if (!args->GetNext(&log_path) || log_path.empty()) {
|
||||
args->ThrowError("The first parameter must be a valid string");
|
||||
return;
|
||||
}
|
||||
|
||||
auto* network_context =
|
||||
content::BrowserContext::GetDefaultStoragePartition(browser_context_)
|
||||
->GetNetworkContext();
|
||||
|
||||
// TODO(deepak1556): Provide more flexibility to this module
|
||||
// by allowing customizations on the capturing options.
|
||||
net_log_writer_->StartNetLog(
|
||||
log_path, net::NetLogCaptureMode::Default(),
|
||||
net_log::NetExportFileWriter::kNoLimit /* file size limit */,
|
||||
base::CommandLine::ForCurrentProcess()->GetCommandLineString(),
|
||||
std::string(), network_context);
|
||||
}
|
||||
|
||||
std::string NetLog::GetLoggingState() const {
|
||||
if (!net_log_state_)
|
||||
return std::string();
|
||||
const base::Value* current_log_state =
|
||||
net_log_state_->FindKeyOfType("state", base::Value::Type::STRING);
|
||||
if (!current_log_state)
|
||||
return std::string();
|
||||
return current_log_state->GetString();
|
||||
}
|
||||
|
||||
bool NetLog::IsCurrentlyLogging() const {
|
||||
const std::string log_state = GetLoggingState();
|
||||
return (log_state == "STARTING_LOG") || (log_state == "LOGGING");
|
||||
}
|
||||
|
||||
std::string NetLog::GetCurrentlyLoggingPath() const {
|
||||
// Net log exporter has a default path which will be used
|
||||
// when no log path is provided, but since we don't allow
|
||||
// net log capture without user provided file path, this
|
||||
// check is completely safe.
|
||||
if (IsCurrentlyLogging()) {
|
||||
const base::Value* current_log_path =
|
||||
net_log_state_->FindKeyOfType("file", base::Value::Type::STRING);
|
||||
if (current_log_path)
|
||||
return current_log_path->GetString();
|
||||
}
|
||||
|
||||
return std::string();
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> NetLog::StopLogging(mate::Arguments* args) {
|
||||
util::Promise promise(isolate());
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
|
||||
if (IsCurrentlyLogging()) {
|
||||
stop_callback_queue_.emplace_back(std::move(promise));
|
||||
net_log_writer_->StopNetLog(nullptr);
|
||||
} else {
|
||||
promise.Resolve(base::FilePath());
|
||||
}
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
void NetLog::OnNewState(const base::DictionaryValue& state) {
|
||||
net_log_state_ = state.CreateDeepCopy();
|
||||
|
||||
if (stop_callback_queue_.empty())
|
||||
return;
|
||||
|
||||
if (GetLoggingState() == "NOT_LOGGING") {
|
||||
for (auto& promise : stop_callback_queue_) {
|
||||
// TODO(zcbenz): Remove the use of CopyablePromise when the
|
||||
// GetFilePathToCompletedLog API accepts OnceCallback.
|
||||
net_log_writer_->GetFilePathToCompletedLog(base::Bind(
|
||||
util::CopyablePromise::ResolveCopyablePromise<const base::FilePath&>,
|
||||
util::CopyablePromise(promise)));
|
||||
}
|
||||
stop_callback_queue_.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// static
|
||||
mate::Handle<NetLog> NetLog::Create(v8::Isolate* isolate,
|
||||
AtomBrowserContext* browser_context) {
|
||||
return mate::CreateHandle(isolate, new NetLog(isolate, browser_context));
|
||||
}
|
||||
|
||||
// static
|
||||
void NetLog::BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype) {
|
||||
prototype->SetClassName(mate::StringToV8(isolate, "NetLog"));
|
||||
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
|
||||
.SetProperty("currentlyLogging", &NetLog::IsCurrentlyLogging)
|
||||
.SetProperty("currentlyLoggingPath", &NetLog::GetCurrentlyLoggingPath)
|
||||
.SetMethod("startLogging", &NetLog::StartLogging)
|
||||
.SetMethod("stopLogging", &NetLog::StopLogging);
|
||||
}
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,60 +0,0 @@
|
||||
// Copyright (c) 2018 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_API_ATOM_API_NET_LOG_H_
|
||||
#define ATOM_BROWSER_API_ATOM_API_NET_LOG_H_
|
||||
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "atom/browser/api/trackable_object.h"
|
||||
#include "atom/common/promise_util.h"
|
||||
#include "base/callback.h"
|
||||
#include "base/values.h"
|
||||
#include "components/net_log/net_export_file_writer.h"
|
||||
#include "native_mate/handle.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class AtomBrowserContext;
|
||||
|
||||
namespace api {
|
||||
|
||||
class NetLog : public mate::TrackableObject<NetLog>,
|
||||
public net_log::NetExportFileWriter::StateObserver {
|
||||
public:
|
||||
static mate::Handle<NetLog> Create(v8::Isolate* isolate,
|
||||
AtomBrowserContext* browser_context);
|
||||
|
||||
static void BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype);
|
||||
|
||||
void StartLogging(mate::Arguments* args);
|
||||
std::string GetLoggingState() const;
|
||||
bool IsCurrentlyLogging() const;
|
||||
std::string GetCurrentlyLoggingPath() const;
|
||||
v8::Local<v8::Promise> StopLogging(mate::Arguments* args);
|
||||
|
||||
protected:
|
||||
explicit NetLog(v8::Isolate* isolate, AtomBrowserContext* browser_context);
|
||||
~NetLog() override;
|
||||
|
||||
// net_log::NetExportFileWriter::StateObserver implementation
|
||||
void OnNewState(const base::DictionaryValue& state) override;
|
||||
|
||||
private:
|
||||
AtomBrowserContext* browser_context_;
|
||||
net_log::NetExportFileWriter* net_log_writer_;
|
||||
std::list<atom::util::Promise> stop_callback_queue_;
|
||||
std::unique_ptr<base::DictionaryValue> net_log_state_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(NetLog);
|
||||
};
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_API_ATOM_API_NET_LOG_H_
|
||||
@@ -1,316 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/api/atom_api_protocol.h"
|
||||
|
||||
#include "atom/browser/atom_browser_client.h"
|
||||
#include "atom/browser/atom_browser_main_parts.h"
|
||||
#include "atom/browser/browser.h"
|
||||
#include "atom/browser/net/url_request_async_asar_job.h"
|
||||
#include "atom/browser/net/url_request_buffer_job.h"
|
||||
#include "atom/browser/net/url_request_fetch_job.h"
|
||||
#include "atom/browser/net/url_request_stream_job.h"
|
||||
#include "atom/browser/net/url_request_string_job.h"
|
||||
#include "atom/common/native_mate_converters/callback.h"
|
||||
#include "atom/common/native_mate_converters/value_converter.h"
|
||||
#include "atom/common/node_includes.h"
|
||||
#include "atom/common/options_switches.h"
|
||||
#include "base/command_line.h"
|
||||
#include "base/strings/string_util.h"
|
||||
#include "content/public/browser/child_process_security_policy.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
#include "url/url_util.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace {
|
||||
|
||||
// List of registered custom standard schemes.
|
||||
std::vector<std::string> g_standard_schemes;
|
||||
|
||||
struct SchemeOptions {
|
||||
bool standard = false;
|
||||
bool secure = false;
|
||||
bool bypassCSP = false;
|
||||
bool allowServiceWorkers = false;
|
||||
bool supportFetchAPI = false;
|
||||
bool corsEnabled = false;
|
||||
};
|
||||
|
||||
struct CustomScheme {
|
||||
std::string scheme;
|
||||
SchemeOptions options;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace mate {
|
||||
|
||||
template <>
|
||||
struct Converter<CustomScheme> {
|
||||
static bool FromV8(v8::Isolate* isolate,
|
||||
v8::Local<v8::Value> val,
|
||||
CustomScheme* out) {
|
||||
mate::Dictionary dict;
|
||||
if (!ConvertFromV8(isolate, val, &dict))
|
||||
return false;
|
||||
if (!dict.Get("scheme", &(out->scheme)))
|
||||
return false;
|
||||
mate::Dictionary opt;
|
||||
// options are optional. Default values specified in SchemeOptions are used
|
||||
if (dict.Get("privileges", &opt)) {
|
||||
opt.Get("standard", &(out->options.standard));
|
||||
opt.Get("supportFetchAPI", &(out->options.supportFetchAPI));
|
||||
opt.Get("secure", &(out->options.secure));
|
||||
opt.Get("bypassCSP", &(out->options.bypassCSP));
|
||||
opt.Get("allowServiceWorkers", &(out->options.allowServiceWorkers));
|
||||
opt.Get("supportFetchAPI", &(out->options.supportFetchAPI));
|
||||
opt.Get("corsEnabled", &(out->options.corsEnabled));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mate
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace api {
|
||||
|
||||
std::vector<std::string> GetStandardSchemes() {
|
||||
return g_standard_schemes;
|
||||
}
|
||||
|
||||
void RegisterSchemesAsPrivileged(v8::Local<v8::Value> val,
|
||||
mate::Arguments* args) {
|
||||
std::vector<CustomScheme> custom_schemes;
|
||||
if (!mate::ConvertFromV8(args->isolate(), val, &custom_schemes)) {
|
||||
args->ThrowError("Argument must be an array of custom schemes.");
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<std::string> secure_schemes, cspbypassing_schemes, fetch_schemes,
|
||||
service_worker_schemes, cors_schemes;
|
||||
for (const auto& custom_scheme : custom_schemes) {
|
||||
// Register scheme to privileged list (https, wss, data, chrome-extension)
|
||||
if (custom_scheme.options.standard) {
|
||||
auto* policy = content::ChildProcessSecurityPolicy::GetInstance();
|
||||
url::AddStandardScheme(custom_scheme.scheme.c_str(),
|
||||
url::SCHEME_WITH_HOST);
|
||||
g_standard_schemes.push_back(custom_scheme.scheme);
|
||||
policy->RegisterWebSafeScheme(custom_scheme.scheme);
|
||||
}
|
||||
if (custom_scheme.options.secure) {
|
||||
secure_schemes.push_back(custom_scheme.scheme);
|
||||
url::AddSecureScheme(custom_scheme.scheme.c_str());
|
||||
}
|
||||
if (custom_scheme.options.bypassCSP) {
|
||||
cspbypassing_schemes.push_back(custom_scheme.scheme);
|
||||
url::AddCSPBypassingScheme(custom_scheme.scheme.c_str());
|
||||
}
|
||||
if (custom_scheme.options.corsEnabled) {
|
||||
cors_schemes.push_back(custom_scheme.scheme);
|
||||
url::AddCorsEnabledScheme(custom_scheme.scheme.c_str());
|
||||
}
|
||||
if (custom_scheme.options.supportFetchAPI) {
|
||||
fetch_schemes.push_back(custom_scheme.scheme);
|
||||
}
|
||||
if (custom_scheme.options.allowServiceWorkers) {
|
||||
service_worker_schemes.push_back(custom_scheme.scheme);
|
||||
}
|
||||
}
|
||||
|
||||
const auto AppendSchemesToCmdLine = [](const char* switch_name,
|
||||
std::vector<std::string> schemes) {
|
||||
// Add the schemes to command line switches, so child processes can also
|
||||
// register them.
|
||||
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
|
||||
switch_name, base::JoinString(schemes, ","));
|
||||
};
|
||||
|
||||
AppendSchemesToCmdLine(atom::switches::kSecureSchemes, secure_schemes);
|
||||
AppendSchemesToCmdLine(atom::switches::kBypassCSPSchemes,
|
||||
cspbypassing_schemes);
|
||||
AppendSchemesToCmdLine(atom::switches::kCORSSchemes, cors_schemes);
|
||||
AppendSchemesToCmdLine(atom::switches::kFetchSchemes, fetch_schemes);
|
||||
AppendSchemesToCmdLine(atom::switches::kServiceWorkerSchemes,
|
||||
service_worker_schemes);
|
||||
AppendSchemesToCmdLine(atom::switches::kStandardSchemes, g_standard_schemes);
|
||||
}
|
||||
|
||||
Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context)
|
||||
: browser_context_(browser_context), weak_factory_(this) {
|
||||
Init(isolate);
|
||||
}
|
||||
|
||||
Protocol::~Protocol() {}
|
||||
void Protocol::UnregisterProtocol(const std::string& scheme,
|
||||
mate::Arguments* args) {
|
||||
CompletionCallback callback;
|
||||
args->GetNext(&callback);
|
||||
auto* getter = static_cast<URLRequestContextGetter*>(
|
||||
browser_context_->GetRequestContext());
|
||||
base::PostTaskWithTraitsAndReplyWithResult(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&Protocol::UnregisterProtocolInIO,
|
||||
base::RetainedRef(getter), scheme),
|
||||
base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
|
||||
}
|
||||
|
||||
// static
|
||||
Protocol::ProtocolError Protocol::UnregisterProtocolInIO(
|
||||
scoped_refptr<URLRequestContextGetter> request_context_getter,
|
||||
const std::string& scheme) {
|
||||
auto* job_factory = request_context_getter->job_factory();
|
||||
if (!job_factory->HasProtocolHandler(scheme))
|
||||
return PROTOCOL_NOT_REGISTERED;
|
||||
job_factory->SetProtocolHandler(scheme, nullptr);
|
||||
return PROTOCOL_OK;
|
||||
}
|
||||
|
||||
bool IsProtocolHandledInIO(
|
||||
scoped_refptr<URLRequestContextGetter> request_context_getter,
|
||||
const std::string& scheme) {
|
||||
bool is_handled =
|
||||
request_context_getter->job_factory()->IsHandledProtocol(scheme);
|
||||
return is_handled;
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> Protocol::IsProtocolHandled(const std::string& scheme) {
|
||||
util::Promise promise(isolate());
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
auto* getter = static_cast<URLRequestContextGetter*>(
|
||||
browser_context_->GetRequestContext());
|
||||
|
||||
base::PostTaskWithTraitsAndReplyWithResult(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&IsProtocolHandledInIO, base::RetainedRef(getter), scheme),
|
||||
base::BindOnce(util::Promise::ResolvePromise<bool>, std::move(promise)));
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
void Protocol::UninterceptProtocol(const std::string& scheme,
|
||||
mate::Arguments* args) {
|
||||
CompletionCallback callback;
|
||||
args->GetNext(&callback);
|
||||
auto* getter = static_cast<URLRequestContextGetter*>(
|
||||
browser_context_->GetRequestContext());
|
||||
base::PostTaskWithTraitsAndReplyWithResult(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&Protocol::UninterceptProtocolInIO,
|
||||
base::RetainedRef(getter), scheme),
|
||||
base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
|
||||
}
|
||||
|
||||
// static
|
||||
Protocol::ProtocolError Protocol::UninterceptProtocolInIO(
|
||||
scoped_refptr<URLRequestContextGetter> request_context_getter,
|
||||
const std::string& scheme) {
|
||||
return request_context_getter->job_factory()->UninterceptProtocol(scheme)
|
||||
? PROTOCOL_OK
|
||||
: PROTOCOL_NOT_INTERCEPTED;
|
||||
}
|
||||
|
||||
void Protocol::OnIOCompleted(const CompletionCallback& callback,
|
||||
ProtocolError error) {
|
||||
// The completion callback is optional.
|
||||
if (callback.is_null())
|
||||
return;
|
||||
|
||||
v8::Locker locker(isolate());
|
||||
v8::HandleScope handle_scope(isolate());
|
||||
|
||||
if (error == PROTOCOL_OK) {
|
||||
callback.Run(v8::Null(isolate()));
|
||||
} else {
|
||||
std::string str = ErrorCodeToString(error);
|
||||
callback.Run(v8::Exception::Error(mate::StringToV8(isolate(), str)));
|
||||
}
|
||||
}
|
||||
|
||||
std::string Protocol::ErrorCodeToString(ProtocolError error) {
|
||||
switch (error) {
|
||||
case PROTOCOL_FAIL:
|
||||
return "Failed to manipulate protocol factory";
|
||||
case PROTOCOL_REGISTERED:
|
||||
return "The scheme has been registered";
|
||||
case PROTOCOL_NOT_REGISTERED:
|
||||
return "The scheme has not been registered";
|
||||
case PROTOCOL_INTERCEPTED:
|
||||
return "The scheme has been intercepted";
|
||||
case PROTOCOL_NOT_INTERCEPTED:
|
||||
return "The scheme has not been intercepted";
|
||||
default:
|
||||
return "Unexpected error";
|
||||
}
|
||||
}
|
||||
|
||||
// static
|
||||
mate::Handle<Protocol> Protocol::Create(v8::Isolate* isolate,
|
||||
AtomBrowserContext* browser_context) {
|
||||
return mate::CreateHandle(isolate, new Protocol(isolate, browser_context));
|
||||
}
|
||||
|
||||
// static
|
||||
void Protocol::BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype) {
|
||||
prototype->SetClassName(mate::StringToV8(isolate, "Protocol"));
|
||||
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
|
||||
.SetMethod("registerStringProtocol",
|
||||
&Protocol::RegisterProtocol<URLRequestStringJob>)
|
||||
.SetMethod("registerBufferProtocol",
|
||||
&Protocol::RegisterProtocol<URLRequestBufferJob>)
|
||||
.SetMethod("registerFileProtocol",
|
||||
&Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
|
||||
.SetMethod("registerHttpProtocol",
|
||||
&Protocol::RegisterProtocol<URLRequestFetchJob>)
|
||||
.SetMethod("registerStreamProtocol",
|
||||
&Protocol::RegisterProtocol<URLRequestStreamJob>)
|
||||
.SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
|
||||
.SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
|
||||
.SetMethod("interceptStringProtocol",
|
||||
&Protocol::InterceptProtocol<URLRequestStringJob>)
|
||||
.SetMethod("interceptBufferProtocol",
|
||||
&Protocol::InterceptProtocol<URLRequestBufferJob>)
|
||||
.SetMethod("interceptFileProtocol",
|
||||
&Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
|
||||
.SetMethod("interceptHttpProtocol",
|
||||
&Protocol::InterceptProtocol<URLRequestFetchJob>)
|
||||
.SetMethod("interceptStreamProtocol",
|
||||
&Protocol::InterceptProtocol<URLRequestStreamJob>)
|
||||
.SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
|
||||
}
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
|
||||
namespace {
|
||||
|
||||
void RegisterSchemesAsPrivileged(v8::Local<v8::Value> val,
|
||||
mate::Arguments* args) {
|
||||
if (atom::Browser::Get()->is_ready()) {
|
||||
args->ThrowError(
|
||||
"protocol.registerSchemesAsPrivileged should be called before "
|
||||
"app is ready");
|
||||
return;
|
||||
}
|
||||
|
||||
atom::api::RegisterSchemesAsPrivileged(val, args);
|
||||
}
|
||||
|
||||
void Initialize(v8::Local<v8::Object> exports,
|
||||
v8::Local<v8::Value> unused,
|
||||
v8::Local<v8::Context> context,
|
||||
void* priv) {
|
||||
v8::Isolate* isolate = context->GetIsolate();
|
||||
mate::Dictionary dict(isolate, exports);
|
||||
dict.SetMethod("registerSchemesAsPrivileged", &RegisterSchemesAsPrivileged);
|
||||
dict.SetMethod("getStandardSchemes", &atom::api::GetStandardSchemes);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_protocol, Initialize)
|
||||
@@ -1,197 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_API_ATOM_API_PROTOCOL_H_
|
||||
#define ATOM_BROWSER_API_ATOM_API_PROTOCOL_H_
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "atom/browser/api/trackable_object.h"
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "atom/browser/net/atom_url_request_job_factory.h"
|
||||
#include "atom/common/promise_util.h"
|
||||
#include "base/callback.h"
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "native_mate/arguments.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
#include "native_mate/handle.h"
|
||||
#include "net/url_request/url_request_context.h"
|
||||
|
||||
namespace base {
|
||||
class DictionaryValue;
|
||||
}
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace api {
|
||||
|
||||
std::vector<std::string> GetStandardSchemes();
|
||||
|
||||
void RegisterSchemesAsPrivileged(v8::Local<v8::Value> val,
|
||||
mate::Arguments* args);
|
||||
|
||||
class Protocol : public mate::TrackableObject<Protocol> {
|
||||
public:
|
||||
using Handler =
|
||||
base::Callback<void(const base::DictionaryValue&, v8::Local<v8::Value>)>;
|
||||
using CompletionCallback = base::Callback<void(v8::Local<v8::Value>)>;
|
||||
|
||||
static mate::Handle<Protocol> Create(v8::Isolate* isolate,
|
||||
AtomBrowserContext* browser_context);
|
||||
|
||||
static void BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype);
|
||||
|
||||
protected:
|
||||
Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context);
|
||||
~Protocol() override;
|
||||
|
||||
private:
|
||||
// Possible errors.
|
||||
enum ProtocolError {
|
||||
PROTOCOL_OK, // no error
|
||||
PROTOCOL_FAIL, // operation failed, should never occur
|
||||
PROTOCOL_REGISTERED,
|
||||
PROTOCOL_NOT_REGISTERED,
|
||||
PROTOCOL_INTERCEPTED,
|
||||
PROTOCOL_NOT_INTERCEPTED,
|
||||
};
|
||||
|
||||
// The protocol handler that will create a protocol handler for certain
|
||||
// request job.
|
||||
template <typename RequestJob>
|
||||
class CustomProtocolHandler
|
||||
: public net::URLRequestJobFactory::ProtocolHandler {
|
||||
public:
|
||||
CustomProtocolHandler(v8::Isolate* isolate,
|
||||
net::URLRequestContextGetter* request_context,
|
||||
const Handler& handler)
|
||||
: isolate_(isolate),
|
||||
request_context_(request_context),
|
||||
handler_(handler) {}
|
||||
~CustomProtocolHandler() override {}
|
||||
|
||||
net::URLRequestJob* MaybeCreateJob(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const override {
|
||||
RequestJob* request_job = new RequestJob(request, network_delegate);
|
||||
request_job->SetHandlerInfo(isolate_, request_context_, handler_);
|
||||
return request_job;
|
||||
}
|
||||
|
||||
private:
|
||||
v8::Isolate* isolate_;
|
||||
net::URLRequestContextGetter* request_context_;
|
||||
Protocol::Handler handler_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(CustomProtocolHandler);
|
||||
};
|
||||
|
||||
// Register the protocol with certain request job.
|
||||
template <typename RequestJob>
|
||||
void RegisterProtocol(const std::string& scheme,
|
||||
const Handler& handler,
|
||||
mate::Arguments* args) {
|
||||
CompletionCallback callback;
|
||||
args->GetNext(&callback);
|
||||
auto* getter = static_cast<URLRequestContextGetter*>(
|
||||
browser_context_->GetRequestContext());
|
||||
base::PostTaskWithTraitsAndReplyWithResult(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&Protocol::RegisterProtocolInIO<RequestJob>,
|
||||
base::RetainedRef(getter), isolate(), scheme, handler),
|
||||
base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
|
||||
}
|
||||
template <typename RequestJob>
|
||||
static ProtocolError RegisterProtocolInIO(
|
||||
scoped_refptr<URLRequestContextGetter> request_context_getter,
|
||||
v8::Isolate* isolate,
|
||||
const std::string& scheme,
|
||||
const Handler& handler) {
|
||||
auto* job_factory = request_context_getter->job_factory();
|
||||
if (job_factory->IsHandledProtocol(scheme))
|
||||
return PROTOCOL_REGISTERED;
|
||||
auto protocol_handler = std::make_unique<CustomProtocolHandler<RequestJob>>(
|
||||
isolate, request_context_getter.get(), handler);
|
||||
if (job_factory->SetProtocolHandler(scheme, std::move(protocol_handler)))
|
||||
return PROTOCOL_OK;
|
||||
else
|
||||
return PROTOCOL_FAIL;
|
||||
}
|
||||
|
||||
// Unregister the protocol handler that handles |scheme|.
|
||||
void UnregisterProtocol(const std::string& scheme, mate::Arguments* args);
|
||||
static ProtocolError UnregisterProtocolInIO(
|
||||
scoped_refptr<URLRequestContextGetter> request_context_getter,
|
||||
const std::string& scheme);
|
||||
|
||||
// Whether the protocol has handler registered.
|
||||
v8::Local<v8::Promise> IsProtocolHandled(const std::string& scheme);
|
||||
|
||||
// Replace the protocol handler with a new one.
|
||||
template <typename RequestJob>
|
||||
void InterceptProtocol(const std::string& scheme,
|
||||
const Handler& handler,
|
||||
mate::Arguments* args) {
|
||||
CompletionCallback callback;
|
||||
args->GetNext(&callback);
|
||||
auto* getter = static_cast<URLRequestContextGetter*>(
|
||||
browser_context_->GetRequestContext());
|
||||
base::PostTaskWithTraitsAndReplyWithResult(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&Protocol::InterceptProtocolInIO<RequestJob>,
|
||||
base::RetainedRef(getter), isolate(), scheme, handler),
|
||||
base::BindOnce(&Protocol::OnIOCompleted, GetWeakPtr(), callback));
|
||||
}
|
||||
template <typename RequestJob>
|
||||
static ProtocolError InterceptProtocolInIO(
|
||||
scoped_refptr<URLRequestContextGetter> request_context_getter,
|
||||
v8::Isolate* isolate,
|
||||
const std::string& scheme,
|
||||
const Handler& handler) {
|
||||
auto* job_factory = request_context_getter->job_factory();
|
||||
if (!job_factory->IsHandledProtocol(scheme))
|
||||
return PROTOCOL_NOT_REGISTERED;
|
||||
// It is possible a protocol is handled but can not be intercepted.
|
||||
if (!job_factory->HasProtocolHandler(scheme))
|
||||
return PROTOCOL_FAIL;
|
||||
auto protocol_handler = std::make_unique<CustomProtocolHandler<RequestJob>>(
|
||||
isolate, request_context_getter.get(), handler);
|
||||
if (!job_factory->InterceptProtocol(scheme, std::move(protocol_handler)))
|
||||
return PROTOCOL_INTERCEPTED;
|
||||
return PROTOCOL_OK;
|
||||
}
|
||||
|
||||
// Restore the |scheme| to its original protocol handler.
|
||||
void UninterceptProtocol(const std::string& scheme, mate::Arguments* args);
|
||||
static ProtocolError UninterceptProtocolInIO(
|
||||
scoped_refptr<URLRequestContextGetter> request_context_getter,
|
||||
const std::string& scheme);
|
||||
|
||||
// Convert error code to JS exception and call the callback.
|
||||
void OnIOCompleted(const CompletionCallback& callback, ProtocolError error);
|
||||
|
||||
// Convert error code to string.
|
||||
std::string ErrorCodeToString(ProtocolError error);
|
||||
|
||||
base::WeakPtr<Protocol> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
|
||||
|
||||
scoped_refptr<AtomBrowserContext> browser_context_;
|
||||
base::WeakPtrFactory<Protocol> weak_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(Protocol);
|
||||
};
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_API_ATOM_API_PROTOCOL_H_
|
||||
@@ -1,90 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/api/atom_api_render_process_preferences.h"
|
||||
|
||||
#include "atom/browser/api/atom_api_web_contents.h"
|
||||
#include "atom/browser/atom_browser_client.h"
|
||||
#include "atom/common/native_mate_converters/value_converter.h"
|
||||
#include "atom/common/node_includes.h"
|
||||
#include "content/public/browser/render_process_host.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
#include "native_mate/object_template_builder.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace api {
|
||||
|
||||
namespace {
|
||||
|
||||
bool IsWebContents(v8::Isolate* isolate, content::RenderProcessHost* process) {
|
||||
content::WebContents* web_contents =
|
||||
static_cast<AtomBrowserClient*>(AtomBrowserClient::Get())
|
||||
->GetWebContentsFromProcessID(process->GetID());
|
||||
if (!web_contents)
|
||||
return false;
|
||||
|
||||
auto api_web_contents = WebContents::FromOrCreate(isolate, web_contents);
|
||||
auto type = api_web_contents->GetType();
|
||||
return type == WebContents::Type::BROWSER_WINDOW ||
|
||||
type == WebContents::Type::WEB_VIEW;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
RenderProcessPreferences::RenderProcessPreferences(
|
||||
v8::Isolate* isolate,
|
||||
const atom::RenderProcessPreferences::Predicate& predicate)
|
||||
: preferences_(predicate) {
|
||||
Init(isolate);
|
||||
}
|
||||
|
||||
RenderProcessPreferences::~RenderProcessPreferences() {}
|
||||
|
||||
int RenderProcessPreferences::AddEntry(const base::DictionaryValue& entry) {
|
||||
return preferences_.AddEntry(entry);
|
||||
}
|
||||
|
||||
void RenderProcessPreferences::RemoveEntry(int id) {
|
||||
preferences_.RemoveEntry(id);
|
||||
}
|
||||
|
||||
// static
|
||||
void RenderProcessPreferences::BuildPrototype(
|
||||
v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype) {
|
||||
prototype->SetClassName(
|
||||
mate::StringToV8(isolate, "RenderProcessPreferences"));
|
||||
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
|
||||
.SetMethod("addEntry", &RenderProcessPreferences::AddEntry)
|
||||
.SetMethod("removeEntry", &RenderProcessPreferences::RemoveEntry);
|
||||
}
|
||||
|
||||
// static
|
||||
mate::Handle<RenderProcessPreferences>
|
||||
RenderProcessPreferences::ForAllWebContents(v8::Isolate* isolate) {
|
||||
return mate::CreateHandle(isolate,
|
||||
new RenderProcessPreferences(
|
||||
isolate, base::Bind(&IsWebContents, isolate)));
|
||||
}
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
|
||||
namespace {
|
||||
|
||||
void Initialize(v8::Local<v8::Object> exports,
|
||||
v8::Local<v8::Value> unused,
|
||||
v8::Local<v8::Context> context,
|
||||
void* priv) {
|
||||
mate::Dictionary dict(context->GetIsolate(), exports);
|
||||
dict.SetMethod("forAllWebContents",
|
||||
&atom::api::RenderProcessPreferences::ForAllWebContents);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_browser_render_process_preferences,
|
||||
Initialize)
|
||||
@@ -1,44 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_API_ATOM_API_RENDER_PROCESS_PREFERENCES_H_
|
||||
#define ATOM_BROWSER_API_ATOM_API_RENDER_PROCESS_PREFERENCES_H_
|
||||
|
||||
#include "atom/browser/render_process_preferences.h"
|
||||
#include "native_mate/handle.h"
|
||||
#include "native_mate/wrappable.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace api {
|
||||
|
||||
class RenderProcessPreferences
|
||||
: public mate::Wrappable<RenderProcessPreferences> {
|
||||
public:
|
||||
static mate::Handle<RenderProcessPreferences> ForAllWebContents(
|
||||
v8::Isolate* isolate);
|
||||
|
||||
static void BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype);
|
||||
|
||||
int AddEntry(const base::DictionaryValue& entry);
|
||||
void RemoveEntry(int id);
|
||||
|
||||
protected:
|
||||
RenderProcessPreferences(
|
||||
v8::Isolate* isolate,
|
||||
const atom::RenderProcessPreferences::Predicate& predicate);
|
||||
~RenderProcessPreferences() override;
|
||||
|
||||
private:
|
||||
atom::RenderProcessPreferences preferences_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(RenderProcessPreferences);
|
||||
};
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_API_ATOM_API_RENDER_PROCESS_PREFERENCES_H_
|
||||
@@ -1,496 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/api/atom_api_url_request.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "atom/browser/api/atom_api_session.h"
|
||||
#include "atom/browser/net/atom_url_request.h"
|
||||
#include "atom/common/api/event_emitter_caller.h"
|
||||
#include "atom/common/native_mate_converters/callback.h"
|
||||
#include "atom/common/native_mate_converters/gurl_converter.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "atom/common/native_mate_converters/string16_converter.h"
|
||||
#include "atom/common/node_includes.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
|
||||
namespace mate {
|
||||
|
||||
template <>
|
||||
struct Converter<scoped_refptr<const net::IOBufferWithSize>> {
|
||||
static v8::Local<v8::Value> ToV8(
|
||||
v8::Isolate* isolate,
|
||||
scoped_refptr<const net::IOBufferWithSize> buffer) {
|
||||
return node::Buffer::Copy(isolate, buffer->data(), buffer->size())
|
||||
.ToLocalChecked();
|
||||
}
|
||||
|
||||
static bool FromV8(v8::Isolate* isolate,
|
||||
v8::Local<v8::Value> val,
|
||||
scoped_refptr<const net::IOBufferWithSize>* out) {
|
||||
auto size = node::Buffer::Length(val);
|
||||
|
||||
if (size == 0) {
|
||||
// Support conversion from empty buffer. A use case is
|
||||
// a GET request without body.
|
||||
// Since zero-sized IOBuffer(s) are not supported, we set the
|
||||
// out pointer to null.
|
||||
*out = nullptr;
|
||||
return true;
|
||||
}
|
||||
auto* data = node::Buffer::Data(val);
|
||||
if (!data) {
|
||||
// This is an error as size is positive but data is null.
|
||||
return false;
|
||||
}
|
||||
|
||||
*out = new net::IOBufferWithSize(size);
|
||||
// We do a deep copy. We could have used Buffer's internal memory
|
||||
// but that is much more complicated to be properly handled.
|
||||
memcpy((*out)->data(), data, size);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mate
|
||||
|
||||
namespace atom {
|
||||
namespace api {
|
||||
|
||||
template <typename Flags>
|
||||
URLRequest::StateBase<Flags>::StateBase(Flags initialState)
|
||||
: state_(initialState) {}
|
||||
|
||||
template <typename Flags>
|
||||
void URLRequest::StateBase<Flags>::SetFlag(Flags flag) {
|
||||
state_ =
|
||||
static_cast<Flags>(static_cast<int>(state_) | static_cast<int>(flag));
|
||||
}
|
||||
|
||||
template <typename Flags>
|
||||
bool URLRequest::StateBase<Flags>::operator==(Flags flag) const {
|
||||
return state_ == flag;
|
||||
}
|
||||
|
||||
template <typename Flags>
|
||||
bool URLRequest::StateBase<Flags>::IsFlagSet(Flags flag) const {
|
||||
return static_cast<int>(state_) & static_cast<int>(flag);
|
||||
}
|
||||
|
||||
URLRequest::RequestState::RequestState()
|
||||
: StateBase(RequestStateFlags::kNotStarted) {}
|
||||
|
||||
bool URLRequest::RequestState::NotStarted() const {
|
||||
return *this == RequestStateFlags::kNotStarted;
|
||||
}
|
||||
|
||||
bool URLRequest::RequestState::Started() const {
|
||||
return IsFlagSet(RequestStateFlags::kStarted);
|
||||
}
|
||||
|
||||
bool URLRequest::RequestState::Finished() const {
|
||||
return IsFlagSet(RequestStateFlags::kFinished);
|
||||
}
|
||||
|
||||
bool URLRequest::RequestState::Canceled() const {
|
||||
return IsFlagSet(RequestStateFlags::kCanceled);
|
||||
}
|
||||
|
||||
bool URLRequest::RequestState::Failed() const {
|
||||
return IsFlagSet(RequestStateFlags::kFailed);
|
||||
}
|
||||
|
||||
bool URLRequest::RequestState::Closed() const {
|
||||
return IsFlagSet(RequestStateFlags::kClosed);
|
||||
}
|
||||
|
||||
URLRequest::ResponseState::ResponseState()
|
||||
: StateBase(ResponseStateFlags::kNotStarted) {}
|
||||
|
||||
bool URLRequest::ResponseState::NotStarted() const {
|
||||
return *this == ResponseStateFlags::kNotStarted;
|
||||
}
|
||||
|
||||
bool URLRequest::ResponseState::Started() const {
|
||||
return IsFlagSet(ResponseStateFlags::kStarted);
|
||||
}
|
||||
|
||||
bool URLRequest::ResponseState::Ended() const {
|
||||
return IsFlagSet(ResponseStateFlags::kEnded);
|
||||
}
|
||||
|
||||
bool URLRequest::ResponseState::Failed() const {
|
||||
return IsFlagSet(ResponseStateFlags::kFailed);
|
||||
}
|
||||
|
||||
mate::Dictionary URLRequest::GetUploadProgress(v8::Isolate* isolate) {
|
||||
mate::Dictionary progress = mate::Dictionary::CreateEmpty(isolate);
|
||||
|
||||
if (atom_request_) {
|
||||
progress.Set("active", true);
|
||||
atom_request_->GetUploadProgress(&progress);
|
||||
} else {
|
||||
progress.Set("active", false);
|
||||
}
|
||||
return progress;
|
||||
}
|
||||
|
||||
URLRequest::URLRequest(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) {
|
||||
InitWith(isolate, wrapper);
|
||||
}
|
||||
|
||||
URLRequest::~URLRequest() {
|
||||
// A request has been created in JS, it was not used and then
|
||||
// it got collected, no close event to cleanup, only destructor
|
||||
// is called.
|
||||
if (atom_request_) {
|
||||
atom_request_->Terminate();
|
||||
}
|
||||
}
|
||||
|
||||
// static
|
||||
mate::WrappableBase* URLRequest::New(mate::Arguments* args) {
|
||||
auto* isolate = args->isolate();
|
||||
v8::Local<v8::Object> options;
|
||||
args->GetNext(&options);
|
||||
mate::Dictionary dict(isolate, options);
|
||||
std::string method;
|
||||
dict.Get("method", &method);
|
||||
std::string url;
|
||||
dict.Get("url", &url);
|
||||
std::string redirect_policy;
|
||||
dict.Get("redirect", &redirect_policy);
|
||||
std::string partition;
|
||||
mate::Handle<api::Session> session;
|
||||
if (dict.Get("session", &session)) {
|
||||
} else if (dict.Get("partition", &partition)) {
|
||||
session = Session::FromPartition(isolate, partition);
|
||||
} else {
|
||||
// Use the default session if not specified.
|
||||
session = Session::FromPartition(isolate, "");
|
||||
}
|
||||
auto* browser_context = session->browser_context();
|
||||
auto* api_url_request = new URLRequest(args->isolate(), args->GetThis());
|
||||
auto atom_url_request = AtomURLRequest::Create(
|
||||
browser_context, method, url, redirect_policy, api_url_request);
|
||||
|
||||
api_url_request->atom_request_ = atom_url_request;
|
||||
|
||||
return api_url_request;
|
||||
}
|
||||
|
||||
// static
|
||||
void URLRequest::BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype) {
|
||||
prototype->SetClassName(mate::StringToV8(isolate, "URLRequest"));
|
||||
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
|
||||
// Request API
|
||||
.MakeDestroyable()
|
||||
.SetMethod("write", &URLRequest::Write)
|
||||
.SetMethod("cancel", &URLRequest::Cancel)
|
||||
.SetMethod("setExtraHeader", &URLRequest::SetExtraHeader)
|
||||
.SetMethod("removeExtraHeader", &URLRequest::RemoveExtraHeader)
|
||||
.SetMethod("setChunkedUpload", &URLRequest::SetChunkedUpload)
|
||||
.SetMethod("followRedirect", &URLRequest::FollowRedirect)
|
||||
.SetMethod("_setLoadFlags", &URLRequest::SetLoadFlags)
|
||||
.SetMethod("getUploadProgress", &URLRequest::GetUploadProgress)
|
||||
.SetProperty("notStarted", &URLRequest::NotStarted)
|
||||
.SetProperty("finished", &URLRequest::Finished)
|
||||
// Response APi
|
||||
.SetProperty("statusCode", &URLRequest::StatusCode)
|
||||
.SetProperty("statusMessage", &URLRequest::StatusMessage)
|
||||
.SetProperty("rawResponseHeaders", &URLRequest::RawResponseHeaders)
|
||||
.SetProperty("httpVersionMajor", &URLRequest::ResponseHttpVersionMajor)
|
||||
.SetProperty("httpVersionMinor", &URLRequest::ResponseHttpVersionMinor);
|
||||
}
|
||||
|
||||
bool URLRequest::NotStarted() const {
|
||||
return request_state_.NotStarted();
|
||||
}
|
||||
|
||||
bool URLRequest::Finished() const {
|
||||
return request_state_.Finished();
|
||||
}
|
||||
|
||||
bool URLRequest::Canceled() const {
|
||||
return request_state_.Canceled();
|
||||
}
|
||||
|
||||
bool URLRequest::Write(scoped_refptr<const net::IOBufferWithSize> buffer,
|
||||
bool is_last) {
|
||||
if (request_state_.Canceled() || request_state_.Failed() ||
|
||||
request_state_.Finished() || request_state_.Closed()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (request_state_.NotStarted()) {
|
||||
request_state_.SetFlag(RequestStateFlags::kStarted);
|
||||
// Pin on first write.
|
||||
Pin();
|
||||
}
|
||||
|
||||
if (is_last) {
|
||||
request_state_.SetFlag(RequestStateFlags::kFinished);
|
||||
EmitRequestEvent(true, "finish");
|
||||
}
|
||||
|
||||
DCHECK(atom_request_);
|
||||
if (atom_request_) {
|
||||
return atom_request_->Write(buffer, is_last);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void URLRequest::Cancel() {
|
||||
if (request_state_.Canceled() || request_state_.Closed()) {
|
||||
// Cancel only once.
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark as canceled.
|
||||
request_state_.SetFlag(RequestStateFlags::kCanceled);
|
||||
|
||||
DCHECK(atom_request_);
|
||||
if (atom_request_ && request_state_.Started()) {
|
||||
// Really cancel if it was started.
|
||||
atom_request_->Cancel();
|
||||
}
|
||||
EmitRequestEvent(true, "abort");
|
||||
|
||||
if (response_state_.Started() && !response_state_.Ended()) {
|
||||
EmitResponseEvent(true, "aborted");
|
||||
}
|
||||
Close();
|
||||
}
|
||||
|
||||
void URLRequest::FollowRedirect() {
|
||||
if (request_state_.Canceled() || request_state_.Closed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
DCHECK(atom_request_);
|
||||
if (atom_request_) {
|
||||
atom_request_->FollowRedirect();
|
||||
}
|
||||
}
|
||||
|
||||
bool URLRequest::SetExtraHeader(const std::string& name,
|
||||
const std::string& value) {
|
||||
// Request state must be in the initial non started state.
|
||||
if (!request_state_.NotStarted()) {
|
||||
// Cannot change headers after send.
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!net::HttpUtil::IsValidHeaderName(name)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!net::HttpUtil::IsValidHeaderValue(value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
DCHECK(atom_request_);
|
||||
if (atom_request_) {
|
||||
atom_request_->SetExtraHeader(name, value);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void URLRequest::RemoveExtraHeader(const std::string& name) {
|
||||
// State must be equal to not started.
|
||||
if (!request_state_.NotStarted()) {
|
||||
// Cannot change headers after send.
|
||||
return;
|
||||
}
|
||||
DCHECK(atom_request_);
|
||||
if (atom_request_) {
|
||||
atom_request_->RemoveExtraHeader(name);
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequest::SetChunkedUpload(bool is_chunked_upload) {
|
||||
// State must be equal to not started.
|
||||
if (!request_state_.NotStarted()) {
|
||||
// Cannot change headers after send.
|
||||
return;
|
||||
}
|
||||
DCHECK(atom_request_);
|
||||
if (atom_request_) {
|
||||
atom_request_->SetChunkedUpload(is_chunked_upload);
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequest::SetLoadFlags(int flags) {
|
||||
// State must be equal to not started.
|
||||
if (!request_state_.NotStarted()) {
|
||||
// Cannot change load flags after start.
|
||||
return;
|
||||
}
|
||||
DCHECK(atom_request_);
|
||||
if (atom_request_) {
|
||||
atom_request_->SetLoadFlags(flags);
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequest::OnReceivedRedirect(
|
||||
int status_code,
|
||||
const std::string& method,
|
||||
const GURL& url,
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers) {
|
||||
if (request_state_.Canceled() || request_state_.Closed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
DCHECK(atom_request_);
|
||||
if (!atom_request_) {
|
||||
return;
|
||||
}
|
||||
|
||||
EmitRequestEvent(false, "redirect", status_code, method, url,
|
||||
response_headers.get());
|
||||
}
|
||||
|
||||
void URLRequest::OnAuthenticationRequired(
|
||||
scoped_refptr<const net::AuthChallengeInfo> auth_info) {
|
||||
if (request_state_.Canceled() || request_state_.Closed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
DCHECK(atom_request_);
|
||||
if (!atom_request_) {
|
||||
return;
|
||||
}
|
||||
|
||||
Emit("login", auth_info.get(),
|
||||
base::Bind(&AtomURLRequest::PassLoginInformation, atom_request_));
|
||||
}
|
||||
|
||||
void URLRequest::OnResponseStarted(
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers) {
|
||||
if (request_state_.Canceled() || request_state_.Failed() ||
|
||||
request_state_.Closed()) {
|
||||
// Don't emit any event after request cancel.
|
||||
return;
|
||||
}
|
||||
response_headers_ = response_headers;
|
||||
response_state_.SetFlag(ResponseStateFlags::kStarted);
|
||||
Emit("response");
|
||||
}
|
||||
|
||||
void URLRequest::OnResponseData(
|
||||
scoped_refptr<const net::IOBufferWithSize> buffer) {
|
||||
if (request_state_.Canceled() || request_state_.Closed() ||
|
||||
request_state_.Failed() || response_state_.Failed()) {
|
||||
// In case we received an unexpected event from Chromium net,
|
||||
// don't emit any data event after request cancel/error/close.
|
||||
return;
|
||||
}
|
||||
if (!buffer || !buffer->data() || !buffer->size()) {
|
||||
return;
|
||||
}
|
||||
Emit("data", buffer);
|
||||
}
|
||||
|
||||
void URLRequest::OnResponseCompleted() {
|
||||
if (request_state_.Canceled() || request_state_.Closed() ||
|
||||
request_state_.Failed() || response_state_.Failed()) {
|
||||
// In case we received an unexpected event from Chromium net,
|
||||
// don't emit any data event after request cancel/error/close.
|
||||
return;
|
||||
}
|
||||
response_state_.SetFlag(ResponseStateFlags::kEnded);
|
||||
Emit("end");
|
||||
Close();
|
||||
}
|
||||
|
||||
void URLRequest::OnError(const std::string& error, bool isRequestError) {
|
||||
auto error_object = v8::Exception::Error(mate::StringToV8(isolate(), error));
|
||||
if (isRequestError) {
|
||||
request_state_.SetFlag(RequestStateFlags::kFailed);
|
||||
EmitRequestEvent(false, "error", error_object);
|
||||
} else {
|
||||
response_state_.SetFlag(ResponseStateFlags::kFailed);
|
||||
EmitResponseEvent(false, "error", error_object);
|
||||
}
|
||||
Close();
|
||||
}
|
||||
|
||||
int URLRequest::StatusCode() const {
|
||||
if (response_headers_) {
|
||||
return response_headers_->response_code();
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
std::string URLRequest::StatusMessage() const {
|
||||
std::string result;
|
||||
if (response_headers_) {
|
||||
result = response_headers_->GetStatusText();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
net::HttpResponseHeaders* URLRequest::RawResponseHeaders() const {
|
||||
return response_headers_.get();
|
||||
}
|
||||
|
||||
uint32_t URLRequest::ResponseHttpVersionMajor() const {
|
||||
if (response_headers_) {
|
||||
return response_headers_->GetHttpVersion().major_value();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint32_t URLRequest::ResponseHttpVersionMinor() const {
|
||||
if (response_headers_) {
|
||||
return response_headers_->GetHttpVersion().minor_value();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void URLRequest::Close() {
|
||||
if (!request_state_.Closed()) {
|
||||
request_state_.SetFlag(RequestStateFlags::kClosed);
|
||||
if (response_state_.Started()) {
|
||||
// Emit a close event if we really have a response object.
|
||||
EmitResponseEvent(true, "close");
|
||||
}
|
||||
EmitRequestEvent(true, "close");
|
||||
}
|
||||
Unpin();
|
||||
if (atom_request_) {
|
||||
// A request has been created in JS, used and then it ended.
|
||||
// We release unneeded net resources.
|
||||
atom_request_->Terminate();
|
||||
}
|
||||
atom_request_ = nullptr;
|
||||
}
|
||||
|
||||
void URLRequest::Pin() {
|
||||
if (wrapper_.IsEmpty()) {
|
||||
wrapper_.Reset(isolate(), GetWrapper());
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequest::Unpin() {
|
||||
wrapper_.Reset();
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void URLRequest::EmitRequestEvent(Args... args) {
|
||||
v8::HandleScope handle_scope(isolate());
|
||||
mate::CustomEmit(isolate(), GetWrapper(), "_emitRequestEvent", args...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void URLRequest::EmitResponseEvent(Args... args) {
|
||||
v8::HandleScope handle_scope(isolate());
|
||||
mate::CustomEmit(isolate(), GetWrapper(), "_emitResponseEvent", args...);
|
||||
}
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,215 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_API_ATOM_API_URL_REQUEST_H_
|
||||
#define ATOM_BROWSER_API_ATOM_API_URL_REQUEST_H_
|
||||
|
||||
#include <array>
|
||||
#include <string>
|
||||
|
||||
#include "atom/browser/api/event_emitter.h"
|
||||
#include "atom/browser/api/trackable_object.h"
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
#include "native_mate/handle.h"
|
||||
#include "native_mate/wrappable_base.h"
|
||||
#include "net/base/auth.h"
|
||||
#include "net/base/io_buffer.h"
|
||||
#include "net/http/http_response_headers.h"
|
||||
#include "net/url_request/url_request_context.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class AtomURLRequest;
|
||||
|
||||
namespace api {
|
||||
|
||||
//
|
||||
// The URLRequest class implements the V8 binding between the JavaScript API
|
||||
// and Chromium native net library. It is responsible for handling HTTP/HTTPS
|
||||
// requests.
|
||||
//
|
||||
// The current class provides only the binding layer. Two other JavaScript
|
||||
// classes (ClientRequest and IncomingMessage) in the net module provide the
|
||||
// final API, including some state management and arguments validation.
|
||||
//
|
||||
// URLRequest's methods fall into two main categories: command and event
|
||||
// methods. They are always executed on the Browser's UI thread.
|
||||
// Command methods are called directly from JavaScript code via the API defined
|
||||
// in BuildPrototype. A command method is generally implemented by forwarding
|
||||
// the call to a corresponding method on AtomURLRequest which does the
|
||||
// synchronization on the Browser IO thread. The latter then calls into Chromium
|
||||
// net library. On the other hand, net library events originate on the IO
|
||||
// thread in AtomURLRequest and are synchronized back on the UI thread, then
|
||||
// forwarded to a corresponding event method in URLRequest and then to
|
||||
// JavaScript via the EmitRequestEvent/EmitResponseEvent helpers.
|
||||
//
|
||||
// URLRequest lifetime management: we followed the Wrapper/Wrappable pattern
|
||||
// defined in native_mate. However, we augment that pattern with a pin/unpin
|
||||
// mechanism. The main reason is that we want the JS API to provide a similar
|
||||
// lifetime guarantees as the XMLHttpRequest.
|
||||
// https://xhr.spec.whatwg.org/#garbage-collection
|
||||
//
|
||||
// The primary motivation is to not garbage collect a URLInstance as long as the
|
||||
// object is emitting network events. For instance, in the following JS code
|
||||
//
|
||||
// (function() {
|
||||
// let request = new URLRequest(...);
|
||||
// request.on('response', (response)=>{
|
||||
// response.on('data', (data) = > {
|
||||
// console.log(data.toString());
|
||||
// });
|
||||
// });
|
||||
// })();
|
||||
//
|
||||
// we still want data to be logged even if the response/request objects are n
|
||||
// more referenced in JavaScript.
|
||||
//
|
||||
// Binding by simply following the native_mate Wrapper/Wrappable pattern will
|
||||
// delete the URLRequest object when the corresponding JS object is collected.
|
||||
// The v8 handle is a private member in WrappableBase and it is always weak,
|
||||
// there is no way to make it strong without changing native_mate.
|
||||
// The solution we implement consists of maintaining some kind of state that
|
||||
// prevents collection of JS wrappers as long as the request is emitting network
|
||||
// events. At initialization, the object is unpinned. When the request starts,
|
||||
// it is pinned. When no more events would be emitted, the object is unpinned
|
||||
// and lifetime is again managed by the standard native mate Wrapper/Wrappable
|
||||
// pattern.
|
||||
//
|
||||
// pin/unpin: are implemented by constructing/reseting a V8 strong persistent
|
||||
// handle.
|
||||
//
|
||||
// The URLRequest/AtmURLRequest interaction could have been implemented in a
|
||||
// single class. However, it implies that the resulting class lifetime will be
|
||||
// managed by two conflicting mechanisms: JavaScript garbage collection and
|
||||
// Chromium reference counting. Reasoning about lifetime issues become much
|
||||
// more complex.
|
||||
//
|
||||
// We chose to split the implementation into two classes linked via a
|
||||
// reference counted/raw pointers. A URLRequest instance is deleted if it is
|
||||
// unpinned and the corresponding JS wrapper object is garbage collected. On the
|
||||
// other hand, an AtmURLRequest instance lifetime is totally governed by
|
||||
// reference counting.
|
||||
//
|
||||
class URLRequest : public mate::EventEmitter<URLRequest> {
|
||||
public:
|
||||
static mate::WrappableBase* New(mate::Arguments* args);
|
||||
|
||||
static void BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype);
|
||||
|
||||
// Methods for reporting events into JavaScript.
|
||||
void OnReceivedRedirect(
|
||||
int status_code,
|
||||
const std::string& method,
|
||||
const GURL& url,
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers);
|
||||
void OnAuthenticationRequired(
|
||||
scoped_refptr<const net::AuthChallengeInfo> auth_info);
|
||||
void OnResponseStarted(
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers);
|
||||
void OnResponseData(scoped_refptr<const net::IOBufferWithSize> data);
|
||||
void OnResponseCompleted();
|
||||
void OnError(const std::string& error, bool isRequestError);
|
||||
mate::Dictionary GetUploadProgress(v8::Isolate* isolate);
|
||||
|
||||
protected:
|
||||
explicit URLRequest(v8::Isolate* isolate, v8::Local<v8::Object> wrapper);
|
||||
~URLRequest() override;
|
||||
|
||||
private:
|
||||
template <typename Flags>
|
||||
class StateBase {
|
||||
public:
|
||||
void SetFlag(Flags flag);
|
||||
|
||||
protected:
|
||||
explicit StateBase(Flags initialState);
|
||||
bool operator==(Flags flag) const;
|
||||
bool IsFlagSet(Flags flag) const;
|
||||
|
||||
private:
|
||||
Flags state_;
|
||||
};
|
||||
|
||||
enum class RequestStateFlags {
|
||||
kNotStarted = 0x0,
|
||||
kStarted = 0x1,
|
||||
kFinished = 0x2,
|
||||
kCanceled = 0x4,
|
||||
kFailed = 0x8,
|
||||
kClosed = 0x10
|
||||
};
|
||||
|
||||
class RequestState : public StateBase<RequestStateFlags> {
|
||||
public:
|
||||
RequestState();
|
||||
bool NotStarted() const;
|
||||
bool Started() const;
|
||||
bool Finished() const;
|
||||
bool Canceled() const;
|
||||
bool Failed() const;
|
||||
bool Closed() const;
|
||||
};
|
||||
|
||||
enum class ResponseStateFlags {
|
||||
kNotStarted = 0x0,
|
||||
kStarted = 0x1,
|
||||
kEnded = 0x2,
|
||||
kFailed = 0x4
|
||||
};
|
||||
|
||||
class ResponseState : public StateBase<ResponseStateFlags> {
|
||||
public:
|
||||
ResponseState();
|
||||
bool NotStarted() const;
|
||||
bool Started() const;
|
||||
bool Ended() const;
|
||||
bool Canceled() const;
|
||||
bool Failed() const;
|
||||
bool Closed() const;
|
||||
};
|
||||
|
||||
bool NotStarted() const;
|
||||
bool Finished() const;
|
||||
bool Canceled() const;
|
||||
bool Failed() const;
|
||||
bool Write(scoped_refptr<const net::IOBufferWithSize> buffer, bool is_last);
|
||||
void Cancel();
|
||||
void FollowRedirect();
|
||||
bool SetExtraHeader(const std::string& name, const std::string& value);
|
||||
void RemoveExtraHeader(const std::string& name);
|
||||
void SetChunkedUpload(bool is_chunked_upload);
|
||||
void SetLoadFlags(int flags);
|
||||
|
||||
int StatusCode() const;
|
||||
std::string StatusMessage() const;
|
||||
net::HttpResponseHeaders* RawResponseHeaders() const;
|
||||
uint32_t ResponseHttpVersionMajor() const;
|
||||
uint32_t ResponseHttpVersionMinor() const;
|
||||
|
||||
void Close();
|
||||
void Pin();
|
||||
void Unpin();
|
||||
template <typename... Args>
|
||||
void EmitRequestEvent(Args... args);
|
||||
template <typename... Args>
|
||||
void EmitResponseEvent(Args... args);
|
||||
|
||||
scoped_refptr<AtomURLRequest> atom_request_;
|
||||
RequestState request_state_;
|
||||
ResponseState response_state_;
|
||||
|
||||
// Used to implement pin/unpin.
|
||||
v8::Global<v8::Object> wrapper_;
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(URLRequest);
|
||||
};
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_API_ATOM_API_URL_REQUEST_H_
|
||||
@@ -1,147 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/api/atom_api_web_request.h"
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "atom/browser/net/atom_network_delegate.h"
|
||||
#include "atom/common/native_mate_converters/callback.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "atom/common/native_mate_converters/value_converter.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
#include "native_mate/object_template_builder.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace mate {
|
||||
|
||||
template <>
|
||||
struct Converter<URLPattern> {
|
||||
static bool FromV8(v8::Isolate* isolate,
|
||||
v8::Local<v8::Value> val,
|
||||
URLPattern* out) {
|
||||
std::string pattern;
|
||||
if (!ConvertFromV8(isolate, val, &pattern))
|
||||
return false;
|
||||
*out = URLPattern(URLPattern::SCHEME_ALL);
|
||||
return out->Parse(pattern) == URLPattern::ParseResult::kSuccess;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mate
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace api {
|
||||
|
||||
namespace {
|
||||
|
||||
template <typename Method, typename Event, typename Listener>
|
||||
void CallNetworkDelegateMethod(
|
||||
URLRequestContextGetter* url_request_context_getter,
|
||||
Method method,
|
||||
Event type,
|
||||
URLPatterns patterns,
|
||||
Listener listener) {
|
||||
// Force creating network delegate.
|
||||
url_request_context_getter->GetURLRequestContext();
|
||||
// Then call the method.
|
||||
auto* network_delegate = url_request_context_getter->network_delegate();
|
||||
(network_delegate->*method)(type, std::move(patterns), std::move(listener));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
WebRequest::WebRequest(v8::Isolate* isolate,
|
||||
AtomBrowserContext* browser_context)
|
||||
: browser_context_(browser_context) {
|
||||
Init(isolate);
|
||||
}
|
||||
|
||||
WebRequest::~WebRequest() {}
|
||||
|
||||
template <AtomNetworkDelegate::SimpleEvent type>
|
||||
void WebRequest::SetSimpleListener(mate::Arguments* args) {
|
||||
SetListener<AtomNetworkDelegate::SimpleListener>(
|
||||
&AtomNetworkDelegate::SetSimpleListenerInIO, type, args);
|
||||
}
|
||||
|
||||
template <AtomNetworkDelegate::ResponseEvent type>
|
||||
void WebRequest::SetResponseListener(mate::Arguments* args) {
|
||||
SetListener<AtomNetworkDelegate::ResponseListener>(
|
||||
&AtomNetworkDelegate::SetResponseListenerInIO, type, args);
|
||||
}
|
||||
|
||||
template <typename Listener, typename Method, typename Event>
|
||||
void WebRequest::SetListener(Method method, Event type, mate::Arguments* args) {
|
||||
// { urls }.
|
||||
URLPatterns patterns;
|
||||
mate::Dictionary dict;
|
||||
args->GetNext(&dict) && dict.Get("urls", &patterns);
|
||||
|
||||
// Function or null.
|
||||
v8::Local<v8::Value> value;
|
||||
Listener listener;
|
||||
if (!args->GetNext(&listener) &&
|
||||
!(args->GetNext(&value) && value->IsNull())) {
|
||||
args->ThrowError("Must pass null or a Function");
|
||||
return;
|
||||
}
|
||||
|
||||
auto* url_request_context_getter = static_cast<URLRequestContextGetter*>(
|
||||
browser_context_->GetRequestContext());
|
||||
if (!url_request_context_getter)
|
||||
return;
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(&CallNetworkDelegateMethod<Method, Event, Listener>,
|
||||
base::RetainedRef(url_request_context_getter), method,
|
||||
type, std::move(patterns), std::move(listener)));
|
||||
}
|
||||
|
||||
// static
|
||||
mate::Handle<WebRequest> WebRequest::Create(
|
||||
v8::Isolate* isolate,
|
||||
AtomBrowserContext* browser_context) {
|
||||
return mate::CreateHandle(isolate, new WebRequest(isolate, browser_context));
|
||||
}
|
||||
|
||||
// static
|
||||
void WebRequest::BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype) {
|
||||
prototype->SetClassName(mate::StringToV8(isolate, "WebRequest"));
|
||||
mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
|
||||
.SetMethod("onBeforeRequest", &WebRequest::SetResponseListener<
|
||||
AtomNetworkDelegate::kOnBeforeRequest>)
|
||||
.SetMethod("onBeforeSendHeaders",
|
||||
&WebRequest::SetResponseListener<
|
||||
AtomNetworkDelegate::kOnBeforeSendHeaders>)
|
||||
.SetMethod("onHeadersReceived",
|
||||
&WebRequest::SetResponseListener<
|
||||
AtomNetworkDelegate::kOnHeadersReceived>)
|
||||
.SetMethod(
|
||||
"onSendHeaders",
|
||||
&WebRequest::SetSimpleListener<AtomNetworkDelegate::kOnSendHeaders>)
|
||||
.SetMethod("onBeforeRedirect",
|
||||
&WebRequest::SetSimpleListener<
|
||||
AtomNetworkDelegate::kOnBeforeRedirect>)
|
||||
.SetMethod("onResponseStarted",
|
||||
&WebRequest::SetSimpleListener<
|
||||
AtomNetworkDelegate::kOnResponseStarted>)
|
||||
.SetMethod(
|
||||
"onCompleted",
|
||||
&WebRequest::SetSimpleListener<AtomNetworkDelegate::kOnCompleted>)
|
||||
.SetMethod("onErrorOccurred", &WebRequest::SetSimpleListener<
|
||||
AtomNetworkDelegate::kOnErrorOccurred>);
|
||||
}
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_API_ATOM_API_WEB_REQUEST_H_
|
||||
#define ATOM_BROWSER_API_ATOM_API_WEB_REQUEST_H_
|
||||
|
||||
#include "atom/browser/api/trackable_object.h"
|
||||
#include "atom/browser/net/atom_network_delegate.h"
|
||||
#include "native_mate/arguments.h"
|
||||
#include "native_mate/handle.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class AtomBrowserContext;
|
||||
|
||||
namespace api {
|
||||
|
||||
class WebRequest : public mate::TrackableObject<WebRequest> {
|
||||
public:
|
||||
static mate::Handle<WebRequest> Create(v8::Isolate* isolate,
|
||||
AtomBrowserContext* browser_context);
|
||||
|
||||
static void BuildPrototype(v8::Isolate* isolate,
|
||||
v8::Local<v8::FunctionTemplate> prototype);
|
||||
|
||||
protected:
|
||||
WebRequest(v8::Isolate* isolate, AtomBrowserContext* browser_context);
|
||||
~WebRequest() override;
|
||||
|
||||
// C++ can not distinguish overloaded member function.
|
||||
template <AtomNetworkDelegate::SimpleEvent type>
|
||||
void SetSimpleListener(mate::Arguments* args);
|
||||
template <AtomNetworkDelegate::ResponseEvent type>
|
||||
void SetResponseListener(mate::Arguments* args);
|
||||
template <typename Listener, typename Method, typename Event>
|
||||
void SetListener(Method method, Event type, mate::Arguments* args);
|
||||
|
||||
private:
|
||||
scoped_refptr<AtomBrowserContext> browser_context_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(WebRequest);
|
||||
};
|
||||
|
||||
} // namespace api
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_API_ATOM_API_WEB_REQUEST_H_
|
||||
@@ -1,117 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/api/stream_subscriber.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "atom/browser/net/url_request_stream_job.h"
|
||||
#include "atom/common/api/event_emitter_caller.h"
|
||||
#include "atom/common/native_mate_converters/callback.h"
|
||||
#include "atom/common/node_includes.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
|
||||
namespace mate {
|
||||
|
||||
StreamSubscriber::StreamSubscriber(
|
||||
v8::Isolate* isolate,
|
||||
v8::Local<v8::Object> emitter,
|
||||
base::WeakPtr<atom::URLRequestStreamJob> url_job,
|
||||
scoped_refptr<base::SequencedTaskRunner> ui_task_runner)
|
||||
: base::RefCountedDeleteOnSequence<StreamSubscriber>(ui_task_runner),
|
||||
isolate_(isolate),
|
||||
emitter_(isolate, emitter),
|
||||
url_job_(url_job),
|
||||
weak_factory_(this) {
|
||||
DCHECK(ui_task_runner->RunsTasksInCurrentSequence());
|
||||
|
||||
auto weak_self = weak_factory_.GetWeakPtr();
|
||||
On("data", base::Bind(&StreamSubscriber::OnData, weak_self));
|
||||
On("end", base::Bind(&StreamSubscriber::OnEnd, weak_self));
|
||||
On("error", base::Bind(&StreamSubscriber::OnError, weak_self));
|
||||
}
|
||||
|
||||
StreamSubscriber::~StreamSubscriber() {
|
||||
RemoveAllListeners();
|
||||
}
|
||||
|
||||
void StreamSubscriber::On(const std::string& event,
|
||||
EventCallback&& callback) { // NOLINT
|
||||
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
|
||||
DCHECK(js_handlers_.find(event) == js_handlers_.end());
|
||||
|
||||
v8::Locker locker(isolate_);
|
||||
v8::Isolate::Scope isolate_scope(isolate_);
|
||||
v8::HandleScope handle_scope(isolate_);
|
||||
// emitter.on(event, EventEmitted)
|
||||
auto fn = CallbackToV8(isolate_, callback);
|
||||
js_handlers_[event] = v8::Global<v8::Value>(isolate_, fn);
|
||||
internal::ValueVector args = {StringToV8(isolate_, event), fn};
|
||||
internal::CallMethodWithArgs(isolate_, emitter_.Get(isolate_), "on", &args);
|
||||
}
|
||||
|
||||
void StreamSubscriber::Off(const std::string& event) {
|
||||
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
|
||||
DCHECK(js_handlers_.find(event) != js_handlers_.end());
|
||||
|
||||
v8::Locker locker(isolate_);
|
||||
v8::Isolate::Scope isolate_scope(isolate_);
|
||||
v8::HandleScope handle_scope(isolate_);
|
||||
auto js_handler = js_handlers_.find(event);
|
||||
DCHECK(js_handler != js_handlers_.end());
|
||||
RemoveListener(js_handler);
|
||||
}
|
||||
|
||||
void StreamSubscriber::OnData(mate::Arguments* args) {
|
||||
v8::Local<v8::Value> buf;
|
||||
args->GetNext(&buf);
|
||||
if (!node::Buffer::HasInstance(buf)) {
|
||||
args->ThrowError("data must be Buffer");
|
||||
return;
|
||||
}
|
||||
|
||||
const char* data = node::Buffer::Data(buf);
|
||||
size_t length = node::Buffer::Length(buf);
|
||||
if (length == 0)
|
||||
return;
|
||||
|
||||
// Pass the data to the URLJob in IO thread.
|
||||
std::vector<char> buffer(data, data + length);
|
||||
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO},
|
||||
base::Bind(&atom::URLRequestStreamJob::OnData,
|
||||
url_job_, base::Passed(&buffer)));
|
||||
}
|
||||
|
||||
void StreamSubscriber::OnEnd(mate::Arguments* args) {
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::Bind(&atom::URLRequestStreamJob::OnEnd, url_job_));
|
||||
}
|
||||
|
||||
void StreamSubscriber::OnError(mate::Arguments* args) {
|
||||
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO},
|
||||
base::Bind(&atom::URLRequestStreamJob::OnError,
|
||||
url_job_, net::ERR_FAILED));
|
||||
}
|
||||
|
||||
void StreamSubscriber::RemoveAllListeners() {
|
||||
DCHECK(owning_task_runner()->RunsTasksInCurrentSequence());
|
||||
v8::Locker locker(isolate_);
|
||||
v8::Isolate::Scope isolate_scope(isolate_);
|
||||
v8::HandleScope handle_scope(isolate_);
|
||||
while (!js_handlers_.empty()) {
|
||||
RemoveListener(js_handlers_.begin());
|
||||
}
|
||||
}
|
||||
|
||||
void StreamSubscriber::RemoveListener(JSHandlersMap::iterator it) {
|
||||
internal::ValueVector args = {StringToV8(isolate_, it->first),
|
||||
it->second.Get(isolate_)};
|
||||
internal::CallMethodWithArgs(isolate_, emitter_.Get(isolate_),
|
||||
"removeListener", &args);
|
||||
js_handlers_.erase(it);
|
||||
}
|
||||
|
||||
} // namespace mate
|
||||
@@ -1,68 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_API_STREAM_SUBSCRIBER_H_
|
||||
#define ATOM_BROWSER_API_STREAM_SUBSCRIBER_H_
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "base/callback.h"
|
||||
#include "base/memory/ref_counted.h"
|
||||
#include "base/memory/ref_counted_delete_on_sequence.h"
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "v8/include/v8.h"
|
||||
|
||||
namespace atom {
|
||||
class URLRequestStreamJob;
|
||||
}
|
||||
|
||||
namespace mate {
|
||||
|
||||
class Arguments;
|
||||
|
||||
class StreamSubscriber
|
||||
: public base::RefCountedDeleteOnSequence<StreamSubscriber> {
|
||||
public:
|
||||
REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
|
||||
|
||||
StreamSubscriber(v8::Isolate* isolate,
|
||||
v8::Local<v8::Object> emitter,
|
||||
base::WeakPtr<atom::URLRequestStreamJob> url_job,
|
||||
scoped_refptr<base::SequencedTaskRunner> ui_task_runner);
|
||||
|
||||
private:
|
||||
friend class base::DeleteHelper<StreamSubscriber>;
|
||||
friend class base::RefCountedDeleteOnSequence<StreamSubscriber>;
|
||||
|
||||
using JSHandlersMap = std::map<std::string, v8::Global<v8::Value>>;
|
||||
using EventCallback = base::Callback<void(mate::Arguments* args)>;
|
||||
|
||||
~StreamSubscriber();
|
||||
|
||||
void On(const std::string& event, EventCallback&& callback); // NOLINT
|
||||
void Off(const std::string& event);
|
||||
|
||||
void OnData(mate::Arguments* args);
|
||||
void OnEnd(mate::Arguments* args);
|
||||
void OnError(mate::Arguments* args);
|
||||
|
||||
void RemoveAllListeners();
|
||||
void RemoveListener(JSHandlersMap::iterator it);
|
||||
|
||||
v8::Isolate* isolate_;
|
||||
v8::Global<v8::Object> emitter_;
|
||||
base::WeakPtr<atom::URLRequestStreamJob> url_job_;
|
||||
|
||||
JSHandlersMap js_handlers_;
|
||||
|
||||
base::WeakPtrFactory<StreamSubscriber> weak_factory_;
|
||||
};
|
||||
|
||||
} // namespace mate
|
||||
|
||||
#endif // ATOM_BROWSER_API_STREAM_SUBSCRIBER_H_
|
||||
@@ -1,106 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/atom_resource_dispatcher_host_delegate.h"
|
||||
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "atom/browser/web_contents_preferences.h"
|
||||
#include "base/strings/utf_string_conversions.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "content/public/browser/download_manager.h"
|
||||
#include "content/public/browser/render_frame_host.h"
|
||||
#include "electron/buildflags/buildflags.h"
|
||||
#include "net/base/escape.h"
|
||||
#include "url/gurl.h"
|
||||
|
||||
#if BUILDFLAG(ENABLE_PDF_VIEWER)
|
||||
#include "atom/common/atom_constants.h"
|
||||
#include "base/strings/stringprintf.h"
|
||||
#include "content/public/browser/stream_info.h"
|
||||
#include "net/url_request/url_request.h"
|
||||
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
#if BUILDFLAG(ENABLE_PDF_VIEWER)
|
||||
void OnPdfResourceIntercepted(
|
||||
const GURL& original_url,
|
||||
int render_process_host_id,
|
||||
int render_frame_id,
|
||||
const content::ResourceRequestInfo::WebContentsGetter&
|
||||
web_contents_getter) {
|
||||
content::WebContents* web_contents = web_contents_getter.Run();
|
||||
if (!web_contents)
|
||||
return;
|
||||
|
||||
auto* web_preferences = WebContentsPreferences::From(web_contents);
|
||||
if (!web_preferences || !web_preferences->IsEnabled(options::kPlugins)) {
|
||||
auto* browser_context = web_contents->GetBrowserContext();
|
||||
auto* download_manager =
|
||||
content::BrowserContext::GetDownloadManager(browser_context);
|
||||
|
||||
download_manager->DownloadUrl(
|
||||
content::DownloadUrlParameters::CreateForWebContentsMainFrame(
|
||||
web_contents, original_url, NO_TRAFFIC_ANNOTATION_YET));
|
||||
return;
|
||||
}
|
||||
|
||||
// The URL passes the original pdf resource url, that will be requested
|
||||
// by the webui page.
|
||||
// chrome://pdf-viewer/index.html?src=https://somepage/123.pdf
|
||||
content::NavigationController::LoadURLParams params(GURL(base::StringPrintf(
|
||||
"%sindex.html?%s=%s", kPdfViewerUIOrigin, kPdfPluginSrc,
|
||||
net::EscapeUrlEncodedData(original_url.spec(), false).c_str())));
|
||||
|
||||
content::RenderFrameHost* frame_host =
|
||||
content::RenderFrameHost::FromID(render_process_host_id, render_frame_id);
|
||||
if (!frame_host) {
|
||||
return;
|
||||
}
|
||||
|
||||
params.frame_tree_node_id = frame_host->GetFrameTreeNodeId();
|
||||
web_contents->GetController().LoadURLWithParams(params);
|
||||
}
|
||||
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
|
||||
|
||||
} // namespace
|
||||
|
||||
AtomResourceDispatcherHostDelegate::AtomResourceDispatcherHostDelegate() {}
|
||||
|
||||
bool AtomResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
|
||||
net::URLRequest* request,
|
||||
const std::string& mime_type,
|
||||
GURL* origin,
|
||||
std::string* payload) {
|
||||
#if BUILDFLAG(ENABLE_PDF_VIEWER)
|
||||
content::ResourceRequestInfo* info =
|
||||
content::ResourceRequestInfo::ForRequest(request);
|
||||
|
||||
int render_process_host_id;
|
||||
int render_frame_id;
|
||||
if (!info->GetAssociatedRenderFrame(&render_process_host_id,
|
||||
&render_frame_id)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (mime_type == "application/pdf") {
|
||||
*origin = GURL(kPdfViewerUIOrigin);
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::UI},
|
||||
base::Bind(&OnPdfResourceIntercepted, request->url(),
|
||||
render_process_host_id, render_frame_id,
|
||||
info->GetWebContentsGetterForRequest()));
|
||||
return true;
|
||||
}
|
||||
#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,31 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_ATOM_RESOURCE_DISPATCHER_HOST_DELEGATE_H_
|
||||
#define ATOM_BROWSER_ATOM_RESOURCE_DISPATCHER_HOST_DELEGATE_H_
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "content/public/browser/resource_dispatcher_host_delegate.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class AtomResourceDispatcherHostDelegate
|
||||
: public content::ResourceDispatcherHostDelegate {
|
||||
public:
|
||||
AtomResourceDispatcherHostDelegate();
|
||||
|
||||
// content::ResourceDispatcherHostDelegate:
|
||||
bool ShouldInterceptResourceAsStream(net::URLRequest* request,
|
||||
const std::string& mime_type,
|
||||
GURL* origin,
|
||||
std::string* payload) override;
|
||||
|
||||
private:
|
||||
DISALLOW_COPY_AND_ASSIGN(AtomResourceDispatcherHostDelegate);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_ATOM_RESOURCE_DISPATCHER_HOST_DELEGATE_H_
|
||||
@@ -1,74 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/io_thread.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "components/net_log/chrome_net_log.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "content/public/browser/network_service_instance.h"
|
||||
#include "net/cert/caching_cert_verifier.h"
|
||||
#include "net/cert/cert_verifier.h"
|
||||
#include "net/cert/cert_verify_proc.h"
|
||||
#include "net/cert/multi_threaded_cert_verifier.h"
|
||||
#include "net/proxy_resolution/proxy_resolution_service.h"
|
||||
#include "net/url_request/url_request_context.h"
|
||||
#include "services/network/network_service.h"
|
||||
#include "services/network/public/cpp/features.h"
|
||||
#include "services/network/url_request_context_builder_mojo.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
IOThread::IOThread(net_log::ChromeNetLog* net_log,
|
||||
SystemNetworkContextManager* system_network_context_manager)
|
||||
: net_log_(net_log) {
|
||||
BrowserThread::SetIOThreadDelegate(this);
|
||||
|
||||
system_network_context_manager->SetUp(
|
||||
&network_context_request_, &network_context_params_,
|
||||
&http_auth_static_params_, &http_auth_dynamic_params_);
|
||||
}
|
||||
|
||||
IOThread::~IOThread() {
|
||||
BrowserThread::SetIOThreadDelegate(nullptr);
|
||||
}
|
||||
|
||||
void IOThread::Init() {
|
||||
if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
|
||||
std::unique_ptr<network::URLRequestContextBuilderMojo> builder =
|
||||
std::make_unique<network::URLRequestContextBuilderMojo>();
|
||||
|
||||
// Enable file:// support.
|
||||
builder->set_file_enabled(true);
|
||||
|
||||
auto cert_verifier = std::make_unique<net::CachingCertVerifier>(
|
||||
std::make_unique<net::MultiThreadedCertVerifier>(
|
||||
net::CertVerifyProc::CreateDefault()));
|
||||
builder->SetCertVerifier(std::move(cert_verifier));
|
||||
|
||||
// Create the network service, so that shared host resolver
|
||||
// gets created which is required to set the auth preferences below.
|
||||
network::NetworkService* network_service = content::GetNetworkServiceImpl();
|
||||
network_service->SetUpHttpAuth(std::move(http_auth_static_params_));
|
||||
network_service->ConfigureHttpAuthPrefs(
|
||||
std::move(http_auth_dynamic_params_));
|
||||
|
||||
system_network_context_ =
|
||||
network_service
|
||||
->CreateNetworkContextWithBuilder(
|
||||
std::move(network_context_request_),
|
||||
std::move(network_context_params_), std::move(builder),
|
||||
&system_request_context_)
|
||||
.release();
|
||||
}
|
||||
}
|
||||
|
||||
void IOThread::CleanUp() {
|
||||
if (!base::FeatureList::IsEnabled(network::features::kNetworkService))
|
||||
system_request_context_->proxy_resolution_service()->OnShutdown();
|
||||
|
||||
if (net_log_)
|
||||
net_log_->ShutDownBeforeTaskScheduler();
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_IO_THREAD_H_
|
||||
#define ATOM_BROWSER_IO_THREAD_H_
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "atom/browser/net/system_network_context_manager.h"
|
||||
#include "base/macros.h"
|
||||
#include "content/public/browser/browser_thread_delegate.h"
|
||||
#include "services/network/public/mojom/network_service.mojom.h"
|
||||
|
||||
namespace net {
|
||||
class URLRequestContext;
|
||||
}
|
||||
|
||||
namespace net_log {
|
||||
class ChromeNetLog;
|
||||
}
|
||||
|
||||
class IOThread : public content::BrowserThreadDelegate {
|
||||
public:
|
||||
explicit IOThread(
|
||||
net_log::ChromeNetLog* net_log,
|
||||
SystemNetworkContextManager* system_network_context_manager);
|
||||
~IOThread() override;
|
||||
|
||||
protected:
|
||||
// BrowserThreadDelegate Implementation, runs on the IO thread.
|
||||
void Init() override;
|
||||
void CleanUp() override;
|
||||
|
||||
private:
|
||||
// The NetLog is owned by the browser process, to allow logging from other
|
||||
// threads during shutdown, but is used most frequently on the IOThread.
|
||||
net_log::ChromeNetLog* net_log_;
|
||||
|
||||
// When the network service is disabled, this holds on to a
|
||||
// content::NetworkContext class that owns |system_request_context_|.
|
||||
// TODO(deepak1556): primary network context has to be destroyed after
|
||||
// other active contexts, but since the ownership of latter is not released
|
||||
// before IO thread is destroyed, it results in a DCHECK failure.
|
||||
// We leak the reference to primary context to workaround this issue,
|
||||
// since there is only one instance for the entire lifetime of app, it is
|
||||
// safe.
|
||||
network::mojom::NetworkContext* system_network_context_;
|
||||
net::URLRequestContext* system_request_context_;
|
||||
|
||||
// These are set on the UI thread, and then consumed during initialization on
|
||||
// the IO thread.
|
||||
network::mojom::NetworkContextRequest network_context_request_;
|
||||
network::mojom::NetworkContextParamsPtr network_context_params_;
|
||||
|
||||
// Initial HTTP auth configuration used when setting up the NetworkService on
|
||||
// the IO Thread. Future updates are sent using the NetworkService mojo
|
||||
// interface, but initial state needs to be set non-racily.
|
||||
network::mojom::HttpAuthStaticParamsPtr http_auth_static_params_;
|
||||
network::mojom::HttpAuthDynamicParamsPtr http_auth_dynamic_params_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(IOThread);
|
||||
};
|
||||
|
||||
#endif // ATOM_BROWSER_IO_THREAD_H_
|
||||
@@ -1,29 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/loader/layered_resource_handler.h"
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
namespace atom {
|
||||
|
||||
LayeredResourceHandler::LayeredResourceHandler(
|
||||
net::URLRequest* request,
|
||||
std::unique_ptr<content::ResourceHandler> next_handler,
|
||||
Delegate* delegate)
|
||||
: content::LayeredResourceHandler(request, std::move(next_handler)),
|
||||
delegate_(delegate) {}
|
||||
|
||||
LayeredResourceHandler::~LayeredResourceHandler() {}
|
||||
|
||||
void LayeredResourceHandler::OnResponseStarted(
|
||||
network::ResourceResponse* response,
|
||||
std::unique_ptr<content::ResourceController> controller) {
|
||||
if (delegate_)
|
||||
delegate_->OnResponseStarted(response);
|
||||
next_handler_->OnResponseStarted(response, std::move(controller));
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,44 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_LOADER_LAYERED_RESOURCE_HANDLER_H_
|
||||
#define ATOM_BROWSER_LOADER_LAYERED_RESOURCE_HANDLER_H_
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "content/browser/loader/layered_resource_handler.h" // nogncheck
|
||||
#include "services/network/public/cpp/resource_response.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
// Resource handler that notifies on various stages of a resource request.
|
||||
class LayeredResourceHandler : public content::LayeredResourceHandler {
|
||||
public:
|
||||
class Delegate {
|
||||
public:
|
||||
Delegate() {}
|
||||
virtual ~Delegate() {}
|
||||
|
||||
virtual void OnResponseStarted(network::ResourceResponse* response) = 0;
|
||||
};
|
||||
|
||||
LayeredResourceHandler(net::URLRequest* request,
|
||||
std::unique_ptr<content::ResourceHandler> next_handler,
|
||||
Delegate* delegate);
|
||||
~LayeredResourceHandler() override;
|
||||
|
||||
// content::LayeredResourceHandler:
|
||||
void OnResponseStarted(
|
||||
network::ResourceResponse* response,
|
||||
std::unique_ptr<content::ResourceController> controller) override;
|
||||
|
||||
private:
|
||||
Delegate* delegate_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(LayeredResourceHandler);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_LOADER_LAYERED_RESOURCE_HANDLER_H_
|
||||
@@ -1,95 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/login_handler.h"
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/browser.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "base/values.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "content/public/browser/web_contents.h"
|
||||
#include "net/base/auth.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace atom {
|
||||
|
||||
LoginHandler::LoginHandler(net::URLRequest* request,
|
||||
const net::AuthChallengeInfo& auth_info,
|
||||
net::NetworkDelegate::AuthCallback callback,
|
||||
net::AuthCredentials* credentials,
|
||||
content::ResourceRequestInfo* resource_request_info)
|
||||
: credentials_(credentials),
|
||||
auth_info_(&auth_info),
|
||||
auth_callback_(std::move(callback)),
|
||||
weak_factory_(this) {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
|
||||
std::unique_ptr<base::DictionaryValue> request_details(
|
||||
new base::DictionaryValue);
|
||||
FillRequestDetails(request_details.get(), request);
|
||||
|
||||
web_contents_getter_ =
|
||||
resource_request_info->GetWebContentsGetterForRequest();
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::UI},
|
||||
base::BindOnce(&Browser::RequestLogin, base::Unretained(Browser::Get()),
|
||||
base::RetainedRef(this), std::move(request_details)));
|
||||
}
|
||||
|
||||
LoginHandler::~LoginHandler() {}
|
||||
|
||||
void LoginHandler::Login(const base::string16& username,
|
||||
const base::string16& password) {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::UI);
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(&LoginHandler::DoLogin, weak_factory_.GetWeakPtr(),
|
||||
username, password));
|
||||
}
|
||||
|
||||
void LoginHandler::CancelAuth() {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::UI);
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(&LoginHandler::DoCancelAuth, weak_factory_.GetWeakPtr()));
|
||||
}
|
||||
|
||||
void LoginHandler::NotifyRequestDestroyed() {
|
||||
auth_callback_.Reset();
|
||||
credentials_ = nullptr;
|
||||
weak_factory_.InvalidateWeakPtrs();
|
||||
}
|
||||
|
||||
content::WebContents* LoginHandler::GetWebContents() const {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::UI);
|
||||
return web_contents_getter_.Run();
|
||||
}
|
||||
|
||||
void LoginHandler::DoCancelAuth() {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
if (!auth_callback_.is_null())
|
||||
std::move(auth_callback_)
|
||||
.Run(net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
|
||||
}
|
||||
|
||||
void LoginHandler::DoLogin(const base::string16& username,
|
||||
const base::string16& password) {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
if (!auth_callback_.is_null()) {
|
||||
credentials_->Set(username, password);
|
||||
std::move(auth_callback_)
|
||||
.Run(net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,75 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_LOGIN_HANDLER_H_
|
||||
#define ATOM_BROWSER_LOGIN_HANDLER_H_
|
||||
|
||||
#include "base/callback.h"
|
||||
#include "base/memory/ref_counted.h"
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "base/sequenced_task_runner_helpers.h"
|
||||
#include "base/strings/string16.h"
|
||||
#include "content/public/browser/resource_request_info.h"
|
||||
#include "net/base/network_delegate.h"
|
||||
|
||||
namespace content {
|
||||
class WebContents;
|
||||
}
|
||||
|
||||
namespace atom {
|
||||
|
||||
// Handles the HTTP basic auth, must be created on IO thread.
|
||||
class LoginHandler : public base::RefCountedThreadSafe<LoginHandler> {
|
||||
public:
|
||||
LoginHandler(net::URLRequest* request,
|
||||
const net::AuthChallengeInfo& auth_info,
|
||||
net::NetworkDelegate::AuthCallback callback,
|
||||
net::AuthCredentials* credentials,
|
||||
content::ResourceRequestInfo* resource_request_info);
|
||||
|
||||
// The auth is cancelled, must be called on UI thread.
|
||||
void CancelAuth();
|
||||
|
||||
// The URLRequest associated with the auth is destroyed.
|
||||
void NotifyRequestDestroyed();
|
||||
|
||||
// Login with |username| and |password|, must be called on UI thread.
|
||||
void Login(const base::string16& username, const base::string16& password);
|
||||
|
||||
// Returns the WebContents associated with the request, must be called on UI
|
||||
// thread.
|
||||
content::WebContents* GetWebContents() const;
|
||||
|
||||
const net::AuthChallengeInfo* auth_info() const { return auth_info_.get(); }
|
||||
|
||||
private:
|
||||
friend class base::RefCountedThreadSafe<LoginHandler>;
|
||||
friend class base::DeleteHelper<LoginHandler>;
|
||||
|
||||
~LoginHandler();
|
||||
|
||||
// Must be called on IO thread.
|
||||
void DoCancelAuth();
|
||||
void DoLogin(const base::string16& username, const base::string16& password);
|
||||
|
||||
// Credentials to be used for the auth.
|
||||
net::AuthCredentials* credentials_;
|
||||
|
||||
// Who/where/what asked for the authentication.
|
||||
scoped_refptr<const net::AuthChallengeInfo> auth_info_;
|
||||
|
||||
// WebContents associated with the login request.
|
||||
content::ResourceRequestInfo::WebContentsGetter web_contents_getter_;
|
||||
|
||||
// Called with preferred value of net::NetworkDelegate::AuthRequiredResponse.
|
||||
net::NetworkDelegate::AuthCallback auth_callback_;
|
||||
|
||||
base::WeakPtrFactory<LoginHandler> weak_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(LoginHandler);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_LOGIN_HANDLER_H_
|
||||
@@ -1,25 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/about_protocol_handler.h"
|
||||
|
||||
#include "atom/browser/net/url_request_about_job.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
AboutProtocolHandler::AboutProtocolHandler() {}
|
||||
|
||||
AboutProtocolHandler::~AboutProtocolHandler() {}
|
||||
|
||||
net::URLRequestJob* AboutProtocolHandler::MaybeCreateJob(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const {
|
||||
return new URLRequestAboutJob(request, network_delegate);
|
||||
}
|
||||
|
||||
bool AboutProtocolHandler::IsSafeRedirectTarget(const GURL& location) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,29 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_ABOUT_PROTOCOL_HANDLER_H_
|
||||
#define ATOM_BROWSER_NET_ABOUT_PROTOCOL_HANDLER_H_
|
||||
|
||||
#include "net/url_request/url_request_job_factory.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class AboutProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler {
|
||||
public:
|
||||
AboutProtocolHandler();
|
||||
~AboutProtocolHandler() override;
|
||||
|
||||
// net::URLRequestJobFactory::ProtocolHandler:
|
||||
net::URLRequestJob* MaybeCreateJob(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const override;
|
||||
bool IsSafeRedirectTarget(const GURL& location) const override;
|
||||
|
||||
private:
|
||||
DISALLOW_COPY_AND_ASSIGN(AboutProtocolHandler);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_ABOUT_PROTOCOL_HANDLER_H_
|
||||
@@ -1,34 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/asar/asar_protocol_handler.h"
|
||||
|
||||
#include "atom/browser/net/asar/url_request_asar_job.h"
|
||||
#include "base/task_runner.h"
|
||||
#include "net/base/filename_util.h"
|
||||
#include "net/base/net_errors.h"
|
||||
|
||||
namespace asar {
|
||||
|
||||
AsarProtocolHandler::AsarProtocolHandler(
|
||||
const scoped_refptr<base::TaskRunner>& file_task_runner)
|
||||
: file_task_runner_(file_task_runner) {}
|
||||
|
||||
AsarProtocolHandler::~AsarProtocolHandler() {}
|
||||
|
||||
net::URLRequestJob* AsarProtocolHandler::MaybeCreateJob(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const {
|
||||
base::FilePath full_path;
|
||||
net::FileURLToFilePath(request->url(), &full_path);
|
||||
auto* job = new URLRequestAsarJob(request, network_delegate);
|
||||
job->Initialize(file_task_runner_, full_path);
|
||||
return job;
|
||||
}
|
||||
|
||||
bool AsarProtocolHandler::IsSafeRedirectTarget(const GURL& location) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace asar
|
||||
@@ -1,37 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_ASAR_ASAR_PROTOCOL_HANDLER_H_
|
||||
#define ATOM_BROWSER_NET_ASAR_ASAR_PROTOCOL_HANDLER_H_
|
||||
|
||||
#include "base/memory/ref_counted.h"
|
||||
#include "net/url_request/url_request_job_factory.h"
|
||||
|
||||
namespace base {
|
||||
class TaskRunner;
|
||||
}
|
||||
|
||||
namespace asar {
|
||||
|
||||
class AsarProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler {
|
||||
public:
|
||||
explicit AsarProtocolHandler(
|
||||
const scoped_refptr<base::TaskRunner>& file_task_runner);
|
||||
~AsarProtocolHandler() override;
|
||||
|
||||
// net::URLRequestJobFactory::ProtocolHandler:
|
||||
net::URLRequestJob* MaybeCreateJob(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const override;
|
||||
bool IsSafeRedirectTarget(const GURL& location) const override;
|
||||
|
||||
private:
|
||||
const scoped_refptr<base::TaskRunner> file_task_runner_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(AsarProtocolHandler);
|
||||
};
|
||||
|
||||
} // namespace asar
|
||||
|
||||
#endif // ATOM_BROWSER_NET_ASAR_ASAR_PROTOCOL_HANDLER_H_
|
||||
@@ -1,337 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/asar/url_request_asar_job.h"
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "atom/common/asar/archive.h"
|
||||
#include "atom/common/asar/asar_util.h"
|
||||
#include "atom/common/atom_constants.h"
|
||||
#include "base/bind.h"
|
||||
#include "base/files/file_util.h"
|
||||
#include "base/strings/string_util.h"
|
||||
#include "base/synchronization/lock.h"
|
||||
#include "base/task_runner.h"
|
||||
#include "base/threading/thread_task_runner_handle.h"
|
||||
#include "net/base/file_stream.h"
|
||||
#include "net/base/filename_util.h"
|
||||
#include "net/base/io_buffer.h"
|
||||
#include "net/base/load_flags.h"
|
||||
#include "net/base/mime_util.h"
|
||||
#include "net/base/net_errors.h"
|
||||
#include "net/filter/gzip_source_stream.h"
|
||||
#include "net/http/http_util.h"
|
||||
#include "net/url_request/url_request_status.h"
|
||||
|
||||
#if defined(OS_WIN)
|
||||
#include "base/win/shortcut.h"
|
||||
#endif
|
||||
|
||||
namespace asar {
|
||||
|
||||
URLRequestAsarJob::FileMetaInfo::FileMetaInfo() = default;
|
||||
|
||||
URLRequestAsarJob::URLRequestAsarJob(net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate)
|
||||
: net::URLRequestJob(request, network_delegate), weak_ptr_factory_(this) {}
|
||||
|
||||
URLRequestAsarJob::~URLRequestAsarJob() {}
|
||||
|
||||
void URLRequestAsarJob::Initialize(
|
||||
const scoped_refptr<base::TaskRunner> file_task_runner,
|
||||
const base::FilePath& file_path) {
|
||||
// Determine whether it is an asar file.
|
||||
base::FilePath asar_path, relative_path;
|
||||
if (!GetAsarArchivePath(file_path, &asar_path, &relative_path)) {
|
||||
InitializeFileJob(file_task_runner, file_path);
|
||||
return;
|
||||
}
|
||||
|
||||
std::shared_ptr<Archive> archive = GetOrCreateAsarArchive(asar_path);
|
||||
Archive::FileInfo file_info;
|
||||
if (!archive || !archive->GetFileInfo(relative_path, &file_info)) {
|
||||
type_ = TYPE_ERROR;
|
||||
return;
|
||||
}
|
||||
|
||||
if (file_info.unpacked) {
|
||||
base::FilePath real_path;
|
||||
archive->CopyFileOut(relative_path, &real_path);
|
||||
InitializeFileJob(file_task_runner, real_path);
|
||||
return;
|
||||
}
|
||||
|
||||
InitializeAsarJob(file_task_runner, archive, relative_path, file_info);
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::InitializeAsarJob(
|
||||
const scoped_refptr<base::TaskRunner> file_task_runner,
|
||||
std::shared_ptr<Archive> archive,
|
||||
const base::FilePath& file_path,
|
||||
const Archive::FileInfo& file_info) {
|
||||
type_ = TYPE_ASAR;
|
||||
file_task_runner_ = file_task_runner;
|
||||
stream_.reset(new net::FileStream(file_task_runner_));
|
||||
archive_ = archive;
|
||||
file_path_ = file_path;
|
||||
file_info_ = file_info;
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::InitializeFileJob(
|
||||
const scoped_refptr<base::TaskRunner> file_task_runner,
|
||||
const base::FilePath& file_path) {
|
||||
type_ = TYPE_FILE;
|
||||
file_task_runner_ = file_task_runner;
|
||||
stream_.reset(new net::FileStream(file_task_runner_));
|
||||
file_path_ = file_path;
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::Start() {
|
||||
if (type_ == TYPE_ASAR || type_ == TYPE_FILE) {
|
||||
auto* meta_info = new FileMetaInfo();
|
||||
if (type_ == TYPE_ASAR) {
|
||||
meta_info->file_path = archive_->path();
|
||||
meta_info->file_exists = true;
|
||||
meta_info->is_directory = false;
|
||||
meta_info->file_size = file_info_.size;
|
||||
}
|
||||
file_task_runner_->PostTaskAndReply(
|
||||
FROM_HERE,
|
||||
base::BindOnce(&URLRequestAsarJob::FetchMetaInfo, file_path_, type_,
|
||||
base::Unretained(meta_info)),
|
||||
base::BindOnce(&URLRequestAsarJob::DidFetchMetaInfo,
|
||||
weak_ptr_factory_.GetWeakPtr(), base::Owned(meta_info)));
|
||||
} else {
|
||||
base::ThreadTaskRunnerHandle::Get()->PostTask(
|
||||
FROM_HERE, base::BindOnce(&URLRequestAsarJob::DidOpen,
|
||||
weak_ptr_factory_.GetWeakPtr(),
|
||||
net::ERR_FILE_NOT_FOUND));
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::Kill() {
|
||||
stream_.reset();
|
||||
weak_ptr_factory_.InvalidateWeakPtrs();
|
||||
|
||||
URLRequestJob::Kill();
|
||||
}
|
||||
|
||||
int URLRequestAsarJob::ReadRawData(net::IOBuffer* dest, int dest_size) {
|
||||
if (remaining_bytes_ < dest_size)
|
||||
dest_size = static_cast<int>(remaining_bytes_);
|
||||
|
||||
// If we should copy zero bytes because |remaining_bytes_| is zero, short
|
||||
// circuit here.
|
||||
if (!dest_size)
|
||||
return 0;
|
||||
|
||||
int rv = stream_->Read(
|
||||
dest, dest_size,
|
||||
base::Bind(&URLRequestAsarJob::DidRead, weak_ptr_factory_.GetWeakPtr(),
|
||||
WrapRefCounted(dest)));
|
||||
if (rv >= 0) {
|
||||
remaining_bytes_ -= rv;
|
||||
DCHECK_GE(remaining_bytes_, 0);
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
bool URLRequestAsarJob::IsRedirectResponse(GURL* location,
|
||||
int* http_status_code,
|
||||
bool* insecure_scheme_was_upgraded) {
|
||||
if (type_ != TYPE_FILE)
|
||||
return false;
|
||||
#if defined(OS_WIN)
|
||||
// Follow a Windows shortcut.
|
||||
// We just resolve .lnk file, ignore others.
|
||||
if (!base::LowerCaseEqualsASCII(file_path_.Extension(), ".lnk"))
|
||||
return false;
|
||||
|
||||
base::FilePath new_path = file_path_;
|
||||
bool resolved;
|
||||
resolved = base::win::ResolveShortcut(new_path, &new_path, NULL);
|
||||
|
||||
// If shortcut is not resolved succesfully, do not redirect.
|
||||
if (!resolved)
|
||||
return false;
|
||||
|
||||
*location = net::FilePathToFileURL(new_path);
|
||||
*http_status_code = 301;
|
||||
*insecure_scheme_was_upgraded = false;
|
||||
return true;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
std::unique_ptr<net::SourceStream> URLRequestAsarJob::SetUpSourceStream() {
|
||||
std::unique_ptr<net::SourceStream> source =
|
||||
net::URLRequestJob::SetUpSourceStream();
|
||||
// Bug 9936 - .svgz files needs to be decompressed.
|
||||
return base::LowerCaseEqualsASCII(file_path_.Extension(), ".svgz")
|
||||
? net::GzipSourceStream::Create(std::move(source),
|
||||
net::SourceStream::TYPE_GZIP)
|
||||
: std::move(source);
|
||||
}
|
||||
|
||||
bool URLRequestAsarJob::GetMimeType(std::string* mime_type) const {
|
||||
if (meta_info_.mime_type_result) {
|
||||
*mime_type = meta_info_.mime_type;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::SetExtraRequestHeaders(
|
||||
const net::HttpRequestHeaders& headers) {
|
||||
std::string range_header;
|
||||
if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) {
|
||||
// This job only cares about the Range header. This method stashes the value
|
||||
// for later use in DidOpen(), which is responsible for some of the range
|
||||
// validation as well. NotifyStartError is not legal to call here since
|
||||
// the job has not started.
|
||||
std::vector<net::HttpByteRange> ranges;
|
||||
if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) {
|
||||
if (ranges.size() == 1) {
|
||||
byte_range_ = ranges[0];
|
||||
} else {
|
||||
range_parse_result_ = net::ERR_REQUEST_RANGE_NOT_SATISFIABLE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int URLRequestAsarJob::GetResponseCode() const {
|
||||
// Request Job gets created only if path exists.
|
||||
return 200;
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::GetResponseInfo(net::HttpResponseInfo* info) {
|
||||
std::string status("HTTP/1.1 200 OK");
|
||||
auto* headers = new net::HttpResponseHeaders(status);
|
||||
|
||||
headers->AddHeader(atom::kCORSHeader);
|
||||
info->headers = headers;
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::FetchMetaInfo(const base::FilePath& file_path,
|
||||
JobType type,
|
||||
FileMetaInfo* meta_info) {
|
||||
if (type == TYPE_FILE) {
|
||||
base::File::Info file_info;
|
||||
meta_info->file_exists = base::GetFileInfo(file_path, &file_info);
|
||||
if (meta_info->file_exists) {
|
||||
meta_info->file_path = file_path;
|
||||
meta_info->file_size = file_info.size;
|
||||
meta_info->is_directory = file_info.is_directory;
|
||||
}
|
||||
}
|
||||
|
||||
// We use GetWellKnownMimeTypeFromExtension() to ensure that configurations
|
||||
// that may have been set by other programs on a user's machine don't affect
|
||||
// the mime type returned (in particular, JS should always be
|
||||
// (application/javascript). See https://crbug.com/797712. Using an accurate
|
||||
// mime type is necessary at least for modules and sw, which enforce strict
|
||||
// mime type requirements.
|
||||
// TODO(deepak1556): Revert this when sw support is removed for file scheme.
|
||||
base::FilePath::StringType file_extension = file_path.Extension();
|
||||
if (file_extension.empty()) {
|
||||
meta_info->mime_type_result = false;
|
||||
} else {
|
||||
meta_info->mime_type_result = net::GetWellKnownMimeTypeFromExtension(
|
||||
file_extension.substr(1), &meta_info->mime_type);
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::DidFetchMetaInfo(const FileMetaInfo* meta_info) {
|
||||
meta_info_ = *meta_info;
|
||||
if (!meta_info_.file_exists || meta_info_.is_directory) {
|
||||
DidOpen(net::ERR_FILE_NOT_FOUND);
|
||||
return;
|
||||
}
|
||||
|
||||
int flags =
|
||||
base::File::FLAG_OPEN | base::File::FLAG_READ | base::File::FLAG_ASYNC;
|
||||
int rv = stream_->Open(
|
||||
meta_info_.file_path, flags,
|
||||
base::Bind(&URLRequestAsarJob::DidOpen, weak_ptr_factory_.GetWeakPtr()));
|
||||
if (rv != net::ERR_IO_PENDING)
|
||||
DidOpen(rv);
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::DidOpen(int result) {
|
||||
if (result != net::OK) {
|
||||
NotifyStartError(
|
||||
net::URLRequestStatus(net::URLRequestStatus::FAILED, result));
|
||||
return;
|
||||
}
|
||||
|
||||
if (range_parse_result_ != net::OK) {
|
||||
NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED,
|
||||
range_parse_result_));
|
||||
return;
|
||||
}
|
||||
|
||||
int64_t file_size, read_offset;
|
||||
if (type_ == TYPE_ASAR) {
|
||||
file_size = file_info_.size;
|
||||
read_offset = file_info_.offset;
|
||||
} else {
|
||||
file_size = meta_info_.file_size;
|
||||
read_offset = 0;
|
||||
}
|
||||
|
||||
if (!byte_range_.ComputeBounds(file_size)) {
|
||||
NotifyStartError(net::URLRequestStatus(
|
||||
net::URLRequestStatus::FAILED, net::ERR_REQUEST_RANGE_NOT_SATISFIABLE));
|
||||
return;
|
||||
}
|
||||
|
||||
remaining_bytes_ =
|
||||
byte_range_.last_byte_position() - byte_range_.first_byte_position() + 1;
|
||||
seek_offset_ = byte_range_.first_byte_position() + read_offset;
|
||||
|
||||
if (remaining_bytes_ > 0 && seek_offset_ != 0) {
|
||||
int rv =
|
||||
stream_->Seek(seek_offset_, base::Bind(&URLRequestAsarJob::DidSeek,
|
||||
weak_ptr_factory_.GetWeakPtr()));
|
||||
if (rv != net::ERR_IO_PENDING) {
|
||||
// stream_->Seek() failed, so pass an intentionally erroneous value
|
||||
// into DidSeek().
|
||||
DidSeek(-1);
|
||||
}
|
||||
} else {
|
||||
// We didn't need to call stream_->Seek() at all, so we pass to DidSeek()
|
||||
// the value that would mean seek success. This way we skip the code
|
||||
// handling seek failure.
|
||||
DidSeek(seek_offset_);
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::DidSeek(int64_t result) {
|
||||
if (result != seek_offset_) {
|
||||
NotifyStartError(net::URLRequestStatus(
|
||||
net::URLRequestStatus::FAILED, net::ERR_REQUEST_RANGE_NOT_SATISFIABLE));
|
||||
return;
|
||||
}
|
||||
set_expected_content_size(remaining_bytes_);
|
||||
NotifyHeadersComplete();
|
||||
}
|
||||
|
||||
void URLRequestAsarJob::DidRead(scoped_refptr<net::IOBuffer> buf, int result) {
|
||||
if (result >= 0) {
|
||||
remaining_bytes_ -= result;
|
||||
DCHECK_GE(remaining_bytes_, 0);
|
||||
}
|
||||
|
||||
buf = nullptr;
|
||||
|
||||
ReadRawDataComplete(result);
|
||||
}
|
||||
|
||||
} // namespace asar
|
||||
@@ -1,137 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_ASAR_URL_REQUEST_ASAR_JOB_H_
|
||||
#define ATOM_BROWSER_NET_ASAR_URL_REQUEST_ASAR_JOB_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "atom/browser/net/js_asker.h"
|
||||
#include "atom/common/asar/archive.h"
|
||||
#include "base/files/file_path.h"
|
||||
#include "base/memory/ref_counted.h"
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "net/http/http_byte_range.h"
|
||||
#include "net/url_request/url_request_job.h"
|
||||
|
||||
namespace base {
|
||||
class TaskRunner;
|
||||
}
|
||||
|
||||
namespace net {
|
||||
class FileStream;
|
||||
}
|
||||
|
||||
namespace asar {
|
||||
|
||||
// Createa a request job according to the file path.
|
||||
net::URLRequestJob* CreateJobFromPath(
|
||||
const base::FilePath& full_path,
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate,
|
||||
const scoped_refptr<base::TaskRunner> file_task_runner);
|
||||
|
||||
class URLRequestAsarJob : public net::URLRequestJob {
|
||||
public:
|
||||
URLRequestAsarJob(net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate);
|
||||
|
||||
void Initialize(const scoped_refptr<base::TaskRunner> file_task_runner,
|
||||
const base::FilePath& file_path);
|
||||
|
||||
protected:
|
||||
~URLRequestAsarJob() override;
|
||||
|
||||
void InitializeAsarJob(const scoped_refptr<base::TaskRunner> file_task_runner,
|
||||
std::shared_ptr<Archive> archive,
|
||||
const base::FilePath& file_path,
|
||||
const Archive::FileInfo& file_info);
|
||||
void InitializeFileJob(const scoped_refptr<base::TaskRunner> file_task_runner,
|
||||
const base::FilePath& file_path);
|
||||
|
||||
// net::URLRequestJob:
|
||||
void Start() override;
|
||||
void Kill() override;
|
||||
int ReadRawData(net::IOBuffer* buf, int buf_size) override;
|
||||
bool IsRedirectResponse(GURL* location,
|
||||
int* http_status_code,
|
||||
bool* insecure_scheme_was_upgraded) override;
|
||||
std::unique_ptr<net::SourceStream> SetUpSourceStream() override;
|
||||
bool GetMimeType(std::string* mime_type) const override;
|
||||
void SetExtraRequestHeaders(const net::HttpRequestHeaders& headers) override;
|
||||
int GetResponseCode() const override;
|
||||
void GetResponseInfo(net::HttpResponseInfo* info) override;
|
||||
|
||||
private:
|
||||
// The type of this job.
|
||||
enum JobType {
|
||||
TYPE_ERROR,
|
||||
TYPE_ASAR,
|
||||
TYPE_FILE,
|
||||
};
|
||||
|
||||
// Meta information about the file. It's used as a member in the
|
||||
// URLRequestFileJob and also passed between threads because disk access is
|
||||
// necessary to obtain it.
|
||||
struct FileMetaInfo {
|
||||
// Size of the file.
|
||||
int64_t file_size = 0;
|
||||
// Mime type associated with the file.
|
||||
std::string mime_type;
|
||||
// Result returned from GetMimeTypeFromFile(), i.e. flag showing whether
|
||||
// obtaining of the mime type was successful.
|
||||
bool mime_type_result = false;
|
||||
// Flag showing whether the file exists.
|
||||
bool file_exists = false;
|
||||
// Flag showing whether the file name actually refers to a directory.
|
||||
bool is_directory = false;
|
||||
// Path to the file.
|
||||
base::FilePath file_path;
|
||||
|
||||
FileMetaInfo();
|
||||
};
|
||||
|
||||
// Fetches file info on a background thread.
|
||||
static void FetchMetaInfo(const base::FilePath& file_path,
|
||||
JobType type,
|
||||
FileMetaInfo* meta_info);
|
||||
|
||||
// Callback after fetching file info on a background thread.
|
||||
void DidFetchMetaInfo(const FileMetaInfo* meta_info);
|
||||
|
||||
// Callback after opening file on a background thread.
|
||||
void DidOpen(int result);
|
||||
|
||||
// Callback after seeking to the beginning of |byte_range_| in the file
|
||||
// on a background thread.
|
||||
void DidSeek(int64_t result);
|
||||
|
||||
// Callback after data is asynchronously read from the file into |buf|.
|
||||
void DidRead(scoped_refptr<net::IOBuffer> buf, int result);
|
||||
|
||||
JobType type_ = TYPE_ERROR;
|
||||
|
||||
std::shared_ptr<Archive> archive_;
|
||||
base::FilePath file_path_;
|
||||
Archive::FileInfo file_info_;
|
||||
|
||||
std::unique_ptr<net::FileStream> stream_;
|
||||
FileMetaInfo meta_info_;
|
||||
scoped_refptr<base::TaskRunner> file_task_runner_;
|
||||
|
||||
net::HttpByteRange byte_range_;
|
||||
int64_t remaining_bytes_ = 0;
|
||||
int64_t seek_offset_ = 0;
|
||||
|
||||
net::Error range_parse_result_ = net::OK;
|
||||
|
||||
base::WeakPtrFactory<URLRequestAsarJob> weak_ptr_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(URLRequestAsarJob);
|
||||
};
|
||||
|
||||
} // namespace asar
|
||||
|
||||
#endif // ATOM_BROWSER_NET_ASAR_URL_REQUEST_ASAR_JOB_H_
|
||||
@@ -1,209 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/atom_cert_verifier.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/browser.h"
|
||||
#include "atom/browser/net/require_ct_delegate.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "base/containers/linked_list.h"
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "net/base/net_errors.h"
|
||||
#include "net/cert/cert_verify_result.h"
|
||||
#include "net/cert/x509_certificate.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace atom {
|
||||
|
||||
VerifyRequestParams::VerifyRequestParams() = default;
|
||||
VerifyRequestParams::~VerifyRequestParams() = default;
|
||||
VerifyRequestParams::VerifyRequestParams(const VerifyRequestParams&) = default;
|
||||
|
||||
namespace {
|
||||
|
||||
class Response : public base::LinkNode<Response> {
|
||||
public:
|
||||
Response(net::CertVerifyResult* verify_result,
|
||||
net::CompletionOnceCallback callback)
|
||||
: verify_result_(verify_result), callback_(std::move(callback)) {}
|
||||
net::CertVerifyResult* verify_result() { return verify_result_; }
|
||||
net::CompletionOnceCallback callback() { return std::move(callback_); }
|
||||
|
||||
private:
|
||||
net::CertVerifyResult* verify_result_;
|
||||
net::CompletionOnceCallback callback_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(Response);
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
class CertVerifierRequest : public AtomCertVerifier::Request {
|
||||
public:
|
||||
CertVerifierRequest(const AtomCertVerifier::RequestParams& params,
|
||||
AtomCertVerifier* cert_verifier)
|
||||
: params_(params),
|
||||
cert_verifier_(cert_verifier),
|
||||
weak_ptr_factory_(this) {}
|
||||
|
||||
~CertVerifierRequest() override {
|
||||
cert_verifier_->RemoveRequest(params_);
|
||||
default_verifier_request_.reset();
|
||||
while (!response_list_.empty() && !first_response_) {
|
||||
base::LinkNode<Response>* response_node = response_list_.head();
|
||||
response_node->RemoveFromList();
|
||||
Response* response = response_node->value();
|
||||
RunResponse(response);
|
||||
}
|
||||
cert_verifier_ = nullptr;
|
||||
weak_ptr_factory_.InvalidateWeakPtrs();
|
||||
}
|
||||
|
||||
void RunResponse(Response* response) {
|
||||
if (custom_response_ == net::ERR_ABORTED) {
|
||||
*(response->verify_result()) = result_;
|
||||
response->callback().Run(error_);
|
||||
} else {
|
||||
response->verify_result()->Reset();
|
||||
response->verify_result()->verified_cert = params_.certificate();
|
||||
cert_verifier_->ct_delegate()->AddCTExcludedHost(params_.hostname());
|
||||
response->callback().Run(custom_response_);
|
||||
}
|
||||
delete response;
|
||||
}
|
||||
|
||||
void Start(const net::NetLogWithSource& net_log) {
|
||||
int error = cert_verifier_->default_verifier()->Verify(
|
||||
params_, &result_,
|
||||
base::Bind(&CertVerifierRequest::OnDefaultVerificationDone,
|
||||
weak_ptr_factory_.GetWeakPtr()),
|
||||
&default_verifier_request_, net_log);
|
||||
if (error != net::ERR_IO_PENDING)
|
||||
OnDefaultVerificationDone(error);
|
||||
}
|
||||
|
||||
void OnDefaultVerificationDone(int error) {
|
||||
error_ = error;
|
||||
auto request = std::make_unique<VerifyRequestParams>();
|
||||
request->hostname = params_.hostname();
|
||||
request->default_result = net::ErrorToString(error);
|
||||
request->error_code = error;
|
||||
request->certificate = params_.certificate();
|
||||
auto response_callback = base::Bind(&CertVerifierRequest::OnResponseInUI,
|
||||
weak_ptr_factory_.GetWeakPtr());
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::UI},
|
||||
base::BindOnce(&CertVerifierRequest::OnVerifyRequestInUI,
|
||||
cert_verifier_->verify_proc(), std::move(request),
|
||||
response_callback));
|
||||
}
|
||||
|
||||
static void OnVerifyRequestInUI(
|
||||
const AtomCertVerifier::VerifyProc& verify_proc,
|
||||
std::unique_ptr<VerifyRequestParams> request,
|
||||
const base::Callback<void(int)>& response_callback) {
|
||||
verify_proc.Run(*(request.get()), response_callback);
|
||||
}
|
||||
|
||||
static void OnResponseInUI(base::WeakPtr<CertVerifierRequest> self,
|
||||
int result) {
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(&CertVerifierRequest::NotifyResponseInIO, self, result));
|
||||
}
|
||||
|
||||
void NotifyResponseInIO(int result) {
|
||||
custom_response_ = result;
|
||||
first_response_ = false;
|
||||
// Responding to first request in the list will initiate destruction of
|
||||
// the class, respond to others in the list inside destructor.
|
||||
base::LinkNode<Response>* response_node = response_list_.head();
|
||||
response_node->RemoveFromList();
|
||||
Response* response = response_node->value();
|
||||
RunResponse(response);
|
||||
}
|
||||
|
||||
void AddResponseListener(net::CertVerifyResult* verify_result,
|
||||
net::CompletionOnceCallback callback) {
|
||||
response_list_.Append(new Response(verify_result, std::move(callback)));
|
||||
}
|
||||
|
||||
const AtomCertVerifier::RequestParams& params() const { return params_; }
|
||||
|
||||
private:
|
||||
using ResponseList = base::LinkedList<Response>;
|
||||
|
||||
const AtomCertVerifier::RequestParams params_;
|
||||
AtomCertVerifier* cert_verifier_;
|
||||
int error_ = net::ERR_IO_PENDING;
|
||||
int custom_response_ = net::ERR_IO_PENDING;
|
||||
bool first_response_ = true;
|
||||
ResponseList response_list_;
|
||||
net::CertVerifyResult result_;
|
||||
std::unique_ptr<AtomCertVerifier::Request> default_verifier_request_;
|
||||
base::WeakPtrFactory<CertVerifierRequest> weak_ptr_factory_;
|
||||
};
|
||||
|
||||
AtomCertVerifier::AtomCertVerifier(RequireCTDelegate* ct_delegate)
|
||||
: default_cert_verifier_(net::CertVerifier::CreateDefault()),
|
||||
ct_delegate_(ct_delegate) {}
|
||||
|
||||
AtomCertVerifier::~AtomCertVerifier() {}
|
||||
|
||||
void AtomCertVerifier::SetVerifyProc(const VerifyProc& proc) {
|
||||
verify_proc_ = proc;
|
||||
}
|
||||
|
||||
int AtomCertVerifier::Verify(const RequestParams& params,
|
||||
net::CertVerifyResult* verify_result,
|
||||
net::CompletionOnceCallback callback,
|
||||
std::unique_ptr<Request>* out_req,
|
||||
const net::NetLogWithSource& net_log) {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
|
||||
if (verify_proc_.is_null()) {
|
||||
ct_delegate_->ClearCTExcludedHostsList();
|
||||
return default_cert_verifier_->Verify(
|
||||
params, verify_result, std::move(callback), out_req, net_log);
|
||||
} else {
|
||||
CertVerifierRequest* request = FindRequest(params);
|
||||
if (!request) {
|
||||
out_req->reset();
|
||||
auto new_request = std::make_unique<CertVerifierRequest>(params, this);
|
||||
new_request->Start(net_log);
|
||||
request = new_request.get();
|
||||
*out_req = std::move(new_request);
|
||||
inflight_requests_[params] = request;
|
||||
}
|
||||
request->AddResponseListener(verify_result, std::move(callback));
|
||||
|
||||
return net::ERR_IO_PENDING;
|
||||
}
|
||||
}
|
||||
|
||||
void AtomCertVerifier::SetConfig(const Config& config) {
|
||||
default_cert_verifier_->SetConfig(config);
|
||||
}
|
||||
|
||||
void AtomCertVerifier::RemoveRequest(const RequestParams& params) {
|
||||
auto it = inflight_requests_.find(params);
|
||||
if (it != inflight_requests_.end())
|
||||
inflight_requests_.erase(it);
|
||||
}
|
||||
|
||||
CertVerifierRequest* AtomCertVerifier::FindRequest(
|
||||
const RequestParams& params) {
|
||||
auto it = inflight_requests_.find(params);
|
||||
if (it != inflight_requests_.end())
|
||||
return it->second;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,71 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_ATOM_CERT_VERIFIER_H_
|
||||
#define ATOM_BROWSER_NET_ATOM_CERT_VERIFIER_H_
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "net/cert/cert_verifier.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class CertVerifierRequest;
|
||||
class RequireCTDelegate;
|
||||
|
||||
struct VerifyRequestParams {
|
||||
std::string hostname;
|
||||
std::string default_result;
|
||||
int error_code;
|
||||
scoped_refptr<net::X509Certificate> certificate;
|
||||
|
||||
VerifyRequestParams();
|
||||
VerifyRequestParams(const VerifyRequestParams&);
|
||||
~VerifyRequestParams();
|
||||
};
|
||||
|
||||
class AtomCertVerifier : public net::CertVerifier {
|
||||
public:
|
||||
explicit AtomCertVerifier(RequireCTDelegate* ct_delegate);
|
||||
~AtomCertVerifier() override;
|
||||
|
||||
using VerifyProc = base::Callback<void(const VerifyRequestParams& request,
|
||||
net::CompletionOnceCallback)>;
|
||||
|
||||
void SetVerifyProc(const VerifyProc& proc);
|
||||
|
||||
const VerifyProc verify_proc() const { return verify_proc_; }
|
||||
RequireCTDelegate* ct_delegate() const { return ct_delegate_; }
|
||||
net::CertVerifier* default_verifier() const {
|
||||
return default_cert_verifier_.get();
|
||||
}
|
||||
|
||||
protected:
|
||||
// net::CertVerifier:
|
||||
int Verify(const RequestParams& params,
|
||||
net::CertVerifyResult* verify_result,
|
||||
net::CompletionOnceCallback callback,
|
||||
std::unique_ptr<Request>* out_req,
|
||||
const net::NetLogWithSource& net_log) override;
|
||||
void SetConfig(const Config& config) override;
|
||||
|
||||
private:
|
||||
friend class CertVerifierRequest;
|
||||
|
||||
void RemoveRequest(const RequestParams& params);
|
||||
CertVerifierRequest* FindRequest(const RequestParams& params);
|
||||
|
||||
std::map<RequestParams, CertVerifierRequest*> inflight_requests_;
|
||||
VerifyProc verify_proc_;
|
||||
std::unique_ptr<net::CertVerifier> default_cert_verifier_;
|
||||
RequireCTDelegate* ct_delegate_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(AtomCertVerifier);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_ATOM_CERT_VERIFIER_H_
|
||||
@@ -1,546 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/atom_network_delegate.h"
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/api/atom_api_web_contents.h"
|
||||
#include "atom/browser/login_handler.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "atom/common/options_switches.h"
|
||||
#include "base/command_line.h"
|
||||
#include "base/stl_util.h"
|
||||
#include "base/strings/string_util.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "content/public/browser/render_frame_host.h"
|
||||
#include "content/public/browser/resource_request_info.h"
|
||||
#include "net/base/load_flags.h"
|
||||
#include "net/base/net_errors.h"
|
||||
#include "net/url_request/url_request.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace atom {
|
||||
|
||||
const char* ResourceTypeToString(content::ResourceType type) {
|
||||
switch (type) {
|
||||
case content::RESOURCE_TYPE_MAIN_FRAME:
|
||||
return "mainFrame";
|
||||
case content::RESOURCE_TYPE_SUB_FRAME:
|
||||
return "subFrame";
|
||||
case content::RESOURCE_TYPE_STYLESHEET:
|
||||
return "stylesheet";
|
||||
case content::RESOURCE_TYPE_SCRIPT:
|
||||
return "script";
|
||||
case content::RESOURCE_TYPE_IMAGE:
|
||||
return "image";
|
||||
case content::RESOURCE_TYPE_OBJECT:
|
||||
return "object";
|
||||
case content::RESOURCE_TYPE_XHR:
|
||||
return "xhr";
|
||||
default:
|
||||
return "other";
|
||||
}
|
||||
}
|
||||
|
||||
int32_t GetWebContentsID(int process_id, int frame_id) {
|
||||
auto* webContents = content::WebContents::FromRenderFrameHost(
|
||||
content::RenderFrameHost::FromID(process_id, frame_id));
|
||||
return atom::api::WebContents::GetIDFromWrappedClass(webContents);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
using ResponseHeadersContainer =
|
||||
std::pair<scoped_refptr<net::HttpResponseHeaders>*, const std::string&>;
|
||||
|
||||
void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener,
|
||||
std::unique_ptr<base::DictionaryValue> details,
|
||||
int render_process_id,
|
||||
int render_frame_id) {
|
||||
int32_t id = GetWebContentsID(render_process_id, render_frame_id);
|
||||
// id must be greater than zero
|
||||
if (id)
|
||||
details->SetInteger("webContentsId", id);
|
||||
return listener.Run(*(details.get()));
|
||||
}
|
||||
|
||||
void RunResponseListener(
|
||||
const AtomNetworkDelegate::ResponseListener& listener,
|
||||
std::unique_ptr<base::DictionaryValue> details,
|
||||
int render_process_id,
|
||||
int render_frame_id,
|
||||
const AtomNetworkDelegate::ResponseCallback& callback) {
|
||||
int32_t id = GetWebContentsID(render_process_id, render_frame_id);
|
||||
// id must be greater than zero
|
||||
if (id)
|
||||
details->SetInteger("webContentsId", id);
|
||||
return listener.Run(*(details.get()), callback);
|
||||
}
|
||||
|
||||
// Test whether the URL of |request| matches |patterns|.
|
||||
bool MatchesFilterCondition(net::URLRequest* request,
|
||||
const URLPatterns& patterns) {
|
||||
if (patterns.empty())
|
||||
return true;
|
||||
|
||||
for (const auto& pattern : patterns) {
|
||||
if (pattern.MatchesURL(request->url()))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Overloaded by multiple types to fill the |details| object.
|
||||
void ToDictionary(base::DictionaryValue* details, net::URLRequest* request) {
|
||||
FillRequestDetails(details, request);
|
||||
details->SetInteger("id", request->identifier());
|
||||
details->SetDouble("timestamp", base::Time::Now().ToDoubleT() * 1000);
|
||||
auto* info = content::ResourceRequestInfo::ForRequest(request);
|
||||
if (info) {
|
||||
details->SetString("resourceType",
|
||||
ResourceTypeToString(info->GetResourceType()));
|
||||
} else {
|
||||
details->SetString("resourceType", "other");
|
||||
}
|
||||
}
|
||||
|
||||
void ToDictionary(base::DictionaryValue* details,
|
||||
const net::HttpRequestHeaders& headers) {
|
||||
auto dict = std::make_unique<base::DictionaryValue>();
|
||||
net::HttpRequestHeaders::Iterator it(headers);
|
||||
while (it.GetNext())
|
||||
dict->SetKey(it.name(), base::Value(it.value()));
|
||||
details->Set("requestHeaders", std::move(dict));
|
||||
}
|
||||
|
||||
void ToDictionary(base::DictionaryValue* details,
|
||||
const net::HttpResponseHeaders* headers) {
|
||||
if (!headers)
|
||||
return;
|
||||
|
||||
auto dict = std::make_unique<base::DictionaryValue>();
|
||||
size_t iter = 0;
|
||||
std::string key;
|
||||
std::string value;
|
||||
while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
|
||||
if (dict->FindKey(key)) {
|
||||
base::ListValue* values = nullptr;
|
||||
if (dict->GetList(key, &values))
|
||||
values->AppendString(value);
|
||||
} else {
|
||||
auto values = std::make_unique<base::ListValue>();
|
||||
values->AppendString(value);
|
||||
dict->Set(key, std::move(values));
|
||||
}
|
||||
}
|
||||
details->Set("responseHeaders", std::move(dict));
|
||||
details->SetString("statusLine", headers->GetStatusLine());
|
||||
details->SetInteger("statusCode", headers->response_code());
|
||||
}
|
||||
|
||||
void ToDictionary(base::DictionaryValue* details, const GURL& location) {
|
||||
details->SetString("redirectURL", location.spec());
|
||||
}
|
||||
|
||||
void ToDictionary(base::DictionaryValue* details,
|
||||
const net::IPEndPoint& remote_endpoint) {
|
||||
details->SetString("ip", remote_endpoint.ToStringWithoutPort());
|
||||
}
|
||||
|
||||
void ToDictionary(base::DictionaryValue* details, bool from_cache) {
|
||||
details->SetBoolean("fromCache", from_cache);
|
||||
}
|
||||
|
||||
void ToDictionary(base::DictionaryValue* details,
|
||||
const net::URLRequestStatus& status) {
|
||||
details->SetString("error", net::ErrorToString(status.error()));
|
||||
}
|
||||
|
||||
// Helper function to fill |details| with arbitrary |args|.
|
||||
template <typename Arg>
|
||||
void FillDetailsObject(base::DictionaryValue* details, Arg arg) {
|
||||
ToDictionary(details, arg);
|
||||
}
|
||||
|
||||
template <typename Arg, typename... Args>
|
||||
void FillDetailsObject(base::DictionaryValue* details, Arg arg, Args... args) {
|
||||
ToDictionary(details, arg);
|
||||
FillDetailsObject(details, args...);
|
||||
}
|
||||
|
||||
// Fill the native types with the result from the response object.
|
||||
void ReadFromResponseObject(const base::DictionaryValue& response,
|
||||
GURL* new_location) {
|
||||
std::string url;
|
||||
if (response.GetString("redirectURL", &url))
|
||||
*new_location = GURL(url);
|
||||
}
|
||||
|
||||
void ReadFromResponseObject(const base::DictionaryValue& response,
|
||||
net::HttpRequestHeaders* headers) {
|
||||
const base::DictionaryValue* dict;
|
||||
if (response.GetDictionary("requestHeaders", &dict)) {
|
||||
headers->Clear();
|
||||
for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd();
|
||||
it.Advance()) {
|
||||
if (it.value().is_string()) {
|
||||
std::string value = it.value().GetString();
|
||||
headers->SetHeader(it.key(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ReadFromResponseObject(const base::DictionaryValue& response,
|
||||
const ResponseHeadersContainer& container) {
|
||||
const base::DictionaryValue* dict;
|
||||
std::string status_line;
|
||||
if (!response.GetString("statusLine", &status_line))
|
||||
status_line = container.second;
|
||||
if (response.GetDictionary("responseHeaders", &dict)) {
|
||||
auto* headers = container.first;
|
||||
*headers = new net::HttpResponseHeaders("");
|
||||
(*headers)->ReplaceStatusLine(status_line);
|
||||
for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd();
|
||||
it.Advance()) {
|
||||
const base::ListValue* list;
|
||||
if (it.value().GetAsList(&list)) {
|
||||
(*headers)->RemoveHeader(it.key());
|
||||
for (size_t i = 0; i < list->GetSize(); ++i) {
|
||||
std::string value;
|
||||
if (list->GetString(i, &value))
|
||||
(*headers)->AddHeader(it.key() + " : " + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
AtomNetworkDelegate::SimpleListenerInfo::SimpleListenerInfo(
|
||||
URLPatterns patterns_,
|
||||
SimpleListener listener_)
|
||||
: url_patterns(patterns_), listener(listener_) {}
|
||||
AtomNetworkDelegate::SimpleListenerInfo::SimpleListenerInfo() = default;
|
||||
AtomNetworkDelegate::SimpleListenerInfo::~SimpleListenerInfo() = default;
|
||||
|
||||
AtomNetworkDelegate::ResponseListenerInfo::ResponseListenerInfo(
|
||||
URLPatterns patterns_,
|
||||
ResponseListener listener_)
|
||||
: url_patterns(patterns_), listener(listener_) {}
|
||||
AtomNetworkDelegate::ResponseListenerInfo::ResponseListenerInfo() = default;
|
||||
AtomNetworkDelegate::ResponseListenerInfo::~ResponseListenerInfo() = default;
|
||||
|
||||
AtomNetworkDelegate::AtomNetworkDelegate() {
|
||||
auto* command_line = base::CommandLine::ForCurrentProcess();
|
||||
if (command_line->HasSwitch(switches::kIgnoreConnectionsLimit)) {
|
||||
std::string value =
|
||||
command_line->GetSwitchValueASCII(switches::kIgnoreConnectionsLimit);
|
||||
ignore_connections_limit_domains_ = base::SplitString(
|
||||
value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
|
||||
}
|
||||
}
|
||||
|
||||
AtomNetworkDelegate::~AtomNetworkDelegate() {}
|
||||
|
||||
void AtomNetworkDelegate::SetSimpleListenerInIO(SimpleEvent type,
|
||||
URLPatterns patterns,
|
||||
SimpleListener callback) {
|
||||
if (callback.is_null())
|
||||
simple_listeners_.erase(type);
|
||||
else
|
||||
simple_listeners_[type] = {std::move(patterns), std::move(callback)};
|
||||
}
|
||||
|
||||
void AtomNetworkDelegate::SetResponseListenerInIO(ResponseEvent type,
|
||||
URLPatterns patterns,
|
||||
ResponseListener callback) {
|
||||
if (callback.is_null())
|
||||
response_listeners_.erase(type);
|
||||
else
|
||||
response_listeners_[type] = {std::move(patterns), std::move(callback)};
|
||||
}
|
||||
|
||||
int AtomNetworkDelegate::OnBeforeURLRequest(
|
||||
net::URLRequest* request,
|
||||
net::CompletionOnceCallback callback,
|
||||
GURL* new_url) {
|
||||
if (!base::ContainsKey(response_listeners_, kOnBeforeRequest)) {
|
||||
for (const auto& domain : ignore_connections_limit_domains_) {
|
||||
if (request->url().DomainIs(domain)) {
|
||||
// Allow unlimited concurrent connections.
|
||||
request->SetPriority(net::MAXIMUM_PRIORITY);
|
||||
request->SetLoadFlags(request->load_flags() | net::LOAD_IGNORE_LIMITS);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return net::OK;
|
||||
}
|
||||
|
||||
return HandleResponseEvent(kOnBeforeRequest, request, std::move(callback),
|
||||
new_url);
|
||||
}
|
||||
|
||||
int AtomNetworkDelegate::OnBeforeStartTransaction(
|
||||
net::URLRequest* request,
|
||||
net::CompletionOnceCallback callback,
|
||||
net::HttpRequestHeaders* headers) {
|
||||
if (!base::ContainsKey(response_listeners_, kOnBeforeSendHeaders))
|
||||
return net::OK;
|
||||
|
||||
return HandleResponseEvent(kOnBeforeSendHeaders, request, std::move(callback),
|
||||
headers, *headers);
|
||||
}
|
||||
|
||||
void AtomNetworkDelegate::OnStartTransaction(
|
||||
net::URLRequest* request,
|
||||
const net::HttpRequestHeaders& headers) {
|
||||
if (!base::ContainsKey(simple_listeners_, kOnSendHeaders))
|
||||
return;
|
||||
|
||||
HandleSimpleEvent(kOnSendHeaders, request, headers);
|
||||
}
|
||||
|
||||
int AtomNetworkDelegate::OnHeadersReceived(
|
||||
net::URLRequest* request,
|
||||
net::CompletionOnceCallback callback,
|
||||
const net::HttpResponseHeaders* original,
|
||||
scoped_refptr<net::HttpResponseHeaders>* override,
|
||||
GURL* allowed) {
|
||||
if (!base::ContainsKey(response_listeners_, kOnHeadersReceived))
|
||||
return net::OK;
|
||||
|
||||
return HandleResponseEvent(
|
||||
kOnHeadersReceived, request, std::move(callback),
|
||||
std::make_pair(override, original->GetStatusLine()), original);
|
||||
}
|
||||
|
||||
void AtomNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
|
||||
const GURL& new_location) {
|
||||
if (!base::ContainsKey(simple_listeners_, kOnBeforeRedirect))
|
||||
return;
|
||||
|
||||
HandleSimpleEvent(
|
||||
kOnBeforeRedirect, request, new_location, request->response_headers(),
|
||||
request->GetResponseRemoteEndpoint(), request->was_cached());
|
||||
}
|
||||
|
||||
void AtomNetworkDelegate::OnResponseStarted(net::URLRequest* request,
|
||||
int net_error) {
|
||||
if (!base::ContainsKey(simple_listeners_, kOnResponseStarted))
|
||||
return;
|
||||
|
||||
if (request->status().status() != net::URLRequestStatus::SUCCESS)
|
||||
return;
|
||||
|
||||
HandleSimpleEvent(kOnResponseStarted, request, request->response_headers(),
|
||||
request->was_cached());
|
||||
}
|
||||
|
||||
void AtomNetworkDelegate::OnCompleted(net::URLRequest* request,
|
||||
bool started,
|
||||
int net_error) {
|
||||
// OnCompleted may happen before other events.
|
||||
callbacks_.erase(request->identifier());
|
||||
|
||||
if (request->status().status() == net::URLRequestStatus::FAILED ||
|
||||
request->status().status() == net::URLRequestStatus::CANCELED) {
|
||||
// Error event.
|
||||
OnErrorOccurred(request, started, net_error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (request->response_headers() &&
|
||||
net::HttpResponseHeaders::IsRedirectResponseCode(
|
||||
request->response_headers()->response_code())) {
|
||||
// Redirect event.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!base::ContainsKey(simple_listeners_, kOnCompleted))
|
||||
return;
|
||||
|
||||
HandleSimpleEvent(kOnCompleted, request, request->response_headers(),
|
||||
request->was_cached());
|
||||
}
|
||||
|
||||
void AtomNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {
|
||||
const auto& it = login_handler_map_.find(request->identifier());
|
||||
if (it != login_handler_map_.end()) {
|
||||
it->second->NotifyRequestDestroyed();
|
||||
it->second = nullptr;
|
||||
login_handler_map_.erase(it);
|
||||
}
|
||||
callbacks_.erase(request->identifier());
|
||||
}
|
||||
|
||||
net::NetworkDelegate::AuthRequiredResponse AtomNetworkDelegate::OnAuthRequired(
|
||||
net::URLRequest* request,
|
||||
const net::AuthChallengeInfo& auth_info,
|
||||
AuthCallback callback,
|
||||
net::AuthCredentials* credentials) {
|
||||
auto* resource_request_info =
|
||||
content::ResourceRequestInfo::ForRequest(request);
|
||||
if (!resource_request_info)
|
||||
return AUTH_REQUIRED_RESPONSE_NO_ACTION;
|
||||
login_handler_map_.emplace(
|
||||
request->identifier(),
|
||||
new LoginHandler(request, auth_info, std::move(callback), credentials,
|
||||
resource_request_info));
|
||||
return AUTH_REQUIRED_RESPONSE_IO_PENDING;
|
||||
}
|
||||
|
||||
bool AtomNetworkDelegate::OnCanGetCookies(const net::URLRequest& request,
|
||||
const net::CookieList& cookie_list,
|
||||
bool allowed_from_caller) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AtomNetworkDelegate::OnCanSetCookie(
|
||||
const net::URLRequest& request,
|
||||
const net::CanonicalCookie& cookie_line,
|
||||
net::CookieOptions* options,
|
||||
bool allowed_from_caller) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AtomNetworkDelegate::OnCanAccessFile(
|
||||
const net::URLRequest& request,
|
||||
const base::FilePath& original_path,
|
||||
const base::FilePath& absolute_path) const {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AtomNetworkDelegate::OnForcePrivacyMode(
|
||||
const GURL& url,
|
||||
const GURL& first_party_for_cookies) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool AtomNetworkDelegate::OnCancelURLRequestWithPolicyViolatingReferrerHeader(
|
||||
const net::URLRequest& request,
|
||||
const GURL& target_url,
|
||||
const GURL& referrer_url) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
// TODO(deepak1556) : Enable after hooking into the reporting service
|
||||
// https://crbug.com/704259
|
||||
bool AtomNetworkDelegate::OnCanQueueReportingReport(
|
||||
const url::Origin& origin) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
void AtomNetworkDelegate::OnCanSendReportingReports(
|
||||
std::set<url::Origin> origins,
|
||||
base::OnceCallback<void(std::set<url::Origin>)> result_callback) const {}
|
||||
|
||||
bool AtomNetworkDelegate::OnCanSetReportingClient(const url::Origin& origin,
|
||||
const GURL& endpoint) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool AtomNetworkDelegate::OnCanUseReportingClient(const url::Origin& origin,
|
||||
const GURL& endpoint) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
void AtomNetworkDelegate::OnErrorOccurred(net::URLRequest* request,
|
||||
bool started,
|
||||
int net_error) {
|
||||
if (!base::ContainsKey(simple_listeners_, kOnErrorOccurred))
|
||||
return;
|
||||
|
||||
HandleSimpleEvent(kOnErrorOccurred, request, request->was_cached(),
|
||||
request->status());
|
||||
}
|
||||
|
||||
template <typename Out, typename... Args>
|
||||
int AtomNetworkDelegate::HandleResponseEvent(
|
||||
ResponseEvent type,
|
||||
net::URLRequest* request,
|
||||
net::CompletionOnceCallback callback,
|
||||
Out out,
|
||||
Args... args) {
|
||||
const auto& info = response_listeners_[type];
|
||||
if (!MatchesFilterCondition(request, info.url_patterns))
|
||||
return net::OK;
|
||||
|
||||
auto details = std::make_unique<base::DictionaryValue>();
|
||||
FillDetailsObject(details.get(), request, args...);
|
||||
|
||||
int render_process_id, render_frame_id;
|
||||
content::ResourceRequestInfo::GetRenderFrameForRequest(
|
||||
request, &render_process_id, &render_frame_id);
|
||||
|
||||
// The |request| could be destroyed before the |callback| is called.
|
||||
callbacks_[request->identifier()] = std::move(callback);
|
||||
|
||||
ResponseCallback response =
|
||||
base::Bind(&AtomNetworkDelegate::OnListenerResultInUI<Out>,
|
||||
base::Unretained(this), request->identifier(), out);
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::UI},
|
||||
base::BindOnce(RunResponseListener, info.listener, std::move(details),
|
||||
render_process_id, render_frame_id, response));
|
||||
return net::ERR_IO_PENDING;
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void AtomNetworkDelegate::HandleSimpleEvent(SimpleEvent type,
|
||||
net::URLRequest* request,
|
||||
Args... args) {
|
||||
const auto& info = simple_listeners_[type];
|
||||
if (!MatchesFilterCondition(request, info.url_patterns))
|
||||
return;
|
||||
|
||||
auto details = std::make_unique<base::DictionaryValue>();
|
||||
FillDetailsObject(details.get(), request, args...);
|
||||
|
||||
int render_process_id, render_frame_id;
|
||||
content::ResourceRequestInfo::GetRenderFrameForRequest(
|
||||
request, &render_process_id, &render_frame_id);
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::UI},
|
||||
base::BindOnce(RunSimpleListener, info.listener, std::move(details),
|
||||
render_process_id, render_frame_id));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void AtomNetworkDelegate::OnListenerResultInIO(
|
||||
uint64_t id,
|
||||
T out,
|
||||
std::unique_ptr<base::DictionaryValue> response) {
|
||||
// The request has been destroyed.
|
||||
if (!base::ContainsKey(callbacks_, id))
|
||||
return;
|
||||
|
||||
ReadFromResponseObject(*response, out);
|
||||
|
||||
bool cancel = false;
|
||||
response->GetBoolean("cancel", &cancel);
|
||||
std::move(callbacks_[id]).Run(cancel ? net::ERR_BLOCKED_BY_CLIENT : net::OK);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void AtomNetworkDelegate::OnListenerResultInUI(
|
||||
uint64_t id,
|
||||
T out,
|
||||
const base::DictionaryValue& response) {
|
||||
auto copy = base::DictionaryValue::From(
|
||||
base::Value::ToUniquePtrValue(response.Clone()));
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(&AtomNetworkDelegate::OnListenerResultInIO<T>,
|
||||
base::Unretained(this), id, out, std::move(copy)));
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,180 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_ATOM_NETWORK_DELEGATE_H_
|
||||
#define ATOM_BROWSER_NET_ATOM_NETWORK_DELEGATE_H_
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "base/callback.h"
|
||||
#include "base/synchronization/lock.h"
|
||||
#include "base/values.h"
|
||||
#include "content/public/browser/resource_request_info.h"
|
||||
#include "extensions/common/url_pattern.h"
|
||||
#include "net/base/network_delegate.h"
|
||||
#include "net/http/http_request_headers.h"
|
||||
#include "net/http/http_response_headers.h"
|
||||
|
||||
class URLPattern;
|
||||
|
||||
namespace atom {
|
||||
|
||||
using URLPatterns = std::set<URLPattern>;
|
||||
|
||||
const char* ResourceTypeToString(content::ResourceType type);
|
||||
|
||||
class LoginHandler;
|
||||
|
||||
class AtomNetworkDelegate : public net::NetworkDelegate {
|
||||
public:
|
||||
using ResponseCallback = base::Callback<void(const base::DictionaryValue&)>;
|
||||
using SimpleListener = base::Callback<void(const base::DictionaryValue&)>;
|
||||
using ResponseListener = base::Callback<void(const base::DictionaryValue&,
|
||||
const ResponseCallback&)>;
|
||||
|
||||
enum SimpleEvent {
|
||||
kOnSendHeaders,
|
||||
kOnBeforeRedirect,
|
||||
kOnResponseStarted,
|
||||
kOnCompleted,
|
||||
kOnErrorOccurred,
|
||||
};
|
||||
|
||||
enum ResponseEvent {
|
||||
kOnBeforeRequest,
|
||||
kOnBeforeSendHeaders,
|
||||
kOnHeadersReceived,
|
||||
};
|
||||
|
||||
struct SimpleListenerInfo {
|
||||
URLPatterns url_patterns;
|
||||
SimpleListener listener;
|
||||
|
||||
SimpleListenerInfo(URLPatterns, SimpleListener);
|
||||
SimpleListenerInfo();
|
||||
~SimpleListenerInfo();
|
||||
};
|
||||
|
||||
struct ResponseListenerInfo {
|
||||
URLPatterns url_patterns;
|
||||
ResponseListener listener;
|
||||
|
||||
ResponseListenerInfo(URLPatterns, ResponseListener);
|
||||
ResponseListenerInfo();
|
||||
~ResponseListenerInfo();
|
||||
};
|
||||
|
||||
AtomNetworkDelegate();
|
||||
~AtomNetworkDelegate() override;
|
||||
|
||||
void SetSimpleListenerInIO(SimpleEvent type,
|
||||
URLPatterns patterns,
|
||||
SimpleListener callback);
|
||||
void SetResponseListenerInIO(ResponseEvent type,
|
||||
URLPatterns patterns,
|
||||
ResponseListener callback);
|
||||
|
||||
protected:
|
||||
// net::NetworkDelegate:
|
||||
int OnBeforeURLRequest(net::URLRequest* request,
|
||||
net::CompletionOnceCallback callback,
|
||||
GURL* new_url) override;
|
||||
int OnBeforeStartTransaction(net::URLRequest* request,
|
||||
net::CompletionOnceCallback callback,
|
||||
net::HttpRequestHeaders* headers) override;
|
||||
void OnBeforeSendHeaders(net::URLRequest* request,
|
||||
const net::ProxyInfo& proxy_info,
|
||||
const net::ProxyRetryInfoMap& proxy_retry_info,
|
||||
net::HttpRequestHeaders* headers) override {}
|
||||
void OnStartTransaction(net::URLRequest* request,
|
||||
const net::HttpRequestHeaders& headers) override;
|
||||
int OnHeadersReceived(
|
||||
net::URLRequest* request,
|
||||
net::CompletionOnceCallback callback,
|
||||
const net::HttpResponseHeaders* original_response_headers,
|
||||
scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
|
||||
GURL* allowed_unsafe_redirect_url) override;
|
||||
void OnBeforeRedirect(net::URLRequest* request,
|
||||
const GURL& new_location) override;
|
||||
void OnResponseStarted(net::URLRequest* request, int net_error) override;
|
||||
void OnNetworkBytesReceived(net::URLRequest* request,
|
||||
int64_t bytes_read) override {}
|
||||
void OnNetworkBytesSent(net::URLRequest* request,
|
||||
int64_t bytes_sent) override {}
|
||||
void OnCompleted(net::URLRequest* request,
|
||||
bool started,
|
||||
int net_error) override;
|
||||
void OnURLRequestDestroyed(net::URLRequest* request) override;
|
||||
void OnPACScriptError(int line_number, const base::string16& error) override {
|
||||
}
|
||||
AuthRequiredResponse OnAuthRequired(
|
||||
net::URLRequest* request,
|
||||
const net::AuthChallengeInfo& auth_info,
|
||||
AuthCallback callback,
|
||||
net::AuthCredentials* credentials) override;
|
||||
bool OnCanGetCookies(const net::URLRequest& request,
|
||||
const net::CookieList& cookie_list,
|
||||
bool allowed_from_caller) override;
|
||||
bool OnCanSetCookie(const net::URLRequest& request,
|
||||
const net::CanonicalCookie& cookie_line,
|
||||
net::CookieOptions* options,
|
||||
bool allowed_from_caller) override;
|
||||
bool OnCanAccessFile(const net::URLRequest& request,
|
||||
const base::FilePath& original_path,
|
||||
const base::FilePath& absolute_path) const override;
|
||||
bool OnForcePrivacyMode(const GURL& url,
|
||||
const GURL& first_party_for_cookies) const override;
|
||||
bool OnCancelURLRequestWithPolicyViolatingReferrerHeader(
|
||||
const net::URLRequest& request,
|
||||
const GURL& target_url,
|
||||
const GURL& referrer_url) const override;
|
||||
bool OnCanQueueReportingReport(const url::Origin& origin) const override;
|
||||
void OnCanSendReportingReports(std::set<url::Origin> origins,
|
||||
base::OnceCallback<void(std::set<url::Origin>)>
|
||||
result_callback) const override;
|
||||
bool OnCanSetReportingClient(const url::Origin& origin,
|
||||
const GURL& endpoint) const override;
|
||||
bool OnCanUseReportingClient(const url::Origin& origin,
|
||||
const GURL& endpoint) const override;
|
||||
|
||||
private:
|
||||
void OnErrorOccurred(net::URLRequest* request, bool started, int net_error);
|
||||
|
||||
template <typename... Args>
|
||||
void HandleSimpleEvent(SimpleEvent type,
|
||||
net::URLRequest* request,
|
||||
Args... args);
|
||||
template <typename Out, typename... Args>
|
||||
int HandleResponseEvent(ResponseEvent type,
|
||||
net::URLRequest* request,
|
||||
net::CompletionOnceCallback callback,
|
||||
Out out,
|
||||
Args... args);
|
||||
|
||||
// Deal with the results of Listener.
|
||||
template <typename T>
|
||||
void OnListenerResultInIO(uint64_t id,
|
||||
T out,
|
||||
std::unique_ptr<base::DictionaryValue> response);
|
||||
template <typename T>
|
||||
void OnListenerResultInUI(uint64_t id,
|
||||
T out,
|
||||
const base::DictionaryValue& response);
|
||||
|
||||
std::map<uint64_t, scoped_refptr<LoginHandler>> login_handler_map_;
|
||||
std::map<SimpleEvent, SimpleListenerInfo> simple_listeners_;
|
||||
std::map<ResponseEvent, ResponseListenerInfo> response_listeners_;
|
||||
std::map<uint64_t, net::CompletionOnceCallback> callbacks_;
|
||||
std::vector<std::string> ignore_connections_limit_domains_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(AtomNetworkDelegate);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_ATOM_NETWORK_DELEGATE_H_
|
||||
@@ -1,521 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/atom_url_request.h"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/api/atom_api_url_request.h"
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "atom/browser/net/atom_url_request_job_factory.h"
|
||||
#include "base/callback.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "net/base/elements_upload_data_stream.h"
|
||||
#include "net/base/io_buffer.h"
|
||||
#include "net/base/load_flags.h"
|
||||
#include "net/base/upload_bytes_element_reader.h"
|
||||
#include "net/url_request/redirect_info.h"
|
||||
|
||||
namespace {
|
||||
const int kBufferSize = 4096;
|
||||
} // namespace
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace internal {
|
||||
|
||||
class UploadOwnedIOBufferElementReader : public net::UploadBytesElementReader {
|
||||
public:
|
||||
explicit UploadOwnedIOBufferElementReader(
|
||||
scoped_refptr<const net::IOBufferWithSize> buffer)
|
||||
: net::UploadBytesElementReader(buffer->data(), buffer->size()),
|
||||
buffer_(buffer) {}
|
||||
|
||||
~UploadOwnedIOBufferElementReader() override {}
|
||||
|
||||
static UploadOwnedIOBufferElementReader* CreateWithBuffer(
|
||||
scoped_refptr<const net::IOBufferWithSize> buffer) {
|
||||
return new UploadOwnedIOBufferElementReader(std::move(buffer));
|
||||
}
|
||||
|
||||
private:
|
||||
scoped_refptr<const net::IOBuffer> buffer_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(UploadOwnedIOBufferElementReader);
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
AtomURLRequest::AtomURLRequest(api::URLRequest* delegate)
|
||||
: delegate_(delegate),
|
||||
response_read_buffer_(new net::IOBuffer(kBufferSize)) {}
|
||||
|
||||
AtomURLRequest::~AtomURLRequest() {
|
||||
DCHECK(!request_context_getter_);
|
||||
DCHECK(!request_);
|
||||
}
|
||||
|
||||
scoped_refptr<AtomURLRequest> AtomURLRequest::Create(
|
||||
AtomBrowserContext* browser_context,
|
||||
const std::string& method,
|
||||
const std::string& url,
|
||||
const std::string& redirect_policy,
|
||||
api::URLRequest* delegate) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
|
||||
DCHECK(browser_context);
|
||||
DCHECK(!url.empty());
|
||||
DCHECK(delegate);
|
||||
if (!browser_context || url.empty() || !delegate) {
|
||||
return nullptr;
|
||||
}
|
||||
scoped_refptr<net::URLRequestContextGetter> request_context_getter(
|
||||
browser_context->GetRequestContext());
|
||||
DCHECK(request_context_getter);
|
||||
scoped_refptr<AtomURLRequest> atom_url_request(new AtomURLRequest(delegate));
|
||||
if (base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoInitialize, atom_url_request,
|
||||
request_context_getter, method, url,
|
||||
redirect_policy))) {
|
||||
return atom_url_request;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void AtomURLRequest::Terminate() {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
delegate_ = nullptr;
|
||||
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoTerminate, this));
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoInitialize(
|
||||
scoped_refptr<net::URLRequestContextGetter> request_context_getter,
|
||||
const std::string& method,
|
||||
const std::string& url,
|
||||
const std::string& redirect_policy) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
DCHECK(request_context_getter);
|
||||
|
||||
redirect_policy_ = redirect_policy;
|
||||
request_context_getter_ = request_context_getter;
|
||||
request_context_getter_->AddObserver(this);
|
||||
auto* context = request_context_getter_->GetURLRequestContext();
|
||||
if (!context) {
|
||||
// Called after shutdown.
|
||||
DoCancelWithError("Cannot start a request after shutdown.", true);
|
||||
return;
|
||||
}
|
||||
|
||||
DCHECK(context);
|
||||
request_ = context->CreateRequest(
|
||||
GURL(url), net::RequestPriority::DEFAULT_PRIORITY, this);
|
||||
if (!request_) {
|
||||
DoCancelWithError("Failed to create a net::URLRequest.", true);
|
||||
return;
|
||||
}
|
||||
request_->set_method(method);
|
||||
// Do not send cookies from the cookie store.
|
||||
DoSetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES);
|
||||
// Set a flag to stop custom protocol from intercepting this request.
|
||||
request_->SetUserData(DisableProtocolInterceptFlagKey(),
|
||||
base::WrapUnique(new base::SupportsUserData::Data()));
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoTerminate() {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
request_.reset();
|
||||
if (request_context_getter_) {
|
||||
request_context_getter_->RemoveObserver(this);
|
||||
request_context_getter_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
bool AtomURLRequest::Write(scoped_refptr<const net::IOBufferWithSize> buffer,
|
||||
bool is_last) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
return base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoWriteBuffer, this, buffer, is_last));
|
||||
}
|
||||
|
||||
void AtomURLRequest::SetChunkedUpload(bool is_chunked_upload) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
|
||||
// The method can be called only before switching to multi-threaded mode,
|
||||
// i.e. before the first call to write.
|
||||
// So it is safe to change the object in the UI thread.
|
||||
is_chunked_upload_ = is_chunked_upload;
|
||||
}
|
||||
|
||||
void AtomURLRequest::Cancel() {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoCancel, this));
|
||||
}
|
||||
|
||||
void AtomURLRequest::FollowRedirect() {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoFollowRedirect, this));
|
||||
}
|
||||
|
||||
void AtomURLRequest::SetExtraHeader(const std::string& name,
|
||||
const std::string& value) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoSetExtraHeader, this, name, value));
|
||||
}
|
||||
|
||||
void AtomURLRequest::RemoveExtraHeader(const std::string& name) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoRemoveExtraHeader, this, name));
|
||||
}
|
||||
|
||||
void AtomURLRequest::PassLoginInformation(
|
||||
const base::string16& username,
|
||||
const base::string16& password) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
if (username.empty() || password.empty()) {
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoCancelAuth, this));
|
||||
} else {
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoSetAuth, this, username, password));
|
||||
}
|
||||
}
|
||||
|
||||
void AtomURLRequest::SetLoadFlags(int flags) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&AtomURLRequest::DoSetLoadFlags, this, flags));
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoWriteBuffer(
|
||||
scoped_refptr<const net::IOBufferWithSize> buffer,
|
||||
bool is_last) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!request_) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (is_chunked_upload_) {
|
||||
// Chunked encoding case.
|
||||
|
||||
bool first_call = false;
|
||||
if (!chunked_stream_writer_) {
|
||||
std::unique_ptr<net::ChunkedUploadDataStream> chunked_stream(
|
||||
new net::ChunkedUploadDataStream(0));
|
||||
chunked_stream_writer_ = chunked_stream->CreateWriter();
|
||||
request_->set_upload(std::move(chunked_stream));
|
||||
first_call = true;
|
||||
}
|
||||
|
||||
if (buffer)
|
||||
// Non-empty buffer.
|
||||
chunked_stream_writer_->AppendData(buffer->data(), buffer->size(),
|
||||
is_last);
|
||||
else if (is_last)
|
||||
// Empty buffer and last chunk, i.e. request.end().
|
||||
chunked_stream_writer_->AppendData(nullptr, 0, true);
|
||||
|
||||
if (first_call) {
|
||||
request_->Start();
|
||||
}
|
||||
} else {
|
||||
if (buffer) {
|
||||
// Handling potential empty buffers.
|
||||
using internal::UploadOwnedIOBufferElementReader;
|
||||
auto* element_reader =
|
||||
UploadOwnedIOBufferElementReader::CreateWithBuffer(std::move(buffer));
|
||||
upload_element_readers_.push_back(
|
||||
std::unique_ptr<net::UploadElementReader>(element_reader));
|
||||
}
|
||||
|
||||
if (is_last) {
|
||||
auto* elements_upload_data_stream = new net::ElementsUploadDataStream(
|
||||
std::move(upload_element_readers_), 0);
|
||||
request_->set_upload(
|
||||
std::unique_ptr<net::UploadDataStream>(elements_upload_data_stream));
|
||||
request_->Start();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoCancel() {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (request_) {
|
||||
request_->Cancel();
|
||||
}
|
||||
DoTerminate();
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoFollowRedirect() {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (request_ && request_->is_redirecting() && redirect_policy_ == "manual") {
|
||||
request_->FollowDeferredRedirect(base::nullopt /* removed_headers */,
|
||||
base::nullopt /* modified_headers */);
|
||||
}
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoSetExtraHeader(const std::string& name,
|
||||
const std::string& value) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!request_) {
|
||||
return;
|
||||
}
|
||||
request_->SetExtraRequestHeaderByName(name, value, true);
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoRemoveExtraHeader(const std::string& name) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!request_) {
|
||||
return;
|
||||
}
|
||||
request_->RemoveRequestHeaderByName(name);
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoSetAuth(const base::string16& username,
|
||||
const base::string16& password) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!request_) {
|
||||
return;
|
||||
}
|
||||
request_->SetAuth(net::AuthCredentials(username, password));
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoCancelAuth() const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!request_) {
|
||||
return;
|
||||
}
|
||||
request_->CancelAuth();
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoCancelWithError(const std::string& error,
|
||||
bool isRequestError) {
|
||||
DoCancel();
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&AtomURLRequest::InformDelegateErrorOccured, this, error,
|
||||
isRequestError));
|
||||
}
|
||||
|
||||
void AtomURLRequest::DoSetLoadFlags(int flags) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!request_) {
|
||||
return;
|
||||
}
|
||||
request_->SetLoadFlags(request_->load_flags() | flags);
|
||||
}
|
||||
|
||||
void AtomURLRequest::OnReceivedRedirect(net::URLRequest* request,
|
||||
const net::RedirectInfo& info,
|
||||
bool* defer_redirect) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!request_ || redirect_policy_ == "follow")
|
||||
return;
|
||||
|
||||
if (redirect_policy_ == "error") {
|
||||
request->Cancel();
|
||||
DoCancelWithError(
|
||||
"Request cannot follow redirect with the current redirect mode", true);
|
||||
} else if (redirect_policy_ == "manual") {
|
||||
*defer_redirect = true;
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers =
|
||||
request->response_headers();
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&AtomURLRequest::InformDelegateReceivedRedirect, this,
|
||||
info.status_code, info.new_method, info.new_url,
|
||||
response_headers));
|
||||
}
|
||||
}
|
||||
|
||||
void AtomURLRequest::OnAuthRequired(net::URLRequest* request,
|
||||
net::AuthChallengeInfo* auth_info) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&AtomURLRequest::InformDelegateAuthenticationRequired,
|
||||
this, scoped_refptr<net::AuthChallengeInfo>(auth_info)));
|
||||
}
|
||||
|
||||
void AtomURLRequest::OnResponseStarted(net::URLRequest* request,
|
||||
int net_error) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!request_) {
|
||||
return;
|
||||
}
|
||||
DCHECK_EQ(request, request_.get());
|
||||
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers =
|
||||
request->response_headers();
|
||||
const auto& status = request_->status();
|
||||
if (status.is_success()) {
|
||||
// Success or pending trigger a Read.
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&AtomURLRequest::InformDelegateResponseStarted, this,
|
||||
response_headers));
|
||||
ReadResponse();
|
||||
} else if (status.status() == net::URLRequestStatus::Status::FAILED) {
|
||||
// Report error on Start.
|
||||
DoCancelWithError(net::ErrorToString(net_error), true);
|
||||
}
|
||||
// We don't report an error is the request is canceled.
|
||||
}
|
||||
|
||||
void AtomURLRequest::ReadResponse() {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
|
||||
int bytes_read = -1;
|
||||
if (request_->Read(response_read_buffer_.get(), kBufferSize, &bytes_read)) {
|
||||
OnReadCompleted(request_.get(), bytes_read);
|
||||
}
|
||||
}
|
||||
|
||||
void AtomURLRequest::OnReadCompleted(net::URLRequest* request, int bytes_read) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!request_) {
|
||||
return;
|
||||
}
|
||||
DCHECK_EQ(request, request_.get());
|
||||
|
||||
const auto status = request_->status();
|
||||
if (status.error() == bytes_read &&
|
||||
bytes_read == net::ERR_CONTENT_DECODING_INIT_FAILED) {
|
||||
// When the request job is unable to create a source stream for the
|
||||
// content encoding, we fail the request.
|
||||
DoCancelWithError(net::ErrorToString(net::ERR_CONTENT_DECODING_INIT_FAILED),
|
||||
true);
|
||||
return;
|
||||
}
|
||||
|
||||
bool response_error = false;
|
||||
bool data_ended = false;
|
||||
bool data_transfer_error = false;
|
||||
do {
|
||||
if (!status.is_success()) {
|
||||
response_error = true;
|
||||
break;
|
||||
}
|
||||
if (bytes_read == 0) {
|
||||
data_ended = true;
|
||||
break;
|
||||
}
|
||||
if (bytes_read < 0 || !CopyAndPostBuffer(bytes_read)) {
|
||||
data_transfer_error = true;
|
||||
break;
|
||||
}
|
||||
} while (
|
||||
request_->Read(response_read_buffer_.get(), kBufferSize, &bytes_read));
|
||||
if (response_error) {
|
||||
DoCancelWithError(net::ErrorToString(status.ToNetError()), false);
|
||||
} else if (data_ended) {
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&AtomURLRequest::InformDelegateResponseCompleted, this));
|
||||
DoTerminate();
|
||||
} else if (data_transfer_error) {
|
||||
// We abort the request on corrupted data transfer.
|
||||
DoCancelWithError("Failed to transfer data from IO to UI thread.", false);
|
||||
}
|
||||
}
|
||||
|
||||
void AtomURLRequest::OnContextShuttingDown() {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
DoCancel();
|
||||
}
|
||||
|
||||
bool AtomURLRequest::CopyAndPostBuffer(int bytes_read) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
|
||||
// data is only a wrapper for the asynchronous response_read_buffer_.
|
||||
// Make a deep copy of payload and transfer ownership to the UI thread.
|
||||
auto buffer_copy = WrapRefCounted(new net::IOBufferWithSize(bytes_read));
|
||||
memcpy(buffer_copy->data(), response_read_buffer_->data(), bytes_read);
|
||||
|
||||
return base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&AtomURLRequest::InformDelegateResponseData, this,
|
||||
buffer_copy));
|
||||
}
|
||||
|
||||
void AtomURLRequest::InformDelegateReceivedRedirect(
|
||||
int status_code,
|
||||
const std::string& method,
|
||||
const GURL& url,
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
if (delegate_)
|
||||
delegate_->OnReceivedRedirect(status_code, method, url, response_headers);
|
||||
}
|
||||
|
||||
void AtomURLRequest::InformDelegateAuthenticationRequired(
|
||||
scoped_refptr<net::AuthChallengeInfo> auth_info) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
if (delegate_)
|
||||
delegate_->OnAuthenticationRequired(auth_info);
|
||||
}
|
||||
|
||||
void AtomURLRequest::InformDelegateResponseStarted(
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
if (delegate_)
|
||||
delegate_->OnResponseStarted(response_headers);
|
||||
}
|
||||
|
||||
void AtomURLRequest::InformDelegateResponseData(
|
||||
scoped_refptr<net::IOBufferWithSize> data) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
|
||||
// Transfer ownership of the data buffer, data will be released
|
||||
// by the delegate's OnResponseData.
|
||||
if (delegate_)
|
||||
delegate_->OnResponseData(data);
|
||||
}
|
||||
|
||||
void AtomURLRequest::InformDelegateResponseCompleted() const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
|
||||
if (delegate_)
|
||||
delegate_->OnResponseCompleted();
|
||||
}
|
||||
|
||||
void AtomURLRequest::InformDelegateErrorOccured(const std::string& error,
|
||||
bool isRequestError) const {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
|
||||
if (delegate_)
|
||||
delegate_->OnError(error, isRequestError);
|
||||
}
|
||||
|
||||
void AtomURLRequest::GetUploadProgress(mate::Dictionary* progress) const {
|
||||
net::UploadProgress upload_progress;
|
||||
if (request_) {
|
||||
progress->Set("started", true);
|
||||
upload_progress = request_->GetUploadProgress();
|
||||
} else {
|
||||
progress->Set("started", false);
|
||||
}
|
||||
progress->Set("current", upload_progress.position());
|
||||
progress->Set("total", upload_progress.size());
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,122 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_ATOM_URL_REQUEST_H_
|
||||
#define ATOM_BROWSER_NET_ATOM_URL_REQUEST_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "atom/browser/api/atom_api_url_request.h"
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "base/memory/ref_counted.h"
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "net/base/auth.h"
|
||||
#include "net/base/chunked_upload_data_stream.h"
|
||||
#include "net/base/io_buffer.h"
|
||||
#include "net/base/upload_element_reader.h"
|
||||
#include "net/http/http_response_headers.h"
|
||||
#include "net/url_request/url_request.h"
|
||||
#include "net/url_request/url_request_context_getter_observer.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class AtomURLRequest : public base::RefCountedThreadSafe<AtomURLRequest>,
|
||||
public net::URLRequest::Delegate,
|
||||
public net::URLRequestContextGetterObserver {
|
||||
public:
|
||||
static scoped_refptr<AtomURLRequest> Create(
|
||||
AtomBrowserContext* browser_context,
|
||||
const std::string& method,
|
||||
const std::string& url,
|
||||
const std::string& redirect_policy,
|
||||
api::URLRequest* delegate);
|
||||
void Terminate();
|
||||
|
||||
bool Write(scoped_refptr<const net::IOBufferWithSize> buffer, bool is_last);
|
||||
void SetChunkedUpload(bool is_chunked_upload);
|
||||
void Cancel();
|
||||
void FollowRedirect();
|
||||
void SetExtraHeader(const std::string& name, const std::string& value) const;
|
||||
void RemoveExtraHeader(const std::string& name) const;
|
||||
void PassLoginInformation(const base::string16& username,
|
||||
const base::string16& password) const;
|
||||
void SetLoadFlags(int flags) const;
|
||||
void GetUploadProgress(mate::Dictionary* progress) const;
|
||||
|
||||
protected:
|
||||
// Overrides of net::URLRequest::Delegate
|
||||
void OnReceivedRedirect(net::URLRequest* request,
|
||||
const net::RedirectInfo& info,
|
||||
bool* defer_redirect) override;
|
||||
void OnAuthRequired(net::URLRequest* request,
|
||||
net::AuthChallengeInfo* auth_info) override;
|
||||
void OnResponseStarted(net::URLRequest* request, int net_error) override;
|
||||
void OnReadCompleted(net::URLRequest* request, int bytes_read) override;
|
||||
|
||||
// Overrides of net::URLRequestContextGetterObserver
|
||||
void OnContextShuttingDown() override;
|
||||
|
||||
private:
|
||||
friend class base::RefCountedThreadSafe<AtomURLRequest>;
|
||||
|
||||
explicit AtomURLRequest(api::URLRequest* delegate);
|
||||
~AtomURLRequest() override;
|
||||
|
||||
void DoInitialize(scoped_refptr<net::URLRequestContextGetter>,
|
||||
const std::string& method,
|
||||
const std::string& url,
|
||||
const std::string& redirect_policy);
|
||||
void DoTerminate();
|
||||
void DoWriteBuffer(scoped_refptr<const net::IOBufferWithSize> buffer,
|
||||
bool is_last);
|
||||
void DoCancel();
|
||||
void DoFollowRedirect();
|
||||
void DoSetExtraHeader(const std::string& name,
|
||||
const std::string& value) const;
|
||||
void DoRemoveExtraHeader(const std::string& name) const;
|
||||
void DoSetAuth(const base::string16& username,
|
||||
const base::string16& password) const;
|
||||
void DoCancelAuth() const;
|
||||
void DoCancelWithError(const std::string& error, bool isRequestError);
|
||||
void DoSetLoadFlags(int flags) const;
|
||||
|
||||
void ReadResponse();
|
||||
bool CopyAndPostBuffer(int bytes_read);
|
||||
|
||||
void InformDelegateReceivedRedirect(
|
||||
int status_code,
|
||||
const std::string& method,
|
||||
const GURL& url,
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers) const;
|
||||
void InformDelegateAuthenticationRequired(
|
||||
scoped_refptr<net::AuthChallengeInfo> auth_info) const;
|
||||
void InformDelegateResponseStarted(
|
||||
scoped_refptr<net::HttpResponseHeaders>) const;
|
||||
void InformDelegateResponseData(
|
||||
scoped_refptr<net::IOBufferWithSize> data) const;
|
||||
void InformDelegateResponseCompleted() const;
|
||||
void InformDelegateErrorOccured(const std::string& error,
|
||||
bool isRequestError) const;
|
||||
|
||||
api::URLRequest* delegate_;
|
||||
std::unique_ptr<net::URLRequest> request_;
|
||||
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
|
||||
|
||||
bool is_chunked_upload_ = false;
|
||||
std::string redirect_policy_;
|
||||
std::unique_ptr<net::ChunkedUploadDataStream> chunked_stream_;
|
||||
std::unique_ptr<net::ChunkedUploadDataStream::Writer> chunked_stream_writer_;
|
||||
std::vector<std::unique_ptr<net::UploadElementReader>>
|
||||
upload_element_readers_;
|
||||
scoped_refptr<net::IOBuffer> response_read_buffer_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(AtomURLRequest);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_ATOM_URL_REQUEST_H_
|
||||
@@ -1,147 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/atom_url_request_job_factory.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "base/memory/ptr_util.h"
|
||||
#include "base/stl_util.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "net/base/load_flags.h"
|
||||
#include "net/url_request/url_request.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
int disable_protocol_intercept_flag_key = 0;
|
||||
|
||||
} // namespace
|
||||
|
||||
typedef net::URLRequestJobFactory::ProtocolHandler ProtocolHandler;
|
||||
|
||||
const void* DisableProtocolInterceptFlagKey() {
|
||||
return &disable_protocol_intercept_flag_key;
|
||||
}
|
||||
|
||||
AtomURLRequestJobFactory::AtomURLRequestJobFactory() {}
|
||||
|
||||
AtomURLRequestJobFactory::~AtomURLRequestJobFactory() {
|
||||
Clear();
|
||||
}
|
||||
|
||||
void AtomURLRequestJobFactory::Chain(
|
||||
std::unique_ptr<net::URLRequestJobFactory> job_factory) {
|
||||
job_factory_ = std::move(job_factory);
|
||||
}
|
||||
|
||||
bool AtomURLRequestJobFactory::SetProtocolHandler(
|
||||
const std::string& scheme,
|
||||
std::unique_ptr<ProtocolHandler> protocol_handler) {
|
||||
if (!protocol_handler) {
|
||||
auto it = protocol_handler_map_.find(scheme);
|
||||
if (it == protocol_handler_map_.end())
|
||||
return false;
|
||||
|
||||
delete it->second;
|
||||
protocol_handler_map_.erase(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (base::ContainsKey(protocol_handler_map_, scheme))
|
||||
return false;
|
||||
protocol_handler_map_[scheme] = protocol_handler.release();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AtomURLRequestJobFactory::InterceptProtocol(
|
||||
const std::string& scheme,
|
||||
std::unique_ptr<ProtocolHandler> protocol_handler) {
|
||||
if (!base::ContainsKey(protocol_handler_map_, scheme) ||
|
||||
base::ContainsKey(original_protocols_, scheme))
|
||||
return false;
|
||||
ProtocolHandler* original_protocol_handler = protocol_handler_map_[scheme];
|
||||
protocol_handler_map_[scheme] = protocol_handler.release();
|
||||
original_protocols_[scheme].reset(original_protocol_handler);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AtomURLRequestJobFactory::UninterceptProtocol(const std::string& scheme) {
|
||||
auto it = original_protocols_.find(scheme);
|
||||
if (it == original_protocols_.end())
|
||||
return false;
|
||||
protocol_handler_map_[scheme] = it->second.release();
|
||||
original_protocols_.erase(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AtomURLRequestJobFactory::HasProtocolHandler(
|
||||
const std::string& scheme) const {
|
||||
return base::ContainsKey(protocol_handler_map_, scheme);
|
||||
}
|
||||
|
||||
void AtomURLRequestJobFactory::Clear() {
|
||||
for (auto& it : protocol_handler_map_)
|
||||
delete it.second;
|
||||
protocol_handler_map_.clear();
|
||||
original_protocols_.clear();
|
||||
}
|
||||
|
||||
net::URLRequestJob* AtomURLRequestJobFactory::MaybeCreateJobWithProtocolHandler(
|
||||
const std::string& scheme,
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
|
||||
auto* job = job_factory_->MaybeCreateJobWithProtocolHandler(scheme, request,
|
||||
network_delegate);
|
||||
if (job)
|
||||
return job;
|
||||
|
||||
auto it = protocol_handler_map_.find(scheme);
|
||||
if (it == protocol_handler_map_.end())
|
||||
return nullptr;
|
||||
|
||||
if (request->GetUserData(DisableProtocolInterceptFlagKey()))
|
||||
return nullptr;
|
||||
|
||||
return it->second->MaybeCreateJob(request, network_delegate);
|
||||
}
|
||||
|
||||
net::URLRequestJob* AtomURLRequestJobFactory::MaybeInterceptRedirect(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate,
|
||||
const GURL& location) const {
|
||||
return job_factory_->MaybeInterceptRedirect(request, network_delegate,
|
||||
location);
|
||||
}
|
||||
|
||||
net::URLRequestJob* AtomURLRequestJobFactory::MaybeInterceptResponse(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const {
|
||||
return job_factory_->MaybeInterceptResponse(request, network_delegate);
|
||||
}
|
||||
|
||||
bool AtomURLRequestJobFactory::IsHandledProtocol(
|
||||
const std::string& scheme) const {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
|
||||
return HasProtocolHandler(scheme) ||
|
||||
net::URLRequest::IsHandledProtocol(scheme);
|
||||
}
|
||||
|
||||
bool AtomURLRequestJobFactory::IsSafeRedirectTarget(
|
||||
const GURL& location) const {
|
||||
if (!location.is_valid()) {
|
||||
// We handle error cases.
|
||||
return true;
|
||||
}
|
||||
return IsHandledProtocol(location.scheme());
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,79 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_ATOM_URL_REQUEST_JOB_FACTORY_H_
|
||||
#define ATOM_BROWSER_NET_ATOM_URL_REQUEST_JOB_FACTORY_H_
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "net/url_request/url_request_job_factory.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
const void* DisableProtocolInterceptFlagKey();
|
||||
|
||||
class AtomURLRequestJobFactory : public net::URLRequestJobFactory {
|
||||
public:
|
||||
AtomURLRequestJobFactory();
|
||||
~AtomURLRequestJobFactory() override;
|
||||
|
||||
// Requests are forwarded to the chained job factory first.
|
||||
void Chain(std::unique_ptr<net::URLRequestJobFactory> job_factory);
|
||||
|
||||
// Sets the ProtocolHandler for a scheme. Returns true on success, false on
|
||||
// failure (a ProtocolHandler already exists for |scheme|). On success,
|
||||
// URLRequestJobFactory takes ownership of |protocol_handler|.
|
||||
bool SetProtocolHandler(const std::string& scheme,
|
||||
std::unique_ptr<ProtocolHandler> protocol_handler);
|
||||
|
||||
// Intercepts the ProtocolHandler for a scheme.
|
||||
bool InterceptProtocol(const std::string& scheme,
|
||||
std::unique_ptr<ProtocolHandler> protocol_handler);
|
||||
bool UninterceptProtocol(const std::string& scheme);
|
||||
|
||||
// Whether the protocol handler is registered by the job factory.
|
||||
bool HasProtocolHandler(const std::string& scheme) const;
|
||||
|
||||
// Clear all protocol handlers.
|
||||
void Clear();
|
||||
|
||||
// URLRequestJobFactory implementation
|
||||
net::URLRequestJob* MaybeCreateJobWithProtocolHandler(
|
||||
const std::string& scheme,
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const override;
|
||||
net::URLRequestJob* MaybeInterceptRedirect(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate,
|
||||
const GURL& location) const override;
|
||||
net::URLRequestJob* MaybeInterceptResponse(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const override;
|
||||
bool IsHandledProtocol(const std::string& scheme) const override;
|
||||
bool IsSafeRedirectTarget(const GURL& location) const override;
|
||||
|
||||
private:
|
||||
using ProtocolHandlerMap = std::map<std::string, ProtocolHandler*>;
|
||||
|
||||
ProtocolHandlerMap protocol_handler_map_;
|
||||
|
||||
// Map that stores the original protocols of schemes.
|
||||
using OriginalProtocolsMap =
|
||||
std::unordered_map<std::string, std::unique_ptr<ProtocolHandler>>;
|
||||
// Can only be accessed in IO thread.
|
||||
OriginalProtocolsMap original_protocols_;
|
||||
|
||||
std::unique_ptr<net::URLRequestJobFactory> job_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(AtomURLRequestJobFactory);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_ATOM_URL_REQUEST_JOB_FACTORY_H_
|
||||
@@ -1,22 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/http_protocol_handler.h"
|
||||
|
||||
#include "net/url_request/url_request_http_job.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
HttpProtocolHandler::HttpProtocolHandler(const std::string& scheme)
|
||||
: scheme_(scheme) {}
|
||||
|
||||
HttpProtocolHandler::~HttpProtocolHandler() {}
|
||||
|
||||
net::URLRequestJob* HttpProtocolHandler::MaybeCreateJob(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const {
|
||||
return net::URLRequestHttpJob::Factory(request, network_delegate, scheme_);
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,30 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_HTTP_PROTOCOL_HANDLER_H_
|
||||
#define ATOM_BROWSER_NET_HTTP_PROTOCOL_HANDLER_H_
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "net/url_request/url_request_job_factory.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class HttpProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler {
|
||||
public:
|
||||
explicit HttpProtocolHandler(const std::string&);
|
||||
~HttpProtocolHandler() override;
|
||||
|
||||
// net::URLRequestJobFactory::ProtocolHandler:
|
||||
net::URLRequestJob* MaybeCreateJob(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate) const override;
|
||||
|
||||
private:
|
||||
std::string scheme_;
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_HTTP_PROTOCOL_HANDLER_H_
|
||||
@@ -1,55 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/js_asker.h"
|
||||
|
||||
#include <utility>
|
||||
|
||||
#include "atom/common/native_mate_converters/callback.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
JsAsker::JsAsker() = default;
|
||||
|
||||
JsAsker::~JsAsker() = default;
|
||||
|
||||
void JsAsker::SetHandlerInfo(
|
||||
v8::Isolate* isolate,
|
||||
net::URLRequestContextGetter* request_context_getter,
|
||||
const JavaScriptHandler& handler) {
|
||||
isolate_ = isolate;
|
||||
request_context_getter_ = request_context_getter;
|
||||
handler_ = handler;
|
||||
}
|
||||
|
||||
// static
|
||||
void JsAsker::AskForOptions(
|
||||
v8::Isolate* isolate,
|
||||
const JavaScriptHandler& handler,
|
||||
std::unique_ptr<base::DictionaryValue> request_details,
|
||||
const BeforeStartCallback& before_start) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
|
||||
v8::Locker locker(isolate);
|
||||
v8::HandleScope handle_scope(isolate);
|
||||
v8::Local<v8::Context> context = isolate->GetCurrentContext();
|
||||
v8::Context::Scope context_scope(context);
|
||||
handler.Run(*(request_details.get()),
|
||||
mate::ConvertToV8(isolate, before_start));
|
||||
}
|
||||
|
||||
// static
|
||||
bool JsAsker::IsErrorOptions(base::Value* value, int* error) {
|
||||
if (value->is_dict()) {
|
||||
base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(value);
|
||||
if (dict->GetInteger("error", error))
|
||||
return true;
|
||||
} else if (value->is_int()) {
|
||||
*error = value->GetInt();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,58 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_JS_ASKER_H_
|
||||
#define ATOM_BROWSER_NET_JS_ASKER_H_
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "base/callback.h"
|
||||
#include "base/values.h"
|
||||
#include "native_mate/arguments.h"
|
||||
#include "net/url_request/url_request_context_getter.h"
|
||||
#include "v8/include/v8.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
using JavaScriptHandler =
|
||||
base::Callback<void(const base::DictionaryValue&, v8::Local<v8::Value>)>;
|
||||
using BeforeStartCallback = base::Callback<void(mate::Arguments* args)>;
|
||||
|
||||
class JsAsker {
|
||||
public:
|
||||
JsAsker();
|
||||
~JsAsker();
|
||||
|
||||
// Called by |CustomProtocolHandler| to store handler related information.
|
||||
void SetHandlerInfo(v8::Isolate* isolate,
|
||||
net::URLRequestContextGetter* request_context_getter,
|
||||
const JavaScriptHandler& handler);
|
||||
|
||||
// Ask handler for options in UI thread.
|
||||
static void AskForOptions(
|
||||
v8::Isolate* isolate,
|
||||
const JavaScriptHandler& handler,
|
||||
std::unique_ptr<base::DictionaryValue> request_details,
|
||||
const BeforeStartCallback& before_start);
|
||||
|
||||
// Test whether the |options| means an error.
|
||||
static bool IsErrorOptions(base::Value* value, int* error);
|
||||
|
||||
net::URLRequestContextGetter* request_context_getter() const {
|
||||
return request_context_getter_;
|
||||
}
|
||||
v8::Isolate* isolate() { return isolate_; }
|
||||
JavaScriptHandler handler() { return handler_; }
|
||||
|
||||
private:
|
||||
v8::Isolate* isolate_;
|
||||
net::URLRequestContextGetter* request_context_getter_;
|
||||
JavaScriptHandler handler_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(JsAsker);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_JS_ASKER_H_
|
||||
@@ -1,36 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/require_ct_delegate.h"
|
||||
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
RequireCTDelegate::RequireCTDelegate() {}
|
||||
|
||||
RequireCTDelegate::~RequireCTDelegate() {}
|
||||
|
||||
void RequireCTDelegate::AddCTExcludedHost(const std::string& host) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
ct_excluded_hosts_.insert(host);
|
||||
}
|
||||
|
||||
void RequireCTDelegate::ClearCTExcludedHostsList() {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
ct_excluded_hosts_.clear();
|
||||
}
|
||||
|
||||
RequireCTDelegate::CTRequirementLevel RequireCTDelegate::IsCTRequiredForHost(
|
||||
const std::string& host,
|
||||
const net::X509Certificate* chain,
|
||||
const net::HashValueVector& hashes) {
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (!ct_excluded_hosts_.empty() &&
|
||||
(ct_excluded_hosts_.find(host) != ct_excluded_hosts_.end()))
|
||||
return CTRequirementLevel::NOT_REQUIRED;
|
||||
return CTRequirementLevel::DEFAULT;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,37 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_REQUIRE_CT_DELEGATE_H_
|
||||
#define ATOM_BROWSER_NET_REQUIRE_CT_DELEGATE_H_
|
||||
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
#include "net/http/transport_security_state.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class RequireCTDelegate
|
||||
: public net::TransportSecurityState::RequireCTDelegate {
|
||||
public:
|
||||
RequireCTDelegate();
|
||||
~RequireCTDelegate() override;
|
||||
|
||||
void AddCTExcludedHost(const std::string& host);
|
||||
void ClearCTExcludedHostsList();
|
||||
|
||||
// net::TransportSecurityState::RequireCTDelegate:
|
||||
CTRequirementLevel IsCTRequiredForHost(
|
||||
const std::string& host,
|
||||
const net::X509Certificate* chain,
|
||||
const net::HashValueVector& hashes) override;
|
||||
|
||||
private:
|
||||
std::set<std::string> ct_excluded_hosts_;
|
||||
DISALLOW_COPY_AND_ASSIGN(RequireCTDelegate);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_REQUIRE_CT_DELEGATE_H_
|
||||
@@ -1,37 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/url_request_about_job.h"
|
||||
|
||||
#include "base/threading/thread_task_runner_handle.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
URLRequestAboutJob::URLRequestAboutJob(net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate)
|
||||
: net::URLRequestJob(request, network_delegate), weak_ptr_factory_(this) {}
|
||||
|
||||
void URLRequestAboutJob::Start() {
|
||||
base::ThreadTaskRunnerHandle::Get()->PostTask(
|
||||
FROM_HERE, base::BindOnce(&URLRequestAboutJob::StartAsync,
|
||||
weak_ptr_factory_.GetWeakPtr()));
|
||||
}
|
||||
|
||||
void URLRequestAboutJob::Kill() {
|
||||
weak_ptr_factory_.InvalidateWeakPtrs();
|
||||
URLRequestJob::Kill();
|
||||
}
|
||||
|
||||
bool URLRequestAboutJob::GetMimeType(std::string* mime_type) const {
|
||||
*mime_type = "text/html";
|
||||
return true;
|
||||
}
|
||||
|
||||
URLRequestAboutJob::~URLRequestAboutJob() {}
|
||||
|
||||
void URLRequestAboutJob::StartAsync() {
|
||||
NotifyHeadersComplete();
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,35 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_URL_REQUEST_ABOUT_JOB_H_
|
||||
#define ATOM_BROWSER_NET_URL_REQUEST_ABOUT_JOB_H_
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "net/url_request/url_request_job.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class URLRequestAboutJob : public net::URLRequestJob {
|
||||
public:
|
||||
URLRequestAboutJob(net::URLRequest*, net::NetworkDelegate*);
|
||||
|
||||
// URLRequestJob:
|
||||
void Start() override;
|
||||
void Kill() override;
|
||||
bool GetMimeType(std::string* mime_type) const override;
|
||||
|
||||
private:
|
||||
~URLRequestAboutJob() override;
|
||||
void StartAsync();
|
||||
|
||||
base::WeakPtrFactory<URLRequestAboutJob> weak_ptr_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(URLRequestAboutJob);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_URL_REQUEST_ABOUT_JOB_H_
|
||||
@@ -1,123 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/url_request_async_asar_job.h"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/common/atom_constants.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "atom/common/native_mate_converters/v8_value_converter.h"
|
||||
#include "base/strings/utf_string_conversions.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
void BeforeStartInUI(base::WeakPtr<URLRequestAsyncAsarJob> job,
|
||||
mate::Arguments* args) {
|
||||
v8::Local<v8::Value> value;
|
||||
int error = net::OK;
|
||||
std::unique_ptr<base::Value> request_options = nullptr;
|
||||
|
||||
if (args->GetNext(&value)) {
|
||||
V8ValueConverter converter;
|
||||
v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();
|
||||
request_options = converter.FromV8Value(value, context);
|
||||
}
|
||||
|
||||
if (request_options) {
|
||||
JsAsker::IsErrorOptions(request_options.get(), &error);
|
||||
} else {
|
||||
error = net::ERR_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestAsyncAsarJob::StartAsync, job,
|
||||
std::move(request_options), error));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
URLRequestAsyncAsarJob::URLRequestAsyncAsarJob(
|
||||
net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate)
|
||||
: asar::URLRequestAsarJob(request, network_delegate), weak_factory_(this) {}
|
||||
|
||||
URLRequestAsyncAsarJob::~URLRequestAsyncAsarJob() = default;
|
||||
|
||||
void URLRequestAsyncAsarJob::Start() {
|
||||
auto request_details = std::make_unique<base::DictionaryValue>();
|
||||
FillRequestDetails(request_details.get(), request());
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&JsAsker::AskForOptions, base::Unretained(isolate()),
|
||||
handler(), std::move(request_details),
|
||||
base::Bind(&BeforeStartInUI, weak_factory_.GetWeakPtr())));
|
||||
}
|
||||
|
||||
void URLRequestAsyncAsarJob::StartAsync(std::unique_ptr<base::Value> options,
|
||||
int error) {
|
||||
if (error != net::OK) {
|
||||
NotifyStartError(
|
||||
net::URLRequestStatus(net::URLRequestStatus::FAILED, error));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string file_path;
|
||||
response_headers_ = new net::HttpResponseHeaders("HTTP/1.1 200 OK");
|
||||
if (options->is_dict()) {
|
||||
base::DictionaryValue* dict =
|
||||
static_cast<base::DictionaryValue*>(options.get());
|
||||
base::Value* pathValue =
|
||||
dict->FindKeyOfType("path", base::Value::Type::STRING);
|
||||
if (pathValue) {
|
||||
file_path = pathValue->GetString();
|
||||
}
|
||||
base::Value* headersValue =
|
||||
dict->FindKeyOfType("headers", base::Value::Type::DICTIONARY);
|
||||
if (headersValue) {
|
||||
for (const auto& iter : headersValue->DictItems()) {
|
||||
response_headers_->AddHeader(iter.first + ": " +
|
||||
iter.second.GetString());
|
||||
}
|
||||
}
|
||||
} else if (options->is_string()) {
|
||||
file_path = options->GetString();
|
||||
}
|
||||
response_headers_->AddHeader(kCORSHeader);
|
||||
|
||||
if (file_path.empty()) {
|
||||
NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED,
|
||||
net::ERR_NOT_IMPLEMENTED));
|
||||
} else {
|
||||
asar::URLRequestAsarJob::Initialize(
|
||||
base::CreateSequencedTaskRunnerWithTraits(
|
||||
{base::MayBlock(), base::TaskPriority::USER_VISIBLE,
|
||||
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}),
|
||||
#if defined(OS_WIN)
|
||||
base::FilePath(base::UTF8ToWide(file_path)));
|
||||
#else
|
||||
base::FilePath(file_path));
|
||||
#endif
|
||||
asar::URLRequestAsarJob::Start();
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequestAsyncAsarJob::Kill() {
|
||||
weak_factory_.InvalidateWeakPtrs();
|
||||
URLRequestAsarJob::Kill();
|
||||
}
|
||||
|
||||
void URLRequestAsyncAsarJob::GetResponseInfo(net::HttpResponseInfo* info) {
|
||||
info->headers = response_headers_;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,37 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_URL_REQUEST_ASYNC_ASAR_JOB_H_
|
||||
#define ATOM_BROWSER_NET_URL_REQUEST_ASYNC_ASAR_JOB_H_
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "atom/browser/net/asar/url_request_asar_job.h"
|
||||
#include "atom/browser/net/js_asker.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
// Like URLRequestAsarJob, but asks the JavaScript handler for file path.
|
||||
class URLRequestAsyncAsarJob : public asar::URLRequestAsarJob, public JsAsker {
|
||||
public:
|
||||
URLRequestAsyncAsarJob(net::URLRequest*, net::NetworkDelegate*);
|
||||
~URLRequestAsyncAsarJob() override;
|
||||
|
||||
void StartAsync(std::unique_ptr<base::Value> options, int error);
|
||||
|
||||
// URLRequestJob:
|
||||
void Start() override;
|
||||
void GetResponseInfo(net::HttpResponseInfo* info) override;
|
||||
void Kill() override;
|
||||
|
||||
private:
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers_;
|
||||
base::WeakPtrFactory<URLRequestAsyncAsarJob> weak_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(URLRequestAsyncAsarJob);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_URL_REQUEST_ASYNC_ASAR_JOB_H_
|
||||
@@ -1,154 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/url_request_buffer_job.h"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/common/atom_constants.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "atom/common/native_mate_converters/v8_value_converter.h"
|
||||
#include "base/strings/string_number_conversions.h"
|
||||
#include "base/strings/utf_string_conversions.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "net/base/mime_util.h"
|
||||
#include "net/base/net_errors.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string GetExtFromURL(const GURL& url) {
|
||||
std::string spec = url.spec();
|
||||
size_t index = spec.find_last_of('.');
|
||||
if (index == std::string::npos || index == spec.size())
|
||||
return std::string();
|
||||
return spec.substr(index + 1, spec.size() - index - 1);
|
||||
}
|
||||
|
||||
void BeforeStartInUI(base::WeakPtr<URLRequestBufferJob> job,
|
||||
mate::Arguments* args) {
|
||||
v8::Local<v8::Value> value;
|
||||
int error = net::OK;
|
||||
std::unique_ptr<base::Value> request_options = nullptr;
|
||||
|
||||
if (args->GetNext(&value)) {
|
||||
V8ValueConverter converter;
|
||||
v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();
|
||||
request_options = converter.FromV8Value(value, context);
|
||||
}
|
||||
|
||||
if (request_options) {
|
||||
JsAsker::IsErrorOptions(request_options.get(), &error);
|
||||
} else {
|
||||
error = net::ERR_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestBufferJob::StartAsync, job,
|
||||
std::move(request_options), error));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
URLRequestBufferJob::URLRequestBufferJob(net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate)
|
||||
: net::URLRequestSimpleJob(request, network_delegate),
|
||||
status_code_(net::HTTP_NOT_IMPLEMENTED),
|
||||
weak_factory_(this) {}
|
||||
|
||||
URLRequestBufferJob::~URLRequestBufferJob() = default;
|
||||
|
||||
void URLRequestBufferJob::Start() {
|
||||
auto request_details = std::make_unique<base::DictionaryValue>();
|
||||
FillRequestDetails(request_details.get(), request());
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&JsAsker::AskForOptions, base::Unretained(isolate()),
|
||||
handler(), std::move(request_details),
|
||||
base::Bind(&BeforeStartInUI, weak_factory_.GetWeakPtr())));
|
||||
}
|
||||
|
||||
void URLRequestBufferJob::StartAsync(std::unique_ptr<base::Value> options,
|
||||
int error) {
|
||||
if (error != net::OK) {
|
||||
NotifyStartError(
|
||||
net::URLRequestStatus(net::URLRequestStatus::FAILED, error));
|
||||
return;
|
||||
}
|
||||
|
||||
const base::Value* binary = nullptr;
|
||||
if (options->is_dict()) {
|
||||
base::DictionaryValue* dict =
|
||||
static_cast<base::DictionaryValue*>(options.get());
|
||||
dict->GetString("mimeType", &mime_type_);
|
||||
dict->GetString("charset", &charset_);
|
||||
dict->GetBinary("data", &binary);
|
||||
} else if (options->is_blob()) {
|
||||
binary = options.get();
|
||||
}
|
||||
|
||||
if (mime_type_.empty()) {
|
||||
std::string ext = GetExtFromURL(request()->url());
|
||||
#if defined(OS_WIN)
|
||||
net::GetWellKnownMimeTypeFromExtension(base::UTF8ToUTF16(ext), &mime_type_);
|
||||
#else
|
||||
net::GetWellKnownMimeTypeFromExtension(ext, &mime_type_);
|
||||
#endif
|
||||
}
|
||||
|
||||
if (!binary) {
|
||||
NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED,
|
||||
net::ERR_NOT_IMPLEMENTED));
|
||||
return;
|
||||
}
|
||||
|
||||
data_ = new base::RefCountedBytes(
|
||||
reinterpret_cast<const unsigned char*>(binary->GetBlob().data()),
|
||||
binary->GetBlob().size());
|
||||
status_code_ = net::HTTP_OK;
|
||||
net::URLRequestSimpleJob::Start();
|
||||
}
|
||||
|
||||
void URLRequestBufferJob::Kill() {
|
||||
weak_factory_.InvalidateWeakPtrs();
|
||||
net::URLRequestSimpleJob::Kill();
|
||||
}
|
||||
|
||||
void URLRequestBufferJob::GetResponseInfo(net::HttpResponseInfo* info) {
|
||||
std::string status("HTTP/1.1 ");
|
||||
status.append(base::IntToString(status_code_));
|
||||
status.append(" ");
|
||||
status.append(net::GetHttpReasonPhrase(status_code_));
|
||||
status.append("\0\0", 2);
|
||||
auto* headers = new net::HttpResponseHeaders(status);
|
||||
|
||||
headers->AddHeader(kCORSHeader);
|
||||
|
||||
if (!mime_type_.empty()) {
|
||||
std::string content_type_header(net::HttpRequestHeaders::kContentType);
|
||||
content_type_header.append(": ");
|
||||
content_type_header.append(mime_type_);
|
||||
headers->AddHeader(content_type_header);
|
||||
}
|
||||
|
||||
info->headers = headers;
|
||||
}
|
||||
|
||||
int URLRequestBufferJob::GetRefCountedData(
|
||||
std::string* mime_type,
|
||||
std::string* charset,
|
||||
scoped_refptr<base::RefCountedMemory>* data,
|
||||
net::CompletionOnceCallback callback) const {
|
||||
*mime_type = mime_type_;
|
||||
*charset = charset_;
|
||||
*data = data_;
|
||||
return net::OK;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_URL_REQUEST_BUFFER_JOB_H_
|
||||
#define ATOM_BROWSER_NET_URL_REQUEST_BUFFER_JOB_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "atom/browser/net/js_asker.h"
|
||||
#include "base/memory/ref_counted_memory.h"
|
||||
#include "net/http/http_status_code.h"
|
||||
#include "net/url_request/url_request_simple_job.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class URLRequestBufferJob : public JsAsker, public net::URLRequestSimpleJob {
|
||||
public:
|
||||
URLRequestBufferJob(net::URLRequest*, net::NetworkDelegate*);
|
||||
~URLRequestBufferJob() override;
|
||||
|
||||
void StartAsync(std::unique_ptr<base::Value> options, int error);
|
||||
|
||||
// URLRequestJob:
|
||||
void Start() override;
|
||||
void GetResponseInfo(net::HttpResponseInfo* info) override;
|
||||
void Kill() override;
|
||||
|
||||
// URLRequestSimpleJob:
|
||||
int GetRefCountedData(std::string* mime_type,
|
||||
std::string* charset,
|
||||
scoped_refptr<base::RefCountedMemory>* data,
|
||||
net::CompletionOnceCallback callback) const override;
|
||||
|
||||
private:
|
||||
std::string mime_type_;
|
||||
std::string charset_;
|
||||
scoped_refptr<base::RefCountedBytes> data_;
|
||||
net::HttpStatusCode status_code_;
|
||||
|
||||
base::WeakPtrFactory<URLRequestBufferJob> weak_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(URLRequestBufferJob);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_URL_REQUEST_BUFFER_JOB_H_
|
||||
@@ -1,328 +0,0 @@
|
||||
// Copyright (c) 2018 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/url_request_context_getter.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/api/atom_api_protocol.h"
|
||||
#include "atom/browser/atom_browser_client.h"
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "atom/browser/browser_process_impl.h"
|
||||
#include "atom/browser/net/about_protocol_handler.h"
|
||||
#include "atom/browser/net/asar/asar_protocol_handler.h"
|
||||
#include "atom/browser/net/atom_cert_verifier.h"
|
||||
#include "atom/browser/net/atom_network_delegate.h"
|
||||
#include "atom/browser/net/atom_url_request_job_factory.h"
|
||||
#include "atom/browser/net/http_protocol_handler.h"
|
||||
#include "atom/browser/net/require_ct_delegate.h"
|
||||
#include "atom/browser/net/system_network_context_manager.h"
|
||||
#include "base/command_line.h"
|
||||
#include "base/strings/string_util.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "chrome/common/chrome_constants.h"
|
||||
#include "chrome/common/pref_names.h"
|
||||
#include "components/network_session_configurator/common/network_switches.h"
|
||||
#include "components/prefs/value_map_pref_store.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "content/public/browser/devtools_network_transaction_factory.h"
|
||||
#include "content/public/browser/network_service_instance.h"
|
||||
#include "net/base/host_mapping_rules.h"
|
||||
#include "net/cert/multi_log_ct_verifier.h"
|
||||
#include "net/cookies/cookie_monster.h"
|
||||
#include "net/dns/mapped_host_resolver.h" // nogncheck
|
||||
#include "net/http/http_auth_handler_factory.h"
|
||||
#include "net/http/http_auth_preferences.h"
|
||||
#include "net/http/http_auth_scheme.h"
|
||||
#include "net/http/http_transaction_factory.h"
|
||||
#include "net/log/net_log.h"
|
||||
#include "net/traffic_annotation/network_traffic_annotation.h"
|
||||
#include "net/url_request/data_protocol_handler.h"
|
||||
#include "net/url_request/static_http_user_agent_settings.h"
|
||||
#include "net/url_request/url_request_intercepting_job_factory.h"
|
||||
#include "net/url_request/url_request_job_factory_impl.h"
|
||||
#include "services/network/ignore_errors_cert_verifier.h"
|
||||
#include "services/network/network_service.h"
|
||||
#include "services/network/public/cpp/network_switches.h"
|
||||
#include "services/network/url_request_context_builder_mojo.h"
|
||||
#include "url/url_constants.h"
|
||||
|
||||
#if !BUILDFLAG(DISABLE_FTP_SUPPORT)
|
||||
#include "net/url_request/ftp_protocol_handler.h"
|
||||
#endif
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
void SetupAtomURLRequestJobFactory(
|
||||
content::ProtocolHandlerMap* protocol_handlers,
|
||||
net::URLRequestContext* url_request_context,
|
||||
AtomURLRequestJobFactory* job_factory) {
|
||||
for (auto& protocol_handler : *protocol_handlers) {
|
||||
job_factory->SetProtocolHandler(protocol_handler.first,
|
||||
std::move(protocol_handler.second));
|
||||
}
|
||||
protocol_handlers->clear();
|
||||
|
||||
job_factory->SetProtocolHandler(url::kAboutScheme,
|
||||
std::make_unique<AboutProtocolHandler>());
|
||||
job_factory->SetProtocolHandler(url::kDataScheme,
|
||||
std::make_unique<net::DataProtocolHandler>());
|
||||
job_factory->SetProtocolHandler(
|
||||
url::kFileScheme,
|
||||
std::make_unique<asar::AsarProtocolHandler>(
|
||||
base::CreateTaskRunnerWithTraits(
|
||||
{base::MayBlock(), base::TaskPriority::USER_BLOCKING,
|
||||
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})));
|
||||
job_factory->SetProtocolHandler(
|
||||
url::kHttpScheme,
|
||||
std::make_unique<HttpProtocolHandler>(url::kHttpScheme));
|
||||
job_factory->SetProtocolHandler(
|
||||
url::kHttpsScheme,
|
||||
std::make_unique<HttpProtocolHandler>(url::kHttpsScheme));
|
||||
job_factory->SetProtocolHandler(
|
||||
url::kWsScheme, std::make_unique<HttpProtocolHandler>(url::kWsScheme));
|
||||
job_factory->SetProtocolHandler(
|
||||
url::kWssScheme, std::make_unique<HttpProtocolHandler>(url::kWssScheme));
|
||||
|
||||
#if !BUILDFLAG(DISABLE_FTP_SUPPORT)
|
||||
auto* host_resolver = url_request_context->host_resolver();
|
||||
job_factory->SetProtocolHandler(
|
||||
url::kFtpScheme, net::FtpProtocolHandler::Create(host_resolver));
|
||||
#endif
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
URLRequestContextGetter::Handle::Handle(
|
||||
base::WeakPtr<AtomBrowserContext> browser_context)
|
||||
: resource_context_(new content::ResourceContext),
|
||||
browser_context_(browser_context),
|
||||
initialized_(false) {}
|
||||
|
||||
URLRequestContextGetter::Handle::~Handle() {}
|
||||
|
||||
content::ResourceContext*
|
||||
URLRequestContextGetter::Handle::GetResourceContext() {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::UI);
|
||||
LazyInitialize();
|
||||
return resource_context_.get();
|
||||
}
|
||||
|
||||
scoped_refptr<URLRequestContextGetter>
|
||||
URLRequestContextGetter::Handle::CreateMainRequestContextGetter(
|
||||
content::ProtocolHandlerMap* protocol_handlers,
|
||||
content::URLRequestInterceptorScopedVector protocol_interceptors) {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::UI);
|
||||
DCHECK(!main_request_context_getter_.get());
|
||||
LazyInitialize();
|
||||
main_request_context_getter_ = new URLRequestContextGetter(
|
||||
this, protocol_handlers, std::move(protocol_interceptors));
|
||||
return main_request_context_getter_;
|
||||
}
|
||||
|
||||
scoped_refptr<URLRequestContextGetter>
|
||||
URLRequestContextGetter::Handle::GetMainRequestContextGetter() {
|
||||
return main_request_context_getter_;
|
||||
}
|
||||
|
||||
network::mojom::NetworkContextPtr
|
||||
URLRequestContextGetter::Handle::GetNetworkContext() {
|
||||
if (!main_network_context_) {
|
||||
main_network_context_request_ = mojo::MakeRequest(&main_network_context_);
|
||||
}
|
||||
return std::move(main_network_context_);
|
||||
}
|
||||
|
||||
network::mojom::NetworkContextParamsPtr
|
||||
URLRequestContextGetter::Handle::CreateNetworkContextParams() {
|
||||
network::mojom::NetworkContextParamsPtr network_context_params =
|
||||
SystemNetworkContextManager::GetInstance()
|
||||
->CreateDefaultNetworkContextParams();
|
||||
|
||||
network_context_params->user_agent = browser_context_->GetUserAgent();
|
||||
|
||||
network_context_params->http_cache_enabled =
|
||||
browser_context_->CanUseHttpCache();
|
||||
|
||||
network_context_params->accept_language =
|
||||
net::HttpUtil::GenerateAcceptLanguageHeader(
|
||||
AtomBrowserClient::Get()->GetApplicationLocale());
|
||||
|
||||
if (!browser_context_->IsOffTheRecord()) {
|
||||
auto base_path = browser_context_->GetPath();
|
||||
network_context_params->http_cache_path =
|
||||
base_path.Append(chrome::kCacheDirname);
|
||||
network_context_params->http_cache_max_size =
|
||||
browser_context_->GetMaxCacheSize();
|
||||
network_context_params->http_server_properties_path =
|
||||
base_path.Append(chrome::kNetworkPersistentStateFilename);
|
||||
network_context_params->cookie_path =
|
||||
base_path.Append(chrome::kCookieFilename);
|
||||
network_context_params->restore_old_session_cookies = false;
|
||||
network_context_params->persist_session_cookies = false;
|
||||
// TODO(deepak1556): Matches the existing behavior https://git.io/fxHMl,
|
||||
// enable encryption as a followup.
|
||||
network_context_params->enable_encrypted_cookies = false;
|
||||
}
|
||||
|
||||
// TODO(deepak1556): Decide the stand on chrome ct policy and
|
||||
// enable it.
|
||||
// See //net/docs/certificate-transparency.md
|
||||
// network_context_params->enforce_chrome_ct_policy = true;
|
||||
return network_context_params;
|
||||
}
|
||||
|
||||
void URLRequestContextGetter::Handle::LazyInitialize() {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::UI);
|
||||
if (initialized_)
|
||||
return;
|
||||
|
||||
initialized_ = true;
|
||||
main_network_context_params_ = CreateNetworkContextParams();
|
||||
|
||||
browser_context_->proxy_config_monitor()->AddToNetworkContextParams(
|
||||
main_network_context_params_.get());
|
||||
|
||||
BrowserProcessImpl::ApplyProxyModeFromCommandLine(
|
||||
browser_context_->in_memory_pref_store());
|
||||
|
||||
if (!main_network_context_request_.is_pending()) {
|
||||
main_network_context_request_ = mojo::MakeRequest(&main_network_context_);
|
||||
}
|
||||
content::BrowserContext::EnsureResourceContextInitialized(
|
||||
browser_context_.get());
|
||||
}
|
||||
|
||||
void URLRequestContextGetter::Handle::ShutdownOnUIThread() {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::UI);
|
||||
if (main_request_context_getter_.get()) {
|
||||
if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestContextGetter::NotifyContextShuttingDown,
|
||||
base::RetainedRef(main_request_context_getter_),
|
||||
std::move(resource_context_)));
|
||||
}
|
||||
}
|
||||
|
||||
if (!BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this))
|
||||
delete this;
|
||||
}
|
||||
|
||||
URLRequestContextGetter::URLRequestContextGetter(
|
||||
URLRequestContextGetter::Handle* context_handle,
|
||||
content::ProtocolHandlerMap* protocol_handlers,
|
||||
content::URLRequestInterceptorScopedVector protocol_interceptors)
|
||||
: context_handle_(context_handle),
|
||||
url_request_context_(nullptr),
|
||||
protocol_interceptors_(std::move(protocol_interceptors)),
|
||||
context_shutting_down_(false) {
|
||||
// Must first be created on the UI thread.
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::UI);
|
||||
|
||||
if (protocol_handlers)
|
||||
std::swap(protocol_handlers_, *protocol_handlers);
|
||||
}
|
||||
|
||||
URLRequestContextGetter::~URLRequestContextGetter() {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
// NotifyContextShuttingDown should have been called.
|
||||
DCHECK(context_shutting_down_);
|
||||
}
|
||||
|
||||
void URLRequestContextGetter::NotifyContextShuttingDown(
|
||||
std::unique_ptr<content::ResourceContext> resource_context) {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
|
||||
// todo(brenca): remove once C70 lands
|
||||
if (url_request_context_ && url_request_context_->cookie_store()) {
|
||||
url_request_context_->cookie_store()->FlushStore(base::NullCallback());
|
||||
}
|
||||
|
||||
context_shutting_down_ = true;
|
||||
resource_context.reset();
|
||||
net::URLRequestContextGetter::NotifyContextShuttingDown();
|
||||
}
|
||||
|
||||
net::URLRequestContext* URLRequestContextGetter::GetURLRequestContext() {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
|
||||
if (context_shutting_down_)
|
||||
return nullptr;
|
||||
|
||||
if (!url_request_context_) {
|
||||
std::unique_ptr<network::URLRequestContextBuilderMojo> builder =
|
||||
std::make_unique<network::URLRequestContextBuilderMojo>();
|
||||
|
||||
// Enable file:// support.
|
||||
builder->set_file_enabled(true);
|
||||
|
||||
auto network_delegate = std::make_unique<AtomNetworkDelegate>();
|
||||
network_delegate_ = network_delegate.get();
|
||||
builder->set_network_delegate(std::move(network_delegate));
|
||||
|
||||
ct_delegate_.reset(new RequireCTDelegate);
|
||||
auto cert_verifier = std::make_unique<AtomCertVerifier>(ct_delegate_.get());
|
||||
builder->SetCertVerifier(std::move(cert_verifier));
|
||||
|
||||
builder->SetCreateHttpTransactionFactoryCallback(
|
||||
base::BindOnce(&content::CreateDevToolsNetworkTransactionFactory));
|
||||
|
||||
builder->set_ct_verifier(std::make_unique<net::MultiLogCTVerifier>());
|
||||
|
||||
auto* network_service = content::GetNetworkServiceImpl();
|
||||
network_context_ = network_service->CreateNetworkContextWithBuilder(
|
||||
std::move(context_handle_->main_network_context_request_),
|
||||
std::move(context_handle_->main_network_context_params_),
|
||||
std::move(builder), &url_request_context_);
|
||||
|
||||
net::TransportSecurityState* transport_security_state =
|
||||
url_request_context_->transport_security_state();
|
||||
transport_security_state->SetRequireCTDelegate(ct_delegate_.get());
|
||||
|
||||
// Add custom standard schemes to cookie schemes.
|
||||
auto* cookie_monster =
|
||||
static_cast<net::CookieMonster*>(url_request_context_->cookie_store());
|
||||
std::vector<std::string> cookie_schemes(
|
||||
{url::kHttpScheme, url::kHttpsScheme, url::kWsScheme, url::kWssScheme});
|
||||
const auto& custom_standard_schemes = atom::api::GetStandardSchemes();
|
||||
cookie_schemes.insert(cookie_schemes.end(), custom_standard_schemes.begin(),
|
||||
custom_standard_schemes.end());
|
||||
cookie_monster->SetCookieableSchemes(cookie_schemes);
|
||||
|
||||
// Setup handlers for custom job factory.
|
||||
top_job_factory_.reset(new AtomURLRequestJobFactory);
|
||||
SetupAtomURLRequestJobFactory(&protocol_handlers_, url_request_context_,
|
||||
top_job_factory_.get());
|
||||
std::unique_ptr<net::URLRequestJobFactory> inner_job_factory(
|
||||
new net::URLRequestJobFactoryImpl);
|
||||
if (!protocol_interceptors_.empty()) {
|
||||
// Set up interceptors in the reverse order.
|
||||
for (auto it = protocol_interceptors_.rbegin();
|
||||
it != protocol_interceptors_.rend(); ++it) {
|
||||
inner_job_factory.reset(new net::URLRequestInterceptingJobFactory(
|
||||
std::move(inner_job_factory), std::move(*it)));
|
||||
}
|
||||
protocol_interceptors_.clear();
|
||||
}
|
||||
top_job_factory_->Chain(std::move(inner_job_factory));
|
||||
url_request_context_->set_job_factory(top_job_factory_.get());
|
||||
}
|
||||
|
||||
return url_request_context_;
|
||||
}
|
||||
|
||||
scoped_refptr<base::SingleThreadTaskRunner>
|
||||
URLRequestContextGetter::GetNetworkTaskRunner() const {
|
||||
return base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO});
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,114 +0,0 @@
|
||||
// Copyright (c) 2018 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_URL_REQUEST_CONTEXT_GETTER_H_
|
||||
#define ATOM_BROWSER_NET_URL_REQUEST_CONTEXT_GETTER_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "base/files/file_path.h"
|
||||
#include "content/public/browser/browser_context.h"
|
||||
#include "content/public/browser/resource_context.h"
|
||||
#include "net/url_request/url_request_context.h"
|
||||
#include "net/url_request/url_request_context_getter.h"
|
||||
#include "services/network/public/mojom/network_service.mojom.h"
|
||||
|
||||
#if DCHECK_IS_ON()
|
||||
#include "base/debug/leak_tracker.h"
|
||||
#endif
|
||||
|
||||
namespace atom {
|
||||
|
||||
class AtomBrowserContext;
|
||||
class AtomNetworkDelegate;
|
||||
class AtomURLRequestJobFactory;
|
||||
class RequireCTDelegate;
|
||||
class ResourceContext;
|
||||
|
||||
class URLRequestContextGetter : public net::URLRequestContextGetter {
|
||||
public:
|
||||
// net::URLRequestContextGetter:
|
||||
net::URLRequestContext* GetURLRequestContext() override;
|
||||
scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
|
||||
const override;
|
||||
|
||||
// Discard reference to URLRequestContext and inform observers to
|
||||
// shutdown. Must be called only on IO thread.
|
||||
void NotifyContextShuttingDown(std::unique_ptr<content::ResourceContext>);
|
||||
|
||||
AtomURLRequestJobFactory* job_factory() const {
|
||||
return top_job_factory_.get();
|
||||
}
|
||||
|
||||
AtomNetworkDelegate* network_delegate() const { return network_delegate_; }
|
||||
|
||||
private:
|
||||
friend class AtomBrowserContext;
|
||||
|
||||
// Responsible for destroying URLRequestContextGetter
|
||||
// on the IO thread.
|
||||
class Handle {
|
||||
public:
|
||||
explicit Handle(base::WeakPtr<AtomBrowserContext> browser_context);
|
||||
~Handle();
|
||||
|
||||
scoped_refptr<URLRequestContextGetter> CreateMainRequestContextGetter(
|
||||
content::ProtocolHandlerMap* protocol_handlers,
|
||||
content::URLRequestInterceptorScopedVector protocol_interceptors);
|
||||
content::ResourceContext* GetResourceContext();
|
||||
scoped_refptr<URLRequestContextGetter> GetMainRequestContextGetter();
|
||||
network::mojom::NetworkContextPtr GetNetworkContext();
|
||||
network::mojom::NetworkContextParamsPtr CreateNetworkContextParams();
|
||||
|
||||
void ShutdownOnUIThread();
|
||||
|
||||
private:
|
||||
friend class URLRequestContextGetter;
|
||||
void LazyInitialize();
|
||||
|
||||
scoped_refptr<URLRequestContextGetter> main_request_context_getter_;
|
||||
std::unique_ptr<content::ResourceContext> resource_context_;
|
||||
base::WeakPtr<AtomBrowserContext> browser_context_;
|
||||
// This is a NetworkContext interface that uses URLRequestContextGetter
|
||||
// NetworkContext, ownership is passed to StoragePartition when
|
||||
// CreateMainNetworkContext is called.
|
||||
network::mojom::NetworkContextPtr main_network_context_;
|
||||
// Request corresponding to |main_network_context_|. Ownership
|
||||
// is passed to network service.
|
||||
network::mojom::NetworkContextRequest main_network_context_request_;
|
||||
network::mojom::NetworkContextParamsPtr main_network_context_params_;
|
||||
bool initialized_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(Handle);
|
||||
};
|
||||
|
||||
URLRequestContextGetter(
|
||||
URLRequestContextGetter::Handle* context_handle,
|
||||
content::ProtocolHandlerMap* protocol_handlers,
|
||||
content::URLRequestInterceptorScopedVector protocol_interceptors);
|
||||
~URLRequestContextGetter() override;
|
||||
|
||||
#if DCHECK_IS_ON()
|
||||
base::debug::LeakTracker<URLRequestContextGetter> leak_tracker_;
|
||||
#endif
|
||||
|
||||
std::unique_ptr<RequireCTDelegate> ct_delegate_;
|
||||
std::unique_ptr<AtomURLRequestJobFactory> top_job_factory_;
|
||||
std::unique_ptr<network::mojom::NetworkContext> network_context_;
|
||||
|
||||
URLRequestContextGetter::Handle* context_handle_;
|
||||
net::URLRequestContext* url_request_context_;
|
||||
AtomNetworkDelegate* network_delegate_;
|
||||
content::ProtocolHandlerMap protocol_handlers_;
|
||||
content::URLRequestInterceptorScopedVector protocol_interceptors_;
|
||||
bool context_shutting_down_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(URLRequestContextGetter);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_URL_REQUEST_CONTEXT_GETTER_H_
|
||||
@@ -1,342 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/url_request_fetch_job.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/api/atom_api_session.h"
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "atom/common/native_mate_converters/v8_value_converter.h"
|
||||
#include "base/guid.h"
|
||||
#include "base/memory/ptr_util.h"
|
||||
#include "base/strings/string_util.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
#include "net/base/io_buffer.h"
|
||||
#include "net/base/net_errors.h"
|
||||
#include "net/http/http_response_headers.h"
|
||||
#include "net/url_request/url_fetcher.h"
|
||||
#include "net/url_request/url_fetcher_response_writer.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
// Convert string to RequestType.
|
||||
net::URLFetcher::RequestType GetRequestType(const std::string& raw) {
|
||||
std::string method = base::ToUpperASCII(raw);
|
||||
if (method.empty() || method == "GET")
|
||||
return net::URLFetcher::GET;
|
||||
else if (method == "POST")
|
||||
return net::URLFetcher::POST;
|
||||
else if (method == "HEAD")
|
||||
return net::URLFetcher::HEAD;
|
||||
else if (method == "DELETE")
|
||||
return net::URLFetcher::DELETE_REQUEST;
|
||||
else if (method == "PUT")
|
||||
return net::URLFetcher::PUT;
|
||||
else if (method == "PATCH")
|
||||
return net::URLFetcher::PATCH;
|
||||
else // Use "GET" as fallback.
|
||||
return net::URLFetcher::GET;
|
||||
}
|
||||
|
||||
// Pipe the response writer back to URLRequestFetchJob.
|
||||
class ResponsePiper : public net::URLFetcherResponseWriter {
|
||||
public:
|
||||
explicit ResponsePiper(URLRequestFetchJob* job) : job_(job) {}
|
||||
|
||||
// net::URLFetcherResponseWriter:
|
||||
int Initialize(net::CompletionOnceCallback callback) override {
|
||||
return net::OK;
|
||||
}
|
||||
int Write(net::IOBuffer* buffer,
|
||||
int num_bytes,
|
||||
net::CompletionOnceCallback callback) override {
|
||||
if (first_write_) {
|
||||
// The URLFetcherResponseWriter doesn't have an event when headers have
|
||||
// been read, so we have to emulate by hooking to first write event.
|
||||
job_->HeadersCompleted();
|
||||
first_write_ = false;
|
||||
}
|
||||
return job_->DataAvailable(buffer, num_bytes, std::move(callback));
|
||||
}
|
||||
int Finish(int net_error, net::CompletionOnceCallback callback) override {
|
||||
return net::OK;
|
||||
}
|
||||
|
||||
private:
|
||||
bool first_write_ = true;
|
||||
URLRequestFetchJob* job_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(ResponsePiper);
|
||||
};
|
||||
|
||||
void BeforeStartInUI(base::WeakPtr<URLRequestFetchJob> job,
|
||||
mate::Arguments* args) {
|
||||
// Pass whatever user passed to the actaul request job.
|
||||
v8::Local<v8::Value> value;
|
||||
mate::Dictionary options;
|
||||
if (!args->GetNext(&value) ||
|
||||
!mate::ConvertFromV8(args->isolate(), value, &options)) {
|
||||
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestFetchJob::OnError, job,
|
||||
net::ERR_NOT_IMPLEMENTED));
|
||||
return;
|
||||
}
|
||||
|
||||
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter;
|
||||
scoped_refptr<AtomBrowserContext> custom_browser_context;
|
||||
// When |session| is set to |null| we use a new request context for fetch
|
||||
// job.
|
||||
if (options.Get("session", &value)) {
|
||||
if (value->IsNull()) {
|
||||
// We have to create the URLRequestContextGetter on UI thread.
|
||||
custom_browser_context =
|
||||
AtomBrowserContext::From(base::GenerateGUID(), true);
|
||||
url_request_context_getter = custom_browser_context->GetRequestContext();
|
||||
} else {
|
||||
mate::Handle<api::Session> session;
|
||||
if (mate::ConvertFromV8(args->isolate(), value, &session) &&
|
||||
!session.IsEmpty()) {
|
||||
AtomBrowserContext* browser_context = session->browser_context();
|
||||
url_request_context_getter = browser_context->GetRequestContext();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
V8ValueConverter converter;
|
||||
v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();
|
||||
std::unique_ptr<base::Value> request_options(
|
||||
converter.FromV8Value(value, context));
|
||||
|
||||
int error = net::OK;
|
||||
if (!request_options || !request_options->is_dict())
|
||||
error = net::ERR_NOT_IMPLEMENTED;
|
||||
|
||||
JsAsker::IsErrorOptions(request_options.get(), &error);
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestFetchJob::StartAsync, job,
|
||||
base::RetainedRef(url_request_context_getter),
|
||||
base::RetainedRef(custom_browser_context),
|
||||
std::move(request_options), error));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
URLRequestFetchJob::URLRequestFetchJob(net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate)
|
||||
: net::URLRequestJob(request, network_delegate), weak_factory_(this) {}
|
||||
|
||||
URLRequestFetchJob::~URLRequestFetchJob() = default;
|
||||
|
||||
void URLRequestFetchJob::Start() {
|
||||
auto request_details = std::make_unique<base::DictionaryValue>();
|
||||
FillRequestDetails(request_details.get(), request());
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&JsAsker::AskForOptions, base::Unretained(isolate()),
|
||||
handler(), std::move(request_details),
|
||||
base::Bind(&BeforeStartInUI, weak_factory_.GetWeakPtr())));
|
||||
}
|
||||
|
||||
void URLRequestFetchJob::StartAsync(
|
||||
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter,
|
||||
scoped_refptr<AtomBrowserContext> browser_context,
|
||||
std::unique_ptr<base::Value> options,
|
||||
int error) {
|
||||
if (error != net::OK) {
|
||||
NotifyStartError(
|
||||
net::URLRequestStatus(net::URLRequestStatus::FAILED, error));
|
||||
return;
|
||||
}
|
||||
|
||||
std::string url, method, referrer;
|
||||
base::DictionaryValue* upload_data = nullptr;
|
||||
base::DictionaryValue* dict =
|
||||
static_cast<base::DictionaryValue*>(options.get());
|
||||
dict->GetString("url", &url);
|
||||
dict->GetString("method", &method);
|
||||
dict->GetString("referrer", &referrer);
|
||||
dict->GetDictionary("uploadData", &upload_data);
|
||||
|
||||
// Check if URL is valid.
|
||||
GURL formated_url(url);
|
||||
if (!formated_url.is_valid()) {
|
||||
NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED,
|
||||
net::ERR_INVALID_URL));
|
||||
return;
|
||||
}
|
||||
|
||||
// Use |request|'s method if |method| is not specified.
|
||||
net::URLFetcher::RequestType request_type;
|
||||
if (method.empty())
|
||||
request_type = GetRequestType(request()->method());
|
||||
else
|
||||
request_type = GetRequestType(method);
|
||||
|
||||
fetcher_ = net::URLFetcher::Create(formated_url, request_type, this);
|
||||
fetcher_->SaveResponseWithWriter(base::WrapUnique(new ResponsePiper(this)));
|
||||
|
||||
// A request context getter is passed by the user.
|
||||
if (url_request_context_getter)
|
||||
fetcher_->SetRequestContext(url_request_context_getter.get());
|
||||
else
|
||||
fetcher_->SetRequestContext(request_context_getter());
|
||||
|
||||
// Use |request|'s referrer if |referrer| is not specified.
|
||||
if (referrer.empty())
|
||||
fetcher_->SetReferrer(request()->referrer());
|
||||
else
|
||||
fetcher_->SetReferrer(referrer);
|
||||
|
||||
// Set the data needed for POSTs.
|
||||
if (upload_data && request_type == net::URLFetcher::POST) {
|
||||
std::string content_type, data;
|
||||
upload_data->GetString("contentType", &content_type);
|
||||
upload_data->GetString("data", &data);
|
||||
fetcher_->SetUploadData(content_type, data);
|
||||
}
|
||||
|
||||
// Use |request|'s headers.
|
||||
fetcher_->SetExtraRequestHeaders(
|
||||
request()->extra_request_headers().ToString());
|
||||
|
||||
fetcher_->Start();
|
||||
|
||||
if (browser_context)
|
||||
custom_browser_context_ = browser_context;
|
||||
}
|
||||
|
||||
void URLRequestFetchJob::OnError(int error) {
|
||||
NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED, error));
|
||||
}
|
||||
|
||||
void URLRequestFetchJob::HeadersCompleted() {
|
||||
response_info_.reset(new net::HttpResponseInfo);
|
||||
response_info_->headers = fetcher_->GetResponseHeaders();
|
||||
NotifyHeadersComplete();
|
||||
}
|
||||
|
||||
int URLRequestFetchJob::DataAvailable(net::IOBuffer* buffer,
|
||||
int num_bytes,
|
||||
net::CompletionOnceCallback callback) {
|
||||
// When pending_buffer_ is empty, there's no ReadRawData() operation waiting
|
||||
// for IO completion, we have to save the parameters until the request is
|
||||
// ready to read data.
|
||||
if (!pending_buffer_.get()) {
|
||||
write_buffer_ = buffer;
|
||||
write_num_bytes_ = num_bytes;
|
||||
write_callback_ = std::move(callback);
|
||||
return net::ERR_IO_PENDING;
|
||||
}
|
||||
|
||||
// Write data to the pending buffer and clear them after the writing.
|
||||
int bytes_read = BufferCopy(buffer, num_bytes, pending_buffer_.get(),
|
||||
pending_buffer_size_);
|
||||
ClearPendingBuffer();
|
||||
ReadRawDataComplete(bytes_read);
|
||||
return bytes_read;
|
||||
}
|
||||
|
||||
void URLRequestFetchJob::Kill() {
|
||||
weak_factory_.InvalidateWeakPtrs();
|
||||
net::URLRequestJob::Kill();
|
||||
fetcher_.reset();
|
||||
custom_browser_context_ = nullptr;
|
||||
}
|
||||
|
||||
int URLRequestFetchJob::ReadRawData(net::IOBuffer* dest, int dest_size) {
|
||||
if (GetResponseCode() == 204) {
|
||||
request()->set_received_response_content_length(prefilter_bytes_read());
|
||||
return net::OK;
|
||||
}
|
||||
|
||||
// When write_buffer_ is empty, there is no data valable yet, we have to save
|
||||
// the dest buffer util DataAvailable.
|
||||
if (!write_buffer_.get()) {
|
||||
pending_buffer_ = dest;
|
||||
pending_buffer_size_ = dest_size;
|
||||
return net::ERR_IO_PENDING;
|
||||
}
|
||||
|
||||
// Read from the write buffer and clear them after reading.
|
||||
int bytes_read =
|
||||
BufferCopy(write_buffer_.get(), write_num_bytes_, dest, dest_size);
|
||||
ClearWriteBuffer();
|
||||
if (!write_callback_.is_null())
|
||||
std::move(write_callback_).Run(bytes_read);
|
||||
return bytes_read;
|
||||
}
|
||||
|
||||
bool URLRequestFetchJob::GetMimeType(std::string* mime_type) const {
|
||||
if (!response_info_ || !response_info_->headers)
|
||||
return false;
|
||||
|
||||
return response_info_->headers->GetMimeType(mime_type);
|
||||
}
|
||||
|
||||
void URLRequestFetchJob::GetResponseInfo(net::HttpResponseInfo* info) {
|
||||
if (response_info_)
|
||||
*info = *response_info_;
|
||||
}
|
||||
|
||||
int URLRequestFetchJob::GetResponseCode() const {
|
||||
if (!response_info_ || !response_info_->headers)
|
||||
return -1;
|
||||
|
||||
return response_info_->headers->response_code();
|
||||
}
|
||||
|
||||
void URLRequestFetchJob::OnURLFetchComplete(const net::URLFetcher* source) {
|
||||
ClearPendingBuffer();
|
||||
ClearWriteBuffer();
|
||||
|
||||
if (fetcher_->GetStatus().is_success()) {
|
||||
if (!response_info_) {
|
||||
// Since we notify header completion only after first write there will be
|
||||
// no response object constructed for http respones with no content 204.
|
||||
// We notify header completion here.
|
||||
HeadersCompleted();
|
||||
return;
|
||||
}
|
||||
if (request_->status().is_io_pending()) {
|
||||
ReadRawDataComplete(0);
|
||||
}
|
||||
} else {
|
||||
NotifyStartError(fetcher_->GetStatus());
|
||||
}
|
||||
}
|
||||
|
||||
int URLRequestFetchJob::BufferCopy(net::IOBuffer* source,
|
||||
int num_bytes,
|
||||
net::IOBuffer* target,
|
||||
int target_size) {
|
||||
int bytes_written = std::min(num_bytes, target_size);
|
||||
memcpy(target->data(), source->data(), bytes_written);
|
||||
return bytes_written;
|
||||
}
|
||||
|
||||
void URLRequestFetchJob::ClearPendingBuffer() {
|
||||
pending_buffer_ = nullptr;
|
||||
pending_buffer_size_ = 0;
|
||||
}
|
||||
|
||||
void URLRequestFetchJob::ClearWriteBuffer() {
|
||||
write_buffer_ = nullptr;
|
||||
write_num_bytes_ = 0;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,81 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_URL_REQUEST_FETCH_JOB_H_
|
||||
#define ATOM_BROWSER_NET_URL_REQUEST_FETCH_JOB_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "atom/browser/net/js_asker.h"
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "net/url_request/url_fetcher_delegate.h"
|
||||
#include "net/url_request/url_request_context_getter.h"
|
||||
#include "net/url_request/url_request_job.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class AtomBrowserContext;
|
||||
|
||||
class URLRequestFetchJob : public JsAsker,
|
||||
public net::URLRequestJob,
|
||||
public net::URLFetcherDelegate {
|
||||
public:
|
||||
URLRequestFetchJob(net::URLRequest*, net::NetworkDelegate*);
|
||||
~URLRequestFetchJob() override;
|
||||
|
||||
void StartAsync(
|
||||
scoped_refptr<net::URLRequestContextGetter> request_context_getter,
|
||||
scoped_refptr<AtomBrowserContext> browser_context,
|
||||
std::unique_ptr<base::Value> options,
|
||||
int error);
|
||||
void OnError(int error);
|
||||
|
||||
// Called by response writer.
|
||||
void HeadersCompleted();
|
||||
int DataAvailable(net::IOBuffer* buffer,
|
||||
int num_bytes,
|
||||
net::CompletionOnceCallback callback);
|
||||
|
||||
protected:
|
||||
// net::URLRequestJob:
|
||||
void Start() override;
|
||||
void Kill() override;
|
||||
int ReadRawData(net::IOBuffer* buf, int buf_size) override;
|
||||
bool GetMimeType(std::string* mime_type) const override;
|
||||
void GetResponseInfo(net::HttpResponseInfo* info) override;
|
||||
int GetResponseCode() const override;
|
||||
|
||||
// net::URLFetcherDelegate:
|
||||
void OnURLFetchComplete(const net::URLFetcher* source) override;
|
||||
|
||||
private:
|
||||
int BufferCopy(net::IOBuffer* source,
|
||||
int num_bytes,
|
||||
net::IOBuffer* target,
|
||||
int target_size);
|
||||
void ClearPendingBuffer();
|
||||
void ClearWriteBuffer();
|
||||
|
||||
scoped_refptr<AtomBrowserContext> custom_browser_context_;
|
||||
std::unique_ptr<net::URLFetcher> fetcher_;
|
||||
std::unique_ptr<net::HttpResponseInfo> response_info_;
|
||||
|
||||
// Saved arguments passed to ReadRawData.
|
||||
scoped_refptr<net::IOBuffer> pending_buffer_;
|
||||
int pending_buffer_size_ = 0;
|
||||
|
||||
// Saved arguments passed to DataAvailable.
|
||||
scoped_refptr<net::IOBuffer> write_buffer_;
|
||||
int write_num_bytes_ = 0;
|
||||
net::CompletionOnceCallback write_callback_;
|
||||
|
||||
base::WeakPtrFactory<URLRequestFetchJob> weak_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(URLRequestFetchJob);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_URL_REQUEST_FETCH_JOB_H_
|
||||
@@ -1,257 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/url_request_stream_job.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/common/api/event_emitter_caller.h"
|
||||
#include "atom/common/atom_constants.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "atom/common/node_includes.h"
|
||||
#include "base/strings/string_number_conversions.h"
|
||||
#include "base/strings/string_util.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "base/threading/thread_task_runner_handle.h"
|
||||
#include "base/time/time.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
#include "net/base/net_errors.h"
|
||||
#include "net/filter/gzip_source_stream.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
void BeforeStartInUI(base::WeakPtr<URLRequestStreamJob> job,
|
||||
mate::Arguments* args) {
|
||||
v8::Local<v8::Value> value;
|
||||
int error = net::OK;
|
||||
bool ended = false;
|
||||
if (!args->GetNext(&value) || !value->IsObject()) {
|
||||
// Invalid opts.
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestStreamJob::OnError, job, net::ERR_FAILED));
|
||||
return;
|
||||
}
|
||||
|
||||
mate::Dictionary opts(args->isolate(), v8::Local<v8::Object>::Cast(value));
|
||||
int status_code;
|
||||
if (!opts.Get("statusCode", &status_code)) {
|
||||
// assume HTTP OK if statusCode is not passed.
|
||||
status_code = 200;
|
||||
}
|
||||
std::string status("HTTP/1.1 ");
|
||||
status.append(base::IntToString(status_code));
|
||||
status.append(" ");
|
||||
status.append(
|
||||
net::GetHttpReasonPhrase(static_cast<net::HttpStatusCode>(status_code)));
|
||||
status.append("\0\0", 2);
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers(
|
||||
new net::HttpResponseHeaders(status));
|
||||
|
||||
if (opts.Get("headers", &value)) {
|
||||
mate::Converter<net::HttpResponseHeaders*>::FromV8(args->isolate(), value,
|
||||
response_headers.get());
|
||||
}
|
||||
|
||||
if (!opts.Get("data", &value)) {
|
||||
// Assume the opts is already a stream
|
||||
value = opts.GetHandle();
|
||||
} else if (value->IsNullOrUndefined()) {
|
||||
// "data" was explicitly passed as null or undefined, assume the user wants
|
||||
// to send an empty body.
|
||||
ended = true;
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestStreamJob::StartAsync, job, nullptr,
|
||||
base::RetainedRef(response_headers), ended, error));
|
||||
return;
|
||||
}
|
||||
|
||||
mate::Dictionary data(args->isolate(), v8::Local<v8::Object>::Cast(value));
|
||||
if (!data.Get("on", &value) || !value->IsFunction() ||
|
||||
!data.Get("removeListener", &value) || !value->IsFunction()) {
|
||||
// If data is passed but it is not a stream, signal an error.
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestStreamJob::OnError, job, net::ERR_FAILED));
|
||||
return;
|
||||
}
|
||||
|
||||
auto subscriber = base::MakeRefCounted<mate::StreamSubscriber>(
|
||||
args->isolate(), data.GetHandle(), job,
|
||||
base::ThreadTaskRunnerHandle::Get());
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestStreamJob::StartAsync, job, subscriber,
|
||||
base::RetainedRef(response_headers), ended, error));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
URLRequestStreamJob::URLRequestStreamJob(net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate)
|
||||
: net::URLRequestJob(request, network_delegate),
|
||||
pending_buf_(nullptr),
|
||||
pending_buf_size_(0),
|
||||
ended_(false),
|
||||
response_headers_(nullptr),
|
||||
weak_factory_(this) {}
|
||||
|
||||
URLRequestStreamJob::~URLRequestStreamJob() {
|
||||
DCHECK(!subscriber_ || subscriber_->HasOneRef());
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::Start() {
|
||||
auto request_details = std::make_unique<base::DictionaryValue>();
|
||||
FillRequestDetails(request_details.get(), request());
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&JsAsker::AskForOptions, base::Unretained(isolate()),
|
||||
handler(), std::move(request_details),
|
||||
base::Bind(&BeforeStartInUI, weak_factory_.GetWeakPtr())));
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::StartAsync(
|
||||
scoped_refptr<mate::StreamSubscriber> subscriber,
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers,
|
||||
bool ended,
|
||||
int error) {
|
||||
if (error != net::OK) {
|
||||
NotifyStartError(
|
||||
net::URLRequestStatus(net::URLRequestStatus::FAILED, error));
|
||||
return;
|
||||
}
|
||||
|
||||
ended_ = ended;
|
||||
response_headers_ = response_headers;
|
||||
subscriber_ = subscriber;
|
||||
request_start_time_ = base::TimeTicks::Now();
|
||||
NotifyHeadersComplete();
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::OnData(std::vector<char>&& buffer) { // NOLINT
|
||||
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
|
||||
if (write_buffer_.empty()) {
|
||||
// Quick branch without copying.
|
||||
write_buffer_ = std::move(buffer);
|
||||
} else {
|
||||
// write_buffer_ += buffer
|
||||
size_t len = write_buffer_.size();
|
||||
write_buffer_.resize(len + buffer.size());
|
||||
std::copy(buffer.begin(), buffer.end(), write_buffer_.begin() + len);
|
||||
}
|
||||
|
||||
// Copy to output.
|
||||
if (pending_buf_) {
|
||||
int len = BufferCopy(&write_buffer_, pending_buf_.get(), pending_buf_size_);
|
||||
write_buffer_.erase(write_buffer_.begin(), write_buffer_.begin() + len);
|
||||
pending_buf_ = nullptr;
|
||||
pending_buf_size_ = 0;
|
||||
ReadRawDataComplete(len);
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::OnEnd() {
|
||||
ended_ = true;
|
||||
if (pending_buf_) {
|
||||
ReadRawDataComplete(0);
|
||||
}
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::OnError(int error) {
|
||||
NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED, error));
|
||||
}
|
||||
|
||||
int URLRequestStreamJob::ReadRawData(net::IOBuffer* dest, int dest_size) {
|
||||
response_start_time_ = base::TimeTicks::Now();
|
||||
|
||||
if (ended_ && write_buffer_.empty())
|
||||
return 0;
|
||||
|
||||
// When write_buffer_ is empty, there is no data valable yet, we have to save
|
||||
// the dest buffer util DataAvailable.
|
||||
if (write_buffer_.empty()) {
|
||||
pending_buf_ = dest;
|
||||
pending_buf_size_ = dest_size;
|
||||
return net::ERR_IO_PENDING;
|
||||
}
|
||||
|
||||
// Read from the write buffer and clear them after reading.
|
||||
int len = BufferCopy(&write_buffer_, dest, dest_size);
|
||||
write_buffer_.erase(write_buffer_.begin(), write_buffer_.begin() + len);
|
||||
return len;
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::DoneReading() {
|
||||
write_buffer_.clear();
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::DoneReadingRedirectResponse() {
|
||||
if (subscriber_) {
|
||||
DCHECK(subscriber_->HasAtLeastOneRef());
|
||||
subscriber_ = nullptr;
|
||||
}
|
||||
DoneReading();
|
||||
}
|
||||
|
||||
std::unique_ptr<net::SourceStream> URLRequestStreamJob::SetUpSourceStream() {
|
||||
std::unique_ptr<net::SourceStream> source =
|
||||
net::URLRequestJob::SetUpSourceStream();
|
||||
size_t i = 0;
|
||||
std::string type;
|
||||
while (response_headers_->EnumerateHeader(&i, "Content-Encoding", &type)) {
|
||||
if (base::LowerCaseEqualsASCII(type, "gzip") ||
|
||||
base::LowerCaseEqualsASCII(type, "x-gzip")) {
|
||||
return net::GzipSourceStream::Create(std::move(source),
|
||||
net::SourceStream::TYPE_GZIP);
|
||||
} else if (base::LowerCaseEqualsASCII(type, "deflate")) {
|
||||
return net::GzipSourceStream::Create(std::move(source),
|
||||
net::SourceStream::TYPE_DEFLATE);
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
bool URLRequestStreamJob::GetMimeType(std::string* mime_type) const {
|
||||
return response_headers_->GetMimeType(mime_type);
|
||||
}
|
||||
|
||||
int URLRequestStreamJob::GetResponseCode() const {
|
||||
return response_headers_->response_code();
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::GetResponseInfo(net::HttpResponseInfo* info) {
|
||||
info->headers = response_headers_;
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::GetLoadTimingInfo(
|
||||
net::LoadTimingInfo* load_timing_info) const {
|
||||
load_timing_info->send_start = request_start_time_;
|
||||
load_timing_info->send_end = request_start_time_;
|
||||
load_timing_info->request_start = request_start_time_;
|
||||
load_timing_info->receive_headers_end = response_start_time_;
|
||||
}
|
||||
|
||||
void URLRequestStreamJob::Kill() {
|
||||
weak_factory_.InvalidateWeakPtrs();
|
||||
net::URLRequestJob::Kill();
|
||||
}
|
||||
|
||||
int URLRequestStreamJob::BufferCopy(std::vector<char>* source,
|
||||
net::IOBuffer* target,
|
||||
int target_size) {
|
||||
int bytes_written = std::min(static_cast<int>(source->size()), target_size);
|
||||
memcpy(target->data(), source->data(), bytes_written);
|
||||
return bytes_written;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,73 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_URL_REQUEST_STREAM_JOB_H_
|
||||
#define ATOM_BROWSER_NET_URL_REQUEST_STREAM_JOB_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "atom/browser/api/stream_subscriber.h"
|
||||
#include "atom/browser/net/js_asker.h"
|
||||
#include "base/memory/scoped_refptr.h"
|
||||
#include "net/base/io_buffer.h"
|
||||
#include "net/http/http_status_code.h"
|
||||
#include "net/url_request/url_request_job.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class URLRequestStreamJob : public JsAsker, public net::URLRequestJob {
|
||||
public:
|
||||
URLRequestStreamJob(net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate);
|
||||
~URLRequestStreamJob() override;
|
||||
|
||||
void StartAsync(scoped_refptr<mate::StreamSubscriber> subscriber,
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers,
|
||||
bool ended,
|
||||
int error);
|
||||
|
||||
void OnData(std::vector<char>&& buffer); // NOLINT
|
||||
void OnEnd();
|
||||
void OnError(int error);
|
||||
|
||||
protected:
|
||||
// URLRequestJob
|
||||
void Start() override;
|
||||
int ReadRawData(net::IOBuffer* buf, int buf_size) override;
|
||||
void DoneReading() override;
|
||||
void DoneReadingRedirectResponse() override;
|
||||
std::unique_ptr<net::SourceStream> SetUpSourceStream() override;
|
||||
bool GetMimeType(std::string* mime_type) const override;
|
||||
int GetResponseCode() const override;
|
||||
void GetResponseInfo(net::HttpResponseInfo* info) override;
|
||||
void GetLoadTimingInfo(net::LoadTimingInfo* load_timing_info) const override;
|
||||
void Kill() override;
|
||||
|
||||
private:
|
||||
int BufferCopy(std::vector<char>* source,
|
||||
net::IOBuffer* target,
|
||||
int target_size);
|
||||
|
||||
// Saved arguments passed to ReadRawData.
|
||||
scoped_refptr<net::IOBuffer> pending_buf_;
|
||||
int pending_buf_size_;
|
||||
|
||||
// Saved arguments passed to OnData.
|
||||
std::vector<char> write_buffer_;
|
||||
|
||||
bool ended_;
|
||||
base::TimeTicks request_start_time_;
|
||||
base::TimeTicks response_start_time_;
|
||||
scoped_refptr<net::HttpResponseHeaders> response_headers_;
|
||||
scoped_refptr<mate::StreamSubscriber> subscriber_;
|
||||
|
||||
base::WeakPtrFactory<URLRequestStreamJob> weak_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(URLRequestStreamJob);
|
||||
};
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_URL_REQUEST_STREAM_JOB_H_
|
||||
@@ -1,116 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/net/url_request_string_job.h"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/common/atom_constants.h"
|
||||
#include "atom/common/native_mate_converters/net_converter.h"
|
||||
#include "atom/common/native_mate_converters/v8_value_converter.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "net/base/net_errors.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
void BeforeStartInUI(base::WeakPtr<URLRequestStringJob> job,
|
||||
mate::Arguments* args) {
|
||||
v8::Local<v8::Value> value;
|
||||
int error = net::OK;
|
||||
std::unique_ptr<base::Value> request_options = nullptr;
|
||||
|
||||
if (args->GetNext(&value)) {
|
||||
V8ValueConverter converter;
|
||||
v8::Local<v8::Context> context = args->isolate()->GetCurrentContext();
|
||||
request_options = converter.FromV8Value(value, context);
|
||||
}
|
||||
|
||||
if (request_options) {
|
||||
JsAsker::IsErrorOptions(request_options.get(), &error);
|
||||
} else {
|
||||
error = net::ERR_NOT_IMPLEMENTED;
|
||||
}
|
||||
|
||||
base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::IO},
|
||||
base::BindOnce(&URLRequestStringJob::StartAsync, job,
|
||||
std::move(request_options), error));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
URLRequestStringJob::URLRequestStringJob(net::URLRequest* request,
|
||||
net::NetworkDelegate* network_delegate)
|
||||
: net::URLRequestSimpleJob(request, network_delegate),
|
||||
weak_factory_(this) {}
|
||||
|
||||
URLRequestStringJob::~URLRequestStringJob() = default;
|
||||
|
||||
void URLRequestStringJob::Start() {
|
||||
auto request_details = std::make_unique<base::DictionaryValue>();
|
||||
FillRequestDetails(request_details.get(), request());
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {content::BrowserThread::UI},
|
||||
base::BindOnce(&JsAsker::AskForOptions, base::Unretained(isolate()),
|
||||
handler(), std::move(request_details),
|
||||
base::Bind(&BeforeStartInUI, weak_factory_.GetWeakPtr())));
|
||||
}
|
||||
|
||||
void URLRequestStringJob::StartAsync(std::unique_ptr<base::Value> options,
|
||||
int error) {
|
||||
if (error != net::OK) {
|
||||
NotifyStartError(
|
||||
net::URLRequestStatus(net::URLRequestStatus::FAILED, error));
|
||||
return;
|
||||
}
|
||||
|
||||
if (options->is_dict()) {
|
||||
base::DictionaryValue* dict =
|
||||
static_cast<base::DictionaryValue*>(options.get());
|
||||
dict->GetString("mimeType", &mime_type_);
|
||||
dict->GetString("charset", &charset_);
|
||||
dict->GetString("data", &data_);
|
||||
} else if (options->is_string()) {
|
||||
data_ = options->GetString();
|
||||
}
|
||||
net::URLRequestSimpleJob::Start();
|
||||
}
|
||||
|
||||
void URLRequestStringJob::Kill() {
|
||||
weak_factory_.InvalidateWeakPtrs();
|
||||
net::URLRequestSimpleJob::Kill();
|
||||
}
|
||||
|
||||
void URLRequestStringJob::GetResponseInfo(net::HttpResponseInfo* info) {
|
||||
std::string status("HTTP/1.1 200 OK");
|
||||
auto* headers = new net::HttpResponseHeaders(status);
|
||||
|
||||
headers->AddHeader(kCORSHeader);
|
||||
|
||||
if (!mime_type_.empty()) {
|
||||
std::string content_type_header(net::HttpRequestHeaders::kContentType);
|
||||
content_type_header.append(": ");
|
||||
content_type_header.append(mime_type_);
|
||||
headers->AddHeader(content_type_header);
|
||||
}
|
||||
|
||||
info->headers = headers;
|
||||
}
|
||||
|
||||
int URLRequestStringJob::GetData(std::string* mime_type,
|
||||
std::string* charset,
|
||||
std::string* data,
|
||||
net::CompletionOnceCallback callback) const {
|
||||
*mime_type = mime_type_;
|
||||
*charset = charset_;
|
||||
*data = data_;
|
||||
return net::OK;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,46 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NET_URL_REQUEST_STRING_JOB_H_
|
||||
#define ATOM_BROWSER_NET_URL_REQUEST_STRING_JOB_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "atom/browser/net/js_asker.h"
|
||||
#include "net/url_request/url_request_simple_job.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class URLRequestStringJob : public JsAsker, public net::URLRequestSimpleJob {
|
||||
public:
|
||||
URLRequestStringJob(net::URLRequest*, net::NetworkDelegate*);
|
||||
~URLRequestStringJob() override;
|
||||
|
||||
void StartAsync(std::unique_ptr<base::Value> options, int error);
|
||||
|
||||
// URLRequestJob:
|
||||
void Start() override;
|
||||
void GetResponseInfo(net::HttpResponseInfo* info) override;
|
||||
void Kill() override;
|
||||
|
||||
// URLRequestSimpleJob:
|
||||
int GetData(std::string* mime_type,
|
||||
std::string* charset,
|
||||
std::string* data,
|
||||
net::CompletionOnceCallback callback) const override;
|
||||
|
||||
private:
|
||||
std::string mime_type_;
|
||||
std::string charset_;
|
||||
std::string data_;
|
||||
|
||||
base::WeakPtrFactory<URLRequestStringJob> weak_factory_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(URLRequestStringJob);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_NET_URL_REQUEST_STRING_JOB_H_
|
||||
@@ -1,22 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_NOTIFICATIONS_MAC_NOTIFICATION_CENTER_DELEGATE_H_
|
||||
#define ATOM_BROWSER_NOTIFICATIONS_MAC_NOTIFICATION_CENTER_DELEGATE_H_
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
namespace atom {
|
||||
class NotificationPresenterMac;
|
||||
}
|
||||
|
||||
@interface NotificationCenterDelegate
|
||||
: NSObject <NSUserNotificationCenterDelegate> {
|
||||
@private
|
||||
atom::NotificationPresenterMac* presenter_;
|
||||
}
|
||||
- (instancetype)initWithPresenter:(atom::NotificationPresenterMac*)presenter;
|
||||
@end
|
||||
|
||||
#endif // ATOM_BROWSER_NOTIFICATIONS_MAC_NOTIFICATION_CENTER_DELEGATE_H_
|
||||
@@ -1,60 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/render_process_preferences.h"
|
||||
|
||||
#include "atom/common/api/api_messages.h"
|
||||
#include "content/public/browser/notification_service.h"
|
||||
#include "content/public/browser/notification_types.h"
|
||||
#include "content/public/browser/render_process_host.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
RenderProcessPreferences::RenderProcessPreferences(const Predicate& predicate)
|
||||
: predicate_(predicate) {
|
||||
registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED,
|
||||
content::NotificationService::AllBrowserContextsAndSources());
|
||||
}
|
||||
|
||||
RenderProcessPreferences::~RenderProcessPreferences() {}
|
||||
|
||||
int RenderProcessPreferences::AddEntry(const base::DictionaryValue& entry) {
|
||||
int id = ++next_id_;
|
||||
entries_[id] =
|
||||
base::DictionaryValue::From(base::Value::ToUniquePtrValue(entry.Clone()));
|
||||
cache_needs_update_ = true;
|
||||
return id;
|
||||
}
|
||||
|
||||
void RenderProcessPreferences::RemoveEntry(int id) {
|
||||
cache_needs_update_ = true;
|
||||
entries_.erase(id);
|
||||
}
|
||||
|
||||
void RenderProcessPreferences::Observe(
|
||||
int type,
|
||||
const content::NotificationSource& source,
|
||||
const content::NotificationDetails& details) {
|
||||
DCHECK_EQ(type, content::NOTIFICATION_RENDERER_PROCESS_CREATED);
|
||||
content::RenderProcessHost* process =
|
||||
content::Source<content::RenderProcessHost>(source).ptr();
|
||||
|
||||
if (!predicate_.Run(process))
|
||||
return;
|
||||
|
||||
UpdateCache();
|
||||
process->Send(new AtomMsg_UpdatePreferences(cached_entries_));
|
||||
}
|
||||
|
||||
void RenderProcessPreferences::UpdateCache() {
|
||||
if (!cache_needs_update_)
|
||||
return;
|
||||
|
||||
cached_entries_.Clear();
|
||||
for (const auto& iter : entries_)
|
||||
cached_entries_.Append(base::Value::ToUniquePtrValue(iter.second->Clone()));
|
||||
cache_needs_update_ = false;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,61 +0,0 @@
|
||||
// Copyright (c) 2016 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_RENDER_PROCESS_PREFERENCES_H_
|
||||
#define ATOM_BROWSER_RENDER_PROCESS_PREFERENCES_H_
|
||||
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "base/callback.h"
|
||||
#include "base/values.h"
|
||||
#include "content/public/browser/notification_observer.h"
|
||||
#include "content/public/browser/notification_registrar.h"
|
||||
|
||||
namespace content {
|
||||
class RenderProcessHost;
|
||||
}
|
||||
|
||||
namespace atom {
|
||||
|
||||
// Sets user preferences for render processes.
|
||||
class RenderProcessPreferences : public content::NotificationObserver {
|
||||
public:
|
||||
using Predicate = base::Callback<bool(content::RenderProcessHost*)>;
|
||||
|
||||
// The |predicate| is used to determine whether to set preferences for a
|
||||
// render process.
|
||||
explicit RenderProcessPreferences(const Predicate& predicate);
|
||||
~RenderProcessPreferences() override;
|
||||
|
||||
int AddEntry(const base::DictionaryValue& entry);
|
||||
void RemoveEntry(int id);
|
||||
|
||||
private:
|
||||
// content::NotificationObserver:
|
||||
void Observe(int type,
|
||||
const content::NotificationSource& source,
|
||||
const content::NotificationDetails& details) override;
|
||||
|
||||
void UpdateCache();
|
||||
|
||||
// Manages our notification registrations.
|
||||
content::NotificationRegistrar registrar_;
|
||||
|
||||
Predicate predicate_;
|
||||
|
||||
int next_id_ = 0;
|
||||
std::unordered_map<int, std::unique_ptr<base::DictionaryValue>> entries_;
|
||||
|
||||
// We need to convert the |entries_| to ListValue for multiple times, this
|
||||
// caches is only updated when we are sending messages.
|
||||
bool cache_needs_update_ = true;
|
||||
base::ListValue cached_entries_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(RenderProcessPreferences);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_RENDER_PROCESS_PREFERENCES_H_
|
||||
@@ -1,61 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/session_preferences.h"
|
||||
|
||||
#include "atom/common/options_switches.h"
|
||||
#include "base/command_line.h"
|
||||
#include "base/memory/ptr_util.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
#if defined(OS_WIN)
|
||||
const base::FilePath::CharType kPathDelimiter = FILE_PATH_LITERAL(';');
|
||||
#else
|
||||
const base::FilePath::CharType kPathDelimiter = FILE_PATH_LITERAL(':');
|
||||
#endif
|
||||
|
||||
} // namespace
|
||||
|
||||
// static
|
||||
int SessionPreferences::kLocatorKey = 0;
|
||||
|
||||
SessionPreferences::SessionPreferences(content::BrowserContext* context) {
|
||||
context->SetUserData(&kLocatorKey, base::WrapUnique(this));
|
||||
}
|
||||
|
||||
SessionPreferences::~SessionPreferences() {}
|
||||
|
||||
// static
|
||||
SessionPreferences* SessionPreferences::FromBrowserContext(
|
||||
content::BrowserContext* context) {
|
||||
return static_cast<SessionPreferences*>(context->GetUserData(&kLocatorKey));
|
||||
}
|
||||
|
||||
// static
|
||||
void SessionPreferences::AppendExtraCommandLineSwitches(
|
||||
content::BrowserContext* context,
|
||||
base::CommandLine* command_line) {
|
||||
SessionPreferences* self = FromBrowserContext(context);
|
||||
if (!self)
|
||||
return;
|
||||
|
||||
base::FilePath::StringType preloads;
|
||||
for (const auto& preload : self->preloads()) {
|
||||
if (!base::FilePath(preload).IsAbsolute()) {
|
||||
LOG(ERROR) << "preload script must have absolute path: " << preload;
|
||||
continue;
|
||||
}
|
||||
if (preloads.empty())
|
||||
preloads = preload;
|
||||
else
|
||||
preloads += kPathDelimiter + preload;
|
||||
}
|
||||
if (!preloads.empty())
|
||||
command_line->AppendSwitchNative(switches::kPreloadScripts, preloads);
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,29 +0,0 @@
|
||||
// Created by Mathias Leppich on 03/02/14.
|
||||
// Copyright (c) 2014 Bit Bar. All rights reserved.
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/ui/cocoa/NSColor+Hex.h"
|
||||
|
||||
@implementation NSColor (Hex)
|
||||
|
||||
+ (NSColor*)colorWithHexColorString:(NSString*)inColorString {
|
||||
unsigned colorCode = 0;
|
||||
unsigned char redByte, greenByte, blueByte;
|
||||
|
||||
if (inColorString) {
|
||||
NSScanner* scanner = [NSScanner scannerWithString:inColorString];
|
||||
(void)[scanner scanHexInt:&colorCode]; // ignore error
|
||||
}
|
||||
redByte = (unsigned char)(colorCode >> 16);
|
||||
greenByte = (unsigned char)(colorCode >> 8);
|
||||
blueByte = (unsigned char)(colorCode); // masks off high bits
|
||||
|
||||
return [NSColor colorWithCalibratedRed:(CGFloat)redByte / 0xff
|
||||
green:(CGFloat)greenByte / 0xff
|
||||
blue:(CGFloat)blueByte / 0xff
|
||||
alpha:1.0];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -1,267 +0,0 @@
|
||||
// Copyright 2016 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_UI_COCOA_TOUCH_BAR_FORWARD_DECLARATIONS_H_
|
||||
#define ATOM_BROWSER_UI_COCOA_TOUCH_BAR_FORWARD_DECLARATIONS_H_
|
||||
|
||||
// Once Chrome no longer supports OSX 10.12.0, this file can be deleted.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#if !defined(MAC_OS_X_VERSION_10_12_1)
|
||||
|
||||
#pragma clang assume_nonnull begin
|
||||
|
||||
@class NSTouchBar, NSTouchBarItem;
|
||||
@class NSScrubber, NSScrubberItemView, NSScrubberArrangedView,
|
||||
NSScrubberTextItemView, NSScrubberImageItemView, NSScrubberSelectionStyle;
|
||||
@protocol NSTouchBarDelegate
|
||||
, NSScrubberDelegate, NSScrubberDataSource, NSScrubberFlowLayoutDelegate,
|
||||
NSScrubberFlowLayout;
|
||||
|
||||
typedef float NSTouchBarItemPriority;
|
||||
static const NSTouchBarItemPriority NSTouchBarItemPriorityHigh = 1000;
|
||||
static const NSTouchBarItemPriority NSTouchBarItemPriorityNormal = 0;
|
||||
static const NSTouchBarItemPriority NSTouchBarItemPriorityLow = -1000;
|
||||
|
||||
enum NSScrubberMode { NSScrubberModeFixed = 0, NSScrubberModeFree };
|
||||
|
||||
typedef NSString* NSTouchBarItemIdentifier;
|
||||
typedef NSString* NSTouchBarCustomizationIdentifier;
|
||||
|
||||
static const NSTouchBarItemIdentifier NSTouchBarItemIdentifierFixedSpaceSmall =
|
||||
@"NSTouchBarItemIdentifierFixedSpaceSmall";
|
||||
|
||||
static const NSTouchBarItemIdentifier NSTouchBarItemIdentifierFixedSpaceLarge =
|
||||
@"NSTouchBarItemIdentifierFixedSpaceLarge";
|
||||
|
||||
static const NSTouchBarItemIdentifier NSTouchBarItemIdentifierFlexibleSpace =
|
||||
@"NSTouchBarItemIdentifierFlexibleSpace";
|
||||
|
||||
static const NSTouchBarItemIdentifier NSTouchBarItemIdentifierOtherItemsProxy =
|
||||
@"NSTouchBarItemIdentifierOtherItemsProxy";
|
||||
|
||||
@interface NSTouchBar : NSObject <NSCoding>
|
||||
|
||||
- (instancetype)init NS_DESIGNATED_INITIALIZER;
|
||||
- (nullable instancetype)initWithCoder:(NSCoder*)aDecoder
|
||||
NS_DESIGNATED_INITIALIZER;
|
||||
|
||||
@property(copy, nullable)
|
||||
NSTouchBarCustomizationIdentifier customizationIdentifier;
|
||||
@property(copy) NSArray* customizationAllowedItemIdentifiers;
|
||||
@property(copy) NSArray* customizationRequiredItemIdentifiers;
|
||||
@property(copy) NSArray* defaultItemIdentifiers;
|
||||
@property(copy, readonly) NSArray* itemIdentifiers;
|
||||
@property(copy, nullable) NSTouchBarItemIdentifier principalItemIdentifier;
|
||||
@property(copy, nullable)
|
||||
NSTouchBarItemIdentifier escapeKeyReplacementItemIdentifier;
|
||||
@property(copy) NSSet* templateItems;
|
||||
@property(nullable, weak) id<NSTouchBarDelegate> delegate;
|
||||
|
||||
- (nullable __kindof NSTouchBarItem*)itemForIdentifier:
|
||||
(NSTouchBarItemIdentifier)identifier;
|
||||
|
||||
@property(readonly, getter=isVisible) BOOL visible;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSTouchBarItem : NSObject <NSCoding>
|
||||
|
||||
- (instancetype)initWithIdentifier:(NSTouchBarItemIdentifier)identifier
|
||||
NS_DESIGNATED_INITIALIZER;
|
||||
- (nullable instancetype)initWithCoder:(NSCoder*)coder
|
||||
NS_DESIGNATED_INITIALIZER;
|
||||
- (instancetype)init NS_UNAVAILABLE;
|
||||
|
||||
@property(readonly, copy) NSTouchBarItemIdentifier identifier;
|
||||
@property NSTouchBarItemPriority visibilityPriority;
|
||||
@property(readonly, nullable) NSView* view;
|
||||
@property(readonly, nullable) NSViewController* viewController;
|
||||
@property(readwrite, copy) NSString* customizationLabel;
|
||||
@property(readonly, getter=isVisible) BOOL visible;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSGroupTouchBarItem : NSTouchBarItem
|
||||
|
||||
+ (NSGroupTouchBarItem*)groupItemWithIdentifier:
|
||||
(NSTouchBarItemIdentifier)identifier
|
||||
items:(NSArray*)items;
|
||||
|
||||
@property(strong) NSTouchBar* groupTouchBar;
|
||||
@property(readwrite, copy, null_resettable) NSString* customizationLabel;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSCustomTouchBarItem : NSTouchBarItem
|
||||
|
||||
@property(readwrite, strong) __kindof NSView* view;
|
||||
@property(readwrite, strong, nullable)
|
||||
__kindof NSViewController* viewController;
|
||||
@property(readwrite, copy, null_resettable) NSString* customizationLabel;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSColorPickerTouchBarItem : NSTouchBarItem
|
||||
|
||||
@property SEL action;
|
||||
@property(weak) id target;
|
||||
@property(copy) NSColor* color;
|
||||
@property(strong) NSColorList* colorList;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSPopoverTouchBarItem : NSTouchBarItem
|
||||
|
||||
@property BOOL showsCloseButton;
|
||||
@property(strong) NSImage* collapsedRepresentationImage;
|
||||
@property(strong) NSString* collapsedRepresentationLabel;
|
||||
@property(strong) NSTouchBar* popoverTouchBar;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSSliderTouchBarItem : NSTouchBarItem
|
||||
|
||||
@property SEL action;
|
||||
@property(weak) id target;
|
||||
@property(copy) NSString* label;
|
||||
@property(strong) NSSlider* slider;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSScrubber : NSView
|
||||
|
||||
@property(weak) id<NSScrubberDelegate> delegate;
|
||||
@property(weak) id<NSScrubberDataSource> dataSource;
|
||||
@property NSScrubberMode mode;
|
||||
@property BOOL showsArrowButtons;
|
||||
@property(getter=isContinuous) BOOL continuous;
|
||||
@property(strong, nullable) NSScrubberSelectionStyle* selectionBackgroundStyle;
|
||||
@property(strong, nullable) NSScrubberSelectionStyle* selectionOverlayStyle;
|
||||
|
||||
- (void)registerClass:(Class)itemViewClass
|
||||
forItemIdentifier:(NSString*)itemIdentifier;
|
||||
|
||||
- (__kindof NSScrubberItemView*)makeItemWithIdentifier:(NSString*)itemIdentifier
|
||||
owner:(id)owner;
|
||||
- (void)reloadData;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSScrubberFlowLayout : NSObject
|
||||
@end
|
||||
|
||||
@interface NSScrubberSelectionStyle : NSObject <NSCoding>
|
||||
|
||||
@property(class, strong, readonly)
|
||||
NSScrubberSelectionStyle* outlineOverlayStyle;
|
||||
@property(class, strong, readonly)
|
||||
NSScrubberSelectionStyle* roundedBackgroundStyle;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSScrubberArrangedView : NSView
|
||||
|
||||
@end
|
||||
|
||||
@interface NSScrubberItemView : NSScrubberArrangedView
|
||||
|
||||
@end
|
||||
|
||||
@interface NSScrubberTextItemView : NSScrubberItemView
|
||||
|
||||
@property(copy) NSString* title;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSScrubberImageItemView : NSScrubberItemView
|
||||
|
||||
@property(copy) NSImage* image;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSWindow (TouchBarSDK)
|
||||
|
||||
@property(strong, readwrite, nullable) NSTouchBar* touchBar;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSButton (TouchBarSDK)
|
||||
|
||||
@property(copy) NSColor* bezelColor;
|
||||
+ (instancetype)buttonWithTitle:(NSString*)title
|
||||
target:(id)target
|
||||
action:(SEL)action;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSTextField (TouchBarSDK)
|
||||
|
||||
+ (instancetype)labelWithString:(NSString*)stringValue;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSSegmentedControl (TouchBarSDK)
|
||||
|
||||
+ (instancetype)segmentedControlWithLabels:(NSArray*)labels
|
||||
trackingMode:(NSSegmentSwitchTracking)trackingMode
|
||||
target:(id)target
|
||||
action:(SEL)action;
|
||||
|
||||
@end
|
||||
|
||||
@protocol NSTouchBarDelegate <NSObject>
|
||||
|
||||
@optional
|
||||
- (nullable NSTouchBarItem*)touchBar:(NSTouchBar*)touchBar
|
||||
makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier;
|
||||
|
||||
@end
|
||||
|
||||
@protocol NSScrubberDelegate <NSObject>
|
||||
|
||||
- (void)scrubber:(NSScrubber*)scrubber
|
||||
didHighlightItemAtIndex:(NSInteger)highlightedIndex;
|
||||
- (void)scrubber:(NSScrubber*)scrubber
|
||||
didSelectItemAtIndex:(NSInteger)selectedIndex;
|
||||
|
||||
@end
|
||||
|
||||
@protocol NSScrubberDataSource <NSObject>
|
||||
|
||||
- (NSInteger)numberOfItemsForScrubber:(NSScrubber*)scrubber;
|
||||
- (__kindof NSScrubberItemView*)scrubber:(NSScrubber*)scrubber
|
||||
viewForItemAtIndex:(NSInteger)index;
|
||||
|
||||
@end
|
||||
|
||||
@protocol NSScrubberFlowLayoutDelegate <NSObject>
|
||||
|
||||
- (NSSize)scrubber:(NSScrubber*)scrubber
|
||||
layout:(NSScrubberFlowLayout*)layout
|
||||
sizeForItemAtIndex:(NSInteger)itemIndex;
|
||||
|
||||
@end
|
||||
|
||||
#pragma clang assume_nonnull end
|
||||
|
||||
#elif MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12_1
|
||||
|
||||
// When compiling against the 10.12.1 SDK or later, just provide forward
|
||||
// declarations to suppress the partial availability warnings.
|
||||
|
||||
@class NSCustomTouchBarItem;
|
||||
@class NSGroupTouchBarItem;
|
||||
@class NSTouchBar;
|
||||
@protocol NSTouchBarDelegate;
|
||||
@class NSTouchBarItem;
|
||||
|
||||
@interface NSWindow (TouchBarSDK)
|
||||
@property(strong, readonly) NSTouchBar* touchBar API_AVAILABLE(macosx(10.12.2));
|
||||
@end
|
||||
|
||||
#endif // MAC_OS_X_VERSION_10_12_1
|
||||
|
||||
#endif // ATOM_BROWSER_UI_COCOA_TOUCH_BAR_FORWARD_DECLARATIONS_H_
|
||||
@@ -1,69 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_UI_MESSAGE_BOX_H_
|
||||
#define ATOM_BROWSER_UI_MESSAGE_BOX_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "base/callback_forward.h"
|
||||
#include "base/strings/string16.h"
|
||||
|
||||
namespace gfx {
|
||||
class ImageSkia;
|
||||
}
|
||||
|
||||
namespace atom {
|
||||
|
||||
class NativeWindow;
|
||||
|
||||
enum MessageBoxType {
|
||||
MESSAGE_BOX_TYPE_NONE = 0,
|
||||
MESSAGE_BOX_TYPE_INFORMATION,
|
||||
MESSAGE_BOX_TYPE_WARNING,
|
||||
MESSAGE_BOX_TYPE_ERROR,
|
||||
MESSAGE_BOX_TYPE_QUESTION,
|
||||
};
|
||||
|
||||
enum MessageBoxOptions {
|
||||
MESSAGE_BOX_NONE = 0,
|
||||
MESSAGE_BOX_NO_LINK = 1 << 0,
|
||||
};
|
||||
|
||||
int ShowMessageBoxSync(NativeWindow* parent_window,
|
||||
MessageBoxType type,
|
||||
const std::vector<std::string>& buttons,
|
||||
int default_id,
|
||||
int cancel_id,
|
||||
int options,
|
||||
const std::string& title,
|
||||
const std::string& message,
|
||||
const std::string& detail,
|
||||
const gfx::ImageSkia& icon);
|
||||
|
||||
typedef base::OnceCallback<void(int code, bool checkbox_checked)>
|
||||
MessageBoxCallback;
|
||||
|
||||
void ShowMessageBox(NativeWindow* parent_window,
|
||||
MessageBoxType type,
|
||||
const std::vector<std::string>& buttons,
|
||||
int default_id,
|
||||
int cancel_id,
|
||||
int options,
|
||||
const std::string& title,
|
||||
const std::string& message,
|
||||
const std::string& detail,
|
||||
const std::string& checkbox_label,
|
||||
bool checkbox_checked,
|
||||
const gfx::ImageSkia& icon,
|
||||
MessageBoxCallback callback);
|
||||
|
||||
// Like ShowMessageBox with simplest settings, but safe to call at very early
|
||||
// stage of application.
|
||||
void ShowErrorBox(const base::string16& title, const base::string16& content);
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_UI_MESSAGE_BOX_H_
|
||||
@@ -1,173 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/ui/message_box.h"
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
#include "atom/browser/native_window.h"
|
||||
#include "base/callback.h"
|
||||
#include "base/mac/mac_util.h"
|
||||
#include "base/strings/sys_string_conversions.h"
|
||||
#include "skia/ext/skia_utils_mac.h"
|
||||
#include "ui/gfx/image/image_skia.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
NSAlert* CreateNSAlert(NativeWindow* parent_window,
|
||||
MessageBoxType type,
|
||||
const std::vector<std::string>& buttons,
|
||||
int default_id,
|
||||
int cancel_id,
|
||||
const std::string& title,
|
||||
const std::string& message,
|
||||
const std::string& detail,
|
||||
const std::string& checkbox_label,
|
||||
bool checkbox_checked,
|
||||
const gfx::ImageSkia& icon) {
|
||||
// Ignore the title; it's the window title on other platforms and ignorable.
|
||||
NSAlert* alert = [[NSAlert alloc] init];
|
||||
[alert setMessageText:base::SysUTF8ToNSString(message)];
|
||||
[alert setInformativeText:base::SysUTF8ToNSString(detail)];
|
||||
|
||||
switch (type) {
|
||||
case MESSAGE_BOX_TYPE_INFORMATION:
|
||||
alert.alertStyle = NSInformationalAlertStyle;
|
||||
break;
|
||||
case MESSAGE_BOX_TYPE_WARNING:
|
||||
case MESSAGE_BOX_TYPE_ERROR:
|
||||
// NSWarningAlertStyle shows the app icon while NSCriticalAlertStyle
|
||||
// shows a warning icon with an app icon badge. Since there is no
|
||||
// error variant, lets just use NSCriticalAlertStyle.
|
||||
alert.alertStyle = NSCriticalAlertStyle;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < buttons.size(); ++i) {
|
||||
NSString* title = base::SysUTF8ToNSString(buttons[i]);
|
||||
// An empty title causes crash on macOS.
|
||||
if (buttons[i].empty())
|
||||
title = @"(empty)";
|
||||
NSButton* button = [alert addButtonWithTitle:title];
|
||||
[button setTag:i];
|
||||
}
|
||||
|
||||
NSArray* ns_buttons = [alert buttons];
|
||||
int button_count = static_cast<int>([ns_buttons count]);
|
||||
|
||||
if (default_id >= 0 && default_id < button_count) {
|
||||
// Focus the button at default_id if the user opted to do so.
|
||||
// The first button added gets set as the default selected.
|
||||
// So remove that default, and make the requested button the default.
|
||||
[[ns_buttons objectAtIndex:0] setKeyEquivalent:@""];
|
||||
[[ns_buttons objectAtIndex:default_id] setKeyEquivalent:@"\r"];
|
||||
}
|
||||
|
||||
// Bind cancel id button to escape key if there is more than one button
|
||||
if (button_count > 1 && cancel_id >= 0 && cancel_id < button_count) {
|
||||
[[ns_buttons objectAtIndex:cancel_id] setKeyEquivalent:@"\e"];
|
||||
}
|
||||
|
||||
if (!checkbox_label.empty()) {
|
||||
alert.showsSuppressionButton = YES;
|
||||
alert.suppressionButton.title = base::SysUTF8ToNSString(checkbox_label);
|
||||
alert.suppressionButton.state = checkbox_checked ? NSOnState : NSOffState;
|
||||
}
|
||||
|
||||
if (!icon.isNull()) {
|
||||
NSImage* image = skia::SkBitmapToNSImageWithColorSpace(
|
||||
*icon.bitmap(), base::mac::GetGenericRGBColorSpace());
|
||||
[alert setIcon:image];
|
||||
}
|
||||
|
||||
return alert;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int ShowMessageBoxSync(NativeWindow* parent_window,
|
||||
MessageBoxType type,
|
||||
const std::vector<std::string>& buttons,
|
||||
int default_id,
|
||||
int cancel_id,
|
||||
int options,
|
||||
const std::string& title,
|
||||
const std::string& message,
|
||||
const std::string& detail,
|
||||
const gfx::ImageSkia& icon) {
|
||||
NSAlert* alert =
|
||||
CreateNSAlert(parent_window, type, buttons, default_id, cancel_id, title,
|
||||
message, detail, "", false, icon);
|
||||
|
||||
// Use runModal for synchronous alert without parent, since we don't have a
|
||||
// window to wait for.
|
||||
if (!parent_window)
|
||||
return [[alert autorelease] runModal];
|
||||
|
||||
__block int ret_code = -1;
|
||||
|
||||
NSWindow* window = parent_window->GetNativeWindow().GetNativeNSWindow();
|
||||
[alert beginSheetModalForWindow:window
|
||||
completionHandler:^(NSModalResponse response) {
|
||||
ret_code = response;
|
||||
[NSApp stopModal];
|
||||
}];
|
||||
|
||||
[NSApp runModalForWindow:window];
|
||||
return ret_code;
|
||||
}
|
||||
|
||||
void ShowMessageBox(NativeWindow* parent_window,
|
||||
MessageBoxType type,
|
||||
const std::vector<std::string>& buttons,
|
||||
int default_id,
|
||||
int cancel_id,
|
||||
int options,
|
||||
const std::string& title,
|
||||
const std::string& message,
|
||||
const std::string& detail,
|
||||
const std::string& checkbox_label,
|
||||
bool checkbox_checked,
|
||||
const gfx::ImageSkia& icon,
|
||||
MessageBoxCallback callback) {
|
||||
NSAlert* alert =
|
||||
CreateNSAlert(parent_window, type, buttons, default_id, cancel_id, title,
|
||||
message, detail, checkbox_label, checkbox_checked, icon);
|
||||
|
||||
// Use runModal for synchronous alert without parent, since we don't have a
|
||||
// window to wait for.
|
||||
if (!parent_window) {
|
||||
int ret = [[alert autorelease] runModal];
|
||||
std::move(callback).Run(ret, alert.suppressionButton.state == NSOnState);
|
||||
} else {
|
||||
NSWindow* window =
|
||||
parent_window ? parent_window->GetNativeWindow().GetNativeNSWindow()
|
||||
: nil;
|
||||
|
||||
// Duplicate the callback object here since c is a reference and gcd would
|
||||
// only store the pointer, by duplication we can force gcd to store a copy.
|
||||
__block MessageBoxCallback callback_ = std::move(callback);
|
||||
|
||||
[alert beginSheetModalForWindow:window
|
||||
completionHandler:^(NSModalResponse response) {
|
||||
std::move(callback_).Run(
|
||||
response, alert.suppressionButton.state == NSOnState);
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
void ShowErrorBox(const base::string16& title, const base::string16& content) {
|
||||
NSAlert* alert = [[NSAlert alloc] init];
|
||||
[alert setMessageText:base::SysUTF16ToNSString(title)];
|
||||
[alert setInformativeText:base::SysUTF16ToNSString(content)];
|
||||
[alert setAlertStyle:NSCriticalAlertStyle];
|
||||
[alert runModal];
|
||||
[alert release];
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,520 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/ui/tray_icon_cocoa.h"
|
||||
|
||||
#include "atom/browser/ui/cocoa/NSString+ANSI.h"
|
||||
#include "atom/browser/ui/cocoa/atom_menu_controller.h"
|
||||
#include "base/strings/sys_string_conversions.h"
|
||||
#include "ui/display/screen.h"
|
||||
#include "ui/events/cocoa/cocoa_event_utils.h"
|
||||
#include "ui/gfx/image/image.h"
|
||||
#include "ui/gfx/mac/coordinate_conversion.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// By default, macOS sets 4px to tray image as left and right padding margin.
|
||||
const CGFloat kHorizontalMargin = 4;
|
||||
// macOS tends to make the title 2px lower.
|
||||
const CGFloat kVerticalTitleMargin = 2;
|
||||
|
||||
} // namespace
|
||||
|
||||
@interface StatusItemView : NSView {
|
||||
atom::TrayIconCocoa* trayIcon_; // weak
|
||||
AtomMenuController* menuController_; // weak
|
||||
atom::TrayIcon::HighlightMode highlight_mode_;
|
||||
BOOL ignoreDoubleClickEvents_;
|
||||
BOOL forceHighlight_;
|
||||
BOOL inMouseEventSequence_;
|
||||
BOOL ANSI_;
|
||||
base::scoped_nsobject<NSImage> image_;
|
||||
base::scoped_nsobject<NSImage> alternateImage_;
|
||||
base::scoped_nsobject<NSString> title_;
|
||||
base::scoped_nsobject<NSMutableAttributedString> attributedTitle_;
|
||||
base::scoped_nsobject<NSStatusItem> statusItem_;
|
||||
base::scoped_nsobject<NSTrackingArea> trackingArea_;
|
||||
}
|
||||
|
||||
@end // @interface StatusItemView
|
||||
|
||||
@implementation StatusItemView
|
||||
|
||||
- (void)dealloc {
|
||||
trayIcon_ = nil;
|
||||
menuController_ = nil;
|
||||
[super dealloc];
|
||||
}
|
||||
|
||||
- (id)initWithIcon:(atom::TrayIconCocoa*)icon {
|
||||
trayIcon_ = icon;
|
||||
menuController_ = nil;
|
||||
highlight_mode_ = atom::TrayIcon::HighlightMode::SELECTION;
|
||||
ignoreDoubleClickEvents_ = NO;
|
||||
forceHighlight_ = NO;
|
||||
inMouseEventSequence_ = NO;
|
||||
|
||||
if ((self = [super initWithFrame:CGRectZero])) {
|
||||
[self registerForDraggedTypes:@[
|
||||
NSFilenamesPboardType,
|
||||
NSStringPboardType,
|
||||
]];
|
||||
|
||||
// Create the status item.
|
||||
NSStatusItem* item = [[NSStatusBar systemStatusBar]
|
||||
statusItemWithLength:NSVariableStatusItemLength];
|
||||
statusItem_.reset([item retain]);
|
||||
[statusItem_ setView:self];
|
||||
// Finalize setup by sizing our views
|
||||
[self updateDimensions];
|
||||
|
||||
// Add NSTrackingArea for listening to mouseEnter, mouseExit, and mouseMove
|
||||
// events
|
||||
trackingArea_.reset([[NSTrackingArea alloc]
|
||||
initWithRect:[self bounds]
|
||||
options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
|
||||
NSTrackingActiveAlways
|
||||
owner:self
|
||||
userInfo:nil]);
|
||||
[self addTrackingArea:trackingArea_];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)updateDimensions {
|
||||
NSStatusBar* bar = [NSStatusBar systemStatusBar];
|
||||
[self setFrame:NSMakeRect(0, 0, [self fullWidth], [bar thickness])];
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (void)removeItem {
|
||||
// Turn off tracking events to prevent crash
|
||||
if (trackingArea_) {
|
||||
[self removeTrackingArea:trackingArea_];
|
||||
trackingArea_.reset();
|
||||
}
|
||||
[[NSStatusBar systemStatusBar] removeStatusItem:statusItem_];
|
||||
[statusItem_ setView:nil];
|
||||
statusItem_.reset();
|
||||
}
|
||||
|
||||
- (void)drawRect:(NSRect)dirtyRect {
|
||||
// Draw the tray icon and title that align with NSStatusItem, layout:
|
||||
// ----------------
|
||||
// | icon | title |
|
||||
/// ----------------
|
||||
|
||||
CGFloat thickness = [[statusItem_ statusBar] thickness];
|
||||
|
||||
// Draw the system bar background.
|
||||
[statusItem_ drawStatusBarBackgroundInRect:self.bounds
|
||||
withHighlight:[self shouldHighlight]];
|
||||
|
||||
// Determine which image to use.
|
||||
NSImage* image = image_.get();
|
||||
if (inMouseEventSequence_ && alternateImage_) {
|
||||
image = alternateImage_.get();
|
||||
}
|
||||
// Apply the higlight color if the image is a template image. When this moves
|
||||
// to using the new [NSStatusItem button] API, this should work automagically.
|
||||
if ([image isTemplate] == YES) {
|
||||
NSImage* imageWithColor = [[image copy] autorelease];
|
||||
[imageWithColor lockFocus];
|
||||
[[self colorWithHighlight:[self isHighlighted]] set];
|
||||
CGRect imageBounds = CGRectMake(0, 0, image.size.width, image.size.height);
|
||||
NSRectFillUsingOperation(imageBounds, NSCompositeSourceAtop);
|
||||
[imageWithColor unlockFocus];
|
||||
image = imageWithColor;
|
||||
}
|
||||
|
||||
// Draw the image
|
||||
[image
|
||||
drawInRect:CGRectMake(roundf(([self iconWidth] - image.size.width) / 2),
|
||||
roundf((thickness - image.size.height) / 2),
|
||||
image.size.width, image.size.height)];
|
||||
|
||||
if (title_) {
|
||||
// Draw title.
|
||||
NSRect titleDrawRect = NSMakeRect([self iconWidth], -kVerticalTitleMargin,
|
||||
[self titleWidth], thickness);
|
||||
[attributedTitle_ drawInRect:titleDrawRect];
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)isDarkMode {
|
||||
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
|
||||
NSString* mode = [defaults stringForKey:@"AppleInterfaceStyle"];
|
||||
return mode && [mode isEqualToString:@"Dark"];
|
||||
}
|
||||
|
||||
- (BOOL)isHighlighted {
|
||||
BOOL highlight = [self shouldHighlight];
|
||||
return highlight | [self isDarkMode];
|
||||
}
|
||||
|
||||
// The width of the full status item.
|
||||
- (CGFloat)fullWidth {
|
||||
if (title_)
|
||||
return [self iconWidth] + [self titleWidth] + kHorizontalMargin;
|
||||
else
|
||||
return [self iconWidth];
|
||||
}
|
||||
|
||||
// The width of the icon.
|
||||
- (CGFloat)iconWidth {
|
||||
if (!image_ && title_)
|
||||
return kHorizontalMargin;
|
||||
CGFloat thickness = [[NSStatusBar systemStatusBar] thickness];
|
||||
CGFloat imageHeight = [image_ size].height;
|
||||
CGFloat imageWidth = [image_ size].width;
|
||||
CGFloat iconWidth = imageWidth;
|
||||
if (imageWidth < thickness) {
|
||||
// Image's width must be larger than menu bar's height.
|
||||
iconWidth = thickness;
|
||||
} else {
|
||||
CGFloat verticalMargin = thickness - imageHeight;
|
||||
// Image must have same horizontal vertical margin.
|
||||
if (verticalMargin > 0 && imageWidth != imageHeight)
|
||||
iconWidth = imageWidth + verticalMargin;
|
||||
CGFloat horizontalMargin = thickness - imageWidth;
|
||||
// Image must have at least kHorizontalMargin horizontal margin on each
|
||||
// side.
|
||||
if (horizontalMargin < 2 * kHorizontalMargin)
|
||||
iconWidth = imageWidth + 2 * kHorizontalMargin;
|
||||
}
|
||||
return iconWidth;
|
||||
}
|
||||
|
||||
// The width of the title.
|
||||
- (CGFloat)titleWidth {
|
||||
if (!title_)
|
||||
return 0;
|
||||
return [attributedTitle_ size].width;
|
||||
}
|
||||
|
||||
- (NSColor*)colorWithHighlight:(BOOL)highlight {
|
||||
return highlight ? [NSColor whiteColor]
|
||||
: [NSColor colorWithRed:0.265625
|
||||
green:0.25390625
|
||||
blue:0.234375
|
||||
alpha:1.0];
|
||||
}
|
||||
|
||||
- (void)setImage:(NSImage*)image {
|
||||
image_.reset([image copy]);
|
||||
[self updateDimensions];
|
||||
}
|
||||
|
||||
- (void)setAlternateImage:(NSImage*)image {
|
||||
alternateImage_.reset([image copy]);
|
||||
}
|
||||
|
||||
- (void)setHighlight:(atom::TrayIcon::HighlightMode)mode {
|
||||
highlight_mode_ = mode;
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (void)setIgnoreDoubleClickEvents:(BOOL)ignore {
|
||||
ignoreDoubleClickEvents_ = ignore;
|
||||
}
|
||||
|
||||
- (BOOL)getIgnoreDoubleClickEvents {
|
||||
return ignoreDoubleClickEvents_;
|
||||
}
|
||||
|
||||
- (void)setTitle:(NSString*)title {
|
||||
if (title.length > 0) {
|
||||
title_.reset([title copy]);
|
||||
ANSI_ = [title containsANSICodes];
|
||||
} else {
|
||||
title_.reset();
|
||||
ANSI_ = NO;
|
||||
}
|
||||
[self updateAttributedTitle];
|
||||
[self updateDimensions];
|
||||
}
|
||||
|
||||
- (NSString*)title {
|
||||
return title_;
|
||||
}
|
||||
|
||||
- (void)updateAttributedTitle {
|
||||
NSDictionary* attributes =
|
||||
@{NSFontAttributeName : [NSFont menuBarFontOfSize:0]};
|
||||
|
||||
if (ANSI_) {
|
||||
NSCharacterSet* whites = [NSCharacterSet whitespaceCharacterSet];
|
||||
NSString* title = [title_ stringByTrimmingCharactersInSet:whites];
|
||||
attributedTitle_.reset([title attributedStringParsingANSICodes]);
|
||||
[attributedTitle_ addAttributes:attributes
|
||||
range:NSMakeRange(0, [attributedTitle_ length])];
|
||||
return;
|
||||
}
|
||||
|
||||
// check title_ being nil
|
||||
NSString* title = @"";
|
||||
if (title_)
|
||||
title = title_;
|
||||
|
||||
attributedTitle_.reset([[NSMutableAttributedString alloc]
|
||||
initWithString:title
|
||||
attributes:attributes]);
|
||||
|
||||
// NSFontAttributeName:[NSFont menuBarFontOfSize:0],
|
||||
// NSForegroundColorAttributeName:[self colorWithHighlight: highlight]
|
||||
[attributedTitle_ addAttributes:attributes
|
||||
range:NSMakeRange(0, [attributedTitle_ length])];
|
||||
[attributedTitle_ addAttribute:NSForegroundColorAttributeName
|
||||
value:[self colorWithHighlight:[self isHighlighted]]
|
||||
range:NSMakeRange(0, [attributedTitle_ length])];
|
||||
}
|
||||
|
||||
- (void)setMenuController:(AtomMenuController*)menu {
|
||||
menuController_ = menu;
|
||||
}
|
||||
|
||||
- (void)mouseDown:(NSEvent*)event {
|
||||
inMouseEventSequence_ = YES;
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (void)mouseUp:(NSEvent*)event {
|
||||
if (!inMouseEventSequence_) {
|
||||
// If the menu is showing, when user clicked the tray icon, the `mouseDown`
|
||||
// event will be dissmissed, we need to close the menu at this time.
|
||||
[self setNeedsDisplay:YES];
|
||||
return;
|
||||
}
|
||||
inMouseEventSequence_ = NO;
|
||||
|
||||
// Show menu when there is a context menu.
|
||||
// NB(hokein): Make tray's behavior more like official one's.
|
||||
// When the tray icon gets clicked quickly multiple times, the
|
||||
// event.clickCount doesn't always return 1. Instead, it returns a value that
|
||||
// counts the clicked times.
|
||||
// So we don't check the clickCount here, just pop up the menu for each click
|
||||
// event.
|
||||
if (menuController_)
|
||||
[statusItem_ popUpStatusItemMenu:[menuController_ menu]];
|
||||
|
||||
// Don't emit click events when menu is showing.
|
||||
if (menuController_)
|
||||
return;
|
||||
|
||||
// If we are ignoring double click events, we should ignore the `clickCount`
|
||||
// value and immediately emit a click event.
|
||||
BOOL shouldBeHandledAsASingleClick =
|
||||
(event.clickCount == 1) || ignoreDoubleClickEvents_;
|
||||
if (shouldBeHandledAsASingleClick)
|
||||
trayIcon_->NotifyClicked(
|
||||
gfx::ScreenRectFromNSRect(event.window.frame),
|
||||
gfx::ScreenPointFromNSPoint([event locationInWindow]),
|
||||
ui::EventFlagsFromModifiers([event modifierFlags]));
|
||||
|
||||
// Double click event.
|
||||
BOOL shouldBeHandledAsADoubleClick =
|
||||
(event.clickCount == 2) && !ignoreDoubleClickEvents_;
|
||||
if (shouldBeHandledAsADoubleClick)
|
||||
trayIcon_->NotifyDoubleClicked(
|
||||
gfx::ScreenRectFromNSRect(event.window.frame),
|
||||
ui::EventFlagsFromModifiers([event modifierFlags]));
|
||||
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
- (void)popUpContextMenu:(atom::AtomMenuModel*)menu_model {
|
||||
// Show a custom menu.
|
||||
if (menu_model) {
|
||||
base::scoped_nsobject<AtomMenuController> menuController([
|
||||
[AtomMenuController alloc] initWithModel:menu_model
|
||||
useDefaultAccelerator:NO]);
|
||||
forceHighlight_ = YES; // Should highlight when showing menu.
|
||||
[self setNeedsDisplay:YES];
|
||||
[statusItem_ popUpStatusItemMenu:[menuController menu]];
|
||||
forceHighlight_ = NO;
|
||||
[self setNeedsDisplay:YES];
|
||||
return;
|
||||
}
|
||||
|
||||
if (menuController_ && ![menuController_ isMenuOpen]) {
|
||||
// Redraw the tray icon to show highlight if it is enabled.
|
||||
[self setNeedsDisplay:YES];
|
||||
[statusItem_ popUpStatusItemMenu:[menuController_ menu]];
|
||||
// The popUpStatusItemMenu returns only after the showing menu is closed.
|
||||
// When it returns, we need to redraw the tray icon to not show highlight.
|
||||
[self setNeedsDisplay:YES];
|
||||
}
|
||||
}
|
||||
|
||||
- (void)rightMouseUp:(NSEvent*)event {
|
||||
trayIcon_->NotifyRightClicked(
|
||||
gfx::ScreenRectFromNSRect(event.window.frame),
|
||||
ui::EventFlagsFromModifiers([event modifierFlags]));
|
||||
}
|
||||
|
||||
- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
|
||||
trayIcon_->NotifyDragEntered();
|
||||
return NSDragOperationCopy;
|
||||
}
|
||||
|
||||
- (void)mouseExited:(NSEvent*)event {
|
||||
trayIcon_->NotifyMouseExited(
|
||||
gfx::ScreenPointFromNSPoint([event locationInWindow]),
|
||||
ui::EventFlagsFromModifiers([event modifierFlags]));
|
||||
}
|
||||
|
||||
- (void)mouseEntered:(NSEvent*)event {
|
||||
trayIcon_->NotifyMouseEntered(
|
||||
gfx::ScreenPointFromNSPoint([event locationInWindow]),
|
||||
ui::EventFlagsFromModifiers([event modifierFlags]));
|
||||
}
|
||||
|
||||
- (void)mouseMoved:(NSEvent*)event {
|
||||
trayIcon_->NotifyMouseMoved(
|
||||
gfx::ScreenPointFromNSPoint([event locationInWindow]),
|
||||
ui::EventFlagsFromModifiers([event modifierFlags]));
|
||||
}
|
||||
|
||||
- (void)draggingExited:(id<NSDraggingInfo>)sender {
|
||||
trayIcon_->NotifyDragExited();
|
||||
}
|
||||
|
||||
- (void)draggingEnded:(id<NSDraggingInfo>)sender {
|
||||
trayIcon_->NotifyDragEnded();
|
||||
|
||||
if (NSPointInRect([sender draggingLocation], self.frame)) {
|
||||
trayIcon_->NotifyDrop();
|
||||
}
|
||||
}
|
||||
|
||||
- (BOOL)handleDrop:(id<NSDraggingInfo>)sender {
|
||||
NSPasteboard* pboard = [sender draggingPasteboard];
|
||||
|
||||
if ([[pboard types] containsObject:NSFilenamesPboardType]) {
|
||||
std::vector<std::string> dropFiles;
|
||||
NSArray* files = [pboard propertyListForType:NSFilenamesPboardType];
|
||||
for (NSString* file in files)
|
||||
dropFiles.push_back(base::SysNSStringToUTF8(file));
|
||||
trayIcon_->NotifyDropFiles(dropFiles);
|
||||
return YES;
|
||||
} else if ([[pboard types] containsObject:NSStringPboardType]) {
|
||||
NSString* dropText = [pboard stringForType:NSStringPboardType];
|
||||
trayIcon_->NotifyDropText(base::SysNSStringToUTF8(dropText));
|
||||
return YES;
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
|
||||
[self handleDrop:sender];
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (void)setNeedsDisplay:(BOOL)display {
|
||||
[self updateAttributedTitle];
|
||||
[super setNeedsDisplay:display];
|
||||
}
|
||||
|
||||
- (BOOL)shouldHighlight {
|
||||
switch (highlight_mode_) {
|
||||
case atom::TrayIcon::HighlightMode::ALWAYS:
|
||||
return true;
|
||||
case atom::TrayIcon::HighlightMode::NEVER:
|
||||
return false;
|
||||
case atom::TrayIcon::HighlightMode::SELECTION:
|
||||
BOOL isMenuOpen = menuController_ && [menuController_ isMenuOpen];
|
||||
return forceHighlight_ || inMouseEventSequence_ || isMenuOpen;
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
namespace atom {
|
||||
|
||||
TrayIconCocoa::TrayIconCocoa() {
|
||||
status_item_view_.reset([[StatusItemView alloc] initWithIcon:this]);
|
||||
}
|
||||
|
||||
TrayIconCocoa::~TrayIconCocoa() {
|
||||
[status_item_view_ removeItem];
|
||||
if (menu_model_)
|
||||
menu_model_->RemoveObserver(this);
|
||||
}
|
||||
|
||||
void TrayIconCocoa::SetImage(const gfx::Image& image) {
|
||||
[status_item_view_ setImage:image.IsEmpty() ? nil : image.AsNSImage()];
|
||||
}
|
||||
|
||||
void TrayIconCocoa::SetPressedImage(const gfx::Image& image) {
|
||||
[status_item_view_ setAlternateImage:image.AsNSImage()];
|
||||
}
|
||||
|
||||
void TrayIconCocoa::SetToolTip(const std::string& tool_tip) {
|
||||
[status_item_view_ setToolTip:base::SysUTF8ToNSString(tool_tip)];
|
||||
}
|
||||
|
||||
void TrayIconCocoa::SetTitle(const std::string& title) {
|
||||
[status_item_view_ setTitle:base::SysUTF8ToNSString(title)];
|
||||
}
|
||||
|
||||
std::string TrayIconCocoa::GetTitle() {
|
||||
return base::SysNSStringToUTF8([status_item_view_ title]);
|
||||
}
|
||||
|
||||
void TrayIconCocoa::SetHighlightMode(TrayIcon::HighlightMode mode) {
|
||||
[status_item_view_ setHighlight:mode];
|
||||
}
|
||||
|
||||
void TrayIconCocoa::SetIgnoreDoubleClickEvents(bool ignore) {
|
||||
[status_item_view_ setIgnoreDoubleClickEvents:ignore];
|
||||
}
|
||||
|
||||
bool TrayIconCocoa::GetIgnoreDoubleClickEvents() {
|
||||
return [status_item_view_ getIgnoreDoubleClickEvents];
|
||||
}
|
||||
|
||||
void TrayIconCocoa::PopUpContextMenu(const gfx::Point& pos,
|
||||
AtomMenuModel* menu_model) {
|
||||
[status_item_view_ popUpContextMenu:menu_model];
|
||||
}
|
||||
|
||||
void TrayIconCocoa::SetContextMenu(AtomMenuModel* menu_model) {
|
||||
// Substribe to MenuClosed event.
|
||||
if (menu_model_)
|
||||
menu_model_->RemoveObserver(this);
|
||||
|
||||
menu_model_ = menu_model;
|
||||
|
||||
if (menu_model) {
|
||||
menu_model->AddObserver(this);
|
||||
// Create native menu.
|
||||
menu_.reset([[AtomMenuController alloc] initWithModel:menu_model
|
||||
useDefaultAccelerator:NO]);
|
||||
} else {
|
||||
menu_.reset();
|
||||
}
|
||||
|
||||
[status_item_view_ setMenuController:menu_.get()];
|
||||
}
|
||||
|
||||
gfx::Rect TrayIconCocoa::GetBounds() {
|
||||
auto bounds = gfx::ScreenRectFromNSRect([status_item_view_ window].frame);
|
||||
return bounds;
|
||||
}
|
||||
|
||||
void TrayIconCocoa::OnMenuWillClose() {
|
||||
[status_item_view_ setNeedsDisplay:YES];
|
||||
}
|
||||
|
||||
// static
|
||||
TrayIcon* TrayIcon::Create() {
|
||||
return new TrayIconCocoa;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,230 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/ui/webui/pdf_viewer_handler.h"
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/common/atom_constants.h"
|
||||
#include "base/bind.h"
|
||||
#include "base/values.h"
|
||||
#include "chrome/browser/browser_process.h"
|
||||
#include "content/public/browser/stream_handle.h"
|
||||
#include "content/public/browser/stream_info.h"
|
||||
#include "content/public/browser/web_contents.h"
|
||||
#include "content/public/browser/web_ui.h"
|
||||
#include "content/public/common/page_zoom.h"
|
||||
#include "content/public/common/url_constants.h"
|
||||
#include "net/http/http_response_headers.h"
|
||||
#include "ui/base/l10n/l10n_util.h"
|
||||
#include "ui/base/webui/web_ui_util.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
void CreateResponseHeadersDictionary(const net::HttpResponseHeaders* headers,
|
||||
base::DictionaryValue* result) {
|
||||
if (!headers)
|
||||
return;
|
||||
|
||||
size_t iter = 0;
|
||||
std::string header_name;
|
||||
std::string header_value;
|
||||
while (headers->EnumerateHeaderLines(&iter, &header_name, &header_value)) {
|
||||
base::Value* existing_value = nullptr;
|
||||
if (result->Get(header_name, &existing_value)) {
|
||||
std::string src = existing_value->GetString();
|
||||
result->SetString(header_name, src + ", " + header_value);
|
||||
} else {
|
||||
result->SetString(header_name, header_value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PopulateStreamInfo(base::DictionaryValue* stream_info,
|
||||
content::StreamInfo* stream,
|
||||
const std::string& original_url) {
|
||||
auto headers_dict = std::make_unique<base::DictionaryValue>();
|
||||
auto stream_url = stream->handle->GetURL().spec();
|
||||
CreateResponseHeadersDictionary(stream->response_headers.get(),
|
||||
headers_dict.get());
|
||||
stream_info->SetString("streamURL", stream_url);
|
||||
stream_info->SetString("originalURL", original_url);
|
||||
stream_info->Set("responseHeaders", std::move(headers_dict));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
PdfViewerHandler::PdfViewerHandler(const std::string& src)
|
||||
: original_url_(src) {}
|
||||
|
||||
PdfViewerHandler::~PdfViewerHandler() {
|
||||
RemoveObserver();
|
||||
}
|
||||
|
||||
void PdfViewerHandler::SetPdfResourceStream(content::StreamInfo* stream) {
|
||||
stream_ = stream;
|
||||
if (!!initialize_callback_id_.get()) {
|
||||
auto list = std::make_unique<base::ListValue>();
|
||||
list->Set(0, std::move(initialize_callback_id_));
|
||||
Initialize(list.get());
|
||||
}
|
||||
}
|
||||
|
||||
void PdfViewerHandler::RegisterMessages() {
|
||||
web_ui()->RegisterMessageCallback(
|
||||
"initialize",
|
||||
base::Bind(&PdfViewerHandler::Initialize, base::Unretained(this)));
|
||||
web_ui()->RegisterMessageCallback(
|
||||
"getDefaultZoom",
|
||||
base::Bind(&PdfViewerHandler::GetInitialZoom, base::Unretained(this)));
|
||||
web_ui()->RegisterMessageCallback(
|
||||
"getInitialZoom",
|
||||
base::Bind(&PdfViewerHandler::GetInitialZoom, base::Unretained(this)));
|
||||
web_ui()->RegisterMessageCallback(
|
||||
"setZoom",
|
||||
base::Bind(&PdfViewerHandler::SetZoom, base::Unretained(this)));
|
||||
web_ui()->RegisterMessageCallback(
|
||||
"getStrings",
|
||||
base::Bind(&PdfViewerHandler::GetStrings, base::Unretained(this)));
|
||||
web_ui()->RegisterMessageCallback(
|
||||
"reload", base::Bind(&PdfViewerHandler::Reload, base::Unretained(this)));
|
||||
}
|
||||
|
||||
void PdfViewerHandler::OnJavascriptAllowed() {
|
||||
AddObserver();
|
||||
}
|
||||
|
||||
void PdfViewerHandler::OnJavascriptDisallowed() {
|
||||
RemoveObserver();
|
||||
}
|
||||
|
||||
void PdfViewerHandler::Initialize(const base::ListValue* args) {
|
||||
CHECK_EQ(1U, args->GetSize());
|
||||
const base::Value* callback_id;
|
||||
CHECK(args->Get(0, &callback_id));
|
||||
|
||||
if (stream_) {
|
||||
CHECK(!initialize_callback_id_.get());
|
||||
AllowJavascript();
|
||||
|
||||
auto stream_info = std::make_unique<base::DictionaryValue>();
|
||||
PopulateStreamInfo(stream_info.get(), stream_, original_url_);
|
||||
ResolveJavascriptCallback(*callback_id, *stream_info);
|
||||
} else {
|
||||
initialize_callback_id_ =
|
||||
base::Value::ToUniquePtrValue(callback_id.Clone());
|
||||
}
|
||||
|
||||
auto zoom_controller =
|
||||
WebContentsZoomController::FromWebContents(web_ui()->GetWebContents());
|
||||
zoom_controller->SetZoomMode(WebContentsZoomController::ZOOM_MODE_MANUAL);
|
||||
zoom_controller->SetZoomLevel(0);
|
||||
}
|
||||
|
||||
void PdfViewerHandler::GetDefaultZoom(const base::ListValue* args) {
|
||||
if (!IsJavascriptAllowed())
|
||||
return;
|
||||
CHECK_EQ(1U, args->GetSize());
|
||||
const base::Value* callback_id;
|
||||
CHECK(args->Get(0, &callback_id));
|
||||
|
||||
auto zoom_controller =
|
||||
WebContentsZoomController::FromWebContents(web_ui()->GetWebContents());
|
||||
double zoom_level = zoom_controller->GetDefaultZoomLevel();
|
||||
ResolveJavascriptCallback(
|
||||
*callback_id, base::Value(content::ZoomLevelToZoomFactor(zoom_level)));
|
||||
}
|
||||
|
||||
void PdfViewerHandler::GetInitialZoom(const base::ListValue* args) {
|
||||
if (!IsJavascriptAllowed())
|
||||
return;
|
||||
CHECK_EQ(1U, args->GetSize());
|
||||
const base::Value* callback_id;
|
||||
CHECK(args->Get(0, &callback_id));
|
||||
|
||||
auto zoom_controller =
|
||||
WebContentsZoomController::FromWebContents(web_ui()->GetWebContents());
|
||||
double zoom_level = zoom_controller->GetZoomLevel();
|
||||
ResolveJavascriptCallback(
|
||||
*callback_id, base::Value(content::ZoomLevelToZoomFactor(zoom_level)));
|
||||
}
|
||||
|
||||
void PdfViewerHandler::SetZoom(const base::ListValue* args) {
|
||||
if (!IsJavascriptAllowed())
|
||||
return;
|
||||
CHECK_EQ(2U, args->GetSize());
|
||||
const base::Value* callback_id;
|
||||
CHECK(args->Get(0, &callback_id));
|
||||
double zoom_level = 0.0;
|
||||
CHECK(args->GetDouble(1, &zoom_level));
|
||||
|
||||
auto zoom_controller =
|
||||
WebContentsZoomController::FromWebContents(web_ui()->GetWebContents());
|
||||
zoom_controller->SetZoomLevel(zoom_level);
|
||||
ResolveJavascriptCallback(*callback_id, base::Value(zoom_level));
|
||||
}
|
||||
|
||||
void PdfViewerHandler::GetStrings(const base::ListValue* args) {
|
||||
if (!IsJavascriptAllowed())
|
||||
return;
|
||||
CHECK_EQ(1U, args->GetSize());
|
||||
const base::Value* callback_id;
|
||||
CHECK(args->Get(0, &callback_id));
|
||||
|
||||
auto result = std::make_unique<base::DictionaryValue>();
|
||||
// TODO(deepak1556): Generate strings from components/pdf_strings.grdp.
|
||||
#define SET_STRING(id, resource) result->SetString(id, resource)
|
||||
SET_STRING("passwordPrompt",
|
||||
"This document is password protected. Please enter a password.");
|
||||
SET_STRING("passwordSubmit", "Submit");
|
||||
SET_STRING("passwordInvalid", "Incorrect password");
|
||||
SET_STRING("pageLoading", "Loading...");
|
||||
SET_STRING("pageLoadFailed", "Failed to load PDF document");
|
||||
SET_STRING("pageReload", "Reload");
|
||||
SET_STRING("bookmarks", "Bookmarks");
|
||||
SET_STRING("labelPageNumber", "Page number");
|
||||
SET_STRING("tooltipRotateCW", "Rotate clockwise");
|
||||
SET_STRING("tooltipDownload", "Download");
|
||||
SET_STRING("tooltipFitToPage", "Fit to page");
|
||||
SET_STRING("tooltipFitToWidth", "Fit to width");
|
||||
SET_STRING("tooltipZoomIn", "Zoom in");
|
||||
SET_STRING("tooltipZoomOut", "Zoom out");
|
||||
#undef SET_STRING
|
||||
|
||||
webui::SetLoadTimeDataDefaults(g_browser_process->GetApplicationLocale(),
|
||||
result.get());
|
||||
ResolveJavascriptCallback(*callback_id, *result);
|
||||
}
|
||||
|
||||
void PdfViewerHandler::Reload(const base::ListValue* args) {
|
||||
CHECK_EQ(0U, args->GetSize());
|
||||
web_ui()->GetWebContents()->ReloadFocusedFrame(false);
|
||||
}
|
||||
|
||||
void PdfViewerHandler::OnZoomLevelChanged(content::WebContents* web_contents,
|
||||
double level,
|
||||
bool is_temporary) {
|
||||
if (web_ui()->GetWebContents() == web_contents) {
|
||||
CallJavascriptFunction("cr.webUIListenerCallback",
|
||||
base::Value("onZoomLevelChanged"),
|
||||
base::Value(content::ZoomLevelToZoomFactor(level)));
|
||||
}
|
||||
}
|
||||
|
||||
void PdfViewerHandler::AddObserver() {
|
||||
auto zoom_controller =
|
||||
WebContentsZoomController::FromWebContents(web_ui()->GetWebContents());
|
||||
zoom_controller->AddObserver(this);
|
||||
}
|
||||
|
||||
void PdfViewerHandler::RemoveObserver() {
|
||||
auto zoom_controller =
|
||||
WebContentsZoomController::FromWebContents(web_ui()->GetWebContents());
|
||||
zoom_controller->RemoveObserver(this);
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,61 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_UI_WEBUI_PDF_VIEWER_HANDLER_H_
|
||||
#define ATOM_BROWSER_UI_WEBUI_PDF_VIEWER_HANDLER_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "atom/browser/web_contents_zoom_controller.h"
|
||||
#include "base/macros.h"
|
||||
#include "content/public/browser/host_zoom_map.h"
|
||||
#include "content/public/browser/web_ui_message_handler.h"
|
||||
|
||||
namespace base {
|
||||
class ListValue;
|
||||
}
|
||||
|
||||
namespace content {
|
||||
struct StreamInfo;
|
||||
}
|
||||
|
||||
namespace atom {
|
||||
|
||||
class PdfViewerHandler : public content::WebUIMessageHandler,
|
||||
public WebContentsZoomController::Observer {
|
||||
public:
|
||||
explicit PdfViewerHandler(const std::string& original_url);
|
||||
~PdfViewerHandler() override;
|
||||
|
||||
void SetPdfResourceStream(content::StreamInfo* stream);
|
||||
|
||||
protected:
|
||||
// WebUIMessageHandler implementation.
|
||||
void RegisterMessages() override;
|
||||
void OnJavascriptAllowed() override;
|
||||
void OnJavascriptDisallowed() override;
|
||||
|
||||
private:
|
||||
void Initialize(const base::ListValue* args);
|
||||
void GetDefaultZoom(const base::ListValue* args);
|
||||
void GetInitialZoom(const base::ListValue* args);
|
||||
void SetZoom(const base::ListValue* args);
|
||||
void GetStrings(const base::ListValue* args);
|
||||
void Reload(const base::ListValue* args);
|
||||
void OnZoomLevelChanged(content::WebContents* web_contents,
|
||||
double level,
|
||||
bool is_temporary);
|
||||
void AddObserver();
|
||||
void RemoveObserver();
|
||||
std::unique_ptr<base::Value> initialize_callback_id_;
|
||||
content::StreamInfo* stream_ = nullptr;
|
||||
std::string original_url_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(PdfViewerHandler);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_UI_WEBUI_PDF_VIEWER_HANDLER_H_
|
||||
@@ -1,259 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/ui/webui/pdf_viewer_ui.h"
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "atom/browser/atom_browser_context.h"
|
||||
#include "atom/browser/loader/layered_resource_handler.h"
|
||||
#include "atom/browser/ui/webui/pdf_viewer_handler.h"
|
||||
#include "atom/common/api/api_messages.h"
|
||||
#include "atom/common/atom_constants.h"
|
||||
#include "base/sequenced_task_runner_helpers.h"
|
||||
#include "base/task/post_task.h"
|
||||
#include "content/browser/loader/resource_dispatcher_host_impl.h"
|
||||
#include "content/browser/loader/resource_request_info_impl.h"
|
||||
#include "content/browser/loader/stream_resource_handler.h"
|
||||
#include "content/browser/resource_context_impl.h"
|
||||
#include "content/browser/streams/stream.h"
|
||||
#include "content/browser/streams/stream_context.h"
|
||||
#include "content/public/browser/browser_task_traits.h"
|
||||
#include "content/public/browser/browser_thread.h"
|
||||
#include "content/public/browser/render_frame_host.h"
|
||||
#include "content/public/browser/render_process_host.h"
|
||||
#include "content/public/browser/render_view_host.h"
|
||||
#include "content/public/browser/resource_context.h"
|
||||
#include "content/public/browser/stream_handle.h"
|
||||
#include "content/public/browser/stream_info.h"
|
||||
#include "content/public/browser/url_data_source.h"
|
||||
#include "content/public/browser/web_contents.h"
|
||||
#include "grit/pdf_viewer_resources_map.h"
|
||||
#include "net/base/load_flags.h"
|
||||
#include "net/base/mime_util.h"
|
||||
#include "net/url_request/url_request.h"
|
||||
#include "net/url_request/url_request_context.h"
|
||||
#include "services/network/public/cpp/resource_response.h"
|
||||
#include "ui/base/resource/resource_bundle.h"
|
||||
|
||||
using content::BrowserThread;
|
||||
|
||||
namespace atom {
|
||||
|
||||
namespace {
|
||||
|
||||
// Extracts the path value from the URL without the leading '/',
|
||||
// which follows the mapping of names in pdf_viewer_resources_map.
|
||||
std::string PathWithoutParams(const std::string& path) {
|
||||
return GURL(kPdfViewerUIOrigin + path).path().substr(1);
|
||||
}
|
||||
|
||||
class BundledDataSource : public content::URLDataSource {
|
||||
public:
|
||||
BundledDataSource() {
|
||||
for (size_t i = 0; i < kPdfViewerResourcesSize; ++i) {
|
||||
std::string resource_path = kPdfViewerResources[i].name;
|
||||
DCHECK(path_to_resource_id_.find(resource_path) ==
|
||||
path_to_resource_id_.end());
|
||||
path_to_resource_id_[resource_path] = kPdfViewerResources[i].value;
|
||||
}
|
||||
}
|
||||
|
||||
// content::URLDataSource implementation.
|
||||
std::string GetSource() const override { return kPdfViewerUIHost; }
|
||||
|
||||
void StartDataRequest(
|
||||
const std::string& path,
|
||||
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
|
||||
const GotDataCallback& callback) override {
|
||||
std::string filename = PathWithoutParams(path);
|
||||
auto entry = path_to_resource_id_.find(filename);
|
||||
|
||||
if (entry != path_to_resource_id_.end()) {
|
||||
int resource_id = entry->second;
|
||||
const ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
|
||||
callback.Run(rb.LoadDataResourceBytes(resource_id));
|
||||
} else {
|
||||
LOG(ERROR) << "Unable to find: " << path;
|
||||
callback.Run(new base::RefCountedString());
|
||||
}
|
||||
}
|
||||
|
||||
std::string GetMimeType(const std::string& path) const override {
|
||||
base::FilePath::StringType ext =
|
||||
base::FilePath::FromUTF8Unsafe(PathWithoutParams(path)).Extension();
|
||||
std::string mime_type;
|
||||
if (!ext.empty() &&
|
||||
net::GetWellKnownMimeTypeFromExtension(ext.substr(1), &mime_type))
|
||||
return mime_type;
|
||||
return "text/html";
|
||||
}
|
||||
|
||||
bool ShouldAddContentSecurityPolicy() const override { return false; }
|
||||
|
||||
bool ShouldDenyXFrameOptions() const override { return false; }
|
||||
|
||||
bool ShouldServeMimeTypeAsContentTypeHeader() const override { return true; }
|
||||
|
||||
private:
|
||||
~BundledDataSource() override {}
|
||||
|
||||
// A map from a resource path to the resource ID.
|
||||
std::map<std::string, int> path_to_resource_id_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(BundledDataSource);
|
||||
};
|
||||
|
||||
// Helper to convert from OnceCallback to Callback.
|
||||
template <typename T>
|
||||
void CallMigrationCallback(T callback,
|
||||
std::unique_ptr<content::StreamInfo> stream_info) {
|
||||
std::move(callback).Run(std::move(stream_info));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
class PdfViewerUI::ResourceRequester
|
||||
: public base::RefCountedThreadSafe<ResourceRequester,
|
||||
BrowserThread::DeleteOnIOThread>,
|
||||
public atom::LayeredResourceHandler::Delegate {
|
||||
public:
|
||||
explicit ResourceRequester(StreamResponseCallback cb)
|
||||
: stream_response_cb_(std::move(cb)) {}
|
||||
|
||||
void StartRequest(const GURL& url,
|
||||
const GURL& origin,
|
||||
int render_process_id,
|
||||
int render_view_id,
|
||||
int render_frame_id,
|
||||
content::ResourceContext* resource_context) {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
|
||||
const net::URLRequestContext* request_context =
|
||||
resource_context->GetRequestContext();
|
||||
std::unique_ptr<net::URLRequest> request(
|
||||
request_context->CreateRequest(url, net::DEFAULT_PRIORITY, nullptr));
|
||||
request->set_method("GET");
|
||||
|
||||
content::ResourceDispatcherHostImpl::Get()->InitializeURLRequest(
|
||||
request.get(), content::Referrer(url, blink::kWebReferrerPolicyDefault),
|
||||
false, // download.
|
||||
render_process_id, render_view_id, render_frame_id,
|
||||
content::PREVIEWS_OFF, resource_context);
|
||||
|
||||
content::ResourceRequestInfoImpl* info =
|
||||
content::ResourceRequestInfoImpl::ForRequest(request.get());
|
||||
content::StreamContext* stream_context =
|
||||
content::GetStreamContextForResourceContext(resource_context);
|
||||
|
||||
std::unique_ptr<content::ResourceHandler> handler =
|
||||
std::make_unique<content::StreamResourceHandler>(
|
||||
request.get(), stream_context->registry(), origin, false);
|
||||
info->set_is_stream(true);
|
||||
stream_info_.reset(new content::StreamInfo);
|
||||
stream_info_->handle =
|
||||
static_cast<content::StreamResourceHandler*>(handler.get())
|
||||
->stream()
|
||||
->CreateHandle();
|
||||
stream_info_->original_url = request->url();
|
||||
|
||||
// Helper to fill stream response details.
|
||||
handler.reset(new atom::LayeredResourceHandler(request.get(),
|
||||
std::move(handler), this));
|
||||
|
||||
content::ResourceDispatcherHostImpl::Get()->BeginURLRequest(
|
||||
std::move(request), std::move(handler),
|
||||
false, // download
|
||||
false, // content_initiated (download specific)
|
||||
false, // do_not_prompt_for_login (download specific)
|
||||
resource_context);
|
||||
}
|
||||
|
||||
protected:
|
||||
// atom::LayeredResourceHandler::Delegate:
|
||||
void OnResponseStarted(network::ResourceResponse* response) override {
|
||||
DCHECK_CURRENTLY_ON(BrowserThread::IO);
|
||||
|
||||
auto resource_response_head = response->head;
|
||||
auto headers = resource_response_head.headers;
|
||||
auto mime_type = resource_response_head.mime_type;
|
||||
if (headers.get())
|
||||
stream_info_->response_headers =
|
||||
new net::HttpResponseHeaders(headers->raw_headers());
|
||||
stream_info_->mime_type = mime_type;
|
||||
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::UI},
|
||||
base::Bind(&CallMigrationCallback<StreamResponseCallback>,
|
||||
base::Passed(&stream_response_cb_),
|
||||
base::Passed(&stream_info_)));
|
||||
}
|
||||
|
||||
private:
|
||||
friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>;
|
||||
friend class base::DeleteHelper<ResourceRequester>;
|
||||
~ResourceRequester() override {}
|
||||
|
||||
StreamResponseCallback stream_response_cb_;
|
||||
std::unique_ptr<content::StreamInfo> stream_info_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(ResourceRequester);
|
||||
};
|
||||
|
||||
PdfViewerUI::PdfViewerUI(content::BrowserContext* browser_context,
|
||||
content::WebUI* web_ui,
|
||||
const std::string& src)
|
||||
: content::WebUIController(web_ui),
|
||||
content::WebContentsObserver(web_ui->GetWebContents()),
|
||||
src_(src) {
|
||||
pdf_handler_ = new PdfViewerHandler(src);
|
||||
web_ui->AddMessageHandler(
|
||||
std::unique_ptr<content::WebUIMessageHandler>(pdf_handler_));
|
||||
content::URLDataSource::Add(browser_context, new BundledDataSource);
|
||||
}
|
||||
|
||||
PdfViewerUI::~PdfViewerUI() {}
|
||||
|
||||
bool PdfViewerUI::OnMessageReceived(
|
||||
const IPC::Message& message,
|
||||
content::RenderFrameHost* render_frame_host) {
|
||||
bool handled = true;
|
||||
IPC_BEGIN_MESSAGE_MAP(PdfViewerUI, message)
|
||||
IPC_MESSAGE_UNHANDLED(handled = false)
|
||||
IPC_END_MESSAGE_MAP()
|
||||
return handled;
|
||||
}
|
||||
|
||||
void PdfViewerUI::OnPdfStreamCreated(
|
||||
std::unique_ptr<content::StreamInfo> stream) {
|
||||
stream_ = std::move(stream);
|
||||
if (pdf_handler_)
|
||||
pdf_handler_->SetPdfResourceStream(stream_.get());
|
||||
resource_requester_ = nullptr;
|
||||
}
|
||||
|
||||
void PdfViewerUI::RenderFrameCreated(content::RenderFrameHost* rfh) {
|
||||
int render_process_id = rfh->GetProcess()->GetID();
|
||||
int render_frame_id = rfh->GetRoutingID();
|
||||
int render_view_id = rfh->GetRenderViewHost()->GetRoutingID();
|
||||
auto resource_context =
|
||||
web_contents()->GetBrowserContext()->GetResourceContext();
|
||||
auto callback =
|
||||
base::BindOnce(&PdfViewerUI::OnPdfStreamCreated, base::Unretained(this));
|
||||
resource_requester_ = new ResourceRequester(std::move(callback));
|
||||
base::PostTaskWithTraits(
|
||||
FROM_HERE, {BrowserThread::IO},
|
||||
base::Bind(&ResourceRequester::StartRequest, resource_requester_,
|
||||
GURL(src_), GURL(kPdfViewerUIOrigin), render_process_id,
|
||||
render_view_id, render_frame_id, resource_context));
|
||||
}
|
||||
|
||||
void PdfViewerUI::OnSaveURLAs(const GURL& url,
|
||||
const content::Referrer& referrer) {
|
||||
web_contents()->SaveFrame(url, referrer);
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,61 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_UI_WEBUI_PDF_VIEWER_UI_H_
|
||||
#define ATOM_BROWSER_UI_WEBUI_PDF_VIEWER_UI_H_
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "base/macros.h"
|
||||
#include "content/public/browser/web_contents_observer.h"
|
||||
#include "content/public/browser/web_ui_controller.h"
|
||||
#include "ipc/ipc_message.h"
|
||||
|
||||
namespace content {
|
||||
class BrowserContext;
|
||||
struct StreamInfo;
|
||||
} // namespace content
|
||||
|
||||
namespace atom {
|
||||
|
||||
class PdfViewerHandler;
|
||||
|
||||
class PdfViewerUI : public content::WebUIController,
|
||||
public content::WebContentsObserver {
|
||||
public:
|
||||
PdfViewerUI(content::BrowserContext* browser_context,
|
||||
content::WebUI* web_ui,
|
||||
const std::string& src);
|
||||
~PdfViewerUI() override;
|
||||
|
||||
// content::WebContentsObserver:
|
||||
bool OnMessageReceived(const IPC::Message& message,
|
||||
content::RenderFrameHost* render_frame_host) override;
|
||||
void RenderFrameCreated(content::RenderFrameHost* rfh) override;
|
||||
|
||||
private:
|
||||
using StreamResponseCallback =
|
||||
base::OnceCallback<void(std::unique_ptr<content::StreamInfo>)>;
|
||||
class ResourceRequester;
|
||||
|
||||
void OnPdfStreamCreated(std::unique_ptr<content::StreamInfo> stream_info);
|
||||
void OnSaveURLAs(const GURL& url, const content::Referrer& referrer);
|
||||
|
||||
// Source URL from where the PDF originates.
|
||||
std::string src_;
|
||||
|
||||
PdfViewerHandler* pdf_handler_;
|
||||
|
||||
scoped_refptr<ResourceRequester> resource_requester_;
|
||||
|
||||
// Pdf Resource stream.
|
||||
std::unique_ptr<content::StreamInfo> stream_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(PdfViewerUI);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_UI_WEBUI_PDF_VIEWER_UI_H_
|
||||
@@ -1,30 +0,0 @@
|
||||
// Copyright (c) 2017 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_UI_WIN_ATOM_DESKTOP_NATIVE_WIDGET_AURA_H_
|
||||
#define ATOM_BROWSER_UI_WIN_ATOM_DESKTOP_NATIVE_WIDGET_AURA_H_
|
||||
|
||||
#include "atom/browser/native_window_views.h"
|
||||
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
class AtomDesktopNativeWidgetAura : public views::DesktopNativeWidgetAura {
|
||||
public:
|
||||
explicit AtomDesktopNativeWidgetAura(
|
||||
views::internal::NativeWidgetDelegate* delegate);
|
||||
|
||||
// internal::NativeWidgetPrivate:
|
||||
void Activate() override;
|
||||
|
||||
private:
|
||||
void OnWindowActivated(wm::ActivationChangeObserver::ActivationReason reason,
|
||||
aura::Window* gained_active,
|
||||
aura::Window* lost_active) override;
|
||||
DISALLOW_COPY_AND_ASSIGN(AtomDesktopNativeWidgetAura);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_UI_WIN_ATOM_DESKTOP_NATIVE_WIDGET_AURA_H_
|
||||
@@ -1,35 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/ui/win/atom_desktop_window_tree_host_win.h"
|
||||
|
||||
#include "atom/browser/ui/win/message_handler_delegate.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
AtomDesktopWindowTreeHostWin::AtomDesktopWindowTreeHostWin(
|
||||
MessageHandlerDelegate* delegate,
|
||||
views::internal::NativeWidgetDelegate* native_widget_delegate,
|
||||
views::DesktopNativeWidgetAura* desktop_native_widget_aura)
|
||||
: views::DesktopWindowTreeHostWin(native_widget_delegate,
|
||||
desktop_native_widget_aura),
|
||||
delegate_(delegate) {}
|
||||
|
||||
AtomDesktopWindowTreeHostWin::~AtomDesktopWindowTreeHostWin() {}
|
||||
|
||||
bool AtomDesktopWindowTreeHostWin::PreHandleMSG(UINT message,
|
||||
WPARAM w_param,
|
||||
LPARAM l_param,
|
||||
LRESULT* result) {
|
||||
return delegate_->PreHandleMSG(message, w_param, l_param, result);
|
||||
}
|
||||
|
||||
bool AtomDesktopWindowTreeHostWin::HasNativeFrame() const {
|
||||
// Since we never use chromium's titlebar implementation, we can just say
|
||||
// that we use a native titlebar. This will disable the repaint locking when
|
||||
// DWM composition is disabled.
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,16 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/browser/ui/win/message_handler_delegate.h"
|
||||
|
||||
namespace atom {
|
||||
|
||||
bool MessageHandlerDelegate::PreHandleMSG(UINT message,
|
||||
WPARAM w_param,
|
||||
LPARAM l_param,
|
||||
LRESULT* result) {
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace atom
|
||||
@@ -1,28 +0,0 @@
|
||||
// Copyright (c) 2015 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_BROWSER_UI_WIN_MESSAGE_HANDLER_DELEGATE_H_
|
||||
#define ATOM_BROWSER_UI_WIN_MESSAGE_HANDLER_DELEGATE_H_
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
namespace atom {
|
||||
|
||||
class MessageHandlerDelegate {
|
||||
public:
|
||||
// Catch-all message handling and filtering. Called before
|
||||
// HWNDMessageHandler's built-in handling, which may pre-empt some
|
||||
// expectations in Views/Aura if messages are consumed. Returns true if the
|
||||
// message was consumed by the delegate and should not be processed further
|
||||
// by the HWNDMessageHandler. In this case, |result| is returned. |result| is
|
||||
// not modified otherwise.
|
||||
virtual bool PreHandleMSG(UINT message,
|
||||
WPARAM w_param,
|
||||
LPARAM l_param,
|
||||
LRESULT* result);
|
||||
};
|
||||
|
||||
} // namespace atom
|
||||
|
||||
#endif // ATOM_BROWSER_UI_WIN_MESSAGE_HANDLER_DELEGATE_H_
|
||||
@@ -1,47 +0,0 @@
|
||||
module atom.mojom;
|
||||
|
||||
import "mojo/public/mojom/base/values.mojom";
|
||||
|
||||
interface ElectronRenderer {
|
||||
Message(
|
||||
bool internal,
|
||||
bool send_to_all,
|
||||
string channel,
|
||||
mojo_base.mojom.ListValue arguments,
|
||||
int32 sender_id);
|
||||
|
||||
TakeHeapSnapshot(handle file) => (bool success);
|
||||
};
|
||||
|
||||
interface ElectronBrowser {
|
||||
// Emits an event on |channel| from the ipcMain JavaScript object in the main
|
||||
// process.
|
||||
Message(
|
||||
bool internal,
|
||||
string channel,
|
||||
mojo_base.mojom.ListValue arguments);
|
||||
|
||||
// Emits an event on |channel| from the ipcMain JavaScript object in the main
|
||||
// process, and waits synchronously for a response.
|
||||
//
|
||||
// NB. this is not marked [Sync] because mojo synchronous methods can be
|
||||
// reordered with respect to asynchronous methods on the same channel.
|
||||
// Instead, callers can manually block on the response to this method.
|
||||
MessageSync(
|
||||
bool internal,
|
||||
string channel,
|
||||
mojo_base.mojom.ListValue arguments) => (mojo_base.mojom.Value result);
|
||||
|
||||
// Emits an event from the |ipcRenderer| JavaScript object in the target
|
||||
// WebContents's main frame, specified by |web_contents_id|.
|
||||
MessageTo(
|
||||
bool internal,
|
||||
bool send_to_all,
|
||||
int32 web_contents_id,
|
||||
string channel,
|
||||
mojo_base.mojom.ListValue arguments);
|
||||
|
||||
MessageHost(
|
||||
string channel,
|
||||
mojo_base.mojom.ListValue arguments);
|
||||
};
|
||||
@@ -1,51 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
// Multiply-included file, no traditional include guard.
|
||||
|
||||
#include "atom/common/draggable_region.h"
|
||||
#include "base/strings/string16.h"
|
||||
#include "base/values.h"
|
||||
#include "content/public/common/common_param_traits.h"
|
||||
#include "content/public/common/referrer.h"
|
||||
#include "ipc/ipc_message_macros.h"
|
||||
#include "ipc/ipc_platform_file.h"
|
||||
#include "ui/gfx/geometry/rect_f.h"
|
||||
#include "ui/gfx/ipc/gfx_param_traits.h"
|
||||
#include "url/gurl.h"
|
||||
|
||||
// The message starter should be declared in ipc/ipc_message_start.h. Since
|
||||
// we don't want to patch Chromium, we just pretend to be Content Shell.
|
||||
|
||||
#define IPC_MESSAGE_START ShellMsgStart
|
||||
|
||||
IPC_STRUCT_TRAITS_BEGIN(atom::DraggableRegion)
|
||||
IPC_STRUCT_TRAITS_MEMBER(draggable)
|
||||
IPC_STRUCT_TRAITS_MEMBER(bounds)
|
||||
IPC_STRUCT_TRAITS_END()
|
||||
|
||||
IPC_MESSAGE_ROUTED3(AtomAutofillFrameHostMsg_ShowPopup,
|
||||
gfx::RectF /* bounds */,
|
||||
std::vector<base::string16> /* values */,
|
||||
std::vector<base::string16> /* labels */)
|
||||
|
||||
IPC_MESSAGE_ROUTED0(AtomAutofillFrameHostMsg_HidePopup)
|
||||
|
||||
IPC_MESSAGE_ROUTED1(AtomAutofillFrameMsg_AcceptSuggestion,
|
||||
base::string16 /* suggestion */)
|
||||
|
||||
// Sent by the renderer when the draggable regions are updated.
|
||||
IPC_MESSAGE_ROUTED1(AtomFrameHostMsg_UpdateDraggableRegions,
|
||||
std::vector<atom::DraggableRegion> /* regions */)
|
||||
|
||||
// Update renderer process preferences.
|
||||
IPC_MESSAGE_CONTROL1(AtomMsg_UpdatePreferences, base::ListValue)
|
||||
|
||||
// Sent by renderer to set the temporary zoom level.
|
||||
IPC_SYNC_MESSAGE_ROUTED1_1(AtomFrameHostMsg_SetTemporaryZoomLevel,
|
||||
double /* zoom level */,
|
||||
double /* result */)
|
||||
|
||||
// Sent by renderer to get the zoom level.
|
||||
IPC_SYNC_MESSAGE_ROUTED0_1(AtomFrameHostMsg_GetZoomLevel, double /* result */)
|
||||
@@ -1,69 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
#include "atom/common/crash_reporter/crash_reporter.h"
|
||||
#include "atom/common/native_mate_converters/file_path_converter.h"
|
||||
#include "base/bind.h"
|
||||
#include "native_mate/dictionary.h"
|
||||
|
||||
#include "atom/common/node_includes.h"
|
||||
|
||||
using crash_reporter::CrashReporter;
|
||||
|
||||
namespace mate {
|
||||
|
||||
template <>
|
||||
struct Converter<CrashReporter::UploadReportResult> {
|
||||
static v8::Local<v8::Value> ToV8(
|
||||
v8::Isolate* isolate,
|
||||
const CrashReporter::UploadReportResult& reports) {
|
||||
mate::Dictionary dict(isolate, v8::Object::New(isolate));
|
||||
dict.Set("date",
|
||||
v8::Date::New(isolate->GetCurrentContext(), reports.first * 1000.0)
|
||||
.ToLocalChecked());
|
||||
dict.Set("id", reports.second);
|
||||
return dict.GetHandle();
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mate
|
||||
|
||||
namespace {
|
||||
|
||||
void AddExtraParameter(const std::string& key, const std::string& value) {
|
||||
CrashReporter::GetInstance()->AddExtraParameter(key, value);
|
||||
}
|
||||
|
||||
void RemoveExtraParameter(const std::string& key) {
|
||||
CrashReporter::GetInstance()->RemoveExtraParameter(key);
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> GetParameters() {
|
||||
return CrashReporter::GetInstance()->GetParameters();
|
||||
}
|
||||
|
||||
void Initialize(v8::Local<v8::Object> exports,
|
||||
v8::Local<v8::Value> unused,
|
||||
v8::Local<v8::Context> context,
|
||||
void* priv) {
|
||||
mate::Dictionary dict(context->GetIsolate(), exports);
|
||||
auto reporter = base::Unretained(CrashReporter::GetInstance());
|
||||
dict.SetMethod("start", base::Bind(&CrashReporter::Start, reporter));
|
||||
dict.SetMethod("addExtraParameter", &AddExtraParameter);
|
||||
dict.SetMethod("removeExtraParameter", &RemoveExtraParameter);
|
||||
dict.SetMethod("getParameters", &GetParameters);
|
||||
dict.SetMethod("getUploadedReports",
|
||||
base::Bind(&CrashReporter::GetUploadedReports, reporter));
|
||||
dict.SetMethod("setUploadToServer",
|
||||
base::Bind(&CrashReporter::SetUploadToServer, reporter));
|
||||
dict.SetMethod("getUploadToServer",
|
||||
base::Bind(&CrashReporter::GetUploadToServer, reporter));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
NODE_LINKED_MODULE_CONTEXT_AWARE(atom_common_crash_reporter, Initialize)
|
||||
@@ -1,33 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_COMMON_ATOM_VERSION_H_
|
||||
#define ATOM_COMMON_ATOM_VERSION_H_
|
||||
|
||||
#define ATOM_MAJOR_VERSION 6
|
||||
#define ATOM_MINOR_VERSION 0
|
||||
#define ATOM_PATCH_VERSION 0
|
||||
// clang-format off
|
||||
#define ATOM_PRE_RELEASE_VERSION -nightly.20190404
|
||||
// clang-format on
|
||||
|
||||
#ifndef ATOM_STRINGIFY
|
||||
#define ATOM_STRINGIFY(n) ATOM_STRINGIFY_HELPER(n)
|
||||
#define ATOM_STRINGIFY_HELPER(n) #n
|
||||
#endif
|
||||
|
||||
#ifndef ATOM_PRE_RELEASE_VERSION
|
||||
#define ATOM_VERSION_STRING \
|
||||
ATOM_STRINGIFY(ATOM_MAJOR_VERSION) \
|
||||
"." ATOM_STRINGIFY(ATOM_MINOR_VERSION) "." ATOM_STRINGIFY(ATOM_PATCH_VERSION)
|
||||
#else
|
||||
#define ATOM_VERSION_STRING \
|
||||
ATOM_STRINGIFY(ATOM_MAJOR_VERSION) \
|
||||
"." ATOM_STRINGIFY(ATOM_MINOR_VERSION) "." ATOM_STRINGIFY( \
|
||||
ATOM_PATCH_VERSION) ATOM_STRINGIFY(ATOM_PRE_RELEASE_VERSION)
|
||||
#endif
|
||||
|
||||
#define ATOM_VERSION "v" ATOM_VERSION_STRING
|
||||
|
||||
#endif // ATOM_COMMON_ATOM_VERSION_H_
|
||||
@@ -1,31 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
// Get basic type definitions.
|
||||
#define IPC_MESSAGE_IMPL
|
||||
#include "atom/common/common_message_generator.h"
|
||||
|
||||
// Generate constructors.
|
||||
#include "ipc/struct_constructor_macros.h"
|
||||
|
||||
// lint: must come after struct_constructor_macros.
|
||||
#include "atom/common/common_message_generator.h"
|
||||
|
||||
// Generate param traits write methods.
|
||||
#include "ipc/param_traits_write_macros.h"
|
||||
namespace IPC {
|
||||
#include "atom/common/common_message_generator.h"
|
||||
} // namespace IPC
|
||||
|
||||
// Generate param traits read methods.
|
||||
#include "ipc/param_traits_read_macros.h"
|
||||
namespace IPC {
|
||||
#include "atom/common/common_message_generator.h"
|
||||
} // namespace IPC
|
||||
|
||||
// Generate param traits log methods.
|
||||
#include "ipc/param_traits_log_macros.h"
|
||||
namespace IPC {
|
||||
#include "atom/common/common_message_generator.h"
|
||||
} // namespace IPC
|
||||
@@ -1,7 +0,0 @@
|
||||
// Copyright (c) 2014 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
// Multiply-included file, no traditional include guard.
|
||||
|
||||
#include "atom/common/api/api_messages.h"
|
||||
@@ -1,66 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_MAC_H_
|
||||
#define ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_MAC_H_
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "atom/common/crash_reporter/crash_reporter.h"
|
||||
#include "base/compiler_specific.h"
|
||||
#include "base/strings/string_piece.h"
|
||||
#include "crashpad/client/crash_report_database.h"
|
||||
#include "crashpad/client/simple_string_dictionary.h"
|
||||
|
||||
namespace base {
|
||||
template <typename T>
|
||||
struct DefaultSingletonTraits;
|
||||
}
|
||||
|
||||
namespace crash_reporter {
|
||||
|
||||
class CrashReporterMac : public CrashReporter {
|
||||
public:
|
||||
static CrashReporterMac* GetInstance();
|
||||
|
||||
void InitBreakpad(const std::string& product_name,
|
||||
const std::string& version,
|
||||
const std::string& company_name,
|
||||
const std::string& submit_url,
|
||||
const base::FilePath& crashes_dir,
|
||||
bool upload_to_server,
|
||||
bool skip_system_crash_handler) override;
|
||||
void SetUploadParameters() override;
|
||||
void SetUploadToServer(bool upload_to_server) override;
|
||||
bool GetUploadToServer() override;
|
||||
void AddExtraParameter(const std::string& key,
|
||||
const std::string& value) override;
|
||||
void RemoveExtraParameter(const std::string& key) override;
|
||||
std::map<std::string, std::string> GetParameters() const override;
|
||||
|
||||
private:
|
||||
friend struct base::DefaultSingletonTraits<CrashReporterMac>;
|
||||
|
||||
CrashReporterMac();
|
||||
~CrashReporterMac() override;
|
||||
|
||||
void SetUploadsEnabled(bool enable_uploads);
|
||||
void SetCrashKeyValue(const base::StringPiece& key,
|
||||
const base::StringPiece& value);
|
||||
|
||||
std::vector<UploadReportResult> GetUploadedReports(
|
||||
const base::FilePath& crashes_dir) override;
|
||||
|
||||
std::unique_ptr<crashpad::SimpleStringDictionary> simple_string_dictionary_;
|
||||
std::unique_ptr<crashpad::CrashReportDatabase> database_;
|
||||
|
||||
DISALLOW_COPY_AND_ASSIGN(CrashReporterMac);
|
||||
};
|
||||
|
||||
} // namespace crash_reporter
|
||||
|
||||
#endif // ATOM_COMMON_CRASH_REPORTER_CRASH_REPORTER_MAC_H_
|
||||
@@ -1,182 +0,0 @@
|
||||
// Copyright (c) 2013 GitHub, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "atom/common/crash_reporter/crash_reporter_mac.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "base/files/file_util.h"
|
||||
#include "base/mac/bundle_locations.h"
|
||||
#include "base/mac/mac_util.h"
|
||||
#include "base/memory/singleton.h"
|
||||
#include "base/strings/string_piece.h"
|
||||
#include "base/strings/stringprintf.h"
|
||||
#include "base/strings/sys_string_conversions.h"
|
||||
#include "base/threading/thread_restrictions.h"
|
||||
#include "crashpad/client/crashpad_client.h"
|
||||
#include "crashpad/client/crashpad_info.h"
|
||||
#include "crashpad/client/settings.h"
|
||||
|
||||
namespace crash_reporter {
|
||||
|
||||
CrashReporterMac::CrashReporterMac() {}
|
||||
|
||||
CrashReporterMac::~CrashReporterMac() {}
|
||||
|
||||
void CrashReporterMac::InitBreakpad(const std::string& product_name,
|
||||
const std::string& version,
|
||||
const std::string& company_name,
|
||||
const std::string& submit_url,
|
||||
const base::FilePath& crashes_dir,
|
||||
bool upload_to_server,
|
||||
bool skip_system_crash_handler) {
|
||||
// check whether crashpad has been initialized.
|
||||
// Only need to initialize once.
|
||||
if (simple_string_dictionary_)
|
||||
return;
|
||||
|
||||
if (is_browser_) {
|
||||
@autoreleasepool {
|
||||
base::FilePath framework_bundle_path = base::mac::FrameworkBundlePath();
|
||||
base::FilePath handler_path =
|
||||
framework_bundle_path.Append("Resources").Append("crashpad_handler");
|
||||
|
||||
std::vector<std::string> args = {
|
||||
"--no-rate-limit",
|
||||
"--no-upload-gzip", // not all servers accept gzip
|
||||
};
|
||||
|
||||
crashpad::CrashpadClient crashpad_client;
|
||||
crashpad_client.StartHandler(handler_path, crashes_dir, crashes_dir,
|
||||
submit_url, StringMap(), args, true, false);
|
||||
} // @autoreleasepool
|
||||
}
|
||||
|
||||
crashpad::CrashpadInfo* crashpad_info =
|
||||
crashpad::CrashpadInfo::GetCrashpadInfo();
|
||||
if (skip_system_crash_handler) {
|
||||
crashpad_info->set_system_crash_reporter_forwarding(
|
||||
crashpad::TriState::kDisabled);
|
||||
}
|
||||
|
||||
simple_string_dictionary_.reset(new crashpad::SimpleStringDictionary());
|
||||
crashpad_info->set_simple_annotations(simple_string_dictionary_.get());
|
||||
|
||||
SetCrashKeyValue("prod", ATOM_PRODUCT_NAME);
|
||||
SetCrashKeyValue("process_type", is_browser_ ? "browser" : "renderer");
|
||||
SetCrashKeyValue("ver", version);
|
||||
|
||||
for (const auto& upload_parameter : upload_parameters_) {
|
||||
SetCrashKeyValue(upload_parameter.first, upload_parameter.second);
|
||||
}
|
||||
if (is_browser_) {
|
||||
database_ = crashpad::CrashReportDatabase::Initialize(crashes_dir);
|
||||
SetUploadToServer(upload_to_server);
|
||||
}
|
||||
}
|
||||
|
||||
bool CrashReporterMac::GetUploadToServer() {
|
||||
bool enabled = true;
|
||||
if (database_) {
|
||||
database_->GetSettings()->GetUploadsEnabled(&enabled);
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
|
||||
void CrashReporterMac::SetUploadToServer(const bool upload_to_server) {
|
||||
if (database_) {
|
||||
database_->GetSettings()->SetUploadsEnabled(upload_to_server);
|
||||
}
|
||||
}
|
||||
|
||||
void CrashReporterMac::SetUploadParameters() {
|
||||
upload_parameters_["platform"] = "darwin";
|
||||
}
|
||||
|
||||
void CrashReporterMac::SetCrashKeyValue(const base::StringPiece& key,
|
||||
const base::StringPiece& value) {
|
||||
simple_string_dictionary_->SetKeyValue(key.data(), value.data());
|
||||
}
|
||||
|
||||
void CrashReporterMac::AddExtraParameter(const std::string& key,
|
||||
const std::string& value) {
|
||||
if (simple_string_dictionary_) {
|
||||
SetCrashKeyValue(key, value);
|
||||
} else {
|
||||
upload_parameters_[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
void CrashReporterMac::RemoveExtraParameter(const std::string& key) {
|
||||
if (simple_string_dictionary_)
|
||||
simple_string_dictionary_->RemoveKey(key.data());
|
||||
else
|
||||
upload_parameters_.erase(key);
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> CrashReporterMac::GetParameters() const {
|
||||
if (simple_string_dictionary_) {
|
||||
std::map<std::string, std::string> ret;
|
||||
crashpad::SimpleStringDictionary::Iterator iter(*simple_string_dictionary_);
|
||||
for (;;) {
|
||||
auto* const entry = iter.Next();
|
||||
if (!entry)
|
||||
break;
|
||||
ret[entry->key] = entry->value;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
return upload_parameters_;
|
||||
}
|
||||
|
||||
std::vector<CrashReporter::UploadReportResult>
|
||||
CrashReporterMac::GetUploadedReports(const base::FilePath& crashes_dir) {
|
||||
std::vector<CrashReporter::UploadReportResult> uploaded_reports;
|
||||
|
||||
{
|
||||
base::ThreadRestrictions::ScopedAllowIO allow_io;
|
||||
if (!base::PathExists(crashes_dir)) {
|
||||
return uploaded_reports;
|
||||
}
|
||||
}
|
||||
// Load crashpad database.
|
||||
std::unique_ptr<crashpad::CrashReportDatabase> database =
|
||||
crashpad::CrashReportDatabase::Initialize(crashes_dir);
|
||||
DCHECK(database);
|
||||
|
||||
std::vector<crashpad::CrashReportDatabase::Report> completed_reports;
|
||||
crashpad::CrashReportDatabase::OperationStatus status =
|
||||
database->GetCompletedReports(&completed_reports);
|
||||
if (status != crashpad::CrashReportDatabase::kNoError) {
|
||||
return uploaded_reports;
|
||||
}
|
||||
|
||||
for (const crashpad::CrashReportDatabase::Report& completed_report :
|
||||
completed_reports) {
|
||||
if (completed_report.uploaded) {
|
||||
uploaded_reports.push_back(
|
||||
UploadReportResult(static_cast<int>(completed_report.creation_time),
|
||||
completed_report.id));
|
||||
}
|
||||
}
|
||||
|
||||
auto sort_by_time = [](const UploadReportResult& a,
|
||||
const UploadReportResult& b) {
|
||||
return a.first >= b.first;
|
||||
};
|
||||
std::sort(uploaded_reports.begin(), uploaded_reports.end(), sort_by_time);
|
||||
return uploaded_reports;
|
||||
}
|
||||
|
||||
// static
|
||||
CrashReporterMac* CrashReporterMac::GetInstance() {
|
||||
return base::Singleton<CrashReporterMac>::get();
|
||||
}
|
||||
|
||||
// static
|
||||
CrashReporter* CrashReporter::GetInstance() {
|
||||
return CrashReporterMac::GetInstance();
|
||||
}
|
||||
|
||||
} // namespace crash_reporter
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user