Parent directory

channels.go

2722 bytes
 1package ytrssil
 2
 3import (
 4	"errors"
 5	"net/http"
 6	"strconv"
 7
 8	"github.com/gin-gonic/gin"
 9
10	"github.com/TheEdgeOfRage/ytrssil-api/db"
11	"github.com/TheEdgeOfRage/ytrssil-api/feedparser"
12	"github.com/TheEdgeOfRage/ytrssil-api/handler"
13)
14
15func (srv *server) ListChannelsJSON(c *gin.Context) {
16	channels, err := srv.handler.ListChannels(c.Request.Context())
17	if err != nil {
18		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
19		return
20	}
21
22	c.JSON(http.StatusOK, gin.H{"channels": channels})
23}
24
25func (srv *server) SubscribeToChannelJSON(c *gin.Context) {
26	var request struct {
27		ChannelID string `json:"channel_id" binding:"required"`
28	}
29	if err := c.ShouldBindJSON(&request); err != nil {
30		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid channel request"})
31		return
32	}
33
34	channel, err := srv.handler.SubscribeToChannel(c.Request.Context(), request.ChannelID)
35	if err != nil {
36		if errors.Is(err, db.ErrAlreadySubscribed) {
37			c.AbortWithStatusJSON(http.StatusConflict, gin.H{"error": err.Error()})
38			return
39		}
40		if errors.Is(err, feedparser.ErrInvalidChannelID) || errors.Is(err, handler.ErrInvalidChannelURL) {
41			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
42			return
43		}
44
45		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
46		return
47	}
48
49	c.JSON(http.StatusOK, channel)
50}
51
52func (srv *server) UnsubscribeFromChannelJSON(c *gin.Context) {
53	err := srv.handler.UnsubscribeFromChannel(c.Request.Context(), c.Param("channel_id"))
54	if err != nil {
55		if errors.Is(err, db.ErrChannelNotFound) {
56			c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": err.Error()})
57			return
58		}
59
60		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
61		return
62	}
63
64	c.JSON(http.StatusOK, gin.H{"msg": "unsubscribed from channel successfully"})
65}
66
67func (srv *server) ToggleChannelShortsJSON(c *gin.Context) {
68	channelID := c.Param("channel_id")
69	enableValue, ok := c.GetQuery("enable")
70	if !ok {
71		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing enable query parameter"})
72		return
73	}
74
75	enable, err := strconv.ParseBool(enableValue)
76	if err != nil {
77		c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid enable query parameter"})
78		return
79	}
80
81	err = srv.handler.ToggleChannelShorts(c.Request.Context(), channelID, enable)
82	if err != nil {
83		if errors.Is(err, db.ErrChannelNotFound) {
84			c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": err.Error()})
85			return
86		}
87
88		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
89		return
90	}
91
92	c.JSON(http.StatusOK, gin.H{"msg": "shorts setting updated", "enable_shorts": enable})
93}