Skip to content

Commit

Permalink
Feature: use alternative file extension name when the downloading is …
Browse files Browse the repository at this point in the history
…not completed.
  • Loading branch information
keuin committed Sep 11, 2022
1 parent 6bbb50f commit 32fbadf
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 8 deletions.
7 changes: 7 additions & 0 deletions common/filename.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package common

import "fmt"

func CombineFileName(base string, ext string) string {
return fmt.Sprintf("%s.%s", base, ext)
}
5 changes: 3 additions & 2 deletions recording/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ type TransportConfig struct {
}

type DownloadConfig struct {
SaveDirectory string `mapstructure:"save_directory"`
DiskWriteBufferBytes int `mapstructure:"disk_write_buffer_bytes"`
SaveDirectory string `mapstructure:"save_directory"`
DiskWriteBufferBytes int `mapstructure:"disk_write_buffer_bytes"`
UseSpecialExtNameBeforeFinishing bool `mapstructure:"use_special_ext_name_when_downloading"`
}

type WatchConfig struct {
Expand Down
38 changes: 32 additions & 6 deletions recording/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type TaskResult struct {
}

const kReadChunkSize = 128 * 1024
const kSpecialExtName = "partial"

// runTaskWithAutoRestart
// start a monitor&download task.
Expand Down Expand Up @@ -193,12 +194,37 @@ func record(
}
streamSource := urlInfo.Data.URLs[0]

fileName := fmt.Sprintf(
"%s.%s",
GenerateFileName(profile.Data.Title, time.Now()),
common.Errorable[string](common.GetFileExtensionFromUrl(streamSource.URL)).OrElse("flv"),
)
filePath := path.Join(task.Download.SaveDirectory, fileName)
var extName string

// the real extension name (without renaming)
originalExtName := common.Errorable[string](common.GetFileExtensionFromUrl(streamSource.URL)).OrElse("flv")

if task.TaskConfig.Download.UseSpecialExtNameBeforeFinishing {
extName = kSpecialExtName
} else {
extName = originalExtName
}

baseName := GenerateFileName(profile.Data.Title, time.Now())
fileName := common.CombineFileName(baseName, extName)
saveDir := task.Download.SaveDirectory
filePath := path.Join(saveDir, fileName)

// rename the extension name to originalExtName when finish writing
defer func() {
if extName == originalExtName {
return
}
from := filePath
to := path.Join(saveDir, common.CombineFileName(baseName, originalExtName))
err := os.Rename(from, to)
if err != nil {
task.logger.Error("Cannot rename %v to %v: %v", from, to, err)
return
}
task.logger.Info("Rename file \"%s\" to \"%s\".", from, to)
}()

file, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
task.logger.Error("Cannot open file for writing: %v", err)
Expand Down

0 comments on commit 32fbadf

Please sign in to comment.