-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-my-device-base.js
More file actions
192 lines (163 loc) · 5.74 KB
/
Copy pathfind-my-device-base.js
File metadata and controls
192 lines (163 loc) · 5.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// needed for node-config within Lambda
process.env.NODE_CONFIG_DIR = `${process.env["LAMBDA_TASK_ROOT"]}/config`;
const request = require('request-promise-native');
const config = require('config');
const Alexa = require('ask-sdk-core');
/**
* iCloud API description of the device, e.g. 'Apple Watch' or 'iPhone'.
* This value may collide if the account has multiple devices of the same
* type - consider using a separate API field in that case.
*
* To find this value, POST to https://fmipmobile.icloud.com/fmipservice/device/{user}/initClient
* with Authorization: Basic [base64 username:password] (if using Postman, make sure SSL certificate
* verification is turned off). Search for 'modelDisplayName' to find all devices named on the account.
*
* @type {string}
*/
const modelDisplayName = `${config.get('iCloud.modelDisplayName')}`;
const iCloud = {
host: 'https://fmipmobile.icloud.com',
paths: {
initClient: '/fmipservice/device/PH/initClient',
playSound: '/fmipservice/device/PH/playSound'
},
user: {
name: `${config.get('iCloud.user')}`,
password: Buffer.from(`${config.get('iCloud.password')}`, 'base64').toString('ascii')
}
};
/**
* iCloud POST request options helper method.
*
* @param {string} path
* @param {Object} [body]
* @return {Object}
*/
function getRequestOptions(path, body = null) {
const auth = Buffer.from(`${iCloud.user.name}:${iCloud.user.password}`).toString('base64');
const options = {
method: 'POST',
uri: `${iCloud.host}${path}`,
headers: {
Authorization: `Basic ${auth}`
},
rejectUnauthorized: false
};
if (body) {
options.json = true;
options.body = body;
options.headers['Content-Type'] = 'application/json';
}
return options;
}
/**
* Requests all device info and attempts to find the specific device ID based on the
* modelDisplayName.
*
* @return {Promise<string>}
*/
async function fetchDeviceId() {
console.log('Starting fetch for device ID via initDevices');
const initResult = await request(
getRequestOptions(iCloud.paths.initClient.replace(/PH/, iCloud.user.name))
);
const data = JSON.parse(initResult);
if (!data.content || !Array.isArray(data.content)) {
console.error('Invalid data from iCloud initClient', initResult);
throw new Error('Invalid data from iCloud initClient');
}
const content = data.content.find(c => c && c.modelDisplayName === modelDisplayName);
if (!content) {
throw new Error(`Unable to determine ID for ${modelDisplayName}`);
}
return content.id;
}
/**
* Launching point.
*
* @param {string} message
* @return {Promise<void>}
*/
async function playSound(message) {
console.log(`Starting play sound for ${modelDisplayName} with message ${message}`);
const deviceId = await fetchDeviceId();
if (!deviceId) {
throw new Error(`Unable to determine ID for ${modelDisplayName}`);
}
console.log(`Playing sound on ${modelDisplayName}, ID: ${deviceId}`);
const result = await request(
getRequestOptions(
iCloud.paths.playSound.replace(/PH/, iCloud.user.name),
{ device: deviceId, subject: message }
)
);
console.log(`Result: ${result}`);
}
const LaunchRequestHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'LaunchRequest' ||
(handlerInput.requestEnvelope.request.type === 'IntentRequest' &&
handlerInput.requestEnvelope.request.intent.name === 'FindDeviceIntent');
},
async handle(handlerInput) {
let speechText = `I have played a sound on your ${modelDisplayName}.`;
try {
await playSound('Alexa is looking for you!');
} catch (error) {
speechText = `Sorry, an error occurred while looking for your ${modelDisplayName}.`;
console.error(error);
}
return handlerInput.responseBuilder
.speak(speechText)
.withSimpleCard(`Find ${modelDisplayName} Triggered`, speechText)
.withShouldEndSession(true)
.getResponse();
}
};
const CancelAndStopIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& (handlerInput.requestEnvelope.request.intent.name === 'AMAZON.CancelIntent'
|| handlerInput.requestEnvelope.request.intent.name === 'AMAZON.StopIntent');
},
handle(handlerInput) {
const speakOutput = "Goodbye!";
return handlerInput.responseBuilder
.speak(speakOutput)
.getResponse();
}
};
const HelpIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest'
&& handlerInput.requestEnvelope.request.intent.name === 'AMAZON.HelpIntent';
},
handle(handlerInput) {
const speakOutput = "Help is not currently available for find my device.";
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt(speakOutput)
.getResponse();
}
};
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.error(`Error handled: ${error.message}`);
const speechText = `Sorry, I can't understand the command. Please say again.`;
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.getResponse();
},
};
exports.handler = Alexa.SkillBuilders.custom()
.addRequestHandlers(
LaunchRequestHandler,
HelpIntentHandler,
CancelAndStopIntentHandler
)
.addErrorHandlers(ErrorHandler)
.lambda();