Greasy Fork

Greasy Fork is available in English.

虎牙Plus

虎牙自动领取任务经验、开宝箱,复制直播流链接,简化页面,去广告, 夜间模式,自动进入剧场模式, 我的订阅页面视频预览

当前为 2021-05-19 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

'use strict';
// ==UserScript==
// @name         虎牙Plus
// @namespace    http://tampermonkey.net/
// @icon         https://www.huya.com/favicon.ico
// @version      1.0.24
// @description  虎牙自动领取任务经验、开宝箱,复制直播流链接,简化页面,去广告, 夜间模式,自动进入剧场模式, 我的订阅页面视频预览
// @author       Francis
// @match        *://*.huya.com/*
// @grant        GM_setClipboard
// @grant        GM_xmlhttpRequest
// @license      MIT
// @require      https://cdn.jsdelivr.net/hls.js/latest/hls.min.js
// ==/UserScript==

let $;

function addUi(){
    let style = document.createElement('style');
    style.appendChild(document.createTextNode(`
span.copy-stream-link:after {
    display: none;
    position: absolute;
    content: "";
    right: -20px;
    top: 6px;
    width: 18px;
    height: 18px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ilNCUBZJ6SOwXpo6q2WunuayPCVrx5/pn6gaRGMWfth4bIbQGu4K3bJu+o1Gb5jN7WgaP89bruI++rn/H+UkS86r+PRZZdqRh6NHBvePbHetKz0TWnGJK1B4zYACSIPh/zw2Rh60LEjLtrXG/bZSdBjclhsQ6AbeLkYs1akmCbnvA9nkVN0BIq9OWEfgZa+p4sxo5gFzMPtxtcjeTQRP95UdhZTL1TTaJFcKTOVOLNcFtNn1aZlt3/rEsxaWQyt1LqUlkCNnEOMizAysnfUrssotfKmyrmSVdEHkePs7tzgUeobWalPafteqOJ26q8AAwB8rQG0tt5ioQAAAABJRU5ErkJggg==);
    background-size: 18px 18px;
}

span.copy-stream-link.copy-success:after {
    display: block;
}

.huya-plus-btn{
    display: block;
    font-size: 11px;
    padding:0 10px;
    color:#b08444;
    background:#FFD29E;
    border-radius:15px;
    margin-left: 30px;
    user-select: none;
    transition:all .5s;
}

.huya-plus-btn:hover{
    color:#FFF;
    background:#ffa801;
}

#huya-ab,
.player-banner-gift,
#player-marquee-wrap,
.room-gg-chat,
.room-mod-ggTop,
#hy-nav-download,
.hy-nav-kaibo,
.hy-nav-item:nth-child(2),
#J_roomGameBuy,
.jump-to-phone,
#week-star-btn,
.g-gift,
#J_bigStreamerStage,
#J_hySide,
.room-business-game,
#J_hostChannel,
#J_BusinessGameRoot,
#sidebarBanner,
.mod-news-section,
.mod-index-list>.live-box,
#J_adCategory
{
    display:none !important;
}

body,
.duya-header-wrap,
#main_col,
.room-hd-l,
.player-gift-wrap,
.chat-room__ft,
.jspPane,
#J_profileNotice>div,
.week-rank__btn,
.J_msg,
.chat-room__list,
.msg-nobleEnter,
.msg-nobleEnter>div,
.msg-nobleSpeak,
.player-face-arrow,
#player-gift-tip,
.jspVerticalBar,
.illegal-report,
.subscribe-hd.sub-on,
.huya-plus-btn,
#player-gift-tip bottom,
#player-gift-tip btn,
.fansBadge-box,
.nav-expand-list,
.tt-user-card,
.share-entrance,
.search-suggest,
.u-links,
.entrance-expand,
.gameBuy-bd,
.guide-to-app,
.chat-room__wrap,
#J_profileNotice,
.msg-onTVLottery,
.room-core,
.msg-noble,
#J_box_msgOfKing,
.msg-of-king,
.subscribe-hd.sub-on,
.huya-plus-btn,
.nav-expand-game dd a,
.subscribe-hd.sub-on,
.huya-plus-btn,
.match-item,
.hy-nav-link,
.hy-nav-title,
.nav-user-title,
#J_roomTitle,
.msg,
.subscribe-hd.sub-on,
.huya-plus-btn,
.cont-item,
.week-rank__btn,
.week-rank-name,
.msg-nobleEnter,
.peo-name,
.search-item,
.history-bd .new-clickstat,
.from,
.to,
.nav-expand-game dd a,
.hy-header-match-preview-name,
#pub_msg_input,
#search-bar-input:focus,
.msg-noble,
#J_box_msgOfKing,
#J_hyUserCard .u-assets,
.room-sidebar,
.duya-header-wrap,
.week-rank__unit,
.chat-room__input,
.chatNotice,
#J_profileNotice,
.plaer-face-icon-bg,
.chat-room__ft__chat,
#tipsOrchat,
.week-rank__btn.active,
#pub_msg_input,
#search-bar-input,
.week-rank__bd li,
.subscribe-live-item,
.subscribe-live-item .txt .msg-row .nick,
.list-hd .title,
.match_body_wrap
{
    transition: background .3s, background-color .3s, color .3s, border-color .3s;
}

.live-box .box-hd .more-list li,
.live-box .box-hd .more-list li:hover,
.night-mode .mod-list .box-hd .filter dd .tag-layer,
.nav-expand-game dd a{
    border-color: #464646 !important;
}

body.night-mode,
.night-mode .duya-header-wrap,
.night-mode #main_col,
.night-mode .room-hd-l,
.night-mode .player-gift-wrap,
.night-mode .chat-room__ft,
.night-mode .jspPane,
.night-mode #J_profileNotice>div,
.night-mode .week-rank__btn,
.night-mode .J_msg,
.night-mode .chat-room__list,
.night-mode .msg-nobleEnter,
.night-mode .msg-nobleEnter>div,
.night-mode .msg-nobleSpeak,
.night-mode .player-face-arrow,
.night-mode #player-gift-tip,
.night-mode .jspVerticalBar,
.night-mode .illegal-report,
.night-mode .subscribe-hd.sub-on,
.night-mode .huya-plus-btn,
.night-mode #player-gift-tip bottom,
.night-mode #player-gift-tip btn,
.night-mode .fansBadge-box,
.night-mode .nav-expand-list,
.night-mode .tt-user-card,
.night-mode .share-entrance,
.night-mode .search-suggest,
.night-mode .u-links,
.night-mode .entrance-expand,
.night-mode .gameBuy-bd,
.night-mode .guide-to-app,
.night-mode .chat-room__wrap,
.night-mode #J_profileNotice,
.night-mode .msg-onTVLottery,
.night-mode .room-core,
.night-mode .msg-noble,
.night-mode .match_body_wrap,
.night-mode #J_roomHdR,
.night-mode .msg-watchTogetherVip,
.night-mode .room-weeklyRankList-content>div,
.night-mode .room-weeklyRankList-nav-item,
.night-mode .huya-footer,
.night-mode .program-preview-box,
.night-mode .program-preview-box .preview-bd,
.night-mode .star-box .star-content
{
    background-color: rgb(47, 48, 53) !important;
}

.night-mode #J_box_msgOfKing,
.night-mode .msg-of-king
{
    background: rgb(47, 48, 53) !important;
}

.night-mode .subscribe-hd.sub-on,
.night-mode .huya-plus-btn,
.night-mode .nav-expand-game dd a,
.night-mode .subscribe-live-item,
.night-mode .room-weeklyRankList-nav-item.room-weeklyRankList-nav-item-active,
.night-mode .game-live-item,
.night-mode .game-live-item .txt .num,
.night-mode .j_anchor_label,
.night-mode .g-gameCard-item,
.night-mode .mod-list .box-hd .filter dd .tag-layer
{
    background-color: #464646 !important;
}

.night-mode .subscribe-hd.sub-on,
.night-mode .huya-plus-btn,
.night-mode .match-item,
.night-mode .mod-list .box-hd .title a,
.night-mode .game-live-item a.title,
.night-mode .j_index-game-title,
.night-mode .live-box .box-hd .more-list li a,
.night-mode .live-box_funny .box-hd .title span,
.night-mode .g-gameCard-fullName
{
    color: #8e8a8a !important;
}

.night-mode .hy-nav-link,
.night-mode .hy-nav-title,
.night-mode .nav-user-title,
.night-mode #J_roomTitle,
.night-mode .msg,
.night-mode .subscribe-hd.sub-on,
.night-mode .huya-plus-btn,
.night-mode .cont-item,
.night-mode .week-rank__btn,
.night-mode .week-rank-name,
.night-mode .msg-nobleEnter,
.night-mode .peo-name,
.night-mode .search-item,
.night-mode .history-bd .new-clickstat,
.night-mode .from,
.night-mode .to,
.night-mode .nav-expand-game dd a,
.night-mode .hy-header-match-preview-name,
.night-mode #pub_msg_input,
.night-mode #search-bar-input:focus,
.night-mode .msg-noble,
.night-mode #J_box_msgOfKing,
.night-mode #J_hyUserCard .u-assets,
.night-mode .follow-ctrl,
.night-mode .subscribe-live-item .txt .msg-row .nick,
.night-mode .list-hd .title,
.night-mode .nick,
.night-mode .fansBadge-hig,
.night-mode .room-weeklyRankList-nav-item,
.night-mode .room-weeklyRankList-content>div,
.night-mode .g-gameCard-fullName:hover
{
    color: #E7E7E7 !important;
}

.night-mode .room-sidebar,
.night-mode .duya-header-wrap,
.night-mode .week-rank__unit,
.night-mode .chat-room__input,
.night-mode .chatNotice,
.night-mode #J_profileNotice,
.night-mode .plaer-face-icon-bg,
.night-mode .chat-room__ft__chat,
.night-mode #tipsOrchat
{
    border-color: #3e3e3e !important;
}

.night-mode .week-rank__btn.active,
.night-mode #pub_msg_input,
.night-mode #J_weekRankList li:hover,
.night-mode #J_fansRankList li:hover,
.night-mode .seat-item:hover,
.night-mode #search-bar-input,
.night-mode .search-item:hover,
.night-mode .video-link:hover,
.night-mode .history-bd .new-clickstat:hover,
.night-mode .video-item:hover,
.night-mode .match-item:hover,
.night-mode .hy-header-match-preview li:hover,
.night-mode .week-rank__bd li:hover,
.night-mode .follow-ctrl,
.night-mode #J_roomWeeklyRankListRoot ul>li:hover,
.night-mode [class^="seat-item-"]:hover
{
    background-color: #565656 !important;
}

.night-mode .subscribe-live-item:hover{
   box-shadow: 2px 2px 10px #565656 !important;
}

.night-mode-btn-wrapper,.setting-btn-wrapper{
    float: left;
    position: relative;
    margin-left:15px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.night-mode-switch-btn,.setting-btn{
    width: 26px;
    height: 26px;
    border-radius: 13px;
}

.huyaplus-page-full-mode #player-wrap{
    height: 100% !important;
}

.huyaplus-page-full-mode #player-gift-wrap{
    position: relative;
    bottom: 0px !important;
    transition: all .5s;
}

.huyaplus-page-full-mode #player-ctrl-wrap{
    position: relative;
    bottom: 0 !important;
    transition: all .5s !important;
}

#player-ctrl-wrap.show, #player-gift-wrap.show{
    bottom: 100px !important;
}

.night-mode-icon,.setting-icon{
   fill: #8A8A8A;
}

.night-mode .night-mode-icon,.night-mode .setting-icon{
   fill: #AEAEAE;
}

.setting-panel-wrapper{
    visibility: hidden;
    width: 200px;
    height: 0;
    position: absolute;
    top: 100%;
    background: #777777;
    padding: 10px;
    transition: height .3s;
    border-bottom-right-radius:5px;
    border-bottom-left-radius:5px;
}

.setting-btn-wrapper:hover .setting-panel-wrapper{
    visibility: visible;
    height: 200px;
}

.video-previewing .item-mask,
.video-previewing .btn-link__hover_i{
    visibility: hidden;
}
`));

    document.head.appendChild(style);

    let copyStreamLinkNode = document.createElement('div');
    copyStreamLinkNode.style = "cursor: pointer;display:inline-flex;vertical-align:top;";
    const openWithPlayerBtn = isMacOS() ? `<span class="huya-plus-btn open-with-iina" style="position: relative;">使用IINA打开</span>`: `<span class="huya-plus-btn open-with-potplayer" style="position: relative;">使用PotPlayer打开</span>`;
    copyStreamLinkNode.innerHTML = `<span class="huya-plus-btn copy-stream-link" style="position: relative;">复制直播流</span>${openWithPlayerBtn}`;
    let titleRigion = document.querySelector('.host-title');
    if(titleRigion){
        titleRigion.appendChild(copyStreamLinkNode);

        document.querySelector('.copy-stream-link').onclick = async e=>{
            GM_setClipboard(await getStreamUrl());
            showCopySuccessIcon();
        };

        $(".open-with-iina").click(async ()=>{
            openStreamWithIINA(await getStreamUrl());
        });

        $(".open-with-potplayer").click(async ()=>{
            openStreamWithPotPlayer(await getStreamUrl());
        });
    }
}

async function getStreamUrl(){
    let url = window.location.href;
    let streamUrl = sessionStorage.getItem(url)
    if(!streamUrl || streamUrl.length === 0){
        streamUrl = await doGetStreamUrl(url).catch(e=>{});
        if(streamUrl && streamUrl.length > 0){
            sessionStorage.setItem(url, streamUrl);
        } else {
            alert("获取直播流失败");
            throw new Error("获取直播流失败");
        }
    }

    let ibitrate = getCurrentIbitrate();
    return convertStreamIbitrate(streamUrl, ibitrate)
}

function getCurrentIbitrate(){
    return $(".player-videotype-list>li.on").attr('ibitrate')
}

function convertStreamIbitrate(streamUrl, ibitrate){
    let ibit = parseInt(ibitrate);
    if(!isNaN(ibit)){
        streamUrl = streamUrl.replace(/(ratio=)(\d+)/, `$1${ibit}`);
    }
    console.log(streamUrl)
    return streamUrl;
}

async function doGetStreamUrl(url){
    try{
        let mobileHtml = await new Promise((resolve,reject)=>{
            GM_xmlhttpRequest({
                method: 'GET',
                headers: {
                    'user-agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
                },
                url: url,
                responseType: 'text',
                onload: resp=>{
                    resolve(resp.responseText);
                },
                onerror: e => {
                    reject(e);
                }
            })
        });
        let streamUrl = /\<script\>\s*var liveLineUrl = "(.+)";\s*\<\/script\>/.exec(mobileHtml)[1];
        if(!streamUrl.startsWith('//')){
            streamUrl = Base64.decode(streamUrl);
        }
        return `https:${streamUrl}`;
    }catch(e){
        throw e;
    }
}

function isMacOS(){
    var UserAgent = navigator.userAgent.toLowerCase();
    return /mac os/.test(UserAgent);
}

function showCopySuccessIcon(){
    $('span.copy-stream-link').addClass('copy-success');
    setTimeout(()=>{$('span.copy-stream-link').removeClass('copy-success');},1000)
}

function autoReceiveBoxReward(){
    let rewardBtns = $(".player-box-list .player-box-stat3").filter((i,it)=>$(it).css("visibility") === 'visible');
    if(rewardBtns.size() > 0){
        let btn = $(rewardBtns[0]);
        btn.click();
        let waitComplete = ()=>{
            if(btn.css("visibility") === 'hidden'){
                $("#player-box").hide();
                console.log("开启宝箱");
                autoReceiveBoxReward();
            } else {
                setTimeout(waitComplete,1000);
            }
        };
        setTimeout(waitComplete,1000);
    }
}

function autoReceiveTaskXP(){
    let taskBtns = $(".tasks .status .status-get");
    if(taskBtns.size() > 0){
        $.each(taskBtns,(_,btn)=>{
            $(btn).click();
        });
        console.log(`自动领取经验,本次完成${taskBtns.length}个任务`)
    }
}

function cleanPage(){
    $(".room-gg-chat").remove();
    $(".room-footer").remove();
}

function completeChatTask(){
    const taskInfo = $(".tasks .tit").filter((i,it)=>$(it).text() === '在1场直播中发送弹幕');
    const taskDone = taskInfo.siblings(".status").find(".status-ing").size() === 0;
    if(!taskDone){
        chat('66666')
    }
}

function chat(msg){
    $("#pub_msg_input").val(msg).keyup();
    $("#msg_send_bt").click();
}

function openStreamWithPotPlayer(streamUrl){
    openStreamWithPlayer("PotPlayer://", streamUrl);
}

function openStreamWithIINA(streamUrl){
    openStreamWithPlayer("iina://weblink?url=", encodeURIComponent(streamUrl))
}

function openStreamWithPlayer(playerUrlSchema, streamUrl){
    window.open(`${playerUrlSchema}${streamUrl}`, "_self")
}

function jqueryLoaded(){
    $ = unsafeWindow.$
    return $;
}

function pageLoaded(){
    if($(".tasks .status").size() == 0){
        $(".nav-user-title").mouseenter()
    }
    return $(".box-icon-word").size() > 0 && $(".tasks .status").size() > 0
}

async function waitLoad(conditionFunc){
    return new Promise(function(resolve,reject){
        let w = ()=>{
            if(conditionFunc()){
                resolve();
            } else {
                setTimeout(w,1000);
            }
        }
        w();
    });
}

let switchDay = ()=>{
    document.body.classList.remove('night-mode');
    localStorage.setItem("night-mode",false);
}

let switchNight = ()=>{
    document.body.classList.add('night-mode');
    localStorage.setItem("night-mode",true);
}

function autoNightMode(){
    if(localStorage.getItem("night-mode") === 'true'){
        switchNight();
    }
}

function addNightModeSwitcher(){
    $("#J_duyaHeaderRight>div").append(`
<div class="night-mode-btn-wrapper" title="夜间模式">
    <div class="night-mode-switch-btn">
        <svg t="1594304048678" class="night-mode-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="13479" width="26" height="26"><path d="M884.466526 372.574316v-226.357895h-222.585263L512 0 362.172632 146.216421H160.175158V362.172632L0 512l160.175158 149.827368v208.734316H362.172632L512 1024l149.827368-153.438316h222.639158V661.827368l139.587369-149.827368-139.587369-139.425684z m-362.172631 407.44421c-50.553263 3.610947-89.088-5.389474-123.472842-21.288421A271.845053 271.845053 0 0 0 557.271579 512c0-109.568-65.212632-203.722105-158.450526-246.730105a270.551579 270.551579 0 0 1 113.178947-24.899369c149.827368 0 271.629474 121.802105 271.629474 271.629474 0 149.827368-121.802105 268.018526-261.281685 268.018526z" p-id="13480"></path></svg>
    </div>
</div>
`)

    $(".night-mode-switch-btn").click(()=>{
        if(document.body.classList.contains("night-mode")){
            switchDay();
        } else {
            switchNight();
        }
    })
}

function settings(){
    $("#J_global_user_tips").before(`
<div class="setting-btn-wrapper" title="设置">
    <div class="setting-btn">
        <svg t="1594304610163" class="setting-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="14953" width="26" height="26"><path d="M972.635487 631.216851L892.207069 548.741164a368.50839 368.50839 0 0 0 1.754802-37.216423 372.456694 372.456694 0 0 0-1.754802-37.216423l80.428418-82.18322a51.181721 51.181721 0 0 0 18.791004-69.82649l-76.699465-132.926241a51.181721 51.181721 0 0 0-69.82649-18.86412l-111.576152 28.73488a385.105891 385.105891 0 0 0-64.488968-37.289539L638.053267 51.181721a51.181721 51.181721 0 0 0-51.181721-51.181721h-153.545163a51.181721 51.181721 0 0 0-51.18172 51.181721l-30.78215 111.064334a384.082256 384.082256 0 0 0-64.488968 37.216423L175.297394 170.727597a51.181721 51.181721 0 0 0-69.826491 18.86412L29.063906 322.517958a51.181721 51.181721 0 0 0 18.86412 69.82649l80.428418 82.183221a368.50839 368.50839 0 0 0-1.754802 37.216422c0 12.502963 0.584934 24.859693 1.754802 37.216423l-80.428418 82.18322a51.181721 51.181721 0 0 0-18.86412 69.826491L105.76337 833.896466a51.181721 51.181721 0 0 0 69.826491 18.86412l111.576151-28.734881a385.252124 385.252124 0 0 0 64.488968 37.216423l30.78215 111.064334a51.181721 51.181721 0 0 0 51.18172 51.181721h153.545163a51.181721 51.181721 0 0 0 51.181721-51.181721l30.782149-111.064334a383.570439 383.570439 0 0 0 64.488968-37.216423l111.503035 28.734881a51.181721 51.181721 0 0 0 69.82649-18.86412l76.699465-132.926241a51.181721 51.181721 0 0 0-19.010354-69.753374z m-462.536522 59.663263a179.20914 179.20914 0 0 1-179.062906-179.062906 179.20914 179.20914 0 0 1 179.062906-179.062906 179.20914 179.20914 0 0 1 179.062906 179.062906 179.282256 179.282256 0 0 1-179.062906 179.062906z m0 0" p-id="14954"></path></svg>
    </div>
    <div class="setting-panel-wrapper">
        <div class="setting-panel">
            <label>直播流清晰度: </label>
            <input id="video-type-bd" type="radio" name="videoType"><label for="video-type-bd">超清</label>
            <input id="video-type-hd" type="radio" name="videoType"><label for="video-type-hd">高清</label>
            <input id="video-type-dvd" type="radio" name="videoType"><label for="video-type-dvd">流畅</label>
        </div>
    </div>
</div>
`)
}

// 自动领取礼物掉落的宝箱
let receiveTimer;
function autoReceiveTreasure(){
    if($("#J_treasureChestContainer .btn").size() === 0){
        return;
    }
    let alreadyChat = false;
    let receive = ()=>{
        if($("#J_treasureChestContainer .btn.usable").size() > 0){
            $("#J_treasureChestContainer .btn.usable").click()
            clearInterval(receiveTimer);
            receiveTimer = undefined;
        } else if($("#J_treasureChestContainer .btn").size() > 0) {
            if(!alreadyChat){
                chat('666')
                alreadyChat = true;
            }
        } else {
            clearInterval(receiveTimer);
            receiveTimer = undefined;
        }
    }
    if(!receiveTimer){
       receiveTimer = setInterval(receive,1000);
    }
}

function addEventListener(){
    $("#player-fullpage-btn").click(()=>{
        if($(".player-narrowpage").size() > 0){
            $("#videoContainer").addClass("huyaplus-page-full-mode");
        } else {
            $("#videoContainer").removeClass("huyaplus-page-full-mode");
            $("#player-ctrl-wrap, #player-gift-wrap").removeClass("show");
        }
    })

    $("#player-fullscreen-btn").click(()=>{
        if($(".player-narrowscreen").size() > 0 && $(".player-narrowpage").size() > 0){
            console.log("add")
            $("#videoContainer").removeClass("huyaplus-page-full-mode");
            $("#player-ctrl-wrap, #player-gift-wrap").removeClass("show");
        } else if($(".player-narrowpage").size() > 0){
            console.log("remove")
            $("#videoContainer").addClass("huyaplus-page-full-mode");
        }
    })

    $("#player-video").dblclick(()=>{
        if($(".player-narrowpage").size() > 0){
            $("#videoContainer").addClass("huyaplus-page-full-mode");
        } else {
            $("#videoContainer").removeClass("huyaplus-page-full-mode");
            $("#player-ctrl-wrap, #player-gift-wrap").removeClass("show");
        }
    })

    let hideTimeout;
    $(".room-player").on("mousemove",".huyaplus-page-full-mode", ()=>{
        $("#player-ctrl-wrap, #player-gift-wrap").addClass("show");
        clearTimeout(hideTimeout);
        hideTimeout = setTimeout(()=>{
            $("#player-ctrl-wrap, #player-gift-wrap").removeClass("show");
        },2000);
    }).on("mouseleave",".huyaplus-page-full-mode", ()=>{
        $("#player-ctrl-wrap, #player-gift-wrap").removeClass("show");
    })
}

function addStreamVideoPreview(){
    let previewTimeout,hls;
     $("body").on('mouseenter','.subscribe-live-item', function(e){
        previewTimeout = setTimeout(()=>{
            let streamUrl = $(e.target).parent().get(0).href;
            $(e.target).parent().prepend(`<video muted="true" id="video-preview" style='width: 100%;height: 100%;display:none;'></video>`)
            doGetStreamUrl(streamUrl).then(videoUrl=>{
                 if(Hls.isSupported()) {
                     videoUrl = convertStreamIbitrate(videoUrl, 500);
                     var video = document.getElementById('video-preview');
                     hls = new Hls();
                     hls.loadSource(videoUrl);
                     hls.attachMedia(video);
                     hls.on(Hls.Events.MANIFEST_PARSED,function() {
                         let video = document.getElementById('video-preview');
                         if(video){
                             $(video).show();
                             video.play();
                             toggleLiveItemMask($(e.target).parent(), false)
                         }
                     });
                 }
            }).catch(e=>{
                console.log("Video Preview failed")
            })
        }, 1000)
    });

    $("body").on('mouseleave','.subscribe-live-item', function(e){
        clearTimeout(previewTimeout);
        $("#video-preview").remove();
        toggleLiveItemMask($(".video-previewing"), true)
        if(hls){
            hls.destroy();
        }
    });
}

function toggleLiveItemMask(liveItemEle, show){
    if(show){
        liveItemEle.removeClass('video-previewing')
    } else {
        liveItemEle.addClass('video-previewing')
    }
}

function autoMaxIbitrate(){
    let el = $('.player-videotype-list>li:first');
    if(el.length === 1){
        el.click();
    }
}

let danmuFilterTimer;
function danmuFilter(){
    let keywords = ["RNG","儿姿","??","??","微信公众号","666"]
    if(danmuFilterTimer){
        clearInterval(danmuFilterTimer);
    }
    danmuFilterTimer = setInterval(()=>{
        let danmuList = $('#danmudiv>.danmu-item')
        let danmuTextList=[];
        for(let i = 0; i < danmuList.length; i++){
            let danmuItem = $(danmuList.get(i));
            let danmuText = danmuItem.find('span').get(0).innerText;
            if(danmuTextList.indexOf(danmuText) > -1){
                console.log(`过滤重复弹幕:${danmuText}`)
                danmuItem.remove()
                continue;
            }
            danmuTextList.push(danmuText)
            for(let keyword of keywords){
                if(danmuText.indexOf(keyword) > -1){
                    console.log(`过滤关键词(${keyword})弹幕:${danmuText}`)
                    danmuItem.remove()
                }
            }
        }
    }, 100)
}

async function initPlayer(){
    autoMaxIbitrate();
    await waitLoad(()=>$("#player-fullpage-btn").length > 0)
    setTimeout(()=>$("#player-fullpage-btn").click(), 1000)
}

let timer,treasureTimer;
(async function() {

    await waitLoad(jqueryLoaded);
    cleanPage();
    autoNightMode();
    await waitLoad(()=>$("#J_duyaHeaderRight>div").length > 0)
    addNightModeSwitcher();
    //settings();
    addUi();
    addStreamVideoPreview();

    if(treasureTimer) clearInterval(treasureTimer)
    treasureTimer = setInterval(autoReceiveTreasure, 30000)

    addEventListener();
    //danmuFilter()
    initPlayer();
    //completeChatTask();
    let intervalInMills = 60 * 1000;
    let task = ()=>{
        autoReceiveBoxReward();
        //autoReceiveTaskXP();
    };
    task();
    if(timer) clearInterval(timer);
    timer = setInterval(task,intervalInMills);
})();