Skip to content

Commit 208a10d

Browse files
committed
bug fixes and some caching stuff
1 parent ccc7151 commit 208a10d

9 files changed

Lines changed: 39 additions & 35 deletions

File tree

backend/internal/api/handler.go

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -478,22 +478,6 @@ func (h *Handler) GetFeed(w http.ResponseWriter, r *http.Request) {
478478
})
479479
}
480480

481-
func containsTag(tagsJSON *string, tag string) bool {
482-
if tagsJSON == nil || *tagsJSON == "" {
483-
return false
484-
}
485-
var tags []string
486-
if err := json.Unmarshal([]byte(*tagsJSON), &tags); err != nil {
487-
return false
488-
}
489-
for _, t := range tags {
490-
if t == tag {
491-
return true
492-
}
493-
}
494-
return false
495-
}
496-
497481
func sortFeed(feed []interface{}) {
498482
sort.Slice(feed, func(i, j int) bool {
499483
t1 := getCreatedAt(feed[i])
@@ -764,6 +748,14 @@ func (h *Handler) GetByTarget(w http.ResponseWriter, r *http.Request) {
764748
enrichedHighlights, _ := hydrateHighlights(h.db, highlights, h.getViewerDID(r))
765749
enrichedBookmarks, _ := hydrateBookmarks(h.db, bookmarks, h.getViewerDID(r))
766750

751+
totalItems := len(enrichedAnnotations) + len(enrichedHighlights) + len(enrichedBookmarks)
752+
753+
if totalItems == 0 {
754+
w.Header().Set("Cache-Control", "public, max-age=60, s-maxage=300")
755+
} else {
756+
w.Header().Set("Cache-Control", "private, max-age=0, no-store")
757+
}
758+
767759
w.Header().Set("Content-Type", "application/json")
768760
json.NewEncoder(w).Encode(map[string]interface{}{
769761
"@context": "http://www.w3.org/ns/anno.jsonld",

extension/src/entrypoints/background.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ export default defineBackground(() => {
5454
});
5555

5656
onMessage('getAnnotations', async ({ data }) => {
57-
return await getAnnotations(data.url);
57+
return await getAnnotations(data.url, [], data.cacheBust);
5858
});
5959

6060
onMessage('activateOnPdf', async ({ data }) => {

extension/src/utils/api.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,22 @@ async function apiRequest(path: string, options: RequestInit = {}): Promise<Resp
8181
return response;
8282
}
8383

84-
export async function getAnnotations(url: string, citedUrls: string[] = []) {
84+
export async function getAnnotations(
85+
url: string,
86+
citedUrls: string[] = [],
87+
cacheBust: boolean = false
88+
) {
8589
try {
8690
const apiUrl = await getApiUrl();
8791
const uniqueUrls = [...new Set([url, ...citedUrls])];
8892

8993
const fetchPromises = uniqueUrls.map(async (u) => {
9094
try {
91-
const res = await fetch(`${apiUrl}/api/targets?source=${encodeURIComponent(u)}`);
95+
let requestUrl = `${apiUrl}/api/targets?source=${encodeURIComponent(u)}`;
96+
if (cacheBust) {
97+
requestUrl += `&t=${Date.now()}`;
98+
}
99+
const res = await fetch(requestUrl);
92100
if (!res.ok) return { annotations: [], highlights: [], bookmarks: [] };
93101
return await res.json();
94102
} catch {

extension/src/utils/messaging.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import type {
1111
interface ProtocolMap {
1212
checkSession(): MarginSession;
1313

14-
getAnnotations(data: { url: string }): Annotation[];
14+
getAnnotations(data: { url: string; cacheBust?: boolean }): Annotation[];
1515
activateOnPdf(data: { tabId: number; url: string }): { redirected: boolean };
1616
createAnnotation(data: {
1717
url: string;

extension/src/utils/overlay.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ export async function initContentScript(ctx: { onInvalidated: (cb: () => void) =
398398
composeModal?.remove();
399399
composeModal = null;
400400

401-
setTimeout(() => fetchAnnotations(), 500);
401+
setTimeout(() => fetchAnnotations(0, true), 500);
402402
} catch (error) {
403403
console.error('Failed to create annotation:', error);
404404
showToast('Failed to create annotation', 'error');
@@ -415,7 +415,7 @@ export async function initContentScript(ctx: { onInvalidated: (cb: () => void) =
415415
showComposeModal(message.data.selector.exact);
416416
}
417417
if (message.type === 'REFRESH_ANNOTATIONS') {
418-
fetchAnnotations();
418+
fetchAnnotations(0, true);
419419
}
420420
if (message.type === 'SCROLL_TO_TEXT' && message.text) {
421421
scrollToText(message.text);
@@ -512,14 +512,17 @@ export async function initContentScript(ctx: { onInvalidated: (cb: () => void) =
512512
}, 2500);
513513
}
514514

515-
async function fetchAnnotations(retryCount = 0) {
515+
async function fetchAnnotations(retryCount = 0, cacheBust = false) {
516516
if (!overlayEnabled) {
517517
sendMessage('updateBadge', { count: 0 });
518518
return;
519519
}
520520

521521
try {
522-
const annotations = await sendMessage('getAnnotations', { url: getPageUrl() });
522+
const annotations = await sendMessage('getAnnotations', {
523+
url: getPageUrl(),
524+
cacheBust,
525+
});
523526

524527
sendMessage('updateBadge', { count: annotations?.length || 0 });
525528

@@ -530,12 +533,12 @@ export async function initContentScript(ctx: { onInvalidated: (cb: () => void) =
530533
if (annotations && annotations.length > 0) {
531534
renderBadges(annotations);
532535
} else if (retryCount < 3) {
533-
setTimeout(() => fetchAnnotations(retryCount + 1), 1000 * (retryCount + 1));
536+
setTimeout(() => fetchAnnotations(retryCount + 1, cacheBust), 1000 * (retryCount + 1));
534537
}
535538
} catch (error) {
536539
console.error('Failed to fetch annotations:', error);
537540
if (retryCount < 3) {
538-
setTimeout(() => fetchAnnotations(retryCount + 1), 1000 * (retryCount + 1));
541+
setTimeout(() => fetchAnnotations(retryCount + 1, cacheBust), 1000 * (retryCount + 1));
539542
}
540543
}
541544
}

web/src/api/client.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -649,6 +649,7 @@ export async function searchActors(
649649
}
650650

651651
export async function resolveHandle(handle: string): Promise<string | null> {
652+
if (handle.startsWith("did:")) return handle;
652653
try {
653654
const res = await fetch(
654655
`https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`,

web/src/lib/og.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ interface APICollection {
6161
}
6262

6363
export async function resolveHandle(handle: string): Promise<string | null> {
64+
if (handle.startsWith("did:")) return handle;
6465
try {
6566
const res = await fetch(
6667
`https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`,
@@ -221,7 +222,7 @@ export async function fetchCollectionOG(uri: string): Promise<OGData | null> {
221222
const icon = item.icon || "📁";
222223
const title = `${icon} ${item.name}`;
223224

224-
let description = "";
225+
let description;
225226
if (item.description) {
226227
description = `By ${author} · ${truncate(item.description, 170)}`;
227228
} else {

web/src/middleware.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export async function onRequest(
3535

3636
if (request.method !== "GET" && request.method !== "HEAD" && request.body) {
3737
init.body = request.body;
38-
// @ts-expect-error
38+
// @ts-expect-error duplex is generic on RequestInit
3939
init.duplex = "half";
4040
}
4141

web/src/pages/og-image.ts

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -389,8 +389,7 @@ function buildAnnotationImage(data: RecordData, logo: string) {
389389
},
390390
});
391391

392-
(children as any).__accent = tc.accent;
393-
return wrapCard(children);
392+
return wrapCard(children, tc.accent);
394393
}
395394

396395
function buildBookmarkImage(data: RecordData, logo: string) {
@@ -516,8 +515,7 @@ function buildBookmarkImage(data: RecordData, logo: string) {
516515
},
517516
});
518517

519-
(children as any).__accent = tc.accent;
520-
return wrapCard(children);
518+
return wrapCard(children, tc.accent);
521519
}
522520

523521
function buildCollectionImage(data: RecordData, logo: string) {
@@ -599,8 +597,7 @@ function buildCollectionImage(data: RecordData, logo: string) {
599597
return wrapCard(children);
600598
}
601599

602-
function wrapCard(children: unknown[]) {
603-
const accent = (children as any).__accent || "#3b82f6";
600+
function wrapCard(children: unknown[], accent: string = "#3b82f6") {
604601
return {
605602
type: "div",
606603
props: {
@@ -674,7 +671,9 @@ export const GET: APIRoute = async ({ url }) => {
674671
const res = await fetch(url);
675672
if (res.ok)
676673
return `data:image/svg+xml,${encodeURIComponent(await res.text())}`;
677-
} catch {}
674+
} catch {
675+
// ignore
676+
}
678677
}
679678
return "";
680679
},

0 commit comments

Comments
 (0)