updating plex json api parts

This commit is contained in:
2023-09-26 15:46:00 -04:00
parent 3c9149f7c0
commit 147ef10c01
2 changed files with 82 additions and 18 deletions

57
main.go
View File

@@ -1,6 +1,7 @@
package main package main
import ( import (
"encoding/json"
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
@@ -14,6 +15,7 @@ import (
type serverSettings struct { type serverSettings struct {
port int port int
jsonPort int
plexAddr string plexAddr string
plexToken string plexToken string
plexTimeout int plexTimeout int
@@ -33,6 +35,10 @@ func setupServerSettings() serverSettings {
if err != nil { if err != nil {
log.Fatal("Unable to parse port string to int, failing....") log.Fatal("Unable to parse port string to int, failing....")
} }
jsonPort, err := strconv.Atoi(envGetter("JSONPORT", "9546"))
if err != nil {
log.Fatal("Unable to parse jsonapi port string to int, failing....")
}
plexToken, value := os.LookupEnv("PLEX_TOKEN") plexToken, value := os.LookupEnv("PLEX_TOKEN")
if !value { if !value {
log.Fatal("No plex token provided, failing....") log.Fatal("No plex token provided, failing....")
@@ -48,6 +54,7 @@ func setupServerSettings() serverSettings {
return serverSettings{ return serverSettings{
port: port, port: port,
jsonPort: jsonPort,
plexAddr: envGetter("PLEX_ADDR", "http://localhost:32400"), plexAddr: envGetter("PLEX_ADDR", "http://localhost:32400"),
plexToken: plexToken, plexToken: plexToken,
plexTimeout: plexTimeout, plexTimeout: plexTimeout,
@@ -56,9 +63,42 @@ func setupServerSettings() serverSettings {
} }
} }
func setupJSONAPI(plexStatsChannel chan *plexStats, settings serverSettings) {
// Create a new router
mux := http.NewServeMux()
// Create a handler for the `/plex-stats` endpoint
mux.HandleFunc("/plex-stats", func(w http.ResponseWriter, r *http.Request) {
// Create a new plexStats struct
plexStats := <-plexStatsChannel
// Marshal the plexStats struct to JSON
jsonBody, err := json.Marshal(plexStats)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Set the content type to JSON
w.Header().Set("Content-Type", "application/json")
// Write the JSON body to the response
w.Write(jsonBody)
})
// Start the server
fmt.Println("Starting JSON API Server.....")
err := http.ListenAndServe(fmt.Sprintf(":%d", settings.jsonPort), mux)
if err != nil {
log.Fatal("Unable to start JSON Server on port: ", settings.jsonPort, " with err: ", err)
}
}
func main() { func main() {
os.Setenv("PORT", "9545") os.Setenv("PORT", "9545")
os.Setenv("JSONPORT", "9546")
os.Setenv("PLEX_ADDR", "https://plex.derajnet.duckdns.org:32400") os.Setenv("PLEX_ADDR", "https://plex.derajnet.duckdns.org:32400")
os.Setenv("PLEX_TOKEN", "5ezJu5cjnhoAbPJRKngs") os.Setenv("PLEX_TOKEN", "5ezJu5cjnhoAbPJRKngs")
os.Setenv("PLEX_TIMEOUT", "10") os.Setenv("PLEX_TIMEOUT", "10")
@@ -75,16 +115,21 @@ func main() {
prometheus.MustRegister(plexTranscodeSessions) prometheus.MustRegister(plexTranscodeSessions)
prometheus.MustRegister(plexAllSessions) prometheus.MustRegister(plexAllSessions)
plexStatsChannel := make(chan *plexStats)
go setupJSONAPI(plexStatsChannel, settings)
go func() { go func() {
for { for {
time.Sleep(time.Second * 60) time.Sleep(time.Second * 5)
fmt.Println("Collecting info...") fmt.Println("Collecting info...")
stats := pc.gatherAllStats() stats := pc.gatherAllStats()
plexActiveSessions.Set(stats.currentSessions) plexStatsChannel <- stats
plexNumMovies.Set(stats.numMovies) plexActiveSessions.Set(stats.CurrentSessions)
plexNumTVShows.Set(stats.numTV) plexNumMovies.Set(stats.NumMovies)
plexTranscodeSessions.Set(stats.numTranscodes) plexNumTVShows.Set(stats.NumTV)
plexAllSessions.Set(stats.numAllSessions) plexTranscodeSessions.Set(stats.NumTranscodes)
plexAllSessions.Set(stats.NumAllSessions)
} }
}() }()

View File

@@ -9,12 +9,22 @@ import (
"net/http" "net/http"
) )
type CurrentlyPlayingDetails struct {
CurrentPlayingTitle string `json:"currentPlayingTitle"`
IpAddress string `json:"ipAddress"`
Platform string `json:"platform"`
Product string `json:"product"`
Title string `json:"title"`
State string `json:"state"`
}
type plexStats struct { type plexStats struct {
currentSessions float64 CurrentSessions float64 `json:"currentSessions"`
numMovies float64 NumMovies float64 `json:"numMovies"`
numTV float64 NumTV float64 `json:"numTV"`
numTranscodes float64 NumTranscodes float64 `json:"numTranscodes"`
numAllSessions float64 NumAllSessions float64 `json:"numAllSessions"`
CurrentlyPlayingDetails CurrentlyPlayingDetails `json:"currentlyPlayingDetails"`
} }
type PlexClient struct { type PlexClient struct {
@@ -73,9 +83,9 @@ func (pc *PlexClient) getActiveSessions() *ActiveSessions {
return &currentActiveSessions return &currentActiveSessions
} }
func (pc *PlexClient) getNumMovies() *ActiveSessions { func (pc *PlexClient) getNumMovies() *RawPlexModel {
result := pc.sendRequest("/library/sections/3/all", nil) //Hard code library ID for now TODO: Grab from library/sections call result := pc.sendRequest("/library/sections/3/all", nil) //Hard code library ID for now TODO: Grab from library/sections call
libraryAll := ActiveSessions{} libraryAll := RawPlexModel{}
err := json.Unmarshal(result, &libraryAll) err := json.Unmarshal(result, &libraryAll)
if err != nil { if err != nil {
fmt.Println("Error unmarshalling num movies: ", err) fmt.Println("Error unmarshalling num movies: ", err)
@@ -123,10 +133,19 @@ func (pc *PlexClient) gatherAllStats() *plexStats {
transcodeDetails := pc.getNumTranscodes() transcodeDetails := pc.getNumTranscodes()
allSessionsData := pc.getServerHistory() allSessionsData := pc.getServerHistory()
allStats.currentSessions = float64(sessionsData.MediaContainer.Size) allStats.CurrentSessions = float64(sessionsData.MediaContainer.Size)
allStats.numMovies = float64(libraryDetails.MediaContainer.Size) allStats.NumMovies = float64(libraryDetails.MediaContainer.Size)
allStats.numTV = float64(tvshowDetails.MediaContainer.Size) allStats.NumTV = float64(tvshowDetails.MediaContainer.Size)
allStats.numTranscodes = float64(transcodeDetails.MediaContainer.Size) allStats.NumTranscodes = float64(transcodeDetails.MediaContainer.Size)
allStats.numAllSessions = float64(allSessionsData.MediaContainer.Size) allStats.NumAllSessions = float64(allSessionsData.MediaContainer.Size)
if len(sessionsData.MediaContainer.Metadata) > 0 {
allStats.CurrentlyPlayingDetails.CurrentPlayingTitle = sessionsData.MediaContainer.Metadata[0].Title
allStats.CurrentlyPlayingDetails.IpAddress = sessionsData.MediaContainer.Metadata[0].Player.Address
allStats.CurrentlyPlayingDetails.Platform = sessionsData.MediaContainer.Metadata[0].Player.Platform
allStats.CurrentlyPlayingDetails.Product = sessionsData.MediaContainer.Metadata[0].Player.Product
allStats.CurrentlyPlayingDetails.State = sessionsData.MediaContainer.Metadata[0].Player.State
allStats.CurrentlyPlayingDetails.Title = sessionsData.MediaContainer.Metadata[0].Player.Title
}
return &allStats return &allStats
} }