Skip to content

Commit

Permalink
add get videos + start working on sqlite watchdog
Browse files Browse the repository at this point in the history
  • Loading branch information
Skeeww committed Aug 30, 2024
1 parent 0f586e2 commit ba8df9c
Show file tree
Hide file tree
Showing 4 changed files with 187 additions and 16 deletions.
42 changes: 26 additions & 16 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
package main

import (
"os"
"fmt"

"enssat.tv/autovodsaver/storage"
"enssat.tv/autovodsaver/twitch"
"enssat.tv/autovodsaver/utils"
"github.com/rs/zerolog"
Expand All @@ -19,19 +18,30 @@ func main() {
logger := ctx.Value(utils.LoggerKey).(*zerolog.Logger)

logger.Info().Msg("AutoVODSaver (by EnssaTV)")
store, newS3Error := storage.NewS3StorageWithContext(ctx, "http://51.159.98.189:9000", "eu-west", "enssatv", storage.Credentials{
AccessKey: accessKey,
SecretKey: secretKey,
Session: "",
})
if newS3Error != nil {
logger.Error().Msg(newS3Error.Error())
os.Exit(1)
}
/*
store, newS3Error := storage.NewS3StorageWithContext(ctx, "http://51.159.98.189:9000", "eu-west", "enssatv", storage.Credentials{
AccessKey: accessKey,
SecretKey: secretKey,
Session: "",
})
if newS3Error != nil {
logger.Error().Msg(newS3Error.Error())
os.Exit(1)
}
video := twitch.GetVideoWithContext(ctx, videoID)
if err := store.Save(&video, outputFile); err != nil {
logger.Error().Msg(err.Error())
os.Exit(1)
}
video := twitch.GetVideoWithContext(ctx, videoID)
if err := store.Save(&video, outputFile); err != nil {
logger.Error().Msg(err.Error())
os.Exit(1)
}
*/
/*
wd := watchdog.NewSQLiteWatchdog("")
if err := wd.Run(); err != nil {
logger.Error().Msg(err.Error())
}
time.Sleep(time.Second * 5)
wd.Stop()
*/
fmt.Println(twitch.GetVideos("mistermv"))
}
52 changes: 52 additions & 0 deletions twitch/vod.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,19 @@ type videoResponse struct {
} `json:"data"`
}

// Représente une réponse de l'api GraphQL de Twitch lors de la requête d'information sur une liste de vidéos d'une chaîne
type userVideosResponse struct {
Data struct {
User struct {
Videos struct {
Edges []struct {
Node Video `json:"node"`
} `json:"edges"`
} `json:"videos"`
} `json:"user"`
} `json:"data"`
}

// Représente une réponse de l'api GraphQL de Twitch lors de la requête d'un token d'accès sur une vidéo
type tokenPlaybackResponse struct {
Data struct {
Expand Down Expand Up @@ -101,6 +114,26 @@ func getPlaybackTokenQuery(videoId string) string {
}`
}

// Requête GraphQL pour récupéré la liste des vidéos disponibles pour une chaîne donnée
func getVideosByChannel(channelName string) string {
return `{
user(login: "` + channelName + `") {
videos(first: 10, type: ARCHIVE) {
edges {
node {
id
title
description
publishedAt
broadcastType
lengthSeconds
}
}
}
}
}`
}

// Récupère la playlist M3U8 ayant la meilleur qualité
func parseM3U8(content string) *PlaylistInfo {
buffer := bytes.NewBufferString(content)
Expand Down Expand Up @@ -163,6 +196,25 @@ func GetVideoWithContext(ctx context.Context, videoId string) Video {
return video.Data.Video
}

// Récupère les informations des vidéos d'une chaîne
func GetVideos(channelName string) []Video {
return GetVideosWithContext(context.Background(), channelName)
}

// Récupère les informations des vidéos d'une chaîne, avec un contexte
func GetVideosWithContext(ctx context.Context, channelName string) []Video {
data, err := internals.PostGraphQL[userVideosResponse](getVideosByChannel(channelName))
if err != nil {
panic(err)
}
videos := make([]Video, 0)
for _, edge := range data.Data.User.Videos.Edges {
edge.Node.Context = ctx
videos = append(videos, edge.Node)
}
return videos
}

// Récupère la playlist de la vidéo
func (v *Video) GetPlaylist() *PlaylistInfo {
value := v.Context.Value(videoPlaybackAccessToken)
Expand Down
73 changes: 73 additions & 0 deletions watchdog/sqlite.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package watchdog

import (
"database/sql"
"fmt"
"time"

"enssat.tv/autovodsaver/twitch"
_ "github.com/mattn/go-sqlite3"
)

const (
createVideosStatusTableStatement = `
CREATE TABLE IF NOT EXISTS videos_status (
id INTEGER NOT NULL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
published_at DATETIME NOT NULL,
duration INTEGER NOT NULL,
status VARCHAR(50) NOT NULL
);
`
)

type SQLiteWatchdog struct {
Watchdog
Database *sql.DB
DatabaseFilePath string
}

func NewSQLiteWatchdog(channelId string) *SQLiteWatchdog {
return &SQLiteWatchdog{
DatabaseFilePath: "./db.sqlite",
Watchdog: Watchdog{
Status: WatchdogStatusStop,
ChannelId: channelId,
VideoHashMap: make(map[twitch.Video]VideoStatus),
OnVideoUpdateChannel: nil,
},
}
}

func (wd *SQLiteWatchdog) Run() error {
// Open connection to the database
db, openDatabaseError := sql.Open("sqlite3", wd.DatabaseFilePath)
if openDatabaseError != nil {
return openDatabaseError
}
defer db.Close()

// Create table "videos_status"
_, createVideoTableError := db.Exec(createVideosStatusTableStatement)
if createVideoTableError != nil {
return createVideoTableError
}

wd.Status = WatchdogStatusRun
wd.Database = db
go wd.watchdog()
return nil
}

func (wd *SQLiteWatchdog) watchdog() {
for wd.Status == WatchdogStatusRun {
fmt.Println("hey")
time.Sleep(1 * time.Second)
}
}

func (wd *SQLiteWatchdog) Stop() error {
wd.Status = WatchdogStatusStop
return nil
}
36 changes: 36 additions & 0 deletions watchdog/watchdog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package watchdog

import "enssat.tv/autovodsaver/twitch"

const (
VideoStatusMissing = "VIDEO_STATUS_MISSING"
VideoStatusArchived = "VIDEO_STATUS_ARCHIVED"
VideoStatusDownloading = "VIDEO_STATUS_DOWNLOADING"
VideoStatusConcatenating = "VIDEO_STATUS_CONCATENATING"
)

const (
WatchdogStatusRun = "WATCHDOG_STATUS_RUN"
WatchdogStatusStop = "WATCHDOG_STATUS_STOP"
)

type VideoStatus string
type WatchdogStatus string

type Watchdog struct {
Status WatchdogStatus
ChannelId string
VideoHashMap map[twitch.Video]VideoStatus
OnVideoUpdateChannel *chan UpdateMessage
}

type UpdateMessage struct {
Type VideoStatus
Video twitch.Video
}

type Watchdoger interface {
Run() error
Stop() error
OnVideoUpdate(ch *chan UpdateMessage)
}

0 comments on commit ba8df9c

Please sign in to comment.