-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (56 loc) · 1.7 KB
/
index.js
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
const path = require('path')
const os = require('os')
const util = require('util')
const fs = require('@skpm/fs')
const sketch = require('sketch')
const FOLDER = path.join(os.tmpdir(), 'com.bomberstudios.sketch-image-downloader')
export default function insertImage(url, parent) {
return Promise.resolve(getImageFromURL(url).then(imagePath => {
if (!imagePath) {
// TODO: something wrong happened, show something to the user
return
} else {
let imageRep = NSImage.alloc().initWithContentsOfFile(imagePath).representations().objectAtIndex(0)
let w = imageRep.pixelsWide() / 2 // Because Retina
let h = imageRep.pixelsHigh() / 2 // Because Retina
let bitmap = new sketch.Image({
image: imagePath,
frame: {
width: w,
height: h
},
parent: parent
})
return bitmap
}
}))
}
export function getImageFromURL(url) {
/*
This function downloads an image from the given URL, and returns a path to the downloaded file, ready to be used by a DataProvider
*/
// TODO: cache file
return Promise.resolve(fetch(url)
.then(res => res.blob())
.then(saveTempFileFromImageData)
.catch((err) => {
console.error(err)
}))
}
function saveTempFileFromImageData (imageData) {
const guid = NSProcessInfo.processInfo().globallyUniqueString()
const imagePath = path.join(FOLDER, `${guid}.jpg`)
try {
fs.mkdirSync(FOLDER)
} catch (err) {
// probably because the folder already exists
// TODO: check that it is really because it already exists
}
try {
fs.writeFileSync(imagePath, imageData, 'NSData')
return imagePath
} catch (err) {
console.error(err)
return undefined
}
}