// Copyright 2019 getensh.com. All rights reserved. // Use of this source code is governed by getensh.com. package local_objs import ( "git.getensh.com/common/gopkgs/database" "gorm.io/gorm" "os" "strings" "time" "xingjia-management-gateway/errors" dbmodel "xingjia-management-gateway/model" "xingjia-management-gateway/parser" ) func parseObjUrls(objUrls []string) []string { ret := []string{} for _, v := range objUrls { array := strings.Split(v, "=") if len(array) != 2 { continue } name := strings.TrimSpace(array[1]) ret = append(ret, name) } return ret } func AddToDb(db *gorm.DB, name string) error { p := dbmodel.TLocalObjs{ Name: name, Used: 0, Timestamp: time.Now().Unix(), } err := p.Insert(db) if err != nil { return errors.DataBaseError } return nil } func prepareInAndOut(in []string, out []string) ([]string, []string) { in = parseObjUrls(in) out = parseObjUrls(out) inM := map[string]bool{} for _, v := range in { if v == "" { continue } inM[v] = true } outM := map[string]bool{} for _, v := range out { if v == "" { continue } outM[v] = true } tmp := []string{} for k, _ := range inM { if _, ok := outM[k]; ok { tmp = append(tmp, k) } } for _, v := range tmp { delete(inM, v) delete(outM, v) } inRet := []string{} outRet := []string{} for v, _ := range inM { inRet = append(inRet, v) } for v, _ := range outM { outRet = append(outRet, v) } return inRet, outRet } func InAndOut(db *gorm.DB, in []string, out []string) error { in, out = prepareInAndOut(in, out) p := dbmodel.TLocalObjs{} if len(in) > 0 { where := map[string]interface{}{} values := map[string]interface{}{} where["name in"] = in values["used"] = 1 err := p.Update(db, where, values) if err != nil { return errors.DataBaseError } } if len(out) == 0 { return nil } where := map[string]interface{}{} where["name in"] = out err := p.Delete(db, where) if err != nil { return errors.DataBaseError } for _, v := range out { path := parser.Conf.ObjPath + v os.Remove(path) } return nil } func DelTask() { t := time.NewTicker(24 * time.Hour) p := dbmodel.TLocalObjs{} where := map[string]interface{}{ "timestamp <": time.Now().Unix() - 24*60*60, "used": 0, } filter := map[string]interface{}{} for { select { case <-t.C: list, _ := p.List(database.DB(), where, nil, -1, -1) for _, v := range list { path := parser.Conf.ObjPath + v.Name os.Remove(path) filter["id"] = v.ID p.Delete(database.DB(), where) } } } }