bykof / cordova-plugin-webserver

A webserver plugin for cordova
Other
119 stars 51 forks source link

Partial Content Support (i.e. streaming videos) #41

Closed nadinengland closed 4 years ago

nadinengland commented 4 years ago

Hey @bykof,

First off, superb Cordova plugin. It's been a life saver having GCGWebServer wrapped and packaged up neatly.

I am using the local webserver as a proxy for cdvfile:// urls, which works great but I've come across an issue. In order to get it working I've had to send the Accept-Ranges header when I am serving video files:

// entry is a cordova-plugin-file 
webserver.sendResponse(request.requestId, {
    path: entry.nativeURL.replace('file://', ''),
    headers: {
        'Content-Type': file.type,
        'Accept-Ranges': 'bytes',
        'Access-Control-Allow-Origin': '*',
    },
});

This does indeed trigger the web view to request the content in chunks, however in order to get GCDWebServer to respond with partial content I've had to make changes to Webserver.swift:


-    func fileRequest(path: String) -> GCDWebServerResponse {
+    func fileRequest(request: GCDWebServerRequest, path: String) -> GCDWebServerResponse {
         // Check if file exists, given its path
         if !(FileManager.default.fileExists(atPath: path)) {
             return GCDWebServerResponse(statusCode: 404);
         }

+         if (request.hasByteRange()) {
+             return GCDWebServerFileResponse(file: path, byteRange: request.byteRange)!
+         }
+        
         return GCDWebServerFileResponse(file: path)!
     }
         // Check if a file path is provided else use regular data response
         let response = responseDict["path"] != nil
-             ? fileRequest(responseDict["path"] as! String)
+             ? fileRequest(request: request, path: responseDict["path"] as! String)
              : GCDWebServerDataResponse(text: responseDict["body"] as! String)

(I'm not 100% certain on the swift/obj-c inter-op, but I presume it is using this method: https://github.com/swisspol/GCDWebServer/blob/master/GCDWebServer/Responses/GCDWebServerFileResponse.h#L94)

Can you see any issues with doing this? If not, and you think it'd be useful I'll send over a pull request.

bykof commented 4 years ago

Hi @nadinengland, first of all thank you for contributing. Second, could you please adapt the android implementation as well?

nadinengland commented 4 years ago

From what I can tell it appears the android code is already setup to support this. I'll test it out locally and report back.

https://github.com/bykof/cordova-plugin-webserver/blob/master/src/android/NanoHTTPDWebserver.java#L100-L113

nadinengland commented 4 years ago

I've tested this on my real android device and it does instead appear to already work, which is brilliant news. I'll setup a pull request now.