-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathUtilities.m
More file actions
1465 lines (1294 loc) · 57.6 KB
/
Utilities.m
File metadata and controls
1465 lines (1294 loc) · 57.6 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
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
//
// Utilities.m
// XBMC Remote
//
// Created by Giovanni Messina on 4/3/13.
// Copyright (c) 2013 joethefox inc. All rights reserved.
//
#import <arpa/inet.h>
#import <mach/mach.h>
#import "Utilities.h"
#import "AppDelegate.h"
#import "NSString+MD5.h"
#import "SDWebImageManager.h"
#import "LocalNetworkAccess.h"
@import StoreKit;
#define GET_ROUNDED_EDGES_RADIUS(size) MAX(MIN(size.width, size.height) * 0.03, 6.0)
#define GET_ROUNDED_EDGES_PATH(rect, radius) [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius];
#define RGBA(r, g, b, a) [UIColor colorWithRed:(r) / 255.0 green:(g) / 255.0 blue:(b) / 255.0 alpha:(a)]
#define GAMMA_DEC(x) pow(x, 2.2)
#define GAMMA_ENC(x) pow(x, 1/2.2)
#define XBMC_LOGO_PADDING 10
#define PERSISTENCE_KEY_VERSION @"VersionUnderReview"
#define PERSISTENCE_KEY_PLAYBACK_ATTEMPTS @"PlaybackAttempts"
#define IMAGE_SIZE_COLOR_AVERAGING CGSizeMake(64, 64) // Scale (down) to this size before averaging an image color
@implementation Utilities
+ (BOOL)isImageUsingAlpha:(CGImageRef)imageRef {
CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
int infoMask = bitmapInfo & kCGBitmapAlphaInfoMask;
return infoMask & (kCGImageAlphaPremultipliedFirst | kCGImageAlphaPremultipliedLast | kCGImageAlphaFirst | kCGImageAlphaLast);
}
+ (CGImageRef)createLinearSRGBFromImage:(UIImage*)image size:(CGSize)size {
CGImageRef inputImageRef = [image CGImage];
if (inputImageRef == NULL) {
return NULL;
}
// For averaging colors a linear color space is required.
CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceLinearSRGB);
if (colorSpace == NULL) {
return NULL;
}
// Enforce images are converted to default (ARGB or RGB, 32bpp, ByteOrderDefault) before analyzing them
size = (size.height > 0 && size.width > 0) ? size : CGSizeMake(CGImageGetWidth(inputImageRef), CGImageGetHeight(inputImageRef));
BOOL anyAlpha = [Utilities isImageUsingAlpha:inputImageRef];
CGImageAlphaInfo alphaInfo = anyAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipLast;
CGContextRef context = CGBitmapContextCreate(NULL,
size.width,
size.height,
8 /* 8 bits per components */,
size.width * 4 /* 4 components for ARGB */,
colorSpace,
alphaInfo & kCGBitmapAlphaInfoMask);
CGColorSpaceRelease(colorSpace);
if (context == NULL) {
return NULL;
}
// Redraw to new format
CGRect rect = CGRectMake(0, 0, CGBitmapContextGetWidth(context), CGBitmapContextGetHeight(context));
CGContextDrawImage(context, rect, inputImageRef);
CGImageRef imageRefOut = CGBitmapContextCreateImage(context);
CGContextRelease(context);
return imageRefOut;
}
+ (UIColor*)averageColorForImageRef:(CGImageRef)rawImageRef {
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(rawImageRef));
if (data == NULL) {
return nil;
}
const UInt8 *rawPixelData = CFDataGetBytePtr(data);
NSUInteger imageHeight = CGImageGetHeight(rawImageRef);
NSUInteger imageWidth = CGImageGetWidth(rawImageRef);
NSUInteger bytesPerRow = CGImageGetBytesPerRow(rawImageRef);
NSUInteger bitsPerComp = CGImageGetBitsPerComponent(rawImageRef);
NSUInteger stride = CGImageGetBitsPerPixel(rawImageRef) / bitsPerComp;
UInt64 red = 0;
UInt64 green = 0;
UInt64 blue = 0;
UInt64 alpha = 0;
CGFloat f = 1.0;
BOOL formatError = NO;
int alphaInfo = CGImageGetBitmapInfo(rawImageRef) & kCGBitmapAlphaInfoMask;
if (alphaInfo == kCGImageAlphaNoneSkipLast) {
// RGB (kCGImageAlphaNoneSkipLast)
for (int row = 0; row < imageHeight; row++) {
const UInt8 *rowPtr = rawPixelData + bytesPerRow * row;
for (int column = 0; column < imageWidth; column++) {
red += rowPtr[0];
green += rowPtr[1];
blue += rowPtr[2];
rowPtr += stride;
}
}
f = 1.0 / (255.0 * imageWidth * imageHeight);
}
else if (alphaInfo == kCGImageAlphaPremultipliedFirst) {
// weight color with alpha to ignore transparent sections
// ARGB (kCGImageAlphaPremultipliedFirst)
for (int row = 0; row < imageHeight; row++) {
const UInt8 *rowPtr = rawPixelData + bytesPerRow * row;
for (int column = 0; column < imageWidth; column++) {
alpha += rowPtr[0];
red += rowPtr[1];
green += rowPtr[2];
blue += rowPtr[3];
rowPtr += stride;
}
}
f = 1.0 / alpha;
formatError = alpha == 0;
}
else {
formatError = YES;
}
CFRelease(data);
// No alpha pixels were found or wrong image format was provided.
if (formatError) {
return nil;
}
// We worked in linear sRGB color space for calculating the average (kCGColorSpaceLinearSRGB).
// Now we need to go back to non-linear sRGB as used in UIColor.
CGFloat sRGB_red = GAMMA_ENC(f * red);
CGFloat sRGB_green = GAMMA_ENC(f * green);
CGFloat sRGB_blue = GAMMA_ENC(f * blue);
return [UIColor colorWithRed:sRGB_red green:sRGB_green blue:sRGB_blue alpha:1];
}
+ (UIColor*)averageColor:(UIImage*)image {
CGImageRef linearSrgbImageRef = [self createLinearSRGBFromImage:image size:IMAGE_SIZE_COLOR_AVERAGING];
if (linearSrgbImageRef == NULL) {
return nil;
}
UIColor *averageColor = [self averageColorForImageRef:linearSrgbImageRef];
CGImageRelease(linearSrgbImageRef);
return averageColor;
}
+ (UIColor*)getUIColorFromImage:(UIImage*)image {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL autocolor_preference = [userDefaults boolForKey:@"autocolor_ui_preference"];
if (!autocolor_preference) {
return UI_AVERAGE_DEFAULT_COLOR;
}
UIColor *uiColor = [Utilities averageColor:image];
return uiColor ?: UI_AVERAGE_DEFAULT_COLOR;
}
+ (UIColor*)tailorColor:(UIColor*)color satscale:(CGFloat)satscale brightscale:(CGFloat)brightscale brightmin:(CGFloat)brightmin brightmax:(CGFloat)brightmax {
CGFloat hue, sat, bright, alpha;
BOOL success = [color getHue:&hue saturation:&sat brightness:&bright alpha:&alpha];
if (!success) {
return nil;
}
// Scale and limit saturation to range [0 ... 1]
sat = MIN(MAX(sat * satscale, 0), 1);
// Scale and limit brightness to range [brightmin ... brightmax]
bright = MIN(MAX(bright * brightscale, brightmin), brightmax);
return [UIColor colorWithHue:hue saturation:sat brightness:bright alpha:alpha];
}
+ (UIColor*)textTintColor:(UIColor*)color {
return [Utilities tailorColor:color satscale:0.33 brightscale:1.5 brightmin:0.7 brightmax:0.9];
}
+ (UIColor*)contrastColor:(UIColor*)color lightColor:(UIColor*)lighter darkColor:(UIColor*)darker {
CGFloat red, green, blue, alpha;
BOOL success = [color getRed:&red green:&green blue:&blue alpha:&alpha];
// Reference https://stackoverflow.com/questions/596216/formula-to-determine-perceived-brightness-of-rgb-color
// Relative luminance for sRGB BT.709 using approximate linearization with gamma 2.2 and weighting
// Middle contrast of relative luminance is around 0.36-0.37
CGFloat luminance = GAMMA_DEC(red) * 0.2126 + GAMMA_DEC(green) * 0.7152 + GAMMA_DEC(blue) * 0.0722;
return (!success || luminance < 0.36) ? lighter : darker;
}
+ (UIColor*)sectionGradientTopColor:(UIColor*)color {
CGFloat hue, sat, bright, alpha;
BOOL success = [color getHue:&hue saturation:&sat brightness:&bright alpha:&alpha];
if (!success) {
return color;
}
// Limit saturation
sat = MIN(MAX(sat, 0), 0.33);
// Limit brightness range
bright = MIN(MAX(bright, 0.4), 0.8);
return [UIColor colorWithHue:hue saturation:sat brightness:bright alpha:alpha];
}
+ (UIColor*)sectionGradientBottomColor:(UIColor*)color {
color = [Utilities sectionGradientTopColor:color];
CGFloat hue, sat, bright, alpha;
BOOL success = [color getHue:&hue saturation:&sat brightness:&bright alpha:&alpha];
if (!success) {
return color;
}
// Desaturate bottom stronger than top
sat = MIN(MAX(sat * 0.33, 0), 1);
// Make bottom slightly brighter than top
bright = MIN(MAX(bright + 0.1, 0.0), 1.0);
return [UIColor colorWithHue:hue saturation:sat brightness:bright alpha:alpha];
}
+ (UIImage*)colorizeImage:(UIImage*)image withColor:(UIColor*)color {
if (color == nil || image.size.width == 0 || image.size.height == 0) {
return image;
}
CGRect contextRect = (CGRect) {.origin = CGPointZero, .size = image.size};
UIImage *newImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIGraphicsBeginImageContextWithOptions(newImage.size, NO, newImage.scale);
[color set];
[newImage drawInRect:contextRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
+ (UIImage*)setLightDarkModeImageAsset:(UIImage*)image lightColor:(UIColor*)lightColor darkColor:(UIColor*)darkColor {
if (@available(iOS 13.0, *)) {
UITraitCollection *scale = [UITraitCollection currentTraitCollection];
UITraitCollection *lightUI = [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight];
UITraitCollection *darkUI = [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark];
UITraitCollection *lightScaledTC = [UITraitCollection traitCollectionWithTraitsFromCollections:@[scale, lightUI]];
UITraitCollection *darkScaledTC = [UITraitCollection traitCollectionWithTraitsFromCollections:@[scale, darkUI]];
UITraitCollection *lightTraitCollection = [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight];
UITraitCollection *darkTraitCollection = [UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark];
__block UIImage *lightImage = image;
[darkScaledTC performAsCurrentTraitCollection:^{
lightImage = [Utilities colorizeImage:lightImage withColor:lightColor];
lightImage = [lightImage imageWithConfiguration:[lightImage.configuration configurationWithTraitCollection:lightTraitCollection]];
}];
__block UIImage *darkImage = image;
[lightScaledTC performAsCurrentTraitCollection:^{
darkImage = [Utilities colorizeImage:darkImage withColor:darkColor];
darkImage = [darkImage imageWithConfiguration:[darkImage.configuration configurationWithTraitCollection:darkTraitCollection]];
}];
[lightImage.imageAsset registerImage:darkImage withTraitCollection:darkTraitCollection];
return lightImage;
}
else {
image = [Utilities colorizeImage:image withColor:lightColor];
return image;
}
}
+ (void)setLogoBackgroundColor:(UIImageView*)imageview mode:(LogoBackgroundType)mode {
UIColor *bgcolor = UIColor.clearColor;
UIColor *imgcolor = nil;
UIColor *bglight = SYSTEMGRAY6_LIGHTMODE;
UIColor *bgdark = SYSTEMGRAY6_DARKMODE;
switch (mode) {
case LogoBackgroundAuto:
// get background color and colorize the image background
imgcolor = [Utilities averageColor:imageview.image];
bgcolor = [Utilities contrastColor:imgcolor lightColor:bglight darkColor:bgdark];
break;
case LogoBackgroundLight:
bgcolor = bglight;
break;
case LogoBackgroundDark:
bgcolor = bgdark;
break;
case LogoBackgroundTransparent:
// bgcolor already defined to clearColor as default
break;
default:
NSLog(@"setLogoBackgroundColor: unknown mode %ld", mode);
break;
}
imageview.backgroundColor = bgcolor;
}
+ (BOOL)getPreferTvPosterMode {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL result = [userDefaults boolForKey:@"prefer_TVposter_preference"];
return result;
}
+ (LogoBackgroundType)getLogoBackgroundMode {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
LogoBackgroundType setting = LogoBackgroundAuto;
NSString *mode = [userDefaults stringForKey:@"logo_background"];
if (mode.length) {
if ([mode isEqualToString:@"dark"]) {
setting = LogoBackgroundDark;
}
else if ([mode isEqualToString:@"light"]) {
setting = LogoBackgroundLight;
}
else if ([mode isEqualToString:@"trans"]) {
setting = LogoBackgroundTransparent;
}
}
return setting;
}
+ (NSDictionary*)buildPlayerSeekPercentageParams:(int)playerID percentage:(float)percentage {
NSDictionary *params = nil;
if (AppDelegate.instance.serverVersion < 15) {
params = @{
@"playerid": @(playerID),
@"value": @(percentage),
};
}
else {
params = @{
@"playerid": @(playerID),
@"value": @{@"percentage": @(percentage)},
};
}
return params;
}
+ (NSDictionary*)buildPlayerSeekStepParams:(NSString*)stepmode {
NSDictionary *params = nil;
if (AppDelegate.instance.serverVersion < 15) {
params = @{@"value": stepmode};
}
else {
params = @{@"value": @{@"step": stepmode}};
}
return params;
}
+ (CGFloat)getTransformX {
// We scale for iPhone with their different device widths.
if (IS_IPHONE) {
return (GET_MAINSCREEN_WIDTH / IPHONE_SCREEN_DESIGN_WIDTH);
}
// For iPad a fixed frame width is used.
else {
return (STACKSCROLL_WIDTH / IPAD_SCREEN_DESIGN_WIDTH);
}
}
+ (UIColor*)getSystemRed:(CGFloat)alpha {
return [UIColor.systemRedColor colorWithAlphaComponent:alpha];
}
+ (UIColor*)getSystemGreen:(CGFloat)alpha {
return [UIColor.systemGreenColor colorWithAlphaComponent:alpha];
}
+ (UIColor*)getKodiBlue {
return RGBA(20, 178, 231, 1.0);
}
+ (UIColor*)getSystemBlue {
return UIColor.systemBlueColor;
}
+ (UIColor*)getSystemTeal {
return UIColor.systemTealColor;
}
+ (UIColor*)getSystemGray1 {
return UIColor.systemGrayColor;
}
+ (UIColor*)getSystemGray2 {
if (@available(iOS 13.0, *)) {
return UIColor.systemGray2Color;
}
else {
return RGBA(174, 174, 178, 1.0);
}
}
+ (UIColor*)getSystemGray3 {
if (@available(iOS 13.0, *)) {
return UIColor.systemGray3Color;
}
else {
return RGBA(199, 199, 204, 1.0);
}
}
+ (UIColor*)getSystemGray4 {
if (@available(iOS 13.0, *)) {
return UIColor.systemGray4Color;
}
else {
return RGBA(209, 209, 214, 1.0);
}
}
+ (UIColor*)getSystemGray5 {
if (@available(iOS 13.0, *)) {
return UIColor.systemGray5Color;
}
else {
return RGBA(229, 229, 234, 1.0);
}
}
+ (UIColor*)getSystemGray6 {
if (@available(iOS 13.0, *)) {
return UIColor.systemGray6Color;
}
else {
return RGBA(242, 242, 247, 1.0);
}
}
+ (UIColor*)get1stLabelColor {
if (@available(iOS 13.0, *)) {
return UIColor.labelColor;
}
else {
return RGBA(0, 0, 0, 1.0);
}
}
+ (UIColor*)get2ndLabelColor {
if (@available(iOS 13.0, *)) {
return UIColor.secondaryLabelColor;
}
else {
return RGBA(60, 60, 67, 0.6);
}
}
+ (UIColor*)get3rdLabelColor {
if (@available(iOS 13.0, *)) {
return UIColor.tertiaryLabelColor;
}
else {
return RGBA(60, 60, 67, 0.3);
}
}
+ (UIColor*)get4thLabelColor {
if (@available(iOS 13.0, *)) {
return UIColor.quaternaryLabelColor;
}
else {
return RGBA(60, 60, 67, 0.18);
}
}
+ (UIColor*)getGrayColor:(int)tone alpha:(CGFloat)alpha {
return RGBA(tone, tone, tone, alpha);
}
+ (CGRect)createCoverInsideJewel:(UIImageView*)jewelView jewelType:(JewelType)type {
CGFloat border_right, border_bottom, border_top, border_left;
// Setup the border width on all 4 sides for each jewel case type
switch (type) {
case JewelTypeCD:
border_right = 14;
border_bottom = 15;
border_top = 11;
border_left = 32;
break;
case JewelTypeDVD:
border_right = 10;
border_bottom = 14;
border_top = 11;
border_left = 35;
break;
case JewelTypeTV:
border_right = 10;
border_bottom = 26;
border_top = 10;
border_left = 15;
break;
default:
return CGRectZero;
break;
}
CGFloat factor = MIN(jewelView.frame.size.width / jewelView.image.size.width, jewelView.frame.size.height / jewelView.image.size.height);
CGRect frame = jewelView.frame;
frame.size.width = ceil((jewelView.image.size.width - border_left - border_right) * factor);
frame.size.height = ceil((jewelView.image.size.height - border_top - border_bottom) * factor);
frame.origin.y = floor(jewelView.center.y - frame.size.height / 2 + (border_top - border_bottom) / 2 * factor);
frame.origin.x = floor(jewelView.center.x - frame.size.width / 2 + (border_left - border_right) / 2 * factor);
return frame;
}
+ (UIAlertController*)createAlertOK:(NSString*)title message:(NSString*)msg {
UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"OK") style:UIAlertActionStyleDefault handler:nil];
[alertCtrl addAction:okButton];
return alertCtrl;
}
+ (UIAlertController*)createAlertCopyClipboard:(NSString*)title message:(NSString*)msg {
UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *copyButton = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Copy to clipboard") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = msg;
}];
UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
[alertCtrl addAction:copyButton];
[alertCtrl addAction:cancelButton];
return alertCtrl;
}
+ (void)powerAction:(NSString*)command onSuccess:(void (^)(void))onSuccess {
[[Utilities getJsonRPC] callMethod:command withParameters:@{} onCompletion:^(NSString *methodName, NSInteger callId, id methodResult, DSJSONRPCError *methodError, NSError *error) {
// User already confirmed, so we only show a short-lived message.
if (methodError == nil && error == nil) {
[Utilities showMessage:LOCALIZED_STR(@"Command executed") color:SUCCESS_MESSAGE_COLOR];
if (onSuccess) {
onSuccess();
}
}
else {
[Utilities showMessage:LOCALIZED_STR(@"Cannot do that") color:ERROR_MESSAGE_COLOR];
}
}];
}
+ (UIAlertController*)createPowerControl {
NSString *title = [NSString stringWithFormat:@"%@\n%@", AppDelegate.instance.obj.serverDescription, AppDelegate.instance.obj.serverIP];
UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
if (!AppDelegate.instance.serverOnLine) {
UIAlertAction *action_wake = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Send Wake-On-LAN") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
// In this case we want to have a user interaction popup instead of a short-lived message.
if ([Utilities isValidMacAddress:AppDelegate.instance.obj.serverHWAddr]) {
[Utilities wakeUp:AppDelegate.instance.obj.serverHWAddr];
[Utilities showMessage:LOCALIZED_STR(@"Command executed") color:SUCCESS_MESSAGE_COLOR];
}
else {
[Utilities showMessage:LOCALIZED_STR(@"No server MAC address defined") color:ERROR_MESSAGE_COLOR];
}
}];
[alertCtrl addAction:action_wake];
}
else {
UIAlertAction *action_pwr_off_system = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Power off System") style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
[self powerAction:@"System.Shutdown" onSuccess:^{
[Utilities stopPollingActiveServer];
}];
}];
[alertCtrl addAction:action_pwr_off_system];
UIAlertAction *action_quit_kodi = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Quit XBMC application") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self powerAction:@"Application.Quit" onSuccess:^{
[Utilities stopPollingActiveServer];
}];
}];
[alertCtrl addAction:action_quit_kodi];
UIAlertAction *action_hibernate = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Hibernate") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self powerAction:@"System.Hibernate" onSuccess:^{
[Utilities stopPollingActiveServer];
}];
}];
[alertCtrl addAction:action_hibernate];
UIAlertAction *action_suspend = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Suspend") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self powerAction:@"System.Suspend" onSuccess:^{
[Utilities stopPollingActiveServer];
}];
}];
[alertCtrl addAction:action_suspend];
UIAlertAction *action_reboot = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Reboot") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self powerAction:@"System.Reboot" onSuccess:nil];
}];
[alertCtrl addAction:action_reboot];
UIAlertAction *action_scan_audio_lib = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Update Audio Library") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self powerAction:@"AudioLibrary.Scan" onSuccess:nil];
}];
[alertCtrl addAction:action_scan_audio_lib];
UIAlertAction *action_clean_audio_lib = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Clean Audio Library") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self powerAction:@"AudioLibrary.Clean" onSuccess:nil];
}];
[alertCtrl addAction:action_clean_audio_lib];
UIAlertAction *action_scan_video_lib = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Update Video Library") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self powerAction:@"VideoLibrary.Scan" onSuccess:nil];
}];
[alertCtrl addAction:action_scan_video_lib];
UIAlertAction *action_clean_video_lib = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Clean Video Library") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self powerAction:@"VideoLibrary.Clean" onSuccess:nil];
}];
[alertCtrl addAction:action_clean_video_lib];
}
UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"Cancel") style:UIAlertActionStyleCancel handler:nil];
[alertCtrl addAction:cancelButton];
alertCtrl.modalPresentationStyle = UIModalPresentationPopover;
return alertCtrl;
}
+ (void)SFloadURL:(NSString*)url fromctrl:(UIViewController<SFSafariViewControllerDelegate>*)fromctrl {
NSURL *nsurl = [NSURL URLWithString:url];
SFSafariViewController *svc = nil;
// Try to load the URL via SFSafariViewController. If this is not possible, check if this is loadable
// with other system applications. If so, load it. If not, show an error popup.
@try {
svc = [[SFSafariViewController alloc] initWithURL:nsurl];
} @catch (NSException *exception) {
if ([UIApplication.sharedApplication canOpenURL:nsurl]) {
[UIApplication.sharedApplication openURL:nsurl options:@{} completionHandler:nil];
}
else {
UIAlertController *alertCtrl = [Utilities createAlertOK:LOCALIZED_STR(@"Error loading page") message:exception.reason];
[fromctrl presentViewController:alertCtrl animated:YES completion:nil];
}
return;
}
UIViewController *ctrl = fromctrl;
svc.delegate = fromctrl;
if (IS_IPAD) {
// On iPad presenting from the active ViewController results in blank screen
ctrl = UIApplication.sharedApplication.keyWindow.rootViewController;
}
if (![svc isBeingPresented]) {
if (ctrl.presentedViewController) {
[ctrl dismissViewControllerAnimated:YES completion:nil];
}
[ctrl presentViewController:svc animated:YES completion:nil];
}
}
+ (void)showLocalNetworkAccessError:(UIViewController*)viewCtrl {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL showLocalNetworkNotice = [userDefaults boolForKey:@"local_network_info_preference"];
if (showLocalNetworkNotice) {
NSString *message = LOCALIZED_STR(@"It seems local network access is not enabled for the Kodi Remote App. This is required for the app to find and connect to Kodi servers in your local network.");
NSString *fix = LOCALIZED_STR(@"The local network access can be enabled in the iOS network or in the app settings. You might need to reset your network settings, restart your iOS device or even remove/re-install the app to let this take effect.");
UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:LOCALIZED_STR(@"Local network notice")
message:[NSString stringWithFormat:@"%@\n\n%@", message, fix]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okButton = [UIAlertAction actionWithTitle:LOCALIZED_STR(@"OK")
style:UIAlertActionStyleDefault
handler:nil];
UIAlertAction *dontShowButton = [UIAlertAction
actionWithTitle:LOCALIZED_STR(@"Don't show this message again")
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction *action) {
[Utilities disableLocalNetworkconnectionNotice];
}];
[alertCtrl addAction:dontShowButton];
[alertCtrl addAction:okButton];
[viewCtrl presentViewController:alertCtrl animated:YES completion:nil];
}
}
+ (void)disableLocalNetworkconnectionNotice {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:NO forKey:@"local_network_info_preference"];
}
+ (void)showMessage:(NSString*)messageText color:(UIColor*)messageColor {
if (!messageText || ![messageColor isKindOfClass:[UIColor class]]) {
return;
}
NSDictionary *params = @{
@"message": messageText,
@"color": messageColor,
};
[[NSNotificationCenter defaultCenter] postNotificationName:@"UIShowMessage" object:nil userInfo:params];
}
+ (DSJSONRPC*)getJsonRPC {
static DSJSONRPC *jsonRPC;
static NSString *checkRPC;
// Calculate checksum for requested JSONRPC configuration
NSString *text = [NSString stringWithFormat:@"%@ %@", AppDelegate.instance.getServerJSONEndPoint, AppDelegate.instance.getServerHTTPHeaders];
NSString *checksum = [text SHA256String];
// Create JSONRPC object if not yet created or new configuration is required
if (jsonRPC == nil || ![checkRPC isEqualToString:checksum]) {
jsonRPC = [[DSJSONRPC alloc] initWithServiceEndpoint:AppDelegate.instance.getServerJSONEndPoint
andHTTPHeaders:AppDelegate.instance.getServerHTTPHeaders];
checkRPC = checksum;
}
return jsonRPC;
}
+ (void)setWebImageAuthorizationOnSuccessNotification:(NSNotification*)note {
if ([note.name isEqualToString:@"XBMCServerConnectionSuccess"]) {
SDWebImageDownloader *manager = [SDWebImageManager sharedManager].imageDownloader;
NSDictionary *httpHeaders = AppDelegate.instance.getServerHTTPHeaders;
if (httpHeaders[@"Authorization"] != nil) {
[manager setValue:httpHeaders[@"Authorization"] forHTTPHeaderField:@"Authorization"];
}
}
}
+ (NSString*)convertTimeFromSeconds:(NSNumber*)seconds {
NSString *result = @"";
if (![seconds respondsToSelector:@selector(intValue)]) {
return result;
}
int secs = [seconds intValue];
int hour = secs / 3600;
int minute = secs / 60 - hour * 60;
int second = secs - (hour * 3600 + minute * 60);
result = [NSString stringWithFormat:@"%02d:%02d", minute, second];
if (hour > 0) {
result = [NSString stringWithFormat:@"%02d:%@", hour, result];
}
return result;
}
+ (NSString*)getItemIconFromDictionary:(NSDictionary*)dict {
NSString *iconName = @"";
if (dict[@"filetype"] != nil) {
NSString *filetype = dict[@"filetype"];
if ([filetype isEqualToString:@"directory"]) {
iconName = @"nocover_filemode";
}
else if ([filetype isEqualToString:@"file"]) {
iconName = @"icon_file";
}
}
return iconName;
}
+ (NSString*)getStringFromItem:(id)item {
NSString *text = @"";
if (item == nil || [item isKindOfClass:[NSNull class]]) {
text = @"";
}
else if ([item isKindOfClass:[NSArray class]]) {
text = [item componentsJoinedByString:@" / "];
text = text.length == 0 ? @"" : text;
}
else if ([item isKindOfClass:[NSNumber class]]) {
text = [NSString stringWithFormat:@"%@", item];
}
else {
text = [item length] == 0 ? @"" : item;
}
return text;
}
+ (NSNumber*)getNumberFromItem:(id)item {
NSNumber *value = @(0);
if (!item) {
return value;
}
// Check for longLongValue as this is supported by both NSNumber and NSString.
// If longLongValue value is not supported, convert via NSString.
if ([item respondsToSelector:@selector(longLongValue)]) {
value = @([item longLongValue]);
}
else {
value = @([[Utilities getStringFromItem:item] longLongValue]);
}
return value;
}
+ (NSString*)getTimeFromItem:(id)item sec2min:(int)secondsToMinute {
NSString *runtime = @"";
if (item == nil || [item isKindOfClass:[NSNull class]]) {
runtime = @"";
}
else if ([item isKindOfClass:[NSArray class]]) {
runtime = [item componentsJoinedByString:@" / "];
}
else if ([item intValue] > 0) {
int minutes = [item intValue] / secondsToMinute;
runtime = minutes ? [NSString stringWithFormat:@"%d min", minutes] : [NSString stringWithFormat:@"<1 min"];
}
return runtime;
}
+ (NSString*)getYearFromItem:(id)item {
NSString *year = @"";
if (item == nil || [item isKindOfClass:[NSNull class]]) {
year = @"";
}
else if ([item isKindOfClass:[NSNumber class]]) {
if ([item integerValue] > 0) {
year = [item stringValue];
}
else {
year = @"";
}
}
else if ([item isKindOfClass:[NSArray class]]) {
year = [item componentsJoinedByString:@" / "];
}
else if ([item integerValue] > 0) {
year = item;
}
return year;
}
+ (float)getFloatValueFromItem:(id)item {
float floatval = 0.0f;
if ([item respondsToSelector:@selector(floatValue)]) {
floatval = [item floatValue];
}
return floatval;
}
+ (NSString*)getRatingFromItem:(id)item {
NSString *rating = @"";
float ratingValue = [Utilities getFloatValueFromItem:item];
if (ratingValue > 0) {
rating = [NSString stringWithFormat:@"%.1f", ratingValue];
}
return rating;
}
+ (NSString*)getClearArtFromDictionary:(NSDictionary*)dict type:(NSString*)type {
// 1st preference: "albumartist.clearart" to prefer albumartist clearart.
NSString *albumArtistClearArtPath = dict[[NSString stringWithFormat:@"albumartist.%@", type]];
if (albumArtistClearArtPath) {
return albumArtistClearArtPath;
}
// 2nd preference: "clearart" w/o any prefix to prefer movie over set clearart.
NSString *pureClearArtPath = dict[type];
if (pureClearArtPath) {
return pureClearArtPath;
}
// Search for any "clearart"
NSString *path = @"";
for (NSString *key in dict) {
if ([key rangeOfString:type].location != NSNotFound) {
path = dict[key];
break; // We want to leave the loop after we found what we were searching for
}
}
return path;
}
+ (NSString*)getThumbnailFromDictionary:(NSDictionary*)dict useBanner:(BOOL)useBanner useIcon:(BOOL)useIcon {
NSString *thumbnailPath = dict[@"thumbnail"];
NSDictionary *art = dict[@"art"];
if ([art[@"poster"] length] != 0) {
thumbnailPath = art[@"poster"];
}
if (useBanner && [art[@"banner"] length] != 0) {
thumbnailPath = art[@"banner"];
}
if (useIcon && [art[@"icon"] length] != 0) {
thumbnailPath = art[@"icon"];
}
return thumbnailPath;
}
+ (NSString*)getDateFromItem:(id)item dateStyle:(NSDateFormatterStyle)dateStyle {
NSString *dateString = @"";
if ([item isKindOfClass:[NSString class]] && [item length] > 0) {
NSDateFormatter *format = [NSDateFormatter new];
format.locale = [NSLocale currentLocale];
format.dateFormat = @"yyyy-MM-dd";
NSDate *date = [format dateFromString:item];
format.dateStyle = dateStyle;
dateString = [format stringFromDate:date];
}
return dateString;
}
+ (int)getSec2Min:(BOOL)convert {
return (AppDelegate.instance.serverVersion > 11 && convert) ? 60 : 1;
}
+ (NSString*)getImageServerURL {
GlobalData *obj = [GlobalData getInstance];
NSString *stringFormat = (AppDelegate.instance.serverVersion > 11) ? @"%@:%@/image/" : @"%@:%@/vfs/";
return [NSString stringWithFormat:stringFormat, obj.serverIP, obj.serverPort];
}
+ (NSString*)formatStringURL:(NSString*)path serverURL:(NSString*)serverURL {
NSString *urlString = @"";
if (path.length > 0 && ![path isEqualToString:@"(null)"]) {
if (![path hasPrefix:@"image://"]) {
urlString = path;
}
else {
urlString = [NSString stringWithFormat:@"http://%@%@", serverURL, [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]]];
}
}
return urlString;
}
+ (CGSize)getSizeOfLabel:(UILabel*)label {
return [label sizeThatFits:CGSizeMake(label.frame.size.width, CGFLOAT_MAX)];
}
+ (UIImage*)roundedCornerImage:(UIImage*)image {
if (image.size.width == 0 || image.size.height == 0) {
return image;
}
CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
// Set radius for corners
CGFloat radius = GET_ROUNDED_EDGES_RADIUS(image.size);
// Define our path, capitalizing on UIKit's corner rounding magic
UIBezierPath *path = GET_ROUNDED_EDGES_PATH(imageRect, radius);
[path addClip];
// Draw the image into the implicit context
[image drawInRect:imageRect];
// Get image and cleanup
UIImage *roundedCornerImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return roundedCornerImage;
}
+ (void)roundedCornerView:(UIView*)view {
view.layer.cornerRadius = GET_ROUNDED_EDGES_RADIUS(view.layer.frame.size);
}
+ (UIImage*)applyRoundedEdgesImage:(UIImage*)image {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL corner_preference = [userDefaults boolForKey:@"rounded_corner_preference"];
if (corner_preference) {
image = [Utilities roundedCornerImage:image];
}
return image;
}
+ (void)applyRoundedEdgesView:(UIView*)view {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL corner_preference = [userDefaults boolForKey:@"rounded_corner_preference"];
if (corner_preference) {
[Utilities roundedCornerView:view];
}
}
+ (CGFloat)getBottomPadding {
CGFloat bottomPadding = UIApplication.sharedApplication.keyWindow.safeAreaInsets.bottom;
return bottomPadding;
}
+ (CGFloat)getTopPadding {
CGFloat topPadding = UIApplication.sharedApplication.keyWindow.safeAreaInsets.top;
return topPadding;
}
+ (CGFloat)getTopPaddingWithNavBar:(UINavigationController*)navCtrl {
// Workaround: Using CGRectGetMaxY resolves a layout issue where otherwise the inset ends below the navbar (e.g.
// iPhone 14 Pro iOS18), but at the same time it causes an issue with the inset not taking into account the status
// bar (e.g. iPod Touch iOS15.5). This seems to be caused by calling this method from viewDidLoad instead
// of willLayoutSubviews. This workaround avoids rework of DetailVC's delicate layout.
CGFloat topPadding = CGRectGetMaxY(navCtrl.navigationBar.frame);
if (topPadding <= navCtrl.navigationBar.frame.size.height) {
topPadding = UIApplication.sharedApplication.statusBarFrame.size.height + navCtrl.navigationBar.frame.size.height;
}
return topPadding;
}
+ (void)sendXbmcHttp:(NSString*)command {
GlobalData *obj = [GlobalData getInstance];
NSString *userPassword = obj.serverPass.length ? [NSString stringWithFormat:@":%@", obj.serverPass] : @"";
NSString *serverHTTP = [NSString stringWithFormat:@"http://%@%@@%@:%@/xbmcCmds/xbmcHttp?command=%@", obj.serverUser, userPassword, obj.serverIP, obj.serverPort, command];
[[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:serverHTTP]] resume];
}
+ (void)giveHapticFeedback {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
BOOL feedbackEnabled = [userDefaults boolForKey:@"vibrate_preference"];
if (feedbackEnabled) {
static UIImpactFeedbackGenerator *generator;
static dispatch_once_t once;
dispatch_once(&once, ^{
generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
});
[generator impactOccurred];
}
}
+ (NSString*)getAppVersionString {
NSDictionary *infoDict = NSBundle.mainBundle.infoDictionary;