73 lines
1.9 KiB
Go
73 lines
1.9 KiB
Go
package universal
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/debridmediamanager/zurg/internal/torrent"
|
|
"github.com/debridmediamanager/zurg/pkg/logutil"
|
|
)
|
|
|
|
func HandleHeadRequest(directory, torrentName, fileName string, w http.ResponseWriter, req *http.Request, torMgr *torrent.TorrentManager, log *logutil.Logger) {
|
|
|
|
torrents, ok := torMgr.DirectoryMap.Get(directory)
|
|
if !ok {
|
|
log.Warnf("Cannot find directory %s", directory)
|
|
http.Error(w, "File not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
torrent, ok := torrents.Get(torrentName)
|
|
if !ok {
|
|
log.Warnf("Cannot find torrent %s from path %s", torrentName, req.URL.Path)
|
|
http.Error(w, "File not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
file, ok := torrent.SelectedFiles.Get(fileName)
|
|
if !ok {
|
|
log.Warnf("Cannot find file %s from path %s", fileName, req.URL.Path)
|
|
http.Error(w, "Cannot find file", http.StatusNotFound)
|
|
return
|
|
}
|
|
if !strings.HasPrefix(file.Link, "http") {
|
|
// This is a dead file, serve an alternate file
|
|
log.Warnf("File %s is no longer available", fileName)
|
|
http.Error(w, "Cannot find file", http.StatusNotFound)
|
|
return
|
|
}
|
|
contentType := getContentMimeType(fileName)
|
|
contentLength := fmt.Sprintf("%d", file.Bytes)
|
|
lastModified := file.Ended
|
|
w.Header().Set("Content-Type", contentType)
|
|
w.Header().Set("Content-Length", contentLength)
|
|
w.Header().Set("Last-Modified", lastModified)
|
|
w.WriteHeader(http.StatusOK)
|
|
}
|
|
|
|
func getContentMimeType(filePath string) string {
|
|
switch filepath.Ext(filePath) {
|
|
case ".mkv":
|
|
return "video/x-matroska"
|
|
case ".mp4":
|
|
return "video/mp4"
|
|
case ".avi":
|
|
return "video/x-msvideo"
|
|
case ".wmv":
|
|
return "video/x-ms-wmv"
|
|
case ".m4v":
|
|
return "video/x-m4v"
|
|
case ".mp3":
|
|
return "audio/mpeg"
|
|
case ".rar":
|
|
return "application/x-rar-compressed"
|
|
case ".zip":
|
|
return "application/zip"
|
|
case ".txt":
|
|
return "text/plain"
|
|
default:
|
|
return "application/octet-stream"
|
|
}
|
|
}
|