]> Sergey Matveev's repositories - tofuproxy.git/blob - rounds/transcodeJXL.go
Raised copyright years
[tofuproxy.git] / rounds / transcodeJXL.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
30         "go.stargrave.org/tofuproxy/fifos"
31 )
32
33 func transcodeCmd2Png(
34         contentType, ext, cmdName string,
35         resp *http.Response,
36         w http.ResponseWriter,
37         req *http.Request,
38 ) (bool, error) {
39         if resp.Header.Get("Content-Type") != contentType {
40                 return true, nil
41         }
42         tmpFd, err := ioutil.TempFile("", "tofuproxy.*."+ext)
43         if err != nil {
44                 log.Fatalln(err)
45         }
46         defer os.Remove(tmpFd.Name())
47         defer tmpFd.Close()
48         defer resp.Body.Close()
49         if _, err = io.Copy(tmpFd, resp.Body); err != nil {
50                 log.Printf("Error during %s: %+v\n", req.URL, err)
51                 return false, err
52         }
53         tmpFd.Close()
54         dstFn := tmpFd.Name() + ".png"
55         cmd := exec.Command(cmdName, tmpFd.Name(), dstFn)
56         err = cmd.Run()
57         defer os.Remove(dstFn)
58         if err != nil {
59                 return false, err
60         }
61         data, err := ioutil.ReadFile(dstFn)
62         if err != nil {
63                 return false, err
64         }
65         w.Header().Add("Content-Type", "image/png")
66         w.WriteHeader(http.StatusOK)
67         w.Write(data)
68         fifos.LogVarious <- fmt.Sprintf(
69                 "%s %s\t%s transcoded to PNG", req.Method, req.URL, contentType,
70         )
71         return false, nil
72 }
73
74 func RoundTranscodeJXL(
75         host string,
76         resp *http.Response,
77         w http.ResponseWriter,
78         req *http.Request,
79 ) (bool, error) {
80         return transcodeCmd2Png("image/jxl", "jxl", "djxl", resp, w, req)
81 }