-
Notifications
You must be signed in to change notification settings - Fork 0
/
Filegai.go
5655 lines (5132 loc) · 168 KB
/
Filegai.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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Author: Hengyi Jiang <[email protected]>
// 2022-05-29
// Version 0.2
/*
BSD 2-Clause License
Copyright (c) 2022, Hengyi Jiang
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package main
import(
"fmt"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"io/ioutil"
"os"
"os/exec"
"syscall"
// "golang.org/x/sys/windows"
"strings"
"strconv"
"errors"
"github.com/gin-gonic/gin"
"net/http"
"bytes"
"crypto/rand"
"time"
"regexp"
"html/template"
"path/filepath"
"flag"
"sort"
"runtime"
)
// Basic types
type Fnode struct{
Name string
IsDir bool
Dev int32 // type is the same as the API return value
Ino uint64 // type is the same as the API return value
Parent_dev int32
Parent_ino uint64
}
type Fnode_view struct{
Name string
IsDir bool
Dev int32 // type is the same as the API return value
Ino uint64 // type is the same as the API return value
Parent_dev int32
Parent_ino uint64
Tag string
Note string
Color string
Note_visible string
Active_css_class string
Pin_class string
Pin_value string
Stash_class string
Stash_value string
}
// for *[]Fnode sort
type byAlpha []*Fnode
func(x byAlpha) Len() int {return len(x)}
func(x byAlpha) Less(i,j int) bool {return strings.ToLower(x[i].Name)<strings.ToLower(x[j].Name) }
func(x byAlpha) Swap(i,j int) {x[i],x[j]=x[j],x[i]}
// for Note_record
type Note_record struct{
Tag string
Name string
Note string
Color int
Color_str string
File_dir string
File_name string
Ndate string
}
type Resource_record struct{
Tag string
Name string
Rs_type int
Page int
Rs_date string
Ref_count int
File_name string
}
// for SQL packing
type Db_column struct{
Type rune // char , varchar, text ==> s, bool =>b, int ==>i, datetim=>t
Name string
Value string
}
type Db_table struct{
Name string
Columns map[string]bool
Data map[string]string // for insert and update
}
func (tab *Db_table) set_name(name string) *Db_table{
tab.Name = name
tab.Columns = make(map[string]bool)
tab.Data = make(map[string]string)
return tab
}
func (tab *Db_table) add_column(name string, to_quote bool) *Db_table{
tab.Columns[name]=to_quote
return tab
}
func (tab *Db_table) set(name string, value string) *Db_table{
to_quote,ok := tab.Columns[name]
if ok{
if to_quote{
tab.Data[name]="\""+strings.ReplaceAll(value,"\"","\"\"")+"\""
}else{
tab.Data[name]=value
}
}else{
panic("table column "+name+" not defined")
}
return tab
}
func (tab *Db_table) clear(){
tab.Name = ""
tab.Columns=make(map[string]bool)
tab.Data=make(map[string]string)
}
func (tab *Db_table) pack_insert() string{
var cols []string
var values []string
for col,value :=range tab.Data{
cols=append(cols,col)
values =append(values,value)
}
str :="INSERT INTO "+tab.Name+"("+strings.Join(cols,",")+") VALUES ("+ strings.Join(values,",") +")"
return str
}
func (tab *Db_table) pack_select(q_cols string, order string, limit string) string{
where_str :=""
where_arr:=[]string{}
order_str :=""
limit_str :=""
for col,value := range tab.Data{
if strings.Contains(value,"%"){
where_arr = append(where_arr, col+" like "+value)
}else if strings.HasPrefix(value,">") || strings.HasPrefix(value,"<"){
where_arr = append(where_arr,col+value)
}else{
where_arr = append(where_arr,col+"="+value)
}
}
if len(where_arr)>0{
where_str = " WHERE "+strings.Join(where_arr," and ")
}
if order !=""{
order_str = " ORDER BY "+order
}
if limit !=""{
limit_str =" LIMIT "+limit
}
str :="SELECT "+q_cols+" FROM "+tab.Name+" "+where_str + order_str + limit_str
return str
}
func (tab *Db_table) pack_count(count_col string) string{
return tab.pack_select("count(*) as "+count_col,"","")
}
func (tab *Db_table) pack_update(check []string) string{
set_arr:=[]string{}
where_str :=""
where_arr:=[]string{}
for col,value :=range tab.Data{
set_arr=append(set_arr,col+"="+value)
}
for _,col := range check{
where_arr = append(where_arr,col+"="+tab.Data[col])
}
if len(where_arr)>0{
where_str = " WHERE "+strings.Join(where_arr," and ")
}
if len(set_arr)>0{
str :="UPDATE "+tab.Name+" SET "+strings.Join(set_arr,",")+where_str
return str
}else{
return ""
}
}
func (tab *Db_table) pack_delete() string{
where_str :=""
where_arr:=[]string{}
for col,value := range tab.Data{
where_arr = append(where_arr,col+"="+value)
}
if len(where_arr)>0{
where_str = " WHERE "+strings.Join(where_arr," and ")
}
return "DELETE FROM "+tab.Name+where_str
}
// extending the db object methods
func do_insert(db_link *sql.DB,sql_insert string)(int64,error){
sql_run, err := db_link.Prepare(sql_insert)
if err !=nil{
fmt.Println("?? error in db operation:")
fmt.Println(sql_insert)
return 0,err
}
res, err :=sql_run.Exec()
if err !=nil{
return 0,err
}
id, err := res.LastInsertId()
if err !=nil{
return 0,err
}
return id,err
}
func do_exec(db_link *sql.DB,sql_cmd string)(int64,error){
sql_run, err := db_link.Prepare(sql_cmd)
if err !=nil{
fmt.Println("?? error in db operation:")
fmt.Println(sql_cmd)
return 0,err
}
res, err :=sql_run.Exec()
if err !=nil{
return 0,err
}
count, err := res.RowsAffected()
if err !=nil{
return 0,err
}
return count,nil
}
func do_update(db_link *sql.DB,sql_update string)(int64,error){
return do_exec(db_link,sql_update)
}
func do_delete(db_link *sql.DB,sql_delete string)(int64,error){
return do_exec(db_link,sql_delete)
}
func do_count(db_link *sql.DB,sql_count string)(int64,error){
rows, err := db_link.Query(sql_count)
defer rows.Close()
if err !=nil{
return 0,err
}
rows.Next()
var count int64
err = rows.Scan(&count)
if err !=nil{
return 0,err
}
return count,nil
}
func do_select_id(db_link *sql.DB,sql_select string)([]int64,error){
rows, err := db_link.Query(sql_select)
r :=[]int64{}
if err !=nil{
return r,err
}
var temp int64
for rows.Next(){
err = rows.Scan(&temp)
if err ==nil{
r=append(r,temp)
}
}
rows.Close()
return r,nil
}
// for tables
func get_table(tab_name string) *Db_table{
tab:=new(Db_table)
switch tab_name{
case "article":
tab.set_name("article").add_column("artid",false).add_column("tag",true)
tab.add_column("title",true).add_column("color",false).add_column("shelf_id",false).add_column("adate",true)
case "article_page":
tab.set_name("article_page").add_column("pgid",false).add_column("pg_tag",true).add_column("tag",true)
tab.add_column("pdate",true).add_column("order_id",false)
case "file_note":
tab.set_name("file_note")
tab.add_column("tag",true).add_column("file_dir",true).add_column("file_name",true).add_column("tag",true)
tab.add_column("note",true).add_column("color",false).add_column("ndate",true).add_column("nid",false)
case "ino_tree":
tab.set_name("ino_tree").add_column("id",false).add_column("host_name",true)
tab.add_column("device_id",false).add_column("ino",false).add_column("parent_ino",false)
tab.add_column("name",true).add_column("type",true).add_column("state",true)
case "resource":
tab.set_name("resource").add_column("rsid",false)
tab.add_column("tag",true).add_column("page",false).add_column("name",true)
tab.add_column("type",false).add_column("rs_date",true).add_column("ref_count",false)
case "resource_link":
tab.set_name("resource_link").add_column("tag",true).add_column("app",false).add_column("app_tag",true)
case "settings":
tab.set_name("settings").add_column("id",false).add_column("key",true).add_column("value",true).add_column("note",true)
case "shortcut":
tab.set_name("shortcut").add_column("file_dir",true).add_column("file_name",true).add_column("type",true)
tab.add_column("track_id",false).add_column("order_id",false).add_column("scid",false)
case "tags":
tab.set_name("tags").add_column("tag_str",true)
default:
fmt.Println("!!warning table name not in the set")
}
return tab
}
// for fs handling
func sys_delim()string{
return string(os.PathSeparator)
}
func str_native_delim(input string)string{
delim :=sys_delim()
if strings.Contains(input,"/") && delim =="\\"{
return strings.ReplaceAll(input,"/","\\")
}
return input
}
func str_db_delim(input string)string{
if strings.Contains(input,"\\"){
return strings.ReplaceAll(input,"\\","/")
}
return input
}
// windows specific codes -------------------------------------------------------------
// for fs handling
// func win_dev_ino(fname string,is_dir bool)(int32,uint64, error) {
// _fname, err := windows.UTF16PtrFromString(fname)
// if err != nil {
// return 0, 0, err
// }
// var handle windows.Handle
// if is_dir{
// handle, err = windows.CreateFile(_fname,windows.GENERIC_READ,windows.FILE_SHARE_READ,nil,windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
// if err != nil {
// return 0,0, err
// }
// }else{
// handle, err = windows.CreateFile(_fname,windows.GENERIC_READ,windows.FILE_SHARE_READ,nil,windows.OPEN_EXISTING, 0 , 0)
// if err != nil {
// return 0,0, err
// }
// }
// defer windows.CloseHandle(handle)
// var data windows.ByHandleFileInformation
// if err = windows.GetFileInformationByHandle(handle, &data); err != nil {
// return 0, 0, err
// }
// return int32(data.VolumeSerialNumber), (uint64(data.FileIndexHigh) << 32) | uint64(data.FileIndexLow), nil
// }
// }
// func folder_entries(path string) []*Fnode{
// var values []*Fnode
// // pnt_fileinfo, _ := os.Stat(path)
// // pnt_stat, ok := pnt_fileinfo.Sys().(*syscall.Stat_t)
// device_id,pnt_fileid,err := win_dev_ino(path,true)
// if err !=nil{
// return values
// }
// if err!=nil {
// return values //empty
// }
// fileInfos,err := ioutil.ReadDir(path)
// if err !=nil{return values}
// for _,info :=range fileInfos{
// // stat, ok := info.Sys().(*syscall.Stat_t)
// _,file_id,err := win_dev_ino(path+info.Name(),info.IsDir())
// if err ==nil{
// if ! strings.HasPrefix(info.Name(),"."){
// // values=append(values,&Fnode{info.Name(),info.IsDir(),stat.Dev,stat.Ino,pnt_stat.Dev,pnt_stat.Ino})
// values=append(values,&Fnode{info.Name(),info.IsDir(),device_id,file_id,device_id,pnt_fileid})
// }
// }
// }
// return values
// }
// func get_Fnode(path string,is_root bool) (*Fnode,error){
// var result Fnode
// delim :=sys_delim()
// if delim=="\\"{
// path = strings.ReplaceAll(path, "/","\\")
// }
// info, err := os.Stat(path)
// if err!=nil{
// return &result,err
// }
// if err!=nil{
// return &result,err
// }
// result.IsDir=info.IsDir()
// result.Dev,result.Ino,err = win_dev_ino(path,info.IsDir())
// if err!=nil{
// return &result,err
// }
// if is_root{
// ensure_folder(&path,delim)
// if strings.HasSuffix(path,delim){
// result.Name=path[0:(len(path)-1)]
// }else{
// result.Name=path
// }
// result.Parent_dev=result.Dev
// result.Parent_ino=result.Ino
// }else{
// result.Name=info.Name()
// var tmp_path string
// if strings.HasSuffix(path,delim){
// tmp_path =path_dir_name(path[0:(len(path)-1)],delim)
// }else{
// tmp_path =path_dir_name(path[0:(len(path))],delim)
// }
// result.Parent_dev,result.Parent_ino, err = win_dev_ino(tmp_path,true)
// if err!=nil{
// return &result,err
// }
// }
// return &result,nil
// }
//---------------------- end of windows specific code-----------------------------------
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// mac specific codes
func get_Fnode(path string,is_root bool) (*Fnode,error){
var result Fnode
delim :=sys_delim()
if delim=="\\"{
path = strings.ReplaceAll(path, "/","\\")
}
info, err := os.Stat(path)
if err!=nil{
return &result,err
}
stat, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return &result,errors.New("error in geting stat") //empty
}
result.IsDir=info.IsDir()
result.Dev=stat.Dev
result.Ino=stat.Ino
if is_root{
ensure_folder(&path,delim)
if strings.HasSuffix(path,delim){
result.Name=path[0:(len(path)-1)]
}else{
result.Name=path
}
result.Parent_dev=stat.Dev
result.Parent_ino=stat.Ino
}else{
result.Name=info.Name()
var tmp_path string
if strings.HasSuffix(path,delim){
tmp_path =path_dir_name(path[0:(len(path)-1)],delim)
}else{
tmp_path =path_dir_name(path[0:(len(path))],delim)
}
info, _ := os.Stat(tmp_path)
stat, _ := info.Sys().(*syscall.Stat_t)
result.Parent_dev=stat.Dev
result.Parent_ino=stat.Ino
}
return &result,nil
}
func folder_entries(path string) []*Fnode{
var values []*Fnode
pnt_fileinfo, _ := os.Stat(path)
pnt_stat, ok := pnt_fileinfo.Sys().(*syscall.Stat_t)
if !ok {
return values //empty
}
fileInfos,err := ioutil.ReadDir(path)
if err !=nil{return values}
for _,info :=range fileInfos{
stat, ok := info.Sys().(*syscall.Stat_t)
if ok{
if ! strings.HasPrefix(info.Name(),"."){
values=append(values,&Fnode{info.Name(),info.IsDir(),stat.Dev,stat.Ino,pnt_stat.Dev,pnt_stat.Ino})
}
}
}
return values
}
// end of mac specific codes++++++++++++++++++++++++++++++++++++++++++++++++++
func (fnode *Fnode) dev_ino() string{
return strconv.FormatUint(uint64(fnode.Dev),10)+"_"+strconv.FormatUint(fnode.Ino,10)
}
func (fnode *Fnode) parent_dev_ino()string{
return strconv.FormatUint(uint64(fnode.Parent_dev),10)+"_"+strconv.FormatUint(fnode.Parent_ino,10)
}
func (fnode *Fnode) device_id() string{
return strconv.FormatUint(uint64(fnode.Dev),10)
}
func (fnode *Fnode) ino() string{
return strconv.FormatUint(fnode.Ino,10)
}
func (fnode *Fnode) parent_ino() string{
return strconv.FormatUint(fnode.Parent_ino,10)
}
//====================================================================================================
// for ino_tree
func register_ino(db_link *sql.DB,node *Fnode)(bool,error){
// do query first
table:=get_table("ino_tree")
tp := "f"
if node.IsDir {
tp="d"
}
host_name:=get_host_name()
table.set("host_name",host_name)
table.set("device_id",node.device_id()).set("ino",node.ino())
count,err := do_count(db_link,table.pack_count("cnt"))
if err !=nil{
return false,err
}
if count >1{
// delete all obsoleted nodes
_,err=do_delete(db_link,table.pack_delete())
if err !=nil{
return false, err
}
}
if count ==1 {
// update the nodes
table.set("name",node.Name).set("parent_ino",strconv.FormatUint(node.Parent_ino,10)).set("type",tp).set("state","a")
_,err :=update_ino(db_link,node)
if err !=nil{
return false,err
}
}
if count==0 || count>1{
table.set("name",node.Name).set("parent_ino",strconv.FormatUint(node.Parent_ino,10)).set("type",tp).set("state","a")
_,err = do_insert(db_link,table.pack_insert())
if err !=nil{
return false,err
}
}
return true,nil
}
func update_ino(db_link *sql.DB,node *Fnode)(bool,error){
table:=get_table("ino_tree")
tp := "f"
if node.IsDir {
tp="d"
}
table.set("device_id",strconv.FormatUint(uint64(node.Dev),10)).set("ino",strconv.FormatUint(node.Ino,10))
table.set("name",node.Name).set("parent_ino",strconv.FormatUint(node.Parent_ino,10)).set("type",tp).set("state","a")
check := []string{"device_id","ino"}
_,err:=do_update(db_link,table.pack_update(check))
if err !=nil{
return false,err
}
return true,nil
}
func delete_ino(db_link *sql.DB,node *Fnode)(bool,error){
table:=get_table("ino_tree")
host_name :=get_host_name()
table.set("device_id",strconv.FormatUint(uint64(node.Dev),10)).set("ino",strconv.FormatUint(node.Ino,10)).set("host_name",host_name)
_,err:=do_delete(db_link,table.pack_delete())
if err !=nil{
return false,err
}
return true,nil
}
func clear_ino(db_link *sql.DB,root_dir string)(bool,error){
host_name :=get_host_name()
fnode,err :=get_Fnode(root_dir,true)
if err !=nil{
return false,err
}
table:=get_table("ino_tree")
table.set("device_id",strconv.FormatUint(uint64(fnode.Dev),10)).set("host_name",host_name)
_,err =do_delete(db_link,table.pack_delete())
if err !=nil{
return false,err
}
return true,nil
}
func query_fnode(db_link *sql.DB,device_id uint64, ino uint64) (*Fnode,error){
table:=get_table("ino_tree")
host_name:=get_host_name()
table.set("device_id",strconv.FormatUint(device_id,10)).set("ino",strconv.FormatUint(ino,10)).set("host_name",host_name)
var node Fnode
tp :="f"
rows, err := db_link.Query(table.pack_select("device_id,ino,parent_ino,name,type","name asc","1"))
defer rows.Close()
if err !=nil{
return &node,err
}
i :=0
for rows.Next(){
err = rows.Scan(&node.Dev,&node.Ino,&node.Parent_ino,&node.Name,&tp)
if err ==nil{
node.IsDir=false
if tp=="d"{
node.IsDir=true
}
}
i+=1
}
if i==0{
return &node,errors.New("no result")
}
return &node,nil
}
func search_fnodes(db_link *sql.DB,host_name string,name string)([]Fnode,error){
var node Fnode
var result []Fnode
table := get_table("ino_tree")
table.set("host_name",host_name).set("name","%"+name+"%")
rows, err := db_link.Query(table.pack_select("device_id,ino,parent_ino,name,type","name asc",""))
defer rows.Close()
if err !=nil{
return result,err
}
tp :="f"
for rows.Next(){
err = rows.Scan(&node.Dev,&node.Ino,&node.Parent_ino,&node.Name,&tp)
if err ==nil{
node.IsDir=false
if tp=="d"{
node.IsDir=true
}
result=append(result,node)
}
}
return result,err
}
func file_url(db_link *sql.DB,device_id uint64, ino uint64,max_level int,delim string) (string,error){
node, err := query_fnode(db_link,device_id,ino)
if max_level<0{
// guard against infinite loop error
return "",errors.New("maxium iteration")
}
if err !=nil{
return "",errors.New("query fnode error")
}
if node.Ino==node.Parent_ino{
return node.Name+delim,nil
}
s:=""
if node.IsDir{
s=delim
}
parent,err:=file_url(db_link,device_id,node.Parent_ino,max_level-1,delim)
if err !=nil{
return "",errors.New("iteration error")
}
// fmt.Printf("%s=>%s",node.Name,s)
return parent+node.Name+s,nil
}
// set calculation
func inos_in_parent(db_link *sql.DB,device_id uint64,parent_id uint64)([]int64){
table:=get_table("ino_tree")
host_name:=get_host_name()
table.set("parent_ino",strconv.FormatUint(parent_id,10)).set("device_id",strconv.FormatUint(device_id,10))
table.set("host_name",host_name)
ids,err:=do_select_id(db_link,table.pack_select("ino","",""))
if err!=nil{
var r []int64
return r
}
return ids
}
func inos_to_update(nodes_fs []*Fnode,inos_db []int64) (map[uint64]bool){
in_db := make(map[uint64]bool)
result :=make(map[uint64]bool)
for _,t := range(inos_db){
in_db[uint64(t)]=true
}
for _, v :=range(nodes_fs){
_, ok:=in_db[v.Ino]
if ok{
result[v.Ino]=true
}
}
return result
}
// func inos_to_insert(nodes_fs []Fnode,inos_update map(uint64)bool)(map(uint64)bool){
// // not used in the code
// to_update := make(map[uint64]bool)
// var result []uint64
// for _,t := range(inos_update){
// to_update[t]=true
// }
// for _, v :=range(nodes_fs){
// _, ok:=to_update[v.Ino]
// if !ok{
// result = append(result,v.Ino)
// }
// }
// return result
// }
func inos_to_delete(nodes_fs []*Fnode,inos_db []int64)(map[uint64]bool){
to_update := inos_to_update(nodes_fs,inos_db)
result := make(map[uint64]bool)
for _, v :=range(inos_db){
_, ok:=to_update[uint64(v)]
if !ok{
result[uint64(v)]=true
}
}
return result
}
func refresh_folder(db_link *sql.DB,folder string,is_root bool){
this_fnode,err := get_Fnode(folder,is_root)
if err !=nil{
return
}
device_id :=this_fnode.Dev
if is_root{
register_ino(db_link,this_fnode)
}
folder_entries := folder_entries(folder)
if is_root{
folder_entries=append(folder_entries,this_fnode)
}
inos_db := inos_in_parent(db_link,uint64(this_fnode.Dev),this_fnode.Ino)
delete_set := inos_to_delete(folder_entries,inos_db)
var temp_fnode Fnode
for _,ino := range(inos_db){
_,ok := delete_set[uint64(ino)]
if ok{
// to delete
// fmt.Printf("deleting ino:%s\n",strconv.FormatInt(ino,10))
temp_fnode.Dev=device_id
temp_fnode.Ino=uint64(ino)
_,err=delete_ino(db_link,&temp_fnode)
if err !=nil{
fmt.Printf("!!error:%s\n",err.Error())
}
}
}
for _,node :=range(folder_entries){
_,ok:=delete_set[node.Ino]
if !ok{
// to insert or update
_,err=register_ino(db_link,node)
if err !=nil{
fmt.Printf("?? registering error:%q,%s,%d",err,node.Name,node.Ino)
}
}
}
}
//====================================================================================================
// common functions
func file_exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil { return true, nil }
if os.IsNotExist(err) { return false, nil }
return true, err
}
func file_no_repeat(path string)(string,error){
file_dir :=path_dir_name(path,sys_delim())
file_name :=path_file_name(path,sys_delim())
if ok,_:=file_exists(path);ok{
var base_name string
var ext string
var result string
if strings.Contains(file_name,"."){
idx := strings.LastIndex(path,".")
base_name =path[0:idx]
ext =path[idx:len(path)]
result=base_name+"(1)"+ext
}else{
base_name =path
ext =""
result=path+"(1)"
}
if ok,_:=file_exists(result);!ok{
return result,nil
}
// this is already filename(1)(2).xxx in the folder
// then scan the folder
reg:=regexp.MustCompile(`^(.*)\((\d+)\)\.([\d\w_]*)$`)
if !strings.Contains(file_name,"."){
reg=regexp.MustCompile(`^(.*)\((\d+)\)$`)
}
entries,err :=ioutil.ReadDir(file_dir)
if err!=nil{
return "",err
}
order_max :=0
for _,info :=range(entries){
if reg.MatchString(info.Name()){
mats := reg.FindStringSubmatch(info.Name())
if len(mats)>1{
order_number,err :=strconv.Atoi(mats[2])
if err!=nil{
return "",err
}
if order_number > order_max{
order_max =order_number
}
}
}
}
order_max +=1
return base_name+"("+strconv.Itoa(order_max)+")"+ext,nil
}
return path,nil
}
func file_safe_mv(old_path string,new_path string,force bool)(string,error){
var new_target string
if ok,err:=file_exists(new_path);ok{
if force{
new_target,err =file_no_repeat(new_path)
if err !=nil{
return "",err
}
}else{
return "",errors.New("file already exists")
}
}else{
new_target=new_path
}
err:=os.Rename(old_path,new_target)
if err!=nil{
return "", err
}
return new_target,nil
}
func get_abs_path(rel_path string) string {
abs_path, err := filepath.Abs(rel_path)
if err != nil {
return rel_path
}
return abs_path
}
func folder_split(folder string,root_dir string,delim string) []string{
var s []string
var r []string
var u string
var tail string
if !strings.HasSuffix(root_dir,delim){
root_dir = root_dir+delim
}
if !strings.Contains(folder,root_dir){
tail = folder
u=""
}else{
r = append(r,root_dir)
idx := strings.Index(folder,root_dir)
tail = folder[(idx+len(root_dir)):]
u=root_dir
}
s = strings.SplitAfter(tail,delim)
for _,t := range(s){
u=u+t
r=append(r,u)
}
return r
}
func register_chain_ino(db_link *sql.DB,folder string,root_dir string,delim string){
lst :=folder_split(folder,root_dir,delim)
is_root :=false
for _,item :=range(lst){
if item==root_dir{
is_root = true
}
refresh_folder(db_link,item,is_root)
is_root =false
}
}
func ensure_folder(folder *string,delim string){
if len(*folder)==0{
return
}
if !strings.HasSuffix(*folder,delim){
*folder = *folder +delim
}
return
}
func mime_decode(rs_type int) string{
coden_tab:=map[int]string{
1: "image/png",
2: "image/jpeg",
3: "image/gif",
4: "image/tiff",
5: "image/bmp",
6: "image/svg+xml",
7: "image/webp",
30: "text/plain",// # text
31: "text/html",
32: "text/xml", //#svg
40: "application/json",
41: "application/pdf",
42: "application/msword",
100:"application/octet-stream",
}
r,ok:=coden_tab[rs_type]
if !ok{
return "application/octet-stream"
}
return r
}
func mime_encode(input string)int{
coden_tab:=map[string]int{
"image/png":1,
"image/jpeg":2,
"image/gif":3,