generated from obsidianmd/obsidian-sample-plugin
-
Couldn't load subscription status.
- Fork 153
Apple Notes importer Improvement for One-way Sync #394
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
Open
jykim
wants to merge
9
commits into
obsidianmd:master
Choose a base branch
from
jykim:apple-notes-skip-duplicates
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
7afbc1a
Add option to skip duplicate notes in Apple Notes importer
jykim 696ebd6
chore: update TypeScript configuration to support ES2019 features
jykim 8a5d745
Add file prefix format option in Apple Notes importer
jykim d0b7cbe
Revert "chore: update TypeScript configuration to support ES2019 feat…
jykim 20195e8
Implemented options to skip numeric suffixes for duplicate file names…
jykim 1ad2259
Enhance Apple Notes importer with duplicate handling options
jykim 24737df
Remove deploy.sh script
jykim 7e1804d
Update Apple Notes importer to use moment.js for date formatting and …
jykim 3e7535d
Add file prefix format persistence in Apple Notes importer
jykim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| import { Notice, Platform, Setting, TFile, TFolder } from 'obsidian'; | ||
| import { Notice, Platform, Setting, TFile, TFolder, moment } from 'obsidian'; | ||
| import { NoteConverter } from './apple-notes/convert-note'; | ||
| import { ANAccount, ANAttachment, ANConverter, ANConverterType, ANFolderType } from './apple-notes/models'; | ||
| import { descriptor } from './apple-notes/descriptor'; | ||
|
|
@@ -14,6 +14,13 @@ const NOTE_FOLDER_PATH = 'Library/Group Containers/group.com.apple.notes'; | |
| const NOTE_DB = 'NoteStore.sqlite'; | ||
| /** Additional amount of seconds that Apple CoreTime datatypes start at, to convert them into Unix timestamps. */ | ||
| const CORETIME_OFFSET = 978307200; | ||
| const LOCAL_STORAGE_KEY = 'apple-notes-importer-file-prefix'; | ||
|
|
||
| enum DuplicateHandling { | ||
| Skip = 'skip', | ||
| ImportUpdated = 'import-updated', | ||
| CreateCopy = 'create-copy' | ||
| } | ||
|
|
||
| export class AppleNotesImporter extends FormatImporter { | ||
| ctx: ImportContext; | ||
|
|
@@ -35,7 +42,9 @@ export class AppleNotesImporter extends FormatImporter { | |
| omitFirstLine = true; | ||
| importTrashed = false; | ||
| includeHandwriting = false; | ||
| duplicateHandling = DuplicateHandling.ImportUpdated; | ||
| trashFolders: number[] = []; | ||
| filePrefixFormat = ''; | ||
|
|
||
| init(): void { | ||
| if (!Platform.isMacOS || !Platform.isDesktop) { | ||
|
|
@@ -50,6 +59,25 @@ export class AppleNotesImporter extends FormatImporter { | |
|
|
||
| this.addOutputLocationSetting('Apple Notes'); | ||
|
|
||
| // Retrieve stored file prefix format | ||
| const storedPrefix = localStorage.getItem(LOCAL_STORAGE_KEY) || ''; | ||
| this.filePrefixFormat = storedPrefix; | ||
|
|
||
| new Setting(this.modal.contentEl) | ||
| .setName('File prefix format') | ||
| .setDesc( | ||
| 'Format for the date prefix in filenames. Use YYYY, MM, DD for year, month, day.' + | ||
| ' Leave blank for no prefix.' | ||
| ) | ||
| .addText(t => t | ||
| .setValue(storedPrefix) | ||
| .setPlaceholder('YYYY-MM-DD') | ||
| .onChange(async v => { | ||
| this.filePrefixFormat = v; | ||
| localStorage.setItem(LOCAL_STORAGE_KEY, v); | ||
| }) | ||
| ); | ||
|
|
||
| new Setting(this.modal.contentEl) | ||
| .setName('Import recently deleted notes') | ||
| .setDesc( | ||
|
|
@@ -81,6 +109,19 @@ export class AppleNotesImporter extends FormatImporter { | |
| .setValue(false) | ||
| .onChange(async v => this.includeHandwriting = v) | ||
| ); | ||
|
|
||
| new Setting(this.modal.contentEl) | ||
| .setName('Handle duplicate files') | ||
| .setDesc( | ||
| 'How to handle notes that already exist in the vault.' | ||
| ) | ||
| .addDropdown(d => d | ||
| .addOption(DuplicateHandling.Skip, 'Skip import') | ||
| .addOption(DuplicateHandling.ImportUpdated, 'Import only updated') | ||
| .addOption(DuplicateHandling.CreateCopy, 'Create a copy') | ||
| .setValue(DuplicateHandling.ImportUpdated) | ||
| .onChange(async v => this.duplicateHandling = v as DuplicateHandling) | ||
| ); | ||
| } | ||
|
|
||
| async getNotesDatabase(): Promise<SQLiteTagSpawned | null> { | ||
|
|
@@ -251,8 +292,39 @@ export class AppleNotesImporter extends FormatImporter { | |
|
|
||
| const folder = this.resolvedFolders[row.ZFOLDER] || this.rootFolder; | ||
|
|
||
| const title = `${row.ZTITLE1}.md`; | ||
| const file = await this.saveAsMarkdownFile(folder, title, ''); | ||
| // Get creation date and format it according to user preference | ||
| let title = row.ZTITLE1; | ||
| if (this.filePrefixFormat) { | ||
| const creationTimestamp = this.decodeTime(row.ZCREATIONDATE3 || row.ZCREATIONDATE2 || row.ZCREATIONDATE1); | ||
| const datePrefix = moment(creationTimestamp).format(this.filePrefixFormat); | ||
| title = `${datePrefix} ${title}`; | ||
| } | ||
|
|
||
| const fullPath = path.join(folder.path, `${title}.md`); | ||
|
|
||
| // Check for duplicate notes based on the selected handling option | ||
| const existingFile = this.vault.getAbstractFileByPath(fullPath); | ||
|
|
||
| if (existingFile && existingFile instanceof TFile) { | ||
| if (this.duplicateHandling === DuplicateHandling.Skip) { | ||
| this.ctx.reportSkipped(row.ZTITLE1, 'note is a duplicate'); | ||
| return existingFile; | ||
| } else if (this.duplicateHandling === DuplicateHandling.ImportUpdated) { | ||
| // Check modification times before skipping | ||
| const appleNoteModTime = this.decodeTime(row.ZMODIFICATIONDATE1); | ||
| const existingFileModTime = existingFile.stat.mtime; | ||
|
|
||
| // Only skip if the Apple Note hasn't been modified since the existing file | ||
| if (appleNoteModTime <= existingFileModTime) { | ||
| this.ctx.reportSkipped(row.ZTITLE1, 'note unchanged since last import'); | ||
| return existingFile; | ||
| } | ||
| // If Apple Note is newer, continue with import (will overwrite) | ||
| } | ||
| // For CreateCopy option, we continue without skipping (will create numbered copy) | ||
| } | ||
|
|
||
| const file = await this.saveAsMarkdownFile(folder, `${title}.md`, ''); | ||
|
|
||
| this.ctx.status(`Importing note ${title}`); | ||
| this.resolvedFiles[id] = file; | ||
|
|
@@ -268,6 +340,7 @@ export class AppleNotesImporter extends FormatImporter { | |
|
|
||
| this.parsedNotes++; | ||
| this.ctx.reportProgress(this.parsedNotes, this.noteCount); | ||
| this.ctx.reportNoteSuccess(title); | ||
| return file; | ||
| } | ||
|
|
||
|
|
@@ -352,9 +425,39 @@ export class AppleNotesImporter extends FormatImporter { | |
| break; | ||
| } | ||
|
|
||
| // Apply date prefix to attachment name if configured | ||
| let finalAttachmentName = outName; | ||
| if (this.filePrefixFormat && row.ZCREATIONDATE) { | ||
| const creationTimestamp = this.decodeTime(row.ZCREATIONDATE); | ||
| const datePrefix = moment(creationTimestamp).format(this.filePrefixFormat); | ||
| finalAttachmentName = `${datePrefix} ${outName}`; | ||
| } | ||
|
|
||
| // Check for existing attachment based on the selected handling option | ||
| const attachmentPath = await this.getAvailablePathForAttachment(`${finalAttachmentName}.${outExt}`, []); | ||
| const existingAttachment = this.vault.getAbstractFileByPath(attachmentPath); | ||
|
|
||
| if (existingAttachment && existingAttachment instanceof TFile) { | ||
| if (this.duplicateHandling === DuplicateHandling.Skip) { | ||
| this.ctx.reportSkipped(finalAttachmentName, 'attachment already exists'); | ||
| return existingAttachment; | ||
| } else if (this.duplicateHandling === DuplicateHandling.ImportUpdated) { | ||
| // Check modification times for attachments | ||
| const appleAttachmentModTime = this.decodeTime(row.ZMODIFICATIONDATE); | ||
| const existingAttachmentModTime = existingAttachment.stat.mtime; | ||
|
|
||
| if (appleAttachmentModTime <= existingAttachmentModTime) { | ||
| this.ctx.reportSkipped(finalAttachmentName, 'attachment unchanged since last import'); | ||
| return existingAttachment; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this be returning null? |
||
| } | ||
| // If Apple attachment is newer, continue with import (will overwrite) | ||
| } | ||
| // For CreateCopy option, we continue without skipping (will create numbered copy) | ||
| } | ||
|
|
||
| try { | ||
| const binary = await this.getAttachmentSource(this.resolvedAccounts[this.owners[row.ZNOTE]], sourcePath); | ||
| const attachmentPath = await this.getAvailablePathForAttachment(`${outName}.${outExt}`, []); | ||
| const attachmentPath = await this.getAvailablePathForAttachment(`${finalAttachmentName}.${outExt}`, []); | ||
|
|
||
| file = await this.vault.createBinary( | ||
| attachmentPath, binary, | ||
|
|
@@ -368,7 +471,7 @@ export class AppleNotesImporter extends FormatImporter { | |
| } | ||
|
|
||
| this.resolvedFiles[id] = file; | ||
| this.ctx.reportAttachmentSuccess(this.resolvedFiles[id].path); | ||
| this.ctx.reportAttachmentSuccess(`${finalAttachmentName}.${outExt}`); | ||
| return file; | ||
| } | ||
|
|
||
|
|
@@ -391,4 +494,21 @@ export class AppleNotesImporter extends FormatImporter { | |
| return await fsPromises.readFile(path.join(os.homedir(), NOTE_FOLDER_PATH, sourcePath)); | ||
| } | ||
| } | ||
|
|
||
| async saveAsMarkdownFile(folder: TFolder, title: string, content: string): Promise<TFile> { | ||
| if (this.duplicateHandling === DuplicateHandling.Skip || this.duplicateHandling === DuplicateHandling.ImportUpdated) { | ||
| // For Skip and ImportUpdated, create the file directly without numeric suffix | ||
| const sanitizedName = sanitizeFileName(title); | ||
| const fullPath = path.join(folder.path, sanitizedName); | ||
|
|
||
| // Check if file already exists and handle overwriting | ||
| const existingFile = this.vault.getAbstractFileByPath(fullPath); | ||
| if (existingFile && existingFile instanceof TFile) { | ||
| // File exists -- will be updated later in resolveNote | ||
| return existingFile; | ||
tgrosinger marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
| // For CreateCopy option, use the default behavior from FormatImporter (creates numbered copies) | ||
| return super.saveAsMarkdownFile(folder, title, content); | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this be returning null?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This comment was missed.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually it seems like maybe the
return nullbelow should not be returning null? Because these cases are successful, they just don't need to do anything. So we don't want the caller of this function to think this was unsuccessful.