Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Blog service lookup blog #19366

Merged
merged 9 commits into from
Sep 29, 2022
42 changes: 42 additions & 0 deletions WordPress/Classes/Models/Blog+History.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import Foundation

extension Blog {

/// Returns the blog currently flagged as the one last used, or the primary blog,
/// or the first blog in an alphanumerically sorted list, whichever is found first.
@objc(lastUsedOrFirstInContext:)
static func lastUsedOrFirst(in context: NSManagedObjectContext) -> Blog? {
lastUsed(in: context)
?? (try? WPAccount.lookupDefaultWordPressComAccount(in: context))?.defaultBlog
?? firstBlog(in: context)
}

/// Returns the blog currently flaged as the one last used.
static func lastUsed(in context: NSManagedObjectContext) -> Blog? {
guard let url = RecentSitesService().recentSites.first else {
return nil
}

return blog(with: NSPredicate(format: "visible = YES AND url = %@", url), in: context)
}

private static func firstBlog(in context: NSManagedObjectContext) -> Blog? {
blog(with: NSPredicate(format: "visible = YES"), in: context)
}

private static func blog(with predicate: NSPredicate, in context: NSManagedObjectContext) -> Blog? {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is translated from BlogService.blogsWithPredicate

let request = NSFetchRequest<Blog>(entityName: NSStringFromClass(Blog.self))
request.includesSubentities = false
request.predicate = predicate
request.fetchLimit = 1
request.sortDescriptors = [NSSortDescriptor(key: "settings.name", ascending: true)]

do {
return try context.fetch(request).first
} catch {
DDLogError("Couldn't fetch blogs with predicate \(predicate): \(error)")
return nil
}
}
Comment on lines +27 to +40
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe in a future iteration it would be cool to throw or return Result<Blog, Error>.

Of course, that's out of scope now and also would require making a choice over which approach to use. Just thinking out loud.


}
29 changes: 0 additions & 29 deletions WordPress/Classes/Services/BlogService.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,35 +26,6 @@ extern NSString *const WPBlogUpdatedNotification;
*/
- (nullable Blog *)blogByHostname:(NSString *)hostname;

/**
Returns the blog currently flagged as the one last used, or the primary blog,
or the first blog in an alphanumerically sorted list, whichever is found first.
*/
- (nullable Blog *)lastUsedOrFirstBlog;

/**
Returns the blog currently flagged as the one last used, or the primary blog,
or the first blog in an alphanumerically sorted list that supports the given
feature, whichever is found first.
*/
- (nullable Blog *)lastUsedOrFirstBlogThatSupports:(BlogFeature)feature;
Comment on lines -35 to -40
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method hasn't been converted. But the code builds without it, so it was clearly unused 😄 👍


/**
Returns the blog currently flaged as the one last used.
*/
- (nullable Blog *)lastUsedBlog;

/**
Returns the first blog in an alphanumerically sorted list.
*/
- (nullable Blog *)firstBlog;

/**
Returns the default WPCom blog.
*/
- (nullable Blog *)primaryBlog;


/**
* Sync all available blogs for an acccount
*
Expand Down
72 changes: 0 additions & 72 deletions WordPress/Classes/Services/BlogService.m
Original file line number Diff line number Diff line change
Expand Up @@ -44,78 +44,6 @@ - (Blog *)blogByHostname:(NSString *)hostname
return [blogs firstObject];
}

- (Blog *)lastUsedOrFirstBlog
{
Blog *blog = [self lastUsedOrPrimaryBlog];

if (!blog) {
blog = [self firstBlog];
}

return blog;
}

- (Blog *)lastUsedOrFirstBlogThatSupports:(BlogFeature)feature
{
Blog *blog = [self lastUsedOrPrimaryBlog];

if (![blog supports:feature]) {
blog = [self firstBlogThatSupports:feature];
}

return blog;
}

- (Blog *)lastUsedOrPrimaryBlog
{
Blog *blog = [self lastUsedBlog];

if (!blog) {
blog = [self primaryBlog];
}

return blog;
}

- (Blog *)lastUsedBlog
{
// Try to get the last used blog, if there is one.
RecentSitesService *recentSitesService = [RecentSitesService new];
NSString *url = [[recentSitesService recentSites] firstObject];
if (!url) {
return nil;
}

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"visible = YES AND url = %@", url];
Blog *blog = [self blogWithPredicate:predicate];

return blog;
}

- (Blog *)primaryBlog
{
return [[WPAccount lookupDefaultWordPressComAccountInContext:self.managedObjectContext] defaultBlog];
}

- (Blog *)firstBlogThatSupports:(BlogFeature)feature
{
NSPredicate *predicate = [self predicateForVisibleBlogs];
NSArray *results = [self blogsWithPredicate:predicate];

for (Blog *blog in results) {
if ([blog supports:feature]) {
return blog;
}
}
return nil;
}

- (Blog *)firstBlog
{
NSPredicate *predicate = [self predicateForVisibleBlogs];
return [self blogWithPredicate:predicate];
}

- (void)syncBlogsForAccount:(WPAccount *)account
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ open class WP3DTouchShortcutCreator: NSObject {
fileprivate func loggedInShortcutArray() -> [UIApplicationShortcutItem] {
var defaultBlogName: String?
if blogService.blogCountForAllAccounts() > 1 {
defaultBlogName = blogService.lastUsedOrFirstBlog()?.settings?.name
defaultBlogName = Blog.lastUsedOrFirst(in: mainContext)?.settings?.name
}

let notificationsShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.Notifications.type,
Expand Down Expand Up @@ -154,7 +154,7 @@ open class WP3DTouchShortcutCreator: NSObject {
}

fileprivate func doesCurrentBlogSupportStats() -> Bool {
guard let currentBlog = blogService.lastUsedOrFirstBlog() else {
guard let currentBlog = Blog.lastUsedOrFirst(in: mainContext) else {
return false
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,7 @@ open class WP3DTouchShortcutHandler: NSObject {
case ShortcutIdentifier.Stats.type:
WPAnalytics.track(.shortcutStats)
clearCurrentViewController()
let blogService: BlogService = BlogService(managedObjectContext: ContextManager.sharedInstance().mainContext)
if let mainBlog = blogService.lastUsedOrFirstBlog() {
if let mainBlog = Blog.lastUsedOrFirst(in: ContextManager.sharedInstance().mainContext) {
tabBarController.mySitesCoordinator.showStats(for: mainBlog)
}
return true
Expand Down
6 changes: 2 additions & 4 deletions WordPress/Classes/System/WordPressAppDelegate+openURL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,7 @@ import AutomatticTracks
let tags = params.value(of: NewPostKey.tags)

let context = ContextManager.sharedInstance().mainContext
let blogService = BlogService(managedObjectContext: context)
guard let blog = blogService.lastUsedOrFirstBlog() else {
guard let blog = Blog.lastUsedOrFirst(in: context) else {
return false
}

Expand Down Expand Up @@ -181,8 +180,7 @@ import AutomatticTracks
let title = params.value(of: NewPostKey.title)

let context = ContextManager.sharedInstance().mainContext
let blogService = BlogService(managedObjectContext: context)
guard let blog = blogService.lastUsedOrFirstBlog() else {
guard let blog = Blog.lastUsedOrFirst(in: context) else {
return false
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import WordPressFlux
extension NavigationAction {
func defaultBlog() -> Blog? {
let context = ContextManager.sharedInstance().mainContext
let service = BlogService(managedObjectContext: context)

return service.lastUsedOrFirstBlog()
return Blog.lastUsedOrFirst(in: context)
}

func blog(from values: [String: String]?) -> Blog? {
Expand Down
15 changes: 5 additions & 10 deletions WordPress/Classes/Utility/ZendeskUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -412,9 +412,8 @@ private extension ZendeskUtils {
}

// 2. Use information from selected site.
let blogService = BlogService(managedObjectContext: context)

guard let blog = blogService.lastUsedBlog() else {
guard let blog = Blog.lastUsed(in: context) else {
// We have no user information.
completion()
return
Expand Down Expand Up @@ -630,9 +629,7 @@ private extension ZendeskUtils {
}

static func getCurrentSiteDescription() -> String {
let blogService = BlogService(managedObjectContext: ContextManager.sharedInstance().mainContext)

guard let blog = blogService.lastUsedBlog() else {
guard let blog = Blog.lastUsed(in: ContextManager.sharedInstance().mainContext) else {
return Constants.noValue
}

Expand Down Expand Up @@ -694,13 +691,13 @@ private extension ZendeskUtils {


// Add gutenbergIsDefault tag
if let blog = blogService.lastUsedBlog() {
if let blog = Blog.lastUsed(in: context) {
if blog.isGutenbergEnabled {
tags.append(Constants.gutenbergIsDefault)
}
}

if let currentSite = blogService.lastUsedOrFirstBlog(), !currentSite.isHostedAtWPcom, !currentSite.isAtomic() {
if let currentSite = Blog.lastUsedOrFirst(in: context), !currentSite.isHostedAtWPcom, !currentSite.isAtomic() {
tags.append(Constants.mobileSelfHosted)
}

Expand Down Expand Up @@ -1045,9 +1042,7 @@ private extension ZendeskUtils {

/// Provides the current site id to `getZendeskMetadata`, if it exists
private static var currentSiteID: Int? {
guard let siteID = BlogService(managedObjectContext: ContextManager.shared.mainContext)
.lastUsedOrFirstBlog()?
.dotComID else {
guard let siteID = Blog.lastUsedOrFirst(in: ContextManager.shared.mainContext)?.dotComID else {
return nil
}
return Int(truncating: siteID)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ class MySiteViewController: UIViewController, NoResultsViewHost {
/// - Returns:the main blog for an account (last selected, or first blog in list).
///
private func mainBlog() -> Blog? {
return blogService.lastUsedOrFirstBlog()
return Blog.lastUsedOrFirst(in: ContextManager.sharedInstance().mainContext)
}

/// This VC is prepared to either show the details for a blog, or show a no-results VC configured to let the user know they have no blogs.
Expand Down Expand Up @@ -911,7 +911,7 @@ class MySiteViewController: UIViewController, NoResultsViewHost {
return
}

guard let blog = blogService.lastUsedOrFirstBlog() else {
guard let blog = Blog.lastUsedOrFirst(in: ContextManager.sharedInstance().mainContext) else {
return
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,8 @@ private class AccountSettingsController: SettingsController {

// If the primary site has no Site Title, then show the displayURL.
if primarySiteName.isEmpty {
let blogService = BlogService(managedObjectContext: ContextManager.sharedInstance().mainContext)
primarySiteName = blogService.primaryBlog()?.displayURL as String? ?? ""
let account = try? WPAccount.lookupDefaultWordPressComAccount(in: ContextManager.sharedInstance().mainContext)
primarySiteName = account?.defaultBlog.displayURL as String? ?? ""
}

let primarySite = EditableTextRow(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
extension NotificationsViewController {

func promptForJetpackCredentials() {
guard let blog = blogService.lastUsedBlog() else {
guard let blog = Blog.lastUsed(in: managedObjectContext()) else {
return
}

Expand Down Expand Up @@ -38,11 +38,4 @@ extension NotificationsViewController {
}
}


// MARK: - Private Computed Properties

fileprivate var blogService: BlogService {
return BlogService(managedObjectContext: managedObjectContext())
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,7 @@ class ReaderReblogPresenter {
}
presentEditor(with: readerPost, blog: blog, origin: origin)
default:
guard let blog = blogService.lastUsedOrFirstBlog() else {
return
}
presentBlogPicker(from: origin,
blog: blog,
blogService: blogService,
readerPost: readerPost)
}
Expand All @@ -55,7 +51,6 @@ class ReaderReblogPresenter {
private extension ReaderReblogPresenter {
/// presents the blog picker before the editor, for users with multiple sites
func presentBlogPicker(from origin: UIViewController,
blog: Blog,
blogService: BlogService,
readerPost: ReaderPost) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,7 @@ class MySitesCoordinator: NSObject {

func showCreateSheet(for blog: Blog?) {
let context = ContextManager.shared.mainContext
let service = BlogService(managedObjectContext: context)
guard let targetBlog = blog ?? service.lastUsedOrFirstBlog() else {
guard let targetBlog = blog ?? Blog.lastUsedOrFirst(in: context) else {
return
}

Expand Down
3 changes: 1 addition & 2 deletions WordPress/Classes/ViewRelated/System/WPTabBarController.m
Original file line number Diff line number Diff line change
Expand Up @@ -446,8 +446,7 @@ - (Blog *)currentOrLastBlog

if (blog == nil) {
NSManagedObjectContext *context = [[ContextManager sharedInstance] mainContext];
BlogService *blogService = [[BlogService alloc] initWithManagedObjectContext:context];
blog = [blogService lastUsedOrFirstBlog];
blog = [Blog lastUsedOrFirstInContext: context];
}

return blog;
Expand Down
6 changes: 6 additions & 0 deletions WordPress/WordPress.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -998,6 +998,8 @@
4A50668128B364CA00DD09F4 /* ContainerContextFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A50667F28B364CA00DD09F4 /* ContainerContextFactory.swift */; };
4A82C43128D321A300486CFF /* Blog+Post.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A82C43028D321A300486CFF /* Blog+Post.swift */; };
4A82C43228D321A300486CFF /* Blog+Post.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A82C43028D321A300486CFF /* Blog+Post.swift */; };
4AD5656F28E413160054C676 /* Blog+History.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AD5656E28E413160054C676 /* Blog+History.swift */; };
4AD5657028E413160054C676 /* Blog+History.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AD5656E28E413160054C676 /* Blog+History.swift */; };
4AFB8FBF2824999500A2F4B2 /* ContextManagerMock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4AFB8FBE2824999400A2F4B2 /* ContextManagerMock.swift */; };
4B2DD0F29CD6AC353C056D41 /* Pods_WordPressUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8DCE7542239FBC709B90EA85 /* Pods_WordPressUITests.framework */; };
4C8A715EBCE7E73AEE216293 /* Pods_WordPressShareExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F47DB4A8EC2E6844E213A3FA /* Pods_WordPressShareExtension.framework */; };
Expand Down Expand Up @@ -5966,6 +5968,7 @@
4A50667E28B3218800DD09F4 /* ManagedObjectContextFactory.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ManagedObjectContextFactory.h; sourceTree = "<group>"; };
4A50667F28B364CA00DD09F4 /* ContainerContextFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerContextFactory.swift; sourceTree = "<group>"; };
4A82C43028D321A300486CFF /* Blog+Post.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Blog+Post.swift"; sourceTree = "<group>"; };
4AD5656E28E413160054C676 /* Blog+History.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Blog+History.swift"; sourceTree = "<group>"; };
4AFB8FBE2824999400A2F4B2 /* ContextManagerMock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContextManagerMock.swift; sourceTree = "<group>"; };
4D520D4E22972BC9002F5924 /* acknowledgements.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; name = acknowledgements.html; path = "../Pods/Target Support Files/Pods-Apps-WordPress/acknowledgements.html"; sourceTree = "<group>"; };
51A5F017948878F7E26979A0 /* Pods-Apps-WordPress.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Apps-WordPress.release.xcconfig"; path = "../Pods/Target Support Files/Pods-Apps-WordPress/Pods-Apps-WordPress.release.xcconfig"; sourceTree = "<group>"; };
Expand Down Expand Up @@ -13432,6 +13435,7 @@
2420BEF025D8DAB300966129 /* Blog+Lookup.swift */,
F10D634E26F0B78E00E46CC7 /* Blog+Organization.swift */,
8B4EDADC27DF9D5E004073B6 /* Blog+MySite.swift */,
4AD5656E28E413160054C676 /* Blog+History.swift */,
);
name = Blog;
sourceTree = "<group>";
Expand Down Expand Up @@ -18929,6 +18933,7 @@
FA681F8A25CA946B00DAA544 /* BaseRestoreStatusFailedViewController.swift in Sources */,
081E4B4C281C019A0085E89C /* TooltipAnchor.swift in Sources */,
3F851415260D0A3300A4B938 /* UnifiedPrologueEditorContentView.swift in Sources */,
4AD5656F28E413160054C676 /* Blog+History.swift in Sources */,
179A70F02729834B006DAC0A /* Binding+OnChange.swift in Sources */,
D8D7DF5A20AD18A400B40A2D /* ImgUploadProcessor.swift in Sources */,
436D56222117312700CEAA33 /* RegisterDomainDetailsViewModel.swift in Sources */,
Expand Down Expand Up @@ -22120,6 +22125,7 @@
3F46EEC928BC493E004F02B2 /* JetpackPromptsViewModel.swift in Sources */,
FABB24D22602FC2C00C8785C /* ReaderHelpers.swift in Sources */,
FABB24D32602FC2C00C8785C /* SubjectContentStyles.swift in Sources */,
4AD5657028E413160054C676 /* Blog+History.swift in Sources */,
FABB24D42602FC2C00C8785C /* AbstractPost.m in Sources */,
FABB24D52602FC2C00C8785C /* PostStatsTableViewController.swift in Sources */,
FABB24D62602FC2C00C8785C /* BlogService+Deduplicate.swift in Sources */,
Expand Down
Loading