cleanup logs and use structs in jf/emby api

Also means times are directly parsed when pulling data from jf/emby,
which was *painful* to get working (something broke the whole program and it
took me an hour to figure out it was this lol). Time parsing should be a
lot stabler too.
This commit is contained in:
Harvey Tindall
2021-02-19 00:47:01 +00:00
parent ce30537ebd
commit 76fa171575
9 changed files with 303 additions and 210 deletions
+24 -26
View File
@@ -20,8 +20,8 @@ func embyDeleteUser(emby *MediaBrowser, userID string) (int, error) {
return resp.StatusCode, err
}
func embyGetUsers(emby *MediaBrowser, public bool) ([]map[string]interface{}, int, error) {
var result []map[string]interface{}
func embyGetUsers(emby *MediaBrowser, public bool) ([]User, int, error) {
var result []User
var data string
var status int
var err error
@@ -39,42 +39,40 @@ func embyGetUsers(emby *MediaBrowser, public bool) ([]map[string]interface{}, in
json.Unmarshal([]byte(data), &result)
emby.userCache = result
emby.CacheExpiry = time.Now().Add(time.Minute * time.Duration(emby.cacheLength))
if id, ok := result[0]["Id"]; ok {
if id.(string)[8] == '-' {
emby.Hyphens = true
}
if result[0].ID[8] == '-' {
emby.Hyphens = true
}
return result, status, nil
}
return emby.userCache, 200, nil
}
func embyUserByName(emby *MediaBrowser, username string, public bool) (map[string]interface{}, int, error) {
var match map[string]interface{}
find := func() (map[string]interface{}, int, error) {
func embyUserByName(emby *MediaBrowser, username string, public bool) (User, int, error) {
var match User
find := func() (User, int, error) {
users, status, err := emby.GetUsers(public)
if err != nil || status != 200 {
return nil, status, err
return User{}, status, err
}
for _, user := range users {
if user["Name"].(string) == username {
if user.Name == username {
return user, status, err
}
}
return nil, status, err
return User{}, status, err
}
match, status, err := find()
if match == nil {
if match.Name == "" {
emby.CacheExpiry = time.Now()
match, status, err = find()
}
return match, status, err
}
func embyUserByID(emby *MediaBrowser, userID string, public bool) (map[string]interface{}, int, error) {
func embyUserByID(emby *MediaBrowser, userID string, public bool) (User, int, error) {
if emby.CacheExpiry.After(time.Now()) {
for _, user := range emby.userCache {
if user["Id"].(string) == userID {
if user.ID == userID {
return user, 200, nil
}
}
@@ -82,23 +80,23 @@ func embyUserByID(emby *MediaBrowser, userID string, public bool) (map[string]in
if public {
users, status, err := emby.GetUsers(public)
if err != nil || status != 200 {
return nil, status, err
return User{}, status, err
}
for _, user := range users {
if user["Id"].(string) == userID {
if user.ID == userID {
return user, status, nil
}
}
return nil, status, err
return User{}, status, err
}
var result map[string]interface{}
var result User
var data string
var status int
var err error
url := fmt.Sprintf("%s/users/%s", emby.Server, userID)
data, status, err = emby.get(url, emby.loginParams)
if err != nil || status != 200 {
return nil, status, err
return User{}, status, err
}
json.Unmarshal([]byte(data), &result)
return result, status, nil
@@ -109,19 +107,19 @@ func embyUserByID(emby *MediaBrowser, userID string, public bool) (map[string]in
// Immediately disable it
// Set password
// Reeenable it
func embyNewUser(emby *MediaBrowser, username, password string) (map[string]interface{}, int, error) {
func embyNewUser(emby *MediaBrowser, username, password string) (User, int, error) {
url := fmt.Sprintf("%s/Users/New", emby.Server)
data := map[string]interface{}{
"Name": username,
}
response, status, err := emby.post(url, data, true)
var recv map[string]interface{}
var recv User
json.Unmarshal([]byte(response), &recv)
if err != nil || !(status == 200 || status == 204) {
return nil, status, err
return User{}, status, err
}
// Step 2: Set password
id := recv["Id"].(string)
id := recv.ID
url = fmt.Sprintf("%s/Users/%s/Password", emby.Server, id)
data = map[string]interface{}{
"Id": id,
@@ -136,7 +134,7 @@ func embyNewUser(emby *MediaBrowser, username, password string) (map[string]inte
return recv, status, nil
}
func embySetPolicy(emby *MediaBrowser, userID string, policy map[string]interface{}) (int, error) {
func embySetPolicy(emby *MediaBrowser, userID string, policy Policy) (int, error) {
url := fmt.Sprintf("%s/Users/%s/Policy", emby.Server, userID)
_, status, err := emby.post(url, policy, false)
if err != nil || status != 200 {
@@ -145,7 +143,7 @@ func embySetPolicy(emby *MediaBrowser, userID string, policy map[string]interfac
return status, nil
}
func embySetConfiguration(emby *MediaBrowser, userID string, configuration map[string]interface{}) (int, error) {
func embySetConfiguration(emby *MediaBrowser, userID string, configuration Configuration) (int, error) {
url := fmt.Sprintf("%s/Users/%s/Configuration", emby.Server, userID)
_, status, err := emby.post(url, configuration, false)
return status, err
+28 -26
View File
@@ -18,8 +18,8 @@ func jfDeleteUser(jf *MediaBrowser, userID string) (int, error) {
return resp.StatusCode, err
}
func jfGetUsers(jf *MediaBrowser, public bool) ([]map[string]interface{}, int, error) {
var result []map[string]interface{}
func jfGetUsers(jf *MediaBrowser, public bool) ([]User, int, error) {
var result []User
var data string
var status int
var err error
@@ -34,45 +34,47 @@ func jfGetUsers(jf *MediaBrowser, public bool) ([]map[string]interface{}, int, e
if err != nil || status != 200 {
return nil, status, err
}
json.Unmarshal([]byte(data), &result)
err := json.Unmarshal([]byte(data), &result)
if err != nil {
fmt.Println(err)
return nil, status, err
}
jf.userCache = result
jf.CacheExpiry = time.Now().Add(time.Minute * time.Duration(jf.cacheLength))
if id, ok := result[0]["Id"]; ok {
if id.(string)[8] == '-' {
jf.Hyphens = true
}
if result[0].ID[8] == '-' {
jf.Hyphens = true
}
return result, status, nil
}
return jf.userCache, 200, nil
}
func jfUserByName(jf *MediaBrowser, username string, public bool) (map[string]interface{}, int, error) {
var match map[string]interface{}
find := func() (map[string]interface{}, int, error) {
func jfUserByName(jf *MediaBrowser, username string, public bool) (User, int, error) {
var match User
find := func() (User, int, error) {
users, status, err := jf.GetUsers(public)
if err != nil || status != 200 {
return nil, status, err
return User{}, status, err
}
for _, user := range users {
if user["Name"].(string) == username {
if user.Name == username {
return user, status, err
}
}
return nil, status, err
return User{}, status, err
}
match, status, err := find()
if match == nil {
if match.Name == "" {
jf.CacheExpiry = time.Now()
match, status, err = find()
}
return match, status, err
}
func jfUserByID(jf *MediaBrowser, userID string, public bool) (map[string]interface{}, int, error) {
func jfUserByID(jf *MediaBrowser, userID string, public bool) (User, int, error) {
if jf.CacheExpiry.After(time.Now()) {
for _, user := range jf.userCache {
if user["Id"].(string) == userID {
if user.ID == userID {
return user, 200, nil
}
}
@@ -80,29 +82,29 @@ func jfUserByID(jf *MediaBrowser, userID string, public bool) (map[string]interf
if public {
users, status, err := jf.GetUsers(public)
if err != nil || status != 200 {
return nil, status, err
return User{}, status, err
}
for _, user := range users {
if user["Id"].(string) == userID {
if user.ID == userID {
return user, status, nil
}
}
return nil, status, err
return User{}, status, err
}
var result map[string]interface{}
var result User
var data string
var status int
var err error
url := fmt.Sprintf("%s/users/%s", jf.Server, userID)
data, status, err = jf.get(url, jf.loginParams)
if err != nil || status != 200 {
return nil, status, err
return User{}, status, err
}
json.Unmarshal([]byte(data), &result)
return result, status, nil
}
func jfNewUser(jf *MediaBrowser, username, password string) (map[string]interface{}, int, error) {
func jfNewUser(jf *MediaBrowser, username, password string) (User, int, error) {
url := fmt.Sprintf("%s/Users/New", jf.Server)
stringData := map[string]string{
"Name": username,
@@ -113,15 +115,15 @@ func jfNewUser(jf *MediaBrowser, username, password string) (map[string]interfac
data[key] = value
}
response, status, err := jf.post(url, data, true)
var recv map[string]interface{}
var recv User
json.Unmarshal([]byte(response), &recv)
if err != nil || !(status == 200 || status == 204) {
return nil, status, err
return User{}, status, err
}
return recv, status, nil
}
func jfSetPolicy(jf *MediaBrowser, userID string, policy map[string]interface{}) (int, error) {
func jfSetPolicy(jf *MediaBrowser, userID string, policy Policy) (int, error) {
url := fmt.Sprintf("%s/Users/%s/Policy", jf.Server, userID)
_, status, err := jf.post(url, policy, false)
if err != nil || status != 200 {
@@ -130,7 +132,7 @@ func jfSetPolicy(jf *MediaBrowser, userID string, policy map[string]interface{})
return status, nil
}
func jfSetConfiguration(jf *MediaBrowser, userID string, configuration map[string]interface{}) (int, error) {
func jfSetConfiguration(jf *MediaBrowser, userID string, configuration Configuration) (int, error) {
url := fmt.Sprintf("%s/Users/%s/Configuration", jf.Server, userID)
_, status, err := jf.post(url, configuration, false)
return status, err
+32 -21
View File
@@ -14,10 +14,12 @@ import (
"github.com/hrfee/jfa-go/common"
)
type serverType bool
type serverType int
var JellyfinServer serverType = false
var EmbyServer serverType = true
const (
JellyfinServer serverType = iota
EmbyServer
)
type serverInfo struct {
LocalAddress string `json:"LocalAddress"`
@@ -45,7 +47,7 @@ type MediaBrowser struct {
userID string
httpClient *http.Client
loginParams map[string]string
userCache []map[string]interface{}
userCache []User
CacheExpiry time.Time
cacheLength int
noFail bool
@@ -131,7 +133,7 @@ func (mb *MediaBrowser) get(url string, params map[string]string) (string, int,
return buf.String(), resp.StatusCode, nil
}
func (mb *MediaBrowser) post(url string, data map[string]interface{}, response bool) (string, int, error) {
func (mb *MediaBrowser) post(url string, data interface{}, response bool) (string, int, error) {
params, _ := json.Marshal(data)
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(params))
for name, value := range mb.header {
@@ -167,7 +169,7 @@ func (mb *MediaBrowser) post(url string, data map[string]interface{}, response b
}
// Authenticate attempts to authenticate using a username & password
func (mb *MediaBrowser) Authenticate(username, password string) (map[string]interface{}, int, error) {
func (mb *MediaBrowser) Authenticate(username, password string) (User, int, error) {
mb.Username = username
mb.password = password
mb.loginParams = map[string]string{
@@ -180,35 +182,44 @@ func (mb *MediaBrowser) Authenticate(username, password string) (map[string]inte
encoder.SetEscapeHTML(false)
err := encoder.Encode(mb.loginParams)
if err != nil {
return nil, 0, err
return User{}, 0, err
}
// loginParams, _ := json.Marshal(jf.loginParams)
url := fmt.Sprintf("%s/Users/authenticatebyname", mb.Server)
req, err := http.NewRequest("POST", url, buffer)
defer mb.timeoutHandler()
if err != nil {
return nil, 0, err
return User{}, 0, err
}
for name, value := range mb.header {
req.Header.Add(name, value)
}
resp, err := mb.httpClient.Do(req)
if err != nil || resp.StatusCode != 200 {
return nil, resp.StatusCode, err
return User{}, resp.StatusCode, err
}
defer resp.Body.Close()
var data io.Reader
var d io.Reader
switch resp.Header.Get("Content-Encoding") {
case "gzip":
data, _ = gzip.NewReader(resp.Body)
d, _ = gzip.NewReader(resp.Body)
default:
data = resp.Body
d = resp.Body
}
data, err := io.ReadAll(d)
if err != nil {
return User{}, 0, err
}
var respData map[string]interface{}
json.NewDecoder(data).Decode(&respData)
json.Unmarshal(data, &respData)
mb.AccessToken = respData["AccessToken"].(string)
user := respData["User"].(map[string]interface{})
mb.userID = respData["User"].(map[string]interface{})["Id"].(string)
var user User
ju, err := json.Marshal(respData["User"])
if err != nil {
return User{}, 0, err
}
json.Unmarshal(ju, &user)
mb.userID = user.ID
mb.auth = fmt.Sprintf("MediaBrowser Client=\"%s\", Device=\"%s\", DeviceId=\"%s\", Version=\"%s\", Token=\"%s\"", mb.client, mb.device, mb.deviceID, mb.version, mb.AccessToken)
mb.header["X-Emby-Authorization"] = mb.auth
mb.Authenticated = true
@@ -224,7 +235,7 @@ func (mb *MediaBrowser) DeleteUser(userID string) (int, error) {
}
// GetUsers returns all (visible) users on the Emby instance.
func (mb *MediaBrowser) GetUsers(public bool) ([]map[string]interface{}, int, error) {
func (mb *MediaBrowser) GetUsers(public bool) ([]User, int, error) {
if mb.serverType == JellyfinServer {
return jfGetUsers(mb, public)
}
@@ -232,7 +243,7 @@ func (mb *MediaBrowser) GetUsers(public bool) ([]map[string]interface{}, int, er
}
// UserByName returns the user corresponding to the provided username.
func (mb *MediaBrowser) UserByName(username string, public bool) (map[string]interface{}, int, error) {
func (mb *MediaBrowser) UserByName(username string, public bool) (User, int, error) {
if mb.serverType == JellyfinServer {
return jfUserByName(mb, username, public)
}
@@ -240,7 +251,7 @@ func (mb *MediaBrowser) UserByName(username string, public bool) (map[string]int
}
// UserByID returns the user corresponding to the provided ID.
func (mb *MediaBrowser) UserByID(userID string, public bool) (map[string]interface{}, int, error) {
func (mb *MediaBrowser) UserByID(userID string, public bool) (User, int, error) {
if mb.serverType == JellyfinServer {
return jfUserByID(mb, userID, public)
}
@@ -248,7 +259,7 @@ func (mb *MediaBrowser) UserByID(userID string, public bool) (map[string]interfa
}
// NewUser creates a new user with the provided username and password.
func (mb *MediaBrowser) NewUser(username, password string) (map[string]interface{}, int, error) {
func (mb *MediaBrowser) NewUser(username, password string) (User, int, error) {
if mb.serverType == JellyfinServer {
return jfNewUser(mb, username, password)
}
@@ -256,7 +267,7 @@ func (mb *MediaBrowser) NewUser(username, password string) (map[string]interface
}
// SetPolicy sets the access policy for the user corresponding to the provided ID.
func (mb *MediaBrowser) SetPolicy(userID string, policy map[string]interface{}) (int, error) {
func (mb *MediaBrowser) SetPolicy(userID string, policy Policy) (int, error) {
if mb.serverType == JellyfinServer {
return jfSetPolicy(mb, userID, policy)
}
@@ -264,7 +275,7 @@ func (mb *MediaBrowser) SetPolicy(userID string, policy map[string]interface{})
}
// SetConfiguration sets the configuration (part of homescreen layout) for the user corresponding to the provided ID.
func (mb *MediaBrowser) SetConfiguration(userID string, configuration map[string]interface{}) (int, error) {
func (mb *MediaBrowser) SetConfiguration(userID string, configuration Configuration) (int, error) {
if mb.serverType == JellyfinServer {
return jfSetConfiguration(mb, userID, configuration)
}
+135
View File
@@ -0,0 +1,135 @@
package mediabrowser
import (
"encoding/json"
"fmt"
"strings"
"time"
)
type magicParse struct {
Parsed time.Time `json:"parseme"`
}
type Time struct {
time.Time
}
func (t *Time) UnmarshalJSON(b []byte) (err error) {
str := strings.TrimSuffix(strings.TrimPrefix(string(b), "\""), "\"")
// Trim nanoseconds to always have 6 digits, so overall length is always the same.
if str[len(str)-1] == 'Z' {
str = str[:26] + "Z"
} else {
str = str[:26]
}
// decent method
t.Time, err = time.Parse("2006-01-02T15:04:05.000000Z", str)
if err == nil {
return
}
t.Time, err = time.Parse("2006-01-02T15:04:05.000000", str)
if err == nil {
return
}
// emby method
t.Time, err = time.Parse("2006-01-02T15:04:05.0000000+00:00", str)
if err == nil {
return
}
fmt.Println("THIRDERR", err)
// magic method
// some stored dates from jellyfin have no timezone at the end, if not we assume UTC
if str[len(str)-1] != 'Z' {
str += "Z"
}
timeJSON := []byte("{ \"parseme\": \"" + str + "\" }")
var parsed magicParse
// Magically turn it into a time.Time
err = json.Unmarshal(timeJSON, &parsed)
t.Time = parsed.Parsed
return
}
type User struct {
Name string `json:"Name"`
ServerID string `json:"ServerId"`
ID string `json:"Id"`
HasPassword bool `json:"HasPassword"`
HasConfiguredPassword bool `json:"HasConfiguredPassword"`
HasConfiguredEasyPassword bool `json:"HasConfiguredEasyPassword"`
EnableAutoLogin bool `json:"EnableAutoLogin"`
LastLoginDate Time `json:"LastLoginDate"`
LastActivityDate Time `json:"LastActivityDate"`
Configuration Configuration `json:"Configuration"`
Policy Policy `json:"Policy"`
}
type SessionInfo struct {
RemoteEndpoint string `json:"RemoteEndPoint"`
UserID string `json:"UserId"`
}
type AuthenticationResult struct {
User User `json:"User"`
AccessToken string `json:"AccessToken"`
ServerID string `json:"ServerId"`
SessionInfo SessionInfo `json:"SessionInfo"`
}
type Configuration struct {
PlayDefaultAudioTrack bool `json:"PlayDefaultAudioTrack"`
SubtitleLanguagePreference string `json:"SubtitleLanguagePreference"`
DisplayMissingEpisodes bool `json:"DisplayMissingEpisodes"`
GroupedFolders []interface{} `json:"GroupedFolders"`
SubtitleMode string `json:"SubtitleMode"`
DisplayCollectionsView bool `json:"DisplayCollectionsView"`
EnableLocalPassword bool `json:"EnableLocalPassword"`
OrderedViews []interface{} `json:"OrderedViews"`
LatestItemsExcludes []interface{} `json:"LatestItemsExcludes"`
MyMediaExcludes []interface{} `json:"MyMediaExcludes"`
HidePlayedInLatest bool `json:"HidePlayedInLatest"`
RememberAudioSelections bool `json:"RememberAudioSelections"`
RememberSubtitleSelections bool `json:"RememberSubtitleSelections"`
EnableNextEpisodeAutoPlay bool `json:"EnableNextEpisodeAutoPlay"`
}
type Policy struct {
IsAdministrator bool `json:"IsAdministrator"`
IsHidden bool `json:"IsHidden"`
IsDisabled bool `json:"IsDisabled"`
BlockedTags []interface{} `json:"BlockedTags"`
EnableUserPreferenceAccess bool `json:"EnableUserPreferenceAccess"`
AccessSchedules []interface{} `json:"AccessSchedules"`
BlockUnratedItems []interface{} `json:"BlockUnratedItems"`
EnableRemoteControlOfOtherUsers bool `json:"EnableRemoteControlOfOtherUsers"`
EnableSharedDeviceControl bool `json:"EnableSharedDeviceControl"`
EnableRemoteAccess bool `json:"EnableRemoteAccess"`
EnableLiveTvManagement bool `json:"EnableLiveTvManagement"`
EnableLiveTvAccess bool `json:"EnableLiveTvAccess"`
EnableMediaPlayback bool `json:"EnableMediaPlayback"`
EnableAudioPlaybackTranscoding bool `json:"EnableAudioPlaybackTranscoding"`
EnableVideoPlaybackTranscoding bool `json:"EnableVideoPlaybackTranscoding"`
EnablePlaybackRemuxing bool `json:"EnablePlaybackRemuxing"`
ForceRemoteSourceTranscoding bool `json:"ForceRemoteSourceTranscoding"`
EnableContentDeletion bool `json:"EnableContentDeletion"`
EnableContentDeletionFromFolders []interface{} `json:"EnableContentDeletionFromFolders"`
EnableContentDownloading bool `json:"EnableContentDownloading"`
EnableSyncTranscoding bool `json:"EnableSyncTranscoding"`
EnableMediaConversion bool `json:"EnableMediaConversion"`
EnabledDevices []interface{} `json:"EnabledDevices"`
EnableAllDevices bool `json:"EnableAllDevices"`
EnabledChannels []interface{} `json:"EnabledChannels"`
EnableAllChannels bool `json:"EnableAllChannels"`
EnabledFolders []string `json:"EnabledFolders"`
EnableAllFolders bool `json:"EnableAllFolders"`
InvalidLoginAttemptCount int `json:"InvalidLoginAttemptCount"`
LoginAttemptsBeforeLockout int `json:"LoginAttemptsBeforeLockout"`
MaxActiveSessions int `json:"MaxActiveSessions"`
EnablePublicSharing bool `json:"EnablePublicSharing"`
BlockedMediaFolders []interface{} `json:"BlockedMediaFolders"`
BlockedChannels []interface{} `json:"BlockedChannels"`
RemoteClientBitrateLimit int `json:"RemoteClientBitrateLimit"`
AuthenticationProviderID string `json:"AuthenticationProviderId"`
PasswordResetProviderID string `json:"PasswordResetProviderId"`
SyncPlayAccess string `json:"SyncPlayAccess"`
}