CSSBuy Auto-Uploader

Automatically upload QC images from CSSBuy

当前为 2020-05-18 提交的版本,查看 最新版本

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         CSSBuy Auto-Uploader
// @namespace    https://www.reddit.com/user/DeliciousLysergic/
// @version      0.4
// @description  Automatically upload QC images from CSSBuy
// @author       DeliciousLysergic
// @match        https://www.cssbuy.com/?go=m&name=orderlist*
// @match        https://imgur.com/*
// @grant        none
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js
// @require      https://cdnjs.cloudflare.com/ajax/libs/blueimp-md5/2.16.0/js/md5.min.js
// @require      https://cdn.jsdelivr.net/npm/[email protected]/jquery.initialize.min.js
// ==/UserScript==

jQuery(function() {

    var $ = window.jQuery;

    // Check if we are on imgur, if so, we're here to get rid of the spaces and bail!
    if(window.location.hostname.includes("imgur"))
    {
        // First group is the URL / a link
        // Second group is ID
        const regexString = /(<a rel="noreferrer nofollow" target="_blank" href="https:\/\/item">https:\/\/item<\/a> \. taobao \. com\/item \. htm\?id=)(\d+)/m;

        function fixLinks()
        {
            var html = $(this).html();
            var match = html.match(regexString);

            if(match != null && match.length == 3)
            {
                var id = match[2];
                var new_match = '<a rel="noreferrer nofollow" target="_blank" href="https://item.taobao.com/item.htm?id=' + id + '">https://item.taobao.com/item.htm?id=' + id + "</a>"
                html = html.replace(match[0], new_match)
                $(this).html(html)
            }
        }

        $(".post-image-description").each(fixLinks);
        $.initialize(".post-image-description", fixLinks);

        return;
    }

    'use strict';
    // Used to store each item's data
    var items = {};

    var clientIds = ["1ffdbfe5699ecec", "447a420679198a0", "956dd191d8320c9", "efb0b998924ef3c", "6f8eb75873d5f89", "9af4f2c84a12716"];
    var clientId = clientIds[Math.floor(Math.random()*clientIds.length)]
    var imageLoadingTime = 5000; // Time it takes for the image URLs to load in the iFrame in milliseconds

    var uploadButtonStyle = "btn btn-sm btn-default margin-bottom-5"

    var usernameMD5 = "";
    var usernameiFrame;

    function setDisabled(button, disabled) {
        if (disabled) 
        {
            button.attr("disabled", "disabled");
            button.text("Uploading...");
        }
        else
        {
            button.attr("disabled", null);
            button.text("Upload to Imgur");
        }
    }

    // https://stackoverflow.com/a/11818658
    function toFixed(num, fixed) {
        var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
        return num.toString().match(re)[0];
    }

    function createAlbum(orderId) {
      
        // Create album
        var albumHash = "";
        var albumId = "";

        items[orderId].infoLabel.text("Creating imgur album...");

        $.ajax({
            url: "https://api.imgur.com/3/album",
            method: "POST",
            headers: {"Authorization": "Client-ID " + clientId},
            data: {
                description: "Auto uploaded using CSSBuy uploader. More info here: TODO: UPDATE!",
                privacy: "hidden"
            },
            success: function(response) {
                albumHash = response.data.deletehash;
                albumId = response.data.id;

                // Upload images to imgur
                var image_count = 0;
                var total_images = items[orderId].qcImages.length;
                var hashes = [];

                items[orderId].infoLabel.text("Uploading images to Imgur... (0/" + total_images + ")");

                // Create description
                var description = "";
                description = description + (items[orderId].itemUrl != "" ? "W2C: " + items[orderId].url + "\n": "");
                description = description + (items[orderId].weight != "" ? "Weight: " + items[orderId].weight + " grams\n": "");
                description = description + (items[orderId].price != "" ? "Price: ¥" + toFixed(items[orderId].price, 2) + "\n": "");
                description = description + (items[orderId].sizing != "" ? "Item Info: " + items[orderId].sizing + "\n": "");

                data = {
                  album: albumHash,
                  description: description
                }

                items[orderId].qcImages.forEach(function(image) {
                    url = image[0]
                    base64Image = image[1]

                    data.image = url;

                    $.ajax({
                        url: "https://api.imgur.com/3/image",
                        method: "POST",
                        headers: {"Authorization": "Client-ID " + clientId},
                        data: data,
                        success: function(result) {
                            hashes.push(result.data.deletehash);
                            image_count += 1
                            
                            items[orderId].infoLabel.text("Uploading images to Imgur... (" + image_count + "/" + total_images + ")");

                            if(image_count == total_images) {
                                var albumUrl = "https://imgur.com/a/" + albumId;

                                console.log("All images uploaded!");
                                console.log("URL: " + albumUrl);

                                // Save result
                                window.localStorage["orderalbum_" + orderId] = albumId

                                // Update button / uploading status
                                items[orderId].uploading = false;
                                items[orderId].uploadButton.text("Uploaded!");

                                // Update progress label & link
                                updateProgressLabel(orderId, albumUrl)

                                // Upload to GOAT QC
                                console.log(items[orderId].url)
                                if(items[orderId].sizing != "")
                                {
                                    // Tell QC Suite about our uploaded QC's (if it's from TaoBao)
                                    // Thank you to https://greasyfork.org/en/scripts/387421-fr-es-basetao-extension/code
                                    if (items[orderId].url.indexOf('item.taobao.com') !== -1) {
                                        // Check if we already have username, otherwise, go retrieve it
                                        if (usernameMD5 == "")
                                        {
                                            usernameiFrame = $("<iframe>", {
                                                onload: "collectUsername()", 
                                                style: "display: none;",
                                                src: "https://www.cssbuy.com/?go=m&"
                                            });
                                            usernameiFrame.insertAfter($("form[name='search-form']"));
                                            setTimeout(function() {
                                                uploadToFashiontools(orderId, albumId);
                                            }, 1500);
                                            return;
                                        }
                                        uploadToFashiontools(orderId, albumId);

                                    }
                                }
                            }
                        },
                        error: function(result)
                        {
                            result = $.parseJSON(result.responseText)
                            items[orderId].infoLabel.text("Failed to upload! Imgur Error: " + result.data.error.message);
                            items[orderId].uploading = false;
                            setDisabled(items[orderId].uploadButton, false)
                            console.log("Failed to upload:");
                            console.log(result.data.error)
                            return;
                        }
                    })
                });
            },
            error: function(result) {
                result = $.parseJSON(result.responseText)
                items[orderId].infoLabel.text("Failed to create album! Imgur Error: " + result.data.error.message);
                items[orderId].uploading = false;
                setDisabled(items[orderId].uploadButton, false)
                console.log("Failed to create album:");
                console.log(result.data.error)
            }
        })

    };

    window.collectUsername = function()
    {
        // Get the username from the homepage
        var username = $("a[href='https://www.cssbuy.com/?go=m&name=edituserinfo']", usernameiFrame.contents()).parent().find("span").text()
        usernameMD5 = md5(username, null, true);
    }

    window.collectPictures = function(orderId) {
        // Check that we are uploading this order atm
        // onload is called when iFrame is initialised
        if(!(orderId in items) || !items[orderId].uploading)
            return;

        // Wait a few seconds to ensure all the images have loaded...
        setTimeout(function() {
            // Check iFrame for all images
            // Add images to a list in form [url, base64]
            var urls = [];
            
            // Retrieve all the images
            items[orderId].iFrame.contents().find("#photolist").find("img").each(function() {
                var url = $(this).attr("src");
                var base64Image = "";

                urls.push([url, base64Image]);
            });

            items[orderId].qcImages = urls

            if(!urls.length)
            {
                items[orderId].infoLabel.text("Found no QC images!")
            }
            else
            {
                items[orderId].infoLabel.text("Found " + urls.length + " QC pictures...")

                createAlbum(orderId);
            }
        }, imageLoadingTime);
    };

    window.copyToClipboard = function(text) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val(text).select();
        document.execCommand("copy");
        $temp.remove();
    }

    window.uploadItem = function(orderId) {
        // If we are already uploading this item, return
        if(items[orderId].uploading)
            return;

        // Update label
        clearLink(orderId)
        items[orderId].infoLabel.text("Getting QC pictures...");
        items[orderId].uploading = true;

        // Disable button
        setDisabled(items[orderId].uploadButton, true)

        // Update iFrame to get pictures
        items[orderId].iFrame.attr("src", items[orderId].qcUrl);
    }

    function uploadToFashiontools(orderId, albumId)
    {
        console.log("Uploading to fashionrepsTools")
        $.post("https://fashionreps.tools/qcdb/qcdb.php", {
            'userhash': usernameMD5,
            'imgur': albumId,
            'w2c': items[orderId].w2c,
            'sizing': items[orderId].sizing,
            'source': 'cssbuyUploader'
        });
    }

    function clearLink(orderId)
    {
        items[orderId].copyButton.hide()
        items[orderId].infoLink.text("")
    }

    function updateProgressLabel(orderId, albumUrl)
    {
        items[orderId].infoLabel.text("Uploaded to ");
        items[orderId].infoLink.text(albumUrl);
        items[orderId].infoLink.attr("href", albumUrl);
        items[orderId].copyButton.show();
        items[orderId].copyButton.attr("onclick", "copyToClipboard('" + albumUrl + "')");
    }

    // Add buttons for each of the items
    var buttonSelector = ".oss-photo-view-button > a:contains('QC PIC')";

    $(buttonSelector).each(function() {
        var orderId = $(this).parent().attr("data-id");

        // Create the "Upload to Imgur" button
        var qcUrl = $(this).attr("href");
        var uploadButton = $("<a>", {
            class: uploadButtonStyle, 
            text: "Upload to Imgur", 
            onclick: "uploadItem('" + orderId + "')",
            orderId: orderId, 
            style: "background: #1bb76e; border: 1px solid #1bb76e; color: white;"
        });
        uploadButton.appendTo($(this).parent());

        // Get parent TR element to retrieve item name & URL & create progress label
        var parentTableEntry = $(this).parentsUntil("tbody");
        var header = $("td div div:nth-child(2)", parentTableEntry.prev())

        // Create progress label
        var label = $("<span>", {
            text: "", 
            style: "font-weight: bold; margin-left: 40px;"
        });
        label.appendTo(header);

        // Create album link
        var link = $("<a>", {style:"margin-right: 10px;"});
        link.appendTo(header);

        // Create copy butotn
        var copyButton = $("<a>", {
            text: "Copy to Clipboard", 
            style: "padding: 3px; font-size: 1em; cursor: pointer;",
        })
        copyButton.hide()
        copyButton.appendTo(header)

        // Get item name/URL
        var itemLink = parentTableEntry.find("td:nth-child(2) a")
        var price = parentTableEntry.find("td:nth-child(3) span")
        var weight = parentTableEntry.find("td:nth-child(6) span")
        var sizing = "";

        var innerText = parentTableEntry.find("td:nth-child(2)").find("span:eq(1)").html()
        var splitText = innerText.toString().split("<br>")
        if (splitText.length == 1)
        {
            var colour = splitText[0].split(" : ")[1]
            sizing = "Color Classification:"+colour
        }
        else if(splitText.length == 2)
        {
            var size = splitText[0].split(" : ")[1]
            var colour = splitText[1].split(" : ")[1]
            sizing = "size:" + size + " Colour:"+color
        }
        else
        {
            sizing = "";
        }
            
        // Create iframe
        var iFrame = $("<iframe>", {
            onload: "collectPictures('" + orderId + "')", 
            style: "display: none;"
        });

        iFrame.insertAfter($("form[name='search-form']"));
        
        // Create new item entry
        items[orderId] = {
            orderId: orderId,
            name: itemLink.text(),
            url: itemLink.attr("href"),
            price: price.text(),
            weight: weight.text(),
            sizing: sizing,
            qcUrl: qcUrl,
            qcImages: [],
            copyButton: copyButton,
            infoLink: link,
            infoLabel: label,
            iFrame: iFrame,
            uploading: false,
            uploadButton: uploadButton
        }

        // Check whether they already have a album saved for this id
        if(("orderalbum_" + orderId) in window.localStorage)
        {
            updateProgressLabel(orderId, "https://imgur.com/a/" + window.localStorage["orderalbum_" + orderId])
        }

    });
});