aboutsummaryrefslogtreecommitdiff
path: root/VKPC/Controller.m
blob: 825aa6ff207527e396eaf385878b447ded068629 (plain)
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
//
//  Controller.m
//  VKPC
//
//  Created by Eugene on 10/23/14.
//  Copyright (c) 2014 Eugene Z. All rights reserved.
//

#import "Controller.h"
#import "PopoverController.h"
#import "Server.h"

static NSString * const kASExecuteJSChrome = @"execute javascript";
static NSString * const kASExecuteJSSafari = @"do JavaScript";
static NSString * const kASCurrentTabChrome = @"active tab";
static NSString * const kASCurrentTabSafari = @"current tab";
static NSString * const kASTabTitleChrome = @"title of";
static NSString * const kASTabTitleSafari = @"name of";

static NSString * const kCommandAfterInjection = @"afterInjection";
static NSString * const kCommandPlayPause = @"playpause";
static NSString * const kCommandPrev = @"prev";
static NSString * const kCommandNext = @"next";
static NSString * const kCommandOperateTrack = @"operateTrack:{id}";

static NSArray *browsers = nil;
static NSString *scriptJS;
#ifdef DEBUG
static NSString *scriptJSUnescaped;
#endif
static NSString *scriptAS;
static NSMutableDictionary *cache = nil;
static NSTimer *timer = nil;
static NSInteger browser;
static BOOL initialized = NO;

@implementation Controller

+ (void)initialize {
    if (initialized) {
        return;
    }
    
    browsers = @[
                     @[@{@"id": @"com.google.Chrome", @"name": @"Google Chrome", @"key": @"chrome"}, @{@"id": @"com.google.Chrome.canary", @"name": @"Google Chrome Canary", @"key": @"chromecanary"}],
                     @[@{@"id": @"org.mozilla.firefox", @"name": @"Firefox", @"key": @"firefox"}],
                     @[@{@"id": @"com.apple.Safari", @"name": @"Safari", @"key": @"safari"}],
                     @[@{@"id": @"com.operasoftware.Opera", @"name": @"Opera", @"key": @"opera"}, @{@"id": @"com.operasoftware.OperaNext", @"name": @"Opera Next", @"key": @"operanext"}],
                     @[@{@"id": @"ru.yandex.desktop.yandex-browser", @"name": @"Yandex", @"key": @"yandex"}]
                     ];
    NSError *error = nil;
    
    scriptJS = GetFileFromResourceAsString(@"inject.js", &error);
    scriptAS = GetFileFromResourceAsString(@"inject.as", &error);
    
    if (error) {
        NSLog(@"Error while reading from resources: %@", error);
        // TODO something
        return;
    }
    
    scriptJS = [scriptJS stringByReplacingOccurrencesOfString:@"{sid}" withString:[NSString stringWithFormat:@"%d", VKPCSessionID]];
//    scriptJS = [scriptJS stringByReplacingOccurrencesOfString:@"{debug}" withString:(VKPCIsDebug ? @"true" : @"false")];
    
#ifdef DEBUG
    scriptJSUnescaped = [NSString stringWithString:scriptJS];
#endif
    
    scriptJS = [scriptJS stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
    scriptJS = [scriptJS stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    
    cache = [[NSMutableDictionary alloc] init];

//    if (NO)
    [self setupTimer];
    
    browser = [[NSUserDefaults standardUserDefaults] integerForKey:VKPCPreferencesBrowser];
    
    [[NSUserDefaults standardUserDefaults] addObserver:(id)[Controller class]
                                            forKeyPath:VKPCPreferencesBrowser
                                               options:NSKeyValueObservingOptionNew
                                               context:NULL];
    
    initialized = YES;
}

+ (void)setupTimer {
    if (timer != nil) {
        [timer invalidate];
        timer = nil;
    }
    
    [self timerCallback:nil];
    timer = [NSTimer scheduledTimerWithTimeInterval:2.0
                                             target:[Controller class]
                                           selector:@selector(timerCallback:)
                                           userInfo:nil
                                            repeats:YES];
}

#ifdef DEBUG
+ (void)debugSendPlay {
    [Controller playpause];
}

+ (void)debugInject {
    [Controller sendCommand:kCommandAfterInjection];
}

+ (void)debugCopyJS {
    NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
    [pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil];
    [pasteBoard setString:scriptJSUnescaped forType:NSStringPboardType];
}

+ (void)debugCopyAS {
    NSString *code = [self findRunningAppAndPrepareASForCommand:kCommandAfterInjection];
    if (code != nil) {
        NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
        [pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil];
        [pasteBoard setString:code forType:NSStringPboardType];
    } else {
        NSLog(@"[Controller debugCopyAS] code == nil");
    }
}
#endif

//static BOOL playlistDelegateSet = NO;
+ (void)timerCallback:(NSTimer *)timer {
    if ([[PopoverController shared] playlistTableController] != nil && [[PopoverController shared] playlistTableController].playlist.delegate == nil) {
        [[PopoverController shared].playlistTableController.playlist setDelegate:(id)[self class]];
        NSLog(@"[Controller timerCallback] playlist delegate set");
//        playlistDelegateSet = YES;
    }
    
    if ([self isASBrowser:browser]) {
        [Controller sendCommand:kCommandAfterInjection];
    } else if ([Server connectedCount:browser] <= 0) {
        [[PopoverController shared].playlistTableController clearPlaylist];
    }
}

+ (void)prev {
    [Controller sendCommand:kCommandPrev];
}

+ (void)next {
    [Controller sendCommand:kCommandNext];
}

+ (void)playpause {
    [Controller sendCommand:kCommandPlayPause];
}

+ (void)operateTrack:(NSString *)trackID {
    [Controller sendCommand:[kCommandOperateTrack stringByReplacingOccurrencesOfString:@"{id}" withString:trackID]];
}

+ (void)sendCommand:(NSString *)command {
    if ([self isASBrowser:browser]) {
        NSString *code = [self findRunningAppAndPrepareASForCommand:command];
        if (code == nil) {
    //        NSLog(@"[Controller sendCommand:] code == nil, returning");
            // Clear playlist?
            [[PopoverController shared].playlistTableController clearPlaylist];
            return;
        }
        
        NSAppleScript *as = [[NSAppleScript alloc] initWithSource:code];
        NSDictionary *error = nil;
        NSAppleEventDescriptor *result = [as executeAndReturnError:&error];
        
        if (error) {
            NSLog(@"[Controller sendCommand:] error: %@", error);
        } else if ([command isEqualToString:kCommandAfterInjection]) {
            int returnValue = 0;
            [result.data getBytes:&returnValue length:result.data.length];
    //        NSLog(@"[Controller sendCommand:] returnValue = %d", returnValue);
            if (returnValue == 1) {
                [[PopoverController shared].playlistTableController clearPlaylist];
            }
        }
    } else {
        if ([Server connectedCount:browser] <= 0) {
            [[PopoverController shared].playlistTableController clearPlaylist];
            return;
        }
        
        // Send to extensions
        [Server send:[self JSONForCommand:@"vkpc" data:command] forBrowser:browser];
    }
}

+ (NSString *)findRunningAppAndPrepareASForCommand:(NSString *)command {
    NSArray *list = browsers[browser];
    NSArray *apps = [[NSWorkspace sharedWorkspace] runningApplications];
    NSDictionary *app;
    
    BOOL found = NO;
    for (int i = 0; i < apps.count; i++) {
        NSRunningApplication *currentApp = apps[i];
        
        for (NSDictionary *dict in list) {
            if ([currentApp.bundleIdentifier isEqualToString:dict[@"id"]]) {
                app = dict;
                found = YES;
                break;
            }
        }
        
        if (found)
            break;
    }
    
    if (!found) {
//        NSLog(@"[Controller findRunningAppAndPrepareASForCommand:] %@ not found in running applications, nil will returned", (NSString *)browsers[browser][0][@"name"]);
        return nil;
    }
    
    NSString *as = scriptAS;
    NSInteger playlistID = [PopoverController shared].playlistTableController.playlist.playlistID;
    
    NSString *ASExecuteJS, *ASCurrentTab, *ASTabTitle;
    if (browser == BrowserSafari) {
        ASExecuteJS = kASExecuteJSSafari;
        ASCurrentTab = kASCurrentTabSafari;
        ASTabTitle = kASTabTitleSafari;
    } else {
        ASExecuteJS = kASExecuteJSChrome;
        ASCurrentTab = kASCurrentTabChrome;
        ASTabTitle = kASTabTitleChrome;
    }
    
    as = [as stringByReplacingOccurrencesOfString:@"{appName}" withString:app[@"name"]];
    as = [as stringByReplacingOccurrencesOfString:@"{js}" withString:scriptJS];
    as = [as stringByReplacingOccurrencesOfString:@"{ASExecuteJS}" withString:ASExecuteJS];
    as = [as stringByReplacingOccurrencesOfString:@"{ASCurrentTab}" withString:ASCurrentTab];
    as = [as stringByReplacingOccurrencesOfString:@"{ASTabTitle}" withString:ASTabTitle];
    
    as = [as stringByReplacingOccurrencesOfString:@"{playlistID}" withString:[NSString stringWithFormat:@"%ld", playlistID]];
    as = [as stringByReplacingOccurrencesOfString:@"{command}" withString:command];
    
    return as;
}

+ (void)handleClient:(NSDictionary *)json {
//    NSLog(@"[Controller handleClient] json: %@", json);
    
    NSInteger fromBrowser = [(NSNumber *)json[@"_browser"] integerValue];
    if (fromBrowser != browser) {
//        NSLog(@"[Controller handleClient] received message from browser=%zd, but current browser=%zd, skipping", fromBrowser, browser);
        return;
    }
    
    NSString *command = json[@"command"];
    NSDictionary *data = json[@"data"];
    if (!command || [command isEqual:[NSNull null]]) {
        NSLog(@"[Controller handleCommand] !json");
        return;
    }
    
    if ([command isEqualToString:@"updatePlaylist"]) {
        NSArray *tracks = data[@"tracks"];
        NSInteger playlistId = [(NSNumber *)data[@"id"] intValue];
        NSString *title = data[@"title"];
        NSDictionary *active = data[@"active"];
        NSString *browser = data[@"browser"];
        
        NSString *activeStatus = active[@"status"];
        NSString *activeId = active[@"id"];
        BOOL playingStatus = ( activeStatus && ![activeStatus isEqual:[NSNull null]] && [activeStatus isEqualToString:@"play"] ) ? YES : NO;
        
        NSLog(@"[server] got updatePlaylist; id=%ld, activeId=%@, activeStatus=%@, browser=%@, title=%@",
              playlistId, (NSString *)active[@"id"], active[@"status"], browser, title);
        
        if ([[PopoverController shared].playlistTableController inited]) {
            NSLog(@"[Controller handleClient] call setPlaylist..");
            [[PopoverController shared].playlistTableController setPlaylistDataWithTracks:tracks title:title id:playlistId activeId:activeId activePlaying:playingStatus browser:browser];
        } else {
            NSLog(@"[Controller handleClient] call preSetPlaylist..");
            [PlaylistTableController preSetPlaylistDataWithTracks:tracks title:title id:playlistId  activeId:activeId activePlaying:playingStatus browser:browser];
        }
    } else if ([command isEqualToString:@"operateTrack"]) {
        NSString *trackId = data[@"id"];
        NSString *status = data[@"status"];
        NSInteger playlistId = [(NSNumber *)data[@"playlistId"] intValue];
        
        NSLog(@"[server] got operateTrack; trackId=%@, status=%@, plId=%ld",
              trackId, status, playlistId);
        
        PlayingStatus playingStatus = (status && ![status isEqual:[NSNull null]] && [status isEqualToString:@"play"]) ? PlayingStatusPlaying : PlayingStatusPaused;
        [[PopoverController shared].playlistTableController setPlayingTrackById:trackId withStatus:playingStatus forPlaylist:playlistId];
    } else if ([command isEqualToString:@"clearPlaylist"]) {
        [[PopoverController shared].playlistTableController clearPlaylist];
    }
}

// PlaylistDeletage
+ (void)playlistIDChanged:(NSInteger)playlistID {
//    NSLog(@"playlist id changed! new id: %zd", playlistID);
    if (initialized) {
//        NSLog(@"now send new playlist id to clients");
        [Server send:[self JSONForCommand:@"set_playlist_id" data:[NSNumber numberWithInteger:playlistID]] forBrowser:-1];
    }
}

// KVO
+ (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:VKPCPreferencesBrowser]) {
        NSNumber *new = change[NSKeyValueChangeKindKey];
        if ([new integerValue] == NSKeyValueChangeSetting) {
            NSInteger value = [(NSNumber *)change[NSKeyValueChangeNewKey] integerValue];
            if (browser != value) {
                NSLog(@"[Controller KVO] new browser is %@", browsers[value][0][@"name"]);
                browser = value;
                [cache removeAllObjects];
                [[PopoverController shared].playlistTableController clearPlaylist];
                [self setupTimer];
            }
        }
    }
}

// Other
+ (BOOL)isASBrowser:(NSInteger)browser {
    return ![[NSUserDefaults standardUserDefaults] boolForKey:VKPCPreferencesUseExtensionMode] && (
                                                                     browser == BrowserChrome
                                                                     || browser == BrowserYandex
                                                                     || browser == BrowserSafari );
}

+ (NSString *)JSONForCommand:(NSString *)command data:(NSObject *)data {
    NSDictionary *dict = @{@"command": command, @"data": data};
    NSError *error;
    NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:(NSJSONWritingOptions)0 error:&error];
    
    if (!json) {
        NSLog(@"[Controller JSONForCommand] error: %@", error.localizedDescription);
        return @"{}";
    } else {
        return [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
    }
}

@end