Skip to content

Commit 7b24117

Browse files
committed
feat(settings): list and reset anisette data from the engine
Drive the Advanced settings anisette list from `plumesign anisette list` instead of the account list, so data left behind by a failed login (an account missing from accounts.json) can still be managed. Render the accounts as a saved-source style list. Accounts present in accounts.json get a red "Reset" action that runs `plumesign anisette reset`; accounts that are only present in the engine's anisette data are marked orphaned and get a red "Delete" action that runs `plumesign anisette remove`. Show "-" when the team ID is empty, and update the anisette server tip to suggest resetting or deleting the account data when requests still fail.
1 parent a0b909a commit 7b24117

11 files changed

Lines changed: 494 additions & 63 deletions

File tree

‎internal/manager/anisette.go‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package manager
33
import (
44
"errors"
55
"net/url"
6+
"regexp"
67
"strings"
78

89
"github.com/bitxeno/atvloadly/internal/exec"
@@ -28,6 +29,62 @@ func ResetAnisette(email string) error {
2829
return nil
2930
}
3031

32+
// RemoveAnisette deletes an account's Anisette data directory through the
33+
// engine. It is used for data left behind by an account that no longer exists
34+
// in the account list: there is no account to re-login for, so the leftover
35+
// data is deleted outright instead of reset.
36+
func RemoveAnisette(email string) error {
37+
email = strings.TrimSpace(email)
38+
if email == "" {
39+
return errors.New("account email is required")
40+
}
41+
42+
if _, err := exec.NewCommand("plumesign", "anisette", "remove", "-u", email).CombinedOutput(); err != nil {
43+
log.Err(err).Msgf("Error removing anisette data for %s", email)
44+
return err
45+
}
46+
log.Infof("Removed anisette data for %s", email)
47+
return nil
48+
}
49+
50+
// AnisetteAccount is one account that has Anisette data stored on disk. The
51+
// engine provisions this data per account, and a failed login can leave data
52+
// behind for an account that is no longer in the account list, so the engine's
53+
// anisette list — not the account list — decides which accounts can be reset.
54+
type AnisetteAccount struct {
55+
Email string `json:"email"`
56+
Name string `json:"name"`
57+
TeamID string `json:"team_id"`
58+
// Orphan is true when the account is not in the account list (accounts.json).
59+
// Its data is leftover from a failed or removed login, so it can only be
60+
// deleted, not reset.
61+
Orphan bool `json:"orphan"`
62+
}
63+
64+
// AnisetteAccounts lists the accounts that have Anisette data stored, by asking
65+
// the engine. Unlike the account list, this includes accounts whose login
66+
// failed but whose data directory still exists; those are marked orphaned so
67+
// the caller knows they can only be deleted.
68+
func AnisetteAccounts() ([]AnisetteAccount, error) {
69+
output, err := exec.NewCommand("plumesign", "anisette", "list").CombinedOutput()
70+
if err != nil {
71+
log.Err(err).Msg("Error listing anisette accounts")
72+
return nil, err
73+
}
74+
accounts := parseAnisetteAccounts(string(output))
75+
76+
known := map[string]bool{}
77+
if stored, err := accountManager.GetAccounts(); err == nil {
78+
for email := range stored.Accounts {
79+
known[email] = true
80+
}
81+
}
82+
for i := range accounts {
83+
accounts[i].Orphan = !known[accounts[i].Email]
84+
}
85+
return accounts, nil
86+
}
87+
3188
// AnisetteServerState is the anisette server the engine provisions against,
3289
// with whether it is the engine default rather than a configured one.
3390
type AnisetteServerState struct {
@@ -111,3 +168,58 @@ func parseAnisetteServer(output string) (string, bool) {
111168
}
112169
return "", false
113170
}
171+
172+
// anisetteAccountRow splits one row of `plumesign anisette list` on runs of two
173+
// or more spaces. The table aligns its columns with spaces, but a value such as
174+
// the NAME field can itself contain a single space, so only a run of spaces is
175+
// treated as the column separator. This keeps the email intact even when a name
176+
// contains spaces.
177+
var anisetteAccountRow = regexp.MustCompile(`\s{2,}`)
178+
179+
// parseAnisetteAccounts reads the fixed-width table printed by
180+
// `plumesign anisette list`:
181+
//
182+
// Accounts with Anisette data:
183+
// ACCOUNT NAME TEAM ID
184+
// user@example.com wu 8245MZ34WA
185+
// other@example.com - -
186+
//
187+
// The first line is a heading and the second is the column header; the rest are
188+
// rows. A blank NAME or TEAM ID is printed as "-", which is normalized to empty.
189+
// An account is kept as long as its email column is non-empty, so data left
190+
// behind by a failed login still appears.
191+
func parseAnisetteAccounts(output string) []AnisetteAccount {
192+
accounts := []AnisetteAccount{}
193+
for _, line := range strings.Split(output, "\n") {
194+
line = strings.TrimRight(line, "\r")
195+
if strings.TrimSpace(line) == "" {
196+
continue
197+
}
198+
fields := anisetteAccountRow.Split(strings.TrimSpace(line), -1)
199+
// Skip the heading and the column header: a data row starts with an
200+
// email, which always contains "@".
201+
if len(fields) < 1 || !strings.Contains(fields[0], "@") {
202+
continue
203+
}
204+
205+
account := AnisetteAccount{Email: strings.TrimSpace(fields[0])}
206+
if len(fields) > 1 {
207+
account.Name = normalizeAnisetteCell(fields[1])
208+
}
209+
if len(fields) > 2 {
210+
account.TeamID = normalizeAnisetteCell(fields[2])
211+
}
212+
accounts = append(accounts, account)
213+
}
214+
return accounts
215+
}
216+
217+
// normalizeAnisetteCell trims a cell and maps the engine's "-" placeholder for
218+
// an empty value to an empty string.
219+
func normalizeAnisetteCell(value string) string {
220+
value = strings.TrimSpace(value)
221+
if value == "-" {
222+
return ""
223+
}
224+
return value
225+
}

‎internal/manager/anisette_test.go‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,121 @@ func TestResetAnisetteReportsEngineFailure(t *testing.T) {
6161
}
6262
}
6363

64+
// fakeAnisetteListEngine puts a plumesign on PATH that prints table on stdout
65+
// for `anisette list` and exits with exitCode.
66+
func fakeAnisetteListEngine(t *testing.T, table string, exitCode string) {
67+
t.Helper()
68+
dir := t.TempDir()
69+
script := "#!/bin/sh\n" +
70+
"cat <<'EOF'\n" + table + "\nEOF\n" +
71+
"exit " + exitCode + "\n"
72+
if err := os.WriteFile(filepath.Join(dir, "plumesign"), []byte(script), 0o755); err != nil {
73+
t.Fatal(err)
74+
}
75+
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
76+
}
77+
78+
// The engine's anisette list is the source of reset targets, so accounts whose
79+
// login failed but whose data directory still exists must show up here even
80+
// though they are absent from the account list. Empty NAME/TEAM ID ("-") is
81+
// normalized to an empty value, and an account missing from accounts.json is
82+
// marked orphaned.
83+
func TestAnisetteAccountsParsesEngineList(t *testing.T) {
84+
dataDir := setSideloadDataDir(t)
85+
plumeDir := filepath.Dir(dataDir)
86+
if err := os.MkdirAll(plumeDir, 0o755); err != nil {
87+
t.Fatal(err)
88+
}
89+
writeJSON(t, plumeDir, "accounts.json",
90+
`{"accounts":{"user@example.com":{"email":"user@example.com","team_id":"8245MZ34WA"}}}`)
91+
fakeAnisetteListEngine(t, `Accounts with Anisette data:
92+
ACCOUNT NAME TEAM ID
93+
user@example.com wu 8245MZ34WA
94+
orphan@example.com - -`, "0")
95+
96+
accounts, err := AnisetteAccounts()
97+
if err != nil {
98+
t.Fatalf("AnisetteAccounts() error = %v", err)
99+
}
100+
101+
if len(accounts) != 2 {
102+
t.Fatalf("got %d accounts, want 2: %+v", len(accounts), accounts)
103+
}
104+
if accounts[0].Email != "user@example.com" || accounts[0].Name != "wu" || accounts[0].TeamID != "8245MZ34WA" {
105+
t.Errorf("first account = %+v", accounts[0])
106+
}
107+
if accounts[0].Orphan {
108+
t.Error("an account in accounts.json was marked orphaned")
109+
}
110+
if accounts[1].Email != "orphan@example.com" {
111+
t.Errorf("orphan account email = %q, want orphan@example.com", accounts[1].Email)
112+
}
113+
if accounts[1].Name != "" || accounts[1].TeamID != "" {
114+
t.Errorf("orphan account placeholders not normalized: %+v", accounts[1])
115+
}
116+
if !accounts[1].Orphan {
117+
t.Error("an account missing from accounts.json was not marked orphaned")
118+
}
119+
}
120+
121+
// Deleting leftover anisette data for an account no longer in the list runs the
122+
// engine's remove command for that account.
123+
func TestRemoveAnisetteRunsEngineCommandForAccount(t *testing.T) {
124+
record := fakeAnisetteEngine(t, "0")
125+
126+
if err := RemoveAnisette("orphan@example.com"); err != nil {
127+
t.Fatalf("RemoveAnisette() error = %v", err)
128+
}
129+
130+
want := "anisette remove -u orphan@example.com"
131+
if got := strings.Join(recordedArgs(t, record), " "); got != want {
132+
t.Errorf("arguments = %q, want %q", got, want)
133+
}
134+
}
135+
136+
// A blank account names no Anisette data, so remove is rejected before any
137+
// command runs.
138+
func TestRemoveAnisetteRequiresAccount(t *testing.T) {
139+
record := fakeAnisetteEngine(t, "0")
140+
141+
if err := RemoveAnisette(" "); err == nil {
142+
t.Fatal("RemoveAnisette() error = nil, want an error")
143+
}
144+
145+
if _, err := os.Stat(record); !os.IsNotExist(err) {
146+
t.Errorf("the engine was run for a blank account (stat err = %v)", err)
147+
}
148+
}
149+
150+
// A failing engine surfaces its error instead of an empty list that would hide
151+
// the problem.
152+
func TestAnisetteAccountsReportsEngineFailure(t *testing.T) {
153+
fakeAnisetteListEngine(t, "Accounts with Anisette data:", "1")
154+
155+
if _, err := AnisetteAccounts(); err == nil {
156+
t.Fatal("AnisetteAccounts() error = nil, want an error")
157+
}
158+
}
159+
160+
// A NAME that contains a single space stays in one column; only runs of two or
161+
// more spaces separate the columns.
162+
func TestParseAnisetteAccountsKeepsSingleSpaceInName(t *testing.T) {
163+
table := `Accounts with Anisette data:
164+
ACCOUNT NAME TEAM ID
165+
user@example.com John Doe 8245MZ34WA`
166+
167+
accounts := parseAnisetteAccounts(table)
168+
if len(accounts) != 1 {
169+
t.Fatalf("got %d accounts, want 1: %+v", len(accounts), accounts)
170+
}
171+
if accounts[0].Name != "John Doe" {
172+
t.Errorf("name = %q, want %q", accounts[0].Name, "John Doe")
173+
}
174+
if accounts[0].TeamID != "8245MZ34WA" {
175+
t.Errorf("team id = %q, want %q", accounts[0].TeamID, "8245MZ34WA")
176+
}
177+
}
178+
64179
// The engine reports the active anisette server on stdout with a log prefix;
65180
// the manager picks the URL out of that line.
66181
func TestAnisetteServerReadsEngineOutput(t *testing.T) {

‎locales/en.json‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -521,13 +521,14 @@
521521
"update_coreadi_confirm": "Are you sure you want update the CoreADI libraries?",
522522
"anisette_server": "Anisette Server",
523523
"anisette_server_default_tag": "Default",
524-
"anisette_server_tips": "Leave empty to use the default server. Changing the server invalidates existing anisette data; reset the account if requests start failing.",
524+
"anisette_server_tips": "Leave empty to use the default server. If requests still fail after changing the server, try resetting or deleting the Anisette data of the account.",
525525
"save": "Save",
526-
"reset_anisette": "Reset Anisette Data",
527-
"reset_anisette_select": "Select an account",
528-
"reset_anisette_empty": "Anisette data is reset per account. Add an Apple ID account first.",
526+
"reset_anisette": "Anisette Data",
527+
"reset_anisette_empty": "No account has Anisette data stored.",
529528
"reset_anisette_confirm": "Are you sure you want to reset the Anisette data of {{email}}? A new device identity is generated on its next use, so the account must log in again.",
529+
"remove_anisette_confirm": "This account is no longer signed in. Are you sure you want to delete its leftover Anisette data?",
530530
"reset": "Reset",
531+
"delete": "Delete",
531532
"cancel": "Cancel",
532533
"confirm": "Confirm",
533534
"toast": {
@@ -536,6 +537,8 @@
536537
"failed": "Update failed",
537538
"reset_success": "Anisette data of {{email}} reset",
538539
"reset_failed": "Reset failed",
540+
"remove_success": "Anisette data of {{email}} deleted",
541+
"remove_failed": "Delete failed",
539542
"server_success": "Anisette server saved",
540543
"server_failed": "Saving anisette server failed"
541544
}

‎locales/sr-Latn.json‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -518,13 +518,14 @@
518518
"update_coreadi_confirm": "Da li ste sigurni da želite da ažurirate CoreADI biblioteke?",
519519
"anisette_server": "Anisette server",
520520
"anisette_server_default_tag": "Podrazumevani",
521-
"anisette_server_tips": "Ostavite prazno za podrazumevani server. Promena servera čini postojeće Anisette podatke nevažećim; resetujte nalog ako zahtevi počnu da otkazuju.",
521+
"anisette_server_tips": "Ostavite prazno za podrazumevani server. Ako zahtevi i dalje ne uspevaju nakon promene servera, pokušajte da resetujete ili obrišete Anisette podatke naloga.",
522522
"save": "Sačuvaj",
523-
"reset_anisette": "Resetuj Anisette podatke",
524-
"reset_anisette_select": "Izaberite nalog",
525-
"reset_anisette_empty": "Anisette podaci se resetuju po nalogu. Prvo dodajte Apple ID nalog.",
523+
"reset_anisette": "Anisette podaci",
524+
"reset_anisette_empty": "Nijedan nalog nema sačuvane Anisette podatke.",
526525
"reset_anisette_confirm": "Da li ste sigurni da želite da resetujete Anisette podatke za {{email}}? Novi identitet uređaja biće kreiran pri sledećem korišćenju, pa se nalog mora ponovo prijaviti.",
526+
"remove_anisette_confirm": "Ovaj nalog više nije prijavljen. Da li ste sigurni da želite da obrišete njegove preostale Anisette podatke?",
527527
"reset": "Resetuj",
528+
"delete": "Obriši",
528529
"cancel": "Otkaži",
529530
"confirm": "Potvrdi",
530531
"toast": {
@@ -533,6 +534,8 @@
533534
"failed": "Ažuriranje nije uspelo",
534535
"reset_success": "Anisette podaci za {{email}} su resetovani",
535536
"reset_failed": "Resetovanje nije uspelo",
537+
"remove_success": "Anisette podaci za {{email}} su obrisani",
538+
"remove_failed": "Brisanje nije uspelo",
536539
"server_success": "Anisette server je sačuvan",
537540
"server_failed": "Čuvanje Anisette servera nije uspelo"
538541
}

‎locales/sr.json‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -518,13 +518,14 @@
518518
"update_coreadi_confirm": "Да ли сте сигурни да желите да ажурирате CoreADI библиотеке?",
519519
"anisette_server": "Anisette сервер",
520520
"anisette_server_default_tag": "Подразумевани",
521-
"anisette_server_tips": "Оставите празно за подразумевани сервер. Промена сервера чини постојеће Anisette податке неважећим; ресетујте налог ако захтеви почну да отказују.",
521+
"anisette_server_tips": "Оставите празно за подразумевани сервер. Ако захтеви и даље не успевају након промене сервера, покушајте да ресетујете или обришете Anisette податке налога.",
522522
"save": "Сачувај",
523-
"reset_anisette": "Ресетуј Anisette податке",
524-
"reset_anisette_select": "Изаберите налог",
525-
"reset_anisette_empty": "Anisette подаци се ресетују по налогу. Прво додајте Apple ID налог.",
523+
"reset_anisette": "Anisette подаци",
524+
"reset_anisette_empty": "Ниједан налог нема сачуване Anisette податке.",
526525
"reset_anisette_confirm": "Да ли сте сигурни да желите да ресетујете Anisette податке за {{email}}? Нови идентитет уређаја биће креиран при следећем коришћењу, па се налог мора поново пријавити.",
526+
"remove_anisette_confirm": "Овај налог више није пријављен. Да ли сте сигурни да желите да обришете његове преостале Anisette податке?",
527527
"reset": "Ресетуј",
528+
"delete": "Обриши",
528529
"cancel": "Откажи",
529530
"confirm": "Потврди",
530531
"toast": {
@@ -533,6 +534,8 @@
533534
"failed": "Ажурирање није успело",
534535
"reset_success": "Anisette подаци за {{email}} су ресетовани",
535536
"reset_failed": "Ресетовање није успело",
537+
"remove_success": "Anisette подаци за {{email}} су обрисани",
538+
"remove_failed": "Брисање није успело",
536539
"server_success": "Anisette сервер је сачуван",
537540
"server_failed": "Чување Anisette сервера није успело"
538541
}

‎locales/sv.json‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -518,13 +518,14 @@
518518
"update_coreadi_confirm": "Vill du verkligen uppdatera CoreADI-biblioteken?",
519519
"anisette_server": "Anisette-server",
520520
"anisette_server_default_tag": "Standard",
521-
"anisette_server_tips": "Lämna tomt för att använda standardservern. Byt av server gör befintlig Anisette-data ogiltig; återställ kontot om anropen börjar misslyckas.",
521+
"anisette_server_tips": "Lämna tomt för att använda standardservern. Om anropen fortfarande misslyckas efter att du bytt server, försök återställa eller ta bort kontots Anisette-data.",
522522
"save": "Spara",
523-
"reset_anisette": "Återställ Anisette-data",
524-
"reset_anisette_select": "Välj ett konto",
525-
"reset_anisette_empty": "Anisette-data återställs per konto. Lägg till ett Apple ID-konto först.",
523+
"reset_anisette": "Anisette-data",
524+
"reset_anisette_empty": "Inget konto har sparad Anisette-data.",
526525
"reset_anisette_confirm": "Vill du verkligen återställa Anisette-data för {{email}}? En ny enhetsidentitet skapas vid nästa användning, så kontot måste logga in igen.",
526+
"remove_anisette_confirm": "Det här kontot är inte längre inloggat. Vill du ta bort dess kvarvarande Anisette-data?",
527527
"reset": "Återställ",
528+
"delete": "Ta bort",
528529
"cancel": "Avbryt",
529530
"confirm": "Bekräfta",
530531
"toast": {
@@ -533,6 +534,8 @@
533534
"failed": "Uppdateringen misslyckades",
534535
"reset_success": "Anisette-data för {{email}} har återställts",
535536
"reset_failed": "Återställningen misslyckades",
537+
"remove_success": "Anisette-data för {{email}} har tagits bort",
538+
"remove_failed": "Borttagningen misslyckades",
536539
"server_success": "Anisette-servern har sparats",
537540
"server_failed": "Det gick inte att spara Anisette-servern"
538541
}

‎locales/zh_cn.json‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -521,13 +521,14 @@
521521
"update_coreadi_confirm": "确认要下载并更新 CoreADI 库文件吗?",
522522
"anisette_server": "Anisette 服务器",
523523
"anisette_server_default_tag": "默认",
524-
"anisette_server_tips": "留空使用默认服务器。更换服务器后已有的 Anisette 数据会失效;如请求开始失败,请重置对应帐号。",
524+
"anisette_server_tips": "留空使用默认服务器。如果更换服务器后还是请求失败,请尝试重置/删除对应帐号的 Anisette 数据。",
525525
"save": "保存",
526-
"reset_anisette": "重置 Anisette 数据",
527-
"reset_anisette_select": "请选择帐号",
528-
"reset_anisette_empty": "Anisette 数据按帐号重置,请先添加 Apple ID 帐号。",
526+
"reset_anisette": "Anisette 数据",
527+
"reset_anisette_empty": "没有保存 Anisette 数据的帐号。",
529528
"reset_anisette_confirm": "确认要重置 {{email}} 的 Anisette 数据吗?下次使用该帐号时将生成新的设备身份,需要重新登录。",
529+
"remove_anisette_confirm": "该帐号已不在登录列表中,确认要删除它残留的 Anisette 数据吗?",
530530
"reset": "重置",
531+
"delete": "删除",
531532
"cancel": "取消",
532533
"confirm": "确认",
533534
"toast": {
@@ -536,6 +537,8 @@
536537
"failed": "更新失败",
537538
"reset_success": "已重置 {{email}} 的 Anisette 数据",
538539
"reset_failed": "重置失败",
540+
"remove_success": "已删除 {{email}} 的 Anisette 数据",
541+
"remove_failed": "删除失败",
539542
"server_success": "Anisette 服务器已保存",
540543
"server_failed": "保存 Anisette 服务器失败"
541544
}

0 commit comments

Comments
 (0)
⌂ 换网址