-
-
Notifications
You must be signed in to change notification settings - Fork 113
feat: Add import and export functionality in surge #362
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
junaid2005p
wants to merge
11
commits into
main
Choose a base branch
from
export
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
7a48b37
feat(backup): add portable backup bundle for import/export
junaid2005p a85900f
feat: add local and remote trasfer services
junaid2005p 481ec6b
feat(cli): add import and export commands with transfer API routes
junaid2005p 9c81e4c
feat: wire transfer services into local and remote startup flows
junaid2005p 8710d43
feat(tui): add tui data transfer flow for import and export
junaid2005p 650d8b6
fix: Fixed path issue
junaid2005p 5a33e02
fix: fixed sessionId issue
junaid2005p 6b4eeef
fix(tui): minor lint issue fix
junaid2005p e9b3aab
feat: remaining components wired in
junaid2005p 27fd129
fix: backup components
junaid2005p 71b7995
fix: fixed COdeQL issues
junaid2005p File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
|
|
||
| "github.com/SurgeDM/Surge/internal/backup" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| var exportCmd = &cobra.Command{ | ||
| Use: "export <file>", | ||
| Short: "Export Surge data to a bundle", | ||
| Args: cobra.ExactArgs(1), | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| if err := initializeGlobalState(); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| includeLogs, _ := cmd.Flags().GetBool("include-logs") | ||
| includePartials, _ := cmd.Flags().GetBool("include-partials") | ||
| leavePaused, _ := cmd.Flags().GetBool("leave-paused") | ||
| jsonOutput, _ := cmd.Flags().GetBool("json") | ||
|
|
||
| transfer, _, err := resolveTransferService() | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| manifest, err := exportBundle(context.Background(), transfer, args[0], backup.ExportOptions{ | ||
| IncludeLogs: includeLogs, | ||
| IncludePartials: includePartials, | ||
| LeavePaused: leavePaused, | ||
| }) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if jsonOutput { | ||
| return printJSON(manifest) | ||
| } | ||
| fmt.Printf("Exported bundle to %s\n", ensureExportPath(args[0])) | ||
| return nil | ||
| }, | ||
| } | ||
|
|
||
| func init() { | ||
| rootCmd.AddCommand(exportCmd) | ||
| exportCmd.Flags().Bool("include-logs", false, "Include Surge log files in the export bundle") | ||
| exportCmd.Flags().Bool("include-partials", false, "Include paused .surge partial files for resumable restore") | ||
| exportCmd.Flags().Bool("leave-paused", false, "Leave downloads paused after export") | ||
| exportCmd.Flags().Bool("json", false, "Output manifest as JSON") | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| "github.com/SurgeDM/Surge/internal/backup" | ||
| "github.com/spf13/cobra" | ||
| ) | ||
|
|
||
| var importCmd = &cobra.Command{ | ||
| Use: "import <file>", | ||
| Short: "Preview or import a Surge bundle", | ||
| Args: cobra.ExactArgs(1), | ||
| RunE: func(cmd *cobra.Command, args []string) error { | ||
| if err := initializeGlobalState(); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| apply, _ := cmd.Flags().GetBool("apply") | ||
| replace, _ := cmd.Flags().GetBool("replace") | ||
| rootDir, _ := cmd.Flags().GetString("root") | ||
| jsonOutput, _ := cmd.Flags().GetBool("json") | ||
|
|
||
| transfer, isRemote, err := resolveTransferService() | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| previewOpts := backup.ImportOptions{ | ||
| RootDir: rootDir, | ||
| Replace: replace, | ||
| } | ||
| preview, err := previewBundle(context.Background(), transfer, args[0], previewOpts) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if !apply { | ||
| if jsonOutput { | ||
| return printJSON(preview) | ||
| } | ||
| printImportPreview(preview) | ||
| return nil | ||
| } | ||
|
|
||
| opts := previewOpts | ||
| if isRemote { | ||
| opts.SessionID = preview.SessionID | ||
| } | ||
| result, err := applyBundle(context.Background(), transfer, args[0], opts) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if jsonOutput { | ||
| return printJSON(result) | ||
| } | ||
| printImportResult(result) | ||
| return nil | ||
| }, | ||
| } | ||
|
|
||
| func init() { | ||
| rootCmd.AddCommand(importCmd) | ||
| importCmd.Flags().Bool("apply", false, "Apply the import after preview succeeds") | ||
| importCmd.Flags().Bool("replace", false, "Replace existing Surge state instead of merging") | ||
| importCmd.Flags().String("root", "", "Root directory for rebased imported paths") | ||
| importCmd.Flags().Bool("json", false, "Output preview/result as JSON") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| package cmd | ||
|
|
||
| import ( | ||
| "context" | ||
| "crypto/rand" | ||
| "encoding/hex" | ||
| "encoding/json" | ||
| "io" | ||
| "net/http" | ||
| "net/url" | ||
| "os" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/SurgeDM/Surge/internal/backup" | ||
| "github.com/SurgeDM/Surge/internal/core" | ||
| ) | ||
|
|
||
| var maxImportPreviewSize int64 = 512 * 1024 * 1024 | ||
|
|
||
| type stagedImportSession struct { | ||
| Path string | ||
| CreatedAt time.Time | ||
| } | ||
|
|
||
| var importSessionStore = struct { | ||
| mu sync.Mutex | ||
| items map[string]stagedImportSession | ||
| }{ | ||
| items: make(map[string]stagedImportSession), | ||
| } | ||
|
|
||
| func cleanupImportSessions() { | ||
| cutoff := time.Now().Add(-1 * time.Hour) | ||
| importSessionStore.mu.Lock() | ||
| defer importSessionStore.mu.Unlock() | ||
| for id, session := range importSessionStore.items { | ||
| if session.CreatedAt.After(cutoff) { | ||
| continue | ||
| } | ||
| _ = os.Remove(session.Path) | ||
| delete(importSessionStore.items, id) | ||
| } | ||
| } | ||
|
|
||
| func newImportSessionID() (string, error) { | ||
| token := make([]byte, 16) | ||
| if _, err := rand.Read(token); err != nil { | ||
| return "", err | ||
| } | ||
| return hex.EncodeToString(token), nil | ||
| } | ||
|
|
||
| func registerTransferRoutes(mux *http.ServeMux, service core.DownloadService) { | ||
| mux.HandleFunc("/data/export", requireMethod(http.MethodPost, func(w http.ResponseWriter, r *http.Request) { | ||
| cleanupImportSessions() | ||
| var opts backup.ExportOptions | ||
| if r.Body != nil { | ||
| if err := json.NewDecoder(r.Body).Decode(&opts); err != nil && err != io.EOF { | ||
| http.Error(w, "invalid export request", http.StatusBadRequest) | ||
| return | ||
| } | ||
| } | ||
|
|
||
| transfer := core.NewLocalTransferService(service, Version) | ||
| tmpFile, err := os.CreateTemp("", "surge-export-*.zip") | ||
| if err != nil { | ||
| http.Error(w, err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
| defer func() { | ||
| _ = tmpFile.Close() | ||
| _ = os.Remove(tmpFile.Name()) | ||
| }() | ||
|
|
||
| manifest, err := transfer.Export(r.Context(), opts, tmpFile) | ||
| if err != nil { | ||
| http.Error(w, err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
| if _, err := tmpFile.Seek(0, 0); err != nil { | ||
| http.Error(w, err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| manifestBytes, _ := json.Marshal(manifest) | ||
| w.Header().Set("Content-Type", "application/octet-stream") | ||
| w.Header().Set("Content-Disposition", "attachment; filename=\"surge-export.surge-export\"") | ||
| w.Header().Set("X-Surge-Manifest", url.QueryEscape(string(manifestBytes))) | ||
| if _, err := io.Copy(w, tmpFile); err != nil { | ||
| return | ||
| } | ||
| })) | ||
|
|
||
| mux.HandleFunc("/data/import/preview", requireMethod(http.MethodPost, func(w http.ResponseWriter, r *http.Request) { | ||
| cleanupImportSessions() | ||
| opts := backup.ImportOptions{ | ||
| RootDir: strings.TrimSpace(r.URL.Query().Get("root_dir")), | ||
| Replace: strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("replace")), "true"), | ||
| } | ||
| tmpFile, err := os.CreateTemp("", "surge-import-preview-*.zip") | ||
| if err != nil { | ||
| http.Error(w, err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
| defer func() { _ = tmpFile.Close() }() | ||
| r.Body = http.MaxBytesReader(w, r.Body, maxImportPreviewSize) | ||
| if _, err := io.Copy(tmpFile, r.Body); err != nil { | ||
| _ = os.Remove(tmpFile.Name()) | ||
| http.Error(w, err.Error(), http.StatusBadRequest) | ||
| return | ||
| } | ||
| if _, err := tmpFile.Seek(0, 0); err != nil { | ||
| _ = os.Remove(tmpFile.Name()) | ||
| http.Error(w, err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| transfer := core.NewLocalTransferService(service, Version) | ||
| preview, err := transfer.PreviewImport(context.Background(), tmpFile, opts) | ||
| if err != nil { | ||
| _ = os.Remove(tmpFile.Name()) | ||
| http.Error(w, err.Error(), http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| sessionID, err := newImportSessionID() | ||
| if err != nil { | ||
| _ = os.Remove(tmpFile.Name()) | ||
| http.Error(w, err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
| importSessionStore.mu.Lock() | ||
| importSessionStore.items[sessionID] = stagedImportSession{ | ||
| Path: tmpFile.Name(), | ||
| CreatedAt: time.Now(), | ||
| } | ||
| importSessionStore.mu.Unlock() | ||
|
|
||
| preview.SessionID = sessionID | ||
| writeJSONResponse(w, http.StatusOK, preview) | ||
| })) | ||
|
|
||
| mux.HandleFunc("/data/import/apply", requireMethod(http.MethodPost, func(w http.ResponseWriter, r *http.Request) { | ||
| cleanupImportSessions() | ||
| var req struct { | ||
| SessionID string `json:"session_id"` | ||
| RootDir string `json:"root_dir"` | ||
| Replace bool `json:"replace"` | ||
| } | ||
| if err := decodeJSONBody(r, &req); err != nil { | ||
| http.Error(w, "invalid request body", http.StatusBadRequest) | ||
| return | ||
| } | ||
| if strings.TrimSpace(req.SessionID) == "" { | ||
| http.Error(w, "missing session_id", http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| importSessionStore.mu.Lock() | ||
| session, ok := importSessionStore.items[req.SessionID] | ||
| if ok { | ||
| delete(importSessionStore.items, req.SessionID) | ||
| } | ||
| importSessionStore.mu.Unlock() | ||
| if !ok { | ||
| http.Error(w, "import session not found", http.StatusNotFound) | ||
| return | ||
| } | ||
| defer func() { _ = os.Remove(session.Path) }() | ||
|
|
||
| file, err := os.Open(session.Path) | ||
| if err != nil { | ||
| http.Error(w, err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
| defer func() { _ = file.Close() }() | ||
|
|
||
| transfer := core.NewLocalTransferService(service, Version) | ||
| result, err := transfer.ApplyImport(r.Context(), file, backup.ImportOptions{ | ||
| RootDir: req.RootDir, | ||
| Replace: req.Replace, | ||
| }) | ||
| if err != nil { | ||
| http.Error(w, err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
| writeJSONResponse(w, http.StatusOK, result) | ||
| })) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.