微博终结者

10/29/2022, 10:24:16 PM

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name        微博终结者
// @namespace   Violentmonkey Scripts
// @match       https://weibo.com/u/*
// @grant       GM_registerMenuCommand
// @version     1.0
// @author      -
// @description 10/29/2022, 10:24:16 PM
// ==/UserScript==

const uid = window.location.pathname.split('/')[2];

GM_registerMenuCommand('删除所有微博', async () => {
  const allWeibo = await loadAllWeibo();
  const toDelete = allWeibo;
  const total = toDelete.length;
  let done = 0;
  await Promise.all(toDelete.map(async ({ id }) => {
    await deleteWeibo(id);
    console.log(`Delete weibo: ${++done}/${total}`);
  }));
});

function getCookies() {
  return document.cookie.split('; ').map(item => item.split('=')).reduce((prev, [key, value]) => { prev[key] = value; return prev; }, {});
}

async function deleteWeibo(id) {
  const resp = await fetch('https://weibo.com/ajax/statuses/destroy', {
    method: 'POST',
    headers: {
      accept: 'application/json',
      'content-type': 'application/json',
      'x-xsrf-token': getCookies()['XSRF-TOKEN'],
    },
    body: JSON.stringify({ id }),
  });
  const data = await resp.json();
  if (!resp.ok) throw { resp, data };
  return data;
}

async function loadWeiboByPage(page) {
  const resp = await fetch(`https://weibo.com/ajax/statuses/mymblog?uid=${uid}&page=${page}&feature=0`);
  const data = await resp.json();
  if (!resp.ok) throw { resp, data };
  return data.data;
}

function loadAllWeibo() {
  return new Promise((resolve, reject) => {
    let page = 0;
    let pageSize = 1;
    let totalPages = 1;
    let done = 0;
    let processing = 0;
    const result = [];
    const loadPage = async page => {
      const { list, total } = await loadWeiboByPage(page);
      if (list.length) {
        result[page] = list;
        pageSize = Math.max(pageSize, list.length);
        totalPages = Math.ceil(total / pageSize);
        console.log(`Loaded: ${++done}/${totalPages}`);
      }
      processing -= 1;
      check();
    };
    const check = () => {
      while (page < totalPages) {
        processing += 1;
        loadPage(++page).catch(reject);
      }
      if (!processing) resolve(result.flat());
    };
    check();
  });
}