boxd/main.go
x 2ff3329a98
TV Show Support
added a seperate table, flags for logging tv shows and listing them.
fixed some captions to look kinda professional.
2024-03-15 06:35:45 +05:30

286 lines
9 KiB
Go

package main
import (
"database/sql"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
"runtime"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/huh/spinner"
"github.com/imroc/req/v3"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/cobra"
"github.com/tidwall/gjson"
)
func entryExists(db *sql.DB, name string, isMovie bool, isSeries bool) (bool, error) {
var count int
var row *sql.Row
if isMovie == true && isSeries == false {
row = db.QueryRow("SELECT COUNT(*) FROM movies WHERE imdb = ?", name)
} else if isMovie == false && isSeries == true {
row = db.QueryRow("SELECT COUNT(*) FROM series WHERE tmdb = ?", name)
} else {
fmt.Println("oops there is some confusion")
os.Exit(1)
}
err := row.Scan(&count)
if err != nil {
return false, err
}
return count > 0, nil
}
func logMedia(isMovie bool, isSeries bool) {
// get the watched media
var inputstring string
huh.NewForm(huh.NewGroup(huh.NewInput().Title("what did you watch today ?").Value(&inputstring)).WithShowHelp(true)).Run()
replacedinput := strings.Replace(inputstring, " ", "+", -1)
// search it on tmdb
var url string
if isMovie == true && isSeries == false {
url = "https://api.themoviedb.org/3/search/movie?query=" + replacedinput + "&page=1"
} else if isMovie == false && isSeries == true {
url = "https://api.themoviedb.org/3/search/tv?query=" + replacedinput + "&page=1"
} else {
fmt.Println("oops there is some confusion")
os.Exit(1)
}
client := req.C()
client.SetCommonHeader("accept", "application/json")
client.SetCommonHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIzZDllYmUxOTNhMGU4OWFjMjM0MzZjNGJhNDg1NTY5ZCIsInN1YiI6IjY1ZWQ3ZTFjYmRjMzRjMDE0NzMyMDgxYiIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.cJ5Aws6Um2VEcyqjhii5IjEihYyGmw5ICbh8ldHVqIs")
resp, err := client.R().Get(url)
if err != nil {
log.Fatal(err)
}
// parsing found json data
MovieInfo := make(map[string]int64)
var MovieList []string
result := gjson.Get(resp.String(), "results")
result.ForEach(func(key, value gjson.Result) bool {
var title gjson.Result
var id gjson.Result
var releaseDate gjson.Result
if isMovie == true && isSeries == false {
title = gjson.Get(value.String(), "title")
id = gjson.Get(value.String(), "id")
releaseDate = gjson.Get(value.String(), "release_date")
} else if isMovie == false && isSeries == true {
title = gjson.Get(value.String(), "name")
id = gjson.Get(value.String(), "id")
releaseDate = gjson.Get(value.String(), "first_air_date")
} else {
fmt.Println("oops there is some confusion")
os.Exit(1)
}
datesplit := strings.Split(releaseDate.String(), "-")
var releaseYear string
if datesplit[0] == "" {
releaseYear = "unknown"
} else {
releaseYear = datesplit[0]
}
comb := title.String() + " (" + releaseYear + ")"
MovieInfo[comb] = id.Int()
return true
})
for key := range MovieInfo {
MovieList = append(MovieList, key)
}
var watchedMovie string
huh.NewSelect[string]().Title("so which one ?").Options(huh.NewOptions(MovieList[:]...)...).Value(&watchedMovie).Run()
// fetch info about the watched media
movid := MovieInfo[watchedMovie]
if isMovie == true && isSeries == false {
url = "https://api.themoviedb.org/3/movie/" + strconv.FormatInt(movid, 10)
} else if isMovie == false && isSeries == true {
url = "https://api.themoviedb.org/3/tv/" + strconv.FormatInt(movid, 10)
} else {
fmt.Println("oops there is some confusion")
os.Exit(1)
}
resp, err = client.R().Get(url)
if err != nil {
log.Fatal(err)
}
var ogTitle gjson.Result
var plot gjson.Result
var imdbid gjson.Result
var releasedday gjson.Result
if isMovie == true && isSeries == false {
ogTitle = gjson.Get(resp.String(), "title")
plot = gjson.Get(resp.String(), "overview")
imdbid = gjson.Get(resp.String(), "imdb_id")
releasedday = gjson.Get(resp.String(), "release_date")
} else if isMovie == false && isSeries == true {
ogTitle = gjson.Get(resp.String(), "name")
plot = gjson.Get(resp.String(), "overview")
imdbid = gjson.Get(resp.String(), "id")
releasedday = gjson.Get(resp.String(), "first_air_date")
} else {
fmt.Println("oops there is some confusion")
os.Exit(1)
}
var ratingvalue string
var movopinion string
var recomend bool
ratetitle := "how would you rate " + ogTitle.String() + "?"
huh.NewForm(huh.NewGroup(
huh.NewInput().Title(ratetitle).Value(&ratingvalue),
huh.NewText().Title("what did you think of this movie ?").Value(&movopinion),
huh.NewConfirm().Title("do you recomend this to others ?").Affirmative("absolutely").Negative("nah").Value(&recomend),
)).Run()
currentdata := time.Now()
watchedDate := currentdata.Format("2006-01-02")
// log info to the database
var db *sql.DB
switch runtime.GOOS {
case "linux", "darwin":
dbLocation := os.Getenv("HOME") + "/Documents/Databases/boxd.db"
d, err := sql.Open("sqlite3", dbLocation)
db = d
if err != nil {
log.Fatal(err)
}
case "windows":
userProfile := os.Getenv("USERPROFILE")
dbLocation := userProfile + "\\Documents\\boxd.db"
d, err := sql.Open("sqlite3", dbLocation)
db = d
if err != nil {
log.Fatal(err)
}
}
defer db.Close()
var dbTableSquema string
if isMovie == true && isSeries == false {
dbTableSquema = `CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
plot TEXT,
releasedDate DATETIME,
imdb TEXT UNIQUE,
watchedOn DATETIME,
rating INTEGER,
opinion TEXT,
recommended INTEGER
);`
} else if isMovie == false && isSeries == true {
dbTableSquema = `CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
plot TEXT,
releasedDate DATETIME,
tmdb TEXT UNIQUE,
watchedOn DATETIME,
rating INTEGER,
opinion TEXT,
recommended INTEGER
);`
} else {
fmt.Println("oops there is some confusion")
os.Exit(1)
}
_, err = db.Exec(dbTableSquema)
if err != nil {
log.Fatal(err)
}
action := func() {
time.Sleep(1 * time.Second)
}
_ = spinner.New().Title("processing").Action(action).Run()
entryExists, err := entryExists(db, imdbid.String(), isMovie, isSeries)
if err != nil {
log.Fatal(err)
}
if entryExists {
fmt.Println("you already logged this media.")
} else if ogTitle.String() == "" || plot.String() == "" || releasedday.String() == "" || imdbid.String() == "" || watchedDate == "" || ratingvalue == "" || movopinion == "" {
fmt.Println("you need the enter all the details.")
} else {
var insertSQL string
if isMovie == true && isSeries == false {
insertSQL = `INSERT INTO movies (title, plot, releasedDate, imdb, watchedOn, rating, opinion, recommended) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`
} else if isMovie == false && isSeries == true {
insertSQL = `INSERT INTO series (title, plot, releasedDate, tmdb, watchedOn, rating, opinion, recommended) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`
} else {
fmt.Println("oops there is some confusion")
os.Exit(1)
}
_, err = db.Exec(insertSQL, ogTitle.String(), plot.String(), releasedday.String(), imdbid.String(), watchedDate, ratingvalue, movopinion, recomend)
if err != nil {
log.Fatal(err)
}
textOnSuccess := ogTitle.String() + " was logged to your diary."
fmt.Println(textOnSuccess)
}
}
func main() {
var isMovie bool
var isSeries bool
cmdLog := &cobra.Command{
Use: "a",
Short: "log media",
Long: `kind of like a movie diary with required
information about the watched movies`,
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
logMedia(isMovie, isSeries)
},
}
cmdList := &cobra.Command{
Use: "l",
Short: "list media",
Long: `kind of like a movie diary with required
information about the watched movies`,
Run: func(cmd *cobra.Command, args []string) {
Listmovies(isMovie, isSeries)
},
}
cmdLog.Flags().BoolVarP(&isMovie, "movie", "m", false, "log a movie")
cmdLog.Flags().BoolVarP(&isSeries, "series", "t", false, "log a tv show")
cmdLog.MarkFlagsOneRequired("movie", "series")
cmdLog.MarkFlagsMutuallyExclusive("movie", "series")
cmdList.Flags().BoolVarP(&isMovie, "movie", "m", false, "list logged movies")
cmdList.Flags().BoolVarP(&isSeries, "series", "t", false, "list logged tv shows")
cmdList.MarkFlagsOneRequired("movie", "series")
cmdList.MarkFlagsMutuallyExclusive("movie", "series")
rootCmd := &cobra.Command{Use: "boxd"}
rootCmd.AddCommand(cmdLog)
rootCmd.AddCommand(cmdList)
rootCmd.Execute()
}