Source: lib/offline/offline_scheme.js

  1. /**
  2. * @license
  3. * Copyright 2016 Google Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. goog.provide('shaka.offline.OfflineScheme');
  18. goog.require('shaka.net.NetworkingEngine');
  19. goog.require('shaka.offline.OfflineUtils');
  20. goog.require('shaka.util.Error');
  21. /**
  22. * @namespace
  23. * @summary A plugin that handles requests for offline content.
  24. * @param {string} uri
  25. * @param {shakaExtern.Request} request
  26. * @return {!Promise.<shakaExtern.Response>}
  27. * @export
  28. */
  29. shaka.offline.OfflineScheme = function(uri, request) {
  30. var manifestParts = /^offline:([0-9]+)$/.exec(uri);
  31. if (manifestParts) {
  32. /** @type {shakaExtern.Response} */
  33. var response = {
  34. uri: uri,
  35. data: new ArrayBuffer(0),
  36. headers: {'content-type': 'application/x-offline-manifest'}
  37. };
  38. return Promise.resolve(response);
  39. }
  40. var segmentParts = /^offline:[0-9]+\/[0-9]+\/([0-9]+)$/.exec(uri);
  41. if (segmentParts) {
  42. var segmentId = Number(segmentParts[1]);
  43. var scheme = shaka.offline.OfflineUtils.DB_SCHEME;
  44. var storageEngine = shaka.offline.OfflineUtils.createStorageEngine();
  45. if (!storageEngine) {
  46. return Promise.reject(new shaka.util.Error(
  47. shaka.util.Error.Severity.CRITICAL,
  48. shaka.util.Error.Category.STORAGE,
  49. shaka.util.Error.Code.STORAGE_NOT_SUPPORTED));
  50. }
  51. return storageEngine.init(scheme)
  52. .then(function() { return storageEngine.get('segment', segmentId); })
  53. .then(function(segment) {
  54. return storageEngine.destroy().then(function() {
  55. if (!segment) {
  56. throw new shaka.util.Error(
  57. shaka.util.Error.Severity.CRITICAL,
  58. shaka.util.Error.Category.STORAGE,
  59. shaka.util.Error.Code.REQUESTED_ITEM_NOT_FOUND, segmentId);
  60. }
  61. return {uri: uri, data: segment.data, headers: {}};
  62. });
  63. });
  64. }
  65. return Promise.reject(new shaka.util.Error(
  66. shaka.util.Error.Severity.CRITICAL,
  67. shaka.util.Error.Category.NETWORK,
  68. shaka.util.Error.Code.MALFORMED_OFFLINE_URI, uri));
  69. };
  70. shaka.net.NetworkingEngine.registerScheme(
  71. 'offline', shaka.offline.OfflineScheme);