-
Notifications
You must be signed in to change notification settings - Fork 26
/
WebCopyer.go
625 lines (530 loc) · 17 KB
/
WebCopyer.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
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
)
/*
var url = "http://ieqi.net/wp-content/themes/ieqi-wptheme/css/main.css"
var destDir = "F:\\kuaipan\\Projects\\webcopyer\\template"
var img_ext = []string{".jpg", ".gif", ".png", ".jpeg", ".JPG", ".GIF", ".PNG", ".JPEG", ".ico", ".ICO"}
var css_ext = []string{".css", ".less", ".CSS", ".LESS"}
var js_ext = []string{".js", ".JS"}
var other_ext = []string{".dll"}
var extArray = []string{".jpg", ".gif", ".png", ".jpeg", ".css", ".less", ".js", ".ico", ".JPG", ".GIF", ".PNG", ".JPEG", ".CSS", ".LESS", ".JS", ".ICO", ".dll"}
var css_resource_list []string
*/
type Config map[string]string
var (
cfg Config
current_url string
destDir string
css_resource_list []string
img_ext []string
css_ext []string
js_ext []string
other_ext []string
html_dir string
img_dir string
css_dir string
js_dir string
other_dir string
configFile *string
help *bool
version *bool
extArray []string
method string
arg1 string
arg2 string
ext string
)
func init() {
configFile = flag.String("config", "config", "配置文件路径")
help = flag.Bool("help", false, "查看帮助")
version = flag.Bool("version", false, "show version")
flag.Parse()
if *help {
fmt.Println()
fmt.Println("复制模板:")
fmt.Println(" webcopyer http://lyric.im/")
fmt.Println(" webcopyer get http://lyric.im/")
fmt.Println()
fmt.Println("拷贝本地模板:")
fmt.Println(" webcopyer getLocal F:\\template\\index.html http://drizzlep.diandian.com/")
fmt.Println()
fmt.Println("拷贝html及其直接关联资源模板:")
fmt.Println(" webcopyer getHtml http://lyric.im/")
fmt.Println()
fmt.Println("拷贝css及其直接关联资源模板:")
fmt.Println(" webcopyer getCss http://lyric.im/styles/style.css")
fmt.Println()
fmt.Println("关于:")
fmt.Println(" version: 1.0")
fmt.Println(" author: 肖立群")
fmt.Println(" email: xlqstar@gmail.com")
fmt.Println(" repo: https://github.com/xlqstar/WebCopyer.git")
fmt.Println()
os.Exit(0)
}
if *version {
fmt.Println()
fmt.Println("关于:")
fmt.Println(" version: 1.0")
fmt.Println(" author: 肖立群")
fmt.Println(" email: xlqstar@gmail.com")
fmt.Println(" repo: https://github.com/xlqstar/WebCopyer.git")
fmt.Println()
os.Exit(0)
}
method = flag.Arg(0)
arg1 = flag.Arg(1)
arg2 = flag.Arg(2)
log.SetFlags(log.Ltime)
//或取配置文件
cfg := Configure(*configFile)
destDir = cfg.getStr("destDir")
img_ext = cfg.getArray("img_ext")
css_ext = cfg.getArray("css_ext")
js_ext = cfg.getArray("js_ext")
other_ext = cfg.getArray("other_ext")
html_dir = fixResPath(cfg.getStr("html_dir"))
img_dir = fixResPath(cfg.getStr("img_dir"))
css_dir = fixResPath(cfg.getStr("css_dir"))
js_dir = fixResPath(cfg.getStr("js_dir"))
other_dir = fixResPath(cfg.getStr("other_dir"))
extArray = arrayMerge(extArray, img_ext)
extArray = arrayMerge(extArray, css_ext)
extArray = arrayMerge(extArray, js_ext)
extArray = arrayMerge(extArray, other_ext)
destDir = checkAndMkDir(destDir)
}
func main() {
// fmt.Println(get_destdir_and_filetype("http://www.chinaz.com/"))
//getAll("http://drizzlep.diandian.com/", "") //获取在线模版
//getAll("F:\\kuaipan\\Projects\\webcopyer\\template\\index.html", "http://drizzlep.diandian.com/page/2/") //获取本地模版
//完整测试
// getHtml("http://www.chinaz.com/")
//测试download
// down_resource("https://ss.cnnic.cn/seallogo.dll?sn=e12020335020010628301467&size=3")
//css测试 常用
// getCss("http://img.chinaz.com/templates/chinaz/css/style.css?v=20121121")
//css测试 import
//getCss("http://download.csdn.net/css/download.css")
//fix_url 测试
// current_url = "http://ieqi.net/"
// fmt.Println(fix_url("./sdfs/sdfa/wahaha.jpg"))
if method == "get" {
if arg1 == "" {
log.Fatal("请正确输入参数")
}
getAll(arg1, "") //获取在线模版
} else if method == "getLocal" || method == "getlocal" {
if arg1 == "" || arg2 == "" {
log.Fatal("请正确输入参数")
}
getAll(arg1, arg2) //获取本地模版
} else if method == "getCss" || method == "getcss" {
if arg1 == "" {
log.Fatal("请正确输入参数")
}
getCss(arg1)
} else if method == "getHtml" || method == "gethtml" {
if arg1 == "" {
log.Fatal("请正确输入参数")
}
getHtml(arg1)
} else {
if method == "" {
log.Fatal("请正确输入参数")
}
getAll(method, "") //获取在线模版
}
}
func getAll(file string, url string) {
var html string
ext = "html"
if strings.HasPrefix(file, "http") || strings.HasPrefix(file, "https") {
html = http_get(file)
current_url = file
} else {
htmlbyte, _ := ioutil.ReadFile(file)
html = string(htmlbyte)
current_url = url
}
html = extruct_html_resource(html)
ioutil.WriteFile(destDir+html_dir+get_true_filename(current_url), []byte(html), 0777) //转储html
for k := range css_resource_list {
current_url_tmp := current_url
current_url = fix_url(css_resource_list[k])
css := http_get(current_url)
css = extruct_css_resource(css) //1、改引用路径 2、下载资源
dest := getDestDir("css")
write_erro := ioutil.WriteFile(destDir+dest+get_true_filename(current_url), []byte(css), 0777) //转储css
if write_erro != nil {
fmt.Println(write_erro)
}
current_url = current_url_tmp
}
log.Println("Done !!")
}
func getHtml(url string) {
ext = "html"
html := http_get(url)
current_url = url
html = extruct_html_resource(html)
ioutil.WriteFile(destDir+html_dir+get_true_filename(url), []byte(html), 0777) //转储css
log.Println("Done !!")
}
func getCss(url string) {
ext = "css"
css := http_get(url)
current_url = url
css = extruct_css_resource(css) //1、改引用路径 2、下载资源
dest := getDestDir("css")
ioutil.WriteFile(destDir+dest+get_true_filename(url), []byte(css), 0777) //转储css
log.Println("Done !!")
}
//==============================================
//css提取
func extruct_css_resource(content string) string {
re1, _ := regexp.Compile("background(-image)?\\s*:[^;})]*url\\s*\\((\\S+)?\\)") //src\s*=\s*(["|'])([\S\s]+?)\1
content = re1.ReplaceAllStringFunc(content, css_change_path_1)
re2, _ := regexp.Compile("@import.*url\\s*(\\(.*\\));") //src\s*=\s*(["|'])([\S\s]+?)\1
content = re2.ReplaceAllStringFunc(content, append_import_css_resource)
return content
}
func css_change_path_1(str string) string {
re, _ := regexp.Compile("background(-image)?\\s*:[^;})]*url\\s*\\((\\S+)?\\)")
old_path := re.FindStringSubmatch(str)[2]
old_path = strings.Trim(old_path, "\"' ")
new_path := css_change_path(str, old_path)
return new_path
}
func append_import_css_resource(str string) string {
re, _ := regexp.Compile("@import.*url\\s*\\((.*)\\);")
import_url := re.FindStringSubmatch(str)[1]
import_url = fix_url(strings.Trim(import_url, "\"' "))
getCss(import_url)
return str
}
//@import.*url\s*(\(.*\));
func css_change_path(str string, old_path string) string {
dir, filetype := get_destdir_and_filetype(old_path)
if dir != "unexcept" {
down_resource(old_path, dir)
true_filename := get_true_filename(old_path)
relPath := getRelPath(css_dir, getDestDir(filetype))
return strings.Replace(str, old_path, relPath+"/"+true_filename, -1)
}
return str
}
//================================================
//htmlt资源提取
func extruct_html_resource(content string) string {
re1, _ := regexp.Compile("src\\s*=\\s*\"([\\S\\s]+?)\"")
re2, _ := regexp.Compile("src\\s*=\\s*'([\\S\\s]+?)'") //src\s*=\s*(["|'])([\S\s]+?)\1
re3, _ := regexp.Compile("<\\s*link([\\S\\s]+?)href\\s*=\\s*\"([\\S\\s]+?)\"") //src\s*=\s*(["|'])([\S\s]+?)\1
re4, _ := regexp.Compile("<\\s*link([\\S\\s]+?)href\\s*=\\s*'([\\S\\s]+?)'") //src\s*=\s*(["|'])([\S\s]+?)\1
re5, _ := regexp.Compile("background(-image)?\\s*:[^;})]*url\\s*\\((\\S+)?\\)") //src\s*=\s*(["|'])([\S\s]+?)\1
content = re1.ReplaceAllStringFunc(content, html_change_path_1)
content = re2.ReplaceAllStringFunc(content, html_change_path_2)
content = re3.ReplaceAllStringFunc(content, html_change_path_3)
content = re4.ReplaceAllStringFunc(content, html_change_path_4)
content = re5.ReplaceAllStringFunc(content, html_css_change_path)
return content
}
func html_change_path_1(str string) string {
re, _ := regexp.Compile("src\\s*=\\s*\"([\\S\\s]+?)\"")
old_path := re.FindStringSubmatch(str)[1]
new_path := html_change_path(str, old_path)
return new_path
}
func html_change_path_2(str string) string {
re, _ := regexp.Compile("src\\s*=\\s*'([\\S\\s]+?)'")
old_path := re.FindStringSubmatch(str)[1]
new_path := html_change_path(str, old_path)
return new_path
}
func html_change_path_3(str string) string {
re, _ := regexp.Compile("<\\s*link([\\S\\s]+?)href\\s*=\\s*\"([\\S\\s]+?)\"")
old_path := re.FindStringSubmatch(str)[2]
new_path := html_change_path(str, old_path)
return new_path
}
func html_change_path_4(str string) string {
re, _ := regexp.Compile("<\\s*link([\\S\\s]+?)href\\s*=\\s*'([\\S\\s]+?)'")
old_path := re.FindStringSubmatch(str)[2]
new_path := html_change_path(str, old_path)
return new_path
}
func html_change_path(str string, old_path string) string {
dir, filetype := get_destdir_and_filetype(old_path)
if dir != "unexcept" {
down_resource(old_path, dir)
if filetype == "css" {
css_resource_list = append(css_resource_list, old_path)
}
true_filename := get_true_filename(old_path)
resDir := getDestDir(filetype)
relPath := getRelPath(html_dir, resDir)
return strings.Replace(str, old_path, relPath+"/"+true_filename, -1)
}
return str
}
func html_css_change_path(str string) string {
re, _ := regexp.Compile("background(-image)?\\s*:[^;})]*url\\s*\\((\\S+)?\\)")
old_path := re.FindStringSubmatch(str)[2]
old_path = strings.Trim(old_path, "\"' ")
new_path := _html_css_change_path(str, old_path)
return new_path
}
func _html_css_change_path(str string, old_path string) string {
dir, filetype := get_destdir_and_filetype(old_path)
if dir != "unexcept" {
down_resource(old_path, dir)
true_filename := get_true_filename(old_path)
resDir := getDestDir(filetype)
relPath := getRelPath(html_dir, resDir)
return strings.Replace(str, old_path, relPath+"/"+true_filename, -1)
}
return str
}
//======================================
func http_get(url string) string {
res, err := http.Get(url)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return string(body)
}
func get_true_filename(url string) string {
filename := filepath.Base(url)
extname := filepath.Ext(url)
for k := range extArray {
if strings.Contains(extname, extArray[k]) {
true_filename := strings.Replace(filename, extname, extArray[k], -1)
return true_filename
}
}
true_filename := strings.Split(filename, "?")[0]
if len(true_filename) > 0 {
if !(url == arg1 || url == method || url == arg2) {
log.Println("发现未知类型文件:" + url)
log.Println()
} else {
true_filename = true_filename + "." + ext
}
return true_filename
}
return filename
}
func get_destdir_and_filetype(url string) (string, string) {
filetype := ""
dir := destDir
if in_array(filepath.Ext(url), img_ext) {
filetype = "images"
} else if in_array(filepath.Ext(url), css_ext) {
filetype = "css"
} else if in_array(filepath.Ext(url), js_ext) {
filetype = "js"
} else if in_array(filepath.Ext(url), other_ext) {
filetype = "other"
} else {
return "unexcept", "unexcept"
}
dir = dir + "\\theme\\" + filetype + "\\"
return dir, filetype
}
func down_resource(url string, destDir string) {
url = strings.Trim(url, " \t\n\r")
filename := get_true_filename(url)
fullfilename := destDir + filename
fixed_url := fix_url(url) //矫正url(相对路径转换为绝对路径)
log.Println("FROM: " + fixed_url)
log.Println("TO: " + fullfilename)
if strings.HasPrefix(fixed_url, "http") || strings.HasPrefix(fixed_url, "https") {
resp, err := http.Get(fixed_url)
if err != nil {
fmt.Println(err)
os.Exit(0)
}
out, create_err := os.Create(fullfilename)
if create_err != nil {
fmt.Println(create_err)
os.Exit(0)
}
_, copy_err := io.Copy(out, resp.Body)
if copy_err != nil {
fmt.Println(copy_err)
os.Exit(0)
}
out.Close()
resp.Body.Close()
}
fmt.Println()
}
func in_array(v string, array []string) bool {
for k := range array {
if strings.Contains(strings.ToLower(v), strings.ToLower(array[k])) {
return true
}
}
return false
}
//http://www.baidu.com/wahaha/sdfds/index.html
func fix_url(url string) string {
re1, _ := regexp.Compile("http[s]?://[^/]+")
destrooturl := re1.FindString(current_url)
//当url为://wahaha/xiaoxixi/tupian.png
if strings.HasPrefix(url, "//") {
url = "http:" + url
} else if strings.HasPrefix(url, "/") {
// re1,_ := regexp.Compile("http[s]?://[^/]+")
// destrooturl := re1.FindString(current_url)
url = destrooturl + url
}
//当url为:"../wahaha/xiaoxixi/tupian.png"、"./wahaha/xiaoxixi/tupian.png"、"wahaha/xiaoxixi/tupian.png"
if !strings.HasPrefix(url, "/") && !strings.HasPrefix(url, "http") && !strings.HasPrefix(url, "https") {
// current_url = strings.TrimSuffix(current_url, "/")
if destrooturl == current_url {
url = current_url + "/" + url
} else {
re2, _ := regexp.Compile("[^/]+?$")
url = re2.ReplaceAllString(current_url, "") + url
}
}
return url
}
func Configure(filePath string) Config {
configByte, err := ioutil.ReadFile(filePath)
if err != nil {
log.Fatal("配置文件不存在!")
}
configMap := Config{}
config := strings.Replace("\r\n", "\n", string(configByte), -1)
configArray := strings.Split(config, "\n")
for _, v := range configArray {
v = Trim(v)
vArray := strings.SplitN(v, ":", 2)
if len(vArray) == 2 && !strings.HasPrefix(v, "#") {
key := Trim(vArray[0])
value := Trim(vArray[1])
configMap[key] = value
}
}
return configMap
}
func (cfg Config) getInt(key string) int {
value, err := strconv.Atoi(cfg[key])
if err != nil {
log.Fatal(key + "值未填写或填写不正确,请确认为整数")
}
return value
}
func (cfg Config) getStr(key string) string {
if cfg[key] == "" {
log.Fatal(key + "值未填写或填写不正确")
}
return cfg[key]
}
func (cfg Config) getArray(key string) []string {
return strings.Split(cfg[key], "|")
}
func Trim(s string) string {
return strings.Trim(s, " \t\n\r")
}
// 检查文件或目录是否存在
// 如果由 filename 指定的文件或目录存在则返回 true,否则返回 false
func exist(filename string) bool {
_, err := os.Stat(filename)
return err == nil || os.IsExist(err)
}
func arrayMerge(old []string, other []string) []string {
for _, v := range other {
old = append(old, v)
}
return old
}
func checkAndMkDir(destDir string) string {
//判断destDir是否存在 不存在的话创建 失败的话报错终止
if !exist(destDir) {
err := os.Mkdir(destDir, os.ModePerm)
if err != nil {
log.Fatal("无法创建目录!")
}
}
destDir = destDir + "\\" + strconv.Itoa(int(time.Now().Unix()))
if !exist(destDir) {
err := os.Mkdir(destDir, os.ModePerm)
if err != nil {
log.Fatal("无法创建目录!")
}
}
if !exist(destDir + "\\theme\\js") {
err := os.MkdirAll(destDir+"\\theme\\js", os.ModePerm)
if err != nil {
log.Fatal("无法创建目录!")
}
}
if !exist(destDir + "\\theme\\images") {
err := os.MkdirAll(destDir+"\\theme\\images", os.ModePerm)
if err != nil {
log.Fatal("无法创建目录!")
}
}
if !exist(destDir + "\\theme\\css") {
err := os.MkdirAll(destDir+"\\theme\\css", os.ModePerm)
if err != nil {
log.Fatal("无法创建目录!")
}
}
return destDir
}
func getDestDir(filetype string) string {
path := ""
if filetype == "images" {
path = img_dir
} else if filetype == "js" {
path = js_dir
} else if filetype == "css" {
path = css_dir
} else if filetype == "other" {
path = other_dir
} else if filetype == "html" {
path = html_dir
}
return path
}
//检查修复各个资源存储路径
func fixResPath(path string) string {
fixed := path
if path == "" || path == "\\" {
fixed = "\\"
} else {
if !strings.HasSuffix(path, "\\") {
fixed = fixed + "\\"
}
}
if !strings.HasPrefix(path, "\\") {
fixed = "\\" + path
}
return fixed
}
func getRelPath(base string, target string) string {
rel, _ := filepath.Rel(base, target)
rel = strings.Replace(rel, "/\\", "/", -1)
rel = strings.Replace(rel, "\\", "/", -1)
return rel
}