desktop.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "imuslab.com/arozos/mod/common"
  13. fs "imuslab.com/arozos/mod/filesystem"
  14. "imuslab.com/arozos/mod/filesystem/arozfs"
  15. "imuslab.com/arozos/mod/filesystem/shortcut"
  16. module "imuslab.com/arozos/mod/modules"
  17. prout "imuslab.com/arozos/mod/prouter"
  18. )
  19. //Desktop script initiation
  20. func DesktopInit() {
  21. systemWideLogger.PrintAndLog("Desktop", "Starting Desktop Services", nil)
  22. router := prout.NewModuleRouter(prout.RouterOption{
  23. ModuleName: "Desktop",
  24. AdminOnly: false,
  25. UserHandler: userHandler,
  26. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  27. common.SendErrorResponse(w, "Permission Denied")
  28. },
  29. })
  30. //Register all the required API
  31. router.HandleFunc("/system/desktop/listDesktop", desktop_listFiles)
  32. router.HandleFunc("/system/desktop/theme", desktop_theme_handler)
  33. router.HandleFunc("/system/desktop/files", desktop_fileLocation_handler)
  34. router.HandleFunc("/system/desktop/host", desktop_hostdetailHandler)
  35. router.HandleFunc("/system/desktop/user", desktop_handleUserInfo)
  36. router.HandleFunc("/system/desktop/preference", desktop_preference_handler)
  37. router.HandleFunc("/system/desktop/createShortcut", desktop_shortcutHandler)
  38. //API related to desktop based operations
  39. router.HandleFunc("/system/desktop/opr/renameShortcut", desktop_handleShortcutRename)
  40. //Initialize desktop database
  41. err := sysdb.NewTable("desktop")
  42. if err != nil {
  43. log.Println("Unable to create database table for Desktop. Please validation your installation.")
  44. log.Fatal(err)
  45. os.Exit(1)
  46. }
  47. //Register Desktop Module
  48. moduleHandler.RegisterModule(module.ModuleInfo{
  49. Name: "Desktop",
  50. Desc: "The Web Desktop experience for everyone",
  51. Group: "Interface Module",
  52. IconPath: "img/desktop/desktop.png",
  53. Version: internal_version,
  54. StartDir: "",
  55. SupportFW: false,
  56. LaunchFWDir: "",
  57. SupportEmb: false,
  58. })
  59. }
  60. /*
  61. FUNCTIONS RELATED TO PARSING DESKTOP FILE ICONS
  62. The functions in this section handle file listing and its icon locations.
  63. */
  64. func desktop_initUserFolderStructure(username string) {
  65. //Call to filesystem for creating user file struture at root dir
  66. userinfo, _ := userHandler.GetUserInfoFromUsername(username)
  67. homedir, err := userinfo.GetHomeDirectory()
  68. if err != nil {
  69. systemWideLogger.PrintAndLog("Desktop", "Unable to initiate user desktop folder", err)
  70. return
  71. }
  72. if !fs.FileExists(filepath.Join(homedir, "Desktop")) {
  73. //Desktop directory not exists. Create one and copy a template desktop
  74. os.MkdirAll(homedir+"Desktop", 0755)
  75. templateFolder := "./system/desktop/template/"
  76. if fs.FileExists(templateFolder) {
  77. templateFiles, _ := filepath.Glob(templateFolder + "*")
  78. for _, tfile := range templateFiles {
  79. input, _ := ioutil.ReadFile(tfile)
  80. ioutil.WriteFile(homedir+"Desktop/"+filepath.Base(tfile), input, 0755)
  81. }
  82. }
  83. }
  84. }
  85. //Return the information about the host
  86. func desktop_hostdetailHandler(w http.ResponseWriter, r *http.Request) {
  87. type returnStruct struct {
  88. Hostname string
  89. DeviceUUID string
  90. BuildVersion string
  91. InternalVersion string
  92. DeviceVendor string
  93. DeviceModel string
  94. VendorIcon string
  95. }
  96. jsonString, _ := json.Marshal(returnStruct{
  97. Hostname: *host_name,
  98. DeviceUUID: deviceUUID,
  99. BuildVersion: build_version,
  100. InternalVersion: internal_version,
  101. DeviceVendor: deviceVendor,
  102. DeviceModel: deviceModel,
  103. VendorIcon: iconVendor,
  104. })
  105. common.SendJSONResponse(w, string(jsonString))
  106. }
  107. func desktop_handleShortcutRename(w http.ResponseWriter, r *http.Request) {
  108. //Check if the user directory already exists
  109. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  110. if err != nil {
  111. common.SendErrorResponse(w, "User not logged in")
  112. return
  113. }
  114. //Get the shortcut file that is renaming
  115. target, err := common.Mv(r, "src", false)
  116. if err != nil {
  117. common.SendErrorResponse(w, "Invalid shortcut file path given")
  118. return
  119. }
  120. //Get the new name
  121. new, err := common.Mv(r, "new", false)
  122. if err != nil {
  123. common.SendErrorResponse(w, "Invalid new name given")
  124. return
  125. }
  126. fsh, subpath, _ := GetFSHandlerSubpathFromVpath(target)
  127. fshAbs := fsh.FileSystemAbstraction
  128. //Check if the file actually exists and it is on desktop
  129. rpath, err := fshAbs.VirtualPathToRealPath(subpath, userinfo.Username)
  130. if err != nil {
  131. common.SendErrorResponse(w, err.Error())
  132. return
  133. }
  134. if target[:14] != "user:/Desktop/" {
  135. common.SendErrorResponse(w, "Shortcut not on desktop")
  136. return
  137. }
  138. if !fshAbs.FileExists(rpath) {
  139. common.SendErrorResponse(w, "File not exists")
  140. return
  141. }
  142. //OK. Change the name of the shortcut
  143. originalShortcut, err := fshAbs.ReadFile(rpath)
  144. if err != nil {
  145. common.SendErrorResponse(w, "Shortcut file read failed")
  146. return
  147. }
  148. lines := strings.Split(string(originalShortcut), "\n")
  149. if len(lines) < 4 {
  150. //Invalid shortcut properties
  151. common.SendErrorResponse(w, "Invalid shortcut file")
  152. return
  153. }
  154. //Change the 2nd line to the new name
  155. lines[1] = new
  156. newShortcutContent := strings.Join(lines, "\n")
  157. err = fshAbs.WriteFile(rpath, []byte(newShortcutContent), 0755)
  158. if err != nil {
  159. common.SendErrorResponse(w, err.Error())
  160. return
  161. }
  162. common.SendOK(w)
  163. }
  164. func desktop_listFiles(w http.ResponseWriter, r *http.Request) {
  165. //Check if the user directory already exists
  166. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  167. username := userinfo.Username
  168. //Initiate the user folder structure. Do nothing if the structure already exists.
  169. desktop_initUserFolderStructure(username)
  170. //List all files inside the user desktop directory
  171. fsh, subpath, err := GetFSHandlerSubpathFromVpath("user:/Desktop/")
  172. if err != nil {
  173. common.SendErrorResponse(w, "Desktop file load failed")
  174. return
  175. }
  176. fshAbs := fsh.FileSystemAbstraction
  177. userDesktopRealpath, _ := fshAbs.VirtualPathToRealPath(subpath, userinfo.Username)
  178. files, err := fshAbs.Glob(userDesktopRealpath + "/*")
  179. if err != nil {
  180. common.SendErrorResponse(w, "Desktop file load failed")
  181. return
  182. }
  183. //Desktop object structure
  184. type desktopObject struct {
  185. Filepath string
  186. Filename string
  187. Ext string
  188. IsDir bool
  189. IsEmptyDir bool
  190. IsShortcut bool
  191. IsShared bool
  192. ShortcutImage string
  193. ShortcutType string
  194. ShortcutName string
  195. ShortcutPath string
  196. IconX int
  197. IconY int
  198. }
  199. var desktopFiles []desktopObject
  200. for _, this := range files {
  201. //Always use linux convension for directory seperator
  202. if filepath.Base(this)[:1] == "." {
  203. //Skipping hidden files
  204. continue
  205. }
  206. this = filepath.ToSlash(this)
  207. thisFileObject := new(desktopObject)
  208. thisFileObject.Filepath, _ = fshAbs.RealPathToVirtualPath(this, userinfo.Username)
  209. thisFileObject.Filename = filepath.Base(this)
  210. thisFileObject.Ext = filepath.Ext(this)
  211. thisFileObject.IsDir = fshAbs.IsDir(this)
  212. if thisFileObject.IsDir {
  213. //Check if this dir is empty
  214. filesInFolder, _ := fshAbs.Glob(filepath.ToSlash(filepath.Clean(this)) + "/*")
  215. fc := 0
  216. for _, f := range filesInFolder {
  217. if filepath.Base(f)[:1] != "." {
  218. fc++
  219. }
  220. }
  221. if fc > 0 {
  222. thisFileObject.IsEmptyDir = false
  223. } else {
  224. thisFileObject.IsEmptyDir = true
  225. }
  226. } else {
  227. //File object. Default true
  228. thisFileObject.IsEmptyDir = true
  229. }
  230. //Check if the file is a shortcut
  231. isShortcut := false
  232. if filepath.Ext(this) == ".shortcut" {
  233. isShortcut = true
  234. shortcutInfo, _ := fshAbs.ReadFile(this)
  235. infoSegments := strings.Split(strings.ReplaceAll(string(shortcutInfo), "\r\n", "\n"), "\n")
  236. if len(infoSegments) < 4 {
  237. thisFileObject.ShortcutType = "invalid"
  238. } else {
  239. thisFileObject.ShortcutType = infoSegments[0]
  240. thisFileObject.ShortcutName = infoSegments[1]
  241. thisFileObject.ShortcutPath = infoSegments[2]
  242. thisFileObject.ShortcutImage = infoSegments[3]
  243. }
  244. }
  245. thisFileObject.IsShortcut = isShortcut
  246. //Check if this file is shared
  247. thisFileObject.IsShared = shareManager.FileIsShared(userinfo, this)
  248. //Check the file location
  249. username, _ := authAgent.GetUserName(w, r)
  250. x, y, _ := getDesktopLocatioFromPath(thisFileObject.Filename, username)
  251. //This file already have a location on desktop
  252. thisFileObject.IconX = x
  253. thisFileObject.IconY = y
  254. desktopFiles = append(desktopFiles, *thisFileObject)
  255. }
  256. //Convert the struct to json string
  257. jsonString, _ := json.Marshal(desktopFiles)
  258. common.SendJSONResponse(w, string(jsonString))
  259. }
  260. //functions to handle desktop icon locations. Location is directly written into the center db.
  261. func getDesktopLocatioFromPath(filename string, username string) (int, int, error) {
  262. //As path include username, there is no different if there are username in the key
  263. locationdata := ""
  264. err := sysdb.Read("desktop", username+"/filelocation/"+filename, &locationdata)
  265. if err != nil {
  266. //The file location is not set. Return error
  267. return -1, -1, errors.New("This file do not have a location registry")
  268. }
  269. type iconLocation struct {
  270. X int
  271. Y int
  272. }
  273. thisFileLocation := iconLocation{
  274. X: -1,
  275. Y: -1,
  276. }
  277. //Start parsing the from the json data
  278. json.Unmarshal([]byte(locationdata), &thisFileLocation)
  279. return thisFileLocation.X, thisFileLocation.Y, nil
  280. }
  281. //Set the icon location of a given filepath
  282. func setDesktopLocationFromPath(filename string, username string, x int, y int) error {
  283. //You cannot directly set path of others people's deskop. Hence, fullpath needed to be parsed from auth username
  284. userinfo, _ := userHandler.GetUserInfoFromUsername(username)
  285. fsh, subpath, _ := GetFSHandlerSubpathFromVpath("user:/Desktop/")
  286. fshAbs := fsh.FileSystemAbstraction
  287. desktoppath, _ := fshAbs.VirtualPathToRealPath(subpath, userinfo.Username)
  288. path := filepath.Join(desktoppath, filename)
  289. type iconLocation struct {
  290. X int
  291. Y int
  292. }
  293. newLocation := new(iconLocation)
  294. newLocation.X = x
  295. newLocation.Y = y
  296. //Check if the file exits
  297. if !fshAbs.FileExists(path) {
  298. return errors.New("Given filename not exists.")
  299. }
  300. //Parse the location to json
  301. jsonstring, err := json.Marshal(newLocation)
  302. if err != nil {
  303. log.Println("[Desktop] Unable to parse new file location on desktop for file: " + path)
  304. return err
  305. }
  306. //systemWideLogger.PrintAndLog(key,string(jsonstring),nil)
  307. //Write result to database
  308. sysdb.Write("desktop", username+"/filelocation/"+filename, string(jsonstring))
  309. return nil
  310. }
  311. func delDesktopLocationFromPath(filename string, username string) {
  312. //Delete a file icon location from db
  313. sysdb.Delete("desktop", username+"/filelocation/"+filename)
  314. }
  315. //Return the user information to the client
  316. func desktop_handleUserInfo(w http.ResponseWriter, r *http.Request) {
  317. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  318. if err != nil {
  319. common.SendErrorResponse(w, err.Error())
  320. return
  321. }
  322. type returnStruct struct {
  323. Username string
  324. UserIcon string
  325. UserGroups []string
  326. IsAdmin bool
  327. StorageQuotaTotal int64
  328. StorageQuotaLeft int64
  329. }
  330. //Calculate the storage quota left
  331. remainingQuota := userinfo.StorageQuota.TotalStorageQuota - userinfo.StorageQuota.UsedStorageQuota
  332. if userinfo.StorageQuota.TotalStorageQuota == -1 {
  333. remainingQuota = -1
  334. }
  335. //Get the list of user permission group names
  336. pgs := []string{}
  337. for _, pg := range userinfo.GetUserPermissionGroup() {
  338. pgs = append(pgs, pg.Name)
  339. }
  340. jsonString, _ := json.Marshal(returnStruct{
  341. Username: userinfo.Username,
  342. UserIcon: userinfo.GetUserIcon(),
  343. IsAdmin: userinfo.IsAdmin(),
  344. UserGroups: pgs,
  345. StorageQuotaTotal: userinfo.StorageQuota.GetUserStorageQuota(),
  346. StorageQuotaLeft: remainingQuota,
  347. })
  348. common.SendJSONResponse(w, string(jsonString))
  349. }
  350. //Icon handling function for web endpoint
  351. func desktop_fileLocation_handler(w http.ResponseWriter, r *http.Request) {
  352. get, _ := common.Mv(r, "get", true) //Check if there are get request for a given filepath
  353. set, _ := common.Mv(r, "set", true) //Check if there are any set request for a given filepath
  354. del, _ := common.Mv(r, "del", true) //Delete the given filename coordinate
  355. if set != "" {
  356. //Set location with given paramter
  357. x := 0
  358. y := 0
  359. sx, _ := common.Mv(r, "x", true)
  360. sy, _ := common.Mv(r, "y", true)
  361. path := set
  362. x, err := strconv.Atoi(sx)
  363. if err != nil {
  364. x = 0
  365. }
  366. y, err = strconv.Atoi(sy)
  367. if err != nil {
  368. y = 0
  369. }
  370. //Set location of icon from path
  371. username, _ := authAgent.GetUserName(w, r)
  372. err = setDesktopLocationFromPath(path, username, x, y)
  373. if err != nil {
  374. common.SendErrorResponse(w, err.Error())
  375. return
  376. }
  377. common.SendJSONResponse(w, string("\"OK\""))
  378. } else if get != "" {
  379. username, _ := authAgent.GetUserName(w, r)
  380. x, y, _ := getDesktopLocatioFromPath(get, username)
  381. result := []int{x, y}
  382. json_string, _ := json.Marshal(result)
  383. common.SendJSONResponse(w, string(json_string))
  384. } else if del != "" {
  385. username, _ := authAgent.GetUserName(w, r)
  386. delDesktopLocationFromPath(del, username)
  387. } else {
  388. //No argument has been set
  389. common.SendJSONResponse(w, "Paramter missing.")
  390. }
  391. }
  392. //////////////////////////////// END OF DESKTOP FILE ICON HANDLER ///////////////////////////////////////////////////
  393. func desktop_theme_handler(w http.ResponseWriter, r *http.Request) {
  394. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  395. if err != nil {
  396. common.SendErrorResponse(w, "User not logged in")
  397. return
  398. }
  399. username := userinfo.Username
  400. //Check if the set GET paramter is set.
  401. targetTheme, _ := common.Mv(r, "set", false)
  402. getUserTheme, _ := common.Mv(r, "get", false)
  403. loadUserTheme, _ := common.Mv(r, "load", false)
  404. if targetTheme == "" && getUserTheme == "" && loadUserTheme == "" {
  405. //List all the currnet themes in the list
  406. themes, err := filepath.Glob("web/img/desktop/bg/*")
  407. if err != nil {
  408. log.Println("[Desktop] Unable to search bg from destkop image root. Are you sure the web data folder exists?")
  409. return
  410. }
  411. //Prase the results to json array
  412. //Tips: You must use captial letter for varable in struct that is accessable as public :)
  413. type desktopTheme struct {
  414. Theme string
  415. Bglist []string
  416. }
  417. var desktopThemeList []desktopTheme
  418. acceptBGFormats := []string{
  419. ".jpg",
  420. ".png",
  421. ".gif",
  422. }
  423. for _, file := range themes {
  424. if fs.IsDir(file) {
  425. thisTheme := new(desktopTheme)
  426. thisTheme.Theme = filepath.Base(file)
  427. bglist, _ := filepath.Glob(file + "/*")
  428. var thisbglist []string
  429. for _, bg := range bglist {
  430. ext := filepath.Ext(bg)
  431. //if (sliceutil.Contains(acceptBGFormats, ext) ){
  432. if common.StringInArray(acceptBGFormats, ext) {
  433. //This file extension is supported
  434. thisbglist = append(thisbglist, filepath.Base(bg))
  435. }
  436. }
  437. thisTheme.Bglist = thisbglist
  438. desktopThemeList = append(desktopThemeList, *thisTheme)
  439. }
  440. }
  441. //Return the results as JSON string
  442. jsonString, err := json.Marshal(desktopThemeList)
  443. if err != nil {
  444. log.Println("[Desktop] Marshal desktop wallpaper list error: " + err.Error())
  445. common.SendJSONResponse(w, string("[]"))
  446. return
  447. }
  448. common.SendJSONResponse(w, string(jsonString))
  449. return
  450. } else if getUserTheme == "true" {
  451. //Get the user's theme from database
  452. result := ""
  453. sysdb.Read("desktop", username+"/theme", &result)
  454. if result == "" {
  455. //This user has not set a theme yet. Use default
  456. common.SendJSONResponse(w, string("\"default\""))
  457. return
  458. } else {
  459. //This user already set a theme. Use its set theme
  460. common.SendJSONResponse(w, string("\""+result+"\""))
  461. return
  462. }
  463. } else if loadUserTheme != "" {
  464. //Load user theme base on folder path
  465. userFsh, err := GetFsHandlerByUUID("user:/")
  466. if err != nil {
  467. common.SendErrorResponse(w, "Unable to resolve user root path")
  468. return
  469. }
  470. userFshAbs := userFsh.FileSystemAbstraction
  471. rpath, err := userFshAbs.VirtualPathToRealPath(loadUserTheme, userinfo.Username)
  472. if err != nil {
  473. common.SendErrorResponse(w, "Custom folder load failed")
  474. return
  475. }
  476. //Check if the folder exists
  477. if !userFshAbs.FileExists(rpath) {
  478. common.SendErrorResponse(w, "Custom folder load failed")
  479. return
  480. }
  481. if userinfo.CanRead(loadUserTheme) == false {
  482. //No read permission
  483. common.SendErrorResponse(w, "Permission denied")
  484. return
  485. }
  486. //Scan for jpg, gif or png
  487. imageList := []string{}
  488. scanPath := filepath.ToSlash(filepath.Clean(rpath)) + "/"
  489. pngFiles, _ := filepath.Glob(scanPath + "*.png")
  490. jpgFiles, _ := filepath.Glob(scanPath + "*.jpg")
  491. gifFiles, _ := filepath.Glob(scanPath + "*.gif")
  492. //Merge all 3 slice into one image list
  493. imageList = append(imageList, pngFiles...)
  494. imageList = append(imageList, jpgFiles...)
  495. imageList = append(imageList, gifFiles...)
  496. //Convert the image list back to vpaths
  497. virtualImageList := []string{}
  498. for _, image := range imageList {
  499. vpath, err := userFshAbs.RealPathToVirtualPath(image, userinfo.Username)
  500. if err != nil {
  501. continue
  502. }
  503. virtualImageList = append(virtualImageList, vpath)
  504. }
  505. js, _ := json.Marshal(virtualImageList)
  506. common.SendJSONResponse(w, string(js))
  507. } else if targetTheme != "" {
  508. //Set the current user theme
  509. sysdb.Write("desktop", username+"/theme", targetTheme)
  510. common.SendJSONResponse(w, "\"OK\"")
  511. return
  512. }
  513. }
  514. func desktop_preference_handler(w http.ResponseWriter, r *http.Request) {
  515. preferenceType, _ := common.Mv(r, "preference", true)
  516. value, _ := common.Mv(r, "value", true)
  517. remove, _ := common.Mv(r, "remove", true)
  518. username, err := authAgent.GetUserName(w, r)
  519. if err != nil {
  520. //user not logged in. Redirect to login page.
  521. common.SendErrorResponse(w, "User not logged in")
  522. return
  523. }
  524. if preferenceType == "" && value == "" {
  525. //Invalid options. Return error reply.
  526. common.SendErrorResponse(w, "Error. Undefined paramter.")
  527. return
  528. } else if preferenceType != "" && value == "" && remove == "" {
  529. //Getting config from the key.
  530. result := ""
  531. sysdb.Read("desktop", username+"/preference/"+preferenceType, &result)
  532. jsonString, _ := json.Marshal(result)
  533. common.SendJSONResponse(w, string(jsonString))
  534. return
  535. } else if preferenceType != "" && value == "" && remove == "true" {
  536. //Remove mode
  537. sysdb.Delete("desktop", username+"/preference/"+preferenceType)
  538. common.SendOK(w)
  539. return
  540. } else if preferenceType != "" && value != "" {
  541. //Setting config from the key
  542. sysdb.Write("desktop", username+"/preference/"+preferenceType, value)
  543. common.SendOK(w)
  544. return
  545. } else {
  546. common.SendErrorResponse(w, "Error. Undefined paramter.")
  547. return
  548. }
  549. }
  550. func desktop_shortcutHandler(w http.ResponseWriter, r *http.Request) {
  551. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  552. if err != nil {
  553. //user not logged in. Redirect to login page.
  554. common.SendErrorResponse(w, "User not logged in")
  555. return
  556. }
  557. shortcutType, err := common.Mv(r, "stype", true)
  558. if err != nil {
  559. common.SendErrorResponse(w, err.Error())
  560. return
  561. }
  562. shortcutText, err := common.Mv(r, "stext", true)
  563. if err != nil {
  564. common.SendErrorResponse(w, err.Error())
  565. return
  566. }
  567. shortcutPath, err := common.Mv(r, "spath", true)
  568. if err != nil {
  569. common.SendErrorResponse(w, err.Error())
  570. return
  571. }
  572. shortcutIcon, err := common.Mv(r, "sicon", true)
  573. if err != nil {
  574. common.SendErrorResponse(w, err.Error())
  575. return
  576. }
  577. shortcutCreationDest, err := common.Mv(r, "sdest", true)
  578. if err != nil {
  579. //Default create on desktop
  580. shortcutCreationDest = "user:/Desktop/"
  581. }
  582. if !userinfo.CanWrite(shortcutCreationDest) {
  583. common.SendErrorResponse(w, "Permission denied")
  584. return
  585. }
  586. //Resolve vpath to fsh and subpath
  587. fsh, subpath, err := GetFSHandlerSubpathFromVpath(shortcutCreationDest)
  588. if err != nil {
  589. common.SendErrorResponse(w, err.Error())
  590. return
  591. }
  592. fshAbs := fsh.FileSystemAbstraction
  593. shorcutRealDest, err := fshAbs.VirtualPathToRealPath(subpath, userinfo.Username)
  594. if err != nil {
  595. common.SendErrorResponse(w, err.Error())
  596. return
  597. }
  598. //Filter illegal characters in the shortcut filename
  599. shortcutText = arozfs.FilterIllegalCharInFilename(shortcutText, " ")
  600. //If dest not exists, create it
  601. if !fshAbs.FileExists(shorcutRealDest) {
  602. fshAbs.MkdirAll(shorcutRealDest, 0755)
  603. }
  604. //Generate a filename for the shortcut
  605. shortcutFilename := shorcutRealDest + "/" + shortcutText + ".shortcut"
  606. counter := 1
  607. for fshAbs.FileExists(shortcutFilename) {
  608. shortcutFilename = shorcutRealDest + "/" + shortcutText + "(" + strconv.Itoa(counter) + ")" + ".shortcut"
  609. counter++
  610. }
  611. //Write the shortcut to file
  612. shortcutContent := shortcut.GenerateShortcutBytes(shortcutPath, shortcutType, shortcutText, shortcutIcon)
  613. err = fshAbs.WriteFile(shortcutFilename, shortcutContent, 0775)
  614. if err != nil {
  615. common.SendErrorResponse(w, err.Error())
  616. return
  617. }
  618. common.SendOK(w)
  619. }