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