share.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. package share
  2. /*
  3. Arozos File Share Manager
  4. author: tobychui
  5. This module handle file share request and other stuffs
  6. */
  7. import (
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "image"
  12. "image/color"
  13. "image/draw"
  14. "image/jpeg"
  15. "io/ioutil"
  16. "log"
  17. "math"
  18. "net/http"
  19. "net/url"
  20. "os"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "github.com/golang/freetype"
  26. "github.com/nfnt/resize"
  27. "github.com/valyala/fasttemplate"
  28. "imuslab.com/arozos/mod/auth"
  29. "imuslab.com/arozos/mod/common"
  30. filesystem "imuslab.com/arozos/mod/filesystem"
  31. "imuslab.com/arozos/mod/filesystem/metadata"
  32. "imuslab.com/arozos/mod/share/shareEntry"
  33. "imuslab.com/arozos/mod/user"
  34. )
  35. type Options struct {
  36. AuthAgent *auth.AuthAgent
  37. UserHandler *user.UserHandler
  38. ShareEntryTable *shareEntry.ShareEntryTable
  39. HostName string
  40. TmpFolder string
  41. }
  42. type Manager struct {
  43. options Options
  44. }
  45. //Create a new Share Manager
  46. func NewShareManager(options Options) *Manager {
  47. //Return a new manager object
  48. return &Manager{
  49. options: options,
  50. }
  51. }
  52. func (s *Manager) HandleOPGServing(w http.ResponseWriter, r *http.Request, shareID string) {
  53. shareEntry := s.GetShareObjectFromUUID(shareID)
  54. if shareEntry == nil {
  55. //This share is not valid
  56. http.NotFound(w, r)
  57. return
  58. }
  59. //Overlap and generate opg
  60. //Load in base template
  61. baseTemplate, err := os.Open("./system/share/default_opg.png")
  62. if err != nil {
  63. fmt.Println(err)
  64. return
  65. }
  66. base, _, err := image.Decode(baseTemplate)
  67. if err != nil {
  68. fmt.Println(err)
  69. return
  70. }
  71. //Create base canvas
  72. rx := image.Rectangle{image.Point{0, 0}, base.Bounds().Size()}
  73. resultopg := image.NewRGBA(rx)
  74. draw.Draw(resultopg, base.Bounds(), base, image.Point{0, 0}, draw.Src)
  75. //Append filename to the image
  76. fontBytes, err := ioutil.ReadFile("./system/share/fonts/TaipeiSansTCBeta-Light.ttf")
  77. if err != nil {
  78. fmt.Println(err)
  79. return
  80. }
  81. utf8Font, err := freetype.ParseFont(fontBytes)
  82. if err != nil {
  83. fmt.Println(err)
  84. return
  85. }
  86. fontSize := float64(42)
  87. ctx := freetype.NewContext()
  88. ctx.SetDPI(72)
  89. ctx.SetFont(utf8Font)
  90. ctx.SetFontSize(fontSize)
  91. ctx.SetClip(resultopg.Bounds())
  92. ctx.SetDst(resultopg)
  93. ctx.SetSrc(image.NewUniform(color.RGBA{255, 255, 255, 255}))
  94. //Check if we need to split the filename into two lines
  95. filename := filepath.Base(shareEntry.FileRealPath)
  96. filenameOnly := strings.TrimSuffix(filename, filepath.Ext(filename))
  97. fs := filesystem.GetFileSize(shareEntry.FileRealPath)
  98. shareMeta := filepath.Ext(shareEntry.FileRealPath) + " / " + filesystem.GetFileDisplaySize(fs, 2)
  99. if isDir(shareEntry.FileRealPath) {
  100. fs, fc := filesystem.GetDirctorySize(shareEntry.FileRealPath, false)
  101. shareMeta = strconv.Itoa(fc) + " items / " + filesystem.GetFileDisplaySize(fs, 2)
  102. }
  103. if len([]rune(filename)) > 20 {
  104. //Split into lines
  105. lines := []string{}
  106. for i := 0; i < len([]rune(filenameOnly)); i += 20 {
  107. endPos := int(math.Min(float64(len([]rune(filenameOnly))), float64(i+20)))
  108. lines = append(lines, string([]rune(filenameOnly)[i:endPos]))
  109. }
  110. for j, line := range lines {
  111. pt := freetype.Pt(100, (j+1)*60+int(ctx.PointToFixed(fontSize)>>6))
  112. _, err = ctx.DrawString(line, pt)
  113. if err != nil {
  114. fmt.Println(err)
  115. return
  116. }
  117. }
  118. fontSize = 36
  119. ctx.SetFontSize(fontSize)
  120. pt := freetype.Pt(100, (len(lines)+1)*60+int(ctx.PointToFixed(fontSize)>>6))
  121. _, err = ctx.DrawString(shareMeta, pt)
  122. if err != nil {
  123. fmt.Println(err)
  124. return
  125. }
  126. } else {
  127. //One liner
  128. pt := freetype.Pt(100, 60+int(ctx.PointToFixed(fontSize)>>6))
  129. _, err = ctx.DrawString(filenameOnly, pt)
  130. if err != nil {
  131. fmt.Println(err)
  132. return
  133. }
  134. fontSize = 36
  135. ctx.SetFontSize(fontSize)
  136. pt = freetype.Pt(100, 120+int(ctx.PointToFixed(fontSize)>>6))
  137. _, err = ctx.DrawString(shareMeta, pt)
  138. if err != nil {
  139. fmt.Println(err)
  140. return
  141. }
  142. }
  143. //Get thumbnail
  144. cacheFileImagePath, err := metadata.GetCacheFilePath(shareEntry.FileRealPath)
  145. if err == nil {
  146. //We got a thumbnail for this file. Render it as well
  147. thumbnailFile, err := os.Open(cacheFileImagePath)
  148. if err != nil {
  149. fmt.Println(err)
  150. return
  151. }
  152. thumb, _, err := image.Decode(thumbnailFile)
  153. if err != nil {
  154. fmt.Println(err)
  155. return
  156. }
  157. resizedThumb := resize.Resize(250, 0, thumb, resize.Lanczos3)
  158. draw.Draw(resultopg, resultopg.Bounds(), resizedThumb, image.Point{-(resultopg.Bounds().Dx() - resizedThumb.Bounds().Dx() - 90), -60}, draw.Over)
  159. }
  160. w.Header().Set("Content-Type", "image/jpeg") // <-- set the content-type header
  161. jpeg.Encode(w, resultopg, nil)
  162. }
  163. //Main function for handle share. Must be called with http.HandleFunc (No auth)
  164. func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
  165. //New download method variables
  166. subpathElements := []string{}
  167. directDownload := false
  168. directServe := false
  169. relpath := ""
  170. id, err := mv(r, "id", false)
  171. if err != nil {
  172. //ID is not defined in the URL paramter. New ID defination is based on the subpath content
  173. requestURI := filepath.ToSlash(filepath.Clean(r.URL.Path))
  174. subpathElements = strings.Split(requestURI[1:], "/")
  175. if len(subpathElements) == 2 {
  176. //E.g. /share/{id} => Show the download page
  177. id = subpathElements[1]
  178. //Check if there is missing / at the end. Redirect if true
  179. if r.URL.Path[len(r.URL.Path)-1:] != "/" {
  180. http.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
  181. return
  182. }
  183. } else if len(subpathElements) >= 3 {
  184. //E.g. /share/download/{uuid} or /share/preview/{uuid}
  185. id = subpathElements[2]
  186. if subpathElements[1] == "download" {
  187. directDownload = true
  188. //Check if this contain a subpath
  189. if len(subpathElements) > 3 {
  190. relpath = strings.Join(subpathElements[3:], "/")
  191. }
  192. } else if subpathElements[1] == "preview" {
  193. directServe = true
  194. } else if len(subpathElements) == 3 {
  195. //Check if the last element is the filename
  196. if strings.Contains(subpathElements[2], ".") {
  197. //Share link contain filename. Redirect to share interface
  198. http.Redirect(w, r, "./", http.StatusTemporaryRedirect)
  199. return
  200. } else {
  201. //Incorrect operation type
  202. w.WriteHeader(http.StatusBadRequest)
  203. w.Header().Set("Content-Type", "text/plain") // this
  204. w.Write([]byte("400 - Operation type not supported: " + subpathElements[1]))
  205. return
  206. }
  207. } else if len(subpathElements) >= 4 {
  208. if subpathElements[1] == "opg" {
  209. //Handle serving opg preview image, usually with
  210. // /share/opg/{req.timestamp}/{uuid}
  211. s.HandleOPGServing(w, r, subpathElements[3])
  212. return
  213. }
  214. //Invalid operation type
  215. w.WriteHeader(http.StatusBadRequest)
  216. w.Header().Set("Content-Type", "text/plain") // this
  217. w.Write([]byte("400 - Operation type not supported: " + subpathElements[1]))
  218. return
  219. }
  220. } else if len(subpathElements) == 1 {
  221. //ID is missing. Serve the id input page
  222. content, err := ioutil.ReadFile("system/share/index.html")
  223. if err != nil {
  224. //Handling index not found. Is server updated correctly?
  225. w.WriteHeader(http.StatusInternalServerError)
  226. w.Write([]byte("500 - Internal Server Error"))
  227. return
  228. }
  229. t := fasttemplate.New(string(content), "{{", "}}")
  230. s := t.ExecuteString(map[string]interface{}{
  231. "hostname": s.options.HostName,
  232. })
  233. w.Write([]byte(s))
  234. return
  235. } else {
  236. http.NotFound(w, r)
  237. return
  238. }
  239. } else {
  240. //Parse and redirect to new share path
  241. download, _ := mv(r, "download", false)
  242. if download == "true" {
  243. directDownload = true
  244. }
  245. serve, _ := mv(r, "serve", false)
  246. if serve == "true" {
  247. directServe = true
  248. }
  249. relpath, _ = mv(r, "rel", false)
  250. redirectURL := "./" + id + "/"
  251. if directDownload == true {
  252. redirectURL = "./download/" + id + "/"
  253. }
  254. http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
  255. return
  256. }
  257. //Check if id exists
  258. val, ok := s.options.ShareEntryTable.UrlToFileMap.Load(id)
  259. if ok {
  260. //Parse the option structure
  261. shareOption := val.(*shareEntry.ShareOption)
  262. //Check for permission
  263. if shareOption.Permission == "anyone" {
  264. //OK to proceed
  265. } else if shareOption.Permission == "signedin" {
  266. if !s.options.AuthAgent.CheckAuth(r) {
  267. //Redirect to login page
  268. if directDownload || directServe {
  269. w.WriteHeader(http.StatusUnauthorized)
  270. w.Write([]byte("401 - Unauthorized"))
  271. } else {
  272. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/preview/?id="+id, 307)
  273. }
  274. return
  275. } else {
  276. //Ok to proccedd
  277. }
  278. } else if shareOption.Permission == "samegroup" {
  279. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  280. if err != nil {
  281. if directDownload || directServe {
  282. w.WriteHeader(http.StatusUnauthorized)
  283. w.Write([]byte("401 - Unauthorized"))
  284. } else {
  285. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/preview/?id="+id, 307)
  286. }
  287. return
  288. }
  289. //Check if all the user groups are inside the share owner groups
  290. valid := true
  291. thisUsersGroupByName := []string{}
  292. for _, pg := range thisuserinfo.PermissionGroup {
  293. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  294. }
  295. for _, allowedpg := range shareOption.Accessibles {
  296. if inArray(thisUsersGroupByName, allowedpg) {
  297. //This required group is inside this user's group. OK
  298. } else {
  299. //This required group is not inside user's group. Reject
  300. valid = false
  301. }
  302. }
  303. if !valid {
  304. //Serve permission denied page
  305. if directDownload || directServe {
  306. w.WriteHeader(http.StatusForbidden)
  307. w.Write([]byte("401 - Forbidden"))
  308. } else {
  309. ServePermissionDeniedPage(w)
  310. }
  311. return
  312. }
  313. } else if shareOption.Permission == "users" {
  314. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  315. if err != nil {
  316. //User not logged in. Redirect to login page
  317. if directDownload || directServe {
  318. w.WriteHeader(http.StatusUnauthorized)
  319. w.Write([]byte("401 - Unauthorized"))
  320. } else {
  321. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  322. }
  323. return
  324. }
  325. //Check if username in the allowed user list
  326. if !inArray(shareOption.Accessibles, thisuserinfo.Username) && shareOption.Owner != thisuserinfo.Username {
  327. //Serve permission denied page
  328. if directDownload || directServe {
  329. w.WriteHeader(http.StatusForbidden)
  330. w.Write([]byte("401 - Forbidden"))
  331. } else {
  332. ServePermissionDeniedPage(w)
  333. }
  334. return
  335. }
  336. } else if shareOption.Permission == "groups" {
  337. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  338. if err != nil {
  339. //User not logged in. Redirect to login page
  340. if directDownload || directServe {
  341. w.WriteHeader(http.StatusUnauthorized)
  342. w.Write([]byte("401 - Unauthorized"))
  343. } else {
  344. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  345. }
  346. return
  347. }
  348. allowAccess := false
  349. thisUsersGroupByName := []string{}
  350. for _, pg := range thisuserinfo.PermissionGroup {
  351. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  352. }
  353. for _, thisUserPg := range thisUsersGroupByName {
  354. if inArray(shareOption.Accessibles, thisUserPg) {
  355. allowAccess = true
  356. }
  357. }
  358. if !allowAccess {
  359. //Serve permission denied page
  360. if directDownload || directServe {
  361. w.WriteHeader(http.StatusForbidden)
  362. w.Write([]byte("401 - Forbidden"))
  363. } else {
  364. ServePermissionDeniedPage(w)
  365. }
  366. return
  367. }
  368. } else {
  369. //Unsupported mode. Show notfound
  370. http.NotFound(w, r)
  371. return
  372. }
  373. //Serve the download page
  374. if isDir(shareOption.FileRealPath) {
  375. type File struct {
  376. Filename string
  377. RelPath string
  378. Filesize string
  379. IsDir bool
  380. }
  381. if directDownload {
  382. if relpath != "" {
  383. //User specified a specific file within the directory. Escape the relpath
  384. targetFilepath := filepath.Join(shareOption.FileRealPath, relpath)
  385. //Check if file exists
  386. if !fileExists(targetFilepath) {
  387. http.NotFound(w, r)
  388. return
  389. }
  390. //Validate the absolute path to prevent path escape
  391. absroot, _ := filepath.Abs(shareOption.FileRealPath)
  392. abstarget, _ := filepath.Abs(targetFilepath)
  393. if len(abstarget) <= len(absroot) || abstarget[:len(absroot)] != absroot {
  394. //Directory escape detected
  395. w.WriteHeader(http.StatusBadRequest)
  396. w.Write([]byte("400 - Bad Request: Invalid relative path"))
  397. return
  398. }
  399. //Serve the target file
  400. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(targetFilepath)), "+", "%20"))
  401. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  402. http.ServeFile(w, r, targetFilepath)
  403. sendOK(w)
  404. } else {
  405. //Download this folder as zip
  406. //Build the filelist to download
  407. //Create a zip using ArOZ Zipper, tmp zip files are located under tmp/share-cache/*.zip
  408. tmpFolder := s.options.TmpFolder
  409. tmpFolder = filepath.Join(tmpFolder, "share-cache")
  410. os.MkdirAll(tmpFolder, 0755)
  411. targetZipFilename := filepath.Join(tmpFolder, filepath.Base(shareOption.FileRealPath)) + ".zip"
  412. //Build a filelist
  413. err := filesystem.ArozZipFile([]string{shareOption.FileRealPath}, targetZipFilename, false)
  414. if err != nil {
  415. //Failed to create zip file
  416. w.WriteHeader(http.StatusInternalServerError)
  417. w.Write([]byte("500 - Internal Server Error: Zip file creation failed"))
  418. log.Println("Failed to create zip file for share download: " + err.Error())
  419. return
  420. }
  421. //Serve thje zip file
  422. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20")+".zip")
  423. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  424. http.ServeFile(w, r, targetZipFilename)
  425. }
  426. } else if directServe {
  427. //Folder provide no direct serve method.
  428. w.WriteHeader(http.StatusBadRequest)
  429. w.Write([]byte("400 - Cannot preview folder type shares"))
  430. return
  431. } else {
  432. //Show download page. Do not allow serving
  433. content, err := ioutil.ReadFile("./system/share/downloadPageFolder.html")
  434. if err != nil {
  435. http.NotFound(w, r)
  436. return
  437. }
  438. //Get file size
  439. fsize, fcount := filesystem.GetDirctorySize(shareOption.FileRealPath, false)
  440. //Build the tree list of the folder
  441. treeList := map[string][]File{}
  442. err = filepath.Walk(filepath.Clean(shareOption.FileRealPath), func(file string, info os.FileInfo, err error) error {
  443. if err != nil {
  444. //If error skip this
  445. return nil
  446. }
  447. if filepath.Base(file)[:1] != "." {
  448. fileSize := filesystem.GetFileSize(file)
  449. if filesystem.IsDir(file) {
  450. fileSize, _ = filesystem.GetDirctorySize(file, false)
  451. }
  452. relPath, err := filepath.Rel(shareOption.FileRealPath, file)
  453. if err != nil {
  454. relPath = ""
  455. }
  456. relPath = filepath.ToSlash(filepath.Clean(relPath))
  457. relDir := filepath.ToSlash(filepath.Dir(relPath))
  458. if relPath == "." {
  459. //The root file object. Skip this
  460. return nil
  461. }
  462. treeList[relDir] = append(treeList[relDir], File{
  463. Filename: filepath.Base(file),
  464. RelPath: filepath.ToSlash(relPath),
  465. Filesize: filesystem.GetFileDisplaySize(fileSize, 2),
  466. IsDir: filesystem.IsDir(file),
  467. })
  468. }
  469. return nil
  470. })
  471. if err != nil {
  472. w.WriteHeader(http.StatusInternalServerError)
  473. w.Write([]byte("500 - Internal Server Error"))
  474. return
  475. }
  476. tl, _ := json.Marshal(treeList)
  477. //Get modification time
  478. fmodtime, _ := filesystem.GetModTime(shareOption.FileRealPath)
  479. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  480. t := fasttemplate.New(string(content), "{{", "}}")
  481. s := t.ExecuteString(map[string]interface{}{
  482. "hostname": s.options.HostName,
  483. "host": r.Host,
  484. "reqid": id,
  485. "mime": "application/x-directory",
  486. "size": filesystem.GetFileDisplaySize(fsize, 2),
  487. "filecount": strconv.Itoa(fcount),
  488. "modtime": timeString,
  489. "downloadurl": "../../share/download/" + id,
  490. "filename": filepath.Base(shareOption.FileRealPath),
  491. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  492. "requri": "//" + r.Host + r.URL.Path,
  493. "opg_image": "/share/opg/" + strconv.Itoa(int(time.Now().Unix())) + "/" + id,
  494. "treelist": tl,
  495. "downloaduuid": id,
  496. })
  497. w.Write([]byte(s))
  498. return
  499. }
  500. } else {
  501. //This share is a file
  502. if directDownload {
  503. //Serve the file directly
  504. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20"))
  505. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  506. http.ServeFile(w, r, shareOption.FileRealPath)
  507. } else if directServe {
  508. w.Header().Set("Access-Control-Allow-Origin", "*")
  509. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  510. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  511. http.ServeFile(w, r, shareOption.FileRealPath)
  512. } else {
  513. //Serve the download page
  514. content, err := ioutil.ReadFile("./system/share/downloadPage.html")
  515. if err != nil {
  516. http.NotFound(w, r)
  517. return
  518. }
  519. //Get file mime type
  520. mime, ext, err := filesystem.GetMime(shareOption.FileRealPath)
  521. if err != nil {
  522. mime = "Unknown"
  523. }
  524. //Load the preview template
  525. templateRoot := "./system/share/"
  526. previewTemplate := ""
  527. if ext == ".mp4" || ext == ".webm" {
  528. previewTemplate = filepath.Join(templateRoot, "video.html")
  529. } else if ext == ".mp3" || ext == ".wav" || ext == ".flac" || ext == ".ogg" {
  530. previewTemplate = filepath.Join(templateRoot, "audio.html")
  531. } else if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".webp" {
  532. previewTemplate = filepath.Join(templateRoot, "image.html")
  533. } else if ext == ".pdf" {
  534. previewTemplate = filepath.Join(templateRoot, "iframe.html")
  535. } else {
  536. //Format do not support preview. Use the default.html
  537. previewTemplate = filepath.Join(templateRoot, "default.html")
  538. }
  539. tp, err := ioutil.ReadFile(previewTemplate)
  540. if err != nil {
  541. tp = []byte("")
  542. }
  543. //Merge two templates
  544. content = []byte(strings.ReplaceAll(string(content), "{{previewer}}", string(tp)))
  545. //Get file size
  546. fsize := filesystem.GetFileSize(shareOption.FileRealPath)
  547. //Get modification time
  548. fmodtime, _ := filesystem.GetModTime(shareOption.FileRealPath)
  549. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  550. //Check if ext match with filepath ext
  551. displayExt := ext
  552. if ext != filepath.Ext(shareOption.FileRealPath) {
  553. displayExt = filepath.Ext(shareOption.FileRealPath) + " (" + ext + ")"
  554. }
  555. t := fasttemplate.New(string(content), "{{", "}}")
  556. s := t.ExecuteString(map[string]interface{}{
  557. "hostname": s.options.HostName,
  558. "host": r.Host,
  559. "reqid": id,
  560. "requri": "//" + r.Host + r.URL.Path,
  561. "mime": mime,
  562. "ext": displayExt,
  563. "size": filesystem.GetFileDisplaySize(fsize, 2),
  564. "modtime": timeString,
  565. "downloadurl": "../../share/download/" + id + "/" + filepath.Base(shareOption.FileRealPath),
  566. "preview_url": "/share/preview/" + id + "/",
  567. "filename": filepath.Base(shareOption.FileRealPath),
  568. "opg_image": "/share/opg/" + strconv.Itoa(int(time.Now().Unix())) + "/" + id,
  569. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  570. })
  571. w.Write([]byte(s))
  572. return
  573. }
  574. }
  575. } else {
  576. //This share not exists
  577. if directDownload {
  578. //Send 404 header
  579. http.NotFound(w, r)
  580. return
  581. } else {
  582. //Send not found page
  583. content, err := ioutil.ReadFile("./system/share/notfound.html")
  584. if err != nil {
  585. http.NotFound(w, r)
  586. return
  587. }
  588. t := fasttemplate.New(string(content), "{{", "}}")
  589. s := t.ExecuteString(map[string]interface{}{
  590. "hostname": s.options.HostName,
  591. "reqid": id,
  592. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  593. })
  594. w.Write([]byte(s))
  595. return
  596. }
  597. }
  598. }
  599. //Check if a file is shared
  600. func (s *Manager) HandleShareCheck(w http.ResponseWriter, r *http.Request) {
  601. //Get the vpath from paramters
  602. vpath, err := mv(r, "path", true)
  603. if err != nil {
  604. sendErrorResponse(w, "Invalid path given")
  605. return
  606. }
  607. //Get userinfo
  608. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  609. if err != nil {
  610. sendErrorResponse(w, "User not logged in")
  611. return
  612. }
  613. //Get realpath from userinfo
  614. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  615. if err != nil {
  616. sendErrorResponse(w, "Unable to resolve realpath")
  617. return
  618. }
  619. type Result struct {
  620. IsShared bool
  621. ShareUUID *shareEntry.ShareOption
  622. }
  623. //Check if share exists
  624. shareExists := s.options.ShareEntryTable.FileIsShared(rpath)
  625. if !shareExists {
  626. //Share not exists
  627. js, _ := json.Marshal(Result{
  628. IsShared: false,
  629. ShareUUID: &shareEntry.ShareOption{},
  630. })
  631. sendJSONResponse(w, string(js))
  632. } else {
  633. //Share exists
  634. thisSharedInfo := s.options.ShareEntryTable.GetShareObjectFromRealPath(rpath)
  635. js, _ := json.Marshal(Result{
  636. IsShared: true,
  637. ShareUUID: thisSharedInfo,
  638. })
  639. sendJSONResponse(w, string(js))
  640. }
  641. }
  642. //Create new share from the given path
  643. func (s *Manager) HandleCreateNewShare(w http.ResponseWriter, r *http.Request) {
  644. //Get the vpath from paramters
  645. vpath, err := mv(r, "path", true)
  646. if err != nil {
  647. sendErrorResponse(w, "Invalid path given")
  648. return
  649. }
  650. //Get userinfo
  651. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  652. if err != nil {
  653. sendErrorResponse(w, "User not logged in")
  654. return
  655. }
  656. //Check if this is in the share folder
  657. vrootID, subpath, err := filesystem.GetIDFromVirtualPath(vpath)
  658. if err != nil {
  659. sendErrorResponse(w, "Unable to resolve virtual path")
  660. return
  661. }
  662. if vrootID == "share" {
  663. shareObject, err := s.options.ShareEntryTable.ResolveShareOptionFromShareSubpath(subpath)
  664. if err != nil {
  665. sendErrorResponse(w, err.Error())
  666. return
  667. }
  668. //Check if this share is own by or accessible by the current user. Reject share modification if not
  669. if !shareObject.IsOwnedBy(userinfo.Username) && !userinfo.CanWrite(vpath) {
  670. sendErrorResponse(w, "Permission Denied: You are not the file owner nor can write to this file")
  671. return
  672. }
  673. }
  674. share, err := s.CreateNewShare(userinfo, vpath)
  675. if err != nil {
  676. sendErrorResponse(w, err.Error())
  677. return
  678. }
  679. js, _ := json.Marshal(share)
  680. sendJSONResponse(w, string(js))
  681. }
  682. // Handle Share Edit.
  683. // For allowing groups / users, use the following syntax
  684. // groups:group1,group2,group3
  685. // users:user1,user2,user3
  686. // For basic modes, use the following keywords
  687. // anyone / signedin / samegroup
  688. // anyone: Anyone who has the link
  689. // signedin: Anyone logged in to this system
  690. // samegroup: The requesting user has the same (or more) user group as the share owner
  691. func (s *Manager) HandleEditShare(w http.ResponseWriter, r *http.Request) {
  692. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  693. if err != nil {
  694. sendErrorResponse(w, "User not logged in")
  695. return
  696. }
  697. uuid, err := mv(r, "uuid", true)
  698. if err != nil {
  699. sendErrorResponse(w, "Invalid path given")
  700. return
  701. }
  702. shareMode, _ := mv(r, "mode", true)
  703. if shareMode == "" {
  704. shareMode = "signedin"
  705. }
  706. //Check if share exists
  707. so := s.options.ShareEntryTable.GetShareObjectFromUUID(uuid)
  708. if so == nil {
  709. //This share url not exists
  710. sendErrorResponse(w, "Share UUID not exists")
  711. return
  712. }
  713. //Check if the user has permission to edit this share
  714. if so.Owner != userinfo.Username && !userinfo.IsAdmin() {
  715. //This file is not shared by this user and this user is not admin. Block this request
  716. sendErrorResponse(w, "Permission denied")
  717. return
  718. }
  719. //Validate and extract the storage mode
  720. ok, sharetype, settings := validateShareModes(shareMode)
  721. if !ok {
  722. sendErrorResponse(w, "Invalid share setting")
  723. return
  724. }
  725. //Analysis the sharetype
  726. if sharetype == "anyone" || sharetype == "signedin" || sharetype == "samegroup" {
  727. //Basic types.
  728. so.Permission = sharetype
  729. if sharetype == "samegroup" {
  730. //Write user groups into accessible (Must be all match inorder to allow access)
  731. userpg := []string{}
  732. for _, pg := range userinfo.PermissionGroup {
  733. userpg = append(userpg, pg.Name)
  734. }
  735. so.Accessibles = userpg
  736. }
  737. //Write changes to database
  738. s.options.ShareEntryTable.Database.Write("share", uuid, so)
  739. } else if sharetype == "groups" || sharetype == "users" {
  740. //Username or group is listed = ok
  741. so.Permission = sharetype
  742. so.Accessibles = settings
  743. //Write changes to database
  744. s.options.ShareEntryTable.Database.Write("share", uuid, so)
  745. }
  746. sendOK(w)
  747. }
  748. func (s *Manager) HandleDeleteShare(w http.ResponseWriter, r *http.Request) {
  749. //Get the vpath from paramters
  750. vpath, err := mv(r, "path", true)
  751. if err != nil {
  752. sendErrorResponse(w, "Invalid path given")
  753. return
  754. }
  755. //Get userinfo
  756. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  757. if err != nil {
  758. sendErrorResponse(w, "User not logged in")
  759. return
  760. }
  761. //Delete the share setting
  762. err = s.DeleteShare(userinfo, vpath)
  763. if err != nil {
  764. sendErrorResponse(w, err.Error())
  765. } else {
  766. sendOK(w)
  767. }
  768. }
  769. //Craete a new file or folder share
  770. func (s *Manager) CreateNewShare(userinfo *user.User, vpath string) (*shareEntry.ShareOption, error) {
  771. //Translate the vpath to realpath
  772. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  773. if err != nil {
  774. return nil, errors.New("Unable to find the file on disk")
  775. }
  776. return s.options.ShareEntryTable.CreateNewShare(rpath, userinfo.Username, userinfo.GetUserPermissionGroupNames())
  777. }
  778. func ServePermissionDeniedPage(w http.ResponseWriter) {
  779. w.WriteHeader(http.StatusForbidden)
  780. pageContent := []byte("Permissioned Denied")
  781. if fileExists("system/share/permissionDenied.html") {
  782. content, err := ioutil.ReadFile("system/share/permissionDenied.html")
  783. if err == nil {
  784. pageContent = content
  785. }
  786. }
  787. w.Write([]byte(pageContent))
  788. }
  789. /*
  790. Validate Share Mode string
  791. will return
  792. 1. bool => Is valid
  793. 2. permission type: {basic / groups / users}
  794. 3. mode string
  795. */
  796. func validateShareModes(mode string) (bool, string, []string) {
  797. // user:a,b,c,d
  798. validModes := []string{"anyone", "signedin", "samegroup"}
  799. if inArray(validModes, mode) {
  800. //Standard modes
  801. return true, mode, []string{}
  802. } else if len(mode) > 7 && mode[:7] == "groups:" {
  803. //Handle custom group case like groups:a,b,c,d
  804. groupList := mode[7:]
  805. if len(groupList) > 0 {
  806. groups := strings.Split(groupList, ",")
  807. return true, "groups", groups
  808. } else {
  809. //Invalid configuration
  810. return false, "groups", []string{}
  811. }
  812. } else if len(mode) > 6 && mode[:6] == "users:" {
  813. //Handle custom usersname like users:a,b,c,d
  814. userList := mode[6:]
  815. if len(userList) > 0 {
  816. users := strings.Split(userList, ",")
  817. return true, "users", users
  818. } else {
  819. //Invalid configuration
  820. return false, "users", []string{}
  821. }
  822. }
  823. return false, "", []string{}
  824. }
  825. //Check and clear shares that its pointinf files no longe exists
  826. func (s *Manager) ValidateAndClearShares() {
  827. //Iterate through all shares within the system
  828. s.options.ShareEntryTable.FileToUrlMap.Range(func(k, v interface{}) bool {
  829. thisRealPath := k.(string)
  830. if !fileExists(thisRealPath) {
  831. //This share source file don't exists anymore. Remove it
  832. s.options.ShareEntryTable.RemoveShareByRealpath(thisRealPath)
  833. log.Println("*Share* Removing share to file: " + thisRealPath + " as it no longer exists")
  834. }
  835. return true
  836. })
  837. }
  838. func (s *Manager) DeleteShare(userinfo *user.User, vpath string) error {
  839. //Translate the vpath to realpath
  840. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  841. if err != nil {
  842. return errors.New("Unable to find the file on disk")
  843. }
  844. return s.options.ShareEntryTable.DeleteShare(rpath)
  845. }
  846. func (s *Manager) GetShareUUIDFromPath(rpath string) string {
  847. return s.options.ShareEntryTable.GetShareUUIDFromPath(rpath)
  848. }
  849. func (s *Manager) GetShareObjectFromRealPath(rpath string) *shareEntry.ShareOption {
  850. return s.options.ShareEntryTable.GetShareObjectFromRealPath(rpath)
  851. }
  852. func (s *Manager) GetShareObjectFromUUID(uuid string) *shareEntry.ShareOption {
  853. return s.options.ShareEntryTable.GetShareObjectFromUUID(uuid)
  854. }
  855. func (s *Manager) FileIsShared(rpath string) bool {
  856. return s.options.ShareEntryTable.FileIsShared(rpath)
  857. }
  858. func (s *Manager) RemoveShareByRealpath(rpath string) error {
  859. return s.RemoveShareByRealpath(rpath)
  860. }
  861. func (s *Manager) RemoveShareByUUID(uuid string) error {
  862. return s.options.ShareEntryTable.RemoveShareByUUID(uuid)
  863. }