* init p2p polling app

This commit is contained in:
2026-03-31 19:09:46 +02:00
parent 4275cbd795
commit b5cb0e83e3
16 changed files with 638 additions and 1 deletions

94
app/app.vue Normal file
View File

@@ -0,0 +1,94 @@
<style>
/* Basic styling to make it look clean */
body {
font-family: system-ui, -apple-system, sans-serif;
background-color: #f4f4f9;
color: #333;
margin: 0;
display: flex;
justify-content: center;
padding: 2rem;
}
header {
margin-bottom: 2rem;
text-align: center;
}
h1 { margin: 0 0 0.5rem 0; }
input {
flex-grow: 1;
padding: 0.75rem;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 1rem;
}
button {
background: #3b82f6;
color: white;
border: none;
padding: 0.75rem 1rem;
border-radius: 6px;
cursor: pointer;
font-weight: bold;
transition: background 0.2s;
}
button:hover { background: #2563eb; }
.status {
font-size: 0.85rem;
color: #666;
}
.status .connected { color: #10b981; font-weight: bold; }
.connectionFailed { color: #FF2525; font-weight: bold; }
.poll-container {
background: white;
padding: 2rem;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
width: 100%;
max-width: 500px;
}
.back-btn {
margin-left: 1rem;
padding: 0.2rem 0.5rem;
font-size: 0.7rem;
background: #64748b;
}
</style>
<template>
<div class="poll-container">
<header>
<h1 @click="activePollId = null" style="cursor:pointer">P2P Polling App 🗳</h1>
<div class="status">
<button v-if="activePollId" @click="activePollId = null" class="back-btn"> Back To List</button>
<span :class="{ 'connected': isConnected }">
{{ isConnected ? 'Synced' : 'Waiting for other Peers...' }}
</span>
<span> | Peers online: {{ connectedPeers }}</span>
</div>
<h2 v-if="connectionAttempFailed" class="connectionFailed"> Connection to Signaling Server Failed!</h2>
</header>
<main>
<PollList v-if="!activePollId" @select-poll="selectPoll" />
<Poll v-else :activePollId="activePollId" :pollData="pollData" :addOption="addOption" :vote="vote"/>
</main>
</div>
</template>
<script setup lang="ts">
const activePollId = ref<string | null>(null);
const { pollData, isConnected, connectionAttempFailed, connectedPeers, addOption, vote } = usePoll(activePollId);
const selectPoll = (id: string) => {
activePollId.value = id;
};
</script>

84
app/components/Poll.vue Normal file
View File

@@ -0,0 +1,84 @@
<style scoped>
.poll-list {
list-style: none;
padding: 0;
margin: 0;
}
.poll-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 8px;
margin-bottom: 0.5rem;
}
.poll-title {
font-size: 1.1rem;
color: #3b82f6;
text-transform: uppercase;
letter-spacing: 1px;
}
.add-option-form {
display: flex;
gap: 0.5rem;
margin-bottom: 2rem;
}
.option-name { font-weight: 500; }
.vote-section { display: flex; align-items: center; gap: 1rem; }
.vote-count { font-size: 0.9rem; color: #475569; }
.vote-btn { padding: 0.4rem 0.8rem; background: #10b981; }
.vote-btn:hover { background: #059669; }
.vote-btn:disabled,
.vote-btn[disabled] { background: #888888; }
.vote-btn:disabled:hover,
.vote-btn[disabled]:hover { background: #AAAAAA; }
</style>
<template>
<div>
<h2 class="poll-title">Poll: {{ activePollId }}</h2>
<p v-if="Object.keys(pollData).length==0">Note: Add at least one Option to save the Poll.</p>
<form @submit.prevent="handleAddNewOption" class="add-option-form">
<input v-model="newOption" placeholder="Enter a new poll option..." required />
<button type="submit">Add Option</button>
</form>
<ul class="poll-list">
<li v-for="(votes, optionName) in pollData" :key="optionName" class="poll-item">
<span class="option-name">{{ optionName }}</span>
<div class="vote-section">
<span class="vote-count">{{ votes.length }} {{ votes.length === 1 ? 'vote' : 'votes' }}</span>
<button @click="vote(String(optionName),String(userGuid))" class="vote-btn" :disabled="voted(votes)">+1</button>
</div>
</li>
</ul>
</div>
</template>
<script setup lang="ts">
import type { PollProps, SignedData, VoteData } from '@/utils/types'
const props = defineProps<PollProps>()
const newOption = ref('');
const handleAddNewOption = () => {
props.addOption(newOption.value);
newOption.value = '';
};
const userGuid = useCookie('user_guid');
const voted = (votes: SignedData<VoteData>[]) => {
for(let vote of votes){
if(vote.data.userid == userGuid.value){
return true;
}
}
return false;
}
</script>

View File

@@ -0,0 +1,62 @@
<style scoped>
.poll-list { margin-top: 1rem; }
.empty-state { text-align: center; color: #94a3b8; font-style: italic; }
.create-poll { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
.poll-links { list-style: none; padding: 0; }
.poll-link-btn {
width: 100%;
text-align: left;
background: #f1f5f9;
color: #1e293b;
margin-bottom: 0.5rem;
display: flex;
justify-content: space-between;
}
.poll-link-btn:hover { background: #e2e8f0; }
</style>
<template>
<div class="poll-list">
<h3>Available Polls</h3>
<ul v-if="polls && polls.length > 0" class="poll-links">
<li v-for="id in polls" :key="id">
<button class="poll-link-btn" @click="$emit('select-poll', id)">
{{ id }} <span></span>
</button>
</li>
</ul>
<p v-else class="empty-state">No polls found. Create the first one!</p>
<div class="create-poll">
<input
v-model="newPollId"
placeholder="Enter new poll name..."
@keyup.enter="createPoll"
/>
<button @click="createPoll">Create & Join</button>
</div>
</div>
</template>
<script setup lang="ts">
const newPollId = ref('');
const polls = ref<string[]>([]);
// Fetch existing polls on mount
const fetchPolls = async () => {
const data = await $fetch<{ polls: string[] }>('/api/polls');
polls.value = data.polls;
};
const createPoll = () => {
const id = newPollId.value.trim().toLowerCase().replace(/\s+/g, '-');
if (id) {
// In a real app, you might want to POST to create it first,
// but here we just navigate to it and let usePoll handle the save.
emit('select-poll', id);
}
};
const emit = defineEmits(['select-poll']);
onMounted(fetchPolls);
</script>

View File

@@ -0,0 +1,99 @@
// composables/usePoll.ts
import { ref, watch, onUnmounted } from 'vue';
import * as Y from 'yjs';
export const usePoll = (pollId: Ref<string | null>) => {
const pollData = ref<PollData>({});
const isConnected = ref(false);
const connectionAttempFailed = ref(false);
const connectedPeers = ref(1);
let ydoc: Y.Doc | null = null;
let provider: any = null;
let yMap: Y.Map<SignedData<VoteData>[]> | null = null;
const cleanup = () => {
if (provider) provider.disconnect();
if (ydoc) ydoc.destroy();
isConnected.value = false;
pollData.value = {};
};
const initPoll = async (id: string) => {
cleanup(); // Clear previous session
ydoc = new Y.Doc();
// 1. Fetch Snapshot from Nuxt API
try {
const response = await $fetch<{ update: number[] | null }>(`/api/polls/${id}`);
if (response?.update) {
Y.applyUpdate(ydoc, new Uint8Array(response.update));
}
} catch (err) {
console.error('Persistence fetch failed', err);
}
yMap = ydoc.getMap<SignedData<VoteData>[]>('shared-poll');
// 2. Local State Sync
yMap.observe(() => {
pollData.value = yMap!.toJSON();
saveStateToServer(id);
});
pollData.value = yMap.toJSON();
// 3. P2P Connection
const { WebrtcProvider } = await import('y-webrtc');
provider = new WebrtcProvider(`nuxt-p2p-${id}`, ydoc, {
signaling: ["ws:localhost:4444", "ws:lynxpi.ddns.net:4444"]
});
provider.on('synced', (arg: {synced: boolean}) => isConnected.value = arg.synced);
provider.on('peers', (data: any) => connectedPeers.value = data.webrtcPeers.length + 1);
};
const saveStateToServer = async (id: string) => {
if (!ydoc) return;
const stateUpdate = Y.encodeStateAsUpdate(ydoc);
await $fetch(`/api/polls/${id}`, {
method: 'POST',
body: { update: Array.from(stateUpdate) }
}).catch(() => {});
};
// Watch for ID changes (e.g., user clicks a link or goes back)
watch(pollId, (newId) => {
if (newId && import.meta.client) {
initPoll(newId);
} else {
cleanup();
}
}, { immediate: true });
onUnmounted(cleanup);
const addOption = (optionName: string) => {
if (yMap && !yMap.has(optionName)) yMap.set(optionName, []);
};
const vote = (optionName: string, uuid: string) => {
if (yMap?.has(optionName)) {
var voteData : SignedData<VoteData>[] | undefined = yMap.get(optionName)
if(voteData != undefined){
var unsignedVoteData : VoteData = {
userid: uuid,
timestamp: new Date().toISOString()
}
var newVote : SignedData<VoteData> = {
data: unsignedVoteData,
signature: "",
}
voteData?.push(newVote)
yMap.set(optionName, voteData);
}
}
};
return { pollData, isConnected, connectionAttempFailed, connectedPeers, addOption, vote };
};

42
app/utils/crypto.ts Normal file
View File

@@ -0,0 +1,42 @@
// utils/crypto.ts
export const generateUserKeyPair = async () => {
return await window.crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]), // 65537
hash: "SHA-256",
},
true, // extractable
["sign", "verify"]
);
};
export const signVote = async (data: any, privateKey: CryptoKey) => {
const encoder = new TextEncoder();
const encodedData = encoder.encode(JSON.stringify(data));
const signature = await window.crypto.subtle.sign(
"RSASSA-PKCS1-v1_5",
privateKey,
encodedData
);
// Convert to Base64 or Hex to store in Yjs easily
return btoa(String.fromCharCode(...new Uint8Array(signature)));
};
export const verifyVote = async (data: any, signatureStr: string, publicKey: CryptoKey) => {
const encoder = new TextEncoder();
const encodedData = encoder.encode(JSON.stringify(data));
// Convert Base64 back to Uint8Array
const signature = Uint8Array.from(atob(signatureStr), c => c.charCodeAt(0));
return await window.crypto.subtle.verify(
"RSASSA-PKCS1-v1_5",
publicKey,
signature,
encodedData
);
};

25
app/utils/types.ts Normal file
View File

@@ -0,0 +1,25 @@
export interface PollProps {
activePollId: string,
pollData: PollData,
addOption: (name: string) => void,
vote: (optionName: string,uuid: string) => void
}
export interface PollData extends Record<string, SignedData<VoteData>[]> {
}
export interface SignedData<T> {
data: T,
signature: string
}
export interface VoteData {
userid: string,
timestamp: string
}
export interface OptionData {
userid: string,
timestamp: string,
optionName: string
}