2015-12-06 21:32:41 +01:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
var Launcher = require('../comp/launcher');
|
|
|
|
|
|
|
|
var StorageFileCache = {
|
|
|
|
name: 'cache',
|
|
|
|
enabled: !!Launcher,
|
|
|
|
|
|
|
|
path: null,
|
|
|
|
|
|
|
|
getPath: function(id) {
|
|
|
|
return Launcher.req('path').join(this.path, id);
|
|
|
|
},
|
|
|
|
|
|
|
|
init: function(callback) {
|
|
|
|
if (this.path) {
|
2015-12-07 22:00:44 +01:00
|
|
|
return callback && callback();
|
2015-12-06 21:32:41 +01:00
|
|
|
}
|
2015-12-07 22:00:44 +01:00
|
|
|
try {
|
|
|
|
var path = Launcher.getUserDataPath('OfflineFiles');
|
|
|
|
var fs = Launcher.req('fs');
|
|
|
|
if (!fs.existsSync(path)) {
|
|
|
|
fs.mkdirSync(path);
|
2015-12-06 21:32:41 +01:00
|
|
|
}
|
2015-12-07 22:00:44 +01:00
|
|
|
this.path = path;
|
|
|
|
} catch (e) {
|
|
|
|
console.error('Error opening local offline storage', e);
|
|
|
|
if (callback) { callback(e); }
|
2015-12-06 21:32:41 +01:00
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
save: function(id, data, callback) {
|
|
|
|
this.init((function(err) {
|
|
|
|
if (err) {
|
2015-12-07 22:00:44 +01:00
|
|
|
return callback && callback(err);
|
2015-12-06 21:32:41 +01:00
|
|
|
}
|
|
|
|
try {
|
2015-12-07 22:00:44 +01:00
|
|
|
Launcher.writeFile(this.getPath(id), data);
|
|
|
|
if (callback) { callback(); }
|
2015-12-06 21:32:41 +01:00
|
|
|
} catch (e) {
|
|
|
|
console.error('Error saving to cache', id, e);
|
2015-12-07 22:00:44 +01:00
|
|
|
if (callback) { callback(e); }
|
2015-12-06 21:32:41 +01:00
|
|
|
}
|
|
|
|
}).bind(this));
|
|
|
|
},
|
|
|
|
|
|
|
|
load: function(id, callback) {
|
|
|
|
this.init((function(err) {
|
|
|
|
if (err) {
|
2015-12-07 22:00:44 +01:00
|
|
|
return callback && callback(null, err);
|
2015-12-06 21:32:41 +01:00
|
|
|
}
|
|
|
|
try {
|
2015-12-07 22:00:44 +01:00
|
|
|
var data = Launcher.readFile(this.getPath(id));
|
|
|
|
if (callback) { callback(null, data.buffer); }
|
2015-12-06 21:32:41 +01:00
|
|
|
} catch (e) {
|
|
|
|
console.error('Error loading from cache', id, e);
|
2015-12-07 22:00:44 +01:00
|
|
|
if (callback) { callback(e, null); }
|
2015-12-06 21:32:41 +01:00
|
|
|
}
|
|
|
|
}).bind(this));
|
|
|
|
},
|
|
|
|
|
|
|
|
remove: function(id, callback) {
|
|
|
|
this.init((function(err) {
|
|
|
|
if (err) {
|
2015-12-07 22:00:44 +01:00
|
|
|
return callback && callback(err);
|
2015-12-06 21:32:41 +01:00
|
|
|
}
|
|
|
|
try {
|
2015-12-07 22:20:18 +01:00
|
|
|
var path = this.getPath(id);
|
|
|
|
if (Launcher.fileExists(path)) {
|
|
|
|
Launcher.deleteFile(path);
|
|
|
|
}
|
2015-12-07 22:00:44 +01:00
|
|
|
if (callback) { callback(); }
|
2015-12-06 21:32:41 +01:00
|
|
|
} catch(e) {
|
|
|
|
console.error('Error removing from cache', id, e);
|
2015-12-07 22:00:44 +01:00
|
|
|
if (callback) { callback(e); }
|
2015-12-06 21:32:41 +01:00
|
|
|
}
|
|
|
|
}).bind(this));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = StorageFileCache;
|