Sixth sense of Facebook

    Chrome extension shows when someone types




    Some people spend too much time on social networks. So much that they are already addicted. One of them is programmer Alexander Kirszenberg, who also likes to delve into the insides of Facebook - in the JavaScript code responsible for the user interface and communications.

    “A couple of months ago, I thought about a small status indicator that shows when one of your friends is typing for you, Alexander writes . - Such a small extension of the UI gives a lot of information about the interlocutor. If the indicator lights up and goes out several times, this indicates indecision. If he caught fire for a long time, someone writes you a great essay. And there is nothing worse than that excruciating feeling when the indicator goes out and no longer lights up. "

    First of all, Alexander decided to find if Facebook sends notifications that someone is typing messages in Facebook Messenger, even if you do not have this Facebook Messenger running. It turned out that he was sending.

    The event of typ"long polling" /pull(long polling) is sent to all friends . A small study showed that the event is indeed sent out for each chat , even if the recipient did not open it and never received it.

    This is how the Sixth Sense Facebook extension for the Chrome browser came about . It shows right in the browser when someone types in a Facebook post.



    The programmer used the undocumented Facebook APIs to create this extension. I had to deal with JavaScript code, which Facebook ruthlessly minifies, turning into a jumble of characters.

    First, he found out which modules Facebook imports through the Asynchronous Module Definition module organization system for asynchronous loading (Facebook has its own AMD implementation). Modules and dependencies are defined by the standard function __d(name, dependencies, factory). There is also require, and requireLazyto import modules.

    The easiest way to see how this works is in the browser console (although Facebook strictly prohibits doing so). It seems that serious guys work there, it’s better not to joke with them.



    But we still dare.



    As you can see, Facebook always downloads the latest version of React - an excellent library of user interface components. Facebook uses React fairly heavily throughout the site. There are over 15,000 React components in the Facebook code (as of October 2015).

    In the source code, you can search __d(and see the list of modules available for import. For the main page there are only 3,000 modules.

    Facebook Messenger, of course, also uses React components. We need to intercept typing notifications. For a more detailed study of the code, Alexander Kirzenberg recommends using the React Developer Tools .





    After installing this extension, a new React tab appears in the Chrome Developer Tools. We select chat on it.



    Here, among the various components of Facebook Messenger, we are looking for a typing indicator, it is between and .

    A search __d('ChatTypingin the React codebase finds two modules: ChatTypingIndicator.react.jsand ChatTypingIndicators.react.js. This is exactly what we need, writes Kirzenberg. He notices that some modules are loaded as needed, so that ChatTypingIndicators.react.jsit can only be detected the second time.

    Here is his code.

    function() {
      var k = c('MercuryThreadInformer').getForFBID(this.props.viewer)
        , l = c('MercuryTypingReceiver').getForFBID(this.props.viewer);
      this._subscriptions = new (c('SubscriptionsHandler'))();
      this._subscriptions.addSubscriptions(
        l.addRetroactiveListener(
          'state-changed',
          this.typingStateChanged
        ),
        k.subscribe(
          'messages-received',
          this.messagesReceived
        )
      );
    },

    Namely, we are interested in the challenge c('MercuryTypingReceiver').

    In the console, you can see how it works.

    > MercuryTypingReceiver.getForFBID
    // function (i){var j=this._getInstances();if(!j[i])j[i]=new this(i);return j[i];}
    > MercuryTypingReceiver.get
    // function (){return this.getForFBID(c('CurrentUser').getID());}

    To check how the status indicator works, Alexander used the Messenger application on his own smartphone to send the corresponding events to his PC and catch them in the console.

    Having studied the code in more detail, he found two more useful modules, MercuryThreadsand ShortProfiles. The first one gets all the information about the Messenger thread by its identifier, the second does the same for the profile.

    In general, after all the research, here's what the final extension code for Chrome looks like, just 40 lines.

    function getUserId(fbid) {
      return fbid.split(':')[1];
    }
    requireLazy(
      ['MercuryTypingReceiver', 'MercuryThreads', 'ShortProfiles'],
      (MercuryTypingReceiver, MercuryThreads, ShortProfiles) => {
        MercuryTypingReceiver
          .get()
          .addRetroactiveListener('state-changed', onStateChanged);
        // Called every time a user starts or stops typing in a thread
        function onStateChanged(state) {
          // State is a dictionary that maps thread ids to the list of the
          // currently typing users ids'
          const threadIds = Object.keys(state);
          // Walk through all threads in order to retrieve a list of all
          // user ids
          const userIds = threadIds.reduce(
            (res, threadId) => res.concat(state[threadId].map(getUserId)),
            []
          );
          MercuryThreads.get().getMultiThreadMeta(threadIds, threads => {
            ShortProfiles.getMulti(userIds, users => {
              // Now that we've retrieved all the information we need
              // about the threads and the users, we send it to the
              // Chrome application to process and display it to the user.
              window.postMessage({
                type: 'update',
                threads,
                users,
                state,
              }, '*');
            });
          });
        }
      }
    );

    A good hack that slightly reveals the insides of Facebook.

    The source code for the extension is published on Github .

    By the way, according to the time stamps from the Facebook messenger, you can even track the sleep mode of your friends ( source code ).


    Also popular now: