« get me outta code hell

index.js - scratchrlol - Simple HTML-based Scratch client
summary refs log tree commit diff
path: root/index.js
blob: bd4208eaac933fdf618b840efae850d89c06f2e0 (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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
const fetch = require('node-fetch')
const fixWS = require('fix-whitespace')
const fs = require('fs')
const http = require('http')
const qs = require('querystring')
const url = require('url')
const util = require('util')

const readFile = util.promisify(fs.readFile)

// General page size.
const limit = 20

const page = async (request, response, text) => {
  const cookies = parseCookies(request)

  const notificationCount = await getMessageCount(cookies.username)

  response.setHeader('Content-Type', 'text/html')
  response.end(fixWS`
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Scratch</title>
        <link rel="stylesheet" href="/style.css">
      </head>
      <body>
        <header>
          ${cookies.username ? fixWS`
            <p>You are logged in as ${cookies.username}. (<a href="/logout">Log out.</a>) You have ${'' + notificationCount} unread <a href="/notifications">${pluralize('notification', notificationCount)}</a>.</p>`
          : fixWS`
            <p>You are not logged in. <a href="/login">Log in.</a></p>
          `}
          <hr>
        </header>
        ${text}
      </body>
    </html>
  `)
}

const getMessageCount = function(username) {
  return fetch(`https://api.scratch.mit.edu/proxy/users/${username}/activity/count`)
    .then(res => res.json())
    .then(foo => foo.msg_count)
}

const getNotifications = function(username, token, pageNumber = 1) {
  const offset = (pageNumber - 1) * limit
  return fetch(`https://api.scratch.mit.edu/users/${username}/messages?x-token=${token}&limit=${limit}&offset=${offset}`)
    .then(res => res.json())
}

const markNotificationsAsRead = function(sessionID, csrfToken) {
  return fetch(`https://scratch.mit.edu/site-api/messages/messages-clear/`, {
    method: 'POST',
    headers: {
      // CSRF token must be specified in both header and cookie!
      Cookie: `scratchsessionsid="${sessionID}"; scratchcsrftoken=${csrfToken}`,
      Referer: 'https://scratch.mit.edu/messages/',
      'X-CSRFToken': csrfToken
    }
  }).then(res => res.text()).then(text => console.log(text))
}

const getProject = function(projectID, token) {
  return fetch(`https://api.scratch.mit.edu/projects/${projectID}?x-token=${token}`)
    .then(res => res.json())
}

const getUser = function(username) {
  return fetch(`https://api.scratch.mit.edu/users/${username}`)
    .then(res => res.json())
}

const last = arr => arr[arr.length - 1]
const filterHTML = text => text.replace(/</g, '&lt;').replace(/>/g, '&gt;')
const pluralize = (word, n) => n === 1 ? word : word + 's'

const templates = {
  user: username => `<a href="/users/${username}">${username}</a>`,
  project: (name, id) => `<a href="/projects/${id}">${filterHTML(name.trim())}</a>`,
  studio: (name, id) => `<a href="/studios/${id}">${filterHTML(name.trim())}</a>`,
  forumThread: (name, id) => `<a href="/topics/${id}">${filterHTML(name.trim())}</a>`,
  longField: text => {
    return text.split('\n')
      .map(filterHTML)
      .reduce((arr, l, i, lines) =>
        [...arr.slice(0, -1), ...l.trim().length
          ? (last(arr).length
            ? [last(arr) + '<br>\n   ' + l]
            : ['<p>' + l]).map(x => i === lines.length - 1 ? x + '</p>' : x)
          : last(arr).length
            ? [last(arr) + '</p>', '']
            : ['']],
        [''])
      .map(line => line.replace(/@([a-zA-Z0-9\-_]+)/g, (m, username) => fixWS`
        <a href="/users/${username}">@${username}</a>
      `))
      .map(line => line.replace(/https?:\/\/([^."<>\s]\.)*scratch\.mit\.edu(\/[^"<>\s]*)/g, (url, subdomain, path) => {
        const text = url
        if (!subdomain) {
          if (path.startsWith('/projects/')) {
            url = path
          } else if (path.startsWith('/users/')) {
            url = path
          }
        }
        return fixWS`
          <a href="${url}">${text}</a>
        `
      }))
      .join('\n')
  },

  notification: (notif, username) => {
    let text = '<li>'

    if (notif.type === 'addcomment') {
      text += templates.user(notif.actor_username)
      text += ` wrote a comment `
      if (notif.comment_type === 0) {
        text += 'on ' + templates.project(notif.comment_obj_title, notif.comment_obj_id)
      } else if (notif.comment_type === 1) {
        if (notif.comment_obj_title === username) {
          text += `on <a href="/users/${notif.comment_obj_title}">your profile</a>`
        } else {
          text += `on <a href="/users/${notif.comment_obj_title}">${notif.comment_obj_title}'s profile</a>`
        }
      } else if (notif.comment_type === 2) {
        text += 'in ' + templates.studio(notif.comment_obj_title, notif.comment_obj_id)
      } else {
        text += `somewhere I don't recognize (${notif.comment_type})`
      }
    } else if (notif.type === 'loveproject' || notif.type === 'favoriteproject') {
      text += templates.user(notif.actor_username)
      if (notif.type === 'loveproject') {
        text += ` loved `
      } else {
        text += ` favorited `
      }
      text += `your project `
      text += templates.project(notif.title || notif.project_title, notif.project_id)
    } else if (notif.type === 'remixproject') {
      text += templates.user(notif.actor_username)
      text += ` remixed your project `
      text += templates.project(notif.parent_title, notif.parent_id)
      text += ` as `
      text += templates.project(notif.title, notif.project_id)
    } else if (notif.type === 'followuser') {
      text += templates.user(notif.actor_username)
      text += ` followed you`
    } else if (notif.type === 'forumpost') {
      text += `There are new posts on `
      text += templates.forumThread(notif.topic_title, notif.topic_id)
    } else if (notif.type === 'curatorinvite') {
      text += templates.user(notif.actor_username)
      text += ` invited you to curate the studio `
      text += templates.studio(notif.title, notif.gallery_id)
    } else if (notif.type === 'becomeownerstudio') {
      text += templates.user(notif.actor_username)
      text += ` promoted you to a manager of the studio `
      console.log(notif)
      text += templates.studio(notif.gallery_title, notif.gallery_id)
    } else if (notif.type === 'studioactivity') {
      text += `There is new activity in `
      text += templates.studio(notif.title, notif.gallery_id)
    } else {
      text += `I'm not sure what kind of notification this is (${notif.type})`
    }

    const lastChar = text.endsWith('</a>') ? text[text.length - 5] : last(text)
    if (lastChar !== '.') {
      text += '.'
    }

    text += '</li>'
    return text
  }
}

const parseCookies = function(request) {
  const list = {}
  const rc = request.headers.cookie

  if (rc) {
    for (let cookie of rc.split(';')) {
      const [ name, ...rest ] = cookie.split('=')
      list[name.trim()] = decodeURI(rest.join('='))
    }
  }

  return list
}

const getData = function(request) {
  return new Promise((resolve, reject) => {
    let body = ''

    request.on('data', data => {
      body += data

      if (body.length > 1e6) {
        request.connection.destroy()
        reject('Too much data')
      }
    })

    request.on('end', () => {
      resolve(qs.parse(body))
    })
  })
}

const handleRequest = async (request, response) => {
  const { pathname, query } = url.parse(request.url)
  const queryData = qs.parse(query)
  const cookie = parseCookies(request)

  if (request.url === '/login') {
    await page(request, response, fixWS`
      <h1>Login</h1>
      <form action="/post-login" method="post">
        <p><label>Username: <input name="username"></label></p>
        <p><label>Token: <input type="password" name="token"></label></p>
        <p><label>Session ID: <input type="password" name="sessionid"></label></p>
        <p><label>CSRF Token: <input type="password" name="csrftoken"></label></p>
        <p><button>Login</button></p>
      </form>
    `)

    return
  }

  if (request.url === '/post-login') {
    const { username, token, sessionid, csrftoken } = await getData(request)

    response.setHeader('Set-Cookie', [
      `username=${username}; HttpOnly`,
      `token=${token}; HttpOnly`,
      `sessionid=${sessionid}; HttpOnly`,
      `csrftoken=${csrftoken}; HttpOnly`
    ])

    request.headers.cookie = response.getHeader('Set-Cookie').join(';') // Cheating! To make the header show right.

    await page(request, response, fixWS`
      <p>Okay, you're logged in.</p>
    `)

    return
  }

  if (request.url === '/logout') {
    await page(request, response, fixWS`
      <h1>Log Out</h1>
      <form action="/post-logout" method="post">
        <p>Are you sure you want to log out?</p>
        <p><button>Log out</button></p>
      </form>
    `)

    return
  }

  if (request.url === '/post-logout') {
    const { username, token, sessionid, csrftoken } = await getData(request)

    const clearCookie = name => `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`

    request.headers.cookie = '' // Cheating, kind of, but to make the header print right :)
    response.setHeader('Set-Cookie', ['username', 'token', 'sessionid', 'csrftoken'].map(clearCookie))

    await page(request, response, fixWS`
      <p>Okay, you've been logged out.</p>
    `)

    return
  }

  if (pathname === '/notifications') {
    if (!cookie.username) {
      await page(request, response, fixWS`
        <p>Sorry, you can't view your notifications until you've <a href="/login">logged in</a>.</p>
      `)

      return
    }

    let { page: pageNumber = 1 } = queryData
    pageNumber = parseInt(pageNumber)
    if (isNaN(pageNumber)) {
      pageNumber = 1
    } else {
      pageNumber = Math.max(1, pageNumber)
    }

    const notifications = await getNotifications(cookie.username, cookie.token, pageNumber)
    const nText = arr => arr.map(n => templates.notification(n, cookie.username)).join('\n')

    const notificationCount = await getMessageCount(cookie.username)
    const currentPageNewCount = Math.max(notificationCount - (limit * (pageNumber - 1)), 0)
    let listText = ''

    if (currentPageNewCount > 0) {
      listText += fixWS`
        <h2>New notifications:</h2>
        <ul>
          ${nText(notifications.slice(0, currentPageNewCount))}
        </ul>
        <form action="/mark-notifications-as-read" method="post">
          <p><button>Mark as read</button></p>
        </form>
      `
    }

    listText += `
      <h2>Read notifications:</h2>
      <ul>
        ${nText(notifications.slice(currentPageNewCount))}
      </ul>
    `

    await page(request, response, fixWS`
      <h1>Notifications</h1>
      ${listText}
      <p>You are on page ${pageNumber}.
        ${notifications.length === limit && `<a href="/notifications?page=${pageNumber + 1}">Next</a>`}
        ${pageNumber > 1 && `<a href="/notifications?page=${pageNumber - 1}">Previous</a>`}</p>
    `)

    return
  }

  if (pathname === '/mark-notifications-as-read') {
    await markNotificationsAsRead(cookie.sessionid, cookie.csrftoken)

    response.writeHead(302, {
      'Location': '/notifications'
    })

    response.end()

    return
  }

  const projectMatch = pathname.match(/^\/projects\/([0-9]*)\/?/)
  if (projectMatch) {
    const projectID = projectMatch[1]

    const project = await getProject(projectID, cookie.token)
    if (project.code === 'NotFound') {
      await page(request, response, fixWS`
        Sorry, that project either doesn't exist or isn't shared.
      `)
      return
    }

    await page(request, response, fixWS`
      <h1>${project.title}</h1>
      <p><img src="${project.image}" alt="The thumbnail for this project"></p>
      <p><a href="https://projects.scratch.mit.edu/${project.id}">Download!</a></p>
      ${project.instructions ? fixWS`
        <h2>Instructions</h2>
        ${templates.longField(project.instructions)}
      ` : fixWS`
        <p>(No instructions.)</p>
      `}
      ${project.description ? fixWS`
        <h2>Notes and Credits</h2>
        ${templates.longField(project.description)}
      ` : fixWS`
        <p>(No notes and credits.)</p>
      `}
    `)

    return
  }

  const userMatch = pathname.match(/^\/users\/([a-zA-Z0-9\-_]*)\/?/)
  if (userMatch) {
    const username = userMatch[1]

    const user = await getUser(username)
    if (username.code === 'NotFound') {
      await page(request, response, fixWS`
        Sorry, that user doesn't exist.
      `)
      return
    }

    await page(request, response, fixWS`
      <h1><img src="${user.profile.images['60x60']}" height="60px" alt="This user's profile picture"> ${user.username}</h1>
      ${user.profile.bio ? fixWS`
        <h2>About Me</h2>
        ${templates.longField(user.profile.bio)}
      ` : fixWS`
        <p>(No "about me".)</p>
      `}
      ${user.profile.status ? fixWS`
        <h2>What I'm Working On</h2>
        ${templates.longField(user.profile.status)}
      ` : fixWS`
        <p>(No "what I'm working on".)</p>
      `}
    `)

    return
  }

  if (pathname === '/style.css') {
    response.writeHead(200, {
      'Content-Type': 'text/css'
    })

    response.end(await readFile('style.css'))

    return
  }

  if (pathname === '/') {
    await page(request, response, fixWS`
      You are at the homepage. Sorry, I haven't implmented any content for it yet.
    `)
  }

  await page(request, response, fixWS`
    404. Sorry, I'm not sure where you are right now.
  `)
}

const server = http.createServer((request, response) => {
  handleRequest(request, response).catch(error => {
    console.error(error)
    return page(request, response, fixWS`
      500. Sorry, there was an internal server error.
    `)
  })
})

server.listen(8000)
console.log('Go!')