Skip to content

Commit

Permalink
🍹 0.4.0, valid image check
Browse files Browse the repository at this point in the history
  • Loading branch information
metowolf committed Nov 14, 2018
1 parent c7e6364 commit 3b0db33
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 59 deletions.
10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
```bash
npm install smms-cli -g
```
or
```bash
yarn global add smms-cli
```

[![asciicast](https://asciinema.org/a/TDoMBDihP9caz0gc3CCYJRdkS.png)](https://asciinema.org/a/TDoMBDihP9caz0gc3CCYJRdkS)

Expand All @@ -28,7 +32,7 @@ Upload a single image
smms dog.png
```

Upload multiple images ([globbing](http://en.wikipedia.org/wiki/Glob_(programming) supported)
Upload multiple images ([globbing](https://www.npmjs.com/package/glob) supported)

```bash
smms "*.jpeg" dog.png
Expand Down Expand Up @@ -68,6 +72,10 @@ smms --version
```bash
npm install smms-cli
```
or
```bash
yarn add smms-cli
```

### API

Expand Down
44 changes: 20 additions & 24 deletions lib/cli.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,25 @@
#!/usr/bin/env node

const Conf = require('conf')
const Table = require('cli-table3')

const fs = require('fs')
const path = require('path')
const util = require('util')
const glob = util.promisify(require('glob'))
const Table = require('cli-table3')
const commander = require('commander')
const config = new Conf()
const smms = require('../')

// preload smms-cli history
const HOME_PATH = process.platform === 'win32' ? 'USERPROFILE' : 'HOME'
const DEFAULT_HISTORY_PATH = `${process.env[HOME_PATH]}/.smms-cli`

// utils
let loadHistory = () => {
try {
let data = fs.readFileSync(DEFAULT_HISTORY_PATH, 'utf8')
data = data.trim()
if (data.length) {
return data.split("\n").map(x => x.split("\t"))
} else {
return []
}
} catch (e) {
return []
}
let history = config.get('history')
if (history === undefined) return []
return history
}

let saveHistory = (smms_history) => {
let data = smms_history.map(x => x.join("\t")).join("\n")
fs.writeFileSync(DEFAULT_HISTORY_PATH, data, 'utf8')
let saveHistory = smms_history => {
config.set('history', smms_history)
}

let collect = (val, arr) => {
Expand Down Expand Up @@ -78,7 +69,7 @@ if (commander.list) {
head: ['datetime', 'filename', 'url']
})
table.push(...smms_history.map(x => {
return [ts2date(x[0]), x[1], x[2]]
return [ts2date(x.timestamp), x.filename, x.url]
}))
console.log(table.toString())
return
Expand All @@ -92,14 +83,14 @@ if (commander.clear) {

if (commander.delete) {
let data = smms_history.find(x => {
return x[2] === commander.delete || x[3] === commander.delete
return x.url === commander.delete || x.hash === commander.delete
})
if (data === undefined) {
console.error(`Sorry, url or hash not found!`)
return
}
smms
.delete(data[3])
.delete(data.hash)
.then((json) => {
console.log(json.msg)
})
Expand All @@ -118,8 +109,13 @@ if (commander.file.length || commander.args.length) {
promises.push(
smms.upload(file)
.then((json) => {
output.push([json.data.filename, json.data.url])
smms_history.push([json.data.timestamp, json.data.filename, json.data.url, json.data.hash])
output.push([path.basename(file), json.data.url])
smms_history.push({
timestamp: json.data.timestamp,
filename: json.data.filename,
url: json.data.url,
hash: json.data.hash
})
})
.catch(err => {
output.push([file, err.msg || err.message])
Expand Down
71 changes: 39 additions & 32 deletions lib/smms.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
const fs = require('fs')
const util = require('util')
const glob = util.promisify(require('glob'))
const path = require('path')
const readChunk = require('read-chunk')
const fileType = require('file-type')
const request = require('request-promise')
const version = require('../package.json').version

const allowExt = ['jpg', 'png', 'gif', 'bmp']

module.exports = {

VERSION: version,
Expand All @@ -24,33 +27,37 @@ module.exports = {
* @param {string} filename - path to a binary image file
* @returns {promise}
*/
upload(filename) {
return glob(filename)
.then(file => {
if (!file.length) {
throw new Error(`Invalid filename`)
}
let formData = {
smfile: fs.createReadStream(filename),
ssl: 1,
format: 'json'
async upload(pathname) {

if (!fs.lstatSync(pathname).isFile()) {
throw new Error(`Invalid path`)
}

let buffer = readChunk.sync(pathname, 0, 4100)
let filetype = fileType(buffer)
if (filetype === null || !allowExt.includes(filetype.ext)) {
throw new Error(`File is not a valid image`)
}

let formData = {
smfile: fs.createReadStream(pathname),
ssl: 1,
format: 'json'
}

let options = {
url: this.api.upload,
formData,
headers: this.headers,
json: true
}

return request.post(options)
.then(response => {
if (response.code !== 'success') {
throw new Error(`${response.code}: ${response.msg}`)
}
return request
.post({
url: this.api.upload,
headers: this.headers,
formData,
json: true
})
.then((json) => {
if (json.code !== 'success') {
throw new Error(json.msg)
}
return json
})
})
.catch(err => {
throw err
return response
})
},

Expand Down Expand Up @@ -80,11 +87,11 @@ module.exports = {
},
json: true
})
.then((json) => {
if (json.code !== 'success') {
throw new Error(json.msg)
.then(response => {
if (response.code !== 'success') {
throw new Error(`${response.code}: ${response.msg}`)
}
return json
return response
})
}

Expand Down
12 changes: 10 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "smms-cli",
"version": "0.3.0",
"version": "0.4.0",
"description": "Upload images to sm.ms",
"main": "lib/smms.js",
"repository": {
Expand All @@ -15,7 +15,10 @@
"dependencies": {
"cli-table3": "^0.5.1",
"commander": "^2.19.0",
"conf": "^2.1.0",
"file-type": "^10.4.0",
"glob": "^7.1.3",
"read-chunk": "^3.0.0",
"request": "^2.88.0",
"request-promise": "^4.2.2"
},
Expand All @@ -24,5 +27,10 @@
},
"bin": {
"smms": "./lib/cli.js"
}
},
"keywords": [
"smms",
"upload",
"images"
]
}
1 change: 1 addition & 0 deletions test/example.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const smms = require('../lib/smms');

console.log(`===> upload image`)
result = await smms.upload('nodejs.png')
console.log(JSON.stringify(result, null, 4))
if (result.code === 'success') {
console.log(`url: ${result.data.url}`)
console.log(`hash: ${result.data.hash}`)
Expand Down

0 comments on commit 3b0db33

Please sign in to comment.