webdriver | Cell 12 | Cell 14 | Search

This code imports necessary modules, sets variables, and defines two primary functions: addPlugins and verifySession. The addPlugins function attaches event listeners to a client object and locks/unlocks promises to update or add session data, while the verifySession function verifies a session by setting the session ID, adding plugins, and interacting with the client object's promise chain.

Cell 13

var importer = require('../Core');
var {
    updateOrAddSession,
    lockPromise
} = importer.import("update session");

var TIMEOUT = 10000;
var scanning = false;

var sessions = [];

var first = false;
function addPlugins(client) {
    if(!first) {
        first = true;
        client.on('result', (result) => {
            if(scanning) {
                return;
            }
            const currentSession = client.sessionId;
            const updateSession = sessions.filter(s => s[1] === currentSession)[0];

            // only update the session often enough that it isn't reused by another process
            if(typeof updateSession !== 'undefined') {
                if((new Date()).getTime() - updateSession[0] <= TIMEOUT / 2) {
                    return;
                }
            }

            return lockPromise(true)
                .then(() => updateOrAddSession(currentSession))
                .then(s => (sessions = s))
                .then(() => lockPromise(false))
                .catch(e => console.log(e));
        });
    }
}

function verifySession(client, session) {
    client.sessionId = session[1];
    var alreadyScanning = false;
    addPlugins(client);
    alreadyScanning = scanning;
    scanning = true
    return client.getWindowHandle()
        .then(r => client.switchToWindow(r))
        .then(() => client.status())
        .then(s => session[1])
        .catch(e => {
            scanning = false || alreadyScanning;
            if(e.message === 'ESOCKETTIMEDOUT' || e.message.includes('no such session') || e.message.includes('chrome not reachable')) {
                console.log('unusable session ' + session);
                session[1] = '';
                return;
            } else {
                console.log('error ' + session[1]);
                console.log(e)
                throw e;
            }
            // if the session is really old and has an error delete it from the list
            //const index = sessions.map(s => s[1]).indexOf(session[1]);
            //sessions[index][1] = null;
        })
        .then(r => {
            scanning = false || alreadyScanning;
            return r;
        })
}

module.exports = {
    lockPromise, verifySession, updateOrAddSession, scanning
};

What the code could have been:

const core = require('../Core');

const { updateOrAddSession, lockPromise } = core.import('update session');

const TIMEOUT = 10000;

let isScanning = false;
const sessions = [];

module.exports = {
  lockPromise,
  verifySession,
  updateOrAddSession,
  getIsScanning() {
    return isScanning;
  }
};

function addPlugins(client) {
  return new Promise((resolve) => {
    if (!sessions.length) {
      client.on('result', (result) => {
        if (isScanning) {
          resolve();
          return;
        }
        const currentSession = client.sessionId;
        const updateSession = sessions.find((s) => s[1] === currentSession);

        if (updateSession && (new Date()).getTime() - updateSession[0] <= TIMEOUT / 2) {
          resolve();
          return;
        }

        lockPromise(true)
         .then(() => updateOrAddSession(currentSession))
         .then((sessions) => (this.sessions = sessions))
         .then(() => lockPromise(false))
         .then(resolve)
         .catch((e) => console.log(e));
      });
    } else {
      resolve();
    }
  });
}

async function verifySession(client, session) {
  try {
    client.sessionId = session[1];
    await addPlugins(client);
    const windowHandle = await client.getWindowHandle();
    await client.switchToWindow(windowHandle);
    await client.status();
    return session[1];
  } catch (e) {
    if (
      e.message === 'ESOCKETTIMEDOUT' ||
      e.message.includes('no such session') ||
      e.message.includes('chrome not reachable')
    ) {
      console.log(`unusable session ${session}`);
      session[1] = '';
      return;
    } else {
      console.log(`error ${session[1]}`);
      console.log(e);
      throw e;
    }
  } finally {
    isScanning = false;
  }
}

Code Breakdown

Variables and Function Imports

addPlugins Function

verifySession Function