mirror of
https://github.com/tenox7/wrp.git
synced 2025-04-21 14:37:00 +00:00
Compare commits
275 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
0fd6967393 | ||
|
3ad8f78c45 | ||
|
e3dbe85c51 | ||
|
30c42bd9b8 | ||
|
12724a262e | ||
|
25a382e809 | ||
|
b03b8a8031 | ||
|
a0eb33fe51 | ||
|
f56c958aba | ||
|
3004962beb | ||
|
4d9319eef2 | ||
|
7916fa1260 | ||
|
9f9014dc15 | ||
|
3231a0a61c | ||
|
94fb4f437b | ||
|
9110ad0853 | ||
|
51c4c35651 | ||
|
b6e402029a | ||
|
9f7107c00b | ||
|
500ad0d19a | ||
|
b5747f52e7 | ||
|
0d998af68c | ||
|
eb38499280 | ||
|
56fa314d61 | ||
|
335a84f52e | ||
|
bb29ce38de | ||
|
db4ed0d811 | ||
|
2f667e447c | ||
|
00304b5d05 | ||
|
9f21d8d06e | ||
|
b0f4170c6c | ||
|
8d165df36d | ||
|
407907bece | ||
|
f838caa328 | ||
|
a8b8a557f7 | ||
|
d036914fcb | ||
|
701240eb7c | ||
|
1d9af26604 | ||
|
5ed55c387c | ||
|
0e3192b69f | ||
|
91870f5724 | ||
|
c1ffd71e25 | ||
|
26b3c21aa7 | ||
|
8cec22eb90 | ||
|
e64f413c76 | ||
|
94d0e0d128 | ||
|
b546b5cbae | ||
|
a2a4152b86 | ||
|
db77479bad | ||
|
33436333cf | ||
|
866750700b | ||
|
3f445abd14 | ||
|
d7eb89e135 | ||
|
bf946f0f63 | ||
|
7673e15b9e | ||
|
d00b1d5d7f | ||
|
3e8f109edd | ||
|
9a0e5809c1 | ||
|
96acf94521 | ||
|
807373d668 | ||
|
703e9d0452 | ||
|
f7799ecba5 | ||
|
37562cce23 | ||
|
631971b0bb | ||
|
23a7ba5cbf | ||
|
2733a84d2d | ||
|
abea41f498 | ||
|
da524ff275 | ||
|
b92478fd6a | ||
|
ee0e72f246 | ||
|
a3c06d346c | ||
|
0065fdc2c7 | ||
|
22efadf9cf | ||
|
4070fa7a53 | ||
|
41a14ad590 | ||
|
a212a14bd8 | ||
|
5a86c32d9a | ||
|
55f3c852f9 | ||
|
79c86a7056 | ||
|
19f4be3ac1 | ||
|
6ffdf1fd7f | ||
|
0796c86e73 | ||
|
d8b4f160ac | ||
|
93e9fddca7 | ||
|
e13a06610b | ||
|
5b28f1d913 | ||
|
da5246b9df | ||
|
8a484813c3 | ||
|
75233ccb97 | ||
|
04954f8be6 | ||
|
884374edcd | ||
|
ba522e3a86 | ||
|
e05135e433 | ||
|
67d550672b | ||
|
71889effe7 | ||
|
6a7ffbb67b | ||
|
f93058fed3 | ||
|
67ed26b8f4 | ||
|
6aefcdacc5 | ||
|
de315fb95f | ||
|
b098b3632a | ||
|
5ec0266f75 | ||
|
7d9cec6297 | ||
|
43df501d97 | ||
|
85d64a3577 | ||
|
993e5723ed | ||
|
9056c798d6 | ||
|
b937bea370 | ||
|
8fd65b3e47 | ||
|
8716a983ce | ||
|
4757cfd32b | ||
|
79e6f3a17e | ||
|
d8f5c6fb28 | ||
|
c816ef712a | ||
|
d28924583c | ||
|
1c17b39ea5 | ||
|
ecb2cc0c06 | ||
|
b571df7a37 | ||
|
78c568ac09 | ||
|
04a755749e | ||
|
e983f244f8 | ||
|
9b76c045d6 | ||
|
c8e391274a | ||
|
7b1274b9d4 | ||
|
0128b3ff8e | ||
|
6de3fad580 | ||
|
d7dcb58adc | ||
|
e5f83225f7 | ||
|
36803c4312 | ||
|
40e081be77 | ||
|
1c18fb9b81 | ||
|
363fbcd225 | ||
|
bf7e7bfb2c | ||
|
fec812bc32 | ||
|
a238a0ea6f | ||
|
444b7b31d7 | ||
|
76e72d5368 | ||
|
c4d9833707 | ||
|
9cd286add8 | ||
|
fdfbe80024 | ||
|
d602124ed6 | ||
|
6e5e829b02 | ||
|
f978d91ba9 | ||
|
9b15feacb2 | ||
|
08a89c6097 | ||
|
fa3bd3f8fb | ||
|
55f4e45b4c | ||
|
9e77aa7261 | ||
|
8a9870d8e2 | ||
|
7c33bc67dc | ||
|
48c4ab8254 | ||
|
bc5f8cabb1 | ||
|
cc16d6c3b9 | ||
|
1d26a451ea | ||
|
cfb608c1f3 | ||
|
d1fcd30db8 | ||
|
c7811a6886 | ||
|
3b88b8665b | ||
|
ad84f6d087 | ||
|
97d1443d8c | ||
|
82bbd4bdaa | ||
|
36d0cdcb0a | ||
|
f5be172d43 | ||
|
cf8b85e15a | ||
|
700c4aa495 | ||
|
f05dde8188 | ||
|
2a22cfd755 | ||
|
56ac414405 | ||
|
a79f477948 | ||
|
c036841c0a | ||
|
878f43af75 | ||
|
b54ebbf9e5 | ||
|
5dc4699ac9 | ||
|
f6e1f3ee88 | ||
|
8aaf435225 | ||
|
4fa913a9dd | ||
|
4302731bc8 | ||
|
d6b33ad140 | ||
|
3dddb70be0 | ||
|
3ff226e1df | ||
|
1ddf005a23 | ||
|
69efa1fb92 | ||
|
2c2fbd11a6 | ||
|
259f998787 | ||
|
1ab9124a4f | ||
|
4d0c8b9e7e | ||
|
fa25e816a7 | ||
|
36427fac64 | ||
|
ac594cdebd | ||
|
11b5ce9b6d | ||
|
b8ae1ceba5 | ||
|
3224c63fd1 | ||
|
733be4a14a | ||
|
4533e38a31 | ||
|
d4043f0b7d | ||
|
c64380dd72 | ||
|
4d911cb330 | ||
|
a3beaf4b14 | ||
|
311bb829da | ||
|
41dfa7dae2 | ||
|
889561aeb0 | ||
|
b90300ba2d | ||
|
c80cb876ce | ||
|
ef04d2da72 | ||
|
2e9773f705 | ||
|
0957fedaee | ||
|
60ca1a0d50 | ||
|
0c728b08fe | ||
|
81b47eb59c | ||
|
15ebf497b8 | ||
|
9215ed57c0 | ||
|
ba0b521762 | ||
|
34b25be7d7 | ||
|
c4e3671468 | ||
|
f73c778b7c | ||
|
c9cedb7f81 | ||
|
f69a6e5219 | ||
|
a258f603b3 | ||
|
b30458930b | ||
|
9fca2704dc | ||
|
62b11cb216 | ||
|
78f9598af5 | ||
|
5ce1c2456f | ||
|
c93c2c883e | ||
|
d7a47d366b | ||
|
ffcaca4907 | ||
|
260840adb5 | ||
|
fcd746aa9a | ||
|
e2c06b2e7b | ||
|
fafe232463 | ||
|
6c49b1f73c | ||
|
a533521784 | ||
|
0f9ebc6252 | ||
|
af5174456a | ||
|
d49ef9c1c2 | ||
|
23b4fbaf63 | ||
|
a91cc60a51 | ||
|
51cd108bad | ||
|
cd2cf0baae | ||
|
a344d177d6 | ||
|
02766d8844 | ||
|
91091cf94b | ||
|
95d9de7348 | ||
|
6449c64e36 | ||
|
b058831ec6 | ||
|
7c50c6e841 | ||
|
2f2e99eb85 | ||
|
4dee5ea8d9 | ||
|
333666d3b0 | ||
|
780143b766 | ||
|
6b89e463f3 | ||
|
ea1ae10f97 | ||
|
eb4201c56b | ||
|
4cd55b31b0 | ||
|
f0ba852785 | ||
|
66412fa95e | ||
|
cd5bb94def | ||
|
357f3ed6bf | ||
|
97c0679e0b | ||
|
e2223af833 | ||
|
60989d3395 | ||
|
74d015a4da | ||
|
8628c00dd7 | ||
|
327baf318a | ||
|
0e07f422f6 | ||
|
f7aece10e9 | ||
|
a7b7164932 | ||
|
7a27cf7b62 | ||
|
749f8bea5d | ||
|
290bc5a977 | ||
|
cc98932f5a | ||
|
f69e213a0b | ||
|
66641a099b | ||
|
872321c699 | ||
|
ba4183e0b4 |
5
.gitignore
vendored
5
.gitignore
vendored
@ -1 +1,4 @@
|
||||
wrp-*
|
||||
wrp-*
|
||||
wrp
|
||||
wrp.exe
|
||||
statik
|
||||
|
14
Dockerfile
Normal file
14
Dockerfile
Normal file
@ -0,0 +1,14 @@
|
||||
FROM golang AS builder
|
||||
WORKDIR /src
|
||||
RUN git clone https://github.com/tenox7/wrp.git
|
||||
WORKDIR /src/wrp
|
||||
RUN go mod download
|
||||
ARG TARGETARCH
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH} go build -o /wrp-${TARGETARCH}
|
||||
|
||||
FROM chromedp/headless-shell
|
||||
ARG TARGETARCH
|
||||
COPY --from=builder /wrp-${TARGETARCH} /wrp
|
||||
ENTRYPOINT ["/wrp"]
|
||||
ENV PATH="/headless-shell:${PATH}"
|
||||
LABEL maintainer="as@tenoware.com"
|
6
Dockerfile.local
Normal file
6
Dockerfile.local
Normal file
@ -0,0 +1,6 @@
|
||||
FROM chromedp/headless-shell
|
||||
ARG TARGETARCH
|
||||
ADD wrp-${TARGETARCH}-linux /wrp
|
||||
ENTRYPOINT ["/wrp"]
|
||||
ENV PATH="/headless-shell:${PATH}"
|
||||
LABEL maintainer="as@tenoware.com"
|
39
Makefile
Normal file → Executable file
39
Makefile
Normal file → Executable file
@ -1,25 +1,28 @@
|
||||
all: linux freebsd openbsd macos windows rpi
|
||||
all: wrp
|
||||
|
||||
linux:
|
||||
GOOS=linux GOARCH=amd64 go build -a -o wrp-linux wrp.go
|
||||
wrp: wrp.go
|
||||
go build -a
|
||||
|
||||
linux-ppc64le:
|
||||
GOOS=linux GOARCH=ppc64le go build -a -o wrp-linux-ppc64le wrp.go
|
||||
cross:
|
||||
GOOS=linux GOARCH=amd64 go build -a -o wrp-amd64-linux
|
||||
GOOS=freebsd GOARCH=amd64 go build -a -o wrp-amd64-freebsd
|
||||
GOOS=openbsd GOARCH=amd64 go build -a -o wrp-amd64-openbsd
|
||||
GOOS=darwin GOARCH=amd64 go build -a -o wrp-amd64-macos
|
||||
GOOS=darwin GOARCH=arm64 go build -a -o wrp-arm64-macos
|
||||
GOOS=windows GOARCH=amd64 go build -a -o wrp-amd64-windows.exe
|
||||
GOOS=linux GOARCH=arm go build -a -o wrp-arm-linux
|
||||
GOOS=linux GOARCH=arm64 go build -a -o wrp-arm64-linux
|
||||
|
||||
rpi:
|
||||
GOOS=linux GOARCH=arm go build -a -o wrp-linux-rpi wrp.go
|
||||
docker-local:
|
||||
GOOS=linux GOARCH=amd64 go build -a -o wrp-amd64-linux
|
||||
GOOS=linux GOARCH=arm64 go build -a -o wrp-arm64-linux
|
||||
docker buildx build --platform linux/amd64,linux/arm64 -t tenox7/wrp:latest -f Dockerfile.local --load .
|
||||
|
||||
freebsd:
|
||||
GOOS=freebsd GOARCH=amd64 go build -a -o wrp-freebsd wrp.go
|
||||
docker-push:
|
||||
docker buildx build --platform linux/amd64,linux/arm64 -t tenox7/wrp:latest --push .
|
||||
|
||||
openbsd:
|
||||
GOOS=openbsd GOARCH=amd64 go build -a -o wrp-openbsd wrp.go
|
||||
|
||||
macos:
|
||||
GOOS=darwin GOARCH=amd64 go build -a -o wrp-macos wrp.go
|
||||
|
||||
windows:
|
||||
GOOS=windows GOARCH=amd64 go build -a -o wrp-windows.exe wrp.go
|
||||
docker-clean:
|
||||
docker buildx prune -a -f
|
||||
|
||||
clean:
|
||||
rm -rf wrp-linux wrp-freebsd wrp-openbsd wrp-macos wrp-windows.exe wrp-linux-rpi
|
||||
rm -rf wrp-* wrp
|
||||
|
229
README.md
229
README.md
@ -1,46 +1,219 @@
|
||||
# WRP - Web Rendering Proxy
|
||||
|
||||
A HTTP proxy server that allows to use historical and obsolete web browsers on the modern web. It works by rendering the web page in to a GIF image. It sends mouse clicks via ISMAP and keystrokes from a text box form input.
|
||||
A browser-in-browser "proxy" server that allows to use historical / vintage web browsers on the modern web. It has two modes:
|
||||
|
||||
## Current Status
|
||||
|
||||
* This is a new reimplementation in GoLang/[ChromeDP](https://github.com/chromedp/chromedp). Python/Webkit being now deprecated.
|
||||
* Beta versiom, but fully supported an maintained.
|
||||
* Works as browser-in-browser. A real http proxy mode is being investigated. Check [issue #35](https://github.com/tenox7/wrp/issues/35) for updates.
|
||||
* As of 4.1 supports clicking on non-link elements (eg. cookie warnings, dropdown menus, etc.) and sending keystrokes. Yes, you can login and use Gmail or play web based games from any old browser.
|
||||
|
||||
## Usage
|
||||
|
||||
1. [Download a WRP binary](https://github.com/tenox7/wrp/releases/) and run it on a machine that will become your WRP server.
|
||||
2. Point your legacy browser to `http://address:port` of WRP server. Do not set or use it as a "Proxy Server" (yet).
|
||||
3. Type a search string or a http/https URL and click GO.
|
||||
4. Adjust your screen width/height/scale/#colors to fit in your old browser.
|
||||
5. Scroll web page by clicking on the in-image scroll bar.
|
||||
6. Send keystrokes by filling in K input box and pressing Go. You also have buttons for backspace, enter and arrow keys.
|
||||
- ISMAP "graphical" mode, renders web page in to a GIF, PNG or JPG image with clickable imagemap.
|
||||
- Simple HTML mode converts web page in to Markdown, then renders it into simplified HTML for old browsers.
|
||||
|
||||

|
||||
|
||||
## Usage Instructions
|
||||
|
||||
* [Download a WRP binary](https://github.com/tenox7/wrp/releases/) run it on a machine that will become your WRP gateway/server. This should be modern hardware and OS. Google Chrome / Chromium Browser is required to be preinstalled. Do not try to run WRP on an old machine like Windows XP or 98.
|
||||
* Make sure you have disabled firewall or open port WRP is listening on (by default 8080).
|
||||
* Point your legacy browser to `http://address:port` of the WRP server. Do not set or use it as a "proxy server".
|
||||
* Type a search string or a full http/https URL and click **Go**.
|
||||
* Select whether you want to use graphical (ISMAP) or simple HTML mode.
|
||||
|
||||
### Image Map Mode
|
||||
|
||||
* Adjust your screen **W**idth/**H**eight/**S**cale/**C**olors to fit in your old browser.
|
||||
* Scroll web page by clicking on the in-image scroll bar on the right.
|
||||
* WRP also allows **a single tall image without the vertical scrollbar** and use client scrolling. To enable this, simply height **H** to `0` . However this should not be used with old and low spec clients. Such tall images will be very large, take a lot of memory and long time to process, especially for GIFs.
|
||||
* Do not use client browser history-back, instead use **Bk** button in the app.
|
||||
* You can re-capture page screenshot without reloading by using **St** (Stop). This is useful if page didn't render fully before screenshot is taken.
|
||||
* You can also reload and re-capture current page with **Re** (Reload).
|
||||
* To send keystrokes, fill **K** input box and press **Go**. There also are buttons for backspace, enter and arrow keys.
|
||||
* If your browser supports it, prefer PNG over GIF/JPG. PNG is much faster, whereas GIF/JPG requires a lot of additional processing on both client and server to encode/decode.
|
||||
* GIF images are by default encoded with 216 colors, "web safe" palette. This uses an ultra fast but not very accurate color mapping algorithm. If you want better color representation switch to 256 color mode.
|
||||
|
||||
### Simple HTML mode
|
||||
|
||||
* Select image type PNG/GIF/JPG. Each individual image from the original web site will be converted to the selected format.
|
||||
* Type maximum image size in pixels.
|
||||
|
||||
## UI explanation
|
||||
|
||||
The first unnamed input box is either search (google) or URL starting with http/https
|
||||
|
||||
`Go` Navigate to the url or perform search
|
||||
|
||||
`Bk` History Back
|
||||
|
||||
`St` Stop, also re-capture screenshot without refreshing page, for example if page
|
||||
render takes a long time or it updates / changes periodically
|
||||
|
||||
`Re` Remote Reload / Refresh
|
||||
|
||||
`Up` Page Up
|
||||
|
||||
`Dn` Page Down
|
||||
|
||||
`W` is width in pixels, adjust it to get rid of horizontal scroll bar
|
||||
|
||||
`H` is height in pixels, adjust it to get rid of vertical scroll bar.
|
||||
It can also be set to 0 to produce one very tall image and use
|
||||
client scroll. This 0 size is experimental, buggy and should be
|
||||
used with PNG and lots of memory on a client side.
|
||||
|
||||
`Z` Zoom or scale
|
||||
|
||||
`M` Mode - ISMAP (clickable imagemap) or simple HTML mode
|
||||
|
||||
`T` Image type PNG / GIF / JPEG
|
||||
|
||||
`C` Colors, for GIF images only
|
||||
|
||||
`K` Keystroke input, you can type some letters in it and when you click Go it will be typed in the remote browser.
|
||||
|
||||
`Bs` Backspace
|
||||
|
||||
`Rt` Return / enter
|
||||
|
||||
### UI Customization
|
||||
|
||||
WRP supports customizing it's own UI using HTML Template file. Download [wrp.html](wrp.html) place in the same directory with wrp binary customize it to your liking.
|
||||
|
||||
## Docker
|
||||
|
||||
https://hub.docker.com/r/tenox7/wrp
|
||||
|
||||
```shell
|
||||
$ docker run -d --rm -p 8080:8080 tenox7/wrp:latest
|
||||
```
|
||||
|
||||
## AWS
|
||||
|
||||
It's possible to run WRP on AWS App Runner.
|
||||
|
||||
First you need to upload the Docker image to ECR - [Instructions](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html).
|
||||
|
||||
Create App Runner service using the uploaded image using the AWS Console or CLI.
|
||||
|
||||
[AWS Console](https://console.aws.amazon.com/apprunner/home#/create)
|
||||
|
||||
```shell
|
||||
aws apprunner create-service --service-name my-app-runner-service --source-configuration '{
|
||||
"ImageRepository": {
|
||||
"ImageIdentifier": "<account_id>.dkr.ecr.<region>.amazonaws.com/wrp:latest",
|
||||
"ImageRepositoryType": "ECR",
|
||||
"ImageConfiguration": {"Port": "8000"},
|
||||
"AutoDeploymentsEnabled": true
|
||||
}
|
||||
}' --instance-configuration '{
|
||||
"Cpu": "1024",
|
||||
"Memory": "2048",
|
||||
"InstanceRoleArn": "arn:aws:iam::<account_id>:role/AppRunnerECRAccessRole"
|
||||
}'
|
||||
```
|
||||
|
||||
## Azure Container Instances
|
||||
|
||||
[Azure Console](https://portal.azure.com/#create/Microsoft.ContainerInstances)
|
||||
|
||||
CLI:
|
||||
|
||||
```shell
|
||||
$ az container create --resource-group wrp --name wrp --image tenox7/wrp:latest --cpu 1 --memory 2 --ports 80 --protocol tcp --os-type Linux --ip-address Public --command-line '/wrp -l :80 -t png -g 1280x0x256'
|
||||
```
|
||||
|
||||
## Google Cloud Run
|
||||
|
||||
```shell
|
||||
$ gcloud run deploy --platform managed --image=tenox7/wrp:latest --memory=2Gi --args='-t=png','-g=1280x0x256'
|
||||
```
|
||||
|
||||
Unfortunately Google Cloud Run forces you to use HTTPS, which likely won't work with old browsers.
|
||||
|
||||
|
||||
## Flags
|
||||
|
||||
```text
|
||||
-l listen address:port (default :8080)
|
||||
-m mode, either ismap (graphical) or html
|
||||
-t image type gif, png or jpg (default gif)
|
||||
-g image geometry, WxHxC, height can be 0 for unlimited (default 1152x600x216)
|
||||
C (number of colors) is only used for GIF
|
||||
-q Jpeg image quality, default 75%
|
||||
-h headless mode, hide browser window on the server (default true)
|
||||
-d chromedp debug logging (default false)
|
||||
-n do not free maps and images after use (default false)
|
||||
-ui html template file (default "wrp.html")
|
||||
-ua user agent, override the default "headless" agent (only for ismap mode)
|
||||
-s delay/sleep after page is rendered before screenshot is taken (default 2s)
|
||||
```
|
||||
-l listen address:port, default :8080
|
||||
-h headed mode, display browser window
|
||||
-d chromedp debug logging
|
||||
|
||||
## Minimal Requirements
|
||||
|
||||
* Server/Gateway requires modern hardware and operating system that is supported by [Go language](https://github.com/golang/go/wiki/MinimumRequirements) and Chrome/Chromium Browser, which must be installed.
|
||||
* Client Browser needs to support `HTML FORMs` and `ISMAP`. Typically [Mosaic 2.0](http://www.ncsa.illinois.edu/enabling/mosaic/versions) would be minimum version for forms. However ISMAP was supported since 0.6B, so if you manually enter url using `?url=...`, you can use the earlier version.
|
||||
|
||||
## FAQ
|
||||
|
||||
### I can't get it to run
|
||||
|
||||
This program does not have a GUI and is run from the command line. After downloading, you may need to enable executable bit on Unix systems, for example:
|
||||
|
||||
```shell
|
||||
$ cd ~/Downloads
|
||||
$ chmod +x wrp-amd64-macos
|
||||
$ ./wrp-amd64-macos
|
||||
```
|
||||
|
||||
### Websites are blocking headless browsers
|
||||
|
||||
This is a well known issue. WRP has some provisions to work around it, but it's a cat and mouse game. The first and foremost recommendation is to change the `User Agent`, so that it doesn't say "headless". Add `-ua="my agent"` to override the default one. Obtain your regular desktop browser user agent and specify it as the flag. For example:
|
||||
|
||||
```shell
|
||||
$ wrp -ua="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
|
||||
```
|
||||
|
||||
### Why is WRP called "proxy" when it's not
|
||||
|
||||
WRP originally started as true http proxy. However this stopped working because the whole internet is now encrypted thanks to [Let's Encrypt](https://en.wikipedia.org/wiki/Let%27s_Encrypt). Legacy browsers do not support modern SSL/TLS certs as well as [HTTP CONNECT](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_method) so this mode had to be disabled.
|
||||
|
||||
### Will you support http proxy mode in future?
|
||||
|
||||
Some efforts (ssl strip) are under way but it's very [difficult](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_method) to do it correctly and the priority is rather low.
|
||||
|
||||
### Why isn't there a Docker image for armv6
|
||||
|
||||
Because https://hub.docker.com/r/chromedp/headless-shell/ doesn't have one. WRP uses that image. If you have a fork that builds for armv6 let me know.
|
||||
|
||||
## History
|
||||
* In 2014, version 1.0 started as a cgi-bin script, adaptation of `webkit2png.py` and `pcidade.py`, [blog post](https://virtuallyfun.com/2014/03/03/surfing-modern-web-with-ancient-browsers/).
|
||||
* Later in 2014, version 2.0 became a stand alone http-proxy server, also support for both Linux/MacOS, [another post](https://virtuallyfun.com/wordpress/2014/03/11/web-rendering-proxy-update//).
|
||||
* In 2016 the whole internet migrated to HTTPS/SSL/TLS and WRP largely stopped working. Python code became unmaintainable and mostly unportable (especially to Windows, even WSL).
|
||||
* In 2019 WRP 3.0 has been rewritten in Golang/Chromedp as browser-in-browser instead of http proxy.
|
||||
* Later in 2019, WRP 4.0 has been completely refactored to use mouse clicks instead using a href nodes. Also in 4.1 added sending keystrokes in to input boxes. You can now login to Gmail.
|
||||
|
||||
## Credits
|
||||
* Version 1.0 (2014) started as a *cgi-bin* script, adaptation of `webkit2png.py` and `pcidade.py`, [blog post](https://virtuallyfun.com/2014/03/03/surfing-modern-web-with-ancient-browsers/).
|
||||
* Version 2.0 became a stand alone http-proxy server, supporting both Linux and MacOS, [another post](https://virtuallyfun.com/wordpress/2014/03/11/web-rendering-proxy-update//).
|
||||
* In 2016 thanks to [Let's Encrypt](https://en.wikipedia.org/wiki/Let%27s_Encrypt) the whole internet migrated to HTTPS/SSL/TLS and WRP largely stopped working. Python code became unmaintainable and there was no easy way to make it work on Windows, even under WSL.
|
||||
* Version 3.0 (2019) has been rewritten in [Go](https://golang.org/) using [Chromedp](https://github.com/chromedp) as browser-in-browser instead of http-proxy. The initial version was [less than 100 lines of code](https://gist.github.com/tenox7/b0f03c039b0a8b67f6c1bf47e2dd0df0).
|
||||
* Version 4.0 has been completely refactored to use mouse clicks via imagemap instead parsing a href nodes.
|
||||
* Version 4.1 added sending keystrokes in to input boxes. You can now login to Gmail. Also now runs as a Docker container and on Cloud Run/Azure Containers.
|
||||
* Version 4.5 introduces rendering whole pages in to a single tall image with client scrolling.
|
||||
* Version 4.6 adds blazing fast gif encoding by [Hill Ma](https://github.com/mahiuchun).
|
||||
* Version 4.6.3 adds arm64 / aarch64 Docker container support - you can run it on Raspberry PI!
|
||||
* Version 4.7 add simple html aka reader aka text mode.
|
||||
* Version 4.8 add image support to simple html mode.
|
||||
|
||||
## Credits
|
||||
|
||||
* Uses [chromedp](https://github.com/chromedp), thanks to [mvdan](https://github.com/mvdan) for dealing with my issues
|
||||
* Uses [go-quantize](https://github.com/ericpauley/go-quantize), thanks to [ericpauley](https://github.com/ericpauley) for developing the missing go quantizer
|
||||
* Thanks to Jason Stevens of [Fun With Virtualization](https://virtuallyfun.com/) for graciously hosting my rumblings
|
||||
* Thanks to [claunia](https://github.com/claunia/) for help with the Python/Webkit version in the past
|
||||
* Thanks to [Hill Ma](https://github.com/mahiuchun) for ultra fast gif encoding algorithm
|
||||
* Historical Python/Webkit versions and prior art can be seen in [wrp-old](https://github.com/tenox7/wrp-old) repo
|
||||
|
||||
## Related
|
||||
|
||||
You may also be interested in:
|
||||
|
||||
* [VncFox](https://github.com/tenox7/vncfox)
|
||||
* [Browservice](https://github.com/ttalvitie/browservice)
|
||||
* [Browsh](https://github.com/browsh-org/browsh)
|
||||
|
||||
## Legal Stuff
|
||||
License: Apache 2.0
|
||||
Copyright (c) 2013-2018 Antoni Sawicki
|
||||
Copyright (c) 2019 Google LLC
|
||||
|
||||
```text
|
||||
License: Apache 2.0
|
||||
Copyright (c) 2013-2025 Antoni Sawicki
|
||||
```
|
||||
|
33
go.mod
Normal file
33
go.mod
Normal file
@ -0,0 +1,33 @@
|
||||
module github.com/tenox7/wrp
|
||||
|
||||
go 1.23
|
||||
|
||||
toolchain go1.24.0
|
||||
|
||||
require (
|
||||
github.com/JohannesKaufmann/html-to-markdown v1.6.0
|
||||
github.com/MaxHalford/halfgone v0.0.0-20171017091812-482157b86ccb
|
||||
github.com/breml/rootcerts v0.2.20
|
||||
github.com/chromedp/cdproto v0.0.0-20250210231439-aea867ea8506
|
||||
github.com/chromedp/chromedp v0.12.1
|
||||
github.com/lithammer/shortuuid/v4 v4.2.0
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
|
||||
github.com/soniakeys/quant v1.0.0
|
||||
github.com/yuin/goldmark v1.7.8
|
||||
golang.org/x/image v0.24.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/PuerkitoBio/goquery v1.10.2 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
github.com/chromedp/sysutil v1.1.0 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
github.com/gobwas/ws v1.4.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/mailru/easyjson v0.9.0 // indirect
|
||||
golang.org/x/net v0.35.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
)
|
171
go.sum
Normal file
171
go.sum
Normal file
@ -0,0 +1,171 @@
|
||||
github.com/JohannesKaufmann/html-to-markdown v1.6.0 h1:04VXMiE50YYfCfLboJCLcgqF5x+rHJnb1ssNmqpLH/k=
|
||||
github.com/JohannesKaufmann/html-to-markdown v1.6.0/go.mod h1:NUI78lGg/a7vpEJTz/0uOcYMaibytE4BUOQS8k78yPQ=
|
||||
github.com/MaxHalford/halfgone v0.0.0-20171017091812-482157b86ccb h1:YQ+d0g0P0F/06oDoeEgDHeZCIrnKgLxXcqYOpe8sTuU=
|
||||
github.com/MaxHalford/halfgone v0.0.0-20171017091812-482157b86ccb/go.mod h1:J86XzS1wgzJPjpQmpriJ+SetP17JSQUd9l+HWQK86jA=
|
||||
github.com/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4yPeE=
|
||||
github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
|
||||
github.com/PuerkitoBio/goquery v1.10.2 h1:7fh2BdHcG6VFZsK7toXBT/Bh1z5Wmy8Q9MV9HqT2AM8=
|
||||
github.com/PuerkitoBio/goquery v1.10.2/go.mod h1:0guWGjcLu9AYC7C1GHnpysHy056u9aEkUHwhdnePMCU=
|
||||
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
|
||||
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
|
||||
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
|
||||
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
|
||||
github.com/breml/rootcerts v0.2.17 h1:0/M2BE2Apw0qEJCXDOkaiu7d5Sx5ObNfe1BkImJ4u1I=
|
||||
github.com/breml/rootcerts v0.2.17/go.mod h1:S/PKh+4d1HUn4HQovEB8hPJZO6pUZYrIhmXBhsegfXw=
|
||||
github.com/breml/rootcerts v0.2.20 h1:koth1lShwiiDp3VOX6/4qKEZ87S7HgDKsnDr47XEIq0=
|
||||
github.com/breml/rootcerts v0.2.20/go.mod h1:S/PKh+4d1HUn4HQovEB8hPJZO6pUZYrIhmXBhsegfXw=
|
||||
github.com/chromedp/cdproto v0.0.0-20240801214329-3f85d328b335/go.mod h1:GKljq0VrfU4D5yc+2qA6OVr8pmO/MBbPEWqWQ/oqGEs=
|
||||
github.com/chromedp/cdproto v0.0.0-20240810084448-b931b754e476 h1:VnjHsRXCRti7Av7E+j4DCha3kf68echfDzQ+wD11SBU=
|
||||
github.com/chromedp/cdproto v0.0.0-20240810084448-b931b754e476/go.mod h1:GKljq0VrfU4D5yc+2qA6OVr8pmO/MBbPEWqWQ/oqGEs=
|
||||
github.com/chromedp/cdproto v0.0.0-20250210231439-aea867ea8506 h1:OfjMcN8R6eUWZfKyJaTnlyiZh1BGgmEKmRkCZuDtGRw=
|
||||
github.com/chromedp/cdproto v0.0.0-20250210231439-aea867ea8506/go.mod h1:RTGuBeCeabAJGi3OZf71a6cGa7oYBfBP75VJZFLv6SU=
|
||||
github.com/chromedp/chromedp v0.10.0 h1:bRclRYVpMm/UVD76+1HcRW9eV3l58rFfy7AdBvKab1E=
|
||||
github.com/chromedp/chromedp v0.10.0/go.mod h1:ei/1ncZIqXX1YnAYDkxhD4gzBgavMEUu7JCKvztdomE=
|
||||
github.com/chromedp/chromedp v0.12.1 h1:kBMblXk7xH5/6j3K9uk8d7/c+fzXWiUsCsPte0VMwOA=
|
||||
github.com/chromedp/chromedp v0.12.1/go.mod h1:F6+wdq9LKFDMoyxhq46ZLz4VLXrsrCAR3sFqJz4Nqc0=
|
||||
github.com/chromedp/sysutil v1.0.0 h1:+ZxhTpfpZlmchB58ih/LBHX52ky7w2VhQVKQMucy3Ic=
|
||||
github.com/chromedp/sysutil v1.0.0/go.mod h1:kgWmDdq8fTzXYcKIBqIYvRRTnYb9aNS9moAV0xufSww=
|
||||
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
|
||||
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
|
||||
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
|
||||
github.com/lithammer/shortuuid/v4 v4.0.0 h1:QRbbVkfgNippHOS8PXDkti4NaWeyYfcBTHtw7k08o4c=
|
||||
github.com/lithammer/shortuuid/v4 v4.0.0/go.mod h1:Zs8puNcrvf2rV9rTH51ZLLcj7ZXqQI3lv67aw4KiB1Y=
|
||||
github.com/lithammer/shortuuid/v4 v4.2.0 h1:LMFOzVB3996a7b8aBuEXxqOBflbfPQAiVzkIcHO0h8c=
|
||||
github.com/lithammer/shortuuid/v4 v4.2.0/go.mod h1:D5noHZ2oFw/YaKCfGy0YxyE7M0wMbezmMjPdhyEFe6Y=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
|
||||
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sebdah/goldie/v2 v2.5.3 h1:9ES/mNN+HNUbNWpVAlrzuZ7jE+Nrczbj8uFRjM7624Y=
|
||||
github.com/sebdah/goldie/v2 v2.5.3/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
|
||||
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
|
||||
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
|
||||
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
|
||||
github.com/soniakeys/quant v1.0.0 h1:N1um9ktjbkZVcywBVAAYpZYSHxEfJGzshHCxx/DaI0Y=
|
||||
github.com/soniakeys/quant v1.0.0/go.mod h1:HI1k023QuVbD4H8i9YdfZP2munIHU4QpjsImz6Y6zds=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
|
||||
github.com/yuin/goldmark v1.7.4 h1:BDXOHExt+A7gwPCJgPIIq7ENvceR7we7rOS9TNoLZeg=
|
||||
github.com/yuin/goldmark v1.7.4/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
|
||||
github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic=
|
||||
github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/image v0.19.0 h1:D9FX4QWkLfkeqaC62SonffIIuYdOk/UE2XKUBgRIBIQ=
|
||||
golang.org/x/image v0.19.0/go.mod h1:y0zrRqlQRWQ5PXaYCOMLTW2fpsxZ8Qh9I/ohnInJEys=
|
||||
golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ=
|
||||
golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
|
||||
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
||||
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
|
||||
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
|
||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
293
ismap.go
Normal file
293
ismap.go
Normal file
@ -0,0 +1,293 @@
|
||||
// WRP ISMAP / ChromeDP routines
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/gif"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/chromedp/cdproto/css"
|
||||
"github.com/chromedp/cdproto/emulation"
|
||||
"github.com/chromedp/cdproto/input"
|
||||
"github.com/chromedp/cdproto/page"
|
||||
"github.com/chromedp/chromedp"
|
||||
"github.com/lithammer/shortuuid/v4"
|
||||
)
|
||||
|
||||
func chromedpStart() (context.CancelFunc, context.CancelFunc) {
|
||||
opts := append(chromedp.DefaultExecAllocatorOptions[:],
|
||||
chromedp.Flag("headless", *headless),
|
||||
chromedp.Flag("hide-scrollbars", false),
|
||||
chromedp.Flag("enable-automation", false),
|
||||
chromedp.Flag("disable-blink-features", "AutomationControlled"),
|
||||
)
|
||||
if *userAgent != "" {
|
||||
opts = append(opts, chromedp.UserAgent(*userAgent))
|
||||
}
|
||||
actx, acncl = chromedp.NewExecAllocator(context.Background(), opts...)
|
||||
ctx, cncl = chromedp.NewContext(actx)
|
||||
return cncl, acncl
|
||||
}
|
||||
|
||||
// Determine what action to take
|
||||
func (rq *wrpReq) action() chromedp.Action {
|
||||
// Mouse Click
|
||||
if rq.mouseX > 0 && rq.mouseY > 0 {
|
||||
log.Printf("%s Mouse Click %d,%d\n", rq.r.RemoteAddr, rq.mouseX, rq.mouseY)
|
||||
return chromedp.MouseClickXY(float64(rq.mouseX)/float64(rq.zoom), float64(rq.mouseY)/float64(rq.zoom))
|
||||
}
|
||||
// Buttons
|
||||
if len(rq.buttons) > 0 {
|
||||
log.Printf("%s Button %v\n", rq.r.RemoteAddr, rq.buttons)
|
||||
switch rq.buttons {
|
||||
case "Bk":
|
||||
return chromedp.NavigateBack()
|
||||
case "St":
|
||||
return chromedp.Stop()
|
||||
case "Re":
|
||||
return chromedp.Reload()
|
||||
case "Bs":
|
||||
return chromedp.KeyEvent("\b")
|
||||
case "Rt":
|
||||
return chromedp.KeyEvent("\r")
|
||||
case "<":
|
||||
return chromedp.KeyEvent("\u0302")
|
||||
case "^":
|
||||
return chromedp.KeyEvent("\u0304")
|
||||
case "v":
|
||||
return chromedp.KeyEvent("\u0301")
|
||||
case ">":
|
||||
return chromedp.KeyEvent("\u0303")
|
||||
case "Up":
|
||||
return chromedp.KeyEvent("\u0308")
|
||||
case "Dn":
|
||||
return chromedp.KeyEvent("\u0307")
|
||||
case "All": // Select all
|
||||
return chromedp.KeyEvent("a", chromedp.KeyModifiers(input.ModifierCtrl))
|
||||
}
|
||||
}
|
||||
// Keys
|
||||
if len(rq.keys) > 0 {
|
||||
log.Printf("%s Sending Keys: %#v\n", rq.r.RemoteAddr, rq.keys)
|
||||
return chromedp.KeyEvent(rq.keys)
|
||||
}
|
||||
// Navigate to URL
|
||||
log.Printf("%s Processing Navigate Request for %s\n", rq.r.RemoteAddr, rq.url)
|
||||
return chromedp.Navigate(rq.url)
|
||||
}
|
||||
|
||||
// Navigate to the desired URL.
|
||||
func (rq *wrpReq) navigate() {
|
||||
ctxErr(chromedp.Run(ctx, rq.action()), rq.w)
|
||||
}
|
||||
|
||||
// Handle context errors
|
||||
func ctxErr(err error, w io.Writer) {
|
||||
// TODO: callers should have retry logic, perhaps create another function
|
||||
// that takes ...chromedp.Action and retries with give up
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
log.Printf("Context error: %s", err)
|
||||
fmt.Fprintf(w, "Context error: %s<BR>\n", err)
|
||||
if err.Error() != "context canceled" {
|
||||
return
|
||||
}
|
||||
ctx, cncl = chromedp.NewContext(actx)
|
||||
log.Printf("Created new context, try again")
|
||||
fmt.Fprintln(w, "Created new context, try again")
|
||||
}
|
||||
|
||||
// https://github.com/chromedp/chromedp/issues/979
|
||||
func chromedpCaptureScreenshot(res *[]byte, h int64) chromedp.Action {
|
||||
if res == nil {
|
||||
panic("res cannot be nil") // TODO: do not panic here, return error
|
||||
}
|
||||
if h == 0 {
|
||||
return chromedp.CaptureScreenshot(res)
|
||||
}
|
||||
|
||||
return chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
var err error
|
||||
*res, err = page.CaptureScreenshot().Do(ctx)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// Capture Screenshot using CDP
|
||||
func (rq *wrpReq) captureScreenshot() {
|
||||
var styles []*css.ComputedStyleProperty
|
||||
var r, g, b int
|
||||
var bgColorSet bool
|
||||
var h int64
|
||||
var pngCap []byte
|
||||
chromedp.Run(ctx,
|
||||
emulation.SetDeviceMetricsOverride(int64(float64(rq.width)/rq.zoom), 10, rq.zoom, false),
|
||||
chromedp.Location(&rq.url),
|
||||
chromedp.ComputedStyle("body", &styles, chromedp.ByQuery),
|
||||
chromedp.ActionFunc(func(ctx context.Context) error {
|
||||
_, _, _, _, _, s, err := page.GetLayoutMetrics().Do(ctx)
|
||||
if err == nil {
|
||||
h = int64(math.Ceil(s.Height))
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
log.Printf("%s Landed on: %s, Height: %v\n", rq.r.RemoteAddr, rq.url, h)
|
||||
for _, style := range styles {
|
||||
if style.Name != "background-color" {
|
||||
continue
|
||||
}
|
||||
fmt.Sscanf(style.Value, "rgb(%d,%d,%d)", &r, &g, &b)
|
||||
bgColorSet = true
|
||||
break
|
||||
}
|
||||
if !bgColorSet {
|
||||
r = 255
|
||||
g = 255
|
||||
b = 255
|
||||
}
|
||||
height := int64(float64(rq.height) / rq.zoom)
|
||||
if rq.height == 0 && h > 0 {
|
||||
height = h + 30
|
||||
}
|
||||
chromedp.Run(
|
||||
ctx, emulation.SetDeviceMetricsOverride(int64(float64(rq.width)/rq.zoom), height, rq.zoom, false),
|
||||
chromedp.Sleep(*delay), // TODO(tenox): find a better way to determine if page is rendered
|
||||
)
|
||||
// Capture screenshot...
|
||||
ctxErr(chromedp.Run(ctx, chromedpCaptureScreenshot(&pngCap, rq.height)), rq.w)
|
||||
seq := shortuuid.New()
|
||||
imgPath := fmt.Sprintf("/img/%s.%s", seq, rq.imgType)
|
||||
mapPath := fmt.Sprintf("/map/%s.map", seq)
|
||||
ismap[mapPath] = *rq
|
||||
var sSize string
|
||||
var iW, iH int
|
||||
switch rq.imgType {
|
||||
case "png":
|
||||
pngBuf := bytes.NewBuffer(pngCap)
|
||||
img[imgPath] = *pngBuf
|
||||
cfg, _, _ := image.DecodeConfig(pngBuf)
|
||||
sSize = fmt.Sprintf("%.0f KB", float32(len(pngBuf.Bytes()))/1024.0)
|
||||
iW = cfg.Width
|
||||
iH = cfg.Height
|
||||
log.Printf("%s Got PNG image: %s, Size: %s, Res: %dx%d\n", rq.r.RemoteAddr, imgPath, sSize, iW, iH)
|
||||
case "gif":
|
||||
i, err := png.Decode(bytes.NewReader(pngCap))
|
||||
if err != nil {
|
||||
log.Printf("%s Failed to decode PNG screenshot: %s\n", rq.r.RemoteAddr, err)
|
||||
fmt.Fprintf(rq.w, "<BR>Unable to decode page PNG screenshot:<BR>%s<BR>\n", err)
|
||||
return
|
||||
}
|
||||
st := time.Now()
|
||||
var gifBuf bytes.Buffer
|
||||
err = gif.Encode(&gifBuf, gifPalette(i, rq.nColors), &gif.Options{})
|
||||
if err != nil {
|
||||
log.Printf("%s Failed to encode GIF: %s\n", rq.r.RemoteAddr, err)
|
||||
fmt.Fprintf(rq.w, "<BR>Unable to encode GIF:<BR>%s<BR>\n", err)
|
||||
return
|
||||
}
|
||||
img[imgPath] = gifBuf
|
||||
sSize = fmt.Sprintf("%.0f KB", float32(len(gifBuf.Bytes()))/1024.0)
|
||||
iW = i.Bounds().Max.X
|
||||
iH = i.Bounds().Max.Y
|
||||
log.Printf("%s Encoded GIF image: %s, Size: %s, Colors: %d, Res: %dx%d, Time: %vms\n", rq.r.RemoteAddr, imgPath, sSize, rq.nColors, iW, iH, time.Since(st).Milliseconds())
|
||||
case "jpg":
|
||||
i, err := png.Decode(bytes.NewReader(pngCap))
|
||||
if err != nil {
|
||||
log.Printf("%s Failed to decode PNG screenshot: %s\n", rq.r.RemoteAddr, err)
|
||||
fmt.Fprintf(rq.w, "<BR>Unable to decode page PNG screenshot:<BR>%s<BR>\n", err)
|
||||
return
|
||||
}
|
||||
st := time.Now()
|
||||
var jpgBuf bytes.Buffer
|
||||
err = jpeg.Encode(&jpgBuf, i, &jpeg.Options{Quality: int(rq.jQual)})
|
||||
if err != nil {
|
||||
log.Printf("%s Failed to encode JPG: %s\n", rq.r.RemoteAddr, err)
|
||||
fmt.Fprintf(rq.w, "<BR>Unable to encode JPG:<BR>%s<BR>\n", err)
|
||||
return
|
||||
}
|
||||
img[imgPath] = jpgBuf
|
||||
sSize = fmt.Sprintf("%.0f KB", float32(len(jpgBuf.Bytes()))/1024.0)
|
||||
iW = i.Bounds().Max.X
|
||||
iH = i.Bounds().Max.Y
|
||||
log.Printf("%s Encoded JPG image: %s, Size: %s, Quality: %d, Res: %dx%d, Time: %vms\n", rq.r.RemoteAddr, imgPath, sSize, *defJpgQual, iW, iH, time.Since(st).Milliseconds())
|
||||
}
|
||||
rq.printUI(uiParams{
|
||||
bgColor: fmt.Sprintf("#%02X%02X%02X", r, g, b),
|
||||
pageHeight: fmt.Sprintf("%d PX", h),
|
||||
imgSize: sSize,
|
||||
imgURL: imgPath,
|
||||
mapURL: mapPath,
|
||||
imgWidth: iW,
|
||||
imgHeight: iH,
|
||||
})
|
||||
log.Printf("%s Done with capture for %s\n", rq.r.RemoteAddr, rq.url)
|
||||
}
|
||||
|
||||
func mapServer(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("%s ISMAP Request for %s [%+v]\n", r.RemoteAddr, r.URL.Path, r.URL.RawQuery)
|
||||
rq, ok := ismap[r.URL.Path]
|
||||
rq.r = r
|
||||
rq.w = w
|
||||
if !ok {
|
||||
fmt.Fprintf(w, "Unable to find map %s\n", r.URL.Path)
|
||||
log.Printf("Unable to find map %s\n", r.URL.Path)
|
||||
return
|
||||
}
|
||||
if !*noDel {
|
||||
defer delete(ismap, r.URL.Path)
|
||||
}
|
||||
n, err := fmt.Sscanf(r.URL.RawQuery, "%d,%d", &rq.mouseX, &rq.mouseY)
|
||||
if err != nil || n != 2 {
|
||||
fmt.Fprintf(w, "n=%d, err=%s\n", n, err)
|
||||
log.Printf("%s ISMAP n=%d, err=%s\n", r.RemoteAddr, n, err)
|
||||
return
|
||||
}
|
||||
log.Printf("%s WrpReq from ISMAP: %+v\n", r.RemoteAddr, rq)
|
||||
if len(rq.url) < 4 {
|
||||
rq.printUI(uiParams{bgColor: "#FFFFFF"})
|
||||
return
|
||||
}
|
||||
rq.navigate() // TODO: if error from navigate do not capture
|
||||
rq.captureScreenshot()
|
||||
}
|
||||
|
||||
// TODO: merge this with html mode IMGZ
|
||||
func imgServerMap(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("%s IMG Request for %s\n", r.RemoteAddr, r.URL.Path)
|
||||
imgBuf, ok := img[r.URL.Path]
|
||||
if !ok || imgBuf.Bytes() == nil {
|
||||
fmt.Fprintf(w, "Unable to find image %s\n", r.URL.Path)
|
||||
log.Printf("%s Unable to find image %s\n", r.RemoteAddr, r.URL.Path)
|
||||
return
|
||||
}
|
||||
if !*noDel {
|
||||
defer delete(img, r.URL.Path)
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, ".gif"):
|
||||
w.Header().Set("Content-Type", "image/gif")
|
||||
case strings.HasSuffix(r.URL.Path, ".png"):
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
case strings.HasSuffix(r.URL.Path, ".jpg"):
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
}
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(imgBuf.Bytes())))
|
||||
w.Header().Set("Cache-Control", "max-age=0")
|
||||
w.Header().Set("Expires", "-1")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
w.Write(imgBuf.Bytes())
|
||||
w.(http.Flusher).Flush()
|
||||
}
|
20
make.ps1
20
make.ps1
@ -1,20 +0,0 @@
|
||||
param (
|
||||
[switch]$clean = $false
|
||||
)
|
||||
$env:GOARCH="amd64"
|
||||
foreach($os in ("linux", "freebsd", "openbsd", "darwin", "windows")) {
|
||||
$env:GOOS=$os
|
||||
$o="wrp-$(if ($os -eq "windows") {$os="windows.exe"})$os"
|
||||
Remove-Item -ErrorAction Ignore $o
|
||||
if (!$clean) {
|
||||
Invoke-Expression "& go build -a -o $o wrp.go"
|
||||
}
|
||||
}
|
||||
|
||||
$env:GOARCH="arm"
|
||||
$env:GOOS="linux"
|
||||
$o="wrp-linux-rpi"
|
||||
Remove-Item -ErrorAction Ignore $o
|
||||
if (!$clean) {
|
||||
Invoke-Expression "& go build -a -o $o wrp.go"
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
Historical versions of WRP and prior art
|
||||
|
||||
License: GNU
|
||||
|
||||
Copyright (c) 2013-2018 Antoni Sawicki
|
||||
Copyright (c) 2012-2013 picidae.net
|
||||
Copyright (c) 2004-2013 Paul Hammond
|
||||
Copyright (c) 2017-2018 Natalia Portillo
|
||||
Copyright (c) 2018 //gir.st/
|
392
old/picidae.py
392
old/picidae.py
@ -1,392 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# picidae.py - makes screenshots of webpages
|
||||
# and analyzes the webpage structure and writes image-maps of the links
|
||||
# as well as forms that are placed on the exact position of the old form.
|
||||
# It is a part of the art project www.picidae.net
|
||||
# http://www.picidae.net
|
||||
|
||||
#
|
||||
# This script is based on webkit2png from Paul Hammond.
|
||||
# It was extended by picidae.net
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
|
||||
|
||||
|
||||
__version__ = "1.0"
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
|
||||
#print "hello ... "
|
||||
|
||||
|
||||
try:
|
||||
import Foundation
|
||||
import WebKit
|
||||
import AppKit
|
||||
import objc
|
||||
import urllib
|
||||
except ImportError:
|
||||
print "Cannot find pyobjc library files. Are you sure it is installed?"
|
||||
sys.exit()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#try:
|
||||
# from optparse import OptionParser
|
||||
#except ImportError:
|
||||
# print "OptionParser not imported"
|
||||
# sys.exit()
|
||||
|
||||
from optparse import OptionParser
|
||||
|
||||
|
||||
class AppDelegate (Foundation.NSObject):
|
||||
# what happens when the app starts up
|
||||
def applicationDidFinishLaunching_(self, aNotification):
|
||||
webview = aNotification.object().windows()[0].contentView()
|
||||
webview.frameLoadDelegate().getURL(webview)
|
||||
|
||||
|
||||
class WebkitLoad (Foundation.NSObject, WebKit.protocols.WebFrameLoadDelegate):
|
||||
# what happens if something goes wrong while loading
|
||||
def webView_didFailLoadWithError_forFrame_(self,webview,error,frame):
|
||||
print " ... something went wrong 1"
|
||||
self.getURL(webview)
|
||||
def webView_didFailProvisionalLoadWithError_forFrame_(self,webview,error,frame):
|
||||
print " ... something went wrong 2"
|
||||
self.getURL(webview)
|
||||
|
||||
def makeFilename(self,URL,options):
|
||||
# make the filename
|
||||
if options.filename:
|
||||
filename = options.filename
|
||||
elif options.md5:
|
||||
try:
|
||||
import md5
|
||||
except ImportError:
|
||||
print "--md5 requires python md5 library"
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
filename = md5.new(URL).hexdigest()
|
||||
else:
|
||||
import re
|
||||
filename = re.sub('\W','',URL);
|
||||
filename = re.sub('^http','',filename);
|
||||
if options.datestamp:
|
||||
import time
|
||||
now = time.strftime("%Y%m%d")
|
||||
filename = now + "-" + filename
|
||||
import os
|
||||
dir = os.path.abspath(os.path.expanduser(options.dir))
|
||||
return os.path.join(dir,filename)
|
||||
|
||||
def saveImages(self,bitmapdata,filename,options):
|
||||
# save the fullsize png
|
||||
if options.fullsize:
|
||||
bitmapdata.representationUsingType_properties_(AppKit.NSPNGFileType,None).writeToFile_atomically_(filename + ".png",objc.YES)
|
||||
|
||||
if options.thumb or options.clipped:
|
||||
# work out how big the thumbnail is
|
||||
width = bitmapdata.pixelsWide()
|
||||
height = bitmapdata.pixelsHigh()
|
||||
thumbWidth = (width * options.scale)
|
||||
thumbHeight = (height * options.scale)
|
||||
|
||||
# make the thumbnails in a scratch image
|
||||
scratch = AppKit.NSImage.alloc().initWithSize_(
|
||||
Foundation.NSMakeSize(thumbWidth,thumbHeight))
|
||||
scratch.lockFocus()
|
||||
AppKit.NSGraphicsContext.currentContext().setImageInterpolation_(
|
||||
AppKit.NSImageInterpolationHigh)
|
||||
thumbRect = Foundation.NSMakeRect(0.0, 0.0, thumbWidth, thumbHeight)
|
||||
clipRect = Foundation.NSMakeRect(0.0,
|
||||
thumbHeight-options.clipheight,
|
||||
options.clipwidth, options.clipheight)
|
||||
bitmapdata.drawInRect_(thumbRect)
|
||||
thumbOutput = AppKit.NSBitmapImageRep.alloc().initWithFocusedViewRect_(thumbRect)
|
||||
clipOutput = AppKit.NSBitmapImageRep.alloc().initWithFocusedViewRect_(clipRect)
|
||||
scratch.unlockFocus()
|
||||
|
||||
# save the thumbnails as pngs
|
||||
if options.thumb:
|
||||
thumbOutput.representationUsingType_properties_(
|
||||
AppKit.NSPNGFileType,None
|
||||
).writeToFile_atomically_(filename + "-thumb.png",objc.YES)
|
||||
if options.clipped:
|
||||
clipOutput.representationUsingType_properties_(
|
||||
AppKit.NSPNGFileType,None
|
||||
).writeToFile_atomically_(filename + "-clipped.png",objc.YES)
|
||||
|
||||
def getURL(self,webview):
|
||||
if self.urls:
|
||||
if self.urls[0] == '-':
|
||||
url = sys.stdin.readline().rstrip()
|
||||
if not url: AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
else:
|
||||
url = self.urls.pop(0)
|
||||
else:
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
#print "<urlcall href=\"\" />", url, "..."
|
||||
#print "<urlcall href=\"%s\" />" % (url)
|
||||
self.resetWebview(webview)
|
||||
webview.mainFrame().loadRequest_(Foundation.NSURLRequest.requestWithURL_(Foundation.NSURL.URLWithString_(url)))
|
||||
if not webview.mainFrame().provisionalDataSource():
|
||||
print "<nosuccess />"
|
||||
self.getURL(webview)
|
||||
|
||||
def resetWebview(self,webview):
|
||||
rect = Foundation.NSMakeRect(0,0,self.options.initWidth,self.options.initHeight)
|
||||
webview.window().setContentSize_((self.options.initWidth,self.options.initHeight))
|
||||
webview.setFrame_(rect)
|
||||
|
||||
def resizeWebview(self,view):
|
||||
view.window().display()
|
||||
view.window().setContentSize_(view.bounds().size)
|
||||
view.setFrame_(view.bounds())
|
||||
|
||||
def captureView(self,view):
|
||||
view.lockFocus()
|
||||
bitmapdata = AppKit.NSBitmapImageRep.alloc()
|
||||
bitmapdata.initWithFocusedViewRect_(view.bounds())
|
||||
view.unlockFocus()
|
||||
return bitmapdata
|
||||
|
||||
# what happens when the page has finished loading
|
||||
def webView_didFinishLoadForFrame_(self,webview,frame):
|
||||
# don't care about subframes
|
||||
if (frame == webview.mainFrame()):
|
||||
view = frame.frameView().documentView()
|
||||
|
||||
self.resizeWebview(view)
|
||||
|
||||
URL = frame.dataSource().initialRequest().URL().absoluteString()
|
||||
filename = self.makeFilename(URL, self.options)
|
||||
|
||||
bitmapdata = self.captureView(view)
|
||||
self.saveImages(bitmapdata,filename,self.options)
|
||||
|
||||
# ----------------------------------
|
||||
# picidae my stuff
|
||||
|
||||
|
||||
#print "url"
|
||||
print "<page>"
|
||||
print frame.dataSource().request().URL().absoluteString()
|
||||
print "</page>"
|
||||
|
||||
|
||||
# Analyse HTML and get links
|
||||
xmloutput = "<map name=\"map\">\r";
|
||||
|
||||
domdocument = frame.DOMDocument()
|
||||
domnodelist = domdocument.getElementsByTagName_('A')
|
||||
i = 0
|
||||
while i < domnodelist.length():
|
||||
# linkvalue
|
||||
value = domnodelist.item_(i).valueForKey_('href')
|
||||
|
||||
# position-rect
|
||||
myrect = domnodelist.item_(i).boundingBox()
|
||||
|
||||
xmin = Foundation.NSMinX(myrect)
|
||||
ymin = Foundation.NSMinY(myrect)
|
||||
xmax = Foundation.NSMaxX(myrect)
|
||||
ymax = Foundation.NSMaxY(myrect)
|
||||
|
||||
# print Link
|
||||
prefix = ""
|
||||
xmloutput += "<area shape=\"rect\" coords=\"%i,%i,%i,%i\" alt=\"\"><![CDATA[%s%s]]></area>\r" % (xmin, ymin, xmax, ymax, prefix, value)
|
||||
i += 1
|
||||
|
||||
#print "</map>"
|
||||
xmloutput += "</map>"
|
||||
f = open(filename +'.xml', 'w+')
|
||||
f.write(xmloutput)
|
||||
f.close()
|
||||
|
||||
# ----------------------------------
|
||||
# get forms
|
||||
xmloutput = "<forms>\r";
|
||||
xmloutput += "<page><![CDATA["
|
||||
xmloutput += frame.dataSource().request().URL().absoluteString()
|
||||
xmloutput += "]]></page>\r"
|
||||
|
||||
domdocument = frame.DOMDocument()
|
||||
domnodelist = domdocument.getElementsByTagName_('form')
|
||||
i = 0
|
||||
while i < domnodelist.length():
|
||||
# form
|
||||
action = domnodelist.item_(i).valueForKey_('action')
|
||||
method = domnodelist.item_(i).valueForKey_('method')
|
||||
xmloutput += "<form method=\"%s\" ><action><![CDATA[%s]]></action>\r" % (method, action)
|
||||
|
||||
# form fields
|
||||
fieldlist = domnodelist.item_(i).getElementsByTagName_('input')
|
||||
j=0
|
||||
while j < fieldlist.length():
|
||||
# values
|
||||
type = fieldlist.item_(j).valueForKey_('type')
|
||||
name = fieldlist.item_(j).valueForKey_('name')
|
||||
formvalue = fieldlist.item_(j).valueForKey_('value')
|
||||
size = fieldlist.item_(j).valueForKey_('size')
|
||||
checked = fieldlist.item_(j).valueForKey_('checked')
|
||||
# write output
|
||||
xmloutput += "\t<input "
|
||||
if (type):
|
||||
xmloutput += "type=\"%s\" " % (type)
|
||||
if (name):
|
||||
xmloutput += "name=\"%s\" " % (name)
|
||||
if (size):
|
||||
xmloutput += "size=\"%s\" " % (size)
|
||||
if (type and type != "hidden"):
|
||||
myrect = fieldlist.item_(j).boundingBox()
|
||||
xmin = Foundation.NSMinX(myrect)
|
||||
ymin = Foundation.NSMinY(myrect)
|
||||
xmax = Foundation.NSMaxX(myrect)
|
||||
ymax = Foundation.NSMaxY(myrect)
|
||||
height = ymax - ymin
|
||||
width = xmax - xmin
|
||||
if (type == "radio" or type == "checkbox"):
|
||||
xmin -= 3
|
||||
ymin -= 3
|
||||
xmloutput += "style=\"position:absolute;top:%i;left:%i;width:%i;height:%i;\" " % (ymin, xmin, width, height)
|
||||
if (checked):
|
||||
xmloutput += "checked=\"%s\" " % (checked)
|
||||
xmloutput += "><![CDATA["
|
||||
if (formvalue and type!="text" and type!="password"):
|
||||
#xmloutput += urllib.quote(formvalue)
|
||||
dummy=10
|
||||
xmloutput += "]]></input>\r"
|
||||
j += 1
|
||||
xmloutput += "</form>\r"
|
||||
i += 1
|
||||
|
||||
xmloutput += "</forms>"
|
||||
f = open(filename +'.form.xml', 'w+')
|
||||
f.write(xmloutput)
|
||||
f.close()
|
||||
|
||||
|
||||
# End picidae
|
||||
# ----------------------------------
|
||||
|
||||
|
||||
#print " ... done"
|
||||
self.getURL(webview)
|
||||
|
||||
#trying to give back the real url
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
# parse the command line
|
||||
usage = """%prog [options] [http://example.net/ ...]
|
||||
|
||||
examples:
|
||||
%prog http://google.com/ # screengrab google
|
||||
%prog -W 1000 -H 1000 http://google.com/ # bigger screengrab of google
|
||||
%prog -T http://google.com/ # just the thumbnail screengrab
|
||||
%prog -TF http://google.com/ # just thumbnail and fullsize grab
|
||||
%prog -o foo http://google.com/ # save images as "foo-thumb.png" etc
|
||||
%prog - # screengrab urls from stdin"""
|
||||
|
||||
cmdparser = OptionParser(usage, version=("webkit2png "+__version__))
|
||||
# TODO: add quiet/verbose options
|
||||
cmdparser.add_option("-W", "--width",type="float",default=800.0,
|
||||
help="initial (and minimum) width of browser (default: 800)")
|
||||
cmdparser.add_option("-H", "--height",type="float",default=600.0,
|
||||
help="initial (and minimum) height of browser (default: 600)")
|
||||
cmdparser.add_option("--clipwidth",type="float",default=200.0,
|
||||
help="width of clipped thumbnail (default: 200)",
|
||||
metavar="WIDTH")
|
||||
cmdparser.add_option("--clipheight",type="float",default=150.0,
|
||||
help="height of clipped thumbnail (default: 150)",
|
||||
metavar="HEIGHT")
|
||||
cmdparser.add_option("-s", "--scale",type="float",default=0.25,
|
||||
help="scale factor for thumbnails (default: 0.25)")
|
||||
cmdparser.add_option("-m", "--md5", action="store_true",
|
||||
help="use md5 hash for filename (like del.icio.us)")
|
||||
cmdparser.add_option("-o", "--filename", type="string",default="",
|
||||
metavar="NAME", help="save images as NAME.png,NAME-thumb.png etc")
|
||||
cmdparser.add_option("-F", "--fullsize", action="store_true",
|
||||
help="only create fullsize screenshot")
|
||||
cmdparser.add_option("-T", "--thumb", action="store_true",
|
||||
help="only create thumbnail sreenshot")
|
||||
cmdparser.add_option("-C", "--clipped", action="store_true",
|
||||
help="only create clipped thumbnail screenshot")
|
||||
cmdparser.add_option("-d", "--datestamp", action="store_true",
|
||||
help="include date in filename")
|
||||
cmdparser.add_option("-D", "--dir",type="string",default="./",
|
||||
help="directory to place images into")
|
||||
(options, args) = cmdparser.parse_args()
|
||||
if len(args) == 0:
|
||||
cmdparser.print_help()
|
||||
return
|
||||
if options.filename:
|
||||
if len(args) != 1 or args[0] == "-":
|
||||
print "--filename option requires exactly one url"
|
||||
return
|
||||
if options.scale == 0:
|
||||
cmdparser.error("scale cannot be zero")
|
||||
# make sure we're outputing something
|
||||
if not (options.fullsize or options.thumb or options.clipped):
|
||||
options.fullsize = True
|
||||
options.thumb = True
|
||||
options.clipped = True
|
||||
# work out the initial size of the browser window
|
||||
# (this might need to be larger so clipped image is right size)
|
||||
options.initWidth = (options.clipwidth / options.scale)
|
||||
options.initHeight = (options.clipheight / options.scale)
|
||||
if options.width>options.initWidth:
|
||||
options.initWidth = options.width
|
||||
if options.height>options.initHeight:
|
||||
options.initHeight = options.height
|
||||
|
||||
|
||||
app = AppKit.NSApplication.sharedApplication()
|
||||
|
||||
# create an app delegate
|
||||
delegate = AppDelegate.alloc().init()
|
||||
AppKit.NSApp().setDelegate_(delegate)
|
||||
|
||||
# create a window
|
||||
rect = Foundation.NSMakeRect(-16000,-16000,100,100)
|
||||
win = AppKit.NSWindow.alloc()
|
||||
win.initWithContentRect_styleMask_backing_defer_ (rect,
|
||||
AppKit.NSBorderlessWindowMask, 2, 0)
|
||||
|
||||
# create a webview object
|
||||
webview = WebKit.WebView.alloc()
|
||||
webview.initWithFrame_(rect)
|
||||
# turn off scrolling so the content is actually x wide and not x-15
|
||||
webview.mainFrame().frameView().setAllowsScrolling_(objc.NO)
|
||||
# add the webview to the window
|
||||
win.setContentView_(webview)
|
||||
|
||||
|
||||
# create a LoadDelegate
|
||||
loaddelegate = WebkitLoad.alloc().init()
|
||||
loaddelegate.options = options
|
||||
loaddelegate.urls = args
|
||||
webview.setFrameLoadDelegate_(loaddelegate)
|
||||
|
||||
app.run()
|
||||
|
||||
if __name__ == '__main__' : main()
|
||||
|
@ -1,506 +0,0 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
# webkit2png - makes screenshots of web pages
|
||||
# http://www.paulhammond.org/webkit2png
|
||||
|
||||
__version__ = "dev"
|
||||
|
||||
# Copyright (c) 2004-2013 Paul Hammond
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
#
|
||||
|
||||
import sys
|
||||
import optparse
|
||||
import re
|
||||
import os
|
||||
|
||||
try:
|
||||
import Foundation
|
||||
import WebKit
|
||||
import AppKit
|
||||
import Quartz
|
||||
import objc
|
||||
except ImportError:
|
||||
print "Cannot find pyobjc library files. Are you sure it is installed?"
|
||||
sys.exit()
|
||||
|
||||
|
||||
class AppDelegate(Foundation.NSObject):
|
||||
# what happens when the app starts up
|
||||
def applicationDidFinishLaunching_(self, aNotification):
|
||||
webview = aNotification.object().windows()[0].contentView()
|
||||
webview.frameLoadDelegate().getURL(webview)
|
||||
self.performSelector_withObject_afterDelay_("timeout:", None,
|
||||
self.timeout)
|
||||
|
||||
def timeout_(self, obj):
|
||||
Foundation.NSLog("timed out!")
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
|
||||
|
||||
class Webkit2PngScriptBridge(Foundation.NSObject):
|
||||
def init(self):
|
||||
self = super(Webkit2PngScriptBridge, self).init()
|
||||
self.is_stopped = False
|
||||
self.start_callback = False
|
||||
return self
|
||||
|
||||
def stop(self):
|
||||
self.is_stopped = True
|
||||
|
||||
def start(self):
|
||||
self.is_stopped = False
|
||||
self.start_callback()
|
||||
|
||||
def isSelectorExcludedFromWebScript_(self, sel):
|
||||
if sel in ['stop', 'start']:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
class WebkitLoad (Foundation.NSObject, WebKit.protocols.WebFrameLoadDelegate):
|
||||
|
||||
# what happens if something goes wrong while loading
|
||||
def webView_didFailLoadWithError_forFrame_(self, webview, error, frame):
|
||||
if error.code() == Foundation.NSURLErrorCancelled:
|
||||
return
|
||||
print " ... something went wrong: "+error.localizedDescription()
|
||||
self.getURL(webview)
|
||||
|
||||
def webView_didFailProvisionalLoadWithError_forFrame_(self, webview, error,
|
||||
frame):
|
||||
if error.code() == Foundation.NSURLErrorCancelled:
|
||||
return
|
||||
print " ... something went wrong: "+error.localizedDescription()
|
||||
self.getURL(webview)
|
||||
|
||||
def makeFilename(self, URL, options):
|
||||
# make the filename
|
||||
if options.filename:
|
||||
filename = options.filename
|
||||
elif options.md5:
|
||||
try:
|
||||
import md5
|
||||
except ImportError:
|
||||
print "--md5 requires python md5 library"
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
filename = md5.new(URL).hexdigest()
|
||||
else:
|
||||
filename = re.sub('^https?', '', URL)
|
||||
filename = re.sub('\W', '', filename)
|
||||
if options.datestamp:
|
||||
import time
|
||||
now = time.strftime("%Y%m%d")
|
||||
filename = now + "-" + filename
|
||||
dir = os.path.abspath(os.path.expanduser(options.dir))
|
||||
if not os.path.exists(options.dir):
|
||||
os.makedirs(dir)
|
||||
return os.path.join(dir, filename)
|
||||
|
||||
def saveImages(self, bitmapdata, filename, options):
|
||||
# save the fullsize png
|
||||
if options.fullsize:
|
||||
bitmapdata.representationUsingType_properties_(
|
||||
AppKit.NSPNGFileType,
|
||||
None
|
||||
).writeToFile_atomically_(filename + "-full.png", objc.YES)
|
||||
|
||||
if options.thumb or options.clipped:
|
||||
# work out how big the thumbnail is
|
||||
width = bitmapdata.pixelsWide()
|
||||
height = bitmapdata.pixelsHigh()
|
||||
thumbWidth = (width * options.scale)
|
||||
thumbHeight = (height * options.scale)
|
||||
|
||||
# make the thumbnails in a scratch image
|
||||
scratch = AppKit.NSImage.alloc().initWithSize_(
|
||||
Foundation.NSMakeSize(thumbWidth, thumbHeight))
|
||||
scratch.lockFocus()
|
||||
AppKit.NSGraphicsContext.currentContext().setImageInterpolation_(
|
||||
AppKit.NSImageInterpolationHigh)
|
||||
thumbRect = Foundation.NSMakeRect(0.0, 0.0, thumbWidth,
|
||||
thumbHeight)
|
||||
clipRect = Foundation.NSMakeRect(
|
||||
0.0,
|
||||
thumbHeight-options.clipheight,
|
||||
options.clipwidth,
|
||||
options.clipheight)
|
||||
bitmapdata.drawInRect_(thumbRect)
|
||||
thumbOutput = AppKit.NSBitmapImageRep.alloc()\
|
||||
.initWithFocusedViewRect_(thumbRect)
|
||||
clipOutput = AppKit.NSBitmapImageRep.alloc()\
|
||||
.initWithFocusedViewRect_(clipRect)
|
||||
scratch.unlockFocus()
|
||||
|
||||
# save the thumbnails as pngs
|
||||
if options.thumb:
|
||||
thumbOutput.representationUsingType_properties_(
|
||||
AppKit.NSPNGFileType, None).writeToFile_atomically_(
|
||||
filename + "-thumb.png", objc.YES)
|
||||
if options.clipped:
|
||||
clipOutput.representationUsingType_properties_(
|
||||
AppKit.NSPNGFileType, None).writeToFile_atomically_(
|
||||
filename + "-clipped.png", objc.YES)
|
||||
|
||||
def getURL(self, webview):
|
||||
if self.urls:
|
||||
if self.urls[0] == '-':
|
||||
url = sys.stdin.readline().rstrip()
|
||||
if not url:
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
else:
|
||||
url = self.urls.pop(0)
|
||||
else:
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
|
||||
nsurl = Foundation.NSURL.URLWithString_(url)
|
||||
if not (nsurl and nsurl.scheme()):
|
||||
nsurl = Foundation.NSURL.alloc().initFileURLWithPath_(url)
|
||||
nsurl = nsurl.absoluteURL()
|
||||
|
||||
if self.options.ignore_ssl_check:
|
||||
Foundation.NSURLRequest.setAllowsAnyHTTPSCertificate_forHost_(objc.YES, nsurl.host())
|
||||
|
||||
print "Fetching", nsurl, "..."
|
||||
self.resetWebview(webview)
|
||||
scriptobject = webview.windowScriptObject()
|
||||
scriptobject.setValue_forKey_(Webkit2PngScriptBridge.alloc().init(),
|
||||
'webkit2png')
|
||||
|
||||
webview.mainFrame().loadRequest_(Foundation.NSURLRequest.requestWithURL_(nsurl))
|
||||
if not webview.mainFrame().provisionalDataSource():
|
||||
print " ... not a proper url?"
|
||||
self.getURL(webview)
|
||||
|
||||
def resetWebview(self, webview):
|
||||
rect = Foundation.NSMakeRect(0, 0, self.options.initWidth,
|
||||
self.options.initHeight)
|
||||
window = webview.window()
|
||||
window.setContentSize_((self.options.initWidth,
|
||||
self.options.initHeight))
|
||||
|
||||
if self.options.transparent:
|
||||
window.setOpaque_(objc.NO)
|
||||
window.setBackgroundColor_(AppKit.NSColor.clearColor())
|
||||
webview.setDrawsBackground_(objc.NO)
|
||||
|
||||
webview.setFrame_(rect)
|
||||
|
||||
def captureView(self, view):
|
||||
bounds = view.bounds()
|
||||
if bounds.size.height > self.options.UNSAFE_max_height:
|
||||
print >> sys.stderr, "Error: page height greater than %s, " \
|
||||
"clipping to avoid crashing windowserver." % \
|
||||
self.options.UNSAFE_max_height
|
||||
bounds.size.height = self.options.UNSAFE_max_height
|
||||
if bounds.size.width > self.options.UNSAFE_max_width:
|
||||
print >> sys.stderr, "Error: page width greater than %s, " \
|
||||
"clipping to avoid crashing windowserver." % \
|
||||
self.options.UNSAFE_max_width
|
||||
bounds.size.width = self.options.UNSAFE_max_width
|
||||
|
||||
view.window().display()
|
||||
view.window().setContentSize_(
|
||||
Foundation.NSSize(self.options.initWidth, self.options.initHeight))
|
||||
view.setFrame_(bounds)
|
||||
|
||||
if hasattr(view, "bitmapImageRepForCachingDisplayInRect_"):
|
||||
bitmapdata = view.bitmapImageRepForCachingDisplayInRect_(bounds)
|
||||
view.cacheDisplayInRect_toBitmapImageRep_(bounds, bitmapdata)
|
||||
else:
|
||||
view.lockFocus()
|
||||
bitmapdata = AppKit.NSBitmapImageRep.alloc()
|
||||
bitmapdata.initWithFocusedViewRect_(bounds)
|
||||
view.unlockFocus()
|
||||
return bitmapdata
|
||||
|
||||
# what happens when the page has finished loading
|
||||
def webView_didFinishLoadForFrame_(self, webview, frame):
|
||||
# don't care about subframes
|
||||
if (frame == webview.mainFrame()):
|
||||
scriptobject = webview.windowScriptObject()
|
||||
if self.options.js:
|
||||
scriptobject.evaluateWebScript_(self.options.js)
|
||||
|
||||
bridge = scriptobject.valueForKey_('webkit2png')
|
||||
|
||||
def doGrab():
|
||||
Foundation.NSTimer.\
|
||||
scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
|
||||
self.options.delay, self, self.doGrab, webview, False)
|
||||
|
||||
if bridge.is_stopped:
|
||||
bridge.start_callback = doGrab
|
||||
else:
|
||||
doGrab()
|
||||
|
||||
def doGrab(self, timer):
|
||||
webview = timer.userInfo()
|
||||
frame = webview.mainFrame()
|
||||
view = frame.frameView().documentView()
|
||||
|
||||
URL = webview.mainFrame().dataSource().initialRequest().URL()\
|
||||
.absoluteString()
|
||||
filename = self.makeFilename(URL, self.options)
|
||||
|
||||
bitmapdata = self.captureView(view)
|
||||
|
||||
if self.options.selector:
|
||||
doc = frame.DOMDocument()
|
||||
el = doc.querySelector_(self.options.selector)
|
||||
|
||||
if not el:
|
||||
print " ... no element matching %s found?" % \
|
||||
self.options.selector
|
||||
self.getURL(webview)
|
||||
return
|
||||
|
||||
left, top = 0, 0
|
||||
parent = el
|
||||
while parent:
|
||||
left += parent.offsetLeft()
|
||||
top += parent.offsetTop()
|
||||
parent = parent.offsetParent()
|
||||
|
||||
zoom = self.options.zoom
|
||||
|
||||
cropRect = view.window().convertRectToBacking_(Foundation.NSMakeRect(
|
||||
zoom * left, zoom * top,
|
||||
zoom * el.offsetWidth(), zoom * el.offsetHeight()))
|
||||
|
||||
cropped = Quartz.CGImageCreateWithImageInRect(
|
||||
bitmapdata.CGImage(), cropRect)
|
||||
bitmapdata = AppKit.NSBitmapImageRep.alloc().initWithCGImage_(
|
||||
cropped)
|
||||
Quartz.CGImageRelease(cropped)
|
||||
|
||||
self.saveImages(bitmapdata, filename, self.options)
|
||||
|
||||
print " ... done"
|
||||
self.getURL(webview)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
# parse the command line
|
||||
usage = """%prog [options] [http://example.net/ ...]
|
||||
|
||||
Examples:
|
||||
%prog http://google.com/ # screengrab google
|
||||
%prog -W 1000 -H 1000 http://google.com/ # bigger screengrab of google
|
||||
%prog -T http://google.com/ # just the thumbnail screengrab
|
||||
%prog -TF http://google.com/ # just thumbnail and fullsize grab
|
||||
%prog -o foo http://google.com/ # save images as "foo-thumb.png" etc
|
||||
%prog - # screengrab urls from stdin
|
||||
%prog /path/to/file.html # screengrab local html file
|
||||
%prog -h | less # full documentation"""
|
||||
|
||||
cmdparser = optparse.OptionParser(usage,
|
||||
version=("webkit2png " + __version__))
|
||||
# TODO: add quiet/verbose options
|
||||
cmdparser.add_option("--debug", action="store_true",
|
||||
help=optparse.SUPPRESS_HELP)
|
||||
|
||||
# warning: setting these too high can crash your window server
|
||||
cmdparser.add_option("--UNSAFE-max-height", type="int", default=30000,
|
||||
help=optparse.SUPPRESS_HELP)
|
||||
cmdparser.add_option("--UNSAFE-max-width", type="int", default=30000,
|
||||
help=optparse.SUPPRESS_HELP)
|
||||
|
||||
group = optparse.OptionGroup(cmdparser, "Network Options")
|
||||
group.add_option("--timeout", type="float", default=60.0,
|
||||
help="page load timeout (default: 60)")
|
||||
group.add_option("--user-agent", type="string", default=False,
|
||||
help="set user agent header")
|
||||
group.add_option("--ignore-ssl-check", action="store_true", default=False,
|
||||
help="ignore SSL Certificate name mismatches")
|
||||
cmdparser.add_option_group(group)
|
||||
|
||||
group = optparse.OptionGroup(cmdparser, "Browser Window Options")
|
||||
group.add_option(
|
||||
"-W", "--width", type="float", default=800.0,
|
||||
help="initial (and minimum) width of browser (default: 800)")
|
||||
group.add_option(
|
||||
"-H", "--height", type="float", default=600.0,
|
||||
help="initial (and minimum) height of browser (default: 600)")
|
||||
group.add_option(
|
||||
"-z", "--zoom", type="float", default=1.0,
|
||||
help='zoom level of browser, equivalent to "Zoom In" and "Zoom Out" '
|
||||
'in "View" menu (default: 1.0)')
|
||||
group.add_option(
|
||||
"--selector", type="string",
|
||||
help="CSS selector for a single element to capture (first matching "
|
||||
"element will be used)")
|
||||
cmdparser.add_option_group(group)
|
||||
|
||||
group = optparse.OptionGroup(cmdparser, "Output size options")
|
||||
group.add_option(
|
||||
"-F", "--fullsize", action="store_true",
|
||||
help="only create fullsize screenshot")
|
||||
group.add_option(
|
||||
"-T", "--thumb", action="store_true",
|
||||
help="only create thumbnail sreenshot")
|
||||
group.add_option(
|
||||
"-C", "--clipped", action="store_true",
|
||||
help="only create clipped thumbnail screenshot")
|
||||
group.add_option(
|
||||
"--clipwidth", type="float", default=200.0,
|
||||
help="width of clipped thumbnail (default: 200)",
|
||||
metavar="WIDTH")
|
||||
group.add_option(
|
||||
"--clipheight", type="float", default=150.0,
|
||||
help="height of clipped thumbnail (default: 150)",
|
||||
metavar="HEIGHT")
|
||||
group.add_option(
|
||||
"-s", "--scale", type="float", default=0.25,
|
||||
help="scale factor for thumbnails (default: 0.25)")
|
||||
cmdparser.add_option_group(group)
|
||||
|
||||
group = optparse.OptionGroup(cmdparser, "Output filename options")
|
||||
group.add_option(
|
||||
"-D", "--dir", type="string", default="./",
|
||||
help="directory to place images into")
|
||||
group.add_option(
|
||||
"-o", "--filename", type="string", default="",
|
||||
metavar="NAME", help="save images as NAME-full.png,NAME-thumb.png etc")
|
||||
group.add_option(
|
||||
"-m", "--md5", action="store_true",
|
||||
help="use md5 hash for filename (like del.icio.us)")
|
||||
group.add_option(
|
||||
"-d", "--datestamp", action="store_true",
|
||||
help="include date in filename")
|
||||
cmdparser.add_option_group(group)
|
||||
|
||||
group = optparse.OptionGroup(cmdparser, "Web page functionality")
|
||||
group.add_option(
|
||||
"--delay", type="float", default=0,
|
||||
help="delay between page load finishing and screenshot")
|
||||
group.add_option(
|
||||
"--js", type="string", default=None,
|
||||
help="JavaScript to execute when the window finishes loading"
|
||||
"(example: --js='document.bgColor=\"red\";'). "
|
||||
"If you need to wait for asynchronous code to finish before "
|
||||
"capturing the screenshot, call webkit2png.stop() before the "
|
||||
"async code runs, then webkit2png.start() to capture the image.")
|
||||
group.add_option(
|
||||
"--noimages", action="store_true",
|
||||
help=optparse.SUPPRESS_HELP)
|
||||
group.add_option(
|
||||
"--no-images", action="store_true",
|
||||
help="don't load images")
|
||||
group.add_option(
|
||||
"--nojs", action="store_true",
|
||||
help=optparse.SUPPRESS_HELP)
|
||||
group.add_option(
|
||||
"--no-js", action="store_true",
|
||||
help="disable JavaScript support")
|
||||
group.add_option(
|
||||
"--transparent", action="store_true",
|
||||
help="render output on a transparent background (requires a web "
|
||||
"page with a transparent background)", default=False)
|
||||
cmdparser.add_option_group(group)
|
||||
|
||||
(options, args) = cmdparser.parse_args()
|
||||
if len(args) == 0:
|
||||
cmdparser.print_usage()
|
||||
return
|
||||
if options.filename:
|
||||
if len(args) != 1 or args[0] == "-":
|
||||
print "--filename option requires exactly one url"
|
||||
return
|
||||
|
||||
# deprecated options
|
||||
if options.nojs:
|
||||
print >> sys.stderr, 'Warning: --nojs will be removed in ' \
|
||||
'webkit2png 1.0. Please use --no-js.'
|
||||
options.no_js = True
|
||||
if options.noimages:
|
||||
print >> sys.stderr, 'Warning: --noimages will be removed in ' \
|
||||
'webkit2png 1.0. Please use --no-images.'
|
||||
options.no_images = True
|
||||
|
||||
if options.scale == 0:
|
||||
cmdparser.error("scale cannot be zero")
|
||||
# make sure we're outputing something
|
||||
if not (options.fullsize or options.thumb or options.clipped):
|
||||
options.fullsize = True
|
||||
options.thumb = True
|
||||
options.clipped = True
|
||||
# work out the initial size of the browser window
|
||||
# (this might need to be larger so clipped image is right size)
|
||||
options.initWidth = (options.clipwidth / options.scale)
|
||||
options.initHeight = (options.clipheight / options.scale)
|
||||
options.width *= options.zoom
|
||||
if options.width > options.initWidth:
|
||||
options.initWidth = options.width
|
||||
if options.height > options.initHeight:
|
||||
options.initHeight = options.height
|
||||
|
||||
# Hide the dock icon (needs to run before NSApplication.sharedApplication)
|
||||
AppKit.NSBundle.mainBundle().infoDictionary()['LSBackgroundOnly'] = '1'
|
||||
|
||||
app = AppKit.NSApplication.sharedApplication()
|
||||
|
||||
# create an app delegate
|
||||
delegate = AppDelegate.alloc().init()
|
||||
delegate.timeout = options.timeout
|
||||
AppKit.NSApp().setDelegate_(delegate)
|
||||
|
||||
# create a window
|
||||
rect = Foundation.NSMakeRect(0, 0, 100, 100)
|
||||
win = AppKit.NSWindow.alloc()
|
||||
win.initWithContentRect_styleMask_backing_defer_(
|
||||
rect, AppKit.NSBorderlessWindowMask, 2, 0)
|
||||
if options.debug:
|
||||
win.orderFrontRegardless()
|
||||
# create a webview object
|
||||
webview = WebKit.WebView.alloc()
|
||||
webview.initWithFrame_(rect)
|
||||
# turn off scrolling so the content is actually x wide and not x-15
|
||||
webview.mainFrame().frameView().setAllowsScrolling_(objc.NO)
|
||||
|
||||
if options.user_agent:
|
||||
webview.setCustomUserAgent_(options.user_agent)
|
||||
else:
|
||||
webkit_version = Foundation.NSBundle.bundleForClass_(WebKit.WebView)\
|
||||
.objectForInfoDictionaryKey_(WebKit.kCFBundleVersionKey)[1:]
|
||||
webview.setApplicationNameForUserAgent_(
|
||||
"Like-Version/6.0 Safari/%s webkit2png/%s" % (webkit_version, __version__))
|
||||
webview.setPreferencesIdentifier_('webkit2png')
|
||||
webview.preferences().setLoadsImagesAutomatically_(not options.no_images)
|
||||
webview.preferences().setJavaScriptEnabled_(not options.no_js)
|
||||
|
||||
if options.zoom != 1.0:
|
||||
webview._setZoomMultiplier_isTextOnly_(options.zoom, False)
|
||||
|
||||
# add the webview to the window
|
||||
win.setContentView_(webview)
|
||||
|
||||
# create a LoadDelegate
|
||||
loaddelegate = WebkitLoad.alloc().init()
|
||||
loaddelegate.options = options
|
||||
loaddelegate.urls = args
|
||||
webview.setFrameLoadDelegate_(loaddelegate)
|
||||
|
||||
app.run()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
212
old/webrender.py
212
old/webrender.py
@ -1,212 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# webrender.py - recursively render web pages to a gif+imagemap of clickable links
|
||||
# caveat: this script requires to be run as a regular user and cannot run as a daemon
|
||||
# from apache cgi-bin, you can use python built in http server instead
|
||||
# usage:
|
||||
# create cgi-bin directory, copy webrender.py to cgi-bin and chmod 755
|
||||
# python -m CGIHTTPServer 8000
|
||||
# navigate web browser to http://x.x.x.x:8000/cgi-bin/webrender.py
|
||||
# the webrender-xxx.gif images are created in the CWD of the http server
|
||||
|
||||
|
||||
__version__ = "1.0"
|
||||
|
||||
#
|
||||
# This program is based on the software picidae.py 1.0 from http://www.picidae.net
|
||||
# It was modified by Antoni Sawicki
|
||||
#
|
||||
# This program is based on the software webkit2png 0.4 from Paul Hammond.
|
||||
# It was extended by picidae.net
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
|
||||
|
||||
try:
|
||||
import sys
|
||||
import os
|
||||
import glob
|
||||
import random
|
||||
import Foundation
|
||||
import WebKit
|
||||
import AppKit
|
||||
import objc
|
||||
import string
|
||||
import urllib
|
||||
import socket
|
||||
import cgi
|
||||
import cgitb; cgitb.enable() # for trubleshooting
|
||||
except ImportError:
|
||||
print "Cannot find pyobjc library files. Are you sure it is installed?"
|
||||
sys.exit()
|
||||
|
||||
|
||||
from optparse import OptionParser
|
||||
|
||||
|
||||
class AppDelegate (Foundation.NSObject):
|
||||
# what happens when the app starts up
|
||||
def applicationDidFinishLaunching_(self, aNotification):
|
||||
webview = aNotification.object().windows()[0].contentView()
|
||||
webview.frameLoadDelegate().getURL(webview)
|
||||
|
||||
|
||||
class WebkitLoad (Foundation.NSObject, WebKit.protocols.WebFrameLoadDelegate):
|
||||
# what happens if something goes wrong while loading
|
||||
def webView_didFailLoadWithError_forFrame_(self,webview,error,frame):
|
||||
print " ... something went wrong 1: " + error.localizedDescription()
|
||||
self.getURL(webview)
|
||||
def webView_didFailProvisionalLoadWithError_forFrame_(self,webview,error,frame):
|
||||
print " ... something went wrong 2: " + error.localizedDescription()
|
||||
self.getURL(webview)
|
||||
|
||||
def getURL(self,webview):
|
||||
if self.urls:
|
||||
if self.urls[0] == '-':
|
||||
url = sys.stdin.readline().rstrip()
|
||||
if not url: AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
else:
|
||||
url = self.urls.pop(0)
|
||||
else:
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
|
||||
self.resetWebview(webview)
|
||||
webview.mainFrame().loadRequest_(Foundation.NSURLRequest.requestWithURL_(Foundation.NSURL.URLWithString_(url)))
|
||||
if not webview.mainFrame().provisionalDataSource():
|
||||
print "<nosuccess />"
|
||||
self.getURL(webview)
|
||||
|
||||
def resetWebview(self,webview):
|
||||
rect = Foundation.NSMakeRect(0,0,1024,768)
|
||||
webview.window().setContentSize_((1024,768))
|
||||
webview.setFrame_(rect)
|
||||
|
||||
def resizeWebview(self,view):
|
||||
view.window().display()
|
||||
view.window().setContentSize_(view.bounds().size)
|
||||
view.setFrame_(view.bounds())
|
||||
|
||||
def captureView(self,view):
|
||||
view.lockFocus()
|
||||
bitmapdata = AppKit.NSBitmapImageRep.alloc()
|
||||
bitmapdata.initWithFocusedViewRect_(view.bounds())
|
||||
view.unlockFocus()
|
||||
return bitmapdata
|
||||
|
||||
# what happens when the page has finished loading
|
||||
def webView_didFinishLoadForFrame_(self,webview,frame):
|
||||
# don't care about subframes
|
||||
if (frame == webview.mainFrame()):
|
||||
view = frame.frameView().documentView()
|
||||
|
||||
self.resizeWebview(view)
|
||||
|
||||
URL = frame.dataSource().initialRequest().URL().absoluteString()
|
||||
|
||||
for fl in glob.glob("webrender-*.gif"):
|
||||
os.remove(fl)
|
||||
|
||||
GIF = "webrender-%s.gif" % (random.randrange(0,1000))
|
||||
|
||||
bitmapdata = self.captureView(view)
|
||||
bitmapdata.representationUsingType_properties_(AppKit.NSGIFFileType,None).writeToFile_atomically_(GIF,objc.YES)
|
||||
|
||||
myurl = "http://%s:%s%s" % (socket.gethostbyname(socket.gethostname()), os.getenv("SERVER_PORT"), os.getenv("SCRIPT_NAME"))
|
||||
|
||||
print "Content-type: text/html\r\n\r\n"
|
||||
print "<!-- webrender.py by Antoni Sawicki -->"
|
||||
print "<html><head><title>Webrender - %s</title></head><body><table border=\"0\"><tr>" % (URL)
|
||||
print "<td><form action=\"%s\">" % (myurl)
|
||||
print "<input type=\"text\" name=\"url\" value=\"%s\" size=\"80\">" % (URL)
|
||||
print "<input type=\"submit\" value=\"go\">"
|
||||
print "</form></td><td>"
|
||||
print "<form action=\"%s\">" % (myurl)
|
||||
print "<input type=\"text\" name=\"search\" value=\"\" size=\"20\">"
|
||||
print "<input type=\"submit\" value=\"search\">"
|
||||
print "</form></td></tr></table>"
|
||||
print "<img src=\"../%s\" alt=\"webrender\" usemap=\"#map\" border=\"0\">" % (GIF)
|
||||
|
||||
|
||||
# Analyse HTML and get links
|
||||
print "<map name=\"map\">";
|
||||
|
||||
domdocument = frame.DOMDocument()
|
||||
domnodelist = domdocument.getElementsByTagName_('A')
|
||||
i = 0
|
||||
while i < domnodelist.length():
|
||||
# linkvalue
|
||||
value = domnodelist.item_(i).valueForKey_('href')
|
||||
|
||||
# position-rect
|
||||
myrect = domnodelist.item_(i).boundingBox()
|
||||
|
||||
xmin = Foundation.NSMinX(myrect)
|
||||
ymin = Foundation.NSMinY(myrect)
|
||||
xmax = Foundation.NSMaxX(myrect)
|
||||
ymax = Foundation.NSMaxY(myrect)
|
||||
|
||||
# print Link
|
||||
escval = string.replace( string.replace(value, "?", "TNXQUE"), "&", "TNXAMP" )
|
||||
print "<area shape=\"rect\" coords=\"%i,%i,%i,%i\" alt=\"\" href=\"%s?url=%s\"></area>" % (xmin, ymin, xmax, ymax, myurl, escval)
|
||||
i += 1
|
||||
|
||||
print "</map>"
|
||||
print "</body></html>"
|
||||
self.getURL(webview)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
# obtain url from cgi input
|
||||
form = cgi.FieldStorage()
|
||||
rawurl = form.getfirst("url", "http://www.google.com")
|
||||
rawsearch = form.getfirst("search")
|
||||
if rawsearch:
|
||||
url = "http://www.google.com/search?q=%s" % (rawsearch)
|
||||
else:
|
||||
url = string.replace( string.replace(rawurl, "TNXAMP", "&"), "TNXQUE", "?")
|
||||
|
||||
|
||||
AppKit.NSApplicationLoad();
|
||||
|
||||
app = AppKit.NSApplication.sharedApplication()
|
||||
|
||||
# create an app delegate
|
||||
delegate = AppDelegate.alloc().init()
|
||||
AppKit.NSApp().setDelegate_(delegate)
|
||||
|
||||
# create a window
|
||||
rect = Foundation.NSMakeRect(-16000,-16000,100,100)
|
||||
win = AppKit.NSWindow.alloc()
|
||||
win.initWithContentRect_styleMask_backing_defer_ (rect, AppKit.NSBorderlessWindowMask, 2, 0)
|
||||
|
||||
# create a webview object
|
||||
webview = WebKit.WebView.alloc()
|
||||
webview.initWithFrame_(rect)
|
||||
# turn off scrolling so the content is actually x wide and not x-15
|
||||
webview.mainFrame().frameView().setAllowsScrolling_(objc.NO)
|
||||
# add the webview to the window
|
||||
win.setContentView_(webview)
|
||||
|
||||
|
||||
# create a LoadDelegate
|
||||
loaddelegate = WebkitLoad.alloc().init()
|
||||
loaddelegate.options = [""]
|
||||
loaddelegate.urls = [url]
|
||||
webview.setFrameLoadDelegate_(loaddelegate)
|
||||
|
||||
app.run()
|
||||
|
||||
if __name__ == '__main__' : main()
|
||||
|
931
old/wrp.py
931
old/wrp.py
@ -1,931 +0,0 @@
|
||||
#!/usr/bin/env python2.7
|
||||
|
||||
# wrp.py - Web Rendering Proxy - https://github.com/tenox7/wrp
|
||||
# A HTTP proxy service that renders the requested URL in to a image associated
|
||||
# with an imagemap of clickable links. This is an adaptation of previous works by
|
||||
# picidae.net and Paul Hammond.
|
||||
|
||||
__version__ = "2.0"
|
||||
|
||||
#
|
||||
# This program is based on the software picidae.py from picidae.net
|
||||
# It was modified by Antoni Sawicki and Natalia Portillo
|
||||
#
|
||||
# This program is based on the software webkit2png from Paul Hammond.
|
||||
# It was extended by picidae.net
|
||||
#
|
||||
# Copyright (c) 2013-2018 Antoni Sawicki
|
||||
# Copyright (c) 2012-2013 picidae.net
|
||||
# Copyright (c) 2004-2013 Paul Hammond
|
||||
# Copyright (c) 2017-2018 Natalia Portillo
|
||||
# Copyright (c) 2018 //gir.st/
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
#
|
||||
|
||||
# Configuration options:
|
||||
PORT = 8080
|
||||
WIDTH = 1024
|
||||
HEIGHT = 768
|
||||
ISMAP = False # ISMAP=True is Server side for Mosaic 1.1 and up. HTML 3.2 supports Client side maps (ISMAP=False)
|
||||
WAIT = 1 # sleep for 1 second to allow javascript renders
|
||||
QUALITY = 75 # For JPEG: image quality 0-100; For PNG: sets compression level (leftmost digit 0 fastest, 9 best)
|
||||
AUTOWIDTH = True # Check for browser width using javascript
|
||||
FORMAT = "AUTO" # AUTO = GIF for mac OS, JPG for rest; PNG, GIF, JPG as supported values.
|
||||
SSLSTRIP = True # enable to automatically downgrade secure requests
|
||||
|
||||
# PythonMagick configuration options
|
||||
MK_MONOCHROME = False # Convert the render to a black and white dithered image
|
||||
MK_GRAYSCALE = False # Convert the render to a grayscal dithered image
|
||||
MK_COLORS = 0 # Reduce number of colors in the image. 0 for not reducing. Less than 256 works in grayscale also.
|
||||
MK_DITHER = False # Dither the image to reduce size. GIFs will always be dithered. Ignored if MK_COLORS is not set.
|
||||
|
||||
import re
|
||||
import random
|
||||
import os
|
||||
import time
|
||||
import string
|
||||
import urllib
|
||||
import socket
|
||||
import SocketServer
|
||||
import SimpleHTTPServer
|
||||
import threading
|
||||
import Queue
|
||||
import sys
|
||||
import logging
|
||||
import StringIO
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
import PythonMagick
|
||||
HasMagick = True
|
||||
except ImportError:
|
||||
HasMagick = False
|
||||
|
||||
# Request queue (URLs go in here)
|
||||
REQ = Queue.Queue()
|
||||
# Response queue (dummy response objects)
|
||||
RESP = Queue.Queue()
|
||||
# Renders dictionary
|
||||
RENDERS = {}
|
||||
|
||||
#######################
|
||||
### Linux CODEPATH ###
|
||||
#######################
|
||||
|
||||
if sys.platform.startswith('linux') or sys.platform.startswith('freebsd'):
|
||||
try:
|
||||
from PyQt5.QtCore import *
|
||||
from PyQt5.QtGui import *
|
||||
from PyQt5.QtWebKit import *
|
||||
from PyQt5.QtWebKitWidgets import *
|
||||
from PyQt5.QtNetwork import *
|
||||
from PyQt5.QtWidgets import *
|
||||
IsPyQt5 = True
|
||||
except ImportError:
|
||||
from PyQt4.QtCore import *
|
||||
from PyQt4.QtGui import *
|
||||
from PyQt4.QtWebKit import *
|
||||
from PyQt4.QtNetwork import *
|
||||
IsPyQt5 = False
|
||||
|
||||
# claunia: Check how to use this in macOS
|
||||
logging.basicConfig(filename='/dev/stdout', level=logging.WARN, )
|
||||
logger = logging.getLogger('wrp')
|
||||
|
||||
# Class for Website-Rendering. Uses QWebPage, which
|
||||
# requires a running QtGui to work.
|
||||
class WebkitRenderer(QObject):
|
||||
def __init__(self, **kwargs):
|
||||
"""Sets default values for the properties."""
|
||||
|
||||
if not QApplication.instance():
|
||||
raise RuntimeError(self.__class__.__name__ + \
|
||||
" requires a running QApplication instance")
|
||||
QObject.__init__(self)
|
||||
|
||||
# Initialize default properties
|
||||
self.width = kwargs.get('width', 0)
|
||||
self.height = kwargs.get('height', 0)
|
||||
self.timeout = kwargs.get('timeout', 0)
|
||||
self.wait = kwargs.get('wait', 0)
|
||||
self.logger = kwargs.get('logger', None)
|
||||
# Set this to true if you want to capture flash.
|
||||
# Not that your desktop must be large enough for
|
||||
# fitting the whole window.
|
||||
self.grabWholeWindow = kwargs.get('grabWholeWindow', False)
|
||||
|
||||
# Set some default options for QWebPage
|
||||
self.qWebSettings = {
|
||||
QWebSettings.JavascriptEnabled : True,
|
||||
QWebSettings.PluginsEnabled : True,
|
||||
QWebSettings.PrivateBrowsingEnabled : True,
|
||||
QWebSettings.JavascriptCanOpenWindows : False
|
||||
}
|
||||
|
||||
def render(self, url):
|
||||
"""Renders the given URL into a QImage object"""
|
||||
# We have to use this helper object because
|
||||
# QApplication.processEvents may be called, causing
|
||||
# this method to get called while it has not returned yet.
|
||||
helper = _WebkitRendererHelper(self)
|
||||
helper._window.resize(self.width, self.height)
|
||||
image = helper.render(url)
|
||||
|
||||
# Bind helper instance to this image to prevent the
|
||||
# object from being cleaned up (and with it the QWebPage, etc)
|
||||
# before the data has been used.
|
||||
image.helper = helper
|
||||
|
||||
return image
|
||||
|
||||
class _WebkitRendererHelper(QObject):
|
||||
"""This helper class is doing the real work. It is required to
|
||||
allow WebkitRenderer.render() to be called "asynchronously"
|
||||
(but always from Qt's GUI thread).
|
||||
"""
|
||||
|
||||
def __init__(self, parent):
|
||||
"""Copies the properties from the parent (WebkitRenderer) object,
|
||||
creates the required instances of QWebPage, QWebView and QMainWindow
|
||||
and registers some Slots.
|
||||
"""
|
||||
QObject.__init__(self)
|
||||
|
||||
# Copy properties from parent
|
||||
for key, value in parent.__dict__.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
# Create and connect required PyQt4 objects
|
||||
self._page = CustomWebPage(logger=self.logger)
|
||||
self._view = QWebView()
|
||||
self._view.setPage(self._page)
|
||||
self._window = QMainWindow()
|
||||
self._window.setCentralWidget(self._view)
|
||||
|
||||
# Import QWebSettings
|
||||
for key, value in self.qWebSettings.iteritems():
|
||||
self._page.settings().setAttribute(key, value)
|
||||
|
||||
# Connect required event listeners
|
||||
if IsPyQt5:
|
||||
self._page.loadFinished.connect(self._on_load_finished)
|
||||
self._page.loadStarted.connect(self._on_load_started)
|
||||
self._page.networkAccessManager().sslErrors.connect(self._on_ssl_errors)
|
||||
self._page.networkAccessManager().finished.connect(self._on_each_reply)
|
||||
else:
|
||||
self.connect(self._page, SIGNAL("loadFinished(bool)"), self._on_load_finished)
|
||||
self.connect(self._page, SIGNAL("loadStarted()"), self._on_load_started)
|
||||
self.connect(self._page.networkAccessManager(),
|
||||
SIGNAL("sslErrors(QNetworkReply *,const QList<QSslError>&)"),
|
||||
self._on_ssl_errors)
|
||||
self.connect(self._page.networkAccessManager(),
|
||||
SIGNAL("finished(QNetworkReply *)"),
|
||||
self._on_each_reply)
|
||||
|
||||
# The way we will use this, it seems to be unesseccary to have Scrollbars enabled
|
||||
self._page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff)
|
||||
self._page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff)
|
||||
self._page.settings().setUserStyleSheetUrl(
|
||||
QUrl("data:text/css,html,body{overflow-y:hidden !important;}"))
|
||||
|
||||
# Show this widget
|
||||
# self._window.show()
|
||||
|
||||
def __del__(self):
|
||||
"""Clean up Qt4 objects. """
|
||||
self._window.close()
|
||||
del self._window
|
||||
del self._view
|
||||
del self._page
|
||||
|
||||
def render(self, url):
|
||||
"""The real worker. Loads the page (_load_page) and awaits
|
||||
the end of the given 'delay'. While it is waiting outstanding
|
||||
QApplication events are processed.
|
||||
After the given delay, the Window or Widget (depends
|
||||
on the value of 'grabWholeWindow' is drawn into a QPixmap
|
||||
"""
|
||||
self._load_page(url, self.width, self.height, self.timeout)
|
||||
# Wait for end of timer. In this time, process
|
||||
# other outstanding Qt events.
|
||||
if self.wait > 0:
|
||||
if self.logger: self.logger.debug("Waiting %d seconds " % self.wait)
|
||||
waitToTime = time.time() + self.wait
|
||||
while time.time() < waitToTime:
|
||||
if QApplication.hasPendingEvents():
|
||||
QApplication.processEvents()
|
||||
|
||||
if self.grabWholeWindow:
|
||||
# Note that this does not fully ensure that the
|
||||
# window still has the focus when the screen is
|
||||
# grabbed. This might result in a race condition.
|
||||
self._view.activateWindow()
|
||||
if IsPyQt5:
|
||||
image = QScreen.grabWindow(self._window.winId())
|
||||
else:
|
||||
image = QPixmap.grabWindow(self._window.winId())
|
||||
else:
|
||||
if IsPyQt5:
|
||||
image = QWidget.grab(self._window)
|
||||
else:
|
||||
image = QPixmap.grabWidget(self._window)
|
||||
|
||||
httpout = WebkitRenderer.httpout
|
||||
|
||||
frame = self._view.page().currentFrame()
|
||||
web_url = frame.url().toString()
|
||||
|
||||
# Write URL map
|
||||
httpout.write("<!-- Web Rendering Proxy v%s by Antoni Sawicki -->\n"
|
||||
% (__version__))
|
||||
httpout.write("<!-- Request for [%s] frame [%s] -->\n"
|
||||
% (WebkitRenderer.req_url, web_url))
|
||||
# Get title
|
||||
httpout.write("<HTML><HEAD>")
|
||||
for ttl in frame.findAllElements('title'):
|
||||
httpout.write((u"<TITLE>%s</TITLE>"
|
||||
% ttl.toPlainText()).encode('utf-8', errors='ignore'))
|
||||
break # Don't repeat bad HTML coding with several title marks
|
||||
httpout.write("</HEAD>\n<BODY>\n")
|
||||
|
||||
if AUTOWIDTH:
|
||||
httpout.write("<script>document.write('<span style=\"display: none;\"><img src=\"http://width-' + document.body.clientWidth + '-px.jpg\" width=\"0\" height=\"0\"></span>');</script>\n")
|
||||
|
||||
if ISMAP == True:
|
||||
httpout.write("<A HREF=\"http://%s\">"
|
||||
"<IMG SRC=\"http://%s\" ALT=\"wrp-render\" ISMAP>\n"
|
||||
"</A>\n" % (WebkitRenderer.req_map, WebkitRenderer.req_img))
|
||||
mapfile = StringIO.StringIO()
|
||||
mapfile.write("default %s\n" % (web_url))
|
||||
else:
|
||||
httpout.write("<IMG SRC=\"http://%s\" ALT=\"wrp-render\" USEMAP=\"#map\">\n"
|
||||
"<MAP NAME=\"map\">\n" % (WebkitRenderer.req_img))
|
||||
|
||||
for x in frame.findAllElements('a'):
|
||||
turl = QUrl(web_url).resolved(QUrl(x.attribute('href'))).toString()
|
||||
xmin, ymin, xmax, ymax = x.geometry().getCoords()
|
||||
if ISMAP == True:
|
||||
mapfile.write("rect %s %i,%i %i,%i\n".decode('utf-8', errors='ignore') % (turl, xmin, ymin, xmax, ymax))
|
||||
else:
|
||||
httpout.write(("<AREA SHAPE=\"RECT\""
|
||||
" COORDS=\"%i,%i,%i,%i\""
|
||||
" ALT=\"%s\" HREF=\"%s\">\n".decode('utf-8', errors='ignore')
|
||||
% (xmin, ymin, xmax, ymax, turl, turl)).encode("utf-8"))
|
||||
|
||||
if ISMAP != True:
|
||||
httpout.write("</MAP>\n")
|
||||
|
||||
httpout.write("</BODY>\n</HTML>\n")
|
||||
|
||||
if ISMAP == True:
|
||||
RENDERS[WebkitRenderer.req_map] = mapfile
|
||||
|
||||
return image
|
||||
|
||||
def _load_page(self, url, width, height, timeout):
|
||||
"""
|
||||
This method implements the logic for retrieving and displaying
|
||||
the requested page.
|
||||
"""
|
||||
|
||||
# This is an event-based application. So we have to wait until
|
||||
# "loadFinished(bool)" raised.
|
||||
cancelAt = time.time() + timeout
|
||||
self.__loading = True
|
||||
self.__loadingResult = False # Default
|
||||
self._page.mainFrame().load(QUrl(url))
|
||||
while self.__loading:
|
||||
if timeout > 0 and time.time() >= cancelAt:
|
||||
raise RuntimeError("Request timed out on %s" % url)
|
||||
while QApplication.hasPendingEvents() and self.__loading:
|
||||
QCoreApplication.processEvents()
|
||||
|
||||
if self.logger: self.logger.debug("Processing result")
|
||||
|
||||
if self.__loading_result == False:
|
||||
if self.logger: self.logger.warning("Failed to load %s" % url)
|
||||
|
||||
# Set initial viewport (the size of the "window")
|
||||
size = self._page.mainFrame().contentsSize()
|
||||
if self.logger: self.logger.debug("contentsSize: %s", size)
|
||||
if width > 0:
|
||||
size.setWidth(width)
|
||||
if height > 0:
|
||||
size.setHeight(height)
|
||||
|
||||
self._window.resize(size)
|
||||
|
||||
def _on_each_reply(self, reply):
|
||||
"""Logs each requested uri"""
|
||||
self.logger.debug("Received %s" % (reply.url().toString()))
|
||||
|
||||
# Eventhandler for "loadStarted()" signal
|
||||
def _on_load_started(self):
|
||||
"""Slot that sets the '__loading' property to true."""
|
||||
if self.logger: self.logger.debug("loading started")
|
||||
self.__loading = True
|
||||
|
||||
# Eventhandler for "loadFinished(bool)" signal
|
||||
def _on_load_finished(self, result):
|
||||
"""Slot that sets the '__loading' property to false and stores
|
||||
the result code in '__loading_result'.
|
||||
"""
|
||||
if self.logger: self.logger.debug("loading finished with result %s", result)
|
||||
self.__loading = False
|
||||
self.__loading_result = result
|
||||
|
||||
# Eventhandler for "sslErrors(QNetworkReply *,const QList<QSslError>&)" signal
|
||||
def _on_ssl_errors(self, reply, errors):
|
||||
"""Slot that writes SSL warnings into the log but ignores them."""
|
||||
for e in errors:
|
||||
if self.logger: self.logger.warn("SSL: " + e.errorString())
|
||||
reply.ignoreSslErrors()
|
||||
|
||||
class CustomWebPage(QWebPage):
|
||||
def __init__(self, **kwargs):
|
||||
super(CustomWebPage, self).__init__()
|
||||
self.logger = kwargs.get('logger', None)
|
||||
|
||||
def javaScriptAlert(self, frame, message):
|
||||
if self.logger: self.logger.debug('Alert: %s', message)
|
||||
|
||||
def javaScriptConfirm(self, frame, message):
|
||||
if self.logger: self.logger.debug('Confirm: %s', message)
|
||||
return False
|
||||
|
||||
def javaScriptPrompt(self, frame, message, default, result):
|
||||
"""This function is called whenever a JavaScript program running inside frame tries to
|
||||
prompt the user for input. The program may provide an optional message, msg, as well
|
||||
as a default value for the input in defaultValue.
|
||||
|
||||
If the prompt was cancelled by the user the implementation should return false;
|
||||
otherwise the result should be written to result and true should be returned.
|
||||
If the prompt was not cancelled by the user, the implementation should return true and
|
||||
the result string must not be null.
|
||||
"""
|
||||
if self.logger: self.logger.debug('Prompt: %s (%s)' % (message, default))
|
||||
return False
|
||||
|
||||
def shouldInterruptJavaScript(self):
|
||||
"""This function is called when a JavaScript program is running for a long period of
|
||||
time. If the user wanted to stop the JavaScript the implementation should return
|
||||
true; otherwise false.
|
||||
"""
|
||||
if self.logger: self.logger.debug("WebKit ask to interrupt JavaScript")
|
||||
return True
|
||||
|
||||
#===============================================================================
|
||||
|
||||
def init_qtgui(display=None, style=None, qtargs=None):
|
||||
"""Initiates the QApplication environment using the given args."""
|
||||
if QApplication.instance():
|
||||
logger.debug("QApplication has already been instantiated. \
|
||||
Ignoring given arguments and returning existing QApplication.")
|
||||
return QApplication.instance()
|
||||
|
||||
qtargs2 = [sys.argv[0]]
|
||||
|
||||
if display:
|
||||
qtargs2.append('-display')
|
||||
qtargs2.append(display)
|
||||
# Also export DISPLAY var as this may be used
|
||||
# by flash plugin
|
||||
os.environ["DISPLAY"] = display
|
||||
|
||||
if style:
|
||||
qtargs2.append('-style')
|
||||
qtargs2.append(style)
|
||||
|
||||
qtargs2.extend(qtargs or [])
|
||||
|
||||
return QApplication(qtargs2)
|
||||
|
||||
# Technically, this is a QtGui application, because QWebPage requires it
|
||||
# to be. But because we will have no user interaction, and rendering can
|
||||
# not start before 'app.exec_()' is called, we have to trigger our "main"
|
||||
# by a timer event.
|
||||
def __main_qt():
|
||||
# Render the page.
|
||||
# If this method times out or loading failed, a
|
||||
# RuntimeException is thrown
|
||||
try:
|
||||
while True:
|
||||
req = REQ.get()
|
||||
WebkitRenderer.httpout = req[0]
|
||||
WebkitRenderer.req_url = req[1]
|
||||
WebkitRenderer.req_img = req[2]
|
||||
WebkitRenderer.req_map = req[3]
|
||||
if WebkitRenderer.req_url == "http://wrp.stop/" or WebkitRenderer.req_url == "http://www.wrp.stop/":
|
||||
print ">>> Terminate Request Received"
|
||||
QApplication.exit(0)
|
||||
break
|
||||
|
||||
# Initialize WebkitRenderer object
|
||||
renderer = WebkitRenderer()
|
||||
renderer.logger = logger
|
||||
renderer.width = WIDTH
|
||||
renderer.height = HEIGHT
|
||||
renderer.timeout = 60
|
||||
renderer.wait = WAIT
|
||||
renderer.grabWholeWindow = False
|
||||
|
||||
image = renderer.render(WebkitRenderer.req_url)
|
||||
qBuffer = QBuffer()
|
||||
|
||||
if HasMagick:
|
||||
image.save(qBuffer, 'png', QUALITY)
|
||||
blob = PythonMagick.Blob(qBuffer.buffer().data())
|
||||
mimg = PythonMagick.Image(blob)
|
||||
mimg.quality(QUALITY)
|
||||
|
||||
if FORMAT=="GIF" and not MK_MONOCHROME and not MK_GRAYSCALE and not MK_DITHER and MK_COLORS != 0 and not MK_COLORS <= 256:
|
||||
mimg.quantizeColors(256)
|
||||
mimg.quantizeDither()
|
||||
mimg.quantize()
|
||||
|
||||
if MK_MONOCHROME:
|
||||
mimg.quantizeColorSpace(PythonMagick.ColorspaceType.GRAYColorspace)
|
||||
mimg.quantizeColors(2)
|
||||
mimg.quantizeDither()
|
||||
mimg.quantize()
|
||||
mimg.monochrome()
|
||||
elif MK_GRAYSCALE:
|
||||
mimg.quantizeColorSpace(PythonMagick.ColorspaceType.GRAYColorspace)
|
||||
if MK_COLORS > 0 and MK_COLORS < 256:
|
||||
mimg.quantizeColors(MK_COLORS)
|
||||
else:
|
||||
mimg.quantizeColors(256)
|
||||
mimg.quantizeDither()
|
||||
mimg.quantize()
|
||||
else:
|
||||
if MK_COLORS > 0:
|
||||
mimg.quantizeColors(MK_COLORS)
|
||||
if MK_DITHER:
|
||||
mimg.quantizeDither()
|
||||
mimg.quantize()
|
||||
|
||||
if FORMAT=="AUTO" or FORMAT=="JPG":
|
||||
mimg.write(blob, "jpg")
|
||||
elif FORMAT=="PNG":
|
||||
mimg.write(blob, "png")
|
||||
elif FORMAT=="GIF":
|
||||
mimg.write(blob, "gif")
|
||||
output = StringIO.StringIO()
|
||||
output.write(blob.data)
|
||||
else:
|
||||
if FORMAT=="AUTO" or FORMAT=="JPG":
|
||||
image.save(qBuffer, 'jpg', QUALITY)
|
||||
elif FORMAT=="PNG":
|
||||
image.save(qBuffer, 'png', QUALITY)
|
||||
|
||||
output = StringIO.StringIO()
|
||||
output.write(qBuffer.buffer().data())
|
||||
|
||||
RENDERS[req[2]] = output
|
||||
|
||||
del renderer
|
||||
print ">>> done: %s [%d kb]..." % (WebkitRenderer.req_img, output.len/1024)
|
||||
|
||||
RESP.put('')
|
||||
|
||||
QApplication.exit(0)
|
||||
except RuntimeError, e:
|
||||
logger.error("main: %s" % e)
|
||||
print >> sys.stderr, e
|
||||
QApplication.exit(1)
|
||||
|
||||
######################
|
||||
### macOS CODEPATH ###
|
||||
######################
|
||||
|
||||
elif sys.platform == "darwin":
|
||||
import Foundation
|
||||
import WebKit
|
||||
import AppKit
|
||||
import objc
|
||||
|
||||
class AppDelegate(Foundation.NSObject):
|
||||
# what happens when the app starts up
|
||||
def applicationDidFinishLaunching_(self, aNotification):
|
||||
webview = aNotification.object().windows()[0].contentView()
|
||||
webview.frameLoadDelegate().getURL(webview)
|
||||
|
||||
class WebkitLoad(Foundation.NSObject, WebKit.protocols.WebFrameLoadDelegate):
|
||||
# what happens if something goes wrong while loading
|
||||
def webView_didFailLoadWithError_forFrame_(self, webview, error, frame):
|
||||
if error.code() == Foundation.NSURLErrorCancelled:
|
||||
return
|
||||
print " ... something went wrong 1: " + error.localizedDescription()
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
|
||||
def webView_didFailProvisionalLoadWithError_forFrame_(self, webview, error, frame):
|
||||
if error.code() == Foundation.NSURLErrorCancelled:
|
||||
return
|
||||
print " ... something went wrong 2: " + error.localizedDescription()
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
|
||||
def getURL(self, webview):
|
||||
req = REQ.get()
|
||||
WebkitLoad.httpout = req[0]
|
||||
WebkitLoad.req_url = req[1]
|
||||
WebkitLoad.req_img = req[2]
|
||||
WebkitLoad.req_map = req[3]
|
||||
|
||||
if WebkitLoad.req_url == "http://wrp.stop/" or WebkitLoad.req_url == "http://www.wrp.stop/":
|
||||
print ">>> Terminate Request Received"
|
||||
AppKit.NSApplication.sharedApplication().terminate_(None)
|
||||
|
||||
nsurl = Foundation.NSURL.URLWithString_(WebkitLoad.req_url)
|
||||
if not (nsurl and nsurl.scheme()):
|
||||
nsurl = Foundation.NSURL.alloc().initFileURLWithPath_(WebkitLoad.req_url)
|
||||
nsurl = nsurl.absoluteURL()
|
||||
|
||||
Foundation.NSURLRequest.setAllowsAnyHTTPSCertificate_forHost_(objc.YES, nsurl.host())
|
||||
|
||||
self.resetWebview(webview)
|
||||
webview.mainFrame().loadRequest_(Foundation.NSURLRequest.requestWithURL_(nsurl))
|
||||
if not webview.mainFrame().provisionalDataSource():
|
||||
print " ... not a proper url?"
|
||||
RESP.put('')
|
||||
self.getURL(webview)
|
||||
|
||||
def resetWebview(self, webview):
|
||||
rect = Foundation.NSMakeRect(0, 0, WIDTH, HEIGHT)
|
||||
webview.window().setContentSize_((WIDTH, HEIGHT))
|
||||
webview.setFrame_(rect)
|
||||
|
||||
def captureView(self, view):
|
||||
view.window().display()
|
||||
view.window().setContentSize_(view.bounds().size)
|
||||
view.setFrame_(view.bounds())
|
||||
|
||||
if hasattr(view, "bitmapImageRepForCachingDisplayInRect_"):
|
||||
bitmapdata = view.bitmapImageRepForCachingDisplayInRect_(view.bounds())
|
||||
view.cacheDisplayInRect_toBitmapImageRep_(view.bounds(), bitmapdata)
|
||||
else:
|
||||
view.lockFocus()
|
||||
bitmapdata = AppKit.NSBitmapImageRep.alloc()
|
||||
bitmapdata.initWithFocusedViewRect_(view.bounds())
|
||||
view.unlockFocus()
|
||||
return bitmapdata
|
||||
|
||||
# what happens when the page has finished loading
|
||||
def webView_didFinishLoadForFrame_(self, webview, frame):
|
||||
# don't care about subframes
|
||||
if frame == webview.mainFrame():
|
||||
view = frame.frameView().documentView()
|
||||
|
||||
output = StringIO.StringIO()
|
||||
|
||||
if HasMagick:
|
||||
output.write(self.captureView(view).representationUsingType_properties_(
|
||||
AppKit.NSPNGFileType, None))
|
||||
blob = PythonMagick.Blob(output)
|
||||
mimg = PythonMagick.Image(blob)
|
||||
mimg.quality(QUALITY)
|
||||
|
||||
if FORMAT=="GIF" and not MK_MONOCHROME and not MK_GRAYSCALE and not MK_DITHER and MK_COLORS != 0 and not MK_COLORS <= 256:
|
||||
mimg.quantizeColors(256)
|
||||
mimg.quantizeDither()
|
||||
mimg.quantize()
|
||||
|
||||
if MK_MONOCHROME:
|
||||
mimg.quantizeColorSpace(PythonMagick.ColorspaceType.GRAYColorspace)
|
||||
mimg.quantizeColors(2)
|
||||
mimg.quantizeDither()
|
||||
mimg.quantize()
|
||||
mimg.monochrome()
|
||||
elif MK_GRAYSCALE:
|
||||
mimg.quantizeColorSpace(PythonMagick.ColorspaceType.GRAYColorspace)
|
||||
if MK_COLORS > 0 and MK_COLORS < 256:
|
||||
mimg.quantizeColors(MK_COLORS)
|
||||
else:
|
||||
mimg.quantizeColors(256)
|
||||
mimg.quantizeDither()
|
||||
mimg.quantize()
|
||||
else:
|
||||
if MK_COLORS > 0:
|
||||
mimg.quantizeColors(MK_COLORS)
|
||||
if MK_DITHER:
|
||||
mimg.quantizeDither()
|
||||
mimg.quantize()
|
||||
|
||||
if FORMAT=="JPG":
|
||||
mimg.write(blob, "jpg")
|
||||
elif FORMAT=="PNG":
|
||||
mimg.write(blob, "png")
|
||||
elif FORMAT=="AUTO" or FORMAT=="GIF":
|
||||
mimg.write(blob, "gif")
|
||||
output = StringIO.StringIO()
|
||||
output.write(blob.data)
|
||||
else:
|
||||
if FORMAT=="AUTO" or FORMAT=="GIF":
|
||||
output.write(self.captureView(view).representationUsingType_properties_(
|
||||
AppKit.NSGIFFileType, None))
|
||||
elif FORMAT=="JPG":
|
||||
output.write(self.captureView(view).representationUsingType_properties_(
|
||||
AppKit.NSJPEGFileType, None))
|
||||
elif FORMAT=="PNG":
|
||||
output.write(self.captureView(view).representationUsingType_properties_(
|
||||
AppKit.NSPNGFileType, None))
|
||||
|
||||
RENDERS[WebkitLoad.req_img] = output
|
||||
|
||||
# url of the rendered page
|
||||
web_url = frame.dataSource().initialRequest().URL().absoluteString()
|
||||
|
||||
httpout = WebkitLoad.httpout
|
||||
|
||||
httpout.write("<!-- Web Rendering Proxy v%s by Antoni Sawicki -->\n"
|
||||
% (__version__))
|
||||
httpout.write("<!-- Request for [%s] frame [%s] -->\n"
|
||||
% (WebkitLoad.req_url, web_url))
|
||||
|
||||
domdocument = frame.DOMDocument()
|
||||
# Get title
|
||||
httpout.write("<HTML><HEAD>")
|
||||
httpout.write((u"<TITLE>%s</TITLE>"
|
||||
% domdocument.title()).encode('utf-8', errors='ignore'))
|
||||
httpout.write("</HEAD>\n<BODY>\n")
|
||||
|
||||
if AUTOWIDTH:
|
||||
httpout.write("<script>document.write('<span style=\"display: none;\"><img src=\"http://width-' + document.body.clientWidth + '-px.jpg\" width=\"0\" height=\"0\"></span>');</script>\n")
|
||||
|
||||
if ISMAP == True:
|
||||
httpout.write("<A HREF=\"http://%s\">"
|
||||
"<IMG SRC=\"http://%s\" ALT=\"wrp-render\" ISMAP>\n"
|
||||
"</A>\n" % (WebkitLoad.req_map, WebkitLoad.req_img))
|
||||
mapfile = StringIO.StringIO()
|
||||
mapfile.write("default %s\n" % (web_url))
|
||||
else:
|
||||
httpout.write("<IMG SRC=\"http://%s\" ALT=\"wrp-render\" USEMAP=\"#map\">\n"
|
||||
"<MAP NAME=\"map\">\n" % (WebkitLoad.req_img))
|
||||
|
||||
domnodelist = domdocument.getElementsByTagName_('A')
|
||||
i = 0
|
||||
while i < domnodelist.length():
|
||||
turl = domnodelist.item_(i).valueForKey_('href')
|
||||
#TODO: crashes? validate url? insert web_url if wrong?
|
||||
myrect = domnodelist.item_(i).boundingBox()
|
||||
|
||||
xmin = Foundation.NSMinX(myrect)
|
||||
ymin = Foundation.NSMinY(myrect)
|
||||
xmax = Foundation.NSMaxX(myrect)
|
||||
ymax = Foundation.NSMaxY(myrect)
|
||||
|
||||
if ISMAP == True:
|
||||
mapfile.write("rect %s %i,%i %i,%i\n".decode('utf-8', errors='ignore') % (turl, xmin, ymin, xmax, ymax))
|
||||
else:
|
||||
httpout.write("<AREA SHAPE=\"RECT\""
|
||||
" COORDS=\"%i,%i,%i,%i\""
|
||||
" ALT=\"%s\" HREF=\"%s\">\n".decode('utf-8', errors='ignore')
|
||||
% (xmin, ymin, xmax, ymax, turl, turl))
|
||||
|
||||
i += 1
|
||||
|
||||
if ISMAP != True:
|
||||
httpout.write("</MAP>\n")
|
||||
|
||||
httpout.write("</BODY>\n</HTML>\n")
|
||||
|
||||
if ISMAP == True:
|
||||
RENDERS[WebkitLoad.req_map] = mapfile
|
||||
|
||||
# Return to Proxy thread and Loop...
|
||||
RESP.put('')
|
||||
self.getURL(webview)
|
||||
|
||||
def main_cocoa():
|
||||
# Launch NS Application
|
||||
AppKit.NSApplicationLoad()
|
||||
app = AppKit.NSApplication.sharedApplication()
|
||||
delegate = AppDelegate.alloc().init()
|
||||
AppKit.NSApp().setDelegate_(delegate)
|
||||
AppKit.NSBundle.mainBundle().infoDictionary()['NSAppTransportSecurity'] = \
|
||||
dict(NSAllowsArbitraryLoads=True)
|
||||
rect = Foundation.NSMakeRect(-16000, -16000, 100, 100)
|
||||
win = AppKit.NSWindow.alloc()
|
||||
win.initWithContentRect_styleMask_backing_defer_(rect, AppKit.NSBorderlessWindowMask, 2, 0)
|
||||
webview = WebKit.WebView.alloc()
|
||||
webview.initWithFrame_(rect)
|
||||
webview.mainFrame().frameView().setAllowsScrolling_(objc.NO)
|
||||
webkit_version = Foundation.NSBundle.bundleForClass_(WebKit.WebView). \
|
||||
objectForInfoDictionaryKey_(WebKit.kCFBundleVersionKey)[1:]
|
||||
webview.setApplicationNameForUserAgent_("Like-Version/6.0 Safari/%s wrp/%s"
|
||||
% (webkit_version, __version__))
|
||||
win.setContentView_(webview)
|
||||
loaddelegate = WebkitLoad.alloc().init()
|
||||
loaddelegate.options = [""]
|
||||
webview.setFrameLoadDelegate_(loaddelegate)
|
||||
app.run()
|
||||
|
||||
#######################
|
||||
### COMMON CODEPATH ###
|
||||
#######################
|
||||
class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
req_url = self.path
|
||||
httpout = self.wfile
|
||||
|
||||
map_re = re.match(r"http://(wrp-\d+\.map).*?(\d+),(\d+)", req_url)
|
||||
wid_re = re.match(r"http://(width-[0-9]+-px\.jpg).*", req_url)
|
||||
gif_re = re.match(r"http://(wrp-\d+\.gif).*", req_url)
|
||||
jpg_re = re.match(r"http://(wrp-\d+\.jpg).*", req_url)
|
||||
png_re = re.match(r"http://(wrp-\d+\.png).*", req_url)
|
||||
|
||||
# Serve Rendered GIF
|
||||
if gif_re:
|
||||
img = gif_re.group(1)
|
||||
print ">>> request for rendered gif image... %s [%d kb]" \
|
||||
% (img, RENDERS[img].len/1024)
|
||||
self.send_response(200, 'OK')
|
||||
self.send_header('Content-type', 'image/gif')
|
||||
self.end_headers()
|
||||
httpout.write(RENDERS[img].getvalue())
|
||||
del RENDERS[img]
|
||||
|
||||
elif jpg_re:
|
||||
img = jpg_re.group(1)
|
||||
print ">>> request for rendered jpg image... %s [%d kb]" \
|
||||
% (img, RENDERS[img].len/1024)
|
||||
self.send_response(200, 'OK')
|
||||
self.send_header('Content-type', 'image/jpeg')
|
||||
self.end_headers()
|
||||
httpout.write(RENDERS[img].getvalue())
|
||||
del RENDERS[img]
|
||||
|
||||
elif png_re:
|
||||
img = png_re.group(1)
|
||||
print ">>> request for rendered png image... %s [%d kb]" \
|
||||
% (img, RENDERS[img].len/1024)
|
||||
self.send_response(200, 'OK')
|
||||
self.send_header('Content-type', 'image/png')
|
||||
self.end_headers()
|
||||
httpout.write(RENDERS[img].getvalue())
|
||||
del RENDERS[img]
|
||||
|
||||
elif wid_re:
|
||||
global WIDTH
|
||||
try:
|
||||
wid = req_url.split("-")
|
||||
WIDTH = int(wid[1])
|
||||
print ">>> width request: %d" % WIDTH
|
||||
except:
|
||||
print ">>> width request error" % WIDTH
|
||||
|
||||
self.send_error(404, "Width request")
|
||||
self.end_headers()
|
||||
|
||||
# Process ISMAP Request
|
||||
elif map_re:
|
||||
map = map_re.group(1)
|
||||
req_x = int(map_re.group(2))
|
||||
req_y = int(map_re.group(3))
|
||||
print ">>> ISMAP request... %s [%d,%d] " % (map, req_x, req_y)
|
||||
|
||||
mapf = RENDERS[map]
|
||||
mapf.seek(0)
|
||||
goto_url = "none"
|
||||
for line in mapf.readlines():
|
||||
if re.match(r"(\S+)", line).group(1) == "default":
|
||||
default_url = re.match(r"\S+\s+(\S+)", line).group(1)
|
||||
|
||||
elif re.match(r"(\S+)", line).group(1) == "rect":
|
||||
try:
|
||||
rect = re.match(r"(\S+)\s+(\S+)\s+(\d+),(\d+)\s+(\d+),(\d+)", line)
|
||||
min_x = int(rect.group(3))
|
||||
min_y = int(rect.group(4))
|
||||
max_x = int(rect.group(5))
|
||||
max_y = int(rect.group(6))
|
||||
if (req_x >= min_x) and \
|
||||
(req_x <= max_x) and \
|
||||
(req_y >= min_y) and \
|
||||
(req_y <= max_y):
|
||||
goto_url = rect.group(2)
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
if goto_url == "none":
|
||||
goto_url = default_url
|
||||
|
||||
print ">>> ISMAP redirect: %s\n" % (goto_url)
|
||||
|
||||
self.send_response(302, "Found")
|
||||
self.send_header("Location", goto_url)
|
||||
self.send_header("Content-type", "text/html")
|
||||
self.end_headers()
|
||||
httpout.write("<HTML><BODY><A HREF=\"%s\">%s</A></BODY></HTML>\n"
|
||||
% (goto_url, goto_url))
|
||||
|
||||
# Process a web page request and generate image
|
||||
else:
|
||||
print ">>> URL request... " + req_url
|
||||
|
||||
if req_url == "http://wrp.stop/" or req_url == "http://www.wrp.stop/":
|
||||
REQ.put((httpout, req_url, "", ""))
|
||||
RESP.get()
|
||||
else:
|
||||
reqst = urllib.urlopen(req_url)
|
||||
|
||||
if reqst.info().type == "text/html" or reqst.info().type == "application/xhtml+xml":
|
||||
# If an error occurs, send error headers to the requester
|
||||
if reqst.getcode() >= 400:
|
||||
self.send_response(reqst.getcode())
|
||||
for hdr in reqst.info():
|
||||
self.send_header(hdr, reqst.info()[hdr])
|
||||
self.end_headers()
|
||||
else:
|
||||
self.send_response(200, 'OK')
|
||||
self.send_header('Content-type', 'text/html')
|
||||
self.end_headers()
|
||||
|
||||
rnd = random.randrange(0, 1000)
|
||||
|
||||
if FORMAT == "GIF":
|
||||
req_extension = ".gif"
|
||||
elif FORMAT == "JPG":
|
||||
req_extension = ".jpg"
|
||||
elif FORMAT == "PNG":
|
||||
req_extension = ".png"
|
||||
elif (sys.platform.startswith('linux') or sys.platform.startswitch('freebsd')) and FORMAT == "AUTO":
|
||||
req_extension = ".jpg"
|
||||
elif sys.platform == "darwin" and FORMAT == "AUTO":
|
||||
req_extension = ".gif"
|
||||
|
||||
req_img = "wrp-%s%s" % (rnd, req_extension)
|
||||
req_map = "wrp-%s.map" % (rnd)
|
||||
|
||||
# To WebKit Thread
|
||||
REQ.put((httpout, req_url, req_img, req_map))
|
||||
# Wait for completition
|
||||
RESP.get()
|
||||
# If the requested file is not HTML or XHTML, just return it as is.
|
||||
else:
|
||||
self.send_response(reqst.getcode())
|
||||
for hdr in reqst.info():
|
||||
self.send_header(hdr, reqst.info()[hdr])
|
||||
self.end_headers()
|
||||
httpout.write(reqst.read())
|
||||
|
||||
def run_proxy():
|
||||
httpd = SocketServer.TCPServer(('', PORT), Proxy)
|
||||
print "Web Rendering Proxy v%s serving at port: %s" % (__version__, PORT)
|
||||
while 1:
|
||||
httpd.serve_forever()
|
||||
|
||||
def main():
|
||||
if(FORMAT != "AUTO" and FORMAT != "GIF" and FORMAT != "JPG" and FORMAT != "PNG"):
|
||||
sys.exit("Unsupported image format \"%s\". Exiting." % FORMAT)
|
||||
|
||||
if (sys.platform.startswith('linux') or sys.platform.startswith('freebsd')) and FORMAT == "GIF" and not HasMagick:
|
||||
sys.exit("GIF format is not supported on this platform. Exiting.")
|
||||
|
||||
# run traffic through sslstrip as a quick workaround for getting SSL webpages to work
|
||||
# NOTE: modern browsers are doing their best to stop this kind of 'attack'. Firefox
|
||||
# supports an about:config flag test.currentTimeOffsetSeconds(int) = 12000000, which
|
||||
# you can use to circumvent those checks.
|
||||
if SSLSTRIP:
|
||||
try:
|
||||
subprocess.check_output(["pidof", "sslstrip"])
|
||||
except:
|
||||
subprocess.Popen(["sslstrip"], stdout=open(os.devnull,'w'), stderr=subprocess.STDOUT) # runs on port 10000 by default
|
||||
QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy, "localhost", 10000))
|
||||
# Launch Proxy Thread
|
||||
threading.Thread(target=run_proxy).start()
|
||||
|
||||
if sys.platform.startswith('linux') or sys.platform.startswith('freebsd'):
|
||||
import signal
|
||||
try:
|
||||
import PyQt5.QtCore
|
||||
except ImportError:
|
||||
import PyQt4.QtCore
|
||||
# Initialize Qt-Application, but make this script
|
||||
# abortable via CTRL-C
|
||||
app = init_qtgui(display=None, style=None)
|
||||
signal.signal(signal.SIGINT, signal.SIG_DFL)
|
||||
|
||||
QTimer.singleShot(0, __main_qt)
|
||||
sys.exit(app.exec_())
|
||||
elif sys.platform == "darwin":
|
||||
main_cocoa()
|
||||
else:
|
||||
sys.exit("Unsupported platform: %s. Exiting." % sys.platform)
|
||||
|
||||
if __name__ == '__main__': main()
|
242
shtml.go
Normal file
242
shtml.go
Normal file
@ -0,0 +1,242 @@
|
||||
// WRP TXT / Simple HTML Mode Routines
|
||||
package main
|
||||
|
||||
// TODO:
|
||||
// - add image processing times counter to the footer
|
||||
// - img cache w/garbage collector / test back/button behavior in old browsers
|
||||
// - add referer header
|
||||
// - svg support
|
||||
// - incorrect cert support in both markdown and image download
|
||||
// - unify cdp and txt image handlers
|
||||
// - use goroutiness to process images
|
||||
// - get inner html from chromedp instead of html2markdown
|
||||
//
|
||||
// - BUG: DomainFromURL always prefixes with http instead of https
|
||||
// reproduces on vsi vms docs
|
||||
// - BUG: markdown table errors
|
||||
// reproduces on hacker news
|
||||
// - BUG: captcha errors using html to markdown, perhaps use cdp inner html + downloaded images
|
||||
// reproduces on https://www.cnn.com/cnn-underscored/electronics
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/gif"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
h2m "github.com/JohannesKaufmann/html-to-markdown"
|
||||
"github.com/JohannesKaufmann/html-to-markdown/plugin"
|
||||
"github.com/lithammer/shortuuid/v4"
|
||||
"github.com/nfnt/resize"
|
||||
"github.com/yuin/goldmark"
|
||||
"github.com/yuin/goldmark/ast"
|
||||
"github.com/yuin/goldmark/extension"
|
||||
"github.com/yuin/goldmark/parser"
|
||||
"github.com/yuin/goldmark/text"
|
||||
"github.com/yuin/goldmark/util"
|
||||
"golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
var imgStor imageStore
|
||||
|
||||
const imgZpfx = "/imgz/"
|
||||
|
||||
func init() {
|
||||
imgStor.img = make(map[string]imageContainer)
|
||||
}
|
||||
|
||||
type imageContainer struct {
|
||||
data []byte
|
||||
url string
|
||||
added time.Time
|
||||
}
|
||||
|
||||
type imageStore struct {
|
||||
img map[string]imageContainer
|
||||
sync.Mutex
|
||||
}
|
||||
|
||||
func (i *imageStore) add(id, url string, img []byte) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
i.img[id] = imageContainer{data: img, url: url, added: time.Now()}
|
||||
}
|
||||
|
||||
func (i *imageStore) get(id string) ([]byte, error) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
img, ok := i.img[id]
|
||||
if !ok {
|
||||
return nil, errors.New("not found")
|
||||
}
|
||||
return img.data, nil
|
||||
}
|
||||
|
||||
func (i *imageStore) del(id string) {
|
||||
i.Lock()
|
||||
defer i.Unlock()
|
||||
delete(i.img, id)
|
||||
}
|
||||
|
||||
func fetchImage(id, url, imgType string, maxSize, imgOpt int) (int, error) {
|
||||
log.Printf("Downloading IMGZ URL=%q for ID=%q", url, id)
|
||||
var in []byte
|
||||
var err error
|
||||
switch url[:4] {
|
||||
case "http":
|
||||
r, err := http.Get(url) // TODO: possibly set a header "referer" here
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("Error downloading %q: %v", url, err)
|
||||
}
|
||||
if r.StatusCode != http.StatusOK {
|
||||
return 0, fmt.Errorf("Error %q HTTP Status Code: %v", url, r.StatusCode)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
in, err = io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("Error reading %q: %v", url, err)
|
||||
}
|
||||
case "data":
|
||||
idx := strings.Index(url, ",")
|
||||
if idx < 1 {
|
||||
return 0, fmt.Errorf("image is embeded but unable to find coma: %q", url)
|
||||
}
|
||||
in, err = base64.StdEncoding.DecodeString(url[idx+1:])
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("error decoding image from url embed: %q: %v", url, err)
|
||||
}
|
||||
}
|
||||
out, err := smallImg(in, imgType, maxSize, imgOpt)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("Error scaling down image: %v", err)
|
||||
}
|
||||
imgStor.add(id, url, out)
|
||||
return len(out), nil
|
||||
}
|
||||
|
||||
func smallImg(src []byte, imgType string, maxSize, imgOpt int) ([]byte, error) {
|
||||
t := http.DetectContentType(src)
|
||||
var err error
|
||||
var img image.Image
|
||||
switch t {
|
||||
case "image/png":
|
||||
img, err = png.Decode(bytes.NewReader(src))
|
||||
case "image/gif":
|
||||
img, err = gif.Decode(bytes.NewReader(src))
|
||||
case "image/jpeg":
|
||||
img, err = jpeg.Decode(bytes.NewReader(src))
|
||||
case "image/webp":
|
||||
img, err = webp.Decode(bytes.NewReader(src))
|
||||
default: // TODO: also add svg
|
||||
err = errors.New("unknown content type: " + t)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("image decode problem: %v", err)
|
||||
}
|
||||
img = resize.Thumbnail(uint(maxSize), uint(maxSize), img, resize.NearestNeighbor)
|
||||
var outBuf bytes.Buffer
|
||||
switch imgType {
|
||||
case "png":
|
||||
err = png.Encode(&outBuf, img)
|
||||
case "gif":
|
||||
err = gif.Encode(&outBuf, gifPalette(img, int64(imgOpt)), &gif.Options{})
|
||||
case "jpg":
|
||||
err = jpeg.Encode(&outBuf, img, &jpeg.Options{Quality: imgOpt})
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gif encode problem: %v", err)
|
||||
}
|
||||
return outBuf.Bytes(), nil
|
||||
}
|
||||
|
||||
type astTransformer struct {
|
||||
imgType string
|
||||
maxSize int
|
||||
imgOpt int
|
||||
totSize int
|
||||
}
|
||||
|
||||
func (t *astTransformer) Transform(node *ast.Document, reader text.Reader, pc parser.Context) {
|
||||
ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
|
||||
if link, ok := n.(*ast.Link); ok && entering {
|
||||
link.Destination = append([]byte("/?m=html&t="+t.imgType+"&s="+strconv.Itoa(t.maxSize)+"&url="), link.Destination...)
|
||||
}
|
||||
if img, ok := n.(*ast.Image); ok && entering {
|
||||
seq := shortuuid.New() + "." + t.imgType
|
||||
size, err := fetchImage(seq, string(img.Destination), t.imgType, t.maxSize, t.imgOpt) // TODO: use goroutines with waitgroup
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
n.Parent().RemoveChildren(n)
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
img.Destination = []byte(imgZpfx + seq)
|
||||
t.totSize += size
|
||||
}
|
||||
return ast.WalkContinue, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (rq *wrpReq) captureMarkdown() {
|
||||
log.Printf("Processing Markdown conversion request for %v", rq.url)
|
||||
// TODO: bug - DomainFromURL always prefixes with http:// instead of https
|
||||
// this causes issues on some websites, fix or write a smarter DomainFromURL
|
||||
c := h2m.NewConverter(h2m.DomainFromURL(rq.url), true, nil)
|
||||
c.Use(plugin.GitHubFlavored())
|
||||
md, err := c.ConvertURL(rq.url) // We could also get inner html from chromedp
|
||||
if err != nil {
|
||||
http.Error(rq.w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
log.Printf("Got %v bytes md from %v", len(md), rq.url)
|
||||
var imgOpt int
|
||||
switch rq.imgType {
|
||||
case "jpg":
|
||||
imgOpt = int(rq.jQual)
|
||||
case "gif":
|
||||
imgOpt = int(rq.nColors)
|
||||
}
|
||||
t := &astTransformer{imgType: rq.imgType, maxSize: int(rq.maxSize), imgOpt: imgOpt}
|
||||
gm := goldmark.New(
|
||||
goldmark.WithExtensions(extension.GFM),
|
||||
goldmark.WithParserOptions(parser.WithASTTransformers(util.Prioritized(t, 100))),
|
||||
)
|
||||
var ht bytes.Buffer
|
||||
err = gm.Convert([]byte(md), &ht)
|
||||
if err != nil {
|
||||
http.Error(rq.w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
log.Printf("Rendered %v bytes html for %v", len(ht.String()), rq.url)
|
||||
rq.printUI(uiParams{
|
||||
text: string(asciify([]byte(ht.String()))),
|
||||
bgColor: "#FFFFFF",
|
||||
imgSize: fmt.Sprintf("%.0f KB", float32(t.totSize)/1024.0),
|
||||
})
|
||||
}
|
||||
|
||||
func imgServerTxt(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("%s IMGZ Request for %s", r.RemoteAddr, r.URL.Path)
|
||||
id := strings.Replace(r.URL.Path, imgZpfx, "", 1)
|
||||
img, err := imgStor.get(id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
log.Printf("%s IMGZ error for %s: %v", r.RemoteAddr, r.URL.Path, err)
|
||||
return
|
||||
}
|
||||
imgStor.del(id)
|
||||
w.Header().Set("Content-Type", http.DetectContentType(img))
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(img)))
|
||||
w.Write(img)
|
||||
w.(http.Flusher).Flush()
|
||||
}
|
89
util.go
Normal file
89
util.go
Normal file
@ -0,0 +1,89 @@
|
||||
// wrp utility functions
|
||||
package main
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color/palette"
|
||||
"log"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/MaxHalford/halfgone"
|
||||
"github.com/soniakeys/quant/median"
|
||||
)
|
||||
|
||||
func printMyIPs(b string) {
|
||||
ap := strings.Split(b, ":")
|
||||
if len(ap) < 1 {
|
||||
log.Fatal("Wrong format of ipaddress:port")
|
||||
}
|
||||
log.Printf("Listen address: %v", b)
|
||||
if ap[0] != "" && ap[0] != "0.0.0.0" {
|
||||
return
|
||||
}
|
||||
a, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
log.Print("Unable to get interfaces: ", err)
|
||||
return
|
||||
}
|
||||
var m string
|
||||
for _, i := range a {
|
||||
n, ok := i.(*net.IPNet)
|
||||
if !ok || n.IP.IsLoopback() || strings.Contains(n.IP.String(), ":") {
|
||||
continue
|
||||
}
|
||||
m = m + n.IP.String() + " "
|
||||
}
|
||||
log.Print("My IP addresses: ", m)
|
||||
}
|
||||
|
||||
func gifPalette(i image.Image, n int64) image.Image {
|
||||
switch n {
|
||||
case 2:
|
||||
i = halfgone.FloydSteinbergDitherer{}.Apply(halfgone.ImageToGray(i))
|
||||
case 216:
|
||||
var FastGifLut = [256]int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}
|
||||
r := i.Bounds()
|
||||
// NOTE: the color index computation below works only for palette.WebSafe!
|
||||
p := image.NewPaletted(r, palette.WebSafe)
|
||||
if i64, ok := i.(image.RGBA64Image); ok {
|
||||
for y := r.Min.Y; y < r.Max.Y; y++ {
|
||||
for x := r.Min.X; x < r.Max.X; x++ {
|
||||
c := i64.RGBA64At(x, y)
|
||||
r6 := FastGifLut[c.R>>8]
|
||||
g6 := FastGifLut[c.G>>8]
|
||||
b6 := FastGifLut[c.B>>8]
|
||||
p.SetColorIndex(x, y, uint8(36*r6+6*g6+b6))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for y := r.Min.Y; y < r.Max.Y; y++ {
|
||||
for x := r.Min.X; x < r.Max.X; x++ {
|
||||
c := i.At(x, y)
|
||||
r, g, b, _ := c.RGBA()
|
||||
r6 := FastGifLut[r&0xff]
|
||||
g6 := FastGifLut[g&0xff]
|
||||
b6 := FastGifLut[b&0xff]
|
||||
p.SetColorIndex(x, y, uint8(36*r6+6*g6+b6))
|
||||
}
|
||||
}
|
||||
}
|
||||
i = p
|
||||
default:
|
||||
q := median.Quantizer(n)
|
||||
i = q.Paletted(i)
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
func asciify(s []byte) []byte {
|
||||
a := make([]byte, len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] > 127 {
|
||||
a[i] = '.'
|
||||
continue
|
||||
}
|
||||
a[i] = s[i]
|
||||
}
|
||||
return a
|
||||
}
|
493
wrp.go
493
wrp.go
@ -1,8 +1,7 @@
|
||||
//
|
||||
// WRP - Web Rendering Proxy
|
||||
//
|
||||
// Copyright (c) 2013-2018 Antoni Sawicki
|
||||
// Copyright (c) 2019 Google LLC
|
||||
// Copyright (c) 2013-2025 Antoni Sawicki
|
||||
//
|
||||
|
||||
package main
|
||||
@ -10,307 +9,303 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"embed"
|
||||
"flag"
|
||||
"fmt"
|
||||
"image/gif"
|
||||
"image/png"
|
||||
"io"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/chromedp/cdproto/emulation"
|
||||
"github.com/chromedp/chromedp"
|
||||
"github.com/ericpauley/go-quantize/quantize"
|
||||
_ "github.com/breml/rootcerts"
|
||||
)
|
||||
|
||||
const version = "4.8.2"
|
||||
|
||||
var (
|
||||
addr = flag.String("l", ":8080", "Listen address:port, default :8080")
|
||||
headless = flag.Bool("h", true, "Headless mode / hide browser window (default true)")
|
||||
noDel = flag.Bool("n", false, "Do not free maps and images after use")
|
||||
defType = flag.String("t", "gif", "Image type: png|gif|jpg")
|
||||
wrpMode = flag.String("m", "ismap", "WRP Mode: ismap|html")
|
||||
defImgSize = flag.Int64("is", 200, "html mode default image size")
|
||||
defJpgQual = flag.Int64("q", 75, "Jpeg image quality, default 75%") // TODO: this should be form dropdown when jpeg is selected as image type
|
||||
fgeom = flag.String("g", "1152x600x216", "Geometry: width x height x colors, height can be 0 for unlimited")
|
||||
htmFnam = flag.String("ui", "wrp.html", "HTML template file for the UI")
|
||||
delay = flag.Duration("s", 2*time.Second, "Delay/sleep after page is rendered and before screenshot is taken")
|
||||
userAgent = flag.String("ua", "", "override chrome user agent")
|
||||
)
|
||||
|
||||
var (
|
||||
version = "4.2"
|
||||
srv http.Server
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
gifmap = make(map[string]bytes.Buffer)
|
||||
ismap = make(map[string]wrpReq)
|
||||
srv http.Server
|
||||
actx, ctx context.Context
|
||||
acncl, cncl context.CancelFunc
|
||||
img = make(map[string]bytes.Buffer)
|
||||
ismap = make(map[string]wrpReq)
|
||||
defGeom geom
|
||||
htmlTmpl *template.Template
|
||||
)
|
||||
|
||||
//go:embed *.html
|
||||
var fs embed.FS
|
||||
|
||||
type geom struct {
|
||||
w int64
|
||||
h int64
|
||||
c int64
|
||||
}
|
||||
|
||||
// TODO: there is a major overlap/duplication/triplication
|
||||
// between the 3 data structs, perhps we could reduce to just one?
|
||||
|
||||
// Data for html template
|
||||
type uiData struct {
|
||||
Version string
|
||||
WrpMode string
|
||||
URL string
|
||||
BgColor string
|
||||
NColors int64
|
||||
JQual int64
|
||||
Width int64
|
||||
Height int64
|
||||
Zoom float64
|
||||
ImgType string
|
||||
ImgURL string
|
||||
ImgSize string
|
||||
ImgWidth int
|
||||
ImgHeight int
|
||||
MaxSize int64
|
||||
MapURL string
|
||||
PageHeight string
|
||||
TeXT string
|
||||
}
|
||||
|
||||
// Parameters for HTML print function
|
||||
type uiParams struct {
|
||||
bgColor string
|
||||
pageHeight string
|
||||
imgSize string
|
||||
imgURL string
|
||||
mapURL string
|
||||
imgWidth int
|
||||
imgHeight int
|
||||
text string
|
||||
}
|
||||
|
||||
// WRP Request
|
||||
type wrpReq struct {
|
||||
U string // url
|
||||
W int64 // width
|
||||
H int64 // height
|
||||
S float64 // scale
|
||||
C int64 // #colors
|
||||
X int64 // mouseX
|
||||
Y int64 // mouseY
|
||||
K string // keys to send
|
||||
F string // Fn buttons
|
||||
url string
|
||||
width int64
|
||||
height int64
|
||||
zoom float64
|
||||
nColors int64
|
||||
jQual int64
|
||||
mouseX int64
|
||||
mouseY int64
|
||||
keys string
|
||||
buttons string
|
||||
imgType string
|
||||
wrpMode string
|
||||
maxSize int64
|
||||
w http.ResponseWriter
|
||||
r *http.Request
|
||||
}
|
||||
|
||||
func (w *wrpReq) parseForm(req *http.Request) {
|
||||
req.ParseForm()
|
||||
w.U = req.FormValue("url")
|
||||
if len(w.U) > 1 && !strings.HasPrefix(w.U, "http") {
|
||||
w.U = fmt.Sprintf("http://www.google.com/search?q=%s", url.QueryEscape(w.U))
|
||||
func (rq *wrpReq) parseForm() {
|
||||
rq.r.ParseForm()
|
||||
rq.wrpMode = rq.r.FormValue("m")
|
||||
if rq.wrpMode == "" {
|
||||
rq.wrpMode = *wrpMode
|
||||
}
|
||||
w.W, _ = strconv.ParseInt(req.FormValue("w"), 10, 64)
|
||||
if w.W < 10 {
|
||||
w.W = 1152
|
||||
rq.url = rq.r.FormValue("url")
|
||||
if len(rq.url) > 1 && !strings.HasPrefix(rq.url, "http") {
|
||||
rq.url = fmt.Sprintf("http://www.google.com/search?q=%s", url.QueryEscape(rq.url))
|
||||
}
|
||||
w.H, _ = strconv.ParseInt(req.FormValue("h"), 10, 64)
|
||||
if w.H < 10 {
|
||||
w.H = 600
|
||||
// TODO: implement atoiOrZero
|
||||
rq.width, _ = strconv.ParseInt(rq.r.FormValue("w"), 10, 64)
|
||||
rq.height, _ = strconv.ParseInt(rq.r.FormValue("h"), 10, 64)
|
||||
if rq.width < 10 && rq.height < 10 {
|
||||
rq.width = defGeom.w
|
||||
rq.height = defGeom.h
|
||||
}
|
||||
w.S, _ = strconv.ParseFloat(req.FormValue("s"), 64)
|
||||
if w.S < 0.1 {
|
||||
w.S = 1.0
|
||||
rq.zoom, _ = strconv.ParseFloat(rq.r.FormValue("z"), 64)
|
||||
if rq.zoom < 0.1 {
|
||||
rq.zoom = 1.0
|
||||
}
|
||||
w.C, _ = strconv.ParseInt(req.FormValue("c"), 10, 64)
|
||||
if w.C < 2 || w.C > 256 {
|
||||
w.C = 256
|
||||
rq.imgType = rq.r.FormValue("t")
|
||||
switch rq.imgType {
|
||||
case "png", "gif", "jpg":
|
||||
default:
|
||||
rq.imgType = *defType
|
||||
}
|
||||
w.K = req.FormValue("k")
|
||||
w.F = req.FormValue("Fn")
|
||||
log.Printf("%s WrpReq from Form: %+v\n", req.RemoteAddr, w)
|
||||
rq.nColors, _ = strconv.ParseInt(rq.r.FormValue("c"), 10, 64)
|
||||
if rq.nColors < 2 || rq.nColors > 256 {
|
||||
rq.nColors = defGeom.c
|
||||
}
|
||||
rq.jQual, _ = strconv.ParseInt(rq.r.FormValue("q"), 10, 64)
|
||||
if rq.jQual < 1 || rq.jQual > 100 {
|
||||
rq.jQual = *defJpgQual
|
||||
}
|
||||
rq.keys = rq.r.FormValue("k")
|
||||
rq.buttons = rq.r.FormValue("Fn")
|
||||
rq.maxSize, _ = strconv.ParseInt(rq.r.FormValue("s"), 10, 64)
|
||||
if rq.maxSize == 0 {
|
||||
rq.maxSize = *defImgSize
|
||||
}
|
||||
log.Printf("%s WrpReq from UI Form: %+v\n", rq.r.RemoteAddr, rq)
|
||||
}
|
||||
|
||||
func (w wrpReq) printPage(out http.ResponseWriter) {
|
||||
out.Header().Set("Cache-Control", "max-age=0")
|
||||
out.Header().Set("Expires", "-1")
|
||||
out.Header().Set("Pragma", "no-cache")
|
||||
out.Header().Set("Content-Type", "text/html")
|
||||
fmt.Fprintf(out, "<!-- Web Rendering Proxy Version %s -->\n", version)
|
||||
fmt.Fprintf(out, "<HTML>\n<HEAD><TITLE>WRP %s</TITLE></HEAD>\n<BODY BGCOLOR=\"#F0F0F0\">\n", w.U)
|
||||
fmt.Fprintf(out, "<FORM ACTION=\"/\" METHOD=\"POST\">\n")
|
||||
fmt.Fprintf(out, "<INPUT TYPE=\"TEXT\" NAME=\"url\" VALUE=\"%s\" SIZE=\"10\">", w.U)
|
||||
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" VALUE=\"Go\">\n")
|
||||
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"Bk\">\n")
|
||||
fmt.Fprintf(out, "W <INPUT TYPE=\"TEXT\" NAME=\"w\" VALUE=\"%d\" SIZE=\"4\"> \n", w.W)
|
||||
fmt.Fprintf(out, "H <INPUT TYPE=\"TEXT\" NAME=\"h\" VALUE=\"%d\" SIZE=\"4\"> \n", w.H)
|
||||
fmt.Fprintf(out, "S <INPUT TYPE=\"TEXT\" NAME=\"s\" VALUE=\"%1.2f\" SIZE=\"3\"> \n", w.S)
|
||||
fmt.Fprintf(out, "C <INPUT TYPE=\"TEXT\" NAME=\"c\" VALUE=\"%d\" SIZE=\"3\">\n", w.C)
|
||||
fmt.Fprintf(out, "K <INPUT TYPE=\"TEXT\" NAME=\"k\" VALUE=\"\" SIZE=\"4\"> \n")
|
||||
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"Bs\">\n")
|
||||
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"Rt\">\n")
|
||||
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"<\">\n")
|
||||
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"^\">\n")
|
||||
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\"v\">\n")
|
||||
fmt.Fprintf(out, "<INPUT TYPE=\"SUBMIT\" NAME=\"Fn\" VALUE=\">\" SIZE=\"1\">\n")
|
||||
fmt.Fprintf(out, "</FORM><BR>\n")
|
||||
}
|
||||
|
||||
func (w wrpReq) printFooter(out http.ResponseWriter) {
|
||||
fmt.Fprintf(out, "\n<P><A HREF=\"/?url=https://github.com/tenox7/wrp/&w=%d&h=%d&s=%1.2f&c=%d\">"+
|
||||
"Web Rendering Proxy Version %s</A> | <A HREF=\"/shutdown/\">Shutdown WRP</A></BODY>\n</HTML>\n", w.W, w.H, w.S, w.C, version)
|
||||
}
|
||||
|
||||
func pageServer(out http.ResponseWriter, req *http.Request) {
|
||||
log.Printf("%s Page Request for %s [%+v]\n", req.RemoteAddr, req.URL.Path, req.URL.RawQuery)
|
||||
var w wrpReq
|
||||
w.parseForm(req)
|
||||
|
||||
if len(w.U) > 4 {
|
||||
w.capture(req.RemoteAddr, out)
|
||||
} else {
|
||||
w.printPage(out)
|
||||
w.printFooter(out)
|
||||
func (rq *wrpReq) printUI(p uiParams) {
|
||||
rq.w.Header().Set("Cache-Control", "max-age=0")
|
||||
rq.w.Header().Set("Expires", "-1")
|
||||
rq.w.Header().Set("Pragma", "no-cache")
|
||||
rq.w.Header().Set("Content-Type", "text/html")
|
||||
if p.bgColor == "" {
|
||||
p.bgColor = "#FFFFFF"
|
||||
}
|
||||
}
|
||||
|
||||
func mapServer(out http.ResponseWriter, req *http.Request) {
|
||||
log.Printf("%s ISMAP Request for %s [%+v]\n", req.RemoteAddr, req.URL.Path, req.URL.RawQuery)
|
||||
w, ok := ismap[req.URL.Path]
|
||||
if !ok {
|
||||
fmt.Fprintf(out, "Unable to find map %s\n", req.URL.Path)
|
||||
log.Printf("Unable to find map %s\n", req.URL.Path)
|
||||
return
|
||||
data := uiData{
|
||||
Version: version,
|
||||
WrpMode: rq.wrpMode,
|
||||
URL: rq.url,
|
||||
BgColor: p.bgColor,
|
||||
Width: rq.width,
|
||||
Height: rq.height,
|
||||
NColors: rq.nColors,
|
||||
JQual: rq.jQual,
|
||||
Zoom: rq.zoom,
|
||||
MaxSize: rq.maxSize,
|
||||
ImgType: rq.imgType,
|
||||
ImgSize: p.imgSize,
|
||||
ImgWidth: p.imgWidth,
|
||||
ImgHeight: p.imgHeight,
|
||||
ImgURL: p.imgURL,
|
||||
MapURL: p.mapURL,
|
||||
PageHeight: p.pageHeight,
|
||||
TeXT: p.text,
|
||||
}
|
||||
defer delete(ismap, req.URL.Path)
|
||||
n, err := fmt.Sscanf(req.URL.RawQuery, "%d,%d", &w.X, &w.Y)
|
||||
if err != nil || n != 2 {
|
||||
fmt.Fprintf(out, "n=%d, err=%s\n", n, err)
|
||||
log.Printf("%s ISMAP n=%d, err=%s\n", req.RemoteAddr, n, err)
|
||||
return
|
||||
}
|
||||
log.Printf("%s WrpReq from ISMAP: %+v\n", req.RemoteAddr, w)
|
||||
if len(w.U) > 4 {
|
||||
w.capture(req.RemoteAddr, out)
|
||||
} else {
|
||||
w.printPage(out)
|
||||
w.printFooter(out)
|
||||
}
|
||||
}
|
||||
|
||||
func imgServer(out http.ResponseWriter, req *http.Request) {
|
||||
log.Printf("%s IMG Request for %s\n", req.RemoteAddr, req.URL.Path)
|
||||
gifbuf, ok := gifmap[req.URL.Path]
|
||||
if !ok || gifbuf.Bytes() == nil {
|
||||
fmt.Fprintf(out, "Unable to find image %s\n", req.URL.Path)
|
||||
log.Printf("Unable to find image %s\n", req.URL.Path)
|
||||
return
|
||||
}
|
||||
defer delete(gifmap, req.URL.Path)
|
||||
out.Header().Set("Content-Type", "image/gif")
|
||||
out.Header().Set("Content-Length", strconv.Itoa(len(gifbuf.Bytes())))
|
||||
out.Header().Set("Cache-Control", "max-age=0")
|
||||
out.Header().Set("Expires", "-1")
|
||||
out.Header().Set("Pragma", "no-cache")
|
||||
out.Write(gifbuf.Bytes())
|
||||
out.(http.Flusher).Flush()
|
||||
}
|
||||
|
||||
func (w wrpReq) capture(c string, out http.ResponseWriter) {
|
||||
var pngbuf []byte
|
||||
var gifbuf bytes.Buffer
|
||||
var err error
|
||||
|
||||
if w.X > 0 && w.Y > 0 {
|
||||
log.Printf("%s Mouse Click %d,%d\n", c, w.X, w.Y)
|
||||
err = chromedp.Run(ctx, chromedp.MouseClickXY(int64(float64(w.X)/w.S), int64(float64(w.Y)/w.S)))
|
||||
} else if len(w.F) > 0 {
|
||||
log.Printf("%s Button %v\n", c, w.F)
|
||||
switch w.F {
|
||||
case "Bk":
|
||||
err = chromedp.Run(ctx, chromedp.NavigateBack())
|
||||
case "Bs":
|
||||
err = chromedp.Run(ctx, chromedp.KeyEvent("\b"))
|
||||
case "Rt":
|
||||
err = chromedp.Run(ctx, chromedp.KeyEvent("\r"))
|
||||
case "<":
|
||||
err = chromedp.Run(ctx, chromedp.KeyEvent("\u0302"))
|
||||
case "^":
|
||||
err = chromedp.Run(ctx, chromedp.KeyEvent("\u0304"))
|
||||
case "v":
|
||||
err = chromedp.Run(ctx, chromedp.KeyEvent("\u0301"))
|
||||
case ">":
|
||||
err = chromedp.Run(ctx, chromedp.KeyEvent("\u0303"))
|
||||
}
|
||||
} else if len(w.K) > 0 {
|
||||
log.Printf("%s Sending Keys: %#v\n", c, w.K)
|
||||
err = chromedp.Run(ctx, chromedp.KeyEvent(w.K))
|
||||
} else {
|
||||
log.Printf("%s Processing Capture Request for %s\n", c, w.U)
|
||||
err = chromedp.Run(ctx,
|
||||
emulation.SetDeviceMetricsOverride(int64(float64(w.W)/w.S), int64(float64(w.H)/w.S), w.S, false),
|
||||
chromedp.Navigate(w.U),
|
||||
)
|
||||
}
|
||||
|
||||
err := htmlTmpl.Execute(rq.w, data)
|
||||
if err != nil {
|
||||
if err.Error() == "context canceled" {
|
||||
log.Printf("%s Contex cancelled, try again", c)
|
||||
fmt.Fprintf(out, "<BR>%s<BR> -- restarting, try again", err)
|
||||
ctx, cancel = chromedp.NewContext(context.Background())
|
||||
} else {
|
||||
log.Printf("%s %s", c, err)
|
||||
fmt.Fprintf(out, "<BR>%s<BR>", err)
|
||||
}
|
||||
return
|
||||
fmt.Fprintf(rq.w, "Error: %v", err)
|
||||
}
|
||||
|
||||
chromedp.Run(
|
||||
ctx, chromedp.Sleep(time.Second*2),
|
||||
chromedp.Location(&w.U),
|
||||
)
|
||||
log.Printf("%s Landed on: %s\n", c, w.U)
|
||||
w.printPage(out)
|
||||
|
||||
// Process Screenshot Image
|
||||
err = chromedp.Run(ctx, chromedp.CaptureScreenshot(&pngbuf))
|
||||
if err != nil {
|
||||
log.Printf("%s Failed to capture screenshot: %s\n", c, err)
|
||||
fmt.Fprintf(out, "<BR>Unable to capture screenshot:<BR>%s<BR>\n", err)
|
||||
return
|
||||
}
|
||||
bytes.NewReader(pngbuf).Seek(0, 0)
|
||||
img, err := png.Decode(bytes.NewReader(pngbuf))
|
||||
if err != nil {
|
||||
log.Printf("%s Failed to decode screenshot: %s\n", c, err)
|
||||
fmt.Fprintf(out, "<BR>Unable to decode page screenshot:<BR>%s<BR>\n", err)
|
||||
return
|
||||
}
|
||||
gifbuf.Reset()
|
||||
err = gif.Encode(&gifbuf, img, &gif.Options{NumColors: int(w.C), Quantizer: quantize.MedianCutQuantizer{}})
|
||||
if err != nil {
|
||||
log.Printf("%s Failed to encode GIF: %s\n", c, err)
|
||||
fmt.Fprintf(out, "<BR>Unable to encode GIF:<BR>%s<BR>\n", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Compose map and gif
|
||||
seq := rand.Intn(9999)
|
||||
imgpath := fmt.Sprintf("/img/%04d.gif", seq)
|
||||
mappath := fmt.Sprintf("/map/%04d.map", seq)
|
||||
gifmap[imgpath] = gifbuf
|
||||
ismap[mappath] = w
|
||||
log.Printf("%s Encoded GIF image: %s, Size: %dKB, Colors: %d\n", c, imgpath, len(gifbuf.Bytes())/1024, w.C)
|
||||
fmt.Fprintf(out, "<A HREF=\"%s\"><IMG SRC=\"%s\" BORDER=\"0\" ISMAP></A>", mappath, imgpath)
|
||||
w.printFooter(out)
|
||||
log.Printf("%s Done with caputure for %s\n", c, w.U)
|
||||
}
|
||||
|
||||
func haltServer(out http.ResponseWriter, req *http.Request) {
|
||||
log.Printf("%s Shutdown Request for %s\n", req.RemoteAddr, req.URL.Path)
|
||||
out.Header().Set("Cache-Control", "max-age=0")
|
||||
out.Header().Set("Expires", "-1")
|
||||
out.Header().Set("Pragma", "no-cache")
|
||||
out.Header().Set("Content-Type", "text/text")
|
||||
fmt.Fprintf(out, "Shutting down WRP...\n")
|
||||
out.(http.Flusher).Flush()
|
||||
func pageServer(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("%s Page Request for %s [%+v]\n", r.RemoteAddr, r.URL.Path, r.URL.RawQuery)
|
||||
rq := wrpReq{
|
||||
r: r,
|
||||
w: w,
|
||||
}
|
||||
rq.parseForm()
|
||||
if len(rq.url) < 4 {
|
||||
rq.printUI(uiParams{bgColor: "#FFFFFF"})
|
||||
return
|
||||
}
|
||||
rq.navigate() // TODO: if error from navigate do not capture
|
||||
if rq.wrpMode == "html" {
|
||||
rq.captureMarkdown()
|
||||
return
|
||||
}
|
||||
rq.captureScreenshot()
|
||||
}
|
||||
|
||||
func haltServer(w http.ResponseWriter, r *http.Request) {
|
||||
log.Printf("%s Shutdown Request for %s\n", r.RemoteAddr, r.URL.Path)
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
fmt.Fprintf(w, "Shutting down WRP...\n")
|
||||
w.(http.Flusher).Flush()
|
||||
time.Sleep(time.Second * 2)
|
||||
cancel()
|
||||
cncl()
|
||||
acncl()
|
||||
srv.Shutdown(context.Background())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func wrpTemplate(t string) string {
|
||||
var tmpl []byte
|
||||
fh, err := os.Open(t)
|
||||
if err != nil {
|
||||
goto builtin
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
tmpl, err = io.ReadAll(fh)
|
||||
if err != nil {
|
||||
goto builtin
|
||||
}
|
||||
log.Printf("Got HTML UI template from %v file, size %v \n", t, len(tmpl))
|
||||
return string(tmpl)
|
||||
|
||||
builtin:
|
||||
fhs, err := fs.Open("wrp.html")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer fhs.Close()
|
||||
|
||||
tmpl, err = io.ReadAll(fhs)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Printf("Got HTML UI template from embed\n")
|
||||
return string(tmpl)
|
||||
}
|
||||
|
||||
func main() {
|
||||
var addr string
|
||||
var head, headless bool
|
||||
var debug bool
|
||||
flag.StringVar(&addr, "l", ":8080", "Listen address:port, default :8080")
|
||||
flag.BoolVar(&head, "h", false, "Headed mode - display browser window")
|
||||
flag.BoolVar(&debug, "d", false, "Debug ChromeDP")
|
||||
var err error
|
||||
log.SetFlags(log.LstdFlags | log.Lshortfile)
|
||||
flag.Parse()
|
||||
if head {
|
||||
headless = false
|
||||
} else {
|
||||
headless = true
|
||||
log.Printf("Web Rendering Proxy Version %s (%v)\n", version, runtime.GOARCH)
|
||||
log.Printf("Using embedded ca-certs from github.com/breml/rootcerts")
|
||||
log.Printf("Args: %q", os.Args)
|
||||
if len(os.Getenv("PORT")) > 0 {
|
||||
*addr = ":" + os.Getenv(("PORT"))
|
||||
}
|
||||
opts := append(chromedp.DefaultExecAllocatorOptions[:],
|
||||
chromedp.Flag("headless", headless),
|
||||
chromedp.Flag("hide-scrollbars", false),
|
||||
)
|
||||
actx, acancel := chromedp.NewExecAllocator(context.Background(), opts...)
|
||||
defer acancel()
|
||||
if debug {
|
||||
ctx, cancel = chromedp.NewContext(actx, chromedp.WithDebugf(log.Printf))
|
||||
} else {
|
||||
ctx, cancel = chromedp.NewContext(actx)
|
||||
printMyIPs(*addr)
|
||||
n, err := fmt.Sscanf(*fgeom, "%dx%dx%d", &defGeom.w, &defGeom.h, &defGeom.c)
|
||||
if err != nil || n != 3 {
|
||||
log.Fatalf("Unable to parse -g geometry flag / %s", err)
|
||||
}
|
||||
defer cancel()
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
cncl, acncl = chromedpStart()
|
||||
defer cncl()
|
||||
defer acncl()
|
||||
|
||||
c := make(chan os.Signal)
|
||||
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-c
|
||||
log.Printf("Interrupt - shutting down.")
|
||||
cancel()
|
||||
cncl()
|
||||
acncl()
|
||||
srv.Shutdown(context.Background())
|
||||
os.Exit(1)
|
||||
}()
|
||||
|
||||
http.HandleFunc("/", pageServer)
|
||||
http.HandleFunc("/map/", mapServer)
|
||||
http.HandleFunc("/img/", imgServer)
|
||||
http.HandleFunc("/img/", imgServerMap)
|
||||
http.HandleFunc(imgZpfx, imgServerTxt)
|
||||
http.HandleFunc("/shutdown/", haltServer)
|
||||
http.HandleFunc("/favicon.ico", http.NotFound)
|
||||
log.Printf("Web Rendering Proxy Version %s\n", version)
|
||||
log.Printf("Starting WRP http server on %s\n", addr)
|
||||
srv.Addr = addr
|
||||
err := srv.ListenAndServe()
|
||||
|
||||
log.Printf("Default Img Type: %v, Geometry: %+v", *defType, defGeom)
|
||||
|
||||
htmlTmpl, err = template.New("wrp.html").Parse(wrpTemplate(*htmFnam))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
log.Print("Starting WRP http server")
|
||||
srv.Addr = *addr
|
||||
err = srv.ListenAndServe()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
86
wrp.html
Normal file
86
wrp.html
Normal file
@ -0,0 +1,86 @@
|
||||
<HTML>
|
||||
<HEAD>
|
||||
<TITLE>WRP {{.URL}}</TITLE>
|
||||
</HEAD>
|
||||
<BODY BGCOLOR="{{.BgColor}}">
|
||||
<FORM ACTION="/" METHOD="POST">
|
||||
<INPUT TYPE="TEXT" NAME="url" VALUE="{{.URL}}" SIZE="20">
|
||||
<INPUT TYPE="SUBMIT" VALUE="Go">
|
||||
{{ if eq .WrpMode "ismap" }}
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="Bk">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="St">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="Re">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="Up">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="Dn">
|
||||
W <INPUT TYPE="TEXT" NAME="w" VALUE="{{.Width}}" SIZE="4">
|
||||
H <INPUT TYPE="TEXT" NAME="h" VALUE="{{.Height}}" SIZE="4">
|
||||
{{ end }}
|
||||
{{ if eq .WrpMode "html" }}
|
||||
S <INPUT TYPE="TEXT" NAME="s" VALUE="{{.MaxSize}}" SIZE="4">
|
||||
{{ end }}
|
||||
{{ if eq .WrpMode "ismap" }}
|
||||
Z <SELECT NAME="z">
|
||||
<OPTION DISABLED>Zoom</OPTION>
|
||||
<OPTION VALUE="0.7" {{ if eq .Zoom 0.7}}SELECTED{{end}}>0.7 x</OPTION>
|
||||
<OPTION VALUE="0.8" {{ if eq .Zoom 0.8}}SELECTED{{end}}>0.8 x</OPTION>
|
||||
<OPTION VALUE="0.9" {{ if eq .Zoom 0.9}}SELECTED{{end}}>0.9 x</OPTION>
|
||||
<OPTION VALUE="1.0" {{ if eq .Zoom 1.0}}SELECTED{{end}}>1.0 x</OPTION>
|
||||
<OPTION VALUE="1.1" {{ if eq .Zoom 1.1}}SELECTED{{end}}>1.1 x</OPTION>
|
||||
<OPTION VALUE="1.2" {{ if eq .Zoom 1.2}}SELECTED{{end}}>1.2 x</OPTION>
|
||||
<OPTION VALUE="1.3" {{ if eq .Zoom 1.3}}SELECTED{{end}}>1.3 x</OPTION>
|
||||
</SELECT>
|
||||
{{ end }}
|
||||
M <SELECT NAME="m">
|
||||
<OPTION DISABLED>Mode</OPTION>
|
||||
<OPTION VALUE="ismap" {{ if eq .WrpMode "ismap"}}SELECTED{{end}}>ISMAP</OPTION>
|
||||
<OPTION VALUE="html" {{ if eq .WrpMode "html"}}SELECTED{{end}}>HTML</OPTION>
|
||||
</SELECT>
|
||||
T <SELECT NAME="t">
|
||||
<OPTION DISABLED>Type</OPTION>
|
||||
<OPTION VALUE="png" {{ if eq .ImgType "png"}}SELECTED{{end}}>PNG</OPTION>
|
||||
<OPTION VALUE="gif" {{ if eq .ImgType "gif"}}SELECTED{{end}}>GIF</OPTION>
|
||||
<OPTION VALUE="jpg" {{ if eq .ImgType "jpg"}}SELECTED{{end}}>JPG</OPTION>
|
||||
</SELECT>
|
||||
{{ if eq .ImgType "gif" }}
|
||||
C <SELECT NAME="c">
|
||||
<OPTION DISABLED>Ncol</OPTION>
|
||||
<OPTION VALUE="256" {{ if eq .NColors 256}}SELECTED{{end}}>256</OPTION>
|
||||
<OPTION VALUE="216" {{ if eq .NColors 216}}SELECTED{{end}}>216</OPTION>
|
||||
<OPTION VALUE="128" {{ if eq .NColors 128}}SELECTED{{end}}>128</OPTION>
|
||||
<OPTION VALUE="64" {{ if eq .NColors 64}}SELECTED{{end}}>64</OPTION>
|
||||
<OPTION VALUE="16" {{ if eq .NColors 16}}SELECTED{{end}}>16</OPTION>
|
||||
<OPTION VALUE="2" {{ if eq .NColors 2}}SELECTED{{end}}>2</OPTION>
|
||||
</SELECT>
|
||||
{{ end }}
|
||||
{{ if eq .ImgType "jpg" }}
|
||||
Q <INPUT TYPE="TEXT" NAME="q" VALUE="{{.JQual}}" SIZE="2">%
|
||||
{{ end }}
|
||||
{{ if eq .WrpMode "ismap" }}
|
||||
K <INPUT TYPE="TEXT" NAME="k" VALUE="" SIZE="4">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="Bs">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="Rt"><!--
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="All">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="<">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="^">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE="v">
|
||||
<INPUT TYPE="SUBMIT" NAME="Fn" VALUE=">" SIZE="1">-->
|
||||
{{ end }}
|
||||
</FORM>
|
||||
<BR>
|
||||
{{if .ImgURL}}
|
||||
<A HREF="{{.MapURL}}">
|
||||
<IMG SRC="{{.ImgURL}}" BORDER="0" ALT="Url: {{.URL}}, Size: {{.ImgSize}} PageHeight: {{.PageHeight}}" WIDTH="{{.ImgWidth}}" HEIGHT="{{.ImgHeight}}" ISMAP>
|
||||
</A>
|
||||
<P>
|
||||
{{end}}
|
||||
{{.TeXT}}
|
||||
<FONT SIZE="-2">
|
||||
<A HREF="/?url=https://github.com/tenox7/wrp/&w={{.Width}}&h={{.Height}}&s={{printf "%.1f" .Zoom}}&c={{.NColors}}&t={{.ImgType}}">Web Rendering Proxy {{.Version}}</A> |
|
||||
<A HREF="/shutdown/">Shutdown WRP</A> |
|
||||
{{ if eq .WrpMode "ismap" }}
|
||||
<A HREF="/">Page Height: {{.PageHeight}}</A> |
|
||||
<A HREF="/">Img Size: {{.ImgSize}}</A>
|
||||
{{end}}
|
||||
</FONT>
|
||||
</BODY>
|
||||
</HTML>
|
Loading…
x
Reference in New Issue
Block a user