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