-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathAppDelegate.m
More file actions
372 lines (308 loc) · 14.5 KB
/
AppDelegate.m
File metadata and controls
372 lines (308 loc) · 14.5 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
//
// AppDelegate.m
// XBMC Remote
//
// Created by Giovanni Messina on 23/3/12.
// Copyright (c) 2012 joethefox inc. All rights reserved.
//
#import "AppDelegate.h"
#import "mainMenu.h"
#import "MasterViewController.h"
#import "ViewControllerIPad.h"
#import "GlobalData.h"
#import "InitialSlidingViewController.h"
#import "UIImageView+WebCache.h"
#import "Utilities.h"
#import "Kodi_Remote-Swift.h"
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
@implementation AppDelegate
@synthesize window = _window;
@synthesize navigationController = _navigationController;
@synthesize windowController = _windowController;
@synthesize dataFilePath;
@synthesize arrayServerList;
@synthesize serverOnLine;
@synthesize serverVersion;
@synthesize serverMinorVersion;
@synthesize obj;
@synthesize customButtonEntry;
@synthesize playlistArtistAlbums;
@synthesize playlistMovies;
@synthesize playlistMusicVideos;
@synthesize playlistTvShows;
@synthesize playlistPVR;
@synthesize globalSearchLookup;
@synthesize serverName;
+ (AppDelegate*)instance {
return (AppDelegate*)UIApplication.sharedApplication.delegate;
}
#pragma mark - Globals
// Amount of bytes per pixel for images cached in memory (32 bit png)
#define BYTES_PER_PIXEL 4
#pragma mark - Init
- (id)init {
if (self = [super init]) {
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
self.dataFilePath = docPaths[0];
NSMutableArray *tempArray = [Utilities unarchivePath:self.dataFilePath file:@"serverList_saved.dat"];
if (tempArray) {
[self setArrayServerList:tempArray];
}
else {
arrayServerList = [NSMutableArray new];
}
// Set the image in-memory cache to 25% of physical memory (but max to 512 MB). maxCost reflects the amount of pixels.
NSInteger memorySize = [[NSProcessInfo processInfo] physicalMemory];
NSInteger maxCost = MIN(memorySize / 4, 512 * 1024 * 1024) / BYTES_PER_PIXEL;
[[SDImageCache sharedImageCache] setMaxMemoryCost:maxCost];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
self.libraryCachePath = [cachePaths[0] stringByAppendingPathComponent:@"LibraryCache"];
[fileManager createDirectoryAtPath:self.libraryCachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
self.epgCachePath = [cachePaths[0] stringByAppendingPathComponent:@"EPGDataCache"];
[fileManager createDirectoryAtPath:self.epgCachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
}
return self;
}
- (void)registerDefaultsFromSettingsBundle {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *bundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
if (!bundle) {
return;
}
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[bundle stringByAppendingPathComponent:@"Root.plist"]];
NSArray *preferences = settings[@"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:preferences.count];
for (NSDictionary *prefSpecification in preferences) {
NSString *key = prefSpecification[@"Key"];
if (key) {
// We can set defaults here as registerDefaults does not overwrite already defined values
defaultsToRegister[key] = prefSpecification[@"DefaultValue"];
}
}
// Register defaults
[userDefaults registerDefaults:defaultsToRegister];
}
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
// Make navigation bar transparent
if (@available(iOS 13, *)) {
UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
[appearance configureWithOpaqueBackground];
[appearance configureWithTransparentBackground];
appearance.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
appearance.titleTextAttributes = @{NSForegroundColorAttributeName : UIColor.whiteColor};
appearance.backgroundColor = UIColor.clearColor;
[UINavigationBar appearance].standardAppearance = appearance;
[UINavigationBar appearance].scrollEdgeAppearance = appearance;
}
// Load user defaults, if not yet set. Avoids need to check for nil.
[self registerDefaultsFromSettingsBundle];
[self setIdleTimerFromUserDefaults];
// Create and set interface style for window
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
[self setInterfaceStyleFromUserDefaults];
[self.window makeKeyAndVisible];
// Create GlobalDate which holds the Kodi server parameters
obj = [GlobalData getInstance];
// Create the menu tree
mainMenuItems = [mainMenu generateMenus];
// Initialize controllers
self.serverName = LOCALIZED_STR(@"No connection");
if (IS_IPHONE) {
InitialSlidingViewController *initialSlidingViewController = [[InitialSlidingViewController alloc] initWithNibName:@"InitialSlidingViewController" bundle:nil];
initialSlidingViewController.mainMenuTable = mainMenuItems;
self.window.rootViewController = initialSlidingViewController;
}
else {
self.windowController = [[ViewControllerIPad alloc] initWithNibName:@"ViewControllerIPad" bundle:nil];
self.windowController.mainMenuTable = mainMenuItems;
self.window.rootViewController = self.windowController;
}
return YES;
}
- (NSURL*)getServerJSONEndPoint {
if (!obj.serverIP || !obj.serverPort) {
return nil;
}
NSString *serverJSON = [NSString stringWithFormat:@"http://%@:%@/jsonrpc", obj.serverIP, obj.serverPort];
return [NSURL URLWithString:serverJSON];
}
- (NSDictionary*)getServerHTTPHeaders {
NSData *authCredential = [[NSString stringWithFormat:@"%@:%@", obj.serverUser, obj.serverPass] dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64AuthCredentials = [authCredential base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", base64AuthCredentials];
NSDictionary *httpHeaders = @{@"Authorization": authValue};
return httpHeaders;
}
#pragma mark - Helper
- (BOOL)connectToServerFromList:(NSString*)host {
if (!host.length) {
return NO;
}
// Host name needs ".local." at the end
if ([host hasSuffix:@".local"]) {
host = [host stringByAppendingString:@"."];
}
// Try to map server name or IP address to the list of Kodi servers
NSInteger index = [self.arrayServerList indexOfObjectPassingTest:^BOOL(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
return [host isEqualToString:obj[@"serverDescription"]] || [host isEqualToString:obj[@"serverIP"]];
}];
// We want to connect to the desired server only. If this is not present, disconnect from any active server.
BOOL result = NO;
NSIndexPath *serverIndexPath;
NSDictionary *params;
if (index != NSNotFound) {
serverIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
params = @{@"index": @(index)};
result = YES;
}
// Case 1: App just starts. Set the last active server before readKodiServerParameters is called
[Utilities saveLastServerIndex:serverIndexPath];
// Case 2: App already runs. Send a notification to select the server via its index.
[NSNotificationCenter.defaultCenter postNotificationName:@"SelectKodiServer" object:nil userInfo:params];
return result;
}
- (void)setIdleTimerFromUserDefaults {
UIApplication.sharedApplication.idleTimerDisabled = [[NSUserDefaults standardUserDefaults] boolForKey:@"lockscreen_preference"];
}
- (void)setInterfaceStyleFromUserDefaults {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *mode = [userDefaults stringForKey:@"theme_mode"];
if (@available(iOS 13.0, *)) {
UIUserInterfaceStyle style = UIUserInterfaceStyleUnspecified;
if (mode.length) {
if ([mode isEqualToString:@"dark_mode"]) {
style = UIUserInterfaceStyleDark;
}
else if ([mode isEqualToString:@"light_mode"]) {
style = UIUserInterfaceStyleLight;
}
}
self.window.overrideUserInterfaceStyle = style;
}
}
- (void)sendWOL:(NSString*)MAC withPort:(NSInteger)WOLport {
CFSocketRef WOLsocket;
WOLsocket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_DGRAM, IPPROTO_UDP, 0, NULL, NULL);
if (WOLsocket) {
int desc = -1;
desc = CFSocketGetNative(WOLsocket);
int yes = -1;
if (setsockopt (desc, SOL_SOCKET, SO_BROADCAST, (char*)&yes, sizeof(yes)) < 0) {
NSLog(@"Set Socket options failed");
}
unsigned char ether_addr[6];
int idx;
for (idx = 0; idx + 2 <= MAC.length; idx += 3) {
NSRange range = NSMakeRange(idx, 2);
NSString *hexStr = [MAC substringWithRange:range];
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
ether_addr[idx / 3] = intValue;
}
/* Build the message to send - 6 x 0xff then 16 x MAC address */
unsigned char message[102];
unsigned char *message_ptr = message;
memset(message_ptr, 0xFF, 6);
message_ptr += 6;
for (int i = 0; i < 16; ++i) {
memcpy(message_ptr, ether_addr, 6);
message_ptr += 6;
}
__auto_type getLocalBroadcastAddress = ^in_addr_t {
in_addr_t broadcastAddress = 0xffffffff;
struct ifaddrs *ifs = NULL;
getifaddrs(&ifs);
for (__auto_type ifIter = ifs; ifIter != NULL; ifIter = ifIter->ifa_next) {
if (ifIter->ifa_flags & IFF_LOOPBACK || ifIter->ifa_flags & IFF_POINTOPOINT || !(ifIter->ifa_flags & IFF_RUNNING))
continue;
if (!ifIter->ifa_addr || ifIter->ifa_addr->sa_family != AF_INET || !ifIter->ifa_broadaddr)
continue;
broadcastAddress = ((struct sockaddr_in*)ifIter->ifa_broadaddr)->sin_addr.s_addr;
break;
}
if (ifs) {
freeifaddrs(ifs);
}
return broadcastAddress;
};
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_len = sizeof(addr);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = getLocalBroadcastAddress();
addr.sin_port = htons(WOLport);
CFDataRef message_data = CFDataCreate(NULL, (unsigned char*)&message, sizeof(message));
CFDataRef destinationAddressData = CFDataCreate(NULL, (const UInt8*)&addr, sizeof(addr));
CFSocketError CFSocketSendData_error = CFSocketSendData(WOLsocket, destinationAddressData, message_data, 30);
if (CFSocketSendData_error) {
NSLog(@"CFSocketSendData error: %li", CFSocketSendData_error);
}
}
}
- (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id>*)options {
// Use URL host to map to server list and connect the server.
return [self connectToServerFromList:url.host.stringByRemovingPercentEncoding];
}
- (void)application:(UIApplication*)application performActionForShortcutItem:(UIApplicationShortcutItem*)shortcutItem completionHandler:(void(^)(BOOL))completionHandler {
// Use shortcut title (= server description) to map to server list and connect the server.
[self connectToServerFromList:shortcutItem.localizedTitle];
}
- (void)applicationDidEnterBackground:(UIApplication*)application {
// Add the server description and address to shortcutItems, which is shown when longpressing the app icon.
NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:self.arrayServerList.count];
for (NSDictionary *server in self.arrayServerList) {
UIApplicationShortcutIcon *icon = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeFavorite];
UIApplicationShortcutItem *shortcut = [[UIApplicationShortcutItem alloc] initWithType:@"ConnectServer"
localizedTitle:server[@"serverDescription"]
localizedSubtitle:server[@"serverIP"]
icon:icon
userInfo:nil];
[items addObject:shortcut];
}
application.shortcutItems = items;
}
- (void)applicationWillEnterForeground:(UIApplication*)application {
[self setIdleTimerFromUserDefaults];
}
- (void)applicationDidBecomeActive:(UIApplication*)application {
// Trigger Local Network Privacy Alert once after app launch
static dispatch_once_t once;
dispatch_once(&once, ^{
LocalNetworkAlertClass *localNetworkAlert = [LocalNetworkAlertClass new];
[localNetworkAlert triggerLocalNetworkPrivacyAlert];
});
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application {
[[SDImageCache sharedImageCache] clearMemory];
}
- (void)saveServerList {
[Utilities archivePath:self.dataFilePath file:@"serverList_saved.dat" data:arrayServerList];
}
- (void)clearDiskCacheAtPath:(NSString*)cachePath {
[[NSFileManager defaultManager] removeItemAtPath:cachePath error:NULL];
[[NSFileManager defaultManager] createDirectoryAtPath:cachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
}
- (void)clearAppDiskCache {
// Clear SDWebImage image cache
[[SDImageCache sharedImageCache] clearDisk];
// Clear library cache
[self clearDiskCacheAtPath:self.libraryCachePath];
// Clear EPG cache
[self clearDiskCacheAtPath:self.epgCachePath];
// Clear network cache
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
@end