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

Allow adding custom bookmarks using AddOrEditBookmarkViewController #1009

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 43 additions & 9 deletions Sources/Bookmarks/BookmarkEditorViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public class BookmarkEditorViewModel: ObservableObject {
}

let context: NSManagedObjectContext
let sanitization: BookmarkSanitization?

public let favoritesDisplayMode: FavoritesDisplayMode

@Published public var bookmark: BookmarkEntity
Expand Down Expand Up @@ -64,12 +66,14 @@ public class BookmarkEditorViewModel: ObservableObject {
public init(editingEntityID: NSManagedObjectID,
bookmarksDatabase: CoreDataDatabase,
favoritesDisplayMode: FavoritesDisplayMode,
errorEvents: EventMapping<BookmarksModelError>?) {
errorEvents: EventMapping<BookmarksModelError>?,
sanitization: BookmarkSanitization? = nil) {

externalUpdates = subject.eraseToAnyPublisher()
self.errorEvents = errorEvents
self.context = bookmarksDatabase.makeContext(concurrencyType: .mainQueueConcurrencyType)
self.favoritesDisplayMode = favoritesDisplayMode
self.sanitization = sanitization

guard let entity = context.object(with: editingEntityID) as? BookmarkEntity else {
// For sync, this is valid scenario in case of a timing issue
Expand All @@ -81,22 +85,17 @@ public class BookmarkEditorViewModel: ObservableObject {
registerForChanges()
}

deinit {
if let observer {
NotificationCenter.default.removeObserver(observer)
self.observer = nil
}
}

public init(creatingFolderWithParentID parentFolderID: NSManagedObjectID?,
bookmarksDatabase: CoreDataDatabase,
favoritesDisplayMode: FavoritesDisplayMode,
errorEvents: EventMapping<BookmarksModelError>?) {
errorEvents: EventMapping<BookmarksModelError>?,
sanitization: BookmarkSanitization? = nil) {

externalUpdates = subject.eraseToAnyPublisher()
self.errorEvents = errorEvents
self.context = bookmarksDatabase.makeContext(concurrencyType: .mainQueueConcurrencyType)
self.favoritesDisplayMode = favoritesDisplayMode
self.sanitization = sanitization

let parent: BookmarkEntity?
if let parentFolderID = parentFolderID {
Expand All @@ -115,6 +114,40 @@ public class BookmarkEditorViewModel: ObservableObject {
registerForChanges()
}

public init(addingBookmarkWith url: String,
title: String,
toFolderWithID folderID: NSManagedObjectID? = nil,
bookmarksDatabase: CoreDataDatabase,
favoritesDisplayMode: FavoritesDisplayMode,
errorEvents: EventMapping<BookmarksModelError>?,
sanitization: BookmarkSanitization? = nil) {
externalUpdates = subject.eraseToAnyPublisher()
self.errorEvents = errorEvents
self.context = bookmarksDatabase.makeContext(concurrencyType: .mainQueueConcurrencyType)
self.favoritesDisplayMode = favoritesDisplayMode
self.sanitization = sanitization

let parent: BookmarkEntity?
if let folderID {
parent = context.object(with: folderID) as? BookmarkEntity
} else {
parent = BookmarkUtils.fetchRootFolder(context)
}
assert(parent != nil)

self.bookmark = BookmarkEntity.makeBookmark(title: title, url: url, parent: parent!, context: context)

refresh()
registerForChanges()
}

deinit {
if let observer {
NotificationCenter.default.removeObserver(observer)
self.observer = nil
}
}

private func registerForChanges() {
observer = NotificationCenter.default.addObserver(forName: NSManagedObjectContext.didSaveObjectsNotification,
object: nil,
Expand Down Expand Up @@ -200,6 +233,7 @@ public class BookmarkEditorViewModel: ObservableObject {

public func save() {
do {
sanitization?.sanitize(bookmark)
try context.save()
} catch {
errorEvents?.fire(.saveFailed(.edit), error: error)
Expand Down
46 changes: 46 additions & 0 deletions Sources/Bookmarks/BookmarkSanitization.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//
// BookmarkSanitization.swift
//
// Copyright © 2024 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import Foundation

/// Provides strategies to sanitize edited Bookmark.
public enum BookmarkSanitization {

/// Treats input as a potentially navigational address, appending scheme and fixing common known issues
case navigational

/// Provides a custom sanitization function
case custom((BookmarkEntity) -> Void)

func sanitize(_ bookmark: BookmarkEntity) {
switch self {
case .navigational:
navigationalSanitization(bookmark)
case .custom(let sanitize):
sanitize(bookmark)
}
}

private func navigationalSanitization(_ bookmark: BookmarkEntity) {
guard let url = bookmark.url else {
return
}

bookmark.url = URL(trimmedAddressBarString: url)?.absoluteString ?? url
}
}
129 changes: 129 additions & 0 deletions Tests/BookmarksTests/BookmarksSanitizationTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
//
// BookmarksSanitizationTests.swift
//
// Copyright © 2024 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

import XCTest
import Persistence
@testable import Bookmarks
import CoreData
import Foundation

final class BookmarksSanitizationTests: XCTestCase {

private var bookmarksDatabase: CoreDataDatabase!
private var location: URL!
private var context: NSManagedObjectContext!
private var rootFolder: BookmarkEntity!

override func setUp() {
super.setUp()

location = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)

let bundle = Bookmarks.bundle
guard let model = CoreDataDatabase.loadModel(from: bundle, named: "BookmarksModel") else {
XCTFail("Failed to load model")
return
}
bookmarksDatabase = CoreDataDatabase(name: type(of: self).description(), containerLocation: location, model: model)
bookmarksDatabase.loadStore()

context = bookmarksDatabase.makeContext(concurrencyType: .privateQueueConcurrencyType)
context.performAndWait {
BookmarkUtils.prepareFoldersStructure(in: context)
try! context.save()
}

rootFolder = BookmarkUtils.fetchRootFolder(context)
}

override func tearDown() {
super.tearDown()

try? FileManager.default.removeItem(at: location)
}

func testRunsCustomSanitization() {
let bookmark = stubBookmark(url: "some.url", in: context)
var didRunCustomFunction = false
let sanitization = BookmarkSanitization.custom { _ in
didRunCustomFunction = true
}

sanitization.sanitize(bookmark)

XCTAssertTrue(didRunCustomFunction)
}

func testNavigationalSanitizationAddsSchemeToURL() {
let bookmark = stubBookmark(url: "some.url", in: context)
let sanitization = BookmarkSanitization.navigational

sanitization.sanitize(bookmark)

XCTAssertEqual(bookmark.url, "http://some.url")
}

func testNavigationalSanitizationAllowsIPAddress() {
let bookmark = stubBookmark(url: "192.168.1.1", in: context)
let sanitization = BookmarkSanitization.navigational

sanitization.sanitize(bookmark)

XCTAssertEqual(bookmark.url, "http://192.168.1.1")
}

func testNavigationalSanitizationKeepsExistingHTTPScheme() {
let bookmark = stubBookmark(url: "https://some.url", in: context)
let sanitization = BookmarkSanitization.navigational

sanitization.sanitize(bookmark)

XCTAssertEqual(bookmark.url, "https://some.url")
}

func testNavigationalSanitizationKeepsExistingScheme() {
let bookmark = stubBookmark(url: "somescheme://some.url", in: context)
let sanitization = BookmarkSanitization.navigational

sanitization.sanitize(bookmark)

XCTAssertEqual(bookmark.url, "somescheme://some.url")
}

func testNavigationalSanitizationUsesPunycodeForEmoji() {
let bookmark = stubBookmark(url: "https://😍.url", in: context)
let sanitization = BookmarkSanitization.navigational

sanitization.sanitize(bookmark)

XCTAssertEqual(bookmark.url, "https://xn--r28h.url")
}

func testNavigationalSanitizationKeepsEmptyString() {
let bookmark = stubBookmark(url: " ", in: context)
let sanitization = BookmarkSanitization.navigational

sanitization.sanitize(bookmark)

XCTAssertEqual(bookmark.url, " ")
}

private func stubBookmark(url: String, in context: NSManagedObjectContext) -> BookmarkEntity {
BookmarkEntity.makeBookmark(title: "", url: url, parent: rootFolder, context: context)
}
}
Loading