agi.file.go 16 KB

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