/
compression.go
450 lines (404 loc) · 10.2 KB
/
compression.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package controllers
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"errors"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/astaxie/beego"
"github.com/simonblowsnow/mm-wiki-ex/app/utils"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
// "github.com/astaxie/beego/logs"
)
// 实现多态
type FileReader interface {
Reader() *tar.Reader
IsDir() bool
Copy(fw *os.File) (int64, error)
}
type GzFileReader struct {
reader *gzip.Reader
file *tar.Reader
info os.FileInfo
}
type ComFileReader struct {
reader *os.File
file *zip.File
}
func (g *GzFileReader) Reader() *tar.Reader {
return tar.NewReader(g.reader)
}
func (c *ComFileReader) Reader() *tar.Reader {
return tar.NewReader(c.reader)
}
func (g *GzFileReader) IsDir() bool {
return g.info.IsDir()
}
func (c *ComFileReader) IsDir() bool {
return c.file.FileInfo().IsDir()
}
func (g *GzFileReader) Copy(fw *os.File) (int64, error) {
return io.Copy(fw, g.file)
}
func (c *ComFileReader) Copy(fw *os.File) (int64, error) {
f, err := c.file.Open()
if err != nil {
return 0, errors.New("Open File Error")
}
defer f.Close()
return io.Copy(fw, f)
}
// decoder := mahonia.NewDecoder("gbk").ConvertString(s)
type FileList struct {
Names []string `json: names`
Types []int `json: types`
}
func (fl *FileList) setValue(i int, fi os.FileInfo, name string) {
fl.Names[i] = name
fl.Types[i] = 0
if fi.IsDir() {
fl.Types[i] = 1
}
}
// 因无法提前得知数组长度,只能通过动态添加方式
func (fl *FileList) setValueD(fi os.FileInfo, name string) {
fl.Names = append(fl.Names, name)
if fi == nil {
fl.Types = append(fl.Types, 0)
return
}
isDir := 0
if fi.IsDir() {
isDir = 1
}
fl.Types = append(fl.Types, isDir)
}
func newFileList(count int) FileList {
names := make([]string, count)
types := make([]int, count)
return FileList{Names: names, Types: types}
}
type Compressor struct {
pageFile string
path string
name string
ext string
folder string
fileRoot string
serveRoot string
exist bool
docType int
}
func CreateCompressor(pageFile string) *Compressor {
absPath := utils.Document.GetAbsPageFileByPageFile(pageFile)
ext := strings.ToLower(path.Ext(pageFile))
_, filename := filepath.Split(pageFile)
return &Compressor{
pageFile: pageFile,
path: absPath,
name: filename,
ext: ext,
exist: false,
}
}
func (c *Compressor) GetName(pageFile string, ext string, filename string) string {
if ext == "" {
ext = strings.ToLower(path.Ext(pageFile))
}
if filename == "" {
_, filename = filepath.Split(pageFile)
}
// 获取除后缀外文件名,处理.tar.gz特殊情况
name := strings.TrimSuffix(filename, path.Ext(pageFile))
if ext == ".gz" && len(name) >= 4 && strings.ToLower(name[len(name)-4:]) == ".tar" {
name = name[:len(name)-4]
}
return name
}
// 用于线上解压
func (c *Compressor) InitCompress(spaceId string, extract bool) error {
c.folder = c.GetName(c.pageFile, c.ext, c.name)
// 检查服务根目录是否存在
docRootDir := beego.AppConfig.String("document::root_dir")
wwwRoot := filepath.Join(docRootDir, "markdowns/serve", spaceId)
flag, _ := utils.File.PathIsExists(wwwRoot)
if !flag {
err := utils.Document.CreateFolder(wwwRoot)
if err != nil {
return errors.New("创建服务目录失败,请联系管理员!")
}
}
c.fileRoot = filepath.Join(wwwRoot, c.folder)
c.serveRoot = filepath.Join("serve", spaceId, c.folder)
// 检测是否存在,也用于获取服务地址
c.exist, _ = utils.File.PathIsExists(c.fileRoot)
if extract {
if c.exist {
return errors.New("检测到已解压的目录,可能已被解压,若需覆盖请先点击清除后再次操作!")
}
if err := utils.Document.CreateFolder(c.fileRoot); err != nil {
return err
}
}
return nil
}
// ==========================================解压相关=========================================================
func (c *Compressor) GetFileList(extract bool) (FileList, error) {
var files FileList
var err error
ext, absPath := c.ext, c.path
if ext == ".zip" {
files, err = c.GetZipFileList(absPath, extract)
} else if ext == ".tar" {
files, err = c.GetTarFileList(absPath, extract)
} else if ext == ".gz" || ext == ".tgz" {
files, err = c.GetGZipFileList(absPath, extract)
}
return files, err
}
// zip文件,仅获取文件列表
func (c *Compressor) GetZipFileList(zipFile string, extract bool) (FileList, error) {
zr, err := zip.OpenReader(zipFile)
defer zr.Close()
if err != nil {
return FileList{}, err
}
fs := newFileList(len(zr.File))
// TODO:此处遇到node_modules这样的极端目录是否影响效率?
for i, file := range zr.File {
fpath := GetFileNameUtf8(file)
// 解压模式过程
if extract {
zr := &ComFileReader{file: file}
c.ExtractFile(zr, fpath)
continue
}
fs.setValue(i, file.FileInfo(), fpath)
}
return fs, nil
}
// tar,仅获取文件列表
func (c *Compressor) GetTarFileList(tarFile string, extract bool) (FileList, error) {
nf := FileList{}
fr, err := os.Open(tarFile)
if err != nil {
return nf, err
}
defer fr.Close()
return c._GetTarFileList(&ComFileReader{reader: fr}, extract)
}
// tar.gz,仅获取文件列表
func (c *Compressor) GetGZipFileList(gzFile string, extract bool) (FileList, error) {
fs := FileList{}
fr, err := os.Open(gzFile)
if err != nil {
return fs, err
}
defer fr.Close()
gr, err := gzip.NewReader(fr)
if err != nil {
return fs, err
}
defer gr.Close()
// 单纯.gz文件,通常内部为单个文件
if IsGZ(gzFile) {
if extract {
if err := c.CopyGZ(gr); err != nil {
return fs, err
}
}
fs.setValueD(nil, gr.Name)
return fs, nil
}
return c._GetTarFileList(&GzFileReader{reader: gr}, extract)
}
// 获取tar和tar.gz文件列表通用过程
func (c *Compressor) _GetTarFileList(fr FileReader, extract bool) (FileList, error) {
fs := FileList{}
tr := fr.Reader()
for {
h, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return fs, err
}
// 解压模式过程
if extract {
cr := &GzFileReader{file: tr, info: h.FileInfo()}
c.ExtractFile(cr, h.Name)
continue
}
fs.setValueD(h.FileInfo(), h.Name)
}
return fs, nil
}
// 判断单纯.gz后缀文件
func IsGZ(name string) bool {
ps := strings.Split(strings.ToLower(name), ".")
l := len(ps)
if l > 1 && ps[l-1] == "gz" && ps[l-2] != "tar" {
return true
}
return false
}
func (c *Compressor) ExtractFile(fr FileReader, name string) error {
dstName := filepath.Join(c.fileRoot, name)
if fr.IsDir() {
if err := utils.Document.CreateFolder(dstName); err != nil {
return err
}
} else {
return CopyFile(fr, dstName)
}
return nil
}
func (c *Compressor) CopyGZ(fr *gzip.Reader) error {
name := fr.Name
dstName := filepath.Join(c.fileRoot, name)
fd := utils.Document.OpenFile(dstName)
if fd == nil {
return errors.New("Open New File Failed")
}
if _, err := io.Copy(fd, fr); err != nil {
return err
}
fd.Close()
return nil
}
func CopyFile(fr FileReader, dstName string) error {
fd := utils.Document.OpenFile(dstName)
if fd == nil {
return errors.New("Open New File Failed")
}
if _, err := fr.Copy(fd); err != nil {
return err
}
fd.Close()
return nil
}
// ================================================单文件提取===============================================
// tar.gz格式内部有些文件夹可能带有./前缀
func GetInnerFilePath(pageFile string, innerFile string) (string, string) {
iFile := innerFile
idx := strings.Index(innerFile, "./")
if idx != -1 {
iFile = innerFile[2:]
}
pagePath, filename := filepath.Split(pageFile)
filePath := filepath.Join(pagePath, "_temp", filename, iFile)
filePath = strings.ReplaceAll(filePath, "\\", "/")
return iFile, filePath
}
func (c *Compressor) ExtractInnerFile(absPath string, innerFile string, dst *os.File) error {
var err error
ext := c.ext
if ext == ".zip" {
err = ExtractZipInnerFile(absPath, innerFile, dst)
} else if ext == ".tar" {
err = ExtractTarInnerFile(absPath, innerFile, dst)
} else if ext == ".gz" || ext == ".tgz" {
err = ExtractGZipInnerFile(absPath, innerFile, dst)
}
return err
}
// ZIP解压单个文件
func ExtractZipInnerFile(zipFile string, innerFile string, dst *os.File) error {
r, err := zip.OpenReader(zipFile)
if err != nil {
return err
}
defer r.Close()
for _, f := range r.File {
fName := GetFileNameUtf8(f)
if fName != innerFile {
continue
}
src, err := f.Open()
if err != nil {
return err
}
if _, err := io.Copy(dst, src); err != nil {
return err
}
src.Close()
break
}
return nil
}
// TAR解压单个文件
func ExtractTarInnerFile(tarFile string, innerFile string, dst *os.File) error {
fr, err := os.Open(tarFile)
if err != nil {
return err
}
defer fr.Close()
return _ExtractTarInnerFile(nil, fr, innerFile, dst)
}
// GZIP解压单个文件
func ExtractGZipInnerFile(gzFile string, innerFile string, dst *os.File) error {
fr, err := os.Open(gzFile)
if err != nil {
return err
}
defer fr.Close()
gr, err := gzip.NewReader(fr)
if err != nil {
return err
}
defer gr.Close()
// 单纯.gz文件,通常内部为单个文件
if IsGZ(gzFile) {
if _, err := io.Copy(dst, gr); err != nil {
return err
}
return nil
}
return _ExtractTarInnerFile(gr, nil, innerFile, dst)
}
// TAR和GZIP解压单个文件通用过程
func _ExtractTarInnerFile(gr *gzip.Reader, fr *os.File, innerFile string, dst *os.File) error {
var tr *tar.Reader
if fr == nil {
tr = tar.NewReader(gr)
} else {
tr = tar.NewReader(fr)
}
for {
h, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return err
}
if h.Name != innerFile {
continue
}
if _, err := io.Copy(dst, tr); err != nil {
return err
}
break
}
return nil
}
// =========================================华丽丽分界线======================================================
//解决文件名乱码问题,如果标示位是0,则是默认的本地编码,默认为gbk
func GetFileNameUtf8(file *zip.File) string {
if file.Flags == 0 {
i := bytes.NewReader([]byte(file.Name))
decoder := transform.NewReader(i, simplifiedchinese.GB18030.NewDecoder())
content, _ := ioutil.ReadAll(decoder)
return string(content)
} else {
return file.Name
}
}