repl.it
@jajoosam/

kat-minus-linus-1

Nodejs

No description

fork
loading
Files
  • index.js
  • config.json
  • index.html
  • think.png
  • Packager files
  • package-lock.json
  • package.json
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
const { readFile } = require('fs');
const express = require('express');
const request = require('request');
const x = require('x-ray')
const app = express();

// We use one cache for both requests because this is a hacky hacky
// and I don't give a damn about no shitty code 2day.
const Cache = {
  validUntil: 0,
  thesephist: 0,
  katmhuang: 0,
}

function getFollowerLine(response) {
  const lines = response.split('\n').filter(line => line.length < 1e4);
  for (const line of lines) {
    if (line.includes('data-nav="followers"')) {
      const followerMatch = /title=\"(\d*) Followers\"/.exec(line);
      if (followerMatch === null) {
        return -1;
      }
      
      const followerCount = followerMatch[1];
      return isNaN(followerCount) ? -1 : +parseInt(followerCount);
    }
  }

  return -1;
}

function withFollowerCountFrom(username, callback) {
  if (Cache.validUntil > Date.now()) {
    callback(Cache[username]);
    return;
  }

  request(`https://twitter.com/${username}`, (err, response, body) => {
    if (err || response.statusCode !== 200) {
      callback(-1);
    }

    callback(getFollowerLine(body));
    Cache[username] = getFollowerLine(body);
    Cache.validUntil = Date.now() + 30 * 1000; // valid for 30 secs.
  });
}

app.get('/', (req, res) => {
  withFollowerCountFrom('thesephist', (followsLinus) => {
    withFollowerCountFrom('katmhuang', (followsKat) => {
      if (followsKat < 0 || followsLinus < 0) {
        res.end('Error talking to Twitter');
      }

      const result = followsLinus > followsKat ? 'YES! hehe' : 'Not yet...';
      const explanation = `Linus has ${followsLinus} followers, Kat has ${followsKat}.<br/>Linus is ${followsLinus > followsKat ? 'ahead' : 'behind'} by ${Math.abs(followsLinus - followsKat)}.`;

      readFile('./index.html', 'utf8', (err, data) => {
        if (err) {
          res.end(`Kat has ${followsKat} followers. Linus has ${followsLinus}.`);
        }

        let tpl = data;
        tpl = tpl.replace('$result', result);
        tpl = tpl.replace('$explanation', explanation);
        res.setHeader('Content-Type', 'text/html');
        res.send(tpl);
      });
    });
  });
});

app.get('/think.png', (req, res) => {
  readFile('./think.png', (err, data) => {
    if (err) {
      res.status(404);
      res.end('error reading file');
      return;
    }

    res.send(data);
  })
});

app.listen(8080);
?