share.go 28 KB

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