all repos — albus-go @ f2f3f8a2cb36a51b320c4ab3470cc16a75367941

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}
17
18func SplitFilename(filename string) (name, ext string) {
19	ext = strings.ToLower(filepath.Ext(filename))
20	name = filename[:len(filename)-len(ext)]
21	return name, ext
22}
23
24func JoinFilename(name, ext string) string {
25	if len(ext) > 0 && ext[0] != '.' {
26		ext = "." + ext
27	}
28	return name + ext
29}
30
31func DownloadFile(filePath string, url string) error {
32	resp, err := http.Get(url)
33	if err != nil {
34		return err
35	}
36	defer resp.Body.Close()
37
38	out, err := os.Create(filePath)
39	if err != nil {
40		return err
41	}
42	defer out.Close()
43
44	_, err = io.Copy(out, resp.Body)
45	return err
46}
47
48func ConvertFile(inputFile string) (string, string) {
49	fileName, fileExtension := SplitFilename(inputFile)
50
51	outputExtension, exists := conversionMap[fileExtension]
52	if !exists {
53		println("Error. Format not supported:", fileExtension)
54		return "", ""
55	}
56
57	outputFile := JoinFilename(fileName, outputExtension)
58	println("Converting...")
59	cmd := exec.Command("pandoc", inputFile, "--pdf-engine=tectonic", "-o", outputFile)
60
61	output, err := cmd.CombinedOutput()
62	if err != nil {
63		println("Error. Command execution failed:", err)
64		return "", ""
65	}
66	println(output)
67	return fileName, outputExtension
68}