FEATURE: added pols
This commit is contained in:
parent
2379e8dae5
commit
c0391f8e69
Binary file not shown.
Binary file not shown.
|
|
@ -131,3 +131,125 @@ def register_routes(app):
|
|||
except Exception as e:
|
||||
response.status = 500
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
@app.route("/api/polls", method="POST")
|
||||
def create_poll():
|
||||
ip = request.environ.get("REMOTE_ADDR", "127.0.0.1")
|
||||
if not _check_rate(ip):
|
||||
response.status = 429
|
||||
return {"success": False, "error": "Rate limit exceeded. Slow down."}
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
if not data:
|
||||
response.status = 400
|
||||
return {"success": False, "error": "No data"}
|
||||
|
||||
channel = data.get("channel", "general")
|
||||
question = data.get("question", "").strip()
|
||||
options = data.get("options", [])
|
||||
|
||||
if channel not in VALID_CHANNELS:
|
||||
response.status = 400
|
||||
return {"success": False, "error": "Invalid channel"}
|
||||
if not question:
|
||||
response.status = 400
|
||||
return {"success": False, "error": "Question is required"}
|
||||
if len(question) > 500:
|
||||
response.status = 400
|
||||
return {"success": False, "error": "Question too long"}
|
||||
if len(options) < 2:
|
||||
response.status = 400
|
||||
return {"success": False, "error": "At least 2 options required"}
|
||||
if len(options) > 20:
|
||||
response.status = 400
|
||||
return {"success": False, "error": "Maximum 20 options allowed"}
|
||||
for opt in options:
|
||||
if not opt.strip():
|
||||
response.status = 400
|
||||
return {"success": False, "error": "Option cannot be empty"}
|
||||
if len(opt) > 200:
|
||||
response.status = 400
|
||||
return {"success": False, "error": "Option too long"}
|
||||
|
||||
ip_hash = hashlib.sha256((_salt + ip).encode()).hexdigest()[:16]
|
||||
expires_at = data.get("expires_at")
|
||||
is_multiple = data.get("is_multiple", False)
|
||||
is_anonymous = data.get("is_anonymous", False)
|
||||
|
||||
poll_id = _db.add_poll(
|
||||
channel=channel,
|
||||
creator_ip=ip_hash,
|
||||
question=question,
|
||||
options=options,
|
||||
expires_at=expires_at,
|
||||
is_multiple=is_multiple,
|
||||
is_anonymous=is_anonymous,
|
||||
)
|
||||
return {"success": True, "poll_id": poll_id}
|
||||
except Exception as e:
|
||||
response.status = 500
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
@app.route("/api/polls", method="GET")
|
||||
def list_polls():
|
||||
try:
|
||||
channel = request.query.get("channel", "general")
|
||||
if channel not in VALID_CHANNELS:
|
||||
channel = "general"
|
||||
polls = _db.get_polls(channel=channel)
|
||||
return {"success": True, "polls": polls}
|
||||
except Exception as e:
|
||||
response.status = 500
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
@app.route("/api/polls/<poll_id:int>", method="GET")
|
||||
def get_poll(poll_id):
|
||||
try:
|
||||
poll = _db.get_poll(poll_id)
|
||||
if not poll:
|
||||
response.status = 404
|
||||
return {"success": False, "error": "Poll not found"}
|
||||
return {"success": True, "poll": poll}
|
||||
except Exception as e:
|
||||
response.status = 500
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
@app.route("/api/polls/<poll_id:int>/vote", method="POST")
|
||||
def vote_poll(poll_id):
|
||||
ip = request.environ.get("REMOTE_ADDR", "127.0.0.1")
|
||||
try:
|
||||
data = request.json
|
||||
if not data or "option_id" not in data:
|
||||
response.status = 400
|
||||
return {"success": False, "error": "option_id required"}
|
||||
|
||||
ip_hash = hashlib.sha256((_salt + ip).encode()).hexdigest()[:16]
|
||||
ok, msg = _db.vote(poll_id, data["option_id"], ip_hash)
|
||||
if not ok:
|
||||
response.status = 400
|
||||
return {"success": False, "error": msg}
|
||||
return {"success": True, "message": msg}
|
||||
except Exception as e:
|
||||
response.status = 500
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
@app.route("/api/polls/<poll_id:int>/close", method="POST")
|
||||
def close_poll(poll_id):
|
||||
ip = request.environ.get("REMOTE_ADDR", "127.0.0.1")
|
||||
ip_hash = hashlib.sha256((_salt + ip).encode()).hexdigest()[:16]
|
||||
|
||||
auth = request.get_header("Authorization", "")
|
||||
token = auth.replace("Bearer ", "")
|
||||
if _admin_token and token == _admin_token:
|
||||
ok, msg = _db.close_poll(poll_id, requester_ip=ip_hash)
|
||||
if not ok:
|
||||
response.status = 400
|
||||
return {"success": False, "error": msg}
|
||||
return {"success": True, "message": msg}
|
||||
|
||||
ok, msg = _db.close_poll(poll_id, requester_ip=ip_hash)
|
||||
if not ok:
|
||||
response.status = 400
|
||||
return {"success": False, "error": msg}
|
||||
return {"success": True, "message": msg}
|
||||
|
|
|
|||
470
index.html
470
index.html
|
|
@ -245,6 +245,220 @@
|
|||
.toast.error { background: #c0392b; color: #fff; }
|
||||
.toast.success { background: #27ae60; color: #fff; }
|
||||
.toast.info { background: #2980b9; color: #fff; }
|
||||
.poll-card {
|
||||
background: #1a2d4a;
|
||||
border-radius: 8px;
|
||||
padding: 14px;
|
||||
margin-bottom: 12px;
|
||||
border-left: 3px solid #f39c12;
|
||||
}
|
||||
.poll-card .poll-question {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: #f1c40f;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.poll-card .poll-meta {
|
||||
font-size: 11px;
|
||||
color: #6a8aaa;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.poll-card .poll-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 8px 10px;
|
||||
margin-bottom: 4px;
|
||||
background: #0f2040;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
.poll-card .poll-option:hover { background: #1a3a5a; }
|
||||
.poll-card .poll-option .poll-bar {
|
||||
position: absolute;
|
||||
left: 0; top: 0; bottom: 0;
|
||||
background: rgba(46, 204, 113, 0.15);
|
||||
border-radius: 6px;
|
||||
transition: width 0.3s;
|
||||
}
|
||||
.poll-card .poll-option .poll-label {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 1;
|
||||
font-size: 14px;
|
||||
}
|
||||
.poll-card .poll-option .poll-pct {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
font-size: 12px;
|
||||
color: #7ec8a3;
|
||||
min-width: 36px;
|
||||
text-align: right;
|
||||
}
|
||||
.poll-card .poll-option .poll-votes {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
font-size: 11px;
|
||||
color: #556677;
|
||||
margin-left: 8px;
|
||||
min-width: 20px;
|
||||
text-align: right;
|
||||
}
|
||||
.poll-card .poll-option.voted {
|
||||
border: 1px solid #2ecc71;
|
||||
}
|
||||
.poll-card .poll-footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-top: 8px;
|
||||
font-size: 12px;
|
||||
color: #556677;
|
||||
}
|
||||
.poll-card .poll-footer button {
|
||||
padding: 4px 12px;
|
||||
background: transparent;
|
||||
border: 1px solid #6a8aaa;
|
||||
border-radius: 4px;
|
||||
color: #a0c4ff;
|
||||
font-size: 11px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.poll-card .poll-footer button:hover {
|
||||
background: #e94560;
|
||||
border-color: #e94560;
|
||||
color: #fff;
|
||||
}
|
||||
.poll-card .poll-status {
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.poll-card .poll-status.active { background: #27ae60; color: #fff; }
|
||||
.poll-card .poll-status.closed { background: #7f8c8d; color: #fff; }
|
||||
.poll-modal-overlay {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0; left: 0; right: 0; bottom: 0;
|
||||
background: rgba(0,0,0,0.6);
|
||||
z-index: 2000;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
.poll-modal-overlay.open { display: flex; }
|
||||
.poll-modal {
|
||||
background: #16213e;
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
width: 90%;
|
||||
max-width: 500px;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.poll-modal h2 {
|
||||
color: #f1c40f;
|
||||
margin-bottom: 16px;
|
||||
font-size: 18px;
|
||||
}
|
||||
.poll-modal label {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
color: #a0c4ff;
|
||||
margin-bottom: 4px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.poll-modal input[type="text"],
|
||||
.poll-modal textarea {
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #1a4a7a;
|
||||
border-radius: 6px;
|
||||
background: #121e38;
|
||||
color: #e0e0e0;
|
||||
font-size: 14px;
|
||||
outline: none;
|
||||
}
|
||||
.poll-modal input:focus, .poll-modal textarea:focus { border-color: #e94560; }
|
||||
.poll-modal textarea { resize: vertical; min-height: 60px; font-family: inherit; }
|
||||
.poll-modal .poll-opt-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.poll-modal .poll-opt-row input { flex: 1; }
|
||||
.poll-modal .poll-opt-row button {
|
||||
padding: 6px 10px;
|
||||
background: transparent;
|
||||
border: 1px solid #e74c3c;
|
||||
border-radius: 4px;
|
||||
color: #e74c3c;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
.poll-modal .poll-opt-row button:hover { background: #e74c3c; color: #fff; }
|
||||
.poll-modal .add-opt-btn {
|
||||
padding: 6px 14px;
|
||||
background: transparent;
|
||||
border: 1px dashed #2a4a7a;
|
||||
border-radius: 6px;
|
||||
color: #6a8aaa;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
margin-top: 4px;
|
||||
width: 100%;
|
||||
}
|
||||
.poll-modal .add-opt-btn:hover {
|
||||
border-color: #e94560;
|
||||
color: #e94560;
|
||||
}
|
||||
.poll-modal .modal-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin-top: 16px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.poll-modal .modal-actions button {
|
||||
padding: 8px 20px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
}
|
||||
.poll-modal .modal-actions .btn-cancel {
|
||||
background: #2a3a5a;
|
||||
color: #8899aa;
|
||||
}
|
||||
.poll-modal .modal-actions .btn-cancel:hover { background: #3a4a6a; }
|
||||
.poll-modal .modal-actions .btn-create {
|
||||
background: #e94560;
|
||||
color: #fff;
|
||||
}
|
||||
.poll-modal .modal-actions .btn-create:hover { background: #d63850; }
|
||||
.poll-modal .modal-actions .btn-create:disabled {
|
||||
background: #4a5a7a;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.poll-modal .poll-check-row {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.poll-modal .poll-check-row label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
}
|
||||
.poll-modal .poll-check-row input[type="checkbox"] {
|
||||
accent-color: #e94560;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
|
@ -264,11 +478,39 @@
|
|||
</div>
|
||||
<div class="input-area">
|
||||
<button class="gif-btn" id="gif-btn" title="Add GIF">GIF</button>
|
||||
<button class="gif-btn" id="poll-btn" title="Create Poll">📊</button>
|
||||
<input type="text" id="msg-input" placeholder="Type a message..." maxlength="2000">
|
||||
<button id="send-btn">Send</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="toast" id="toast"></div>
|
||||
<div class="poll-modal-overlay" id="poll-modal">
|
||||
<div class="poll-modal">
|
||||
<h2>📊 Create Poll</h2>
|
||||
<label>Question</label>
|
||||
<textarea id="poll-question" maxlength="500" placeholder="What do you want to ask?"></textarea>
|
||||
<label>Options</label>
|
||||
<div id="poll-options">
|
||||
<div class="poll-opt-row">
|
||||
<input type="text" class="poll-opt-input" maxlength="200" placeholder="Option 1">
|
||||
<button class="poll-remove-opt" style="visibility:hidden">✕</button>
|
||||
</div>
|
||||
<div class="poll-opt-row">
|
||||
<input type="text" class="poll-opt-input" maxlength="200" placeholder="Option 2">
|
||||
<button class="poll-remove-opt" style="visibility:hidden">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="add-opt-btn" id="poll-add-opt">+ Add option</button>
|
||||
<div class="poll-check-row">
|
||||
<label><input type="checkbox" id="poll-multiple"> Allow multiple choices</label>
|
||||
<label><input type="checkbox" id="poll-anonymous"> Anonymous votes</label>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button class="btn-cancel" id="poll-cancel">Cancel</button>
|
||||
<button class="btn-create" id="poll-create">Create Poll</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
const CHANNELS = [
|
||||
{ id: 'general', name: 'General', icon: '💬' },
|
||||
|
|
@ -280,6 +522,20 @@
|
|||
let currentChannel = 'general';
|
||||
let pollInterval = null;
|
||||
let selectedGifUrl = null;
|
||||
let votedPolls = new Set();
|
||||
let pollsData = [];
|
||||
|
||||
function loadVotedPolls() {
|
||||
try {
|
||||
const saved = localStorage.getItem('votedPolls_' + currentChannel);
|
||||
if (saved) votedPolls = new Set(JSON.parse(saved));
|
||||
} catch(e) {}
|
||||
}
|
||||
function saveVotedPolls() {
|
||||
try {
|
||||
localStorage.setItem('votedPolls_' + currentChannel, JSON.stringify([...votedPolls]));
|
||||
} catch(e) {}
|
||||
}
|
||||
|
||||
const messagesEl = document.getElementById('messages');
|
||||
const inputEl = document.getElementById('msg-input');
|
||||
|
|
@ -354,6 +610,117 @@
|
|||
if (e.key === 'Enter') gifSearchBtn.click();
|
||||
});
|
||||
|
||||
// --- Poll creation ---
|
||||
const pollModal = document.getElementById('poll-modal');
|
||||
const pollBtn = document.getElementById('poll-btn');
|
||||
const pollCancel = document.getElementById('poll-cancel');
|
||||
const pollCreate = document.getElementById('poll-create');
|
||||
const pollAddOpt = document.getElementById('poll-add-opt');
|
||||
const pollQuestion = document.getElementById('poll-question');
|
||||
const pollOptionsEl = document.getElementById('poll-options');
|
||||
const pollMultiple = document.getElementById('poll-multiple');
|
||||
const pollAnonymous = document.getElementById('poll-anonymous');
|
||||
|
||||
function resetPollForm() {
|
||||
pollQuestion.value = '';
|
||||
pollMultiple.checked = false;
|
||||
pollAnonymous.checked = false;
|
||||
pollOptionsEl.innerHTML = '';
|
||||
for (let i = 1; i <= 2; i++) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'poll-opt-row';
|
||||
const inp = document.createElement('input');
|
||||
inp.type = 'text';
|
||||
inp.className = 'poll-opt-input';
|
||||
inp.maxLength = 200;
|
||||
inp.placeholder = 'Option ' + i;
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'poll-remove-opt';
|
||||
btn.textContent = '✕';
|
||||
btn.style.visibility = i <= 2 ? 'hidden' : 'visible';
|
||||
btn.addEventListener('click', () => row.remove());
|
||||
row.appendChild(inp);
|
||||
row.appendChild(btn);
|
||||
pollOptionsEl.appendChild(row);
|
||||
}
|
||||
pollCreate.disabled = false;
|
||||
}
|
||||
|
||||
pollBtn.addEventListener('click', () => {
|
||||
resetPollForm();
|
||||
pollModal.classList.add('open');
|
||||
});
|
||||
|
||||
pollCancel.addEventListener('click', () => {
|
||||
pollModal.classList.remove('open');
|
||||
});
|
||||
|
||||
pollModal.addEventListener('click', e => {
|
||||
if (e.target === pollModal) pollModal.classList.remove('open');
|
||||
});
|
||||
|
||||
pollAddOpt.addEventListener('click', () => {
|
||||
const rows = pollOptionsEl.querySelectorAll('.poll-opt-row');
|
||||
const idx = rows.length + 1;
|
||||
const row = document.createElement('div');
|
||||
row.className = 'poll-opt-row';
|
||||
const inp = document.createElement('input');
|
||||
inp.type = 'text';
|
||||
inp.className = 'poll-opt-input';
|
||||
inp.maxLength = 200;
|
||||
inp.placeholder = 'Option ' + idx;
|
||||
const btn = document.createElement('button');
|
||||
btn.className = 'poll-remove-opt';
|
||||
btn.textContent = '✕';
|
||||
btn.addEventListener('click', () => row.remove());
|
||||
row.appendChild(inp);
|
||||
row.appendChild(btn);
|
||||
pollOptionsEl.appendChild(row);
|
||||
// Show remove on all rows if > 2
|
||||
if (rows.length + 1 > 2) {
|
||||
pollOptionsEl.querySelectorAll('.poll-remove-opt').forEach(b => b.style.visibility = 'visible');
|
||||
}
|
||||
});
|
||||
|
||||
pollCreate.addEventListener('click', async () => {
|
||||
const question = pollQuestion.value.trim();
|
||||
const optionInputs = pollOptionsEl.querySelectorAll('.poll-opt-input');
|
||||
const options = [];
|
||||
optionInputs.forEach(inp => {
|
||||
const v = inp.value.trim();
|
||||
if (v) options.push(v);
|
||||
});
|
||||
|
||||
if (!question) { showToast('Please enter a question', 'error'); return; }
|
||||
if (options.length < 2) { showToast('At least 2 options required', 'error'); return; }
|
||||
|
||||
pollCreate.disabled = true;
|
||||
try {
|
||||
const r = await fetch('/api/polls', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
channel: currentChannel,
|
||||
question,
|
||||
options,
|
||||
is_multiple: pollMultiple.checked,
|
||||
is_anonymous: pollAnonymous.checked,
|
||||
})
|
||||
});
|
||||
const data = await r.json();
|
||||
if (data.success) {
|
||||
showToast('Poll created!', 'success');
|
||||
pollModal.classList.remove('open');
|
||||
loadPolls();
|
||||
} else {
|
||||
showToast(data.error || 'Failed to create poll', 'error');
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('Network error', 'error');
|
||||
}
|
||||
pollCreate.disabled = false;
|
||||
});
|
||||
|
||||
function showToast(msg, type = 'info') {
|
||||
toastEl.textContent = msg;
|
||||
toastEl.className = 'toast visible ' + type;
|
||||
|
|
@ -374,16 +741,71 @@
|
|||
function switchChannel(channel) {
|
||||
if (channel === currentChannel) return;
|
||||
currentChannel = channel;
|
||||
loadVotedPolls();
|
||||
renderChannels();
|
||||
messagesEl.innerHTML = '<div class="empty-state">Loading...</div>';
|
||||
loadMessages();
|
||||
loadPolls();
|
||||
}
|
||||
|
||||
async function loadPolls() {
|
||||
try {
|
||||
const r = await fetch(`/api/polls?channel=${currentChannel}`);
|
||||
const data = await r.json();
|
||||
if (data.success) pollsData = data.polls || [];
|
||||
else pollsData = [];
|
||||
} catch (e) {
|
||||
pollsData = [];
|
||||
}
|
||||
}
|
||||
|
||||
function renderPolls() {
|
||||
if (!pollsData.length) return '';
|
||||
let html = '';
|
||||
pollsData.forEach(poll => {
|
||||
const isClosed = poll.status === 'closed';
|
||||
const isExpired = poll.expires_at && Date.now() > poll.expires_at;
|
||||
const hasVoted = votedPolls.has(poll.id) || poll.options.some(o => o.votes > 0 && false);
|
||||
const total = poll.total_votes || 0;
|
||||
let optionsHtml = '';
|
||||
poll.options.forEach(opt => {
|
||||
const pct = total > 0 ? Math.round((opt.votes / total) * 100) : 0;
|
||||
const votedClass = hasVoted ? ' voted' : '';
|
||||
if (isClosed || isExpired || hasVoted) {
|
||||
optionsHtml += `<div class="poll-option${votedClass}">
|
||||
<div class="poll-bar" style="width:${pct}%"></div>
|
||||
<span class="poll-label">${escapeHtml(opt.label)}</span>
|
||||
<span class="poll-pct">${pct}%</span>
|
||||
<span class="poll-votes">${opt.votes}</span>
|
||||
</div>`;
|
||||
} else {
|
||||
optionsHtml += `<div class="poll-option" data-poll-id="${poll.id}" data-opt-id="${opt.id}">
|
||||
<span class="poll-label">${escapeHtml(opt.label)}</span>
|
||||
<span class="poll-pct" style="color:#6a8aaa">${opt.votes} votes</span>
|
||||
</div>`;
|
||||
}
|
||||
});
|
||||
const statusLabel = isClosed || poll.status === 'closed' ? 'Closed' :
|
||||
isExpired ? 'Expired' : 'Active';
|
||||
const statusClass = isClosed || isExpired ? 'closed' : 'active';
|
||||
const creatorLabel = poll.is_anonymous ? 'Anonymous' : escapeHtml(poll.creator_ip);
|
||||
html += `<div class="poll-card" data-poll-id="${poll.id}">
|
||||
<div class="poll-question">📊 ${escapeHtml(poll.question)}</div>
|
||||
<div class="poll-meta">by ${creatorLabel} · ${total} vote${total !== 1 ? 's' : ''} · <span class="poll-status ${statusClass}">${statusLabel}</span></div>
|
||||
<div class="poll-options">${optionsHtml}</div>
|
||||
</div>`;
|
||||
});
|
||||
return html;
|
||||
}
|
||||
|
||||
async function loadMessages() {
|
||||
try {
|
||||
const r = await fetch(`/api/messages?channel=${currentChannel}&limit=50`);
|
||||
const data = await r.json();
|
||||
if (data.success) renderMessages(data.messages || []);
|
||||
if (data.success) {
|
||||
window._lastMessages = data.messages || [];
|
||||
renderMessages(window._lastMessages);
|
||||
}
|
||||
else showToast('Failed to load messages', 'error');
|
||||
} catch (e) {
|
||||
showToast('Network error', 'error');
|
||||
|
|
@ -391,15 +813,15 @@
|
|||
}
|
||||
|
||||
function renderMessages(msgs) {
|
||||
if (msgs.length === 0) {
|
||||
const pollsHtml = renderPolls();
|
||||
if (msgs.length === 0 && !pollsHtml) {
|
||||
messagesEl.innerHTML = '<div class="empty-state">💬 No messages yet. Be the first!</div>';
|
||||
return;
|
||||
}
|
||||
let html = '';
|
||||
let html = pollsHtml;
|
||||
msgs.forEach(msg => {
|
||||
const time = new Date(msg.timestamp).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
|
||||
let contentHtml = escapeHtml(msg.content || '');
|
||||
// Try gif_url from API first, fallback to parsing content for old messages
|
||||
let gifToShow = msg.gif_url || null;
|
||||
if (!gifToShow) {
|
||||
const gifMatch = msg.content.match(/https?:\/\/[^\s]+\.(gif|webp)(\?[^\s]*)?/i);
|
||||
|
|
@ -415,9 +837,40 @@
|
|||
</div>`;
|
||||
});
|
||||
messagesEl.innerHTML = html;
|
||||
attachPollHandlers();
|
||||
messagesEl.scrollTop = messagesEl.scrollHeight;
|
||||
}
|
||||
|
||||
function attachPollHandlers() {
|
||||
document.querySelectorAll('.poll-card .poll-option:not(.voted)').forEach(el => {
|
||||
const pollId = parseInt(el.dataset.pollId);
|
||||
const optId = parseInt(el.dataset.optId);
|
||||
if (!pollId || !optId) return;
|
||||
if (votedPolls.has(pollId)) return;
|
||||
el.addEventListener('click', async () => {
|
||||
try {
|
||||
const r = await fetch(`/api/polls/${pollId}/vote`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ option_id: optId })
|
||||
});
|
||||
const data = await r.json();
|
||||
if (data.success) {
|
||||
votedPolls.add(pollId);
|
||||
saveVotedPolls();
|
||||
showToast('Vote recorded!', 'success');
|
||||
loadPolls().then(() => renderMessages(window._lastMessages || []));
|
||||
} else {
|
||||
showToast(data.error || 'Failed to vote', 'error');
|
||||
loadPolls().then(() => renderMessages(window._lastMessages || []));
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('Network error', 'error');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
const text = inputEl.value.trim();
|
||||
if (!text && !selectedGifUrl) return;
|
||||
|
|
@ -448,14 +901,21 @@
|
|||
}
|
||||
|
||||
// Init
|
||||
loadVotedPolls();
|
||||
renderChannels();
|
||||
loadMessages();
|
||||
loadPolls();
|
||||
|
||||
sendBtn.addEventListener('click', sendMessage);
|
||||
inputEl.addEventListener('keydown', e => { if (e.key === 'Enter') sendMessage(); });
|
||||
|
||||
// Auto-poll every 3 seconds
|
||||
setInterval(() => loadMessages(), 3000);
|
||||
setInterval(() => {
|
||||
loadMessages();
|
||||
loadPolls().then(() => {
|
||||
if (window._lastMessages) renderMessages(window._lastMessages);
|
||||
});
|
||||
}, 3000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
|
|
@ -3,9 +3,12 @@ models/base.py — declarative base & the Messages model.
|
|||
"""
|
||||
|
||||
from sqlalchemy import create_engine, Integer, String, Text
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, sessionmaker
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
Column, Integer, String, Text, Boolean, BigInteger,
|
||||
ForeignKey, UniqueConstraint
|
||||
)
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
|
@ -21,6 +24,54 @@ class Messages(Base):
|
|||
gif_url: Mapped[Optional[str]] = mapped_column(Text, nullable=True, default=None)
|
||||
timestamp: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
|
||||
class Poll(Base):
|
||||
__tablename__ = "polls"
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
channel = Column(String(32), nullable=False, default="general")
|
||||
creator_ip = Column(String(64), nullable=False)
|
||||
question = Column(Text, nullable=False) # encrypted
|
||||
created_at = Column(BigInteger, nullable=False)
|
||||
expires_at = Column(BigInteger, nullable=True)
|
||||
is_multiple = Column(Boolean, default=False)
|
||||
is_anonymous = Column(Boolean, default=False)
|
||||
status = Column(String(16), default="active") # active | closed | deleted
|
||||
|
||||
options = relationship("PollOption", back_populates="poll",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="PollOption.position")
|
||||
votes = relationship("PollVote", back_populates="poll",
|
||||
cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class PollOption(Base):
|
||||
__tablename__ = "poll_options"
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
poll_id = Column(Integer, ForeignKey("polls.id"), nullable=False)
|
||||
label = Column(Text, nullable=False) # encrypted
|
||||
position = Column(Integer, default=0)
|
||||
|
||||
poll = relationship("Poll", back_populates="options")
|
||||
votes = relationship("PollVote", back_populates="option",
|
||||
cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class PollVote(Base):
|
||||
__tablename__ = "poll_votes"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("poll_id", "voter_ip",
|
||||
name="uq_poll_voter"),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
poll_id = Column(Integer, ForeignKey("polls.id"), nullable=False)
|
||||
option_id = Column(Integer, ForeignKey("poll_options.id"), nullable=False)
|
||||
voter_ip = Column(String(64), nullable=False) # IP-hash
|
||||
voted_at = Column(BigInteger, nullable=False)
|
||||
|
||||
poll = relationship("Poll", back_populates="votes")
|
||||
option = relationship("PollOption", back_populates="votes")
|
||||
|
||||
def make_engine(db_cfg):
|
||||
"""Create a SQLAlchemy engine from DatabaseConfig."""
|
||||
|
|
|
|||
141
models/db.py
141
models/db.py
|
|
@ -10,7 +10,7 @@ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
|||
import base64
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from .base import make_engine, Messages
|
||||
from .base import make_engine, Messages, Poll, PollOption, PollVote
|
||||
|
||||
|
||||
class DBfrontend:
|
||||
|
|
@ -77,3 +77,142 @@ class DBfrontend:
|
|||
session.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
def add_poll(
|
||||
self,
|
||||
channel: str,
|
||||
creator_ip: str,
|
||||
question: str,
|
||||
options: list[str],
|
||||
expires_at: Optional[int] = None,
|
||||
is_multiple: bool = False,
|
||||
is_anonymous: bool = False,
|
||||
) -> int:
|
||||
with self.Session() as session:
|
||||
poll = Poll(
|
||||
channel=channel,
|
||||
creator_ip=creator_ip,
|
||||
question=self._encrypt(question),
|
||||
created_at=int(time.time() * 1000),
|
||||
expires_at=expires_at,
|
||||
is_multiple=is_multiple,
|
||||
is_anonymous=is_anonymous,
|
||||
status="active",
|
||||
)
|
||||
session.add(poll)
|
||||
session.flush()
|
||||
|
||||
for i, label in enumerate(options):
|
||||
opt = PollOption(poll_id=poll.id, label=self._encrypt(label), position=i)
|
||||
session.add(opt)
|
||||
|
||||
session.commit()
|
||||
return poll.id
|
||||
|
||||
def get_polls(self, channel: str = "general") -> list:
|
||||
with self.Session() as session:
|
||||
polls = (
|
||||
session.query(Poll)
|
||||
.filter(Poll.channel == channel, Poll.status != "deleted")
|
||||
.order_by(Poll.created_at.desc())
|
||||
.limit(20)
|
||||
)
|
||||
result = []
|
||||
for poll in polls.all():
|
||||
result.append(self._serialize_poll(session, poll))
|
||||
return result
|
||||
|
||||
def get_poll(self, poll_id: int) -> Optional[dict]:
|
||||
with self.Session() as session:
|
||||
poll = session.get(Poll, poll_id)
|
||||
if not poll or poll.status == "deleted":
|
||||
return None
|
||||
return self._serialize_poll(session, poll, include_voters=True)
|
||||
|
||||
def _serialize_poll(self, session, poll, include_voters=False) -> dict:
|
||||
options_data = []
|
||||
total_votes = 0
|
||||
for opt in poll.options:
|
||||
vote_count = len(opt.votes)
|
||||
total_votes += vote_count
|
||||
voters = [v.voter_ip for v in opt.votes] if include_voters else None
|
||||
options_data.append({
|
||||
"id": opt.id,
|
||||
"label": self._decrypt(opt.label),
|
||||
"position": opt.position,
|
||||
"votes": vote_count,
|
||||
"voters": voters,
|
||||
})
|
||||
|
||||
return {
|
||||
"id": poll.id,
|
||||
"channel": poll.channel,
|
||||
"creator_ip": poll.creator_ip,
|
||||
"question": self._decrypt(poll.question),
|
||||
"created_at": poll.created_at,
|
||||
"expires_at": poll.expires_at,
|
||||
"is_multiple": poll.is_multiple,
|
||||
"is_anonymous": poll.is_anonymous,
|
||||
"status": poll.status,
|
||||
"options": options_data,
|
||||
"total_votes": total_votes,
|
||||
}
|
||||
|
||||
def vote(self, poll_id: int, option_id: int, voter_ip: str) -> tuple[bool, str]:
|
||||
with self.Session() as session:
|
||||
poll = session.get(Poll, poll_id)
|
||||
if not poll or poll.status != "active":
|
||||
return False, "Poll is not active"
|
||||
|
||||
if poll.expires_at and int(time.time() * 1000) > poll.expires_at:
|
||||
poll.status = "closed"
|
||||
session.commit()
|
||||
return False, "Poll has expired"
|
||||
|
||||
option_valid = any(opt.id == option_id for opt in poll.options)
|
||||
if not option_valid:
|
||||
return False, "Invalid option"
|
||||
|
||||
if not poll.is_multiple:
|
||||
existing = (
|
||||
session.query(PollVote)
|
||||
.filter(PollVote.poll_id == poll_id, PollVote.voter_ip == voter_ip)
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
return False, "You have already voted in this poll"
|
||||
|
||||
existing_opt = (
|
||||
session.query(PollVote)
|
||||
.filter(
|
||||
PollVote.poll_id == poll_id,
|
||||
PollVote.option_id == option_id,
|
||||
PollVote.voter_ip == voter_ip,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing_opt:
|
||||
return False, "You have already voted for this option"
|
||||
|
||||
vote = PollVote(
|
||||
poll_id=poll_id,
|
||||
option_id=option_id,
|
||||
voter_ip=voter_ip,
|
||||
voted_at=int(time.time() * 1000),
|
||||
)
|
||||
session.add(vote)
|
||||
session.commit()
|
||||
return True, "Vote recorded"
|
||||
|
||||
def close_poll(self, poll_id: int, requester_ip: str) -> tuple[bool, str]:
|
||||
with self.Session() as session:
|
||||
poll = session.get(Poll, poll_id)
|
||||
if not poll:
|
||||
return False, "Poll not found"
|
||||
if poll.status != "active":
|
||||
return False, "Poll is not active"
|
||||
if poll.creator_ip != requester_ip:
|
||||
return False, "Only the creator can close this poll"
|
||||
poll.status = "closed"
|
||||
session.commit()
|
||||
return True, "Poll closed"
|
||||
|
|
|
|||
Loading…
Reference in New Issue