partage

File upload system
git clone git://git.z3bra.org/partage.git
Log | Files | Refs | README | LICENSE

partage-trash.go (1924B)


      1 package main
      2 
      3 import (
      4 	"log"
      5 	"flag"
      6 	"os"
      7 	"time"
      8 	"path/filepath"
      9 	"encoding/json"
     10 	
     11 	"github.com/dustin/go-humanize"
     12 )
     13 
     14 type metadata struct {
     15 	Filename string
     16 	Size int64
     17 	Expiry int64
     18 }
     19 
     20 var conf struct {
     21 	filepath string
     22 	metapath string
     23 }
     24 
     25 var verbose bool
     26 var count int64
     27 var deleted int64
     28 var size int64
     29 
     30 func readmeta(filename string) (metadata, error) {
     31 	j, err := os.ReadFile(filename)
     32 	if err != nil {
     33 		return metadata{}, err
     34 	}
     35 
     36 	var meta metadata
     37 	err = json.Unmarshal(j, &meta)
     38 	if err != nil {
     39 		return metadata{}, err
     40 	}
     41 
     42 	return meta, nil
     43 }
     44 
     45 func checkexpiry(path string, info os.FileInfo, err error) error {
     46 	if filepath.Ext(path) != ".json" {
     47 		return nil
     48 	}
     49 	meta, err := readmeta(path)
     50 	if err != nil {
     51 		log.Fatal(err)
     52 	}
     53 
     54 
     55 	count++
     56 
     57 	now := time.Now().Unix()
     58 	if verbose {
     59 		log.Printf("now: %s, expiry: %s\n", now, meta.Expiry);
     60 	}
     61 
     62 	if meta.Expiry > 0 && now >= meta.Expiry {
     63 		if verbose {
     64 			expiration :=  humanize.Time(time.Unix(meta.Expiry, 0))
     65 			log.Printf("%s/%s: expired %s\n", conf.filepath, meta.Filename, expiration)
     66 		}
     67 		if err = os.Remove(conf.filepath + "/" + meta.Filename); err != nil {
     68 			log.Fatal(err)
     69 		}
     70 		if err = os.Remove(path); err != nil {
     71 			log.Fatal(err)
     72 		}
     73 		deleted++
     74 		return nil
     75 	} else {
     76 		if verbose {
     77 			expiration :=  humanize.Time(time.Unix(meta.Expiry, 0))
     78 			log.Printf("%s/%s: expire in %s\n", conf.filepath, meta.Filename, expiration)
     79 		}
     80 		size += meta.Size
     81 	}
     82 
     83 	return nil
     84 }
     85 
     86 func main() {
     87 	flag.BoolVar(&verbose,         "v", false, "Verbose logging")
     88 	flag.StringVar(&conf.filepath, "f", "./files", "Directory containing files")
     89 	flag.StringVar(&conf.metapath, "m", "./meta", "Directory containing metadata")
     90 
     91 	flag.Parse()
     92 
     93 	err := filepath.Walk(conf.metapath, checkexpiry)
     94 	if err != nil {
     95 		log.Fatal(err)
     96 	}
     97 
     98 	if verbose && count > 0 {
     99 		log.Printf("%d/%d file(s) deleted (remaining: %s)", deleted, count, humanize.IBytes(uint64(size)))
    100 	}
    101 }