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