1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
| // ==UserScript== // @name 视频速度终极控制 (WebSocket/XHR/时间拉伸全支持) // @namespace http://tampermonkey.net/ // @version 8.0 // @description 终极方案:WebSocket拦截、XHR劫持、时间拉伸,确保100%进度 // @author You // @match *://*/* // @grant none // ==/UserScript==
(function() { 'use strict';
// ==================== 配置 ==================== const SPEED_SLOW = 0.5; const SPEED_NORMAL = 1.0; const FAST_SPEEDS = [2.0, 4.0, 8.0, 16.0]; let currentFastIndex = 0; let currentSpeed = SPEED_NORMAL;
// 状态管理 let lastReportedProgress = 0; let progressInterval = null; let videoStartTime = 0; let videoDuration = 0; let targetVideo = null;
// 时间拉伸相关 let timeOffset = 0; let originalDateNow = Date.now; let originalPerformanceNow = performance.now; let timeStretchActive = false;
// ==================== UI提示 ==================== function createToast() { const toast = document.createElement('div'); toast.id = 'speed-master-toast'; Object.assign(toast.style, { position: 'fixed', top: '20px', right: '20px', backgroundColor: 'rgba(0, 0, 0, 0.95)', color: '#00ff00', padding: '15px 25px', borderRadius: '8px', zIndex: '9999999', fontSize: '14px', fontFamily: 'monospace', opacity: '0', pointerEvents: 'none', boxShadow: '0 0 20px rgba(0,255,0,0.3)', border: '1px solid #00ff00', maxWidth: '400px', wordBreak: 'break-word' }); document.body.appendChild(toast); return toast; }
function showMessage(text, duration = 3000) { let toast = document.getElementById('speed-master-toast'); if (!toast) toast = createToast(); toast.textContent = `[${new Date().toLocaleTimeString()}] ${text}`; toast.style.opacity = '1'; if (window.toastTimeout) clearTimeout(window.toastTimeout); window.toastTimeout = setTimeout(() => toast.style.opacity = '0', duration); console.log(`[SpeedMaster] ${text}`); }
// ==================== 工具函数 ==================== function getAllVideos() { return Array.from(document.querySelectorAll('video')); }
function hijackVideoSpeed(video, speed) { if (!video) return; video.playbackRate = speed; try { if (!video._hijacked) { video._hijacked = true; Object.defineProperty(video, 'playbackRate', { get: function() { return this._customRate || speed; }, set: function(v) { this._customRate = v; }, configurable: true }); video._customRate = speed; } else { video._customRate = speed; } } catch (e) {} }
// ==================== WebSocket拦截 ==================== function setupWebSocketInterceptor() { const OriginalWebSocket = window.WebSocket; const socketMessages = new Set();
window.WebSocket = function(url, protocols) { const socket = new OriginalWebSocket(url, protocols);
// 只拦截可能包含进度信息的连接 if (url.includes('progress') || url.includes('learn') || url.includes('course')) { showMessage(`📡 拦截WebSocket: ${url}`);
// 拦截发送消息 const originalSend = socket.send; socket.send = function(data) { // 检查是否包含进度信息 if (typeof data === 'string') { try { // 尝试解析JSON if (data.includes('progress') || data.includes('percent')) { const parsed = JSON.parse(data); // 修改进度值 if (parsed.progress) parsed.progress = Math.min(parsed.progress, lastReportedProgress); if (parsed.percent) parsed.percent = Math.min(parsed.percent, lastReportedProgress); if (parsed.currentTime) { // 根据速度调整上报的时间 parsed.currentTime = parsed.currentTime * (currentSpeed / Math.max(1, currentSpeed)); } data = JSON.stringify(parsed); showMessage(`📤 WebSocket消息已修改: ${data.substring(0, 100)}`); } } catch (e) { // 不是JSON,忽略 } } return originalSend.call(this, data); };
// 拦截接收消息 socket.addEventListener('message', function(event) { if (typeof event.data === 'string' && event.data.includes('progress')) { try { const data = JSON.parse(event.data); // 可以在这里修改接收到的数据 // 注意:不能直接修改event.data,需要更高级的劫持 showMessage(`📥 WebSocket接收: ${event.data.substring(0, 100)}`); } catch (e) {} } }, true);
socketMessages.add(socket); }
return socket; };
// 保持原型链 window.WebSocket.prototype = OriginalWebSocket.prototype; window.WebSocket.CLOSED = OriginalWebSocket.CLOSED; window.WebSocket.CLOSING = OriginalWebSocket.CLOSING; window.WebSocket.CONNECTING = OriginalWebSocket.CONNECTING; window.WebSocket.OPEN = OriginalWebSocket.OPEN;
showMessage('📡 WebSocket拦截器已激活'); }
// ==================== XHR劫持 ==================== function setupXHRInterceptor() { const OriginalXHR = window.XMLHttpRequest;
window.XMLHttpRequest = function() { const xhr = new OriginalXHR(); const originalOpen = xhr.open; const originalSend = xhr.send; const originalSetRequestHeader = xhr.setRequestHeader;
let url = ''; let method = ''; let requestData = ''; let headers = {};
// 拦截open xhr.open = function(m, u, async, user, password) { method = m; url = u; return originalOpen.apply(this, arguments); };
// 拦截setRequestHeader xhr.setRequestHeader = function(header, value) { headers[header] = value; return originalSetRequestHeader.apply(this, arguments); };
// 拦截send xhr.send = function(data) { requestData = data;
// 只拦截可能包含进度信息的请求 if (url.includes('progress') || url.includes('learn') || url.includes('course') || url.includes('record') || url.includes('watch') || url.includes('video')) {
showMessage(`🌐 拦截XHR: ${method} ${url}`);
// 修改请求数据 if (data && typeof data === 'string') { try { if (data.includes('progress') || data.includes('percent') || data.includes('currentTime')) { const parsed = JSON.parse(data); let modified = false;
// 修改进度相关字段 if (parsed.progress) { parsed.progress = Math.min(parsed.progress, lastReportedProgress); modified = true; } if (parsed.percent) { parsed.percent = Math.min(parsed.percent, lastReportedProgress); modified = true; } if (parsed.currentTime && videoDuration) { // 根据速度调整上报的时间 const expectedTime = (lastReportedProgress / 100) * videoDuration; parsed.currentTime = expectedTime; modified = true; }
if (modified) { data = JSON.stringify(parsed); showMessage(`📤 XHR数据已修改: ${data.substring(0, 100)}`); } } } catch (e) {} }
// 拦截响应 xhr.addEventListener('readystatechange', function() { if (xhr.readyState === 4 && xhr.status === 200) { try { const responseText = xhr.responseText; if (responseText && responseText.includes('progress')) { showMessage(`📥 XHR响应: ${responseText.substring(0, 100)}`);
// 这里可以修改responseText,但需要更复杂的劫持 // 可以使用Object.defineProperty劫持responseText } } catch (e) {} } }); }
return originalSend.call(this, data); };
return xhr; };
// 保持静态属性 window.XMLHttpRequest.DONE = OriginalXHR.DONE; window.XMLHttpRequest.HEADERS_RECEIVED = OriginalXHR.HEADERS_RECEIVED; window.XMLHttpRequest.LOADING = OriginalXHR.LOADING; window.XMLHttpRequest.OPENED = OriginalXHR.OPENED; window.XMLHttpRequest.UNSENT = OriginalXHR.UNSENT;
// 保持原型方法 window.XMLHttpRequest.prototype = OriginalXHR.prototype;
showMessage('🌐 XHR拦截器已激活'); }
// ==================== 时间拉伸 ==================== function setupTimeStretching() { // 保存原始函数 const originalDateNow = Date.now; const originalPerformanceNow = performance.now; const originalGetTime = Date.prototype.getTime;
// 记录基准时间 const baseRealTime = Date.now(); let stretchedTime = baseRealTime; let stretchFactor = 1.0;
// 更新时间拉伸因子 function updateStretchFactor(speed) { if (speed > 1.2) { // 快速播放时,时间应该走得更慢(欺骗平台) // 比如16倍速,时间应该走得慢16倍,让平台以为看了16倍的时间 stretchFactor = 1 / speed; } else { stretchFactor = 1.0; }
// 调整基准时间,保持连续性 const currentRealTime = originalDateNow(); const expectedStretchedTime = stretchedTime + (currentRealTime - baseRealTime) * stretchFactor; stretchedTime = expectedStretchedTime;
showMessage(`⏱️ 时间拉伸因子: ${stretchFactor.toFixed(3)} (速度: ${speed}x)`); }
// 劫持Date.now Date.now = function() { if (!timeStretchActive || stretchFactor === 1.0) { return originalDateNow(); }
const realNow = originalDateNow(); // 返回拉伸后的时间 return stretchedTime + (realNow - baseRealTime) * stretchFactor; };
// 劫持new Date().getTime() Date.prototype.getTime = function() { if (!timeStretchActive || stretchFactor === 1.0) { return originalGetTime.call(this); }
// 如果是当前时间的Date对象,进行拉伸 if (this === new Date(originalDateNow()).getTime()) { return Date.now(); }
return originalGetTime.call(this); };
// 劫持performance.now performance.now = function() { if (!timeStretchActive || stretchFactor === 1.0) { return originalPerformanceNow(); }
const realNow = originalPerformanceNow(); // performance.now是从navigationStart开始的相对时间 // 需要根据拉伸因子调整 return realNow * stretchFactor; };
// 提供给外部调用的接口 window.__speedMaster = window.__speedMaster || {}; window.__speedMaster.updateStretchFactor = updateStretchFactor; window.__speedMaster.activateTimeStretch = function(active) { timeStretchActive = active; if (active) { baseRealTime = originalDateNow(); stretchedTime = baseRealTime; } showMessage(`⏱️ 时间拉伸: ${active ? '激活' : '关闭'}`); };
showMessage('⏱️ 时间拉伸拦截器已就绪'); }
// ==================== 进度管理核心 ==================== function startProgressManagement(videos) { if (videos.length === 0) return;
targetVideo = videos[0]; videoDuration = targetVideo.duration; videoStartTime = Date.now(); lastReportedProgress = 0;
// 激活时间拉伸 if (window.__speedMaster && window.__speedMaster.activateTimeStretch) { window.__speedMaster.activateTimeStretch(true); window.__speedMaster.updateStretchFactor(currentSpeed); }
if (progressInterval) clearInterval(progressInterval);
progressInterval = setInterval(() => { try { if (!targetVideo || targetVideo.paused) return;
const currentTime = targetVideo.currentTime; if (!videoDuration || videoDuration === 0) return;
// 计算真实进度 const realProgress = (currentTime / videoDuration) * 100;
// 计算基于时间的"虚假"进度(模拟正常观看) const elapsedRealSeconds = (Date.now() - videoStartTime) / 1000; const fakeProgress = (elapsedRealSeconds / videoDuration) * 100;
// 上报进度 = 真实进度(但不能超过基于时间的进度太多) // 这样既保证进度真实,又不会被检测出异常 let reportProgress; if (currentSpeed > 2.0) { // 快速模式下,上报进度不能超过真实进度太多 reportProgress = Math.min(realProgress, fakeProgress + 5); } else { reportProgress = realProgress; }
// 确保进度递增 reportProgress = Math.max(reportProgress, lastReportedProgress); // 确保不超过100 reportProgress = Math.min(100, reportProgress);
// 进度有变化时触发事件 if (Math.abs(reportProgress - lastReportedProgress) >= 0.5 || reportProgress >= 99) { triggerAllEvents(targetVideo); lastReportedProgress = reportProgress;
// 每10%显示一次提示 if (Math.floor(reportProgress) % 10 === 0 && reportProgress > 0) { showMessage(`📊 进度: ${reportProgress.toFixed(1)}% (真实: ${realProgress.toFixed(1)}%)`); } }
// 处理完成 if (realProgress >= 99.5) { forceComplete(targetVideo); }
// 更新时间拉伸因子(动态调整) if (window.__speedMaster && window.__speedMaster.updateStretchFactor) { window.__speedMaster.updateStretchFactor(currentSpeed); }
} catch (e) { console.error('进度管理错误:', e); } }, 50); // 50ms检查一次,更精细的控制 }
function triggerAllEvents(video) { if (!video) return;
// 基础事件 const events = [ 'timeupdate', 'progress', 'durationchange', 'loadedmetadata', 'seeking', 'seeked', 'waiting', 'playing', 'canplay', 'canplaythrough' ];
events.forEach(name => { try { video.dispatchEvent(new Event(name)); } catch (e) {} });
// 尝试触发React/Vue等框架的事件 if (video.__reactProps$) { try { const props = Object.values(video.__reactProps$)[0]; if (props && props.onTimeUpdate) props.onTimeUpdate({ type: 'timeupdate', target: video }); if (props && props.onProgress) props.onProgress({ type: 'progress', target: video }); } catch (e) {} }
// 触发jQuery事件 if (window.jQuery) { try { window.jQuery(video).trigger('timeupdate'); window.jQuery(video).trigger('progress'); } catch (e) {} } }
function forceComplete(video) { if (video._completed) return; video._completed = true;
showMessage('🎉 视频完成,强制上报100%进度');
// 连续触发多次事件 for (let i = 0; i < 15; i++) { setTimeout(() => { if (!video) return; ['timeupdate', 'progress', 'ended', 'complete'].forEach(name => { try { video.dispatchEvent(new Event(name)); } catch (e) {} });
// 最后几次尝试设置currentTime到结尾 if (i > 10 && video.duration) { try { video.currentTime = video.duration; } catch (e) {} } }, i * 150); }
// 关闭时间拉伸 if (window.__speedMaster && window.__speedMaster.activateTimeStretch) { setTimeout(() => { window.__speedMaster.activateTimeStretch(false); }, 2000); } }
// ==================== 速度控制 ==================== function setSpeed(speed) { currentSpeed = speed; const videos = getAllVideos();
videos.forEach(video => { hijackVideoSpeed(video, speed); });
if (speed > 1.2) { startProgressManagement(videos); showMessage(`🚀 速度: ${speed}x (全拦截模式激活)`); } else { if (progressInterval) { clearInterval(progressInterval); progressInterval = null; } if (window.__speedMaster && window.__speedMaster.activateTimeStretch) { window.__speedMaster.activateTimeStretch(false); } showMessage(`✅ 速度: ${speed}x`); } }
function handleFastSpeed() { const speed = FAST_SPEEDS[currentFastIndex]; currentFastIndex = (currentFastIndex + 1) % FAST_SPEEDS.length; setSpeed(speed); }
function handleSlowSpeed() { setSpeed(SPEED_SLOW); }
function handleNormalSpeed() { setSpeed(SPEED_NORMAL); currentFastIndex = 0; }
// ==================== 键盘监听 ==================== function handleKeyDown(e) { const active = document.activeElement; if (active && ['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName)) return;
const key = e.key;
if (key === '.' || key === '>') { e.preventDefault(); handleFastSpeed(); } else if (key === ',' || key === '<') { e.preventDefault(); handleSlowSpeed(); } else if (key === '/' || key === '?') { e.preventDefault(); handleNormalSpeed(); } }
// ==================== 初始化 ==================== function init() { // 创建UI createToast();
// 设置拦截器(按顺序) setupXHRInterceptor(); // 先拦截XHR setupWebSocketInterceptor(); // 再拦截WebSocket setupTimeStretching(); // 最后设置时间拉伸
// 键盘监听 window.addEventListener('keydown', handleKeyDown, true);
// 页面卸载时清理 window.addEventListener('beforeunload', function() { if (progressInterval) clearInterval(progressInterval); // 恢复原始函数(可选) if (timeStretchActive) { Date.now = originalDateNow; performance.now = originalPerformanceNow; Date.prototype.getTime = originalGetTime; } });
// 显示启动信息 showMessage(` 🎬 视频速度终极控制 v8.0 ├─ 快捷键: ,=0.5x .=2/4/8/16x /=1x ├─ WebSocket拦截: ✅ ├─ XHR劫持: ✅ ├─ 时间拉伸: ✅ └─ 进度管理: 智能适配 `, 6000);
console.log('SpeedMaster initialized with all interceptors'); }
// 启动 init();
})();
|