-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·754 lines (599 loc) · 16 KB
/
main.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
package main
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
_ "image/jpeg"
"io"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
excelize "github.com/xuri/excelize/v2"
"go.uber.org/zap"
cli "gopkg.in/urfave/cli.v1"
)
const (
DEFAULT_SERVICE_PORT = "8080"
htmlPage = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-eqgo builuiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
</body>
</html>`
configFileName = "config.cfg"
maxDownloadThreads = 5
)
func NewLogger() (*zap.Logger, error) {
cfg := zap.NewProductionConfig()
cfg.OutputPaths = []string{
"./logs.log",
"stderr",
}
return cfg.Build()
}
type SortlyParserConfig struct {
Port string `json:"port"`
RootFolder string `json:"root_folder"`
RootLinks string `json:"root_links"`
FilePath string `json:"file_path"`
Logger *zap.Logger
SaveConfig bool
Threads int64
}
func NewSortlyParserConfig(logger *zap.Logger) *SortlyParserConfig {
return &SortlyParserConfig{
Logger: logger,
}
}
func (spc *SortlyParserConfig) ParseInput(c *cli.Context) error {
var errR error
portRe := regexp.MustCompile(`(?m)^[1-9][0-9]{1,4}$`)
newPort := portRe.FindString(c.GlobalString("port"))
if newPort == "" {
errR = errors.New("bad port input")
}
spc.Port = newPort
rootFolder := c.GlobalString("dir")
if rootFolder != "" {
rootFolder = strings.Replace(rootFolder, "\\", "/", -1)
if rootFolder[len(rootFolder)-1] != '/' {
rootFolder += "/"
}
if _, err := os.Stat(rootFolder); errors.Is(err, os.ErrNotExist) {
spc.Logger.Error("root folder does not exist")
}
spc.RootFolder = rootFolder
}
rootLinks := c.GlobalString("links")
if rootLinks != "" && rootLinks[len(rootLinks)-1] != '/' {
rootLinks += "/"
spc.RootLinks = rootLinks
}
filePath := c.GlobalString("file")
if filePath != "" {
filePath = strings.Replace(filePath, "\\", "/", -1)
if _, err := os.Stat(filePath); errors.Is(err, os.ErrNotExist) {
errR = errors.New("file does not exist")
}
spc.FilePath = filePath
}
saveConfig := c.GlobalString("cfg")
if saveConfig == "1" {
spc.SaveConfig = true
}
thr := c.GlobalString("threads")
threads, err := strconv.ParseInt(thr, 10, 32)
if err != nil || threads == 0 {
spc.Logger.Error(
fmt.Sprintf("can not parse threads value, using default, reason: %v", err),
)
threads = maxDownloadThreads
}
spc.Threads = threads
return errR
}
func (spc *SortlyParserConfig) ReadConfig() error {
_, err := os.Stat(configFileName)
if errors.Is(err, os.ErrNotExist) {
return os.ErrNotExist
}
if !errors.Is(err, os.ErrNotExist) && err != nil {
return fmt.Errorf("can not check file, reason: %v", err)
}
f, err := os.Open(configFileName)
if err != nil {
return fmt.Errorf("can not open file, reason: %v", err)
}
newSpc := &SortlyParserConfig{}
err = json.NewDecoder(f).Decode(newSpc)
if err != nil {
return fmt.Errorf("can not decoding, reason: %v", err)
}
if newSpc.Port == "" {
return errors.New("config port is empty, bad config")
}
if newSpc.RootFolder == "" {
return errors.New("root folder is empty, bad config")
}
if newSpc.RootLinks == "" {
return errors.New("root links is empty, bad config")
}
spc.Port = newSpc.Port
spc.RootFolder = newSpc.RootFolder
spc.RootLinks = newSpc.RootLinks
return nil
}
func (spc *SortlyParserConfig) WriteConfig() {
f, err := os.Create("config.cfg")
if err != nil {
spc.Logger.Error(
fmt.Sprintf("can not open file to write config, reason: %v", err),
)
}
configStr := fmt.Sprintf("{\n\t%s%s%s\n\t%s%s%s\n\t%s%s%s\n}",
`"port":"`, spc.Port, `",`,
`"root_folder":"`, spc.RootFolder, `",`,
`"root_links":"`, spc.RootLinks, `"`)
_, err = f.WriteString(configStr)
if err != nil {
spc.Logger.Error(
fmt.Sprintf("can not write config to file, reason: %v", err),
)
}
}
type SortlyParser struct {
Cfg *SortlyParserConfig
}
type Parser struct {
Cfg *SortlyParserConfig
excelFileOrig *excelize.File
excelFileNew *excelize.File
currRow int
downloadedItems int32
downloadCh chan struct{}
wg sync.WaitGroup
FolderList []*Folder
}
type Folder struct {
Name string
Item *Item
Path string
FolderList []*Folder
ItemList []*Item
}
type Item struct {
Name string
Url []string
Row int
}
func NewSortlyParser(spc *SortlyParserConfig) *SortlyParser {
return &SortlyParser{
Cfg: spc,
}
}
func (sp *SortlyParser) CreateParser() *Parser {
return &Parser{
Cfg: sp.Cfg,
downloadCh: make(chan struct{}, sp.Cfg.Threads),
}
}
func (sp *Parser) ReadExcel() {
fmt.Println()
sp.Cfg.Logger.Info("Excel parse started")
f, err := excelize.OpenFile(sp.Cfg.FilePath)
if err != nil {
sp.Cfg.Logger.Error("can not open file")
}
sp.excelFileOrig = f
sp.excelFileNew = f
sp.currRow = 2
for {
nameCell, _ := excelize.CoordinatesToCellName(1, sp.currRow)
entryName, err := f.GetCellValue("Sheet1", nameCell)
if err != nil {
sp.Cfg.Logger.Error("cant read Entry Name cell")
}
if entryName == "" {
break
}
nameCell, _ = excelize.CoordinatesToCellName(2, sp.currRow)
entryType, _ := f.GetCellValue("Sheet1", nameCell)
_ = entryType
sp.AddItem(entryType, entryName)
sp.currRow++
}
fmt.Println()
sp.Cfg.Logger.Info("Excel parse done")
fmt.Println()
sp.Cfg.Logger.Info("Images parse started")
sp.ParseAllItems(sp.FolderList)
fmt.Println()
sp.Cfg.Logger.Info("Images parse done")
fmt.Println()
sp.SaveExcelFile()
fmt.Println()
sp.Cfg.Logger.Info("Sortly parsing work is done!")
fmt.Println()
}
func (sp *Parser) AddItem(entryType, entryName string) {
var (
rootFolder *Folder
path = ""
)
for i := 5; i < 10; i++ {
nameCell, _ := excelize.CoordinatesToCellName(i, sp.currRow)
folderName, _ := sp.excelFileOrig.GetCellValue("Sheet1", nameCell)
if folderName == "" {
if i == 5 && entryType == "Folder" {
sp.FolderList = append(sp.FolderList, &Folder{
Name: entryName,
Item: &Item{
Name: entryName,
Url: sp.GetUrls(),
Row: sp.currRow,
},
Path: fmt.Sprintf("%s/", entryName),
})
break
}
break
}
for _, f := range sp.FolderList {
rootFolder = GetFolderByName(f, folderName)
path += fmt.Sprintf("%s/", rootFolder.Name)
}
}
if rootFolder != nil {
path += fmt.Sprintf("%s/", entryName)
switch entryType {
case "Folder":
{
rootFolder.FolderList = append(rootFolder.FolderList, &Folder{
Name: entryName,
Item: &Item{
Name: entryName,
Url: sp.GetUrls(),
Row: sp.currRow,
},
Path: path,
})
}
case "Item":
{
rootFolder.ItemList = append(rootFolder.ItemList, &Item{
Name: entryName,
Url: sp.GetUrls(),
Row: sp.currRow,
})
}
}
}
}
func (sp *Parser) GetUrls() []string {
urls := make([]string, 0, 3)
for column := 10; column < 13; column++ {
nameCell, _ := excelize.CoordinatesToCellName(column, sp.currRow)
photoURL, _ := sp.excelFileOrig.GetCellValue("Sheet1", nameCell)
if photoURL == "" {
break
}
urls = append(urls, photoURL)
}
return urls
}
func GetFolderByName(rootFolder *Folder, name string) *Folder {
if rootFolder.Name == name {
return rootFolder
}
for _, f := range rootFolder.FolderList {
folderR := GetFolderByName(f, name)
if folderR != nil {
return folderR
}
}
return nil
}
func (sp *Parser) ParseAllItems(folderList []*Folder) {
if folderList == nil {
return
}
for _, f := range folderList {
sp.downloadCh <- struct{}{}
sp.wg.Add(1)
go sp.Save(f.Item, f)
for _, i := range f.ItemList {
sp.downloadCh <- struct{}{}
sp.wg.Add(1)
go sp.Save(i, f)
}
sp.ParseAllItems(f.FolderList)
}
sp.wg.Wait()
}
func (sp *Parser) Save(item *Item, folder *Folder) {
atomic.AddInt32(&sp.downloadedItems, 1)
data := md5.Sum([]byte(item.Name + time.Now().String()))
hash := hex.EncodeToString(data[:2])
pictureFolder := fmt.Sprintf("%s%s", sp.Cfg.RootFolder, folder.Path)
for i := 1; i <= len(item.Url); i++ {
pictureFilename := fmt.Sprintf("%s photo(%d)%s.jpg", item.Name, i, hash)
_, err := os.Stat(pictureFolder)
if errors.Is(err, os.ErrNotExist) {
mrdirErr := os.MkdirAll(pictureFolder, 0777)
if mrdirErr != nil {
sp.Cfg.Logger.Error(
fmt.Sprintf("cannot create directory for folder, reason:%s", err),
)
continue
}
sp.Cfg.Logger.Info("Directory created: %s\n" + pictureFolder)
fmt.Println()
}
_, err = os.Stat(pictureFolder + pictureFilename)
if errors.Is(err, os.ErrNotExist) {
err := sp.SaveFileFromURL(item.Url[i-1], pictureFilename, pictureFolder)
if err != nil {
sp.Cfg.Logger.Error(
fmt.Sprintf("saving picture from url, reason: %v", err),
)
}
sp.Cfg.Logger.Info(
fmt.Sprintf(`picture "%s" download complete`, pictureFilename),
)
}
if !errors.Is(err, os.ErrNotExist) && err != nil {
sp.Cfg.Logger.Error(
fmt.Sprintf(`picture "%s" local check before saving, reason: %v`, item.Url[i], err),
)
break
}
nameCell, _ := excelize.CoordinatesToCellName(9+i, item.Row)
sp.excelFileNew.SetCellValue("Sheet1", nameCell, sp.Cfg.RootLinks+folder.Path+item.Name+" photo("+strconv.Itoa(i)+")"+hash+".jpg")
}
<-sp.downloadCh
sp.wg.Done()
}
func (sp *Parser) SaveFileFromURL(url string, filename string, dir string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
file := fmt.Sprintf("%s/%s", dir, filename)
f, _ := os.OpenFile(file, os.O_CREATE|os.O_WRONLY, 0777)
io.Copy(f, resp.Body)
if err != nil {
return err
}
return nil
}
func (sp *Parser) SaveExcelFile() {
excelFolder := fmt.Sprintf("%sexcel", sp.Cfg.RootFolder)
_, err := os.Stat(excelFolder)
if errors.Is(err, os.ErrNotExist) {
mrdirErr := os.MkdirAll(excelFolder, 0777)
if mrdirErr != nil {
sp.Cfg.Logger.Error(
fmt.Sprintf("Error: cannot create directory for excel folder, reason:%s", err),
)
return
}
}
if err != nil && !errors.Is(err, os.ErrNotExist) {
sp.Cfg.Logger.Error(
fmt.Sprintf("excel folder local check, reason %v", err),
)
return
}
sp.Cfg.Logger.Info("Directory created " + sp.Cfg.RootFolder + "excel")
fmt.Println()
err = sp.excelFileNew.SaveAs(sp.Cfg.RootFolder + "excel/" + sp.FolderList[0].Name + ".xlsx")
if err != nil {
sp.Cfg.Logger.Error(
fmt.Sprintf("saving resulting excel, reason %v", err),
)
return
}
sp.Cfg.Logger.Info("Excel file formed " + sp.Cfg.RootFolder + "excel/" + sp.FolderList[0].Name + ".xlsx")
}
func (sp *SortlyParser) UploadFile(w http.ResponseWriter, r *http.Request) {
sp.Cfg.Logger.Info("File Upload Endpoint Hit")
// Parse our multipart form, 10 << 20 specifies a maximum
// upload of 10 MB files.
r.ParseMultipartForm(10 << 20)
// FormFile returns the first file for the given key `myFile`
// it also returns the FileHeader so we can get the Filename,
// the Header and the size of the file
file, handler, err := r.FormFile("myFile")
if err != nil {
sp.Cfg.Logger.Error(
fmt.Sprintf("retrieving the file, reason %v", err),
)
return
}
defer file.Close()
sp.Cfg.Logger.Info(
fmt.Sprintf("Uploaded File: %+v\n", handler.Filename),
)
sp.Cfg.Logger.Info(
fmt.Sprintf("File Size: %+v\n", handler.Size),
)
sp.Cfg.Logger.Info(
fmt.Sprintf("MIME Header: %+v\n", handler.Header),
)
fileBytes, err := io.ReadAll(file)
if err != nil {
sp.Cfg.Logger.Error(
fmt.Sprintf("read uploading file bytes: %s", err),
)
return
}
_, err = os.Stat(sp.Cfg.RootFolder + "temp-files")
if err != nil {
err := os.MkdirAll("temp-files", 0777)
if err != nil {
sp.Cfg.Logger.Error(
fmt.Sprintf("checking folder for uploading files: %s", err),
)
return
}
sp.Cfg.Logger.Info("Directory created /temp-files")
}
err = os.WriteFile("temp-files/"+handler.Filename, fileBytes, 0777)
if err != nil {
sp.Cfg.Logger.Error(
fmt.Sprintf("writing uploading file: %s", err),
)
}
sp.Cfg.Logger.Info("Successfully upload file")
fmt.Fprintf(w, "Successfully Uploaded File\nWait for a pictures loading\n")
sp.Cfg.FilePath = fmt.Sprintf("temp-files/%s", handler.Filename)
parser := sp.CreateParser()
go parser.ReadExcel()
}
func (sp *SortlyParser) ViewHandler(w http.ResponseWriter, r *http.Request) {
title := "Upload your file here"
body := []byte(
fmt.Sprintf(`<form
enctype="multipart/form-data"
action="http://localhost:%s/upload"
method="post"
>
<input type="file" name="myFile" />
<input type="submit" value="upload" />
</form>`,
sp.Cfg.Port),
)
fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", title, body)
}
func (sp *SortlyParser) ServerRun() {
http.HandleFunc("/upload", sp.UploadFile)
http.HandleFunc("/", sp.ViewHandler)
log.Fatal(http.ListenAndServe(
fmt.Sprintf(":%s", sp.Cfg.Port),
nil),
)
}
func (sp *SortlyParser) GetUserInput() error {
var (
rootFolder string = ""
rootLinks string = ""
errorWraper = func(anyErr error) func() error {
err := anyErr
return func() error {
return err
}
}
errFunc func() error
)
app := cli.NewApp()
app.Name = "sortly_excel_parser"
app.Version = "1.1.0"
app.Usage = "Парсит картинки из эксель файлов формата сортли и создает новый эксель файл со ссылками на картинки."
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "port,p",
Value: DEFAULT_SERVICE_PORT,
Usage: "Порт веб сервиса, на котором хостится веб страница загрузки",
},
cli.StringFlag{
Name: "dir,d",
Value: rootFolder,
Usage: "Корневая директория сохранения файлов (Вводить желательно в ковычках)",
},
cli.StringFlag{
Name: "links,l",
Value: rootLinks,
Usage: "Начальная директория для формирования ссылок",
},
cli.StringFlag{
Name: "file,f",
Value: "",
Usage: "Директория к файлу, чтобы обработать без хоста",
},
cli.StringFlag{
Name: "cfg",
Value: "",
Usage: "Сохранить конфигурацию в файл для работы без параметров командной строки. 1 чтобы сохранить",
},
cli.StringFlag{
Name: "threads, t",
Value: strconv.Itoa(maxDownloadThreads),
Usage: "Количество потоков для одновременной скачки",
},
}
app.Action = func(c *cli.Context) {
err := sp.Cfg.ParseInput(c)
errFunc = errorWraper(err)
}
app.Run(os.Args)
return errFunc()
}
func main() {
var (
sp = &SortlyParser{}
)
logger, err := NewLogger()
if err != nil {
panic("cannot init logger")
}
spc := NewSortlyParserConfig(logger)
sp = NewSortlyParser(spc)
logger.Info("Sortly parser is started!")
err = sp.Cfg.ReadConfig()
if err != nil && !errors.Is(err, os.ErrNotExist) {
logger.Error(
fmt.Sprintf("parse config: %v", err),
)
}
errUserInput := sp.GetUserInput()
if errUserInput != nil && err != nil {
logger.Error(
fmt.Sprintf("reading user input: %v", errUserInput),
)
logger.Error(
fmt.Sprintf("reading config file: %v", err),
)
logger.Fatal("Parser config is invalid. Shutdown...")
}
fmt.Println()
fmt.Println(`/////////////////////////////////////////`)
fmt.Println(`/// Welcome to The Gelikon Opera! ///`)
fmt.Println(`/////////////////////////////////////////`)
fmt.Println()
fmt.Println(`Excel Sortly parser is ready to work!`)
fmt.Println()
sp.Cfg.Logger.Info(
fmt.Sprintf(`Link prefix is "%s"`, sp.Cfg.RootLinks),
)
sp.Cfg.Logger.Info(
fmt.Sprintf(`Rootfolder is "%s"`, sp.Cfg.RootFolder),
)
if sp.Cfg.SaveConfig {
sp.Cfg.WriteConfig()
}
if sp.Cfg.FilePath != "" {
sp.Cfg.Logger.Info("File mod is ON!")
sp.Cfg.Logger.Info(
fmt.Sprintf(`File path is "%s"`, sp.Cfg.FilePath),
)
sp.CreateParser().ReadExcel()
return
}
fmt.Println("\nServer started on port " + sp.Cfg.Port + "\n")
fmt.Println("To start working with parser - just open in your browser (your IP):" + sp.Cfg.Port)
fmt.Println("For example 127.0.0.1:" + sp.Cfg.Port)
sp.ServerRun()
}