/
Component.service.js
1274 lines (1131 loc) · 42.7 KB
/
Component.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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: javascript; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
(function() {
'use strict';
/**
* @name Component
* @constructor
* @param {object} futureComponentData - either an object literal or a promise
*/
function Component(futureComponentData) {
// Data is immediately available
if (typeof futureComponentData.then !== 'function') {
this.init(futureComponentData);
if (this.pid && !this.id) {
// Prepare for the creation of a new component;
// Get UID from the server.
var newComponentData = Component.$$resource.newguid(this.pid);
this.$unwrap(newComponentData);
this.isNew = true;
}
}
else {
// The promise will be unwrapped first
this.$unwrap(futureComponentData);
}
}
/**
* @memberof Component
* @desc The factory we'll use to register with Angular
* @returns the Component constructor
*/
Component.$factory = ['$q', '$timeout', '$log', 'sgSettings', 'Preferences', 'Card', 'Gravatar', 'Resource', function($q, $timeout, $log, Settings, Preferences, Card, Gravatar, Resource) {
angular.extend(Component, {
$q: $q,
$timeout: $timeout,
$log: $log,
$Preferences: Preferences,
$Card: Card,
$gravatar: Gravatar,
$$resource: new Resource(Settings.activeUser('folderURL') + 'Calendar', Settings.activeUser()),
timeFormat: "%H:%M",
// Filter parameters common to events and tasks
$query: { value: '', search: 'title_Category_Location' },
// Filter paramaters specific to events
$queryEvents: { sort: 'start', asc: 1, filterpopup: 'view_next7' },
// Filter parameters specific to tasks
$queryTasks: { sort: 'status', asc: 1, filterpopup: 'view_incomplete' },
$refreshTimeout: null,
$ghost: {}
});
Preferences.ready().then(function() {
// Initialize filter parameters from user's settings
if (Preferences.settings.Calendar.EventsFilterState)
Component.$queryEvents.filterpopup = Preferences.settings.Calendar.EventsFilterState;
if (Preferences.settings.Calendar.TasksFilterState)
Component.$queryTasks.filterpopup = Preferences.settings.Calendar.TasksFilterState;
if (Preferences.settings.Calendar.EventsSortingState) {
Component.$queryEvents.sort = Preferences.settings.Calendar.EventsSortingState[0];
Component.$queryEvents.asc = parseInt(Preferences.settings.Calendar.EventsSortingState[1]);
}
if (Preferences.settings.Calendar.TasksSortingState) {
Component.$queryTasks.sort = Preferences.settings.Calendar.TasksSortingState[0];
Component.$queryTasks.asc = parseInt(Preferences.settings.Calendar.TasksSortingState[1]);
}
Component.$queryTasks.show_completed = parseInt(Preferences.settings.ShowCompletedTasks);
// Initialize categories from user's defaults
Component.$categories = Preferences.defaults.SOGoCalendarCategoriesColors;
// Initialize time format from user's defaults
if (Preferences.defaults.SOGoTimeFormat) {
Component.timeFormat = Preferences.defaults.SOGoTimeFormat;
}
});
return Component; // return constructor
}];
/**
* @module SOGo.SchedulerUI
* @desc Factory registration of Component in Angular module.
*/
try {
angular.module('SOGo.SchedulerUI');
}
catch(e) {
angular.module('SOGo.SchedulerUI', ['SOGo.Common']);
}
angular.module('SOGo.SchedulerUI')
.factory('Component', Component.$factory);
/**
* @function $selectedCount
* @memberof Component
* @desc Return the number of events or tasks selected by the user.
* @returns the number of selected events or tasks
*/
Component.$selectedCount = function() {
var count;
count = 0;
if (Component.$events) {
count += (_.filter(Component.$events, function(event) { return event.selected; })).length;
}
if (Component.$tasks) {
count += (_.filter(Component.$tasks, function(task) { return task.selected; })).length;
}
return count;
};
/**
* @function $startRefreshTimeout
* @memberof Component
* @desc Starts the refresh timeout for the current selected component type, for all calendars
*/
Component.$startRefreshTimeout = function(type) {
var _this = this;
if (Component.$refreshTimeout)
Component.$timeout.cancel(Component.$refreshTimeout);
Component.$Preferences.ready().then(function() {
// Restart the refresh timer, if needed
var refreshViewCheck = Component.$Preferences.defaults.SOGoRefreshViewCheck;
if (refreshViewCheck && refreshViewCheck != 'manually') {
var f = angular.bind(_this, Component.$filter, type);
Component.$refreshTimeout = Component.$timeout(f, refreshViewCheck.timeInterval()*1000);
}
});
};
/**
* @function $filter
* @memberof Component
* @desc Search for components matching some criterias
* @param {string} type - either 'events' or 'tasks'
* @param {object} [options] - additional options to the query
* @returns a collection of Components instances
*/
Component.$filter = function(type, options) {
var _this = this,
now = new Date(),
day = now.getDate(),
month = now.getMonth() + 1,
year = now.getFullYear(),
queryKey = '$query' + type.capitalize(),
params = {
day: '' + year + (month < 10?'0':'') + month + (day < 10?'0':'') + day,
};
Component.$startRefreshTimeout(type);
return this.$Preferences.ready().then(function() {
var futureComponentData,
dirty = false,
otherType;
angular.extend(_this.$query, params);
if (options) {
_.forEach(_.keys(options), function(key) {
// Query parameters common to events and tasks are compared
dirty |= (_this.$query[key] && options[key] != Component.$query[key]);
if (key == 'reload' && options[key])
dirty = true;
// Update either the common parameters or the type-specific parameters
else if (angular.isDefined(_this.$query[key]))
_this.$query[key] = options[key];
else
_this[queryKey][key] = options[key];
});
}
// Perform query with both common and type-specific parameters
futureComponentData = _this.$$resource.fetch(null, type + 'list',
angular.extend(_this[queryKey], _this.$query));
// Invalidate cached results of other type if $query has changed
otherType = (type == 'tasks')? '$events' : '$tasks';
if (dirty) {
delete Component[otherType];
Component.$log.debug('force reload of ' + otherType);
}
return _this.$unwrapCollection(type, futureComponentData);
});
};
/**
* @function $find
* @desc Fetch a component from a specific calendar.
* @param {string} calendarId - the calendar ID
* @param {string} componentId - the component ID
* @param {string} [occurrenceId] - the component ID
* @see {@link Calendar.$getComponent}
*/
Component.$find = function(calendarId, componentId, occurrenceId) {
var futureComponentData, path = [calendarId, componentId];
if (occurrenceId)
path.push(occurrenceId);
futureComponentData = this.$$resource.fetch(path.join('/'), 'view');
return new Component(futureComponentData);
};
/**
* @function filterCategories
* @desc Search for categories matching some criterias
* @param {string} search - the search string to match
* @returns a collection of strings
*/
Component.filterCategories = function(query) {
var re = new RegExp(query, 'i');
return _.filter(_.keys(Component.$categories), function(category) {
return category.search(re) != -1;
});
};
/**
* @function saveSelectedList
* @desc Save to the user's settings the currently selected list.
* @param {string} componentType - either "events" or "tasks"
* @returns a promise of the HTTP operation
*/
Component.saveSelectedList = function(componentType) {
return this.$$resource.post(null, 'saveSelectedList', { list: componentType + 'ListView' });
};
/**
* @function $eventsBlocksForView
* @desc Events blocks for a specific week
* @param {string} view - Either 'day' or 'week'
* @param {Date} type - Date of any day of the desired period
* @returns a promise of a collection of objects describing the events blocks
*/
Component.$eventsBlocksForView = function(view, date) {
var _this = this;
return Component.$Preferences.ready().then(function(data) {
var firstDayOfWeek, viewAction, startDate, endDate, params;
firstDayOfWeek = Component.$Preferences.defaults.SOGoFirstDayOfWeek;
if (view == 'day') {
viewAction = 'dayView';
startDate = endDate = date;
}
else if (view == 'multicolumnday') {
viewAction = 'multicolumndayView';
startDate = endDate = date;
}
else if (view == 'week') {
viewAction = 'weekView';
startDate = date.beginOfWeek(firstDayOfWeek);
endDate = new Date();
endDate.setTime(startDate.getTime());
endDate.addDays(6);
}
else if (view == 'month') {
viewAction = 'monthView';
startDate = date;
startDate.setDate(1);
startDate = startDate.beginOfWeek(firstDayOfWeek);
endDate = new Date();
endDate.setTime(date.getTime());
endDate.setMonth(endDate.getMonth() + 1);
endDate.addDays(-1);
endDate = endDate.endOfWeek(firstDayOfWeek);
}
return _this.$eventsBlocks(viewAction, startDate, endDate);
});
};
/**
* @function $eventsBlocks
* @desc Events blocks for a specific view and period
* @param {string} view - Either 'day', 'multicolumnday', 'week' or 'month'
* @param {Date} startDate - period's start date
* @param {Date} endDate - period's end date
* @returns a promise of a collection of objects describing the events blocks
*/
Component.$eventsBlocks = function(view, startDate, endDate) {
var params, futureComponentData, i, j, dayDates = [], dayNumbers = [],
deferred = Component.$q.defer();
params = { view: view.toLowerCase(), sd: startDate.getDayString(), ed: endDate.getDayString() };
futureComponentData = this.$$resource.fetch(null, 'eventsblocks', params);
futureComponentData.then(function(views) {
var reduceComponent, associateComponent;
reduceComponent = function(objects, eventData, i) {
var componentData = _.zipObject(this.eventsFields, eventData),
start = new Date(componentData.c_startdate * 1000),
component;
componentData.hour = start.getHourString();
componentData.blocks = [];
component = new Component(componentData);
// Filter out categories for which there's no associated color
component.categories = _.filter(component.categories, function(name) {
return Component.$Preferences.defaults.SOGoCalendarCategoriesColors[name];
});
objects.push(component);
return objects;
};
associateComponent = function(block) {
this[block.nbr].blocks.push(block); // Associate block to component
block.component = this[block.nbr]; // Associate component to block
};
Component.$views = [];
Component.$timeout(function() {
_.forEach(views, function(data, viewIndex) {
var components = [], blocks = {}, allDayBlocks = {}, viewData;
// Change some attributes names
data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_folder'), 1, 'pid');
data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_name'), 1, 'id');
data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_recurrence_id'), 1, 'occurrenceId');
data.eventsFields.splice(_.indexOf(data.eventsFields, 'c_title'), 1, 'summary');
// Instantiate Component objects
_.reduce(data.events, _.bind(reduceComponent, data), components);
// Associate Component objects to blocks positions
_.forEach(_.flatten(data.blocks), _.bind(associateComponent, components));
// Associate Component objects to all-day blocks positions
_.forEach(_.flatten(data.allDayBlocks), _.bind(associateComponent, components));
// Build array of dates
if (dayDates.length === 0) {
dayDates = _.flatMap(data.days, 'date');
dayNumbers = _.flatMap(data.days, 'number');
}
// Convert array of blocks to an object literal with date strings as keys
for (i = 0; i < data.blocks.length; i++) {
for (j = 0; j < data.blocks[i].length; j++) {
data.blocks[i][j].dayIndex = i + (viewIndex * data.blocks.length);
data.blocks[i][j].dayNumber = dayNumbers[i];
}
blocks[dayDates[i]] = data.blocks[i];
}
// Convert array of all-day blocks to object with days as keys
for (i = 0; i < data.allDayBlocks.length; i++) {
for (j = 0; j < data.allDayBlocks[i].length; j++) {
data.allDayBlocks[i][j].dayIndex = i + (viewIndex * data.allDayBlocks.length);
data.allDayBlocks[i][j].dayNumber = dayNumbers[i];
}
allDayBlocks[dayDates[i]] = data.allDayBlocks[i];
}
// "blocks" is now an object literal with the following structure:
// { day: [
// { start: number,
// length: number,
// siblings: number,
// realSiblings: number,
// position: number,
// nbr: number,
// component: Component },
// .. ],
// .. }
//
// Where day is a string with format YYYYMMDD
Component.$log.debug('blocks ready (' + _.flatten(data.blocks).length + ')');
Component.$log.debug('all day blocks ready (' + _.flatten(data.allDayBlocks).length + ')');
// Save the blocks to the object model
viewData = { blocks: blocks, allDayBlocks: allDayBlocks };
if (data.id && data.calendarName) {
// The multicolumnday view also includes calendar information
viewData.id = data.id;
viewData.calendarName = data.calendarName;
}
Component.$views.push(viewData);
});
deferred.resolve(Component.$views);
});
}, deferred.reject);
return deferred.promise;
};
/**
* @function $unwrapCollection
* @desc Unwrap a promise and instanciate new Component objects using received data.
* @param {string} type - either 'events' or 'tasks'
* @param {promise} futureComponentData - a promise of the components' metadata
* @returns a promise of the HTTP operation
*/
Component.$unwrapCollection = function(type, futureComponentData) {
var _this = this,
components = [];
return futureComponentData.then(function(data) {
return Component.$timeout(function() {
var fields = _.invokeMap(data.fields, 'toLowerCase');
fields.splice(_.indexOf(fields, 'c_folder'), 1, 'pid');
fields.splice(_.indexOf(fields, 'c_name'), 1, 'id');
fields.splice(_.indexOf(fields, 'c_recurrence_id'), 1, 'occurrenceId');
// Instanciate Component objects
_.reduce(data[type], function(components, componentData, i) {
var data = _.zipObject(fields, componentData), component;
component = new Component(data);
// Filter out categories for which there's no associated color
component.categories = _.filter(component.categories, function(name) {
return Component.$Preferences.defaults.SOGoCalendarCategoriesColors[name];
});
components.push(component);
return components;
}, components);
Component.$log.debug('list of ' + type + ' ready (' + components.length + ')');
// Save the list of components to the object model
Component['$' + type] = components;
return components;
});
});
};
/**
* @function $resetGhost
* @desc Prepare the ghost object for the next drag by resetting appropriate attributes
*/
Component.$resetGhost = function() {
this.$ghost.pointerHandler = null;
this.$ghost.component = null;
this.$ghost.startHour = null;
this.$ghost.endHour = null;
};
/**
* @function $parseDate
* @desc Parse a date string with format YYYY-MM-DDTHH:MM
* @param {string} dateString - the string representing the date
* @param {object} [options] - additional options (use {no_time: true} to ignore the time)
* @returns a date object
*/
Component.$parseDate = function(dateString, options) {
var date, time;
date = dateString.substring(0,10).split('-');
if (options && options.no_time)
return new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]));
time = dateString.substring(11,16).split(':');
return new Date(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]),
parseInt(time[0]), parseInt(time[1]), 0, 0);
};
/**
* @function init
* @memberof Component.prototype
* @desc Extend instance with required attributes and new data.
* @param {object} data - attributes of component
*/
Component.prototype.init = function(data) {
var _this = this;
this.categories = [];
this.repeat = {};
this.alarm = { action: 'display', quantity: 5, unit: 'MINUTES', reference: 'BEFORE', relation: 'START' };
this.status = 'not-specified';
this.delta = 60;
angular.extend(this, data);
if (this.component == 'vevent')
this.type = 'appointment';
else if (this.component == 'vtodo')
this.type = 'task';
if (this.startDate) {
if (angular.isString(this.startDate))
// Ex: 2015-10-25T22:34:51+00:00
this.start = Component.$parseDate(this.startDate);
else
// Date object
this.start = this.startDate;
}
else if (this.type == 'appointment') {
this.start = new Date();
this.start.setMinutes(Math.round(this.start.getMinutes()/15)*15);
}
if (this.endDate) {
this.end = Component.$parseDate(this.endDate);
this.delta = this.start.minutesTo(this.end);
}
else if (this.type == 'appointment') {
this.setDelta(this.delta);
}
if (this.dueDate)
this.due = Component.$parseDate(this.dueDate);
if (this.completedDate)
this.completed = Component.$parseDate(this.completedDate);
else if (this.type == 'task')
this.completed = new Date();
if (this.c_category)
this.categories = _.invokeMap(this.c_category, 'asCSSIdentifier');
// Parse recurrence rule definition and initialize default values
this.$isRecurrent = angular.isDefined(data.repeat);
if (this.repeat.days) {
var byDayMask = _.find(this.repeat.days, function(o) {
return angular.isDefined(o.occurrence);
});
if (byDayMask) {
if (this.repeat.frequency == 'yearly')
this.repeat.year = { byday: true };
this.repeat.month = {
type: 'byday',
occurrence: byDayMask.occurrence.toString(),
day: byDayMask.day
};
}
}
else {
this.repeat.days = [];
}
if (angular.isUndefined(this.repeat.frequency))
this.repeat.frequency = 'never';
if (angular.isUndefined(this.repeat.interval))
this.repeat.interval = 1;
if (angular.isUndefined(this.repeat.month))
this.repeat.month = { occurrence: '1', day: 'SU', type: 'bymonthday' };
if (angular.isUndefined(this.repeat.monthdays))
// TODO: initialize this.repeat.monthdays with month day of start date
this.repeat.monthdays = [];
if (angular.isUndefined(this.repeat.months))
// TODO: initialize this.repeat.months with month of start date
this.repeat.months = [];
if (angular.isUndefined(this.repeat.year))
this.repeat.year = {};
if (this.repeat.count)
this.repeat.end = 'count';
else if (this.repeat.until) {
this.repeat.end = 'until';
this.repeat.until = Component.$parseDate(this.repeat.until, { no_time: true });
}
else
this.repeat.end = 'never';
this.$hasCustomRepeat = this.hasCustomRepeat();
if (this.isNew) {
// Set default values
Component.$Preferences.ready().then(function() {
var type = (_this.type == 'appointment')? 'Events' : 'Tasks';
// Set default classification
_this.classification = Component.$Preferences.defaults['SOGoCalendar' + type + 'DefaultClassification'].toLowerCase();
// Set default alarm
var units = { M: 'MINUTES', H: 'HOURS', D: 'DAYS', W: 'WEEKS' };
var match = /-PT?([0-9]+)([MHDW])/.exec(Component.$Preferences.defaults.SOGoCalendarDefaultReminder);
if (match) {
_this.$hasAlarm = true;
_this.alarm.quantity = parseInt(match[1]);
_this.alarm.unit = units[match[2]];
}
// Set notitifications
_this.sendAppointmentNotifications = Component.$Preferences.defaults.SOGoAppointmentSendEMailNotifications;
});
}
else {
this.$hasAlarm = angular.isDefined(data.alarm);
}
// Allow the component to be moved to a different calendar
this.destinationCalendar = this.pid;
// if (this.organizer && this.organizer.email) {
// this.organizer.$image = Component.$gravatar(this.organizer.email, 32);
// }
// Load freebusy of attendees
this.updateFreeBusy();
this.selected = false;
};
/**
* @function hasCustomRepeat
* @memberof Component.prototype
* @desc Check if the component has a custom recurrence rule.
* @returns true if the recurrence rule requires the full recurrence editor
*/
Component.prototype.hasCustomRepeat = function() {
var b = angular.isDefined(this.repeat) &&
(this.repeat.interval > 1 ||
this.repeat.days && this.repeat.days.length > 0 ||
this.repeat.monthdays && this.repeat.monthdays.length > 0 ||
this.repeat.months && this.repeat.months.length > 0);
return b;
};
/**
* @function isEditable
* @memberof Component.prototype
* @desc Check if the component is editable and not an occurrence of a recurrent component
* @returns true or false
*/
Component.prototype.isEditable = function() {
return (!this.occurrenceId && !this.isReadOnly);
};
/**
* @function isEditableOccurrence
* @memberof Component.prototype
* @desc Check if the component is editable and an occurrence of a recurrent component
* @returns true or false
*/
Component.prototype.isEditableOccurrence = function() {
return (this.occurrenceId && !this.isReadOnly);
};
/**
* @function isInvitation
* @memberof Component.prototype
* @desc Check if the component an invitation and not an occurrence of a recurrent component
* @returns true or false
*/
Component.prototype.isInvitation = function() {
return (!this.occurrenceId && this.userHasRSVP);
};
/**
* @function isInvitationOccurrence
* @memberof Component.prototype
* @desc Check if the component an invitation and an occurrence of a recurrent component
* @returns true or false
*/
Component.prototype.isInvitationOccurrence = function() {
return (this.occurrenceId && this.userHasRSVP);
};
/**
* @function isReadOnly
* @memberof Component.prototype
* @desc Check if the component is not editable and not an invitation
* @returns true or false
*/
Component.prototype.isReadOnly = function() {
return (this.isReadOnly && !this.userHasRSVP);
};
/**
* @function enablePercentComplete
* @memberof Component.prototype
* @desc Check if the percent completion should be enabled with respect to the
* component's type and status.
* @returns true if the percent completion should be displayed
*/
Component.prototype.enablePercentComplete = function() {
return (this.type == 'task' &&
this.status != 'not-specified' &&
this.status != 'cancelled');
};
/**
* @function coversFreeBusy
* @memberof Component.prototype
* @desc Check if a specific quarter matches the component's period
* @returns true if the quarter covers the component's period
*/
Component.prototype.coversFreeBusy = function(day, hour, quarter) {
var b = (angular.isDefined(this.freebusy[day]) &&
angular.isDefined(this.freebusy[day][hour]) &&
this.freebusy[day][hour][quarter] == 1);
return b;
};
/**
* @function updateFreeBusyCoverage
* @memberof Component.prototype
* @desc Build a 15-minute-based representation of the component's period.
* @returns an object literal hashed by days and hours and arrays of four 1's and 0's
*/
Component.prototype.updateFreeBusyCoverage = function() {
var _this = this, freebusy = {};
if (this.start && this.end) {
var roundedStart = new Date(this.start.getTime()),
roundedEnd = new Date(this.end.getTime()),
startQuarter = parseInt(roundedStart.getMinutes()/15 + 0.5),
endQuarter = parseInt(roundedEnd.getMinutes()/15 + 0.5);
roundedStart.setMinutes(15*startQuarter);
roundedEnd.setMinutes(15*endQuarter);
_.forEach(roundedStart.daysUpTo(roundedEnd), function(date, index) {
var currentDay = date.getDate(),
dayKey = date.getDayString(),
hourKey;
if (dayKey == _this.start.getDayString()) {
hourKey = date.getHours().toString();
freebusy[dayKey] = {};
freebusy[dayKey][hourKey] = [];
while (startQuarter > 0) {
freebusy[dayKey][hourKey].push(0);
startQuarter--;
}
}
else {
date = date.beginOfDay();
freebusy[dayKey] = {};
}
while (date.getTime() < _this.end.getTime() &&
date.getDate() == currentDay) {
hourKey = date.getHours().toString();
if (angular.isUndefined(freebusy[dayKey][hourKey]))
freebusy[dayKey][hourKey] = [];
freebusy[dayKey][hourKey].push(1);
date.addMinutes(15);
}
});
return freebusy;
}
};
/**
* @function updateFreeBusy
* @memberof Component.prototype
* @desc Update the freebusy coverage representation and the attendees freebusy information
*/
Component.prototype.updateFreeBusy = function() {
var _this = this;
this.freebusy = this.updateFreeBusyCoverage();
if (this.attendees) {
_.forEach(this.attendees, function(attendee) {
attendee.image = Component.$gravatar(attendee.email, 32);
_this.updateFreeBusyAttendee(attendee);
});
}
};
/**
* @function setDelta
* @memberof Component.prototype
* @desc Set the end time to the specified number of minutes after the start time.
* @param {number} delta - the number of minutes
*/
Component.prototype.setDelta = function(delta) {
this.delta = delta;
this.end = new Date(this.start.getTime());
this.end.setMinutes(Math.round(this.end.getMinutes()/15)*15);
this.end.addMinutes(this.delta);
};
/**
* @function updateFreeBusyAttendee
* @memberof Component.prototype
* @desc Update the freebusy information for the component's period for a specific attendee.
* @param {Object} card - an Card object instance of the attendee
*/
Component.prototype.updateFreeBusyAttendee = function(attendee) {
var params, url, days;
if (attendee.uid) {
params =
{
sday: this.start.getDayString(),
eday: this.end.getDayString()
};
url = ['..', '..', attendee.uid, 'freebusy.ifb'];
days = _.map(this.start.daysUpTo(this.end), function(day) { return day.getDayString(); });
if (angular.isUndefined(attendee.freebusy))
attendee.freebusy = {};
// Fetch FreeBusy information
Component.$$resource.fetch(url.join('/'), 'ajaxRead', params).then(function(data) {
_.forEach(days, function(day) {
var hour;
if (angular.isUndefined(attendee.freebusy[day]))
attendee.freebusy[day] = {};
if (angular.isUndefined(data[day]))
data[day] = {};
for (var i = 0; i <= 23; i++) {
hour = i.toString();
if (data[day][hour])
attendee.freebusy[day][hour] = [
data[day][hour]["0"],
data[day][hour]["15"],
data[day][hour]["30"],
data[day][hour]["45"]
];
else
attendee.freebusy[day][hour] = [0, 0, 0, 0];
}
});
});
}
};
/**
* @function getClassName
* @memberof Component.prototype
* @desc Return the component CSS class name based on its container (calendar) ID.
* @param {string} [base] - the prefix to add to the class name (defaults to "fg")
* @returns a string representing the foreground CSS class name
*/
Component.prototype.getClassName = function(base) {
if (angular.isUndefined(base))
base = 'fg';
return base + '-folder' + (this.destinationCalendar || this.c_folder || this.pid);
};
/**
* @function addAttendee
* @memberof Component.prototype
* @desc Add an attendee and fetch his freebusy info.
* @param {Object} card - an Card object instance to be added to the attendees list
*/
Component.prototype.addAttendee = function(card) {
var _this = this, attendee, list, url, params;
if (card) {
if (card.$isList({expandable: true})) {
// Decompose list members
list = Component.$Card.$find(card.container, card.c_name);
list.$id().then(function(listId) {
_.forEach(list.refs, function(ref) {
attendee = {
name: ref.c_cn,
email: ref.$preferredEmail(),
role: 'req-participant',
status: 'needs-action',
uid: ref.c_uid
};
if (!_.find(_this.attendees, function(o) {
return o.email == attendee.email;
})) {
// Contact is not already an attendee, add it
attendee.image = Component.$gravatar(attendee.email, 32);
if (_this.attendees)
_this.attendees.push(attendee);
else
_this.attendees = [attendee];
_this.updateFreeBusyAttendee(attendee);
}
});
});
}
else {
// Single contact
attendee = {
name: card.c_cn,
email: card.$preferredEmail(),
role: 'req-participant',
status: 'needs-action',
uid: card.c_uid
};
if (!_.find(this.attendees, function(o) {
return o.email == attendee.email;
})) {
attendee.image = Component.$gravatar(attendee.email, 32);
if (this.attendees)
this.attendees.push(attendee);
else
this.attendees = [attendee];
this.updateFreeBusyAttendee(attendee);
}
}
}
};
/**
* @function hasAttendee
* @memberof Component.prototype
* @desc Verify if one of the email addresses of a Card instance matches an attendee.
* @param {Object} card - an Card object instance
* @returns true if the Card matches an attendee
*/
Component.prototype.hasAttendee = function(card) {
var attendee = _.find(this.attendees, function(attendee) {
return _.find(card.emails, function(email) {
return email.value == attendee.email;
});
});
return angular.isDefined(attendee);
};
/**
* @function deleteAttendee
* @memberof Component.prototype
* @desc Remove an attendee from the component
* @param {Object} attendee - an object literal defining an attendee
*/
Component.prototype.deleteAttendee = function(attendee) {
var index = _.findIndex(this.attendees, function(currentAttendee) {
return currentAttendee.email == attendee.email;
});
this.attendees.splice(index, 1);
};
/**
* @function canRemindAttendeesByEmail
* @memberof Component.prototype
* @desc Verify if the component's reminder must be send by email and if it has at least one attendee.
* @returns true if attendees can receive a reminder by email
*/
Component.prototype.canRemindAttendeesByEmail = function() {
return this.alarm.action == 'email' &&
!this.isReadOnly &&
this.attendees && this.attendees.length > 0;
};
/**
* @function addAttachUrl
* @memberof Component.prototype
* @desc Add a new attach URL if not already defined
* @param {string} attachUrl - the URL
* @returns the number of values in the list of attach URLs
*/
Component.prototype.addAttachUrl = function(attachUrl) {
if (angular.isUndefined(this.attachUrls)) {
this.attachUrls = [{value: attachUrl}];
}
else {
for (var i = 0; i < this.attachUrls.length; i++) {
if (this.attachUrls[i].value == attachUrl) {
break;
}
}
if (i == this.attachUrls.length)
this.attachUrls.push({value: attachUrl});
}
return this.attachUrls.length - 1;
};
/**
* @function deleteAttachUrl
* @memberof Component.prototype
* @desc Remove an attach URL
* @param {number} index - the URL index in the list of attach URLs
*/
Component.prototype.deleteAttachUrl = function(index) {
if (index > -1 && this.attachUrls.length > index) {
this.attachUrls.splice(index, 1);
}
};
/**
* @function $addDueDate
* @memberof Component.prototype
* @desc Add a due date
*/
Component.prototype.$addDueDate = function() {
this.due = new Date();
this.due.setMinutes(Math.round(this.due.getMinutes()/15)*15);
this.dueDate = this.due.toISOString();
};
/**
* @function $deleteDueDate
* @memberof Component.prototype
* @desc Delete a due date
*/
Component.prototype.$deleteDueDate = function() {
delete this.due;
delete this.dueDate;
};
/**
* @function $addStartDate
* @memberof Component.prototype
* @desc Add a start date
*/
Component.prototype.$addStartDate = function() {
this.start = new Date();
this.start.setMinutes(Math.round(this.start.getMinutes()/15)*15);
};
/**
* @function $deleteStartDate
* @memberof Component.prototype
* @desc Delete a start date
*/
Component.prototype.$deleteStartDate = function() {
delete this.start;
delete this.startDate;
};