-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
80 lines (67 loc) · 1.97 KB
/
app.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
"use strict";
const Homey = require("homey");
const { PassThrough } = require("stream");
const axios = require('axios')
const FormData = require("form-data");
const CONTENT_TYPES = {
png: "image/png",
jpg: "image/jpeg",
gif: "image/gif",
};
class ImagePoster extends Homey.App {
async onInit() {
this.log("Image Poster is running...");
this.initializeActions();
}
async initializeActions() {
const sendImageCard = this.homey.flow.getActionCard("sendimage");
sendImageCard.registerRunListener(async (args, state) => {
console.log("[SEND IMAGE] " + JSON.stringify(args));
const image = args.droptoken;
const URL = args.URL;
const form = new FormData();
if (image.getStream) {
console.log("get stream");
const stream = await image.getStream();
form.append("image", stream, {
contentType: stream.contentType,
filename: stream.filename,
name: "image",
});
} else {
//backwards compatibility
const buf = await image.getBuffer();
if (typeof buf === "string") {
form.append("image", buf);
} else {
form.append("image", buf, {
contentType: CONTENT_TYPES[image.getFormat()],
filename: "x." + image.getFormat(),
name: "image",
});
}
}
try {
console.log("Send stream to: ", URL)
const response = await axios({
url: URL,
method: "POST",
data: form.pipe(new PassThrough()),
headers: form.getHeaders(),
});
console.log("Send done: ", response);
if (response.statusText !== "OK") {
console.log("Response NOT OK:", response.statusText);
return false;
} else {
console.log("Response:", response.data);
return true;
}
} catch (err){
console.log("Error:", err)
return false;
}
});
}
}
module.exports = ImagePoster;