midr @ c430ebff167dcfc073c1c6a3375d6284936218a7

 1package controller
 2
 3import (
 4	"log"
 5	"net/http"
 6	"strconv"
 7	"strings"
 8	"time"
 9
10	"git.sr.ht/~gabrielgio/midr/db"
11	"git.sr.ht/~gabrielgio/midr/worker"
12	"github.com/gin-gonic/gin"
13)
14
15type Env struct {
16	Entries db.EntryModel
17	Worker  worker.Worker
18}
19
20func logBytes(logc <-chan []byte) {
21	for l := range logc {
22		logs := strings.TrimRight(string(l), "\t \n")
23		log.Println(logs)
24	}
25}
26
27func (e *Env) GetEntries(c *gin.Context) {
28	entries := e.Entries.All()
29	c.HTML(http.StatusOK, "index", entries)
30}
31
32func (e *Env) GetEntry(c *gin.Context) {
33	id := c.Param("id")
34	if id != "" {
35		entry := e.Entries.Find(id)
36		c.HTML(http.StatusOK, "entry", entry)
37	} else {
38		c.HTML(http.StatusOK, "entry", db.Entry{})
39	}
40}
41
42func (e *Env) UpdateEntry(c *gin.Context) {
43	var entry db.Entry
44	c.ShouldBind(&entry)
45	e.Entries.Update(entry)
46	c.Redirect(http.StatusFound, "/")
47}
48
49func (e *Env) CreateEntry(c *gin.Context) {
50	var entry db.Entry
51	c.ShouldBind(&entry)
52	e.Entries.Create(&entry)
53	log := e.Worker.RunYtDlpWorker(&entry)
54	go logBytes(log)
55
56	c.Redirect(http.StatusFound, "/")
57}
58
59func (e *Env) DeleteEntry(c *gin.Context) {
60	var entry db.Entry
61	id := c.Param("id")
62	e.Entries.Delete(id)
63	u64, _ := strconv.ParseUint(id, 10, 32)
64	e.Worker.RemoveJob(uint(u64))
65	c.HTML(http.StatusOK, "entry", entry)
66}
67
68func (e *Env) GetJobs(c *gin.Context) {
69	jobs := e.Worker.GetJobs()
70	c.JSON(http.StatusOK, jobs)
71}
72
73func (e *Env) StartScheduler() {
74	e.Worker.StartReader()
75	go func() {
76		for {
77			entries := e.Entries.All()
78
79			for _, entry := range entries {
80				log := e.Worker.RunYtDlpWorker(&entry)
81				if log != nil {
82					go logBytes(log)
83				}
84			}
85			time.Sleep(30 * time.Second)
86		}
87	}()
88}