Greasy Fork

Greasy Fork is available in English.

steam补充包工具

To dear sbeamer!

当前为 2018-12-29 提交的版本,查看 最新版本

// ==UserScript==
// @name         steam补充包工具
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  To dear sbeamer!
// @author       ZXR
// @match        https://steamcommunity.com//tradingcards/boostercreator/
// @include			*steamcommunity.com/*boostercreator*
// @icon         https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f4/f41c579d01a4e5fa0f4f91d69cb93896b8478ccf_medium.jpg
// steamcn       https://steamcn.com/suid-457526
// steam         https://steamcommunity.com/id/zhangxuerui/
// ==/UserScript==

//获取cookie,组装存储key
const cookie = document.cookie;
const boosterKey = 'steam_booster'

//游戏选择器
let gameSelector = document.getElementById("booster_game_selector");
//下方展示部分
let gameForm = document.getElementsByClassName('booster_creator_right')[0]

//是否根据存储的收藏游戏过滤,默认为是
let filter = true

//用于切换过滤的备份option数据
let backUpOptions = []

//过滤后的option
let filterOptions = []

//当前可以做补充包的游戏,用于一键做包,只有filter为true才会收集数据
let availableGame = []

//游戏管理页面
let searchInfo = ''
let searchResult = [];
let pageNum = 1;
let totalCount = 0;
const pageSize = 8

//该用户存储的补充包信息
let boosterInfo = {}

//开始制作补充包
function createBooster(index) {
    document.getElementById("createButton").innerHTML = "正在制作第 " + (index + 1) + "个补充包"
    let item = availableGame[index]
    $J.ajax({
        url: 'https://steamcommunity.com/tradingcards/ajaxcreatebooster/',
        type: 'POST',
        data: {
            sessionid: cookie.split('sessionid=')[1].split(';')[0],
            appid: item.value,
            series: 1,
            tradability_preference: 1
        },
        crossDomain: true,
        xhrFields: {withCredentials: true}
    }).success(function () {
        if (!filter) {
            for (let i = 0; i < backUpOptions.length; i++) {
                if (backUpOptions[i].value === item.value) {
                    backUpOptions[i].setAttribute("class", "unavailable")
                    break;
                }
            }
        } else {
            for (let i = 0; i < filterOptions.length; i++) {
                if (filterOptions[i].value === item.value) {
                    filterOptions[i].setAttribute("class", "unavailable")
                    break;
                }
            }
        }
        if (index + 1 < availableGame.length) {
            //默认500毫秒后进行下一次制作,不建议太快
            setTimeout(function () {
                createBooster(index + 1)
            }, 500)
        } else {
            document.getElementById("createButton").innerHTML = "全部完成"
            document.getElementById("createButton").setAttribute('class','btnv6_blue_blue_innerfade btn_medium btn_makepack btn_disabled')
        }
    }).error(function () {
        document.getElementById("createButton").innerHTML = "制作失败,请检查宝石数量或刷新页面"
    });
}

//过滤和展示全部之间进行切换
function filterConvert() {
    gameSelector.options.length = 0;
    if (filter) {
        backUpOptions.map((item) => {
            gameSelector.add(item)
        })
        document.getElementById("convertButton").innerHTML = "过滤"
    } else {
        filterOptions.map((item) => {
            gameSelector.add(item)
        })
        document.getElementById("convertButton").innerHTML = "展示全部"
    }
    filter = !filter
}

//判断字符串是否为空,不为空是true,为空是false
function stringNotBlank(value) {
    if (!value || value.trim() === '') {
        return false;
    } else {
        return true;
    }
}

//判断字符串是否为空,为空是true,不为空是false
function stringBlank(value) {
    if (!value || value.trim() === '') {
        return true;
    } else {
        return false;
    }
}

//执行搜索
function doSearch() {
    let inputValue = document.getElementById('searchInput').value
    if (stringNotBlank(inputValue)) {
        searchInfo = inputValue
    } else {
        searchInfo = ''
    }
    searchResult = []
    if (stringBlank(searchInfo)) {
        for (let i = 0; i < backUpOptions.length; i++) {
            if (stringNotBlank(backUpOptions[i].value)) {
                searchResult.push({appid: backUpOptions[i].value, name: backUpOptions[i].text})
            }
        }
    } else {
        for (let i = 0; i < backUpOptions.length; i++) {
            //支持模糊大小写匹配和appid
            if ((stringNotBlank(backUpOptions[i].value) && backUpOptions[i].text.toUpperCase().indexOf(searchInfo.toUpperCase()) !== -1) || (stringNotBlank(backUpOptions[i].value) && backUpOptions[i].value === searchInfo)) {
                searchResult.push({appid: backUpOptions[i].value, name: backUpOptions[i].text})
            }
        }
    }
    pageNum = 1
    generateGameList(pageNum, pageSize, searchResult)
}

//生成游戏列表
function generateGameList(pageNum, pageSize, searchResult) {
    //重新生成,删除旧数据
    for (let i = gameForm.childNodes.length - 1; i >= 0; i--) {
        gameForm.removeChild(gameForm.childNodes[i]);
    }

    let searchInput = document.createElement('input');
    searchInput.setAttribute('id', 'searchInput')
    searchInput.setAttribute('style', 'background-color: rgba( 103, 193, 245, 0.2 );\n' +
        '    color: #fff;\n' +
        '    border: 1px solid #000;\n' +
        '    border-radius: 3px;\n' +
        '    box-shadow: 1px 1px 0px rgba( 103, 193, 245, 0.15 );\n' +
        '    width: 300px;\n' +
        '    padding: 5px;\n' +
        '    max-width: calc( 100% - 80px - 2px );')
    if (searchInfo && searchInfo.trim() !== '') {
        searchInput.value = searchInfo
    }

    let searchButton = document.createElement('button')
    searchButton.setAttribute('id', 'searchButton')
    searchButton.innerHTML = '搜索'
    searchButton.setAttribute('style', '    border-radius: 2px;\n' +
        '    border: none;\n' +
        '    padding: 1px;\n' +
        '    display: inline-block;\n' +
        '    cursor: pointer;\n' +
        '    text-decoration: none !important;\n' +
        '    color: #67c1f5 !important;\n' +
        '    background: rgba( 103, 193, 245, 0.2 );\n' +
        '    height: 26px;\n' +
        '    width: 100px;\n' +
        '    float: right;\n' +
        '    margin-bottom: 32px;')
    searchButton.onclick = function () {
        doSearch()
    }
    gameForm.appendChild(searchInput)
    gameForm.appendChild(searchButton)


    let startIndex = (pageNum - 1) * pageSize
    if (startIndex > searchResult.length - 1) {
        return null;
    }
    let table = document.createElement('table')
    table.setAttribute('style', 'width:100%')
    for (let i = startIndex; i < searchResult.length && i < startIndex + pageSize; i++) {

        let item = searchResult[i]

        let tr = document.createElement('tr');
        tr.setAttribute('style', 'height:60px')

        let img = document.createElement('img');
        img.setAttribute('src', 'https://steamcdn-a.akamaihd.net/steam/apps/' + item['appid'] + '/capsule_sm_120.jpg')
        let aTag = document.createElement('a');
        aTag.setAttribute('href', 'https://store.steampowered.com/app/' + item['appid'])
        aTag.setAttribute('target', '_blank')
        aTag.appendChild(img)

        let name = document.createElement('span')
        name.innerHTML = item['name']
        name.setAttribute('style', 'display: inline-block;overflow: hidden;text-overflow: ellipsis;width: 320px;white-space: nowrap; margin-left: 16px;')
        name.setAttribute('title', item['name'])

        let button = document.createElement('button')
        button.innerHTML = boosterInfo['game'].indexOf(item['appid']) < 0 ? '收藏' : '移除'
        button.setAttribute('class', 'btnv6_blue_blue_innerfade btn_medium btn_makepack')
        button.setAttribute('style', boosterInfo['game'].indexOf(item['appid']) < 0 ? 'height:26px;width:60px;float:right;margin-top:14px' : 'height:26px;width:60px;float:right;margin-top:14px;background:rebeccapurple')
        button.setAttribute('id', item['appid'])
        button.onclick = boosterInfo['game'].indexOf(item['appid']) < 0 ? function () {
            saveItem(item['appid'])
        } : function () {
            deleteItem(item['appid'])
        }

        tr.appendChild(aTag);
        tr.appendChild(name)
        tr.appendChild(button)
        table.appendChild(tr)
    }
    gameForm.appendChild(table)

    //计算页数
    totalCount = Math.ceil(searchResult.length / pageSize)

    //上一页按钮
    let beforeButton = document.createElement('button');
    beforeButton.setAttribute('id', 'beforeButton')
    beforeButton.innerHTML = '上一页'
    if (pageNum === 1) {
        beforeButton.setAttribute('class', 'btnv6_blue_blue_innerfade btn_medium btn_makepack btn_disabled');
    } else {
        beforeButton.setAttribute('class', 'btnv6_blue_blue_innerfade btn_medium btn_makepack');
    }

    beforeButton.setAttribute('style', 'height: 25px;margin-right: 30px;width: 80px;')
    beforeButton.onclick = function () {
        beforePage()
    }
    gameForm.appendChild(beforeButton)

    let pageSpan = document.createElement('span');
    pageSpan.innerHTML = '共 ' + totalCount + ' 页,当前第 ' + pageNum + ' 页'
    gameForm.appendChild(pageSpan)


    //下一页按钮
    let afterButton = document.createElement('button');
    afterButton.setAttribute('id', 'afterButton')
    afterButton.innerHTML = '下一页'
    if (pageNum === totalCount) {
        afterButton.setAttribute('class', 'btnv6_blue_blue_innerfade btn_medium btn_makepack btn_disabled');
    } else {
        afterButton.setAttribute('class', 'btnv6_blue_blue_innerfade btn_medium btn_makepack');
    }
    afterButton.setAttribute('style', 'height: 25px;margin-left: 30px;width: 80px;')
    afterButton.onclick = function () {
        afterPage()
    }
    gameForm.appendChild(afterButton)

}

//上一页
function beforePage() {
    if (pageNum < 2) {
        return
    }
    pageNum = pageNum - 1
    generateGameList(pageNum, pageSize, searchResult)
}

//下一页
function afterPage() {
    if (pageNum > totalCount - 1) {
        return
    }
    pageNum = pageNum + 1
    generateGameList(pageNum, pageSize, searchResult)
}

//生成一键做包等
function generateCreateButton() {
    //每次删除后重新创建
    let tempCreate = document.getElementById('createButton')
    if (tempCreate !== null) {
        tempCreate.parentNode.removeChild(tempCreate)
    }
    let tempConvert = document.getElementById('convertButton')
    if (tempConvert !== null) {
        tempConvert.parentNode.removeChild(tempConvert)
    }

    //更新下拉列表
    gameSelector.options.length = 0;
    filterOptions.map((item) => {
        gameSelector.add(item)
    })

    //绘制创建按钮
    let createButton = document.createElement('button')
    createButton.setAttribute('id', 'createButton')
    createButton.onclick = function () {
        createBooster(0)
    }
    if (availableGame.length === 0) {
        createButton.innerHTML = '收藏全部冷却中'
        createButton.setAttribute('class', 'btnv6_blue_blue_innerfade btn_medium btn_makepack btn_disabled')
    } else {
        createButton.innerHTML = '一键制作 ' + availableGame.length + ' 个补充包'
        createButton.setAttribute('class', 'btnv6_blue_blue_innerfade btn_medium btn_makepack')
    }
    createButton.setAttribute('style', 'height: 29px; margin-top: 16px;width: 178px;')
    document.getElementsByClassName('booster_game_selector')[0].appendChild(createButton)

    //绘制转换按钮
    let convertButton = document.createElement('button')
    convertButton.setAttribute('id', 'convertButton')
    convertButton.setAttribute('class', 'btnv6_blue_blue_innerfade btn_medium btn_makepack')
    convertButton.innerHTML = '展示全部'
    convertButton.setAttribute('style', 'height: 29px; margin-top: 16px;width: 100px;margin-left:22px')
    convertButton.onclick = function () {
        filterConvert()
    }
    document.getElementsByClassName('booster_game_selector')[0].appendChild(convertButton)
}

//根据appid获取ooption
function getOptionById(appid) {
    if (backUpOptions.length === 0) {
        return null
    }
    for (let i = 0; i < backUpOptions.length; i++) {
        if (backUpOptions[i].value && backUpOptions[i].value === appid) {
            return backUpOptions[i]
        }
    }
    return null
}

//添加进入下拉列表和可制作列表
function addToList(item) {
    if (item == null) {
        return
    }
    let filterIndex = -1
    for (let i = 0; i < filterOptions.length; i++) {
        if (item.value && item.value === filterOptions[i].value) {
            filterIndex = i
            break
        }
    }
    if (filterIndex < 0) {
        filterOptions.push(item)
    }
    if ('available' === item.getAttribute('class')) {
        let availableIndex = -1
        for (let i = 0; i < availableGame.length; i++) {
            if (availableGame[i].value === item.value) {
                availableIndex = i
                break
            }
        }
        if (availableIndex < 0) {
            availableGame.push(item)
        }
    }
}

//根据appid移除时从下拉列表和制作列表删除
function deleteFromList(appid) {
    if (stringBlank(appid)) {
        return
    }
    let filterIndex = -1
    for (let i = 0; i < filterOptions.length; i++) {
        if (appid === filterOptions[i].value) {
            filterIndex = i
            break
        }
    }
    if (filterIndex > -1) {
        filterOptions.splice(filterIndex, 1)
    }
    let availableIndex = -1
    for (let i = 0; i < availableGame.length; i++) {
        if (appid === availableGame[i].value) {
            availableIndex = i
            break
        }
    }
    if (availableIndex > -1) {
        availableGame.splice(availableIndex, 1)
    }

}


//新增游戏收藏
function saveItem(appid) {
    if (boosterInfo['game'].indexOf(appid) >= 0) {
        return
    }
    boosterInfo['game'].push(appid)
    saveStorage(boosterKey, boosterInfo)

    //刷新下拉列表,重新生成按钮和表单
    addToList(getOptionById(appid))
    generateCreateButton()
    generateGameList(pageNum, pageSize, searchResult)
}

//移除游戏收藏
function deleteItem(appid) {
    if (boosterInfo['game'].indexOf(appid) === -1) {
        return
    }
    boosterInfo['game'].splice(boosterInfo['game'].indexOf(appid), 1)
    saveStorage(boosterKey, boosterInfo)

    //刷新下拉列表,重新生成按钮和表单
    deleteFromList(appid)
    generateCreateButton()
    generateGameList(pageNum, pageSize, searchResult)
}

//从localStorage取值
function getStorage(key) {
    return JSON.parse(localStorage.getItem(key))
}

//将值存入从localStorage
function saveStorage(key, item) {
    localStorage.setItem(key, JSON.stringify(item))
}

//初始化数据
function init() {
    //没有可以做补充包的游戏,直接返回
    if (!gameSelector || gameSelector.length === 0) {
        return
    }
    //删除默认展示
    for (let i = gameForm.childNodes.length - 1; i >= 0; i--) {
        gameForm.removeChild(gameForm.childNodes[i]);
    }

    //从localStorage取用户自定义值,默认为空
    boosterInfo = getStorage(boosterKey)
    if (!boosterInfo) {
        boosterInfo = {}
        boosterInfo['game'] = []
    }

    for (let i = 0; i < gameSelector.length; i++) {
        let item = gameSelector.options[i];
        backUpOptions.push(item)
        if (item.value) {
            searchResult.push({appid: item.value, name: item.text})
        }
        if (filter) {
            if (item.value && boosterInfo['game'].indexOf(item.value) > -1) {
                filterOptions.push(item)
                if (item.getAttribute("class") === "available") {
                    availableGame.push(item)
                }
            }
        } else {
            filterOptions.push(item)
        }
    }
    //生成一键制作补充包等按钮
    generateCreateButton()
    //生成下部游戏列表展示
    generateGameList(pageNum, pageSize, searchResult)
}

//执行初始化工作
init();