<commit_before>/**
 *
 * wechaty: Wechat for Bot. and for human who talk to bot/robot
 *
 * Class PuppetWeb Events
 *
 * use to control wechat in web browser.
 *
 * Licenst: ISC
 * https://github.com/zixia/wechaty
 *
 */

/**************************************
 *
 * Events for Class PuppetWeb
 * 
 * here `this` is a PuppetWeb Instance
 *
 ***************************************/
const util  = require('util')
const fs    = require('fs')
const co    = require('co')

const log = require('../brolog-env')
const Contact = require('../contact')
const Message = require('../message')
const MediaMessage = require('../message-media')

const PuppetWebEvent = {
  onBrowserDead

  , onServerLogin
  , onServerLogout

  , onServerConnection
  , onServerDisconnect

  , onServerDing
  , onServerScan
  , onServerUnload
  , onServerLog

  , onServerMessage
}

function onBrowserDead(e) {
  log.verbose('PuppetWebEvent', 'onBrowserDead(%s)', e && e.message || e)
  // because this function is async, so maybe entry more than one times.
  // guard by variable: isBrowserBirthing to prevent the 2nd time entrance.
  if (this.isBrowserBirthing) {
    log.warn('PuppetWebEvent', 'onBrowserDead() is busy, this call will return now. stack: %s', (new Error()).stack)
    return
  }

  this.scan = null
  
  return co.call(this, function* () {
    log.verbose('PuppetWebEvent', 'onBrowserDead() co() set isBrowserBirthing true')
    this.isBrowserBirthing = true

    const TIMEOUT = 180000 // 180s / 3m
    // this.watchDog(`onBrowserDead() set a timeout of ${Math.floor(TIMEOUT / 1000)} seconds to prevent unknown state change`, {timeout: TIMEOUT})
    this.emit('watchdog', {
      data: `onBrowserDead() set a timeout of ${Math.floor(TIMEOUT / 1000)} seconds to prevent unknown state change`
      , timeout: TIMEOUT
    })

    if (!this.browser || !this.bridge) {
      const e = new Error('no browser or no bridge') 
      log.error('PuppetWebEvent', 'onBrowserDead() %s', e.message)
      throw e
    }

    log.verbose('PuppetWebEvent', 'onBrowserDead() try to reborn browser')

    yield this.browser.quit()
                      .catch(e => { // fail safe
                        log.warn('PuppetWebEvent', 'browser.quit() exception: %s', e.message)
                      })
    log.verbose('PuppetWebEvent', 'onBrowserDead() old browser quited')

    this.browser = yield this.initBrowser()
    log.verbose('PuppetWebEvent', 'onBrowserDead() new browser inited')

    // this.bridge = yield this.bridge.init()
    this.bridge = yield this.initBridge()
    log.verbose('PuppetWebEvent', 'onBrowserDead() bridge re-inited')

    const dong = yield this.ding()
    if (/dong/i.test(dong)) {
      log.verbose('PuppetWebEvent', 'onBrowserDead() ding() works well after reset')
    } else {
      log.warn('PuppetWebEvent', 'onBrowserDead() ding() get error return after reset: ' + dong)
    }
  })
  .catch(e => { // Exception
    log.error('PuppetWebEvent', 'onBrowserDead() exception: %s', e.message)

    log.warn('PuppetWebEvent', 'onBrowserDead() try to re-init PuppetWeb itself')
    return this.quit()
              .catch(e => log.warn('PuppetWebEvent', 'onBrowserDead() fail safe for this.quit(): %s', e.message))
              .then(_ => this.init())
  })
  .then(() => { // Finally
    log.verbose('PuppetWebEvent', 'onBrowserDead() new browser borned')
    this.isBrowserBirthing = false

    this.emit('watchdog', {
      data: `onBrowserDead() new browser borned`<commit_msg>use targetState instead of isBirthing<commit_after>/**
 *
 * wechaty: Wechat for Bot. and for human who talk to bot/robot
 *
 * Class PuppetWeb Events
 *
 * use to control wechat in web browser.
 *
 * Licenst: ISC
 * https://github.com/zixia/wechaty
 *
 */

/**************************************
 *
 * Events for Class PuppetWeb
 * 
 * here `this` is a PuppetWeb Instance
 *
 ***************************************/
const util  = require('util')
const fs    = require('fs')
const co    = require('co')

const log = require('../brolog-env')
const Contact = require('../contact')
const Message = require('../message')
const MediaMessage = require('../message-media')

const PuppetWebEvent = {
  onBrowserDead

  , onServerLogin
  , onServerLogout

  , onServerConnection
  , onServerDisconnect

  , onServerDing
  , onServerScan
  , onServerUnload
  , onServerLog

  , onServerMessage
}

function onBrowserDead(e) {
  log.verbose('PuppetWebEvent', 'onBrowserDead(%s)', e && e.message || e)
  // because this function is async, so maybe entry more than one times.
  // guard by variable: isBrowserBirthing to prevent the 2nd time entrance.
  // if (this.isBrowserBirthing) {
  //   log.warn('PuppetWebEvent', 'onBrowserDead() is busy, this call will return now. stack: %s', (new Error()).stack)
  //   return
  // }

  if (this.browser && this.browser.targetState() !== 'open') {
    log.verbose('PuppetWebEvent', 'onBrowserDead() will do nothing because browser.targetState !== open')
    return
  }

  if (this.browser && this.browser.currentState() === 'opening') {
    log.warn('PuppetWebEvent', 'onBrowserDead() will do nothing because browser.currentState = opening. stack: %s', (new Error()).stack)
    return
  }

  this.scan = null
  
  return co.call(this, function* () {
    // log.verbose('PuppetWebEvent', 'onBrowserDead() co() set isBrowserBirthing true')
    // this.isBrowserBirthing = true

    const TIMEOUT = 180000 // 180s / 3m
    // this.watchDog(`onBrowserDead() set a timeout of ${Math.floor(TIMEOUT / 1000)} seconds to prevent unknown state change`, {timeout: TIMEOUT})
    this.emit('watchdog', {
      data: `onBrowserDead() set a timeout of ${Math.floor(TIMEOUT / 1000)} seconds to prevent unknown state change`
      , timeout: TIMEOUT
    })

    if (!this.browser || !this.bridge) {
      const e = new Error('no browser or no bridge') 
      log.error('PuppetWebEvent', 'onBrowserDead() %s', e.message)
      throw e
    }

    log.verbose('PuppetWebEvent', 'onBrowserDead() try to reborn browser')

    yield this.browser.quit()
                      .catch(e => { // fail safe
                        log.warn('PuppetWebEvent', 'browser.quit() exception: %s, %s', e.message, e.stack)
                      })
    log.verbose('PuppetWebEvent', 'onBrowserDead() old browser quited')

    if (this.browser.targetState() !== 'open') {
      log.warn('PuppetWebEvent', 'onBrowserDead() will not init browser because browser.targetState !== open')
      return
    }

    this.browser = yield this.initBrowser()
    log.verbose('PuppetWebEvent', 'onBrowserDead() new browser inited')

    // this.bridge = yield this.bridge.init()
    this.bridge = yield this.initBridge()
    log.verbose('PuppetWebEvent', 'onBrowserDead() bridge re-inited')

    const dong = yield this.ding()
    if (/dong/i.test(dong)) {
      log.verbose('PuppetWebEvent', 'onBrowserDead() ding() works well after reset')
    } else {
      log.warn('PuppetWebEvent', 'onBrowserDead() ding() get error return after reset: ' + dong)
    }
  })
  .catch(e => { // Exception
    log.error('PuppetWebEvent', 'onBrowserDead() exception: %s', e.message)

    log.warn('PuppetWebEvent', 'onBrowserDead() try to re-init PuppetWeb itself')
    return this.quit()
              .catch(e => log.warn('PuppetWebEvent', 'onBrowserDead() fail safe for this.quit(): %s', e.message))
              .then(_ => this.init())
  })
  .then(() => { // Finally
    log.verbose('PuppetWebEvent', 'onBrowserDead() new browser borned')
    // this.isBrowserBirthing = false

    this.emit('watchdog', {
      data: `onBrowserDead() new browser borned`
{'fraction_non_alphanumeric': 0.16064151439463653, 'fraction_numerical': 0.004995398974628631, 'mean_word_length': 3.2479061976549413, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7425916', 'n_tokens_mistral': 2437, 'n_tokens_neox': 2327, 'n_words': 616}