added ability to update simkl episode count

This commit is contained in:
2024-08-11 12:20:26 -04:00
parent aaf0f421f2
commit 8a6b3bd2b7
8 changed files with 190 additions and 45 deletions

View File

@ -1,6 +1,7 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
@ -37,3 +38,78 @@ func (a *App) SimklGetUserWatchlist() SimklWatchList {
return watchlist
}
func SimklPostHelper(url string, body interface{}) json.RawMessage {
reader, _ := json.Marshal(body)
client := &http.Client{}
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(reader))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+simklJwt.AccessToken)
req.Header.Add("simkl-api-key", os.Getenv("SIMKL_CLIENT_ID"))
resp, err := client.Do(req)
if err != nil {
fmt.Println("Errored when sending request to the server")
message, _ := json.Marshal(struct {
Message string `json:"message" ts_type:"message"`
}{
Message: "Errored when sending request to the server" + err.Error(),
})
return message
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
return respBody
}
func (a *App) SimklSyncEpisodes(anime Anime, progress int) interface{} {
var episodes []Episode
var url string
var shows []SimklPostShow
if progress >= anime.WatchedEpisodesCount {
for i := 1; i <= progress; i++ {
episodes = append(episodes, Episode{Number: i})
}
url = "https://api.simkl.com/sync/history"
} else {
for i := anime.WatchedEpisodesCount; i > progress; i-- {
episodes = append(episodes, Episode{Number: i})
}
url = "https://api.simkl.com/sync/history/remove"
}
formattedShow := SimklPostShow{
Title: anime.Show.Title,
Ids: Ids{
Simkl: anime.Show.Ids.Simkl,
Mal: anime.Show.Ids.Mal,
Anilist: anime.Show.Ids.AniList,
},
Episodes: episodes,
}
shows = append(shows, formattedShow)
simklSync := SimklSyncHistoryType{shows}
respBody := SimklPostHelper(url, simklSync)
var success interface{}
err := json.Unmarshal(respBody, &success)
if err != nil {
log.Printf("Failed at unmarshal, %s\n", err)
}
return success
}