-
Notifications
You must be signed in to change notification settings - Fork 0
/
polls.js
314 lines (288 loc) · 12.2 KB
/
polls.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
// Caches to store fetched data and reduce network requests
const nameCache = {};
const hiddenPollsCache = {};
const displayNameCache = {};
const accountLevelCache = {};
const pubkeyCache = {};
document.addEventListener('DOMContentLoaded', function() {
fetchBlockHeight()
.then(() => {
searchPolls();
})
.catch(error => {
console.error('An error occurred in the fetch chain:', error);
});
});
function fetchBlockHeight() {
return fetch('/blocks/height')
.then(response => response.text())
.then(data => {
document.getElementById('block-height').textContent = data;
return data;
})
.catch(error => {
console.error('Error fetching block height:', error);
document.getElementById('block-height').textContent = `Error: ${error}`;
});
}
async function searchPolls() {
document.getElementById('poll-results').innerHTML = '<p>Searching...</p>';
// Start building the table header
let tableHtml = `
<table>
<tr>
<th>Poll Name</th>
<th>Description</th>
<th>Owner</th>
<th>Poll Options</th>
<th>Published</th>
</tr>
</table>
<p id="loading-indicator">Loading</p>
`;
// Insert the initial table structure and loading indicator
document.getElementById('poll-results').innerHTML = tableHtml;
// Counters for shown and hidden polls
let shownPollsCount = 0;
let hiddenPollsCount = 0;
try {
const response = await fetch('/polls');
const results = await response.json();
if (results && results.length > 0) {
// Sort the results by published date descending
results.sort((a, b) => b.published - a.published);
// Process each poll sequentially
for (const result of results) {
const [isHidden, displayName, creatorLevel] = await Promise.all([
checkHiddenPolls(result.owner, result.pollName),
displayNameOrAddress(result.owner),
fetchAccountLevel(result.owner)
]);
// Update counters based on poll visibility
if (isHidden) {
hiddenPollsCount++;
} else {
shownPollsCount++;
let publishedString = new Date(result.published).toLocaleString();
let pollOptionsString = result.pollOptions.map(option => option.optionName).join(', ');
// Construct row HTML for this poll
let rowHtml = `
<tr>
<td><span class="clickable-name" data-name="${result.pollName}">${result.pollName}</span>`;
rowHtml += `</td>
<td>${result.description}</td>
<td>${displayName} (Lv.${creatorLevel})</td>
<td>${pollOptionsString}</td>
<td>${publishedString}</td>
</tr>
`;
// Append the row to the table
document.querySelector('#poll-results table').insertAdjacentHTML('beforeend', rowHtml);
// Attach click listener for the clickable poll name
const clickableElement = document.querySelector(`.clickable-name[data-name="${result.pollName}"]`);
if (clickableElement) {
clickableElement.addEventListener('click', function() {
document.body.scrollTop = document.documentElement.scrollTop = 0;
let target = this.getAttribute('data-name');
fetchPoll(target);
});
} else {
console.error(`Element not found for pollName: ${result.pollName}`);
}
}
// Optional: Small delay to yield control back to the main thread
//await new Promise(resolve => setTimeout(resolve, 0));
}
// Update the loading indicator after processing all polls
document.getElementById('loading-indicator').innerHTML = `${shownPollsCount} Polls Shown, ${hiddenPollsCount} Polls Hidden`;
} else {
document.getElementById('poll-results').innerHTML = '<p>No results found.</p>';
}
} catch (error) {
console.error('Error searching polls:', error);
document.getElementById('poll-results').innerHTML = `<p>Error: ${error}</p>`;
}
}
async function checkHiddenPolls(address, poll) {
const cacheKey = `${address}_${poll}`;
if (hiddenPollsCache[cacheKey] !== undefined) {
return hiddenPollsCache[cacheKey];
}
let name = await fetchName(address);
if (name === '') {
hiddenPollsCache[cacheKey] = false;
return false;
}
try {
const response = await fetch(`/arbitrary/resources/search?name=${name}&identifier=qomboHidePoll${poll}&mode=ALL&service=CHAIN_DATA`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const results = await response.json();
const isHidden = results.length > 0;
hiddenPollsCache[cacheKey] = isHidden;
return isHidden;
} catch (error) {
console.error('Error checking hidden polls:', error);
hiddenPollsCache[cacheKey] = false;
return false;
}
}
async function fetchPoll(pollName) {
try {
const pollResponse = await fetch('/polls/' + encodeURIComponent(pollName));
const pollData = await pollResponse.json();
const voteResponse = await fetch('/polls/votes/' + encodeURIComponent(pollName));
const voteData = await voteResponse.json();
const voteCountMap = new Map(voteData.voteCounts.map(item => [item.optionName, item.voteCount]));
const voteWeightMap = new Map(voteData.voteWeights.map(item => [item.optionName, item.voteWeight]));
pollData.pollOptions.forEach(option => {
option.voteCount = voteCountMap.get(option.optionName) || 0;
option.voteWeight = voteWeightMap.get(option.optionName) || 0;
});
let displayName = await displayNameOrAddress(pollData.owner);
let publishedString = new Date(pollData.published).toLocaleString();
let htmlContent = `<table><tr><th>${pollData.pollName} <button id="copy-embed-link-button" data-poll-name="${encodeURIComponent(pollData.pollName)}">Copy Embed Link</button></th><td>${displayName}</td>`;
htmlContent += `<td>${publishedString}</td></tr></table>`;
htmlContent += `<table><tr><td>${pollData.description}</td></tr></table>`;
htmlContent += `<table><tr><th>Poll Options</th>`;
pollData.pollOptions.forEach((option, index) => {
htmlContent += `<td>Vote <button onclick="voteOnPoll('${pollData.pollName}', ${index})">${option.optionName}</button></td>`;
});
htmlContent += `</tr><tr><th>Vote Counts (Total: ${voteData.totalVotes})</th>`;
pollData.pollOptions.forEach(option => {
let percentage = (option.voteCount/voteData.totalVotes*100).toFixed(2);
htmlContent += `<td>${option.voteCount} (${percentage}%)</td>`;
});
htmlContent += `</tr><tr><th>Vote Weights (Total: ${voteData.totalWeight})</th>`;
pollData.pollOptions.forEach(option => {
let percentage = (option.voteWeight/voteData.totalWeight*100).toFixed(2);
htmlContent += `<td>${option.voteWeight} (${percentage}%)</td>`;
});
htmlContent += `</tr></table>`;
htmlContent += `<button onclick="showVotes('${pollData.pollName}')">Show Votes</button>`;
htmlContent += `<div id="voter-info"></div>`;
document.getElementById('poll-details').innerHTML = htmlContent;
// Attach the event listener
const copyEmbedLinkButton = document.getElementById('copy-embed-link-button');
if (copyEmbedLinkButton) {
copyEmbedLinkButton.addEventListener('click', function() {
const pollName = decodeURIComponent(this.getAttribute('data-poll-name'));
copyEmbedLink(pollName);
});
}
} catch (error) {
console.error('Error fetching poll:', error);
document.getElementById('poll-details').innerHTML = `Error: ${error}`;
}
}
async function showVotes(pollName) {
try {
const voteResponse = await fetch('/polls/votes/' + encodeURIComponent(pollName));
const voteData = await voteResponse.json();
let voterInfoHtml = '<table><tr><th>Voter</th><th>Option</th></tr>';
for (const vote of voteData.votes) {
let voterAddress = await pubkeyToAddress(vote.voterPublicKey);
let voterDisplayName = await displayNameOrAddress(voterAddress);
let optionName = vote.optionIndex;
voterInfoHtml += `<tr><td>${voterDisplayName}</td><td>${optionName}</td></tr>`;
}
voterInfoHtml += '</table>';
document.getElementById('voter-info').innerHTML = voterInfoHtml;
} catch (error) {
console.error('Error fetching voter information:', error);
document.getElementById('voter-info').innerHTML = `Error: ${error}`;
}
}
async function voteOnPoll(pollName, optionId) {
try {
await qortalRequest({
action: "VOTE_ON_POLL",
pollName: pollName,
optionIndex: optionId,
});
} catch (error) {
console.error('Error voting on poll:', error);
}
}
async function fetchName(address) {
if (nameCache[address]) {
return nameCache[address];
}
try {
const response = await fetch(`/names/address/${address}`);
const names = await response.json();
const name = names[0] ? names[0].name : '';
nameCache[address] = name;
return name;
} catch (error) {
console.error('Error fetching name:', error);
return '';
}
}
async function displayNameOrAddress(address) {
if (displayNameCache[address]) {
return displayNameCache[address];
}
try {
const response = await fetch(`/names/address/${address}`);
const names = await response.json();
if (names[0]) {
const displayName = `<img src="/arbitrary/THUMBNAIL/${names[0].name}/qortal_avatar"
style="width:24px;height:24px;"
onerror="this.style='display:none'"
>${names[0].name}`;
displayNameCache[address] = displayName;
return displayName;
} else {
displayNameCache[address] = address;
return address;
}
} catch (error) {
console.error('Error fetching name:', error);
displayNameCache[address] = address;
return address;
}
}
async function pubkeyToAddress(pubkey) {
if (pubkeyCache[pubkey]) {
return pubkeyCache[pubkey];
}
try {
const response = await fetch(`/addresses/convert/${pubkey}`);
const address = await response.text();
pubkeyCache[pubkey] = address;
return address;
} catch (error) {
console.error('Error fetching address:', error);
return pubkey;
}
}
async function fetchAccountLevel(address) {
if (accountLevelCache[address]) {
return accountLevelCache[address];
}
try {
const response = await fetch(`/addresses/${address}`);
const accountInfo = await response.json();
accountLevelCache[address] = accountInfo.level;
return accountInfo.level;
} catch (error) {
console.error('Error fetching account level:', error);
}
}
async function copyEmbedLink(pollName) {
console.log('copyEmbedLink called with pollName:', pollName); // Add this line
try {
const response = await qortalRequest({
action: "CREATE_AND_COPY_EMBED_LINK",
name: pollName,
type: 'POLL',
ref: 'qortal://APP/Qombo'
});
alert(`Embed link copied to clipboard: ${response}`);
} catch (error) {
console.error('Error copying embed link:', error);
alert('Error copying embed link: ' + error);
}
}