2024-04-25 20:22:05 +07:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
2024-04-29 21:45:18 +07:00
|
|
|
"time"
|
2024-04-25 20:22:05 +07:00
|
|
|
|
|
|
|
"github.com/aarondl/opt/omit"
|
|
|
|
"github.com/mattn/go-sqlite3"
|
|
|
|
"github.com/tigorlazuardi/redmage/models"
|
|
|
|
"github.com/tigorlazuardi/redmage/pkg/errs"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (api *API) SubredditsCreate(ctx context.Context, params *models.Subreddit) (subreddit *models.Subreddit, err error) {
|
|
|
|
ctx, span := tracer.Start(ctx, "*API.SubredditsCreate")
|
|
|
|
defer span.End()
|
|
|
|
|
2024-04-29 21:45:18 +07:00
|
|
|
now := time.Now()
|
2024-04-25 20:22:05 +07:00
|
|
|
set := &models.SubredditSetter{
|
2024-04-26 22:13:04 +07:00
|
|
|
Name: omit.From(params.Name),
|
|
|
|
EnableSchedule: omit.From(params.EnableSchedule),
|
|
|
|
Subtype: omit.From(params.Subtype),
|
|
|
|
Schedule: omit.From(params.Schedule),
|
|
|
|
Countback: omit.From(params.Countback),
|
2024-04-29 21:45:18 +07:00
|
|
|
CreatedAt: omit.From(now.Unix()),
|
|
|
|
UpdatedAt: omit.From(now.Unix()),
|
2024-04-25 20:22:05 +07:00
|
|
|
}
|
|
|
|
|
2024-05-23 13:49:37 +07:00
|
|
|
api.lockf(func() {
|
|
|
|
subreddit, err = models.Subreddits.Insert(ctx, api.db, set)
|
|
|
|
})
|
2024-04-25 20:22:05 +07:00
|
|
|
if err != nil {
|
|
|
|
var sqliteErr sqlite3.Error
|
|
|
|
if errors.As(err, &sqliteErr) {
|
|
|
|
if sqliteErr.Code == sqlite3.ErrConstraint {
|
|
|
|
return subreddit, errs.Wrapw(err, "subreddit with that name already exists", "set", set).Code(http.StatusConflict)
|
|
|
|
}
|
|
|
|
return subreddit, errs.Wrapw(err, "failed to create subreddit", "set", set)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-03 23:40:05 +07:00
|
|
|
_, err = api.ScheduleSet(ctx, ScheduleSetParams{
|
|
|
|
Subreddit: subreddit.Name,
|
|
|
|
Status: ScheduleStatus(params.EnableSchedule), // Possible value should only be 0 or 1
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return subreddit, errs.Wrapw(err, "failed to set schedule status")
|
|
|
|
}
|
|
|
|
|
2024-05-21 22:27:11 +07:00
|
|
|
if params.EnableSchedule == 1 {
|
|
|
|
_, err = api.scheduler.Put(subreddit.Name, subreddit.Schedule)
|
|
|
|
if err != nil {
|
|
|
|
return subreddit, errs.Wrapw(err, "failed to put job to scheduler")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-25 20:22:05 +07:00
|
|
|
return subreddit, nil
|
|
|
|
}
|