-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAppDelegate.m
1682 lines (1572 loc) · 76.6 KB
/
AppDelegate.m
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
//
// AppDelegate.m
// Hachidori
//
// Created by James M. on 8/7/10.
// Copyright 2009-2018 MAL Updater OS X Group and James Moy All rights reserved. Code licensed under New BSD License
//
#import "AppDelegate.h"
#import "Hachidori.h"
#import "Hachidori+Update.h"
#import "Hachidori+userinfo.h"
#import "Hachidori+MultiScrobble.h"
#import "OfflineViewQueue.h"
#import "PFMoveApplication.h"
#import "Preferences.h"
#import "FixSearchDialog.h"
#import "Hotkeys.h"
#import "AutoExceptions.h"
#import "AnimeRelations.h"
#import "ExceptionsCache.h"
#import "Utility.h"
#import "HistoryWindow.h"
#import "DonationWindowController.h"
#import <MSWeakTimer_macOS/MSWeakTimer.h>
#import "ClientConstants.h"
#import "StatusUpdateWindow.h"
#import <TorrentBrowser/TorrentBrowser.h>
#import "ShareMenu.h"
#import "PFAboutWindowController.h"
#import "servicemenucontroller.h"
#import "AniListScoreConvert.h"
#import "PatreonLicenseManager.h"
#import "CrashWindowController.h"
@interface AppDelegate ()
@property (strong) CrashWindowController *cwincontroller;
@end
@implementation AppDelegate
@synthesize window;
@synthesize historywindowcontroller;
@synthesize fsdialog;
@synthesize managedObjectContext;
@synthesize statusMenu;
@synthesize statusItem;
@synthesize statusImage;
@synthesize timer;
@synthesize openstream;
@synthesize togglescrobbler;
@synthesize updatenow;
@synthesize confirmupdate;
@synthesize findtitle;
@synthesize seperator;
@synthesize lastupdateheader;
@synthesize updatecorrectmenu;
@synthesize updatecorrect;
@synthesize updatedtitle;
@synthesize updatedepisode;
@synthesize seperator2;
@synthesize updatedcorrecttitle;
@synthesize updatedupdatestatus;
@synthesize revertrewatch;
@synthesize shareMenuItem;
@synthesize ScrobblerStatus;
@synthesize LastScrobbled;
@synthesize openAnimePage;
@synthesize animeinfo;
@synthesize img;
@synthesize windowcontent;
@synthesize animeinfooutside;
@synthesize scrobbling;
@synthesize scrobbleractive;
@synthesize panelactive;
@synthesize haengine;
@synthesize updatetoolbaritem;
@synthesize correcttoolbaritem;
@synthesize sharetoolbaritem;
@synthesize _preferencesWindowController;
@synthesize streamlinkopenw;
#pragma mark -
#pragma mark Initalization
/**
Returns the support directory for the application, used to store the Core Data
store file. This code uses a directory named "Hachidori" for
the content, either in the NSApplicationSupportDirectory location or (if the
former cannot be found), the system's temporary directory.
*/
- (NSString *)applicationSupportDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *basePath = (paths.count > 0) ? paths[0] : NSTemporaryDirectory();
return [basePath stringByAppendingPathComponent:@"Hachidori"];
}
/**
Creates, retains, and returns the managed object model for the application
by merging all of the models found in the application bundle.
*/
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel) return managedObjectModel;
managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application. This
implementation will create and return a coordinator, having added the
store for the application to it. (The directory for the store is created,
if necessary.)
*/
- (NSPersistentStoreCoordinator *) persistentStoreCoordinator {
if (persistentStoreCoordinator) return persistentStoreCoordinator;
NSManagedObjectModel *mom = self.managedObjectModel;
if (!mom) {
NSAssert(NO, @"Managed object model is nil");
NSLog(@"%@:%@ No model to generate a store from", [self class], NSStringFromSelector(_cmd));
return nil;
}
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *applicationSupportDirectory = [self applicationSupportDirectory];
NSError *error = nil;
if ( ![fileManager fileExistsAtPath:applicationSupportDirectory isDirectory:NULL] ) {
if (![fileManager createDirectoryAtPath:applicationSupportDirectory withIntermediateDirectories:NO attributes:nil error:&error]) {
NSAssert(NO, ([NSString stringWithFormat:@"Failed to create App Support directory %@ : %@", applicationSupportDirectory,error]));
NSLog(@"Error creating application support directory at %@ : %@",applicationSupportDirectory,error);
return nil;
}
}
NSURL *url = [NSURL fileURLWithPath: [applicationSupportDirectory stringByAppendingPathComponent: @"Update History.sqlite"]];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: mom];
NSDictionary *options = @{
NSMigratePersistentStoresAutomaticallyOption : @YES,
NSInferMappingModelAutomaticallyOption : @YES
};
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:url
options:options
error:&error]) {
[[NSApplication sharedApplication] presentError:error];
persistentStoreCoordinator = nil;
return nil;
}
return persistentStoreCoordinator;
}
/**
Returns the managed object context for the application (which is already
bound to the persistent store coordinator for the application.)
*/
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext) return managedObjectContext;
NSPersistentStoreCoordinator *coordinator = self.persistentStoreCoordinator;
if (!coordinator) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:@"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
[dict setValue:@"There was an error building up the data file." forKey:NSLocalizedFailureReasonErrorKey];
NSError *error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
[[NSApplication sharedApplication] presentError:error];
return nil;
}
managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
managedObjectContext.persistentStoreCoordinator = coordinator;
return managedObjectContext;
}
+ (void)initialize {
//Create a Dictionary
NSMutableDictionary * defaultValues = [NSMutableDictionary dictionary];
// Defaults
defaultValues[@"Token"] = @"";
defaultValues[@"ScrobbleatStartup"] = @NO;
defaultValues[@"setprivate"] = @NO;
defaultValues[@"useSearchCache"] = @YES;
defaultValues[@"exceptions"] = [[NSMutableArray alloc] init];
defaultValues[@"ignoredirectories"] = [[NSMutableArray alloc] init];
defaultValues[@"IgnoreTitleRules"] = [[NSMutableArray alloc] init];
defaultValues[@"ConfirmNewTitle"] = @YES;
defaultValues[@"ConfirmUpdates"] = @NO;
defaultValues[@"UseAutoExceptions"] = @YES;
defaultValues[@"UseAnimeRelations"] = @YES;
defaultValues[@"enablekodiapi"] = @NO;
defaultValues[@"RewatchEnabled"] = @YES;
defaultValues[@"kodiaddress"] = @"";
defaultValues[@"kodiport"] = @"3005";
#ifdef oss
defaultValues[@"donated"] = @YES;
defaultValues[@"oss"] = @YES;
#else
defaultValues[@"donated"] = @NO;
defaultValues[@"activepatron"] = @NO;
defaultValues[@"oss"] = @NO;
defaultValues[@"autodownloadtorrents"] = @NO;
defaultValues[@"autodownloadinterval"] = @(3600);
#endif
defaultValues[@"MALAPIURL"] = @"https://malapi.malupdaterosx.moe";
defaultValues[@"timerinterval"] = @(300);
defaultValues[@"showcorrection"] = @YES;
defaultValues[@"NSApplicationCrashOnExceptions"] = @YES;
defaultValues[@"enableplexapi"] = @NO;
defaultValues[@"plexaddress"] = @"localhost";
defaultValues[@"plexport"] = @"32400";
defaultValues[@"plexidentifier"] = @"Hachidori_Plex_Client";
defaultValues[@"plexusehttps"] = @NO;
defaultValues[@"currentservice"] = @(0);
defaultValues[@"torrentagreement"] = @NO;
defaultValues[@"torrentsiteselected"] = @(0);
defaultValues[@"useDirectoryAsWhitelist"] = @NO;
defaultValues[@"youtubedetection"] = @NO;
// Social
defaultValues[@"tweetonscrobble"] = @NO;
defaultValues[@"twitteraddanime"] = @YES;
defaultValues[@"twitterupdateanime"] = @YES;
defaultValues[@"twitterupdatestatus"] = @NO;
defaultValues[@"twitteraddanimeformat"] = @"Started watching %title% Episode %episode% on %service% - %url% #hachidori";
defaultValues[@"twitterupdateanimeformat"] = @"%status% %title% Episode %episode% on %service% - %url% #hachidori";
defaultValues[@"twitterupdatestatusformat"] = @"Updated %title% Episode %episode% (%status%) on %service% - %url% #hachidori";
defaultValues[@"usediscordrichpresence"] = @NO;
// MultiScrobble
defaultValues[@"multiscrobbleenabled"] = @NO;
defaultValues[@"multiscrobblescrobblesenabled"] = @YES;
defaultValues[@"multiscrobbleentryupdatesenabled"] = @YES;
defaultValues[@"multiscrobblescorrectionsenabled"] = @NO;
defaultValues[@"multiscrobbleanilistenabled"] = @NO;
defaultValues[@"multiscrobblekitsuenabled"] = @NO;
defaultValues[@"sendanalytics"] = @YES;
// Refresh Token Fail State
defaultValues[@"AniListRefreshFailed"] = @NO;
defaultValues[@"KitsuRefreshFailed"] = @NO;
defaultValues[@"MALRefreshFailed"] = @NO;
//Register Dictionary
[[NSUserDefaults standardUserDefaults]
registerDefaults:defaultValues];
}
- (void) awakeFromNib {
// Register queue
_privateQueue = dispatch_queue_create("moe.ateliershiori.Hachidori", DISPATCH_QUEUE_CONCURRENT);
//Create the NSStatusBar and set its length
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
//Allocates and loads the images into the application which will be used for our NSStatusItem
statusImage = [NSImage imageNamed:@"hachidori-status"];
//Yosemite Dark Menu Support
[statusImage setTemplate:YES];
//Sets the images in our NSStatusItem
statusItem.image = statusImage;
//Tells the NSStatusItem what menu to load
statusItem.menu = statusMenu;
//Sets the tooptip for our item
[statusItem setToolTip:NSLocalizedString(@"Hachidori",nil)];
//Enables highlighting
[statusItem setHighlightMode:YES];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
#ifdef oss
#else
[MSACAppCenter start:@"d37cc407-6d11-42e6-84e7-222899deb28c" withServices:@[
[MSACAnalytics class],
[MSACCrashes class]
]];
[MSACCrashes setDelegate:self];
[MSACCrashes setEnabled:[NSUserDefaults.standardUserDefaults boolForKey:@"sendanalytics"]];
[MSACAnalytics setEnabled:[NSUserDefaults.standardUserDefaults boolForKey:@"sendanalytics"]];
#endif
// Initialize haengine
haengine = [[Hachidori alloc] init];
haengine.managedObjectContext = managedObjectContext;
// Add Observers
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(recievedNotification:) name:@"MultiScrobbleNotification" object:nil];
#ifdef oss
#else
// Set up Torrent Browser (closed source)
_tbc = [[TorrentBrowserController alloc] initwithManagedObjectContext:managedObjectContext];
// Start Timer for Auto Downloading of Torrents if enabled
if ([NSUserDefaults.standardUserDefaults boolForKey:@"autodownloadtorrents"]) {
if ([_tbc.tmanager startAutoDownloadTimer]) {
NSLog(@"Timer started");
}
else {
NSLog(@"Failed to start timer.");
}
}
// Check Beta
if ([Utility checkBeta]) {
[self showNotification:@"Experimental Update Branch is Enabled" message:@"Hachidori will use the prerelease branch since you are using a prerelease version." withIdentifier:[NSString stringWithFormat:@"betanotif-%@", [NSDate date]]];
}
#endif
#ifdef DEBUG
#else
// Check if Application is in the /Applications Folder
PFMoveToApplicationsFolderIfNecessary();
#endif
// Show Donation Message
if ([NSUserDefaults.standardUserDefaults boolForKey:@"donated"] && [NSUserDefaults.standardUserDefaults boolForKey:@"patreon_license"]) {
[Utility patreonDonateCheck:self];
}
else {
[Utility donateCheck:self];
}
// Set Defaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Set Notification Center Delegate
[NSUserNotificationCenter defaultUserNotificationCenter].delegate = self;
//Register Global Hotkey
[self registerHotkey];
// Disable Update and Share Buttons
[updatetoolbaritem setEnabled:NO];
[sharetoolbaritem setEnabled:NO];
[correcttoolbaritem setEnabled:NO];
[openAnimePage setEnabled:NO];
// Hide Window
[window close];
//Set up Yosemite UI Enhancements
if ([defaults boolForKey:@"DisableYosemiteTitleBar"] != 1) {
// OS X 10.10 code here.
//Hide Title Bar
if (@available(macOS 11, *)) {
self.window.titleVisibility = NSWindowTitleVisible;
self.window.toolbarStyle = NSWindowToolbarStyleUnified;
}
else {
self.window.titleVisibility = NSWindowTitleHidden;
}
// Fix Window Size
NSRect frame = window.frame;
frame.size = CGSizeMake(460, 291);
[window setFrame:frame display:YES];
}
else {
if (@available(macOS 11, *)) {
self.window.toolbarStyle = NSWindowToolbarStyleExpanded;
// Fix Window Size
NSRect frame = window.frame;
frame.size = CGSizeMake(460, 291);
[window setFrame:frame display:YES];
}
}
if ([defaults boolForKey:@"DisableYosemiteVibrance"] != 1) {
//Add NSVisualEffectView to Window
windowcontent.blendingMode = NSVisualEffectBlendingModeBehindWindow;
windowcontent.state = NSVisualEffectStateFollowsWindowActiveState;
//Make Animeinfo textview transparrent
[animeinfooutside setDrawsBackground:NO];
animeinfo.backgroundColor = [NSColor clearColor];
}
else {
windowcontent.state = NSVisualEffectStateInactive;
[animeinfooutside setDrawsBackground:NO];
animeinfo.backgroundColor = [NSColor clearColor];
}
// Fix template images
// There is a bug where template images are not made even if they are set in XCAssets
NSArray *images = @[@"update", @"history", @"correct", @"Info", @"clear"];
NSImage * image;
for (NSString *imagename in images) {
image = [NSImage imageNamed:imagename];
[image setTemplate:YES];
}
// Set up Service Menu
[_servicemenu setmenuitemvaluefromdefaults];
__weak AppDelegate *weakself = self;
_servicemenu.actionblock = ^(int selected, int previousservice) {
[weakself.haengine setNotifier];
[weakself showNotification:@"Changed Services" message:[NSString stringWithFormat:@"Now using %@", [Hachidori currentServiceName]] withIdentifier:@"servicechanged"];
if (!weakself.haengine.lastscrobble) {
[weakself resetUI];
}
else {
[weakself performRefreshUI:1];
dispatch_async(weakself.privateQueue, ^{
weakself.haengine.ratingtype = [weakself.haengine getRatingType];
});
}
//[weakself.haengine resetinfo];
//
weakself.servicenamemenu.enabled = NO;
};
[haengine checkaccountinformation];
// Notify User if there is no Account Info
if (![Hachidori getCurrentFirstAccount]) {
// First time prompt
NSAlert * alert = [[NSAlert alloc] init] ;
[alert addButtonWithTitle:NSLocalizedString(@"Yes",nil)];
[alert addButtonWithTitle:NSLocalizedString(@"No",nil)];
[alert setMessageText:NSLocalizedString(@"Welcome to Hachidori",nil)];
[alert setInformativeText:NSLocalizedString(@"Before using this program, you need to add an account. Do you want to open Preferences to authorize your account now?",nil)];
// Set Message type to Warning
alert.alertStyle = NSInformationalAlertStyle;
if ([alert runModal]== NSAlertFirstButtonReturn) {
// Show Preference Window and go to Login Preference Pane
[NSApp activateIgnoringOtherApps:YES];
[self.preferencesWindowController showWindow:nil];
[(MASPreferencesWindowController *)self.preferencesWindowController selectControllerAtIndex:1];
}
}
// Autostart Scrobble at Startup
if ([defaults boolForKey:@"ScrobbleatStartup"] == 1) {
[self autostarttimer];
}
// Import existing Exceptions Data
[AutoExceptions importToCoreData];
// Temporarily disable MAL Sync
[defaults setBool:FALSE forKey:@"MALSyncEnabled"];
_servicenamemenu.enabled = NO;
[MSACAnalytics trackEvent:@"App Loaded" withProperties:@{@"donated" : [NSUserDefaults.standardUserDefaults boolForKey:@"donated"] ? @"YES" : @"NO"}];
// Auth URL handling
[[NSAppleEventManager sharedAppleEventManager]
setEventHandler:self
andSelector:@selector(handleURLEvent:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
}
- (void)dealloc {
[NSNotificationCenter.defaultCenter removeObserver:self];
}
- (void)recievedNotification:(NSNotification *)notification {
if ([notification.name isEqualToString:@"MultiScrobbleNotification"]) {
if ([notification.object isKindOfClass:[NSDictionary class]]) {
NSDictionary *notificationinfo = notification.object;
dispatch_async(dispatch_get_main_queue(), ^{
[self showNotification:notificationinfo[@"title"] message:notificationinfo[@"message"] withIdentifier:notificationinfo[@"identifier"]];
});
}
}
}
- (void)handleURLEvent:(NSAppleEventDescriptor*)event
withReplyEvent:(NSAppleEventDescriptor*)replyEvent {
NSString* url = [event paramDescriptorForKeyword:keyDirectObject].stringValue;
[NSNotificationCenter.defaultCenter postNotificationName:@"hachidori_auth" object:url];
}
#pragma mark General UI Functions
- (NSWindowController *)preferencesWindowController {
if (!_preferencesWindowController)
{
NSViewController *generalViewController = [[GeneralPrefController alloc] init];
NSViewController *loginViewController = [[LoginPref alloc] initwithAppDelegate:self];
NSViewController *syncController = [SyncPrefs new];
NSViewController *suViewController = [[SoftwareUpdatesPref alloc] init];
NSViewController *exceptionsViewController = [[ExceptionsPref alloc] init];
NSViewController *hotkeyViewController = [[HotkeysPrefs alloc] init];
NSViewController *plexviewController = [PlexPrefs new];
NSViewController *advancedViewController = [[AdvancedPrefController alloc] init];
NSViewController *socialViewController = [[SocialPrefController alloc] initWithTwitterManager:haengine.twittermanager.twittermanager];
NSArray *controllers;
#ifdef oss
controllers = @[generalViewController, loginViewController, socialViewController, syncController, hotkeyViewController , plexviewController, exceptionsViewController, suViewController, advancedViewController];
#else
NSViewController *bittorrentpreferences = [[BittorrentPreferences alloc] initwithTorrentManager:_tbc.tmanager];
controllers = @[generalViewController, loginViewController, socialViewController, syncController, hotkeyViewController , plexviewController, bittorrentpreferences, exceptionsViewController, suViewController, advancedViewController];
#endif
_preferencesWindowController = [[MASPreferencesWindowController alloc] initWithViewControllers:controllers];
}
return _preferencesWindowController;
}
- (IBAction)showPreferences:(id)sender
{
//Since LSUIElement is set to 1 to hide the dock icon, it causes unattended behavior of having the program windows not show to the front.
[NSApp activateIgnoringOtherApps:YES];
[self.preferencesWindowController showWindow:nil];
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
if (!managedObjectContext) return NSTerminateNow;
if (![managedObjectContext commitEditing]) {
NSLog(@"%@:%@ unable to commit editing to terminate", [self class], NSStringFromSelector(_cmd));
return NSTerminateCancel;
}
if (!managedObjectContext.hasChanges) return NSTerminateNow;
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// This error handling simply presents error information in a panel with an
// "Ok" button, which does not include any attempt at error recovery (meaning,
// attempting to fix the error.) As a result, this implementation will
// present the information to the user and then follow up with a panel asking
// if the user wishes to "Quit Anyway", without saving the changes.
// Typically, this process should be altered to include application-specific
// recovery steps.
BOOL result = [sender presentError:error];
if (result) return NSTerminateCancel;
NSString *question = NSLocalizedString(@"Could not save changes while quitting. Quit anyway?", @"Quit without saves error question message");
NSString *info = NSLocalizedString(@"Quitting now will lose any changes you have made since the last successful save", @"Quit without saves error question info");
NSString *quitButton = NSLocalizedString(@"Quit anyway", @"Quit anyway button title");
NSString *cancelButton = NSLocalizedString(@"Cancel", @"Cancel button title");
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = question;
alert.informativeText = info;
[alert addButtonWithTitle:quitButton];
[alert addButtonWithTitle:cancelButton];
NSInteger answer = [alert runModal];
if (answer == NSAlertAlternateReturn) return NSTerminateCancel;
}
return NSTerminateNow;
}
- (IBAction)togglescrobblewindow:(id)sender
{
if (window.visible) {
[window close];
} else {
//Since LSUIElement is set to 1 to hide the dock icon, it causes unattended behavior of having the program windows not show to the front.
[NSApp activateIgnoringOtherApps:YES];
[window makeKeyAndOrderFront:self];
}
}
- (IBAction)showOfflineQueue:(id)sender{
//Since LSUIElement is set to 1 to hide the dock icon, it causes unattended behavior of having the program windows not show to the front.
[NSApp activateIgnoringOtherApps:YES];
if (!_owindow) {
_owindow = [[OfflineViewQueue alloc] init];
}
[_owindow.window makeKeyAndOrderFront:nil];
}
- (IBAction)getHelp:(id)sender{
//Show Help
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://help.malupdaterosx.moe/hachidori/"]];
}
- (IBAction)reportIssue:(id)sender{
//Show Help
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://support.malupdaterosx.moe/index.php?forums/hachidori-issue-tracker-support.10/"]];
}
- (IBAction)reportStreamIssue:(id)sender{
//Show Help
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://support.malupdaterosx.moe/index.php?forums/hachidori-stream-detection-support.11/"]];
}
- (IBAction)showAboutWindow:(id)sender{
// Properly show the about window in a menu item application
[NSApp activateIgnoringOtherApps:YES];
if (!_aboutWindowController) {
_aboutWindowController = [PFAboutWindowController new];
}
(self.aboutWindowController).appURL = [[NSURL alloc] initWithString:@"https://malupdaterosx.moe/hachidori/"];
NSMutableString *copyrightstr = [NSMutableString new];
NSDictionary *bundleDict = [NSBundle mainBundle].infoDictionary;
[copyrightstr appendFormat:@"%@ \r\r",bundleDict[@"NSHumanReadableCopyright"]];
if (((NSNumber *)[[NSUserDefaults standardUserDefaults] objectForKey:@"donated"]).boolValue) {
[copyrightstr appendFormat:@"This copy is registered to: %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"donor"]];
}
else {
[copyrightstr appendString:@"UNREGISTERED COPY"];
}
(self.aboutWindowController).appCopyright = [[NSAttributedString alloc] initWithString:copyrightstr
attributes:@{
NSForegroundColorAttributeName:[NSColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f],
NSFontAttributeName:[NSFont fontWithName:[NSFont systemFontOfSize:12.0f].familyName size:11]}];
[self.aboutWindowController showWindow:nil];
}
- (void)disableUpdateItems{
// Disables update options to prevent erorrs
panelactive = true;
[statusMenu setAutoenablesItems:NO];
[updatecorrect setAutoenablesItems:NO];
[updatenow setEnabled:NO];
[togglescrobbler setEnabled:NO];
[updatedcorrecttitle setEnabled:NO];
[updatedupdatestatus setEnabled:NO];
[revertrewatch setEnabled:NO];
[confirmupdate setEnabled:NO];
[findtitle setEnabled:NO];
[openstream setEnabled:NO];
[_servicemenu enableservicemenuitems:NO];
_servicenamemenu.enabled = NO;
}
- (void)enableUpdateItems{
// Reenables update options
panelactive = false;
[updatenow setEnabled:YES];
[togglescrobbler setEnabled:YES];
[updatedcorrecttitle setEnabled:YES];
if (confirmupdate.hidden) {
[updatedupdatestatus setEnabled:YES];
}
if (!confirmupdate.hidden && !haengine.lastscrobble.LastScrobbledTitleNew) {
[updatedupdatestatus setEnabled:YES];
[updatecorrect setAutoenablesItems:YES];
[revertrewatch setEnabled:YES];
}
[updatecorrect setAutoenablesItems:YES];
[confirmupdate setEnabled:YES];
[findtitle setEnabled:YES];
[openstream setEnabled:YES];
[_servicemenu enableservicemenuitems:YES];
_servicenamemenu.enabled = NO;
}
- (void)unhideMenus{
//Show Last Scrobbled Title and operations */
[seperator setHidden:NO];
[lastupdateheader setHidden:NO];
[updatedtitle setHidden:NO];
[updatedepisode setHidden:NO];
[seperator2 setHidden:NO];
[updatecorrectmenu setHidden:NO];
[updatedcorrecttitle setHidden:NO];
[shareMenuItem setHidden:NO];
}
- (void)toggleScrobblingUIEnable:(BOOL)enable{
dispatch_async(dispatch_get_main_queue(), ^{
updatenow.enabled = enable;
togglescrobbler.enabled = enable;
confirmupdate.enabled = enable;
findtitle.enabled = enable;
revertrewatch.enabled = enable;
openstream.enabled = enable;
_servicenamemenu.enabled = NO;
[_servicemenu enableservicemenuitems:enable];
if (!enable) {
[updatenow setTitle:NSLocalizedString(@"Updating...",nil)];
[self setStatusText:NSLocalizedString(@"Scrobble Status: Scrobbling...",nil)];
}
else {
[updatenow setTitle:NSLocalizedString(@"Update Now",nil)];
}
_servicenamemenu.enabled = NO;
});
}
- (void)EnableStatusUpdating:(BOOL)enable{
updatecorrect.autoenablesItems = enable;
updatetoolbaritem.enabled = enable;
updatedupdatestatus.enabled = enable;
revertrewatch.enabled = enable;
_servicenamemenu.enabled = NO;
}
- (void)enterDonationKey{
//Since LSUIElement is set to 1 to hide the dock icon, it causes unattended behavior of having the program windows not show to the front.
[NSApp activateIgnoringOtherApps:YES];
if (!_dwindow) {
_dwindow = [[DonationWindowController alloc] init];
}
[_dwindow.window makeKeyAndOrderFront:nil];
}
- (IBAction)enterDonationKey:(id)sender {
[self enterDonationKey];
}
- (IBAction)deactivatePatreonLicense:(id)sender {
NSAlert *alert = [[NSAlert alloc] init] ;
[alert addButtonWithTitle:NSLocalizedString(@"Yes",nil)];
[alert addButtonWithTitle:NSLocalizedString(@"No",nil)];
[alert setMessageText:NSLocalizedString(@"Do you want to deauthorize your Patreon license?",nil)];
alert.informativeText = NSLocalizedString(@"By deauthorizing your Patreon license, you will lose access to donor features. However, you may reauthorize your license by registering it again.",nil);
// Set Message type to Warning
alert.alertStyle = NSAlertStyleInformational;
NSModalResponse returncode = [alert runModal];
if (returncode == NSAlertFirstButtonReturn) {
[Utility deactivatePatreonLicense:self];
}
}
- (void)performsendupdatenotification:(int)status{
dispatch_async(dispatch_get_main_queue(), ^{
//Enable the Update button if a title is detected
switch (status) { // 0 - nothing playing; 1 - same episode playing; 21 - Add Title Successful; 22 - Update Title Successful; 51 - Can't find Title; 52 - Add Failed; 53 - Update Failed; 54 - Scrobble Failed;
case ScrobblerNothingPlaying:
[self setStatusText:@"Scrobble Status: Idle..."];
break;
case ScrobblerSameEpisodePlaying:
[self setStatusText:@"Scrobble Status: Same Episode Playing, Scrobble not needed."];
break;
case ScrobblerUpdateNotNeeded:
[self setStatusText:@"Scrobble Status: No update needed."];
break;
case ScrobblerConfirmNeeded:{
[self setStatusText:@"Scrobble Status: Please confirm update."];
NSDictionary * userinfo = @{@"title": haengine.lastscrobble.LastScrobbledTitle, @"episode": haengine.lastscrobble.LastScrobbledEpisode};
[self showConfirmationNotification:@"Confirm Update" message:[NSString stringWithFormat:@"Click here to confirm update for %@ Episode %@.",haengine.lastscrobble.LastScrobbledActualTitle,haengine.lastscrobble.LastScrobbledEpisode] updateData:userinfo withIdentifier:haengine.lastscrobble.AniID];
break;
}
case ScrobblerAddTitleSuccessful:
case ScrobblerUpdateSuccessful:{
[self setStatusText:@"Scrobble Status: Scrobble Successful..."];
NSString * notificationmsg;
if (haengine.lastscrobble.rewatching) {
notificationmsg = [NSString stringWithFormat:@"Rewatching %@ Episode %@",haengine.lastscrobble.LastScrobbledActualTitle,haengine.lastscrobble.LastScrobbledEpisode];
}
else {
notificationmsg = [NSString stringWithFormat:@"%@ Episode %@",haengine.lastscrobble.LastScrobbledActualTitle,haengine.lastscrobble.LastScrobbledEpisode];
}
[self showNotification:@"Scrobble Successful." message:notificationmsg withIdentifier:haengine.lastscrobble.AniID];
//Add History Record
[HistoryWindow addrecord:haengine.lastscrobble.LastScrobbledActualTitle Episode:haengine.lastscrobble.LastScrobbledEpisode Date:[NSDate date]];
break;
}
case ScrobblerOfflineQueued:
[self setStatusText:@"Scrobble Status: Scrobble Queued..."];
[self showNotification:@"Scrobble Queued." message:[NSString stringWithFormat:@"%@ - %@",haengine.lastscrobble.LastScrobbledActualTitle,haengine.lastscrobble.LastScrobbledEpisode] withIdentifier:@"scrobblequeued"];
break;
case ScrobblerTitleNotFound:
if (!((NSNumber *)[[NSUserDefaults standardUserDefaults] valueForKey:@"showcorrection"]).boolValue) {
[self setStatusText:NSLocalizedString(@"Scrobble Status: Can't find title. Retrying in 5 mins...",nil)];
[self showNotification:NSLocalizedString(@"Couldn't find title.",nil) message:[NSString stringWithFormat:NSLocalizedString(@"Click here to find %@ manually.",nil), haengine.detectedscrobble.FailedTitle] withIdentifier:@"notfound"];
}
break;
case ScrobblerAddTitleFailed:
case ScrobblerUpdateFailed:
[self showNotification:NSLocalizedString(@"Scrobble Unsuccessful.",nil) message:NSLocalizedString(@"Retrying in 5 mins...",nil) withIdentifier:@"scrobblefailed"];
[self setStatusText:NSLocalizedString(@"Scrobble Status: Scrobble Failed. Retrying in 5 mins...",nil)];
break;
case ScrobblerFailed:
[self showNotification:NSLocalizedString(@"Scrobble Unsuccessful.",nil) message:NSLocalizedString(@"Check user credentials in Preferences. You may need to login again.",nil) withIdentifier:@"badcredentials"];
[self setStatusText:NSLocalizedString(@"Scrobble Status: Scrobble Failed. User credentials might have expired.",nil)];
break;
case ScrobblerInvalidScrobble:
[self showNotification:@"Invalid Scrobble" message:@"You are trying to scrobble a title that haven't been aired or finished airing yet, which is not allowed." withIdentifier:@"invalidscrobble"];
[self setStatusText:@"Scrobble Status: Invalid Scrobble."];
break;
default:
break;
}
});
}
- (void)performRefreshUI:(int)status{
dispatch_async(dispatch_get_main_queue(), ^{
if (haengine.Success == 1) {
[findtitle setHidden:true];
[self setStatusMenuTitleEpisode:haengine.lastscrobble.LastScrobbledActualTitle ? haengine.lastscrobble.LastScrobbledActualTitle : haengine.lastscrobble.LastScrobbledTitle episode:haengine.lastscrobble.LastScrobbledEpisode];
if (status != 3 && haengine.lastscrobble.confirmed) {
// Show normal info
[self updateLastScrobbledTitleStatus:false];
//Enable Update Status functions
[self EnableStatusUpdating:YES];
[confirmupdate setHidden:YES];
[self showRevertRewatchMenu];
}
else {
// Show that user needs to confirm update
[self updateLastScrobbledTitleStatus:true];
[confirmupdate setHidden:NO];
if (haengine.lastscrobble.LastScrobbledTitleNew) {
// Disable Update Status functions for new and unconfirmed titles.
[self EnableStatusUpdating:NO];
[revertrewatch setHidden:YES];
}
else {
[self EnableStatusUpdating:YES];
[self showRevertRewatchMenu];
}
}
[sharetoolbaritem setEnabled:YES];
[correcttoolbaritem setEnabled:YES];
_servicenamemenu.enabled = NO;
[openAnimePage setEnabled:YES];
// Show hidden menus
[self unhideMenus];
NSDictionary * ainfo = haengine.lastscrobble.LastScrobbledInfo;
if (ainfo !=nil) { // Checks if Hachidori already populated info about the just updated title.
[self showAnimeInfo:ainfo];
switch ([Hachidori currentService]) {
case 0:
[_shareMenu generateShareMenu:@[[NSString stringWithFormat:@"%@ - %@", haengine.lastscrobble.LastScrobbledActualTitle, haengine.lastscrobble.LastScrobbledEpisode ], [NSURL URLWithString:[NSString stringWithFormat:@"https://kitsu.io/anime/%@", haengine.lastscrobble.AniID]]]];
break;
case 1:
[_shareMenu generateShareMenu:@[[NSString stringWithFormat:@"%@ - %@", haengine.lastscrobble.LastScrobbledActualTitle, haengine.lastscrobble.LastScrobbledEpisode ], [NSURL URLWithString:[NSString stringWithFormat:@"https://anilist.co/anime/%@", haengine.lastscrobble.AniID]]]];
break;
case 2:
[_shareMenu generateShareMenu:@[[NSString stringWithFormat:@"%@ - %@", haengine.lastscrobble.LastScrobbledActualTitle, haengine.lastscrobble.LastScrobbledEpisode ], [NSURL URLWithString:[NSString stringWithFormat:@"https://myanimelist.net/anime/%@", haengine.lastscrobble.AniID]]]];
break;
default:
break;
}
}
}
if (status == ScrobblerTitleNotFound) {
//Show option to find title
[findtitle setHidden:false];
if (((NSNumber *)[[NSUserDefaults standardUserDefaults] valueForKey:@"showcorrection"]).boolValue) {
[self showCorrectionSearchWindow:self];
}
}
// Enable Menu Items
scrobbleractive = false;
[self toggleScrobblingUIEnable:true];
});
}
- (void)resetUI {
// Resets the UI when the user logs out
[_shareMenu resetShareMenu];
[updatecorrect setAutoenablesItems:NO];
[self EnableStatusUpdating:NO];
[revertrewatch setHidden:YES];
[sharetoolbaritem setEnabled:NO];
[correcttoolbaritem setEnabled:NO];
[openAnimePage setEnabled:NO];
[findtitle setHidden:YES];
[confirmupdate setHidden:YES];
lastupdateheader.hidden = YES;
updatedtitle.hidden = YES;
updatedepisode.hidden = YES;
seperator2.hidden = YES;
updatecorrectmenu.hidden = YES;
shareMenuItem.hidden = YES;
_nowplayingview.hidden = YES;
_nothingplayingview.hidden = NO;
_servicenamemenu.enabled = NO;
[self setStatusToolTip:@"Hachidori"];
}
#pragma mark Timer Functions
- (IBAction)toggletimer:(id)sender {
//Check to see if a token exist
if (![Hachidori getCurrentFirstAccount]) {
[self showNotification:NSLocalizedString(@"Hachidori",nil) message:NSLocalizedString(@"Please log in with your account in Preferences before you enable scrobbling",nil) withIdentifier:@"noaccount"];
}
else {
if (scrobbling == FALSE) {
[self starttimer];
[togglescrobbler setTitle:NSLocalizedString(@"Stop Scrobbling",nil)];
[self showNotification:NSLocalizedString(@"Hachidori",nil) message:NSLocalizedString(@"Auto Scrobble is now turned on.",nil) withIdentifier:@"autoscrobble"];
ScrobblerStatus.objectValue = @"Scrobble Status: Started";
//Set Scrobbling State to true
scrobbling = TRUE;
}
else {
[self stoptimer];
[togglescrobbler setTitle:NSLocalizedString(@"Start Scrobbling",nil)];
ScrobblerStatus.objectValue = @"Scrobble Status: Stopped";
[self showNotification:NSLocalizedString(@"Hachidori",nil) message:NSLocalizedString(@"Auto Scrobble is now turned off.",nil) withIdentifier:@"autoscrobble"];
//Set Scrobbling State to false
scrobbling = FALSE;
}
}
}
- (void)autostarttimer {
//Check to see if there is an API Key stored
if (![Hachidori getCurrentFirstAccount]) {
[self showNotification:NSLocalizedString(@"Hachidori",nil) message:NSLocalizedString(@"Unable to start scrobbling since there is no login. Please verify your login in Preferences.",nil) withIdentifier:@"noaccount"];
}
else {
[self starttimer];
[togglescrobbler setTitle:NSLocalizedString(@"Stop Scrobbling",nil)];
ScrobblerStatus.objectValue = @"Scrobble Status: Started";
//Set Scrobbling State to true
scrobbling = TRUE;
}
}
- (void)firetimer {
//Tell haengine to detect and scrobble if necessary.
NSLog(@"Starting...");
if (!scrobbleractive) {
scrobbleractive = true;
__weak AppDelegate *weakSelf = self;
// Disable toggle scrobbler and update now menu items
[self toggleScrobblingUIEnable:false];
__block NSDictionary *expireddict = [haengine checkexpired];
if ([self checkRequireRefresh:expireddict]) {
scrobbleractive = false;
[self refreshToken:^(bool success, NSArray *failedservices) {
if (success) {
[weakSelf firetimer];
}
else {
[self showFailedRefreshTokenNotice:failedservices];
}
} withExpiredDict:expireddict];
return;
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"UseAutoExceptions"]) {
// Check for latest list of Auto Exceptions automatically each week
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"ExceptionsLastUpdated"]) {
if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"ExceptionsLastUpdated"] timeIntervalSinceNow] < -604800) {
// Has been 1 Week, update Auto Exceptions
[AutoExceptions updateAutoExceptions];
}
}
else {
// First time, populate
[AutoExceptions updateAutoExceptions];
}
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"UseAnimeRelations"]) {
// Check for latest list of Anime Relations automatically each week
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"AnimeRelationsLastUpdated"]) {
if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"AnimeRelationsLastUpdated"] timeIntervalSinceNow] < -604800) {
// Has been 1 Week, update Anime Relations
[AnimeRelations updateRelations];
}
}
else {
// First time, populate
[AnimeRelations updateRelations];
}
}
int status = 0;
for (int i = 0; i < 2; i++) {
if (i == 0) {
if ([haengine getQueueCount] > 0 && haengine.online) {
NSDictionary * status = [haengine scrobblefromqueue];
int success = [status[@"success"] intValue];
int fail = [status[@"fail"] intValue];
bool confirmneeded = [status[@"confirmneeded"] boolValue];
if (confirmneeded) {
dispatch_async(dispatch_get_main_queue(), ^{
[self setStatusText:@"Scrobble Status: Please confirm update."];
NSDictionary * userinfo = @{@"title": haengine.lastscrobble.LastScrobbledTitle, @"episode": haengine.lastscrobble.LastScrobbledEpisode};
[self showConfirmationNotification:@"Confirm Update" message:[NSString stringWithFormat:@"Click here to confirm update for %@ Episode %@.",haengine.lastscrobble.LastScrobbledActualTitle,haengine.lastscrobble.LastScrobbledEpisode] updateData:userinfo withIdentifier:haengine.lastscrobble.AniID];
});
break;
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self showNotification:@"Updated Queued Items" message:[NSString stringWithFormat:@"%i scrobbled successfully and %i failed",success, fail] withIdentifier:@"queued"];
});
}
}
}
else {
status = [haengine startscrobbling];
[self performsendupdatenotification:status];
}
}
[self performRefreshUI:status];
}
}
- (void)starttimer {
NSLog(@"Auto Scrobble Started.");
timer = [MSWeakTimer scheduledTimerWithTimeInterval:[[(NSNumber *)[NSUserDefaults standardUserDefaults] valueForKey:@"timerinterval"] intValue]
target:self
selector:@selector(firetimer)
userInfo:nil
repeats:YES
dispatchQueue:_privateQueue];
}
- (void)stoptimer {
NSLog(@"Auto Scrobble Stopped.");
//Stop Timer
[timer invalidate];
}
- (IBAction)updatenow:(id)sender{
if ([Hachidori getCurrentFirstAccount]) {
dispatch_async(_privateQueue, ^{
[self firetimer];
});
}
else