mirror of https://github.com/calzoneman/sync.git
Fix subtitles race condition
This commit is contained in:
parent
eb02ad0836
commit
66b08f53d1
|
@ -17,6 +17,7 @@ function md5(input) {
|
|||
|
||||
var slice = Array.prototype.slice;
|
||||
var subtitleDir = path.resolve(__dirname, '..', 'google-drive-subtitles');
|
||||
var subtitleLock = {};
|
||||
var ONE_HOUR = 60 * 60 * 1000;
|
||||
var ONE_DAY = 24 * ONE_HOUR;
|
||||
|
||||
|
@ -86,19 +87,23 @@ function handleGetSubtitles(req, res) {
|
|||
var file = [id, lang, md5(name)].join('_') + '.vtt';
|
||||
var fileAbsolute = path.join(subtitleDir, file);
|
||||
|
||||
fs.exists(fileAbsolute, function (exists) {
|
||||
if (exists) {
|
||||
res.sendFile(file, { root: subtitleDir });
|
||||
} else {
|
||||
fetchSubtitles(id, lang, name, vid, fileAbsolute, function (err) {
|
||||
if (err) {
|
||||
Logger.errlog.log(err.stack);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
takeSubtitleLock(fileAbsolute, function () {
|
||||
fs.exists(fileAbsolute, function (exists) {
|
||||
if (exists) {
|
||||
res.sendFile(file, { root: subtitleDir });
|
||||
});
|
||||
}
|
||||
delete subtitleLock[fileAbsolute];
|
||||
} else {
|
||||
fetchSubtitles(id, lang, name, vid, fileAbsolute, function (err) {
|
||||
delete subtitleLock[fileAbsolute];
|
||||
if (err) {
|
||||
Logger.errlog.log(err.stack);
|
||||
return res.sendStatus(500);
|
||||
}
|
||||
|
||||
res.sendFile(file, { root: subtitleDir });
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -169,5 +174,22 @@ function clearOldSubtitles() {
|
|||
});
|
||||
}
|
||||
|
||||
function takeSubtitleLock(filename, cb) {
|
||||
if (!subtitleLock.hasOwnProperty(filename)) {
|
||||
subtitleLock[filename] = true;
|
||||
return setImmediate(cb);
|
||||
}
|
||||
|
||||
var tries = 1;
|
||||
var interval = setInterval(function () {
|
||||
tries++;
|
||||
if (!subtitleLock.hasOwnProperty(filename) || tries >= 5) {
|
||||
subtitleLock[filename] = true;
|
||||
clearInterval(interval);
|
||||
return setImmediate(cb);
|
||||
}
|
||||
}, 200);
|
||||
}
|
||||
|
||||
setInterval(clearOldSubtitles, ONE_HOUR);
|
||||
clearOldSubtitles();
|
||||
|
|
Loading…
Reference in New Issue