This commit is contained in:
Pallab91 2025-02-28 01:25:26 +05:30
parent 6d09ce3e39
commit a2fbc15948
1 changed files with 178 additions and 121 deletions

233
main.ts
View File

@ -1,85 +1,120 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian'; import { Plugin, PluginSettingTab, Setting, Notice, App } from "obsidian";
// Remember to rename these classes and interfaces! interface GitHubSyncSettings {
repoOwner: string;
interface MyPluginSettings { repoName: string;
mySetting: string; branch: string;
authToken: string;
folderPath: string;
} }
const DEFAULT_SETTINGS: MyPluginSettings = { const DEFAULT_SETTINGS: GitHubSyncSettings = {
mySetting: 'default' repoOwner: "",
} repoName: "",
branch: "main",
authToken: "",
folderPath: "/",
};
export default class MyPlugin extends Plugin { export default class GitHubSyncPlugin extends Plugin {
settings: MyPluginSettings; settings: GitHubSyncSettings;
async onload() { async onload() {
await this.loadSettings(); await this.loadSettings();
this.addSettingTab(new GitHubSyncSettingTab(this.app, this));
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => {
// Called when the user clicks the icon.
new Notice('This is a notice!');
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText('Status Bar Text');
// This adds a simple command that can be triggered anywhere
this.addCommand({ this.addCommand({
id: 'open-sample-modal-simple', id: "github-pull",
name: 'Open sample modal (simple)', name: "Pull from GitHub",
callback: () => { callback: () => this.pullFromGitHub(),
new SampleModal(this.app).open();
}
}); });
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({ this.addCommand({
id: 'sample-editor-command', id: "github-add-commit-push",
name: 'Sample editor command', name: "Commit & Push",
editorCallback: (editor: Editor, view: MarkdownView) => { callback: () => this.commitAndPush(),
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
}); });
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
} }
// This command will only show up in Command Palette when the check function returns true async pullFromGitHub() {
return true; try {
const response = await fetch(
`https://api.github.com/repos/${this.settings.repoOwner}/${this.settings.repoName}/contents/${this.settings.folderPath}?ref=${this.settings.branch}`,
{
headers: { Authorization: `token ${this.settings.authToken}` },
}
);
if (!response.ok) throw new Error(`Failed to fetch files: ${response.statusText}`);
const files = await response.json();
for (const file of files) {
if (file.type === "file") {
const contentResponse = await fetch(file.download_url);
const content = await contentResponse.text();
const filePath = `${this.settings.folderPath}/${file.name}`;
await this.app.vault.adapter.write(filePath, content);
} }
} }
});
// This adds a settings tab so the user can configure various aspects of the plugin new Notice("Pull completed successfully!");
this.addSettingTab(new SampleSettingTab(this.app, this)); } catch (error) {
console.error("GitHub Pull Error:", error);
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin) new Notice("GitHub Pull failed. Check console.");
// Using this function will automatically remove the event listener when this plugin is disabled. }
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
} }
onunload() { async commitAndPush() {
try {
const files = await this.app.vault.adapter.list(this.settings.folderPath);
for (const filePath of files.files) {
if (!filePath.startsWith(this.settings.folderPath)) continue;
const content = await this.app.vault.adapter.read(filePath);
const base64Content = btoa(unescape(encodeURIComponent(content)));
// Fetch the existing file metadata (needed for updating a file on GitHub)
const metadataResponse = await fetch(
`https://api.github.com/repos/${this.settings.repoOwner}/${this.settings.repoName}/contents/${filePath}`,
{
headers: {
Authorization: `token ${this.settings.authToken}`,
},
}
);
let sha = "";
if (metadataResponse.ok) {
const metadata = await metadataResponse.json();
sha = metadata.sha; // GitHub requires the SHA of existing files
}
// Commit and push
const response = await fetch(
`https://api.github.com/repos/${this.settings.repoOwner}/${this.settings.repoName}/contents/${filePath}`,
{
method: "PUT",
headers: {
Authorization: `token ${this.settings.authToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
message: "#",
content: base64Content,
branch: this.settings.branch,
sha: sha || undefined, // If file is new, omit SHA
}),
}
);
if (!response.ok) throw new Error(`Failed to commit: ${response.statusText}`);
}
new Notice("Commit & Push successful!");
} catch (error) {
console.error("GitHub Commit & Push Error:", error);
new Notice("Commit & Push failed. Check console.");
}
} }
async loadSettings() { async loadSettings() {
@ -91,43 +126,65 @@ export default class MyPlugin extends Plugin {
} }
} }
class SampleModal extends Modal { class GitHubSyncSettingTab extends PluginSettingTab {
constructor(app: App) { plugin: GitHubSyncPlugin;
super(app);
}
onOpen() { constructor(app: App, plugin: GitHubSyncPlugin) {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin); super(app, plugin);
this.plugin = plugin; this.plugin = plugin;
} }
display(): void { display(): void {
const {containerEl} = this; const { containerEl } = this;
containerEl.empty(); containerEl.empty();
new Setting(containerEl) new Setting(containerEl)
.setName('Setting #1') .setName("GitHub Repository Owner")
.setDesc('It\'s a secret') .setDesc("Enter your GitHub username or organization.")
.addText(text => text .addText(text => text
.setPlaceholder('Enter your secret') .setValue(this.plugin.settings.repoOwner)
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => { .onChange(async (value) => {
this.plugin.settings.mySetting = value; this.plugin.settings.repoOwner = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName("GitHub Repository Name")
.setDesc("Enter your GitHub repository name.")
.addText(text => text
.setValue(this.plugin.settings.repoName)
.onChange(async (value) => {
this.plugin.settings.repoName = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName("Branch Name")
.setDesc("Branch to sync with (default: main).")
.addText(text => text
.setValue(this.plugin.settings.branch)
.onChange(async (value) => {
this.plugin.settings.branch = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName("GitHub Auth Token")
.setDesc("Enter your GitHub authentication token (hidden after input).")
.addText(text => text
.setValue(this.plugin.settings.authToken ? "********" : "")
.onChange(async (value) => {
this.plugin.settings.authToken = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName("Folder Path")
.setDesc("Enter the folder path in the repository to sync with.")
.addText(text => text
.setValue(this.plugin.settings.folderPath)
.onChange(async (value) => {
this.plugin.settings.folderPath = value;
await this.plugin.saveSettings(); await this.plugin.saveSettings();
})); }));
} }