Commit da3b459d authored by Emmanuel Raviart's avatar Emmanuel Raviart

Initial commit

parents
{
"env": {
"node": true
},
"globals": {
"Promise": true,
"Set": true
},
"parser": "babel-eslint",
"plugins": [
"html"
],
"rules": {
"comma-dangle": [2, "always-multiline"],
"max-len": [2, 120, 2],
"no-undef": 2,
"no-unused-expressions": 2,
"no-unused-vars": 2,
"no-use-before-define": [2, "nofunc"],
"quotes": [2, "double", "avoid-escape"],
"semi": [2, "never"],
"strict": 0
}
}
.DS_Store
node_modules
/.sapper/
yarn.lock
yarn-error.log
/templates/.*
/export/
/build/
/app/manifest/
/data.json
# Discourse-Ambiancer
_Automatic web slideshow displaying data retrieved using Discourse API_
By: Emmanuel Raviart <mailto:emmanuel@raviart.com>
Copyright (C) 2018 Paula Forteza & Emmanuel Raviart
https://framagit.org/parlement-ouvert/discourse-ambiancer
> Discourse-Ambiancer is free software; you can redistribute it and/or modify
> it under the terms of the GNU Affero General Public License as
> published by the Free Software Foundation, either version 3 of the
> License, or (at your option) any later version.
>
> Discourse-Ambiancer is distributed in the hope that it will be useful,
> but WITHOUT ANY WARRANTY; without even the implied warranty of
> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
> GNU Affero General Public License for more details.
>
> You should have received a copy of the GNU Affero General Public License
> along with this program. If not, see <http://www.gnu.org/licenses/>.
# sapper-template
The default [Sapper](https://github.com/sveltejs/sapper) template. To clone it and get started:
```bash
npx degit sveltejs/sapper-template my-app
cd my-app
npm install # or yarn!
npm run dev
```
Open up [localhost:3000](http://localhost:3000) and start clicking around.
Consult [sapper.svelte.technology](https://sapper.svelte.technology) for help getting started.
## Structure
Sapper expects to find three directories in the root of your project — `app`, `assets` and `routes`.
### app
The [app](app) directory contains the entry points for your app — `client.js`, `server.js` and (optionally) a `service-worker.js` — along with your main `App.html` component.
### assets
The [assets](assets) directory contains any static assets that should be available. These are served using [serve-static](https://github.com/expressjs/serve-static).
In your [service-worker.js](app/service-worker.js) file, you can import these as `assets` from the generated manifest...
```js
import { assets } from './manifest/service-worker.js';
```
...so that you can cache them (though you can choose not to, for example if you don't want to cache very large files).
### routes
This is the heart of your Sapper app. There are two kinds of routes — *pages*, and *server routes*.
**Pages** are Svelte components written in `.html` files. When a user first visits the application, they will be served a server-rendered version of the route in question, plus some JavaScript that 'hydrates' the page and initialises a client-side router. From that point forward, navigating to other pages is handled entirely on the client for a fast, app-like feel. (Sapper will preload and cache the code for these subsequent pages, so that navigation is instantaneous.)
**Server routes** are modules written in `.js` files, that export functions corresponding to HTTP methods. Each function receives Express `request` and `response` objects as arguments, plus a `next` function. This is useful for creating a JSON API, for example.
There are three simple rules for naming the files that define your routes:
* A file called `routes/about.html` corresponds to the `/about` route. A file called `routes/blog/[slug].html` corresponds to the `/blog/:slug` route, in which case `params.slug` is available to the route
* The file `routes/index.html` (or `routes/index.js`) corresponds to the root of your app. `routes/about/index.html` is treated the same as `routes/about.html`.
* Files and directories with a leading underscore do *not* create routes. This allows you to colocate helper modules and components with the routes that depend on them — for example you could have a file called `routes/_helpers/datetime.js` and it would *not* create a `/_helpers/datetime` route
## Webpack config
Sapper uses webpack to provide code-splitting, dynamic imports and hot module reloading, as well as compiling your Svelte components. As long as you don't do anything daft, you can edit the configuration files to add whatever loaders and plugins you'd like.
## Production mode and deployment
To start a production version of your app, run `npm run build && npm start`. This will disable hot module replacement, and activate the appropriate webpack plugins.
You can deploy your application to any environment that supports Node 8 or above. As an example, to deploy to [Now](https://zeit.co/now), run these commands:
```bash
npm install -g now
now
```
## Using external components
When using Svelte components installed from npm, such as [@sveltejs/svelte-virtual-list](https://github.com/sveltejs/svelte-virtual-list), Svelte needs the original component source (rather than any precompiled JavaScript that ships with the component). This allows the component to be rendered server-side, and also keeps your client-side app smaller.
Because of that, it's essential that webpack doesn't treat the package as an *external dependency*. You can either modify the `externals` option in [webpack/server.config.js](webpack/server.config.js), or simply install the package to `devDependencies` rather than `dependencies`, which will cause it to get bundled (and therefore compiled) with your app:
```bash
yarn add -D @sveltejs/svelte-virtual-list
```
## Bugs and feedback
Sapper is in early development, and may have the odd rough edge here and there. Please be vocal over on the [Sapper issue tracker](https://github.com/sveltejs/sapper/issues).
<main>
<svelte:component this={Page} {...props}/>
</main>
<script>
export default {
// components: {
// },
}
</script>
\ No newline at end of file
import "./global.scss"
import "bootstrap"
import { init } from "sapper/runtime.js"
import { routes } from "./manifest/client.js"
import App from "./App.html"
init({
target: document.querySelector("#sapper"),
routes,
App,
})
@import "node_modules/bootstrap/scss/bootstrap";
\ No newline at end of file
import "./global.scss"
import compression from "compression"
import fs from "fs"
import http from "http"
import path from "path"
import Polka from "polka"
import sapper from "sapper"
import serve from "serve-static"
import url from "url"
import WebSocket from "uws"
import App from "./App.html"
import { routes } from "./manifest/server.js"
import config from "../config.js"
const dataPath = path.resolve("data.json")
function loadData(path) {
const data = fs.existsSync(path) ? JSON.parse(fs.readFileSync(path)) : {}
if (data.acceptedMessagesId) {
// Remove duplicate IDs.
data.acceptedMessagesId = data.acceptedMessagesId.reduce((ids, id) => (ids.includes(id) ? ids : [...ids, id]), [])
} else {
data.acceptedMessagesId = []
}
if (data.acceptedProjectsId) {
// Remove duplicate IDs.
data.acceptedProjectsId = data.acceptedProjectsId.reduce((ids, id) => (ids.includes(id) ? ids : [...ids, id]), [])
} else {
data.acceptedProjectsId = []
}
if (data.duration === undefined) data.duration = 60
if (data.messagesCategory === undefined) data.messagesCategory = null
if (data.nowPlaying === undefined) data.nowPlaying = "default"
if (data.playingCategorySlug === undefined) data.playingCategorySlug = config.projectsCategory.slug
if (data.playingMessageId === undefined) data.playingMessageId = null
if (data.playingProjectId === undefined) data.playingProjectId = null
if (data.playingTopicId === undefined) data.playingTopicId = null
if (data.projectsCategory === undefined) data.projectsCategory = null
if (data.rejectedMessagesId) {
// Remove duplicate IDs.
data.rejectedMessagesId = data.rejectedMessagesId.reduce((ids, id) => (ids.includes(id) ? ids : [...ids, id]), [])
} else {
data.rejectedMessagesId = []
}
if (data.rejectedProjectsId) {
// Remove duplicate IDs.
data.rejectedProjectsId = data.rejectedProjectsId.reduce((ids, id) => (ids.includes(id) ? ids : [...ids, id]), [])
} else {
data.rejectedProjectsId = []
}
data.seconds = null
data.secondsRunning = false
return data
}
function saveData(path, data) {
fs.writeFileSync(path, JSON.stringify(data, null, 2))
}
function sendDataToWssClients(wss, data) {
const dataString = JSON.stringify(data, null, 2)
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(dataString)
}
})
}
const polka = Polka({
server: http.createServer(),
}).use(
compression({ threshold: 0 }),
serve("assets"),
sapper({
routes,
App,
})
)
const data = loadData(dataPath)
let seconds = 0
// https://zeit.co/blog/async-and-await
function sleep(time) {
return new Promise(resolve => setTimeout(resolve, time))
}
async function ticTac() {
while (true) {
if (data.nowPlaying === "pitches") {
if (data.playingTopicId !== null) {
// if (seconds >= data.duration) {
// data.playingTopicId = null
// seconds = 0
// }
data.seconds = seconds
sendDataToWssClients(adminWss, data)
sendDataToWssClients(homeWss, data)
}
if (data.secondsRunning) {
seconds += 1 // Must be just before sleep and end of loop.
}
} else if (data.nowPlaying === "results") {
// TODO
} else if (data.nowPlaying === "slideshow") {
if (seconds >= 10) {
seconds = 0
if (data.playingCategorySlug === config.projectsCategory.slug && data.acceptedMessagesId.length > 0) {
data.playingCategorySlug = config.messagesCategory.slug
let index = data.playingMessageId === null ? 0 : data.acceptedMessagesId.indexOf(data.playingMessageId)
data.playingTopicId = data.playingMessageId =
index < 0
? null
: index + 1 < data.acceptedMessagesId.length
? data.acceptedMessagesId[index + 1]
: data.acceptedMessagesId[0]
} else {
data.playingCategorySlug = config.projectsCategory.slug
let index = data.playingProjectId === null ? 0 : data.acceptedProjectsId.indexOf(data.playingProjectId)
data.playingTopicId = data.playingProjectId =
index < 0
? null
: index + 1 < data.acceptedProjectsId.length
? data.acceptedProjectsId[index + 1]
: data.acceptedProjectsId[0]
}
// Don't save data to minimize the risk of concurrent savings.
// saveData(dataPath, data)
sendDataToWssClients(adminWss, data)
sendDataToWssClients(homeWss, data)
if (data.secondsRunning) {
seconds += 1 // Must be just before sleep and end of loop.
}
}
} else {
// data.nowPlaying === "default"
}
await sleep(1000)
}
}
// const adminWss = new WebSocket.Server({ server: polka.server })
const adminWss = new WebSocket.Server({ noServer: true })
const homeWss = new WebSocket.Server({ noServer: true })
adminWss.on("connection", ws => {
// console.log("adminWss Connection")
ws.on("message", msg => {
// console.log("adminWss received:", msg)
const entry = JSON.parse(msg)
if (entry.type === "acceptedMessagesId") {
// const data = loadData(dataPath)
data.acceptedMessagesId = entry.acceptedMessagesId
saveData(dataPath, data)
sendDataToWssClients(homeWss, data)
} else if (entry.type === "acceptedProjectsId") {
// const data = loadData(dataPath)
data.acceptedProjectsId = entry.acceptedProjectsId
saveData(dataPath, data)
sendDataToWssClients(homeWss, data)
} else if (entry.type === "duration") {
data.duration = entry.duration
// saveData(dataPath, data)
sendDataToWssClients(homeWss, data)
} else if (entry.type === "messagesCategory") {
// console.log(entry.messagesCategory)
// const data = loadData(dataPath)
data.messagesCategory = entry.messagesCategory
saveData(dataPath, data)
sendDataToWssClients(homeWss, data)
} else if (entry.type === "nowPlaying") {
// const data = loadData(dataPath)
data.nowPlaying = entry.nowPlaying
seconds = data.seconds = 0
saveData(dataPath, data)
sendDataToWssClients(homeWss, data)
} else if (entry.type === "playingTopicId") {
// const data = loadData(dataPath)
data.playingTopicId = entry.playingTopicId
seconds = data.seconds = 0
data.secondsRunning = false
saveData(dataPath, data)
sendDataToWssClients(homeWss, data)
} else if (entry.type === "projectsCategory") {
// console.log(entry.projectsCategory)
// const data = loadData(dataPath)
data.projectsCategory = entry.projectsCategory
saveData(dataPath, data)
sendDataToWssClients(homeWss, data)
} else if (entry.type === "rejectedMessagesId") {
// const data = loadData(dataPath)
data.rejectedMessagesId = entry.rejectedMessagesId
saveData(dataPath, data)
} else if (entry.type === "rejectedProjectsId") {
// const data = loadData(dataPath)
data.rejectedProjectsId = entry.rejectedProjectsId
saveData(dataPath, data)
} else if (entry.type === "secondsRunning") {
// const data = loadData(dataPath)
data.secondsRunning = entry.secondsRunning
saveData(dataPath, data)
sendDataToWssClients(homeWss, data)
} else {
console.error("Unknown message type:", entry.type)
}
})
// const data = loadData(dataPath)
ws.send(JSON.stringify(data, null, 2))
})
homeWss.on("connection", ws => {
// console.log("homeWss Connection")
ws.on("message", msg => {
console.log("homeWss received:", msg)
})
const data = loadData(dataPath)
ws.send(JSON.stringify(data, null, 2))
})
polka.server.on("upgrade", (request, socket, head) => {
const pathname = url.parse(request.url).pathname
// console.log("on upgrade", pathname)
if (pathname === "/") {
homeWss.handleUpgrade(request, socket, head, function done(ws) {
homeWss.emit("connection", ws, request)
})
} else if (pathname === "/admin") {
adminWss.handleUpgrade(request, socket, head, function done(ws) {
adminWss.emit("connection", ws, request)
})
} else {
socket.destroy()
}
})
ticTac()
polka.listen(process.env.PORT)
import { timestamp, assets, shell, routes } from "./manifest/service-worker.js"
const ASSETS = `cache${timestamp}`
// `shell` is an array of all the files generated by webpack,
// `assets` is an array of everything in the `assets` directory
const to_cache = shell.concat(assets)
const cached = new Set(to_cache)
self.addEventListener("install", event => {
event.waitUntil(
caches
.open(ASSETS)
.then(cache => cache.addAll(to_cache))
.then(() => {
self.skipWaiting()
}),
)
})
self.addEventListener("activate", event => {
event.waitUntil(
caches.keys().then(async keys => {
// delete old caches
for (const key of keys) {
if (key !== ASSETS) await caches.delete(key)
}
self.clients.claim()
}),
)
})
self.addEventListener("fetch", event => {
if (event.request.method !== "GET") return
const url = new URL(event.request.url)
// don't try to handle e.g. data: URIs
if (!url.protocol.startsWith("http")) return
// ignore dev server requests
if (url.hostname === self.location.hostname && url.port !== self.location.port) return
// always serve assets and webpack-generated files from cache
if (url.host === self.location.host && cached.has(url.pathname)) {
event.respondWith(caches.match(event.request))
return
}
// for pages, you might want to serve a shell `index.html` file,
// which Sapper has generated for you. It's not right for every
// app, but if it's right for yours then uncomment this section
/*
if (url.origin === self.origin && routes.find(route => route.pattern.test(url.pathname))) {
event.respondWith(caches.match('/index.html'));
return;
}
*/
// for everything else, try the network first, falling back to
// cache if the user is offline. (If the pages never change, you
// might prefer a cache-first approach to a network-first one.)
event.respondWith(
caches.open(`offline${timestamp}`).then(async cache => {
try {
if (event.request.cache === "only-if-cache") {
// workaround Chrome devtools bug https://github.com/sveltejs/sapper-template/issues/34
event.request.mode = "same-origin"
}
const response = await fetch(event.request)
cache.put(event.request, response.clone())
return response
} catch (err) {
const response = await cache.match(event.request)
if (response) return response
throw err
}
}),
)
})
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#aa1e1e">
%sapper.base%
<link rel="stylesheet" href="global.css">
<link rel="manifest" href="manifest.json">
<link rel="icon" type="image/png" href="favicon.png">
<!-- Sapper generates a <style> tag containing critical CSS
for the current page. CSS for the rest of the app is
lazily loaded when it precaches secondary pages -->
%sapper.styles%
<!-- This contains the contents of the <svelte:head> component, if
the current page has one -->
%sapper.head%
</head>
<body>
<!-- The application will be rendered inside this element,
because `app/client.js` references it -->
<div id="sapper">%sapper.html%</div>
<!-- Sapper creates a <script> tag containing `app/client.js`
and anything else it needs to hydrate the app and
initialise the router -->
%sapper.scripts%
</body>
</html>
/* Cf https://google.github.io/material-design-icons/ */
@font-face {
font-family: "Material Icons";
font-style: normal;
font-weight: 400;
src: url(/material-design-icons/iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */
src: local("Material Icons"), local("MaterialIcons-Regular"),
url(/material-design-icons/iconfont/MaterialIcons-Regular.woff2) format("woff2"),
url(/material-design-icons/iconfont/MaterialIcons-Regular.woff) format("woff"),
url(/material-design-icons/iconfont/MaterialIcons-Regular.ttf) format("truetype");
}
.material-icons {
font-family: "Material Icons";
font-weight: normal;
font-style: normal;
font-size: 24px; /* Preferred icon size */
display: inline-block;
line-height: 1;
text-transform: none;
letter-spacing: normal;
word-wrap: normal;
white-space: nowrap;
direction: ltr;
/* Support for all WebKit browsers. */
-webkit-font-smoothing: antialiased;
/* Support for Safari and Chrome. */
text-rendering: optimizeLegibility;
/* Support for Firefox. */
-moz-osx-font-smoothing: grayscale;
/* Support for IE. */
font-feature-settings: "liga";
}
{
"background_color": "#ffffff",
"theme_color": "#aa1e1e",
"name": "TODO",
"short_name": "TODO",
"display": "minimal-ui",
"start_url": "/",
"icons": [
{
"src": "svelte-logo-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "svelte-logo-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
../node_modules/material-design-icons
\ No newline at end of file
File added
<nav class="bg-secondary fixed-top navbar navbar-dark navbar-expand-lg">
<a class="navbar-brand" href="/" rel="prefetch">{config.title}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Basculer l'affichage de la navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="ml-auto navbar-nav">
{#each menuItems as menuItem (menuItem.slug)}
{#if menuItem.slug === slug}
<li class="nav-item active">
<a class="nav-link" href="{menuItem.urlPath}" rel="prefetch">{menuItem.title} <span class="sr-only">(actuel)</span></a>
</li>
{:else}
<li class="nav-item">
<a class="nav-link" href="{menuItem.urlPath}" rel="prefetch">{menuItem.title}</a>
</li>
{/if}
{/each}
</ul>
</div>
</nav>
<div style="height: 40px;"></div>
<script>
import config from "../config.js"
export default {
helpers: {
config,
menuItems: [
{
slug: "default",
title: "Accueil",
urlPath: "/admin",
},
{
slug: "defis",
title: "Défis",
urlPath: "/admin/defis",
},
{
slug: "messages",
title: "Messages",
urlPath: "/admin/messages",
},
{
slug: "pitches",
title: "Pitches",
urlPath: "/admin/pitches",
},
{
slug: "slideshow",
title: "Diaporama",
urlPath: "/admin/slideshow",
},
],
},
}
</script>
\ No newline at end of file
<article class="card topic-screen">
{#if topicEmbed.image_url}
<img class="card-img-top image" src="{topicEmbed.image_url}" alt="logo de la fiche">
{/if}
<div class="card-body">
<h1 class="card-title display-3">
{#if topicEmbed.showId}
<span class="badge badge-primary">#{topicEmbed.id}</span>
{/if}
{topicEmbed.title}
</h1>
<p class="card-text">{@html topicEmbed.excerpt}</p>
<div>
<div class="d-flex footer justify-content-between">
{#if duration !== null && seconds !== null}
<span class="display-1{duration < seconds ? " bg-danger text-white" : duration - 10 < seconds ? " bg-warning text-dark" : ""} pl-1 pr-1">{toMinutesSeconds(duration - seconds)}
</span>
<audio id="ring_sound" src="/ring.mp3"></audio>
{#if duration < seconds}
<script>
if (document !== undefined) {
document.getElementById("ring_sound").play()
}
</script>
{/if}
{/if}
<a class="card-link display-4" href="{urlResolve(config.apiUrl, `/t/${topicEmbed.slug}/${topicEmbed.id}`)}">{urlResolve(config.apiUrl, `/t/${topicEmbed.id}`)}</a>
</div>
{#if nextTopicEmbed !== null}
<hr>
<div class="bg-secondary lead text-right text-white">
Suivant :
{#if nextTopicEmbed.showId}
<b>#{nextTopicEmbed.id}</b>
{/if}
{nextTopicEmbed.title}
</div>
{/if}
</div>
</div>
</article>
<style type="text/scss">
.image {
max-height: 360px;
object-fit: contain;
}
.footer {
align-items: baseline;
}
.topic-screen {
height: 100vh;
}
</style>
<script>
import urlResolve from "url-resolve"
import config from "../config.js"
import {toMinutesSeconds} from "../utils.js"