Last active
March 5, 2020 06:25
-
-
Save jirawatee/14978ac18a71df99ff2cc3469d6c105e to your computer and use it in GitHub Desktop.
doImage function in UCL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const doImage = async (event) => { | |
const path = require("path"); | |
const os = require("os"); | |
const fs = require("fs"); | |
const UUID = require("uuid-v4"); | |
// กำหนด URL ในการไปดึง binary จาก LINE กรณีผู้ใช้อัพโหลดภาพมาเอง | |
let url = `${LINE_CONTENT_API}/${event.message.id}/content`; | |
// ตรวจสอบว่าภาพนั้นถูกส่งมจาก LIFF หรือไม่ | |
if (event.message.contentProvider.type === 'external') { | |
// กำหนด URL รูปภาพที่ LIFF ส่งมา | |
url = event.message.contentProvider.originalContentUrl; | |
} | |
// ดาวน์โหลด binary | |
let buffer = await request.get({ | |
headers: LINE_HEADER, | |
uri: url, | |
encoding: null // แก้ปัญหา binary ไม่สมบูรณ์จาก default encoding ที่เป็น utf-8 | |
}); | |
// สร้างไฟล์ temp ใน local จาก binary ที่ได้ | |
const tempLocalFile = path.join(os.tmpdir(), 'temp.jpg'); | |
await fs.writeFileSync(tempLocalFile, buffer); | |
// กำหนดชื่อ bucket ใน Cloud Storage for Firebase | |
const bucket = admin.storage().bucket('YOUR-BUCKET-NAME'); | |
// อัพโหลดไฟล์ขึ้น Cloud Storage for Firebase | |
await bucket.upload(tempLocalFile, { | |
destination: `${event.source.userId}.jpg`, // ให้ชื่อไฟล์เป็น userId ของ LINE | |
metadata: { | |
cacheControl: 'no-cache', | |
metadata: { | |
// สำหรับ permanent public URL ใน Cloud Storage | |
firebaseStorageDownloadTokens: UUID() | |
} | |
} | |
}); | |
/// ลบไฟล์ temp หลังจากอัพโหลดเสร็จ | |
fs.unlinkSync(tempLocalFile) | |
// ตอบกลับเพื่อ handle UX เนื่องจากทั้งดาวน์โหลดและอัพโหลดต้องใช้เวลา | |
reply(event.replyToken, { type: 'text', text: 'ขอคิดแป๊บนะเตง...' }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment