@shun-js/remotion-server 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 qiaowenbin<uikoo9@qq.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/app.js ADDED
@@ -0,0 +1,26 @@
1
+ // config
2
+ const { parseServerConfig } = require('@shun-js/shun-config');
3
+
4
+ // init
5
+ (async () => {
6
+ // config
7
+ const config = await parseServerConfig(process.argv);
8
+ if (!config) {
9
+ console.log('read server config fail');
10
+ return;
11
+ }
12
+
13
+ // options
14
+ const options = {};
15
+
16
+ // options config
17
+ options.config = config;
18
+
19
+ // options log
20
+ options.log = require('qiao-log');
21
+ options.logOptions = require('./server/log-options.js')();
22
+
23
+ // go
24
+ const app = await require('qiao-z')(options);
25
+ app.listen(config.port);
26
+ })();
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@shun-js/remotion-server",
3
+ "version": "0.6.2",
4
+ "description": "remotion.cool server",
5
+ "license": "MIT",
6
+ "author": "uikoo9 <uikoo9@qq.com>",
7
+ "homepage": "https://github.com/uikoo9/shun-js",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/uikoo9/shun-js.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/uikoo9/shun-js/issues"
14
+ },
15
+ "files": [
16
+ "server",
17
+ "app.js"
18
+ ],
19
+ "dependencies": {
20
+ "@shun-js/shun-config": "^0.3.1",
21
+ "@shun-js/shun-service": "^0.3.1",
22
+ "@supabase/supabase-js": "^2.93.3",
23
+ "qiao-file": "^5.0.6",
24
+ "qiao-log": "^5.1.9",
25
+ "qiao-z": "^5.8.9"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "registry": "https://registry.npmjs.org/"
30
+ },
31
+ "gitHead": "231f4b191bfc76a8501f4f978a64de3275b06839"
32
+ }
package/server/1 ADDED
@@ -0,0 +1,177 @@
1
+ require('dotenv').config();
2
+ const { renderVideo } = require('./renderer');
3
+ const { uploadToR2 } = require('./uploader');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+
7
+ // 配置
8
+ const CONFIG = {
9
+ POLL_INTERVAL: 60 * 1000, // 60秒检查一次
10
+ MAX_CONCURRENT: 1, // 同时只渲染1个视频
11
+ OUTPUT_DIR: path.join(__dirname, 'output'),
12
+ };
13
+
14
+ // 确保输出目录存在
15
+ if (!fs.existsSync(CONFIG.OUTPUT_DIR)) {
16
+ fs.mkdirSync(CONFIG.OUTPUT_DIR, { recursive: true });
17
+ }
18
+
19
+ let isProcessing = false;
20
+
21
+ /**
22
+ * 更新作品状态
23
+ */
24
+ async function updateWorkStatus(workId, status, updates = {}) {
25
+ try {
26
+ const { error } = await supabase
27
+ .from('works')
28
+ .update({
29
+ status,
30
+ updated_at: new Date().toISOString(),
31
+ ...updates,
32
+ })
33
+ .eq('id', workId);
34
+
35
+ if (error) {
36
+ console.error(`Error updating work ${workId} to ${status}:`, error);
37
+ }
38
+ } catch (error) {
39
+ console.error('Unexpected error updating work status:', error);
40
+ }
41
+ }
42
+
43
+ /**
44
+ * 处理单个作品的渲染
45
+ */
46
+ async function processWork(work) {
47
+ const workId = work.id;
48
+ const outputPath = path.join(CONFIG.OUTPUT_DIR, `${workId}.mp4`);
49
+
50
+ console.log(`\n[${new Date().toISOString()}] Processing work: ${workId}`);
51
+ console.log(`Title: ${work.title}`);
52
+
53
+ try {
54
+ // 1. 更新状态为 rendering
55
+ await updateWorkStatus(workId, 'rendering', {
56
+ render_started_at: new Date().toISOString(),
57
+ });
58
+
59
+ // 2. 渲染视频
60
+ console.log('Rendering video...');
61
+ await renderVideo({
62
+ sourceCode: work.source_code,
63
+ outputPath,
64
+ width: work.width || 1920,
65
+ height: work.height || 1080,
66
+ fps: work.fps || 30,
67
+ });
68
+
69
+ console.log('Video rendered successfully');
70
+
71
+ // 3. 上传到 R2
72
+ console.log('Uploading to R2...');
73
+ const videoUrl = await uploadToR2({
74
+ filePath: outputPath,
75
+ workId: workId,
76
+ });
77
+
78
+ console.log('Video uploaded:', videoUrl);
79
+
80
+ // 4. 获取视频信息
81
+ const stats = fs.statSync(outputPath);
82
+ const durationInFrames = Math.round(5 * (work.fps || 30)); // 暂时硬编码为5秒
83
+
84
+ // 5. 更新数据库
85
+ await updateWorkStatus(workId, 'published', {
86
+ video_url: videoUrl,
87
+ render_completed_at: new Date().toISOString(),
88
+ published_at: new Date().toISOString(),
89
+ duration_in_frames: durationInFrames,
90
+ duration_seconds: durationInFrames / (work.fps || 30),
91
+ });
92
+
93
+ console.log(`✅ Work ${workId} completed successfully`);
94
+
95
+ // 6. 清理本地文件
96
+ fs.unlinkSync(outputPath);
97
+ } catch (error) {
98
+ console.error(`❌ Error processing work ${workId}:`, error);
99
+
100
+ // 更新为失败状态
101
+ await updateWorkStatus(workId, 'render_failed', {
102
+ render_error: error.message,
103
+ render_completed_at: new Date().toISOString(),
104
+ });
105
+
106
+ // 清理可能存在的文件
107
+ if (fs.existsSync(outputPath)) {
108
+ fs.unlinkSync(outputPath);
109
+ }
110
+ }
111
+ }
112
+
113
+ /**
114
+ * 主处理循环
115
+ */
116
+ async function processQueue() {
117
+ if (isProcessing) {
118
+ console.log('Already processing, skipping...');
119
+ return;
120
+ }
121
+
122
+ isProcessing = true;
123
+
124
+ try {
125
+ const works = await fetchPendingWorks();
126
+
127
+ if (works.length === 0) {
128
+ console.log(`[${new Date().toISOString()}] No pending works`);
129
+ } else {
130
+ console.log(`[${new Date().toISOString()}] Found ${works.length} pending work(s)`);
131
+
132
+ for (const work of works) {
133
+ await processWork(work);
134
+ }
135
+ }
136
+ } catch (error) {
137
+ console.error('Error in process queue:', error);
138
+ } finally {
139
+ isProcessing = false;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * 启动 Worker
145
+ */
146
+ async function start() {
147
+ console.log('='.repeat(60));
148
+ console.log('Remotion Render Worker Started');
149
+ console.log('='.repeat(60));
150
+ console.log(`Poll Interval: ${CONFIG.POLL_INTERVAL / 1000}s`);
151
+ console.log(`Max Concurrent: ${CONFIG.MAX_CONCURRENT}`);
152
+ console.log(`Output Directory: ${CONFIG.OUTPUT_DIR}`);
153
+ console.log('='.repeat(60));
154
+
155
+ // 立即执行一次
156
+ await processQueue();
157
+
158
+ // 定期执行
159
+ setInterval(processQueue, CONFIG.POLL_INTERVAL);
160
+ }
161
+
162
+ // 优雅退出
163
+ process.on('SIGINT', () => {
164
+ console.log('\nReceived SIGINT, shutting down gracefully...');
165
+ process.exit(0);
166
+ });
167
+
168
+ process.on('SIGTERM', () => {
169
+ console.log('\nReceived SIGTERM, shutting down gracefully...');
170
+ process.exit(0);
171
+ });
172
+
173
+ // 启动
174
+ start().catch((error) => {
175
+ console.error('Failed to start worker:', error);
176
+ process.exit(1);
177
+ });
@@ -0,0 +1,34 @@
1
+ /**
2
+ * log options
3
+ * @returns
4
+ */
5
+ module.exports = () => {
6
+ // log options
7
+ const logLevel = 'debug';
8
+ const logPattern = 'yyyy-MM-dd-hh';
9
+ const logPath = require('path').resolve(__dirname, '../logs/qiao-z.log');
10
+
11
+ return {
12
+ pm2: true,
13
+ pm2InstanceVar: 'INSTANCE_ID',
14
+ appenders: {
15
+ stdout: {
16
+ type: 'stdout',
17
+ },
18
+ datefile: {
19
+ type: 'dateFile',
20
+ pattern: logPattern,
21
+ filename: logPath,
22
+ keepFileExt: true,
23
+ numBackups: 30,
24
+ compress: true,
25
+ },
26
+ },
27
+ categories: {
28
+ default: {
29
+ level: logLevel,
30
+ appenders: ['stdout', 'datefile'],
31
+ },
32
+ },
33
+ };
34
+ };
@@ -0,0 +1,36 @@
1
+ // supabase
2
+ const { createClient } = require('@supabase/supabase-js');
3
+
4
+ // logger
5
+ const Logger = require('qiao-log');
6
+ const logOptions = require('../log-options.js')();
7
+ const logger = Logger(logOptions);
8
+
9
+ /**
10
+ * fetchPendingWorks
11
+ * @returns
12
+ */
13
+ exports.fetchPendingWorks = async () => {
14
+ const methodName = 'fetchPendingWorks';
15
+ try {
16
+ // supabase
17
+ const supabase = createClient(global.QZ_CONFIG.SUPABASE_URL, global.QZ_CONFIG.SUPABASE_SERVICE_KEY);
18
+
19
+ // query
20
+ const { data, error } = await supabase.rpc('get_pending_works_locked', {
21
+ max_count: 1,
22
+ });
23
+
24
+ // check
25
+ if (error) {
26
+ logger.error(methodName, 'Error fetching pending works:', error);
27
+ return [];
28
+ }
29
+
30
+ // r
31
+ return data || [];
32
+ } catch (error) {
33
+ logger.error(methodName, 'Unexpected error fetching works:', error);
34
+ return [];
35
+ }
36
+ };
@@ -0,0 +1,28 @@
1
+ // model
2
+ const { fetchPendingWorks } = require('../model/RemotionModel.js');
3
+
4
+ // logger
5
+ const Logger = require('qiao-log');
6
+ const logOptions = require('../log-options.js')();
7
+ const logger = Logger(logOptions);
8
+
9
+ // RemotionTask.js
10
+ exports.runAndInit = true;
11
+ exports.time = '* 1 * * *';
12
+ exports.tick = async () => {
13
+ await genRemotionVideo();
14
+ };
15
+
16
+ // gen remotion video
17
+ async function genRemotionVideo() {
18
+ const methodName = 'genRemotionVideo';
19
+
20
+ // go
21
+ logger.info(methodName, 'start');
22
+
23
+ const rows = await fetchPendingWorks();
24
+ console.log(rows);
25
+
26
+ // end
27
+ logger.info(methodName, 'end');
28
+ }
@@ -0,0 +1,77 @@
1
+ // services
2
+ const { feishuBot } = require('@shun-js/shun-service');
3
+
4
+ /**
5
+ * feishuMsg
6
+ * @param {*} msg
7
+ */
8
+ exports.feishuMsg = (msg) => {
9
+ if (global.QZ_CONFIG.env !== 'production') return;
10
+
11
+ feishuBot({
12
+ url: global.QZ_CONFIG.feishu.url,
13
+ feishuUrl: global.QZ_CONFIG.feishu.feishuUrl,
14
+ feishuMsg: msg,
15
+ });
16
+ };
17
+
18
+ // is bot
19
+ function isBot(req) {
20
+ const ua = req.useragent;
21
+ const hasOSName = ua && ua.os && ua.os.name;
22
+ const isGoogleBot = ua && ua.browser && ua.browser.name === 'Googlebot';
23
+ const isMetaBot = ua && ua.browser && ua.browser.name === 'meta-externalagent';
24
+ const isSafariBot = ua && ua.engine && ua.engine.name === 'WebKit' && ua.engine.version === '605.1.15';
25
+ return !hasOSName || isGoogleBot || isMetaBot || isSafariBot;
26
+ }
27
+
28
+ /**
29
+ * errorFeishuMsg
30
+ * @param {*} req
31
+ * @param {*} msg
32
+ * @returns
33
+ */
34
+ exports.errorFeishuMsg = (req, msg) => {
35
+ // check
36
+ if (isBot(req)) return;
37
+
38
+ // msg
39
+ const uaJson = JSON.stringify(req.useragent || {});
40
+ exports.feishuMsg(`【通知】服务异常,${msg},请查看日志,ua:${uaJson}`);
41
+ };
42
+
43
+ /**
44
+ * chatFeishuMsg
45
+ * @param {*} req
46
+ * @returns
47
+ */
48
+ exports.chatFeishuMsg = (req) => {
49
+ // check
50
+ if (isBot(req)) return;
51
+
52
+ // msg
53
+ const uaJson = JSON.stringify(req.useragent || {});
54
+ const userid = req.headers.userid;
55
+ const prompt = decodeURIComponent(req.body.userPrompt);
56
+
57
+ const msg = `【通知】/chat被访问\nuserid:${userid}\nua:\n${uaJson}\nprompt:\n${prompt}`;
58
+ exports.feishuMsg(msg);
59
+ };
60
+
61
+ /**
62
+ * chatResFeishuMsg
63
+ * @param {*} req
64
+ * @returns
65
+ */
66
+ exports.chatResFeishuMsg = (req, chatRes) => {
67
+ // check
68
+ if (isBot(req)) return;
69
+
70
+ // msg
71
+ const uaJson = JSON.stringify(req.useragent || {});
72
+ const userid = req.headers.userid;
73
+ const prompt = decodeURIComponent(req.body.userPrompt);
74
+
75
+ const msg = `【通知】/chat生成成功\nuserid:${userid}\nua:\n${uaJson}\nprompt:\n${prompt}\nres:${chatRes}`;
76
+ exports.feishuMsg(msg);
77
+ };