Greasy Fork 支持简体中文。

X Spaces +

Addon for X Spaces with custom emojis, enhanced transcript including mute/unmute, hand raise/lower, mic invites, join/leave events, and speaker queuing.

目前為 2025-03-28 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name X Spaces +
  3. // @namespace Violentmonkey Scripts
  4. // @version 1.95
  5. // @description Addon for X Spaces with custom emojis, enhanced transcript including mute/unmute, hand raise/lower, mic invites, join/leave events, and speaker queuing.
  6. // @author x.com/blankspeaker and x.com/PrestonHenshawX
  7. // @match https://twitter.com/*
  8. // @match https://x.com/*
  9. // @run-at document-start
  10. // @grant none
  11. // ==/UserScript==
  12.  
  13. (function () {
  14. 'use strict';
  15.  
  16. const OrigWebSocket = window.WebSocket;
  17. const OrigXMLHttpRequest = window.XMLHttpRequest;
  18. let myUserId = null;
  19. let myParticipantIndex = null;
  20. let myUsername = null;
  21. let captionsData = [];
  22. let emojiReactions = [];
  23. let currentSpaceId = null;
  24. let lastSpaceId = null;
  25. let handRaiseDurations = [];
  26. const activeHandRaises = new Map();
  27. let dynamicUrl = '';
  28. let previousOccupancy = null;
  29. let totalParticipants = 0;
  30. let capturedCookie = null;
  31.  
  32. let selectedCustomEmoji = null;
  33.  
  34. const customEmojis = [
  35. '😂', '😲', '😢', '✌️', '💯',
  36. '👏', '✊', '👍', '👎', '👋',
  37. '😍', '😃', '😠', '🤔', '😷',
  38. '🔥', '🎯', '✨', '🥇', '✋',
  39. '🙌', '🙏', '🎶', '🎙', '🙉',
  40. '🪐', '🎨', '🎮', '🏛️', '💸',
  41. '🌲', '🐞', '❤️', '🧡', '💛',
  42. '💚', '💙', '💜', '🖤', '🤎',
  43. '💄', '🏠', '💡', '💢', '💻',
  44. '🖥️', '📺', '🎚️', '🎛️', '📡',
  45. '🔋', '🗒️', '📰', '📌', '💠',
  46. ];
  47.  
  48. const originalEmojis = ['😂', '😲', '😢', '💜', '💯', '👏', '✊', '👍', '👎', '👋'];
  49. const emojiMap = new Map();
  50. customEmojis.forEach((emoji, index) => {
  51. const originalEmoji = originalEmojis[index % originalEmojis.length];
  52. emojiMap.set(emoji, originalEmoji);
  53. });
  54.  
  55. async function fetchReplayUrl(dynUrl) {
  56. if (!dynUrl || !dynUrl.includes('/dynamic_playlist.m3u8?type=live')) {
  57. return 'Invalid Dynamic URL';
  58. }
  59. const masterUrl = dynUrl.replace('/dynamic_playlist.m3u8?type=live', '/master_playlist.m3u8');
  60. try {
  61. const response = await fetch(masterUrl);
  62. const text = await response.text();
  63. const playlistMatch = text.match(/playlist_\d+\.m3u8/);
  64. if (playlistMatch) {
  65. return dynUrl.replace('dynamic_playlist.m3u8', playlistMatch[0]).replace('type=live', 'type=replay');
  66. }
  67. return 'No playlist found';
  68. } catch (error) {
  69. const converterUrl = `data:text/html;charset=utf-8,${encodeURIComponent(`
  70. <!DOCTYPE html>
  71. <html>
  72. <body>
  73. <textarea id="input" rows="4" cols="50">${dynUrl}</textarea><br>
  74. <button onclick="convert()">Generate Replay URL</button><br>
  75. <textarea id="result" rows="4" cols="50" readonly></textarea><br>
  76. <button onclick="navigator.clipboard.writeText(document.getElementById('result').value)">Copy</button>
  77. <script>
  78. async function convert() {
  79. const corsProxy = "https://cors.viddastrage.workers.dev/corsproxy/?apiurl=";
  80. const dynUrl = document.getElementById('input').value;
  81. const masterUrl = dynUrl.replace('/dynamic_playlist.m3u8?type=live', '/master_playlist.m3u8');
  82. try {
  83. const response = await fetch(corsProxy + masterUrl);
  84. const text = await response.text();
  85. const playlistMatch = text.match(/playlist_\\d+\\.m3u8/);
  86. if (playlistMatch) {
  87. const replayUrl = dynUrl.replace('dynamic_playlist.m3u8', playlistMatch[0]).replace('type=live', 'type=replay');
  88. document.getElementById('result').value = replayUrl;
  89. } else {
  90. document.getElementById('result').value = 'No playlist found';
  91. }
  92. } catch (e) {
  93. document.getElementById('result').value = 'Error: ' + e.message;
  94. }
  95. }
  96. </script>
  97. </body>
  98. </html>
  99. `)}`;
  100. return converterUrl;
  101. }
  102. }
  103.  
  104. function debounce(func, wait) {
  105. let timeout;
  106. return function (...args) {
  107. clearTimeout(timeout);
  108. timeout = setTimeout(() => func(...args), wait);
  109. };
  110. }
  111.  
  112. function getSpaceIdFromUrl() {
  113. const urlMatch = window.location.pathname.match(/\/i\/spaces\/([^/]+)/);
  114. return urlMatch ? urlMatch[1] : null;
  115. }
  116.  
  117. window.WebSocket = function (url, protocols) {
  118. const ws = new OrigWebSocket(url, protocols);
  119. const originalSend = ws.send;
  120.  
  121. ws.send = function (data) {
  122. if (typeof data === 'string') {
  123. try {
  124. const parsed = JSON.parse(data);
  125. if (parsed.payload && typeof parsed.payload === 'string') {
  126. const payloadParsed = JSON.parse(parsed.payload);
  127. if (payloadParsed.body) {
  128. const bodyParsed = JSON.parse(payloadParsed.body);
  129. if (parsed.sender && parsed.sender.user_id) {
  130. myUserId = myUserId || parsed.sender.user_id;
  131. myParticipantIndex = myParticipantIndex || payloadParsed.participant_index;
  132. myUsername = myUsername || payloadParsed.sender?.username || bodyParsed.username || 'You';
  133. }
  134. if (bodyParsed.type === 2 && selectedCustomEmoji) {
  135. bodyParsed.body = selectedCustomEmoji;
  136. payloadParsed.body = JSON.stringify(bodyParsed);
  137. parsed.payload = JSON.stringify(payloadParsed);
  138. data = JSON.stringify(parsed);
  139. const emojiReaction = {
  140. displayName: myUsername || 'You',
  141. handle: `@${myUsername || 'You'}`,
  142. emoji: selectedCustomEmoji,
  143. timestamp: Date.now(),
  144. uniqueId: `${Date.now()}-${myUsername || 'You'}-${selectedCustomEmoji}-${Date.now()}`
  145. };
  146. emojiReactions.push(emojiReaction);
  147. if (transcriptPopup && transcriptPopup.style.display === 'block') {
  148. debouncedUpdateTranscriptPopup();
  149. }
  150. }
  151. }
  152. }
  153. } catch (e) {
  154. }
  155. }
  156. return originalSend.call(this, data);
  157. };
  158.  
  159. let originalOnMessage = null;
  160. ws.onmessage = function (event) {
  161. if (originalOnMessage) originalOnMessage.call(this, event);
  162. try {
  163. const message = JSON.parse(event.data);
  164.  
  165. if (message.kind === 1 && message.payload) {
  166. const payload = JSON.parse(message.payload);
  167. const body = payload.body ? JSON.parse(payload.body) : null;
  168.  
  169. if (body) {
  170. const participantIndex = body.guestParticipantIndex || payload.sender?.participant_index || 'unknown';
  171. let displayName = payload.sender?.display_name || body.displayName || 'Unknown';
  172. let handle = payload.sender?.username || body.username || 'Unknown';
  173. const timestamp = message.timestamp / 1e6 || Date.now();
  174.  
  175. const logSystemMessages = localStorage.getItem(STORAGE_KEYS.SHOW_SYSTEM_MESSAGES) !== 'false';
  176.  
  177. if (body.type === 40 && body.guestBroadcastingEvent && logSystemMessages) {
  178. let eventText = '';
  179. switch (body.guestBroadcastingEvent) {
  180. case 4:
  181. eventText = `${displayName} (${handle}) dropped the mic`;
  182. break;
  183. case 5:
  184. eventText = `${displayName} (${handle}) invited you to grab a mic`;
  185. break;
  186. case 9:
  187. eventText = `${displayName} (${handle}) grabbed a mic`;
  188. break;
  189. case 10:
  190. eventText = `${displayName} (${handle}) had their mic removed by host`;
  191. break;
  192. case 16:
  193. eventText = `${displayName} (${handle}) muted`;
  194. break;
  195. case 17:
  196. eventText = `${displayName} (${handle}) unmuted`;
  197. break;
  198. case 18:
  199. eventText = `${displayName} (${handle}) muted all participants`;
  200. break;
  201. case 19:
  202. eventText = `${displayName} (${handle}) unmuted all participants`;
  203. break;
  204. case 20:
  205. eventText = `${displayName} (${handle}) invited a new cohost`;
  206. break;
  207. case 21:
  208. eventText = `${displayName} (${handle}) removed a cohost`;
  209. break;
  210. case 22:
  211. eventText = `${displayName} (${handle}) became a cohost`;
  212. break;
  213. case 23:
  214. eventText = `${displayName} (${handle}) raised their hand`;
  215. handQueue.set(participantIndex, { displayName, timestamp });
  216. activeHandRaises.set(participantIndex, timestamp);
  217. updateQueueButtonVisibility();
  218. break;
  219. case 24:
  220. eventText = `${displayName} (${handle}) lowered their hand`;
  221. const startTime = activeHandRaises.get(participantIndex);
  222. if (startTime) {
  223. const duration = (timestamp - startTime) / 1000;
  224. const sortedQueue = Array.from(handQueue.entries())
  225. .sort(([, a], [, b]) => a.timestamp - b.timestamp);
  226. if (sortedQueue.length > 0 && sortedQueue[0][0] === participantIndex && duration >= 60) {
  227. handRaiseDurations.push(duration);
  228. if (handRaiseDurations.length > 50) handRaiseDurations.shift();
  229. }
  230. handQueue.delete(participantIndex);
  231. activeHandRaises.delete(participantIndex);
  232. updateQueueButtonVisibility();
  233. }
  234. break;
  235. default:
  236. eventText = `${displayName} (${handle}) triggered event ${body.guestBroadcastingEvent}`;
  237. }
  238. const systemEvent = {
  239. displayName: 'System',
  240. handle: '',
  241. text: eventText,
  242. timestamp,
  243. uniqueId: `${timestamp}-event-${body.guestBroadcastingEvent}-${handle}`
  244. };
  245. captionsData.push(systemEvent);
  246. if (transcriptPopup && transcriptPopup.style.display === 'block') {
  247. updateTranscriptPopup();
  248. }
  249. }
  250.  
  251. if (body.type === 45 && body.body) {
  252. const caption = {
  253. displayName,
  254. handle: `@${handle}`,
  255. text: body.body,
  256. timestamp,
  257. uniqueId: `${timestamp}-${displayName}-${handle}-${body.body}`
  258. };
  259. const isDuplicate = captionsData.some(c => c.uniqueId === caption.uniqueId);
  260. const lastCaption = captionsData[captionsData.length - 1];
  261. const isDifferentText = !lastCaption || lastCaption.text !== caption.text;
  262. if (!isDuplicate && isDifferentText) {
  263. if (activeHandRaises.has(participantIndex) && logSystemMessages) {
  264. const startTime = activeHandRaises.get(participantIndex);
  265. const duration = (timestamp - startTime) / 1000;
  266. const sortedQueue = Array.from(handQueue.entries())
  267. .sort(([, a], [, b]) => a.timestamp - b.timestamp);
  268. if (sortedQueue.length > 0 && sortedQueue[0][0] === participantIndex && duration >= 60) {
  269. handRaiseDurations.push(duration);
  270. if (handRaiseDurations.length > 50) handRaiseDurations.shift();
  271. }
  272. const handLowerEvent = {
  273. displayName: 'System',
  274. handle: '',
  275. text: `${displayName} (${handle}) lowered their hand (started speaking)`,
  276. timestamp,
  277. uniqueId: `${timestamp}-handlower-speaking-${participantIndex}`
  278. };
  279. captionsData.push(handLowerEvent);
  280. handQueue.delete(participantIndex);
  281. activeHandRaises.delete(participantIndex);
  282. updateQueueButtonVisibility();
  283. }
  284. captionsData.push(caption);
  285. if (transcriptPopup && transcriptPopup.style.display === 'block') {
  286. updateTranscriptPopup();
  287. }
  288. }
  289. }
  290.  
  291. if (body.type === 2 && body.body) {
  292. const captureEmojis = localStorage.getItem(STORAGE_KEYS.SHOW_EMOJIS) !== 'false';
  293. if (captureEmojis) {
  294. const emojiReaction = {
  295. displayName,
  296. handle: `@${handle}`,
  297. emoji: body.body,
  298. timestamp,
  299. uniqueId: `${timestamp}-${displayName}-${body.body}-${Date.now()}`
  300. };
  301. const isDuplicate = emojiReactions.some(e =>
  302. e.uniqueId === emojiReaction.uniqueId ||
  303. (e.displayName === emojiReaction.displayName &&
  304. e.emoji === emojiReaction.emoji &&
  305. Math.abs(e.timestamp - emojiReaction.timestamp) < 50)
  306. );
  307. if (!isDuplicate) {
  308. emojiReactions.push(emojiReaction);
  309. if (transcriptPopup && transcriptPopup.style.display === 'block') {
  310. debouncedUpdateTranscriptPopup();
  311. }
  312. }
  313. }
  314. }
  315. }
  316. }
  317.  
  318. if (message.kind === 2 && message.payload) {
  319. const payload = JSON.parse(message.payload);
  320. const body = payload.body ? JSON.parse(payload.body) : null;
  321.  
  322. if (body && body.occupancy !== undefined && body.total_participants !== undefined) {
  323. const currentOccupancy = body.occupancy;
  324. totalParticipants = body.total_participants;
  325. const timestamp = Date.now();
  326. const logSystemMessages = localStorage.getItem(STORAGE_KEYS.SHOW_SYSTEM_MESSAGES) !== 'false';
  327.  
  328. if (previousOccupancy !== null && logSystemMessages) {
  329. let eventText;
  330. if (currentOccupancy > previousOccupancy) {
  331. eventText = `A new user joined - Current ${currentOccupancy} - Total ${totalParticipants}`;
  332. } else if (currentOccupancy < previousOccupancy) {
  333. eventText = `A user left - Current ${currentOccupancy} - Total ${totalParticipants}`;
  334. }
  335. if (eventText) {
  336. const occupancyEvent = {
  337. displayName: 'System',
  338. handle: '',
  339. text: eventText,
  340. timestamp,
  341. uniqueId: `${timestamp}-occupancy-${currentOccupancy}`
  342. };
  343. captionsData.push(occupancyEvent);
  344. if (transcriptPopup && transcriptPopup.style.display === 'block') {
  345. updateTranscriptPopup();
  346. }
  347. }
  348. }
  349. previousOccupancy = currentOccupancy;
  350. }
  351. }
  352.  
  353. const payloadString = JSON.stringify(payload);
  354. if (payloadString.includes('dynamic_playlist.m3u8?type=live')) {
  355. const urlMatch = payloadString.match(/https:\/\/prod-fastly-[^/]+?\.video\.pscp\.tv\/[^"]+?dynamic_playlist\.m3u8\?type=live/);
  356. if (urlMatch) dynamicUrl = urlMatch[0];
  357. }
  358.  
  359. if (payload.room_id) {
  360. currentSpaceId = payload.room_id;
  361. }
  362.  
  363. const urlSpaceId = getSpaceIdFromUrl();
  364. if (urlSpaceId && payload.room_id !== urlSpaceId) return;
  365. } catch (e) {
  366. }
  367. };
  368.  
  369. Object.defineProperty(ws, 'onmessage', {
  370. set: function (callback) {
  371. originalOnMessage = callback;
  372. },
  373. get: function () {
  374. return ws.onmessage;
  375. }
  376. });
  377.  
  378. return ws;
  379. };
  380.  
  381. window.XMLHttpRequest = function () {
  382. const xhr = new OrigXMLHttpRequest();
  383. const originalOpen = xhr.open;
  384. const originalSend = xhr.send;
  385.  
  386. xhr.open = function (method, url, async, user, password) {
  387. if (typeof url === 'string' && url.includes('dynamic_playlist.m3u8?type=live')) {
  388. dynamicUrl = url;
  389. }
  390. xhr._method = method;
  391. xhr._url = url;
  392. return originalOpen.apply(this, arguments);
  393. };
  394.  
  395. xhr.send = function (data) {
  396. if (xhr._method === 'POST') {
  397. try {
  398. const payload = JSON.parse(data);
  399. if (xhr._url.includes('https://proxsee.pscp.tv/api/v2/createBroadcast') && payload.cookie) {
  400. capturedCookie = payload.cookie;
  401. }
  402.  
  403. if (payload.broadcast_id &&
  404. (xhr._url.includes('https://proxsee.pscp.tv/api/v2/') ||
  405. xhr._url.includes('https://guest.pscp.tv/api/v1/audiospace/'))) {
  406. currentSpaceId = payload.broadcast_id;
  407. }
  408. } catch (e) {
  409. }
  410. }
  411. return originalSend.apply(this, arguments);
  412. };
  413.  
  414. return xhr;
  415. };
  416.  
  417. const OriginalFetch = window.fetch;
  418. window.fetch = function (resource, init = {}) {
  419. const url = typeof resource === 'string' ? resource : resource.url;
  420. const method = init.method || 'GET';
  421.  
  422. if (method === 'POST' && init.body) {
  423. try {
  424. const payload = JSON.parse(init.body);
  425.  
  426. if (url.includes('https://proxsee.pscp.tv/api/v2/createBroadcast') && payload.cookie) {
  427. capturedCookie = payload.cookie;
  428. }
  429.  
  430. if (payload.broadcast_id &&
  431. (url.includes('https://proxsee.pscp.tv/api/v2/') ||
  432. url.includes('https://guest.pscp.tv/api/v1/audiospace/'))) {
  433. currentSpaceId = payload.broadcast_id;
  434. }
  435. } catch (e) {
  436. }
  437. }
  438. return OriginalFetch.apply(this, arguments);
  439. };
  440.  
  441. let transcriptPopup = null;
  442. let transcriptButton = null;
  443. let queueButton = null;
  444. let handQueuePopup = null;
  445. let queueRefreshInterval = null;
  446. const handQueue = new Map();
  447. let lastSpaceState = false;
  448. let lastSpeaker = { username: '', handle: '' };
  449.  
  450. const STORAGE_KEYS = {
  451. LAST_SPACE_ID: 'xSpacesCustomReactions_lastSpaceId',
  452. HAND_DURATIONS: 'xSpacesCustomReactions_handRaiseDurations',
  453. SHOW_EMOJIS: 'xSpacesCustomReactions_showEmojis',
  454. SHOW_SYSTEM_MESSAGES: 'xSpacesCustomReactions_showSystemMessages'
  455. };
  456.  
  457. const debouncedUpdateTranscriptPopup = debounce(updateTranscriptPopup, 2000);
  458.  
  459. function saveSettings() {
  460. localStorage.setItem(STORAGE_KEYS.LAST_SPACE_ID, currentSpaceId || '');
  461. localStorage.setItem(STORAGE_KEYS.HAND_DURATIONS, JSON.stringify(handRaiseDurations));
  462. }
  463.  
  464. function loadSettings() {
  465. lastSpaceId = localStorage.getItem(STORAGE_KEYS.LAST_SPACE_ID) || null;
  466. const savedDurations = localStorage.getItem(STORAGE_KEYS.HAND_DURATIONS);
  467. if (savedDurations) handRaiseDurations = JSON.parse(savedDurations);
  468. }
  469.  
  470. function hideOriginalEmojiButtons() {
  471. const originalButtons = document.querySelectorAll('.css-175oi2r.r-1awozwy.r-18u37iz.r-9aw3ui.r-1777fci.r-tuq35u > div > button');
  472. originalButtons.forEach(button => button.style.display = 'none');
  473. }
  474.  
  475. function createEmojiPickerGrid() {
  476. const emojiPicker = document.querySelector('.css-175oi2r.r-1awozwy.r-18u37iz.r-9aw3ui.r-1777fci.r-tuq35u');
  477. if (!emojiPicker || emojiPicker.querySelector('.emoji-grid-container')) return;
  478.  
  479. hideOriginalEmojiButtons();
  480.  
  481. const gridContainer = document.createElement('div');
  482. gridContainer.className = 'emoji-grid-container';
  483. gridContainer.style.display = 'grid';
  484. gridContainer.style.gridTemplateColumns = 'repeat(5, 1fr)';
  485. gridContainer.style.gap = '10px';
  486. gridContainer.style.padding = '10px';
  487.  
  488. const fragment = document.createDocumentFragment();
  489.  
  490. customEmojis.forEach(emoji => {
  491. const emojiButton = document.createElement('button');
  492. emojiButton.setAttribute('aria-label', `React with ${emoji}`);
  493. emojiButton.setAttribute('role', 'button');
  494. emojiButton.className = 'css-175oi2r r-1awozwy r-z2wwpe r-6koalj r-18u37iz r-1w6e6rj r-a2tzq0 r-tuq35u r-1loqt21 r-o7ynqc r-6416eg r-1ny4l3l';
  495. emojiButton.type = 'button';
  496. emojiButton.style.margin = '5px';
  497.  
  498. const emojiDiv = document.createElement('div');
  499. emojiDiv.dir = 'ltr';
  500. emojiDiv.className = 'css-146c3p1 r-bcqeeo r-1ttztb7 r-qvutc0 r-37j5jr r-1blvdjr r-vrz42v r-16dba41';
  501. emojiDiv.style.color = 'rgb(231, 233, 234)';
  502.  
  503. const emojiImg = document.createElement('img');
  504. emojiImg.alt = emoji;
  505. emojiImg.draggable = 'false';
  506. emojiImg.src = `https://abs-0.twimg.com/emoji/v2/svg/${emoji.codePointAt(0).toString(16)}.svg`;
  507. emojiImg.title = emoji;
  508. emojiImg.className = 'r-4qtqp9 r-dflpy8 r-k4bwe5 r-1kpi4qh r-pp5qcn r-h9hxbl';
  509.  
  510. emojiDiv.appendChild(emojiImg);
  511. emojiButton.appendChild(emojiDiv);
  512.  
  513. emojiButton.addEventListener('click', (e) => {
  514. e.preventDefault();
  515. e.stopPropagation();
  516.  
  517. selectedCustomEmoji = emoji;
  518.  
  519. const originalEmoji = emojiMap.get(emoji);
  520. if (originalEmoji) {
  521. const originalButton = Array.from(document.querySelectorAll('button[aria-label^="React with"]'))
  522. .find(button => button.querySelector('img')?.alt === originalEmoji);
  523. if (originalButton) originalButton.click();
  524. }
  525. });
  526.  
  527. fragment.appendChild(emojiButton);
  528. });
  529.  
  530. const linksDiv = document.createElement('div');
  531. linksDiv.style.gridColumn = '1 / -1';
  532. linksDiv.style.textAlign = 'center';
  533. linksDiv.style.fontSize = '12px';
  534. linksDiv.style.color = 'rgba(231, 233, 234, 0.8)';
  535. linksDiv.style.marginTop = '10px';
  536. linksDiv.style.display = 'flex';
  537. linksDiv.style.justifyContent = 'center';
  538. linksDiv.style.gap = '15px';
  539.  
  540. const aboutLink = document.createElement('a');
  541. aboutLink.href = 'https://greasyfork.org/en/scripts/530560-x-spaces';
  542. aboutLink.textContent = 'About';
  543. aboutLink.style.color = 'inherit';
  544. aboutLink.style.textDecoration = 'none';
  545. aboutLink.target = '_blank';
  546. linksDiv.appendChild(aboutLink);
  547.  
  548. const dynamicLink = document.createElement('a');
  549. dynamicLink.href = '#';
  550. dynamicLink.textContent = dynamicUrl ? 'Dynamic (Click to Copy)' : 'Dynamic (N/A)';
  551. dynamicLink.style.color = 'inherit';
  552. dynamicLink.style.textDecoration = 'none';
  553. dynamicLink.style.cursor = 'pointer';
  554. dynamicLink.addEventListener('click', (e) => {
  555. e.preventDefault();
  556. if (dynamicUrl) {
  557. navigator.clipboard.writeText(dynamicUrl).then(() => {
  558. dynamicLink.textContent = 'Dynamic (Copied!)';
  559. setTimeout(() => dynamicLink.textContent = 'Dynamic (Click to Copy)', 2000);
  560. }).catch(() => {
  561. dynamicLink.textContent = 'Dynamic (Copy Failed)';
  562. setTimeout(() => dynamicLink.textContent = 'Dynamic (Click to Copy)', 2000);
  563. });
  564. }
  565. });
  566. linksDiv.appendChild(dynamicLink);
  567.  
  568. const replayLink = document.createElement('a');
  569. replayLink.href = '#';
  570. replayLink.textContent = 'Replay (Click to Copy)';
  571. replayLink.style.color = 'inherit';
  572. replayLink.style.textDecoration = 'none';
  573. replayLink.style.cursor = 'pointer';
  574. replayLink.addEventListener('click', async (e) => {
  575. e.preventDefault();
  576. if (!dynamicUrl) {
  577. replayLink.textContent = 'Replay (No Dynamic URL)';
  578. setTimeout(() => replayLink.textContent = 'Replay (Click to Copy)', 2000);
  579. return;
  580. }
  581. replayLink.textContent = 'Generating...';
  582. const newReplayUrl = await fetchReplayUrl(dynamicUrl);
  583. if (newReplayUrl.startsWith('http')) {
  584. navigator.clipboard.writeText(newReplayUrl).then(() => {
  585. replayLink.textContent = 'Replay (Copied!)';
  586. setTimeout(() => replayLink.textContent = 'Replay (Click to Copy)', 2000);
  587. }).catch(() => {
  588. replayLink.textContent = 'Replay (Copy Failed)';
  589. setTimeout(() => replayLink.textContent = 'Replay (Click to Copy)', 2000);
  590. });
  591. } else if (newReplayUrl.startsWith('data:text/html')) {
  592. replayLink.textContent = 'Replay (Open Converter)';
  593. replayLink.href = newReplayUrl;
  594. replayLink.target = '_blank';
  595. setTimeout(() => {
  596. replayLink.textContent = 'Replay (Click to Copy)';
  597. replayLink.href = '#';
  598. replayLink.target = '';
  599. }, 5000);
  600. } else {
  601. replayLink.textContent = `Replay (${newReplayUrl})`;
  602. setTimeout(() => replayLink.textContent = 'Replay (Click to Copy)', 2000);
  603. }
  604. });
  605. linksDiv.appendChild(replayLink);
  606.  
  607. const updateDynamicLink = () => {
  608. dynamicLink.textContent = dynamicUrl ? 'Dynamic (Click to Copy)' : 'Dynamic (N/A)';
  609. };
  610. setInterval(updateDynamicLink, 1000);
  611.  
  612. fragment.appendChild(linksDiv);
  613. gridContainer.appendChild(fragment);
  614. emojiPicker.appendChild(gridContainer);
  615. }
  616.  
  617. function detectEndedUI() {
  618. const endedContainer = document.querySelector('div[data-testid="sheetDialog"] div.css-175oi2r.r-18u37iz.r-13qz1uu.r-1wtj0ep');
  619. if (endedContainer) {
  620. const hasEndedText = Array.from(endedContainer.querySelectorAll('span')).some(span => span.textContent.toLowerCase().includes('ended'));
  621. const hasCloseButton = endedContainer.querySelector('button[aria-label="Close"]');
  622. const hasShareButton = endedContainer.querySelector('button[aria-label="Share"]');
  623. if (hasEndedText && hasCloseButton && hasShareButton) return endedContainer;
  624. }
  625. return null;
  626. }
  627.  
  628. function addDownloadOptionToShareDropdown(dropdown) {
  629. if (dropdown.querySelector('#download-transcript-share') && dropdown.querySelector('#copy-replay-url-share')) return;
  630.  
  631. const menuItems = dropdown.querySelectorAll('div[role="menuitem"]');
  632. const itemCount = Array.from(menuItems).filter(item => item.id !== 'download-transcript-share' && item.id !== 'copy-replay-url-share').length;
  633. if (itemCount !== 4) return;
  634.  
  635. const downloadItem = document.createElement('div');
  636. downloadItem.id = 'download-transcript-share';
  637. downloadItem.setAttribute('role', 'menuitem');
  638. downloadItem.setAttribute('tabindex', '0');
  639. downloadItem.className = 'css-175oi2r r-1loqt21 r-18u37iz r-1mmae3n r-3pj75a r-13qz1uu r-o7ynqc r-6416eg r-1ny4l3l';
  640. downloadItem.style.transition = 'background-color 0.2s ease';
  641.  
  642. const downloadIconContainer = document.createElement('div');
  643. downloadIconContainer.className = 'css-175oi2r r-1777fci r-faml9v';
  644.  
  645. const downloadIcon = document.createElement('svg');
  646. downloadIcon.viewBox = '0 0 24 24';
  647. downloadIcon.setAttribute('aria-hidden', 'true');
  648. downloadIcon.className = 'r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-lrvibr r-m6rgpd r-1nao33i r-1q142lx';
  649. downloadIcon.innerHTML = '<g><path d="M19 3H5c-1.11 0-2 .89-2 2v14c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm-2 16H7v-6h10v6zm2-8H5V5h14v6z"/></g>';
  650. downloadIconContainer.appendChild(downloadIcon);
  651.  
  652. const downloadTextContainer = document.createElement('div');
  653. downloadTextContainer.className = 'css-175oi2r r-16y2uox r-1wbh5a2';
  654.  
  655. const downloadText = document.createElement('div');
  656. downloadText.dir = 'ltr';
  657. downloadText.className = 'css-146c3p1 r-bcqeeo r-1ttztb7 r-qvutc0 r-37j5jr r-a023e6 r-rjixqe r-b88u0q';
  658. downloadText.style.color = 'rgb(231, 233, 234)';
  659. downloadText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Download Transcript</span>';
  660. downloadTextContainer.appendChild(downloadText);
  661.  
  662. downloadItem.appendChild(downloadIconContainer);
  663. downloadItem.appendChild(downloadTextContainer);
  664.  
  665. const downloadStyle = document.createElement('style');
  666. downloadStyle.textContent = '#download-transcript-share:hover { background-color: rgba(231, 233, 234, 0.1); }';
  667. downloadItem.appendChild(downloadStyle);
  668.  
  669. downloadItem.addEventListener('click', async (e) => {
  670. e.preventDefault();
  671. const transcripts = await formatTranscriptForDownload();
  672.  
  673. const transcriptionBlob = new Blob([transcripts.transcription.content], { type: 'text/plain' });
  674. const transcriptionUrl = URL.createObjectURL(transcriptionBlob);
  675. const transcriptionLink = document.createElement('a');
  676. transcriptionLink.href = transcriptionUrl;
  677. transcriptionLink.download = transcripts.transcription.filename;
  678. document.body.appendChild(transcriptionLink);
  679. transcriptionLink.click();
  680. document.body.removeChild(transcriptionLink);
  681. URL.revokeObjectURL(transcriptionUrl);
  682.  
  683. const systemBlob = new Blob([transcripts.system.content], { type: 'text/plain' });
  684. const systemUrl = URL.createObjectURL(systemBlob);
  685. const systemLink = document.createElement('a');
  686. systemLink.href = systemUrl;
  687. systemLink.download = transcripts.system.filename;
  688. document.body.appendChild(systemLink);
  689. systemLink.click();
  690. document.body.removeChild(systemLink);
  691. URL.revokeObjectURL(systemUrl);
  692.  
  693. dropdown.style.display = 'none';
  694. });
  695.  
  696. const replayItem = document.createElement('div');
  697. replayItem.id = 'copy-replay-url-share';
  698. replayItem.setAttribute('role', 'menuitem');
  699. replayItem.setAttribute('tabindex', '0');
  700. replayItem.className = 'css-175oi2r r-1loqt21 r-18u37iz r-1mmae3n r-3pj75a r-13qz1uu r-o7ynqc r-6416eg r-1ny4l3l';
  701. replayItem.style.transition = 'background-color 0.2s ease';
  702.  
  703. const replayIconContainer = document.createElement('div');
  704. replayIconContainer.className = 'css-175oi2r r-1777fci r-faml9v';
  705.  
  706. const replayIcon = document.createElement('svg');
  707. replayIcon.viewBox = '0 0 24 24';
  708. replayIcon.setAttribute('aria-hidden', 'true');
  709. replayIcon.className = 'r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-lrvibr r-m6rgpd r-1nao33i r-1q142lx';
  710. replayIcon.innerHTML = '<g><path d="M12 3.75c-4.55 0-8.25 3.69-8.25 8.25 0 1.92.66 3.68 1.75 5.08L4.3 19.2l2.16-1.19c1.4 1.09 3.16 1.74 5.04 1.74 4.56 0 8.25-3.69 8.25-8.25S16.56 3.75 12 3.75zm1 11.24h-2v-2h2v2zm0-3.5h-2v-4h2v4z"/></g>';
  711. replayIconContainer.appendChild(replayIcon);
  712.  
  713. const replayTextContainer = document.createElement('div');
  714. replayTextContainer.className = 'css-175oi2r r-16y2uox r-1wbh5a2';
  715.  
  716. const replayText = document.createElement('div');
  717. replayText.dir = 'ltr';
  718. replayText.className = 'css-146c3p1 r-bcqeeo r-1ttztb7 r-qvutc0 r-37j5jr r-a023e6 r-rjixqe r-b88u0q';
  719. replayText.style.color = 'rgb(231, 233, 234)';
  720. replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Copy Replay URL</span>';
  721. replayTextContainer.appendChild(replayText);
  722.  
  723. replayItem.appendChild(replayIconContainer);
  724. replayItem.appendChild(replayTextContainer);
  725.  
  726. const replayStyle = document.createElement('style');
  727. replayStyle.textContent = '#copy-replay-url-share:hover { background-color: rgba(231, 233, 234, 0.1); }';
  728. replayItem.appendChild(replayStyle);
  729.  
  730. replayItem.addEventListener('click', async (e) => {
  731. e.preventDefault();
  732. if (!dynamicUrl) {
  733. replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">No Dynamic URL</span>';
  734. setTimeout(() => replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Copy Replay URL</span>', 2000);
  735. dropdown.style.display = 'none';
  736. return;
  737. }
  738. replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Generating...</span>';
  739. const newReplayUrl = await fetchReplayUrl(dynamicUrl);
  740. if (newReplayUrl.startsWith('http')) {
  741. navigator.clipboard.writeText(newReplayUrl).then(() => {
  742. replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Copied!</span>';
  743. setTimeout(() => replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Copy Replay URL</span>', 2000);
  744. }).catch(() => {
  745. replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Copy Failed</span>';
  746. setTimeout(() => replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Copy Replay URL</span>', 2000);
  747. });
  748. } else if (newReplayUrl.startsWith('data:text/html')) {
  749. replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Open Converter</span>';
  750. window.open(newReplayUrl, '_blank');
  751. setTimeout(() => replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Copy Replay URL</span>', 5000);
  752. } else {
  753. replayText.innerHTML = `<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">${newReplayUrl}</span>`;
  754. setTimeout(() => replayText.innerHTML = '<span class="css-1jxf684 r-bcqeeo r-1ttztb7 r-qvutc0 r-poiln3">Copy Replay URL</span>', 2000);
  755. }
  756. dropdown.style.display = 'none';
  757. });
  758.  
  759. const shareViaItem = dropdown.querySelector('div[data-testid="share-by-tweet"]');
  760. if (shareViaItem) {
  761. dropdown.insertBefore(downloadItem, shareViaItem.nextSibling);
  762. dropdown.insertBefore(replayItem, downloadItem.nextSibling);
  763. } else {
  764. dropdown.appendChild(downloadItem);
  765. dropdown.appendChild(replayItem);
  766. }
  767. }
  768.  
  769. function updateVisibilityAndPosition() {
  770. const reactionToggle = document.querySelector('button svg path[d="M17 12v3h-2.998v2h3v3h2v-3h3v-2h-3.001v-3H17zm-5 6.839c-3.871-2.34-6.053-4.639-7.127-6.609-1.112-2.04-1.031-3.7-.479-4.82.561-1.13 1.667-1.84 2.91-1.91 1.222-.06 2.68.51 3.892 2.16l.806 1.09.805-1.09c1.211-1.65 2.668-2.22 3.89-2.16 1.242.07 2.347.78 2.908 1.91.334.677.49 1.554.321 2.59h2.011c.153-1.283-.039-2.469-.539-3.48-.887-1.79-2.647-2.91-4.601-3.01-1.65-.09-3.367.56-4.796 2.01-1.43-1.45-3.147-2.1-4.798-2.01-1.954.1-3.714 1.22-4.601 3.01-.896 1.81-.846 4.17.514 6.67 1.353 2.48 4.003 5.12 8.382 7.67l.502.299v-2.32z"]');
  771. const peopleButton = document.querySelector('button svg path[d="M6.662 18H.846l.075-1.069C1.33 11.083 4.335 9 7.011 9c1.416 0 2.66.547 3.656 1.53-1.942 1.373-3.513 3.758-4.004 7.47zM7 8c1.657 0 3-1.346 3-3S8.657 2 7 2 4 3.346 4 5s1.343 3 3 3zm10.616 1.27C18.452 8.63 19 7.632 19 6.5 19 4.57 17.433 3 15.5 3S12 4.57 12 6.5c0 1.132.548 2.13 1.384 2.77.589.451 1.317.73 2.116.73s1.527-.279 2.116-.73zM8.501 19.972l-.029 1.027h14.057l-.029-1.027c-.184-6.618-3.736-8.977-7-8.977s-6.816 2.358-7 8.977z"]');
  772. const isInSpace = reactionToggle !== null || peopleButton !== null;
  773. const endedScreen = Array.from(document.querySelectorAll('.css-146c3p1.r-bcqeeo.r-1ttztb7.r-qvutc0.r-37j5jr.r-1b43r93.r-b88u0q.r-xnfwke.r-tsynxw span.css-1jxf684.r-bcqeeo.r-1ttztb7.r-qvutc0.r-poiln3')).find(span => span.textContent.includes('Ended'));
  774.  
  775. if (isInSpace && !lastSpaceState) {
  776. const urlSpaceId = getSpaceIdFromUrl();
  777. if (urlSpaceId) {
  778. currentSpaceId = urlSpaceId;
  779. if (currentSpaceId !== lastSpaceId) {
  780. handQueue.clear();
  781. activeHandRaises.clear();
  782. captionsData = [];
  783. emojiReactions = [];
  784. lastSpeaker = { username: '', handle: '' };
  785. previousOccupancy = null;
  786. totalParticipants = 0;
  787. if (transcriptPopup) {
  788. const captionWrapper = transcriptPopup.querySelector('#transcript-output');
  789. if (captionWrapper) captionWrapper.innerHTML = '';
  790. }
  791. } else {
  792. handQueue.clear();
  793. activeHandRaises.clear();
  794. if (transcriptPopup && transcriptPopup.style.display === 'block') updateTranscriptPopup();
  795. }
  796. lastSpaceId = currentSpaceId;
  797. saveSettings();
  798. }
  799. } else if (!isInSpace && lastSpaceState && !endedScreen) {
  800. currentSpaceId = null;
  801. saveSettings();
  802. activeHandRaises.clear();
  803. }
  804.  
  805. if (isInSpace && peopleButton) {
  806. const peopleBtn = peopleButton.closest('button');
  807. if (peopleBtn) {
  808. const rect = peopleBtn.getBoundingClientRect();
  809. const baseTop = rect.top - 10;
  810. transcriptButton.style.position = 'fixed';
  811. transcriptButton.style.left = `${rect.left - 46}px`;
  812. transcriptButton.style.top = `${queueButton && queueButton.style.display !== 'none' ? baseTop + 40 : rect.top}px`;
  813. transcriptButton.style.display = 'block';
  814.  
  815. if (queueButton) {
  816. queueButton.style.position = 'fixed';
  817. queueButton.style.left = `${rect.left - 46}px`;
  818. queueButton.style.top = `${baseTop}px`;
  819. queueButton.style.display = handQueue.size > 0 ? 'block' : 'none';
  820. }
  821.  
  822. if (handQueuePopup) {
  823. handQueuePopup.style.right = transcriptPopup.style.right;
  824. handQueuePopup.style.bottom = transcriptPopup.style.bottom;
  825. }
  826. }
  827. if (reactionToggle) createEmojiPickerGrid();
  828. } else {
  829. transcriptButton.style.display = 'none';
  830. if (queueButton) queueButton.style.display = 'none';
  831. if (handQueuePopup) handQueuePopup.style.display = 'none';
  832. transcriptPopup.style.display = 'none';
  833. if (queueRefreshInterval) {
  834. clearInterval(queueRefreshInterval);
  835. queueRefreshInterval = null;
  836. }
  837. }
  838.  
  839. const endedContainer = detectEndedUI();
  840. if (endedContainer && lastSpaceState) {
  841. currentSpaceId = null;
  842. saveSettings();
  843. activeHandRaises.clear();
  844. transcriptButton.style.display = 'none';
  845. if (queueButton) queueButton.style.display = 'none';
  846. if (handQueuePopup) handQueuePopup.style.display = 'none';
  847. transcriptPopup.style.display = 'none';
  848. if (queueRefreshInterval) {
  849. clearInterval(queueRefreshInterval);
  850. queueRefreshInterval = null;
  851. }
  852. }
  853.  
  854. lastSpaceState = isInSpace;
  855. }
  856.  
  857. function updateQueueButtonVisibility() {
  858. if (queueButton) {
  859. queueButton.style.display = handQueue.size > 0 ? 'block' : 'none';
  860. updateVisibilityAndPosition();
  861. }
  862. }
  863.  
  864. async function formatTranscriptForDownload() {
  865. const spaceId = getSpaceIdFromUrl();
  866. const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  867. const baseHeader = '--- Space URLs ---\n' +
  868. (spaceId ? `Space URL: https://x.com/i/spaces/${spaceId}\n` : 'Space URL: Not available\n') +
  869. (dynamicUrl ? `Live URL: ${dynamicUrl}\n` : 'Live URL: Not available\n');
  870.  
  871. let replayUrl = 'Replay URL: Not available\n';
  872. try {
  873. const generatedReplayUrl = await fetchReplayUrl(dynamicUrl);
  874. replayUrl = `Replay URL: ${generatedReplayUrl}\n`;
  875. } catch (e) {
  876. replayUrl = 'Replay URL: Failed to generate\n';
  877. }
  878.  
  879. const header = `${baseHeader}${replayUrl}-----------------\n\n`;
  880.  
  881. const combinedData = [
  882. ...captionsData.map(item => ({ ...item, type: 'caption' })),
  883. ...emojiReactions.map(item => ({ ...item, type: 'emoji' }))
  884. ].sort((a, b) => a.timestamp - b.timestamp);
  885.  
  886. let transcriptionText = header;
  887. let previousSpeakerTrans = { username: '', handle: '' };
  888. const transcriptions = combinedData.filter(item => item.type === 'caption' && item.displayName !== 'System');
  889.  
  890. transcriptions.forEach((item, i) => {
  891. let { displayName, handle } = item;
  892. if (displayName === 'Unknown' && previousSpeakerTrans.username) {
  893. displayName = previousSpeakerTrans.username;
  894. handle = previousSpeakerTrans.handle;
  895. }
  896. if (i > 0 && previousSpeakerTrans.username !== displayName) {
  897. const date = new Date(item.timestamp);
  898. const timestampStr = date.toISOString().replace('T', ' ').substring(0, 19);
  899. transcriptionText += `\n[${timestampStr}]\n`;
  900. }
  901. transcriptionText += `${displayName} ${handle}\n${item.text}\n\n`;
  902. previousSpeakerTrans = { username: displayName, handle };
  903. });
  904.  
  905. let systemText = header;
  906. let previousSpeakerSys = { username: '', handle: '' };
  907. const systemAndReactions = combinedData.filter(item => item.type === 'emoji' || (item.type === 'caption' && item.displayName === 'System'));
  908.  
  909. systemAndReactions.forEach((item, i) => {
  910. let { displayName, handle } = item;
  911. if (displayName === 'Unknown' && previousSpeakerSys.username) {
  912. displayName = previousSpeakerSys.username;
  913. handle = previousSpeakerSys.handle;
  914. }
  915. if (i > 0 && previousSpeakerSys.username !== displayName && item.type === 'caption') {
  916. const date = new Date(item.timestamp);
  917. const timestampStr = date.toISOString().replace('T', ' ').substring(0, 19);
  918. systemText += `\n[${timestampStr}]\n`;
  919. }
  920. if (item.type === 'caption') {
  921. systemText += `${displayName} ${handle}\n${item.text}\n\n`;
  922. } else if (item.type === 'emoji') {
  923. systemText += `${displayName} reacted with ${item.emoji}\n`;
  924. }
  925. previousSpeakerSys = { username: displayName, handle };
  926. });
  927.  
  928. return {
  929. transcription: { content: transcriptionText, filename: `transcriptions_${timestamp}.txt` },
  930. system: { content: systemText, filename: `system_reactions_${timestamp}.txt` }
  931. };
  932. }
  933.  
  934. let isUserScrolledUp = false;
  935. let currentFontSize = 14;
  936. let searchTerm = '';
  937.  
  938. function filterTranscript(captions, emojis, term) {
  939. if (!term) return { captions, emojis };
  940. const filteredCaptions = captions.filter(caption =>
  941. caption.text.toLowerCase().includes(term.toLowerCase()) ||
  942. caption.displayName.toLowerCase().includes(term.toLowerCase()) ||
  943. caption.handle.toLowerCase().includes(term.toLowerCase())
  944. );
  945. const filteredEmojis = emojis.filter(emoji =>
  946. emoji.emoji.toLowerCase().includes(term.toLowerCase()) ||
  947. emoji.displayName.toLowerCase().includes(term.toLowerCase()) ||
  948. emoji.handle.toLowerCase().includes(term.toLowerCase())
  949. );
  950. return { captions: filteredCaptions, emojis: filteredEmojis };
  951. }
  952.  
  953. function updateTranscriptPopup() {
  954. if (!transcriptPopup || transcriptPopup.style.display !== 'block') return;
  955.  
  956. let queueContainer = transcriptPopup.querySelector('#queue-container');
  957. let searchContainer = transcriptPopup.querySelector('#search-container');
  958. let scrollArea = transcriptPopup.querySelector('#transcript-scrollable');
  959. let systemArea = transcriptPopup.querySelector('#system-messages');
  960. let saveButton = transcriptPopup.querySelector('.save-button');
  961. let textSizeContainer = transcriptPopup.querySelector('.text-size-container');
  962. let systemToggleButton = transcriptPopup.querySelector('#system-toggle-button');
  963. let emojiToggleButton = transcriptPopup.querySelector('#emoji-toggle-button');
  964. let replayToggleButton = transcriptPopup.querySelector('#replay-toggle-button');
  965. let currentScrollTop = scrollArea ? scrollArea.scrollTop : 0;
  966. let wasAtBottom = scrollArea ? (scrollArea.scrollHeight - scrollArea.scrollTop - scrollArea.clientHeight < 50) : true;
  967.  
  968. let showEmojisInUI = localStorage.getItem(STORAGE_KEYS.SHOW_EMOJIS) !== 'false';
  969. let showSystemMessagesInUI = localStorage.getItem(STORAGE_KEYS.SHOW_SYSTEM_MESSAGES) !== 'false';
  970. let isReplayEnabled = localStorage.getItem('xSpacesCustomReactions_replayEnabled') !== 'false';
  971.  
  972. if (!queueContainer || !searchContainer || !scrollArea || !systemArea || !saveButton || !textSizeContainer || !systemToggleButton || !emojiToggleButton || !replayToggleButton) {
  973. transcriptPopup.innerHTML = '';
  974.  
  975. queueContainer = document.createElement('div');
  976. queueContainer.id = 'queue-container';
  977. queueContainer.style.marginBottom = '10px';
  978. transcriptPopup.appendChild(queueContainer);
  979.  
  980. searchContainer = document.createElement('div');
  981. searchContainer.id = 'search-container';
  982. searchContainer.style.display = 'none';
  983. searchContainer.style.marginBottom = '5px';
  984.  
  985. const searchInput = document.createElement('input');
  986. searchInput.type = 'text';
  987. searchInput.placeholder = 'Search transcript...';
  988. searchInput.style.width = '87%';
  989. searchInput.style.padding = '5px';
  990. searchInput.style.backgroundColor = 'rgba(255, 255, 255, 0.1)';
  991. searchInput.style.border = 'none';
  992. searchInput.style.borderRadius = '5px';
  993. searchInput.style.color = 'white';
  994. searchInput.style.fontSize = '14px';
  995. searchInput.addEventListener('input', (e) => {
  996. searchTerm = e.target.value.trim();
  997. updateTranscriptPopup();
  998. });
  999.  
  1000. searchContainer.appendChild(searchInput);
  1001. transcriptPopup.appendChild(searchContainer);
  1002.  
  1003. scrollArea = document.createElement('div');
  1004. scrollArea.id = 'transcript-scrollable';
  1005. scrollArea.style.flex = '1';
  1006. scrollArea.style.overflowY = 'auto';
  1007. scrollArea.style.maxHeight = '250px';
  1008. scrollArea.style.marginBottom = '5px';
  1009.  
  1010. const captionWrapper = document.createElement('div');
  1011. captionWrapper.id = 'transcript-output';
  1012. captionWrapper.style.color = '#e7e9ea';
  1013. captionWrapper.style.fontFamily = 'Arial, sans-serif';
  1014. captionWrapper.style.whiteSpace = 'pre-wrap';
  1015. captionWrapper.style.fontSize = `${currentFontSize}px`;
  1016. scrollArea.appendChild(captionWrapper);
  1017. transcriptPopup.appendChild(scrollArea);
  1018.  
  1019. systemArea = document.createElement('div');
  1020. systemArea.id = 'system-messages';
  1021. systemArea.style.height = '4em';
  1022. systemArea.style.overflowY = 'auto';
  1023. systemArea.style.borderTop = '1px solid rgba(255, 255, 255, 0.3)';
  1024. systemArea.style.paddingTop = '5px';
  1025. systemArea.style.marginBottom = '5px';
  1026.  
  1027. const systemWrapper = document.createElement('div');
  1028. systemWrapper.id = 'system-output';
  1029. systemWrapper.style.color = '#e7e9ea';
  1030. systemWrapper.style.fontFamily = 'Arial, sans-serif';
  1031. systemWrapper.style.whiteSpace = 'pre-wrap';
  1032. systemWrapper.style.fontSize = `${currentFontSize}px`;
  1033. systemArea.appendChild(systemWrapper);
  1034. transcriptPopup.appendChild(systemArea);
  1035.  
  1036. const controlsContainer = document.createElement('div');
  1037. controlsContainer.style.display = 'flex';
  1038. controlsContainer.style.alignItems = 'center';
  1039. controlsContainer.style.justifyContent = 'space-between';
  1040. controlsContainer.style.padding = '5px 0';
  1041. controlsContainer.style.borderTop = '1px solid rgba(255, 255, 255, 0.3)';
  1042.  
  1043. saveButton = document.createElement('div');
  1044. saveButton.className = 'save-button';
  1045. saveButton.textContent = '💾 Save Transcript';
  1046. saveButton.style.color = '#1DA1F2';
  1047. saveButton.style.fontSize = '14px';
  1048. saveButton.style.cursor = 'pointer';
  1049. saveButton.addEventListener('click', async () => {
  1050. saveButton.textContent = '💾 Saving...';
  1051. const transcripts = await formatTranscriptForDownload();
  1052.  
  1053. // Download the transcription file first
  1054. const transcriptionBlob = new Blob([transcripts.transcription.content], { type: 'text/plain' });
  1055. const transcriptionUrl = URL.createObjectURL(transcriptionBlob);
  1056. const transcriptionLink = document.createElement('a');
  1057. transcriptionLink.href = transcriptionUrl;
  1058. transcriptionLink.download = transcripts.transcription.filename;
  1059. document.body.appendChild(transcriptionLink);
  1060. transcriptionLink.click();
  1061. document.body.removeChild(transcriptionLink);
  1062. URL.revokeObjectURL(transcriptionUrl);
  1063.  
  1064. // Wait 10 seconds before downloading the system and emoji reactions file
  1065. setTimeout(() => {
  1066. const systemBlob = new Blob([transcripts.system.content], { type: 'text/plain' });
  1067. const systemUrl = URL.createObjectURL(systemBlob);
  1068. const systemLink = document.createElement('a');
  1069. systemLink.href = systemUrl;
  1070. systemLink.download = transcripts.system.filename;
  1071. document.body.appendChild(systemLink);
  1072. systemLink.click();
  1073. document.body.removeChild(systemLink);
  1074. URL.revokeObjectURL(systemUrl);
  1075.  
  1076. saveButton.textContent = '💾 Save Transcript';
  1077. }, 10000); // 10-second delay
  1078. });
  1079. saveButton.addEventListener('mouseover', () => saveButton.style.color = '#FF9800');
  1080. saveButton.addEventListener('mouseout', () => saveButton.style.color = '#1DA1F2');
  1081.  
  1082. textSizeContainer = document.createElement('div');
  1083. textSizeContainer.className = 'text-size-container';
  1084. textSizeContainer.style.display = 'flex';
  1085. textSizeContainer.style.alignItems = 'center';
  1086.  
  1087. systemToggleButton = document.createElement('span');
  1088. systemToggleButton.id = 'system-toggle-button';
  1089. systemToggleButton.style.position = 'relative';
  1090. systemToggleButton.style.fontSize = '14px';
  1091. systemToggleButton.style.cursor = 'pointer';
  1092. systemToggleButton.style.marginRight = '5px';
  1093. systemToggleButton.style.width = '14px';
  1094. systemToggleButton.style.height = '14px';
  1095. systemToggleButton.style.display = 'inline-flex';
  1096. systemToggleButton.style.alignItems = 'center';
  1097. systemToggleButton.style.justifyContent = 'center';
  1098. systemToggleButton.title = 'Toggle System Messages in UI';
  1099. systemToggleButton.innerHTML = '📢';
  1100.  
  1101. const systemNotAllowedOverlay = document.createElement('span');
  1102. systemNotAllowedOverlay.style.position = 'absolute';
  1103. systemNotAllowedOverlay.style.width = '14px';
  1104. systemNotAllowedOverlay.style.height = '14px';
  1105. systemNotAllowedOverlay.style.border = '2px solid red';
  1106. systemNotAllowedOverlay.style.borderRadius = '50%';
  1107. systemNotAllowedOverlay.style.transform = 'rotate(45deg)';
  1108. systemNotAllowedOverlay.style.background = 'transparent';
  1109. systemNotAllowedOverlay.style.display = showSystemMessagesInUI ? 'none' : 'block';
  1110.  
  1111. const systemSlash = document.createElement('span');
  1112. systemSlash.style.position = 'absolute';
  1113. systemSlash.style.width = '2px';
  1114. systemSlash.style.height = '18px';
  1115. systemSlash.style.background = 'red';
  1116. systemSlash.style.transform = 'rotate(-45deg)';
  1117. systemSlash.style.top = '-2px';
  1118. systemSlash.style.left = '6px';
  1119. systemNotAllowedOverlay.appendChild(systemSlash);
  1120.  
  1121. systemToggleButton.appendChild(systemNotAllowedOverlay);
  1122.  
  1123. systemToggleButton.addEventListener('click', () => {
  1124. showSystemMessagesInUI = !showSystemMessagesInUI;
  1125. systemNotAllowedOverlay.style.display = showSystemMessagesInUI ? 'none' : 'block';
  1126. localStorage.setItem(STORAGE_KEYS.SHOW_SYSTEM_MESSAGES, showSystemMessagesInUI);
  1127. updateTranscriptPopup();
  1128. });
  1129.  
  1130. emojiToggleButton = document.createElement('span');
  1131. emojiToggleButton.id = 'emoji-toggle-button';
  1132. emojiToggleButton.style.position = 'relative';
  1133. emojiToggleButton.style.fontSize = '14px';
  1134. emojiToggleButton.style.cursor = 'pointer';
  1135. emojiToggleButton.style.marginRight = '5px';
  1136. emojiToggleButton.style.width = '14px';
  1137. emojiToggleButton.style.height = '14px';
  1138. emojiToggleButton.style.display = 'inline-flex';
  1139. emojiToggleButton.style.alignItems = 'center';
  1140. emojiToggleButton.style.justifyContent = 'center';
  1141. emojiToggleButton.title = 'Toggle Emoji Reactions in UI';
  1142. emojiToggleButton.innerHTML = '🙂';
  1143.  
  1144. const emojiNotAllowedOverlay = document.createElement('span');
  1145. emojiNotAllowedOverlay.style.position = 'absolute';
  1146. emojiNotAllowedOverlay.style.width = '14px';
  1147. emojiNotAllowedOverlay.style.height = '14px';
  1148. emojiNotAllowedOverlay.style.border = '2px solid red';
  1149. emojiNotAllowedOverlay.style.borderRadius = '50%';
  1150. emojiNotAllowedOverlay.style.transform = 'rotate(45deg)';
  1151. emojiNotAllowedOverlay.style.background = 'transparent';
  1152. emojiNotAllowedOverlay.style.display = showEmojisInUI ? 'none' : 'block';
  1153.  
  1154. const emojiSlash = document.createElement('span');
  1155. emojiSlash.style.position = 'absolute';
  1156. emojiSlash.style.width = '2px';
  1157. emojiSlash.style.height = '18px';
  1158. emojiSlash.style.background = 'red';
  1159. emojiSlash.style.transform = 'rotate(-45deg)';
  1160. emojiSlash.style.top = '-2px';
  1161. emojiSlash.style.left = '6px';
  1162. emojiNotAllowedOverlay.appendChild(emojiSlash);
  1163.  
  1164. emojiToggleButton.appendChild(emojiNotAllowedOverlay);
  1165.  
  1166. emojiToggleButton.addEventListener('click', () => {
  1167. showEmojisInUI = !showEmojisInUI;
  1168. emojiNotAllowedOverlay.style.display = showEmojisInUI ? 'none' : 'block';
  1169. localStorage.setItem(STORAGE_KEYS.SHOW_EMOJIS, showEmojisInUI);
  1170. updateTranscriptPopup();
  1171. });
  1172.  
  1173. replayToggleButton = document.createElement('span');
  1174. replayToggleButton.id = 'replay-toggle-button';
  1175. replayToggleButton.style.position = 'relative';
  1176. replayToggleButton.style.fontSize = '14px';
  1177. replayToggleButton.style.cursor = 'pointer';
  1178. replayToggleButton.style.marginRight = '5px';
  1179. replayToggleButton.style.width = '14px';
  1180. replayToggleButton.style.height = '14px';
  1181. replayToggleButton.style.display = 'inline-flex';
  1182. replayToggleButton.style.alignItems = 'center';
  1183. replayToggleButton.style.justifyContent = 'center';
  1184. replayToggleButton.title = 'Toggle Replay Availability';
  1185. replayToggleButton.innerHTML = '📼';
  1186.  
  1187. const replayNotAllowedOverlay = document.createElement('span');
  1188. replayNotAllowedOverlay.style.position = 'absolute';
  1189. replayNotAllowedOverlay.style.width = '14px';
  1190. replayNotAllowedOverlay.style.height = '14px';
  1191. replayNotAllowedOverlay.style.border = '2px solid red';
  1192. replayNotAllowedOverlay.style.borderRadius = '50%';
  1193. replayNotAllowedOverlay.style.transform = 'rotate(45deg)';
  1194. replayNotAllowedOverlay.style.background = 'transparent';
  1195. replayNotAllowedOverlay.style.display = isReplayEnabled ? 'none' : 'block';
  1196.  
  1197. const replaySlash = document.createElement('span');
  1198. replaySlash.style.position = 'absolute';
  1199. replaySlash.style.width = '2px';
  1200. replaySlash.style.height = '18px';
  1201. replaySlash.style.background = 'red';
  1202. replaySlash.style.transform = 'rotate(-45deg)';
  1203. replaySlash.style.top = '-2px';
  1204. replaySlash.style.left = '6px';
  1205. replayNotAllowedOverlay.appendChild(replaySlash);
  1206.  
  1207. replayToggleButton.appendChild(replayNotAllowedOverlay);
  1208.  
  1209. replayToggleButton.addEventListener('click', async () => {
  1210. isReplayEnabled = !isReplayEnabled;
  1211. replayNotAllowedOverlay.style.display = isReplayEnabled ? 'none' : 'block';
  1212. localStorage.setItem('xSpacesCustomReactions_replayEnabled', isReplayEnabled);
  1213.  
  1214. if (!capturedCookie) {
  1215. return;
  1216. }
  1217.  
  1218. const broadcastId = currentSpaceId;
  1219. if (!broadcastId) {
  1220. return;
  1221. }
  1222.  
  1223. const payload = {
  1224. topics: [],
  1225. is_space_available_for_clipping: false,
  1226. cookie: capturedCookie,
  1227. is_space_available_for_replay: isReplayEnabled,
  1228. locale: "en",
  1229. replay_start_time: 0,
  1230. no_incognito: false,
  1231. replay_edited_title: "",
  1232. replay_thumbnail_time_code: 0,
  1233. broadcast_id: broadcastId
  1234. };
  1235.  
  1236. try {
  1237. const response = await fetch('https://proxsee.pscp.tv/api/v2/replayBroadcastEdit?build=com.atebits.Tweetie210.86', {
  1238. method: 'POST',
  1239. headers: {
  1240. 'Content-Type': 'application/json'
  1241. },
  1242. body: JSON.stringify(payload)
  1243. });
  1244. if (!response.ok) {
  1245. }
  1246. } catch (error) {
  1247. }
  1248.  
  1249. updateTranscriptPopup();
  1250. });
  1251.  
  1252. const magnifierEmoji = document.createElement('span');
  1253. magnifierEmoji.textContent = '🔍';
  1254. magnifierEmoji.style.marginRight = '5px';
  1255. magnifierEmoji.style.fontSize = '14px';
  1256. magnifierEmoji.style.cursor = 'pointer';
  1257. magnifierEmoji.title = 'Search transcript';
  1258. magnifierEmoji.addEventListener('click', () => {
  1259. searchContainer.style.display = searchContainer.style.display === 'none' ? 'block' : 'none';
  1260. if (searchContainer.style.display === 'block') searchInput.focus();
  1261. else {
  1262. searchTerm = '';
  1263. searchInput.value = '';
  1264. updateTranscriptPopup();
  1265. }
  1266. });
  1267.  
  1268. const textSizeSlider = document.createElement('input');
  1269. textSizeSlider.type = 'range';
  1270. textSizeSlider.min = '12';
  1271. textSizeSlider.max = '18';
  1272. textSizeSlider.value = currentFontSize;
  1273. textSizeSlider.style.width = '50px';
  1274. textSizeSlider.style.cursor = 'pointer';
  1275. textSizeSlider.title = 'Adjust transcript text size';
  1276. textSizeSlider.addEventListener('input', () => {
  1277. currentFontSize = parseInt(textSizeSlider.value, 10);
  1278. const captionWrapper = transcriptPopup.querySelector('#transcript-output');
  1279. const systemWrapper = transcriptPopup.querySelector('#system-output');
  1280. if (captionWrapper) captionWrapper.style.fontSize = `${currentFontSize}px`;
  1281. if (systemWrapper) systemWrapper.style.fontSize = `${currentFontSize}px`;
  1282. localStorage.setItem('xSpacesCustomReactions_textSize', currentFontSize);
  1283. });
  1284.  
  1285. const savedTextSize = localStorage.getItem('xSpacesCustomReactions_textSize');
  1286. if (savedTextSize) {
  1287. currentFontSize = parseInt(savedTextSize, 10);
  1288. textSizeSlider.value = currentFontSize;
  1289. }
  1290.  
  1291. textSizeContainer.appendChild(systemToggleButton);
  1292. textSizeContainer.appendChild(emojiToggleButton);
  1293. textSizeContainer.appendChild(replayToggleButton);
  1294. textSizeContainer.appendChild(magnifierEmoji);
  1295. textSizeContainer.appendChild(textSizeSlider);
  1296.  
  1297. controlsContainer.appendChild(saveButton);
  1298. controlsContainer.appendChild(textSizeContainer);
  1299.  
  1300. transcriptPopup.appendChild(controlsContainer);
  1301. }
  1302.  
  1303. const { captions: filteredCaptions, emojis: filteredEmojis } = filterTranscript(captionsData, emojiReactions, searchTerm);
  1304. const uiCaptions = filteredCaptions.filter(c => c.displayName !== 'System');
  1305. const uiSystemMessages = showSystemMessagesInUI ? filteredCaptions.filter(c => c.displayName === 'System') : [];
  1306. const uiEmojis = showEmojisInUI ? filteredEmojis : [];
  1307.  
  1308. const transcriptionData = [
  1309. ...uiCaptions.map(item => ({ ...item, type: 'caption' })),
  1310. ...uiEmojis.map(item => ({ ...item, type: 'emoji' }))
  1311. ].sort((a, b) => a.timestamp - b.timestamp);
  1312.  
  1313. const systemData = uiSystemMessages.map(item => ({ ...item, type: 'caption' }))
  1314. .sort((a, b) => a.timestamp - b.timestamp);
  1315.  
  1316. const hasTranscriptions = captionsData.some(caption => caption.displayName !== 'System');
  1317.  
  1318. if (!hasTranscriptions && !searchTerm) {
  1319. const captionWrapper = scrollArea.querySelector('#transcript-output');
  1320. if (captionWrapper) {
  1321. captionWrapper.innerHTML = `<div style="color: #FFD700; font-size: ${currentFontSize}px; margin-bottom: 10px;">Transcription not started. To start, turn closed captions on and off momentarily from the ... menu.</div>`;
  1322. }
  1323. const systemWrapper = systemArea.querySelector('#system-output');
  1324. if (systemWrapper) systemWrapper.innerHTML = '';
  1325. return;
  1326. }
  1327.  
  1328. let previousSpeaker = lastSpeaker || { username: '', handle: '' };
  1329. if (transcriptionData.length > 200) {
  1330. for (let i = transcriptionData.length - 201; i >= 0; i--) {
  1331. if (transcriptionData[i].type === 'caption') {
  1332. previousSpeaker = { username: transcriptionData[i].displayName, handle: transcriptionData[i].handle };
  1333. break;
  1334. }
  1335. }
  1336. }
  1337.  
  1338. const recentTranscriptionData = transcriptionData.slice(-200);
  1339. let transcriptionGroups = [];
  1340. let currentGroup = null;
  1341. recentTranscriptionData.forEach(item => {
  1342. if (item.type === 'caption') {
  1343. if (currentGroup) {
  1344. transcriptionGroups.push(currentGroup);
  1345. currentGroup = null;
  1346. }
  1347. transcriptionGroups.push(item);
  1348. } else if (item.type === 'emoji' && showEmojisInUI) {
  1349. if (currentGroup && currentGroup.displayName === item.displayName && currentGroup.emoji === item.emoji &&
  1350. Math.abs(item.timestamp - currentGroup.items[currentGroup.items.length - 1].timestamp) < 50) {
  1351. currentGroup.count++;
  1352. currentGroup.items.push(item);
  1353. } else {
  1354. if (currentGroup) transcriptionGroups.push(currentGroup);
  1355. currentGroup = { displayName: item.displayName, emoji: item.emoji, count: 1, items: [item] };
  1356. }
  1357. }
  1358. });
  1359. if (currentGroup) transcriptionGroups.push(currentGroup);
  1360.  
  1361. let transcriptionHtml = '';
  1362. if (transcriptionData.length > 200) {
  1363. transcriptionHtml += '<div style="color: #FFD700; font-size: 12px; margin-bottom: 10px;">Showing the last 200 lines. Save transcript to see the full conversation.</div>';
  1364. }
  1365. transcriptionGroups.forEach((group) => {
  1366. if (group.type === 'caption') {
  1367. let { displayName, handle, text } = group;
  1368. if (displayName === 'Unknown' && previousSpeaker.username) {
  1369. displayName = previousSpeaker.username;
  1370. handle = previousSpeaker.handle;
  1371. }
  1372. transcriptionHtml += `<span style="font-size: ${currentFontSize}px; color: #1DA1F2">${displayName}</span> ` +
  1373. `<span style="font-size: ${currentFontSize}px; color: #808080">${handle}</span><br>` +
  1374. `<span style="font-size: ${currentFontSize}px; color: #FFFFFF">${text}</span><br><br>`;
  1375. previousSpeaker = { username: displayName, handle };
  1376. } else if (showEmojisInUI) {
  1377. let { displayName, emoji, count } = group;
  1378. if (displayName === 'Unknown' && previousSpeaker.username) {
  1379. displayName = previousSpeaker.username;
  1380. }
  1381. const countText = count > 1 ? ` <span style="font-size: ${currentFontSize}px; color: #FFD700">x${count}</span>` : '';
  1382. transcriptionHtml += `<span style="font-size: ${currentFontSize}px; color: #FFD700">${displayName}</span> ` +
  1383. `<span style="font-size: ${currentFontSize}px; color: #FFFFFF">reacted with ${emoji}${countText}</span><br>`;
  1384. previousSpeaker = { username: displayName, handle: group.items[0].handle };
  1385. }
  1386. });
  1387.  
  1388. let systemHtml = '';
  1389. systemData.slice(-10).forEach((item) => {
  1390. let { text } = item;
  1391. systemHtml += `<span style="font-size: ${currentFontSize}px; color: #FF4500">${text}</span><br>`;
  1392. });
  1393.  
  1394. const captionWrapper = scrollArea.querySelector('#transcript-output');
  1395. if (captionWrapper) {
  1396. captionWrapper.innerHTML = transcriptionHtml;
  1397. lastSpeaker = previousSpeaker;
  1398. if (wasAtBottom && !searchTerm) scrollArea.scrollTop = scrollArea.scrollHeight;
  1399. else scrollArea.scrollTop = currentScrollTop;
  1400. scrollArea.onscroll = () => {
  1401. isUserScrolledUp = scrollArea.scrollHeight - scrollArea.scrollTop - scrollArea.clientHeight > 50;
  1402. };
  1403. }
  1404.  
  1405. const systemWrapper = systemArea.querySelector('#system-output');
  1406. if (systemWrapper) {
  1407. systemWrapper.innerHTML = systemHtml;
  1408. systemArea.scrollTop = systemArea.scrollHeight;
  1409. }
  1410.  
  1411. if (handQueuePopup && handQueuePopup.style.display === 'block') {
  1412. updateHandQueueContent(handQueuePopup.querySelector('#hand-queue-content'));
  1413. }
  1414. }
  1415.  
  1416. function updateHandQueueContent(queueContent) {
  1417. if (!queueContent) return;
  1418. queueContent.innerHTML = '<strong>Speaking Queue</strong><br>';
  1419. if (handQueue.size === 0) {
  1420. queueContent.innerHTML += 'No hands raised.<br>';
  1421. } else {
  1422. const now = Date.now();
  1423. const sortedQueue = Array.from(handQueue.entries()).sort(([, a], [, b]) => a.timestamp - b.timestamp);
  1424.  
  1425. const queueList = document.createElement('div');
  1426. queueList.style.display = 'flex';
  1427. queueList.style.flexDirection = 'column';
  1428. queueList.style.gap = '8px';
  1429.  
  1430. const numberEmojis = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣', '7️⃣', '8️⃣', '9️⃣', '🔟'];
  1431.  
  1432. sortedQueue.forEach(([, { displayName, timestamp }], index) => {
  1433. const timeUp = Math.floor((now - timestamp) / 1000);
  1434. let timeStr;
  1435. if (timeUp >= 3600) {
  1436. const hours = Math.floor(timeUp / 3600);
  1437. const minutes = Math.floor((timeUp % 3600) / 60);
  1438. const seconds = timeUp % 60;
  1439. timeStr = `${hours}h ${minutes}m ${seconds}s`;
  1440. } else {
  1441. const minutes = Math.floor(timeUp / 60);
  1442. const seconds = timeUp % 60;
  1443. timeStr = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
  1444. }
  1445.  
  1446. const positionEmoji = index < 10 ? numberEmojis[index] : '';
  1447. const entry = document.createElement('div');
  1448. const text = document.createElement('span');
  1449. text.textContent = `${positionEmoji} ${displayName}: ${timeStr}`;
  1450. entry.appendChild(text);
  1451. queueList.appendChild(entry);
  1452. });
  1453.  
  1454. queueContent.appendChild(queueList);
  1455. }
  1456.  
  1457. if (handRaiseDurations.length > 0) {
  1458. const averageContainer = document.createElement('div');
  1459. averageContainer.style.color = 'red';
  1460. averageContainer.style.fontSize = '12px';
  1461. averageContainer.style.marginTop = '10px';
  1462. averageContainer.style.textAlign = 'right';
  1463.  
  1464. const averageSeconds = handRaiseDurations.reduce((a, b) => a + b, 0) / handRaiseDurations.length;
  1465. let avgStr;
  1466. if (averageSeconds >= 3600) {
  1467. const hours = Math.floor(averageSeconds / 3600);
  1468. const minutes = Math.floor((averageSeconds % 3600) / 60);
  1469. const seconds = Math.floor(averageSeconds % 60);
  1470. avgStr = `${hours}h ${minutes}m ${seconds}s`;
  1471. } else {
  1472. const minutes = Math.floor(averageSeconds / 60);
  1473. const seconds = Math.floor(averageSeconds % 60);
  1474. avgStr = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
  1475. }
  1476. averageContainer.textContent = `Average Wait: ${avgStr}`;
  1477.  
  1478. queueContent.appendChild(averageContainer);
  1479. }
  1480. }
  1481.  
  1482. function init() {
  1483. transcriptButton = document.createElement('button');
  1484. transcriptButton.textContent = '📜';
  1485. transcriptButton.style.zIndex = '10001';
  1486. transcriptButton.style.fontSize = '18px';
  1487. transcriptButton.style.padding = '0';
  1488. transcriptButton.style.backgroundColor = 'transparent';
  1489. transcriptButton.style.border = '0.3px solid #40648085';
  1490. transcriptButton.style.borderRadius = '50%';
  1491. transcriptButton.style.width = '36px';
  1492. transcriptButton.style.height = '36px';
  1493. transcriptButton.style.cursor = 'pointer';
  1494. transcriptButton.style.display = 'none';
  1495. transcriptButton.style.lineHeight = '32px';
  1496. transcriptButton.style.textAlign = 'center';
  1497. transcriptButton.style.position = 'fixed';
  1498. transcriptButton.style.color = 'white';
  1499. transcriptButton.style.filter = 'grayscale(100%) brightness(200%)';
  1500. transcriptButton.title = 'Transcript';
  1501.  
  1502. transcriptButton.addEventListener('mouseover', () => transcriptButton.style.backgroundColor = '#595b5b40');
  1503. transcriptButton.addEventListener('mouseout', () => transcriptButton.style.backgroundColor = 'transparent');
  1504. transcriptButton.addEventListener('click', () => {
  1505. const isVisible = transcriptPopup.style.display === 'block';
  1506. transcriptPopup.style.display = isVisible ? 'none' : 'block';
  1507. if (!isVisible) updateTranscriptPopup();
  1508. });
  1509.  
  1510. queueButton = document.createElement('button');
  1511. queueButton.textContent = '✋';
  1512. queueButton.style.zIndex = '10001';
  1513. queueButton.style.fontSize = '18px';
  1514. queueButton.style.padding = '0';
  1515. queueButton.style.backgroundColor = 'transparent';
  1516. queueButton.style.border = '0.3px solid #40648085';
  1517. queueButton.style.borderRadius = '50%';
  1518. queueButton.style.width = '36px';
  1519. queueButton.style.height = '36px';
  1520. queueButton.style.cursor = 'pointer';
  1521. queueButton.style.display = 'none';
  1522. queueButton.style.lineHeight = '32px';
  1523. queueButton.style.textAlign = 'center';
  1524. queueButton.style.position = 'fixed';
  1525. queueButton.style.color = 'white';
  1526. queueButton.style.filter = 'grayscale(100%) brightness(200%)';
  1527. queueButton.title = 'View Speaking Queue';
  1528.  
  1529. queueButton.addEventListener('mouseover', () => queueButton.style.backgroundColor = '#595b5b40');
  1530. queueButton.addEventListener('mouseout', () => queueButton.style.backgroundColor = 'transparent');
  1531. queueButton.addEventListener('click', () => {
  1532. if (!handQueuePopup) {
  1533. handQueuePopup = document.createElement('div');
  1534. handQueuePopup.id = 'hand-queue-popup';
  1535. handQueuePopup.style.position = 'fixed';
  1536. handQueuePopup.style.backgroundColor = 'rgba(21, 32, 43, 0.8)';
  1537. handQueuePopup.style.borderRadius = '10px';
  1538. handQueuePopup.style.padding = '10px';
  1539. handQueuePopup.style.zIndex = '10003';
  1540. handQueuePopup.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.5)';
  1541. handQueuePopup.style.width = '200px';
  1542. handQueuePopup.style.maxHeight = '200px';
  1543. handQueuePopup.style.overflowY = 'auto';
  1544. handQueuePopup.style.color = 'white';
  1545. handQueuePopup.style.fontSize = '14px';
  1546. handQueuePopup.style.display = 'none';
  1547.  
  1548. const closeHandButton = document.createElement('button');
  1549. closeHandButton.textContent = 'X';
  1550. closeHandButton.style.position = 'sticky';
  1551. closeHandButton.style.top = '5px';
  1552. closeHandButton.style.right = '5px';
  1553. closeHandButton.style.float = 'right';
  1554. closeHandButton.style.background = 'none';
  1555. closeHandButton.style.border = 'none';
  1556. closeHandButton.style.color = 'white';
  1557. closeHandButton.style.fontSize = '14px';
  1558. closeHandButton.style.cursor = 'pointer';
  1559. closeHandButton.style.padding = '0';
  1560. closeHandButton.style.width = '20px';
  1561. closeHandButton.style.height = '20px';
  1562. closeHandButton.style.lineHeight = '20px';
  1563. closeHandButton.style.textAlign = 'center';
  1564. closeHandButton.addEventListener('mouseover', () => closeHandButton.style.color = 'red');
  1565. closeHandButton.addEventListener('mouseout', () => closeHandButton.style.color = 'white');
  1566. closeHandButton.addEventListener('click', (e) => {
  1567. e.stopPropagation();
  1568. handQueuePopup.style.display = 'none';
  1569. });
  1570.  
  1571. const queueContent = document.createElement('div');
  1572. queueContent.id = 'hand-queue-content';
  1573. queueContent.style.paddingTop = '10px';
  1574.  
  1575. handQueuePopup.appendChild(closeHandButton);
  1576. handQueuePopup.appendChild(queueContent);
  1577. document.body.appendChild(handQueuePopup);
  1578. }
  1579.  
  1580. handQueuePopup.style.display = handQueuePopup.style.display === 'block' ? 'none' : 'block';
  1581. if (handQueuePopup.style.display === 'block') {
  1582. updateHandQueueContent(handQueuePopup.querySelector('#hand-queue-content'));
  1583. if (queueRefreshInterval) clearInterval(queueRefreshInterval);
  1584. queueRefreshInterval = setInterval(() => updateHandQueueContent(handQueuePopup.querySelector('#hand-queue-content')), 1000);
  1585. } else if (queueRefreshInterval) {
  1586. clearInterval(queueRefreshInterval);
  1587. queueRefreshInterval = null;
  1588. }
  1589. updateVisibilityAndPosition();
  1590. });
  1591.  
  1592. transcriptPopup = document.createElement('div');
  1593. transcriptPopup.style.position = 'fixed';
  1594. transcriptPopup.style.bottom = '150px';
  1595. transcriptPopup.style.right = '20px';
  1596. transcriptPopup.style.backgroundColor = 'rgba(21, 32, 43, 0.9)';
  1597. transcriptPopup.style.borderRadius = '10px';
  1598. transcriptPopup.style.padding = '10px';
  1599. transcriptPopup.style.zIndex = '10002';
  1600. transcriptPopup.style.maxHeight = '400px';
  1601. transcriptPopup.style.display = 'none';
  1602. transcriptPopup.style.width = '306px';
  1603. transcriptPopup.style.color = 'white';
  1604. transcriptPopup.style.fontSize = '14px';
  1605. transcriptPopup.style.lineHeight = '1.5';
  1606. transcriptPopup.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.5)';
  1607. transcriptPopup.style.display = 'flex';
  1608. transcriptPopup.style.flexDirection = 'column';
  1609.  
  1610. document.body.appendChild(queueButton);
  1611. document.body.appendChild(transcriptButton);
  1612. document.body.appendChild(transcriptPopup);
  1613.  
  1614. loadSettings();
  1615.  
  1616. const observer = new MutationObserver((mutationsList) => {
  1617. for (const mutation of mutationsList) {
  1618. if (mutation.type === 'childList') {
  1619. updateVisibilityAndPosition();
  1620. const dropdown = document.querySelector('div[data-testid="Dropdown"]');
  1621. if (dropdown && dropdown.closest('[role="menu"]') && (captionsData.length > 0 || emojiReactions.length > 0)) {
  1622. addDownloadOptionToShareDropdown(dropdown);
  1623. }
  1624. const audioElements = document.querySelectorAll('audio');
  1625. audioElements.forEach(audio => {
  1626. if (audio.src && audio.src.includes('dynamic_playlist.m3u8?type=live')) dynamicUrl = audio.src;
  1627. });
  1628. }
  1629. }
  1630. });
  1631.  
  1632. observer.observe(document.body, { childList: true, subtree: true });
  1633. updateVisibilityAndPosition();
  1634. setInterval(updateVisibilityAndPosition, 2000);
  1635. }
  1636.  
  1637. if (document.readyState === 'loading') {
  1638. document.addEventListener('DOMContentLoaded', init);
  1639. } else {
  1640. init();
  1641. }
  1642. })();