agi.file.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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. rpath = filepath.ToSlash(filepath.Clean(rpath)) + "/*"
  163. fileList, err := specialGlob(rpath)
  164. if err != nil {
  165. g.raiseError(err)
  166. reply, _ := vm.ToValue(false)
  167. return reply
  168. }
  169. //Translate all paths to virtual paths
  170. results := []string{}
  171. for _, file := range fileList {
  172. //if IsDir(file) {
  173. isHidden, _ := hidden.IsHidden(file, true)
  174. if !isHidden {
  175. thisRpath, _ := realpathToVirtualpath(file, u)
  176. results = append(results, thisRpath)
  177. }
  178. //}
  179. }
  180. reply, _ := vm.ToValue(results)
  181. return reply
  182. })
  183. //Usage
  184. //filelib.walk("user:/") => list everything recursively
  185. //filelib.walk("user:/", "folder") => list all folder recursively
  186. //filelib.walk("user:/", "file") => list all files recursively
  187. vm.Set("_filelib_walk", func(call otto.FunctionCall) otto.Value {
  188. vpath, err := call.Argument(0).ToString()
  189. if err != nil {
  190. g.raiseError(err)
  191. reply, _ := vm.ToValue(false)
  192. return reply
  193. }
  194. mode, err := call.Argument(1).ToString()
  195. if err != nil {
  196. mode = "all"
  197. }
  198. rpath, err := virtualPathToRealPath(vpath, u)
  199. if err != nil {
  200. g.raiseError(err)
  201. reply, _ := vm.ToValue(false)
  202. return reply
  203. }
  204. results := []string{}
  205. filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  206. if err != nil {
  207. //Ignore this error file and continue
  208. return nil
  209. }
  210. thisVpath, err := realpathToVirtualpath(path, u)
  211. if err != nil {
  212. return nil
  213. }
  214. if mode == "file" {
  215. if !info.IsDir() {
  216. results = append(results, thisVpath)
  217. }
  218. } else if mode == "folder" {
  219. if info.IsDir() {
  220. results = append(results, thisVpath)
  221. }
  222. } else {
  223. results = append(results, thisVpath)
  224. }
  225. return nil
  226. })
  227. reply, _ := vm.ToValue(results)
  228. return reply
  229. })
  230. //Glob
  231. //glob("user:/Desktop/*.mp3") => return fileList in array
  232. //glob("/") => return a list of root directories
  233. //glob("user:/Desktop/*", "mostRecent") => return fileList in mostRecent sorting mode
  234. //glob("user:/Desktop/*", "user") => return fileList in array in user prefered sorting method
  235. vm.Set("_filelib_glob", func(call otto.FunctionCall) otto.Value {
  236. regex, err := call.Argument(0).ToString()
  237. if err != nil {
  238. g.raiseError(err)
  239. reply, _ := vm.ToValue(false)
  240. return reply
  241. }
  242. userSortMode, err := call.Argument(1).ToString()
  243. if err != nil || userSortMode == "" || userSortMode == "undefined" {
  244. userSortMode = "default"
  245. }
  246. //Handle when regex = "." or "./" (listroot)
  247. if filepath.ToSlash(filepath.Clean(regex)) == "/" || filepath.Clean(regex) == "." {
  248. //List Root
  249. rootDirs := []string{}
  250. fileHandlers := u.GetAllFileSystemHandler()
  251. for _, fsh := range fileHandlers {
  252. if fsh.Hierarchy == "backup" || fsh.Filesystem == "virtual" {
  253. } else {
  254. rootDirs = append(rootDirs, fsh.UUID+":/")
  255. }
  256. }
  257. reply, _ := vm.ToValue(rootDirs)
  258. return reply
  259. } else {
  260. //Check for permission
  261. if !u.CanRead(regex) {
  262. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  263. }
  264. //This function can only handle wildcard in filename but not in dir name
  265. vrootPath := filepath.Dir(regex)
  266. regexFilename := filepath.Base(regex)
  267. //Rewrite and validate the sort mode
  268. if userSortMode == "user" {
  269. //Use user sorting mode.
  270. if g.Option.UserHandler.GetDatabase().KeyExists("fs-sortpref", u.Username+"/"+filepath.ToSlash(vrootPath)) {
  271. g.Option.UserHandler.GetDatabase().Read("fs-sortpref", u.Username+"/"+filepath.ToSlash(vrootPath), &userSortMode)
  272. } else {
  273. userSortMode = "default"
  274. }
  275. }
  276. if !fssort.SortModeIsSupported(userSortMode) {
  277. log.Println("[AGI] Sort mode: " + userSortMode + " not supported. Using default")
  278. userSortMode = "default"
  279. }
  280. //Translate the virtual path to realpath
  281. rrootPath, err := virtualPathToRealPath(vrootPath, u)
  282. if err != nil {
  283. g.raiseError(err)
  284. reply, _ := vm.ToValue(false)
  285. return reply
  286. }
  287. suitableFiles, err := filepath.Glob(filepath.Join(rrootPath, regexFilename))
  288. if err != nil {
  289. g.raiseError(err)
  290. reply, _ := vm.ToValue(false)
  291. return reply
  292. }
  293. //Sort the files
  294. newFilelist := fssort.SortFileList(suitableFiles, userSortMode)
  295. //Return the results in virtual paths
  296. results := []string{}
  297. for _, file := range newFilelist {
  298. isHidden, _ := hidden.IsHidden(file, true)
  299. if isHidden {
  300. //Hidden file. Skip this
  301. continue
  302. }
  303. thisRpath, _ := realpathToVirtualpath(filepath.ToSlash(file), u)
  304. results = append(results, thisRpath)
  305. }
  306. reply, _ := vm.ToValue(results)
  307. return reply
  308. }
  309. })
  310. //Advance Glob using file system special Glob, cannot use to scan root dirs
  311. vm.Set("_filelib_aglob", func(call otto.FunctionCall) otto.Value {
  312. regex, err := call.Argument(0).ToString()
  313. if err != nil {
  314. g.raiseError(err)
  315. reply, _ := vm.ToValue(false)
  316. return reply
  317. }
  318. userSortMode, err := call.Argument(1).ToString()
  319. if err != nil || userSortMode == "" || userSortMode == "undefined" {
  320. userSortMode = "default"
  321. }
  322. if regex != "/" && !u.CanRead(regex) {
  323. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  324. }
  325. //This function can only handle wildcard in filename but not in dir name
  326. vrootPath := filepath.Dir(regex)
  327. regexFilename := filepath.Base(regex)
  328. //Rewrite and validate the sort mode
  329. if userSortMode == "user" {
  330. //Use user sorting mode.
  331. if g.Option.UserHandler.GetDatabase().KeyExists("fs-sortpref", u.Username+"/"+filepath.ToSlash(vrootPath)) {
  332. g.Option.UserHandler.GetDatabase().Read("fs-sortpref", u.Username+"/"+filepath.ToSlash(vrootPath), &userSortMode)
  333. } else {
  334. userSortMode = "default"
  335. }
  336. }
  337. if !fssort.SortModeIsSupported(userSortMode) {
  338. log.Println("[AGI] Sort mode: " + userSortMode + " not supported. Using default")
  339. userSortMode = "default"
  340. }
  341. //Translate the virtual path to realpath
  342. rrootPath, err := virtualPathToRealPath(vrootPath, u)
  343. if err != nil {
  344. g.raiseError(err)
  345. reply, _ := vm.ToValue(false)
  346. return reply
  347. }
  348. suitableFiles, err := specialGlob(filepath.Join(rrootPath, regexFilename))
  349. if err != nil {
  350. g.raiseError(err)
  351. reply, _ := vm.ToValue(false)
  352. return reply
  353. }
  354. //Sort the files
  355. newFilelist := fssort.SortFileList(suitableFiles, userSortMode)
  356. //Parse the results (Only extract the filepath)
  357. results := []string{}
  358. for _, filename := range newFilelist {
  359. isHidden, _ := hidden.IsHidden(filename, true)
  360. if isHidden {
  361. //Hidden file. Skip this
  362. continue
  363. }
  364. thisVpath, _ := u.RealPathToVirtualPath(filename)
  365. results = append(results, thisVpath)
  366. }
  367. reply, _ := vm.ToValue(results)
  368. return reply
  369. })
  370. //filesize("user:/Desktop/test.txt")
  371. vm.Set("_filelib_filesize", func(call otto.FunctionCall) otto.Value {
  372. vpath, err := call.Argument(0).ToString()
  373. if err != nil {
  374. g.raiseError(err)
  375. reply, _ := vm.ToValue(false)
  376. return reply
  377. }
  378. //Check for permission
  379. if !u.CanRead(vpath) {
  380. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  381. }
  382. //Translate the virtual path to realpath
  383. rpath, err := virtualPathToRealPath(vpath, u)
  384. if err != nil {
  385. g.raiseError(err)
  386. reply, _ := vm.ToValue(false)
  387. return reply
  388. }
  389. //Get filesize of file
  390. rawsize := fs.GetFileSize(rpath)
  391. if err != nil {
  392. g.raiseError(err)
  393. reply, _ := vm.ToValue(false)
  394. return reply
  395. }
  396. reply, _ := vm.ToValue(rawsize)
  397. return reply
  398. })
  399. //fileExists("user:/Desktop/test.txt") => return true / false
  400. vm.Set("_filelib_fileExists", func(call otto.FunctionCall) otto.Value {
  401. vpath, err := call.Argument(0).ToString()
  402. if err != nil {
  403. g.raiseError(err)
  404. reply, _ := vm.ToValue(false)
  405. return reply
  406. }
  407. //Check for permission
  408. if !u.CanRead(vpath) {
  409. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  410. }
  411. //Translate the virtual path to realpath
  412. rpath, err := virtualPathToRealPath(vpath, u)
  413. if err != nil {
  414. g.raiseError(err)
  415. reply, _ := vm.ToValue(false)
  416. return reply
  417. }
  418. if fileExists(rpath) {
  419. reply, _ := vm.ToValue(true)
  420. return reply
  421. } else {
  422. reply, _ := vm.ToValue(false)
  423. return reply
  424. }
  425. })
  426. //fileExists("user:/Desktop/test.txt") => return true / false
  427. vm.Set("_filelib_isDir", func(call otto.FunctionCall) otto.Value {
  428. vpath, err := call.Argument(0).ToString()
  429. if err != nil {
  430. g.raiseError(err)
  431. reply, _ := vm.ToValue(false)
  432. return reply
  433. }
  434. //Check for permission
  435. if !u.CanRead(vpath) {
  436. panic(vm.MakeCustomError("PermissionDenied", "Path access denied: "+vpath))
  437. }
  438. //Translate the virtual path to realpath
  439. rpath, err := virtualPathToRealPath(vpath, u)
  440. if err != nil {
  441. g.raiseError(err)
  442. reply, _ := vm.ToValue(false)
  443. return reply
  444. }
  445. if _, err := os.Stat(rpath); os.IsNotExist(err) {
  446. //File not exists
  447. panic(vm.MakeCustomError("File Not Exists", "Required path not exists"))
  448. }
  449. if IsDir(rpath) {
  450. reply, _ := vm.ToValue(true)
  451. return reply
  452. } else {
  453. reply, _ := vm.ToValue(false)
  454. return reply
  455. }
  456. })
  457. //Make directory command
  458. vm.Set("_filelib_mkdir", func(call otto.FunctionCall) otto.Value {
  459. vdir, err := call.Argument(0).ToString()
  460. if err != nil {
  461. return otto.FalseValue()
  462. }
  463. //Check for permission
  464. if !u.CanWrite(vdir) {
  465. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  466. }
  467. //Translate the path to realpath
  468. rdir, err := virtualPathToRealPath(vdir, u)
  469. if err != nil {
  470. log.Println(err.Error())
  471. return otto.FalseValue()
  472. }
  473. //Create the directory at rdir location
  474. err = os.MkdirAll(rdir, 0755)
  475. if err != nil {
  476. log.Println(err.Error())
  477. return otto.FalseValue()
  478. }
  479. return otto.TrueValue()
  480. })
  481. //Get MD5 of the given filepath, not implemented
  482. vm.Set("_filelib_md5", func(call otto.FunctionCall) otto.Value {
  483. log.Println("Call to MD5 Functions!")
  484. return otto.FalseValue()
  485. })
  486. //Get the root name of the given virtual path root
  487. vm.Set("_filelib_rname", func(call otto.FunctionCall) otto.Value {
  488. //Get virtual path from the function input
  489. vpath, err := call.Argument(0).ToString()
  490. if err != nil {
  491. g.raiseError(err)
  492. return otto.FalseValue()
  493. }
  494. //Get fs handler from the vpath
  495. fsHandler, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  496. if err != nil {
  497. g.raiseError(err)
  498. return otto.FalseValue()
  499. }
  500. //Return the name of the fsHandler
  501. name, _ := vm.ToValue(fsHandler.Name)
  502. return name
  503. })
  504. vm.Set("_filelib_mtime", func(call otto.FunctionCall) otto.Value {
  505. vpath, err := call.Argument(0).ToString()
  506. if err != nil {
  507. g.raiseError(err)
  508. reply, _ := vm.ToValue(false)
  509. return reply
  510. }
  511. //Check for permission
  512. if !u.CanRead(vpath) {
  513. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  514. }
  515. parseToUnix, err := call.Argument(1).ToBoolean()
  516. if err != nil {
  517. parseToUnix = false
  518. }
  519. rpath, err := virtualPathToRealPath(vpath, u)
  520. if err != nil {
  521. log.Println(err.Error())
  522. return otto.FalseValue()
  523. }
  524. info, err := os.Stat(rpath)
  525. if err != nil {
  526. log.Println(err.Error())
  527. return otto.FalseValue()
  528. }
  529. modTime := info.ModTime()
  530. if parseToUnix {
  531. result, _ := otto.ToValue(modTime.Unix())
  532. return result
  533. } else {
  534. result, _ := otto.ToValue(modTime.Format("2006-01-02 15:04:05"))
  535. return result
  536. }
  537. })
  538. /*
  539. vm.Set("_filelib_decodeURI", func(call otto.FunctionCall) otto.Value {
  540. originalURI, err := call.Argument(0).ToString()
  541. if err != nil {
  542. g.raiseError(err)
  543. reply, _ := vm.ToValue(false)
  544. return reply
  545. }
  546. decodedURI := specialURIDecode(originalURI)
  547. result, err := otto.ToValue(decodedURI)
  548. if err != nil {
  549. g.raiseError(err)
  550. reply, _ := vm.ToValue(false)
  551. return reply
  552. }
  553. return result
  554. })
  555. */
  556. //Other file operations, wip
  557. //Wrap all the native code function into an imagelib class
  558. vm.Run(`
  559. var filelib = {};
  560. filelib.writeFile = _filelib_writeFile;
  561. filelib.readFile = _filelib_readFile;
  562. filelib.deleteFile = _filelib_deleteFile;
  563. filelib.readdir = _filelib_readdir;
  564. filelib.walk = _filelib_walk;
  565. filelib.glob = _filelib_glob;
  566. filelib.aglob = _filelib_aglob;
  567. filelib.filesize = _filelib_filesize;
  568. filelib.fileExists = _filelib_fileExists;
  569. filelib.isDir = _filelib_isDir;
  570. filelib.md5 = _filelib_md5;
  571. filelib.mkdir = _filelib_mkdir;
  572. filelib.mtime = _filelib_mtime;
  573. filelib.rootName = _filelib_rname;
  574. `)
  575. }