forked from sajari/docconv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoc.go
90 lines (77 loc) · 1.78 KB
/
doc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
"time"
)
// Convert MS Word DOC
func ConvertDoc(r io.Reader) (string, map[string]string) {
f, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
log.Println("TempFile:", err)
}
defer os.Remove(f.Name())
io.Copy(f, r)
// Meta data
mc := make(chan map[string]string, 1)
go func() {
meta := make(map[string]string)
metaStr, err := exec.Command("wvSummary", f.Name()).Output()
if err != nil {
log.Println("wvSummary:", err)
}
// Parse meta output
info := make(map[string]string)
for _, line := range strings.Split(string(metaStr), "\n") {
if parts := strings.SplitN(line, "=", 2); len(parts) > 1 {
info[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
}
// Convert parsed meta
if tmp, ok := info["Last Modified"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := info["Created"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
mc <- meta
}()
// Document body
bc := make(chan string, 1)
go func() {
// Save output to a file
outputFile, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
log.Println("TempFile Out:", err)
return
}
defer os.Remove(outputFile.Name())
err = exec.Command("wvText", f.Name(), outputFile.Name()).Run()
if err != nil {
log.Println("wvText:", err)
}
var buf bytes.Buffer
_, err = buf.ReadFrom(outputFile)
if err != nil {
log.Println("wvText:", err)
}
bc <- buf.String()
}()
body := <-bc
meta := <-mc
if len(body) == 0 {
f.Seek(0, 0)
return ConvertDocx(f)
}
return body, meta
}