desktop.go 21 KB

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