<commit_before>'use strict'

require('babel-polyfill')

const AutoLaunch = require('auto-launch-patched')
const Desktop = require('cozy-desktop').default
const electron = require('electron')
const notify = require('electron-main-notification')
const fs = require('fs')
const debounce = require('lodash.debounce')
const os = require('os')
const path = require('path')
const {spawn} = require('child_process')

const {app, autoUpdater, BrowserWindow, dialog, ipcMain, Menu, shell, session} = electron
const autoLauncher = new AutoLaunch({
  name: 'Cozy-Desktop',
  isHidden: true
})
const desktop = new Desktop(process.env.COZY_DESKTOP_DIR)
const lastFilesPath = path.join(desktop.basePath, 'last-files')

app.locale = (() => {
  const env = process.env
  const envLocale = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE
  if (envLocale && envLocale.match(/^fr_/i)) {
    return 'fr'
  } else {
    return 'en'
  }
})()

const translations = require(`./locales/${app.locale}.json`)

const translate = key => translations[key] ||
  key.substr(key.indexOf(' ') + 1) // Key without prefix

const interpolate = (string, ...args) => {
  return string.replace(/{(\d+)}/g, (_, index) => args[parseInt(index)])
}

const platformName = () => {
  switch (process.platform) {
    case 'darwin': return 'macOS'
    case 'freebsd': return 'FreeBSD'
    case 'linux': return 'Linux'
    case 'sunos': return 'SunOS'
    case 'win32': return 'Windows'
    default: return process.platform
  }
}

// This server is used for checking if a new release is available
// and installing the updates
const nutsServer = 'https://nuts.cozycloud.cc'

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let tray
let diskTimeout

let state = 'not-configured'
let errorMessage = ''
let lastFiles = []
let newReleaseAvailable = false

const windowOptions = {
  width: 1024,
  height: 768,
  icon: `${__dirname}/images/icon.png`
}

const showWindow = () => {
  if (mainWindow) {
    mainWindow.focus()
  } else {
    createWindow()
  }
}

const sendToMainWindow = (...args) => {
  if (mainWindow && mainWindow.webContents) {
    mainWindow.webContents.send(...args)
  }
}

const sendErrorToMainWindow = (msg) => {
  if (msg === 'Client has been revoked') {
    sendToMainWindow('revoked')
  } else {
    sendToMainWindow('sync-error', msg)
  }
  notify('Cozy-Desktop', { body: msg })
}

const goToTab = (tab) => {
  const alreadyShown = !!mainWindow
  showWindow()
  if (alreadyShown) {
    sendToMainWindow('go-to-tab', tab)
  } else {
    mainWindow.webContents.once('dom-ready', () => {
      sendToMainWindow('go-to-tab', tab)
    })
  }
}

const goToMyCozy = () => {
  shell.openExternal(desktop.config.cozyUrl)
}

const openCozyFolder = () => {
  shell.openItem(desktop.config.syncPath)
}

const buildAppMenu = () => {
  const template = [
    {
      label: translate('AppMenu Edit'),
      submenu: [
        { label: translate('AppMenu Undo'), accelerator: 'CmdOrCtrl+Z', role: 'undo' },
        { label: translate('AppMenu Redo'), accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
        { type: 'separator' },
        { label: translate('AppMenu Select All'), accelerator: 'CmdOrCtrl+A', role: 'selectall' },
        { type: 'separator' },
        { label: translate('AppMenu Cut'), accelerator: 'CmdOrCtrl+X', role: 'cut' },
        { label: translate('AppMenu Copy'), accelerator: 'CmdOrCtrl+C', role: 'copy' },
        { label: translate('AppMenu Paste'), accelerator: 'CmdOrCtrl+V', role: 'paste' }
      ]
    },
    {
      label: translate('AppMenu Window'),
      role: 'window',
      submenu: [
        { label: translate('AppMenu Minimize'), accelerator: 'CmdOrCtrl+M', role: 'minimize' },
        { label: translate('AppMenu Close'), accelerator: 'CmdOrCtrl+W', role: 'close' }
      ]
    }
  ]

  if (process.platform === 'darwin') {
    template.unshift({
      label: 'Cozy Desktop',
      submenu: [
        { label: translate('AppMenu Hide Cozy Desktop'), accelerator: 'Command+H', role: 'hide' },
        { label: translate('AppMenu Hide Others'), accelerator: 'Command+Alt+H', role: 'hideothers' },
        { label: translate('AppMenu Show All'), role: 'unhide' },
        { type: 'separator' },
        { label: translate('AppMenu Quit'), accelerator: 'Command+Q', click () { app.quit() } }
      ]
    })
    template[2].submenu.push({ type: 'separator' })
    template[2].submenu.push({ label: translate('AppMenu Bring All to Front'), role: 'front' })
  }

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

const setTrayIcon = (state) => {
  if (process.platform === 'darwin') {
    tray.setImage(`${__dirname}/images/tray-icon-osx/${state}Template.png`)
    tray.setPressedImage(`${__dirname}/images/tray-icon-osx/${state}Highlight.png`)
  } else {
    tray.setImage(`${__dirname}/images/tray-icon-linux/${state}.png`)
  }
}

const checkForNewRelease = () => {
  const arch = os.arch()
  const platform = os.platform()
  const version = app.getVersion()
  if (platform !== 'darwin') {
    return
  }
  autoUpdater.addListener('update-downloaded', (event, releaseNotes, releaseName) => {
    releaseName = releaseName || 'unknown'
    releaseNotes = releaseNotes || `New version ${releaseName} available`
    newReleaseAvailable = true
    sendToMainWindow('new-release-available', releaseNotes || '', releaseName || '')
  })
  autoUpdater.addListener('error', (err) => console.error(err))
  autoUpdater.setFeedURL(`${nutsServer}/update/${platform}_${arch}/${version}`)
  autoUpdater.checkForUpdates()
  setInterval(() => {
    autoUpdater.checkForUpdates()
  }, 86400) // Check if a new release is available once per day
}

const updateState = (newState, filename) => {
  if (state === 'error' && newState === 'offline') {
    return
  }
  state = newState
  let statusLabel = ''
  if (state === 'error') {
    setTrayIcon('error')
    statusLabel = errorMessage = filename
  } else if (filename) {
    setTrayIcon('sync')<commit_msg>Do not prevent Windows auto-updates<commit_after>'use strict'

require('babel-polyfill')

const AutoLaunch = require('auto-launch-patched')
const Desktop = require('cozy-desktop').default
const electron = require('electron')
const notify = require('electron-main-notification')
const fs = require('fs')
const debounce = require('lodash.debounce')
const os = require('os')
const path = require('path')
const {spawn} = require('child_process')

const {app, autoUpdater, BrowserWindow, dialog, ipcMain, Menu, shell, session} = electron
const autoLauncher = new AutoLaunch({
  name: 'Cozy-Desktop',
  isHidden: true
})
const desktop = new Desktop(process.env.COZY_DESKTOP_DIR)
const lastFilesPath = path.join(desktop.basePath, 'last-files')

app.locale = (() => {
  const env = process.env
  const envLocale = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE
  if (envLocale && envLocale.match(/^fr_/i)) {
    return 'fr'
  } else {
    return 'en'
  }
})()

const translations = require(`./locales/${app.locale}.json`)

const translate = key => translations[key] ||
  key.substr(key.indexOf(' ') + 1) // Key without prefix

const interpolate = (string, ...args) => {
  return string.replace(/{(\d+)}/g, (_, index) => args[parseInt(index)])
}

const platformName = () => {
  switch (process.platform) {
    case 'darwin': return 'macOS'
    case 'freebsd': return 'FreeBSD'
    case 'linux': return 'Linux'
    case 'sunos': return 'SunOS'
    case 'win32': return 'Windows'
    default: return process.platform
  }
}

// This server is used for checking if a new release is available
// and installing the updates
const nutsServer = 'https://nuts.cozycloud.cc'

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let tray
let diskTimeout

let state = 'not-configured'
let errorMessage = ''
let lastFiles = []
let newReleaseAvailable = false

const windowOptions = {
  width: 1024,
  height: 768,
  icon: `${__dirname}/images/icon.png`
}

const showWindow = () => {
  if (mainWindow) {
    mainWindow.focus()
  } else {
    createWindow()
  }
}

const sendToMainWindow = (...args) => {
  if (mainWindow && mainWindow.webContents) {
    mainWindow.webContents.send(...args)
  }
}

const sendErrorToMainWindow = (msg) => {
  if (msg === 'Client has been revoked') {
    sendToMainWindow('revoked')
  } else {
    sendToMainWindow('sync-error', msg)
  }
  notify('Cozy-Desktop', { body: msg })
}

const goToTab = (tab) => {
  const alreadyShown = !!mainWindow
  showWindow()
  if (alreadyShown) {
    sendToMainWindow('go-to-tab', tab)
  } else {
    mainWindow.webContents.once('dom-ready', () => {
      sendToMainWindow('go-to-tab', tab)
    })
  }
}

const goToMyCozy = () => {
  shell.openExternal(desktop.config.cozyUrl)
}

const openCozyFolder = () => {
  shell.openItem(desktop.config.syncPath)
}

const buildAppMenu = () => {
  const template = [
    {
      label: translate('AppMenu Edit'),
      submenu: [
        { label: translate('AppMenu Undo'), accelerator: 'CmdOrCtrl+Z', role: 'undo' },
        { label: translate('AppMenu Redo'), accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
        { type: 'separator' },
        { label: translate('AppMenu Select All'), accelerator: 'CmdOrCtrl+A', role: 'selectall' },
        { type: 'separator' },
        { label: translate('AppMenu Cut'), accelerator: 'CmdOrCtrl+X', role: 'cut' },
        { label: translate('AppMenu Copy'), accelerator: 'CmdOrCtrl+C', role: 'copy' },
        { label: translate('AppMenu Paste'), accelerator: 'CmdOrCtrl+V', role: 'paste' }
      ]
    },
    {
      label: translate('AppMenu Window'),
      role: 'window',
      submenu: [
        { label: translate('AppMenu Minimize'), accelerator: 'CmdOrCtrl+M', role: 'minimize' },
        { label: translate('AppMenu Close'), accelerator: 'CmdOrCtrl+W', role: 'close' }
      ]
    }
  ]

  if (process.platform === 'darwin') {
    template.unshift({
      label: 'Cozy Desktop',
      submenu: [
        { label: translate('AppMenu Hide Cozy Desktop'), accelerator: 'Command+H', role: 'hide' },
        { label: translate('AppMenu Hide Others'), accelerator: 'Command+Alt+H', role: 'hideothers' },
        { label: translate('AppMenu Show All'), role: 'unhide' },
        { type: 'separator' },
        { label: translate('AppMenu Quit'), accelerator: 'Command+Q', click () { app.quit() } }
      ]
    })
    template[2].submenu.push({ type: 'separator' })
    template[2].submenu.push({ label: translate('AppMenu Bring All to Front'), role: 'front' })
  }

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

const setTrayIcon = (state) => {
  if (process.platform === 'darwin') {
    tray.setImage(`${__dirname}/images/tray-icon-osx/${state}Template.png`)
    tray.setPressedImage(`${__dirname}/images/tray-icon-osx/${state}Highlight.png`)
  } else {
    tray.setImage(`${__dirname}/images/tray-icon-linux/${state}.png`)
  }
}

const checkForNewRelease = () => {
  const arch = os.arch()
  const platform = os.platform()
  const version = app.getVersion()
  if (platform !== 'darwin' && platform !== 'win32') {
    return
  }
  autoUpdater.addListener('update-downloaded', (event, releaseNotes, releaseName) => {
    releaseName = releaseName || 'unknown'
    releaseNotes = releaseNotes || `New version ${releaseName} available`
    newReleaseAvailable = true
    sendToMainWindow('new-release-available', releaseNotes || '', releaseName || '')
  })
  autoUpdater.addListener('error', (err) => console.error(err))
  autoUpdater.setFeedURL(`${nutsServer}/update/${platform}_${arch}/${version}`)
  autoUpdater.checkForUpdates()
  setInterval(() => {
    autoUpdater.checkForUpdates()
  }, 86400) // Check if a new release is available once per day
}

const updateState = (newState, filename) => {
  if (state === 'error' && newState === 'offline') {
    return
  }
  state = newState
  let statusLabel = ''
  if (state === 'error') {
    setTrayIcon('error')
    statusLabel = errorMessage = filename
  } else if (filename) {
    setTrayIcon('sync')
{'fraction_non_alphanumeric': 0.16331863465621427, 'fraction_numerical': 0.002939735423811857, 'mean_word_length': 3.7542701863354035, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 41, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4774771', 'n_tokens_mistral': 3998, 'n_tokens_neox': 3886, 'n_words': 917}