1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111 |
- package share
- /*
- Arozos File Share Manager
- author: tobychui
- This module handle file share request and other stuffs
- */
- import (
- "encoding/json"
- "fmt"
- "image"
- "image/color"
- "image/draw"
- "image/jpeg"
- "io"
- "io/fs"
- "io/ioutil"
- "log"
- "math"
- "net/http"
- "net/url"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "time"
- "github.com/golang/freetype"
- "github.com/nfnt/resize"
- uuid "github.com/satori/go.uuid"
- "github.com/valyala/fasttemplate"
- "imuslab.com/arozos/mod/auth"
- "imuslab.com/arozos/mod/common"
- filesystem "imuslab.com/arozos/mod/filesystem"
- "imuslab.com/arozos/mod/filesystem/metadata"
- "imuslab.com/arozos/mod/share/shareEntry"
- "imuslab.com/arozos/mod/user"
- )
- type Options struct {
- AuthAgent *auth.AuthAgent
- UserHandler *user.UserHandler
- ShareEntryTable *shareEntry.ShareEntryTable
- HostName string
- TmpFolder string
- }
- type Manager struct {
- options Options
- }
- //Create a new Share Manager
- func NewShareManager(options Options) *Manager {
- //Return a new manager object
- return &Manager{
- options: options,
- }
- }
- func (s *Manager) HandleOPGServing(w http.ResponseWriter, r *http.Request, shareID string) {
- shareEntry := s.GetShareObjectFromUUID(shareID)
- if shareEntry == nil {
- //This share is not valid
- http.NotFound(w, r)
- return
- }
- //Overlap and generate opg
- //Load in base template
- baseTemplate, err := os.Open("./system/share/default_opg.png")
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- base, _, err := image.Decode(baseTemplate)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- //Create base canvas
- rx := image.Rectangle{image.Point{0, 0}, base.Bounds().Size()}
- resultopg := image.NewRGBA(rx)
- draw.Draw(resultopg, base.Bounds(), base, image.Point{0, 0}, draw.Src)
- //Append filename to the image
- fontBytes, err := ioutil.ReadFile("./system/share/fonts/TaipeiSansTCBeta-Light.ttf")
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- utf8Font, err := freetype.ParseFont(fontBytes)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- fontSize := float64(42)
- ctx := freetype.NewContext()
- ctx.SetDPI(72)
- ctx.SetFont(utf8Font)
- ctx.SetFontSize(fontSize)
- ctx.SetClip(resultopg.Bounds())
- ctx.SetDst(resultopg)
- ctx.SetSrc(image.NewUniform(color.RGBA{255, 255, 255, 255}))
- //Check if we need to split the filename into two lines
- filename := filepath.Base(shareEntry.FileRealPath)
- filenameOnly := strings.TrimSuffix(filename, filepath.Ext(filename))
- fs := filesystem.GetFileSize(shareEntry.FileRealPath)
- shareMeta := filepath.Ext(shareEntry.FileRealPath) + " / " + filesystem.GetFileDisplaySize(fs, 2)
- if isDir(shareEntry.FileRealPath) {
- fs, fc := filesystem.GetDirctorySize(shareEntry.FileRealPath, false)
- shareMeta = strconv.Itoa(fc) + " items / " + filesystem.GetFileDisplaySize(fs, 2)
- }
- if len([]rune(filename)) > 20 {
- //Split into lines
- lines := []string{}
- for i := 0; i < len([]rune(filenameOnly)); i += 20 {
- endPos := int(math.Min(float64(len([]rune(filenameOnly))), float64(i+20)))
- lines = append(lines, string([]rune(filenameOnly)[i:endPos]))
- }
- for j, line := range lines {
- pt := freetype.Pt(100, (j+1)*60+int(ctx.PointToFixed(fontSize)>>6))
- _, err = ctx.DrawString(line, pt)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- return
- }
- }
- fontSize = 36
- ctx.SetFontSize(fontSize)
- pt := freetype.Pt(100, (len(lines)+1)*60+int(ctx.PointToFixed(fontSize)>>6))
- _, err = ctx.DrawString(shareMeta, pt)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- } else {
- //One liner
- pt := freetype.Pt(100, 60+int(ctx.PointToFixed(fontSize)>>6))
- _, err = ctx.DrawString(filenameOnly, pt)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- fontSize = 36
- ctx.SetFontSize(fontSize)
- pt = freetype.Pt(100, 120+int(ctx.PointToFixed(fontSize)>>6))
- _, err = ctx.DrawString(shareMeta, pt)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- }
- //Get thumbnail
- ownerinfo, err := s.options.UserHandler.GetUserInfoFromUsername(shareEntry.Owner)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- fsh, err := ownerinfo.GetFileSystemHandlerFromVirtualPath(shareEntry.FileVirtualPath)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- rpath, _ := fsh.FileSystemAbstraction.VirtualPathToRealPath(shareEntry.FileVirtualPath, shareEntry.Owner)
- cacheFileImagePath, err := metadata.GetCacheFilePath(fsh, rpath)
- if err == nil {
- //We got a thumbnail for this file. Render it as well
- thumbnailFile, err := os.Open(cacheFileImagePath)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- thumb, _, err := image.Decode(thumbnailFile)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- resizedThumb := resize.Resize(250, 0, thumb, resize.Lanczos3)
- draw.Draw(resultopg, resultopg.Bounds(), resizedThumb, image.Point{-(resultopg.Bounds().Dx() - resizedThumb.Bounds().Dx() - 90), -60}, draw.Over)
- } else if isDir(shareEntry.FileRealPath) {
- //Is directory but no thumbnail. Use default foldr share thumbnail
- thumbnailFile, err := os.Open("./system/share/folder.png")
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- thumb, _, err := image.Decode(thumbnailFile)
- if err != nil {
- fmt.Println("[share/opg] " + err.Error())
- http.NotFound(w, r)
- return
- }
- resizedThumb := resize.Resize(250, 0, thumb, resize.Lanczos3)
- draw.Draw(resultopg, resultopg.Bounds(), resizedThumb, image.Point{-(resultopg.Bounds().Dx() - resizedThumb.Bounds().Dx() - 90), -60}, draw.Over)
- }
- w.Header().Set("Content-Type", "image/jpeg")
- jpeg.Encode(w, resultopg, nil)
- }
- //Main function for handle share. Must be called with http.HandleFunc (No auth)
- func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
- //New download method variables
- subpathElements := []string{}
- directDownload := false
- directServe := false
- relpath := ""
- id, err := mv(r, "id", false)
- if err != nil {
- //ID is not defined in the URL paramter. New ID defination is based on the subpath content
- requestURI := filepath.ToSlash(filepath.Clean(r.URL.Path))
- subpathElements = strings.Split(requestURI[1:], "/")
- if len(subpathElements) == 2 {
- //E.g. /share/{id} => Show the download page
- id = subpathElements[1]
- //Check if there is missing / at the end. Redirect if true
- if r.URL.Path[len(r.URL.Path)-1:] != "/" {
- http.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
- return
- }
- } else if len(subpathElements) >= 3 {
- //E.g. /share/download/{uuid} or /share/preview/{uuid}
- id = subpathElements[2]
- if subpathElements[1] == "download" {
- directDownload = true
- //Check if this contain a subpath
- if len(subpathElements) > 3 {
- relpath = strings.Join(subpathElements[3:], "/")
- }
- } else if subpathElements[1] == "preview" {
- directServe = true
- } else if len(subpathElements) == 3 {
- //Check if the last element is the filename
- if strings.Contains(subpathElements[2], ".") {
- //Share link contain filename. Redirect to share interface
- http.Redirect(w, r, "./", http.StatusTemporaryRedirect)
- return
- } else {
- //Incorrect operation type
- w.WriteHeader(http.StatusBadRequest)
- w.Header().Set("Content-Type", "text/plain") // this
- w.Write([]byte("400 - Operation type not supported: " + subpathElements[1]))
- return
- }
- } else if len(subpathElements) >= 4 {
- if subpathElements[1] == "opg" {
- //Handle serving opg preview image, usually with
- // /share/opg/{req.timestamp}/{uuid}
- s.HandleOPGServing(w, r, subpathElements[3])
- return
- }
- //Invalid operation type
- w.WriteHeader(http.StatusBadRequest)
- w.Header().Set("Content-Type", "text/plain") // this
- w.Write([]byte("400 - Operation type not supported: " + subpathElements[1]))
- return
- }
- } else if len(subpathElements) == 1 {
- //ID is missing. Serve the id input page
- content, err := ioutil.ReadFile("system/share/index.html")
- if err != nil {
- //Handling index not found. Is server updated correctly?
- w.WriteHeader(http.StatusInternalServerError)
- w.Write([]byte("500 - Internal Server Error"))
- return
- }
- t := fasttemplate.New(string(content), "{{", "}}")
- s := t.ExecuteString(map[string]interface{}{
- "hostname": s.options.HostName,
- })
- w.Write([]byte(s))
- return
- } else {
- http.NotFound(w, r)
- return
- }
- } else {
- //Parse and redirect to new share path
- download, _ := mv(r, "download", false)
- if download == "true" {
- directDownload = true
- }
- serve, _ := mv(r, "serve", false)
- if serve == "true" {
- directServe = true
- }
- relpath, _ = mv(r, "rel", false)
- redirectURL := "./" + id + "/"
- if directDownload == true {
- redirectURL = "./download/" + id + "/"
- }
- http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
- return
- }
- //Check if id exists
- val, ok := s.options.ShareEntryTable.UrlToFileMap.Load(id)
- if ok {
- //Parse the option structure
- shareOption := val.(*shareEntry.ShareOption)
- //Check for permission
- if shareOption.Permission == "anyone" {
- //OK to proceed
- } else if shareOption.Permission == "signedin" {
- if !s.options.AuthAgent.CheckAuth(r) {
- //Redirect to login page
- if directDownload || directServe {
- w.WriteHeader(http.StatusUnauthorized)
- w.Write([]byte("401 - Unauthorized"))
- } else {
- http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/preview/?id="+id, 307)
- }
- return
- } else {
- //Ok to proccedd
- }
- } else if shareOption.Permission == "samegroup" {
- thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
- if err != nil {
- if directDownload || directServe {
- w.WriteHeader(http.StatusUnauthorized)
- w.Write([]byte("401 - Unauthorized"))
- } else {
- http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/preview/?id="+id, 307)
- }
- return
- }
- //Check if all the user groups are inside the share owner groups
- valid := true
- thisUsersGroupByName := []string{}
- for _, pg := range thisuserinfo.PermissionGroup {
- thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
- }
- for _, allowedpg := range shareOption.Accessibles {
- if inArray(thisUsersGroupByName, allowedpg) {
- //This required group is inside this user's group. OK
- } else {
- //This required group is not inside user's group. Reject
- valid = false
- }
- }
- if !valid {
- //Serve permission denied page
- if directDownload || directServe {
- w.WriteHeader(http.StatusForbidden)
- w.Write([]byte("401 - Forbidden"))
- } else {
- ServePermissionDeniedPage(w)
- }
- return
- }
- } else if shareOption.Permission == "users" {
- thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
- if err != nil {
- //User not logged in. Redirect to login page
- if directDownload || directServe {
- w.WriteHeader(http.StatusUnauthorized)
- w.Write([]byte("401 - Unauthorized"))
- } else {
- http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
- }
- return
- }
- //Check if username in the allowed user list
- if !inArray(shareOption.Accessibles, thisuserinfo.Username) && shareOption.Owner != thisuserinfo.Username {
- //Serve permission denied page
- if directDownload || directServe {
- w.WriteHeader(http.StatusForbidden)
- w.Write([]byte("401 - Forbidden"))
- } else {
- ServePermissionDeniedPage(w)
- }
- return
- }
- } else if shareOption.Permission == "groups" {
- thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
- if err != nil {
- //User not logged in. Redirect to login page
- if directDownload || directServe {
- w.WriteHeader(http.StatusUnauthorized)
- w.Write([]byte("401 - Unauthorized"))
- } else {
- http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
- }
- return
- }
- allowAccess := false
- thisUsersGroupByName := []string{}
- for _, pg := range thisuserinfo.PermissionGroup {
- thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
- }
- for _, thisUserPg := range thisUsersGroupByName {
- if inArray(shareOption.Accessibles, thisUserPg) {
- allowAccess = true
- }
- }
- if !allowAccess {
- //Serve permission denied page
- if directDownload || directServe {
- w.WriteHeader(http.StatusForbidden)
- w.Write([]byte("401 - Forbidden"))
- } else {
- ServePermissionDeniedPage(w)
- }
- return
- }
- } else {
- //Unsupported mode. Show notfound
- http.NotFound(w, r)
- return
- }
- //Resolve the fsh from the entry
- owner, err := s.options.UserHandler.GetUserInfoFromUsername(shareOption.Owner)
- if err != nil {
- w.WriteHeader(http.StatusForbidden)
- w.Write([]byte("401 - Share account not exists"))
- return
- }
- targetFsh, err := owner.GetFileSystemHandlerFromVirtualPath(shareOption.FileVirtualPath)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- w.Write([]byte("500 - Unable to load Shared File"))
- return
- }
- targetFshAbs := targetFsh.FileSystemAbstraction
- fileRuntimeAbsPath, _ := targetFshAbs.VirtualPathToRealPath(shareOption.FileVirtualPath, owner.Username)
- if !targetFshAbs.FileExists(fileRuntimeAbsPath) {
- http.NotFound(w, r)
- return
- }
- //Serve the download page
- if targetFshAbs.IsDir(fileRuntimeAbsPath) {
- //This share is a folder
- type File struct {
- Filename string
- RelPath string
- Filesize string
- IsDir bool
- }
- if directDownload {
- if relpath != "" {
- //User specified a specific file within the directory. Escape the relpath
- targetFilepath := filepath.Join(fileRuntimeAbsPath, relpath)
- //Check if file exists
- if !targetFshAbs.FileExists(targetFilepath) {
- http.NotFound(w, r)
- return
- }
- //Validate the absolute path to prevent path escape
- reqPath := filepath.ToSlash(filepath.Clean(targetFilepath))
- rootPath, _ := targetFshAbs.VirtualPathToRealPath(shareOption.FileVirtualPath, shareOption.Owner)
- if !strings.HasPrefix(reqPath, rootPath) {
- //Directory escape detected
- w.WriteHeader(http.StatusBadRequest)
- w.Write([]byte("400 - Bad Request: Invalid relative path"))
- return
- }
- //Serve the target file
- w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(targetFilepath)), "+", "%20"))
- w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
- //http.ServeFile(w, r, targetFilepath)
- f, _ := targetFshAbs.ReadStream(targetFilepath)
- io.Copy(w, f)
- f.Close()
- } else {
- //Download this folder as zip
- //Create a zip using ArOZ Zipper, tmp zip files are located under tmp/share-cache/*.zip
- tmpFolder := s.options.TmpFolder
- tmpFolder = filepath.Join(tmpFolder, "share-cache")
- os.MkdirAll(tmpFolder, 0755)
- targetZipFilename := filepath.Join(tmpFolder, filepath.Base(fileRuntimeAbsPath)) + ".zip"
- //Check if the target fs require buffer
- zippingSource := shareOption.FileRealPath
- localBuff := ""
- if targetFsh.RequireBuffer {
- //Buffer all the required files for zipping
- localBuff = filepath.Join(tmpFolder, uuid.NewV4().String(), filepath.Base(fileRuntimeAbsPath))
- os.MkdirAll(localBuff, 0755)
- //Buffer all files into tmp folder
- targetFshAbs.Walk(fileRuntimeAbsPath, func(path string, info fs.FileInfo, err error) error {
- relPath := strings.TrimPrefix(filepath.ToSlash(path), filepath.ToSlash(fileRuntimeAbsPath))
- localPath := filepath.Join(localBuff, relPath)
- if info.IsDir() {
- os.MkdirAll(localPath, 0755)
- } else {
- f, err := targetFshAbs.ReadStream(path)
- if err != nil {
- log.Println("[Share] Buffer and zip download operation failed: ", err)
- }
- dest, err := os.OpenFile(localPath, os.O_CREATE|os.O_WRONLY, 0775)
- if err != nil {
- log.Println("[Share] Buffer and zip download operation failed: ", err)
- }
- _, err = io.Copy(dest, f)
- if err != nil {
- log.Println("[Share] Buffer and zip download operation failed: ", err)
- }
- f.Close()
- }
- return nil
- })
- zippingSource = localBuff
- }
- //Build a filelist
- err := filesystem.ArozZipFile([]string{zippingSource}, targetZipFilename, false)
- if err != nil {
- //Failed to create zip file
- w.WriteHeader(http.StatusInternalServerError)
- w.Write([]byte("500 - Internal Server Error: Zip file creation failed"))
- log.Println("Failed to create zip file for share download: " + err.Error())
- return
- }
- //Serve thje zip file
- w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20")+".zip")
- w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
- http.ServeFile(w, r, targetZipFilename)
- //Remove the buffer file if exists
- if targetFsh.RequireBuffer {
- os.RemoveAll(filepath.Dir(localBuff))
- }
- }
- } else if directServe {
- //Folder provide no direct serve method.
- w.WriteHeader(http.StatusBadRequest)
- w.Write([]byte("400 - Cannot preview folder type shares"))
- return
- } else {
- //Show download page. Do not allow serving
- content, err := ioutil.ReadFile("./system/share/downloadPageFolder.html")
- if err != nil {
- http.NotFound(w, r)
- return
- }
- //Get file size
- fsize, fcount := targetFsh.GetDirctorySizeFromRealPath(fileRuntimeAbsPath, false)
- //Build the tree list of the folder
- treeList := map[string][]File{}
- err = targetFshAbs.Walk(filepath.Clean(fileRuntimeAbsPath), func(file string, info os.FileInfo, err error) error {
- if err != nil {
- //If error skip this
- return nil
- }
- if filepath.Base(file)[:1] != "." {
- fileSize := targetFshAbs.GetFileSize(file)
- if targetFshAbs.IsDir(file) {
- fileSize, _ = targetFsh.GetDirctorySizeFromRealPath(file, false)
- }
- relPath, err := filepath.Rel(fileRuntimeAbsPath, file)
- if err != nil {
- relPath = ""
- }
- relPath = filepath.ToSlash(filepath.Clean(relPath))
- relDir := filepath.ToSlash(filepath.Dir(relPath))
- if relPath == "." {
- //The root file object. Skip this
- return nil
- }
- treeList[relDir] = append(treeList[relDir], File{
- Filename: filepath.Base(file),
- RelPath: filepath.ToSlash(relPath),
- Filesize: filesystem.GetFileDisplaySize(fileSize, 2),
- IsDir: targetFshAbs.IsDir(file),
- })
- }
- return nil
- })
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- w.Write([]byte("500 - Internal Server Error"))
- return
- }
- tl, _ := json.Marshal(treeList)
- //Get modification time
- fmodtime, _ := targetFshAbs.GetModTime(fileRuntimeAbsPath)
- timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
- t := fasttemplate.New(string(content), "{{", "}}")
- s := t.ExecuteString(map[string]interface{}{
- "hostname": s.options.HostName,
- "host": r.Host,
- "reqid": id,
- "mime": "application/x-directory",
- "size": filesystem.GetFileDisplaySize(fsize, 2),
- "filecount": strconv.Itoa(fcount),
- "modtime": timeString,
- "downloadurl": "../../share/download/" + id,
- "filename": filepath.Base(fileRuntimeAbsPath),
- "reqtime": strconv.Itoa(int(time.Now().Unix())),
- "requri": "//" + r.Host + r.URL.Path,
- "opg_image": "/share/opg/" + strconv.Itoa(int(time.Now().Unix())) + "/" + id,
- "treelist": tl,
- "downloaduuid": id,
- })
- w.Write([]byte(s))
- return
- }
- } else {
- //This share is a file
- if directDownload {
- //Serve the file directly
- w.Header().Set("Content-Disposition", "attachment; filename=\""+filepath.Base(shareOption.FileVirtualPath)+"\"")
- w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
- f, _ := targetFshAbs.ReadStream(fileRuntimeAbsPath)
- io.Copy(w, f)
- f.Close()
- } else if directServe {
- w.Header().Set("Access-Control-Allow-Origin", "*")
- w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
- w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
- f, _ := targetFshAbs.ReadStream(fileRuntimeAbsPath)
- io.Copy(w, f)
- f.Close()
- } else {
- //Serve the download page
- content, err := ioutil.ReadFile("./system/share/downloadPage.html")
- if err != nil {
- http.NotFound(w, r)
- return
- }
- //Get file mime type
- mime, ext, err := filesystem.GetMime(fileRuntimeAbsPath)
- if err != nil {
- mime = "Unknown"
- }
- //Load the preview template
- templateRoot := "./system/share/"
- previewTemplate := ""
- if ext == ".mp4" || ext == ".webm" {
- previewTemplate = filepath.Join(templateRoot, "video.html")
- } else if ext == ".mp3" || ext == ".wav" || ext == ".flac" || ext == ".ogg" {
- previewTemplate = filepath.Join(templateRoot, "audio.html")
- } else if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".webp" {
- previewTemplate = filepath.Join(templateRoot, "image.html")
- } else if ext == ".pdf" {
- previewTemplate = filepath.Join(templateRoot, "iframe.html")
- } else {
- //Format do not support preview. Use the default.html
- previewTemplate = filepath.Join(templateRoot, "default.html")
- }
- tp, err := ioutil.ReadFile(previewTemplate)
- if err != nil {
- tp = []byte("")
- }
- //Merge two templates
- content = []byte(strings.ReplaceAll(string(content), "{{previewer}}", string(tp)))
- //Get file size
- fsize := targetFshAbs.GetFileSize(fileRuntimeAbsPath)
- //Get modification time
- fmodtime, _ := targetFshAbs.GetModTime(fileRuntimeAbsPath)
- timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
- //Check if ext match with filepath ext
- displayExt := ext
- if ext != filepath.Ext(fileRuntimeAbsPath) {
- displayExt = filepath.Ext(fileRuntimeAbsPath) + " (" + ext + ")"
- }
- t := fasttemplate.New(string(content), "{{", "}}")
- s := t.ExecuteString(map[string]interface{}{
- "hostname": s.options.HostName,
- "host": r.Host,
- "reqid": id,
- "requri": "//" + r.Host + r.URL.Path,
- "mime": mime,
- "ext": displayExt,
- "size": filesystem.GetFileDisplaySize(fsize, 2),
- "modtime": timeString,
- "downloadurl": "../../share/download/" + id + "/" + filepath.Base(fileRuntimeAbsPath),
- "preview_url": "/share/preview/" + id + "/",
- "filename": filepath.Base(fileRuntimeAbsPath),
- "opg_image": "/share/opg/" + strconv.Itoa(int(time.Now().Unix())) + "/" + id,
- "reqtime": strconv.Itoa(int(time.Now().Unix())),
- })
- w.Write([]byte(s))
- return
- }
- }
- } else {
- //This share not exists
- if directDownload {
- //Send 404 header
- http.NotFound(w, r)
- return
- } else {
- //Send not found page
- content, err := ioutil.ReadFile("./system/share/notfound.html")
- if err != nil {
- http.NotFound(w, r)
- return
- }
- t := fasttemplate.New(string(content), "{{", "}}")
- s := t.ExecuteString(map[string]interface{}{
- "hostname": s.options.HostName,
- "reqid": id,
- "reqtime": strconv.Itoa(int(time.Now().Unix())),
- })
- w.Write([]byte(s))
- return
- }
- }
- }
- //Check if a file is shared
- func (s *Manager) HandleShareCheck(w http.ResponseWriter, r *http.Request) {
- //Get the vpath from paramters
- vpath, err := mv(r, "path", true)
- if err != nil {
- sendErrorResponse(w, "Invalid path given")
- return
- }
- //Get userinfo
- userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
- if err != nil {
- sendErrorResponse(w, "User not logged in")
- return
- }
- fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
- pathHash := shareEntry.GetPathHash(fsh, vpath, userinfo.Username)
- type Result struct {
- IsShared bool
- ShareUUID *shareEntry.ShareOption
- }
- //Check if share exists
- shareExists := s.options.ShareEntryTable.FileIsShared(pathHash)
- if !shareExists {
- //Share not exists
- js, _ := json.Marshal(Result{
- IsShared: false,
- ShareUUID: &shareEntry.ShareOption{},
- })
- sendJSONResponse(w, string(js))
- } else {
- //Share exists
- thisSharedInfo := s.options.ShareEntryTable.GetShareObjectFromPathHash(pathHash)
- js, _ := json.Marshal(Result{
- IsShared: true,
- ShareUUID: thisSharedInfo,
- })
- sendJSONResponse(w, string(js))
- }
- }
- //Create new share from the given path
- func (s *Manager) HandleCreateNewShare(w http.ResponseWriter, r *http.Request) {
- //Get the vpath from paramters
- vpath, err := mv(r, "path", true)
- if err != nil {
- sendErrorResponse(w, "Invalid path given")
- return
- }
- //Get userinfo
- userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
- if err != nil {
- sendErrorResponse(w, "User not logged in")
- return
- }
- //Check if this is in the share folder
- vrootID, subpath, err := filesystem.GetIDFromVirtualPath(vpath)
- if err != nil {
- sendErrorResponse(w, "Unable to resolve virtual path")
- return
- }
- if vrootID == "share" {
- shareObject, err := s.options.ShareEntryTable.ResolveShareOptionFromShareSubpath(subpath)
- if err != nil {
- sendErrorResponse(w, err.Error())
- return
- }
- //Check if this share is own by or accessible by the current user. Reject share modification if not
- if !shareObject.IsOwnedBy(userinfo.Username) && !userinfo.CanWrite(vpath) {
- sendErrorResponse(w, "Permission Denied: You are not the file owner nor can write to this file")
- return
- }
- }
- //Get the target fsh that this vpath come from
- vpathSourceFsh := userinfo.GetRootFSHFromVpathInUserScope(vpath)
- if vpathSourceFsh == nil {
- sendErrorResponse(w, "Invalid vpath given")
- return
- }
- share, err := s.CreateNewShare(userinfo, vpathSourceFsh, vpath)
- if err != nil {
- sendErrorResponse(w, err.Error())
- return
- }
- js, _ := json.Marshal(share)
- sendJSONResponse(w, string(js))
- }
- // Handle Share Edit.
- // For allowing groups / users, use the following syntax
- // groups:group1,group2,group3
- // users:user1,user2,user3
- // For basic modes, use the following keywords
- // anyone / signedin / samegroup
- // anyone: Anyone who has the link
- // signedin: Anyone logged in to this system
- // samegroup: The requesting user has the same (or more) user group as the share owner
- func (s *Manager) HandleEditShare(w http.ResponseWriter, r *http.Request) {
- userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
- if err != nil {
- sendErrorResponse(w, "User not logged in")
- return
- }
- uuid, err := mv(r, "uuid", true)
- if err != nil {
- sendErrorResponse(w, "Invalid path given")
- return
- }
- shareMode, _ := mv(r, "mode", true)
- if shareMode == "" {
- shareMode = "signedin"
- }
- //Check if share exists
- so := s.options.ShareEntryTable.GetShareObjectFromUUID(uuid)
- if so == nil {
- //This share url not exists
- sendErrorResponse(w, "Share UUID not exists")
- return
- }
- //Check if the user has permission to edit this share
- if so.Owner != userinfo.Username && !userinfo.IsAdmin() {
- //This file is not shared by this user and this user is not admin. Block this request
- sendErrorResponse(w, "Permission denied")
- return
- }
- //Validate and extract the storage mode
- ok, sharetype, settings := validateShareModes(shareMode)
- if !ok {
- sendErrorResponse(w, "Invalid share setting")
- return
- }
- //Analysis the sharetype
- if sharetype == "anyone" || sharetype == "signedin" || sharetype == "samegroup" {
- //Basic types.
- so.Permission = sharetype
- if sharetype == "samegroup" {
- //Write user groups into accessible (Must be all match inorder to allow access)
- userpg := []string{}
- for _, pg := range userinfo.PermissionGroup {
- userpg = append(userpg, pg.Name)
- }
- so.Accessibles = userpg
- }
- //Write changes to database
- s.options.ShareEntryTable.Database.Write("share", uuid, so)
- } else if sharetype == "groups" || sharetype == "users" {
- //Username or group is listed = ok
- so.Permission = sharetype
- so.Accessibles = settings
- //Write changes to database
- s.options.ShareEntryTable.Database.Write("share", uuid, so)
- }
- sendOK(w)
- }
- func (s *Manager) HandleDeleteShare(w http.ResponseWriter, r *http.Request) {
- //Get the vpath from paramters
- vpath, err := mv(r, "path", true)
- if err != nil {
- sendErrorResponse(w, "Invalid path given")
- return
- }
- //Get userinfo
- userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
- if err != nil {
- sendErrorResponse(w, "User not logged in")
- return
- }
- //Delete the share setting
- err = s.DeleteShare(userinfo, vpath)
- if err != nil {
- sendErrorResponse(w, err.Error())
- } else {
- sendOK(w)
- }
- }
- //Craete a new file or folder share
- func (s *Manager) CreateNewShare(userinfo *user.User, srcFsh *filesystem.FileSystemHandler, vpath string) (*shareEntry.ShareOption, error) {
- //Translate the vpath to realpath
- return s.options.ShareEntryTable.CreateNewShare(srcFsh, vpath, userinfo.Username, userinfo.GetUserPermissionGroupNames())
- }
- func ServePermissionDeniedPage(w http.ResponseWriter) {
- w.WriteHeader(http.StatusForbidden)
- pageContent := []byte("Permissioned Denied")
- if fileExists("system/share/permissionDenied.html") {
- content, err := ioutil.ReadFile("system/share/permissionDenied.html")
- if err == nil {
- pageContent = content
- }
- }
- w.Write([]byte(pageContent))
- }
- /*
- Validate Share Mode string
- will return
- 1. bool => Is valid
- 2. permission type: {basic / groups / users}
- 3. mode string
- */
- func validateShareModes(mode string) (bool, string, []string) {
- // user:a,b,c,d
- validModes := []string{"anyone", "signedin", "samegroup"}
- if inArray(validModes, mode) {
- //Standard modes
- return true, mode, []string{}
- } else if len(mode) > 7 && mode[:7] == "groups:" {
- //Handle custom group case like groups:a,b,c,d
- groupList := mode[7:]
- if len(groupList) > 0 {
- groups := strings.Split(groupList, ",")
- return true, "groups", groups
- } else {
- //Invalid configuration
- return false, "groups", []string{}
- }
- } else if len(mode) > 6 && mode[:6] == "users:" {
- //Handle custom usersname like users:a,b,c,d
- userList := mode[6:]
- if len(userList) > 0 {
- users := strings.Split(userList, ",")
- return true, "users", users
- } else {
- //Invalid configuration
- return false, "users", []string{}
- }
- }
- return false, "", []string{}
- }
- //Check and clear shares that its pointinf files no longe exists
- func (s *Manager) ValidateAndClearShares() {
- //Iterate through all shares within the system
- s.options.ShareEntryTable.FileToUrlMap.Range(func(k, v interface{}) bool {
- thisShareOption := v.(*shareEntry.ShareOption)
- vpath := thisShareOption.FileVirtualPath
- userinfo, _ := s.options.UserHandler.GetUserInfoFromUsername(thisShareOption.Owner)
- fsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
- if err != nil {
- //The file system handler that provide this share file is gone. Skip this
- return true
- }
- fshAbs := fsh.FileSystemAbstraction
- thisVpath, _ := fshAbs.VirtualPathToRealPath(vpath, userinfo.Username)
- pathHash := shareEntry.GetPathHash(fsh, vpath, userinfo.Username)
- if !fshAbs.FileExists(thisVpath) {
- //This share source file don't exists anymore. Remove it
- s.options.ShareEntryTable.RemoveShareByPathHash(pathHash)
- log.Println("*Share* Removing share to file: " + vpath + " as it no longer exists")
- }
- return true
- })
- }
- func (s *Manager) DeleteShare(userinfo *user.User, vpath string) error {
- ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
- return s.options.ShareEntryTable.DeleteShareByPathHash(ps)
- }
- func (s *Manager) GetShareUUIDFromUserAndVpath(userinfo *user.User, vpath string) string {
- ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
- return s.options.ShareEntryTable.GetShareUUIDFromPathHash(ps)
- }
- func (s *Manager) GetShareObjectFromUserAndVpath(userinfo *user.User, vpath string) *shareEntry.ShareOption {
- ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
- return s.options.ShareEntryTable.GetShareObjectFromPathHash(ps)
- }
- func (s *Manager) GetShareObjectFromUUID(uuid string) *shareEntry.ShareOption {
- return s.options.ShareEntryTable.GetShareObjectFromUUID(uuid)
- }
- func (s *Manager) FileIsShared(userinfo *user.User, vpath string) bool {
- ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
- return s.options.ShareEntryTable.FileIsShared(ps)
- }
- func (s *Manager) RemoveShareByUUID(uuid string) error {
- return s.options.ShareEntryTable.RemoveShareByUUID(uuid)
- }
- func getPathHashFromUsernameAndVpath(userinfo *user.User, vpath string) string {
- fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
- return shareEntry.GetPathHash(fsh, vpath, userinfo.Username)
- }
|