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