-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathdb.js
More file actions
223 lines (204 loc) · 5.48 KB
/
Copy pathdb.js
File metadata and controls
223 lines (204 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import axios from 'axios';
import Dexie from 'dexie';
import store from '@/store';
// import pkg from "../../package.json";
const db = new Dexie('yesplaymusic');
db.version(4).stores({
trackDetail: '&id, updateTime',
lyric: '&id, updateTime',
album: '&id, updateTime',
});
db.version(3)
.stores({
trackSources: '&id, createTime',
})
.upgrade(tx =>
tx
.table('trackSources')
.toCollection()
.modify(
track => !track.createTime && (track.createTime = new Date().getTime())
)
);
db.version(1).stores({
trackSources: '&id',
});
let tracksCacheBytes = 0;
// 等待 settings 可用
async function waitForSettingsReady(timeoutMs = 5000) {
const interval = 100;
const maxTries = Math.ceil(timeoutMs / interval);
let tries = 0;
while (
(store.state == null ||
store.state.settings == null ||
store.state.settings.cacheLimit === undefined) &&
tries < maxTries
) {
await new Promise(resolve => setTimeout(resolve, interval));
tries++;
}
return store.state && store.state.settings;
}
// 初始化现有缓存总大小,确保应用启动时能正确判断并清理超限缓存
async function initTracksCacheBytes() {
if (!process.env.IS_ELECTRON) return;
try {
await waitForSettingsReady();
const all = await db.trackSources.toArray();
tracksCacheBytes = all.reduce(
(sum, t) => sum + (t?.source?.byteLength || 0),
0
);
console.debug(
'[debug][db.js] initTracksCacheBytes, total bytes:',
tracksCacheBytes
);
deleteExcessCache();
} catch (err) {
console.debug('[debug][db.js] initTracksCacheBytes failed', err);
}
}
// 模块加载时触发初始化
initTracksCacheBytes();
async function deleteExcessCache() {
if (
store.state.settings.cacheLimit === false ||
tracksCacheBytes < store.state.settings.cacheLimit * Math.pow(1024, 2)
) {
return;
}
try {
const delCache = await db.trackSources.orderBy('createTime').first();
await db.trackSources.delete(delCache.id);
tracksCacheBytes -= delCache.source.byteLength;
console.debug(
`[debug][db.js] deleteExcessCacheSucces, track: ${delCache.name}, size: ${delCache.source.byteLength}, cacheSize:${tracksCacheBytes}`
);
deleteExcessCache();
} catch (error) {
console.debug('[debug][db.js] deleteExcessCacheFailed', error);
}
}
export function cacheTrackSource(trackInfo, url, bitRate, from = 'netease') {
if (!process.env.IS_ELECTRON) return;
const name = trackInfo.name;
const artist =
(trackInfo.ar && trackInfo.ar[0]?.name) ||
(trackInfo.artists && trackInfo.artists[0]?.name) ||
'Unknown';
let cover = trackInfo.al.picUrl;
if (cover.slice(0, 5) !== 'https') {
cover = 'https' + cover.slice(4);
}
axios.get(`${cover}?param=512y512`);
axios.get(`${cover}?param=224y224`);
axios.get(`${cover}?param=1024y1024`);
return axios
.get(url, {
responseType: 'arraybuffer',
})
.then(response => {
db.trackSources.put({
id: trackInfo.id,
source: response.data,
bitRate,
from,
name,
artist,
createTime: new Date().getTime(),
});
console.debug(`[debug][db.js] cached track 👉 ${name} by ${artist}`);
tracksCacheBytes += response.data.byteLength;
deleteExcessCache();
return { trackID: trackInfo.id, source: response.data, bitRate };
});
}
export function getTrackSource(id) {
return db.trackSources.get(Number(id)).then(track => {
if (!track) return null;
console.debug(
`[debug][db.js] get track from cache 👉 ${track.name} by ${track.artist}`
);
return track;
});
}
export function cacheTrackDetail(track, privileges) {
db.trackDetail.put({
id: track.id,
detail: track,
privileges: privileges,
updateTime: new Date().getTime(),
});
}
export function getTrackDetailFromCache(ids) {
return db.trackDetail
.filter(track => {
return ids.includes(String(track.id));
})
.toArray()
.then(tracks => {
const result = { songs: [], privileges: [] };
ids.map(id => {
const one = tracks.find(t => String(t.id) === id);
result.songs.push(one?.detail);
result.privileges.push(one?.privileges);
});
if (result.songs.includes(undefined)) {
return undefined;
}
return result;
});
}
export function cacheLyric(id, lyrics) {
db.lyric.put({
id,
lyrics,
updateTime: new Date().getTime(),
});
}
export function getLyricFromCache(id) {
return db.lyric.get(Number(id)).then(result => {
if (!result) return undefined;
return result.lyrics;
});
}
export function cacheAlbum(id, album) {
db.album.put({
id: Number(id),
album,
updateTime: new Date().getTime(),
});
}
export function getAlbumFromCache(id) {
return db.album.get(Number(id)).then(result => {
if (!result) return undefined;
return result.album;
});
}
export function countDBSize() {
const trackSizes = [];
return db.trackSources
.each(track => {
trackSizes.push(track.source.byteLength);
})
.then(() => {
const res = {
bytes: trackSizes.reduce((s1, s2) => s1 + s2, 0),
length: trackSizes.length,
};
tracksCacheBytes = res.bytes;
console.debug(
`[debug][db.js] load tracksCacheBytes: ${tracksCacheBytes}`
);
return res;
});
}
export function clearDB() {
return new Promise(resolve => {
db.tables.forEach(function (table) {
table.clear();
});
resolve();
});
}