api_rest_replay.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package api_rest
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. "github.com/bettercap/recording"
  7. "github.com/evilsocket/islazy/fs"
  8. )
  9. var (
  10. errNotReplaying = errors.New("not replaying")
  11. )
  12. func (mod *RestAPI) errAlreadyReplaying() error {
  13. return fmt.Errorf("the module is already replaying a session from %s", mod.recordFileName)
  14. }
  15. func (mod *RestAPI) startReplay(filename string) (err error) {
  16. if mod.replaying {
  17. return mod.errAlreadyReplaying()
  18. } else if mod.recording {
  19. return mod.errAlreadyRecording()
  20. } else if mod.recordFileName, err = fs.Expand(filename); err != nil {
  21. return err
  22. }
  23. mod.State.Store("load_progress", 0)
  24. defer func() {
  25. mod.State.Store("load_progress", 100.0)
  26. }()
  27. mod.loading = true
  28. defer func() {
  29. mod.loading = false
  30. }()
  31. mod.Info("loading %s ...", mod.recordFileName)
  32. start := time.Now()
  33. mod.record, err = recording.Load(mod.recordFileName, func(progress float64, done int, total int) {
  34. mod.State.Store("load_progress", progress)
  35. })
  36. if err != nil {
  37. return err
  38. }
  39. loadedIn := time.Since(start)
  40. // we need the api itself up and running
  41. if !mod.Running() {
  42. if err := mod.Start(); err != nil {
  43. return err
  44. }
  45. }
  46. mod.recStarted = mod.record.Session.StartedAt()
  47. mod.recStopped = mod.record.Session.StoppedAt()
  48. duration := mod.recStopped.Sub(mod.recStarted)
  49. mod.recTime = int(duration.Seconds())
  50. mod.replaying = true
  51. mod.recording = false
  52. mod.Info("loaded %s of recording (%d frames) started at %s in %s, started replaying ...",
  53. duration,
  54. mod.record.Session.Frames(),
  55. mod.recStarted,
  56. loadedIn)
  57. return nil
  58. }
  59. func (mod *RestAPI) stopReplay() error {
  60. if !mod.replaying {
  61. return errNotReplaying
  62. }
  63. mod.replaying = false
  64. mod.Info("stopped replaying from %s ...", mod.recordFileName)
  65. mod.recordFileName = ""
  66. return nil
  67. }