JLChen
2021-08-02 38f4fb064df09f344fc3237409c76a9fba2a8a9e
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
/*
 * Copyright (c) 2010-2020 Belledonne Communications SARL.
 *
 * This file is part of linphone-iphone
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
 
#import "HistoryListTableView.h"
#import "UIHistoryCell.h"
#import "LinphoneManager.h"
#import "PhoneMainView.h"
#import "Utils.h"
 
@implementation HistoryListTableView
 
@synthesize missedFilter;
 
#pragma mark - Lifecycle Functions
 
- (void)initHistoryTableViewController {
    missedFilter = false;
}
 
- (id)init {
    self = [super init];
    if (self) {
        [self initHistoryTableViewController];
    }
    return self;
}
 
- (id)initWithCoder:(NSCoder *)decoder {
    self = [super initWithCoder:decoder];
    if (self) {
        [self initHistoryTableViewController];
    }
    return self;
}
 
#pragma mark - ViewController Functions
 
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(loadData)
                                               name:kLinphoneAddressBookUpdate
                                             object:nil];
 
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(loadData)
                                               name:kLinphoneCallUpdate
                                             object:nil];
 
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(coreUpdateEvent:)
                                               name:kLinphoneCoreUpdate
                                             object:nil];
    [self loadData];
}
 
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
 
    [NSNotificationCenter.defaultCenter removeObserver:self name:kLinphoneAddressBookUpdate object:nil];
    [NSNotificationCenter.defaultCenter removeObserver:self name:kLinphoneCoreUpdate object:nil];
    [NSNotificationCenter.defaultCenter removeObserver:self name:kLinphoneCallUpdate object:nil];
}
 
#pragma mark - Event Functions
 
- (void)coreUpdateEvent:(NSNotification *)notif {
    @try {
        // Invalid all pointers
        [self loadData];
    }
    @catch (NSException *exception) {
        if ([exception.name isEqualToString:@"LinphoneCoreException"]) {
            LOGE(@"Core already destroyed");
            return;
        }
        LOGE(@"Uncaught exception : %@", exception.description);
        abort();
    }
}
 
#pragma mark - Property Functions
 
- (void)setMissedFilter:(BOOL)amissedFilter {
    if (missedFilter == amissedFilter) {
        return;
    }
    missedFilter = amissedFilter;
    [self loadData];
}
 
#pragma mark - UITableViewDataSource Functions
 
- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    [calendar setTimeZone:timeZone];
    NSDateComponents *dateComps =
        [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:inputDate];
 
    dateComps.hour = dateComps.minute = dateComps.second = 0;
    return [calendar dateFromComponents:dateComps];
}
 
- (void)loadData {
    for (id day in self.sections.allKeys) {
        for (id log in self.sections[day]) {
            linphone_call_log_unref([log pointerValue]);
        }
    }
 
    const bctbx_list_t *logs = linphone_core_get_call_logs(LC);
    self.sections = [NSMutableDictionary dictionary];
    while (logs != NULL) {
        LinphoneCallLog *log = (LinphoneCallLog *)logs->data;
        if (!missedFilter || linphone_call_log_get_status(log) == LinphoneCallMissed) {
            NSDate *startDate = [self
                dateAtBeginningOfDayForDate:[NSDate
                                                dateWithTimeIntervalSince1970:linphone_call_log_get_start_date(log)]];
            NSMutableArray *eventsOnThisDay = [self.sections objectForKey:startDate];
            if (eventsOnThisDay == nil) {
                eventsOnThisDay = [NSMutableArray array];
                [self.sections setObject:eventsOnThisDay forKey:startDate];
            }
 
            linphone_call_log_set_user_data(log, NULL);
 
            // if this contact was already the previous entry, do not add it twice
            LinphoneCallLog *prev = [eventsOnThisDay lastObject] ? [[eventsOnThisDay lastObject] pointerValue] : NULL;
            if (prev && linphone_address_weak_equal(linphone_call_log_get_remote_address(prev),
                                                    linphone_call_log_get_remote_address(log))) {
                bctbx_list_t *list = linphone_call_log_get_user_data(prev);
                list = bctbx_list_append(list, log);
                linphone_call_log_set_user_data(prev, list);
            } else {
                [eventsOnThisDay addObject:[NSValue valueWithPointer:linphone_call_log_ref(log)]];
            }
        }
        logs = bctbx_list_next(logs);
    }
 
    [self computeSections];
 
    [super loadData];
    
    if (IPAD) {
        if (![self selectFirstRow]) {
            HistoryDetailsView *view = VIEW(HistoryDetailsView);
            [view setCallLogId:nil];
        }
    }
}
 
- (void)computeSections {
    NSArray *unsortedDays = [self.sections allKeys];
    _sortedDays = [[NSMutableArray alloc]
        initWithArray:[unsortedDays sortedArrayUsingComparator:^NSComparisonResult(NSDate *d1, NSDate *d2) {
          return [d2 compare:d1]; // reverse order
        }]];
}
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sortedDays.count;
}
 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *logs = [_sections objectForKey:_sortedDays[section]];
    return logs.count;
}
 
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    CGRect frame = CGRectMake(0, 0, tableView.frame.size.width, 44);
    UIView *tempView = [[UIView alloc] initWithFrame:frame];
    if (@available(iOS 13, *)) {
        tempView.backgroundColor = [UIColor systemBackgroundColor];
    } else {
        tempView.backgroundColor = [UIColor whiteColor];
    }
 
    UILabel *tempLabel = [[UILabel alloc] initWithFrame:frame];
    tempLabel.backgroundColor = [UIColor clearColor];
    tempLabel.textColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"color_A.png"]];
    NSDate *eventDate = _sortedDays[section];
    NSDate *currentDate = [self dateAtBeginningOfDayForDate:[NSDate date]];
    if ([eventDate isEqualToDate:currentDate]) {
        tempLabel.text = NSLocalizedString(@"TODAY", nil);
    } else if ([eventDate isEqualToDate:[currentDate dateByAddingTimeInterval:-3600 * 24]]) {
        tempLabel.text = NSLocalizedString(@"YESTERDAY", nil);
    } else {
        tempLabel.text = [LinphoneUtils timeToString:eventDate.timeIntervalSince1970 withFormat:LinphoneDateHistoryList]
                             .uppercaseString;
    }
    tempLabel.textAlignment = NSTextAlignmentCenter;
    tempLabel.font = [UIFont boldSystemFontOfSize:17];
    tempLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [tempView addSubview:tempLabel];
 
    return tempView;
}
 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *kCellId = @"UIHistoryCell";
    UIHistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    if (cell == nil) {
        cell = [[UIHistoryCell alloc] initWithIdentifier:kCellId];
    }
 
    id logId = [_sections objectForKey:_sortedDays[indexPath.section]][indexPath.row];
    LinphoneCallLog *log = [logId pointerValue];
    [cell setCallLog:log];
    [super accessoryForCell:cell atPath:indexPath];
    cell.contentView.userInteractionEnabled = false;
    return cell;
}
 
#pragma mark - UITableViewDelegate Functions
 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    if (![self isEditing]) {
        id log = [_sections objectForKey:_sortedDays[indexPath.section]][indexPath.row];
        LinphoneCallLog *callLog = [log pointerValue];
        if (callLog != NULL) {
            if (IPAD) {
                UIHistoryCell *cell = (UIHistoryCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
                [cell onDetails:self];
            } else {
                const LinphoneAddress *addr = linphone_call_log_get_remote_address(callLog);
                [LinphoneManager.instance call:addr];
            }
        }
    }
}
 
- (void)tableView:(UITableView *)tableView
    commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
     forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [tableView beginUpdates];
        id log = [_sections objectForKey:_sortedDays[indexPath.section]][indexPath.row];
        LinphoneCallLog *callLog = [log pointerValue];
        MSList *count = linphone_call_log_get_user_data(callLog);
        while (count) {
            linphone_core_remove_call_log(LC, count->data);
            count = count->next;
        }
        linphone_core_remove_call_log(LC, callLog);
        linphone_call_log_unref(callLog);
        [[_sections objectForKey:_sortedDays[indexPath.section]] removeObject:log];
        if (((NSArray *)[_sections objectForKey:_sortedDays[indexPath.section]]).count == 0) {
            [_sections removeObjectForKey:_sortedDays[indexPath.section]];
            [_sortedDays removeObjectAtIndex:indexPath.section];
            [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section]
                     withRowAnimation:UITableViewRowAnimationFade];
        }
 
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
        [tableView endUpdates];
    }
}
 
- (void)removeSelectionUsing:(void (^)(NSIndexPath *))remover {
    [super removeSelectionUsing:^(NSIndexPath *indexPath) {
      id log = [_sections objectForKey:_sortedDays[indexPath.section]][indexPath.row];
      LinphoneCallLog *callLog = [log pointerValue];
      MSList *count = linphone_call_log_get_user_data(callLog);
      while (count) {
          linphone_core_remove_call_log(LC, count->data);
          count = count->next;
      }
      linphone_core_remove_call_log(LC, callLog);
      linphone_call_log_unref(callLog);
      [[_sections objectForKey:_sortedDays[indexPath.section]] removeObject:log];
      if (((NSArray *)[_sections objectForKey:_sortedDays[indexPath.section]]).count == 0) {
          [_sections removeObjectForKey:_sortedDays[indexPath.section]];
          [_sortedDays removeObjectAtIndex:indexPath.section];
      }
    }];
}
 
@end