提交词典到个人必应词典

提交词典到个人必应翻译

目前為 2022-10-12 提交的版本,檢視 最新版本

// ==UserScript==
// @name         提交词典到个人必应词典
// @namespace 	 [email protected]
// @version      0.4
// @description  提交词典到个人必应翻译
// @author       [email protected]
// @match        *://*.*/*
// @match        *://*.*.*/*
// @match        *://*/*
// @license      AGPL License
// @grant        GM_download
// @grant        GM_openInTab
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @grant        unsafeWindow
// @grant        GM_setClipboard
// @grant        GM_getResourceURL
// @grant        GM_getResourceText
// @grant        GM_info
// @grant        GM_registerMenuCommand
// @grant        GM_cookie
// ==/UserScript==

(function () {
    'use strict';
    if (typeof window != 'undefined' && !window.$) {
        window.$ = {
            get: function (URL, queryJSON, callback) {
                let xhr;
                if (window.XMLHttpRequest) {
                    xhr = new XMLHttpRequest();
                } else {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                            callback(xhr.responseText);
                        } else {
                            callback(new Error("AJAX GET did not find the requested file"), undefined);
                        }
                    }
                }
                let querystring = this._queryjson2querystring(queryJSON);
                let joiner
                if (!URL.includes('?')) {
                    joiner = "?"
                } else {
                    joiner = "&"
                }

                xhr.open("get", URL + joiner + querystring, true);
                xhr.send(null);
            },
            post: function (URL, queryJSON, callback) {
                let xhr;
                if (window.XMLHttpRequest) {
                    xhr = new window.XMLHttpRequest();
                } else {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4) {
                        if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                            callback(xhr.responseText);
                        } else {
                            callback(new Error("AJAX POST did not find the requested file"), undefined);
                        }
                    }
                }
                let querystring = this._queryjson2querystring(queryJSON);
                xhr.open("post", URL, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.send(querystring);
            },
            _queryjson2querystring: function (json) {
                var arr = [];
                for (var k in json) {
                    arr.push(k + "=" + encodeURIComponent(json[k]));
                }
                return arr.join("&");
            }
        }
    }


    class SubmitToBing {
        base_remote_url = "https://local.12gm.com:18800"

        constructor() {
        }

        get(method, request_data) {
            let url = this.remote_url(method)
            return new Promise((resolve, reject) => {
                $.get(url, request_data, (data) => {
                    resolve(data)
                })
            })
        }

        post(method, data) {
            let url = this.remote_url(method)
            return new Promise((resolve, reject) => {
                $.post(url, data, (data) => {
                    resolve(data)
                })
            })
        }

        get_button_html() {
            let html = `
            <style>
            .add_wordtodocument{
                display: block;
                z-index: 1050;position: fixed;
                right: 7px;
                top: 130px;
                height: 55px;
                font-weight: 900;
                background: -webkit-linear-gradient(45deg, #70f7fe, #fbd7c6, #fdefac, #bfb5dd, #bed5f5);
                -moz-linear-gradient(45deg, #70f7fe, #fbd7c6, #fdefac, #bfb5dd, #bed5f5);
                -ms-linear-gradient(45deg, #70f7fe, #fbd7c6, #fdefac, #bfb5dd, #bed5f5);
                color: transparent;
                /*设置字体颜色透明*/
                /*背景裁剪为文本形式*/
                animation: ran 10s linear infinite;
                /*动态10s展示*/
                border-radius: 25px;
                padding: 0 10px;
            }
            .add_worddiv{
                float: left;
                width: 200px;
                display:none;
            }
            .add_wordinput{    
                width: 200px;
                height: 30px;
                line-height: 30px;
                border-radius: 10px;
                color: #333333;
            }
            .add_worddivbutton{
                float: left;
                width: 65px;
                margin-left: 5px;
            }
            .add_worddiv ul{
                margin: 0;
                float: left;
                padding: 0px;
            }
            .add_worddiv ul li{
                float: left;
            }
            .add_worddiv ul li .group_span{
                color: #000;
                font-size: 12px;
                line-height: 20px;
                /* height: 20px; */
                padding-left: 5px;
            }
            .add_worddiv ul .grouptitle{
                height: 14px;
            }
            .add_wordbutton{
                display: block;
                width: 100%;
                float: left;
                font-weight: bold;
                font-size: 30px;
                line-height: 55px;
                text-align: center;
                color: indianred;
            }
            .worddiv_iframediv{
                display: block;
                width: 100%;
                float: left;
                font-weight: bold;
                font-size: 30px;
                line-height: 55px;
                text-align: center;
                color: indianred;
            }
            .worddiv_iframediv{
                display: none;
                width: 100%;
                float: left;
                font-weight: bold;
                font-size: 30px;
                line-height: 55px;
                text-align: center;
                color: indianred;
            }
            .worddiv_iframe{
                display: block;
                width: 100%;
                height: 800px;
            }
            </style>
            <div class="add_wordtodocument">
                <div class="add_worddiv">
                    <ul>
                        <li class="grouptitle"><span class="group_span">默认分组名</span></li>
                        <li><input type="text" class="add_wordinput"/></li>
                    </ul>
                </div>
            <div class="add_worddivbutton">
                <a href="javascript:void(0)" id="my_bing_putwords_botton" class="add_wordbutton">
                    Add
                </a>
            </div>
            <div class="worddiv_iframediv">
                <iframe class="worddiv_iframe" style="display:none;" src="#" frameborder="0" scrolling="0"></iframe>
            </div>
            </div>
            `
            return html
        }

        init() {
            this.set_html()
            this.listing_buttom()
        }

        is_mobile_browser() {
            let mobile_match = navigator.userAgent.match(
                /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
            )
            if (mobile_match) {
                this.get_trans_word_index = 2
                this.mobile_browser = 1
            }else{
                this.get_trans_word_index = 3
                this.mobile_browser = 0
            }
        }

        exclude(){
            let exclude_hosts = ["12gm.com"]
            let hostname = window.location.hostname
            hostname = hostname.split(".").slice(-2).join('.').toLowerCase()
            if(exclude_hosts.indexOf(hostname) != -1){
                return true
            }else{
                return false
            }
        }

        set_html() {
            if(!this.exclude()){
                let up_html = this.get_button_html(190, "Add")
                document.querySelector('body').insertAdjacentHTML("afterBegin", up_html);
            }
        }

        listin_documentalive() {
            
        }

        remove(selector) {
            let ele = document.querySelector(selector)
            if (ele) {
                ele.remove()
            }
        }

        get_document() {
            let words = [...(
                new Set(
                            document.documentElement.textContent.split(/[^a-zA-Z]/)
                            .join(" ").split(/(?<=[a-z])\B(?=[A-Z])/)
                            .join(" ").split(/\s+/)
                    )
                )]
                let is_notword = /^[a-z]+[A-Z]$/
                let new_words = []
                for(let word of words){
                    if(is_notword.test(word) || word.length < 3){
                        console.log(`${word} filter.`)
                    }else{
                        new_words.push(word)
                    }
                }
            console.log(`requested words:`,new_words)
            new_words.join(" ")
            return new_words
        }
        
        split_html(html){
            html = html.replaceAll(/<.+?>/g, '')
            return html
        }   

        put_to_remote_local_vocabulary(callback) {
            let doc = document.documentElement.outerHTML;
            if (doc) {
                let url = this.remote_url('put_translate_words')
                $.post(url, {
                    "doc": doc,
                    "t_group": location.hostname
                }, (data) => {
                    if (callback) {
                        callback(data)
                    }
                })
            }
        }

		local_storage(key,value){
			if(value){
				localStorage.setItem(key,value)
			}else{
				return localStorage.getItem(key)
			}
		}

        set_groupname() {
            this.local_storage("group_name",window.location.hostname)
        }

        get_groupname() {
            let group_name = this.local_storage("group_name")
            if(!group_name){
                group_name = this.get_defaultgroupname()
            }
            return group_name
        }

        get_defaultgroupname() {
            return window.location.hostname
        }


        remote_url(method) {
            let url = `${this.base_remote_url}/api?method=${method}&key=9LrQN0~14,dSmoO^&module=com_translate`;
            return url
        }
        
        translate_wordtotran(){
            let trans_target = document.querySelector("#outlined-multiline-static")
            setInterval(function(){
                let text = window.getSelection().toString()
                let trans_target_text = trans_target.value
                if(text && text != trans_target_text){
                    trans_target.value = trans_target_text
                }
            },500)
        }
        
        //给添加的元素添加监听事件
        listing(selector,event,callback){
            let ele = document.querySelector(selector)
            if(ele){
                ele.addEventListener(event,()=>{
                    callback()
                })
            }
        }

        //给添加的元素添加监听事件
        listing_buttom() {
            //this.translate_wordtotran()
            this.listing('#my_bing_putwords_botton','click',()=>{
                document.querySelector(`.add_worddiv`).style.display = 'block'
                document.querySelector(`.add_wordtodocument`).style.width = '290px'
                let add_wordinput = document.querySelector(`.add_wordinput`)
                if(!add_wordinput.value){
                    let defaultgroupname = this.get_defaultgroupname()
                    add_wordinput.value = defaultgroupname
                }else{
                    // 暂时不更新.
                    // let group_name = add_wordinput.value
                    // this.set_groupname(group_name)
                    // let doc = this.get_document()
                    // this.post("put_group",{
                    //     doc: doc,
                    //     group_name: group_name,
                    //     incremental:true
                    // }).then((result)=>{
                    //     console.log(result)
                    // })
                }
                let group_name = add_wordinput.value
                this.set_groupname(group_name)
                let doc = this.get_document()
                this.post("put_group",{
                    doc: doc,
                    group_name: group_name,
                    incremental:true
                }).then((result)=>{
                    console.log(result)
                })

            })
        }

    }
    let bing = new SubmitToBing()
    bing.init()
})();