Skip to content

Commit 743c3c2

Browse files
committed
refactor: ♻️ prepare codebase for potential readwise reader property sync
1 parent 4c786b4 commit 743c3c2

File tree

5 files changed

+75
-24
lines changed

5 files changed

+75
-24
lines changed

Diff for: src/constants/index.ts

+3
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,9 @@ Tags: {{ tags }}
8181
protectFrontmatter: false,
8282
protectedFields: 'connections\nstatus\ntags',
8383
updateFrontmatter: true,
84+
syncPropertiesToReadwise: false,
85+
titleProperty: 'title',
86+
authorProperty: 'author'
8487
};
8588

8689
export const FRONTMATTER_TO_ESCAPE = ['title', 'sanitized_title', 'author', 'authorStr'];

Diff for: src/main.ts

+67-22
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import slugify from '@sindresorhus/slugify';
22
import filenamify from 'filenamify';
33
import { ConfigureOptions, Environment, Template } from 'nunjucks';
4-
import { normalizePath, Plugin, TFile } from 'obsidian';
4+
import { CachedMetadata, normalizePath, Plugin, TFile } from 'obsidian';
55
import spacetime from 'spacetime';
66
import * as YAML from 'yaml';
77

@@ -427,22 +427,22 @@ export default class ReadwiseMirror extends Plugin {
427427

428428
const metadata: ReadwiseMetadata = {
429429
id: user_book_id,
430-
title: title,
430+
title,
431431
sanitized_title: sanitizedTitle,
432-
author: author,
433-
authorStr: authorStr,
434-
document_note: document_note,
435-
summary: summary,
436-
category: category,
437-
num_highlights: num_highlights,
432+
author: authors,
433+
authorStr,
434+
document_note,
435+
summary,
436+
category,
437+
num_highlights,
438438
created: created ? this.formatDate(created) : '',
439439
updated: updated ? this.formatDate(updated) : '',
440440
cover_image_url: cover_image_url.replace('SL200', 'SL500').replace('SY160', 'SY500'),
441441
highlights_url: readwise_url,
442-
highlights: highlights,
442+
highlights,
443443
last_highlight_at: last_highlight_at ? this.formatDate(last_highlight_at) : '',
444-
source_url: source_url,
445-
unique_url: unique_url,
444+
source_url,
445+
unique_url,
446446
tags: this.formatTags(book_tags),
447447
highlight_tags: this.formatTags(highlightTags),
448448
tags_nohash: this.formatTags(book_tags, true, "'"),
@@ -451,12 +451,27 @@ export default class ReadwiseMirror extends Plugin {
451451

452452
// Escape specific fields used in frontmatter
453453
// TODO: Tidy up code. It doesn't make sense to remove the frontmatter markers and then add them back
454-
const frontmatterYaml = YAML.parse(
455-
this.frontMatterTemplate
456-
.render(this.escapeFrontmatter(metadata, FRONTMATTER_TO_ESCAPE))
454+
let frontmatterYaml;
455+
try {
456+
const renderedTemplate = this.frontMatterTemplate.render(
457+
this.escapeFrontmatter(metadata, FRONTMATTER_TO_ESCAPE)
458+
);
459+
const cleanedTemplate = renderedTemplate
457460
.replace(/^---\n/, '')
458-
.replace(/\n---\n*$/, '')
459-
);
461+
.replace(/\n---\n*$/, '');
462+
frontmatterYaml = YAML.parse(cleanedTemplate);
463+
} catch (error) {
464+
if (error instanceof YAML.YAMLParseError) {
465+
console.error('Failed to parse YAML frontmatter:', error.message);
466+
throw new Error(`Invalid YAML frontmatter: ${error.message}`);
467+
} else if (error instanceof Error) {
468+
console.error('Error processing frontmatter template:', error.message);
469+
throw new Error(`Failed to process frontmatter: ${error.message}`);
470+
} else {
471+
console.error('Unknown error processing frontmatter:', error);
472+
throw new Error('Failed to process frontmatter due to unknown error');
473+
}
474+
}
460475
const frontMatterContents = this.settings.frontMatter
461476
? ['---', YAML.stringify(frontmatterYaml, YAML_TOSTRING_OPTIONS), '---'].join('\n')
462477
: '';
@@ -714,19 +729,42 @@ export default class ReadwiseMirror extends Plugin {
714729
this.notify.setStatusBarText(`Readwise: Updated ${this.lastUpdatedHumanReadableFormat()} elsewhere`);
715730
}
716731

717-
public ensureDedupPropertyInTemplate(template: string): string {
718-
if (!this.settings.trackFiles) return template;
719-
720-
const propertyName = this.settings.trackingProperty;
721-
const propertyValue = `${propertyName}: {{ highlights_url }}`;
722-
732+
public addSyncPropertiesToFrontmatterTemplate(template: string): string {
723733
const lines = template.split('\n');
724734
const frontmatterStart = lines.findIndex((line) => line.trim() === '---');
725735
const frontmatterEnd =
726736
lines.slice(frontmatterStart + 1).findIndex((line) => line.trim() === '---') + frontmatterStart + 1;
727737

728738
if (frontmatterStart === -1 || frontmatterEnd <= frontmatterStart) return template;
729739

740+
const propertiesToAdd: string[] = [];
741+
742+
// Add tracking property if enabled
743+
if (this.settings.trackFiles) {
744+
console.warn('Adding tracking property to frontmatter template');
745+
const trackingProperty = `${this.settings.trackingProperty}: {{ highlights_url }}`;
746+
propertiesToAdd.push(trackingProperty);
747+
}
748+
749+
// If no properties to add, return original template
750+
if (propertiesToAdd.length === 0) return template;
751+
752+
// Remove any existing properties
753+
const propertyNames = [
754+
this.settings.trackingProperty,
755+
];
756+
757+
const filteredLines = lines.filter((line, index) => {
758+
if (index < frontmatterStart || index > frontmatterEnd) return true;
759+
return !propertyNames.some(prop => line.trim().startsWith(`${prop}:`));
760+
});
761+
762+
// Add new properties before closing ---
763+
filteredLines.splice(frontmatterEnd, 0, ...propertiesToAdd);
764+
765+
return filteredLines.join('\n');
766+
}
767+
730768
// Update the frontmatter template with the sync properties
731769
public updateFrontmatteTemplate() {
732770
this.frontMatterTemplate = new Template(
@@ -736,6 +774,13 @@ export default class ReadwiseMirror extends Plugin {
736774
true
737775
);
738776
}
777+
778+
// Dedicated function to handle metadata change events
779+
private onMetadataChange(file: TFile) {
780+
const metadata: CachedMetadata = this.app.metadataCache.getFileCache(file);
781+
if (metadata && !this.isSyncing) {
782+
console.log(`Updated metadata cache for file: ${file.path}: ${JSON.stringify(metadata?.frontmatter)}`);
783+
}
739784
}
740785

741786
async onload() {

Diff for: src/models/readwise.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export interface ReadwiseMetadata {
5050
id: number; // book id from Readwise API
5151
title: string;
5252
sanitized_title: string;
53-
author: string;
53+
author: string[];
5454
authorStr: string;
5555
document_note: string;
5656
summary: string;

Diff for: src/models/settings.ts

+3
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,7 @@ export interface PluginSettings {
2323
protectFrontmatter: boolean; // Protect specified frontmatter fields from updates
2424
protectedFields: string; // List of frontmatter fields to protect
2525
updateFrontmatter: boolean; // Allow updating of non-protected frontmatter fields
26+
syncPropertiesToReadwise: boolean; // Sync title/author changes back to Readwise
27+
titleProperty: string; // Frontmatter property for syncing title
28+
authorProperty: string; // Frontmatter property for syncing author
2629
}

Diff for: src/test/sample-data.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export const sampleMetadata: ReadwiseMetadata = {
2525
id: 12345,
2626
title: "My Book:\nA Subtitle's Journey",
2727
sanitized_title: "My Book - A Subtitle's Journey",
28-
author: 'O\'Reilly, Tim & "Doc" Smith',
28+
author: ['O\'Reilly, Tim', '"Doc" Smith'],
2929
authorStr: '[[O\'Reilly, Tim]] and [["Doc" Smith]]',
3030
document_note: 'Line 1\nLine 2\nLine 3: Important!',
3131
summary: 'Contains > and < symbols\nAnd some * wildcards & ampersands',

0 commit comments

Comments
 (0)