提交词典到个人必应词典

提交词典到个人必应翻译

当前为 2022-10-17 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         提交词典到个人必应词典
// @namespace 	 [email protected]
// @version      0.7
// @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 MyDict {
        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;
            }

            .tip {
                position: relative;
                margin-left: 20px;
                margin-top: 20px;
                width: 200px;
                background: #8b1a02;
                padding: 10px;
                position: fixed;
                top: 0;
                left: 40%;
                /*设置圆角*/
                z-index: 2100000000;
                -webkit-border-radius: 5px;
                -moz-border-radius: 5px;
                border-radius: 5px;
                display:none;
            }

            /*提示框-左三角*/
            .tip-trangle-left {
                position: absolute;
                bottom: 15px;
                left: -10px;
                width: 0;
                height: 0;
                border-top: 15px solid transparent;
                border-bottom: 15px solid transparent;
                border-right: 15px solid #8b1a02;
            }

            /*提示框-右三角*/
            .tip-trangle-right {
                position: absolute;
                top: 15px;
                right: -10px;
                width: 0;
                height: 0;
                border-top: 15px solid transparent;
                border-bottom: 15px solid transparent;
                border-left: 15px solid #8b1a02;
            }

            /*提示框-上三角*/
            .tip-trangle-top {
                position: absolute;
                top: -10px;
                left: 20px;
                width: 0;
                height: 0;
                border-left: 15px solid transparent;
                border-right: 15px solid transparent;
                border-bottom: 15px solid #8b1a02;
            }

            /*提示框-下三角*/
            .tip-trangle-bottom {
                position: absolute;
                bottom: -10px;
                left: 20px;
                width: 0;
                height: 0;
                border-left: 15px solid transparent;
                border-right: 15px solid transparent;
                border-top: 15px solid #8b1a02;
            }
            </style>

            <div class="tip" style="background-color: #8b1a02;" id="WordToNoteBookButton">
                <div class="tip-trangle-bottom"></div>
                单词添加成功提示:<br/>
                <span></span>
            </div>

            <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>
            `
            return html
        }

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

        info(message){
            let id = "#WordToNoteBookButton"
            let note = document.querySelector(id)
            if(note){
                note.querySelector('span').innerHTML = message
                note.style.display = 'block'
                setTimeout(() => {
                    note.style.display = 'none'
                },1500)
            }
        }

        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
        }

		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)
				})
			})
		}

        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)
                })

            })

            document.onkeydown = function(e) {
                if(e.key == 'h') {

                    let saladict = document.querySelector('#saladict-dictpanel-root .saladict-panel')
                    if(!saladict){
                        return
                    }
                    let shadowRoot = saladict.shadowRoot
                    if(!shadowRoot){
                        return
                    }
                    let SearchBox = shadowRoot.querySelector(".menuBar-SearchBox")
                    if(!SearchBox){
                        return
                    }
                    let word = SearchBox.value
                    if(word){
                        let data = window.MyDict.get("put_word",{
                            group:"eudic默认生词本",
                            word
                        }).then((data)=>{
                            console.log(data)
                            window.MyDict.info(`${word}添加到生词本.`)
                        })
                    }
                    e.preventDefault();
                    return false;
                }
            }

        }
    }
    window.MyDict = new MyDict()
    window.MyDict.init()
})();