-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
107 lines (87 loc) · 2.63 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
process.env.PATH = process.env.PATH + ':' + process.env['LAMBDA_TASK_ROOT']
const AWS = require('aws-sdk')
const { spawn, spawnSync } = require('child_process') //
const { createReadStream, createWriteStream } = require('fs')
const s3 = new AWS.S3({ region: 'ap-northeast-2' });
const ffprobePath = '/opt/nodejs/ffprobe'
const ffmpegPath = '/opt/nodejs/ffmpeg'
const allowedTypes = ['mov', 'mpg', 'mpeg', 'mp4', 'wmv', 'avi', 'webm']
const width = process.env.WIDTH
const height = process.env.HEIGHT
module.exports.handler = async (event, context) => {
const srcKey = decodeURIComponent(event.Records[0].s3.object.key).replace(/\+/g, ' ')
const bucket = event.Records[0].s3.bucket.name
const target = s3.getSignedUrl('getObject', { Bucket: bucket, Key: srcKey, Expires: 1000 })
let fileType = srcKey.match(/\.\w+$/)
if (!fileType) {
throw new Error(`invalid file type found for key: ${srcKey}`)
}
fileType = fileType[0].slice(1)
if (allowedTypes.indexOf(fileType) === -1) {
throw new Error(`filetype: ${fileType} is not an allowed type`)
}
function createImage(seek) {
return new Promise((resolve, reject) => {
let tmpFile = createWriteStream(`/tmp/screenshot.jpg`)
const ffmpeg = spawn(ffmpegPath, [
'-ss',
seek,
'-i',
target,
'-vf',
`thumbnail,scale=${width}:${height}`,
'-qscale:v',
'2',
'-frames:v',
'1',
'-f',
'image2',
'-c:v',
'mjpeg',
'pipe:1'
])
ffmpeg.stdout.pipe(tmpFile)
ffmpeg.on('close', function(code) {
tmpFile.end()
resolve()
})
ffmpeg.on('error', function(err) {
console.log(err)
reject()
})
})
}
function uploadToS3(x) {
return new Promise((resolve, reject) => {
let tmpFile = createReadStream(`/tmp/screenshot.jpg`)
let dstKey = srcKey.replace(/\.\w+$/, `-${x}.jpg`).replace('/video/', '/thumb/')
var params = {
Bucket: bucket,
Key: dstKey,
Body: tmpFile,
ContentType: `image/jpg`
}
s3.upload(params, function(err, data) {
if (err) {
console.log(err)
reject()
}
console.log(`successful upload to ${bucket}/${dstKey}`)
resolve()
})
})
}
const ffprobe = spawnSync(ffprobePath, [
'-v',
'error',
'-show_entries',
'format=duration',
'-of',
'default=nw=1:nk=1',
target
])
const duration = Math.ceil(ffprobe.stdout.toString())
await createImage(duration * 0.25)
await uploadToS3(1)
return console.log(`processed ${bucket}/${srcKey} successfully`)
}