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 setLoginState(false); 148 }; 149 150 return ( 151 <div class="flex flex-col items-center"> 152 <Show when={!loginState() && !notice().includes("Loading")}> 153 <form class="flex flex-col" onsubmit={(e) => e.preventDefault()}> 154 <label for="handle" class="ml-0.5"> 155 Handle 156 </label> 157 <input 158 type="text" 159 id="handle" 160 placeholder="user.bsky.social" 161 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" 162 onInput={(e) => setLoginInput(e.currentTarget.value)} 163 /> 164 <button 165 onclick={() => loginBsky(loginInput())} 166 class="rounded bg-blue-600 py-1.5 font-bold text-slate-100 hover:bg-blue-700" 167 > 168 Login 169 </button> 170 </form> 171 <div class="mt-3"> 172 Remember to use your main password, not an app password. 173 </div> 174 </Show> 175 <Show when={loginState() && handle()}> 176 <div class="mb-4"> 177 Logged in as @{handle()} 178 <a 179 href="" 180 class="ml-2 text-red-500 dark:text-red-400" 181 onclick={() => logoutBsky()} 182 > 183 Logout 184 </a> 185 </div> 186 </Show> 187 <Show when={notice()}> 188 <div class="m-3">{notice()}</div> 189 </Show> 190 </div> 191 ); 192}; 193 194const Fetch: Component = () => { 195 const [progress, setProgress] = createSignal(0); 196 const [followCount, setFollowCount] = createSignal(0); 197 const [notice, setNotice] = createSignal(""); 198 199 const fetchHiddenAccounts = async () => { 200 const fetchFollows = async () => { 201 const PAGE_LIMIT = 100; 202 const fetchPage = async (cursor?: string) => { 203 return await rpc.get("com.atproto.repo.listRecords", { 204 params: { 205 repo: agent.sub, 206 collection: "app.bsky.graph.follow", 207 limit: PAGE_LIMIT, 208 cursor: cursor, 209 }, 210 }); 211 }; 212 213 let res = await fetchPage(); 214 let follows = res.data.records; 215 setNotice(`Fetching follows: ${follows.length}`); 216 217 while (res.data.cursor && res.data.records.length >= PAGE_LIMIT) { 218 setNotice(`Fetching follows: ${follows.length}`); 219 res = await fetchPage(res.data.cursor); 220 follows = follows.concat(res.data.records); 221 } 222 223 return follows; 224 }; 225 226 setProgress(0); 227 const follows = await fetchFollows(); 228 setFollowCount(follows.length); 229 const tmpFollows: FollowRecord[] = []; 230 setNotice(""); 231 232 const timer = (ms: number) => new Promise((res) => setTimeout(res, ms)); 233 for (let i = 0; i < follows.length; i = i + 10) { 234 if (follows.length > 1000) await timer(1000); 235 follows.slice(i, i + 10).forEach(async (record) => { 236 let status: RepoStatus | undefined = undefined; 237 const follow = record.value as AppBskyGraphFollow.Record; 238 let handle = ""; 239 240 try { 241 const res = await rpc.get("app.bsky.actor.getProfile", { 242 params: { actor: follow.subject }, 243 }); 244 245 handle = res.data.handle; 246 const viewer = res.data.viewer!; 247 248 if (viewer.blockedBy) { 249 status = 250 viewer.blocking || viewer.blockingByList ? 251 RepoStatus.BLOCKEDBY | RepoStatus.BLOCKING 252 : RepoStatus.BLOCKEDBY; 253 } else if (res.data.did.includes(agent.sub)) { 254 status = RepoStatus.YOURSELF; 255 } else if (viewer.blocking || viewer.blockingByList) { 256 status = RepoStatus.BLOCKING; 257 } 258 } catch (e: any) { 259 handle = await resolveDid(follow.subject); 260 261 status = 262 e.message.includes("not found") ? RepoStatus.DELETED 263 : e.message.includes("deactivated") ? RepoStatus.DEACTIVATED 264 : e.message.includes("suspended") ? RepoStatus.SUSPENDED 265 : undefined; 266 } 267 268 const status_label = 269 status == RepoStatus.DELETED ? "Deleted" 270 : status == RepoStatus.DEACTIVATED ? "Deactivated" 271 : status == RepoStatus.SUSPENDED ? "Suspended" 272 : status == RepoStatus.YOURSELF ? "Literally Yourself" 273 : status == RepoStatus.BLOCKING ? "Blocking" 274 : status == RepoStatus.BLOCKEDBY ? "Blocked by" 275 : RepoStatus.BLOCKEDBY | RepoStatus.BLOCKING ? "Mutual Block" 276 : ""; 277 278 if (status !== undefined) { 279 tmpFollows.push({ 280 did: follow.subject, 281 handle: handle, 282 uri: record.uri, 283 status: status, 284 status_label: status_label, 285 toDelete: false, 286 visible: true, 287 }); 288 } 289 setProgress(progress() + 1); 290 if (progress() == followCount()) setFollowRecords(tmpFollows); 291 }); 292 } 293 }; 294 295 const unfollow = async () => { 296 const writes = followRecords 297 .filter((record) => record.toDelete) 298 .map((record): Brand.Union<ComAtprotoRepoApplyWrites.Delete> => { 299 return { 300 $type: "com.atproto.repo.applyWrites#delete", 301 collection: "app.bsky.graph.follow", 302 rkey: record.uri.split("/").pop()!, 303 }; 304 }); 305 306 const BATCHSIZE = 200; 307 for (let i = 0; i < writes.length; i += BATCHSIZE) { 308 await rpc.call("com.atproto.repo.applyWrites", { 309 data: { 310 repo: agent.sub, 311 writes: writes.slice(i, i + BATCHSIZE), 312 }, 313 }); 314 } 315 316 setFollowRecords([]); 317 setProgress(0); 318 setFollowCount(0); 319 setNotice( 320 `Unfollowed ${writes.length} account${writes.length > 1 ? "s" : ""}`, 321 ); 322 }; 323 324 return ( 325 <div class="flex flex-col items-center"> 326 <Show when={!followRecords.length}> 327 <button 328 type="button" 329 onclick={() => fetchHiddenAccounts()} 330 class="rounded bg-blue-600 px-2 py-2 font-bold text-slate-100 hover:bg-blue-700" 331 > 332 Preview 333 </button> 334 </Show> 335 <Show when={followRecords.length}> 336 <button 337 type="button" 338 onclick={() => unfollow()} 339 class="rounded bg-blue-600 px-2 py-2 font-bold text-slate-100 hover:bg-blue-700" 340 > 341 Confirm 342 </button> 343 </Show> 344 <Show when={notice()}> 345 <div class="m-3">{notice()}</div> 346 </Show> 347 <Show when={followCount() && progress() != followCount()}> 348 <div class="m-3"> 349 Progress: {progress()}/{followCount()} 350 </div> 351 </Show> 352 </div> 353 ); 354}; 355 356const Follows: Component = () => { 357 const [selectedCount, setSelectedCount] = createSignal(0); 358 359 createEffect(() => { 360 setSelectedCount(followRecords.filter((record) => record.toDelete).length); 361 }); 362 363 function editRecords( 364 status: RepoStatus, 365 field: keyof FollowRecord, 366 value: boolean, 367 ) { 368 const range = followRecords 369 .map((record, index) => { 370 if (record.status & status) return index; 371 }) 372 .filter((i) => i !== undefined); 373 setFollowRecords(range, field, value); 374 } 375 376 const options: { status: RepoStatus; label: string }[] = [ 377 { status: RepoStatus.DELETED, label: "Deleted" }, 378 { status: RepoStatus.DEACTIVATED, label: "Deactivated" }, 379 { status: RepoStatus.SUSPENDED, label: "Suspended" }, 380 { status: RepoStatus.BLOCKEDBY, label: "Blocked By" }, 381 { status: RepoStatus.BLOCKING, label: "Blocking" }, 382 ]; 383 384 return ( 385 <div class="mt-6 flex flex-col sm:w-full sm:flex-row sm:justify-center"> 386 <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"> 387 <For each={options}> 388 {(option, index) => ( 389 <div 390 classList={{ 391 "sm:pb-2 min-w-36 sm:mb-2 mt-3 sm:mt-0": true, 392 "sm:border-b sm:border-b-gray-300 dark:sm:border-b-gray-500": 393 index() < options.length - 1, 394 }} 395 > 396 <div> 397 <label class="mb-2 mt-1 inline-flex cursor-pointer items-center"> 398 <input 399 type="checkbox" 400 class="peer sr-only" 401 checked 402 onChange={(e) => 403 editRecords( 404 option.status, 405 "visible", 406 e.currentTarget.checked, 407 ) 408 } 409 /> 410 <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> 411 <span class="ms-3 select-none">{option.label}</span> 412 </label> 413 </div> 414 <div class="flex items-center"> 415 <input 416 type="checkbox" 417 id={option.label} 418 class="h-4 w-4 rounded" 419 onChange={(e) => 420 editRecords( 421 option.status, 422 "toDelete", 423 e.currentTarget.checked, 424 ) 425 } 426 /> 427 <label for={option.label} class="ml-2 select-none"> 428 Select All 429 </label> 430 </div> 431 </div> 432 )} 433 </For> 434 <div class="min-w-36 pt-3 sm:pt-0"> 435 <span> 436 Selected: {selectedCount()}/{followRecords.length} 437 </span> 438 </div> 439 </div> 440 <div class="sm:min-w-96"> 441 <For each={followRecords}> 442 {(record, index) => ( 443 <Show when={record.visible}> 444 <div 445 classList={{ 446 "mb-1 flex items-center border-b dark:border-b-gray-500 py-1": 447 true, 448 "bg-red-300 dark:bg-rose-800": record.toDelete, 449 }} 450 > 451 <div class="mx-2"> 452 <input 453 type="checkbox" 454 id={"record" + index()} 455 class="h-4 w-4 rounded" 456 checked={record.toDelete} 457 onChange={(e) => 458 setFollowRecords( 459 index(), 460 "toDelete", 461 e.currentTarget.checked, 462 ) 463 } 464 /> 465 </div> 466 <div> 467 <label for={"record" + index()} class="flex flex-col"> 468 <Show when={record.handle.length}> 469 <span>@{record.handle}</span> 470 </Show> 471 <span>{record.did}</span> 472 <span>{record.status_label}</span> 473 </label> 474 </div> 475 </div> 476 </Show> 477 )} 478 </For> 479 </div> 480 </div> 481 ); 482}; 483 484const App: Component = () => { 485 const [theme, setTheme] = createSignal( 486 ( 487 localStorage.theme === "dark" || 488 (!("theme" in localStorage) && 489 globalThis.matchMedia("(prefers-color-scheme: dark)").matches) 490 ) ? 491 "dark" 492 : "light", 493 ); 494 495 return ( 496 <div class="m-5 flex flex-col items-center text-slate-900 dark:text-slate-100"> 497 <div class="mb-2 flex w-[20rem] items-center"> 498 <div class="basis-1/3"> 499 <div 500 class="w-fit cursor-pointer" 501 onclick={() => { 502 setTheme(theme() === "light" ? "dark" : "light"); 503 if (theme() === "dark") 504 document.documentElement.classList.add("dark"); 505 else document.documentElement.classList.remove("dark"); 506 localStorage.theme = theme(); 507 }} 508 > 509 {theme() === "dark" ? 510 <TbMoonStar class="size-6" /> 511 : <TbSun class="size-6" />} 512 </div> 513 </div> 514 <div class="basis-1/3 text-center text-xl font-bold"> 515 <a href="">cleanfollow</a> 516 </div> 517 <div class="justify-right flex basis-1/3 gap-x-2"> 518 <a 519 href="https://bsky.app/profile/did:plc:b3pn34agqqchkaf75v7h43dk" 520 target="_blank" 521 > 522 <Bluesky class="size-6" /> 523 </a> 524 <a 525 href="https://github.com/notjuliet/cleanfollow-bsky" 526 target="_blank" 527 > 528 <AiFillGithub class="size-6" /> 529 </a> 530 </div> 531 </div> 532 <div class="mb-2 text-center"> 533 <p>Select inactive or blocked accounts to unfollow</p> 534 </div> 535 <Login /> 536 <Show when={loginState()}> 537 <Fetch /> 538 <Show when={followRecords.length}> 539 <Follows /> 540 </Show> 541 </Show> 542 </div> 543 ); 544}; 545 546export default App;