forked from mindoc-org/mindoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import.go
118 lines (88 loc) · 2.17 KB
/
import.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package converter
import (
"errors"
"github.com/lifei6671/mindoc/utils"
"os"
"path/filepath"
"crypto/md5"
"io"
"fmt"
"os/exec"
"github.com/lifei6671/mindoc/utils/ziptil"
"io/ioutil"
"encoding/xml"
)
type ResolveResult struct {
}
type XmlResult struct {
XMLName xml.Name `xml:"ncx"`
Head XmlHead `xml:"head"`
NavMap XmlTocNavMap `xml:"navMap"`
Title string `xml:"docTitle>text"`
}
type XmlHead struct {
XMLName xml.Name `xml:"head"`
Meta []XmlMeta `xml:"meta"`
}
type XmlMeta struct {
XMLName xml.Name `xml:"meta"`
Content string `xml:"content,attr"`
Name string `xml:"name,attr"`
}
type XmlDocTitle struct {
Text string `xml:"text"`
}
type XmlTocNavMap struct {
XMLName xml.Name `xml:"navMap"`
NavPoint []XmlNavPoint `xml:"navPoint"`
}
type XmlNavPoint struct {
XMLName xml.Name `xml:"navPoint"`
Content XmlContent `xml:"content"`
NavLabel string `xml:"navLabel>text"`
}
type XmlContent struct {
XMLName xml.Name `xml:"content"`
Src string `xml:"src,attr"`
}
type XmlNavLabel struct {
}
func Resolve(p string) (ResolveResult,error) {
result := ResolveResult{
}
if !utils.FileExists(p) {
return result,errors.New("文件不存在 " + p)
}
w := md5.New()
io.WriteString(w, p) //将str写入到w中
md5str := fmt.Sprintf("%x", w.Sum(nil)) //w.Sum(nil)将w的hash转成[]byte格式
tempPath := filepath.Join(os.TempDir(),md5str)
os.MkdirAll(tempPath,0766)
epub := filepath.Join(tempPath , "book.epub")
args := []string{p,epub}
cmd := exec.Command(ebookConvert, args...)
if err := cmd.Run(); err != nil {
fmt.Println("执行转换命令失败:" + err.Error())
return result,err
}
fmt.Println(epub)
unzipPath := filepath.Join(tempPath,"output")
if err := ziptil.Unzip(epub, unzipPath); err != nil {
fmt.Println("解压缩失败:" + err.Error())
return result,err
}
xmlPath := filepath.Join(unzipPath,"toc.ncx")
data,err := ioutil.ReadFile(xmlPath);
if err != nil {
fmt.Println("toc.ncx 文件不存在:" + err.Error())
return result,err
}
v := XmlResult{}
err = xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Println("解析XML失败:" + err.Error())
return result,err
}
fmt.Println(v)
return result,nil
}