This repository was archived by the owner on May 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.ts
More file actions
203 lines (172 loc) · 4.71 KB
/
main.ts
File metadata and controls
203 lines (172 loc) · 4.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import {
App,
Editor,
MarkdownView,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
request,
} from 'obsidian';
interface PostMediumDraftPluginSettings {
userMediumToken: string;
userName?: string;
userProperName?: string;
userId?: string;
}
const DEFAULT_SETTINGS: PostMediumDraftPluginSettings = {
userMediumToken: '',
}
export default class PostMediumDraftPlugin extends Plugin {
settings: PostMediumDraftPluginSettings;
async publishToMedium(view: MarkdownView) {
if (!view || !view.file) {
new Notice('Failed to post: No file in active view!');
return;
}
if (!this.settings.userMediumToken || !this.settings.userId) {
new Notice('Please check your Medium token');
return;
}
const body = {
"title": view.file.basename,
"content": view.getViewData(),
"contentFormat": "markdown",
"publishStatus": "draft",
}
try {
const reqBody = {
url: `https://api.medium.com/v1/users/${this.settings.userId}/posts`,
method: 'POST',
headers: {
'Authorization': `Bearer ${this.settings.userMediumToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
},
body: JSON.stringify(body),
};
const response = await request(reqBody);
const data = JSON.parse(response);
const message = `Posted Medium draft: ${data.data.url}`;
new Notice(message);
} catch (error) {
new Notice(`Failed to post to Medium: ${error}`);
}
}
async onload() {
await this.loadSettings();
// This creates an icon in the left ribbon.
const ribbonIconPost = this.addRibbonIcon('monitor-up', 'Post Medium draft', (evt: MouseEvent) => {
// Called when the user clicks the icon.
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) {
new Notice('Failed to post: No file in active view!');
return;
}
if (evt.which && evt.which === 1) {
this.publishToMedium(view);
}
});
ribbonIconPost.addClass('post-medium-ribbon-class');
// Add commands
this.addCommand({
id: 'post-medium-draft',
name: 'Send Note',
editorCallback: (_, view: MarkdownView) => {
this.publishToMedium(view);
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingTab(this.app, this));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.checkValidToken(this.settings.userMediumToken);
}
async saveSettings() {
await this.saveData(this.settings);
}
async checkValidToken(token: string) {
try {
const response = await request({
url: 'https://api.medium.com/v1/me',
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
});
const data = JSON.parse(response);
const username = data.data.username;
const properName = data.data.name;
this.settings.userName = username;
this.settings.userProperName = properName;
this.settings.userId = data.data.id;
return {
state: 'success',
data,
};
} catch (error) {
console.error('Error while checking Medium token:', error);
return {
state: 'error',
error,
};
}
}
}
class MetaModal extends Modal {
displayText: string[];
constructor(app: App, texts: string | string[] = 'Hello') {
super(app);
this.displayText = Array.isArray(texts) ? texts : [texts];
}
onOpen() {
const {contentEl} = this;
this.displayText.forEach(element => {
contentEl.createEl('p', {text: element});
});
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SettingTab extends PluginSettingTab {
plugin: PostMediumDraftPlugin;
constructor(app: App, plugin: PostMediumDraftPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Medium service integration token')
.setDesc('Create one in your Medium account settings under: Security and apps > Integration tokens')
.addText(text => text
.setPlaceholder('Enter your token')
.setValue(this.plugin.settings.userMediumToken)
.onChange(async (value) => {
this.plugin.settings.userMediumToken = value;
await this.plugin.saveSettings();
// Check if the token is valid
if (value) {
const result = await this.plugin.checkValidToken(value)
if (result.state === 'success') {
const username = result.data.data.username;
const message = `Token is valid! Username: ${username}`;
new Notice(message);
} else {
const message = `Token is invalid! Error: ${result.error}`;
new Notice(message);
}
}
}));
}
}