agi.file.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. package agi
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "io"
  8. "io/fs"
  9. "log"
  10. "os"
  11. "path/filepath"
  12. "github.com/robertkrimen/otto"
  13. "imuslab.com/arozos/mod/filesystem/fssort"
  14. "imuslab.com/arozos/mod/filesystem/hidden"
  15. user "imuslab.com/arozos/mod/user"
  16. )
  17. /*
  18. AJGI File Processing Library
  19. This is a library for handling image related functionalities in agi scripts.
  20. By Alanyueng 2020 <- This person write shitty code that need me to tidy up (by tobychui)
  21. Complete rewrite by tobychui in Sept 2020
  22. */
  23. func (g *Gateway) FileLibRegister() {
  24. err := g.RegisterLib("filelib", g.injectFileLibFunctions)
  25. if err != nil {
  26. log.Fatal(err)
  27. }
  28. }
  29. func (g *Gateway) injectFileLibFunctions(vm *otto.Otto, u *user.User) {
  30. //Legacy File system API
  31. //writeFile(virtualFilepath, content) => return true/false when succeed / failed
  32. vm.Set("_filelib_writeFile", func(call otto.FunctionCall) otto.Value {
  33. vpath, err := call.Argument(0).ToString()
  34. if err != nil {
  35. g.raiseError(err)
  36. return otto.FalseValue()
  37. }
  38. //Check for permission
  39. if !u.CanWrite(vpath) {
  40. panic(vm.MakeCustomError("PermissionDenied", "Path access denied: "+vpath))
  41. }
  42. content, err := call.Argument(1).ToString()
  43. if err != nil {
  44. g.raiseError(err)
  45. return otto.FalseValue()
  46. }
  47. //Check if there is quota for the given length
  48. if !u.StorageQuota.HaveSpace(int64(len(content))) {
  49. //User have no remaining storage quota
  50. g.raiseError(errors.New("Storage Quota Fulled"))
  51. return otto.FalseValue()
  52. }
  53. //Translate the virtual path to realpath
  54. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  55. if err != nil {
  56. g.raiseError(err)
  57. return otto.FalseValue()
  58. }
  59. //Check if file already exists.
  60. if fsh.FileSystemAbstraction.FileExists(rpath) {
  61. //Check if this user own this file
  62. isOwner := u.IsOwnerOfFile(fsh, vpath)
  63. if isOwner {
  64. //This user own this system. Remove this file from his quota
  65. u.RemoveOwnershipFromFile(fsh, vpath)
  66. }
  67. }
  68. //Create and write to file using ioutil
  69. err = fsh.FileSystemAbstraction.WriteFile(rpath, []byte(content), 0755)
  70. if err != nil {
  71. g.raiseError(err)
  72. return otto.FalseValue()
  73. }
  74. //Add the filesize to user quota
  75. u.SetOwnerOfFile(fsh, vpath)
  76. reply, _ := vm.ToValue(true)
  77. return reply
  78. })
  79. vm.Set("_filelib_deleteFile", func(call otto.FunctionCall) otto.Value {
  80. vpath, err := call.Argument(0).ToString()
  81. if err != nil {
  82. g.raiseError(err)
  83. return otto.FalseValue()
  84. }
  85. //Check for permission
  86. if !u.CanWrite(vpath) {
  87. panic(vm.MakeCustomError("PermissionDenied", "Path access denied: "+vpath))
  88. }
  89. //Translate the virtual path to realpath
  90. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  91. if err != nil {
  92. g.raiseError(err)
  93. return otto.FalseValue()
  94. }
  95. //Check if file already exists.
  96. if fsh.FileSystemAbstraction.FileExists(rpath) {
  97. //Check if this user own this file
  98. isOwner := u.IsOwnerOfFile(fsh, vpath)
  99. if isOwner {
  100. //This user own this system. Remove this file from his quota
  101. u.RemoveOwnershipFromFile(fsh, vpath)
  102. }
  103. } else {
  104. g.raiseError(errors.New("File not exists"))
  105. return otto.FalseValue()
  106. }
  107. //Remove the file
  108. fsh.FileSystemAbstraction.Remove(rpath)
  109. reply, _ := vm.ToValue(true)
  110. return reply
  111. })
  112. //readFile(virtualFilepath) => return content in string
  113. vm.Set("_filelib_readFile", func(call otto.FunctionCall) otto.Value {
  114. vpath, err := call.Argument(0).ToString()
  115. if err != nil {
  116. g.raiseError(err)
  117. return otto.FalseValue()
  118. }
  119. //Check for permission
  120. if !u.CanRead(vpath) {
  121. panic(vm.MakeCustomError("PermissionDenied", "Path access denied: "+vpath))
  122. }
  123. //Translate the virtual path to realpath
  124. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  125. if err != nil {
  126. g.raiseError(err)
  127. return otto.FalseValue()
  128. }
  129. //Create and write to file using ioUtil
  130. content, err := fsh.FileSystemAbstraction.ReadFile(rpath)
  131. if err != nil {
  132. g.raiseError(err)
  133. return otto.FalseValue()
  134. }
  135. reply, _ := vm.ToValue(string(content))
  136. return reply
  137. })
  138. //Listdir
  139. //readdir("user:/Desktop") => return filelist in array
  140. /*
  141. vm.Set("_filelib_readdir", func(call otto.FunctionCall) otto.Value {
  142. vpath, err := call.Argument(0).ToString()
  143. if err != nil {
  144. g.raiseError(err)
  145. return otto.FalseValue()
  146. }
  147. //Translate the virtual path to realpath
  148. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  149. if err != nil {
  150. g.raiseError(err)
  151. return otto.FalseValue()
  152. }
  153. fshAbs := fsh.FileSystemAbstraction
  154. rpath = filepath.ToSlash(filepath.Clean(rpath)) + "/*"
  155. fileList, err := fshAbs.Glob(rpath)
  156. if err != nil {
  157. g.raiseError(err)
  158. return otto.FalseValue()
  159. }
  160. //Translate all paths to virtual paths
  161. results := []string{}
  162. for _, file := range fileList {
  163. isHidden, _ := hidden.IsHidden(file, true)
  164. if !isHidden {
  165. thisRpath, _ := fshAbs.RealPathToVirtualPath(file, u.Username)
  166. results = append(results, thisRpath)
  167. }
  168. }
  169. reply, _ := vm.ToValue(results)
  170. return reply
  171. })
  172. */
  173. //Usage
  174. //filelib.walk("user:/") => list everything recursively
  175. //filelib.walk("user:/", "folder") => list all folder recursively
  176. //filelib.walk("user:/", "file") => list all files recursively
  177. vm.Set("_filelib_walk", func(call otto.FunctionCall) otto.Value {
  178. vpath, err := call.Argument(0).ToString()
  179. if err != nil {
  180. g.raiseError(err)
  181. return otto.FalseValue()
  182. }
  183. mode, err := call.Argument(1).ToString()
  184. if err != nil {
  185. mode = "all"
  186. }
  187. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  188. if err != nil {
  189. g.raiseError(err)
  190. return otto.FalseValue()
  191. }
  192. results := []string{}
  193. fsh.FileSystemAbstraction.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  194. if err != nil {
  195. //Ignore this error file and continue
  196. return nil
  197. }
  198. thisVpath, err := realpathToVirtualpath(fsh, path, u)
  199. if err != nil {
  200. return nil
  201. }
  202. if mode == "file" {
  203. if !info.IsDir() {
  204. results = append(results, thisVpath)
  205. }
  206. } else if mode == "folder" {
  207. if info.IsDir() {
  208. results = append(results, thisVpath)
  209. }
  210. } else {
  211. results = append(results, thisVpath)
  212. }
  213. return nil
  214. })
  215. reply, _ := vm.ToValue(results)
  216. return reply
  217. })
  218. //Glob
  219. //glob("user:/Desktop/*.mp3") => return fileList in array
  220. //glob("/") => return a list of root directories
  221. //glob("user:/Desktop/*", "mostRecent") => return fileList in mostRecent sorting mode
  222. //glob("user:/Desktop/*", "user") => return fileList in array in user prefered sorting method
  223. vm.Set("_filelib_glob", func(call otto.FunctionCall) otto.Value {
  224. regex, err := call.Argument(0).ToString()
  225. if err != nil {
  226. g.raiseError(err)
  227. return otto.FalseValue()
  228. }
  229. userSortMode, err := call.Argument(1).ToString()
  230. if err != nil || userSortMode == "" || userSortMode == "undefined" {
  231. userSortMode = "default"
  232. }
  233. //Handle when regex = "." or "./" (listroot)
  234. if filepath.ToSlash(filepath.Clean(regex)) == "/" || filepath.Clean(regex) == "." {
  235. //List Root
  236. rootDirs := []string{}
  237. fileHandlers := u.GetAllFileSystemHandler()
  238. for _, fsh := range fileHandlers {
  239. if fsh.Hierarchy == "backup" {
  240. } else {
  241. rootDirs = append(rootDirs, fsh.UUID+":/")
  242. }
  243. }
  244. reply, _ := vm.ToValue(rootDirs)
  245. return reply
  246. } else {
  247. //Check for permission
  248. if !u.CanRead(regex) {
  249. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  250. }
  251. //This function can only handle wildcard in filename but not in dir name
  252. vrootPath := filepath.Dir(regex)
  253. regexFilename := filepath.Base(regex)
  254. //Rewrite and validate the sort mode
  255. if userSortMode == "user" {
  256. //Use user sorting mode.
  257. if g.Option.UserHandler.GetDatabase().KeyExists("fs-sortpref", u.Username+"/"+filepath.ToSlash(filepath.Clean(vrootPath))) {
  258. g.Option.UserHandler.GetDatabase().Read("fs-sortpref", u.Username+"/"+filepath.ToSlash(filepath.Clean(vrootPath)), &userSortMode)
  259. } else {
  260. userSortMode = "default"
  261. }
  262. }
  263. if !fssort.SortModeIsSupported(userSortMode) {
  264. log.Println("[AGI] Sort mode: " + userSortMode + " not supported. Using default")
  265. userSortMode = "default"
  266. }
  267. //Translate the virtual path to realpath
  268. fsh, rrootPath, err := virtualPathToRealPath(vrootPath, u)
  269. if err != nil {
  270. g.raiseError(err)
  271. return otto.FalseValue()
  272. }
  273. suitableFiles, err := fsh.FileSystemAbstraction.Glob(filepath.Join(rrootPath, regexFilename))
  274. if err != nil {
  275. g.raiseError(err)
  276. return otto.FalseValue()
  277. }
  278. fileList := []string{}
  279. fis := []fs.FileInfo{}
  280. for _, thisFile := range suitableFiles {
  281. fi, err := fsh.FileSystemAbstraction.Stat(thisFile)
  282. if err == nil {
  283. fileList = append(fileList, thisFile)
  284. fis = append(fis, fi)
  285. }
  286. }
  287. //Sort the files
  288. newFilelist := fssort.SortFileList(fileList, fis, userSortMode)
  289. //Return the results in virtual paths
  290. results := []string{}
  291. for _, file := range newFilelist {
  292. isHidden, _ := hidden.IsHidden(file, true)
  293. if isHidden {
  294. //Hidden file. Skip this
  295. continue
  296. }
  297. thisVpath, _ := realpathToVirtualpath(fsh, file, u)
  298. results = append(results, thisVpath)
  299. }
  300. reply, _ := vm.ToValue(results)
  301. return reply
  302. }
  303. })
  304. //Advance Glob using file system special Glob, cannot use to scan root dirs
  305. vm.Set("_filelib_aglob", func(call otto.FunctionCall) otto.Value {
  306. regex, err := call.Argument(0).ToString()
  307. if err != nil {
  308. g.raiseError(err)
  309. return otto.FalseValue()
  310. }
  311. userSortMode, err := call.Argument(1).ToString()
  312. if err != nil || userSortMode == "" || userSortMode == "undefined" {
  313. userSortMode = "default"
  314. }
  315. if regex != "/" && !u.CanRead(regex) {
  316. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  317. }
  318. //This function can only handle wildcard in filename but not in dir name
  319. vrootPath := filepath.Dir(regex)
  320. regexFilename := filepath.Base(regex)
  321. //Rewrite and validate the sort mode
  322. if userSortMode == "user" {
  323. //Use user sorting mode.
  324. if g.Option.UserHandler.GetDatabase().KeyExists("fs-sortpref", u.Username+"/"+filepath.ToSlash(filepath.Clean(vrootPath))) {
  325. g.Option.UserHandler.GetDatabase().Read("fs-sortpref", u.Username+"/"+filepath.ToSlash(filepath.Clean(vrootPath)), &userSortMode)
  326. } else {
  327. userSortMode = "default"
  328. }
  329. }
  330. if !fssort.SortModeIsSupported(userSortMode) {
  331. log.Println("[AGI] Sort mode: " + userSortMode + " not supported. Using default")
  332. userSortMode = "default"
  333. }
  334. //Translate the virtual path to realpath
  335. fsh, err := u.GetFileSystemHandlerFromVirtualPath(vrootPath)
  336. if err != nil {
  337. g.raiseError(err)
  338. return otto.FalseValue()
  339. }
  340. fshAbs := fsh.FileSystemAbstraction
  341. rrootPath, _ := fshAbs.VirtualPathToRealPath(vrootPath, u.Username)
  342. suitableFiles, err := fshAbs.Glob(filepath.Join(rrootPath, regexFilename))
  343. if err != nil {
  344. g.raiseError(err)
  345. return otto.FalseValue()
  346. }
  347. fileList := []string{}
  348. fis := []fs.FileInfo{}
  349. for _, thisFile := range suitableFiles {
  350. fi, err := fsh.FileSystemAbstraction.Stat(thisFile)
  351. if err == nil {
  352. fileList = append(fileList, thisFile)
  353. fis = append(fis, fi)
  354. }
  355. }
  356. //Sort the files
  357. newFilelist := fssort.SortFileList(fileList, fis, userSortMode)
  358. //Parse the results (Only extract the filepath)
  359. results := []string{}
  360. for _, filename := range newFilelist {
  361. isHidden, _ := hidden.IsHidden(filename, true)
  362. if isHidden {
  363. //Hidden file. Skip this
  364. continue
  365. }
  366. thisVpath, _ := realpathToVirtualpath(fsh, filename, u)
  367. results = append(results, thisVpath)
  368. }
  369. reply, _ := vm.ToValue(results)
  370. return reply
  371. })
  372. vm.Set("_filelib_readdir", func(call otto.FunctionCall) otto.Value {
  373. vpath, err := call.Argument(0).ToString()
  374. if err != nil {
  375. g.raiseError(err)
  376. return otto.FalseValue()
  377. }
  378. //Check for permission
  379. if !u.CanRead(vpath) {
  380. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  381. }
  382. userSortMode, err := call.Argument(1).ToString()
  383. if err != nil || userSortMode == "" || userSortMode == "undefined" {
  384. userSortMode = "default"
  385. }
  386. //Rewrite and validate the sort mode
  387. if userSortMode == "user" {
  388. //Use user sorting mode.
  389. if g.Option.UserHandler.GetDatabase().KeyExists("fs-sortpref", u.Username+"/"+filepath.ToSlash(filepath.Clean(vpath))) {
  390. g.Option.UserHandler.GetDatabase().Read("fs-sortpref", u.Username+"/"+filepath.ToSlash(filepath.Clean(vpath)), &userSortMode)
  391. } else {
  392. userSortMode = "default"
  393. }
  394. }
  395. if !fssort.SortModeIsSupported(userSortMode) {
  396. log.Println("[AGI] Sort mode: " + userSortMode + " not supported. Using default")
  397. userSortMode = "default"
  398. }
  399. fsh, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  400. if err != nil {
  401. g.raiseError(err)
  402. return otto.FalseValue()
  403. }
  404. fshAbs := fsh.FileSystemAbstraction
  405. rpath, err := fshAbs.VirtualPathToRealPath(vpath, u.Username)
  406. if err != nil {
  407. g.raiseError(err)
  408. return otto.FalseValue()
  409. }
  410. dirEntry, err := fshAbs.ReadDir(rpath)
  411. if err != nil {
  412. g.raiseError(err)
  413. return otto.FalseValue()
  414. }
  415. type fileInfo struct {
  416. Filename string
  417. Filepath string
  418. Ext string
  419. Filesize int64
  420. Modtime int64
  421. IsDir bool
  422. }
  423. //Sort the dirEntry by file info, a bit slow :(
  424. entries := map[string]fs.DirEntry{}
  425. fnames := []string{}
  426. fis := []fs.FileInfo{}
  427. if userSortMode != "default" {
  428. //Prepare the data structure for sorting
  429. for _, de := range dirEntry {
  430. fnames = append(fnames, de.Name())
  431. fstat, _ := de.Info()
  432. fis = append(fis, fstat)
  433. thisFsDirEntry := de
  434. entries[de.Name()] = thisFsDirEntry
  435. }
  436. //Sort it
  437. sortedNameList := fssort.SortFileList(fnames, fis, userSortMode)
  438. //Update dirEntry sequence
  439. newDirEntry := []fs.DirEntry{}
  440. for _, key := range sortedNameList {
  441. newDirEntry = append(newDirEntry, entries[key])
  442. }
  443. dirEntry = newDirEntry
  444. }
  445. results := []fileInfo{}
  446. for _, de := range dirEntry {
  447. isHidden, _ := hidden.IsHidden(de.Name(), false)
  448. if isHidden {
  449. continue
  450. }
  451. fstat, _ := de.Info()
  452. vpath, _ := realpathToVirtualpath(fsh, filepath.ToSlash(filepath.Join(rpath, de.Name())), u)
  453. thisInfo := fileInfo{
  454. Filename: de.Name(),
  455. Filepath: vpath,
  456. Ext: filepath.Ext(de.Name()),
  457. Filesize: fstat.Size(),
  458. Modtime: fstat.ModTime().Unix(),
  459. IsDir: de.IsDir(),
  460. }
  461. results = append(results, thisInfo)
  462. }
  463. js, _ := json.Marshal(results)
  464. r, _ := vm.ToValue(string(js))
  465. return r
  466. })
  467. //filesize("user:/Desktop/test.txt")
  468. vm.Set("_filelib_filesize", func(call otto.FunctionCall) otto.Value {
  469. vpath, err := call.Argument(0).ToString()
  470. if err != nil {
  471. g.raiseError(err)
  472. return otto.FalseValue()
  473. }
  474. //Check for permission
  475. if !u.CanRead(vpath) {
  476. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  477. }
  478. fsh, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  479. if err != nil {
  480. g.raiseError(err)
  481. return otto.FalseValue()
  482. }
  483. fshAbs := fsh.FileSystemAbstraction
  484. rpath, err := fshAbs.VirtualPathToRealPath(vpath, u.Username)
  485. if err != nil {
  486. g.raiseError(err)
  487. return otto.FalseValue()
  488. }
  489. //Get filesize of file
  490. rawsize := fshAbs.GetFileSize(rpath)
  491. if err != nil {
  492. g.raiseError(err)
  493. return otto.FalseValue()
  494. }
  495. reply, _ := vm.ToValue(rawsize)
  496. return reply
  497. })
  498. //fileExists("user:/Desktop/test.txt") => return true / false
  499. vm.Set("_filelib_fileExists", func(call otto.FunctionCall) otto.Value {
  500. vpath, err := call.Argument(0).ToString()
  501. if err != nil {
  502. g.raiseError(err)
  503. return otto.FalseValue()
  504. }
  505. //Check for permission
  506. if !u.CanRead(vpath) {
  507. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  508. }
  509. fsh, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  510. if err != nil {
  511. g.raiseError(err)
  512. return otto.FalseValue()
  513. }
  514. fshAbs := fsh.FileSystemAbstraction
  515. rpath, err := fshAbs.VirtualPathToRealPath(vpath, u.Username)
  516. if err != nil {
  517. g.raiseError(err)
  518. return otto.FalseValue()
  519. }
  520. if fshAbs.FileExists(rpath) {
  521. return otto.TrueValue()
  522. } else {
  523. return otto.FalseValue()
  524. }
  525. })
  526. //fileExists("user:/Desktop/test.txt") => return true / false
  527. vm.Set("_filelib_isDir", func(call otto.FunctionCall) otto.Value {
  528. vpath, err := call.Argument(0).ToString()
  529. if err != nil {
  530. g.raiseError(err)
  531. return otto.FalseValue()
  532. }
  533. //Check for permission
  534. if !u.CanRead(vpath) {
  535. panic(vm.MakeCustomError("PermissionDenied", "Path access denied: "+vpath))
  536. }
  537. //Translate the virtual path to realpath
  538. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  539. if err != nil {
  540. g.raiseError(err)
  541. return otto.FalseValue()
  542. }
  543. if _, err := fsh.FileSystemAbstraction.Stat(rpath); os.IsNotExist(err) {
  544. //File not exists
  545. panic(vm.MakeCustomError("File Not Exists", "Required path not exists"))
  546. }
  547. if fsh.FileSystemAbstraction.IsDir(rpath) {
  548. return otto.TrueValue()
  549. } else {
  550. return otto.FalseValue()
  551. }
  552. })
  553. //Make directory command
  554. vm.Set("_filelib_mkdir", func(call otto.FunctionCall) otto.Value {
  555. vdir, err := call.Argument(0).ToString()
  556. if err != nil {
  557. return otto.FalseValue()
  558. }
  559. //Check for permission
  560. if !u.CanWrite(vdir) {
  561. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  562. }
  563. //Translate the path to realpath
  564. fsh, rdir, err := virtualPathToRealPath(vdir, u)
  565. if err != nil {
  566. log.Println(err.Error())
  567. return otto.FalseValue()
  568. }
  569. //Create the directory at rdir location
  570. err = fsh.FileSystemAbstraction.MkdirAll(rdir, 0755)
  571. if err != nil {
  572. log.Println(err.Error())
  573. return otto.FalseValue()
  574. }
  575. return otto.TrueValue()
  576. })
  577. //Get MD5 of the given filepath, not implemented
  578. vm.Set("_filelib_md5", func(call otto.FunctionCall) otto.Value {
  579. vpath, err := call.Argument(0).ToString()
  580. if err != nil {
  581. g.raiseError(err)
  582. return otto.FalseValue()
  583. }
  584. //Check for permission
  585. if !u.CanRead(vpath) {
  586. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  587. }
  588. fsh, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  589. if err != nil {
  590. g.raiseError(err)
  591. return otto.FalseValue()
  592. }
  593. fshAbs := fsh.FileSystemAbstraction
  594. rpath, err := fshAbs.VirtualPathToRealPath(vpath, u.Username)
  595. if err != nil {
  596. g.raiseError(err)
  597. return otto.FalseValue()
  598. }
  599. f, err := fshAbs.ReadStream(rpath)
  600. if err != nil {
  601. g.raiseError(err)
  602. return otto.FalseValue()
  603. }
  604. defer f.Close()
  605. h := md5.New()
  606. if _, err := io.Copy(h, f); err != nil {
  607. g.raiseError(err)
  608. return otto.FalseValue()
  609. }
  610. md5Sum := hex.EncodeToString(h.Sum(nil))
  611. result, _ := vm.ToValue(md5Sum)
  612. return result
  613. })
  614. //Get the root name of the given virtual path root
  615. vm.Set("_filelib_rname", func(call otto.FunctionCall) otto.Value {
  616. //Get virtual path from the function input
  617. vpath, err := call.Argument(0).ToString()
  618. if err != nil {
  619. g.raiseError(err)
  620. return otto.FalseValue()
  621. }
  622. //Get fs handler from the vpath
  623. fsHandler, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  624. if err != nil {
  625. g.raiseError(err)
  626. return otto.FalseValue()
  627. }
  628. //Return the name of the fsHandler
  629. name, _ := vm.ToValue(fsHandler.Name)
  630. return name
  631. })
  632. vm.Set("_filelib_mtime", func(call otto.FunctionCall) otto.Value {
  633. vpath, err := call.Argument(0).ToString()
  634. if err != nil {
  635. g.raiseError(err)
  636. return otto.FalseValue()
  637. }
  638. //Check for permission
  639. if !u.CanRead(vpath) {
  640. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  641. }
  642. parseToUnix, err := call.Argument(1).ToBoolean()
  643. if err != nil {
  644. parseToUnix = false
  645. }
  646. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  647. if err != nil {
  648. log.Println(err.Error())
  649. return otto.FalseValue()
  650. }
  651. info, err := fsh.FileSystemAbstraction.Stat(rpath)
  652. if err != nil {
  653. log.Println(err.Error())
  654. return otto.FalseValue()
  655. }
  656. modTime := info.ModTime()
  657. if parseToUnix {
  658. result, _ := otto.ToValue(modTime.Unix())
  659. return result
  660. } else {
  661. result, _ := otto.ToValue(modTime.Format("2006-01-02 15:04:05"))
  662. return result
  663. }
  664. })
  665. //Other file operations, wip
  666. //Wrap all the native code function into an imagelib class
  667. vm.Run(`
  668. var filelib = {};
  669. filelib.writeFile = _filelib_writeFile;
  670. filelib.readFile = _filelib_readFile;
  671. filelib.deleteFile = _filelib_deleteFile;
  672. filelib.walk = _filelib_walk;
  673. filelib.glob = _filelib_glob;
  674. filelib.aglob = _filelib_aglob;
  675. filelib.filesize = _filelib_filesize;
  676. filelib.fileExists = _filelib_fileExists;
  677. filelib.isDir = _filelib_isDir;
  678. filelib.md5 = _filelib_md5;
  679. filelib.mkdir = _filelib_mkdir;
  680. filelib.mtime = _filelib_mtime;
  681. filelib.rootName = _filelib_rname;
  682. filelib.readdir = function(path, sortmode){
  683. var s = _filelib_readdir(path, sortmode);
  684. return JSON.parse(s);
  685. };
  686. `)
  687. }