thomasauirer / New Userscript

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      2025-12-25
// @description  try to take over the world!
// @author       You
// @match        http://zscx.sgbaodian.com/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=sgbaodian.com
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @license      MIT
// ==/UserScript==

(function () {
  'use strict';

  /* ================== 配置区 ================== */

  const API_URL = 'https://sg.8658340.xyz/api/redis/random-savedata';

  const STORAGE_KEY = 'saveData';
  const SYNC_FLAG = 'last_sync_ts';

  const USER_KEY = 'redis_username';
  const PASS_KEY = 'redis_password';

  const SYNC_INTERVAL = 60; // 秒

  /* ================== 菜单配置 ================== */

  GM_registerMenuCommand('⚙ 设置账号密码', () => {
    const u = prompt('请输入账号:', GM_getValue(USER_KEY, ''));
    const p = prompt('请输入密码:', GM_getValue(PASS_KEY, ''));

    if (!u || !p) {
      alert('账号或密码不能为空');
      return;
    }

    GM_setValue(USER_KEY, u);
    GM_setValue(PASS_KEY, p);

    alert('✅ 保存成功,刷新页面后生效');
  });

  /* ================== 主逻辑 ================== */

  const username = GM_getValue(USER_KEY, '');
  const password = GM_getValue(PASS_KEY, '');

  if (!username || !password) {
    console.warn('未配置账号密码,脚本未执行');
    return;
  }

  const nowTs = Math.floor(Date.now() / 1000);
  const lastSync = localStorage.getItem(SYNC_FLAG);

  if (lastSync && (nowTs - parseInt(lastSync, 10) < SYNC_INTERVAL)) {
    console.log('⏭ 数据刚刚同步过,跳过请求');
    return;
  }

  GM_xmlhttpRequest({
    method: 'POST',
    url: API_URL,
    headers: {
      'Content-Type': 'application/json'
    },
    data: JSON.stringify({
      username,
      password
    }),
    onload: function (response) {
      try {
        const serverResponse = JSON.parse(response.responseText);

        if (serverResponse.code === 200 && serverResponse.data) {

          // 验证 data 是否为合法 JSON
          JSON.parse(serverResponse.data);

          localStorage.setItem(STORAGE_KEY, serverResponse.data);
          localStorage.setItem(SYNC_FLAG, nowTs.toString());

          console.log('✅ 成功从 Redis 同步 SaveData,刷新页面中…');
          setTimeout(() => location.reload(), 500);

        }
        else {
          console.error('❌ 服务器返回错误:', serverResponse.message);
        }
      }
      catch (e) {
        console.error('❌ 解析服务器数据失败', e);
      }
    },
    onerror: function (err) {
      console.error('❌ 网络请求失败', err);
    }
  });

})();