Skip to content

Commit

Permalink
chore:add prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
zhaohongxuan committed May 11, 2022
1 parent db20a94 commit 07a1af6
Show file tree
Hide file tree
Showing 13 changed files with 521 additions and 431 deletions.
10 changes: 7 additions & 3 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,25 @@
"parser": "@typescript-eslint/parser",
"env": { "node": true },
"plugins": [
"@typescript-eslint"
"@typescript-eslint","prettier"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
"plugin:@typescript-eslint/recommended",
"prettier"
],
"parserOptions": {
"sourceType": "module"
},
"rules": {
"prettier/prettier": 2, //means error
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": ["error", { "args": "none" }],
"@typescript-eslint/ban-ts-comment": "off",
"no-prototype-builtins": "off",
"@typescript-eslint/no-empty-function": "off"
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-explicit-any": ["off"]

}
}
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
14 changes: 14 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"semi": true,
"trailingComma": "none",
"singleQuote": true,
"printWidth": 80,
"overrides": [
{
"files": "*.ts",
"options": {
"parser": "typescript"
}
}
]
}
152 changes: 86 additions & 66 deletions main.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
import { App, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import {
App,
MarkdownView,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting
} from 'obsidian';
import FileManager from './src/fileManager';
import SyncNotebooks from './src/syncNotebooks';
import * as express from 'express';
import { Server,ServerResponse } from 'http'
import { Server, ServerResponse } from 'http';
import { createProxyMiddleware } from 'http-proxy-middleware';

interface WereadPluginSettings {
Expand All @@ -12,16 +20,20 @@ interface WereadPluginSettings {

const DEFAULT_SETTINGS: WereadPluginSettings = {
cookie: '',
noteLocation: '/Hypothesis/weread/'
}
noteLocation: '/weread/'
};

export default class WereadPlugin extends Plugin {
settings: WereadPluginSettings;
private syncNotebooks: SyncNotebooks;
async onload() {
console.log("load weread plugin")
console.log('load weread plugin');
await this.loadSettings();
const fileManager = new FileManager(this.app.vault, this.app.metadataCache, this.settings.noteLocation);
const fileManager = new FileManager(
this.app.vault,
this.app.metadataCache,
this.settings.noteLocation
);
this.syncNotebooks = new SyncNotebooks(fileManager);
const app = express();

Expand All @@ -34,7 +46,7 @@ export default class WereadPlugin extends Plugin {
name: 'Sync Weread command',
callback: () => {
this.startSync(app);
},
}
});

// This adds a complex command that can check whether the current state of the app allows execution of the command
Expand All @@ -43,7 +55,8 @@ export default class WereadPlugin extends Plugin {
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
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.
Expand All @@ -61,16 +74,16 @@ export default class WereadPlugin extends Plugin {
this.addSettingTab(new WereadSettingTab(this.app, this));
}

async startSync(app:any) {
async startSync(app: any) {
new Notice('start to sync weread notes!');
this.startMiddleServer(app).then(server => {
console.log('Start syncing Weread note...')
this.syncNotebooks.startSync().then(res=>{
this.startMiddleServer(app).then((server) => {
console.log('Start syncing Weread note...');
this.syncNotebooks.startSync().then((res) => {
server.close(() => {
console.log('HTTP server closed ', res, server);
});
new Notice('weread notes sync complete!');
})
});
});
}

Expand All @@ -79,57 +92,64 @@ export default class WereadPlugin extends Plugin {
}

async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}

async saveSettings() {
await this.saveData(this.settings);
}

async startMiddleServer(app: any): Promise<Server> {
const cookie = this.settings.cookie
const cookie = this.settings.cookie;
if (cookie === undefined || cookie == '') {
new Notice("cookie未设置,请填写Cookie")
new Notice('cookie未设置,请填写Cookie');
}
const escapeCookie = this.escapeCookie(cookie)
app.use('/', createProxyMiddleware({
target: 'https://i.weread.qq.com',
changeOrigin: true,
onProxyReq: function (proxyReq, req, res) {

try {
proxyReq.setHeader('Cookie', escapeCookie);
} catch (error) {
new Notice("cookie 设置失败,检查Cookie格式")
}
},
onProxyRes: function (proxyRes, req, res:ServerResponse) {
if(res.statusCode!=200){
new Notice("获取微信读书服务器数据异常!")
const escapeCookie = this.escapeCookie(cookie);
app.use(
'/',
createProxyMiddleware({
target: 'https://i.weread.qq.com',
changeOrigin: true,
onProxyReq: function (proxyReq, req, res) {
try {
proxyReq.setHeader('Cookie', escapeCookie);
} catch (error) {
new Notice('cookie 设置失败,检查Cookie格式');
}
},
onProxyRes: function (proxyRes, req, res: ServerResponse) {
if (res.statusCode != 200) {
new Notice('获取微信读书服务器数据异常!');
}
proxyRes.headers['Access-Control-Allow-Origin'] = '*';
}
proxyRes.headers['Access-Control-Allow-Origin'] = '*';
}
})
})
);
const server = app.listen(8081);
return server
return server;
}

async shutdownMiddleServer(server: Server) {
server.close(() => {
console.log('HTTP server closed')
})
console.log('HTTP server closed');
});
}

escapeCookie(cookie:string): string {
const esacpeCookie = cookie.split(';')
.map(v => {

escapeCookie(cookie: string): string {
const esacpeCookie = cookie
.split(';')
.map((v) => {
const arr = v.split('=');
const decodeCookie = decodeURIComponent(arr[1].trim())
return arr[0] + "=" + encodeURIComponent(decodeCookie)
}).join(";")
console.log("escape cookie:", esacpeCookie)
return esacpeCookie
const decodeCookie = decodeURIComponent(arr[1].trim());
return arr[0] + '=' + encodeURIComponent(decodeCookie);
})
.join(';');
console.log('escape cookie:', esacpeCookie);
return esacpeCookie;
}
}

Expand Down Expand Up @@ -165,29 +185,29 @@ class WereadSettingTab extends PluginSettingTab {
new Setting(containerEl)
.setName('Cookie')
.setDesc('Input you weread Cookies')
.addTextArea(text => text
.setPlaceholder('Input you weread Cookie')
.setValue(this.plugin.settings.cookie)
.onChange(async (value) => {
console.log('New Cookie: ' + value);
this.plugin.settings.cookie = value;
await this.plugin.saveSettings();
}));
.addTextArea((text) =>
text
.setPlaceholder('Input you weread Cookie')
.setValue(this.plugin.settings.cookie)
.onChange(async (value) => {
console.log('New Cookie: ' + value);
this.plugin.settings.cookie = value;
await this.plugin.saveSettings();
})
);

new Setting(containerEl)
.setName('Notes Location')
.setDesc('Your Weread Notes location')
.addTextArea(text => text
.setPlaceholder('Which folder to place your notes')
.setValue(this.plugin.settings.noteLocation)
.onChange(async (value) => {
console.log('Notes Location: ' + value);
this.plugin.settings.noteLocation = value;
await this.plugin.saveSettings();
}));
.addTextArea((text) =>
text
.setPlaceholder('Which folder to place your notes')
.setValue(this.plugin.settings.noteLocation)
.onChange(async (value) => {
console.log('Notes Location: ' + value);
this.plugin.settings.noteLocation = value;
await this.plugin.saveSettings();
})
);
}

}



101 changes: 54 additions & 47 deletions src/api.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,61 @@

import { Notice } from 'obsidian';
import axios from 'axios';
export default class ApiManager {
//will proxy to 'https://i.weread.qq.com';
readonly baseUrl: string = 'http://localhost:8081';

private getHeaders() {
return {
'Host': 'i.weread.qq.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
// 'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Content-Type': 'application/json',
}
}
//will proxy to 'https://i.weread.qq.com';
readonly baseUrl: string = 'http://localhost:8081';

async getNotebooks() {
try {
let noteBooks =[]
const resp = await axios.get(this.baseUrl+'/user/notebooks',{
})
private getHeaders() {
return {
Host: 'i.weread.qq.com',
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
// 'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Content-Type': 'application/json'
};
}

noteBooks = resp.data.books
//todo test code
noteBooks = noteBooks.slice(0, 30)
return noteBooks
} catch (e) {
new Notice('Failed to fetch weread notebooks . Please check your API token and try again.')
}
}
async getNotebookHighlights(bookId:string) {
async getNotebooks() {
try {
let noteBooks = [];
const resp = await axios.get(this.baseUrl + '/user/notebooks', {});

try {
const resp = await axios.get(this.baseUrl+'/book/bookmarklist?bookId='+bookId,{})
return resp.data
} catch (e) {
new Notice('Failed to fetch weread notebook highlights . Please check your API token and try again.')
console.error(e);
}
}
noteBooks = resp.data.books;
//todo test code
noteBooks = noteBooks.slice(0, 30);
return noteBooks;
} catch (e) {
new Notice(
'Failed to fetch weread notebooks . Please check your API token and try again.'
);
}
}
async getNotebookHighlights(bookId: string) {
try {
const resp = await axios.get(
this.baseUrl + '/book/bookmarklist?bookId=' + bookId,
{}
);
return resp.data;
} catch (e) {
new Notice(
'Failed to fetch weread notebook highlights . Please check your API token and try again.'
);
console.error(e);
}
}

async getNotebookReviews(bookId:string){
try {
const requestUrl = `${this.baseUrl}/review/list?bookId=${bookId}&listType=11&mine=1&synckey=0`
const resp = await axios.get(requestUrl)
return resp.data
} catch (e) {
new Notice('Failed to fetch weread notebook reviews . Please check your API token and try again.')
console.error(e);
}
}
}
async getNotebookReviews(bookId: string) {
try {
const requestUrl = `${this.baseUrl}/review/list?bookId=${bookId}&listType=11&mine=1&synckey=0`;
const resp = await axios.get(requestUrl);
return resp.data;
} catch (e) {
new Notice(
'Failed to fetch weread notebook reviews . Please check your API token and try again.'
);
console.error(e);
}
}
}
Loading

0 comments on commit 07a1af6

Please sign in to comment.