0

I want to reproduce music files from google drive on a web page. I have the link for each file but the response cache headers for the calls are 'no-cache, no-store, max-age=0, must-revalidate" so it will never be saved on the browser cache. Is there any way to add cache to google drive files requests?

The problem:

When you use the drive link for a music file (mp3) https://drive.google.com/a/pucp.pe/uc?id=1kYYS9FZ9Vxif5WJM9ZQcY4SR35NMgoIE&export=download the GET API call receives a 302 code which generates a redirect to another URL, in this case, to 'https://doc-0o-28-docs.googleusercontent.com/docs/securesc/bgp95l3eabkkpccn0qi0qopvc4e7d4mq/us95e8ush1v4b7vvijq1vj1d7ru4rlpo/1556330400000/01732506421897009934/01732506421897009934/1kYYS9FZ9Vxif5WJM9ZQcY4SR35NMgoIE?h=14771753379018855219&e=download'. Each of these calls has no-cache in headers.

  1. I tried using workbox (cache API) but I don't find a way to cache redirects, probably I need to cache both calls (the first GET and the redirect). However, if I use the redirected URL the caching works, but I don't have access to that URL until the first call is made.

  2. I tried to use a proxy server from a NodeJS server

app.get("/test", (req, res) => {
    try {
      https.get(
        URL,
        function(response) {
          res.writeHead(response.statusCode, {...response.headers, 
            "Cache-Control": "public, max-age=120",
            "Expires": new Date(Date.now() + 120000).toUTCString() })

          response.pipe(res);
        }
      );
    } catch (e) {
      console.log(e);
    }
  });

I tried using the first URL with no luck. I tried using the redirect URL but I get a "Status Code: 302 Found"

One solution could be to download the file and serve it directly from my server but I will be missing the point of using the drive storage. I really want to use google drive storage and not duplicate all files on my server.

Is there a recommended way to do the caching for this case? maybe there is some google drive configuration that I'm missing. Or do you know another approach I could take in this case?

Juan Carlos
  • 40
  • 1
  • 6

1 Answers1

0

You should be able to cache redirected responses using Workbox (and the Cache Storage API in general). HTTP 30x redirects are followed automatically by default, and you should only have to route the original, non-redirected URL.

Here's a live example of a Glitch project that uses Workbox to cache that MP3 file: https://glitch.com/edit/#!/horn-sausage?path=sw.js:9:0

The relevant snippet of code, that also accounts for the fact that there is no CORS used when serving the files (so you'll get back an opaque response with a status of 0) is:

workbox.routing.registerRoute(
  new RegExp('https://drive.google.com/'),
  new workbox.strategies.CacheFirst({
    plugins: [
      new workbox.cacheableResponse.Plugin({statuses: [0, 200]})
    ],
  })
);
Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167