forked from luciuskwok/HelTweetica
/
TimelineHTMLController.m
718 lines (577 loc) · 25.6 KB
/
TimelineHTMLController.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
//
// TimelineHTMLController.m
// HelTweetica
//
// Created by Lucius Kwok on 5/22/10.
/*
Copyright (c) 2010, Felt Tip Inc. 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.
3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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 "TimelineHTMLController.h"
#import "TwitterFavoriteAction.h"
#import "TwitterDeleteAction.h"
#import "TwitterLoadDirectMessagesAction.h"
#import "TwitterLoadTimelineAction.h"
#import "TwitterLoadListsAction.h"
#import "TwitterLoadSavedSearchesAction.h"
#import "TwitterDirectMessageConversation.h"
// Constants
#ifdef TARGET_PROJECT_MAC
const int kDefaultMaxTweetsShown = 400;
#else
const int kDefaultMaxTweetsShown = 160;
#endif
const int kRewriteHTMLTimerInterval = 60;
static NSString *kTimelineIdentifier = @"Timeline";
static NSString *kMentionsIdentifier = @"Mentions";
static NSString *kDirectMessagesIdentifier = @"Direct";
static NSString *kFavoritesIdentifier = @"Favorites";
@implementation TimelineHTMLController
@synthesize webView, twitter, account, timeline, messages;
@synthesize maxTweetsShown, webViewHasValidHTML, isLoading, noInternetConnection, suppressNetworkErrorAlerts;
@synthesize customPageTitle, customTabName;
@synthesize useRewriteHTMLTimer;
@synthesize delegate;
- (id)init {
self = [super init];
if (self) {
// Load the HTML templates.
directMessageRowTemplate = [[self loadHTMLTemplate:@"dm-row-template"] retain];
directMessageRowSectionOpenTemplate = [[self loadHTMLTemplate:@"dm-row-section-open"] retain];
directMessageRowSectionCloseHTML = [[self loadHTMLTemplate:@"dm-row-section-close"] retain];
tweetRowTemplate = [[self loadHTMLTemplate:@"tweet-row-template"] retain];
tweetGapRowTemplate = [[self loadHTMLTemplate:@"load-gap-template"] retain];
// Loading template
loadingHTML = [@"<div class='status'><img class='status_spinner_image' src='spinner.gif'> Loading...</div>" retain];
// Misc
isLoading = YES;
maxTweetsShown = kDefaultMaxTweetsShown;
// Timeline update notifications
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(timelineDidFinishLoading:) name:TwitterTimelineDidFinishLoadingNotification object:nil];
[nc addObserver:self selector:@selector(showTwitterError:) name:TwitterErrorNotification object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[webView release];
[twitter release];
[account release];
[timeline release];
[messages release];
[directMessageRowTemplate release];
[directMessageRowSectionOpenTemplate release];
[directMessageRowSectionCloseHTML release];
[tweetRowTemplate release];
[tweetGapRowTemplate release];
[loadingHTML release];
[customPageTitle release];
[customTabName release];
[rewriteHTMLTimer invalidate];
rewriteHTMLTimer = nil;
[super dealloc];
}
#pragma mark Timeline selection
- (void)updateForNewTimeline {
// Call this after selecting a different timeline.
suppressNetworkErrorAlerts = NO;
self.messages = [timeline messagesWithLimit:maxTweetsShown];
[self rewriteTweetArea];
// Notify delegate that a different timeline was selected.
if ([delegate respondsToSelector:@selector(didSelectTimeline:)])
[delegate didSelectTimeline:timeline];
}
- (void)selectHomeTimeline {
self.customTabName = kTimelineIdentifier;
self.timeline = account.homeTimeline;
[self updateForNewTimeline];
}
- (void)selectMentionsTimeline {
self.customTabName = kMentionsIdentifier;
self.timeline = account.mentions;
[self updateForNewTimeline];
}
- (void)selectDirectMessageTimeline {
self.customTabName = kDirectMessagesIdentifier;
self.timeline = account.directMessages;
[self updateForNewTimeline];
}
- (void)selectFavoritesTimeline {
self.customTabName = kFavoritesIdentifier;
self.timeline = account.favorites;
[self updateForNewTimeline];
[self refresh];
}
#pragma mark Twitter status line
- (void)showTwitterStatusWithString:(NSString *)string {
[webView setDocumentElement:@"twitter_status" innerHTML:string];
[webView setDocumentElement:@"twitter_status" visibility:YES];
//[webView setDocumentElement:@"twitter_status" height:24];
}
- (void)showLoadingStatus {
[self showTwitterStatusWithString:@"<img src='fave-spinner.gif'> Loading..."];
}
- (void)hideTwitterStatus {
[webView setDocumentElement:@"twitter_status" visibility:NO];
//[webView setDocumentElement:@"twitter_status" innerHTML:@""];
//[webView setDocumentElement:@"twitter_status" height:0];
}
#pragma mark Loading
- (void)refresh {
isLoading = YES;
[self showLoadingStatus];
//[self setLoadingSpinnerVisibility:YES];
if (timeline == account.homeTimeline || timeline == account.mentions || timeline == account.directMessages) {
self.messages = [timeline messagesWithLimit: maxTweetsShown];
[self rewriteTweetArea];
[twitter refreshNow];
} else {
if (timeline == account.favorites) {
// Reload messages ignoring what's already local in case there are gaps in our version of the timeline.
[timeline reloadAll];
} else {
[timeline reloadNewer];
}
}
[webView scrollToTop];
}
- (void)loadTimeline:(TwitterTimeline*)aTimeline {
self.timeline = aTimeline;
self.messages = [timeline messagesWithLimit:maxTweetsShown];
if (noInternetConnection == NO) {
isLoading = YES;
[self showLoadingStatus];
if (timeline == account.favorites) {
// Reload messages ignoring what's already local in case there are gaps in our version of the timeline.
[timeline reloadAll];
} else {
[timeline reloadNewer];
}
}
}
- (void)loadOlderWithMaxIdentifier:(NSNumber*)maxIdentifier {
// Replace link to load the gap or load older with a Loading spinner
if (maxIdentifier) {
// Load gap
NSString *element = [NSString stringWithFormat:@"gap-%@", [maxIdentifier stringValue]];
[self.webView setDocumentElement:element innerHTML:loadingHTML];
} else {
[self.webView setDocumentElement:@"footer" innerHTML:loadingHTML];
}
isLoading = YES;
[timeline loadOlderWithMaxIdentifier:maxIdentifier];
}
- (BOOL)array:(NSArray *)arrayA containsObjectsNotInArray:(NSArray *)arrayB {
for (id item in arrayA) {
if ([arrayB containsObject:item] == NO)
return YES;
}
return NO;
}
- (void)loadList:(TwitterList*)list {
TwitterTimeline *listTimeline = list.statuses;
// Style the page title
NSString *pageTitle = list.fullName;
NSArray *nameParts = [list.fullName componentsSeparatedByString:@"/"];
if (nameParts.count == 2) {
pageTitle = [NSString stringWithFormat:@"%@/<b>%@</b>", [nameParts objectAtIndex:0], [nameParts objectAtIndex:1]];
}
self.customPageTitle = pageTitle;
self.customTabName = NSLocalizedString (@"List", @"tab");
// Create Twitter action to load list statuses into the timeline.
NSString *method = [NSString stringWithFormat:@"%@/lists/%@/statuses", list.username, list.identifier];
listTimeline.loadAction = [[[TwitterLoadTimelineAction alloc] initWithTwitterMethod:method] autorelease];
listTimeline.loadAction.countKey = @"per_page";
suppressNetworkErrorAlerts = NO;
// Set the Twitter cache connection.
[list setTwitter:twitter account:account];
// Load timeline
[self loadTimeline: listTimeline];
// Rewrite and scroll web view
[self rewriteTweetArea];
[self.webView scrollToTop];
// Notify delegate that a different timeline was selected.
if ([delegate respondsToSelector:@selector(didSelectTimeline:)])
[delegate didSelectTimeline:timeline];
}
#pragma mark Favorite status update
- (void) fave: (NSNumber*) messageIdentifier {
noInternetConnection = NO;
TwitterStatusUpdate *message = [twitter statusUpdateWithIdentifier: messageIdentifier];
if (message == nil) {
NSLog (@"Cannot find the message to fave (or unfave). id == %@", messageIdentifier);
return;
}
BOOL isFave = [account messageIsFavorite:messageIdentifier];
TwitterFavoriteAction *action = [[[TwitterFavoriteAction alloc] initWithMessage:message destroy:isFave] autorelease];
action.completionTarget= self;
action.completionAction = @selector(didFave:);
[twitter startTwitterAction:action withAccount:account];
// Change the star to a spinner.
NSString *element = [NSString stringWithFormat:@"star-%@", [message.identifier stringValue]];
NSString *html = @"<img src='fave-spinner.gif'>";
[self.webView setDocumentElement:element innerHTML:html];
}
- (void)didFave:(TwitterFavoriteAction *)action {
TwitterStatusUpdate *message = [action message];
if (action.success == NO) return;
BOOL isFave = !action.destroy;
// Change the display of the star next to tweet in root view
NSString *element = [NSString stringWithFormat:@"star-%@", [message.identifier stringValue]];
NSString *html = isFave ? @"<img src='action-star-on.png'>" : @"<img src='action-star.png'>";
[self.webView setDocumentElement:element innerHTML:html];
// Remove from favorites timeline
if (isFave) {
[account addFavorites:[NSArray arrayWithObject:message]];
} else {
[account removeFavorite:message.identifier];
}
}
#pragma mark Delete status update
- (void)deleteStatusUpdate:(NSNumber *)identifier {
// Change the trash can to a spinner.
NSString *element = [NSString stringWithFormat:@"trash-%@", [identifier stringValue]];
NSString *html = @"<img src='fave-spinner.gif'>";
[self.webView setDocumentElement:element innerHTML:html];
TwitterDeleteAction *action = [[[TwitterDeleteAction alloc] initWithMessageIdentifier:identifier] autorelease];
action.completionTarget= self;
action.completionAction = @selector(didDeleteStatusUpdate:);
[twitter startTwitterAction:action withAccount:account];
}
- (void)didDeleteStatusUpdate:(TwitterDeleteAction *)action {
[twitter deleteStatusUpdate:action.identifier];
self.messages = [timeline messagesWithLimit:maxTweetsShown];
[self rewriteTweetArea];
}
#pragma mark Web view updating
- (void)loadWebView {
// Load template and replace special tags with data
NSString *template = [self webPageTemplate];
if (template == nil) return;
NSMutableString *html = [NSMutableString stringWithString:template];
// Use the timeline HTML controller to create the HTML content.
NSString *tweetAreaHTML = @"<div class='login'><a href='action:login'>Please log in.</a></div>";
NSString *currentAccountHTML = @"";
NSString *tabAreaHTML = @"";
if (account.screenName != nil) {
tweetAreaHTML = [self tweetAreaHTML];
currentAccountHTML = [self currentAccountHTML];
tabAreaHTML = [self tabAreaHTML];
}
// Replace custom tags with HTML
[html replaceOccurrencesOfString:@"<tweetAreaHTML/>" withString:tweetAreaHTML options:0 range:NSMakeRange(0, html.length)];
[html replaceOccurrencesOfString:@"<currentAccountHTML/>" withString:currentAccountHTML options:0 range:NSMakeRange(0, html.length)];
[html replaceOccurrencesOfString:@"<tabAreaHTML/>" withString:tabAreaHTML options:0 range:NSMakeRange(0, html.length)];
[self.webView loadHTMLString:html];
if (useRewriteHTMLTimer) {
[self scheduleRewriteHTMLTimer];
}
}
- (void)setLoadingSpinnerVisibility:(BOOL)isVisible {
if (webViewHasValidHTML)
[self.webView setDocumentElement:@"spinner" visibility:isVisible];
}
- (void)rewriteTweetArea {
if (webViewHasValidHTML) {
// Replace tab area HTML with current tab
if (customTabName != nil) {
[self.webView setDocumentElement:@"tab_area" innerHTML:[self tabAreaHTML]];
}
// Replace tweet area HTML with new tweets
NSString *result = [self.webView setDocumentElement:@"tweet_area" innerHTML:[self tweetAreaHTML]];
if ([result length] == 0) { // If the result of the JavaScript call is empty, there was an error.
NSLog (@"JavaScript error in refreshing tweet area. Reloading entire web view.");
[self loadWebView];
}
} else {
// This isn't really a bug or exception to call this method when the web view isn't ready, so it isn't logged.
//NSLog (@"rewriteTweetArea called when webViewHasValidHTML == NO.");
}
if (useRewriteHTMLTimer) {
[self scheduleRewriteHTMLTimer];
}
}
- (void)scheduleRewriteHTMLTimer {
if (useRewriteHTMLTimer) {
[rewriteHTMLTimer invalidate];
rewriteHTMLTimer = [NSTimer scheduledTimerWithTimeInterval:kRewriteHTMLTimerInterval target:self selector:@selector(fireRewriteHTMLTimer:) userInfo:nil repeats:NO];
}
}
- (void)fireRewriteHTMLTimer:(NSTimer *)timer {
if (useRewriteHTMLTimer) {
[self rewriteTweetArea];
}
}
#pragma mark Web actions
- (BOOL)handleWebAction:(NSString*)action {
BOOL handled = YES;
NSNumber *messageIdentifier = [self number64WithString:[action lastPathComponent]];
// Select a timeline
if ([action isEqualToString:kTimelineIdentifier]) { // Home Timeline
self.customPageTitle = nil; // Reset the custom page title.
[self selectHomeTimeline];
} else if ([action isEqualToString:kMentionsIdentifier]) { // Mentions
self.customPageTitle = nil; // Reset the custom page title.
[self selectMentionsTimeline];
} else if ([action isEqualToString:kDirectMessagesIdentifier]) { // Mentions
self.customPageTitle = nil; // Reset the custom page title.
[self selectDirectMessageTimeline];
} else if ([action isEqualToString:kFavoritesIdentifier]) { // Favorites
self.customPageTitle = nil; // Reset the custom page title.
[self selectFavoritesTimeline];
}
// Other actions
else if ([action hasPrefix:@"fave"]) { // Add message to favorites or remove from favorites
[self fave:messageIdentifier];
} else if ([action hasPrefix:@"loadOlder"]) { // Load older
[self loadOlderWithMaxIdentifier:nil];
} else if ([action hasPrefix:@"loadGap"]) { // Load gap
[self loadOlderWithMaxIdentifier:messageIdentifier];
} else {
handled = NO;
}
return handled;
}
- (NSNumber*)number64WithString:(NSString*)string {
if (string == nil) return nil;
NSScanner *scanner = [NSScanner scannerWithString:string];
SInt64 identifierInt64;
if ([scanner scanLongLong: &identifierInt64])
return [NSNumber numberWithLongLong: identifierInt64];
return nil;
}
#pragma mark HTML
- (NSString *)htmlWithTemplate:(NSString *)template substitutions:(NSDictionary *)substitutions {
if (template == nil) return nil;
// Use scanner to replace curly-bracketed variables with values
NSScanner *scanner = [NSScanner scannerWithString:template];
NSMutableString *tweetRowHTML = [[[NSMutableString alloc] init] autorelease];
NSString *scannedString, *key, *value;
BOOL displayBlock = YES;
// Set scanner to include whitespace
[scanner setCharactersToBeSkipped:nil];
while ([scanner isAtEnd] == NO) {
// Scan characters up to opening of variable curly brace
if ([scanner scanUpToString:@"{" intoString:&scannedString] && displayBlock) {
[tweetRowHTML appendString:scannedString];
}
// Scan name of variable or block
if ([scanner scanUpToString:@"}" intoString:&scannedString]) {
if ([scannedString hasPrefix:@"{Block:"]) {
// Block
if ([scannedString length] > 7) {
key = [scannedString substringFromIndex:7];
value = [substitutions objectForKey:key];
displayBlock = (value != nil);
}
} else if ([scannedString hasPrefix:@"{/Block"]) {
// End Block
displayBlock = YES;
} else {
// Variable
if (displayBlock && [scannedString length] > 1) {
key = [scannedString substringFromIndex:1];
value = [substitutions objectForKey:key];
if (value)
[tweetRowHTML appendString:value];
}
}
}
// Scan past closing curly brace
[scanner scanString:@"}" intoString:nil];
}
return tweetRowHTML;
}
- (NSString *)htmlWithStatusUpdate:(TwitterStatusUpdate *)statusUpdate rowIndex:(int)rowIndex {
// Skip rows with invalid identifiers.
if ([statusUpdate.identifier longLongValue] < 1000) return @"";
BOOL lastRow = (rowIndex >= maxTweetsShown - 1 || rowIndex >= messages.count - 1);
NSMutableDictionary *substitutions = [NSMutableDictionary dictionary];
NSMutableString *gapRowHTML = nil;
// Append "Load gap" row if needed
BOOL gap = [timeline hasGapAfter:statusUpdate.identifier];
NSString *messageIdentifier = [statusUpdate.identifier stringValue];
if ((gap == YES) && (lastRow == NO)) {
gapRowHTML = [NSMutableString stringWithString:tweetGapRowTemplate];
[gapRowHTML replaceOccurrencesOfString:@"{gapIdentifier}" withString:messageIdentifier options:0 range:NSMakeRange(0, gapRowHTML.length)];
}
// Special handling for new-style retweets.
if ([statusUpdate.retweetedStatusIdentifier longLongValue] != 0) {
[substitutions setObject:@"<img src='retweet.png'>" forKey:@"retweetIcon"];
if (statusUpdate.userScreenName)
[substitutions setObject:statusUpdate.userScreenName forKey:@"retweetedBy"];
statusUpdate = [twitter statusUpdateWithIdentifier:statusUpdate.retweetedStatusIdentifier];
}
// Row style
NSString *rowStyle = [self styleForStatusUpdate:statusUpdate rowIndex:rowIndex];
if (rowStyle != nil)
[substitutions setObject:rowStyle forKey:@"tweetRowStyle"];
// Favorites
if ([account messageIsFavorite:statusUpdate.identifier])
[substitutions setObject:@"-on" forKey:@"faveImageSuffix"];
// Own tweets.
if ([statusUpdate.userIdentifier isEqualToNumber:account.identifier]) {
// Show delete action but hide reply, dm, and retweet buttons.
[substitutions setObject:@"YES" forKey:@"ownActions"];
} else {
// Always show action buttons on right side of page.
[substitutions setObject:@"YES" forKey:@"actions"];
}
// Add values from status update.
[substitutions addEntriesFromDictionary:[statusUpdate htmlSubstitutions]];
// Load template and apply substitutions.
NSString *html = [self htmlWithTemplate:tweetRowTemplate substitutions:substitutions];
if (gapRowHTML != nil)
html = [html stringByAppendingString:gapRowHTML];
return html;
}
- (NSString *)styleForStatusUpdate:(TwitterStatusUpdate *)statusUpdate rowIndex:(int)rowIndex {
NSString *style = nil;
// Mentions
NSRange found = [statusUpdate.text rangeOfString:[NSString stringWithFormat:@"@%@", account.screenName] options:NSCaseInsensitiveSearch];
if (found.location != NSNotFound)
style = @"mention_tweet_row";
// Own tweets
if ([statusUpdate.userIdentifier isEqualToNumber:account.identifier] || [statusUpdate.userScreenName isEqualToString:account.screenName])
style = @"self_tweet_row";
return style;
}
- (NSString *)htmlWithDirectMessageConversation:(TwitterDirectMessageConversation *)conversation rowIndex:(int)rowIndex {
// Each row in the messages array corresponds to one conversation with one user. Each conversation has a subarray of direct messages, sorted by date, newest first.
NSMutableString *html = [NSMutableString string];
// Open the row and substitute the user screenName and profileImageURL in the template.
NSMutableDictionary *substitutions = [NSMutableDictionary dictionary];
TwitterUser *user = [twitter userWithIdentifier:conversation.userIdentifier];
[substitutions setObject:user.screenName forKey:@"screenName"];
[substitutions setObject:user.profileImageURL forKey:@"profileImageURL"];
[html appendString:[self htmlWithTemplate:directMessageRowSectionOpenTemplate substitutions:substitutions]];
// Loop through each message
for (TwitterDirectMessage *message in conversation.messages) {
[html appendString:[self htmlWithTemplate:directMessageRowTemplate substitutions:[message htmlSubstitutions]]];
}
// Close the row.
[html appendString:directMessageRowSectionCloseHTML];
return html;
}
- (NSString *)loadHTMLTemplate:(NSString *)templateName {
// Load main template
NSError *error = nil;
NSString *filePath = [[NSBundle mainBundle] pathForResource:templateName ofType:@"html"];
NSString *html = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if (error != nil)
NSLog (@"Error loading %@.html: %@", templateName, [error localizedDescription]);
return html;
}
- (NSString *)webPageTemplate {
return [self loadHTMLTemplate:@"main-template"];
}
- (NSString *)currentAccountHTML {
return [NSString stringWithFormat:@"<a href='action:user/%@'>%@</a>", account.screenName, account.screenName];
}
- (NSString *)tabAreaHTML {
NSMutableString *html = [[[NSMutableString alloc] init] autorelease];
int selectedTab = 0;
NSString *tabName = self.customTabName;
if ([tabName isEqualToString: kTimelineIdentifier] || (tabName == nil)) {
selectedTab = 1;
} else if ([tabName isEqualToString: kMentionsIdentifier]) {
selectedTab = 2;
} else if ([tabName isEqualToString: kDirectMessagesIdentifier]) {
selectedTab = 3;
} else if ([tabName isEqualToString: kFavoritesIdentifier]) {
selectedTab = 4;
} else {
selectedTab = 5;
}
[html appendFormat:@"<div class='tab %@selected' onclick=\"location.href='action:Timeline';\">Timeline</div>", (selectedTab == 1)? @"" : @"de"];
[html appendFormat:@"<div class='tab %@selected' onclick=\"location.href='action:Mentions';\">Mentions</div>", (selectedTab == 2)? @"" : @"de"];
[html appendFormat:@"<div class='tab %@selected' onclick=\"location.href='action:Direct';\">Direct</div>", (selectedTab == 3)? @"" : @"de"];
[html appendFormat:@"<div class='tab %@selected' onclick=\"location.href='action:Favorites';\">Favorites</div>", (selectedTab == 4)? @"" : @"de"];
if (selectedTab == 5)
[html appendFormat:@"<div class='tab selected'>%@</div>", tabName];
return html;
}
- (NSString*) tweetAreaHTML {
NSMutableString *html = [[[NSMutableString alloc] init] autorelease];
// Page Title for Lists and Search
if (customPageTitle) {
// Put the title inside a regular tweet table row.
[html appendString:@"<div class='tweet_table'><div class='tweet_row'><div class='tweet_avatar'></div><div class='tweet_content'>"];
[html appendFormat:@"<div class='page_title'>%@</div>", customPageTitle];
[html appendString:@"</div></div></div>"];
}
[html appendString:@"<div class='tweet_table'> "];
// Rows of status updates or direct messages.
id rowItem;
for (int index=0; index<messages.count; index++) {
rowItem = [messages objectAtIndex:index];
if ([rowItem isKindOfClass:[TwitterStatusUpdate class]]) {
[html appendString:[self htmlWithStatusUpdate:rowItem rowIndex:index]];
} else if ([rowItem isKindOfClass:[TwitterDirectMessageConversation class]]) {
[html appendString:[self htmlWithDirectMessageConversation:rowItem rowIndex:index]];
}
}
[html appendString:@"</div> "]; // Close tweet_table
// Footer
[html appendString:@"<div id='footer'>"];
[html appendString:[self tweetAreaFooterHTML]];
[html appendString:@"</div> "]; // Close footer
return html;
}
- (NSString*) tweetAreaFooterHTML {
NSString *result = @"";
if (noInternetConnection) {
result = @"<div class='status'>No Internet connection.</div>";
} else if (account.xAuthToken == nil) {
result = @"<div class='status'><a href='action:login'>Please log in.</a></div>";
} else if (isLoading) { // (actions.count > 0 || !webViewHasValidHTML)
result = loadingHTML;
} else if (messages.count == 0) {
result = @"<div class='status'>No messages.</div>";
} else if (timeline.noOlderMessages) {
result = @"";
} else if (messages.count < maxTweetsShown) {
// Action to Load older messages
result = @"<div class='load_older'><a href='action:loadOlder'>Load older messages</a></div> ";
}
return result;
}
- (void) replaceBlock:(NSString*)blockName display:(BOOL)display inTemplate:(NSMutableString*)template {
// Find beginning and end of block tags
NSString *openTag = [NSString stringWithFormat:@"{Block:%@}", blockName];
NSString *closeTag = [NSString stringWithFormat:@"{/Block:%@}", blockName];
if (display) {
// Just remove the tags if we're displaying the block
[template replaceOccurrencesOfString:openTag withString:@"" options:0 range:NSMakeRange(0, template.length)];
[template replaceOccurrencesOfString:closeTag withString:@"" options:0 range:NSMakeRange(0, template.length)];
} else {
// Remove the entire block if we're not displaying it
NSRange openRange = [template rangeOfString:openTag];
NSRange closeRange = [template rangeOfString:closeTag];
if (openRange.location == NSNotFound || closeRange.location == NSNotFound) return; // Can't find both tags
NSRange replaceRange = NSMakeRange(openRange.location, closeRange.location + closeRange.length - openRange.location);
[template replaceCharactersInRange:replaceRange withString:@""];
}
}
#pragma mark Notifications
- (void)timelineDidFinishLoading:(NSNotification *)notification {
TwitterTimeline *aTimeline = [notification object];
if (aTimeline == self.timeline) {
isLoading = NO;
[self hideTwitterStatus];
self.messages = [timeline messagesWithLimit: maxTweetsShown];
[self rewriteTweetArea];
}
}
- (void)showTwitterError:(NSNotification *)notification {
NSError *error = [notification object];
NSString *message = [error localizedDescription];
//int statusCode = [error code];
[self showTwitterStatusWithString:message];
}
@end