110 lines
2.4 KiB
Go
110 lines
2.4 KiB
Go
package subscribers
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
|
|
"backend/app/events"
|
|
"backend/app/events/publishers"
|
|
"backend/app/http/posts"
|
|
"backend/app/jobs"
|
|
"backend/database/fields"
|
|
"backend/providers/job"
|
|
|
|
"git.ipao.vip/rogeecn/atom/contracts"
|
|
"github.com/ThreeDotsLabs/watermill/message"
|
|
"github.com/pkg/errors"
|
|
"github.com/samber/lo"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
var _ contracts.EventHandler = (*PostCreated)(nil)
|
|
|
|
// @provider(event)
|
|
type PostCreated struct {
|
|
log *logrus.Entry `inject:"false"`
|
|
|
|
postSvc *posts.Service
|
|
job *job.Job
|
|
}
|
|
|
|
func (e *PostCreated) Prepare() error {
|
|
e.log = logrus.WithField("module", "events.subscribers.post_created")
|
|
return nil
|
|
}
|
|
|
|
// PublishToTopic implements contracts.EventHandler.
|
|
func (e *PostCreated) PublishToTopic() string {
|
|
return events.TopicProcessed
|
|
}
|
|
|
|
// Topic implements contracts.EventHandler.
|
|
func (e *PostCreated) Topic() string {
|
|
return events.TopicPostCreated
|
|
}
|
|
|
|
// Handler implements contracts.EventHandler.
|
|
func (e *PostCreated) Handler(msg *message.Message) ([]*message.Message, error) {
|
|
var payload publishers.PostCreated
|
|
err := json.Unmarshal(msg.Payload, &payload)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
e.log.Infof("received event %s", msg.Payload)
|
|
|
|
post, err := e.postSvc.GetPostByID(context.Background(), payload.ID)
|
|
if err != nil {
|
|
return nil, errors.Wrapf(err, "failed to get user by id: %d", payload.ID)
|
|
}
|
|
|
|
video, ok := lo.Find(post.Assets.Data, func(asset fields.MediaAsset) bool {
|
|
return asset.Type == fields.MediaAssetTypeVideo
|
|
})
|
|
|
|
if !ok {
|
|
e.log.Warnf("post %d %s has no video asset", post.ID, post.Title)
|
|
return nil, nil
|
|
}
|
|
|
|
job, err := e.job.Client()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// cut video
|
|
_, err = job.Insert(context.Background(), jobs.PostVideoCutJob{
|
|
PostID: post.ID,
|
|
MediaID: video.Media,
|
|
TenantID: post.TenantID,
|
|
UserID: post.UserID,
|
|
}, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// extract audio
|
|
_, err = job.Insert(context.Background(), jobs.PostVideoExtractAudioJob{
|
|
PostID: post.ID,
|
|
MediaID: video.Media,
|
|
TenantID: post.TenantID,
|
|
UserID: post.UserID,
|
|
Mark: "audio-preview",
|
|
}, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
_, err = job.Insert(context.Background(), jobs.PostVideoExtractAudioJob{
|
|
PostID: post.ID,
|
|
MediaID: video.Media,
|
|
TenantID: post.TenantID,
|
|
UserID: post.UserID,
|
|
Mark: "audio",
|
|
}, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return nil, nil
|
|
}
|