File size: 8,829 Bytes
4dfaeff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203

var updateInfoGotten = false;
var isLatestVersion = localStorage.getItem('isLatestVersion') || false;


var statusObserver = new MutationObserver(function (mutationsList) {
    for (const mutation of mutationsList) {
        if (mutation.type === 'attributes' || mutation.type === 'childList') {
            if (statusDisplay.innerHTML.includes('<span id="update-status"')) {
                if (getUpdateStatus() === "success") {
                    updatingInfoElement.innerText = i18n(updateSuccess_i18n);
                    noUpdateHtml();
                    localStorage.setItem('isLatestVersion', 'true');
                    isLatestVersion = true;
                    enableUpdateBtns();
                } else if (getUpdateStatus() === "failure") {
                    updatingInfoElement.innerHTML = i18n(updateFailure_i18n);
                    disableUpdateBtn_enableCancelBtn();
                } else if (getUpdateStatus() != "") {
                    updatingInfoElement.innerText = getUpdateStatus();
                    enableUpdateBtns();
                }
                updateStatus.parentNode.removeChild(updateStatus);
                if (updateSpinner) updateSpinner.stop();
            }
        }
    }
});

var showingUpdateInfo = false;
async function getLatestRelease() {
    try {
        const response = await fetch('https://api.github.com/repos/gaizhenbiao/chuanhuchatgpt/releases/latest');
        if (!response.ok) {
            console.log(`Error: ${response.status} - ${response.statusText}`);
            updateInfoGotten = true;
            return null;
        }
        const data = await response.json();
        updateInfoGotten = true;
        return data;
    } catch (error) {
        console.log(`Error: ${error}`);
        updateInfoGotten = true;
        return null;
    }
}

var releaseNoteElement = document.getElementById('release-note-content');
var updatingInfoElement = document.getElementById('updating-info');
async function updateLatestVersion() {
    const currentVersionElement = document.getElementById('current-version');
    const reVersion = /<a[^>]*>([^<]*)<\/a>/g;
    const versionMatch = reVersion.exec(currentVersionElement.innerHTML);
    const currentVersion = (versionMatch && versionMatch[1].length == 8) ? versionMatch[1] : null;
    const latestVersionElement = document.getElementById('latest-version-title');
    const versionInfoElement = document.getElementById('version-info-title');
    releaseNoteElement = document.getElementById('release-note-content');
    updatingInfoElement = document.getElementById('updating-info');
    
    const versionTime = document.getElementById('version-time').innerText;
    const localVersionTime = versionTime !== "unknown" ? (new Date(versionTime)).getTime() : 0;
    updateInfoGotten = true; //无论成功与否都只执行一次,否则容易api超限...
    try {
        const data = await getLatestRelease();
        const releaseNote = data.body;
        if (releaseNote) {
            releaseNoteElement.innerHTML = marked.parse(releaseNote, {mangle: false, headerIds: false});
        }
        const latestVersion = data.tag_name;
        if (currentVersion) {
            if (latestVersion <= currentVersion) {
                noUpdate();
            } else {
                latestVersionElement.textContent = latestVersion;
                console.log(`New version ${latestVersion} found!`);
                if (!isInIframe) openUpdateToast();
            }
        } else { //如果当前版本号获取失败,使用时间比较
            const latestVersionTime = (new Date(data.created_at)).getTime();
            if (latestVersionTime) {
                const latestVersionInfo = `<a href="https://github.com/gaizhenbiao/chuanhuchatgpt/releases/latest" target="_blank" id="latest-version-title" style="text-decoration: none;">${latestVersion}</a>`
                const manualUpdateInfo = `<a href="https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/使用教程#手动更新" target="_blanks" style="text-decoration: none;">manual update</a>`
                if (localVersionTime == 0) {
                    const infoMessage = `Local version check failed. \nBut latest revision is ${latestVersionInfo}. \n\nWhen Update needed, \n- If you are using Docker, try to update package. \n- If you didn't use git, try ${manualUpdateInfo}.`
                    versionInfoElement.innerHTML = marked.parse(infoMessage, {mangle: false, headerIds: false});
                    console.log(`New version ${latestVersion} found!`);
                    disableUpdateBtn_enableCancelBtn();
                } else if (localVersionTime < latestVersionTime) {
                    const infoMessage = `Local version check failed, it seems to be a local rivision. \n\nBut latest revision is ${latestVersionInfo}. Try ${manualUpdateInfo}.`
                    versionInfoElement.innerHTML = marked.parse(infoMessage, {mangle: false, headerIds: false});
                    console.log(`New version ${latestVersion} found!`);
                    disableUpdateBtn_enableCancelBtn();
                    // if (!isInIframe) openUpdateToast();
                } else {
                    noUpdate("Local version check failed, it seems to be a local rivision. <br>But your revision is newer than the latest release.");
                }
            }
        }
        currentTime = new Date().getTime();
        localStorage.setItem('lastCheckTime', currentTime);
    } catch (error) {
        console.error(error);
    }
}

function getUpdateInfo() {
    window.open('https://github.com/gaizhenbiao/chuanhuchatgpt/releases/latest', '_blank');
    closeUpdateToast();
}

var updateSpinner = null;

function bgUpdateChuanhu() {
    updateChuanhuBtn.click();
    updatingInfoElement.innerText = i18n(updatingMsg_i18n);
    var updatingSpinner = document.getElementById('updating-spinner');
    try {
        updateSpinner = new Spin.Spinner({color:'#06AE56',top:'45%',lines:9}).spin(updatingSpinner);
    } catch (error) {
        console.error("Can't create spinner")
    }
    updatingInfoElement.classList.remove('hideK');
    disableUpdateBtns();
    const releaseNoteWrap = document.getElementById('release-note-wrap');
    releaseNoteWrap.style.setProperty('display', 'none');
    statusObserver.observe(statusDisplay, { childList: true, subtree: true, characterData: true});
}
function cancelUpdate() {
    closeUpdateToast();
}
function openUpdateToast() {
    showingUpdateInfo = true;
    setUpdateWindowHeight();
}
function closeUpdateToast() {
    updateToast.style.setProperty('top', '-500px');
    showingUpdateInfo = false;
    if (updatingInfoElement.classList.contains('hideK') === false) {
        updatingInfoElement.classList.add('hideK');
    }
}
function manualCheckUpdate() {
    openUpdateToast();
    updateLatestVersion();
    currentTime = new Date().getTime();
    localStorage.setItem('lastCheckTime', currentTime);
}
function noUpdate(message="") {
    localStorage.setItem('isLatestVersion', 'true');
    isLatestVersion = true;
    noUpdateHtml(message);
}
function noUpdateHtml(message="") {
    const versionInfoElement = document.getElementById('version-info-title');
    const gotoUpdateBtn = document.getElementById('goto-update-btn');
    const closeUpdateBtn = document.getElementById('close-update-btn');
    const releaseNoteWrap = document.getElementById('release-note-wrap');
    releaseNoteWrap.style.setProperty('display', 'none');
    if (message === "") {
        versionInfoElement.textContent = i18n(usingLatest_i18n)
    } else {
        versionInfoElement.innerHTML = message;
    }
    gotoUpdateBtn.classList.add('hideK');
    closeUpdateBtn.classList.remove('hideK');
}

var updateStatus = null;
function getUpdateStatus() {
    updateStatus = statusDisplay.querySelector("#update-status");
    if (updateStatus) {
        return updateStatus.innerText;
    } else {
        return "unknown";
    }
}

function disableUpdateBtns() {
    const updatesButtons = document.querySelectorAll('.btn-update');
    updatesButtons.forEach( function (btn) {
        btn.disabled = true;
    });
}
function enableUpdateBtns() {
    const updatesButtons = document.querySelectorAll('.btn-update');
    updatesButtons.forEach( function (btn) {
        btn.disabled = false;
    });
}
function disableUpdateBtn_enableCancelBtn() {
    document.querySelector('#update-button.btn-update').disabled = true;
    document.querySelector('#cancel-button.btn-update').disabled = false;
}

function setUpdateWindowHeight() {
    if (!showingUpdateInfo) {return;}
    const scrollPosition = window.scrollY;
    // const originalTop = updateToast.style.getPropertyValue('top');
    const resultTop = scrollPosition - 20 + 'px';
    updateToast.style.setProperty('top', resultTop);
}