Skip to content

Instantly share code, notes, and snippets.

@benjacoblee
Created November 1, 2023 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjacoblee/7b0e87310f178f0160d5f7ea044ad5bd to your computer and use it in GitHub Desktop.
Save benjacoblee/7b0e87310f178f0160d5f7ea044ad5bd to your computer and use it in GitHub Desktop.
freetube-cron.go
package main
import (
"bufio"
"encoding/json"
"log"
"os"
"slices"
"sort"
"github.com/r--w/pocketbase"
)
type video struct {
VideoID string `json:"videoId"`
Author string `json:"author"`
Title string `json:"title"`
TimeWatched int `json:"timeWatched"`
}
type customErr string
const program = "FREETUBE_CRON"
func (e customErr) Error() string {
return string(e)
}
func main() {
f, err := os.OpenFile(os.Getenv("FREETUBE_LOG"), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
log.Printf("%v\n", err)
}
f.Truncate(0) // clear file
defer f.Close()
log.SetOutput(f)
log.Printf("%v: Running", program)
client := createClient()
recentlyWatched := getRecentlyWatched()
clientCreateResponse(recentlyWatched, client)
}
func getRecentlyWatched() (lastFive []video) {
var (
videos = []video{}
filepath = os.Getenv("FREETUBE_HISTORY_PATH")
file, err = os.Open(filepath)
scanner = bufio.NewScanner(file)
)
if err != nil {
log.Println(err)
}
defer file.Close()
for scanner.Scan() {
var video video
json.Unmarshal([]byte(scanner.Text()), &video)
if !slices.Contains(videos, video) && len(video.Title) > 0 {
videos = append(videos, video)
}
}
sort.Slice(videos, func(i, j int) bool {
timestampA := int64(videos[i].TimeWatched)
timestampB := int64(videos[j].TimeWatched)
return timestampA < timestampB
})
lastFive = videos[len(videos)-5:]
return
}
func clientCreateResponse(recentlyWatched []video, client *pocketbase.Client) []video {
for _, v := range recentlyWatched {
collectionName := os.Getenv("FREETUBE_HISTORY_COLLECTION_NAME")
response, err := client.Create(collectionName, v)
if err != nil {
log.Println(err)
return nil
}
log.Printf("RESPONSE: %v\n", response)
}
return recentlyWatched
}
func createClient() *pocketbase.Client {
client := pocketbase.NewClient(os.Getenv("PB_URL"))
return client
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment