Paperclip/pkg/internal/services/merger.go

61 lines
1.3 KiB
Go
Raw Normal View History

2024-08-20 09:08:40 +00:00
package services
import (
"fmt"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/database"
"git.solsynth.dev/hydrogen/paperclip/pkg/internal/models"
jsoniter "github.com/json-iterator/go"
"github.com/spf13/viper"
"io"
"os"
"path/filepath"
)
func MergeFileChunks(meta models.Attachment, arrange []string) (models.Attachment, error) {
destMap := viper.GetStringMap("destinations.temporary")
var dest models.LocalDestination
rawDest, _ := jsoniter.Marshal(destMap)
_ = jsoniter.Unmarshal(rawDest, &dest)
destPath := filepath.Join(dest.Path, meta.Uuid)
destFile, err := os.Create(destPath)
if err != nil {
return meta, err
}
defer destFile.Close()
2024-08-20 14:55:58 +00:00
// Merge files
2024-08-20 09:08:40 +00:00
for _, chunk := range arrange {
chunkPath := filepath.Join(dest.Path, fmt.Sprintf("%s.%s", meta.Uuid, chunk))
chunkFile, err := os.Open(chunkPath)
if err != nil {
return meta, err
}
_, err = io.Copy(destFile, chunkFile)
if err != nil {
_ = chunkFile.Close()
return meta, err
}
_ = chunkFile.Close()
}
2024-08-20 14:55:58 +00:00
// Do post-upload tasks
2024-08-20 09:08:40 +00:00
meta.IsUploaded = true
meta.FileChunks = nil
2024-08-20 09:08:40 +00:00
database.C.Save(&meta)
CacheAttachment(meta)
2024-08-20 11:17:43 +00:00
PublishAnalyzeTask(meta)
2024-08-20 14:55:58 +00:00
// Clean up
for _, chunk := range arrange {
chunkPath := filepath.Join(dest.Path, fmt.Sprintf("%s.%s", meta.Uuid, chunk))
_ = os.Remove(chunkPath)
}
2024-08-20 09:08:40 +00:00
return meta, nil
}