This repository has been archived by the owner on Jul 23, 2022. It is now read-only.
forked from adamghill/exchanger
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
289 lines (243 loc) · 10 KB
/
index.js
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
var path = require('path')
, moment = require('moment')
, crypto = require('crypto')
, xml2js = require('xml2js')
;
var Q = require('q');
var soap = require('soap');
var __ = function() {};
/**
* Initialize a soap client to communicate with the EWS server
* @param settings
* @param settings.username
* @param settings.password
* @param settings.url - host url for ews server. EX: mail.huntingtonlearningcenter.com
*
* @return {promise - exchanger client}
*/
__.initialize = function(settings) {
var instance = new __();
instance.username = settings.username;
instance.security = {
basic: new soap.BasicAuthSecurity(settings.username, settings.password),
ntlm: new soap.NtlmAuthSecurity(settings.username, settings.password),
ws: new soap.WSSecurity(settings.username, settings.password)
};
// TODO: Handle different locations of where the asmx lives.
var endpoint = 'https://' + path.join(settings.url, 'EWS/Exchange.asmx');
var url = path.join(__dirname, 'Services.wsdl');
return Q.nfcall(soap.createClient, url, {
endpoint: endpoint
}).then(
function(client) {
instance.client = client;
instance.setSecurity();
return instance;
}
);
};
/**
* Sets the security to be used. Default basic security
* @param {string} type - in [basic, ntlm, or ws]
*/
__.prototype.setSecurity = function(type) {
type = type || 'basic';
if (Object.keys(this.security).indexOf(type) < 0) {
return;
}
this.client.setSecurity(this.security[type]);
};
/**
* Gets all emails from
* @param {string} folderName - default inbox
* @param {integer} limit - default 10
* @return {promise - array email objects}
*/
__.prototype.getEmails = function(folderName, limit) {
folderName = folderName || 'inbox';
limit = limit || 10;
var soapRequest =
'<tns:FindItem Traversal="Shallow" xmlns:tns="http://schemas.microsoft.com/exchange/services/2006/messages">' +
'<tns:ItemShape>' +
'<t:BaseShape>IdOnly</t:BaseShape>' +
'<t:AdditionalProperties>' +
'<t:FieldURI FieldURI="item:ItemId"></t:FieldURI>' +
// '<t:FieldURI FieldURI="item:ConversationId"></t:FieldURI>' +
// '<t:FieldURI FieldURI="message:ReplyTo"></t:FieldURI>' +
// '<t:FieldURI FieldURI="message:ToRecipients"></t:FieldURI>' +
// '<t:FieldURI FieldURI="message:CcRecipients"></t:FieldURI>' +
// '<t:FieldURI FieldURI="message:BccRecipients"></t:FieldURI>' +
'<t:FieldURI FieldURI="item:DateTimeCreated"></t:FieldURI>' +
'<t:FieldURI FieldURI="item:DateTimeSent"></t:FieldURI>' +
'<t:FieldURI FieldURI="item:HasAttachments"></t:FieldURI>' +
'<t:FieldURI FieldURI="item:Size"></t:FieldURI>' +
'<t:FieldURI FieldURI="message:From"></t:FieldURI>' +
'<t:FieldURI FieldURI="message:IsRead"></t:FieldURI>' +
'<t:FieldURI FieldURI="item:Importance"></t:FieldURI>' +
'<t:FieldURI FieldURI="item:Subject"></t:FieldURI>' +
'<t:FieldURI FieldURI="item:DateTimeReceived"></t:FieldURI>' +
'</t:AdditionalProperties>' +
'</tns:ItemShape>' +
'<tns:IndexedPageItemView BasePoint="Beginning" Offset="0" MaxEntriesReturned="10"></tns:IndexedPageItemView>' +
'<tns:ParentFolderIds>' +
'<t:DistinguishedFolderId Id="inbox"></t:DistinguishedFolderId>' +
'</tns:ParentFolderIds>' +
'</tns:FindItem>';
return Q.nfcall(this.client.FindItem, soapRequest).spread(
function(result, body) {
var parser = new xml2js.Parser();
return Q.nfcall(parser.parseString, body).then(
function(result) {
var responseCode = result['s:Body']['m:FindItemResponse']['m:ResponseMessages']['m:FindItemResponseMessage']['m:ResponseCode'];
if (responseCode !== 'NoError') {
return callback(new Error(responseCode));
}
var rootFolder = result['s:Body']['m:FindItemResponse']['m:ResponseMessages']['m:FindItemResponseMessage']['m:RootFolder'];
var emails = [];
rootFolder['t:Items']['t:Message'].forEach(function(item, idx) {
var md5hasher = crypto.createHash('md5');
md5hasher.update(item['t:Subject'] + item['t:DateTimeSent']);
var hash = md5hasher.digest('hex');
var itemId = {
id: item['t:ItemId']['@'].Id,
changeKey: item['t:ItemId']['@'].ChangeKey
};
var dateTimeReceived = item['t:DateTimeReceived'];
emails.push({
id: itemId.id + '|' + itemId.changeKey,
hash: hash,
subject: item['t:Subject'],
dateTimeReceived: moment(dateTimeReceived).format("MM/DD/YYYY, h:mm:ss A"),
size: item['t:Size'],
importance: item['t:Importance'],
hasAttachments: (item['t:HasAttachments'] === 'true'),
from: item['t:From']['t:Mailbox']['t:Name'],
isRead: (item['t:IsRead'] === 'true'),
meta: {
itemId: itemId
}
});
});
return emails;
}
);
}
);
}
/**
* Checks if the account can be successfully accessed
* Currently uses getEmails until a better function is coded.
* @returns {promise resolves if login successful}
*/
__.prototype.checkLogin = __.prototype.getEmails;
/**
* Other preconstructed EWS soap requests
*/
// __.prototype.getEmail = function(itemId, callback) {
// if ((!itemId['id'] || !itemId['changeKey']) && itemId.indexOf('|') > 0) {
// var s = itemId.split('|');
// itemId = {
// id: itemId.split('|')[0],
// changeKey: itemId.split('|')[1]
// };
// }
// if (!itemId.id || !itemId.changeKey) {
// return callback(new Error('Id is not correct.'));
// }
// var soapRequest =
// '<tns:GetItem xmlns="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' +
// '<tns:ItemShape>' +
// '<t:BaseShape>Default</t:BaseShape>' +
// '<t:IncludeMimeContent>true</t:IncludeMimeContent>' +
// '</tns:ItemShape>' +
// '<tns:ItemIds>' +
// '<t:ItemId Id="' + itemId.id + '" ChangeKey="' + itemId.changeKey + '" />' +
// '</tns:ItemIds>' +
// '</tns:GetItem>';
// this.client.GetItem(soapRequest, function(err, result, body) {
// if (err) {
// return callback(err);
// }
// var parser = new xml2js.Parser();
// parser.parseString(body, function(err, result) {
// var responseCode = result['s:Body']['m:GetItemResponse']['m:ResponseMessages']['m:GetItemResponseMessage']['m:ResponseCode'];
// if (responseCode !== 'NoError') {
// return callback(new Error(responseCode));
// }
// var item = result['s:Body']['m:GetItemResponse']['m:ResponseMessages']['m:GetItemResponseMessage']['m:Items']['t:Message'];
// var itemId = {
// id: item['t:ItemId']['@'].Id,
// changeKey: item['t:ItemId']['@'].ChangeKey
// };
// function handleMailbox(mailbox) {
// var mailboxes = [];
// if (!mailbox || !mailbox['t:Mailbox']) {
// return mailboxes;
// }
// mailbox = mailbox['t:Mailbox'];
// function getMailboxObj(mailboxItem) {
// return {
// name: mailboxItem['t:Name'],
// emailAddress: mailboxItem['t:EmailAddress']
// };
// }
// if (mailbox instanceof Array) {
// mailbox.forEach(function(m, idx) {
// mailboxes.push(getMailboxObj(m));
// })
// } else {
// mailboxes.push(getMailboxObj(mailbox));
// }
// return mailboxes;
// }
// var toRecipients = handleMailbox(item['t:ToRecipients']);
// var ccRecipients = handleMailbox(item['t:CcRecipients']);
// var from = handleMailbox(item['t:From']);
// var email = {
// id: itemId.id + '|' + itemId.changeKey,
// subject: item['t:Subject'],
// bodyType: item['t:Body']['@']['t:BodyType'],
// body: item['t:Body']['#'],
// size: item['t:Size'],
// dateTimeSent: item['t:DateTimeSent'],
// dateTimeCreated: item['t:DateTimeCreated'],
// toRecipients: toRecipients,
// ccRecipients: ccRecipients,
// from: from,
// isRead: (item['t:IsRead'] == 'true') ? true : false,
// meta: {
// itemId: itemId
// }
// };
// callback(null, email);
// });
// });
// }
// __.prototype.getFolders = function(id, callback) {
// if (typeof(id) == 'function') {
// callback = id;
// id = 'inbox';
// }
// var soapRequest =
// '<tns:FindFolder xmlns:tns="http://schemas.microsoft.com/exchange/services/2006/messages">' +
// '<tns:FolderShape>' +
// '<t:BaseShape>Default</t:BaseShape>' +
// '</tns:FolderShape>' +
// '<tns:ParentFolderIds>' +
// '<t:DistinguishedFolderId Id="inbox"></t:DistinguishedFolderId>' +
// '</tns:ParentFolderIds>' +
// '</tns:FindFolder>';
// this.client.FindFolder(soapRequest, function(err, result) {
// if (err) {
// callback(err)
// }
// if (result.ResponseMessages.FindFolderResponseMessage.ResponseCode == 'NoError') {
// var rootFolder = result.ResponseMessages.FindFolderResponseMessage.RootFolder;
// rootFolder.Folders.Folder.forEach(function(folder) {
// // console.log(folder);
// });
// callback(null, {});
// }
// });
// }
module.exports = __;