« get me outta code hell

scratchrlol - Simple HTML-based Scratch client
summary refs log tree commit diff
diff options
context:
space:
mode:
-rwxr-xr-xindex.js42
1 files changed, 42 insertions, 0 deletions
diff --git a/index.js b/index.js
index 361803b..24e8454 100755
--- a/index.js
+++ b/index.js
@@ -88,6 +88,19 @@ const compareArr = (a1, a2) => a1.length === a2.length && a1.every((x, i) => typ
 const filterHTML = text => text.replace(/</g, '&lt;').replace(/>/g, '&gt;')
 const pluralize = (word, n) => n === 1 ? word : word + 's'
 
+function shuffle(array) {
+  // Stolen :) https://stackoverflow.com/a/2450976/4633828
+  let currentIndex = array.length
+  while (currentIndex !== 0) {
+    const randomIndex = Math.floor(Math.random() * currentIndex)
+    currentIndex -= 1
+    const temporaryValue = array[currentIndex]
+    array[currentIndex] = array[randomIndex]
+    array[randomIndex] = temporaryValue
+  }
+  return array
+}
+
 const templates = {
   user: username => `<a href="/users/${username}">${username}</a>`,
   project: (name, id) => `<a href="/projects/${id}">${filterHTML(name.trim())}</a>`,
@@ -295,6 +308,22 @@ const getData = function(request) {
   })
 }
 
+const explore = {
+  users: async () => {
+    const getUrl = mode => {
+      const limit = Math.ceil(Math.random() * 40)
+      const offset = Math.floor(Math.random() * 400)
+      return `https://api.scratch.mit.edu/explore/projects?mode=${mode}&limit=${limit}&offset=${offset}`
+    }
+
+    const fetchResults = await Promise.all(['recent', 'trending', 'popular'].map(m => fetch(getUrl(m)).then(res => res.json())))
+    console.log(fetchResults)
+    const projects = fetchResults.reduce((acc, arr) => acc.concat(arr), [])
+    const selected = shuffle(projects).slice(0, 15)
+    return selected.map(project => project.author)
+  }
+}
+
 const handleRequest = async (request, response) => {
   const { pathname, query } = url.parse(request.url)
   const queryData = qs.parse(query)
@@ -558,6 +587,19 @@ const handleRequest = async (request, response) => {
     }
   }
 
+  if (urlParts[0] === 'explore') {
+    if (compareArr(urlParts.slice(1), ['users'])) {
+      const users = await explore.users()
+
+      return page(request, response, fixWS`
+        <h1>Explore Users</h1>
+        <p>Here are some randomly picked users to check out:</p>
+        <p>${users.map(u => templates.user(u.username, u.id)).join(', ')}</p>
+        <p>(Users are randomly selected from the authors of a variety of recent and trending projects.)</p>
+      `)
+    }
+  }
+
   if (compareArr(urlParts, ['style.css'])) {
     response.writeHead(200, {
       'Content-Type': 'text/css'