agi.file.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. rootDirs = append(rootDirs, fsh.UUID+":/")
  241. }
  242. reply, _ := vm.ToValue(rootDirs)
  243. return reply
  244. } else {
  245. //Check for permission
  246. if !u.CanRead(regex) {
  247. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  248. }
  249. //This function can only handle wildcard in filename but not in dir name
  250. vrootPath := filepath.Dir(regex)
  251. regexFilename := filepath.Base(regex)
  252. //Rewrite and validate the sort mode
  253. if userSortMode == "user" {
  254. //Use user sorting mode.
  255. if g.Option.UserHandler.GetDatabase().KeyExists("fs-sortpref", u.Username+"/"+filepath.ToSlash(vrootPath)) {
  256. g.Option.UserHandler.GetDatabase().Read("fs-sortpref", u.Username+"/"+filepath.ToSlash(vrootPath), &userSortMode)
  257. } else {
  258. userSortMode = "default"
  259. }
  260. }
  261. if !fssort.SortModeIsSupported(userSortMode) {
  262. log.Println("[AGI] Sort mode: " + userSortMode + " not supported. Using default")
  263. userSortMode = "default"
  264. }
  265. //Translate the virtual path to realpath
  266. rrootPath, err := virtualPathToRealPath(vrootPath, u)
  267. if err != nil {
  268. g.raiseError(err)
  269. reply, _ := vm.ToValue(false)
  270. return reply
  271. }
  272. suitableFiles, err := filepath.Glob(filepath.Join(rrootPath, regexFilename))
  273. if err != nil {
  274. g.raiseError(err)
  275. reply, _ := vm.ToValue(false)
  276. return reply
  277. }
  278. //Sort the files
  279. newFilelist := fssort.SortFileList(suitableFiles, userSortMode)
  280. //Return the results in virtual paths
  281. results := []string{}
  282. for _, file := range newFilelist {
  283. thisRpath, _ := realpathToVirtualpath(filepath.ToSlash(file), u)
  284. results = append(results, thisRpath)
  285. }
  286. reply, _ := vm.ToValue(results)
  287. return reply
  288. }
  289. })
  290. //Advance Glob using file system special Glob, cannot use to scan root dirs
  291. vm.Set("_filelib_aglob", func(call otto.FunctionCall) otto.Value {
  292. regex, err := call.Argument(0).ToString()
  293. if err != nil {
  294. g.raiseError(err)
  295. reply, _ := vm.ToValue(false)
  296. return reply
  297. }
  298. userSortMode, err := call.Argument(1).ToString()
  299. if err != nil || userSortMode == "" || userSortMode == "undefined" {
  300. userSortMode = "default"
  301. }
  302. if regex != "/" && !u.CanRead(regex) {
  303. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  304. }
  305. //This function can only handle wildcard in filename but not in dir name
  306. vrootPath := filepath.Dir(regex)
  307. regexFilename := filepath.Base(regex)
  308. //Rewrite and validate the sort mode
  309. if userSortMode == "user" {
  310. //Use user sorting mode.
  311. if g.Option.UserHandler.GetDatabase().KeyExists("fs-sortpref", u.Username+"/"+filepath.ToSlash(vrootPath)) {
  312. g.Option.UserHandler.GetDatabase().Read("fs-sortpref", u.Username+"/"+filepath.ToSlash(vrootPath), &userSortMode)
  313. } else {
  314. userSortMode = "default"
  315. }
  316. }
  317. if !fssort.SortModeIsSupported(userSortMode) {
  318. log.Println("[AGI] Sort mode: " + userSortMode + " not supported. Using default")
  319. userSortMode = "default"
  320. }
  321. //Translate the virtual path to realpath
  322. rrootPath, err := virtualPathToRealPath(vrootPath, u)
  323. if err != nil {
  324. g.raiseError(err)
  325. reply, _ := vm.ToValue(false)
  326. return reply
  327. }
  328. suitableFiles, err := specialGlob(filepath.Join(rrootPath, regexFilename))
  329. if err != nil {
  330. g.raiseError(err)
  331. reply, _ := vm.ToValue(false)
  332. return reply
  333. }
  334. //Sort the files
  335. newFilelist := fssort.SortFileList(suitableFiles, userSortMode)
  336. //Parse the results (Only extract the filepath)
  337. results := []string{}
  338. for _, filename := range newFilelist {
  339. thisVpath, _ := u.RealPathToVirtualPath(filename)
  340. results = append(results, thisVpath)
  341. }
  342. reply, _ := vm.ToValue(results)
  343. return reply
  344. })
  345. //filesize("user:/Desktop/test.txt")
  346. vm.Set("_filelib_filesize", func(call otto.FunctionCall) otto.Value {
  347. vpath, err := call.Argument(0).ToString()
  348. if err != nil {
  349. g.raiseError(err)
  350. reply, _ := vm.ToValue(false)
  351. return reply
  352. }
  353. //Check for permission
  354. if !u.CanRead(vpath) {
  355. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  356. }
  357. //Translate the virtual path to realpath
  358. rpath, err := virtualPathToRealPath(vpath, u)
  359. if err != nil {
  360. g.raiseError(err)
  361. reply, _ := vm.ToValue(false)
  362. return reply
  363. }
  364. //Get filesize of file
  365. rawsize := fs.GetFileSize(rpath)
  366. if err != nil {
  367. g.raiseError(err)
  368. reply, _ := vm.ToValue(false)
  369. return reply
  370. }
  371. reply, _ := vm.ToValue(rawsize)
  372. return reply
  373. })
  374. //fileExists("user:/Desktop/test.txt") => return true / false
  375. vm.Set("_filelib_fileExists", func(call otto.FunctionCall) otto.Value {
  376. vpath, err := call.Argument(0).ToString()
  377. if err != nil {
  378. g.raiseError(err)
  379. reply, _ := vm.ToValue(false)
  380. return reply
  381. }
  382. //Check for permission
  383. if !u.CanRead(vpath) {
  384. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  385. }
  386. //Translate the virtual path to realpath
  387. rpath, err := virtualPathToRealPath(vpath, u)
  388. if err != nil {
  389. g.raiseError(err)
  390. reply, _ := vm.ToValue(false)
  391. return reply
  392. }
  393. if fileExists(rpath) {
  394. reply, _ := vm.ToValue(true)
  395. return reply
  396. } else {
  397. reply, _ := vm.ToValue(false)
  398. return reply
  399. }
  400. })
  401. //fileExists("user:/Desktop/test.txt") => return true / false
  402. vm.Set("_filelib_isDir", func(call otto.FunctionCall) otto.Value {
  403. vpath, err := call.Argument(0).ToString()
  404. if err != nil {
  405. g.raiseError(err)
  406. reply, _ := vm.ToValue(false)
  407. return reply
  408. }
  409. //Check for permission
  410. if !u.CanRead(vpath) {
  411. panic(vm.MakeCustomError("PermissionDenied", "Path access denied: "+vpath))
  412. }
  413. //Translate the virtual path to realpath
  414. rpath, err := virtualPathToRealPath(vpath, u)
  415. if err != nil {
  416. g.raiseError(err)
  417. reply, _ := vm.ToValue(false)
  418. return reply
  419. }
  420. if _, err := os.Stat(rpath); os.IsNotExist(err) {
  421. //File not exists
  422. panic(vm.MakeCustomError("File Not Exists", "Required path not exists"))
  423. }
  424. if IsDir(rpath) {
  425. reply, _ := vm.ToValue(true)
  426. return reply
  427. } else {
  428. reply, _ := vm.ToValue(false)
  429. return reply
  430. }
  431. })
  432. //Make directory command
  433. vm.Set("_filelib_mkdir", func(call otto.FunctionCall) otto.Value {
  434. vdir, err := call.Argument(0).ToString()
  435. if err != nil {
  436. return otto.FalseValue()
  437. }
  438. //Check for permission
  439. if !u.CanWrite(vdir) {
  440. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  441. }
  442. //Translate the path to realpath
  443. rdir, err := virtualPathToRealPath(vdir, u)
  444. if err != nil {
  445. log.Println(err.Error())
  446. return otto.FalseValue()
  447. }
  448. //Create the directory at rdir location
  449. err = os.MkdirAll(rdir, 0755)
  450. if err != nil {
  451. log.Println(err.Error())
  452. return otto.FalseValue()
  453. }
  454. return otto.TrueValue()
  455. })
  456. //Get MD5 of the given filepath
  457. vm.Set("_filelib_md5", func(call otto.FunctionCall) otto.Value {
  458. log.Println("Call to MD5 Functions!")
  459. return otto.FalseValue()
  460. })
  461. //Get the root name of the given virtual path root
  462. vm.Set("_filelib_rname", func(call otto.FunctionCall) otto.Value {
  463. //Get virtual path from the function input
  464. vpath, err := call.Argument(0).ToString()
  465. if err != nil {
  466. g.raiseError(err)
  467. return otto.FalseValue()
  468. }
  469. //Get fs handler from the vpath
  470. fsHandler, err := u.GetFileSystemHandlerFromVirtualPath(vpath)
  471. if err != nil {
  472. g.raiseError(err)
  473. return otto.FalseValue()
  474. }
  475. //Return the name of the fsHandler
  476. name, _ := vm.ToValue(fsHandler.Name)
  477. return name
  478. })
  479. vm.Set("_filelib_mtime", func(call otto.FunctionCall) otto.Value {
  480. vpath, err := call.Argument(0).ToString()
  481. if err != nil {
  482. g.raiseError(err)
  483. reply, _ := vm.ToValue(false)
  484. return reply
  485. }
  486. //Check for permission
  487. if !u.CanRead(vpath) {
  488. panic(vm.MakeCustomError("PermissionDenied", "Path access denied"))
  489. }
  490. parseToUnix, err := call.Argument(1).ToBoolean()
  491. if err != nil {
  492. parseToUnix = false
  493. }
  494. rpath, err := virtualPathToRealPath(vpath, u)
  495. if err != nil {
  496. log.Println(err.Error())
  497. return otto.FalseValue()
  498. }
  499. info, err := os.Stat(rpath)
  500. if err != nil {
  501. log.Println(err.Error())
  502. return otto.FalseValue()
  503. }
  504. modTime := info.ModTime()
  505. if parseToUnix {
  506. result, _ := otto.ToValue(modTime.Unix())
  507. return result
  508. } else {
  509. result, _ := otto.ToValue(modTime.Format("2006-01-02 15:04:05"))
  510. return result
  511. }
  512. })
  513. /*
  514. vm.Set("_filelib_decodeURI", func(call otto.FunctionCall) otto.Value {
  515. originalURI, err := call.Argument(0).ToString()
  516. if err != nil {
  517. g.raiseError(err)
  518. reply, _ := vm.ToValue(false)
  519. return reply
  520. }
  521. decodedURI := specialURIDecode(originalURI)
  522. result, err := otto.ToValue(decodedURI)
  523. if err != nil {
  524. g.raiseError(err)
  525. reply, _ := vm.ToValue(false)
  526. return reply
  527. }
  528. return result
  529. })
  530. */
  531. //Other file operations, wip
  532. //Wrap all the native code function into an imagelib class
  533. vm.Run(`
  534. var filelib = {};
  535. filelib.writeFile = _filelib_writeFile;
  536. filelib.readFile = _filelib_readFile;
  537. filelib.deleteFile = _filelib_deleteFile;
  538. filelib.readdir = _filelib_readdir;
  539. filelib.walk = _filelib_walk;
  540. filelib.glob = _filelib_glob;
  541. filelib.aglob = _filelib_aglob;
  542. filelib.filesize = _filelib_filesize;
  543. filelib.fileExists = _filelib_fileExists;
  544. filelib.isDir = _filelib_isDir;
  545. filelib.md5 = _filelib_md5;
  546. filelib.mkdir = _filelib_mkdir;
  547. filelib.mtime = _filelib_mtime;
  548. filelib.rname = _filelib_rname;
  549. `)
  550. }