Skip to content

Commit cc6d917

Browse files
committed
Initial commit
0 parents  commit cc6d917

File tree

8 files changed

+665
-0
lines changed

8 files changed

+665
-0
lines changed

LICENSE

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright 2020 HackMD
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# HackMD API Clients
2+
3+
## Node.JS
4+
5+
See [README](./nodejs)
6+
7+
## LICENSE
8+
9+
MIT

nodejs/.gitignore

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Logs
2+
logs
3+
*.log
4+
npm-debug.log*
5+
yarn-debug.log*
6+
yarn-error.log*
7+
lerna-debug.log*
8+
9+
# Diagnostic reports (https://nodejs.org/api/report.html)
10+
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11+
12+
# Runtime data
13+
pids
14+
*.pid
15+
*.seed
16+
*.pid.lock
17+
18+
# Directory for instrumented libs generated by jscoverage/JSCover
19+
lib-cov
20+
21+
# Coverage directory used by tools like istanbul
22+
coverage
23+
*.lcov
24+
25+
# nyc test coverage
26+
.nyc_output
27+
28+
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29+
.grunt
30+
31+
# Bower dependency directory (https://bower.io/)
32+
bower_components
33+
34+
# node-waf configuration
35+
.lock-wscript
36+
37+
# Compiled binary addons (https://nodejs.org/api/addons.html)
38+
build/Release
39+
40+
# Dependency directories
41+
node_modules/
42+
jspm_packages/
43+
44+
# Snowpack dependency directory (https://snowpack.dev/)
45+
web_modules/
46+
47+
# TypeScript cache
48+
*.tsbuildinfo
49+
50+
# Optional npm cache directory
51+
.npm
52+
53+
# Optional eslint cache
54+
.eslintcache
55+
56+
# Microbundle cache
57+
.rpt2_cache/
58+
.rts2_cache_cjs/
59+
.rts2_cache_es/
60+
.rts2_cache_umd/
61+
62+
# Optional REPL history
63+
.node_repl_history
64+
65+
# Output of 'npm pack'
66+
*.tgz
67+
68+
# Yarn Integrity file
69+
.yarn-integrity
70+
71+
# dotenv environment variables file
72+
.env
73+
.env.test
74+
75+
# parcel-bundler cache (https://parceljs.org/)
76+
.cache
77+
.parcel-cache
78+
79+
# Next.js build output
80+
.next
81+
82+
# Nuxt.js build / generate output
83+
.nuxt
84+
dist
85+
86+
# Gatsby files
87+
.cache/
88+
# Comment in the public line in if your project uses Gatsby and not Next.js
89+
# https://nextjs.org/blog/next-9-1#public-directory-support
90+
# public
91+
92+
# vuepress build output
93+
.vuepress/dist
94+
95+
# Serverless directories
96+
.serverless/
97+
98+
# FuseBox cache
99+
.fusebox/
100+
101+
# DynamoDB Local files
102+
.dynamodb/
103+
104+
# TernJS port file
105+
.tern-port
106+
107+
# Stores VSCode versions used for testing VSCode extensions
108+
.vscode-test
109+
110+
# yarn v2
111+
112+
.yarn/cache
113+
.yarn/unplugged
114+
.yarn/build-state.yml
115+
.pnp.*

nodejs/README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# HackMD Node.js API Client
2+
3+
## Installation
4+
5+
```bash
6+
npm install @hackmd/api --save
7+
```
8+
9+
## Usage
10+
11+
TODO

nodejs/package.json

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
{
2+
"name": "@hackmd/api",
3+
"version": "0.0.1",
4+
"description": "HackMD/CodiMD Node.js API Client",
5+
"main": "dist/index.js",
6+
"scripts": {
7+
"build": "tsc -d",
8+
"prepublishOnly": "npm run build"
9+
},
10+
"keywords": [
11+
"HackMD",
12+
"API Client"
13+
],
14+
"files": [
15+
"dist/*",
16+
"README.md",
17+
"LICENSE"
18+
],
19+
"author": "",
20+
"license": "ISC",
21+
"devDependencies": {
22+
"@types/cheerio": "^0.22.17",
23+
"@types/fs-extra": "^8.1.0",
24+
"@types/node": "^13.11.1",
25+
"@types/node-fetch": "^2.5.6",
26+
"@types/tough-cookie": "^4.0.0",
27+
"@types/tough-cookie-filestore": "^0.0.0",
28+
"typescript": "^3.8.3"
29+
},
30+
"dependencies": {
31+
"cheerio": "^1.0.0-rc.3",
32+
"fetch-cookie": "^0.8.0",
33+
"fs-extra": "^9.0.0",
34+
"node-fetch": "^2.6.0",
35+
"tough-cookie": "^4.0.0",
36+
"tough-cookie-filestore": "^0.0.1",
37+
"tslib": "^1.11.1"
38+
}
39+
}

nodejs/src/index.ts

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
import cheerio from 'cheerio'
2+
import * as fs from 'fs-extra'
3+
import nodeFetch from 'node-fetch'
4+
import tough = require('tough-cookie')
5+
import FileCookieStore from 'tough-cookie-filestore'
6+
import * as url from 'url'
7+
8+
interface APIOptions {
9+
serverUrl: string
10+
cookiePath: string,
11+
enterprise: boolean
12+
}
13+
14+
type nodeFetchType = (url: RequestInfo, init?: RequestInit | undefined) => Promise<Response>
15+
16+
function encodeFormComponent(form: object) {
17+
return Object.entries(form).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&')
18+
}
19+
20+
export enum ExportType {
21+
PDF,
22+
SLIDE,
23+
MD,
24+
HTML
25+
}
26+
27+
export type HistoryItem = {
28+
id: string
29+
text: string
30+
time: number | string
31+
tags: string[]
32+
}
33+
34+
/**
35+
* codimd API Client
36+
*/
37+
class API {
38+
public readonly serverUrl: string
39+
private readonly enterprise: boolean
40+
private readonly _fetch: nodeFetchType
41+
42+
constructor(config: APIOptions) {
43+
const {serverUrl, cookiePath, enterprise} = config
44+
45+
fs.ensureFileSync(cookiePath)
46+
47+
const jar = new FileCookieStore(cookiePath)
48+
const fetch: nodeFetchType = require('fetch-cookie')(nodeFetch, new tough.CookieJar(jar as any))
49+
50+
this._fetch = fetch
51+
this.serverUrl = serverUrl
52+
this.enterprise = enterprise
53+
}
54+
55+
async login(email: string, password: string) {
56+
const response = await this.fetch(`${this.serverUrl}/login`, {
57+
method: 'post',
58+
body: encodeFormComponent({email, password}),
59+
headers: await this.wrapHeaders({
60+
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
61+
})
62+
})
63+
64+
return response.status === 200
65+
}
66+
67+
async loginLdap(username: string, password: string) {
68+
const response = await this.fetch(`${this.serverUrl}/auth/ldap`, {
69+
method: 'post',
70+
body: encodeFormComponent({username, password}),
71+
headers: await this.wrapHeaders({
72+
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
73+
})
74+
})
75+
return response.status === 200
76+
}
77+
78+
async logout() {
79+
const response = await this.fetch(`${this.serverUrl}/logout`, {
80+
method: this.enterprise ? 'POST' : 'GET',
81+
headers: await this.wrapHeaders({
82+
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
83+
})
84+
})
85+
return response.status === 200
86+
}
87+
88+
async isLogin() {
89+
const response = await this.fetch(`${this.serverUrl}/me`)
90+
return response.status === 200
91+
}
92+
93+
async getMe() {
94+
const response = await this.fetch(`${this.serverUrl}/me`)
95+
return response.json()
96+
}
97+
98+
async getHistory(): Promise<{ history: HistoryItem[] }> {
99+
const response = await this.fetch(`${this.serverUrl}/history`)
100+
return response.json()
101+
}
102+
103+
async newNote(body: string) {
104+
let response
105+
if (this.enterprise) {
106+
response = await this.fetch(`${this.serverUrl}/new`, {
107+
method: 'POST',
108+
body: encodeFormComponent({content: body}),
109+
headers: await this.wrapHeaders({
110+
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
111+
})
112+
})
113+
} else {
114+
const contentType = 'text/markdown;charset=UTF-8'
115+
response = await this.fetch(`${this.serverUrl}/new`, {
116+
method: 'POST',
117+
body,
118+
headers: {
119+
'Content-Type': contentType
120+
}
121+
})
122+
}
123+
124+
if (response.status === 200) {
125+
return response.url
126+
} else {
127+
throw new Error('Create note failed')
128+
}
129+
}
130+
131+
async export(noteId: string, type: ExportType, output: string) {
132+
let res: Response
133+
switch (type) {
134+
case ExportType.PDF:
135+
res = await this.fetch(`${this.serverUrl}/${noteId}/pdf`)
136+
break
137+
case ExportType.HTML:
138+
res = await this.fetch(`${this.serverUrl}/s/${noteId}`)
139+
break
140+
case ExportType.SLIDE:
141+
res = await this.fetch(`${this.serverUrl}/${noteId}/slide`)
142+
break
143+
case ExportType.MD:
144+
default:
145+
res = await this.fetch(`${this.serverUrl}/${noteId}/download`)
146+
}
147+
148+
return this.downloadFile(res, output)
149+
}
150+
151+
private async downloadFile(res: any, output: string) {
152+
const fileStream = fs.createWriteStream(output)
153+
154+
await new Promise((resolve, reject) => {
155+
res.body.pipe(fileStream)
156+
res.body.on('error', (err: any) => {
157+
reject(err)
158+
})
159+
fileStream.on('finish', function () {
160+
resolve()
161+
})
162+
})
163+
}
164+
165+
get fetch() {
166+
return this._fetch
167+
}
168+
169+
get domain() {
170+
return url.parse(this.serverUrl).host
171+
}
172+
173+
private async wrapHeaders(headers: any) {
174+
if (this.enterprise) {
175+
const csrf = await this.loadCSRFToken()
176+
return {
177+
...headers,
178+
'X-XSRF-Token': csrf
179+
}
180+
} else {
181+
return headers
182+
}
183+
}
184+
185+
private async loadCSRFToken() {
186+
const html = await this.fetch(`${this.serverUrl}`).then(r => r.text())
187+
const $ = cheerio.load(html)
188+
189+
return $('meta[name="csrf-token"]').attr('content') || ''
190+
}
191+
}
192+
193+
export default API

nodejs/tsconfig.json

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"compilerOptions": {
3+
"declaration": true,
4+
"importHelpers": true,
5+
"module": "commonjs",
6+
"outDir": "dist",
7+
"rootDir": "src",
8+
"strict": true,
9+
"target": "es2017",
10+
"esModuleInterop": true
11+
},
12+
"include": [
13+
"src/**/*"
14+
]
15+
}

0 commit comments

Comments
 (0)