/
Card.service.js
694 lines (620 loc) · 20 KB
/
Card.service.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
(function() {
'use strict';
/**
* @name Card
* @constructor
* @param {object} futureCardData
* @param {string} [partial]
*/
function Card(futureCardData, partial) {
// Data is immediately available
if (typeof futureCardData.then !== 'function') {
this.init(futureCardData, partial);
if (this.pid && !this.id) {
// Prepare for the creation of a new card;
// Get UID from the server.
var newCardData = Card.$$resource.newguid(this.pid);
this.$unwrap(newCardData);
this.isNew = true;
}
}
else {
// The promise will be unwrapped first
this.$unwrap(futureCardData);
}
}
Card.$TEL_TYPES = ['work', 'home', 'cell', 'fax', 'pager'];
Card.$EMAIL_TYPES = ['work', 'home', 'pref'];
Card.$URL_TYPES = ['work', 'home', 'pref'];
Card.$ADDRESS_TYPES = ['work', 'home'];
/**
* @memberof Card
* @desc The factory we'll use to register with Angular.
* @returns the Card constructor
*/
Card.$factory = ['$q', '$timeout', 'sgSettings', 'sgCard_STATUS', 'Resource', 'Preferences', function($q, $timeout, Settings, Card_STATUS, Resource, Preferences) {
angular.extend(Card, {
STATUS: Card_STATUS,
$$resource: new Resource(Settings.activeUser('folderURL') + 'Contacts', Settings.activeUser()),
$q: $q,
$timeout: $timeout,
$Preferences: Preferences
});
// Initialize categories from user's defaults
if (Preferences.defaults.SOGoContactsCategories) {
Card.$categories = Preferences.defaults.SOGoContactsCategories;
}
if (Preferences.defaults.SOGoAlternateAvatar)
Card.$alternateAvatar = Preferences.defaults.SOGoAlternateAvatar;
return Card; // return constructor
}];
/**
* @module SOGo.ContactsUI
* @desc Factory registration of Card in Angular module.
*/
try {
angular.module('SOGo.ContactsUI');
}
catch(e) {
angular.module('SOGo.ContactsUI', ['SOGo.Common', 'SOGo.PreferencesUI']);
}
angular.module('SOGo.ContactsUI')
.constant('sgCard_STATUS', {
NOT_LOADED: 0,
DELAYED_LOADING: 1,
LOADING: 2,
LOADED: 3,
DELAYED_MS: 300
})
.factory('Card', Card.$factory);
/**
* @memberof Card
* @desc Fetch a card from a specific addressbook.
* @param {string} addressbookId - the addressbook ID
* @param {string} cardId - the card ID
* @see {@link AddressBook.$getCard}
*/
Card.$find = function(addressbookId, cardId) {
var futureCardData = this.$$resource.fetch([addressbookId, cardId].join('/'), 'view');
if (cardId) return new Card(futureCardData); // a single card
return Card.$unwrapCollection(futureCardData); // a collection of cards
};
/**
* @function filterCategories
* @memberof Card.prototype
* @desc Search for categories matching some criterias
* @param {string} search - the search string to match
* @returns a collection of strings
*/
Card.filterCategories = function(query) {
var re = new RegExp(query, 'i');
return _.map(_.filter(Card.$categories, function(category) {
return category.search(re) != -1;
}), function(category) {
return { value: category };
});
};
/**
* @memberof Card
* @desc Unwrap to a collection of Card instances.
* @param {object} futureCardData
*/
Card.$unwrapCollection = function(futureCardData) {
var collection = {};
collection.$futureCardData = futureCardData;
futureCardData.then(function(cards) {
Card.$timeout(function() {
angular.forEach(cards, function(data, index) {
collection[data.id] = new Card(data);
});
});
});
return collection;
};
/**
* @function init
* @memberof Card.prototype
* @desc Extend instance with required attributes and new data.
* @param {object} data - attributes of card
*/
Card.prototype.init = function(data, partial) {
var _this = this;
if (angular.isUndefined(this.refs))
this.refs = [];
if (angular.isUndefined(this.categories))
this.categories = [];
this.c_screenname = null;
angular.extend(this, data);
if (!this.pid)
this.pid = this.container;
if (!this.$$fullname)
this.$$fullname = this.$fullname();
if (!this.$$email)
this.$$email = this.$preferredEmail(partial);
if (!this.$$image)
this.$$image = this.image;
if (!this.$$image)
this.$$image = Card.$Preferences.avatar(this.$$email, 40, {no_404: true});
if (this.hasphoto)
this.photoURL = Card.$$resource.path(this.pid, this.id, 'photo');
if (this.isgroup)
this.c_component = 'vlist';
this.$avatarIcon = this.$isList()? 'group' : 'person';
if (data.orgs && data.orgs.length)
this.orgs = _.map(data.orgs, function(org) { return { 'value': org }; });
if (data.notes && data.notes.length)
this.notes = _.map(data.notes, function(note) { return { 'value': note }; });
else if (!this.notes || !this.notes.length)
this.notes = [ { value: '' } ];
// Lowercase the type of specific fields
angular.forEach(['addresses', 'phones', 'urls'], function(key) {
angular.forEach(_this[key], function(o) {
if (o.type) o.type = o.type.toLowerCase();
});
});
// Instanciate Card objects for list members
angular.forEach(this.refs, function(o, i) {
if (o.email) o.emails = [{value: o.email}];
o.id = o.reference;
_this.refs[i] = new Card(o);
});
// Instanciate date object of birthday
if (this.birthday && angular.isString(this.birthday)) {
var dlp = Card.$Preferences.$mdDateLocaleProvider;
this.birthday = this.birthday.parseDate(dlp, '%Y-%m-%d');
this.$birthday = dlp.formatDate(this.birthday);
}
this.$loaded = angular.isDefined(this.c_name)? Card.STATUS.LOADED : Card.STATUS.NOT_LOADED;
// An empty attribute to trick md-autocomplete when adding attendees from the appointment editor
this.empty = ' ';
};
/**
* @function $id
* @memberof Card.prototype
* @desc Return the card ID.
* @returns the card ID
*/
Card.prototype.$id = function() {
return this.$futureCardData.then(function(data) {
return data.id;
});
};
/**
* @function $isLoading
* @memberof Card.prototype
* @returns true if the Card definition is still being retrieved from server after a specific delay
* @see sgCard_STATUS
*/
Card.prototype.$isLoading = function() {
return this.$loaded == Card.STATUS.LOADING;
};
/**
* @function $reload
* @memberof Card.prototype
* @desc Fetch all available attributes of the contact.
* @returns a promise of the HTTP operation
*/
Card.prototype.$reload = function() {
var _this = this, futureCardData;
if (this.$futureCardData)
return this;
futureCardData = Card.$$resource.fetch([this.pid, this.id].join('/'), 'view');
return this.$unwrap(futureCardData);
};
/**
* @function $members
* @memberof Card.prototype
* @desc Fetch members of the LDAP group.
* @returns a promise that resolves with the members
*/
Card.prototype.$members = function() {
var _this = this;
if (this.members)
return Card.$q.when(this.members);
if (this.isgroup) {
return Card.$$resource.fetch([this.pid, this.id].join('/'), 'members').then(function(data) {
_this.members = _.map(data.members, function(member) {
return new Card(member);
});
return _this.members;
});
}
};
/**
* @function $save
* @memberof Card.prototype
* @desc Save the card to the server.
*/
Card.prototype.$save = function() {
var _this = this,
action = 'saveAsContact';
if (this.c_component == 'vlist') {
action = 'saveAsList';
_.forEach(this.refs, function(ref) {
ref.reference = ref.id;
});
}
return Card.$$resource.save([this.pid, this.id || '_new_'].join('/'),
this.$omit(),
{ action: action })
.then(function(data) {
// Format birthdate
if (_this.birthday)
_this.$birthday = Card.$Preferences.$mdDateLocaleProvider.formatDate(_this.birthday);
// Make a copy of the data for an eventual reset
_this.$shadowData = _this.$omit(true);
return data;
});
};
Card.prototype.$delete = function(attribute, index) {
if (attribute) {
if (index > -1 && this[attribute].length > index) {
this[attribute].splice(index, 1);
}
else
delete this[attribute];
}
else {
// No arguments -- delete card
return Card.$$resource.remove([this.pid, this.id].join('/'));
}
};
/**
* @function export
* @memberof Card.prototype
* @desc Download the current card
* @returns a promise of the HTTP operation
*/
Card.prototype.export = function() {
var data, options;
data = { uids: [ this.id ] };
options = {
type: 'application/octet-stream',
filename: this.$$fullname + '.ldif'
};
return Card.$$resource.download(this.pid, 'export', data, options);
};
Card.prototype.$fullname = function(options) {
var fn = this.c_cn || '', html = options && options.html, email, names;
if (fn.length === 0) {
names = [];
if (this.c_givenname && this.c_givenname.length > 0)
names.push(this.c_givenname);
if (this.nickname && this.nickname.length > 0)
names.push((html?'<em>':'') + this.nickname + (html?'</em>':''));
if (this.c_sn && this.c_sn.length > 0)
names.push(this.c_sn);
if (names.length > 0)
fn = names.join(' ');
else if (this.org && this.org.length > 0) {
fn = this.org;
}
else if (this.emails && this.emails.length > 0) {
email = _.find(this.emails, function(i) { return i.value !== ''; });
if (email)
fn = email.value;
}
}
if (this.contactinfo)
fn += ' (' + this.contactinfo.split("\n").join("; ") + ')';
return fn;
};
Card.prototype.$description = function() {
var description = [];
if (this.title) description.push(this.title);
if (this.role) description.push(this.role);
if (this.org) description.push(this.org);
if (this.orgs) description = _.concat(description, _.map(this.orgs, 'value'));
if (this.description) description.push(this.description);
return description.join(', ');
};
/**
* @function $preferredEmail
* @memberof Card.prototype
* @desc Get the preferred email address.
* @param {string} [partial] - a partial string that the email must match
* @returns the first email address of type "pref" or the first address if none found
*/
Card.prototype.$preferredEmail = function(partial) {
var email, re;
if (partial) {
re = new RegExp(partial, 'i');
email = _.find(this.emails, function(o) {
return re.test(o.value);
});
}
if (email) {
email = email.value;
}
else {
email = _.find(this.emails, function(o) {
return o.type == 'pref';
});
if (email) {
email = email.value;
}
else if (this.emails && this.emails.length) {
email = this.emails[0].value;
}
else if (this.c_mail && this.c_mail.length) {
email = this.c_mail[0];
}
else {
email = '';
}
}
return email;
};
/**
* @function $shortFormat
* @memberof Card.prototype
* @param {string} [partial] - a partial string that the email must match
* @returns the fullname along with a matching email address in parentheses
*/
Card.prototype.$shortFormat = function(partial) {
var fullname = [this.$$fullname],
email = this.$preferredEmail(partial);
if (email && email != this.$$fullname)
fullname.push(' <' + email + '>');
return fullname.join(' ');
};
Card.prototype.$isCard = function() {
return this.c_component == 'vcard';
};
Card.prototype.$isList = function(options) {
// isGroup attribute means it's a group of a LDAP source (not automatically expanded on the client-side)
var condition = (!options || !options.expandable || options.expandable && !this.isgroup);
return this.c_component == 'vlist' && condition;
};
Card.prototype.$addOrg = function(org) {
if (angular.isUndefined(this.orgs)) {
this.orgs = [org];
}
else if (org != this.org && !_.includes(this.orgs, org)) {
this.orgs.push(org);
}
return this.orgs.length - 1;
};
// Card.prototype.$addCategory = function(category) {
// if (category) {
// if (angular.isUndefined(this.categories)) {
// this.categories = [{value: category}];
// }
// else {
// for (var i = 0; i < this.categories.length; i++) {
// if (this.categories[i].value == category) {
// break;
// }
// }
// if (i == this.categories.length)
// this.categories.push({value: category});
// }
// }
// };
Card.prototype.$addEmail = function(type) {
if (angular.isUndefined(this.emails)) {
this.emails = [{type: type, value: ''}];
}
else if (_.isUndefined(_.find(this.emails, function(i) { return i.value === ''; }))) {
this.emails.push({type: type, value: ''});
}
return this.emails.length - 1;
};
Card.prototype.$addScreenName = function(screenName) {
this.c_screenname = screenName;
};
Card.prototype.$addPhone = function(type) {
if (angular.isUndefined(this.phones)) {
this.phones = [{type: type, value: ''}];
}
else if (_.isUndefined(_.find(this.phones, function(i) { return i.value === ''; }))) {
this.phones.push({type: type, value: ''});
}
return this.phones.length - 1;
};
Card.prototype.$addUrl = function(type, url) {
if (angular.isUndefined(this.urls)) {
this.urls = [{type: type, value: url}];
}
else if (_.isUndefined(_.find(this.urls, function(i) { return i.value == url; }))) {
this.urls.push({type: type, value: url});
}
return this.urls.length - 1;
};
Card.prototype.$addAddress = function(type, postoffice, street, street2, locality, region, country, postalcode) {
if (angular.isUndefined(this.addresses)) {
this.addresses = [{type: type, postoffice: postoffice, street: street, street2: street2, locality: locality, region: region, country: country, postalcode: postalcode}];
}
else if (!_.find(this.addresses, function(i) {
return i.street == street &&
i.street2 == street2 &&
i.locality == locality &&
i.country == country &&
i.postalcode == postalcode;
})) {
this.addresses.push({type: type, postoffice: postoffice, street: street, street2: street2, locality: locality, region: region, country: country, postalcode: postalcode});
}
return this.addresses.length - 1;
};
Card.prototype.$addMember = function(email) {
var card = new Card({email: email, emails: [{value: email}]}),
i;
if (angular.isUndefined(this.refs)) {
this.refs = [card];
}
else if (email.length === 0) {
this.refs.push(card);
}
else {
for (i = 0; i < this.refs.length; i++) {
if (this.refs[i].email == email) {
break;
}
}
if (i == this.refs.length)
this.refs.push(card);
}
return this.refs.length - 1;
};
/**
* @function $certificate
* @memberof Account.prototype
* @desc View the S/MIME certificate details associated to the account.
* @returns a promise of the HTTP operation
*/
Card.prototype.$certificate = function() {
var _this = this;
if (this.hasCertificate) {
if (this.$$certificate)
return Card.$q.when(this.$$certificate);
else {
return Card.$$resource.fetch([this.pid, this.id].join('/'), 'certificate').then(function(data) {
_this.$$certificate = data;
return data;
});
}
}
else {
return Card.$q.reject();
}
};
/**
* @function $removeCertificate
* @memberof Account.prototype
* @desc Remove any S/MIME certificate associated with the account.
* @returns a promise of the HTTP operation
*/
Card.prototype.$removeCertificate = function() {
var _this = this;
return Card.$$resource.fetch([this.pid, this.id].join('/'), 'removeCertificate').then(function() {
_this.hasCertificate = false;
});
};
/**
* @function explode
* @memberof Card.prototype
* @desc Create a new Card associated to each email address of this card.
* @return an array of Card instances
*/
Card.prototype.explode = function() {
var _this = this, cards = [], data;
if (this.emails) {
if (this.emails.length > 1) {
data = this.$omit();
_.forEach(this.emails, function(email) {
var card = new Card(angular.extend({}, data, {emails: [email]}));
cards.push(card);
});
return cards;
}
else
return [this];
}
return [];
};
/**
* @function $reset
* @memberof Card.prototype
* @desc Reset the original state the card's data.
*/
Card.prototype.$reset = function() {
var _this = this;
angular.forEach(this, function(value, key) {
if (key != 'constructor' && key[0] != '$') {
delete _this[key];
}
});
this.init(this.$shadowData);
this.$shadowData = this.$omit(true);
};
/**
* @function $updateMember
* @memberof Card.prototype
* @desc Update an existing list member from a Card instance.
* A list member has the following attribtues:
* - email
* - reference
* - fn
* @param {number} index
* @param {string} email
* @param {Card} card
*/
// Card.prototype.$updateMember = function(index, email, card) {
// var ref = {
// email: email,
// emails: [{value: email}],
// reference: card.c_name,
// c_cn: card.$fullname()
// };
// this.refs[index] = new Card(ref);
// };
/**
* @function $unwrap
* @memberof Card.prototype
* @desc Unwrap a promise and make a copy of the resolved data.
* @param {object} futureCardData - a promise of the Card's data
*/
Card.prototype.$unwrap = function(futureCardData) {
var _this = this;
// Card is not loaded yet
this.$loaded = Card.STATUS.DELAYED_LOADING;
Card.$timeout(function() {
if (_this.$loaded != Card.STATUS.LOADED)
_this.$loaded = Card.STATUS.LOADING;
}, Card.STATUS.DELAYED_MS);
// Expose the promise
this.$futureCardData = futureCardData.then(function(data) {
_this.init(data);
// Mark card as loaded
_this.$loaded = Card.STATUS.LOADED;
// Make a copy of the data for an eventual reset
_this.$shadowData = _this.$omit(true);
return _this;
});
return this.$futureCardData;
};
/**
* @function $omit
* @memberof Card.prototype
* @desc Return a sanitized object used to send to the server.
* @param {boolean} [deep] - make a deep copy if true
* @return an object literal copy of the Card instance
*/
Card.prototype.$omit = function(deep) {
var card = {};
angular.forEach(this, function(value, key) {
if (key == 'refs') {
card.refs = _.map(value, function(o) {
return o.$omit(deep);
});
}
else if (key != 'constructor' && key[0] != '$') {
if (deep)
card[key] = angular.copy(value);
else
card[key] = value;
}
});
// We convert back our birthday object
if (!deep) {
if (card.birthday)
card.birthday = card.birthday.format(Card.$Preferences.$mdDateLocaleProvider, '%Y-%m-%d');
else
card.birthday = '';
}
// We flatten the organizations to an array of strings
if (this.orgs)
card.orgs = _.map(this.orgs, 'value');
// We flatten the notes to an array of strings
if (this.notes)
card.notes = _.map(this.notes, 'value');
return card;
};
Card.prototype.toString = function() {
var desc = this.id + ' ' + this.$$fullname;
if (this.$$email)
desc += ' <' + this.$$email + '>';
return '[' + desc + ']';
};
})();