X Spaces +

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

目前為 2025-04-12 提交的版本,檢視 最新版本

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