-
Notifications
You must be signed in to change notification settings - Fork 0
/
dreamwidth-js-img-upload
executable file
·73 lines (61 loc) · 1.92 KB
/
dreamwidth-js-img-upload
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
#!/usr/bin/env node
'use strict';
let cp = require('child_process')
let program = require('commander')
let concat = require('concat-stream')
let fetch = require('node-fetch')
let FormData = require('form-data')
let cli = require('./lib/cli')
let dw = require('./lib/dreamwidth')
let SessionCache = require('./lib/sessioncache')
let mime = function(input) {
let kid = cp.spawnSync('file', ['-b', '--mime-type', '-'], {
input,
timeout: 10 * 1000,
})
if (kid.status !== 0) cli.errx('failed to determine a mime type'
+ (kid.error ? `: ${kid.error}` : ''))
return kid.stdout.toString()
}
program
.usage('[options] < file.jpg')
.option('-u, --res-url', 'print only an image url after the upload')
.parse(process.argv)
let jrn = new dw.Dreamwidth(process.env.dw_login, process.env.dw_password)
let session = new SessionCache(60*60*24*1000, function(reason) {
this.log(`session: obtaining a new one (${reason.message})`)
return jrn.session().then( val => {
return val.ljsession
})
})
session.log = cli.perrx
process.stdin.pipe(concat( input => {
if (!input.length) cli.errx('invalid input')
let form = new FormData()
form.append('files', input, {
// we need to set the content-type explicitly for we provide
// to FormData just a buffer instead of a readable stream (w/
// path, from which FormData would have been able to determine
// content-type by itself)
contentType: mime(input),
})
session.get().then( sid => {
// console.log(sid)
return fetch('https://www.dreamwidth.org/api/v1/file/new', {
method: 'POST',
headers: {
cookie: `ljsession=${encodeURIComponent(sid)}`,
},
body: form,
})
}).then( res => res.json()).then( json => {
if (program.resUrl && json.result && json.result.url) {
console.log(json.result.url)
} else {
console.log(json)
}
if (json.success !== 1) process.exit(1)
}).catch( err => {
cli.errx(err)
})
}))