agi.file.go 23 KB

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