agi.file.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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. if userSortMode != "default" {
  425. //Prepare the data structure for sorting
  426. newDirEntry := fssort.SortDirEntryList(dirEntry, userSortMode)
  427. dirEntry = newDirEntry
  428. }
  429. results := []fileInfo{}
  430. for _, de := range dirEntry {
  431. isHidden, _ := hidden.IsHidden(de.Name(), false)
  432. if isHidden {
  433. continue
  434. }
  435. fstat, _ := de.Info()
  436. vpath, _ := realpathToVirtualpath(fsh, filepath.ToSlash(filepath.Join(rpath, de.Name())), u)
  437. thisInfo := fileInfo{
  438. Filename: de.Name(),
  439. Filepath: vpath,
  440. Ext: filepath.Ext(de.Name()),
  441. Filesize: fstat.Size(),
  442. Modtime: fstat.ModTime().Unix(),
  443. IsDir: de.IsDir(),
  444. }
  445. results = append(results, thisInfo)
  446. }
  447. js, _ := json.Marshal(results)
  448. r, _ := vm.ToValue(string(js))
  449. return r
  450. })
  451. //filesize("user:/Desktop/test.txt")
  452. vm.Set("_filelib_filesize", func(call otto.FunctionCall) otto.Value {
  453. vpath, err := call.Argument(0).ToString()
  454. if err != nil {
  455. g.raiseError(err)
  456. return otto.FalseValue()
  457. }
  458. //Check for permission
  459. if !u.CanRead(vpath) {
  460. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  461. }
  462. fsh, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  463. if err != nil {
  464. g.raiseError(err)
  465. return otto.FalseValue()
  466. }
  467. fshAbs := fsh.FileSystemAbstraction
  468. rpath, err := fshAbs.VirtualPathToRealPath(vpath, u.Username)
  469. if err != nil {
  470. g.raiseError(err)
  471. return otto.FalseValue()
  472. }
  473. //Get filesize of file
  474. rawsize := fshAbs.GetFileSize(rpath)
  475. if err != nil {
  476. g.raiseError(err)
  477. return otto.FalseValue()
  478. }
  479. reply, _ := vm.ToValue(rawsize)
  480. return reply
  481. })
  482. //fileExists("user:/Desktop/test.txt") => return true / false
  483. vm.Set("_filelib_fileExists", func(call otto.FunctionCall) otto.Value {
  484. vpath, err := call.Argument(0).ToString()
  485. if err != nil {
  486. g.raiseError(err)
  487. return otto.FalseValue()
  488. }
  489. //Check for permission
  490. if !u.CanRead(vpath) {
  491. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  492. }
  493. fsh, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  494. if err != nil {
  495. g.raiseError(err)
  496. return otto.FalseValue()
  497. }
  498. fshAbs := fsh.FileSystemAbstraction
  499. rpath, err := fshAbs.VirtualPathToRealPath(vpath, u.Username)
  500. if err != nil {
  501. g.raiseError(err)
  502. return otto.FalseValue()
  503. }
  504. if fshAbs.FileExists(rpath) {
  505. return otto.TrueValue()
  506. } else {
  507. return otto.FalseValue()
  508. }
  509. })
  510. //fileExists("user:/Desktop/test.txt") => return true / false
  511. vm.Set("_filelib_isDir", func(call otto.FunctionCall) otto.Value {
  512. vpath, err := call.Argument(0).ToString()
  513. if err != nil {
  514. g.raiseError(err)
  515. return otto.FalseValue()
  516. }
  517. //Check for permission
  518. if !u.CanRead(vpath) {
  519. panic(vm.MakeCustomError("PermissionDenied", "Path access denied: "+vpath))
  520. }
  521. //Translate the virtual path to realpath
  522. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  523. if err != nil {
  524. g.raiseError(err)
  525. return otto.FalseValue()
  526. }
  527. if _, err := fsh.FileSystemAbstraction.Stat(rpath); os.IsNotExist(err) {
  528. //File not exists
  529. panic(vm.MakeCustomError("File Not Exists", "Required path not exists"))
  530. }
  531. if fsh.FileSystemAbstraction.IsDir(rpath) {
  532. return otto.TrueValue()
  533. } else {
  534. return otto.FalseValue()
  535. }
  536. })
  537. //Make directory command
  538. vm.Set("_filelib_mkdir", func(call otto.FunctionCall) otto.Value {
  539. vdir, err := call.Argument(0).ToString()
  540. if err != nil {
  541. return otto.FalseValue()
  542. }
  543. //Check for permission
  544. if !u.CanWrite(vdir) {
  545. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  546. }
  547. //Translate the path to realpath
  548. fsh, rdir, err := virtualPathToRealPath(vdir, u)
  549. if err != nil {
  550. log.Println(err.Error())
  551. return otto.FalseValue()
  552. }
  553. //Create the directory at rdir location
  554. err = fsh.FileSystemAbstraction.MkdirAll(rdir, 0755)
  555. if err != nil {
  556. log.Println(err.Error())
  557. return otto.FalseValue()
  558. }
  559. return otto.TrueValue()
  560. })
  561. //Get MD5 of the given filepath, not implemented
  562. vm.Set("_filelib_md5", func(call otto.FunctionCall) otto.Value {
  563. vpath, err := call.Argument(0).ToString()
  564. if err != nil {
  565. g.raiseError(err)
  566. return otto.FalseValue()
  567. }
  568. //Check for permission
  569. if !u.CanRead(vpath) {
  570. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  571. }
  572. fsh, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  573. if err != nil {
  574. g.raiseError(err)
  575. return otto.FalseValue()
  576. }
  577. fshAbs := fsh.FileSystemAbstraction
  578. rpath, err := fshAbs.VirtualPathToRealPath(vpath, u.Username)
  579. if err != nil {
  580. g.raiseError(err)
  581. return otto.FalseValue()
  582. }
  583. f, err := fshAbs.ReadStream(rpath)
  584. if err != nil {
  585. g.raiseError(err)
  586. return otto.FalseValue()
  587. }
  588. defer f.Close()
  589. h := md5.New()
  590. if _, err := io.Copy(h, f); err != nil {
  591. g.raiseError(err)
  592. return otto.FalseValue()
  593. }
  594. md5Sum := hex.EncodeToString(h.Sum(nil))
  595. result, _ := vm.ToValue(md5Sum)
  596. return result
  597. })
  598. //Get the root name of the given virtual path root
  599. vm.Set("_filelib_rname", func(call otto.FunctionCall) otto.Value {
  600. //Get virtual path from the function input
  601. vpath, err := call.Argument(0).ToString()
  602. if err != nil {
  603. g.raiseError(err)
  604. return otto.FalseValue()
  605. }
  606. //Get fs handler from the vpath
  607. fsHandler, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  608. if err != nil {
  609. g.raiseError(err)
  610. return otto.FalseValue()
  611. }
  612. //Return the name of the fsHandler
  613. name, _ := vm.ToValue(fsHandler.Name)
  614. return name
  615. })
  616. vm.Set("_filelib_mtime", func(call otto.FunctionCall) otto.Value {
  617. vpath, err := call.Argument(0).ToString()
  618. if err != nil {
  619. g.raiseError(err)
  620. return otto.FalseValue()
  621. }
  622. //Check for permission
  623. if !u.CanRead(vpath) {
  624. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  625. }
  626. parseToUnix, err := call.Argument(1).ToBoolean()
  627. if err != nil {
  628. parseToUnix = false
  629. }
  630. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  631. if err != nil {
  632. log.Println(err.Error())
  633. return otto.FalseValue()
  634. }
  635. info, err := fsh.FileSystemAbstraction.Stat(rpath)
  636. if err != nil {
  637. log.Println(err.Error())
  638. return otto.FalseValue()
  639. }
  640. modTime := info.ModTime()
  641. if parseToUnix {
  642. result, _ := otto.ToValue(modTime.Unix())
  643. return result
  644. } else {
  645. result, _ := otto.ToValue(modTime.Format("2006-01-02 15:04:05"))
  646. return result
  647. }
  648. })
  649. //ArozOS v2.0 New features
  650. //Reading or writing from hex to target virtual filepath
  651. //Write binary from hex string
  652. vm.Set("_filelib_writeBinaryFile", func(call otto.FunctionCall) otto.Value {
  653. vpath, err := call.Argument(0).ToString()
  654. if err != nil {
  655. g.raiseError(err)
  656. return otto.FalseValue()
  657. }
  658. //Check for permission
  659. if !u.CanWrite(vpath) {
  660. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  661. }
  662. hexContent, err := call.Argument(1).ToString()
  663. if err != nil {
  664. g.raiseError(err)
  665. return otto.FalseValue()
  666. }
  667. //Get the target vpath
  668. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  669. if err != nil {
  670. log.Println(err.Error())
  671. return otto.FalseValue()
  672. }
  673. //Decode the hex content to bytes
  674. hexContentInByte, err := hex.DecodeString(hexContent)
  675. if err != nil {
  676. g.raiseError(err)
  677. return otto.FalseValue()
  678. }
  679. //Write the file to target file
  680. err = fsh.FileSystemAbstraction.WriteFile(rpath, hexContentInByte, 0775)
  681. if err != nil {
  682. g.raiseError(err)
  683. return otto.FalseValue()
  684. }
  685. return otto.TrueValue()
  686. })
  687. //Read file from external fsh. Small file only
  688. vm.Set("_filelib_readBinaryFile", func(call otto.FunctionCall) otto.Value {
  689. vpath, err := call.Argument(0).ToString()
  690. if err != nil {
  691. g.raiseError(err)
  692. return otto.NullValue()
  693. }
  694. //Check for permission
  695. if !u.CanRead(vpath) {
  696. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  697. }
  698. //Get the target vpath
  699. fsh, rpath, err := virtualPathToRealPath(vpath, u)
  700. if err != nil {
  701. g.raiseError(err)
  702. return otto.NullValue()
  703. }
  704. if !fsh.FileSystemAbstraction.FileExists(rpath) {
  705. //Check if the target file exists
  706. g.raiseError(err)
  707. return otto.NullValue()
  708. }
  709. content, err := fsh.FileSystemAbstraction.ReadFile(rpath)
  710. if err != nil {
  711. g.raiseError(err)
  712. return otto.NullValue()
  713. }
  714. hexifiedContent := hex.EncodeToString(content)
  715. val, _ := vm.ToValue(hexifiedContent)
  716. return val
  717. })
  718. //Other file operations, wip
  719. //Wrap all the native code function into an imagelib class
  720. vm.Run(`
  721. var filelib = {};
  722. filelib.writeFile = _filelib_writeFile;
  723. filelib.readFile = _filelib_readFile;
  724. filelib.deleteFile = _filelib_deleteFile;
  725. filelib.walk = _filelib_walk;
  726. filelib.glob = _filelib_glob;
  727. filelib.aglob = _filelib_aglob;
  728. filelib.filesize = _filelib_filesize;
  729. filelib.fileExists = _filelib_fileExists;
  730. filelib.isDir = _filelib_isDir;
  731. filelib.md5 = _filelib_md5;
  732. filelib.mkdir = _filelib_mkdir;
  733. filelib.mtime = _filelib_mtime;
  734. filelib.rootName = _filelib_rname;
  735. filelib.readdir = function(path, sortmode){
  736. var s = _filelib_readdir(path, sortmode);
  737. return JSON.parse(s);
  738. };
  739. `)
  740. }