This repository was archived by the owner on Sep 15, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathReaderPostServiceRemote.m
More file actions
273 lines (235 loc) · 11.7 KB
/
Copy pathReaderPostServiceRemote.m
File metadata and controls
273 lines (235 loc) · 11.7 KB
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
#import "ReaderPostServiceRemote.h"
#import "RemoteReaderPost.h"
#import "RemoteSourcePostAttribution.h"
#import "ReaderTopicServiceRemote.h"
#import "WPKit-Swift.h"
@import NSObject_SafeExpectations;
@import WordPressShared;
NSString * const PostRESTKeyPosts = @"posts";
// Param keys
NSString * const ParamsKeyAlgorithm = @"algorithm";
NSString * const ParamKeyBefore = @"before";
NSString * const ParamKeyMeta = @"meta";
NSString * const ParamKeyNumber = @"number";
NSString * const ParamKeyOffset = @"offset";
NSString * const ParamKeyOrder = @"order";
NSString * const ParamKeyDescending = @"DESC";
NSString * const ParamKeyMetaValue = @"site,feed";
@implementation ReaderPostServiceRemote
- (void)fetchPostsFromEndpoint:(NSURL *)endpoint
algorithm:(NSString *)algorithm
count:(NSUInteger)count
before:(NSDate *)date
success:(void (^)(NSArray<RemoteReaderPost *> *posts, NSString *algorithm))success
failure:(void (^)(NSError *error))failure
{
NSNumber *numberToFetch = @(count);
NSMutableDictionary *params = [@{
ParamKeyNumber:numberToFetch,
ParamKeyBefore: [DateUtils isoStringFromDate:date],
ParamKeyOrder: ParamKeyDescending,
ParamKeyMeta: ParamKeyMetaValue
} mutableCopy];
if (algorithm) {
params[ParamsKeyAlgorithm] = algorithm;
}
[self fetchPostsFromEndpoint:endpoint withParameters:params success:success failure:failure];
}
- (void)fetchPostsFromEndpoint:(NSURL *)endpoint
algorithm:(NSString *)algorithm
count:(NSUInteger)count
offset:(NSUInteger)offset
success:(void (^)(NSArray<RemoteReaderPost *> *posts, NSString *algorithm))success
failure:(void (^)(NSError *))failure
{
NSMutableDictionary *params = [@{
ParamKeyNumber:@(count),
ParamKeyOffset: @(offset),
ParamKeyOrder: ParamKeyDescending,
ParamKeyMeta: ParamKeyMetaValue
} mutableCopy];
if (algorithm) {
params[ParamsKeyAlgorithm] = algorithm;
}
[self fetchPostsFromEndpoint:endpoint withParameters:params success:success failure:failure];
}
- (void)fetchPost:(NSUInteger)postID
fromSite:(NSUInteger)siteID
isFeed:(BOOL)isFeed
success:(void (^)(RemoteReaderPost *post))success
failure:(void (^)(NSError *error))failure {
NSString *feedType = (isFeed) ? @"feed" : @"sites";
NSString *path = [NSString stringWithFormat:@"read/%@/%lu/posts/%lu/?meta=site", feedType, (unsigned long)siteID, (unsigned long)postID];
NSString *requestUrl = [self pathForEndpoint:path
withVersion:ServiceRemoteWordPressComRESTApiVersion_1_2];
[self.wordPressComRestApi GET:requestUrl
parameters:nil
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (!success) {
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// Do all of this work on a background thread, then call success on the main thread.
// Do this to avoid any chance of blocking the UI while parsing.
RemoteReaderPost *post = [[RemoteReaderPost alloc] initWithDictionary: (NSDictionary *)responseObject];
dispatch_async(dispatch_get_main_queue(), ^{
success(post);
});
});
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
/**
Fetches a specific post from the specified URL
@param postURL The URL of the post to fetch
@param success block called on a successful fetch.
@param failure block called if there is any error. `error` can be any underlying network error.
*/
- (void)fetchPostAtURL:(NSURL *)postURL
success:(void (^)(RemoteReaderPost *post))success
failure:(void (^)(NSError *error))failure
{
NSString *path = [self apiPathForPostAtURL:postURL];
if (!path) {
failure(nil);
return;
}
[self.wordPressComRestApi GET:path
parameters:nil
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (!success) {
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// Do all of this work on a background thread, then call success on the main thread.
// Do this to avoid any chance of blocking the UI while parsing.
RemoteReaderPost *post = [[RemoteReaderPost alloc] initWithDictionary:(NSDictionary *)responseObject];
dispatch_async(dispatch_get_main_queue(), ^{
success(post);
});
});
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (void)likePost:(NSUInteger)postID
forSite:(NSUInteger)siteID
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
NSString *path = [NSString stringWithFormat:@"sites/%lu/posts/%lu/likes/new", (unsigned long)siteID, (unsigned long)postID];
NSString *requestUrl = [self pathForEndpoint:path
withVersion:ServiceRemoteWordPressComRESTApiVersion_1_1];
[self.wordPressComRestApi POST:requestUrl parameters:nil success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (success) {
success();
}
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (void)unlikePost:(NSUInteger)postID
forSite:(NSUInteger)siteID
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
NSString *path = [NSString stringWithFormat:@"sites/%lu/posts/%lu/likes/mine/delete", (unsigned long)siteID, (unsigned long)postID];
NSString *requestUrl = [self pathForEndpoint:path
withVersion:ServiceRemoteWordPressComRESTApiVersion_1_1];
[self.wordPressComRestApi POST:requestUrl parameters:nil success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (success) {
success();
}
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (NSString *)endpointUrlForSearchPhrase:(NSString *)phrase
{
NSAssert([phrase length] > 0, @"A search phrase is required.");
NSString *endpoint = [NSString stringWithFormat:@"read/search?q=%@", [phrase stringByUrlEncoding]];
NSString *absolutePath = [self pathForEndpoint:endpoint withVersion:ServiceRemoteWordPressComRESTApiVersion_1_2];
NSURL *url = [NSURL URLWithString:absolutePath relativeToURL:self.wordPressComRestApi.baseURL];
return [url absoluteString];
}
#pragma mark - Private Methods
/**
Fetches the posts from the specified remote endpoint
@param params A dictionary of parameters supported by the endpoint. Params are converted to the request's query string.
@param success block called on a successful fetch.
@param failure block called if there is any error. `error` can be any underlying network error.
*/
- (void)fetchPostsFromEndpoint:(NSURL *)endpoint
withParameters:(NSDictionary *)params
success:(void (^)(NSArray<RemoteReaderPost *> *posts, NSString *algorithm))success
failure:(void (^)(NSError *))failure
{
NSString *path = [endpoint path];
[self.wordPressComRestApi GET:path
parameters:params
success:^(id responseObject, NSHTTPURLResponse *httpResponse) {
if (!success) {
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// NOTE: Do all of this work on a background thread, then call success on the main thread.
// Do this to avoid any chance of blocking the UI while parsing.
// NOTE: If an offset param was specified sortRank will be derived
// from the offset + order of the results, ONLY if a `before` param
// was not specified. If a `before` param exists we favor sorting by date.
BOOL rankByOffset = [params objectForKey:ParamKeyOffset] != nil && [params objectForKey:ParamKeyBefore] == nil;
__block CGFloat offset = [[params numberForKey:ParamKeyOffset] floatValue];
NSString *algorithm = [responseObject stringForKey:ParamsKeyAlgorithm];
NSArray *jsonPosts = [responseObject arrayForKey:PostRESTKeyPosts];
NSArray *posts = [jsonPosts wp_map:^id(NSDictionary *jsonPost) {
if (rankByOffset) {
RemoteReaderPost *post = [self formatPostDictionary:jsonPost offset:offset];
offset++;
return post;
}
return [[RemoteReaderPost alloc] initWithDictionary:jsonPost];
}];
// Now call success on the main thread.
dispatch_async(dispatch_get_main_queue(), ^{
success(posts, algorithm);
});
});
} failure:^(NSError *error, NSHTTPURLResponse *httpResponse) {
if (failure) {
failure(error);
}
}];
}
- (RemoteReaderPost *)formatPostDictionary:(NSDictionary *)dict offset:(CGFloat)offset
{
RemoteReaderPost *post = [[RemoteReaderPost alloc] initWithDictionary:dict];
// It's assumed that sortRank values are in descending order. Since
// offsets are ascending, we store its negative to ensure we get a proper sort order.
CGFloat adjustedOffset = -offset;
post.sortRank = @(adjustedOffset);
return post;
}
- (nullable NSString *)apiPathForPostAtURL:(NSURL *)url
{
NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
NSString *hostname = components.host;
NSArray *pathComponents = [[components.path pathComponents] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != '/'"] ];
NSString *slug = [components.path lastPathComponent];
// We expect 4 path components for a post – year, month, day, slug, plus a '/' on either end
if (hostname == nil || pathComponents.count != 4 || slug == nil) {
return nil;
}
NSString *path = [NSString stringWithFormat:@"sites/%@/posts/slug:%@?meta=site,likes", hostname, slug];
return [self pathForEndpoint:path
withVersion:ServiceRemoteWordPressComRESTApiVersion_1_1];
}
@end