William Bowling is sharing code with you

Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.

Don't show this again

wbowling / adium (fork of adium / adium)

Fork of Adium for patches/improvements

Clone this repository (size: 338.7 MB): HTTPS / SSH
hg clone https://bitbucket.org/wbowling/adium
hg clone ssh://hg@bitbucket.org/wbowling/adium

adium / Plugins / Purple Service / ESIRCAccount.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
//
//  ESIRCAccount.m
//  Adium
//
//  Created by Evan Schoenberg on 3/4/06.
//  Copyright 2006 The Adium Team. All rights reserved.
//

#import "ESIRCAccount.h"
#import <Adium/AIHTMLDecoder.h>
#import <Adium/AIChat.h>
#import <Adium/AIContentMessage.h>
#import <Adium/AIListContact.h>
#import <Adium/AIMenuControllerProtocol.h>
#import "AIMessageViewController.h"
#import <AIUtilities/AIMenuAdditions.h>
#import <AIUtilities/AIAttributedStringAdditions.h>
#import <libpurple/irc.h>
#import <libpurple/cmds.h>
#import "SLPurpleCocoaAdapter.h"

@interface SLPurpleCocoaAdapter ()
- (BOOL)attemptPurpleCommandOnMessage:(NSString *)originalMessage fromAccount:(AIAccount *)sourceAccount inChat:(AIChat *)chat;
@end

@interface ESIRCAccount()
- (void)sendRawCommand:(NSString *)command;
- (void)apply:(BOOL)apply operation:(NSString *)operation flag:(NSString *)flag;
@end

static PurpleConversation *fakeConversation(PurpleAccount *account);

@implementation ESIRCAccount

/*!
 * @brief Our explicit formatted UID contains our hostname, so we can differentiate ourself.
 */
- (NSString *)explicitFormattedUID
{
        if (self.host) {
                return [NSString stringWithFormat:@"%@ (%@)", self.host, self.displayName];
        } else {
                return self.displayName;
        }
}

#pragma mark IRC-ism overloads

/*!
 * @brief We always want to autocomplete the UID.
 */
- (BOOL)chatShouldAutocompleteUID:(AIChat *)inChat
{
        return YES;
}

/*!
 * @brief Use the object ID for password name
 *
 * We mess around a lot with the UID. This lets it actually save right.
 */
- (BOOL)useInternalObjectIDForPasswordName
{
        return YES;
}

- (BOOL)openChat:(AIChat *)chat
{
        chat.hideUserIconAndStatus = YES;
        
        return [super openChat:chat];
}

/*!
 * @brief Open the info inspector when getting info
 *
 * A user can /whois; we want to display info for this case.
 */
- (void)openInspectorForContactInfo:(AIListContact *)theContact
{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AIShowContactInfo" object:theContact];
}

#pragma mark Command handling
/*!
 * @brief We've connected
 *
 * Send the commands the user wants sent when we do so. Creates a fake conversation to pipe them through.
 */
- (void)didConnect
{
        [super didConnect];
        
        PurpleConversation *conv = fakeConversation(self.purpleAccount);
        
        for (NSString *command in [[self preferenceForKey:KEY_IRC_COMMANDS
                                                                                                group:GROUP_ACCOUNT_STATUS] componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {
                if ([command hasPrefix:@"/"]) {
                        command = [command substringFromIndex:1];
                }
                
                command = [command stringByReplacingOccurrencesOfString:@"$me" withString:self.displayName];
                
                if (command.length) {
                        char *error;
                        PurpleCmdStatus cmdStatus = purple_cmd_do_command(conv, [command UTF8String], [command UTF8String], &error);
                        
                        if (cmdStatus == PURPLE_CMD_STATUS_NOT_FOUND) {
                                // If it's not found, send it as a raw command like we do in chats.
                                [self sendRawCommand:command];
                        } else if (cmdStatus != PURPLE_CMD_STATUS_OK) {
                                // The command failed with something other than "not found" - log it.
                                AILogWithSignature(@"Command (%@) failed: %d - %@", command, cmdStatus, [NSString stringWithUTF8String:error]);
                        }
                }
        }
        
        // The fakeConversation was allocated; now free it.
        g_free(conv);
        
        // Set a fake display name preference since we differ from global always.
        [self setPreference:[[NSAttributedString stringWithString:@"Adium"] dataRepresentation]
                                 forKey:KEY_ACCOUNT_DISPLAY_NAME
                                  group:GROUP_ACCOUNT_STATUS];
}

/*!
 * @brief Send a raw command to the IRC server.
 */
- (void)sendRawCommand:(NSString *)command
{
        PurpleConnection *connection = purple_account_get_connection(account);
        
        if (!connection)
                return;
        
        const char *quote = [command UTF8String];
        irc_cmd_quote(connection->proto_data, NULL, NULL, &quote);      
}

/*!
 * @brief This creates a fake PurpleConversation
 *
 * This fake conversation is used for sending purple_cmd_do_command() messages, which requires
 * a conversation for the command to occur. Free this when finished.
 *
 * This is taken from irchelper.c, the pidgin plugin.
 */
static PurpleConversation *fakeConversation(PurpleAccount *account)
{
        PurpleConversation *conv;
        
        conv = g_new0(PurpleConversation, 1);
        conv->type = PURPLE_CONV_TYPE_IM;
        /* If we use this then the conversation updated signal is fired and
         * other plugins might start doing things to our conversation, such as
         * setting data on it which we would then need to free etc. It's easier
         * just to be more hacky by setting account directly. */
        /* purple_conversation_set_account(conv, account); */
        conv->account = account;
        
        return conv;
}

- (NSString *)encodedAttributedStringForSendingContentMessage:(AIContentMessage *)inContentMessage
{
        
        NSString        *encodedString = nil;
        BOOL            didCommand = [self.purpleAdapter attemptPurpleCommandOnMessage:inContentMessage.message.string
                                                                                                                         fromAccount:(AIAccount *)inContentMessage.source
                                                                                                                                  inChat:inContentMessage.chat];
        
        NSRange meRange = [inContentMessage.message.string rangeOfString:@"/me " options:NSCaseInsensitiveSearch];
        
        if (!didCommand || meRange.location == 0) {
                if (meRange.location == 0) {
                        inContentMessage.sendContent = NO;
                }
                /* If we're sending a message on an encryption chat (can this even happen on irc?), we can encode the HTML normally, as links will go through fine.
                 * If we're sending a message normally, IRC will drop the title of any link, so we preprocess it to be in the form "title (link)"
                 */
                encodedString = [AIHTMLDecoder encodeHTML:(inContentMessage.chat.isSecure ? inContentMessage.message : [inContentMessage.message attributedStringByConvertingLinksToURLStrings])
                                                                                  headers:NO
                                                                                 fontTags:YES
                                                           includingColorTags:YES
                                                                        closeFontTags:YES
                                                                                styleTags:YES
                                           closeStyleTagsOnFontChange:YES
                                                                   encodeNonASCII:NO
                                                                         encodeSpaces:NO
                                                                           imagesPath:nil
                                                                attachmentsAsText:YES
                                                onlyIncludeOutgoingImages:NO
                                                                   simpleTagsOnly:YES
                                                                   bodyBackground:NO
                                                          allowJavascriptURLs:YES];
        }
        
        if (!didCommand && [inContentMessage.message.string hasPrefix:@"/"]) {
                // Try to send it to the server, if we don't know what it is; definitely don't display.
                [self sendRawCommand:[inContentMessage.message.string substringFromIndex:1]];
                return nil;
        } else {
                return encodedString;
        }
}

#pragma mark Libpurple
- (const char *)protocolPlugin
{
        return "prpl-irc";
}

- (const char *)purpleAccountName
{
        return [[NSString stringWithFormat:@"%@@%@", self.formattedUID, self.host] UTF8String];
}

- (NSString *)defaultUsername
{
        return @"Adium";
}

- (NSString *)defaultRealname
{
        return AILocalizedString(@"Adium User", nil);
}

- (void)configurePurpleAccount
{
        [super configurePurpleAccount];
        
        purple_account_set_username(self.purpleAccount, self.purpleAccountName);
        
        // Encoding
        NSString *encoding = [self preferenceForKey:KEY_IRC_ENCODING group:GROUP_ACCOUNT_STATUS] ?: @"UTF-8";
        purple_account_set_string(self.purpleAccount, "encoding", [encoding UTF8String]);
        
        if (![encoding isEqualToString:@"UTF-8"]) {
                purple_account_set_bool(self.purpleAccount, "autodetect_utf8", TRUE);
        }
        
        // Use SSL
        BOOL useSSL = [[self preferenceForKey:KEY_IRC_USE_SSL group:GROUP_ACCOUNT_STATUS] boolValue];
        purple_account_set_bool(self.purpleAccount, "ssl", useSSL);
        
        // Username (for connecting)
        NSString *username = [self preferenceForKey:KEY_IRC_USERNAME group:GROUP_ACCOUNT_STATUS] ?: self.defaultUsername;
        purple_account_set_string(self.purpleAccount, "username", [username UTF8String]);
        
        // Realname (for connecting)
        NSString *realname = [self preferenceForKey:KEY_IRC_REALNAME group:GROUP_ACCOUNT_STATUS] ?: self.defaultRealname;
        purple_account_set_string(self.purpleAccount, "realname", [realname UTF8String]);
}

/*!
 * @brief Our display name; either retrieve our current nickname, or return our stored one.
 */
- (NSString *)displayName
{
        // Try and get the purple display name, since it changes without telling us.
        if (account) {
                PurpleConnection        *purpleConnection = purple_account_get_connection(account);
                
                if (purpleConnection) {
                        return [NSString stringWithUTF8String:purple_connection_get_display_name(purpleConnection)];
                }
        }
        
        return self.formattedUID;
}


/*!
 * @brief Re-create the chat's join options.
 */
- (NSDictionary *)extractChatCreationDictionaryFromConversation:(PurpleConversation *)conv
{
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[NSString stringWithUTF8String:purple_conversation_get_name(conv)] forKey:@"channel"];
        const char *pass = purple_conversation_get_data(conv, "password");
        if (pass)
                [dict setObject: [NSString stringWithUTF8String:pass] forKey:@"password"];
        
        return dict;
}

/*!
 * @brief Should an autoreply be sent to this message?
 */
- (BOOL)shouldSendAutoreplyToMessage:(AIContentMessage *)message
{
        return NO;
}

#pragma mark Server contacts (NickServ, ChanServ)
/*!
 * @brief Sends a raw command to identify for the nickname
 */
- (void)identifyForName:(NSString *)name password:(NSString *)inPassword
{
        if ([self.host rangeOfString:@"quakenet" options:NSCaseInsensitiveSearch].location != NSNotFound) {
                [self sendRawCommand:[NSString stringWithFormat:@"PRIVMSG Q@CServe.quakenet.org :AUTH %@ %@", name, inPassword]];
        } else if ([self.host rangeOfString:@"undernet" options:NSCaseInsensitiveSearch].location != NSNotFound) {
                [self sendRawCommand:[NSString stringWithFormat:@"PRIVMSG X@channels.undernet.org :LOGIN %@ %@", name, inPassword]];
        } else if ([self.host rangeOfString:@"gamesurge" options:NSCaseInsensitiveSearch].location != NSNotFound) {
                [self sendRawCommand:[NSString stringWithFormat:@"PRIVMSG AuthServ@Services.GameSurge.net :AUTH %@ %@", name, inPassword]];
        } else {
                [self sendRawCommand:[NSString stringWithFormat:@"NICKSERV identify %@", inPassword]];  
        }
}

/*!
 * @brief Is this contact a server contact?
 */
BOOL contactUIDIsServerContact(NSString *contactUID)
{
        return (([contactUID caseInsensitiveCompare:@"nickserv"] == NSOrderedSame) ||
                        ([contactUID caseInsensitiveCompare:@"chanserv"] == NSOrderedSame) ||
                        ([contactUID rangeOfString:@"-connect" options:(NSBackwardsSearch | NSCaseInsensitiveSearch | NSAnchoredSearch)].location != NSNotFound));
}

/*!
 * @brief Can we send an offline message to this contact?
 *
 * We can only send offline messages to the server contacts, since such a message might cause us to connect
 */
- (BOOL)canSendOfflineMessageToContact:(AIListContact *)inContact
{
        return contactUIDIsServerContact(inContact.UID);
}


/*!
 * @brief Don't log server contacts (services) or FreeNode's stupidity.
 */
- (BOOL)shouldLogChat:(AIChat *)chat
{
        NSString *source = chat.listObject.UID;
        BOOL shouldLog = YES;
        
        if (source && (([source caseInsensitiveCompare:@"nickserv"] == NSOrderedSame) ||
                                   ([source caseInsensitiveCompare:@"chanserv"] == NSOrderedSame) ||
                                   ([source rangeOfString:@"-connect" options:(NSBackwardsSearch | NSCaseInsensitiveSearch | NSAnchoredSearch)].location != NSNotFound))) {
                shouldLog = NO; 
        }
        
        return (shouldLog && [super shouldLogChat:chat]);
}

#pragma mark Chat handling

/*!
 * @brief Allow the chat to close unless we're quitting.
 */
- (BOOL)closeChat:(AIChat*)chat
{
        if(adium.isQuitting)
                return NO;
        else
                return [super closeChat:chat];
}

/*!
 * @brief Do group chats support topics?
 */
- (BOOL)groupChatsSupportTopic
{
        return YES;
}

/*!
 * @brief Our flags in a chat
 */
- (AIGroupChatFlags)flagsInChat:(AIChat *)chat
{
        NSString *ourUID = [NSString stringWithUTF8String:purple_normalize(self.purpleAccount, [self.displayName UTF8String])];
        
        // XXX Once we don't create a fake contact for ourself, we should do this the right way.
        return [chat flagsForContact:[self contactWithUID:ourUID]];
}

#pragma mark Action Menu
-(NSMenu*)actionMenuForChat:(AIChat*)chat
{
        NSMenu *menu;
        
        NSArray *listObjects = chat.chatContainer.messageViewController.selectedListObjects;
        AIListObject *listObject = nil;
        
        if (listObjects.count) {
                listObject = [listObjects objectAtIndex:0];
        }
        
        menu = [adium.menuController contextualMenuWithLocations:[NSArray arrayWithObjects:
                                                                                                                          [NSNumber numberWithInteger:Context_Contact_GroupChat_ParticipantAction],             
                                                                                                                          [NSNumber numberWithInteger:Context_Contact_Manage],
                                                                                                                          nil]
                                                                                           forListObject:listObject
                                                                                                          inChat:chat];
        
        
        
        [menu addItem:[NSMenuItem separatorItem]];
        
        [menu addItemWithTitle:AILocalizedString(@"Op", nil)
                                        target:self
                                        action:@selector(op)
                         keyEquivalent:@""
                                           tag:AIRequiresOp];
        
        [menu addItemWithTitle:AILocalizedString(@"Deop", nil)
                                        target:self
                                        action:@selector(deop)
                         keyEquivalent:@""
                                           tag:AIRequiresOp];
        
        [menu addItemWithTitle:AILocalizedString(@"Voice", nil)
                                        target:self
                                        action:@selector(voice)
                         keyEquivalent:@""
                                           tag:AIRequiresOp];
        
        [menu addItemWithTitle:AILocalizedString(@"Devoice", nil)
                                        target:self
                                        action:@selector(devoice)
                         keyEquivalent:@""
                                           tag:AIRequiresOp];
        
        [menu addItem:[NSMenuItem separatorItem]];
        
        [menu addItemWithTitle:AILocalizedString(@"Kick", nil)
                                        target:self
                                        action:@selector(kick)
                         keyEquivalent:@""
                                           tag:AIRequiresHalfop];
        
        [menu addItemWithTitle:AILocalizedString(@"Ban", nil)
                                        target:self
                                        action:@selector(ban)
                         keyEquivalent:@""
                                           tag:AIRequiresHalfop];
        
        [menu addItemWithTitle:AILocalizedString(@"Bankick", nil)
                                        target:self
                                        action:@selector(bankick)
                         keyEquivalent:@""
                                           tag:AIRequiresHalfop];
        
        return menu;
}

- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
        AIOperationRequirement req = menuItem.tag;
        AIChat *chat = adium.interfaceController.activeChat;
        BOOL anySelected = chat.chatContainer.messageViewController.selectedListObjects.count > 0;
        
        AIGroupChatFlags flags = [self flagsInChat:chat];
        
        switch (req) {
                case AIRequiresHalfop:
                        return (anySelected && ((flags & AIGroupChatOp) == AIGroupChatOp || (flags & AIGroupChatHalfOp) == AIGroupChatHalfOp));
                        break;
                        
                case AIRequiresOp:
                        return (anySelected && ((flags & AIGroupChatOp) == AIGroupChatOp));
                        break;
                        
                case AIRequiresNoLevel:
                        return anySelected;
                        break;
                        
                default:
                        return YES;
                        break;
        }
}

#pragma mark Action Menu's Actions
- (void)apply:(BOOL)apply operation:(NSString *)operation flag:(NSString *)flag
{
        AIChat *chat = adium.interfaceController.activeChat;
        NSArray *objects = chat.chatContainer.messageViewController.selectedListObjects;
        
        NSMutableString *names = [NSMutableString string];
        
        for (NSUInteger x = 0; x < objects.count; x++) {
                AIListObject *listObject = [objects objectAtIndex:x];
                
                if ([flag isEqualToString:@"b"] && [listObject valueForProperty:@"User Host"]) {
                        [names appendString:[NSString stringWithFormat:@"*!%@", [listObject valueForProperty:@"User Host"]]];
                } else {
                        [names appendString:listObject.UID];
                }
                
                [names appendString:@" "];
                
                if ((x+1) % 4 == 0 || x+1 == objects.count) {
                        if ([operation isEqualToString:@"MODE"]) {
                                [self sendRawCommand:[NSString stringWithFormat:@"MODE %@ %@%@ %@",
                                                                          chat.name,
                                                                          (apply ? @"+" : @"-"),
                                                                          [@"" stringByPaddingToLength:(x + 1) % 4 ?: 4
                                                                                                                withString:flag 
                                                                                                   startingAtIndex:0],
                                                                          names]];
                        } else if ([operation isEqualToString:@"KICK"]) {
                                [self sendRawCommand:[NSString stringWithFormat:@"KICK %@ %@",
                                                                          chat.name,
                                                                          [names stringByReplacingOccurrencesOfString:@" " withString:@","]]];
                        }
                        
                        [names setString:@""];
                }
        }
}

- (void)op
{
        [self apply:YES operation:@"MODE" flag:@"o"];
}

- (void)deop
{
        [self apply:NO operation:@"MODE" flag:@"o"];
}

- (void)voice
{
        [self apply:YES operation:@"MODE" flag:@"v"];
}

- (void)devoice
{
        [self apply:NO operation:@"MODE" flag:@"v"];
}

- (void)kick
{
        [self apply:NO operation:@"KICK" flag:nil];
}

- (void)ban
{
        [self apply:YES operation:@"MODE" flag:@"b"];
}

- (void)bankick
{
        [self ban];
        [self kick];
}

#pragma mark File transfer
- (BOOL)canSendFolders
{
        return NO;
}

- (void)beginSendOfFileTransfer:(ESFileTransfer *)fileTransfer
{
        [super _beginSendOfFileTransfer:fileTransfer];
}

- (void)acceptFileTransferRequest:(ESFileTransfer *)fileTransfer
{
    [super acceptFileTransferRequest:fileTransfer];    
}

- (void)rejectFileReceiveRequest:(ESFileTransfer *)fileTransfer
{
    [super rejectFileReceiveRequest:fileTransfer];    
}

- (void)cancelFileTransfer:(ESFileTransfer *)fileTransfer
{
        [super cancelFileTransfer:fileTransfer];
}

@end