Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save XYShaoKang/292c3eefe00e392b28350f34d336fe55 to your computer and use it in GitHub Desktop.
Save XYShaoKang/292c3eefe00e392b28350f34d336fe55 to your computer and use it in GitHub Desktop.
将力扣已解决的题目添加到收藏夹.md

一键将力扣已解决的题目添加到收藏夹

复制下面的代码,打开力扣,按 F12 打开控制台,粘贴代码回车

可以修改 temp123456 为自己想要的收藏夹名字

{
  const favoriteName='temp123456'
  const PAGE_SIZE = 50
  function getQuestions(page) {
    return fetch('https://leetcode-cn.com/graphql/', {
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        query: `
        query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {
          problemsetQuestionList( categorySlug: $categorySlug limit: $limit skip: $skip filters: $filters ) {
            hasMore
            total
            questions {
              acRate
              difficulty
              freqBar
              frontendQuestionId
              isFavor
              paidOnly
              solutionNum
              status
              title
              titleCn
              titleSlug
              topicTags {
                name
                nameTranslated
                id
                slug
              }
              extra {
                hasVideoSolution
                topCompanyTags {
                  imgUrl
                  slug
                  numSubscribed
                }
              }
            }
          }
        }
        `,
        variables: {
          categorySlug: '',
          skip: page * PAGE_SIZE,
          limit: PAGE_SIZE,
          filters: { status: 'AC' },
        },
      }),
      method: 'POST',
      mode: 'cors',
      credentials: 'include',
    })
      .then((res) => res.json())
      .then(({ data }) => data.problemsetQuestionList.questions)
  }
  async function getallQuestions() {
    var graphql = JSON.stringify({
      query: `query allQuestions {
                allQuestionsBeta {
                  ...questionSummaryFields
                  __typename
                }
              }
              fragment questionSummaryFields on QuestionNode {
                titleSlug
                questionId
                questionFrontendId
                __typename
              }
      `,
      operationName: 'allQuestions',
      variables: {},
    })

    var option = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: graphql,
    }

    const res = await fetch('https://leetcode-cn.com/graphql/', option).then(
      (res) => res.json()
    )
    return res.data.allQuestionsBeta
  }
  function favorite(favoriteId, questionIds) {
    return fetch('https://leetcode-cn.com/graphql/', {
      headers: {
        'content-type': 'application/json',
      },
      referrerPolicy: 'strict-origin-when-cross-origin',
      body: JSON.stringify({
        query: `mutation addQuestionToFavorite {${questionIds
          .map(
            (
              questionId,
              i
            ) => `add${i}: addQuestionToFavorite(favoriteIdHash: "${favoriteId}", questionId: "${questionId}") {
                    questionId
                    __typename
                  }`
          )
          .join('\n')}}`,
        operationName: 'addQuestionToFavorite',
        variables: { favoriteIdHash: 'gErHDFQH', questionId: '132' },
      }),
      method: 'POST',
      mode: 'cors',
      credentials: 'include',
    }).then((res) => res.json())
  }

  function getFavoriteList() {
    return fetch('https://leetcode-cn.com/graphql/', {
      headers: {
        'content-type': 'application/json',
      },
      referrerPolicy: 'strict-origin-when-cross-origin',
      body: '{"operationName":"allFavorites","variables":{},"query":"query allFavorites {\\n  favoritesLists {\\n    allFavorites {\\n      idHash\\n      name\\n      isPublicFavorite\\n      questions {\\n        questionId\\n        __typename\\n      }\\n      __typename\\n    }\\n    officialFavorites {\\n      idHash\\n      name\\n      questions {\\n        questionId\\n        __typename\\n      }\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n"}',
      method: 'POST',
      mode: 'cors',
      credentials: 'include',
    })
      .then((res) => res.json())
      .then(({ data }) => data.favoritesLists.allFavorites)
  }
  function sleep(time) {
    return new Promise(function (resolve, reject) {
      setTimeout(resolve, time)
    })
  }
  function createFavorite(favoriteName) {
    return fetch('https://leetcode-cn.com/graphql/', {
      headers: {
        'content-type': 'application/json',
      },
      referrerPolicy: 'strict-origin-when-cross-origin',
      body: `{"operationName":"addQuestionToNewFavorite","variables":{"questionId":"1","isPublicFavorite":false,"name":"${favoriteName}"},"query":"mutation addQuestionToNewFavorite($name: String!, $isPublicFavorite: Boolean!, $questionId: String!) {\\n  addQuestionToNewFavorite(name: $name, isPublicFavorite: $isPublicFavorite, questionId: $questionId) {\\n    ok\\n    error\\n    name\\n    isPublicFavorite\\n    favoriteIdHash\\n    questionId\\n    __typename\\n  }\\n}\\n"}`,
      method: 'POST',
      mode: 'cors',
      credentials: 'include',
    })
      .then((res) => res.json())
      .then(({ data }) => data.addQuestionToNewFavorite.favoriteIdHash)
  }
  const allQuestionIds = (await getallQuestions()).reduce(
    (o, { questionFrontendId, questionId }) =>
      Object.assign(o, { [questionFrontendId]: questionId }),
    {}
  )
  let favoriteId
  async function favoriteAC(favoriteName, page = 0) {
    const questions = await getQuestions(page)

    const ids = questions.map((q) => allQuestionIds[q.frontendQuestionId])
    if (!favoriteId) {
      const favoriteList = await getFavoriteList()
      favoriteId = favoriteList.find(
        ({ name }) => name === favoriteName
      )?.idHash
      if (!favoriteId) {
        favoriteId = await createFavorite(favoriteName)
      }
    }

    await favorite(favoriteId, ids)
    if (questions.length === PAGE_SIZE) {
      await sleep(500)
      return favoriteAC(favoriteName, page + 1)
    }
  }

  void (function () {
    favoriteAC(favoriteName)
  })()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment