babylon.database.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. module BABYLON {
  2. export class Database {
  3. private callbackManifestChecked: (boolean) => any;
  4. private currentSceneUrl: string;
  5. private db: IDBDatabase;
  6. private enableSceneOffline: boolean;
  7. private enableTexturesOffline: boolean;
  8. private manifestVersionFound: number;
  9. private mustUpdateRessources: boolean;
  10. private hasReachedQuota: boolean;
  11. private isSupported: boolean;
  12. // Handling various flavors of prefixed version of IndexedDB
  13. private idbFactory = <IDBFactory> (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14. static IsUASupportingBlobStorage = true;
  15. static IDBStorageEnabled = true;
  16. constructor(urlToScene: string, callbackManifestChecked: (checked: boolean) => any) {
  17. this.callbackManifestChecked = callbackManifestChecked;
  18. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  19. this.db = null;
  20. this.enableSceneOffline = false;
  21. this.enableTexturesOffline = false;
  22. this.manifestVersionFound = 0;
  23. this.mustUpdateRessources = false;
  24. this.hasReachedQuota = false;
  25. if (!Database.IDBStorageEnabled) {
  26. this.callbackManifestChecked(true);
  27. } else {
  28. this.checkManifestFile();
  29. }
  30. }
  31. static parseURL = (url: string) => {
  32. var a = document.createElement('a');
  33. a.href = url;
  34. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  35. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  36. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  37. return absLocation;
  38. }
  39. static ReturnFullUrlLocation = (url: string): string => {
  40. if (url.indexOf("http:/") === -1) {
  41. return (Database.parseURL(window.location.href) + url);
  42. }
  43. else {
  44. return url;
  45. }
  46. }
  47. public checkManifestFile() {
  48. function noManifestFile() {
  49. that.enableSceneOffline = false;
  50. that.enableTexturesOffline = false;
  51. that.callbackManifestChecked(false);
  52. }
  53. var that = this;
  54. var timeStampUsed = false;
  55. var manifestURL = this.currentSceneUrl + ".manifest";
  56. var xhr: XMLHttpRequest = new XMLHttpRequest();
  57. if (navigator.onLine) {
  58. // Adding a timestamp to by-pass browsers' cache
  59. timeStampUsed = true;
  60. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61. }
  62. xhr.open("GET", manifestURL, true);
  63. xhr.addEventListener("load",() => {
  64. if (xhr.status === 200 || Tools.ValidateXHRData(xhr, 1)) {
  65. try {
  66. var manifestFile = JSON.parse(xhr.response);
  67. this.enableSceneOffline = manifestFile.enableSceneOffline;
  68. this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  69. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  70. this.manifestVersionFound = manifestFile.version;
  71. }
  72. if (this.callbackManifestChecked) {
  73. this.callbackManifestChecked(true);
  74. }
  75. }
  76. catch (ex) {
  77. noManifestFile();
  78. }
  79. }
  80. else {
  81. noManifestFile();
  82. }
  83. }, false);
  84. xhr.addEventListener("error", event => {
  85. if (timeStampUsed) {
  86. timeStampUsed = false;
  87. // Let's retry without the timeStamp
  88. // It could fail when coupled with HTML5 Offline API
  89. var retryManifestURL = this.currentSceneUrl + ".manifest";
  90. xhr.open("GET", retryManifestURL, true);
  91. xhr.send();
  92. }
  93. else {
  94. noManifestFile();
  95. }
  96. }, false);
  97. try {
  98. xhr.send();
  99. }
  100. catch (ex) {
  101. Tools.Error("Error on XHR send request.");
  102. that.callbackManifestChecked(false);
  103. }
  104. }
  105. public openAsync(successCallback, errorCallback) {
  106. function handleError() {
  107. that.isSupported = false;
  108. if (errorCallback) errorCallback();
  109. }
  110. var that = this;
  111. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  112. // Your browser doesn't support IndexedDB
  113. this.isSupported = false;
  114. if (errorCallback) errorCallback();
  115. }
  116. else {
  117. // If the DB hasn't been opened or created yet
  118. if (!this.db) {
  119. this.hasReachedQuota = false;
  120. this.isSupported = true;
  121. var request: IDBOpenDBRequest = this.idbFactory.open("babylonjs", 1);
  122. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  123. request.onerror = event => {
  124. handleError();
  125. };
  126. // executes when a version change transaction cannot complete due to other active transactions
  127. request.onblocked = event => {
  128. Tools.Error("IDB request blocked. Please reload the page.");
  129. handleError();
  130. };
  131. // DB has been opened successfully
  132. request.onsuccess = event => {
  133. this.db = request.result;
  134. successCallback();
  135. };
  136. // Initialization of the DB. Creating Scenes & Textures stores
  137. request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
  138. this.db = (<any>(event.target)).result;
  139. try {
  140. var scenesStore = this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  141. var versionsStore = this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  142. var texturesStore = this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  143. }
  144. catch (ex) {
  145. Tools.Error("Error while creating object stores. Exception: " + ex.message);
  146. handleError();
  147. }
  148. };
  149. }
  150. // DB has already been created and opened
  151. else {
  152. if (successCallback) successCallback();
  153. }
  154. }
  155. }
  156. public loadImageFromDB(url: string, image: HTMLImageElement) {
  157. var completeURL = Database.ReturnFullUrlLocation(url);
  158. var saveAndLoadImage = () => {
  159. if (!this.hasReachedQuota && this.db !== null) {
  160. // the texture is not yet in the DB, let's try to save it
  161. this._saveImageIntoDBAsync(completeURL, image);
  162. }
  163. // If the texture is not in the DB and we've reached the DB quota limit
  164. // let's load it directly from the web
  165. else {
  166. image.src = url;
  167. }
  168. };
  169. if (!this.mustUpdateRessources) {
  170. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  171. }
  172. // First time we're download the images or update requested in the manifest file by a version change
  173. else {
  174. saveAndLoadImage();
  175. }
  176. }
  177. private _loadImageFromDBAsync(url: string, image: HTMLImageElement, notInDBCallback: () => any) {
  178. if (this.isSupported && this.db !== null) {
  179. var texture;
  180. var transaction: IDBTransaction = this.db.transaction(["textures"]);
  181. transaction.onabort = event => {
  182. image.src = url;
  183. };
  184. transaction.oncomplete = event => {
  185. var blobTextureURL;
  186. if (texture) {
  187. var URL = window.URL || window.webkitURL;
  188. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  189. image.onerror = () => {
  190. Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  191. image.src = url;
  192. };
  193. image.src = blobTextureURL;
  194. }
  195. else {
  196. notInDBCallback();
  197. }
  198. };
  199. var getRequest: IDBRequest = transaction.objectStore("textures").get(url);
  200. getRequest.onsuccess = event => {
  201. texture = (<any>(event.target)).result;
  202. };
  203. getRequest.onerror = event => {
  204. Tools.Error("Error loading texture " + url + " from DB.");
  205. image.src = url;
  206. };
  207. }
  208. else {
  209. Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  210. image.src = url;
  211. }
  212. }
  213. private _saveImageIntoDBAsync(url: string, image: HTMLImageElement) {
  214. if (this.isSupported) {
  215. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  216. var generateBlobUrl = () => {
  217. var blobTextureURL;
  218. if (blob) {
  219. var URL = window.URL || window.webkitURL;
  220. try {
  221. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  222. }
  223. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  224. catch (ex) {
  225. blobTextureURL = URL.createObjectURL(blob);
  226. }
  227. }
  228. image.src = blobTextureURL;
  229. };
  230. if (Database.IsUASupportingBlobStorage) { // Create XHR
  231. var xhr = new XMLHttpRequest(),
  232. blob: Blob;
  233. xhr.open("GET", url, true);
  234. xhr.responseType = "blob";
  235. xhr.addEventListener("load",() => {
  236. if (xhr.status === 200) {
  237. // Blob as response (XHR2)
  238. blob = xhr.response;
  239. var transaction = this.db.transaction(["textures"], "readwrite");
  240. // the transaction could abort because of a QuotaExceededError error
  241. transaction.onabort = (event) => {
  242. try {
  243. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  244. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  245. this.hasReachedQuota = true;
  246. }
  247. }
  248. catch (ex) { }
  249. generateBlobUrl();
  250. };
  251. transaction.oncomplete = event => {
  252. generateBlobUrl();
  253. };
  254. var newTexture = { textureUrl: url, data: blob };
  255. try {
  256. // Put the blob into the dabase
  257. var addRequest = transaction.objectStore("textures").put(newTexture);
  258. addRequest.onsuccess = event => {
  259. };
  260. addRequest.onerror = event => {
  261. generateBlobUrl();
  262. };
  263. }
  264. catch (ex) {
  265. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  266. if (ex.code === 25) {
  267. Database.IsUASupportingBlobStorage = false;
  268. }
  269. image.src = url;
  270. }
  271. }
  272. else {
  273. image.src = url;
  274. }
  275. }, false);
  276. xhr.addEventListener("error", event => {
  277. Tools.Error("Error in XHR request in BABYLON.Database.");
  278. image.src = url;
  279. }, false);
  280. xhr.send();
  281. }
  282. else {
  283. image.src = url;
  284. }
  285. }
  286. else {
  287. Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  288. image.src = url;
  289. }
  290. }
  291. private _checkVersionFromDB(url: string, versionLoaded) {
  292. var updateVersion = event => {
  293. // the version is not yet in the DB or we need to update it
  294. this._saveVersionIntoDBAsync(url, versionLoaded);
  295. };
  296. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  297. }
  298. private _loadVersionFromDBAsync(url: string, callback, updateInDBCallback) {
  299. if (this.isSupported) {
  300. var version;
  301. try {
  302. var transaction = this.db.transaction(["versions"]);
  303. transaction.oncomplete = event => {
  304. if (version) {
  305. // If the version in the JSON file is > than the version in DB
  306. if (this.manifestVersionFound > version.data) {
  307. this.mustUpdateRessources = true;
  308. updateInDBCallback();
  309. }
  310. else {
  311. callback(version.data);
  312. }
  313. }
  314. // version was not found in DB
  315. else {
  316. this.mustUpdateRessources = true;
  317. updateInDBCallback();
  318. }
  319. };
  320. transaction.onabort = event => {
  321. callback(-1);
  322. };
  323. var getRequest = transaction.objectStore("versions").get(url);
  324. getRequest.onsuccess = event => {
  325. version = (<any>(event.target)).result;
  326. };
  327. getRequest.onerror = event => {
  328. Tools.Error("Error loading version for scene " + url + " from DB.");
  329. callback(-1);
  330. };
  331. }
  332. catch (ex) {
  333. Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  334. callback(-1);
  335. }
  336. }
  337. else {
  338. Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  339. callback(-1);
  340. }
  341. }
  342. private _saveVersionIntoDBAsync(url: string, callback) {
  343. if (this.isSupported && !this.hasReachedQuota) {
  344. try {
  345. // Open a transaction to the database
  346. var transaction = this.db.transaction(["versions"], "readwrite");
  347. // the transaction could abort because of a QuotaExceededError error
  348. transaction.onabort = event => {
  349. try {//backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  350. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  351. this.hasReachedQuota = true;
  352. }
  353. }
  354. catch (ex) { }
  355. callback(-1);
  356. };
  357. transaction.oncomplete = event => {
  358. callback(this.manifestVersionFound);
  359. };
  360. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  361. // Put the scene into the database
  362. var addRequest = transaction.objectStore("versions").put(newVersion);
  363. addRequest.onsuccess = event => {
  364. };
  365. addRequest.onerror = event => {
  366. Tools.Error("Error in DB add version request in BABYLON.Database.");
  367. };
  368. }
  369. catch (ex) {
  370. Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  371. callback(-1);
  372. }
  373. }
  374. else {
  375. callback(-1);
  376. }
  377. }
  378. private loadFileFromDB(url: string, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer?: boolean) {
  379. var completeUrl = Database.ReturnFullUrlLocation(url);
  380. var saveAndLoadFile = event => {
  381. // the scene is not yet in the DB, let's try to save it
  382. this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  383. };
  384. this._checkVersionFromDB(completeUrl, version => {
  385. if (version !== -1) {
  386. if (!this.mustUpdateRessources) {
  387. this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  388. }
  389. else {
  390. this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  391. }
  392. }
  393. else {
  394. errorCallback();
  395. }
  396. });
  397. }
  398. private _loadFileFromDBAsync(url, callback, notInDBCallback, useArrayBuffer?: boolean) {
  399. if (this.isSupported) {
  400. var targetStore: string;
  401. if (url.indexOf(".babylon") !== -1) {
  402. targetStore = "scenes";
  403. }
  404. else {
  405. targetStore = "textures";
  406. }
  407. var file;
  408. var transaction = this.db.transaction([targetStore]);
  409. transaction.oncomplete = event => {
  410. if (file) {
  411. callback(file.data);
  412. }
  413. // file was not found in DB
  414. else {
  415. notInDBCallback();
  416. }
  417. };
  418. transaction.onabort = event => {
  419. notInDBCallback();
  420. };
  421. var getRequest = transaction.objectStore(targetStore).get(url);
  422. getRequest.onsuccess = event => {
  423. file = (<any>(event.target)).result;
  424. };
  425. getRequest.onerror = event => {
  426. Tools.Error("Error loading file " + url + " from DB.");
  427. notInDBCallback();
  428. };
  429. }
  430. else {
  431. Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  432. callback();
  433. }
  434. }
  435. private _saveFileIntoDBAsync(url: string, callback, progressCallback, useArrayBuffer?: boolean) {
  436. if (this.isSupported) {
  437. var targetStore: string;
  438. if (url.indexOf(".babylon") !== -1) {
  439. targetStore = "scenes";
  440. }
  441. else {
  442. targetStore = "textures";
  443. }
  444. // Create XHR
  445. var xhr = new XMLHttpRequest(), fileData;
  446. xhr.open("GET", url, true);
  447. if (useArrayBuffer) {
  448. xhr.responseType = "arraybuffer";
  449. }
  450. xhr.onprogress = progressCallback;
  451. xhr.addEventListener("load",() => {
  452. if (xhr.status === 200 || Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  453. // Blob as response (XHR2)
  454. //fileData = xhr.responseText;
  455. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  456. if (!this.hasReachedQuota) {
  457. // Open a transaction to the database
  458. var transaction = this.db.transaction([targetStore], "readwrite");
  459. // the transaction could abort because of a QuotaExceededError error
  460. transaction.onabort = (event) => {
  461. try {
  462. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  463. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  464. this.hasReachedQuota = true;
  465. }
  466. }
  467. catch (ex) { }
  468. callback(fileData);
  469. };
  470. transaction.oncomplete = event => {
  471. callback(fileData);
  472. };
  473. var newFile;
  474. if (targetStore === "scenes") {
  475. newFile = { sceneUrl: url, data: fileData, version: this.manifestVersionFound };
  476. }
  477. else {
  478. newFile = { textureUrl: url, data: fileData };
  479. }
  480. try {
  481. // Put the scene into the database
  482. var addRequest = transaction.objectStore(targetStore).put(newFile);
  483. addRequest.onsuccess = event => {
  484. };
  485. addRequest.onerror = event => {
  486. Tools.Error("Error in DB add file request in BABYLON.Database.");
  487. };
  488. }
  489. catch (ex) {
  490. callback(fileData);
  491. }
  492. }
  493. else {
  494. callback(fileData);
  495. }
  496. }
  497. else {
  498. callback();
  499. }
  500. }, false);
  501. xhr.addEventListener("error", event => {
  502. Tools.Error("error on XHR request.");
  503. callback();
  504. }, false);
  505. xhr.send();
  506. }
  507. else {
  508. Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  509. callback();
  510. }
  511. }
  512. }
  513. }