aboutsummaryrefslogtreecommitdiff
path: root/src/routes/index.js
blob: 5f4376430c05a667862e5b33a65614b57751ab54 (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
const express = require('express');
const he = require('he');
const router = express.Router();
const geddit = require('../geddit.js');
const G = new geddit.Geddit();


// GET /
router.get('/', async (req, res) => {
  res.redirect("/r/all")
});

// GET /r/:id
router.get('/r/:subreddit/:sort?', async (req, res) => {
  var subreddit = req.params.subreddit;
  var query = req.query;
  var sort = req.params.sort ? req.params.sort : 'hot';
  var options = req.query;

  var postsReq = G.getSubmissions(sort, `${subreddit}`, options);
  var aboutReq = G.getSubreddit(`${subreddit}`);

  var [posts, about] = await Promise.all([postsReq, aboutReq]);
  console.log(`posts for ${subreddit}`);
  console.log(posts.posts.length);

  res.render('index', { subreddit, posts, about });
});

// GET /comments/:id
router.get('/comments/:id', async (req, res) => {
  var id = req.params.id;

  response = await G.getSubmissionComments(id);

  res.render('comments', unescape_submission(response));
});

// GET /subs
router.get('/subs', async (req, res) => {
  res.render('subs');
});

// GET /media
router.get('/media/*', async (req, res) => {
  var url = req.params[0];
  console.log(`making request to ${url}`);
  return await fetch(url, {
    headers: {
      Accept: "*/*",
    }
  });
});

module.exports = router;

function unescape_submission(response) {
  var post = response.submission.data;
  var comments = response.comments;

  if (post.selftext_html) {
    post.selftext_html = he.decode(post.selftext_html);
  }
  comments.forEach(unescape_comment);

  return { post, comments };
}

function unescape_comment(comment) {
  if (comment.data.body_html) {
    comment.data.body_html = he.decode(comment.data.body_html);
  }
  if (comment.data.replies) {
    if(comment.data.replies.data) {
      if(comment.data.replies.data.children) {
        comment.data.replies.data.children.forEach(unescape_comment);
      }
    }
  }
}