-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathMenusService.m
409 lines (350 loc) · 16.3 KB
/
MenusService.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
#import "MenusService.h"
#import "BasePost.h"
#import "Blog.h"
#import "Menu.h"
#import "MenuItem.h"
#import "MenuLocation.h"
@import WordPressData;
#import "PostService.h"
#import "WordPress-Swift.h"
@import WordPressKit;
@implementation MenusService
#pragma mark - Menus availability
- (BOOL)blogSupportsMenusCustomization:(Blog *)blog
{
NSParameterAssert([blog isKindOfClass:[Blog class]]);
return [blog supports:BlogFeatureMenus];
}
#pragma mark - Remote queries: Getting menus
- (void)syncMenusForBlog:(Blog *)blog
success:(nullable MenusServiceSuccessBlock)success
failure:(nullable MenusServiceFailureBlock)failure
{
NSParameterAssert([blog isKindOfClass:[Blog class]]);
NSAssert([self blogSupportsMenusCustomization:blog], @"Do not call this method on unsupported blogs, check with blogSupportsMenusCustomization first.");
if (blog.wordPressComRestApi == nil) {
if (failure) {
failure([self unknownErrorForInvalidApiFailure]);
}
return;
}
MenusServiceRemote *remote = [[MenusServiceRemote alloc] initWithWordPressComRestApi:blog.wordPressComRestApi];
[remote getMenusForSiteID:blog.dotComID
success:^(NSArray<RemoteMenu *> * _Nullable remoteMenus, NSArray<RemoteMenuLocation *> * _Nullable remoteLocations) {
[self.managedObjectContext performBlock:^{
NSArray *locations = nil;
if (remoteLocations.count) {
locations = [self menuLocationsFromRemoteMenuLocations:remoteLocations];
}
NSArray *menus = [remoteMenus wp_map:^Menu *(RemoteMenu *remoteMenu) {
Menu *menu = [self menuFromRemoteMenu:remoteMenu];
[self refreshLocationsForMenu:menu
matchingRemoteLocationNames:remoteMenu.locationNames
availableLocations:locations];
return menu;
}];
// Create a new default menu.
Menu *defaultMenu = [Menu newDefaultMenu:self.managedObjectContext];
// Ensure the default menu is the first menu in the list of menus.
NSMutableArray *mutableMenus = [NSMutableArray arrayWithArray:menus];
[mutableMenus insertObject:defaultMenu atIndex:0];
menus = mutableMenus;
// Set the default menu to locations, if needed.
for (MenuLocation *location in locations) {
if (location.menu) {
continue;
}
location.menu = defaultMenu;
}
blog.menuLocations = [NSOrderedSet orderedSetWithArray:locations];
blog.menus = [NSOrderedSet orderedSetWithArray:menus];
[[ContextManager sharedInstance] saveContext:self.managedObjectContext
withCompletionBlock:success
onQueue:dispatch_get_main_queue()];
}];
}
failure:failure];
}
#pragma mark - Creating and updating menus
- (void)createOrUpdateMenu:(Menu *)menu
forBlog:(Blog *)blog
success:(nullable MenusServiceCreateOrUpdateMenuRequestSuccessBlock)success
failure:(nullable MenusServiceFailureBlock)failure
{
NSParameterAssert([blog isKindOfClass:[Blog class]]);
NSParameterAssert([menu isKindOfClass:[Menu class]]);
NSAssert([self blogSupportsMenusCustomization:blog], @"Do not call this method on unsupported blogs, check with blogSupportsMenusCustomization first.");
if (blog.wordPressComRestApi == nil) {
if (failure) {
failure([self unknownErrorForInvalidApiFailure]);
}
return;
}
__weak __typeof(self) weakSelf = self;
if (menu.menuID.integerValue == 0) {
// Need to create the menu first.
[self createMenuWithName:menu.name
blog:blog
success:^(NSNumber *menuID) {
// Set the new menuID and continue the update.
menu.menuID = menuID;
[weakSelf updateMenu:menu
forBlog:blog
success:success
failure:failure];
}
failure:failure];
} else {
[self updateMenu:menu
forBlog:blog
success:success
failure:failure];
}
}
- (void)deleteMenu:(Menu *)menu
forBlog:(Blog *)blog
success:(nullable MenusServiceSuccessBlock)success
failure:(nullable MenusServiceFailureBlock)failure
{
NSParameterAssert([blog isKindOfClass:[Blog class]]);
NSParameterAssert([menu isKindOfClass:[Menu class]]);
NSAssert([self blogSupportsMenusCustomization:blog], @"Do not call this method on unsupported blogs, check with blogSupportsMenusCustomization first.");
if (blog.wordPressComRestApi == nil) {
if (failure) {
failure([self unknownErrorForInvalidApiFailure]);
}
return;
}
void(^completeMenuDeletion)(void) = ^() {
[self.managedObjectContext performBlock:^{
[self.managedObjectContext deleteObject:menu];
[self.managedObjectContext processPendingChanges];
[[ContextManager sharedInstance] saveContext:self.managedObjectContext];
if (success) {
success();
}
}];
};
if (!menu.menuID.integerValue) {
// Menu was only created locally, no need to delete remotely.
completeMenuDeletion();
return;
}
MenusServiceRemote *remote = [[MenusServiceRemote alloc] initWithWordPressComRestApi:blog.wordPressComRestApi];
[remote deleteMenuForID:menu.menuID
siteID:blog.dotComID
success:completeMenuDeletion
failure:failure];
}
- (MenuItem *)createItemWithPageID:(NSManagedObjectID *)pageObjectID inContext:(NSManagedObjectContext *)context {
Page *page = [context existingObjectWithID:pageObjectID error:nil];
if (page == nil) {
return nil;
}
if ([page.parentID integerValue] > 0) {
return nil;
}
MenuItem *pageItem = [NSEntityDescription insertNewObjectForEntityForName:[MenuItem entityName] inManagedObjectContext:self.managedObjectContext];
pageItem.contentID = page.postID;
pageItem.name = page.titleForDisplay;
pageItem.type = MenuItemTypePage;
return pageItem;
}
#pragma mark - private
- (void)createMenuWithName:(NSString *)menuName
blog:(Blog *)blog
success:(nullable void(^)(NSNumber *menuID))success
failure:(nullable MenusServiceFailureBlock)failure
{
MenusServiceRemote *remote = [[MenusServiceRemote alloc] initWithWordPressComRestApi:blog.wordPressComRestApi];
[remote createMenuWithName:menuName
siteID:blog.dotComID
success:^(RemoteMenu * _Nonnull remoteMenu) {
[self.managedObjectContext performBlock:^{
if (success) {
success(remoteMenu.menuID);
}
}];
}
failure:failure];
}
- (void)updateMenu:(Menu *)menu
forBlog:(Blog *)blog
success:(nullable void(^)(void))success
failure:(nullable MenusServiceFailureBlock)failure
{
NSMutableArray *locationNames = nil;
if (menu.locations.count) {
locationNames = [NSMutableArray arrayWithCapacity:menu.locations.count];
for (MenuLocation *location in menu.locations) {
if (location.name.length) {
[locationNames addObject:location.name];
}
}
}
NSArray *remoteItems = nil;
if (menu.items.count) {
remoteItems = [self remoteItemsFromMenuItems:menu.items];
}
MenusServiceRemote *remote = [[MenusServiceRemote alloc] initWithWordPressComRestApi:blog.wordPressComRestApi];
[remote updateMenuForID:menu.menuID
siteID:blog.dotComID
withName:menu.name
withLocations:locationNames
withItems:remoteItems
success:^(RemoteMenu * _Nonnull remoteMenu) {
[self.managedObjectContext performBlock:^{
/*
Update the local menu with the fresh MenuItems from remote.
We need to replace the MenuItems as it's difficult to keep track of
which items are equal to one another, especially when a menuID is unknown.
*/
menu.items = nil;
for (RemoteMenuItem *remoteItem in remoteMenu.items) {
[self addMenuItemFromRemoteMenuItem:remoteItem forMenu:menu];
}
[[ContextManager sharedInstance] saveContext:self.managedObjectContext
withCompletionBlock:success
onQueue:dispatch_get_main_queue()];
}];
}
failure:failure];
}
- (NSError *)unknownErrorForInvalidApiFailure
{
return [NSError errorWithDomain:WordPressComRestApiErrorDomain code:WordPressComRestApiErrorCodeUnknown userInfo:nil];
}
#pragma mark - Menu managed objects from RemoteMenu objects
- (Menu *)menuFromRemoteMenu:(RemoteMenu *)remoteMenu
{
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:[Menu entityName]
inManagedObjectContext:self.managedObjectContext];
Menu *menu = [[Menu alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];
menu.name = remoteMenu.name;
menu.details = remoteMenu.details;
menu.menuID = remoteMenu.menuID;
for (RemoteMenuItem *remoteItem in remoteMenu.items) {
[self addMenuItemFromRemoteMenuItem:remoteItem forMenu:menu];
}
return menu;
}
#pragma mark - MenuItem managed objects via RemoteMenuItem objects
- (MenuItem *)addMenuItemFromRemoteMenuItem:(RemoteMenuItem *)remoteMenuItem forMenu:(Menu *)menu
{
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:[MenuItem entityName]
inManagedObjectContext:self.managedObjectContext];
MenuItem *item = [[MenuItem alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];
item.itemID = remoteMenuItem.itemID;
item.contentID = remoteMenuItem.contentID;
item.details = remoteMenuItem.details;
item.linkTarget = remoteMenuItem.linkTarget;
item.linkTitle = remoteMenuItem.linkTitle;
item.name = remoteMenuItem.name;
item.type = remoteMenuItem.type;
item.typeFamily = remoteMenuItem.typeFamily;
item.typeLabel = remoteMenuItem.typeLabel;
item.urlStr = remoteMenuItem.urlStr;
item.menu = menu;
item.classes = remoteMenuItem.classes;
if (remoteMenuItem.children) {
for (RemoteMenuItem *childRemoteItem in remoteMenuItem.children) {
MenuItem *childItem = [self addMenuItemFromRemoteMenuItem:childRemoteItem forMenu:menu];
childItem.parent = item;
}
}
return item;
}
#pragma mark - MenuLocations managed objects from RemoteMenuLocation objects
- (NSArray *)menuLocationsFromRemoteMenuLocations:(NSArray<RemoteMenuLocation *> *)remoteMenuLocations
{
NSMutableArray *locations = [NSMutableArray arrayWithCapacity:remoteMenuLocations.count];
[self.managedObjectContext performBlockAndWait:^{
// remove the current menus related to the blog
for (RemoteMenuLocation *remoteMenuLocation in remoteMenuLocations) {
[locations addObject:[self menuLocationFromRemoteMenuLocation:remoteMenuLocation]];
}
}];
return [NSArray arrayWithArray:locations];
}
- (MenuLocation *)menuLocationFromRemoteMenuLocation:(RemoteMenuLocation *)remoteMenuLocation
{
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:[MenuLocation entityName]
inManagedObjectContext:self.managedObjectContext];
MenuLocation *location = [[MenuLocation alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:self.managedObjectContext];
location.name = remoteMenuLocation.name;
location.details = remoteMenuLocation.details;
location.defaultState = remoteMenuLocation.defaultState;
return location;
}
#pragma mark - Local storage
- (void)refreshLocationsForMenu:(Menu *)menu
matchingRemoteLocationNames:(nullable NSArray *)remoteLocationNames
availableLocations:(nullable NSArray *)locations
{
NSArray *menuLocations = nil;
if (remoteLocationNames.count) {
menuLocations = [locations filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name IN %@", remoteLocationNames]];
}
if (menuLocations.count) {
[menu setLocations:[NSSet setWithArray:menuLocations]];
}
}
#pragma mark - RemoteMenu objects from Menu objects
- (NSArray *)remoteItemsFromMenuItems:(NSOrderedSet<MenuItem *> *)menuItems
{
NSMutableArray *remoteItems = [NSMutableArray arrayWithCapacity:menuItems.count];
for (MenuItem *item in menuItems) {
// Only add top-level items since MenuItem keeps all associated items under it's children relationship.
if (item.parent) {
continue;
}
// Children of item will be added as remoteItem.children.
RemoteMenuItem *remoteItem = [self remoteItemFromItem:item withItems:menuItems];
[remoteItems addObject:remoteItem];
}
return [NSArray arrayWithArray:remoteItems];
}
- (RemoteMenuItem *)remoteItemFromItem:(MenuItem *)item withItems:(NSOrderedSet<MenuItem *> *)items
{
RemoteMenuItem *remoteItem = [[RemoteMenuItem alloc] init];
remoteItem.itemID = item.itemID;
remoteItem.contentID = item.contentID;
remoteItem.details = item.details;
remoteItem.linkTarget = item.linkTarget;
remoteItem.linkTitle = item.linkTitle;
remoteItem.name = item.name;
remoteItem.type = item.type;
remoteItem.classes = item.classes;
if (remoteItem.type) {
// Override the type_family param based on the type.
// This is a weird behavior of the API and is not documented.
NSString *typeFamily;
if ([remoteItem.type isEqualToString:MenuItemTypeCustom]) {
typeFamily = @"custom";
} else if ([remoteItem.type isEqualToString:MenuItemTypeTag] || [remoteItem.type isEqualToString:MenuItemTypeCategory]){
typeFamily = @"taxonomy";
} else {
typeFamily = @"post_type";
}
if (typeFamily.length) {
remoteItem.typeFamily = typeFamily;
}
}
remoteItem.typeLabel = item.typeLabel;
remoteItem.urlStr = item.urlStr;
if (item.children.count) {
// Find the children of the item and them to remoteItem.children.
NSMutableArray *children = [NSMutableArray arrayWithCapacity:item.children.count];
for (MenuItem *anItem in items) {
if (!anItem.parent) {
continue;
}
if (anItem.parent == item) {
[children addObject:[self remoteItemFromItem:anItem withItems:items]];
}
remoteItem.children = children;
}
}
return remoteItem;
}
@end