Browse Source

Own Thread for API access in MainMenu. Pref Window still networking in main thread.

Thomas Buck 11 years ago
parent
commit
892e1b0a96

+ 2
- 2
RedditBar.xcodeproj/project.pbxproj View File

37
 /* End PBXContainerItemProxy section */
37
 /* End PBXContainerItemProxy section */
38
 
38
 
39
 /* Begin PBXFileReference section */
39
 /* Begin PBXFileReference section */
40
-		E90E74B3184FAA0F00F38929 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = "<group>"; };
40
+		E90E74B3184FAA0F00F38929 /* en */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = "<group>"; };
41
 		E90E74B6184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/MainMenu.strings; sourceTree = "<group>"; };
41
 		E90E74B6184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/MainMenu.strings; sourceTree = "<group>"; };
42
 		E90E74B7184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/Prefs.strings; sourceTree = "<group>"; };
42
 		E90E74B7184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/Prefs.strings; sourceTree = "<group>"; };
43
-		E90E74B8184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/Localizable.strings; sourceTree = "<group>"; };
43
+		E90E74B8184FAADE00F38929 /* de */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/Localizable.strings; sourceTree = "<group>"; };
44
 		E90E74B9184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/InfoPlist.strings; sourceTree = "<group>"; };
44
 		E90E74B9184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/InfoPlist.strings; sourceTree = "<group>"; };
45
 		E90E74BA184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = de; path = de.lproj/Credits.rtf; sourceTree = "<group>"; };
45
 		E90E74BA184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = de; path = de.lproj/Credits.rtf; sourceTree = "<group>"; };
46
 		E90E74BB184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/InfoPlist.strings; sourceTree = "<group>"; };
46
 		E90E74BB184FAADE00F38929 /* de */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = de; path = de.lproj/InfoPlist.strings; sourceTree = "<group>"; };

+ 6
- 0
RedditBar/AppDelegate.h View File

30
 -(IBAction)showAbout:(id)sender;
30
 -(IBAction)showAbout:(id)sender;
31
 -(IBAction)linkToOpen:(id)sender;
31
 -(IBAction)linkToOpen:(id)sender;
32
 
32
 
33
+-(void)reloadListWithOptions;
34
+-(void)reloadListIsAuthenticatedCallback;
35
+-(void)reloadListNotAuthenticatedCallback;
36
+-(void)reloadListHasSubredditsCallback:(NSArray *)items;
37
+-(void)reloadListHasFrontpageCallback:(NSArray *)items;
38
+
33
 -(void)prefReturnName:(NSString *)name Modhash:(NSString *)modhash subscriptions:(Boolean)subscriptions subreddits:(NSString *)subreddits length:(NSInteger)length;
39
 -(void)prefReturnName:(NSString *)name Modhash:(NSString *)modhash subscriptions:(Boolean)subscriptions subreddits:(NSString *)subreddits length:(NSInteger)length;
34
 
40
 
35
 @end
41
 @end

+ 41
- 35
RedditBar/AppDelegate.m View File

57
     [currentState setLength:[store integerForKey:@"length"]];
57
     [currentState setLength:[store integerForKey:@"length"]];
58
 }
58
 }
59
 
59
 
60
--(void)reloadListWithOptions {
61
-    if ([currentState.modhash isEqualToString:@""]) {
62
-        [firstMenuItem setTitle:NSLocalizedString(@"Not logged in!", @"Statusitem when no modhash is stored")];
60
+-(void)reloadListNotAuthenticatedCallback {
61
+    [firstMenuItem setTitle:NSLocalizedString(@"Login Error!", @"Statusitem when API is not authenticated")];
62
+    [self clearMenuItems];
63
+    [firstMenuItem setHidden:NO];
64
+}
65
+
66
+-(void)reloadListHasFrontpageCallback:(NSArray *)items {
67
+    if (items == nil) {
68
+        [firstMenuItem setTitle:NSLocalizedString(@"Error reading Frontpage!", @"Status api Read error")];
63
         [self clearMenuItems];
69
         [self clearMenuItems];
64
         [firstMenuItem setHidden:NO];
70
         [firstMenuItem setHidden:NO];
65
-        [self showPreferences:nil];
66
         return;
71
         return;
67
     }
72
     }
68
-    api = [[Reddit alloc] initWithUsername:currentState.username Modhash:currentState.modhash];
69
-    NSString *tmp = @"";
70
-    if (![api isAuthenticatedNewModhash:&tmp]) {
71
-        [firstMenuItem setTitle:NSLocalizedString(@"Login Error!", @"Statusitem when API is not authenticated")];
73
+    redditItems = items;
74
+    [self clearMenuItems];
75
+    [firstMenuItem setHidden:YES];
76
+    [self putItemArrayInMenu:redditItems];
77
+}
78
+
79
+-(void)reloadListHasSubredditsCallback:(NSArray *)items {
80
+    if (items == nil) {
81
+        [firstMenuItem setTitle:NSLocalizedString(@"Error reading Subreddits!", @"Status api read error")];
72
         [self clearMenuItems];
82
         [self clearMenuItems];
73
         [firstMenuItem setHidden:NO];
83
         [firstMenuItem setHidden:NO];
74
         return;
84
         return;
75
     }
85
     }
76
-    
77
-    // Reddit gives out new modhashes all the time??
78
-    //if (![tmp isEqualToString:@""]) {
79
-    //    NSLog(@"Modhash has changed!\n");
80
-    //    currentState.modhash = tmp; // We got a new modhash from reddit
81
-    //    [self savePreferences];
82
-    //}
83
-    
84
-    if (currentState.useSubscriptions) {
85
-        NSArray *items = [api readFrontpageLength:currentState.length];
86
-        if (items == nil) {
87
-            [firstMenuItem setTitle:NSLocalizedString(@"Error reading Frontpage!", @"Status api Read error")];
88
-            [self clearMenuItems];
89
-            [firstMenuItem setHidden:NO];
90
-            return;
91
-        }
92
-        redditItems = items;
93
-    } else {
94
-        NSArray *items = [api readSubreddits:currentState.subreddits Length:currentState.length];
95
-        if (items == nil) {
96
-            [firstMenuItem setTitle:NSLocalizedString(@"Error reading Subreddits!", @"Status api read error")];
97
-            [self clearMenuItems];
98
-            [firstMenuItem setHidden:NO];
99
-            return;
100
-        }
101
-        redditItems = items;
102
-    }
86
+    redditItems = items;
103
     [self clearMenuItems];
87
     [self clearMenuItems];
104
     [firstMenuItem setHidden:YES];
88
     [firstMenuItem setHidden:YES];
105
     [self putItemArrayInMenu:redditItems];
89
     [self putItemArrayInMenu:redditItems];
106
 }
90
 }
107
 
91
 
92
+-(void)reloadListIsAuthenticatedCallback {
93
+    if (currentState.useSubscriptions) {
94
+        [NSThread detachNewThreadSelector:@selector(readFrontpage:) toTarget:api withObject:self];
95
+    } else {
96
+        [api setSubreddits:currentState.subreddits];
97
+        [NSThread detachNewThreadSelector:@selector(readSubreddits:) toTarget:api withObject:self];
98
+    }
99
+}
100
+
101
+-(void)reloadListWithOptions {
102
+    if ([currentState.modhash isEqualToString:@""]) {
103
+        [firstMenuItem setTitle:NSLocalizedString(@"Not logged in!", @"Statusitem when no modhash is stored")];
104
+        [self clearMenuItems];
105
+        [firstMenuItem setHidden:NO];
106
+        [self showPreferences:nil];
107
+        return;
108
+    }
109
+    
110
+    api = [[Reddit alloc] initWithUsername:currentState.username Modhash:currentState.modhash Length:currentState.length];
111
+    [NSThread detachNewThreadSelector:@selector(isAuthenticatedNewModhash:) toTarget:api withObject:self];
112
+}
113
+
108
 -(IBAction)linkToOpen:(id)sender {
114
 -(IBAction)linkToOpen:(id)sender {
109
     NSString *title = [(NSMenuItem *)sender title];
115
     NSString *title = [(NSMenuItem *)sender title];
110
     if ([title isEqualToString:NSLocalizedString(@"Link...", nil)]) {
116
     if ([title isEqualToString:NSLocalizedString(@"Link...", nil)]) {

+ 10
- 4
RedditBar/Reddit.h View File

14
 @property (atomic, retain) NSString *username;
14
 @property (atomic, retain) NSString *username;
15
 @property (atomic, retain) NSString *modhash;
15
 @property (atomic, retain) NSString *modhash;
16
 @property (atomic, retain) NSString *password;
16
 @property (atomic, retain) NSString *password;
17
+@property (atomic) NSInteger length;
18
+@property (atomic, retain) NSArray *subreddits;
17
 
19
 
20
+// Used by Pref Window, unthreaded
18
 -(id)initWithUsername:(NSString *)name Password:(NSString *)pass;
21
 -(id)initWithUsername:(NSString *)name Password:(NSString *)pass;
19
 -(NSString *)queryModhash;
22
 -(NSString *)queryModhash;
20
 
23
 
21
--(id)initWithUsername:(NSString *)name Modhash:(NSString *)hash;
22
--(BOOL)isAuthenticatedNewModhash:(NSString **)newModHash;
24
+// Used by MainMenu
25
+-(id)initWithUsername:(NSString *)name Modhash:(NSString *)hash Length:(NSInteger)leng;
23
 
26
 
24
--(NSArray *)readFrontpageLength:(NSInteger)length;
25
--(NSArray *)readSubreddits:(NSArray *)source Length:(NSInteger)length;
27
+// Use Threaded!
28
+-(void)isAuthenticatedNewModhash:(id)parent;
29
+-(void)readFrontpage:(id)parent;
30
+-(void)readSubreddits:(id)parent;
26
 
31
 
32
+// Internal
27
 -(NSData *)queryAPI:(NSString *)api withData:(NSString *)string andResponse:(NSHTTPURLResponse **)res;
33
 -(NSData *)queryAPI:(NSString *)api withData:(NSString *)string andResponse:(NSHTTPURLResponse **)res;
28
 -(NSString *)urlencode:(NSString *)string;
34
 -(NSString *)urlencode:(NSString *)string;
29
 
35
 

+ 53
- 37
RedditBar/Reddit.m View File

7
 //
7
 //
8
 
8
 
9
 #import "Reddit.h"
9
 #import "Reddit.h"
10
+#import "AppDelegate.h"
10
 
11
 
11
 @implementation Reddit
12
 @implementation Reddit
12
 
13
 
14
 NSString *author = @"xythobuz";
15
 NSString *author = @"xythobuz";
15
 NSString *appName = @"RedditBar";
16
 NSString *appName = @"RedditBar";
16
 
17
 
17
-@synthesize username, modhash, password;
18
+NSInteger maxTitleLength = 50;
19
+NSString *replaceTextForTitle = @"...";
18
 
20
 
19
--(id)initWithUsername:(NSString *)name Modhash:(NSString *)hash {
21
+@synthesize username, modhash, password, length, subreddits;
22
+
23
+-(id)initWithUsername:(NSString *)name Modhash:(NSString *)hash Length:(NSInteger)leng {
20
     self = [super init];
24
     self = [super init];
21
     if (self) {
25
     if (self) {
22
         username = name;
26
         username = name;
23
         modhash = hash;
27
         modhash = hash;
24
         password = nil;
28
         password = nil;
29
+        length = leng;
25
     }
30
     }
26
     return self;
31
     return self;
27
 }
32
 }
36
     return self;
41
     return self;
37
 }
42
 }
38
 
43
 
39
--(BOOL)isAuthenticatedNewModhash:(NSString **)newModHash {
40
-    NSHTTPURLResponse *response;
41
-    NSData *data = [self queryAPI:@"api/me.json" withResponse:&response];
42
-    if ((data != nil) && ([response statusCode] == 200)) {
43
-        NSError *error;
44
-        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
45
-        NSDictionary *data = [json valueForKey:@"data"];
46
-        if (data == nil)
47
-            return FALSE;
48
-        NSString *newHash = [data valueForKey:@"modhash"];
49
-        if ((newHash == nil) || ([newHash isEqualToString:@""]))
50
-            return FALSE;
51
-        if (![newHash isEqualToString:modhash]) {
52
-            modhash = newHash;
53
-            *newModHash = newHash;
54
-        }
55
-        return TRUE;
56
-        
57
-    }
58
-    return FALSE;
59
-}
60
-
61
 -(NSString *)queryModhash {
44
 -(NSString *)queryModhash {
62
     NSMutableString *stringData = [NSMutableString stringWithString:@"api_type=json"];
45
     NSMutableString *stringData = [NSMutableString stringWithString:@"api_type=json"];
63
     [stringData appendFormat:@"&user=%@", [self urlencode: username]];
46
     [stringData appendFormat:@"&user=%@", [self urlencode: username]];
92
     }
75
     }
93
 }
76
 }
94
 
77
 
95
--(NSArray *)readFrontpageLength:(NSInteger)length {
96
-    NSHTTPURLResponse *response;
97
-    NSString *url = [NSString stringWithFormat:@"hot.json?limit=%ld", (long)length];
98
-    NSData *data = [self queryAPI:url withResponse:&response];
99
-    if ((data == nil) || ([response statusCode] != 200)) {
100
-        return nil;
101
-    }
78
+-(NSArray *)convertJSONToItemArray:(NSData *)data {
102
     NSError *error;
79
     NSError *error;
103
     NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
80
     NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
104
     NSDictionary *dat = [json valueForKey:@"data"];
81
     NSDictionary *dat = [json valueForKey:@"data"];
120
         if (!isSelf) {
97
         if (!isSelf) {
121
             comments = [NSString stringWithFormat:@"http://www.reddit.com%@", [current valueForKey:@"permalink"]];
98
             comments = [NSString stringWithFormat:@"http://www.reddit.com%@", [current valueForKey:@"permalink"]];
122
         }
99
         }
100
+        if ([name length] > maxTitleLength) {
101
+            name = [NSString stringWithFormat:@"%@%@", [name substringToIndex:(maxTitleLength - [replaceTextForTitle length])], replaceTextForTitle];
102
+        }
123
         RedditItem *r = [RedditItem itemWithName:name Link:link Comments:comments Self:isSelf];
103
         RedditItem *r = [RedditItem itemWithName:name Link:link Comments:comments Self:isSelf];
124
         [array insertObject:r atIndex:i];
104
         [array insertObject:r atIndex:i];
125
     }
105
     }
126
     return array;
106
     return array;
127
 }
107
 }
128
 
108
 
129
--(NSArray *)readSubreddits:(NSArray *)source Length:(NSInteger)length {
109
+-(void)readFrontpage:(id)parent {
110
+    NSHTTPURLResponse *response;
111
+    NSString *url = [NSString stringWithFormat:@"hot.json?limit=%ld", (long)length];
112
+    NSData *data = [self queryAPI:url withResponse:&response];
113
+    if ((data == nil) || ([response statusCode] != 200)) {
114
+        [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:nil waitUntilDone:false];
115
+    } else {
116
+        [parent performSelectorOnMainThread:@selector(reloadListHasFrontpageCallback:) withObject:[self convertJSONToItemArray:data] waitUntilDone:false];
117
+    }
118
+}
119
+
120
+-(void)readSubreddits:(id)parent {
130
     // TODO read subreddits (as multireddit?)
121
     // TODO read subreddits (as multireddit?)
131
-    return nil;
122
+    // TODO if implemented, enable checkbox in prefs
123
+}
124
+
125
+-(void)isAuthenticatedNewModhash:(id)parent {
126
+    NSHTTPURLResponse *response;
127
+    NSData *data = [self queryAPI:@"api/me.json" withResponse:&response];
128
+    if ((data != nil) && ([response statusCode] == 200)) {
129
+        NSError *error;
130
+        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
131
+        NSDictionary *data = [json valueForKey:@"data"];
132
+        if (data == nil) {
133
+            [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
134
+            return;
135
+        }
136
+        NSString *newHash = [data valueForKey:@"modhash"];
137
+        if ((newHash == nil) || ([newHash isEqualToString:@""])) {
138
+            [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
139
+            return;
140
+        }
141
+        if (![newHash isEqualToString:modhash]) {
142
+            modhash = newHash;
143
+        }
144
+        [parent performSelectorOnMainThread:@selector(reloadListIsAuthenticatedCallback) withObject:nil waitUntilDone:false];
145
+        return;
146
+        
147
+    }
148
+    [parent performSelectorOnMainThread:@selector(reloadListNotAuthenticatedCallback) withObject:nil waitUntilDone:false];
132
 }
149
 }
133
 
150
 
134
 -(NSData *)queryAPI:(NSString *)api withResponse:(NSHTTPURLResponse **)res {
151
 -(NSData *)queryAPI:(NSString *)api withResponse:(NSHTTPURLResponse **)res {
135
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
152
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
136
     [request setTimeoutInterval:5.0];
153
     [request setTimeoutInterval:5.0];
137
-    [request setCachePolicy:NSURLCacheStorageNotAllowed];
154
+    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
138
     [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
155
     [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
139
     [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
156
     [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
140
     if ((modhash != nil) && (![modhash isEqualToString:@""]))
157
     if ((modhash != nil) && (![modhash isEqualToString:@""]))
153
     NSString *requestBodyLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestBodyData length]];
170
     NSString *requestBodyLength = [NSString stringWithFormat:@"%lu", (unsigned long)[requestBodyData length]];
154
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
171
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[self getAPIPoint:api]];
155
     [request setTimeoutInterval:5.0];
172
     [request setTimeoutInterval:5.0];
156
-    [request setCachePolicy:NSURLCacheStorageNotAllowed];
173
+    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
157
     [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
174
     [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
158
     [request setValue:requestBodyLength forHTTPHeaderField:@"Content-Length"];
175
     [request setValue:requestBodyLength forHTTPHeaderField:@"Content-Length"];
159
     [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
176
     [request setValue:[NSString stringWithFormat:@"%@/%@ by %@", appName, version, author] forHTTPHeaderField:@"User-Agent"];
170
 }
187
 }
171
 
188
 
172
 -(NSURL *)getAPIPoint:(NSString *)where {
189
 -(NSURL *)getAPIPoint:(NSString *)where {
173
-    NSString *url = @"https://ssl.reddit.com";
174
-    return [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", url, where]];
190
+    return [NSURL URLWithString:[NSString stringWithFormat:@"https://ssl.reddit.com/%@", where]];
175
 }
191
 }
176
 
192
 
177
 -(NSString *)urlencode:(NSString *)string {
193
 -(NSString *)urlencode:(NSString *)string {

+ 1
- 1
RedditBar/RedditBar-Info.plist View File

21
 	<key>CFBundleSignature</key>
21
 	<key>CFBundleSignature</key>
22
 	<string>????</string>
22
 	<string>????</string>
23
 	<key>CFBundleVersion</key>
23
 	<key>CFBundleVersion</key>
24
-	<string>137</string>
24
+	<string>150</string>
25
 	<key>LSApplicationCategoryType</key>
25
 	<key>LSApplicationCategoryType</key>
26
 	<string>public.app-category.utilities</string>
26
 	<string>public.app-category.utilities</string>
27
 	<key>LSMinimumSystemVersion</key>
27
 	<key>LSMinimumSystemVersion</key>

BIN
RedditBar/de.lproj/Localizable.strings View File


BIN
RedditBar/en.lproj/Localizable.strings View File


Loading…
Cancel
Save