Skip to content

Commit

Permalink
feat: apply 1.5.1 feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
studiowebux committed Oct 16, 2024
1 parent 9bd63db commit b13ac5f
Show file tree
Hide file tree
Showing 7 changed files with 130 additions and 42 deletions.
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "spotify-link",
"name": "Spotify Link",
"version": "1.5.1",
"version": "1.5.2",
"minAppVersion": "0.15.0",
"description": "Include the song you're currently listening to in your note.",
"author": "Studio Webux",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "spotify-link",
"version": "1.5.1",
"version": "1.5.2",
"description": "Include the song you're currently listening to in your Obsidian (https://obsidian.md) note",
"main": "main.js",
"scripts": {
Expand Down
1 change: 1 addition & 0 deletions src/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,5 @@ export const DEFAULT_SETTINGS: SpotifyLinkSettings = {
],
defaultDestination: "",
overwrite: false,
autoOpen: false,
};
97 changes: 77 additions & 20 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
Notice,
Plugin,
TFile,
type Vault,
addIcon,
normalizePath,
} from "obsidian";
Expand All @@ -23,6 +24,7 @@ import {
getCurrentlyPlayingTrackAsString,
} from "./api";
import { processCurrentlyPlayingTrack } from "./output";
import { isPath } from "./utils";

export default class SpotifyLinkPlugin extends Plugin {
settings: SpotifyLinkSettings;
Expand All @@ -32,13 +34,35 @@ export default class SpotifyLinkPlugin extends Plugin {
spotifyUrl = "";
statusBar: HTMLElement;

async loadOrGetTemplate(input: string) {
if (!input) return "";
const exists = await this.app.vault.adapter.exists(input, true);
if (exists) {
return this.app.vault.adapter.read(input);
async loadOrGetTemplate(input: string): Promise<string> {
try {
if (!input) return "";
const exists = await this.app.vault.adapter.exists(input, true);
if (exists) {
return this.app.vault.adapter.read(input);
} else {
// Retry adding the .md file extension automatically.
const exists_with_md = await this.app.vault.adapter.exists(
input + ".md",
true,
);
if (exists_with_md) {
return this.app.vault.adapter.read(input + ".md");
}
}

if (isPath(input)) {
new Notice(
"[WARN] Spotify Link Plugin: The provided template looks like a path, if so, the file hasn't been found.",
10000,
);
}

return input; // This is the inline template.
} catch (e) {
new Notice("[ERROR] Spotify Link Plugin: " + e.message, 10000);
return "";
}
return input; // This is the inline template.
}

async saveSettings() {
Expand All @@ -49,6 +73,44 @@ export default class SpotifyLinkPlugin extends Plugin {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}

async autoOpen(filename: string) {
if (this.settings.autoOpen === true) {
try {
await this.app.workspace
.getLeaf()
.openFile(this.app.vault.getAbstractFileByPath(filename) as TFile);
} catch (e) {
new Notice("[ERROR] Spotify Link Plugin: " + e.message, 10000);
}
}
}

async createFolder(vault: Vault, folder: string) {
try {
await vault.createFolder(folder);
} catch (e) {
if (e.message !== "Folder already exists.") {
new Notice("[ERROR] Spotify Link Plugin: " + e.message, 10000);
}
}
}

async overwrite(filename: string, content: string, exists: boolean) {
if (this.settings.overwrite === true) {
try {
await this.app.vault.modify(
this.app.vault.getAbstractFileByPath(filename) as TFile,
content,
);
if (exists) {
new Notice("Spotify Link Plugin: track or episode overwritten.");
}
} catch (e) {
new Notice("[ERROR] Spotify Link Plugin: " + e.message, 10000);
}
}
}

async createFile(parent: string, id: string) {
let content = "";
let track: CurrentlyPlayingTrack | string | null = null;
Expand Down Expand Up @@ -85,24 +147,19 @@ export default class SpotifyLinkPlugin extends Plugin {
const filename = `${normalizePath(
`/${parent}/${(track as CurrentlyPlayingTrack)?.item?.name ?? new Date().toISOString()}`,
).replace(/[:|.]/g, "_")}.md`;
const exists = await this.app.vault.adapter.exists(filename, true);

const exists = await this.app.vault.adapter.exists(filename, true);
const folder = filename.substring(0, filename.lastIndexOf("/"));
try {
await this.createFolder(this.app.vault, folder);
await this.app.vault.create(filename, content);
await this.autoOpen(filename);
} catch (e) {
if (this.settings.overwrite === true) {
try {
await this.app.vault.modify(
this.app.vault.getAbstractFileByPath(filename) as TFile,
content,
);
if (exists) {
new Notice("Spotify Link Plugin: track or episode overwritten.");
}
} catch (e) {
new Notice("[ERROR] Spotify Link Plugin: " + e.message, 3000);
}
}
await this.overwrite(filename, content, exists);
// Auto open the file even if there is an error.
// Probably an already exists as the others should be handle correctly.
await this.autoOpen(filename);
new Notice("[ERROR] Spotify Link Plugin: " + e.message, 10000);
}
}

Expand Down
39 changes: 33 additions & 6 deletions src/settingsTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,19 @@ export default class SettingsTab extends PluginSettingTab {
.createEl("li", { text: "{{ progress_min_sec }}" })
.createEl("li", { text: "{{ timestamp }}" });

divDoc.createEl("p", { text: "Template Selection:" });
divDoc.createEl("p", {
text: "You have two options to specify a template: 'Inline' or 'Path-based'.",
});
divDoc
.createEl("ul")
.createEl("li", {
text: "To use the inline method, simply include your template directly.",
})
.createEl("li", {
text: "For path-based selection, you must reference the Vault. A valid example would be: 'Templates/Spotify/track.md' and the content structure is exactly the same as the inline template.",
});

new Setting(containerEl)
.setName("Template for song")
.setDesc(
Expand Down Expand Up @@ -184,13 +197,27 @@ export default class SettingsTab extends PluginSettingTab {
}),
);

new Setting(containerEl).setName("Allow overwrite").addToggle((toggle) => {
toggle.setValue(this.plugin.settings.overwrite);
toggle.onChange(async (value: boolean) => {
this.plugin.settings.overwrite = value;
await this.plugin.saveSettings();
new Setting(containerEl)
.setName("Allow overwrite")
.setDesc("Overwrite the file if it already exists in the vault.")
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.overwrite);
toggle.onChange(async (value: boolean) => {
this.plugin.settings.overwrite = value;
await this.plugin.saveSettings();
});
});

new Setting(containerEl)
.setName("Auto Open")
.setDesc("Automatically open the newly created file in the active leaf.")
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.autoOpen);
toggle.onChange(async (value: boolean) => {
this.plugin.settings.autoOpen = value;
await this.plugin.saveSettings();
});
});
});

containerEl.createEl("hr");

Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export type SpotifyLinkSettings = {
menu: Array<{ name: string; enabled: boolean; id: string }>;
defaultDestination: string;
overwrite: boolean;
autoOpen: boolean;
};

//
Expand Down
30 changes: 16 additions & 14 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@

export function prepareData(data: { [key: string]: string }) {
return Object.keys(data)
.map(
(key) =>
encodeURIComponent(key) + "=" + encodeURIComponent(data[key])
)
.join("&");
return Object.keys(data)
.map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&");
}

export function millisToMinutesAndSeconds(millis: number) {
const minutes: number = Math.floor(millis / 60000);
const seconds: number = parseInt(((millis % 60000) / 1000).toFixed(0));
if (minutes === 0) {
return (seconds < 10 ? "0" : "") + seconds + "s";
}
return minutes + "m:" + (seconds < 10 ? "0" : "") + seconds + "s";
const minutes: number = Math.floor(millis / 60000);
const seconds: number = parseInt(((millis % 60000) / 1000).toFixed(0));
if (minutes === 0) {
return (seconds < 10 ? "0" : "") + seconds + "s";
}
return minutes + "m:" + (seconds < 10 ? "0" : "") + seconds + "s";
}

export function millisToSeconds(millis: number) {
return (millis / 1000).toFixed(0);
return (millis / 1000).toFixed(0);
}

// Best effort / guessing to try to catch and indicate invalid / not found path
export function isPath(str: string) {
const pathRegex = /^[a-zA-Z0-9_\\/.]+$/;
return Boolean(str.match(pathRegex));
}

0 comments on commit b13ac5f

Please sign in to comment.