]> Sergey Matveev's repositories - tofuproxy.git/blob - rounds/transcodeWebP.go
Raised copyright years
[tofuproxy.git] / rounds / transcodeWebP.go
1 /*
2 tofuproxy -- flexible HTTP/HTTPS proxy, TLS terminator, X.509 TOFU
3              manager, WARC/geminispace browser
4 Copyright (C) 2021-2022 Sergey Matveev <stargrave@stargrave.org>
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, version 3 of the License.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package rounds
20
21 import (
22         "fmt"
23         "io"
24         "io/ioutil"
25         "log"
26         "net/http"
27         "os"
28         "os/exec"
29         "strings"
30
31         "go.stargrave.org/tofuproxy/fifos"
32 )
33
34 const CmdDWebP = "dwebp"
35
36 func isXombrero(req *http.Request) bool {
37         return strings.Contains(req.Header.Get("User-Agent"), "AppleWebKit/538.15")
38 }
39
40 func RoundTranscodeWebP(
41         host string,
42         resp *http.Response,
43         w http.ResponseWriter,
44         req *http.Request,
45 ) (bool, error) {
46         if resp.Header.Get("Content-Type") != "image/webp" || isXombrero(req) {
47                 return true, nil
48         }
49         tmpFd, err := ioutil.TempFile("", "tofuproxy.*.webp")
50         if err != nil {
51                 log.Fatalln(err)
52         }
53         defer os.Remove(tmpFd.Name())
54         defer tmpFd.Close()
55         defer resp.Body.Close()
56         if _, err = io.Copy(tmpFd, resp.Body); err != nil {
57                 log.Printf("Error during %s: %+v\n", req.URL, err)
58                 return false, err
59         }
60         tmpFd.Close()
61         cmd := exec.Command(CmdDWebP, tmpFd.Name(), "-o", "-")
62         data, err := cmd.Output()
63         if err != nil {
64                 return false, err
65         }
66         w.Header().Add("Content-Type", "image/png")
67         w.WriteHeader(http.StatusOK)
68         w.Write(data)
69         fifos.LogVarious <- fmt.Sprintf("%s %s\tWebP transcoded to PNG", req.Method, req.URL)
70         return false, nil
71 }