Run a giveaway from a bsky post. Choose from those who interacted with it
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
6 <meta property="og:title" content="at://giveaways 🎉">
7 <meta property="og:image" content="/images/cover.jpg">
8 <meta property="og:description" content="Host a giveaway from a Bluesky post.">
9
10 <title>at://giveaways 🎉</title>
11 <link href="https://cdn.jsdelivr.net/npm/daisyui@5" rel="stylesheet" type="text/css"/>
12 <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
13 <script src="https://unpkg.com/alpinejs" defer></script>
14
15 <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
16 <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
17 <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
18 <link rel="manifest" href="/site.webmanifest">
19
20 <script type="module">
21 import {
22 CompositeHandleResolver,
23 DohJsonHandleResolver,
24 WellKnownHandleResolver,
25 CompositeDidDocumentResolver,
26 PlcDidDocumentResolver,
27 WebDidDocumentResolver
28 } from 'https://esm.sh/@atcute/identity-resolver';
29
30 const handleResolver = new CompositeHandleResolver({
31 strategy: 'race',
32 methods: {
33 dns: new DohJsonHandleResolver({dohUrl: 'https://mozilla.cloudflare-dns.com/dns-query'}),
34 http: new WellKnownHandleResolver(),
35 },
36 });
37
38 window.resolveHandle = async (handle) => await handleResolver.resolve(handle);
39
40 const docResolver = new CompositeDidDocumentResolver({
41 methods: {
42 plc: new PlcDidDocumentResolver(),
43 web: new WebDidDocumentResolver(),
44 },
45 });
46
47 window.resolveDidDocument = async (did) => await docResolver.resolve(did);
48
49 </script>
50
51 <script>
52
53 const constellationEndpoint = 'https://constellation.microcosm.blue';
54 const likesCollection = 'app.bsky.feed.like';
55 const repostsCollection = 'app.bsky.feed.repost';
56
57 function getQueryParams() {
58 const params = new URLSearchParams(window.location.search);
59
60 // Get post_url and validate it's a Bluesky URL or AT URI
61 let postUrl = params.get('post_url') || '';
62 if (postUrl && !postUrl.startsWith('https://bsky.app/') && !postUrl.startsWith('at://')) {
63 console.warn('Invalid post_url parameter. Must be a Bluesky URL or AT URI.');
64 postUrl = '';
65 }
66
67 // Get winner_count and ensure it's a positive number
68 let winnerCount = parseInt(params.get('winner_count')) || 1;
69 if (winnerCount < 1) {
70 console.warn('Invalid winner_count parameter. Must be a positive number.');
71 winnerCount = 1;
72 }
73
74 // Get option and ensure it's one of the valid options
75 let option = params.get('option') || 'likes';
76 if (option && !['likes', 'reposts', 'both'].includes(option)) {
77 console.warn('Invalid option parameter. Must be "likes", "reposts", or "both".');
78 option = 'likes';
79 }
80
81 return {
82 post_url: postUrl,
83 winner_count: winnerCount,
84 option: option
85 };
86 }
87
88 async function callConstellationEndpoint(target, collection, path, cursor = null) {
89 try {
90 const url = new URL(`${constellationEndpoint}/links/distinct-dids`);
91 url.searchParams.append('target', target);
92 url.searchParams.append('collection', collection);
93 url.searchParams.append('path', path);
94 if (cursor) {
95 url.searchParams.append('cursor', cursor);
96 }
97 const response = await fetch(url);
98 if (!response.ok) {
99 throw new Error(`HTTP error! Status: ${response.status}`);
100 }
101
102 return await response.json();
103 } catch (error) {
104 console.error('Error calling constellation endpoint:', error);
105 throw error;
106 }
107 }
108
109 document.addEventListener('alpine:init', () => {
110 Alpine.data('giveaway', () => ({
111 //Form input
112 post_url: '',
113 winner_count: 1,
114 likes_only: true,
115 reposts_only: false,
116 likes_and_reposts: false,
117
118 error: '',
119 loading: false,
120 winners: [],
121 participants: 0,
122 showResults: false,
123
124 // Initialize component with query parameters
125 init() {
126 const params = getQueryParams();
127
128 // Set form values from query parameters
129 if (params.post_url) {
130 this.post_url = params.post_url;
131 }
132
133 if (params.winner_count && params.winner_count > 0) {
134 this.winner_count = params.winner_count;
135 }
136
137 // Set winning options based on the option parameter
138 if (params.option) {
139 this.likes_only = params.option === 'likes';
140 this.reposts_only = params.option === 'reposts';
141 this.likes_and_reposts = params.option === 'both';
142 }
143
144 // Automatically run the giveaway if post_url is provided
145 if (params.post_url) {
146 // Use setTimeout to ensure the component is fully initialized
147 setTimeout(() => {
148 this.runGiveaway();
149 }, 100);
150 }
151 },
152
153 validateCheckBoxes(event) {
154 const targetId = event.target.id;
155 this.likes_only = targetId === 'likes';
156 this.reposts_only = targetId === 'reposts_only';
157 this.likes_and_reposts = targetId === 'likes_and_reposts';
158 },
159 async runGiveaway() {
160 this.error = '';
161 this.loading = true;
162 this.winners = [];
163 this.showResults = false;
164
165 try {
166 //Form validation
167 if (this.winner_count < 1) {
168 this.error = 'SOMEBODY has to win';
169 return;
170 }
171
172 if (!this.likes_only && !this.reposts_only && !this.likes_and_reposts) {
173 this.error = 'Well, you have to pick some way for them to win';
174 return;
175 }
176
177 let atUri = '';
178 if (this.post_url.startsWith('at://')) {
179 atUri = this.post_url;
180 } else {
181 //More checks to make sure it's a bsky url
182 if (!this.post_url.startsWith('https://bsky.app/')) {
183 this.error = 'Link to the Bluesky post or at uri please';
184 return;
185 }
186 const postSplit = this.post_url.split('/');
187 if (postSplit.length < 7) {
188 this.error = 'Invalid Bluesky post URL. Should look like https://bsky.app/profile/baileytownsend.dev/post/3lbq7o74fcc2d';
189 return;
190 }
191 try {
192 const handle = postSplit[4];
193 const recordKey = postSplit[6];
194
195 let did = await window.resolveHandle(handle);
196 atUri = `at://${did}/app.bsky.feed.post/${recordKey}`;
197
198 } catch (e) {
199 console.log(e);
200 this.error = e.message;
201 return;
202 }
203 }
204
205
206 // Determine which collections to fetch based on user selection
207 const collections = [];
208 if (this.likes_only || this.likes_and_reposts) {
209 collections.push(likesCollection);
210 }
211 if (this.reposts_only || this.likes_and_reposts) {
212 collections.push(repostsCollection);
213 }
214
215 // Path to extract the subject URI
216 const path = '.subject.uri';
217
218 // Fetch data for each collection
219 const results = [];
220 for (const collection of collections) {
221 console.log(`Fetching ${collection} data...`);
222 let cursor = null;
223 let pageCount = 1;
224
225 do {
226 console.log(`Fetching ${collection} data, page ${pageCount}${cursor ? ' with cursor' : ''}...`);
227 const response = await callConstellationEndpoint(atUri, collection, path, cursor);
228 console.log(`${collection} response (page ${pageCount}):`, response);
229
230 if (response && response.linking_dids) {
231 let dids = response.linking_dids.map(x => ({
232 collection: collection,
233 did: x
234 }))
235 results.push(...dids);
236 cursor = response.cursor;
237 pageCount++;
238 } else {
239 cursor = null;
240 }
241 } while (cursor);
242
243 console.log(`Completed fetching ${collection} data, total pages: ${pageCount - 1}`);
244 }
245
246
247 let uniqueDids = [];
248 if (this.likes_only || this.reposts_only) {
249 uniqueDids = results.map(x => x.did);
250 }
251 if (this.likes_and_reposts) {
252 const likesDids = results.filter(x => x.collection === likesCollection).map(x => x.did);
253 const repostsDids = results.filter(x => x.collection === repostsCollection).map(x => x.did);
254 uniqueDids = likesDids.filter(did => repostsDids.includes(did));
255 }
256
257 this.participants = uniqueDids.length;
258 // Select winners
259 if (uniqueDids.length === 0) {
260 this.error = 'No participants found for this post';
261 return;
262 }
263
264 const winnerCount = Math.min(this.winner_count, uniqueDids.length);
265
266 // Randomly select winners
267 for (let i = 0; i < winnerCount; i++) {
268 const randomIndex = Math.floor(Math.random() * uniqueDids.length);
269 try {
270 const didDoc = await window.resolveDidDocument(uniqueDids[randomIndex]);
271 const handle = didDoc.alsoKnownAs[0].replace("at://", "") ?? uniqueDids[randomIndex];
272 this.winners.push(handle);
273 } catch (e) {
274 console.log(e);
275 this.winners.push(uniqueDids[randomIndex]);
276 }
277
278 // Remove the winner to avoid duplicates
279 uniqueDids.splice(randomIndex, 1);
280 }
281
282 this.showResults = true;
283
284 } catch (error) {
285 console.error('Error in runGiveaway:', error);
286 this.error = `Error fetching data: ${error.message}`;
287 } finally {
288 this.loading = false;
289 }
290 }
291
292 }))
293 })
294 </script>
295</head>
296
297
298<body>
299<div class="hero bg-base-200 min-h-screen">
300 <div class="hero-content flex-col ">
301 <div class="text-center">
302 <h1 class="text-5xl font-bold">at://giveaways 🎉</h1>
303 <p class="py-6">
304 Pick which Bluesky post you want to use for a giveaway.
305 </p>
306 <div>uses <a class="link" href="https://constellation.microcosm.blue/">constellation
307 🌌</a>
308 powered
309 by
310 <a href="https://microcosm.blue" class="link"><span
311 style="color: rgb(243, 150, 169);">m</span><span style="color: rgb(244, 156, 92);">i</span><span
312 style="color: rgb(199, 176, 76);">c</span><span style="color: rgb(146, 190, 76);">r</span><span
313 style="color: rgb(78, 198, 136);">o</span><span style="color: rgb(81, 194, 182);">c</span><span
314 style="color: rgb(84, 190, 215);">o</span><span style="color: rgb(143, 177, 241);">s</span><span
315 style="color: rgb(206, 157, 241);">m</span></a>
316 </div>
317 </div>
318 <div class="card bg-base-100 w-full max-w-sm shrink-0 shadow-2xl">
319 <div class="card-body" x-data="giveaway">
320 <form x-on:submit.prevent="await runGiveaway()">
321 <fieldset class="fieldset">
322 <label for="post_url" class="label">Post Url</label>
323 <input x-model="post_url" id="post_url" type="text" class="input"
324 placeholder="https://bsky.app/profile/baileytownsend.dev/post/3lutd557tyk2y"/>
325 <label for="winner_count" class="label">How many winners?</label>
326 <input x-model="winner_count" id="winner_count" type="number" class="input" value="1"/>
327 <fieldset class="fieldset bg-base-100 border-base-300 rounded-box w-64 border p-4">
328 <legend class="fieldset-legend">Winning options</legend>
329 <label class="label">
330 <input x-model="likes_only" x-on:change="validateCheckBoxes($event)"
331 id="likes"
332 type="checkbox"
333 checked="checked"
334 class="checkbox"/>
335 Likes only
336 </label>
337 <label class="label">
338 <input x-model="reposts_only" x-on:change="validateCheckBoxes($event)" id="reposts_only"
339 type="checkbox"
340 class="checkbox"/>
341 Reposts only
342 </label>
343 <label class="label">
344 <input x-model="likes_and_reposts" x-on:change="validateCheckBoxes($event)"
345 id="likes_and_reposts"
346 type="checkbox"
347 class="checkbox"/>
348 Likes & Reposts
349 </label>
350
351 </fieldset>
352 <span x-show="error" x-text="error" class="text-red-500 text-lg font-bold"></span>
353 <button type="submit" class="btn btn-neutral mt-4" x-bind:disabled="loading">
354 <span x-show="!loading">I choose you!</span>
355 <span x-show="loading" class="loading loading-spinner"></span>
356 </button>
357 </fieldset>
358 </form>
359
360 <!-- Results Section -->
361 <div x-show="showResults" class="mt-6 p-4 bg-base-200 rounded-lg">
362 <h3 class="text-xl font-bold mb-2">🎉 Winners 🎉</h3>
363 <p class="mb-2">Total participants: <span x-text="participants"></span></p>
364 <ol class="list-decimal pl-5">
365 <template x-for="winner in winners">
366 <li class="mb-1">
367 <a class="link" x-bind:href="`https://bsky.app/profile/${winner}`" x-text="winner"></a>
368 </li>
369 </template>
370 </ol>
371 <a x-bind:href="post_url" class="link">View the giveaway post</a>
372 </div>
373
374 <a href="https://tangled.sh/@baileytownsend.dev/at-giveaways" class="link mt-4 block">View on <span
375 class="font-semibold italic">tangled.sh</span></a>
376
377 <!-- URL Parameters Documentation -->
378 <div class="mt-6 p-4 bg-base-200 rounded-lg text-sm">
379 <h3 class="text-lg font-bold mb-2">🔗 URL Parameters</h3>
380 <p class="mb-2">You can create links that automatically run giveaways with these GET query parameters:</p>
381 <ul class="list-disc pl-5 mb-2">
382 <li><code>post_url</code>: URL of the Bluesky post</li>
383 <li><code>winner_count</code>: Number of winners (default: 1)</li>
384 <li><code>option</code>: 'likes', 'reposts', or 'both' (default: 'likes')</li>
385 </ul>
386
387 </div>
388 </div>
389 </div>
390 </div>
391</div>
392</body>
393</html>