Repository navigation
Expand file tree
/
Copy pathHAEntityListViewController.m
More file actions
422 lines (387 loc) · 18.1 KB
/
Copy pathHAEntityListViewController.m
File metadata and controls
422 lines (387 loc) · 18.1 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
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
#import "HAEntityListViewController.h"
#import "HAAuthClient.h"
#import "HADevicePickerViewController.h"
#import "HACameraViewController.h"
#import "HAEntityDetailViewController.h"
#import "HAHomeManager.h"
#import "HAHomesViewController.h"
#import "HASettingsViewController.h"
#import "HAURLCompatibility.h"
#import "HAWatchManager.h"
@interface HAEntityListViewController () <NSURLConnectionDataDelegate, UISearchBarDelegate,
HAAuthClientDelegate, HADevicePickerViewControllerDelegate, HAHomesViewControllerDelegate>
@property(nonatomic, copy) NSString *baseURLString;
@property(nonatomic, copy) NSString *accessToken;
@property(nonatomic, retain) NSArray *entities;
@property(nonatomic, retain) NSArray *allEntities;
@property(nonatomic, retain) UISegmentedControl *viewSelector;
@property(nonatomic, retain) UISearchBar *searchBar;
@property(nonatomic, copy) NSString *searchText;
@property(nonatomic, retain) UINavigationController *devicePickerNavigationController;
@property(nonatomic, retain) UINavigationController *homesNavigationController;
@property(nonatomic, retain) NSMutableData *responseData;
@property(nonatomic, retain) NSURLConnection *connection;
@property(nonatomic, retain) HAAuthClient *authClient;
@property(nonatomic, assign) NSInteger statusCode;
@property(nonatomic, assign) BOOL retriedAfterTokenRefresh;
@end
@implementation HAEntityListViewController
@synthesize baseURLString = _baseURLString;
@synthesize accessToken = _accessToken;
@synthesize entities = _entities;
@synthesize allEntities = _allEntities;
@synthesize viewSelector = _viewSelector;
@synthesize searchBar = _searchBar;
@synthesize searchText = _searchText;
@synthesize devicePickerNavigationController = _devicePickerNavigationController;
@synthesize homesNavigationController = _homesNavigationController;
@synthesize responseData = _responseData;
@synthesize connection = _connection;
@synthesize authClient = _authClient;
@synthesize statusCode = _statusCode;
@synthesize retriedAfterTokenRefresh = _retriedAfterTokenRefresh;
- (id)initWithBaseURLString:(NSString *)baseURLString accessToken:(NSString *)accessToken {
self = [super initWithStyle:UITableViewStylePlain];
if (self) {
while ([baseURLString hasSuffix:@"/"]) {
baseURLString = [baseURLString substringToIndex:[baseURLString length] - 1];
}
self.baseURLString = baseURLString;
self.accessToken = accessToken;
self.entities = [NSArray array];
self.allEntities = [NSArray array];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Home Assistant";
self.viewSelector = [[[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:@"My Devices", @"All Devices", nil]] autorelease];
[self.viewSelector sizeToFit];
CGRect selectorFrame = self.viewSelector.frame;
selectorFrame.size.width = MIN(selectorFrame.size.width, 190.0);
selectorFrame.size.height = MIN(selectorFrame.size.height, 25.0);
self.viewSelector.frame = selectorFrame;
self.viewSelector.selectedSegmentIndex = 0;
[self.viewSelector addTarget:self action:@selector(viewSelectionChanged:)
forControlEvents:UIControlEventValueChanged];
self.navigationItem.titleView = self.viewSelector;
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
initWithTitle:@"⌂"
style:UIBarButtonItemStylePlain
target:self
action:@selector(showHomes:)] autorelease];
[self updateNavigationButton];
self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)] autorelease];
self.searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.searchBar.placeholder = @"Search all devices";
self.searchBar.delegate = self;
[self refresh:nil];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self updateVisibleEntities];
}
- (void)refresh:(id)sender {
[self.connection cancel];
NSString *savedAccessToken = [HAHomeManager accessTokenForBaseURLString:self.baseURLString];
if ([savedAccessToken length] > 0) {
self.accessToken = savedAccessToken;
}
NSURL *url = HAURLWithString([self.baseURLString stringByAppendingString:@"/api/states"]);
NSMutableURLRequest *request = HAMutableURLRequestWithURL(url);
[request setValue:[NSString stringWithFormat:@"Bearer %@", self.accessToken]
forHTTPHeaderField:@"Authorization"];
self.responseData = [NSMutableData data];
self.connection = HAStartURLConnection(request, self);
self.navigationItem.rightBarButtonItem.enabled = NO;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.responseData setLength:0];
self.statusCode = [response respondsToSelector:@selector(statusCode)]
? [(id)response statusCode]
: 0;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.navigationItem.rightBarButtonItem.enabled = YES;
self.connection = nil;
if (self.statusCode == 401) {
self.responseData = nil;
if (!self.retriedAfterTokenRefresh) {
[self refreshExpiredSession];
} else {
self.retriedAfterTokenRefresh = NO;
[self showError:@"Home Assistant rejected the renewed session. Please sign in again."];
}
return;
}
NSError *error = nil;
id response = [NSJSONSerialization JSONObjectWithData:self.responseData options:0 error:&error];
self.responseData = nil;
if (![response isKindOfClass:[NSArray class]]) {
[self showError:@"Home Assistant returned an unreadable entity list."];
return;
}
self.allEntities = [response sortedArrayUsingComparator:^NSComparisonResult(id first, id second) {
return [[self displayNameForEntity:first] localizedCaseInsensitiveCompare:[self displayNameForEntity:second]];
}];
[[HAWatchManager sharedManager] updateEntities:self.allEntities];
self.retriedAfterTokenRefresh = NO;
[self updateVisibleEntities];
}
- (void)refreshExpiredSession {
NSString *refreshToken = [HAHomeManager refreshTokenForBaseURLString:self.baseURLString];
if ([refreshToken length] == 0) {
[self showError:@"Your session expired and cannot be renewed. Please sign in again."];
return;
}
self.retriedAfterTokenRefresh = YES;
self.authClient = [[[HAAuthClient alloc] initWithBaseURLString:self.baseURLString] autorelease];
self.authClient.delegate = self;
[self.authClient refreshAccessTokenWithRefreshToken:refreshToken];
}
- (void)authClient:(HAAuthClient *)client didAuthenticateWithAccessToken:(NSString *)accessToken {
self.accessToken = accessToken;
[HAHomeManager updateAccessToken:accessToken forBaseURLString:self.baseURLString];
self.authClient.delegate = nil;
self.authClient = nil;
[self refresh:nil];
}
- (void)authClient:(HAAuthClient *)client didRequestVerificationCodeWithMessage:(NSString *)message {
[self authClient:client didFailWithMessage:@"Home Assistant unexpectedly requested verification while renewing the session."];
}
- (void)authClient:(HAAuthClient *)client didFailWithMessage:(NSString *)message {
self.authClient.delegate = nil;
self.authClient = nil;
self.retriedAfterTokenRefresh = NO;
self.navigationItem.rightBarButtonItem.enabled = YES;
[self showError:[NSString stringWithFormat:@"Could not renew the session: %@", message]];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
self.navigationItem.rightBarButtonItem.enabled = YES;
self.connection = nil;
self.responseData = nil;
[self showError:[NSString stringWithFormat:@"Connection failed: %@", [error localizedDescription]]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.entities count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"HAEntityCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:identifier] autorelease];
}
NSDictionary *entity = [self.entities objectAtIndex:indexPath.row];
cell.textLabel.text = [self displayNameForEntity:entity];
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ — %@",
[entity objectForKey:@"entity_id"] ?: @"Unknown entity",
[entity objectForKey:@"state"] ?: @"unknown"];
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return self.viewSelector.selectedSegmentIndex == 0;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return self.viewSelector.selectedSegmentIndex == 0
? UITableViewCellEditingStyleDelete
: UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle != UITableViewCellEditingStyleDelete ||
self.viewSelector.selectedSegmentIndex != 0 ||
indexPath.row >= (NSInteger)[self.entities count]) {
return;
}
NSString *entityID = [[self.entities objectAtIndex:indexPath.row] objectForKey:@"entity_id"];
NSMutableArray *selectedIDs = [NSMutableArray arrayWithArray:[HAHomeManager selectedEntityIDs]];
[selectedIDs removeObject:entityID];
[HAHomeManager setSelectedEntityIDs:selectedIDs];
[[HAWatchManager sharedManager] syncCurrentContext];
[self updateVisibleEntities];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *entity = [self.entities objectAtIndex:indexPath.row];
NSString *entityID = [entity objectForKey:@"entity_id"];
if ([entityID hasPrefix:@"camera."]) {
HACameraViewController *camera = [[[HACameraViewController alloc]
initWithEntity:entity baseURLString:self.baseURLString accessToken:self.accessToken] autorelease];
[self.navigationController pushViewController:camera animated:YES];
return;
}
HAEntityDetailViewController *controller = [[[HAEntityDetailViewController alloc]
initWithEntity:entity baseURLString:self.baseURLString accessToken:self.accessToken] autorelease];
[self.navigationController pushViewController:controller animated:YES];
}
- (void)viewSelectionChanged:(UISegmentedControl *)sender {
[self updateNavigationButton];
self.tableView.tableHeaderView = sender.selectedSegmentIndex == 1 ? self.searchBar : nil;
if (sender.selectedSegmentIndex == 0) {
self.searchText = nil;
self.searchBar.text = nil;
}
[self updateVisibleEntities];
}
- (void)addDevice:(id)sender {
NSArray *favorites = [HAHomeManager selectedEntityIDs];
NSMutableArray *available = [NSMutableArray array];
for (NSDictionary *entity in self.allEntities) {
if (![favorites containsObject:[entity objectForKey:@"entity_id"]]) {
[available addObject:entity];
}
}
HADevicePickerViewController *picker = [[[HADevicePickerViewController alloc]
initWithEntities:available] autorelease];
picker.delegate = self;
self.devicePickerNavigationController = [[[UINavigationController alloc]
initWithRootViewController:picker] autorelease];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
self.devicePickerNavigationController.modalPresentationStyle = UIModalPresentationFormSheet;
} else {
self.devicePickerNavigationController.modalPresentationStyle = UIModalPresentationPageSheet;
self.devicePickerNavigationController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
}
[self presentViewController:self.devicePickerNavigationController animated:YES completion:nil];
}
- (void)devicePicker:(HADevicePickerViewController *)picker didAddEntityID:(NSString *)entityID {
NSMutableArray *favorites = [NSMutableArray arrayWithArray:[HAHomeManager selectedEntityIDs]];
if (![favorites containsObject:entityID]) {
[favorites addObject:entityID];
[HAHomeManager setSelectedEntityIDs:favorites];
[[HAWatchManager sharedManager] syncCurrentContext];
}
[self dismissViewControllerAnimated:YES completion:nil];
self.devicePickerNavigationController = nil;
[self updateVisibleEntities];
}
- (void)devicePickerDidCancel:(HADevicePickerViewController *)picker {
[self dismissViewControllerAnimated:YES completion:nil];
self.devicePickerNavigationController = nil;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
self.searchText = searchText;
[self updateVisibleEntities];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
}
- (void)updateNavigationButton {
if (self.viewSelector.selectedSegmentIndex == 0) {
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(addDevice:)] autorelease];
} else {
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:@selector(refresh:)] autorelease];
}
}
- (void)updateVisibleEntities {
if (self.viewSelector.selectedSegmentIndex == 1) {
if ([self.searchText length] == 0) {
self.entities = self.allEntities;
} else {
NSMutableArray *matches = [NSMutableArray array];
for (NSDictionary *entity in self.allEntities) {
NSDictionary *attributes = [entity objectForKey:@"attributes"];
NSString *name = [attributes objectForKey:@"friendly_name"] ?: @"";
NSString *entityID = [entity objectForKey:@"entity_id"] ?: @"";
if ([name rangeOfString:self.searchText options:NSCaseInsensitiveSearch].location != NSNotFound ||
[entityID rangeOfString:self.searchText options:NSCaseInsensitiveSearch].location != NSNotFound) {
[matches addObject:entity];
}
}
self.entities = matches;
}
} else {
NSArray *favorites = [HAHomeManager selectedEntityIDs];
NSMutableArray *selected = [NSMutableArray array];
for (NSDictionary *entity in self.allEntities) {
if ([favorites containsObject:[entity objectForKey:@"entity_id"]]) {
[selected addObject:entity];
}
}
self.entities = selected;
}
[self.tableView reloadData];
}
- (NSString *)displayNameForEntity:(NSDictionary *)entity {
NSDictionary *attributes = [entity objectForKey:@"attributes"];
NSString *friendlyName = [attributes objectForKey:@"friendly_name"];
return [friendlyName length] > 0 ? friendlyName : [entity objectForKey:@"entity_id"];
}
- (void)showHomes:(id)sender {
HAHomesViewController *homes = [[[HAHomesViewController alloc] initWithStyle:UITableViewStyleGrouped]
autorelease];
homes.delegate = self;
self.homesNavigationController = [[[UINavigationController alloc]
initWithRootViewController:homes] autorelease];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
self.homesNavigationController.modalPresentationStyle = UIModalPresentationFormSheet;
} else {
self.homesNavigationController.modalPresentationStyle = UIModalPresentationPageSheet;
}
[self presentViewController:self.homesNavigationController animated:YES completion:nil];
}
- (void)homesViewControllerDidChooseHome:(NSDictionary *)home {
[self dismissViewControllerAnimated:YES completion:nil];
HAHomesViewController *homes = (HAHomesViewController *)
[[self.homesNavigationController viewControllers] objectAtIndex:0];
homes.delegate = nil;
self.homesNavigationController = nil;
UIViewController *controller = nil;
if (home == nil) {
controller = [[[HASettingsViewController alloc] init] autorelease];
} else {
controller = [[[HAEntityListViewController alloc]
initWithBaseURLString:[home objectForKey:HAHomeBaseURLKey]
accessToken:[home objectForKey:HAHomeAccessTokenKey]] autorelease];
}
[self.navigationController setViewControllers:[NSArray arrayWithObject:controller] animated:NO];
}
- (void)showError:(NSString *)message {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Home Assistant"
message:message
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease];
[alert show];
}
- (void)dealloc {
[_connection cancel];
[_connection release];
_authClient.delegate = nil;
[_authClient release];
[_responseData release];
[_entities release];
[_allEntities release];
[_viewSelector release];
_searchBar.delegate = nil;
[_searchBar release];
[_searchText release];
HADevicePickerViewController *picker =
(HADevicePickerViewController *)[_devicePickerNavigationController topViewController];
picker.delegate = nil;
[_devicePickerNavigationController release];
HAHomesViewController *homes = (HAHomesViewController *)
[[_homesNavigationController viewControllers] objectAtIndex:0];
homes.delegate = nil;
[_homesNavigationController release];
[_baseURLString release];
[_accessToken release];
[super dealloc];
}
@end