Skip to content

Commit

Permalink
done image uploaders
Browse files Browse the repository at this point in the history
  • Loading branch information
shd101wyy committed Jun 15, 2017
1 parent 1b2788e commit 15f1fa4
Show file tree
Hide file tree
Showing 7 changed files with 93 additions and 71 deletions.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,7 @@
"dependencies": {
"cheerio": "0.15.0",
"gray-matter": "^2.1.1",
"imgur": "^0.2.1",
"request": "^2.76.0",
"request": "^2.81.0",
"temp": "^0.8.3",
"uslug": "^1.0.4"
},
Expand Down
28 changes: 0 additions & 28 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,34 +176,6 @@ export function activate(context: vscode.ExtensionContext) {


/*
function openPreviewAutomatically(textEditor:vscode.TextEditor) {
if (!textEditor) return
if (isMarkdownFile(textEditor.document)) {
const automaticallyShowPreviewOfMarkdownBeingEdited = vscode.workspace.getConfiguration('markdown-preview-enhanced')
.get<boolean>("automaticallyShowPreviewOfMarkdownBeingEdited")
if (!automaticallyShowPreviewOfMarkdownBeingEdited) return
const previewUri = getMarkdownUri(textEditor.document.uri);
return vscode.commands.executeCommand(
'vscode.previewHtml',
previewUri,
vscode.ViewColumn.Two,
`Preview '${path.basename(textEditor.document.uri.fsPath)}'`)
.then((success)=> {
}, (reason)=> {
vscode.window.showErrorMessage(reason)
})
}
}
openPreviewAutomatically(vscode.window.activeTextEditor) // first time
context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor((textEditor)=> {
openPreviewAutomatically(textEditor)
}))
context.subscriptions.push(vscode.window.onDidChangeVisibleTextEditors(textEditors=> {
// console.log('onDidChangeonDidChangeVisibleTextEditors ', textEditors)
}))
Expand Down
26 changes: 13 additions & 13 deletions src/image-helper.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import * as vscode from "vscode"
import * as path from "path"
import * as fs from "fs"
import * as imgur from "imgur"

import {isMarkdownFile} from "./markdown-preview-enhanced-view"
import * as utility from "./utility"
import * as smAPI from "./sm"
import * as imgurAPI from "./imgur"

/**
* Copy ans paste image at imageFilePath to config.imageForlderPath.
Expand Down Expand Up @@ -139,22 +139,22 @@ export function uploadImageFile(sourceUri: any, imageFilePath: string, imageUplo

if (imageUploader === 'imgur') {
// A single image
imgur.uploadFile(imageFilePath)
.then((json)=> {
setUploadedImageURL(imageFileName, json.data.link, editor, hint, curPos)
imgurAPI.uploadFile(imageFilePath)
.then((url)=> {
setUploadedImageURL(imageFileName, url, editor, hint, curPos)
})
.catch((err)=> {
utility.showErrorMessage(err.message.message)
utility.showErrorMessage(err)
})
} else { // sm.ms
smAPI.uploadFile(imageFilePath,
(err, url)=> {
if (err)
return utility.showErrorMessage(err)
else
setUploadedImageURL(imageFileName, url, editor, hint, curPos)
smAPI.uploadFile(imageFilePath)
.then((url)=> {
setUploadedImageURL(imageFileName, url, editor, hint, curPos)
})
.catch((err)=> {
utility.showErrorMessage(err)
})
}

})
}
}

48 changes: 48 additions & 0 deletions src/imgur.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// imgur api
// referenced from node-imgur:
// https://github.com/kaimallea/node-imgur/blob/master/lib/imgur.js
import * as request from "request"
import * as fs from "fs"
import * as path from "path"

// The following client ID is tied to the
// registered 'node-imgur' app and is available
// here for public, anonymous usage via this node
// module only.
const IMGUR_API_URL = process.env.IMGUR_API_URL || 'https://api.imgur.com/3/';
const IMGUR_CLIENT_ID = process.env.IMGUR_CLIENT_ID || 'f0ea04148a54268';

export function uploadFile(filePath):Promise<string> {
return new Promise((resolve, reject)=> {
const headers = {
Authorization: `Client-ID ${IMGUR_CLIENT_ID}`
}

request.post({
url: `${IMGUR_API_URL}image`,
encoding: 'utf8',
formData: {image: fs.createReadStream(filePath)},
json: true,
headers
},
(err, httpResponse, body)=> {
if (err) {
return reject(err)
}
if (body.success) {
return resolve(body.data.link)
} else {
return resolve(body.data.error.message)
}
})
})
}

/*
uploadFile('/Users/wangyiyi/Desktop/markdown-example/test.jpg')
.then((url)=> {
...
}).then((error)=> {
...
})
*/
7 changes: 5 additions & 2 deletions src/markdown-preview-enhanced-webview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ interface MarkdownConfig {

previewTheme?: string,

imageFolderPath?: string
imageFolderPath?: string,
imageUploader?: string
}

/**
Expand Down Expand Up @@ -347,12 +348,14 @@ function initImageHelper() {
const copyLabel = imageHelper.getElementsByClassName('copy-label')[0] as HTMLLabelElement
copyLabel.innerText = `Copy image to ${config.imageFolderPath[0] == '/' ? 'root' : 'relative'} ${config.imageFolderPath} folder`

const imageUploaderSelect = imageHelper.getElementsByClassName('uploader-select')[0] as HTMLSelectElement
imageUploaderSelect.value = config.imageUploader

// drop area has 2 events:
// 1. paste(copy) image to imageFolderPath
// 2. upload image
const dropArea = window['$']('.drop-area', imageHelper)
const fileUploader = window['$']('.file-uploader', imageHelper)
const imageUploaderSelect = imageHelper.getElementsByClassName('uploader-select')[0] as HTMLSelectElement
dropArea.on('drop dragend dragstart dragenter dragleave drag dragover', (e)=> {
e.preventDefault()
e.stopPropagation()
Expand Down
51 changes: 26 additions & 25 deletions src/sm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,37 @@ import * as request from "request"
import * as fs from "fs"
import * as path from "path"

export function uploadFile(filePath, callback) {
const headers = {
authority: 'sm.ms',
'user-agent': 'markdown-preview-enhanced'
export function uploadFile(filePath):Promise<string> {
return new Promise((resolve, reject)=> {
const headers = {
authority: 'sm.ms',
'user-agent': 'markdown-preview-enhanced'

}
request.post({
url:'https://sm.ms/api/upload',
formData: {smfile: fs.createReadStream(filePath)},
headers:headers},
(err, httpResponse, body)=> {
try {
body = JSON.parse(body)
if (err)
callback('Failed to upload image')
else if (body.code === 'error')
callback(body.msg, null)
else
callback(null, body.data.url)
} catch (error) {
callback('Failed to connect to sm.ms host', null)
}
request.post({
url:'https://sm.ms/api/upload',
formData: {smfile: fs.createReadStream(filePath)},
headers:headers
},
(err, httpResponse, body)=> {
try {
body = JSON.parse(body)
if (err)
return reject('Failed to upload image')
else if (body.code === 'error')
return reject(body.msg)
else
return resolve(body.data.url)
} catch (error) {
return reject('Failed to connect to sm.ms host')
}
})
})
}

/*
// example of how to use this API
smAPI.uploadFile '/Users/wangyiyi/Desktop/test.html', (err, url)->
if err
console.log err
else
console.log url
smAPI.uploadFile('/Users/wangyiyi/Desktop/test.jpg')
.then((url)=> {...})
.catch((error)=> {...})
*/
1 change: 0 additions & 1 deletion src/utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import * as path from "path"
import * as fs from "fs"
import * as vscode from "vscode"
import {exec} from "child_process"
import * as electron from "electron"

export function getExtensionDirectoryPath() {
return path.resolve(__dirname, "../../") //
Expand Down

0 comments on commit 15f1fa4

Please sign in to comment.