Unfollow tool for Bluesky
1import {
2 type Component,
3 createEffect,
4 createSignal,
5 For,
6 onMount,
7 Show,
8} from "solid-js";
9import { createStore } from "solid-js/store";
10
11import { XRPC } from "@atcute/client";
12import {
13 AppBskyGraphFollow,
14 At,
15 Brand,
16 ComAtprotoRepoApplyWrites,
17} from "@atcute/client/lexicons";
18import {
19 configureOAuth,
20 createAuthorizationUrl,
21 finalizeAuthorization,
22 getSession,
23 OAuthUserAgent,
24 resolveFromIdentity,
25 type Session,
26} from "@atcute/oauth-browser-client";
27import { AiFillGithub, Bluesky, TbMoonStar, TbSun } from "./svg";
28
29configureOAuth({
30 metadata: {
31 client_id: import.meta.env.VITE_OAUTH_CLIENT_ID,
32 redirect_uri: import.meta.env.VITE_OAUTH_REDIRECT_URL,
33 },
34});
35
36enum RepoStatus {
37 BLOCKEDBY = 1 << 0,
38 BLOCKING = 1 << 1,
39 DELETED = 1 << 2,
40 DEACTIVATED = 1 << 3,
41 SUSPENDED = 1 << 4,
42 YOURSELF = 1 << 5,
43}
44
45type FollowRecord = {
46 did: string;
47 handle: string;
48 uri: string;
49 status: RepoStatus;
50 status_label: string;
51 toDelete: boolean;
52 visible: boolean;
53};
54
55const [followRecords, setFollowRecords] = createStore<FollowRecord[]>([]);
56const [loginState, setLoginState] = createSignal(false);
57let rpc: XRPC;
58let agent: OAuthUserAgent;
59
60const resolveDid = async (did: string) => {
61 const res = await fetch(
62 did.startsWith("did:web") ?
63 `https://${did.split(":")[2]}/.well-known/did.json`
64 : "https://plc.directory/" + did,
65 );
66
67 return res
68 .json()
69 .then((doc) => {
70 for (const alias of doc.alsoKnownAs) {
71 if (alias.includes("at://")) {
72 return alias.split("//")[1];
73 }
74 }
75 })
76 .catch(() => "");
77};
78
79const Login: Component = () => {
80 const [loginInput, setLoginInput] = createSignal("");
81 const [handle, setHandle] = createSignal("");
82 const [notice, setNotice] = createSignal("");
83
84 onMount(async () => {
85 setNotice("Loading...");
86
87 const init = async (): Promise<Session | undefined> => {
88 const params = new URLSearchParams(location.hash.slice(1));
89
90 if (params.has("state") && (params.has("code") || params.has("error"))) {
91 history.replaceState(null, "", location.pathname + location.search);
92
93 const session = await finalizeAuthorization(params);
94 const did = session.info.sub;
95
96 localStorage.setItem("lastSignedIn", did);
97 return session;
98 } else {
99 const lastSignedIn = localStorage.getItem("lastSignedIn");
100
101 if (lastSignedIn) {
102 try {
103 return await getSession(lastSignedIn as At.DID);
104 } catch (err) {
105 localStorage.removeItem("lastSignedIn");
106 throw err;
107 }
108 }
109 }
110 };
111
112 const session = await init().catch(() => {});
113
114 if (session) {
115 agent = new OAuthUserAgent(session);
116 rpc = new XRPC({ handler: agent });
117
118 setLoginState(true);
119 setHandle(await resolveDid(agent.sub));
120 }
121
122 setNotice("");
123 });
124
125 const loginBsky = async (handle: string) => {
126 try {
127 setNotice(`Resolving your identity...`);
128 const resolved = await resolveFromIdentity(handle);
129
130 setNotice(`Contacting your data server...`);
131 const authUrl = await createAuthorizationUrl({
132 scope: import.meta.env.VITE_OAUTH_SCOPE,
133 ...resolved,
134 });
135
136 setNotice(`Redirecting...`);
137 await new Promise((resolve) => setTimeout(resolve, 250));
138
139 location.assign(authUrl);
140 } catch {
141 setNotice("Error during OAuth login");
142 }
143 };
144
145 const logoutBsky = async () => {
146 await agent.signOut();
147 };
148
149 return (
150 <div class="flex flex-col items-center">
151 <Show when={!loginState() && !notice().includes("Loading")}>
152 <form class="flex flex-col" onsubmit={(e) => e.preventDefault()}>
153 <label for="handle" class="ml-0.5">
154 Handle
155 </label>
156 <input
157 type="text"
158 id="handle"
159 placeholder="user.bsky.social"
160 class="dark:bg-dark-100 mb-2 rounded-lg border border-gray-400 px-2 py-1 focus:outline-none focus:ring-1 focus:ring-gray-300"
161 onInput={(e) => setLoginInput(e.currentTarget.value)}
162 />
163 <button
164 onclick={() => loginBsky(loginInput())}
165 class="rounded bg-blue-600 py-1.5 font-bold text-slate-100 hover:bg-blue-700"
166 >
167 Login
168 </button>
169 </form>
170 <div class="mt-3">
171 Remember to use your main password, not an app password.
172 </div>
173 </Show>
174 <Show when={loginState() && handle()}>
175 <div class="mb-4">
176 Logged in as @{handle()}
177 <a
178 href=""
179 class="ml-2 text-red-500 dark:text-red-400"
180 onclick={() => logoutBsky()}
181 >
182 Logout
183 </a>
184 </div>
185 </Show>
186 <Show when={notice()}>
187 <div class="m-3">{notice()}</div>
188 </Show>
189 </div>
190 );
191};
192
193const Fetch: Component = () => {
194 const [progress, setProgress] = createSignal(0);
195 const [followCount, setFollowCount] = createSignal(0);
196 const [notice, setNotice] = createSignal("");
197
198 const fetchHiddenAccounts = async () => {
199 const fetchFollows = async () => {
200 const PAGE_LIMIT = 100;
201 const fetchPage = async (cursor?: string) => {
202 return await rpc.get("com.atproto.repo.listRecords", {
203 params: {
204 repo: agent.sub,
205 collection: "app.bsky.graph.follow",
206 limit: PAGE_LIMIT,
207 cursor: cursor,
208 },
209 });
210 };
211
212 let res = await fetchPage();
213 let follows = res.data.records;
214
215 while (res.data.cursor && res.data.records.length >= PAGE_LIMIT) {
216 res = await fetchPage(res.data.cursor);
217 follows = follows.concat(res.data.records);
218 }
219
220 return follows;
221 };
222
223 setProgress(0);
224 setNotice("");
225
226 const follows = await fetchFollows();
227 setFollowCount(follows.length);
228 const tmpFollows: FollowRecord[] = [];
229
230 follows.forEach(async (record) => {
231 let status: RepoStatus | undefined = undefined;
232 const follow = record.value as AppBskyGraphFollow.Record;
233 let handle = "";
234
235 try {
236 const res = await rpc.get("app.bsky.actor.getProfile", {
237 params: { actor: follow.subject },
238 });
239
240 handle = res.data.handle;
241 const viewer = res.data.viewer!;
242
243 if (viewer.blockedBy) {
244 status =
245 viewer.blocking || viewer.blockingByList ?
246 RepoStatus.BLOCKEDBY | RepoStatus.BLOCKING
247 : RepoStatus.BLOCKEDBY;
248 } else if (res.data.did.includes(agent.sub)) {
249 status = RepoStatus.YOURSELF;
250 } else if (viewer.blocking || viewer.blockingByList) {
251 status = RepoStatus.BLOCKING;
252 }
253 } catch (e: any) {
254 handle = await resolveDid(follow.subject);
255
256 status =
257 e.message.includes("not found") ? RepoStatus.DELETED
258 : e.message.includes("deactivated") ? RepoStatus.DEACTIVATED
259 : e.message.includes("suspended") ? RepoStatus.SUSPENDED
260 : undefined;
261 }
262
263 const status_label =
264 status == RepoStatus.DELETED ? "Deleted"
265 : status == RepoStatus.DEACTIVATED ? "Deactivated"
266 : status == RepoStatus.SUSPENDED ? "Suspended"
267 : status == RepoStatus.YOURSELF ? "Literally Yourself"
268 : status == RepoStatus.BLOCKING ? "Blocking"
269 : status == RepoStatus.BLOCKEDBY ? "Blocked by"
270 : RepoStatus.BLOCKEDBY | RepoStatus.BLOCKING ? "Mutual Block"
271 : "";
272
273 if (status !== undefined) {
274 tmpFollows.push({
275 did: follow.subject,
276 handle: handle,
277 uri: record.uri,
278 status: status,
279 status_label: status_label,
280 toDelete: false,
281 visible: true,
282 });
283 }
284 setProgress(progress() + 1);
285 if (progress() == followCount()) setFollowRecords(tmpFollows);
286 });
287 };
288
289 const unfollow = async () => {
290 const writes = followRecords
291 .filter((record) => record.toDelete)
292 .map((record): Brand.Union<ComAtprotoRepoApplyWrites.Delete> => {
293 return {
294 $type: "com.atproto.repo.applyWrites#delete",
295 collection: "app.bsky.graph.follow",
296 rkey: record.uri.split("/").pop()!,
297 };
298 });
299
300 const BATCHSIZE = 200;
301 for (let i = 0; i < writes.length; i += BATCHSIZE) {
302 await rpc.call("com.atproto.repo.applyWrites", {
303 data: {
304 repo: agent.sub,
305 writes: writes.slice(i, i + BATCHSIZE),
306 },
307 });
308 }
309
310 setFollowRecords([]);
311 setProgress(0);
312 setFollowCount(0);
313 setNotice(
314 `Unfollowed ${writes.length} account${writes.length > 1 ? "s" : ""}`,
315 );
316 };
317
318 return (
319 <div class="flex flex-col items-center">
320 <Show when={!followRecords.length}>
321 <button
322 type="button"
323 onclick={() => fetchHiddenAccounts()}
324 class="rounded bg-blue-600 px-2 py-2 font-bold text-slate-100 hover:bg-blue-700"
325 >
326 Preview
327 </button>
328 </Show>
329 <Show when={followRecords.length}>
330 <button
331 type="button"
332 onclick={() => unfollow()}
333 class="rounded bg-blue-600 px-2 py-2 font-bold text-slate-100 hover:bg-blue-700"
334 >
335 Confirm
336 </button>
337 </Show>
338 <Show when={notice()}>
339 <div class="m-3">{notice()}</div>
340 </Show>
341 <Show when={followCount() && progress() != followCount()}>
342 <div class="m-3">
343 Progress: {progress()}/{followCount()}
344 </div>
345 </Show>
346 </div>
347 );
348};
349
350const Follows: Component = () => {
351 const [selectedCount, setSelectedCount] = createSignal(0);
352
353 createEffect(() => {
354 setSelectedCount(followRecords.filter((record) => record.toDelete).length);
355 });
356
357 function editRecords(
358 status: RepoStatus,
359 field: keyof FollowRecord,
360 value: boolean,
361 ) {
362 const range = followRecords
363 .map((record, index) => {
364 if (record.status & status) return index;
365 })
366 .filter((i) => i !== undefined);
367 setFollowRecords(range, field, value);
368 }
369
370 const options: { status: RepoStatus; label: string }[] = [
371 { status: RepoStatus.DELETED, label: "Deleted" },
372 { status: RepoStatus.DEACTIVATED, label: "Deactivated" },
373 { status: RepoStatus.SUSPENDED, label: "Suspended" },
374 { status: RepoStatus.BLOCKEDBY, label: "Blocked By" },
375 { status: RepoStatus.BLOCKING, label: "Blocking" },
376 ];
377
378 return (
379 <div class="mt-6 flex flex-col sm:w-full sm:flex-row sm:justify-center">
380 <div class="dark:bg-dark-500 sticky top-0 mb-3 mr-5 flex w-full flex-wrap justify-around border-b border-b-gray-400 bg-slate-100 pb-3 sm:top-3 sm:mb-0 sm:w-auto sm:flex-col sm:self-start sm:border-none">
381 <For each={options}>
382 {(option, index) => (
383 <div
384 classList={{
385 "sm:pb-2 min-w-36 sm:mb-2 mt-3 sm:mt-0": true,
386 "sm:border-b sm:border-b-gray-300 dark:sm:border-b-gray-500":
387 index() < options.length - 1,
388 }}
389 >
390 <div>
391 <label class="mb-2 mt-1 inline-flex cursor-pointer items-center">
392 <input
393 type="checkbox"
394 class="peer sr-only"
395 checked
396 onChange={(e) =>
397 editRecords(
398 option.status,
399 "visible",
400 e.currentTarget.checked,
401 )
402 }
403 />
404 <span class="peer relative h-5 w-9 rounded-full bg-gray-200 after:absolute after:start-[2px] after:top-[2px] after:h-4 after:w-4 after:rounded-full after:border after:border-gray-300 after:bg-white after:transition-all after:content-[''] peer-checked:bg-blue-600 peer-checked:after:translate-x-full peer-checked:after:border-white peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rtl:peer-checked:after:-translate-x-full dark:border-gray-600 dark:bg-gray-700 dark:peer-focus:ring-blue-800"></span>
405 <span class="ms-3 select-none">{option.label}</span>
406 </label>
407 </div>
408 <div class="flex items-center">
409 <input
410 type="checkbox"
411 id={option.label}
412 class="h-4 w-4 rounded"
413 onChange={(e) =>
414 editRecords(
415 option.status,
416 "toDelete",
417 e.currentTarget.checked,
418 )
419 }
420 />
421 <label for={option.label} class="ml-2 select-none">
422 Select All
423 </label>
424 </div>
425 </div>
426 )}
427 </For>
428 <div class="min-w-36 pt-3 sm:pt-0">
429 <span>
430 Selected: {selectedCount()}/{followRecords.length}
431 </span>
432 </div>
433 </div>
434 <div class="sm:min-w-96">
435 <For each={followRecords}>
436 {(record, index) => (
437 <Show when={record.visible}>
438 <div
439 classList={{
440 "mb-1 flex items-center border-b dark:border-b-gray-500 py-1":
441 true,
442 "bg-red-300 dark:bg-rose-800": record.toDelete,
443 }}
444 >
445 <div class="mx-2">
446 <input
447 type="checkbox"
448 id={"record" + index()}
449 class="h-4 w-4 rounded"
450 checked={record.toDelete}
451 onChange={(e) =>
452 setFollowRecords(
453 index(),
454 "toDelete",
455 e.currentTarget.checked,
456 )
457 }
458 />
459 </div>
460 <div>
461 <label for={"record" + index()} class="flex flex-col">
462 <Show when={record.handle.length}>
463 <span>@{record.handle}</span>
464 </Show>
465 <span>{record.did}</span>
466 <span>{record.status_label}</span>
467 </label>
468 </div>
469 </div>
470 </Show>
471 )}
472 </For>
473 </div>
474 </div>
475 );
476};
477
478const App: Component = () => {
479 const [theme, setTheme] = createSignal(
480 (
481 localStorage.theme === "dark" ||
482 (!("theme" in localStorage) &&
483 globalThis.matchMedia("(prefers-color-scheme: dark)").matches)
484 ) ?
485 "dark"
486 : "light",
487 );
488
489 return (
490 <div class="m-5 flex flex-col items-center text-slate-900 dark:text-slate-100">
491 <div class="mb-2 flex w-[20rem] items-center">
492 <div class="basis-1/3">
493 <div
494 class="w-fit cursor-pointer"
495 onclick={() => {
496 setTheme(theme() === "light" ? "dark" : "light");
497 if (theme() === "dark")
498 document.documentElement.classList.add("dark");
499 else document.documentElement.classList.remove("dark");
500 localStorage.theme = theme();
501 }}
502 >
503 {theme() === "dark" ?
504 <TbMoonStar class="size-6" />
505 : <TbSun class="size-6" />}
506 </div>
507 </div>
508 <div class="basis-1/3 text-center text-xl font-bold">
509 <a href="">cleanfollow</a>
510 </div>
511 <div class="justify-right flex basis-1/3 gap-x-2">
512 <a
513 href="https://bsky.app/profile/did:plc:b3pn34agqqchkaf75v7h43dk"
514 target="_blank"
515 >
516 <Bluesky class="size-6" />
517 </a>
518 <a
519 href="https://github.com/notjuliet/cleanfollow-bsky"
520 target="_blank"
521 >
522 <AiFillGithub class="size-6" />
523 </a>
524 </div>
525 </div>
526 <div class="mb-2 text-center">
527 <p>Select inactive or blocked accounts to unfollow</p>
528 </div>
529 <Login />
530 <Show when={loginState()}>
531 <Fetch />
532 <Show when={followRecords.length}>
533 <Follows />
534 </Show>
535 </Show>
536 </div>
537 );
538};
539
540export default App;