YouTube Enhancer (Real-Time Subscriber Count)

Adds an overlay to YouTube channel banners showing real-time subscriber count.

当前为 2024-12-14 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube Enhancer (Real-Time Subscriber Count)
  3. // @description Adds an overlay to YouTube channel banners showing real-time subscriber count.
  4. // @icon https://raw.githubusercontent.com/exyezed/youtube-enhancer/refs/heads/main/extras/youtube-enhancer.png
  5. // @version 1.3
  6. // @author exyezed
  7. // @namespace https://github.com/exyezed/youtube-enhancer/
  8. // @supportURL https://github.com/exyezed/youtube-enhancer/issues
  9. // @license MIT
  10. // @match https://www.youtube.com/*
  11. // @grant GM_xmlhttpRequest
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16.  
  17. const OPTIONS = ['subscribers', 'views', 'videos'];
  18. const FONT_LINK = "https://fonts.googleapis.com/css2?family=Rubik:wght@400;700&display=swap";
  19. const API_BASE_URL = 'https://exyezed.vercel.app/api/channel/';
  20. const STATS_API_URL = 'https://api.livecounts.io/youtube-live-subscriber-counter/stats/';
  21. const DEFAULT_UPDATE_INTERVAL = 2000;
  22. const DEFAULT_OVERLAY_OPACITY = 0.75;
  23.  
  24. let overlay = null;
  25. let isUpdating = false;
  26. let intervalId = null;
  27. let currentChannelName = null;
  28. let updateInterval = parseInt(localStorage.getItem('youtubeEnhancerInterval')) || DEFAULT_UPDATE_INTERVAL;
  29. let overlayOpacity = parseFloat(localStorage.getItem('youtubeEnhancerOpacity')) || DEFAULT_OVERLAY_OPACITY;
  30.  
  31. const lastSuccessfulStats = new Map();
  32. const previousStats = new Map();
  33.  
  34. function init() {
  35. loadFonts();
  36. initializeLocalStorage();
  37. addStyles();
  38. observePageChanges();
  39. addNavigationListener();
  40. }
  41.  
  42. function loadFonts() {
  43. const fontLink = document.createElement("link");
  44. fontLink.rel = "stylesheet";
  45. fontLink.href = FONT_LINK;
  46. document.head.appendChild(fontLink);
  47. }
  48.  
  49. function initializeLocalStorage() {
  50. OPTIONS.forEach(option => {
  51. if (localStorage.getItem(`show-${option}`) === null) {
  52. localStorage.setItem(`show-${option}`, 'true');
  53. }
  54. });
  55. }
  56.  
  57. function addStyles() {
  58. const style = document.createElement('style');
  59. style.textContent = `
  60. .settings-button {
  61. position: absolute;
  62. top: 12px;
  63. right: 12px;
  64. width: 16px;
  65. height: 16px;
  66. cursor: pointer;
  67. z-index: 2;
  68. transition: transform 0.3s ease;
  69. }
  70. .settings-button:hover {
  71. transform: rotate(45deg);
  72. }
  73. .settings-menu {
  74. position: absolute;
  75. top: 35px;
  76. right: 12px;
  77. background: rgba(0, 0, 0, 0.95);
  78. padding: 10px;
  79. border-radius: 6px;
  80. z-index: 2;
  81. display: none;
  82. }
  83. .settings-menu.show {
  84. display: flex;
  85. }
  86. .interval-slider, .opacity-slider {
  87. width: 160px;
  88. margin: 5px 0;
  89. height: 4px;
  90. }
  91. .interval-value, .opacity-value {
  92. color: white;
  93. font-size: 12px;
  94. margin-top: 3px;
  95. margin-bottom: 8px;
  96. }
  97. .setting-group {
  98. margin-bottom: 10px;
  99. }
  100. .setting-group:last-child {
  101. margin-bottom: 0;
  102. }
  103. @keyframes spin {
  104. from { transform: rotate(0deg); }
  105. to { transform: rotate(360deg); }
  106. }
  107. `;
  108. document.head.appendChild(style);
  109. }
  110.  
  111. function createSettingsButton() {
  112. const button = document.createElement('div');
  113. button.className = 'settings-button';
  114. const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  115. svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
  116. svg.setAttribute("viewBox", "0 0 512 512");
  117. const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
  118. path.setAttribute("fill", "white");
  119. path.setAttribute("d", "M495.9 166.6c3.2 8.7 .5 18.4-6.4 24.6l-43.3 39.4c1.1 8.3 1.7 16.8 1.7 25.4s-.6 17.1-1.7 25.4l43.3 39.4c6.9 6.2 9.6 15.9 6.4 24.6c-4.4 11.9-9.7 23.3-15.8 34.3l-4.7 8.1c-6.6 11-14 21.4-22.1 31.2c-5.9 7.2-15.7 9.6-24.5 6.8l-55.7-17.7c-13.4 10.3-28.2 18.9-44 25.4l-12.5 57.1c-2 9.1-9 16.3-18.2 17.8c-13.8 2.3-28 3.5-42.5 3.5s-28.7-1.2-42.5-3.5c-9.2-1.5-16.2-8.7-18.2-17.8l-12.5-57.1c-15.8-6.5-30.6-15.1-44-25.4L83.1 425.9c-8.8 2.8-18.6 .3-24.5-6.8c-8.1-9.8-15.5-20.2-22.1-31.2l-4.7-8.1c-6.1-11-11.4-22.4-15.8-34.3c-3.2-8.7-.5-18.4 6.4-24.6l43.3-39.4C64.6 273.1 64 264.6 64 256s.6-17.1 1.7-25.4L22.4 191.2c-6.9-6.2-9.6-15.9-6.4-24.6c4.4-11.9 9.7-23.3 15.8-34.3l4.7-8.1c6.6-11 14-21.4 22.1-31.2c5.9-7.2 15.7-9.6 24.5-6.8l55.7 17.7c13.4-10.3 28.2-18.9 44-25.4l12.5-57.1c2-9.1 9-16.3 18.2-17.8C227.3 1.2 241.5 0 256 0s28.7 1.2 42.5 3.5c9.2 1.5 16.2 8.7 18.2 17.8l12.5 57.1c15.8 6.5 30.6 15.1 44 25.4l55.7-17.7c8.8-2.8 18.6-.3 24.5 6.8c8.1 9.8 15.5 20.2 22.1 31.2l4.7 8.1c6.1 11 11.4 22.4 15.8 34.3zM256 336a80 80 0 1 0 0-160 80 80 0 1 0 0 160z");
  120. svg.appendChild(path);
  121. button.appendChild(svg);
  122. return button;
  123. }
  124.  
  125. function createSettingsMenu() {
  126. const menu = document.createElement('div');
  127. menu.className = 'settings-menu';
  128. menu.style.gap = '15px';
  129. menu.style.width = '360px';
  130. const displaySection = createDisplaySection();
  131. const controlsSection = createControlsSection();
  132. menu.appendChild(displaySection);
  133. menu.appendChild(controlsSection);
  134. return menu;
  135. }
  136.  
  137. function createDisplaySection() {
  138. const displaySection = document.createElement('div');
  139. displaySection.style.flex = '1';
  140. const displayLabel = document.createElement('label');
  141. displayLabel.textContent = 'Display Options';
  142. displayLabel.style.marginBottom = '10px';
  143. displayLabel.style.display = 'block';
  144. displayLabel.style.fontSize = '16px';
  145. displayLabel.style.fontWeight = 'bold';
  146. displaySection.appendChild(displayLabel);
  147. OPTIONS.forEach(option => {
  148. const checkboxContainer = document.createElement('div');
  149. checkboxContainer.style.display = 'flex';
  150. checkboxContainer.style.alignItems = 'center';
  151. checkboxContainer.style.marginTop = '5px';
  152. const checkbox = document.createElement('input');
  153. checkbox.type = 'checkbox';
  154. checkbox.id = `show-${option}`;
  155. checkbox.checked = localStorage.getItem(`show-${option}`) !== 'false';
  156. checkbox.style.marginRight = '8px';
  157. checkbox.style.cursor = 'pointer';
  158. const checkboxLabel = document.createElement('label');
  159. checkboxLabel.htmlFor = `show-${option}`;
  160. checkboxLabel.textContent = option.charAt(0).toUpperCase() + option.slice(1);
  161. checkboxLabel.style.cursor = 'pointer';
  162. checkboxLabel.style.color = 'white';
  163. checkboxLabel.style.fontSize = '14px';
  164. checkbox.addEventListener('change', () => {
  165. localStorage.setItem(`show-${option}`, checkbox.checked);
  166. updateDisplayState();
  167. });
  168. checkboxContainer.appendChild(checkbox);
  169. checkboxContainer.appendChild(checkboxLabel);
  170. displaySection.appendChild(checkboxContainer);
  171. });
  172.  
  173. return displaySection;
  174. }
  175.  
  176. function createControlsSection() {
  177. const controlsSection = document.createElement('div');
  178. controlsSection.style.flex = '1';
  179. const intervalLabel = document.createElement('label');
  180. intervalLabel.textContent = 'Update Interval';
  181. intervalLabel.style.display = 'block';
  182. intervalLabel.style.marginBottom = '5px';
  183. intervalLabel.style.fontSize = '16px';
  184. intervalLabel.style.fontWeight = 'bold';
  185. const intervalSlider = document.createElement('input');
  186. intervalSlider.type = 'range';
  187. intervalSlider.min = '2';
  188. intervalSlider.max = '10';
  189. intervalSlider.value = updateInterval / 1000;
  190. intervalSlider.step = '1';
  191. intervalSlider.className = 'interval-slider';
  192. const intervalValue = document.createElement('div');
  193. intervalValue.className = 'interval-value';
  194. intervalValue.textContent = `${intervalSlider.value}s`;
  195. intervalValue.style.marginBottom = '15px';
  196. intervalValue.style.fontSize = '14px';
  197. intervalSlider.addEventListener('input', (e) => {
  198. const newInterval = parseInt(e.target.value) * 1000;
  199. intervalValue.textContent = `${e.target.value}s`;
  200. updateInterval = newInterval;
  201. localStorage.setItem('youtubeEnhancerInterval', newInterval);
  202. if (intervalId) {
  203. clearInterval(intervalId);
  204. intervalId = setInterval(() => {
  205. updateOverlayContent(overlay, currentChannelName);
  206. }, newInterval);
  207. }
  208. });
  209. const opacityLabel = document.createElement('label');
  210. opacityLabel.textContent = 'Background Opacity';
  211. opacityLabel.style.display = 'block';
  212. opacityLabel.style.marginBottom = '5px';
  213. opacityLabel.style.fontSize = '16px';
  214. opacityLabel.style.fontWeight = 'bold';
  215. const opacitySlider = document.createElement('input');
  216. opacitySlider.type = 'range';
  217. opacitySlider.min = '50';
  218. opacitySlider.max = '90';
  219. opacitySlider.value = overlayOpacity * 100;
  220. opacitySlider.step = '5';
  221. opacitySlider.className = 'opacity-slider';
  222. const opacityValue = document.createElement('div');
  223. opacityValue.className = 'opacity-value';
  224. opacityValue.textContent = `${opacitySlider.value}%`;
  225. opacityValue.style.fontSize = '14px';
  226. opacitySlider.addEventListener('input', (e) => {
  227. const newOpacity = parseInt(e.target.value) / 100;
  228. opacityValue.textContent = `${e.target.value}%`;
  229. overlayOpacity = newOpacity;
  230. localStorage.setItem('youtubeEnhancerOpacity', newOpacity);
  231. if (overlay) {
  232. overlay.style.backgroundColor = `rgba(0, 0, 0, ${newOpacity})`;
  233. }
  234. });
  235. controlsSection.appendChild(intervalLabel);
  236. controlsSection.appendChild(intervalSlider);
  237. controlsSection.appendChild(intervalValue);
  238. controlsSection.appendChild(opacityLabel);
  239. controlsSection.appendChild(opacitySlider);
  240. controlsSection.appendChild(opacityValue);
  241.  
  242. return controlsSection;
  243. }
  244.  
  245. function createSpinner() {
  246. const spinnerContainer = document.createElement('div');
  247. spinnerContainer.style.position = 'absolute';
  248. spinnerContainer.style.top = '0';
  249. spinnerContainer.style.left = '0';
  250. spinnerContainer.style.width = '100%';
  251. spinnerContainer.style.height = '100%';
  252. spinnerContainer.style.display = 'flex';
  253. spinnerContainer.style.justifyContent = 'center';
  254. spinnerContainer.style.alignItems = 'center';
  255. spinnerContainer.classList.add('spinner-container');
  256.  
  257. const spinner = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  258. spinner.setAttribute("viewBox", "0 0 512 512");
  259. spinner.setAttribute("width", "64");
  260. spinner.setAttribute("height", "64");
  261. spinner.classList.add('loading-spinner');
  262. spinner.style.animation = "spin 1s linear infinite";
  263.  
  264. const secondaryPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
  265. secondaryPath.setAttribute("d", "M0 256C0 114.9 114.1 .5 255.1 0C237.9 .5 224 14.6 224 32c0 17.7 14.3 32 32 32C150 64 64 150 64 256s86 192 192 192c69.7 0 130.7-37.1 164.5-92.6c-3 6.6-3.3 14.8-1 22.2c1.2 3.7 3 7.2 5.4 10.3c1.2 1.5 2.6 3 4.1 4.3c.8 .7 1.6 1.3 2.4 1.9c.4 .3 .8 .6 1.3 .9s.9 .6 1.3 .8c5 2.9 10.6 4.3 16 4.3c11 0 21.8-5.7 27.7-16c-44.3 76.5-127 128-221.7 128C114.6 512 0 397.4 0 256z");
  266. secondaryPath.style.opacity = "0.4";
  267. secondaryPath.style.fill = "white";
  268.  
  269. const primaryPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
  270. primaryPath.setAttribute("d",
  271. "M224 32c0-17.7 14.3-32 32-32C397.4 0 512 114.6 512 256c0 46.6-12.5 90.4-34.3 128c-8.8 15.3-28.4 20.5-43.7 11.7s-20.5-28.4-11.7-43.7c16.3-28.2 25.7-61 25.7-96c0-106-86-192-192-192c-17.7 0-32-14.3-32-32z");
  272. primaryPath.style.fill = "white";
  273.  
  274. spinner.appendChild(secondaryPath);
  275. spinner.appendChild(primaryPath);
  276. spinnerContainer.appendChild(spinner);
  277. return spinnerContainer;
  278. }
  279.  
  280. function createSVGIcon(path) {
  281. const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  282. svg.setAttribute("viewBox", "0 0 640 512");
  283. svg.setAttribute("width", "2rem");
  284. svg.setAttribute("height", "2rem");
  285. svg.style.marginRight = "0.5rem";
  286. svg.style.display = "none";
  287.  
  288. const svgPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
  289. svgPath.setAttribute("d", path);
  290. svgPath.setAttribute("fill", "white");
  291.  
  292. svg.appendChild(svgPath);
  293. return svg;
  294. }
  295.  
  296. function createStatContainer(className, iconPath) {
  297. const container = document.createElement('div');
  298. Object.assign(container.style, {
  299. display: 'flex',
  300. flexDirection: 'column',
  301. alignItems: 'center',
  302. justifyContent: 'center',
  303. visibility: 'hidden',
  304. width: '33%',
  305. height: '100%',
  306. padding: '0 1rem'
  307. });
  308.  
  309. const numberContainer = document.createElement('div');
  310. Object.assign(numberContainer.style, {
  311. display: 'flex',
  312. flexDirection: 'column',
  313. alignItems: 'center',
  314. justifyContent: 'center'
  315. });
  316.  
  317. const differenceElement = document.createElement('div');
  318. differenceElement.classList.add(`${className}-difference`);
  319. Object.assign(differenceElement.style, {
  320. fontSize: '2.5rem',
  321. height: '2.5rem',
  322. marginBottom: '1rem'
  323. });
  324.  
  325. const digitContainer = createNumberContainer();
  326. digitContainer.classList.add(`${className}-number`);
  327. Object.assign(digitContainer.style, {
  328. fontSize: '4rem',
  329. fontWeight: 'bold',
  330. lineHeight: '1',
  331. height: '4rem',
  332. fontFamily: 'inherit',
  333. letterSpacing: '0.025em'
  334. });
  335.  
  336. numberContainer.appendChild(differenceElement);
  337. numberContainer.appendChild(digitContainer);
  338.  
  339. const labelContainer = document.createElement('div');
  340. Object.assign(labelContainer.style, {
  341. display: 'flex',
  342. alignItems: 'center',
  343. marginTop: '0.5rem'
  344. });
  345.  
  346. const icon = createSVGIcon(iconPath);
  347. Object.assign(icon.style, {
  348. width: '2rem',
  349. height: '2rem',
  350. marginRight: '0.75rem'
  351. });
  352.  
  353. const labelElement = document.createElement('div');
  354. labelElement.classList.add(`${className}-label`);
  355. labelElement.style.fontSize = '2rem';
  356.  
  357. labelContainer.appendChild(icon);
  358. labelContainer.appendChild(labelElement);
  359.  
  360. container.appendChild(numberContainer);
  361. container.appendChild(labelContainer);
  362.  
  363. return container;
  364. }
  365.  
  366. function createOverlay(bannerElement) {
  367. clearExistingOverlay();
  368.  
  369. if (!bannerElement) return null;
  370.  
  371. const overlay = document.createElement('div');
  372. overlay.classList.add('channel-banner-overlay');
  373. Object.assign(overlay.style, {
  374. position: 'absolute',
  375. top: '0',
  376. left: '0',
  377. width: '100%',
  378. height: '100%',
  379. backgroundColor: `rgba(0, 0, 0, ${overlayOpacity})`,
  380. borderRadius: '15px',
  381. zIndex: '1',
  382. display: 'flex',
  383. justifyContent: 'space-around',
  384. alignItems: 'center',
  385. color: 'white',
  386. fontFamily: 'Rubik, sans-serif'
  387. });
  388.  
  389. const settingsButton = createSettingsButton();
  390. const settingsMenu = createSettingsMenu();
  391. overlay.appendChild(settingsButton);
  392. overlay.appendChild(settingsMenu);
  393.  
  394. settingsButton.addEventListener('click', (e) => {
  395. e.stopPropagation();
  396. settingsMenu.classList.toggle('show');
  397. });
  398.  
  399. document.addEventListener('click', (e) => {
  400. if (!settingsMenu.contains(e.target) && !settingsButton.contains(e.target)) {
  401. settingsMenu.classList.remove('show');
  402. }
  403. });
  404.  
  405. const spinner = createSpinner();
  406. overlay.appendChild(spinner);
  407.  
  408. const subscribersElement = createStatContainer('subscribers', "M144 160c-44.2 0-80-35.8-80-80S99.8 0 144 0s80 35.8 80 80s-35.8 80-80 80zm368 0c-44.2 0-80-35.8-80-80s35.8-80 80-80s80 35.8 80 80s-35.8 80-80 80zM0 298.7C0 239.8 47.8 192 106.7 192h42.7c15.9 0 31 3.5 44.6 9.7c-1.3 7.2-1.9 14.7-1.9 22.3c0 38.2 16.8 72.5 43.3 96c-.2 0-.4 0-.7 0H21.3C9.6 320 0 310.4 0 298.7zM405.3 320c-.2 0-.4 0-.7 0c26.6-23.5 43.3-57.8 43.3-96c0-7.6-.7-15-1.9-22.3c13.6-6.3 28.7-9.7 44.6-9.7h42.7C592.2 192 640 239.8 640 298.7c0 11.8-9.6 21.3-21.3 21.3H405.3zM416 224c0 53-43 96-96 96s-96-43-96-96s43-96 96-96s96 43 96 96zM128 485.3C128 411.7 187.7 352 261.3 352H378.7C452.3 352 512 411.7 512 485.3c0 14.7-11.9 26.7-26.7 26.7H154.7c-14.7 0-26.7-11.9-26.7-26.7z");
  409. const viewsElement = createStatContainer('views', "M288 32c-80.8 0-145.5 36.8-192.6 80.6C48.6 156 17.3 208 2.5 243.7c-3.3 7.9-3.3 16.7 0 24.6C17.3 304 48.6 356 95.4 399.4C142.5 443.2 207.2 480 288 480s145.5-36.8 192.6-80.6c46.8-43.5 78.1-95.4 93-131.1c3.3-7.9 3.3-16.7 0-24.6c-14.9-35.7-46.2-87.7-93-131.1C433.5 68.8 368.8 32 288 32zM144 256a144 144 0 1 1 288 0 144 144 0 1 1 -288 0zm144-64c0 35.3-28.7 64-64 64c-7.1 0-13.9-1.2-20.3-3.3c-5.5-1.8-11.9 1.6-11.7 7.4c.3 6.9 1.3 13.8 3.2 20.7c13.7 51.2 66.4 81.6 117.6 67.9s81.6-66.4 67.9-117.6c-11.1-41.5-47.8-69.4-88.6-71.1c-5.8-.2-9.2 6.1-7.4 11.7c2.1 6.4 3.3 13.2 3.3 20.3z");
  410. const videosElement = createStatContainer('videos', "M0 128C0 92.7 28.7 64 64 64H320c35.3 0 64 28.7 64 64V384c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V128zM559.1 99.8c10.4 5.6 16.9 16.4 16.9 28.2V384c0 11.8-6.5 22.6-16.9 28.2s-23 5-32.9-1.6l-96-64L416 337.1V320 192 174.9l14.2-9.5 96-64c9.8-6.5 22.4-7.2 32.9-1.6z");
  411.  
  412. overlay.appendChild(subscribersElement);
  413. overlay.appendChild(viewsElement);
  414. overlay.appendChild(videosElement);
  415. bannerElement.appendChild(overlay);
  416. updateDisplayState();
  417. return overlay;
  418. }
  419.  
  420. function fetchWithGM(url, headers = {}) {
  421. return new Promise((resolve, reject) => {
  422. GM_xmlhttpRequest({
  423. method: "GET",
  424. url: url,
  425. headers: headers,
  426. onload: function(response) {
  427. if (response.status === 200) {
  428. resolve(JSON.parse(response.responseText));
  429. } else {
  430. reject(new Error(`Failed to fetch: ${response.status}`));
  431. }
  432. },
  433. onerror: function(error) {
  434. reject(error);
  435. },
  436. });
  437. });
  438. }
  439.  
  440. async function fetchChannelId(channelName) {
  441. try {
  442. const response = await fetchWithGM(`${API_BASE_URL}${channelName}`);
  443. if (!response || !response.channel_id) {
  444. throw new Error('Invalid channel ID response');
  445. }
  446. return response.channel_id;
  447. } catch (error) {
  448. console.error('Error fetching channel ID:', error);
  449. const metaTag = document.querySelector('meta[itemprop="channelId"]');
  450. if (metaTag && metaTag.content) {
  451. return metaTag.content;
  452. }
  453. const urlMatch = window.location.href.match(/channel\/(UC[\w-]+)/);
  454. if (urlMatch && urlMatch[1]) {
  455. return urlMatch[1];
  456. }
  457. throw new Error('Could not determine channel ID');
  458. }
  459. }
  460. async function fetchChannelStats(channelId) {
  461. try {
  462. let retries = 3;
  463. let lastError;
  464. while (retries > 0) {
  465. try {
  466. const stats = await fetchWithGM(
  467. `${STATS_API_URL}${channelId}`,
  468. {
  469. origin: "https://livecounts.io",
  470. referer: "https://livecounts.io/",
  471. }
  472. );
  473. if (!stats || typeof stats.followerCount === 'undefined') {
  474. throw new Error('Invalid stats response');
  475. }
  476. lastSuccessfulStats.set(channelId, stats);
  477. return stats;
  478. } catch (e) {
  479. lastError = e;
  480. retries--;
  481. if (retries > 0) {
  482. await new Promise(resolve => setTimeout(resolve, 1000));
  483. }
  484. }
  485. }
  486. if (lastSuccessfulStats.has(channelId)) {
  487. return lastSuccessfulStats.get(channelId);
  488. }
  489. const fallbackStats = {
  490. followerCount: 0,
  491. bottomOdos: [0, 0],
  492. error: true
  493. };
  494. const subCountElem = document.querySelector('#subscriber-count');
  495. if (subCountElem) {
  496. const subText = subCountElem.textContent;
  497. const subMatch = subText.match(/[\d,]+/);
  498. if (subMatch) {
  499. fallbackStats.followerCount = parseInt(subMatch[0].replace(/,/g, ''));
  500. }
  501. }
  502. return fallbackStats;
  503. } catch (error) {
  504. console.error('Error fetching channel stats:', error);
  505. throw error;
  506. }
  507. }
  508.  
  509. function clearExistingOverlay() {
  510. const existingOverlay = document.querySelector('.channel-banner-overlay');
  511. if (existingOverlay) {
  512. existingOverlay.remove();
  513. }
  514. if (intervalId) {
  515. clearInterval(intervalId);
  516. intervalId = null;
  517. }
  518. lastSuccessfulStats.clear();
  519. previousStats.clear();
  520. isUpdating = false;
  521. overlay = null;
  522. }
  523.  
  524. function createDigitElement() {
  525. const digit = document.createElement('span');
  526. Object.assign(digit.style, {
  527. display: 'inline-block',
  528. width: '0.6em',
  529. textAlign: 'center',
  530. marginRight: '0.025em',
  531. marginLeft: '0.025em'
  532. });
  533. return digit;
  534. }
  535.  
  536. function createCommaElement() {
  537. const comma = document.createElement('span');
  538. comma.textContent = ',';
  539. Object.assign(comma.style, {
  540. display: 'inline-block',
  541. width: '0.3em',
  542. textAlign: 'center'
  543. });
  544. return comma;
  545. }
  546.  
  547. function createNumberContainer() {
  548. const container = document.createElement('div');
  549. Object.assign(container.style, {
  550. display: 'flex',
  551. justifyContent: 'center',
  552. alignItems: 'center',
  553. letterSpacing: '0.025em'
  554. });
  555. return container;
  556. }
  557.  
  558. function updateDigits(container, newValue) {
  559. const newValueStr = newValue.toString();
  560. const digits = [];
  561. for (let i = newValueStr.length - 1; i >= 0; i -= 3) {
  562. const start = Math.max(0, i - 2);
  563. digits.unshift(newValueStr.slice(start, i + 1));
  564. }
  565. while (container.firstChild) {
  566. container.removeChild(container.firstChild);
  567. }
  568. let digitIndex = 0;
  569. for (let i = 0; i < digits.length; i++) {
  570. const group = digits[i];
  571. for (let j = 0; j < group.length; j++) {
  572. const digitElement = createDigitElement();
  573. digitElement.textContent = group[j];
  574. container.appendChild(digitElement);
  575. digitIndex++;
  576. }
  577. if (i < digits.length - 1) {
  578. container.appendChild(createCommaElement());
  579. }
  580. }
  581. let elementIndex = 0;
  582. for (let i = 0; i < digits.length; i++) {
  583. const group = digits[i];
  584. for (let j = 0; j < group.length; j++) {
  585. const digitElement = container.children[elementIndex];
  586. const newDigit = parseInt(group[j]);
  587. const currentDigit = parseInt(digitElement.textContent || '0');
  588. if (currentDigit !== newDigit) {
  589. animateDigit(digitElement, currentDigit, newDigit);
  590. }
  591. elementIndex++;
  592. }
  593. if (i < digits.length - 1) {
  594. elementIndex++;
  595. }
  596. }
  597. }
  598.  
  599. function animateDigit(element, start, end) {
  600. const duration = 1000;
  601. const startTime = performance.now();
  602.  
  603. function update(currentTime) {
  604. const elapsed = currentTime - startTime;
  605. const progress = Math.min(elapsed / duration, 1);
  606. const easeOutQuart = 1 - Math.pow(1 - progress, 4);
  607. const current = Math.round(start + (end - start) * easeOutQuart);
  608. element.textContent = current;
  609.  
  610. if (progress < 1) {
  611. requestAnimationFrame(update);
  612. }
  613. }
  614.  
  615. requestAnimationFrame(update);
  616. }
  617.  
  618. function showContent(overlay) {
  619. const spinnerContainer = overlay.querySelector('.spinner-container');
  620. if (spinnerContainer) {
  621. spinnerContainer.remove();
  622. }
  623.  
  624. const containers = overlay.querySelectorAll('div[style*="visibility: hidden"]');
  625. containers.forEach(container => {
  626. container.style.visibility = 'visible';
  627. });
  628.  
  629. const icons = overlay.querySelectorAll('svg[style*="display: none"]');
  630. icons.forEach(icon => {
  631. icon.style.display = 'block';
  632. });
  633. }
  634.  
  635. function updateDifferenceElement(element, currentValue, previousValue) {
  636. if (!previousValue) return;
  637. const difference = currentValue - previousValue;
  638. if (difference === 0) {
  639. element.textContent = '';
  640. return;
  641. }
  642. const sign = difference > 0 ? '+' : '';
  643. element.textContent = `${sign}${difference.toLocaleString()}`;
  644. element.style.color = difference > 0 ? '#1ed760' : '#f3727f';
  645. setTimeout(() => {
  646. element.textContent = '';
  647. }, 1000);
  648. }
  649.  
  650. function updateDisplayState() {
  651. const overlay = document.querySelector('.channel-banner-overlay');
  652. if (!overlay) return;
  653. const statContainers = overlay.querySelectorAll('div[style*="width"]');
  654. if (!statContainers.length) return;
  655. let visibleCount = 0;
  656. const visibleContainers = [];
  657. statContainers.forEach(container => {
  658. const numberContainer = container.querySelector('[class$="-number"]');
  659. if (!numberContainer) return;
  660. const type = numberContainer.className.replace('-number', '');
  661. const isVisible = localStorage.getItem(`show-${type}`) !== 'false';
  662. if (isVisible) {
  663. container.style.display = 'flex';
  664. visibleCount++;
  665. visibleContainers.push(container);
  666. } else {
  667. container.style.display = 'none';
  668. }
  669. });
  670. visibleContainers.forEach(container => {
  671. container.style.width = '';
  672. container.style.margin = '';
  673. switch (visibleCount) {
  674. case 1:
  675. container.style.width = '100%';
  676. break;
  677. case 2:
  678. container.style.width = '50%';
  679. break;
  680. case 3:
  681. container.style.width = '33.33%';
  682. break;
  683. default:
  684. container.style.display = 'none';
  685. }
  686. });
  687. overlay.style.display = 'flex';
  688. }
  689.  
  690. async function updateOverlayContent(overlay, channelName) {
  691. if (isUpdating || channelName !== currentChannelName) return;
  692. isUpdating = true;
  693. try {
  694. const channelId = await fetchChannelId(channelName);
  695. const stats = await fetchChannelStats(channelId);
  696. if (channelName !== currentChannelName) {
  697. isUpdating = false;
  698. return;
  699. }
  700. if (stats.error) {
  701. const containers = overlay.querySelectorAll('[class$="-number"]');
  702. containers.forEach(container => {
  703. if (container.classList.contains('subscribers-number') && stats.followerCount > 0) {
  704. updateDigits(container, stats.followerCount);
  705. } else {
  706. container.textContent = '---';
  707. }
  708. });
  709. return;
  710. }
  711.  
  712. const updateElement = (className, value, label) => {
  713. const numberContainer = overlay.querySelector(`.${className}-number`);
  714. const differenceElement = overlay.querySelector(`.${className}-difference`);
  715. const labelElement = overlay.querySelector(`.${className}-label`);
  716. if (numberContainer) {
  717. updateDigits(numberContainer, value);
  718. }
  719. if (differenceElement && previousStats.has(channelId)) {
  720. const previousValue = className === 'subscribers' ?
  721. previousStats.get(channelId).followerCount :
  722. previousStats.get(channelId).bottomOdos[className === 'views' ? 0 : 1];
  723. updateDifferenceElement(differenceElement, value, previousValue);
  724. }
  725. if (labelElement) {
  726. labelElement.textContent = label;
  727. }
  728. };
  729. updateElement('subscribers', stats.followerCount, 'Subscribers');
  730. updateElement('views', stats.bottomOdos[0], 'Views');
  731. updateElement('videos', stats.bottomOdos[1], 'Videos');
  732. if (!previousStats.has(channelId)) {
  733. showContent(overlay);
  734. }
  735. previousStats.set(channelId, stats);
  736. } catch (error) {
  737. console.error(`Error updating overlay: ${error.message}`);
  738. const containers = overlay.querySelectorAll('[class$="-number"]');
  739. containers.forEach(container => {
  740. container.textContent = '---';
  741. });
  742. } finally {
  743. isUpdating = false;
  744. }
  745. }
  746.  
  747. function addOverlay(bannerElement) {
  748. const channelName = window.location.pathname.split("/")[1].replace("@", "");
  749.  
  750. if (channelName === currentChannelName && overlay) {
  751. return;
  752. }
  753.  
  754. currentChannelName = channelName;
  755. overlay = createOverlay(bannerElement);
  756.  
  757. if (overlay) {
  758. if (intervalId) {
  759. clearInterval(intervalId);
  760. }
  761.  
  762. intervalId = setInterval(() => {
  763. updateOverlayContent(overlay, channelName);
  764. }, updateInterval);
  765.  
  766. updateOverlayContent(overlay, channelName);
  767. }
  768. }
  769.  
  770. function isChannelPage() {
  771. return window.location.pathname.startsWith("/@") ||
  772. window.location.pathname.startsWith("/channel/") ||
  773. window.location.pathname.startsWith("/c/");
  774. }
  775.  
  776. function observePageChanges() {
  777. const observer = new MutationObserver((mutations) => {
  778. for (const mutation of mutations) {
  779. if (mutation.type === 'childList') {
  780. const bannerElement = document.getElementById('page-header-banner-sizer');
  781. if (bannerElement && isChannelPage()) {
  782. addOverlay(bannerElement);
  783. break;
  784. }
  785. }
  786. }
  787. });
  788.  
  789. observer.observe(document.body, {
  790. childList: true,
  791. subtree: true
  792. });
  793. }
  794.  
  795. function addNavigationListener() {
  796. window.addEventListener("yt-navigate-finish", () => {
  797. if (!isChannelPage()) {
  798. clearExistingOverlay();
  799. currentChannelName = null;
  800. } else {
  801. const bannerElement = document.getElementById('page-header-banner-sizer');
  802. if (bannerElement) {
  803. addOverlay(bannerElement);
  804. }
  805. }
  806. });
  807. }
  808.  
  809. init();
  810. console.log('YouTube Enhancer (Real-Time Subscriber Count) is running');
  811. })();