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

Shortcuts: Open Note #1163

Merged
merged 17 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
18 changes: 18 additions & 0 deletions IntentsExtension/Extensions/FileManager+Intents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//
// FileManager+Intents.swift
// IntentsExtension
//
// Created by Charlie Scheer on 5/31/24.
// Copyright © 2024 Simperium. All rights reserved.
//

import Foundation

// This exists in a8cTracks but we aren't currently importing that into intents but we need this for FileManager to meet FileManagerProtocol
extension FileManager {
func directoryExistsAtURL(_ url: URL) -> Bool {
var isDir: ObjCBool = false
let exists = self.fileExists(atPath: url.path, isDirectory: &isDir)
return exists && isDir.boolValue
}
}
23 changes: 23 additions & 0 deletions IntentsExtension/Extensions/IntentNote+Helpers.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
//
// IntentNote.swift
// IntentsExtension
//
// Created by Charlie Scheer on 5/29/24.
// Copyright © 2024 Simperium. All rights reserved.
//

import Intents

extension IntentNote {
static func allNotes(in coreDataWrapper: ExtensionCoreDataWrapper) throws -> [IntentNote] {
guard let notes = coreDataWrapper.resultsController?.notes() else {
throw IntentsError.couldNotFetchNotes
}

return makeIntentNotes(from: notes)
}

static func makeIntentNotes(from notes: [Note]) -> [IntentNote] {
notes.map({ IntentNote(identifier: $0.simperiumKey, display: $0.title) })
}
}
2 changes: 2 additions & 0 deletions IntentsExtension/IntentHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ class IntentHandler: INExtension {
switch intent {
case is OpenNewNoteIntent:
return OpenNewNoteIntentHandler()
case is OpenNoteIntent:
return OpenNoteIntentHandler()
default:
return self
}
Expand Down
34 changes: 34 additions & 0 deletions IntentsExtension/IntentHandlers/OpenNoteIntentHandler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//
// OpenNoteIntentHandler.swift
// IntentsExtension
//
// Created by Charlie Scheer on 5/29/24.
// Copyright © 2024 Simperium. All rights reserved.
//

import Intents

class OpenNoteIntentHandler: NSObject, OpenNoteIntentHandling {
let coredataWrapper = ExtensionCoreDataWrapper()

func provideNoteOptionsCollection(for intent: OpenNoteIntent, with completion: @escaping (INObjectCollection<IntentNote>?, (any Error)?) -> Void) {
do {
let intentNotes = try IntentNote.allNotes(in: coredataWrapper)
completion(INObjectCollection(items: intentNotes), nil)
} catch {
completion(nil, IntentsError.couldNotFetchNotes)
}
}

func handle(intent: OpenNoteIntent, completion: @escaping (OpenNoteIntentResponse) -> Void) {
guard let identifier = intent.note?.identifier else {
completion(OpenNoteIntentResponse(code: .failure, userActivity: nil))
return
}

let activity = NSUserActivity(activityType: ActivityType.openNoteShortcut.rawValue)
activity.userInfo = [IntentsConstants.noteIdentifierKey: identifier]

completion(OpenNoteIntentResponse(code: .continueInApp, userActivity: activity))
}
}
61 changes: 61 additions & 0 deletions IntentsExtension/Models/Note+Intents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// This file contains the required class structure to be able to fetch and use core data files in widgets and intents
// We have collapsed the auto generated core data files into a single file as it is unlikely that the files will need to
// be regenerated. Contained in this file is the generated class files Note+CoreDataClass.swift and Note+CoreDataProperties.swift

import Foundation
import CoreData

@objc(Note)
public class Note: SPManagedObject {

}

extension Note {

@nonobjc public class func fetchRequest() -> NSFetchRequest<Note> {
return NSFetchRequest<Note>(entityName: "Note")
}

public override func awakeFromInsert() {
super.awakeFromInsert()

if simperiumKey.isEmpty {
simperiumKey = UUID().uuidString.replacingOccurrences(of: "-", with: "")
}
}

@NSManaged public var content: String?
@NSManaged public var creationDate: Date?
@NSManaged public override var isDeleted: Bool
@NSManaged public var lastPosition: NSNumber?
@NSManaged public var modificationDate: Date?
@NSManaged public var noteSynced: NSNumber?
@NSManaged public var owner: String?
@NSManaged public var pinned: NSNumber?
@NSManaged public var publishURL: String?
@NSManaged public var remoteId: String?
@NSManaged public var shareURL: String?
@NSManaged public var systemTags: String?
@NSManaged public var tags: String?
}

extension Note {
var title: String {
let noteStructure = NoteContentHelper.structure(of: content)
return title(with: noteStructure.title)
}

private func title(with range: Range<String.Index>?) -> String {
guard let range = range, let content = content else {
return Constants.defaultTitle
}

let result = String(content[range])
return result.droppingPrefix(Constants.titleMarkdownPrefix)
}
}

private struct Constants {
static let defaultTitle = NSLocalizedString("New Note...", comment: "Default title for notes")
static let titleMarkdownPrefix = "# "
}
21 changes: 21 additions & 0 deletions IntentsExtension/Models/SPManagedObject+Intents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// This file contains the required class structure to be able to fetch and use core data files in widgets and intents
// We have collapsed the auto generated core data files into a single file as it is unlikely that the files will need to
// be regenerated. Contained in this file is the generated class files SPManagedObject+CoreDataClass.swift and SPManagedObject+CoreDataProperties.swift

import Foundation
import CoreData

@objc(SPManagedObject)
public class SPManagedObject: NSManagedObject {

}

extension SPManagedObject {

@nonobjc public class func fetchRequest() -> NSFetchRequest<SPManagedObject> {
return NSFetchRequest<SPManagedObject>(entityName: "SPManagedObject")
}

@NSManaged public var ghostData: String?
@NSManaged public var simperiumKey: String
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@
<key>IntentsSupported</key>
<array>
<string>OpenNewNoteIntent</string>
<string>OpenNoteIntent</string>
</array>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.intents-service</string>
<key>NSExtensionPrincipalClass</key>
<string>$(PRODUCT_MODULE_NAME).IntentHandler</string>
</dict>
<key>TeamIDPrefix</key>
<string>$(TeamIdentifierPrefix)</string>
<key>TeamIDPrefix</key>
<string>$(TeamIdentifierPrefix)</string>
</dict>
</plist>
34 changes: 34 additions & 0 deletions IntentsExtension/Tools/ExtensionCoreDataWrapper.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//
// ExtensionCoreDataWrapper.swift
// IntentsExtension
//
// Created by Charlie Scheer on 5/29/24.
// Copyright © 2024 Simperium. All rights reserved.
//

import Foundation
import CoreData

class ExtensionCoreDataWrapper {
private lazy var coreDataManager: CoreDataManager? = {
do {
return try CoreDataManager(storageSettings: StorageSettings(), for: .intents)
} catch {
return nil
}
}()

lazy var resultsController: ExtensionResultsController? = {
guard let coreDataManager else {
return nil
}
return ExtensionResultsController(context: coreDataManager.managedObjectContext)
}()

func context() -> NSManagedObjectContext? {
guard let coreDataManager else {
return nil
}
return coreDataManager.managedObjectContext
}
}
charliescheer marked this conversation as resolved.
Show resolved Hide resolved
68 changes: 68 additions & 0 deletions IntentsExtension/Tools/ExtensionResultsController.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//
// ExtensionResultsController.swift
// IntentsExtension
//
// Created by Charlie Scheer on 5/29/24.
// Copyright © 2024 Simperium. All rights reserved.
//

import Foundation
import CoreData
import SimplenoteSearch
import SimplenoteFoundation

class ExtensionResultsController {

/// Data Controller
///
let managedObjectContext: NSManagedObjectContext

/// Initialization
///
init(context: NSManagedObjectContext) {
self.managedObjectContext = context
}

// MARK: - Notes

/// Fetch notes with given tag and limit
/// If no tag is specified, will fetch notes that are not deleted. If there is no limit specified it will fetch all of the notes
///
func notes(limit: Int = .zero) -> [Note]? {
let request: NSFetchRequest<Note> = fetchRequestForNotes(limit: limit)
return performFetch(from: request)
}

/// Returns note given a simperium key
///
func note(forSimperiumKey key: String) -> Note? {
return notes()?.first { note in
note.simperiumKey == key
}
}

func noteExists(forSimperiumKey key: String) -> Bool {
note(forSimperiumKey: key) != nil
}

private func fetchRequestForNotes(limit: Int = .zero) -> NSFetchRequest<Note> {
let fetchRequest = NSFetchRequest<Note>(entityName: Note.entityName)
fetchRequest.fetchLimit = limit
fetchRequest.sortDescriptors = [NSSortDescriptor.descriptorForNotes(sortMode: .alphabeticallyAscending)]
fetchRequest.predicate = NSPredicate.predicateForNotes(deleted: false)

return fetchRequest
}

// MARK: Fetching

private func performFetch<T: NSManagedObject>(from request: NSFetchRequest<T>) -> [T]? {
do {
let objects = try managedObjectContext.fetch(request)
return objects
} catch {
NSLog("Couldn't fetch objects: %@", error.localizedDescription)
return nil
}
}
}
13 changes: 13 additions & 0 deletions IntentsExtension/Tools/IntentsConstants.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//
// IntentsConstants.swift
// IntentsExtension
//
// Created by Charlie Scheer on 5/29/24.
// Copyright © 2024 Simperium. All rights reserved.
//

import Foundation

struct IntentsConstants {
static let noteIdentifierKey = "OpenNoteIntentHandlerIdentifierKey"
}
27 changes: 27 additions & 0 deletions IntentsExtension/Tools/IntentsError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//
// IntentsError.swift
// IntentsExtension
//
// Created by Charlie Scheer on 5/29/24.
// Copyright © 2024 Simperium. All rights reserved.
//

import Foundation

enum IntentsError: Error {
case couldNotFetchNotes

var title: String {
switch self {
case .couldNotFetchNotes:
return NSLocalizedString("Could not fetch Notes", comment: "Note fetch error title")
}
}

var message: String {
switch self {
case .couldNotFetchNotes:
return NSLocalizedString("Attempt to fetch notes failed. Please try again later.", comment: "Data Fetch error message")
}
}
}
Loading