/
media-library.js
79 lines (73 loc) · 2.62 KB
/
media-library.js
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
const xhr = require('xhr');
const LIBRARY_PREFIX = 'https://cdn.scratch.mit.edu/scratchr2/static/__8d9c95eb5aa1272a311775ca32568417__/medialibraries/';
const LIBRARY_URL = {
sprite: `${LIBRARY_PREFIX}spriteLibrary.json`,
costume: `${LIBRARY_PREFIX}costumeLibrary.json`,
backdrop: `${LIBRARY_PREFIX}backdropLibrary.json`
};
const SPRITE_OBJECT_PREFIX = 'https://cdn.assets.scratch.mit.edu/internalapi/asset/';
const SPRITE_OBJECT_SUFFIX = '/get/';
class MediaLibrary {
constructor () {
/*
* Cached library data, from JSON.
* @type {Object}
*/
this._libraryData = {};
/**
* Cached sprite data, from JSON.
* @type {Object.<!string, Object>}
*/
this._spriteData = {};
}
/**
* Get the media library data for a particular scratchr2 library.
* In the future, load this from `scratch-storage` asset manager,
* e.g., for offline support.
* @param {string} libraryType Type of library, i.e., sprite, costume, sound, backdrop.
* @param {!Function} callback Callback, called with list of data.
*/
getMediaLibrary (libraryType, callback) {
if (!this._libraryData.hasOwnProperty(libraryType)) {
this._libraryData[libraryType] = null;
}
if (this._libraryData[libraryType]) {
callback(this._libraryData[libraryType]);
} else {
xhr.get({
useXDR: true,
url: LIBRARY_URL[libraryType]
}, (err, response, body) => {
if (!err) {
const data = JSON.parse(body);
this._libraryData[libraryType] = data;
callback(this._libraryData[libraryType]);
}
});
}
}
/**
* Get media library info for a specific scratchr2 sprite.
* In the future, load this from `scratch-storage` asset manager,
* e.g., for offline support.
* @param {string} url URL to sprite (md5.json).
* @param {!Function} callback Callback, called with sprite data.
*/
getSprite (url, callback) {
if (this._spriteData.hasOwnProperty(url)) {
callback(url, this._spriteData[url]);
} else {
xhr.get({
useXDR: true,
url: SPRITE_OBJECT_PREFIX + url + SPRITE_OBJECT_SUFFIX
}, (err, response, body) => {
if (!err) {
const data = JSON.parse(body);
this._spriteData[url] = data;
callback(url, data);
}
});
}
}
}
module.exports = MediaLibrary;