Bl4Cc4t / GoodTwitter2

Userscript to modify the looks of twitter.com
496 stars 63 forks source link

Fixing getInfo()'s regex for name #532

Closed 9c23a5 closed 1 year ago

9c23a5 commented 1 year ago

Modified L120 removing (?:true|false) in the regex, since the previous text on my own infoScript is "media_count":xxx,.

This fixes screen_name showing on the left-side user profile panel, instead of the actual name. Tested this on my own account, I don't know if infoScript heavily changes through accounts though.

Bl4Cc4t commented 1 year ago

Thank you for your contribution! That is one issue I never saw myself before, since both my screen_name and name is exactly the same :/

In general it is a bad idea to use regex on that JSON here. The order of the fields can always change... errors of the past :D The reason the (?:true|false) was there was because previously, some people had their nearest city show up as their name - because there is also a "name" field with timezone information in that text.

If you don't mind, could you please test if the following also works for you? Just replace the current getInfo function with it :)

  // get account information
  let info = null
  function getInfo() {
    if (info)
      return info

    let user = null
    try {
      for (let e of Array.from(document.querySelectorAll("#react-root ~ script"))) {
        if (e.textContent.includes("__INITIAL_STATE__")) {
          let match = e.textContent.match(/__INITIAL_STATE__=(\{.*?\});window/)
          if (match) {
            let initialState = JSON.parse(match[1])
            user = Object.values(initialState?.entities?.users?.entities)[0] ?? null
          }
          break
        }
      }
    } catch (e) {
      console.error(e)
    }

    if (user) {
      info = {
        bannerUrl: user.profile_banner_url,
        avatarUrl: user.profile_image_url_https,
        screenName: user.screen_name,
        name: user.name,
        id: user.id_str,
        stats: {
          tweets: user.statuses_count,
          followers: user.followers_count,
          following: user.friends_count
        }
      }
      console.log("user info", info)
    } else {
      console.error("match of __INITIAL_STATE__ unsuccessful, falling back to default values")
      info = {
        bannerUrl: "",
        avatarUrl: defaultAvatarUrl,
        screenName: "youarenotloggedin",
        name: "Anonymous",
        id: "0",
        stats: {
          tweets: 0,
          followers: 0,
          following: 0
        }
      }
    }

    return info
  }
Bl4Cc4t commented 1 year ago

Great, I'll close this then. Thanks for spotting this!