Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save calvintwr/626d1812cf8a431349fe3070aac7bb89 to your computer and use it in GitHub Desktop.
Save calvintwr/626d1812cf8a431349fe3070aac7bb89 to your computer and use it in GitHub Desktop.
'use strict'
const iCloud = require('apple-icloud')
const debug = require('debug')('autocontact:apps:autocontact:index.js')
const D = require('dottie')
debug.log = console.log.bind(console)
// Note: sessions seemed to be invalidated once every 14 days. #setInterval to re-validate
const cloudRestartInterval = 12 * 24 * 60 * 60 * 1000 // 12 days
let cloudInterval = false
var cloud
function start(callback) {
cloud = new iCloud('session.json', process.env.ICLOUD_USR, process.env.ICLOUD_PWD)
// not sure if binding this will catch all errors during login.
cloud.on('err', err => {
let error = err
if (typeof err === 'string') error = Error(err)
if (typeof callback === 'function') callback(err)
error.sendEmail = true
ERROR_HANDLER(error)
})
cloud.on('sessionUpdate', () => {
cloud.saveSession()
})
cloud.on('ready', () => {
debug('Cloud is connected.')
global.CLOUD = cloud
// set the cloud session refresh interval only once.
// 23May2021-calvin: I suspect this will no longer work anyway and ought to be removed.
if(!cloudInterval) {
cloudInterval = setInterval(() => {
start(() => { console.log('Cloud sessions refreshed!') })
}, cloudRestartInterval)
}
cloud.Contacts.list().then(data => {
//debug(data)
let success = D.get(data, 'contacts.0.phones')
if (success) return debug('Contacts can be retrieved. All good.')
let err = Error('There is some error in the connection. Unable to retrieve contact.')
err.debug = data
throw err
})
if (typeof callback === 'function') callback()
})
return cloud
}
function restart(callback) {
global.CLOUD = undefined
clearInterval(cloudInterval)
cloudInterval = false
start(callback)
}
module.exports = {
start,
restart,
session: cloud
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment