installer.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. package modules
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "time"
  12. "github.com/go-git/go-git/v5"
  13. uuid "github.com/satori/go.uuid"
  14. agi "imuslab.com/arozos/mod/agi"
  15. fs "imuslab.com/arozos/mod/filesystem"
  16. "imuslab.com/arozos/mod/info/logger"
  17. "imuslab.com/arozos/mod/utils"
  18. )
  19. /*
  20. Module Installer
  21. author: tobychui
  22. This script handle the installation of modules in the arozos system
  23. */
  24. // Install a module via selecting a zip file
  25. func (m *ModuleHandler) InstallViaZip(realpath string, gateway *agi.Gateway) error {
  26. //Check if file exists
  27. if !utils.FileExists(realpath) {
  28. return errors.New("*Module Installer* Installer file not found. Given: " + realpath)
  29. }
  30. //Unzip to a temporary folder; always clean it up when we're done
  31. unzipTmpFolder := "./tmp/installer/" + strconv.Itoa(int(time.Now().Unix()))
  32. err := fs.Unzip(realpath, unzipTmpFolder)
  33. if err != nil {
  34. return err
  35. }
  36. defer os.RemoveAll(unzipTmpFolder)
  37. //Find sub-folders that contain init.agi – those are valid module folders
  38. files, _ := filepath.Glob(unzipTmpFolder + "/*")
  39. folders := []string{}
  40. for _, file := range files {
  41. if utils.IsDir(file) && utils.FileExists(filepath.Join(file, "init.agi")) {
  42. folders = append(folders, file)
  43. }
  44. }
  45. if len(folders) == 0 {
  46. return errors.New("*Module Installer* No valid module found in zip (no sub-folder containing init.agi)")
  47. }
  48. //Move each valid module folder into the web root
  49. installedFolders := []string{}
  50. for _, folder := range folders {
  51. destPath := filepath.Join("./web", filepath.Base(folder))
  52. //Remove any existing installation first (supports updating)
  53. if utils.FileExists(destPath) {
  54. os.RemoveAll(destPath)
  55. }
  56. if err := os.Rename(folder, destPath); err != nil {
  57. logger.PrintAndLog("Modules", fmt.Sprint("*Module Installer* Failed to move module:", err), nil)
  58. return errors.New("Failed to install " + filepath.Base(folder) + ": " + err.Error())
  59. }
  60. installedFolders = append(installedFolders, destPath)
  61. }
  62. //Activate each installed module and refresh the sorted list
  63. for _, folder := range installedFolders {
  64. m.ActivateModuleByRoot(folder, gateway)
  65. }
  66. m.ModuleSortList()
  67. return nil
  68. }
  69. // Reload all modules from agi file again
  70. func (m *ModuleHandler) ReloadAllModules(gateway *agi.Gateway) error {
  71. //Clear the current registered module list
  72. newModuleList := []*ModuleInfo{}
  73. for _, thisModule := range m.LoadedModule {
  74. if !thisModule.allowReload {
  75. //This module is registered by system. Do not allow reload
  76. newModuleList = append(newModuleList, thisModule)
  77. }
  78. }
  79. m.LoadedModule = newModuleList
  80. //Reload all webapp init.agi gateway script from source
  81. gateway.InitiateAllWebAppModules()
  82. m.ModuleSortList()
  83. return nil
  84. }
  85. // Install a module via git clone
  86. func (m *ModuleHandler) InstallModuleViaGit(gitURL string, gateway *agi.Gateway) error {
  87. //Download the module from the gitURL
  88. logger.PrintAndLog("Modules", fmt.Sprint("Starting module installation by Git cloning ", gitURL), nil)
  89. newDownloadUUID := uuid.NewV4().String()
  90. downloadFolder := filepath.Join(m.tmpDirectory, "download", newDownloadUUID)
  91. os.MkdirAll(downloadFolder, 0777)
  92. _, err := git.PlainClone(downloadFolder, false, &git.CloneOptions{
  93. URL: gitURL,
  94. Progress: os.Stdout,
  95. })
  96. if err != nil {
  97. return err
  98. }
  99. //Copy all folder within the download folder to the web root
  100. downloadedFiles, _ := filepath.Glob(downloadFolder + "/*")
  101. copyPendingList := []string{}
  102. for _, file := range downloadedFiles {
  103. if utils.IsDir(file) {
  104. //Exclude two special folder: github and images
  105. if filepath.Base(file) == ".github" || filepath.Base(file) == "images" || filepath.Base(file)[:1] == "." {
  106. //Reserved folder for putting Github readme screenshots or other things
  107. continue
  108. }
  109. //This file object is a folder. Copy to webroot
  110. copyPendingList = append(copyPendingList, file)
  111. }
  112. }
  113. //Do the copying
  114. //WIP
  115. /*
  116. for _, src := range copyPendingList {
  117. fs.FileCopy(src, "./web/", "skip", func(progress int, filename string) {
  118. logger.PrintAndLog("Modules", fmt.Sprint("Copying ", filename), nil)
  119. })
  120. }
  121. */
  122. //Clean up the download folder
  123. os.RemoveAll(downloadFolder)
  124. //Add the newly installed module to module list
  125. for _, moduleFolder := range copyPendingList {
  126. //This module folder has been moved to web successfully.
  127. m.ActivateModuleByRoot(moduleFolder, gateway)
  128. }
  129. //Sort the module lsit
  130. m.ModuleSortList()
  131. return nil
  132. }
  133. func (m *ModuleHandler) ActivateModuleByRoot(moduleFolder string, gateway *agi.Gateway) error {
  134. //Check if there is init.agi. If yes, load it as an module
  135. thisModuleEstimataedRoot := filepath.Join("./web/", filepath.Base(moduleFolder))
  136. if utils.FileExists(thisModuleEstimataedRoot) {
  137. if utils.FileExists(filepath.Join(thisModuleEstimataedRoot, "init.agi")) {
  138. //Load this as an module
  139. startDef, err := os.ReadFile(filepath.Join(thisModuleEstimataedRoot, "init.agi"))
  140. if err != nil {
  141. logger.PrintAndLog("Modules", "*Module Activator* Failed to read init.agi from "+filepath.Base(moduleFolder), nil)
  142. return errors.New("Failed to read init.agi from " + filepath.Base(moduleFolder))
  143. }
  144. //Execute the init script using AGI
  145. logger.PrintAndLog("Modules", fmt.Sprint("Starting module: ", filepath.Base(moduleFolder)), nil)
  146. err = gateway.RunScript(string(startDef))
  147. if err != nil {
  148. logger.PrintAndLog("Modules", "*Module Activator* "+filepath.Base(moduleFolder)+" Starting failed"+err.Error(), nil)
  149. return errors.New(filepath.Base(moduleFolder) + " Starting failed: " + err.Error())
  150. }
  151. }
  152. }
  153. return nil
  154. }
  155. // Handle and return the information of the current installed modules
  156. func (m *ModuleHandler) HandleModuleInstallationListing(w http.ResponseWriter, r *http.Request) {
  157. type ModuleInstallInfo struct {
  158. Name string // Name of the module
  159. Desc string // Description of module
  160. Group string // Group of the module
  161. Version string // Version of the module
  162. IconPath string // The icon access path of the module
  163. InstallDate string // The last editing date of the module folder
  164. InitAGIDate string // Last modification date of init.agi specifically
  165. InstallDir string // Path on disk (forward-slash, relative to server root)
  166. DiskSpace int64 // Disk space used
  167. Uninstallable bool // Indicate if this can be uninstalled
  168. }
  169. results := []ModuleInstallInfo{}
  170. for _, mod := range m.LoadedModule {
  171. if mod.StartDir == "" {
  172. continue
  173. }
  174. if !utils.FileExists(filepath.Join("./web", mod.StartDir)) {
  175. continue
  176. }
  177. dirPath := filepath.Join("./web", filepath.Dir(mod.StartDir))
  178. totalsize, _ := fs.GetDirctorySize(dirPath, false)
  179. // Folder mod time (kept for backward compat)
  180. mtime, err := fs.GetModTime(dirPath)
  181. if err != nil {
  182. logger.PrintAndLog("Modules", fmt.Sprint(err), nil)
  183. }
  184. t := time.Unix(mtime, 0)
  185. // init.agi mod time (more precise install/update date)
  186. agiDate := ""
  187. agiPath := filepath.Join(dirPath, "init.agi")
  188. if utils.FileExists(agiPath) {
  189. if agiInfo, statErr := os.Stat(agiPath); statErr == nil {
  190. agiDate = agiInfo.ModTime().Format("2006-01-02")
  191. }
  192. }
  193. canUninstall := true
  194. if mod.Name == "System Setting" || mod.Group == "System Tools" {
  195. canUninstall = false
  196. }
  197. results = append(results, ModuleInstallInfo{
  198. Name: mod.Name,
  199. Desc: mod.Desc,
  200. Group: mod.Group,
  201. Version: mod.Version,
  202. IconPath: mod.IconPath,
  203. InstallDate: t.Format("2006-01-02"),
  204. InitAGIDate: agiDate,
  205. InstallDir: filepath.ToSlash(dirPath),
  206. DiskSpace: totalsize,
  207. Uninstallable: canUninstall,
  208. })
  209. }
  210. js, _ := json.Marshal(results)
  211. utils.SendJSONResponse(w, string(js))
  212. }
  213. // Uninstall the given module
  214. func (m *ModuleHandler) UninstallModule(moduleName string) error {
  215. //Check if this module is allowed to be removed
  216. var targetModuleInfo *ModuleInfo = nil
  217. for _, mod := range m.LoadedModule {
  218. if mod.Name == moduleName {
  219. targetModuleInfo = mod
  220. break
  221. }
  222. }
  223. if targetModuleInfo.Group == "System Tools" || targetModuleInfo.Name == "System Setting" {
  224. //Reject Remove Operation
  225. return errors.New("Protected modules cannot be removed")
  226. }
  227. //Check if the module exists
  228. if utils.FileExists(filepath.Join("./web", moduleName)) {
  229. //Remove the module
  230. logger.PrintAndLog("Modules", fmt.Sprint("Removing Module: ", moduleName), nil)
  231. os.RemoveAll(filepath.Join("./web", moduleName))
  232. //Unregister the module from loaded list
  233. newLoadedModuleList := []*ModuleInfo{}
  234. for _, thisModule := range m.LoadedModule {
  235. if thisModule.Name != moduleName {
  236. newLoadedModuleList = append(newLoadedModuleList, thisModule)
  237. }
  238. }
  239. m.LoadedModule = newLoadedModuleList
  240. // Fire the uninstall hook so subsystems can clean up (e.g. remove cron jobs)
  241. if m.OnModuleUninstall != nil {
  242. m.OnModuleUninstall(moduleName)
  243. }
  244. } else {
  245. return errors.New("Module not exists")
  246. }
  247. return nil
  248. }
  249. // HandleUploadAndInstall accepts a multipart-uploaded zip file and installs it.
  250. // The file must be submitted in the "zipfile" field.
  251. func (m *ModuleHandler) HandleUploadAndInstall(w http.ResponseWriter, r *http.Request, gateway *agi.Gateway) {
  252. if err := r.ParseMultipartForm(64 << 20); err != nil {
  253. utils.SendErrorResponse(w, "Failed to parse upload: "+err.Error())
  254. return
  255. }
  256. file, header, err := r.FormFile("zipfile")
  257. if err != nil {
  258. utils.SendErrorResponse(w, "No zip file provided")
  259. return
  260. }
  261. defer file.Close()
  262. if filepath.Ext(header.Filename) != ".zip" {
  263. utils.SendErrorResponse(w, "Only .zip files are accepted")
  264. return
  265. }
  266. // Save to a temporary path
  267. tmpDir := filepath.Join(m.tmpDirectory, "installer")
  268. if err := os.MkdirAll(tmpDir, 0755); err != nil {
  269. utils.SendErrorResponse(w, "Failed to create temp directory")
  270. return
  271. }
  272. tmpPath := filepath.Join(tmpDir, strconv.FormatInt(time.Now().UnixNano(), 10)+"_upload.zip")
  273. out, err := os.Create(tmpPath)
  274. if err != nil {
  275. utils.SendErrorResponse(w, "Failed to create temp file: "+err.Error())
  276. return
  277. }
  278. if _, err = io.Copy(out, file); err != nil {
  279. out.Close()
  280. os.Remove(tmpPath)
  281. utils.SendErrorResponse(w, "Failed to write upload: "+err.Error())
  282. return
  283. }
  284. out.Close()
  285. // Install and clean up regardless of outcome
  286. installErr := m.InstallViaZip(tmpPath, gateway)
  287. os.Remove(tmpPath)
  288. if installErr != nil {
  289. utils.SendErrorResponse(w, "Installation failed: "+installErr.Error())
  290. return
  291. }
  292. utils.SendOK(w)
  293. }