<commit_before>const express = require('express')
const nmd = require('nano-markdown')
const _ = require('lodash/fp')

const router = express.Router()

const complianceTriggers = require('../compliance-triggers')
const configManager = require('../new-config-manager')
const plugins = require('../plugins')
const semver = require('semver')
const state = require('../middlewares/state')
const version = require('../../package.json').version
const customRequestQueries = require('../new-admin/services/customInfoRequests')

const urlsToPing = [
  `us.archive.ubuntu.com`,
  `uk.archive.ubuntu.com`,
  `za.archive.ubuntu.com`,
  `cn.archive.ubuntu.com`
]

const speedtestFiles = [
  {
    url: 'https://github.com/lamassu/speed-test-assets/raw/main/python-defaults_2.7.18-3.tar.gz',
    size: 44668
  }
]

function checkHasLightning (settings) {
  return configManager.getWalletSettings('BTC', settings.config).layer2 !== 'no-layer2'
}

const createTerms = terms => (terms.active && terms.text) ? ({
  active: terms.active,
  title: terms.title,
  text: nmd(terms.text),
  accept: terms.acceptButtonText,
  cancel: terms.cancelButtonText
}) : null

const buildTriggers = (allTriggers) => {
  const normalTriggers = []
  const customTriggers = _.filter(o => {
    if (_.isEmpty(o.customInfoRequestId) || _.isNil(o.customInfoRequestId)) normalTriggers.push(o)
    return !_.isNil(o.customInfoRequestId) && !_.isEmpty(o.customInfoRequestId)
  }, allTriggers)

  return _.flow([_.map(_.get('customInfoRequestId')), customRequestQueries.batchGetCustomInfoRequest])(customTriggers)
    .then(res => {
      res.forEach((details, index) => {
        // make sure we aren't attaching the details to the wrong trigger
        if (customTriggers[index].customInfoRequestId !== details.id) return
        customTriggers[index] = { ...customTriggers[index], customInfoRequest: details }
      })
      return [...normalTriggers, ...customTriggers]
    })
}

function poll (req, res, next) {
  const machineVersion = req.query.version
  const machineModel = req.query.model
  const deviceId = req.deviceId
  const deviceTime = req.deviceTime
  const pid = req.query.pid
  const settings = req.settings
  const operatorId = res.locals.operatorId
  const localeConfig = configManager.getLocale(deviceId, settings.config)
  const zeroConfLimits = _.reduce((acc, cryptoCode) => {
    acc[cryptoCode] = configManager.getWalletSettings(cryptoCode, settings.config).zeroConfLimit
    return acc
  }, {}, localeConfig.cryptoCurrencies)
  const pi = plugins(settings, deviceId)
  const hasLightning = checkHasLightning(settings)

  const triggersAutomationPromise = configManager.getTriggersAutomation(settings.config)
  const triggersPromise = buildTriggers(configManager.getTriggers(settings.config))

  const operatorInfo = configManager.getOperatorInfo(settings.config)
  const machineInfo = { deviceId: req.deviceId, deviceName: req.deviceName }
  const cashOutConfig = configManager.getCashOut(deviceId, settings.config)
  const receipt = configManager.getReceipt(settings.config)
  const terms = configManager.getTermsConditions(settings.config)
  const enablePaperWalletOnly = configManager.getCompliance(settings.config).enablePaperWalletOnly

  state.pids = _.update(operatorId, _.set(deviceId, { pid, ts: Date.now() }), state.pids)

  return Promise.all([pi.pollQueries(deviceTime, req.query, machineVersion, machineModel), triggersPromise, triggersAutomationPromise])
    .then(([results, triggers, triggersAutomation]) => {
      const reboot = pid && state.reboots?.[operatorId]?.[deviceId] === pid
      const shutdown = pid && state.shutdowns?.[operatorId]?.[deviceId] === pid
      const restartServices = pid && state.restartServicesMap?.[operatorId]?.[deviceId] === pid
      const langs = localeConfig.languages

      const locale = {
        fiatCode: localeConfig.fiatCurrency,
        localeInfo: {
          primaryLocale: langs[0],
          primaryLocales: langs,
          country: localeConfig.country
        }
      }

      const response = {
        error: null,
        locale,
        version,
        receiptPrintingActive: receipt.active,
        smsReceiptActive: receipt.sms,
        enablePaperWalletOnly,
        twoWayMode: cashOutConfig.active,
        zeroConfLimits,
        reboot,
        shutdown,
        restartServices,<commit_msg>refactor: inline variables and reformat promises<commit_after>const express = require('express')
const nmd = require('nano-markdown')
const _ = require('lodash/fp')

const router = express.Router()

const complianceTriggers = require('../compliance-triggers')
const configManager = require('../new-config-manager')
const plugins = require('../plugins')
const semver = require('semver')
const state = require('../middlewares/state')
const version = require('../../package.json').version
const customRequestQueries = require('../new-admin/services/customInfoRequests')

const urlsToPing = [
  `us.archive.ubuntu.com`,
  `uk.archive.ubuntu.com`,
  `za.archive.ubuntu.com`,
  `cn.archive.ubuntu.com`
]

const speedtestFiles = [
  {
    url: 'https://github.com/lamassu/speed-test-assets/raw/main/python-defaults_2.7.18-3.tar.gz',
    size: 44668
  }
]

function checkHasLightning (settings) {
  return configManager.getWalletSettings('BTC', settings.config).layer2 !== 'no-layer2'
}

const createTerms = terms => (terms.active && terms.text) ? ({
  active: terms.active,
  title: terms.title,
  text: nmd(terms.text),
  accept: terms.acceptButtonText,
  cancel: terms.cancelButtonText
}) : null

const buildTriggers = (allTriggers) => {
  const normalTriggers = []
  const customTriggers = _.filter(o => {
    if (_.isEmpty(o.customInfoRequestId) || _.isNil(o.customInfoRequestId)) normalTriggers.push(o)
    return !_.isNil(o.customInfoRequestId) && !_.isEmpty(o.customInfoRequestId)
  }, allTriggers)

  return _.flow([_.map(_.get('customInfoRequestId')), customRequestQueries.batchGetCustomInfoRequest])(customTriggers)
    .then(res => {
      res.forEach((details, index) => {
        // make sure we aren't attaching the details to the wrong trigger
        if (customTriggers[index].customInfoRequestId !== details.id) return
        customTriggers[index] = { ...customTriggers[index], customInfoRequest: details }
      })
      return [...normalTriggers, ...customTriggers]
    })
}

function poll (req, res, next) {
  const machineVersion = req.query.version
  const machineModel = req.query.model
  const deviceId = req.deviceId
  const deviceTime = req.deviceTime
  const pid = req.query.pid
  const settings = req.settings
  const operatorId = res.locals.operatorId
  const localeConfig = configManager.getLocale(deviceId, settings.config)
  const zeroConfLimits = _.reduce((acc, cryptoCode) => {
    acc[cryptoCode] = configManager.getWalletSettings(cryptoCode, settings.config).zeroConfLimit
    return acc
  }, {}, localeConfig.cryptoCurrencies)
  const pi = plugins(settings, deviceId)
  const hasLightning = checkHasLightning(settings)

  const operatorInfo = configManager.getOperatorInfo(settings.config)
  const machineInfo = { deviceId: req.deviceId, deviceName: req.deviceName }
  const cashOutConfig = configManager.getCashOut(deviceId, settings.config)
  const receipt = configManager.getReceipt(settings.config)
  const terms = configManager.getTermsConditions(settings.config)
  const enablePaperWalletOnly = configManager.getCompliance(settings.config).enablePaperWalletOnly

  state.pids = _.update(operatorId, _.set(deviceId, { pid, ts: Date.now() }), state.pids)

  return Promise.all([
      pi.pollQueries(deviceTime, req.query, machineVersion, machineModel),
      buildTriggers(configManager.getTriggers(settings.config)),
      configManager.getTriggersAutomation(settings.config)
    ])
    .then(([results, triggers, triggersAutomation]) => {
      const reboot = pid && state.reboots?.[operatorId]?.[deviceId] === pid
      const shutdown = pid && state.shutdowns?.[operatorId]?.[deviceId] === pid
      const restartServices = pid && state.restartServicesMap?.[operatorId]?.[deviceId] === pid
      const langs = localeConfig.languages

      const locale = {
        fiatCode: localeConfig.fiatCurrency,
        localeInfo: {
          primaryLocale: langs[0],
          primaryLocales: langs,
          country: localeConfig.country
        }
      }

      const response = {
        error: null,
        locale,
        version,
        receiptPrintingActive: receipt.active,
        smsReceiptActive: receipt.sms,
        enablePaperWalletOnly,
        twoWayMode: cashOutConfig.active,
        zeroConfLimits,
        reboot,
        shutdown,
        restartServices,
{'fraction_non_alphanumeric': 0.12450957765981999, 'fraction_numerical': 0.003000230786983614, 'mean_word_length': 3.972461273666093, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 17, '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': '5257412', 'n_tokens_mistral': 2615, 'n_tokens_neox': 2579, 'n_words': 497}