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 url.searchParams.append('limit', '100');
95 if (cursor) {
96 url.searchParams.append('cursor', cursor);
97 }
98 const response = await fetch(url);
99 if (!response.ok) {
100 throw new Error(`HTTP error! Status: ${response.status}`);
101 }
102
103 return await response.json();
104 } catch (error) {
105 console.error('Error calling constellation endpoint:', error);
106 throw error;
107 }
108 }
109
110 document.addEventListener('alpine:init', () => {
111 Alpine.data('giveaway', () => ({
112 //Form input
113 post_url: '',
114 winner_count: 1,
115 likes_only: true,
116 reposts_only: false,
117 likes_and_reposts: false,
118
119 error: '',
120 loading: false,
121 winners: [],
122 participants: 0,
123 showResults: false,
124 statusText: '',
125
126 // Initialize component with query parameters
127 init() {
128 const params = getQueryParams();
129
130 // Set form values from query parameters
131 if (params.post_url) {
132 this.post_url = params.post_url;
133 }
134
135 if (params.winner_count && params.winner_count > 0) {
136 this.winner_count = params.winner_count;
137 }
138
139 // Set winning options based on the option parameter
140 if (params.option) {
141 this.likes_only = params.option === 'likes';
142 this.reposts_only = params.option === 'reposts';
143 this.likes_and_reposts = params.option === 'both';
144 }
145
146 // Automatically run the giveaway if post_url is provided
147 if (params.post_url) {
148 // Use setTimeout to ensure the component is fully initialized
149 setTimeout(() => {
150 this.runGiveaway();
151 }, 100);
152 }
153 },
154
155 validateCheckBoxes(event) {
156 const targetId = event.target.id;
157 this.likes_only = targetId === 'likes';
158 this.reposts_only = targetId === 'reposts_only';
159 this.likes_and_reposts = targetId === 'likes_and_reposts';
160 },
161 async runGiveaway() {
162 this.error = '';
163 this.loading = true;
164 this.winners = [];
165 this.showResults = false;
166
167 try {
168 //Form validation
169 if (this.winner_count < 1) {
170 this.error = 'SOMEBODY has to win';
171 return;
172 }
173
174 if (!this.likes_only && !this.reposts_only && !this.likes_and_reposts) {
175 this.error = 'Well, you have to pick some way for them to win';
176 return;
177 }
178
179 let atUri = '';
180 if (this.post_url.startsWith('at://')) {
181 atUri = this.post_url;
182 } else {
183 //More checks to make sure it's a bsky url
184 if (!this.post_url.startsWith('https://bsky.app/')) {
185 this.error = 'Link to the Bluesky post or at uri please';
186 return;
187 }
188 const postSplit = this.post_url.split('/');
189 if (postSplit.length < 7) {
190 this.error = 'Invalid Bluesky post URL. Should look like https://bsky.app/profile/baileytownsend.dev/post/3lbq7o74fcc2d';
191 return;
192 }
193 try {
194 const handle = postSplit[4];
195 const recordKey = postSplit[6];
196
197 let did = await window.resolveHandle(handle);
198 atUri = `at://${did}/app.bsky.feed.post/${recordKey}`;
199
200 } catch (e) {
201 console.log(e);
202 this.error = e.message;
203 return;
204 }
205 }
206
207
208 // Determine which collections to fetch based on user selection
209 const collections = [];
210 if (this.likes_only || this.likes_and_reposts) {
211 collections.push(likesCollection);
212 }
213 if (this.reposts_only || this.likes_and_reposts) {
214 collections.push(repostsCollection);
215 }
216
217 // Path to extract the subject URI
218 const path = '.subject.uri';
219
220 // Fetch data for each collection
221 const results = [];
222 for (const collection of collections) {
223 console.log(`Fetching ${collection} data...`);
224 let cursor = null;
225 let pageCount = 1;
226 let displayTypeText = ''
227 let displayTotal = 0;
228 if (collection === likesCollection) {
229 displayTypeText = 'likes'
230 }else if (collection === repostsCollection) {
231 displayTypeText = 'reposts'
232 }
233 else {
234 displayTypeText = 'both'
235 }
236 do {
237 console.log(`Fetching ${collection} data, page ${pageCount}${cursor ? ' with cursor' : ''}...`);
238 const response = await callConstellationEndpoint(atUri, collection, path, cursor);
239 console.log(`${collection} response (page ${pageCount}):`, response);
240
241 if (response && response.linking_dids) {
242 displayTotal += response.linking_dids.length;
243 this.statusText = `${displayTotal}/${response.total} ${displayTypeText} fetched.`;
244
245 let dids = response.linking_dids.map(x => ({
246 collection: collection,
247 did: x
248 }))
249 results.push(...dids);
250 cursor = response.cursor;
251 pageCount++;
252 } else {
253 cursor = null;
254 }
255 } while (cursor);
256
257 console.log(`Completed fetching ${collection} data, total pages: ${pageCount - 1}`);
258 }
259
260
261 let uniqueDids = [];
262 if (this.likes_only || this.reposts_only) {
263 uniqueDids = results.map(x => x.did);
264 }
265 if (this.likes_and_reposts) {
266 const likesDids = results.filter(x => x.collection === likesCollection).map(x => x.did);
267 const repostsDids = results.filter(x => x.collection === repostsCollection).map(x => x.did);
268 uniqueDids = likesDids.filter(did => repostsDids.includes(did));
269 }
270
271 this.participants = uniqueDids.length;
272 // Select winners
273 if (uniqueDids.length === 0) {
274 this.error = 'No participants found for this post';
275 return;
276 }
277
278 const winnerCount = Math.min(this.winner_count, uniqueDids.length);
279
280 // Randomly select winners
281 for (let i = 0; i < winnerCount; i++) {
282 const randomIndex = Math.floor(Math.random() * uniqueDids.length);
283 try {
284 const didDoc = await window.resolveDidDocument(uniqueDids[randomIndex]);
285 const handle = didDoc.alsoKnownAs[0].replace("at://", "") ?? uniqueDids[randomIndex];
286 this.winners.push(handle);
287 } catch (e) {
288 console.log(e);
289 this.winners.push(uniqueDids[randomIndex]);
290 }
291
292 // Remove the winner to avoid duplicates
293 uniqueDids.splice(randomIndex, 1);
294 }
295
296 this.showResults = true;
297
298 } catch (error) {
299 console.error('Error in runGiveaway:', error);
300 this.error = `Error fetching data: ${error.message}`;
301 } finally {
302 this.loading = false;
303 }
304 }
305
306 }))
307 })
308 </script>
309</head>
310
311
312<body>
313<div class="hero bg-base-200 min-h-screen">
314 <div class="hero-content flex-col ">
315 <div class="text-center">
316 <h1 class="text-5xl font-bold">at://giveaways 🎉</h1>
317 <p class="py-6">
318 Pick which Bluesky post you want to use for a giveaway.
319 </p>
320 <div>uses <a class="link" href="https://constellation.microcosm.blue/">constellation
321 🌌</a>
322 powered
323 by
324 <a href="https://microcosm.blue" class="link"><span
325 style="color: rgb(243, 150, 169);">m</span><span style="color: rgb(244, 156, 92);">i</span><span
326 style="color: rgb(199, 176, 76);">c</span><span style="color: rgb(146, 190, 76);">r</span><span
327 style="color: rgb(78, 198, 136);">o</span><span style="color: rgb(81, 194, 182);">c</span><span
328 style="color: rgb(84, 190, 215);">o</span><span style="color: rgb(143, 177, 241);">s</span><span
329 style="color: rgb(206, 157, 241);">m</span></a>
330 </div>
331 </div>
332 <div class="card bg-base-100 w-full max-w-sm shrink-0 shadow-2xl">
333 <div class="card-body" x-data="giveaway">
334 <form x-on:submit.prevent="await runGiveaway()">
335 <fieldset class="fieldset">
336 <label for="post_url" class="label">Post Url</label>
337 <input x-model="post_url" id="post_url" type="text" class="input"
338 placeholder="https://bsky.app/profile/baileytownsend.dev/post/3lutd557tyk2y"/>
339 <label for="winner_count" class="label">How many winners?</label>
340 <input x-model="winner_count" id="winner_count" type="number" class="input" value="1"/>
341 <fieldset class="fieldset bg-base-100 border-base-300 rounded-box w-64 border p-4">
342 <legend class="fieldset-legend">Winning options</legend>
343 <label class="label">
344 <input x-model="likes_only" x-on:change="validateCheckBoxes($event)"
345 id="likes"
346 type="checkbox"
347 checked="checked"
348 class="checkbox"/>
349 Likes only
350 </label>
351 <label class="label">
352 <input x-model="reposts_only" x-on:change="validateCheckBoxes($event)" id="reposts_only"
353 type="checkbox"
354 class="checkbox"/>
355 Reposts only
356 </label>
357 <label class="label">
358 <input x-model="likes_and_reposts" x-on:change="validateCheckBoxes($event)"
359 id="likes_and_reposts"
360 type="checkbox"
361 class="checkbox"/>
362 Likes & Reposts
363 </label>
364
365 </fieldset>
366 <span x-show="error" x-text="error" class="text-red-500 text-lg font-bold"></span>
367 <span x-show="statusText && loading" x-text="statusText" class="text-gray-500 text-lg font-bold"></span>
368 <span x-show="statusText && loading" class="text-gray-500 text-sm font-bold">Posts with lots of likes and reposts can take a while. It will show an error if it fails.</span>
369 <button type="submit" class="btn btn-neutral mt-4" x-bind:disabled="loading">
370 <span x-show="!loading">I choose you!</span>
371 <span x-show="loading" class="loading loading-spinner"></span>
372 </button>
373 </fieldset>
374 </form>
375
376 <!-- Results Section -->
377 <div x-show="showResults" class="mt-6 p-4 bg-base-200 rounded-lg">
378 <h3 class="text-xl font-bold mb-2">🎉 Winners 🎉</h3>
379 <p class="mb-2">Total participants: <span x-text="participants"></span></p>
380 <ol class="list-decimal pl-5">
381 <template x-for="winner in winners">
382 <li class="mb-1">
383 <a class="link" x-bind:href="`https://bsky.app/profile/${winner}`" x-text="winner"></a>
384 </li>
385 </template>
386 </ol>
387 <a x-bind:href="post_url" class="link">View the giveaway post</a>
388 </div>
389
390 <a href="https://tangled.sh/@baileytownsend.dev/at-giveaways" class="link mt-4 block">View on <span
391 class="font-semibold italic">tangled.sh</span></a>
392
393 <!-- URL Parameters Documentation -->
394 <div class="mt-6 p-4 bg-base-200 rounded-lg text-sm">
395 <h3 class="text-lg font-bold mb-2">🔗 URL Parameters</h3>
396 <p class="mb-2">You can create links that automatically run the giveaway when the page is loaded with these GET query parameters:</p>
397 <ul class="list-disc pl-5 mb-2">
398 <li><code>post_url</code>: URL of the Bluesky post</li>
399 <li><code>winner_count</code>: Number of winners (default: 1)</li>
400 <li><code>option</code>: 'likes', 'reposts', or 'both' (default: 'likes')</li>
401 </ul>
402
403 </div>
404 </div>
405 </div>
406 </div>
407</div>
408</body>
409</html>