agi.file.go 16 KB

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