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