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