diff --git a/channel/channel_file.go b/channel/channel_file.go index f793a70..41ba5df 100644 --- a/channel/channel_file.go +++ b/channel/channel_file.go @@ -44,9 +44,12 @@ func (ch *Channel) Cleanup() error { if ch.File == nil { return nil } + filename := ch.File.Name() + defer func() { ch.Filesize = 0 ch.Duration = 0 + ch.File = nil }() // Sync the file to ensure data is written to disk @@ -58,13 +61,15 @@ func (ch *Channel) Cleanup() error { } // Delete the empty file - if ch.Filesize <= 0 { - if err := os.Remove(ch.File.Name()); err != nil { + fileInfo, err := os.Stat(filename) + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("stat file delete zero file: %w", err) + } + if fileInfo != nil && fileInfo.Size() == 0 { + if err := os.Remove(filename); err != nil { return fmt.Errorf("remove zero file: %w", err) } } - - ch.File = nil return nil } diff --git a/channel/channel_record.go b/channel/channel_record.go index 95c0e54..849bfde 100644 --- a/channel/channel_record.go +++ b/channel/channel_record.go @@ -54,13 +54,14 @@ func (ch *Channel) Monitor() { } } - if err != nil { - if !errors.Is(err, context.Canceled) { - ch.Error("record stream: %s", err.Error()) - } - if err := ch.Cleanup(); err != nil { - ch.Error("cleanup canceled channel: %s", err.Error()) - } + // Always cleanup when monitor exits, regardless of error + if err := ch.Cleanup(); err != nil { + ch.Error("cleanup on monitor exit: %s", err.Error()) + } + + // Log error if it's not a context cancellation + if err != nil && !errors.Is(err, context.Canceled) { + ch.Error("record stream: %s", err.Error()) } } @@ -85,6 +86,13 @@ func (ch *Channel) RecordStream(ctx context.Context, client *chaturbate.Client) return fmt.Errorf("next file: %w", err) } + // Ensure file is cleaned up when this function exits in any case + defer func() { + if err := ch.Cleanup(); err != nil { + ch.Error("cleanup on record stream exit: %s", err.Error()) + } + }() + playlist, err := stream.GetPlaylist(ctx, ch.Config.Resolution, ch.Config.Framerate) if err != nil { return fmt.Errorf("get playlist: %w", err)