mac-contacts
Version:
Fetch the contacts from macOS/Apple in JSON format.
88 lines (74 loc) • 2.77 kB
JavaScript
;
var _require = require('child_process'),
spawn = _require.spawn;
var path = require('path');
/**
* fetchAllContacts
* Fetches the macOS/Apple contacts.
*
* @name fetchAllContacts
* @function
* @param {Function} onProgress A function which is called on progress, with the following object:
* - progress (information about the progress)
* - contactInfo (information about the contact)
* @return {Promise} A promise resolving with the contacts as an array.
*/
module.exports = function fetchAllContacts(onProgress) {
return new Promise(function (resolve, reject) {
// Define the path to the AppleScript file
var scriptPath = path.join(__dirname, 'fetch-contacts.scpt'); // Update the script file name and location
// Spawn a child process to run the AppleScript
var scriptProcess = spawn('osascript', [scriptPath]);
var contactsData = [];
// Process the data
var processData = function processData(data) {
var output = data.toString();
var lines = output.split('\n');
lines.forEach(function (line) {
if (line.trim()) {
// Check if the line contains progress in the form of "[current/total] {contact information in json format}"
var progressMatch = line.match(/^\[(\d+)\/(\d+)\] (.+)$/);
if (progressMatch) {
var current = parseInt(progressMatch[1], 10);
var total = parseInt(progressMatch[2], 10);
var percent = current / total * 100;
// Extract the contact information JSON
var contactInfo = null;
try {
contactInfo = JSON.parse(progressMatch[3].trim());
} catch (error) {
console.error('Error parsing contact information:', error);
}
// Send both progress and contact info in the progress event
if (onProgress && contactInfo) {
onProgress({
progress: {
current: current,
total: total,
percent: percent
},
contact: contactInfo
});
}
// Collect contact data
if (contactInfo) {
contactsData.push(contactInfo);
}
}
}
});
};
// Listen to stdout and stderr streams for output
scriptProcess.stdout.on('data', processData);
scriptProcess.stderr.on('data', processData);
// Handle process closure
scriptProcess.on('close', function (code) {
if (code !== 0) {
reject('AppleScript process exited with code ' + code);
return;
}
// Resolve the promise with the collected contacts data
resolve(contactsData);
});
});
};