@@ -2,8 +2,11 @@ package torrstor
22
33import (
44 "sync"
5-
5+ "slices"
6+ "os"
7+ "path/filepath"
68 "server/torr/storage"
9+ "server/settings"
710
811 "github.com/anacrolix/torrent/metainfo"
912 ts "github.com/anacrolix/torrent/storage"
@@ -70,3 +73,52 @@ func (s *Storage) GetCache(hash metainfo.Hash) *Cache {
7073 }
7174 return nil
7275}
76+
77+ func (s * Storage ) cleanPieces () {
78+ s .mu .Lock ()
79+ defer s .mu .Unlock ()
80+ var filled int64 = 0
81+ for _ , ch := range s .caches {
82+ filled += ch .filled
83+ }
84+ overfill := filled - s .capacity
85+ if overfill < 0 {
86+ return
87+ }
88+ sortCachesByModifiedDate := func (a , b * Cache ) int {
89+ aname := filepath .Join (settings .BTsets .TorrentsSavePath , a .hash .HexString ())
90+ bname := filepath .Join (settings .BTsets .TorrentsSavePath , b .hash .HexString ())
91+ ainfo , err := os .Stat (aname )
92+ if err != nil {
93+ return - 1
94+ }
95+ binfo , err := os .Stat (bname )
96+ if err != nil {
97+ return 1
98+ }
99+ return ainfo .ModTime ().Compare (binfo .ModTime ())
100+ }
101+ nonempty := slices .Values (slices .Collect (func (yield func (* Cache ) bool ) {
102+ for _ , c := range s .caches {
103+ if c .filled > 0 {
104+ if ! yield (c ) {
105+ return
106+ }
107+ }
108+ }
109+ }))
110+ // fill sortedcaches with refs to non-empty caches sorted by respective
111+ // folder modified date in descending order (older first)
112+ sortedcaches := slices .SortedFunc (nonempty , sortCachesByModifiedDate )
113+ for _ , c := range sortedcaches {
114+ _cap := c .capacity
115+ c .capacity = max (c .filled - overfill , 0 )
116+ overfill -= c .filled
117+ c .doCleanPieces ()
118+ overfill += c .filled
119+ c .capacity = _cap
120+ if overfill <= 0 {
121+ return
122+ }
123+ }
124+ }
0 commit comments