-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathWCChatController.m
2870 lines (1984 loc) · 86.6 KB
/
WCChatController.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
/* $Id$ */
/*
* Copyright (c) 2003-2009 Axel Andersson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#import "WCAccount.h"
#import "WCAccountsController.h"
#import "WCApplicationController.h"
#import "WCChatController.h"
#import "WCChatWindow.h"
#import "WCErrorQueue.h"
#import "WCMessages.h"
#import "WCPreferences.h"
#import "WCStats.h"
#import "WCTopic.h"
#import "WCUser.h"
#import "WCUserCell.h"
#import "WCUserInfo.h"
#import "WCFiles.h"
#import "WCFile.h"
#import "WCTransfers.h"
#import "WCBoards.h"
#import "WCBoard.h"
#import "WCPublicChat.h"
#import "WCUserTableCellView.h"
#import "WCChatTableCellView.h"
#import "iTunes.h"
#import "NSString+Emoji.h"
#import "NSImage+Data.h"
#define WCPublicChatID 1
#define WCLastChatFormat @"WCLastChatFormat"
#define WCLastChatEncoding @"WCLastChatEncoding"
#define WCChatPrepend 13
#define WCChatLimit 4096
NSString * const WCChatUserAppearedNotification = @"WCChatUserAppearedNotification";
NSString * const WCChatUserDisappearedNotification = @"WCChatUserDisappearedNotification";
NSString * const WCChatUserNickDidChangeNotification = @"WCChatUserNickDidChangeNotification";
NSString * const WCChatSelfWasKickedFromPublicChatNotification = @"WCChatSelfWasKickedFromPublicChatNotification";
NSString * const WCChatSelfWasBannedNotification = @"WCChatSelfWasBannedNotification";
NSString * const WCChatSelfWasDisconnectedNotification = @"WCChatSelfWasDisconnectedNotification";
NSString * const WCChatRegularChatDidAppearNotification = @"WCChatRegularChatDidAppearNotification";
NSString * const WCChatHighlightedChatDidAppearNotification = @"WCChatHighlightedChatDidAppearNotification";
NSString * const WCChatEventDidAppearNotification = @"WCChatEventDidAppearNotification";
NSString * const WCChatHighlightColorKey = @"WCChatHighlightColorKey";
NSString * const WCUserPboardType = @"WCUserPboardType";
enum _WCChatFormat {
WCChatPlainText,
WCChatRTF,
WCChatRTFD,
};
typedef enum _WCChatFormat WCChatFormat;
@interface WCChatController(Private)
- (void)_updatePreferences;
- (void)_updateSaveChatForPanel:(NSSavePanel *)savePanel;
- (void)_setTopic:(WCTopic *)topic;
- (void)_appendRow;
- (void)_printTimestamp;
- (void)_printTopic;
- (void)_printUserJoin:(WCUser *)user;
- (void)_printUserLeave:(WCUser *)user;
- (void)_printUserChange:(WCUser *)user nick:(NSString *)nick;
- (void)_printUserChange:(WCUser *)user status:(NSString *)status;
- (void)_printUserKick:(WCUser *)victim by:(WCUser *)killer message:(NSString *)message;
- (void)_printUserBan:(WCUser *)victim message:(NSString *)message;
- (void)_printUserBanned:(WCUser *)victim expirationDate:(NSDate *)date;
- (void)_printUserDisconnect:(WCUser *)victim message:(NSString *)message;
- (void)_printChat:(NSString *)chat by:(WCUser *)user;
- (void)_sendImage:(NSURL *)url;
- (void)_sendiTunes;
- (NSArray *)_commands;
- (BOOL)_runCommand:(NSString *)command;
- (NSString *)_stringByCompletingString:(NSString *)string;
- (void)_applyChatAttributesToAttributedString:(NSMutableAttributedString *)attributedString;
- (void)_applyHTMLTagsForHighlightsToMutableString:(NSMutableString *)mutableString;
- (NSColor *)_highlightColorForChat:(NSString *)chat;
- (NSDictionary *)_currentTheme;
- (void)_loadTheme:(NSDictionary *)theme;
@end
@implementation WCChatController(Private)
- (void)_updatePreferences {
NSMutableArray *highlightPatterns, *highlightColors;
NSEnumerator *enumerator;
NSDictionary *highlight;
highlightPatterns = [NSMutableArray array];
highlightColors = [NSMutableArray array];
enumerator = [[[WCSettings settings] objectForKey:WCHighlights] objectEnumerator];
while((highlight = [enumerator nextObject])) {
[highlightPatterns addObject:[highlight objectForKey:WCHighlightsPattern]];
[highlightColors addObject:WIColorFromString([highlight objectForKey:WCHighlightsColor])];
}
if(![highlightPatterns isEqualToArray:_highlightPatterns] || ![highlightColors isEqualToArray:_highlightColors]) {
[_highlightPatterns setArray:highlightPatterns];
[_highlightColors setArray:highlightColors];
}
}
- (void)_updateSaveChatForPanel:(NSSavePanel *)savePanel {
WIChatLogType type;
type = [_saveChatFileFormatPopUpButton indexOfSelectedItem];
[savePanel setAllowedFileTypes:[NSArray arrayWithObject:[[WIChatLogController typeExtentions] objectAtIndex:type]]];
}
#pragma mark -
- (void)_setTopic:(WCTopic *)topic {
[topic retain];
[_topic release];
_topic = topic;
if([[_topic topic] length] > 0) {
NSString *topicString = [NSSWF:@"%@ - by %@ - %@", [_topic topic], [_topic nick], [_topicDateFormatter stringFromDate:[_topic date]]];
[_topicTextField setToolTip:topicString];
[_topicTextField setStringValue:topicString];
} else {
[_topicTextField setToolTip:NULL];
[_topicTextField setStringValue:@""];
}
}
#pragma mark -
- (void)_printTimestamp {
NSDate *date;
NSTimeInterval interval;
if(!_timestamp)
_timestamp = [[NSDate date] retain];
interval = [[[WCSettings settings] objectForKey:WCChatTimestampChatInterval] doubleValue];
date = [NSDate dateWithTimeIntervalSinceNow:-interval];
if([date compare:_timestamp] == NSOrderedDescending) {
[self printEvent:[_timestampDateFormatter stringFromDate:[NSDate date]]];
[_timestamp release];
_timestamp = [[NSDate date] retain];
}
}
- (void)_printTopic {
[self printEvent:[NSSWF: NSLS(@"%@ changed topic to %@", @"Topic changed (nick, topic)"),
[_topic nick], [_topic topic]]];
}
- (void)_printUserJoin:(WCUser *)user {
[self printEvent:[NSSWF:NSLS(@"%@ has joined", @"User has joined message (nick)"),
[user nick]]];
}
- (void)_printUserLeave:(WCUser *)user {
[self printEvent:[NSSWF:NSLS(@"%@ has left", @"User has left message (nick)"),
[user nick]]];
}
- (void)_printUserChange:(WCUser *)user nick:(NSString *)nick {
[self printEvent:[NSSWF:NSLS(@"%@ is now known as %@", @"User rename message (oldnick, newnick)"),
[user nick], nick]];
}
- (void)_printUserChange:(WCUser *)user status:(NSString *)status {
[self printEvent:[NSSWF:NSLS(@"%@ changed status to %@", @"User status changed message (nick, status)"),
[user nick], status]];
}
- (void)_printUserKick:(WCUser *)victim by:(WCUser *)killer message:(NSString *)message {
if([message length] > 0) {
[self printEvent:[NSSWF:NSLS(@"%@ was kicked by %@ (%@)", @"User kicked message (victim, killer, message)"),
[victim nick], [killer nick], message]];
} else {
[self printEvent:[NSSWF:NSLS(@"%@ was kicked by %@", @"User kicked message (victim, killer)"),
[victim nick], [killer nick]]];
}
}
- (void)_printUserBan:(WCUser *)victim message:(NSString *)message {
if([message length] > 0) {
[self printEvent:[NSSWF:NSLS(@"%@ was banned (%@)", @"User banned message (victim, message)"),
[victim nick], message]];
} else {
[self printEvent:[NSSWF:NSLS(@"%@ was banned", @"User banned message (victim)"),
[victim nick]]];
}
}
- (void)_printUserBanned:(WCUser *)victim expirationDate:(NSDate *)date {
if(date) {
[self printEvent:[NSSWF:NSLS(@"Your are banned from this server until %@", @"User banned message (expiration date)"), date]];
} else {
[self printEvent:[NSSWF:NSLS(@"Your are indefinitely banned from this server", @"User banned message")]];
}
}
- (void)_printUserDisconnect:(WCUser *)victim message:(NSString *)message {
if([message length] > 0) {
[self printEvent:[NSSWF:NSLS(@"%@ was disconnected (%@)", @"User disconnected message (victim, message)"),
[victim nick], message]];
} else {
[self printEvent:[NSSWF:NSLS(@"%@ was disconnected", @"User disconnected message (victim)"),
[victim nick]]];
}
}
- (void)_printChat:(NSString *)chat by:(WCUser *)user {
WIChatLogController *logController;
NSString *nick, *formattedDate, *formattedLogs, *chatString;
NSAttributedString *attrString;
NSMutableAttributedString *mutableOutput;
NSDictionary *message;
BOOL timestamp;
NSFont *font;
NSDictionary *theme;
theme = [[WCSettings settings] themeWithName:@"Wired"];
font = WIFontFromString ([theme objectForKey:WCThemesChatFont]);
chat = [[chat componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@"\n"];
logController = [[WCApplicationController sharedController] logController];
timestamp = [[[self connection] theme] boolForKey:WCThemesChatTimestampEveryLine];
nick = [user nick];
formattedDate = (timestamp) ? [_timestampEveryLineDateFormatter stringFromDate:[NSDate date]] : @"";
formattedLogs = [NSSWF:@"[%@]\t%@: %@\n", [_timestampEveryLineDateFormatter stringFromDate:[NSDate date]], nick, chat];
chatString = chat;
if ([chatString hasPrefix:@"<img src='data:image/png;base64,"]) {
NSArray *comps = [chatString componentsSeparatedByString:@"base64,"];
NSString *base64String = [[comps lastObject] substringToIndex:[[comps lastObject] length] - 3];
NSImage *image = [NSImage imageWithData:[NSData dataWithBase64EncodedString:base64String]];
id <NSTextAttachmentCell> cell = [[[NSTextAttachmentCell alloc] initImageCell:image] autorelease];
NSTextAttachment *attachment = [[[NSTextAttachment alloc] initWithData:nil ofType:nil] autorelease];
[attachment setAttachmentCell:cell];
NSAttributedString *attrString = [NSAttributedString attributedStringWithAttachment:attachment];
mutableOutput = [[[NSMutableAttributedString alloc] initWithAttributedString:attrString] autorelease];
}
else if ([chatString hasPrefix:@"<img src='http"]) {
NSData *imageData = [chatString dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString *imageString = [[NSAttributedString alloc] initWithHTML:imageData documentAttributes:nil];
if (imageString) {
mutableOutput = [[[NSMutableAttributedString alloc] initWithAttributedString:imageString] autorelease];
}
} else {
if([[[self connection] theme] boolForKey:WCThemesShowSmileys])
chatString = [chat stringByReplacingEmojiCheatCodesWithUnicode];
attrString = [NSAttributedString attributedStringWithString:chatString attributes:@{
NSFontAttributeName: font
}];
mutableOutput = [[[NSMutableAttributedString alloc] initWithAttributedString:attrString] autorelease];
[self _applyHighlightsToMutableString:mutableOutput];
[self _applyClickableURLs:mutableOutput];
}
message = [NSDictionary dictionaryWithObjectsAndKeys:
[user icon], @"icon",
formattedDate, @"timestamp",
nick, @"nick",
mutableOutput, @"message", nil];
[_messages addObject:message];
[self _appendRow];
if([[WCSettings settings] boolForKey:WCChatLogsPlainTextEnabled])
[logController appendChatLogAsPlainText:formattedLogs
forConnectionName:[[self connection] name]];
}
- (void)_printActionChat:(NSString *)chat by:(WCUser *)user {
WIChatLogController *logController;
NSString *nick, *formattedDate, *formattedLogs, *chatString;
NSAttributedString *attrString;
NSMutableAttributedString *mutableOutput;
NSDictionary *message;
BOOL timestamp;
NSFont *font;
NSDictionary *theme;
theme = [[WCSettings settings] themeWithName:@"Wired"];
font = WIFontFromString ([theme objectForKey:WCThemesChatFont]);
chat = [[chat componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@"\n"];
logController = [[WCApplicationController sharedController] logController];
nick = [user nick];
timestamp = [[[self connection] theme] boolForKey:WCThemesChatTimestampEveryLine];
formattedDate = (timestamp) ? [_timestampEveryLineDateFormatter stringFromDate:[NSDate date]] : @"";
formattedLogs = [NSSWF:@"[%@]\t*** %@ %@\n", [_timestampEveryLineDateFormatter stringFromDate:[NSDate date]], [user nick], chat];
chatString = [NSSWF:@"%@ %@", nick, chat];
if([[[self connection] theme] boolForKey:WCThemesShowSmileys])
chatString = [chatString stringByReplacingEmojiCheatCodesWithUnicode];
attrString = [NSAttributedString attributedStringWithString:chatString attributes:@{
NSFontAttributeName: [font boldFont]
}];
mutableOutput = [[[NSMutableAttributedString alloc] initWithAttributedString:attrString] autorelease];
[self _applyHighlightsToMutableString:mutableOutput];
[self _applyClickableURLs:mutableOutput];
message = [NSDictionary dictionaryWithObjectsAndKeys:
@"true", @"me",
[user icon], @"icon",
formattedDate, @"timestamp",
nick, @"nick",
mutableOutput, @"message", nil];
[_messages addObject:message];
[self _appendRow];
if([[WCSettings settings] boolForKey:WCChatLogsPlainTextEnabled])
[logController appendChatLogAsPlainText:formattedLogs forConnectionName:[[self connection] name]];
}
- (void)_appendRow {
//[_chatTableView beginUpdates];
NSInteger lastRow = [_messages count] == 0 ? 0 : [_messages count] - 1;
NSIndexSet *lastRowIndexSet = [NSIndexSet indexSetWithIndex:lastRow];
[_chatTableView insertRowsAtIndexes:lastRowIndexSet
withAnimation:NSTableViewAnimationSlideUp];
//[_chatTableView endUpdates];
[_chatTableView scrollToBottomAnimated];
}
#pragma mark -
- (void)_sendiTunes
{
iTunesApplication *iTunes;
WIP7Message *message;
WCUser *user;
NSString *chat, *name, *artist, *album;
user = [self userWithUserID:[[self connection] userID]];
if (@available(macOS 10.15, *)) {
iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.Music"];
} else {
iTunes = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
}
if([iTunes isRunning] && [iTunes currentTrack] && [iTunes playerState] != iTunesEPlSStopped) {
name = [[iTunes currentTrack] name];
artist = [[iTunes currentTrack] artist];
album = [[iTunes currentTrack] album];
if(!name || [name length] <= 0 )
name = NSLS(@"Unknow Track", @"Unknow Track");
if(!artist || [artist length] <= 0)
artist = NSLS(@"Unknow Artist", @"Unknow Artist");
if(!album || [album length] <= 0)
album = NSLS(@"Unknow Album", @"Unknow Album");
chat = [NSSWF:NSLS(@"is listening to %@ performed by %@ in album %@.", @"Now playing message"),
name,
artist,
album];
if(chat && [chat length] > 0) {
message = [WIP7Message messageWithName:@"wired.chat.send_me" spec:WCP7Spec];
[message setUInt32:[self chatID] forName:@"wired.chat.id"];
[message setString:chat forName:@"wired.chat.me"];
[[self connection] sendMessage:message];
}
}
}
- (void)_sendImage:(NSURL *)url {
NSString *html;
WIP7Message *message;
NSImage *image;
NSString *base64;
NSData *imageData;
CGFloat newHeight;
if([[url scheme] hasPrefix:@"http"]) {
html = [NSSWF:@"<img src='%@'/>", [url absoluteString]];
// imageData = [NSData dataWithContentsOfURL:url];
// image = [NSImage imageWithData:imageData];
//
// if(image) {
// if (image.size.width > 350) {
// newHeight = 350 / image.size.width * image.size.height;
// image = [image scaledImageWithSize:NSMakeSize(350, newHeight)];
// }
//
// base64 = [[image TIFFRepresentation] base64EncodedString];
// html = [NSSWF:@"<img src='data:image/png;base64, %@'/>", base64];
// }
} else if ([url scheme] == nil && [[url absoluteString] hasPrefix:@"/"]) {
image = [NSImage imageWithContentsOfFile:[url absoluteString]];
if(image) {
if (image.size.width > 350) {
newHeight = 350 / image.size.width * image.size.height;
image = [image scaledImageWithSize:NSMakeSize(350, newHeight)];
}
base64 = [[image TIFFRepresentation] base64EncodedString];
html = [NSSWF:@"<img src='data:image/png;base64, %@'/>", base64];
}
}
if(html && [html length] > 0) {
message = [WIP7Message messageWithName:@"wired.chat.send_say" spec:WCP7Spec];
[message setUInt32:[self chatID] forName:@"wired.chat.id"];
[message setString:html forName:@"wired.chat.say"];
[[self connection] sendMessage:message];
}
}
- (void)_sendLocalImage:(NSURL *)url {
NSImage *image;
NSString *html;
NSString *base64ImageString;
NSData *imageData;
CGFloat newHeight;
image = [NSImage imageWithData:[NSData dataWithContentsOfURL:url]];
if (image.size.width > 350) {
newHeight = 350 / image.size.width * image.size.height;
image = [image scaledImageWithSize:NSMakeSize(350, newHeight)];
}
imageData = [image TIFFRepresentation];
base64ImageString = [imageData base64EncodedString];
html = [NSSWF:@"<img src='data:image/png;base64, %@'/>", base64ImageString];
if(html && [html length] > 0) {
[self sendChat:html];
}
}
#pragma mark -
- (NSArray *)_commands {
return [NSArray arrayWithObjects:
@"/help",
@"/me",
@"/exec",
@"/nick",
@"/status",
@"/stats",
@"/clear",
@"/topic",
@"/broadcast",
@"/ping",
@"/afk",
@"/img",
@"/itunes",
NULL];
}
- (BOOL)_runCommand:(NSString *)string {
NSString *command, *argument;
WIP7Message *message;
NSRange range;
NSUInteger transaction;
range = [string rangeOfString:@" "];
if(range.location == NSNotFound) {
command = string;
argument = @"";
} else {
command = [string substringToIndex:range.location];
argument = [string substringFromIndex:range.location + 1];
}
if([command isEqualToString:@"/me"] && [argument length] > 0) {
if([argument length] > WCChatLimit)
argument = [argument substringToIndex:WCChatLimit];
message = [WIP7Message messageWithName:@"wired.chat.send_me" spec:WCP7Spec];
[message setUInt32:[self chatID] forName:@"wired.chat.id"];
[message setString:argument forName:@"wired.chat.me"];
[[self connection] sendMessage:message];
[[WCStats stats] addUnsignedLongLong:[argument length] forKey:WCStatsChat];
return YES;
}
else if([command isEqualToString:@"/exec"] && [argument length] > 0) {
NSString *output;
output = [[self class] outputForShellCommand:argument];
if(output && [output length] > 0) {
if([output length] > WCChatLimit)
output = [output substringToIndex:WCChatLimit];
message = [WIP7Message messageWithName:@"wired.chat.send_say" spec:WCP7Spec];
[message setUInt32:[self chatID] forName:@"wired.chat.id"];
[message setString:output forName:@"wired.chat.say"];
[[self connection] sendMessage:message];
}
return YES;
}
else if(([command isEqualToString:@"/nick"] ||
[command isEqualToString:@"/n"]) && [argument length] > 0) {
message = [WIP7Message messageWithName:@"wired.user.set_nick" spec:WCP7Spec];
[message setString:argument forName:@"wired.user.nick"];
[[self connection] sendMessage:message];
return YES;
}
else if([command isEqualToString:@"/status"] || [command isEqualToString:@"/s"]){
message = [WIP7Message messageWithName:@"wired.user.set_status" spec:WCP7Spec];
[message setString:argument forName:@"wired.user.status"];
[[self connection] sendMessage:message];
return YES;
}
else if([command isEqualToString:@"/stats"]) {
[self stats:self];
return YES;
}
else if([command isEqualToString:@"/clear"]) {
[self clearChat];
return YES;
}
else if([command isEqualToString:@"/topic"]) {
message = [WIP7Message messageWithName:@"wired.chat.set_topic" spec:WCP7Spec];
[message setUInt32:[self chatID] forName:@"wired.chat.id"];
[message setString:argument forName:@"wired.chat.topic.topic"];
[[self connection] sendMessage:message];
return YES;
}
else if([command isEqualToString:@"/broadcast"] && [argument length] > 0) {
message = [WIP7Message messageWithName:@"wired.message.send_broadcast" spec:WCP7Spec];
[message setString:argument forName:@"wired.message.broadcast"];
[[self connection] sendMessage:message];
return YES;
}
else if([command isEqualToString:@"/ping"]) {
message = [WIP7Message messageWithName:@"wired.send_ping" spec:WCP7Spec];
transaction = [[self connection] sendMessage:message fromObserver:self selector:@selector(wiredSendPingReply:)];
[_pings setObject:[NSNumber numberWithDouble:[NSDate timeIntervalSinceReferenceDate]]
forKey:[NSNumber numberWithUnsignedInt:transaction]];
return YES;
}
else if([command isEqualToString:@"/afk"]) {
message = [WIP7Message messageWithName:@"wired.user.set_idle" spec:WCP7Spec];
[message setBool:YES forName:@"wired.user.idle"];
[[self connection] sendMessage:message];
return YES;
}
else if([command isEqualToString:@"/img"]) {
if(argument && [argument length] > 0) {
NSURL *url = [NSURL URLWithString:argument];
if(url)
[self _sendImage:url];
}
return YES;
}
else if([command isEqualToString:@"/itunes"]) {
[self _sendiTunes];
return YES;
}
return NO;
}
#pragma mark -
- (NSString *)_stringByCompletingString:(NSString *)string {
NSEnumerator *enumerator, *setEnumerator;
NSArray *nicks, *commands, *set, *matchingSet = NULL;
NSString *match, *prefix = NULL;
NSUInteger matches = 0;
nicks = [self nicks];
commands = [self _commands];
enumerator = [[NSArray arrayWithObjects:nicks, commands, NULL] objectEnumerator];
while((set = [enumerator nextObject])) {
setEnumerator = [set objectEnumerator];
while((match = [setEnumerator nextObject])) {
if([match rangeOfString:string options:NSCaseInsensitiveSearch].location == 0) {
if(matches == 0) {
prefix = match;
matches = 1;
} else {
prefix = [prefix commonPrefixWithString:match options:NSCaseInsensitiveSearch];
if([prefix length] < [match length])
matches++;
}
matchingSet = set;
}
}
}
if(matches > 1)
return prefix;
if(matches == 1) {
if(matchingSet == nicks)
return [prefix stringByAppendingString:[[WCSettings settings] objectForKey:WCChatTabCompleteNicksString]];
else if(matchingSet == commands)
return [prefix stringByAppendingString:@" "];
}
return string;
}
- (void)_applyChatAttributesToAttributedString:(NSMutableAttributedString *)attributedString {
static NSCharacterSet *whitespaceSet, *nonWhitespaceSet, *nonTimestampSet, *nonHighlightSet;
NSMutableCharacterSet *characterSet;
NSScanner *scanner;
NSString *word, *chat;
NSColor *color;
NSRange range, nickRange;
if(!whitespaceSet) {
whitespaceSet = [[NSCharacterSet whitespaceAndNewlineCharacterSet] retain];
nonWhitespaceSet = [[whitespaceSet invertedSet] retain];
characterSet = [[NSMutableCharacterSet decimalDigitCharacterSet] mutableCopy];
[characterSet addCharactersInString:@":."];
[characterSet invert];
nonTimestampSet = [characterSet copy];
[characterSet release];
nonHighlightSet = [[NSCharacterSet alphanumericCharacterSet] retain];
}
range = NSMakeRange(0, [attributedString length]);
[attributedString addAttribute:NSForegroundColorAttributeName value:_chatColor range:range];
[attributedString addAttribute:NSFontAttributeName value:_chatFont range:range];
scanner = [NSScanner scannerWithString:[attributedString string]];
[scanner setCharactersToBeSkipped:NULL];
while(![scanner isAtEnd]) {
[scanner skipUpToCharactersFromSet:nonWhitespaceSet];
range.location = [scanner scanLocation];
if(![scanner scanUpToCharactersFromSet:whitespaceSet intoString:&word])
break;
range.length = [scanner scanLocation] - range.location;
if([word rangeOfCharacterFromSet:nonTimestampSet].location == NSNotFound ||
[word isEqualToString:@"PM"] || [word isEqualToString:@"AM"]) {
[attributedString addAttribute:NSForegroundColorAttributeName value:_timestampEveryLineColor range:range];
continue;
}
if([word isEqualToString:@"<<<"]) {
if([scanner scanUpToString:@">>>" intoString:NULL]) {
range.length = [scanner scanLocation] - range.location + 3;
[attributedString addAttribute:NSForegroundColorAttributeName value:_eventsColor range:range];
[scanner scanUpToString:@"\n" intoString:NULL];
continue;
}
}
if([word isEqualToString:@"*"] || [word isEqualToString:@"***"]) {
[scanner scanUpToString:@"\n" intoString:NULL];
continue;
}
nickRange = range;
if([word hasSuffix:@":"]) {
nickRange.length--;
if(![scanner isAtEnd])
[scanner setScanLocation:[scanner scanLocation] + 1];
} else {
[scanner scanUpToString:@":" intoString:NULL];
nickRange.length = [scanner scanLocation] - range.location;
if(![scanner isAtEnd])
[scanner setScanLocation:[scanner scanLocation] + 1];
}
if([scanner scanUpToString:@"\n" intoString:&chat]) {
color = [self _highlightColorForChat:chat];
if(color != NULL)
[attributedString addAttribute:NSForegroundColorAttributeName value:color range:nickRange];
}
}
}
- (void)_applyHTMLTagsForHighlightsToMutableString:(NSMutableString *)mutableString; {
NSColor *color;
NSString *string, *highlightString;
NSRange range;
color = [self _highlightColorForChat:mutableString];
if(!color)
return;
for(NSString *pattern in _highlightPatterns) {
range = [mutableString rangeOfString:pattern options:NSCaseInsensitiveSearch];
if(range.location == NSNotFound)
return;
string = [mutableString substringWithRange:range];
if(string) {
highlightString = [NSSWF:@"<span style='color:%@;'>%@</span>", [NSSWF:@"#%.6lx", (unsigned long)[color HTMLValue]], string];
[mutableString replaceOccurrencesOfString:string withString:highlightString];
}
}
}
- (void)_applyClickableURLs:(NSMutableAttributedString *)mutableString {
NSRange range;
range = [[mutableString string] rangeOfRegex:[NSSWF:@"(^|\\s)(%@)(\\.|,|:|\\?|!)?(\\s|$)", [NSString URLRegex]]
options:RKLCaseless | RKLMultiline
capture:0];
if (range.location != NSNotFound) {
[mutableString addAttribute:NSLinkAttributeName value:[[mutableString string] substringWithRange:range] range:range];
}
range = [[mutableString string] rangeOfRegex:[NSSWF:@"(^|\\s)(%@)(\\.|,|:|\\?|!)?(\\s|$)", [NSString schemelessURLRegex]]
options:RKLCaseless | RKLMultiline
capture:0];
if (range.location != NSNotFound) {
[mutableString addAttribute:NSLinkAttributeName value:[[mutableString string] substringWithRange:range] range:range];
}
range = [[mutableString string] rangeOfRegex:[NSSWF:@"(^|\\s)(%@)(\\.|,|:|\\?|!)?(\\s|$)", [NSString mailtoURLRegex]]
options:RKLCaseless | RKLMultiline
capture:0];
if (range.location != NSNotFound) {
[mutableString addAttribute:NSLinkAttributeName value:[[mutableString string] substringWithRange:range] range:range];
}
}
- (void)_applyHighlightsToMutableString:(NSMutableAttributedString *)mutableString {
NSColor *color;
NSAttributedString *highlightString;
NSString *string;
NSRange range;
color = [self _highlightColorForChat:[mutableString string]];
if(!color)
return;
for(NSString *pattern in _highlightPatterns) {
range = [[mutableString string] rangeOfString:pattern options:NSCaseInsensitiveSearch];
if(range.location == NSNotFound)
return;
string = [[mutableString string] substringWithRange:range];
if(string) {
//highlightString = [NSSWF:@"<span style='color:%@;'>%@</span>", [NSSWF:@"#%.6lx", (unsigned long)[color HTMLValue]], string];
highlightString = [NSAttributedString attributedStringWithString:string
attributes:@{NSForegroundColorAttributeName: color}];
[mutableString replaceCharactersInRange:range withAttributedString:highlightString];
}
}
}
#pragma mark -
- (NSColor *)_highlightColorForChat:(NSString *)chat {
NSCharacterSet *alphanumericCharacterSet;
NSRange range;
NSUInteger i, count, length, index;
alphanumericCharacterSet = [NSCharacterSet alphanumericCharacterSet];
length = [chat length];
count = [_highlightPatterns count];
for(i = 0; i < count; i++) {
range = [chat rangeOfString:[_highlightPatterns objectAtIndex:i] options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound) {
index = range.location + range.length;
if(index == length || ![alphanumericCharacterSet characterIsMember:[chat characterAtIndex:index]])
return [_highlightColors objectAtIndex:i];
}
}
return NULL;
}
#pragma mark -
- (NSDictionary *)_currentTheme {
return ([[self connection] theme] ?
[[self connection] theme] :
[[WCSettings settings] themeWithIdentifier:[[WCSettings settings] objectForKey:WCTheme]]);
}
- (void)_loadTheme:(NSDictionary *)theme {
[self themeDidChange:theme];
}
@end
@implementation WCChatController
+ (NSString *)outputForShellCommand:(NSString *)command {
NSTask *task;
NSPipe *pipe;
NSFileHandle *fileHandle;
NSDictionary *environment;
NSData *data;
double timeout = 5.0;
pipe = [NSPipe pipe];
fileHandle = [pipe fileHandleForReading];
environment = [NSDictionary dictionaryWithObject:@"/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin" forKey:@"PATH"];
task = [[[NSTask alloc] init] autorelease];
[task setLaunchPath:@"/bin/sh"];
[task setArguments:[NSArray arrayWithObjects:@"-c", command, NULL]];
[task setStandardOutput:pipe];
[task setStandardError:pipe];
[task setEnvironment:environment];
[task launch];
while([task isRunning]) {
usleep(100000);
timeout -= 0.1;
if(timeout <= 0.0) {
[task terminate];
break;
}
}
data = [fileHandle readDataToEndOfFile];
return [NSString stringWithData:data encoding:NSUTF8StringEncoding];
}
+ (void)applyHTMLTagsForURLToMutableString:(NSMutableString *)mutableString {
NSString *substring;
NSRange range;
/* Do this in a custom loop to avoid corrupted strings when using $1 multiple times */
do {