gui: a custom provider's icon from an image URL, or its name's letters (usrname1833)

usrname1833 on Discord: many sites serve no {HOST}/favicon.ico, so a custom
provider's icon came out wrong or missing, with no way to give it one.

The provider editor's icon row now has Get icon, a pull-down that opens the
app's own menu (no native select) headed Icon:
- Automatic: the site's icon from the base URL, as before.
- Image URL…: a url box under the row, focused; Enter fetches the address,
  Escape puts it away and gives focus back to Get icon.
- Letter icon: the name's first letters on a coloured tile (letterIcon).

POST /api/icons/url (provider.IconFromURL) fetches the typed address the way
a favicon is fetched: guardClient (public addresses only), iconURL (https,
public host, no userinfo), fetchIcon's 15s timeout, MaxIcon 1 MB and the
type sniffed to PNG/JPEG/GIF/WebP/ICO/SVG. An address that can't be used
gives the letter tile with a warn note saying why, and the box stays for
another try. The old From the website button and its two strings are gone;
eight new strings in zh, zh-TW, ja and de. app.js +1,484 bytes to
1,309,847 (budget 1,316,874), core 1,534,839 (1,539,856); no budget raised.

Run at this tree (rebased on origin/main e484b1e93), on mote:
- gofmt -l clean; go vet ./internal/provider ./internal/gui on darwin,
  linux (nogui) and windows; go build ./..., linux nogui and windows builds.
- go test ./internal/provider: ok (TestIconFromURL new: a PNG kept; HTML,
  404, over 1 MB and a stalled server each give the letters with why; http,
  loopback, localhost and userinfo addresses refused; an empty name takes
  the base's site label).
- go test -run "Budget|Icon|Favicon|Provider|Settings" ./internal/gui:
  TestCoreScriptBudget ok; TestSettingsSaveKeepsWhatItDoesNotSend red, the
  same at a clean e484b1e93 (#4514).
- node --test icon-url (new), models-add-and-icons, i18n-keys: 27 of 28.
  icon-url is Chromium and WebKit x 420 and 1100 x en, zh, zh-TW, ja, de,
  20 of 20 (menu, posted bodies, warn note, Escape focus, no scroll, no
  spill at 420, Save sends the icon). The one red is i18n-keys' "Unmarked"
  in plugins/routing, the same at a clean e484b1e93 (#4524).
Screenshots of the menu and the warn note checked in both engines.

Broken by hand: no letter fallback on a failed fetch -> TestIconFromURL red
('"" isn't stored'); the exported path skipping iconURL -> red for all four
refused addresses; icon-url.test.cjs on main's app.js and i18n.js -> 0 of
10 in Chromium (no Get icon).

Not tried: a real image address on a live site from the built app, and the
whole GUI suite (mote was running another session's full suite).
This commit is contained in:
yetone
2026-10-31 19:54:28 +08:00
parent 5cc2eea2fe
commit 1dc22a37c5
6 changed files with 346 additions and 21 deletions
+40 -13
View File
@@ -8279,24 +8279,40 @@ function iconPicker(ed) {
};
const choose = el("button", "text", t("Choose a picture…"));
choose.onclick = () => file.click();
// the site's own icon, looked for from the base URL typed above
const site = el("button", "text", t("From the website"));
site.title = t("Look for the icon of the site the base URL is on");
site.onclick = async () => {
const base = draft[apiField[draft.api]] || draft.chat || draft.responses || draft.anthropic || "";
// the site's own icon (as before), a picture's address, or the name's
// letters on a tile: many sites have no /favicon.ico (usrname1833)
const base = () => draft[apiField[draft.api]] || draft.chat || draft.responses || draft.anthropic || "";
const site = el("button", "text", t("Get icon"));
site.setAttribute("aria-haspopup", "menu");
site.setAttribute("aria-expanded", "false");
site.append(svg(CHEV, 11, 1.7));
const get = async (path, body) => {
site.disabled = true;
site.textContent = t("Looking…");
let note = "", kind = "warn";
try {
const data = await api("icons/favicon", { url: base, name: draft.name || "" });
const data = await api(path, { name: draft.name || "", ...body });
draft.icon = data.icon;
editorError("");
draw();
syncHead();
if (data.failed) note = t("That picture couldn't be used, so the icon is the name's letters: {why}", { why: data.failed });
asking = !!data.failed;
} catch (e) {
editorError(e.message);
site.disabled = false;
site.textContent = t("From the website");
note = e.message;
kind = "err";
}
draw();
syncHead();
editorError(note, kind);
};
site.onclick = (e) => {
e.stopPropagation();
openProtoMenu(site, [
{ v: "site", name: "Automatic", note: "The site's own icon, looked for from the base URL" },
{ v: "url", name: "Image URL…", note: "A PNG, JPEG, GIF, WebP, ICO or SVG at a public https address" },
{ v: "letter", name: "Letter icon", note: "The name's first letters on a coloured tile" },
], "", (v) => {
if (v === "url") { asking = true; draw(); return box.querySelector(".icon-url").focus({ preventScroll: true }); }
v === "site" ? get("icons/favicon", { url: base() }) : get("icons/url", { base: base() });
}, "Icon");
};
const builtin = el("button", "text", t("Built-in icons"));
builtin.onclick = () => { open = !open; draw(); };
@@ -8306,6 +8322,17 @@ function iconPicker(ed) {
reset.onclick = () => { draft.icon = ""; draw(); syncHead(); };
box.append(reset);
}
if (asking) {
const u = input(typed, "https://example.com/icon.png", "url");
u.className = "icon-url";
u.setAttribute("aria-label", t("Image URL"));
u.onkeydown = (e) => {
e.stopPropagation();
if (e.key === "Escape") { asking = false; draw(); box.querySelector("[aria-haspopup]").focus({ preventScroll: true }); }
else if (e.key === "Enter" && (typed = u.value.trim()) && !site.disabled) get("icons/url", { url: typed, base: base() });
};
box.append(u);
}
if (open) {
const grid = el("div", "icon-grid");
const names = [...new Set([...(providers.presets || []).map((p) => p.icon), ...MORE_ICONS].filter((n) => n && n !== "generic"))]
@@ -8329,7 +8356,7 @@ function iconPicker(ed) {
find.oninput();
}
};
let open = false, seek = "";
let open = false, seek = "", asking = false, typed = "";
// the dialog's title shows the icon too
const syncHead = () => {
const old = ed.querySelector(".ehead .ic");
+32 -8
View File
@@ -1465,8 +1465,14 @@ const I18N = {
"Choose a picture…": "选择图片…",
"Built-in icons": "内置图标",
"Find an icon…": "查找图标…",
"From the website": "从网站获取",
"Look for the icon of the site the base URL is on": "按上面填的 Base URL 找到对应网站的图标",
"Get icon": "获取图标",
"The site's own icon, looked for from the base URL": "按上面填的 Base URL 找到对应网站的图标",
"Image URL…": "图片 URL…",
"A PNG, JPEG, GIF, WebP, ICO or SVG at a public https address": "公开 https 地址上的 PNG、JPEG、GIF、WebP、ICO 或 SVG",
"Letter icon": "字母图标",
"The name's first letters on a coloured tile": "名称的首字母,放在彩色底块上",
"Image URL": "图片 URL",
"That picture couldn't be used, so the icon is the name's letters: {why}": "这张图片用不了,已改用名称的字母图标:{why}",
"Looking…": "查找中…",
"what {agent} ships with": "{agent} 自带的默认值",
"clears the default model; {agent} picks one on its own": "清除显式默认模型,由 {agent} 自动选择",
@@ -5721,8 +5727,14 @@ const I18N = {
"Choose a picture…": "選擇圖片…",
"Built-in icons": "內建圖示",
"Find an icon…": "查詢圖示…",
"From the website": "從網站取得",
"Look for the icon of the site the base URL is on": "按上面填的 Base URL 找到對應網站的圖示",
"Get icon": "取得圖示",
"The site's own icon, looked for from the base URL": "按上面填的 Base URL 找到對應網站的圖示",
"Image URL…": "圖片 URL…",
"A PNG, JPEG, GIF, WebP, ICO or SVG at a public https address": "公開 https 位址上的 PNG、JPEG、GIF、WebP、ICO 或 SVG",
"Letter icon": "字母圖示",
"The name's first letters on a coloured tile": "名稱的首字母,放在彩色底塊上",
"Image URL": "圖片 URL",
"That picture couldn't be used, so the icon is the name's letters: {why}": "這張圖片無法使用,已改用名稱的字母圖示:{why}",
"Looking…": "查詢中…",
"what {agent} ships with": "{agent} 自帶的預設值",
"clears the default model; {agent} picks one on its own": "清除顯式預設模型,由 {agent} 自動選擇",
@@ -9949,8 +9961,14 @@ const I18N = {
"Choose a picture…": "画像を選択…",
"Built-in icons": "組み込みアイコン",
"Find an icon…": "アイコンを検索…",
"From the website": "ウェブサイトから",
"Look for the icon of the site the base URL is on": "ベース URL のサイトのアイコンを探します",
"Get icon": "アイコンを取得",
"The site's own icon, looked for from the base URL": "ベース URL のサイト自身のアイコンを探します",
"Image URL…": "画像 URL…",
"A PNG, JPEG, GIF, WebP, ICO or SVG at a public https address": "公開 https アドレスにある PNG、JPEG、GIF、WebP、ICO または SVG",
"Letter icon": "文字アイコン",
"The name's first letters on a coloured tile": "名前の頭文字を色付きのタイルに表示します",
"Image URL": "画像 URL",
"That picture couldn't be used, so the icon is the name's letters: {why}": "この画像は使えないため、名前の文字アイコンにしました:{why}",
"Looking…": "検索中…",
"what {agent} ships with": "{agent} の初期設定",
"clears the default model; {agent} picks one on its own": "デフォルトモデルをクリアします。{agent} が自分で選びます",
@@ -14208,8 +14226,14 @@ const I18N = {
"Choose a picture…": "Bild auswählen…",
"Built-in icons": "Integrierte Symbole",
"Find an icon…": "Symbol suchen…",
"From the website": "Von der Website",
"Look for the icon of the site the base URL is on": "Symbol der Website zur Basis-URL suchen",
"Get icon": "Symbol holen",
"The site's own icon, looked for from the base URL": "Das eigene Symbol der Website, gesucht über die Basis-URL",
"Image URL…": "Bild-URL…",
"A PNG, JPEG, GIF, WebP, ICO or SVG at a public https address": "Ein PNG, JPEG, GIF, WebP, ICO oder SVG unter einer öffentlichen https-Adresse",
"Letter icon": "Buchstabensymbol",
"The name's first letters on a coloured tile": "Die Anfangsbuchstaben des Namens auf einer farbigen Kachel",
"Image URL": "Bild-URL",
"That picture couldn't be used, so the icon is the name's letters: {why}": "Dieses Bild ließ sich nicht verwenden, daher zeigt das Symbol die Buchstaben des Namens: {why}",
"Looking…": "Suche läuft…",
"what {agent} ships with": "was {agent} mitbringt",
"clears the default model; {agent} picks one on its own": "leert das Standardmodell; {agent} wählt selbst eines",
+15
View File
@@ -1229,6 +1229,21 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
}
writeJSON(rw, map[string]string{"icon": icon})
})
// a picture's address typed for the icon, or with none the letter tile;
// one that can't be used gives the tile too, and failed says why
mux.HandleFunc("POST /api/icons/url", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ URL, Name, Base string }
if err := json.NewDecoder(io.LimitReader(r.Body, 64<<10)).Decode(&in); err != nil {
fail(rw, err)
return
}
icon, failed, err := provider.IconFromURL(r.Context(), in.URL, in.Name, in.Base)
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, map[string]string{"icon": icon, "failed": failed})
})
mux.HandleFunc("GET /api/icons/{name}", func(rw http.ResponseWriter, r *http.Request) {
// a big picture comes scaled to what the window draws (#909)
f, ctype := provider.IconServed(r.PathValue("name"))
+166
View File
@@ -0,0 +1,166 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// usrname1833 on Discord: many sites have no /favicon.ico, so a custom
// provider's icon came out wrong or missing. The editor's Get icon opens the
// app's own menu (never a native select) with Automatic (the site's icon, as
// before), Image URL… and Letter icon. A typed address is sent with Enter; one
// the backend couldn't use comes back as the letter tile with a note saying
// why, and the box stays for another try. Escape puts the box away. What is
// picked is what Save sends. No click scrolls the page. In Chromium and
// WebKit, at 420 and 1100 wide, in every language.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const relay = {
id: "relay", name: "My Relay", icon: "generic", host: "relay.example.com", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "gpt-5", name: "gpt-5", on: true }], chosen: ["gpt-5"],
fetched: new Date(Date.now() - 3600e3).toISOString(), agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
};
const ICON = { favicon: "file:00000000000000aa.png", url: "file:00000000000000bb.png", letter: "file:00000000000000cc.svg" };
const FAILED = "the icon URL answered 404 Not Found";
function serve(lang, posts) {
const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
const body = req.method() === "POST" ? req.postDataJSON() || {} : null;
if (body && url.pathname.startsWith("/api/")) posts.push({ path: url.pathname, body });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/icons/favicon") return json({ icon: ICON.favicon });
if (url.pathname === "/api/icons/url") {
if (!body.url) return json({ icon: ICON.letter, failed: "" });
return json(body.url.endsWith("/gone.png") ? { icon: ICON.letter, failed: FAILED } : { icon: ICON.url, failed: "" });
}
if (url.pathname.startsWith("/api/icons/")) return route.fulfill({ contentType: "image/svg+xml", body: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8"><rect width="8" height="8"/></svg>' });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const KEYS = ["Get icon", "Automatic", "The site's own icon, looked for from the base URL", "Image URL…",
"A PNG, JPEG, GIF, WebP, ICO or SVG at a public https address", "Letter icon",
"The name's first letters on a coloured tile", "Image URL", "That picture couldn't be used, so the icon is the name's letters: {why}", "Icon"];
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const width of [420, 1100]) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine} ${width} ${lang}: a custom provider's icon from an image URL or its letters`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${width}-${lang}-icon-url.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
// every new word is said in every language, and the test reads its labels from there
const w = await page.evaluate(([lang, keys]) => Object.fromEntries(keys.map((k) => [k, lang === "en" ? k : I18N[lang]?.[k]])), [lang, KEYS]);
assert.deepEqual(KEYS.filter((k) => !w[k]), [], `${lang} lacks these`);
const editor = page.locator("#modal:not([hidden]) .editor");
await page.locator(".row.provider", { hasText: "My Relay" }).click();
const pick = editor.locator(".icon-pick");
await pick.waitFor();
const scrolls = () => page.evaluate(() => [scrollY, ...[...document.querySelectorAll("#modal, #modal .editor, #modal .ebody")].map((e) => e.scrollTop)]);
// the row and the address box under it in view, so no step needs Playwright to scroll
await pick.evaluate((p) => p.scrollIntoView({ block: "start" }));
const before = await scrolls();
const get = pick.getByRole("button", { name: w["Get icon"] });
assert.equal(await get.getAttribute("aria-haspopup"), "menu");
const menu = page.locator(".proto-menu");
// past the menu's fade, for a person looking at the pictures only
const shot = async (what) => process.env.ARTIFACT_DIR && (await page.waitForTimeout(250), page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${width}-${lang}-icon-url-${what}.png`) }));
const choose = async (name) => {
await pick.getByRole("button", { name: w["Get icon"] }).click();
await menu.waitFor();
assert.equal(await menu.locator(".pm-head").textContent(), w.Icon);
assert.deepEqual(await menu.locator(".pm-name").allTextContents(), [w.Automatic, w["Image URL…"], w["Letter icon"]]);
await shot("menu");
await menu.getByRole("menuitemradio", { name: new RegExp("^" + name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")) }).click();
await menu.waitFor({ state: "detached" });
};
const now = () => pick.locator(".icon-now img").getAttribute("src");
const posted = async (p) => {
for (let i = 0; i < 100 && !posts.some((x) => x.path === p); i++) await page.waitForTimeout(30);
const at = posts.findIndex((x) => x.path === p);
assert(at >= 0, `nothing posted to ${p}`);
return posts.splice(at, 1)[0].body;
};
assert.equal(await editor.locator("select").count(), 0, "a native select");
// Automatic: the site's icon from the base URL, as before
await choose(w.Automatic);
assert.deepEqual(await posted("/api/icons/favicon"), { name: "My Relay", url: "https://relay.example.com/v1" });
await page.waitForFunction((src) => document.querySelector(".editor .icon-now img")?.getAttribute("src")?.endsWith(src), ICON.favicon.slice(5));
// Image URL…: a box for the address, focused; Enter sends it
await choose(w["Image URL…"]);
const box = pick.getByRole("textbox", { name: w["Image URL"] });
await box.waitFor();
assert(await box.evaluate((b) => b === document.activeElement), "the address box isn't focused");
assert.equal(await box.getAttribute("type"), "url");
await box.fill("https://cdn.example.com/gone.png");
await box.press("Enter");
assert.deepEqual(await posted("/api/icons/url"), { name: "My Relay", url: "https://cdn.example.com/gone.png", base: "https://relay.example.com/v1" });
// it couldn't be used: the letters, a note saying why, and the box kept
const note = editor.locator(".editor-error");
await note.waitFor();
assert.match(await note.getAttribute("class"), /\bwarn\b/);
assert.equal(await note.textContent(), w["That picture couldn't be used, so the icon is the name's letters: {why}"].replace("{why}", FAILED));
assert((await now()).endsWith(ICON.letter.slice(5)));
assert.equal(await box.inputValue(), "https://cdn.example.com/gone.png");
await shot("note");
await box.fill("https://cdn.example.com/logo.png");
await box.press("Enter");
assert.equal((await posted("/api/icons/url")).url, "https://cdn.example.com/logo.png");
await box.waitFor({ state: "detached" });
assert.equal(await note.count(), 0, "the note outlived a picture that worked");
assert((await now()).endsWith(ICON.url.slice(5)));
// Escape puts the box away and leaves the dialog open
await choose(w["Image URL…"]);
await box.press("Escape");
await box.waitFor({ state: "detached" });
assert(await editor.isVisible(), "Escape closed the editor");
assert(await pick.getByRole("button", { name: w["Get icon"] }).evaluate((b) => b === document.activeElement), "focus didn't go back to Get icon");
// Letter icon: the name's letters, asked with no address
await choose(w["Letter icon"]);
assert.deepEqual(await posted("/api/icons/url"), { name: "My Relay", base: "https://relay.example.com/v1" });
await page.waitForFunction((src) => document.querySelector(".editor .icon-now img")?.getAttribute("src")?.endsWith(src), ICON.letter.slice(5));
assert.deepEqual(await scrolls(), before, "a click scrolled");
// at 420 the row stays inside the dialog
const over = await pick.evaluate((p) => [...p.children].filter((c) => c.getBoundingClientRect().right > p.getBoundingClientRect().right + 1).map((c) => c.className || c.textContent));
assert.deepEqual(over, [], "the icon row spills out");
await editor.locator(".bar").getByRole("button", { name: lang === "en" ? "Save" : await page.evaluate((l) => I18N[l].Save, lang), exact: true }).click();
assert.equal((await posted("/api/provider/save")).icon, ICON.letter);
assert.deepEqual(errors, []);
});
}
}
}
+25
View File
@@ -40,6 +40,31 @@ func FaviconFor(ctx context.Context, base, name string) (string, error) {
return favicon(ctx, guardClient(), sites, name, iconURL)
}
// IconFromURL keeps the picture at an address the user typed for a custom
// provider, since many sites have no /favicon.ico (usrname1833). It is
// fetched as a site's icon is: a public https host only, through the guarded
// client, within fetchIcon's time and MaxIcon, and kept only when StoreIcon
// knows it as a picture. With no address, or one that fails, it keeps the
// letter tile of name (or of base's site) instead, and failed says why.
func IconFromURL(ctx context.Context, raw, name, base string) (icon, failed string, err error) {
return iconFromURL(ctx, guardClient(), raw, cmp.Or(strings.TrimSpace(name), siteLabel(base)), iconURL)
}
func iconFromURL(ctx context.Context, c *http.Client, raw, name string, check func(string) (string, error)) (icon, failed string, err error) {
if raw = strings.TrimSpace(raw); raw != "" {
u, err := check(raw)
if err != nil {
failed = fmt.Sprintf("%s is not a picture's https address on a public host", raw)
} else if icon, err = fetchIcon(ctx, c, u); err == nil {
return icon, "", nil
} else {
failed = err.Error()
}
}
icon, err = letterIcon(name)
return icon, failed, err
}
// faviconSites are the https origins to look on for base's icon: its host
// with its port, then each domain above it down to two labels.
func faviconSites(base string) ([]string, error) {
+68
View File
@@ -10,6 +10,7 @@ import (
"reflect"
"strings"
"testing"
"time"
)
func TestFaviconSites(t *testing.T) {
@@ -174,3 +175,70 @@ func TestFavicon(t *testing.T) {
}
stored(icon, svg)
}
// A picture's address typed for a custom provider's icon (usrname1833) is
// kept when it is a picture, and anything else leaves the name's letters
// with the reason: a page, a missing file, one over MaxIcon, one too slow,
// an address that isn't public https, and no address at all.
func TestIconFromURL(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
png := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR")
mux := http.NewServeMux()
mux.HandleFunc("/icon.png", func(rw http.ResponseWriter, r *http.Request) { rw.Write(png) })
mux.HandleFunc("/page", func(rw http.ResponseWriter, r *http.Request) { rw.Write([]byte("<html><body>hi</body></html>")) })
mux.HandleFunc("/huge.png", func(rw http.ResponseWriter, r *http.Request) {
rw.Write(append(append([]byte{}, png...), make([]byte, MaxIcon)...))
})
mux.HandleFunc("/slow.png", func(rw http.ResponseWriter, r *http.Request) { <-r.Context().Done() })
srv := httptest.NewServer(mux)
defer srv.Close()
pass := func(s string) (string, error) { return s, nil }
read := func(icon string) string {
t.Helper()
b, err := os.ReadFile(IconFile(strings.TrimPrefix(icon, iconPrefix)))
if err != nil {
t.Fatalf("%q isn't stored: %v", icon, err)
}
return string(b)
}
icon, failed, err := iconFromURL(context.Background(), srv.Client(), srv.URL+"/icon.png", "My Relay", pass)
if err != nil || failed != "" || read(icon) != string(png) {
t.Fatalf("a picture: %q %q %v", icon, failed, err)
}
for _, c := range []struct {
path, why string
timeout bool
}{
{"/page", "not a picture", false},
{"/missing.png", "404", false},
{"/huge.png", "over 1 MB", false},
{"/slow.png", "could not fetch", true},
} {
ctx, cancel := context.Background(), func() {}
if c.timeout {
ctx, cancel = context.WithTimeout(ctx, 300*time.Millisecond)
}
icon, failed, err := iconFromURL(ctx, srv.Client(), srv.URL+c.path, "My Relay", pass)
cancel()
if err != nil || !strings.Contains(failed, c.why) || !strings.Contains(read(icon), ">MR</text>") {
t.Errorf("%s: %q %q %v, want the letters MR and %q", c.path, read(icon), failed, err, c.why)
}
}
// none typed: the letters, with nothing to say
if icon, failed, err := iconFromURL(context.Background(), srv.Client(), " ", "My Relay", pass); err != nil || failed != "" || !strings.Contains(read(icon), ">MR</text>") {
t.Errorf("no address: %q %q %v", icon, failed, err)
}
// the guard: only a public https address is fetched, and with no name
// the letters are the base URL's site's
for _, raw := range []string{"http://example.com/icon.png", srv.URL + "/icon.png", "https://localhost/icon.png", "https://user@example.com/i.png"} {
icon, failed, err := IconFromURL(context.Background(), raw, "", "https://api.kiwi.dev/v1")
if err != nil || !strings.Contains(failed, "not a picture's https address") || !strings.Contains(read(icon), ">Ki</text>") {
t.Errorf("%s: %q %q %v, want it refused and the letters Ki", raw, read(icon), failed, err)
}
}
}