44 "net/http"
55 "server/torrshash"
66 "strings"
7+ "sync"
8+ "time"
79
810 "server/dlna"
911 "server/log"
@@ -27,8 +29,16 @@ type torrReqJS struct {
2729 Poster string `json:"poster,omitempty"`
2830 Data string `json:"data,omitempty"`
2931 SaveToDB bool `json:"save_to_db,omitempty"`
32+ Filter string `json:"filter,omitempty"`
3033}
3134
35+ var (
36+ listCache []* state.TorrentStatus
37+ listCacheTime time.Time
38+ listCacheMu sync.Mutex
39+ listCacheTTL = 2 * time .Second
40+ )
41+
3242// torrents godoc
3343//
3444// @Summary Handle torrents informations
@@ -69,7 +79,7 @@ func torrents(c *gin.Context) {
6979 }
7080 case "list" :
7181 {
72- listTorrents (c )
82+ listTorrents (c , req . Filter )
7383 }
7484 case "drop" :
7585 {
@@ -193,16 +203,41 @@ func remTorrent(req torrReqJS, c *gin.Context) {
193203 c .Status (200 )
194204}
195205
196- func listTorrents (c * gin.Context ) {
197- list := torr .ListTorrent ()
206+ func listTorrents (c * gin.Context , filter string ) {
207+ if filter == "" {
208+ filter = "all"
209+ }
210+
211+ // Return cached response for "all" filter if fresh enough
212+ if filter == "all" {
213+ listCacheMu .Lock ()
214+ if listCache != nil && time .Since (listCacheTime ) < listCacheTTL {
215+ cached := listCache
216+ listCacheMu .Unlock ()
217+ c .JSON (200 , cached )
218+ return
219+ }
220+ listCacheMu .Unlock ()
221+ }
222+
223+ list := torr .ListTorrentFiltered (filter )
198224 if len (list ) == 0 {
199225 c .JSON (200 , []* state.TorrentStatus {})
200226 return
201227 }
202228 var stats []* state.TorrentStatus
203229 for _ , tr := range list {
204- stats = append (stats , tr .Status ())
230+ stats = append (stats , tr .StatusLight ())
205231 }
232+
233+ // Cache "all" results
234+ if filter == "all" {
235+ listCacheMu .Lock ()
236+ listCache = stats
237+ listCacheTime = time .Now ()
238+ listCacheMu .Unlock ()
239+ }
240+
206241 c .JSON (200 , stats )
207242}
208243
0 commit comments