utils.go (view raw)
1package main
2
3import (
4 "io"
5 "net/http"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10)
11
12var conversionMap = map[string]string{
13 ".docx": ".pdf",
14 ".odt": ".pdf",
15 ".epub": ".html",
16 ".md": ".pdf",
17}
18
19func SplitFilename(filename string) (name, ext string) {
20 ext = strings.ToLower(filepath.Ext(filename))
21 name = filename[:len(filename)-len(ext)]
22 return name, ext
23}
24
25func JoinFilename(name, ext string) string {
26 if len(ext) > 0 && ext[0] != '.' {
27 ext = "." + ext
28 }
29 return name + ext
30}
31
32func DownloadFile(filePath string, url string) error {
33 resp, err := http.Get(url)
34 if err != nil {
35 return err
36 }
37 defer resp.Body.Close()
38
39 out, err := os.Create(filePath)
40 if err != nil {
41 return err
42 }
43 defer out.Close()
44
45 _, err = io.Copy(out, resp.Body)
46 return err
47}
48
49func ConvertFile(inputFile string) (string, string) {
50 fileName, fileExtension := SplitFilename(inputFile)
51
52 outputExtension, exists := conversionMap[fileExtension]
53 if !exists {
54 println("Error. Format not supported:", fileExtension)
55 return "", ""
56 }
57
58 outputFile := JoinFilename(fileName, outputExtension)
59 println("Converting...")
60 cmd := exec.Command("pandoc", inputFile, "--pdf-engine=tectonic", "-o", outputFile)
61
62 output, err := cmd.CombinedOutput()
63 if err != nil {
64 println("Error. Command execution failed:", err)
65 return "", ""
66 }
67 println(output)
68 return fileName, outputExtension
69}