/** * 视频缓存管理工具 * 用于管理本地视频缓存,清理过期或超出限制的缓存 */ const MAX_CACHE_SIZE = 50; // 最多缓存50个视频 const MAX_CACHE_AGE = 30 * 24 * 60 * 60 * 1000; // 30天过期 /** * 清理过期的视频缓存 */ export function cleanExpiredCache() { try { const cacheInfo = uni.getStorageSync('video_cache_info') || {}; const now = Date.now(); let cleaned = 0; Object.keys(cacheInfo).forEach(key => { const cache = cacheInfo[key]; // 检查是否过期 if (now - cache.time > MAX_CACHE_AGE) { console.log('[CacheManager] 清理过期缓存:', cache.url); // 删除文件 uni.removeSavedFile({ filePath: cache.path, success: () => { console.log('[CacheManager] 文件已删除:', cache.path); } }); // 删除映射 uni.removeStorageSync(key); delete cacheInfo[key]; cleaned++; } }); // 更新缓存信息 if (cleaned > 0) { uni.setStorageSync('video_cache_info', cacheInfo); console.log(`[CacheManager] 已清理 ${cleaned} 个过期缓存`); } return cleaned; } catch (e) { console.error('[CacheManager] 清理缓存失败:', e); return 0; } } /** * 清理最旧的缓存(当缓存数量超过限制时) */ export function cleanOldestCache() { try { const cacheInfo = uni.getStorageSync('video_cache_info') || {}; const cacheList = Object.keys(cacheInfo).map(key => ({ key, ...cacheInfo[key] })); // 如果缓存数量未超过限制,不需要清理 if (cacheList.length <= MAX_CACHE_SIZE) { return 0; } // 按时间排序,删除最旧的 cacheList.sort((a, b) => a.time - b.time); const toDelete = cacheList.length - MAX_CACHE_SIZE; let cleaned = 0; for (let i = 0; i < toDelete; i++) { const cache = cacheList[i]; console.log('[CacheManager] 清理旧缓存:', cache.url); // 删除文件 uni.removeSavedFile({ filePath: cache.path, success: () => { console.log('[CacheManager] 文件已删除:', cache.path); } }); // 删除映射 uni.removeStorageSync(cache.key); delete cacheInfo[cache.key]; cleaned++; } // 更新缓存信息 if (cleaned > 0) { uni.setStorageSync('video_cache_info', cacheInfo); console.log(`[CacheManager] 已清理 ${cleaned} 个旧缓存`); } return cleaned; } catch (e) { console.error('[CacheManager] 清理缓存失败:', e); return 0; } } /** * 获取缓存统计信息 */ export function getCacheStats() { try { const cacheInfo = uni.getStorageSync('video_cache_info') || {}; const cacheList = Object.keys(cacheInfo); return { count: cacheList.length, maxCount: MAX_CACHE_SIZE, maxAge: MAX_CACHE_AGE }; } catch (e) { console.error('[CacheManager] 获取缓存统计失败:', e); return { count: 0, maxCount: MAX_CACHE_SIZE, maxAge: MAX_CACHE_AGE }; } } /** * 清空所有视频缓存 */ export function clearAllCache() { try { const cacheInfo = uni.getStorageSync('video_cache_info') || {}; let cleaned = 0; Object.keys(cacheInfo).forEach(key => { const cache = cacheInfo[key]; // 删除文件 uni.removeSavedFile({ filePath: cache.path, success: () => { console.log('[CacheManager] 文件已删除:', cache.path); } }); // 删除映射 uni.removeStorageSync(key); cleaned++; }); // 清空缓存信息 uni.removeStorageSync('video_cache_info'); console.log(`[CacheManager] 已清空所有缓存,共 ${cleaned} 个`); return cleaned; } catch (e) { console.error('[CacheManager] 清空缓存失败:', e); return 0; } }