added ability to delete entries. Added MAL RefreshToken Function

This commit is contained in:
John O'Keefe 2024-09-18 14:05:41 -04:00
parent 5cdf86a147
commit 00930f611e
14 changed files with 282 additions and 23 deletions

View File

@ -489,3 +489,39 @@ func (a *App) AniListUpdateEntry(updateBody AniListUpdateVariables) AniListGetSi
return post
}
func (a *App) AniListDeleteEntry(mediaListId int) DeleteAniListReturn {
type Variables = struct {
Id int `json:"id"`
}
body := struct {
Query string `json:"query"`
Variables Variables `json:"variables"`
}{
Query: `
mutation(
$id:Int,
){
DeleteMediaListEntry(
id:$id,
){
deleted
}
}
`,
Variables: Variables{
Id: mediaListId,
},
}
returnedBody, _ := AniListQuery(body, true)
var post DeleteAniListReturn
err := json.Unmarshal(returnedBody, &post)
if err != nil {
log.Printf("Failed at unmarshal, %s\n", err)
}
return post
}

View File

@ -139,6 +139,14 @@ type AniListUpdateVariables struct {
CompletedAt CompletedAt `json:"completedAt"`
}
type DeleteAniListReturn struct {
Data struct {
DeleteMediaListEntry struct {
Deleted bool `json:"deleted"`
} `json:"DeleteMediaListEntry"`
} `json:"data"`
}
//var MediaListSort = struct {
// MediaId string
// MediaIdDesc string

View File

@ -11,13 +11,14 @@ import (
"strings"
)
func MALHelper(method string, malUrl string, body url.Values) json.RawMessage {
func MALHelper(method string, malUrl string, body url.Values) (json.RawMessage, string) {
client := &http.Client{}
req, _ := http.NewRequest(method, malUrl, strings.NewReader(body.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Authorization", "Bearer "+myAnimeListJwt.AccessToken)
fmt.Println(myAnimeListJwt.AccessToken)
resp, err := client.Do(req)
@ -29,13 +30,18 @@ func MALHelper(method string, malUrl string, body url.Values) json.RawMessage {
Message: "Errored when sending request to the server" + err.Error(),
})
return message
return message, resp.Status
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
return respBody
if resp.Status == "401 Unauthorized" {
refreshMyAnimeListAuthorizationToken()
MALHelper(method, malUrl, body)
}
return respBody, resp.Status
}
func (a *App) GetMyAnimeList(count int) MALWatchlist {
@ -45,11 +51,13 @@ func (a *App) GetMyAnimeList(count int) MALWatchlist {
var malList MALWatchlist
respBody := MALHelper("GET", malUrl, nil)
respBody, resStatus := MALHelper("GET", malUrl, nil)
err := json.Unmarshal(respBody, &malList)
if err != nil {
log.Printf("Failed to unmarshal json response, %s\n", err)
if resStatus == "200 OK" {
err := json.Unmarshal(respBody, &malList)
if err != nil {
log.Printf("Failed to unmarshal json response, %s\n", err)
}
}
return malList
@ -71,23 +79,40 @@ func (a *App) MyAnimeListUpdate(anime MALAnime, update MALUploadStatus) MalListS
malUrl := "https://api.myanimelist.net/v2/anime/" + strconv.Itoa(anime.Id) + "/my_list_status"
var status MalListStatus
respBody := MALHelper("PATCH", malUrl, body)
err := json.Unmarshal(respBody, &status)
if err != nil {
log.Printf("Failed to unmarshal json response, %s\n", err)
respBody, respStatus := MALHelper("PATCH", malUrl, body)
if respStatus == "200 OK" {
err := json.Unmarshal(respBody, &status)
if err != nil {
log.Printf("Failed to unmarshal json response, %s\n", err)
}
}
return status
}
func (a *App) GetMyAnimeListAnime(id int) MALAnime {
fmt.Println(id)
malUrl := "https://api.myanimelist.net/v2/anime/" + strconv.Itoa(id) + "?fields=id,title,main_picture,alternative_titles,start_date,end_date,synopsis,mean,rank,popularity,num_list_users,num_scoring_users,nsfw,genres,created_at,updated_at,media_type,status,my_list_status,num_episodes,start_season,broadcast,source,average_episode_duration,rating,pictures,background,related_anime,recommendations,studios,statistics"
respBody := MALHelper("GET", malUrl, nil)
respBody, respStatus := MALHelper("GET", malUrl, nil)
var malAnime MALAnime
err := json.Unmarshal(respBody, &malAnime)
if err != nil {
log.Printf("Failed to unmarshal json response, %s\n", err)
if respStatus == "200 OK" {
err := json.Unmarshal(respBody, &malAnime)
if err != nil {
log.Printf("Failed to unmarshal json response, %s\n", err)
}
}
return malAnime
}
func (a *App) DeleteMyAnimeListEntry(id int) bool {
malUrl := "https://api.myanimelist.net/v2/anime/" + strconv.Itoa(id) + "/my_list_status"
_, respStatus := MALHelper("DELETE", malUrl, nil)
if respStatus == "200 OK" {
return true
} else {
return false
}
}

View File

@ -224,6 +224,77 @@ func getMyAnimeListAuthorizationToken(content string, verifier *CodeVerifier) My
return post
}
func refreshMyAnimeListAuthorizationToken() {
dataForURLs := struct {
GrantType string `json:"grant_type"`
RefreshToken string `json:"refresh_token"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURI string `json:"redirect_uri"`
}{
GrantType: "refresh_token",
RefreshToken: myAnimeListJwt.RefreshToken,
ClientID: Environment.MAL_CLIENT_ID,
ClientSecret: Environment.MAL_CLIENT_SECRET,
RedirectURI: Environment.MAL_CALLBACK_URI,
}
data := url.Values{}
data.Set("grant_type", dataForURLs.GrantType)
data.Set("refresh_token", dataForURLs.RefreshToken)
data.Set("client_id", dataForURLs.ClientID)
data.Set("client_secret", dataForURLs.ClientSecret)
data.Set("redirect_uri", dataForURLs.RedirectURI)
response, err := http.NewRequest("POST", "https://myanimelist.net/v1/oauth2/token", 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")
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)
err = json.Unmarshal(returnedBody, &myAnimeListJwt)
if err != nil {
log.Printf("Failed at unmarshal, %s\n", err)
}
_ = myAnimeListRing.Set(keyring.Item{
Key: "MyAnimeListTokenType",
Data: []byte(myAnimeListJwt.TokenType),
})
_ = myAnimeListRing.Set(keyring.Item{
Key: "MyAnimeListExpiresIn",
Data: []byte(strconv.Itoa(myAnimeListJwt.ExpiresIn)),
})
_ = myAnimeListRing.Set(keyring.Item{
Key: "MyAnimeListAccessToken",
Data: []byte(myAnimeListJwt.AccessToken),
})
_ = myAnimeListRing.Set(keyring.Item{
Key: "MyAnimeListRefreshToken",
Data: []byte(myAnimeListJwt.RefreshToken),
})
_, err = runtime.MessageDialog(*wailsContext, runtime.MessageDialogOptions{
Title: "MyAnimeList Authorization",
Message: "It is now safe to close your browser tab",
})
if err != nil {
fmt.Println(err)
}
return
}
func (a *App) GetMyAnimeListLoggedInUser() MyAnimeListUser {
a.MyAnimeListLogin()

View File

@ -289,3 +289,30 @@ func (a *App) SimklSearch(aniListAnime MediaList) SimklAnime {
return result
}
func (a *App) SimklSyncRemove(anime SimklAnime) bool {
url := "https://api.simkl.com/sync/history/remove"
var show = SimklShowStatus{
Title: anime.Show.Title,
Ids: Ids{
Simkl: anime.Show.Ids.Simkl,
Mal: anime.Show.Ids.Mal,
Anilist: anime.Show.Ids.AniList,
},
}
respBody := SimklHelper("POST", url, show)
var success SimklDeleteType
err := json.Unmarshal(respBody, &success)
if err != nil {
log.Printf("Failed at unmarshal, %s\n", err)
}
if success.Deleted.Shows >= 1 {
return true
} else {
return false
}
}

View File

@ -119,3 +119,15 @@ type SimklSearchType []struct {
TotalEpisodes int `json:"total_episodes"`
AnimeType string `json:"anime_type"`
}
type SimklDeleteType struct {
Deleted struct {
Movies int `json:"movies"`
Shows int `json:"shows"`
Episodes int `json:"episodes"`
} `json:"deleted"`
NotFound struct {
Movies []interface{} `json:"movies"`
Shows []interface{} `json:"shows"`
} `json:"not_found"`
}

View File

@ -93,7 +93,7 @@ body:graphql {
body:graphql:vars {
{
"userId": 413504,
"mediaId": 168345,
"mediaId": 170998,
"listType": "ANIME"
}
}

View File

@ -53,7 +53,7 @@ body:graphql {
body:graphql:vars {
{
"search": "dungeon people",
"search": "dan-da-dan",
"listType": "ANIME"
}
}

View File

@ -5,7 +5,7 @@ meta {
}
get {
url: https://api.myanimelist.net/v2/anime/53580?fields=id,title,main_picture,alternative_titles,start_date,end_date,synopsis,mean,rank,popularity,num_list_users,num_scoring_users,nsfw,genres,created_at,updated_at,media_type,status,my_list_status,num_episodes,start_season,broadcast,source,average_episode_duration,rating,pictures,background,related_anime,recommendations,studios,statistics
url: https://api.myanimelist.net/v2/anime/57380?fields=id,title,main_picture,alternative_titles,start_date,end_date,synopsis,mean,rank,popularity,num_list_users,num_scoring_users,nsfw,genres,created_at,updated_at,media_type,status,my_list_status,num_episodes,start_season,broadcast,source,average_episode_duration,rating,pictures,background,related_anime,recommendations,studios,statistics
body: none
auth: bearer
}

View File

@ -8,11 +8,11 @@ vars {
MAL_CALLBACK_URI: {{process.env.MAL_CALLBACK_URI}}
}
vars:secret [
ANILIST_ACCESS_TOKEN,
code,
SIMKL_AUTH_TOKEN,
ANILIST_ACCESS_TOKEN,
MAL_CODE,
MAL_VERIFIER,
MAL_USER,
MAL_ACCESS_TOKEN
~MAL_ACCESS_TOKEN
]

View File

@ -20,10 +20,11 @@
import type {AniListUpdateVariables} from "../anilist/types/AniListTypes";
import convertDateStringToAniList from "../helperFunctions/convertDateStringToAniList";
import {
AniListUpdateEntry,
AniListDeleteEntry,
AniListUpdateEntry, DeleteMyAnimeListEntry,
MyAnimeListUpdate,
SimklSyncEpisodes,
SimklSyncRating,
SimklSyncRating, SimklSyncRemove,
SimklSyncStatus
} from "../../wailsjs/go/main/App";
import {AddAnimeServiceToTable} from "../helperModules/AddAnimeServiceToTable.svelte";
@ -286,6 +287,16 @@
submitSuccess.set(true)
setTimeout(() => submitSuccess.set(false), 2000)
}
const deleteEntries = async () => {
submitting.set(true)
if (isAniListLoggedIn && currentAniListAnime.data.MediaList.mediaId !== 0) await AniListDeleteEntry(currentAniListAnime.data.MediaList.id)
if (malLoggedIn && currentMalAnime.id !== 0) await DeleteMyAnimeListEntry(currentMalAnime.id)
if (simklLoggedIn && currentSimklAnime.show.ids.simkl !== 0) await SimklSyncRemove(currentSimklAnime)
submitting.set(false)
submitSuccess.set(true)
setTimeout(() => submitSuccess.set(false), 2000)
}
</script>
<form on:submit|preventDefault={handleSubmit} class="container py-10">
@ -420,7 +431,27 @@
<AnimeTable/>
<div class="bg-white rounded-lg shadow max-w-4-4 dark:bg-gray-800">
<div class="bg-white flex rounded-lg shadow max-w-4-4 dark:bg-gray-800">
<div class="w-full mx-auto max-w-screen-xl p-4 md:flex md:items-center md:justify-start">
<Button disabled={isSubmitting}
id="delete-button"
class="text-white bg-red-700 {$submitSuccess ?
'dark:bg-green-600 hover:bg-green-800 dark:hover:bg-green-700 focus:ring-4 focus:ring-green-300 dark:focus:ring-green-800' :
'dark:bg-red-600 hover:bg-red-800 dark:hover:bg-red-700 focus:ring-4 focus:ring-red-300 dark:focus:ring-red-800'
} font-medium
rounded-lg text-sm px-5 py-2.5 me-2 mb-2 focus:outline-none"
on:click={deleteEntries}>
<svg id="submit-loader" aria-hidden="true" role="status"
class="{isSubmitting ? 'inline': 'hidden'} w-4 h-4 me-3 text-white animate-spin"
viewBox="0 0 100 101" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
fill="#E5E7EB"/>
<path d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
fill="currentColor"/>
</svg>
Delete Entries
</Button>
</div>
<div class="w-full mx-auto max-w-screen-xl p-4 md:flex md:items-center md:justify-end">
<Button disabled={isSubmitting}
id="sync-button"

View File

@ -2,6 +2,8 @@
// This file is automatically generated. DO NOT EDIT
import {main} from '../models';
export function AniListDeleteEntry(arg1:number):Promise<main.DeleteAniListReturn>;
export function AniListLogin():Promise<void>;
export function AniListSearch(arg1:string):Promise<any>;
@ -14,6 +16,8 @@ export function CheckIfMyAnimeListLoggedIn():Promise<boolean>;
export function CheckIfSimklLoggedIn():Promise<boolean>;
export function DeleteMyAnimeListEntry(arg1:number):Promise<boolean>;
export function GetAniListItem(arg1:number,arg2:boolean):Promise<main.AniListGetSingleAnime>;
export function GetAniListLoggedInUser():Promise<main.AniListUser>;
@ -48,4 +52,6 @@ export function SimklSyncEpisodes(arg1:main.SimklAnime,arg2:number):Promise<main
export function SimklSyncRating(arg1:main.SimklAnime,arg2:number):Promise<main.SimklAnime>;
export function SimklSyncRemove(arg1:main.SimklAnime):Promise<boolean>;
export function SimklSyncStatus(arg1:main.SimklAnime,arg2:string):Promise<main.SimklAnime>;

View File

@ -2,6 +2,10 @@
// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
// This file is automatically generated. DO NOT EDIT
export function AniListDeleteEntry(arg1) {
return window['go']['main']['App']['AniListDeleteEntry'](arg1);
}
export function AniListLogin() {
return window['go']['main']['App']['AniListLogin']();
}
@ -26,6 +30,10 @@ export function CheckIfSimklLoggedIn() {
return window['go']['main']['App']['CheckIfSimklLoggedIn']();
}
export function DeleteMyAnimeListEntry(arg1) {
return window['go']['main']['App']['DeleteMyAnimeListEntry'](arg1);
}
export function GetAniListItem(arg1, arg2) {
return window['go']['main']['App']['GetAniListItem'](arg1, arg2);
}
@ -94,6 +102,10 @@ export function SimklSyncRating(arg1, arg2) {
return window['go']['main']['App']['SimklSyncRating'](arg1, arg2);
}
export function SimklSyncRemove(arg1) {
return window['go']['main']['App']['SimklSyncRemove'](arg1);
}
export function SimklSyncStatus(arg1, arg2) {
return window['go']['main']['App']['SimklSyncStatus'](arg1, arg2);
}

View File

@ -168,6 +168,37 @@ export namespace main {
}
}
export class DeleteAniListReturn {
// Go type: struct { DeleteMediaListEntry struct { Deleted bool "json:\"deleted\"" } "json:\"DeleteMediaListEntry\"" }
data: any;
static createFrom(source: any = {}) {
return new DeleteAniListReturn(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.data = this.convertValues(source["data"], Object);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
export class MALAnime {
id: id;
title: title;