cache-service.js 19.1 KB
Newer Older
范雪寒's avatar
范雪寒 committed
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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
/*
 Copyright 2014 Google Inc. All Rights Reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

// While overkill for this specific sample in which there is only one cache,
// this is one best practice that can be followed in general to keep track of
// multiple caches used by a given service worker, and keep them all versioned.
// It maps a shorthand identifier for a cache to a specific, versioned cache name.

// Note that since global state is discarded in between service worker restarts, these
// variables will be reinitialized each time the service worker handles an event, and you
// should not attempt to change their values inside an event handler. (Treat them as constants.)

// If at any point you want to force pages that use this service worker to start using a fresh
// cache, then increment the CACHE_VERSION value. It will kick off the service worker update
// flow and the old cache(s) will be purged as part of the activate event handler when the
// updated service worker is activated.
var CACHE_SID = 0;
var CACHE_VER = '';
var isPlayerPage = false;
// var CURRENT_CACHES = {};
// var CURRENT_CACHES = null;

async function progressDownloader(urlOrRequest, port, sid) {
  let url = urlOrRequest;
  let response = await fetch(url);
  if (urlOrRequest instanceof Request) {
    url = urlOrRequest.url;
  }
  let isBin = false;
  if (url.endsWith('.mp4')
    || url.endsWith('.mp3')
    || url.endsWith('.jpg')
    || url.endsWith('.png')){
    isBin = true;
  }

  const reader = response.body.getReader();
  const contentLength = +response.headers.get('Content-Length');
  port.postMessage({
    len: contentLength,
    status: 'init',
    sid
  });
  let receivedLength = 0;
  let mb = 0;
  let timeS = new Date().getTime();
  let timeD = 0;
  let speed = 0;
  let chunks = []; // array of received binary chunks (comprises the body)
  while(true) {
    const {done, value} = await reader.read();
    if (done) {
      break;
    }
    chunks.push(value);
    receivedLength += value.length;
    /*mb += value.length;
    if(mb > 1000 * 1000) {
      timeD = new Date().getTime() - timeS;
      // timeD = timeD /1000;
      speed = mb / timeD;
      mb = 0;
      timeS = new Date().getTime();
    }*/
    // console.log(`Received ${receivedLength} of ${contentLength}`)
    // cb && cb(receivedLength , contentLength)
    port.postMessage({
      loaded: value.length,
      status: 'downloading',
      sid
    });
  }

  if (isBin) {
    return new Blob(chunks);
  } else {
    let chunksAll = new Uint8Array(receivedLength);
    let position = 0;
    for(let chunk of chunks) {
      chunksAll.set(chunk, position);
      position += chunk.length;
    }
    return chunksAll; //new TextDecoder("utf-8").decode(chunksAll);
  }

}
self.addEventListener('install', function(event) {
  event.waitUntil(self.skipWaiting()); // Activate worker immediately
});

self.addEventListener('activate', function(event) {
  event.waitUntil(self.clients.claim({
    includeUncontrolled: true
  }).then(function() {
    // After the activation and claiming is complete, send a message to each of the controlled
    // pages letting it know that it's active.
    // This will trigger navigator.serviceWorker.onmessage in each client.
    return self.clients.matchAll().then(function(clients) {
      return Promise.all(clients.map(function(client) {
        // return client.postMessage('The service worker has activated and ' +
        //   'taken control.');
        return client.postMessage({
          name: 'initOk',
        });

      }));
    });
  })); // Become available to all pages
});
/*
self.addEventListener('activate', function(event) {
  // Delete all caches that aren't named in CURRENT_CACHES.
  // While there is only one cache in this example, the same logic will handle the case where
  // there are multiple versioned caches.
  // var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
  //   return CURRENT_CACHES[key];
  // });

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      // return Promise.all(
      //   cacheNames.map(function(cacheName) {
      //     if (expectedCacheNames.indexOf(cacheName) === -1) {
      //       // If this cache name isn't present in the array of "expected" cache names, then delete it.
      //       console.log('Deleting out of date cache:', cacheName);
      //       return caches.delete(cacheName);
      //     }
      //   })
      // );
    }).then(function() {
      return clients.claim();
    }).then(function() {
      // After the activation and claiming is complete, send a message to each of the controlled
      // pages letting it know that it's active.
      // This will trigger navigator.serviceWorker.onmessage in each client.
      return self.clients.matchAll().then(function(clients) {
        return Promise.all(clients.map(function(client) {
          return client.postMessage('The service worker has activated and ' +
            'taken control.');
        }));
      });
    })
  );
});*/

self.addEventListener('message', function(event) {
  // console.log('Handling message event:', event);
  if (event.data.command === 'remove') {
    if (!event.data.key) {
      return;
    }
    caches.delete(event.data.key)
    /*caches.keys().then(function(cacheNames) {
      console.log('clear', cacheNames);
      // return caches.delete(event.data.ver);
      // CACHE_VER = event.data.newVer;
      // CACHE_SID = event.data.sid;
      if (!event.data.key) {
        return;
      }
      return caches.delete(event.data.key);
      return Promise.all(
        cacheNames.map(function(cacheName) {
          if ( cache_ver === cacheName) {
            // If this cache name isn't present in the array of "expected" cache names, then delete it.
            console.log('Deleting out of date cache:', cacheName);
            // localStorage.removeItem('item-cache-'+event.data.sid);
            // self.clients.matchAll().then(function(clients) {
            //   clients.forEach(function(client) {
            //     client.postMessage({
            //
            //     });
            //   });
            // });
            console.log('delete', cacheName)
            return caches.delete(cacheName);
          }
        })
      );
    })*/
      /*.then(function() {
      return clients.claim();
    })*/
      /*.then(function() {
      // After the activation and claiming is complete, send a message to each of the controlled
      // pages letting it know that it's active.
      // This will trigger navigator.serviceWorker.onmessage in each client.
      return self.clients.matchAll().then(function(clients) {
        return Promise.all(clients.map(function(client) {
          return client.postMessage('The service worker has activated and ' +
            'taken control.');
        }));
      });
    })*/
      .then(function() {
        console.log('delete finished')
      event.ports[0].postMessage({
        error: null
      });
    });
    return;
  }
  if (event.data.command === 'clearAll') {
    event.waitUntil(
      caches.keys().then(function(cacheNames) {
        return Promise.all(
          cacheNames.map(function(cacheName) {
            return caches.delete(cacheName);
          })
        );
      }).then(function() {
        event.ports[0].postMessage({
          error: null
        });
      }).catch(err => {
        event.ports[0].postMessage({
          error: err,
        });
      })
    );
    return;
  }
  if (event.data.command === 'listCachedCoursewares') {
    var cacheData = {}
    // caches.open('item-cache-c965d3a0630911e994fa058136a96bb1-1556518161000').then(r=>{console.log(r.keys().then(items=>console.log(items[0])))})
    caches.keys().then((cacheNames) => {
      cacheNames.map((cacheName) => {
        if (cacheName.indexOf('item-cache') > -1) {
          var size = 0;
          caches.open(cacheName).then((cache) => {
            console.log(cacheName)
            cache.keys().then((requests) => {
              console.log(requests[0])
              for(var req of requests) {
                console.log(req)
                cache.match(req.url).then(resp => {
                  console.log(resp.headers.entries())
                })
              //   cache.match(req.url).then((resp) => {
              //     console.log(req.url, resp.length)
              //     size += parseInt(resp.headers['Content-Length'])
              //   }).catch(err => {
              //     console.log(err)
              //   });
              }
            }).then(() => {
              cacheData.cacheName = size;
            })
          });

        }
      });
    }).then(function(result) {
      // event.ports[0].postMessage({
      //   error: null,
      //   urls: urls
      // });
    });
    return;
  }

  // var key = 'item-cache-' + event.data.sid + '-'+ event.data.ver;
  var key = event.data.key;
  var p = caches.open(key).then(function(cache) {
    // throw {name: 'QuotaExceededError'}
    switch (event.data.command) {
      // This command returns a list of the URLs corresponding to the Request objects
      // that serve as keys for the current cache.
      case 'keys':
        return cache.keys().then(function(requests) {
          var urls = requests.map(function(request) {
            return request.url;
          });

          return urls.sort();
        }).then(function(urls) {
          // event.ports[0] corresponds to the MessagePort that was transferred as part of the controlled page's
          // call to controller.postMessage(). Therefore, event.ports[0].postMessage() will trigger the onmessage
          // handler from the controlled page.
          // It's up to you how to structure the messages that you send back; this is just one example.
          event.ports[0].postMessage({
            error: null,
            urls: urls
          });
        });

      // This command adds a new request/response pair to the cache.
      case 'add':
        // If event.data.url isn't a valid URL, new Request() will throw a TypeError which will be handled
        // by the outer .catch().
        // Hardcode {mode: 'no-cors} since the default for new Requests constructed from strings is to require
        // CORS, and we don't have any way of knowing whether an arbitrary URL that a user entered supports CORS.
        var request = new Request(event.data.url, {mode: 'cors', cache: 'reload'}); //  {mode: 'no-cors'}
        // console.log('start', event.data.url);
        // return fetch(request)
        //   .then(function(res){
        //     return res.arrayBuffer();
        //   })
          const startTime = new Date().getTime();
          let len = 0;
          return progressDownloader(request, event.ports[0], event.data.sid).then((ab) => {
            var cl = ab.size ? ab.size : ab.byteLength;
            len = cl;
            return cache.put(event.data.url, new Response(ab, {
              // url: event.data.url,
              // type: 'cors',
              status: 200,
              statusText: 'OK',
              headers: [
                ['Content-Length', cl+''],
              ]
            }));
          }).then(function(r) {
            event.ports[0].postMessage({
              error: null,
              status: 'finished',
              len: len,
              time: new Date().getTime() - startTime
            });
          });

      // This command removes a request/response pair from the cache (assuming it exists).
      case 'delete':
        return cache.delete(event.data.url).then(function(success) {
          event.ports[0].postMessage({
            error: success ? null : 'Item was not found in the cache.'
          });
        });

      default:
        // This will be handled by the outer .catch().
        throw Error('Unknown command: ' + event.data.command);
    }
  }).catch(function(error) {
    // If the promise rejects, handle it by returning a standardized error message to the controlled page.
    console.log('Message handling failed:', event.data.url, error);
    // if (error.name == 'QuotaExceededError') {
      event.ports[0].postMessage({
        //error: {name: 'QuotaExceededError'}
        error: {name: error.name, message: error.message},
        status: 'error'
      });
    // }
  });

  // Beginning in Chrome 51, event is an ExtendableMessageEvent, which supports
  // the waitUntil() method for extending the lifetime of the event handler
  // until the promise is resolved.
  if ('waitUntil' in event) {
    event.waitUntil(p);
  }

  // Without support for waitUntil(), there's a chance that if the promise chain
  // takes "too long" to execute, the service worker might be automatically
  // stopped before it's complete.
});


self.addEventListener('fetch', function(event) {

  // console.log('Handling fetch event for', event.request.method, event.request.url);
  // if (event.request.method !== 'GET' || !CACHE_SID || !CACHE_VER) {
  //   event.respondWith(function(){
  //     return fetch(request).then(networkResponse => {
  //       return networkResponse;
  //     }).catch(_ => {
  //       console.error('direct Fetching failed:', error);
  //
  //       throw error;
  //     })
  //   });
  //
  //   return;
  // }

  /*if (!CACHE_SID || !CACHE_VER) {
    event.request.mode = 'no-cors';
    return fetch(event.request).then(function(response) {
      // console.log('Response from network is:', response);
      console.log(999)
      return response;
    }).catch(function(error) {
      // This catch() will handle exceptions thrown from the fetch() operation.
      // Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
      // It will return a normal response object that has the appropriate error code set.
      console.error('Fetching failed 9:', error);

      throw error;
    });
  }*/
  // var isNormReq = !CACHE_SID || !CACHE_VER;
  // var key = 'item-cache-' + CACHE_SID + '-'+ CACHE_VER;
  if (event.request.method == 'GET' ) {
    if (event.request.headers.get('range')) {
      var pos =
        Number(/^bytes\=(\d+)\-$/g.exec(event.request.headers.get('range'))[1]);
      // console.log('Range request for', event.request.url,
      //   ', starting position:', pos);
      event.respondWith(
        caches.match(event.request.url, {
          ignoreSearch: true,
          ignoreVary: true
        }).then(function(response) {
          if (response) {
            console.log('Found response in cache:', event.request.url);
            return response.arrayBuffer().then(ab => {
              return new Response(
                ab.slice(pos),
                {
                  status: 206,
                  statusText: 'Partial Content',
                  headers: [
                    ['Content-Length', ab.byteLength+''],
                    ['Content-Range', 'bytes ' + pos + '-' +
                    (ab.byteLength - 1) + '/' + ab.byteLength]]
                });
            });

            // return response;
          }
          // event.request.mode = 'cors';
          // event.request.cache = 'reload';
          var request = new Request(event.request.url,
            {
              method: event.request.method,
              mode: 'cors',
              cache: 'reload',
              headers: event.request.headers
            });
          return fetch(request).then(function(response) {
            console.log('Response from network is:', event.request.url);
            return response;
          })/*.then(res => {
            return res.arrayBuffer();
          }).then(ab => {
            return new Response(
              ab.slice(pos),
              {
                status: 206,
                statusText: 'Partial Content',
                headers: [
                  ['Content-Length', ab.byteLength+''],
                  ['Content-Range', 'bytes ' + pos + '-' +
                  (ab.byteLength - 1) + '/' + (pos + ab.byteLength)]]
              });
          })*/
        })
        /*caches.open(key)
          .then(function(cache) {
            return cache.match(event.request.url);
          }).then(function(res) {
          if (!res) {
            return fetch(event.request)
              .then(res => {
                return res.arrayBuffer();
              });
          }
          return res.arrayBuffer();
        }).then(function(ab) {
          return new Response(
            ab.slice(pos),
            {
              status: 206,
              statusText: 'Partial Content',
              headers: [
                ['Content-Length', ab.byteLength+''],
                ['Content-Range', 'bytes ' + pos + '-' +
                (ab.byteLength - 1) + '/' + ab.byteLength]]
            });
        })*/
      );
    } else {
      // console.log('Non-range request for', event.request.url);
      event.respondWith(
        // caches.match() will look for a cache entry in all of the caches available to the service worker.
        // It's an alternative to first opening a specific named cache and then matching on that.
        caches.match(event.request, {
          ignoreSearch: true,
          ignoreVary: true
        }).then(function(response) {
          if (response) {
            // console.log('%c Response in cache:', 'color:DodgerBlue;', response);
            return response;
          }

          // event.request will always have the proper mode set ('cors, 'no-cors', etc.) so we don't
          // have to hardcode 'no-cors' like we do when fetch()ing in the install handler.
          // event.request.mode = 'cors';
          // cache: 'reload'
          if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
            return;
          }
          // console.log('No response found in cache.', event.request.url);
          return fetch(event.request).then(function(response) {
            // console.log('%c Response from network is:', 'color:#bada55', response);

            return response;
          }).catch(function(error) {
            // This catch() will handle exceptions thrown from the fetch() operation.
            // Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
            // It will return a normal response object that has the appropriate error code set.
            console.error('Fetching failed:', error);

            // throw error;
          });
        })
      );
    }
  } else {
    event.respondWith(
      fetch(event.request).then(function(response) {
        // console.log('not get from network:', response);
        // console.log(888)
        return response;
      }).catch(function(error) {
        // This catch() will handle exceptions thrown from the fetch() operation.
        // Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
        // It will return a normal response object that has the appropriate error code set.
        console.error('Fetching failed 8:', error);
        throw error;
      })
    );
  }
});