Files
Anitrack/AniListUserFunctions.go
T
John O'Keefe 79022c04a8 style(go): reformat embedded GraphQL queries with consistent indentation
Normalize the AniList GraphQL query strings in AniListFunctions.go
and AniListUserFunctions.go so every operation uses the same
indentation scheme: two-space steps, field and nested selection sets
uniformly indented, and keywords/arguments spaced consistently
(query ($search: String!), relations {, startDate {, etc.). Also
break the AniListBrowse parameter list onto its own trailing
parameter line for readability.

The queries themselves are unchanged - this is whitespace-only
normalization of the raw string literals, done with the new
project-local Neovim setup (.nvim.lua) that formats embedded GraphQL
via prettier. No behavior change; queries return identical results.
2026-09-24 13:50:31 -04:00

222 lines
6.5 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"github.com/zalando/go-keyring"
)
var aniListJwt AniListJWT
// aniKeyringService is the OS keyring service name all AniTrack secrets
// live under (same wallet the 99designs/keyring build used).
const aniKeyringService = "AniTrack"
func aniRingSet(key string, data []byte) error {
if err := keyring.Set(aniKeyringService, key, string(data)); err != nil {
log.Printf("anilist: save %s failed: %s", key, err)
return err
}
return nil
}
var aniCtxShutdown, aniCancel = context.WithCancel(context.Background())
func (a *App) CheckIfAniListLoggedIn() bool {
if (AniListJWT{} == aniListJwt) {
tokenType, tokenErr := keyring.Get(aniKeyringService, "anilistTokenType")
expiresIn, expiresInErr := keyring.Get(aniKeyringService, "anilistTokenExpiresIn")
refreshToken, refreshTokenErr := keyring.Get(aniKeyringService, "anilistRefreshToken")
accessToken, accessTokenErr := keyring.Get(aniKeyringService, "anilistAccessToken")
if (tokenErr != nil || expiresInErr != nil || refreshTokenErr != nil || accessTokenErr != nil) || len(accessToken) == 0 {
return false
} else {
var expiresInConvertErr error
aniListJwt.TokenType = tokenType
aniListJwt.AccessToken = accessToken
aniListJwt.RefreshToken = refreshToken
aniListJwt.ExpiresIn, expiresInConvertErr = strconv.Atoi(expiresIn)
if expiresInConvertErr != nil {
log.Printf("anilist: invalid expiresIn %q: %s", expiresIn, expiresInConvertErr)
return false
}
return true
}
} else {
return true
}
}
func (a *App) AniListLogin() {
if (AniListJWT{} == aniListJwt) {
tokenType, tokenErr := keyring.Get(aniKeyringService, "anilistTokenType")
expiresIn, expiresInErr := keyring.Get(aniKeyringService, "anilistTokenExpiresIn")
refreshToken, refreshTokenErr := keyring.Get(aniKeyringService, "anilistRefreshToken")
accessToken, accessTokenErr := keyring.Get(aniKeyringService, "anilistAccessToken")
if (tokenErr != nil || expiresInErr != nil || refreshTokenErr != nil || accessTokenErr != nil) || len(accessToken) == 0 {
getAniListCodeUrl := "https://anilist.co/api/v2/oauth/authorize?client_id=" + Environment.ANILIST_APP_ID + "&redirect_uri=" + Environment.ANILIST_CALLBACK_URI + "&response_type=code"
if err := a.app.Browser.OpenURL(getAniListCodeUrl); err != nil {
log.Printf("anilist: failed to open browser: %s", err)
return
}
serverDone := &sync.WaitGroup{}
serverDone.Add(1)
a.handleAniListCallback(serverDone)
serverDone.Wait()
} else {
var expiresInConvertErr error
aniListJwt.TokenType = tokenType
aniListJwt.AccessToken = accessToken
aniListJwt.RefreshToken = refreshToken
aniListJwt.ExpiresIn, expiresInConvertErr = strconv.Atoi(expiresIn)
if expiresInConvertErr != nil {
log.Printf("anilist: invalid expiresIn %q: %s", expiresIn, expiresInConvertErr)
}
}
}
}
func (a *App) handleAniListCallback(wg *sync.WaitGroup) {
mux := http.NewServeMux()
srv := &http.Server{Addr: ":6734", Handler: mux}
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
select {
case <-aniCtxShutdown.Done():
fmt.Println("Shutting down...")
return
default:
}
content := r.FormValue("code")
if content != "" {
aniListJwt = getAniListAuthorizationToken(content)
_ = aniRingSet("anilistTokenType", []byte(aniListJwt.TokenType))
_ = aniRingSet("anilistTokenExpiresIn", []byte(strconv.Itoa(aniListJwt.ExpiresIn)))
_ = aniRingSet("anilistAccessToken", []byte(aniListJwt.AccessToken))
_ = aniRingSet("anilistRefreshToken", []byte(aniListJwt.RefreshToken))
a.app.Dialog.Info().
SetTitle("AniList Authorization").
SetMessage("It is now safe to close your browser tab").
Show()
fmt.Println("Shutting down...")
aniCancel()
if err := srv.Shutdown(context.Background()); err != nil {
log.Println("server.Shutdown:", err)
}
} else {
_, err := fmt.Fprintf(w, "Getting code failed.")
if err != nil {
return
}
}
})
go func() {
defer wg.Done()
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listen: %s\n", err)
}
fmt.Println("Shutting down...")
}()
}
func getAniListAuthorizationToken(content string) AniListJWT {
apiUrl := "https://anilist.co/api/v2/oauth/token"
resource := "/api/v2/oauth/token"
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("client_id", Environment.ANILIST_APP_ID)
data.Set("client_secret", Environment.ANILIST_SECRET_TOKEN)
data.Set("redirect_uri", Environment.ANILIST_CALLBACK_URI)
data.Set("code", content)
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String()
response, err := http.NewRequest("POST", urlStr, strings.NewReader(data.Encode()))
if err != nil {
log.Printf("Failed at response, %s\n", err)
}
response.Header.Add("Content-type", "application/x-www-form-urlencoded")
response.Header.Add("Accept", "application/json")
client := &http.Client{}
res, resErr := client.Do(response)
if resErr != nil {
log.Printf("Failed at res, %s\n", err)
}
defer res.Body.Close()
returnedBody, err := io.ReadAll(res.Body)
if err != nil {
log.Printf("Could not read returned body, %s\n.", err)
}
var post AniListJWT
err = json.Unmarshal(returnedBody, &post)
if err != nil {
log.Printf("Failed at unmarshal, %s\n", err)
}
return post
}
func (a *App) GetAniListLoggedInUser() AniListUser {
a.AniListLogin()
body := struct {
Query string `json:"query"`
}{
Query: `
query {
Viewer {
id
name
avatar {
large
medium
}
bannerImage
siteUrl
}
}
`,
}
user, _ := AniListQuery(body, true)
var post AniListUser
err := json.Unmarshal(user, &post)
if err != nil {
log.Printf("Failed at unmarshal, %s\n", err)
}
return post
}
func (a *App) LogoutAniList() string {
if (AniListJWT{} != aniListJwt) {
typeErr := keyring.Delete(aniKeyringService, "anilistTokenType")
expiresInErr := keyring.Delete(aniKeyringService, "anilistTokenExpiresIn")
accessTokenErr := keyring.Delete(aniKeyringService, "anilistAccessToken")
refreshTokenErr := keyring.Delete(aniKeyringService, "anilistRefreshToken")
if typeErr != nil || expiresInErr != nil || accessTokenErr != nil || refreshTokenErr != nil {
log.Printf("anilist: logout cleanup failed (type=%v expires=%v access=%v refresh=%v)", typeErr, expiresInErr, accessTokenErr, refreshTokenErr)
}
aniListJwt = AniListJWT{}
}
return "AniList Logged Out Successfully"
}