aboutsummaryrefslogtreecommitdiff
path: root/bot.js
blob: 5c17efd23cfeb59a71dfbd9aaa2ac03909f0147a (plain)
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
var Libhoney = require("libhoney");
var hny = new Libhoney({
    writeKey: process.env.HONEYCOMB_KEY,
    dataset: "crabravebot"
})
const { Composer } = require('micro-bot');
const child_process = require('child_process');
const fs = require('fs');
const url = require('url');
const { JSDOM } = require("jsdom");

// the bot
const bot = new Composer();

// start command
bot.command('/start', async ({ from, replyWithMarkdown, botInfo }) =>
  replyWithMarkdown(`Hi *${from.first_name || from.username}*!
To shitpost, type @${botInfo.username} and type the text you want to overlay over crab rave.
This was originally made by @boringcactus in one afternoon when she was bored.
This bot isn't super reliable but the source is at https://github.com/boringcactus/crabravebot,
and you can use this bot from the Web at https://crabravebot.herokuapp.com/`));

// styles
const STYLES = {
  'classic': {
    'video': 'https://cdn.glitch.com/70ea37b5-d264-46e5-a1db-29c786c86515%2FCrabRaveQuieter.mp4?v=1548223581701',
    'thumb': 'https://cdn.glitch.com/70ea37b5-d264-46e5-a1db-29c786c86515%2FCrabRaveBackground.png?v=1566350372048',
  },
  'otamatone': {
    'video': 'https://cdn.glitch.com/70ea37b5-d264-46e5-a1db-29c786c86515%2FCrabRaveOtamatone.mp4?v=1566354239409',
    'thumb': 'https://cdn.glitch.com/70ea37b5-d264-46e5-a1db-29c786c86515%2FCrabRaveOtamatoneBackground.png?v=1566354702285',
  },
  'garfield': {
    'video': 'https://cdn.glitch.com/70ea37b5-d264-46e5-a1db-29c786c86515%2FCrabRaveGarfield.mp4?v=1575143374116',
    'thumb': 'https://cdn.glitch.com/70ea37b5-d264-46e5-a1db-29c786c86515%2FCrabRaveGarfieldBackground.png?v=1575143434563',
  },
}

// inline query
bot.on('inline_query', async ({ inlineQuery, answerInlineQuery }) => {
  const query = inlineQuery.query || '';
  console.log('Got query', query);
  if (query.length > 1) {
    const result = [
      {
        type: "video",
        id: "classic",
        video_url: "https://crabravebot.herokuapp.com/video/" + encodeURIComponent(query) + ".mp4?v1",
        mime_type: "video/mp4",
        thumb_url: "https://crabravebot.herokuapp.com/video/" + encodeURIComponent(query) + ".png?v1",
        title: 'Classic'
      },
      {
        type: "video",
        id: "otamatone",
        video_url: "https://crabravebot.herokuapp.com/video/" + encodeURIComponent(query) + ".mp4?v1&style=otamatone",
        mime_type: "video/mp4",
        thumb_url: "https://crabravebot.herokuapp.com/video/" + encodeURIComponent(query) + ".png?v1&style=otamatone",
        title: 'Otamatone (original by TheRealSullyG)'
      },
      {
        type: "video",
        id: "garfield",
        video_url: "https://crabravebot.herokuapp.com/video/" + encodeURIComponent(query) + ".mp4?v1&style=garfield",
        mime_type: "video/mp4",
        thumb_url: "https://crabravebot.herokuapp.com/video/" + encodeURIComponent(query) + ".png?v1&style=garfield",
        title: 'Garfield (original by @jondancesto)'
      },
    ];
    return answerInlineQuery(result);
  }
});

function fixPaths() {
  for (let style of Object.keys(STYLES)) {
    try {
      let path = require('path').join('/tmp', style, 'video');
      fs.mkdirSync(path, {recursive: true});
    } catch (e) {
      console.log(e);
    }
  }
}

module.exports = {
  bot,
  server(req, res) {
    if (req.url === '/') {
      res.end(`
        <html>
        <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Crab Rave Bot</title>
        </head>
        <body>
        <main>
        <h1>it's a tool for adding things to crab rave</h1>
        <form action="/add-text" method="GET">
        <textarea id="text" name="text" rows="6" cols="25"></textarea>
        <p>
          Style:
          <input type="radio" id="classic" name="style" value="classic" checked><label for="classic">Classic</label>
          <input type="radio" id="otamatone" name="style" value="otamatone"><label for="otamatone">Otamatone</label> (<a href="https://youtu.be/VI5I3MuKJlo">original</a> by TheRealSullyG)
          <input type="radio" id="garfield" name="style" value="garfield"><label for="garfield">Garfield</label> (<a href="https://twitter.com/jondancesto/status/1199796307218427904">original</a> by @jondancesto)
        </p>
        <input type="submit" value="Overlay!">
        </form>
        <p><a href="https://t.me/crabravebot">also available as a Telegram bot</a></p>
        <p>brought to you by <a href="https://www.boringcactus.com">boringcactus</a></p>
        </main>
        <img id="preview" style="max-width: 100%;" src="https://crabravebot.herokuapp.com/video/.png">
        <script type="text/javascript">
        const img = document.getElementById('preview'),
          text = document.getElementById('text'),
          classic = document.getElementById('classic');
        setInterval(() => {
          let style = document.querySelector('input[name="style"]:checked').value;
          img.src = "https://crabravebot.herokuapp.com/video/" + encodeURIComponent(text.value) + '.png?style=' + style;
        }, 1000);
        </script>
        </body>
        </html>
      `);
    } else if (req.url.startsWith('/add-text')) {
      const parsed = url.parse(req.url, true);
      const data = parsed.query.text;
      const style = parsed.query.style;
      res.writeHead(303, {
        'Location': "https://crabravebot.herokuapp.com/video/" + encodeURIComponent(data) + ".mp4?style=" + style
      });
      res.end();
    } else if (req.url.startsWith('/video/')) {
      fixPaths();
      if (!fs.existsSync('/tmp/classic/video')) {
        console.log('what???');
        child_process.spawnSync('ls', ['/tmp', '/tmp/classic', '/tmp/classic/video']);
      }
      const parsed = url.parse(req.url, true);
      const match = /^\/video\/(.*)\.(mp4|png)/.exec(parsed.pathname);
      if (match === null) {
        console.error('Bad URL: ' + match);
        res.writeHead(400);
        res.end();
        return;
      }
      const text = decodeURIComponent(match[1]);
      console.log('Match:', text);
      const type = match[2];
      if (type === 'mp4') {
        const ev = hny.newEvent();
        ev.addField('type', 'bake');
        ev.addField('text', text);
        ev.send();
      }
      const style = parsed.query.style || 'classic';
      if (!Object.keys(STYLES).includes(style)) {
        console.error("Bad style");
        res.writeHead(400);
        res.end();
        return;
      }
      const path = require('path').join('/tmp', style, encodeURIComponent(match[0]));
      if (type === 'mp4') {
        res.setHeader('Content-Type', 'video/mp4');
      } else {
        res.setHeader('Content-Type', 'image/png');
      }
      console.log('Name:', path);
      // TODO don't do this dumb thing
      if (!fs.existsSync(path)) {
        if (!fs.existsSync(path + '.png')) {
          const dom = new JSDOM(`<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg version="1.1" viewBox="0 0 848 480">
</svg>`, {contentType: 'image/svg+xml'});
          const document = dom.window.document;
          const lines = text.split('\n');
          let y = 300 - (75 * lines.length) / 2;
          for (let line of lines) {
            const lineNode = document.createElement('text');
            lineNode.setAttribute('x', 424);
            lineNode.setAttribute('y', y);
            y += 75;
            lineNode.setAttribute('style', "text-anchor:middle;alignment-baseline:middle;font-family:'DejaVu Sans',sans-serif;font-weight:bold;font-size:48pt;fill:white;stroke:black;stroke-width:1px;");
            lineNode.textContent = line;
            document.querySelector('svg').append(lineNode);
          }
          const svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' + dom.serialize();
          fs.writeFileSync(path + '.svg', svg);
          console.log('convert', '-background', 'none', path + '.svg', path + '.png');
          child_process.spawnSync('convert', ['-background', 'none', path + '.svg', path + '.png'], {stdio: ['inherit', 'inherit', 'inherit']});
        }
        if (type === 'mp4') {
          let background = STYLES[style].video;
          let args = [
            '-hide_banner',
            '-i', background,
            '-i', path + '.png',
            '-filter_complex', 'overlay=x=0:y=0',
            '-c:v', 'libx264', '-preset', 'superfast', '-crf', '27', '-f', 'mp4', '-c:a', 'copy',
            '-y', path
          ];
          console.log('ffmpeg', ...args);
          let child = child_process.spawnSync(
            'ffmpeg',
            args,
            {
              stdio: ['inherit', 'inherit', 'inherit']
            }
          );
        } else {
          let background_url = STYLES[style].thumb;
          let background = '/tmp/' + style + '.png';
          if (!fs.existsSync(background)) {
            child_process.spawnSync('curl', ['-o', background, background_url]);
          }
          child_process.spawnSync('composite', [path + '.png', background, path]);
        }
      }
      if (fs.existsSync(path)) {
        fs.createReadStream(path).pipe(res);
      } else {
        console.log('what the fuck', path);
      }
    }
  },
};