<%= get_flash(@conn, :info) %>
+<%= get_flash(@conn, :error) %>
+ <%= @inner_content %> +diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..485e324
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,38 @@
+# The directory Mix will write compiled artifacts to.
+/_build/
+
+# If you run "mix test --cover", coverage assets end up here.
+/cover/
+
+# The directory Mix downloads your dependencies sources to.
+/deps/
+
+# Where 3rd-party dependencies like ExDoc output generated docs.
+/doc/
+
+# Ignore .fetch files in case you like to edit your project deps locally.
+/.fetch
+
+# If the VM crashes, it generates a dump, let's ignore it too.
+erl_crash.dump
+
+# Also ignore archive artifacts (built via "mix archive.build").
+*.ez
+
+# Ignore package tarball (built via "mix hex.build").
+demo-*.tar
+
+# Ignore assets that are produced by build tools.
+/priv/static/assets/
+
+# Ignore digested assets cache.
+/priv/static/cache_manifest.json
+
+# In case you use Node.js/npm, you want to ignore these.
+npm-debug.log
+/assets/node_modules/
+
+# Database files
+*.db
+*.db-*
+
diff --git a/assets/css/app.css b/assets/css/app.css
new file mode 100644
index 0000000..3ed0af3
--- /dev/null
+++ b/assets/css/app.css
@@ -0,0 +1,95 @@
+/* This file is for your main application CSS */
+@import "./phoenix.css";
+
+/* Alerts and form errors used by phx.new */
+.alert {
+ padding: 15px;
+ margin-bottom: 20px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+}
+.alert-info {
+ color: #31708f;
+ background-color: #d9edf7;
+ border-color: #bce8f1;
+}
+.alert-warning {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+ border-color: #faebcc;
+}
+.alert-danger {
+ color: #a94442;
+ background-color: #f2dede;
+ border-color: #ebccd1;
+}
+.alert p {
+ margin-bottom: 0;
+}
+.alert:empty {
+ display: none;
+}
+.invalid-feedback {
+ color: #a94442;
+ display: block;
+ margin: -1rem 0 2rem;
+}
+
+/* LiveView specific classes for your customization */
+.phx-no-feedback.invalid-feedback,
+.phx-no-feedback .invalid-feedback {
+ display: none;
+}
+
+.phx-click-loading {
+ opacity: 0.5;
+ transition: opacity 1s ease-out;
+}
+
+.phx-disconnected{
+ cursor: wait;
+}
+.phx-disconnected *{
+ pointer-events: none;
+}
+
+.phx-modal {
+ opacity: 1!important;
+ position: fixed;
+ z-index: 1;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ background-color: rgb(0,0,0);
+ background-color: rgba(0,0,0,0.4);
+}
+
+.phx-modal-content {
+ background-color: #fefefe;
+ margin: 15vh auto;
+ padding: 20px;
+ border: 1px solid #888;
+ width: 80%;
+}
+
+.phx-modal-close {
+ color: #aaa;
+ float: right;
+ font-size: 28px;
+ font-weight: bold;
+}
+
+.phx-modal-close:hover,
+.phx-modal-close:focus {
+ color: black;
+ text-decoration: none;
+ cursor: pointer;
+}
+
+.phx-hero canvas {
+ width: 100%;
+ height: 200px;
+ image-rendering: pixelated;
+}
diff --git a/assets/css/app.css~ b/assets/css/app.css~
new file mode 100644
index 0000000..24920cf
--- /dev/null
+++ b/assets/css/app.css~
@@ -0,0 +1,89 @@
+/* This file is for your main application CSS */
+@import "./phoenix.css";
+
+/* Alerts and form errors used by phx.new */
+.alert {
+ padding: 15px;
+ margin-bottom: 20px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+}
+.alert-info {
+ color: #31708f;
+ background-color: #d9edf7;
+ border-color: #bce8f1;
+}
+.alert-warning {
+ color: #8a6d3b;
+ background-color: #fcf8e3;
+ border-color: #faebcc;
+}
+.alert-danger {
+ color: #a94442;
+ background-color: #f2dede;
+ border-color: #ebccd1;
+}
+.alert p {
+ margin-bottom: 0;
+}
+.alert:empty {
+ display: none;
+}
+.invalid-feedback {
+ color: #a94442;
+ display: block;
+ margin: -1rem 0 2rem;
+}
+
+/* LiveView specific classes for your customization */
+.phx-no-feedback.invalid-feedback,
+.phx-no-feedback .invalid-feedback {
+ display: none;
+}
+
+.phx-click-loading {
+ opacity: 0.5;
+ transition: opacity 1s ease-out;
+}
+
+.phx-disconnected{
+ cursor: wait;
+}
+.phx-disconnected *{
+ pointer-events: none;
+}
+
+.phx-modal {
+ opacity: 1!important;
+ position: fixed;
+ z-index: 1;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ background-color: rgb(0,0,0);
+ background-color: rgba(0,0,0,0.4);
+}
+
+.phx-modal-content {
+ background-color: #fefefe;
+ margin: 15vh auto;
+ padding: 20px;
+ border: 1px solid #888;
+ width: 80%;
+}
+
+.phx-modal-close {
+ color: #aaa;
+ float: right;
+ font-size: 28px;
+ font-weight: bold;
+}
+
+.phx-modal-close:hover,
+.phx-modal-close:focus {
+ color: black;
+ text-decoration: none;
+ cursor: pointer;
+}
diff --git a/assets/css/phoenix.css b/assets/css/phoenix.css
new file mode 100644
index 0000000..0d59050
--- /dev/null
+++ b/assets/css/phoenix.css
@@ -0,0 +1,101 @@
+/* Includes some default style for the starter application.
+ * This can be safely deleted to start fresh.
+ */
+
+/* Milligram v1.4.1 https://milligram.github.io
+ * Copyright (c) 2020 CJ Patoilo Licensed under the MIT license
+ */
+
+*,*:after,*:before{box-sizing:inherit}html{box-sizing:border-box;font-size:62.5%}body{color:#000000;font-family:'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;font-size:1.6em;font-weight:300;letter-spacing:.01em;line-height:1.6}blockquote{border-left:0.3rem solid #d1d1d1;margin-left:0;margin-right:0;padding:1rem 1.5rem}blockquote *:last-child{margin-bottom:0}.button,button,input[type='button'],input[type='reset'],input[type='submit']{background-color:#0069d9;border:0.1rem solid #0069d9;border-radius:.4rem;color:#fff;cursor:pointer;display:inline-block;font-size:1.1rem;font-weight:700;height:3.8rem;letter-spacing:.1rem;line-height:3.8rem;padding:0 3.0rem;text-align:center;text-decoration:none;text-transform:uppercase;white-space:nowrap}.button:focus,.button:hover,button:focus,button:hover,input[type='button']:focus,input[type='button']:hover,input[type='reset']:focus,input[type='reset']:hover,input[type='submit']:focus,input[type='submit']:hover{background-color:#606c76;border-color:#606c76;color:#fff;outline:0}.button[disabled],button[disabled],input[type='button'][disabled],input[type='reset'][disabled],input[type='submit'][disabled]{cursor:default;opacity:.5}.button[disabled]:focus,.button[disabled]:hover,button[disabled]:focus,button[disabled]:hover,input[type='button'][disabled]:focus,input[type='button'][disabled]:hover,input[type='reset'][disabled]:focus,input[type='reset'][disabled]:hover,input[type='submit'][disabled]:focus,input[type='submit'][disabled]:hover{background-color:#0069d9;border-color:#0069d9}.button.button-outline,button.button-outline,input[type='button'].button-outline,input[type='reset'].button-outline,input[type='submit'].button-outline{background-color:transparent;color:#0069d9}.button.button-outline:focus,.button.button-outline:hover,button.button-outline:focus,button.button-outline:hover,input[type='button'].button-outline:focus,input[type='button'].button-outline:hover,input[type='reset'].button-outline:focus,input[type='reset'].button-outline:hover,input[type='submit'].button-outline:focus,input[type='submit'].button-outline:hover{background-color:transparent;border-color:#606c76;color:#606c76}.button.button-outline[disabled]:focus,.button.button-outline[disabled]:hover,button.button-outline[disabled]:focus,button.button-outline[disabled]:hover,input[type='button'].button-outline[disabled]:focus,input[type='button'].button-outline[disabled]:hover,input[type='reset'].button-outline[disabled]:focus,input[type='reset'].button-outline[disabled]:hover,input[type='submit'].button-outline[disabled]:focus,input[type='submit'].button-outline[disabled]:hover{border-color:inherit;color:#0069d9}.button.button-clear,button.button-clear,input[type='button'].button-clear,input[type='reset'].button-clear,input[type='submit'].button-clear{background-color:transparent;border-color:transparent;color:#0069d9}.button.button-clear:focus,.button.button-clear:hover,button.button-clear:focus,button.button-clear:hover,input[type='button'].button-clear:focus,input[type='button'].button-clear:hover,input[type='reset'].button-clear:focus,input[type='reset'].button-clear:hover,input[type='submit'].button-clear:focus,input[type='submit'].button-clear:hover{background-color:transparent;border-color:transparent;color:#606c76}.button.button-clear[disabled]:focus,.button.button-clear[disabled]:hover,button.button-clear[disabled]:focus,button.button-clear[disabled]:hover,input[type='button'].button-clear[disabled]:focus,input[type='button'].button-clear[disabled]:hover,input[type='reset'].button-clear[disabled]:focus,input[type='reset'].button-clear[disabled]:hover,input[type='submit'].button-clear[disabled]:focus,input[type='submit'].button-clear[disabled]:hover{color:#0069d9}code{background:#f4f5f6;border-radius:.4rem;font-size:86%;margin:0 .2rem;padding:.2rem .5rem;white-space:nowrap}pre{background:#f4f5f6;border-left:0.3rem solid #0069d9;overflow-y:hidden}pre>code{border-radius:0;display:block;padding:1rem 1.5rem;white-space:pre}hr{border:0;border-top:0.1rem solid #f4f5f6;margin:3.0rem 0}input[type='color'],input[type='date'],input[type='datetime'],input[type='datetime-local'],input[type='email'],input[type='month'],input[type='number'],input[type='password'],input[type='search'],input[type='tel'],input[type='text'],input[type='url'],input[type='week'],input:not([type]),textarea,select{-webkit-appearance:none;background-color:transparent;border:0.1rem solid #d1d1d1;border-radius:.4rem;box-shadow:none;box-sizing:inherit;height:3.8rem;padding:.6rem 1.0rem .7rem;width:100%}input[type='color']:focus,input[type='date']:focus,input[type='datetime']:focus,input[type='datetime-local']:focus,input[type='email']:focus,input[type='month']:focus,input[type='number']:focus,input[type='password']:focus,input[type='search']:focus,input[type='tel']:focus,input[type='text']:focus,input[type='url']:focus,input[type='week']:focus,input:not([type]):focus,textarea:focus,select:focus{border-color:#0069d9;outline:0}select{background:url('data:image/svg+xml;utf8,') center right no-repeat;padding-right:3.0rem}select:focus{background-image:url('data:image/svg+xml;utf8,')}select[multiple]{background:none;height:auto}textarea{min-height:6.5rem}label,legend{display:block;font-size:1.6rem;font-weight:700;margin-bottom:.5rem}fieldset{border-width:0;padding:0}input[type='checkbox'],input[type='radio']{display:inline}.label-inline{display:inline-block;font-weight:normal;margin-left:.5rem}.container{margin:0 auto;max-width:112.0rem;padding:0 2.0rem;position:relative;width:100%}.row{display:flex;flex-direction:column;padding:0;width:100%}.row.row-no-padding{padding:0}.row.row-no-padding>.column{padding:0}.row.row-wrap{flex-wrap:wrap}.row.row-top{align-items:flex-start}.row.row-bottom{align-items:flex-end}.row.row-center{align-items:center}.row.row-stretch{align-items:stretch}.row.row-baseline{align-items:baseline}.row .column{display:block;flex:1 1 auto;margin-left:0;max-width:100%;width:100%}.row .column.column-offset-10{margin-left:10%}.row .column.column-offset-20{margin-left:20%}.row .column.column-offset-25{margin-left:25%}.row .column.column-offset-33,.row .column.column-offset-34{margin-left:33.3333%}.row .column.column-offset-40{margin-left:40%}.row .column.column-offset-50{margin-left:50%}.row .column.column-offset-60{margin-left:60%}.row .column.column-offset-66,.row .column.column-offset-67{margin-left:66.6666%}.row .column.column-offset-75{margin-left:75%}.row .column.column-offset-80{margin-left:80%}.row .column.column-offset-90{margin-left:90%}.row .column.column-10{flex:0 0 10%;max-width:10%}.row .column.column-20{flex:0 0 20%;max-width:20%}.row .column.column-25{flex:0 0 25%;max-width:25%}.row .column.column-33,.row .column.column-34{flex:0 0 33.3333%;max-width:33.3333%}.row .column.column-40{flex:0 0 40%;max-width:40%}.row .column.column-50{flex:0 0 50%;max-width:50%}.row .column.column-60{flex:0 0 60%;max-width:60%}.row .column.column-66,.row .column.column-67{flex:0 0 66.6666%;max-width:66.6666%}.row .column.column-75{flex:0 0 75%;max-width:75%}.row .column.column-80{flex:0 0 80%;max-width:80%}.row .column.column-90{flex:0 0 90%;max-width:90%}.row .column .column-top{align-self:flex-start}.row .column .column-bottom{align-self:flex-end}.row .column .column-center{align-self:center}@media (min-width: 40rem){.row{flex-direction:row;margin-left:-1.0rem;width:calc(100% + 2.0rem)}.row .column{margin-bottom:inherit;padding:0 1.0rem}}a{color:#0069d9;text-decoration:none}a:focus,a:hover{color:#606c76}dl,ol,ul{list-style:none;margin-top:0;padding-left:0}dl dl,dl ol,dl ul,ol dl,ol ol,ol ul,ul dl,ul ol,ul ul{font-size:90%;margin:1.5rem 0 1.5rem 3.0rem}ol{list-style:decimal inside}ul{list-style:circle inside}.button,button,dd,dt,li{margin-bottom:1.0rem}fieldset,input,select,textarea{margin-bottom:1.5rem}blockquote,dl,figure,form,ol,p,pre,table,ul{margin-bottom:2.5rem}table{border-spacing:0;display:block;overflow-x:auto;text-align:left;width:100%}td,th{border-bottom:0.1rem solid #e1e1e1;padding:1.2rem 1.5rem}td:first-child,th:first-child{padding-left:0}td:last-child,th:last-child{padding-right:0}@media (min-width: 40rem){table{display:table;overflow-x:initial}}b,strong{font-weight:bold}p{margin-top:0}h1,h2,h3,h4,h5,h6{font-weight:300;letter-spacing:-.1rem;margin-bottom:2.0rem;margin-top:0}h1{font-size:4.6rem;line-height:1.2}h2{font-size:3.6rem;line-height:1.25}h3{font-size:2.8rem;line-height:1.3}h4{font-size:2.2rem;letter-spacing:-.08rem;line-height:1.35}h5{font-size:1.8rem;letter-spacing:-.05rem;line-height:1.5}h6{font-size:1.6rem;letter-spacing:0;line-height:1.4}img{max-width:100%}.clearfix:after{clear:both;content:' ';display:table}.float-left{float:left}.float-right{float:right}
+
+/* General style */
+h1{font-size: 3.6rem; line-height: 1.25}
+h2{font-size: 2.8rem; line-height: 1.3}
+h3{font-size: 2.2rem; letter-spacing: -.08rem; line-height: 1.35}
+h4{font-size: 1.8rem; letter-spacing: -.05rem; line-height: 1.5}
+h5{font-size: 1.6rem; letter-spacing: 0; line-height: 1.4}
+h6{font-size: 1.4rem; letter-spacing: 0; line-height: 1.2}
+pre{padding: 1em;}
+
+.container{
+ margin: 0 auto;
+ max-width: 80.0rem;
+ padding: 0 2.0rem;
+ position: relative;
+ width: 100%
+}
+select {
+ width: auto;
+}
+
+/* Phoenix promo and logo */
+.phx-hero {
+ text-align: center;
+ border-bottom: 1px solid #e3e3e3;
+ background: #eee;
+ border-radius: 6px;
+ padding: 3em 3em 1em;
+ margin-bottom: 3rem;
+ font-weight: 200;
+ font-size: 120%;
+}
+.phx-hero input {
+ background: #ffffff;
+}
+.phx-logo {
+ min-width: 300px;
+ margin: 1rem;
+ display: block;
+}
+.phx-logo img {
+ width: auto;
+ display: block;
+}
+
+/* Headers */
+header {
+ width: 100%;
+ background: #fdfdfd;
+ border-bottom: 1px solid #eaeaea;
+ margin-bottom: 2rem;
+}
+header section {
+ align-items: center;
+ display: flex;
+ flex-direction: column;
+ justify-content: space-between;
+}
+header section :first-child {
+ order: 2;
+}
+header section :last-child {
+ order: 1;
+}
+header nav ul,
+header nav li {
+ margin: 0;
+ padding: 0;
+ display: block;
+ text-align: right;
+ white-space: nowrap;
+}
+header nav ul {
+ margin: 1rem;
+ margin-top: 0;
+}
+header nav a {
+ display: block;
+}
+
+@media (min-width: 40.0rem) { /* Small devices (landscape phones, 576px and up) */
+ header section {
+ flex-direction: row;
+ }
+ header nav ul {
+ margin: 1rem;
+ }
+ .phx-logo {
+ flex-basis: 527px;
+ margin: 2rem 1rem;
+ }
+}
diff --git a/assets/js/app.js b/assets/js/app.js
new file mode 100644
index 0000000..85bf1a4
--- /dev/null
+++ b/assets/js/app.js
@@ -0,0 +1,47 @@
+// We import the CSS which is extracted to its own file by esbuild.
+// Remove this line if you add a your own CSS build pipeline (e.g postcss).
+import "../css/app.css"
+
+// If you want to use Phoenix channels, run `mix help phx.gen.channel`
+// to get started and then uncomment the line below.
+import "./user_socket.js"
+
+// You can include dependencies in two ways.
+//
+// The simplest option is to put them in assets/vendor and
+// import them using relative paths:
+//
+// import "./vendor/some-package.js"
+//
+// Alternatively, you can `npm install some-package` and import
+// them using a path starting with the package name:
+//
+// import "some-package"
+//
+
+// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
+import "phoenix_html"
+// Establish Phoenix Socket and LiveView configuration.
+import {Socket} from "phoenix"
+import {LiveSocket} from "phoenix_live_view"
+import topbar from "../vendor/topbar"
+
+let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
+let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
+
+// Show progress bar on live navigation and form submits
+topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
+window.addEventListener("phx:page-loading-start", info => topbar.show())
+window.addEventListener("phx:page-loading-stop", info => topbar.hide())
+
+// connect if there are any LiveViews on the page
+liveSocket.connect()
+
+// expose liveSocket on window for web console debug logs and latency simulation:
+// >> liveSocket.enableDebug()
+// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session
+// >> liveSocket.disableLatencySim()
+window.liveSocket = liveSocket
+
+//
+
diff --git a/assets/js/user_socket.js b/assets/js/user_socket.js
new file mode 100644
index 0000000..7f53f37
--- /dev/null
+++ b/assets/js/user_socket.js
@@ -0,0 +1,153 @@
+// NOTE: The contents of this file will only be executed if
+// you uncomment its entry in "assets/js/app.js".
+
+// Bring in Phoenix channels client library:
+import {Socket} from "phoenix"
+
+// And connect to the path in "lib/demo_web/endpoint.ex". We pass the
+// token for authentication. Read below how it should be used.
+let socket = new Socket("/socket", {params: {token: window.userToken}})
+
+// When you connect, you'll often need to authenticate the client.
+// For example, imagine you have an authentication plug, `MyAuth`,
+// which authenticates the session and assigns a `:current_user`.
+// If the current user exists you can assign the user's token in
+// the connection for use in the layout.
+//
+// In your "lib/demo_web/router.ex":
+//
+// pipeline :browser do
+// ...
+// plug MyAuth
+// plug :put_user_token
+// end
+//
+// defp put_user_token(conn, _) do
+// if current_user = conn.assigns[:current_user] do
+// token = Phoenix.Token.sign(conn, "user socket", current_user.id)
+// assign(conn, :user_token, token)
+// else
+// conn
+// end
+// end
+//
+// Now you need to pass this token to JavaScript. You can do so
+// inside a script tag in "lib/demo_web/templates/layout/app.html.heex":
+//
+//
+//
+// You will need to verify the user token in the "connect/3" function
+// in "lib/demo_web/channels/user_socket.ex":
+//
+// def connect(%{"token" => token}, socket, _connect_info) do
+// # max_age: 1209600 is equivalent to two weeks in seconds
+// case Phoenix.Token.verify(socket, "user socket", token, max_age: 1_209_600) do
+// {:ok, user_id} ->
+// {:ok, assign(socket, :user, user_id)}
+//
+// {:error, reason} ->
+// :error
+// end
+// end
+//
+// Finally, connect to the socket:
+socket.connect()
+
+const draw_graph = (ctx, tbl) => {
+ let tmax=0
+ for(v of tbl) {
+ tmax = Math.max(v, tmax)
+ }
+ ctx.fillStyle = "#fff"
+ ctx.strokeStyle = "#00f"
+ ctx.fillRect(0, 0, 400, 200)
+ ctx.lineWidth = 2
+ for(let i=0; i < tbl.length; ++i) {
+ ctx.beginPath();
+ ctx.moveTo(200*Math.sqrt(i/200), 200)
+ ctx.lineTo(200*Math.sqrt(i/200),
+ 200-(200*Math.sqrt(tbl[i]/tmax)))
+ ctx.stroke();
+
+ }
+ ctx.fillStyle = "#000"
+ for (let i of [0, 2, 5, 10, 25, 50, 100, 200, 500]) {
+ ctx.fillText(i, 200*Math.sqrt(i/200), 10)
+ }
+}
+
+let interval = null
+const ping = () => {
+ const canvas = document.querySelector("#ping_canvas")
+ ctx = canvas.getContext("2d")
+ const tbl = new Array(400).fill(0)
+ return () => {
+ let d1 = Date.now();
+ let id = (Math.random()*0xffffffff).toString(16)
+ channel.push("ping", {id})
+ .receive("ok", resp => {
+ if (resp.id != id) {
+ console.log("ERROR :'(", id, resp);
+ if (interval) {
+ clearInterval(interval)
+ interval = null
+ }
+ return;
+ }
+ let t = Date.now()-d1
+ //console.log("PING!", t)
+ tbl[Math.min(t, 399)] += 1
+ draw_graph(ctx, tbl)
+ })
+ }
+}
+
+// Now that you are connected, you can join channels with a topic.
+// Let's assume you have a channel with a topic named `room` and the
+// subtopic is its id - in this case lobby:
+let channel = socket.channel("room:lobby", {})
+
+channel.join()
+ .receive("ok", resp => {
+ console.log("Joined successfully", resp)
+ interval = setInterval(ping(), 100)
+ })
+ .receive("error", resp => {
+ if (interval) {
+ clearInterval(interval)
+ interval = null
+ }
+ console.log("Unable to join", resp)
+ })
+
+const input_fib = document.querySelector("#in_fib")
+const btn_fib = document.querySelector("#btn_fib")
+const res_div = document.querySelector("#results")
+let queries = {}
+
+btn_fib.onclick = evt => {
+ console.log(input_fib.value)
+ channel.push("fib", {query: input_fib.value})
+ .receive("ok", resp => {
+ const elem = document.createElement("div")
+ elem.innerHTML = "Waiting... " + input_fib.value
+ res_div.prepend(elem)
+ queries[resp.id] = elem
+ console.log("OK", resp)
+ })
+ .receive("error", err => {
+ console.log("Error", resp)
+ })
+}
+
+channel.on("response", resp => {
+ if (queries[resp.id]) {
+ const elem = queries[resp.id]
+ elem.innerHTML = resp.query + " => " + resp.result
+ } else {
+ console.log("Query not found :'''(((")
+ }
+ console.log(resp)
+})
+
+export default socket
diff --git a/assets/vendor/topbar.js b/assets/vendor/topbar.js
new file mode 100644
index 0000000..ff7fbb6
--- /dev/null
+++ b/assets/vendor/topbar.js
@@ -0,0 +1,157 @@
+/**
+ * @license MIT
+ * topbar 1.0.0, 2021-01-06
+ * http://buunguyen.github.io/topbar
+ * Copyright (c) 2021 Buu Nguyen
+ */
+(function (window, document) {
+ "use strict";
+
+ // https://gist.github.com/paulirish/1579671
+ (function () {
+ var lastTime = 0;
+ var vendors = ["ms", "moz", "webkit", "o"];
+ for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
+ window.requestAnimationFrame =
+ window[vendors[x] + "RequestAnimationFrame"];
+ window.cancelAnimationFrame =
+ window[vendors[x] + "CancelAnimationFrame"] ||
+ window[vendors[x] + "CancelRequestAnimationFrame"];
+ }
+ if (!window.requestAnimationFrame)
+ window.requestAnimationFrame = function (callback, element) {
+ var currTime = new Date().getTime();
+ var timeToCall = Math.max(0, 16 - (currTime - lastTime));
+ var id = window.setTimeout(function () {
+ callback(currTime + timeToCall);
+ }, timeToCall);
+ lastTime = currTime + timeToCall;
+ return id;
+ };
+ if (!window.cancelAnimationFrame)
+ window.cancelAnimationFrame = function (id) {
+ clearTimeout(id);
+ };
+ })();
+
+ var canvas,
+ progressTimerId,
+ fadeTimerId,
+ currentProgress,
+ showing,
+ addEvent = function (elem, type, handler) {
+ if (elem.addEventListener) elem.addEventListener(type, handler, false);
+ else if (elem.attachEvent) elem.attachEvent("on" + type, handler);
+ else elem["on" + type] = handler;
+ },
+ options = {
+ autoRun: true,
+ barThickness: 3,
+ barColors: {
+ 0: "rgba(26, 188, 156, .9)",
+ ".25": "rgba(52, 152, 219, .9)",
+ ".50": "rgba(241, 196, 15, .9)",
+ ".75": "rgba(230, 126, 34, .9)",
+ "1.0": "rgba(211, 84, 0, .9)",
+ },
+ shadowBlur: 10,
+ shadowColor: "rgba(0, 0, 0, .6)",
+ className: null,
+ },
+ repaint = function () {
+ canvas.width = window.innerWidth;
+ canvas.height = options.barThickness * 5; // need space for shadow
+
+ var ctx = canvas.getContext("2d");
+ ctx.shadowBlur = options.shadowBlur;
+ ctx.shadowColor = options.shadowColor;
+
+ var lineGradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
+ for (var stop in options.barColors)
+ lineGradient.addColorStop(stop, options.barColors[stop]);
+ ctx.lineWidth = options.barThickness;
+ ctx.beginPath();
+ ctx.moveTo(0, options.barThickness / 2);
+ ctx.lineTo(
+ Math.ceil(currentProgress * canvas.width),
+ options.barThickness / 2
+ );
+ ctx.strokeStyle = lineGradient;
+ ctx.stroke();
+ },
+ createCanvas = function () {
+ canvas = document.createElement("canvas");
+ var style = canvas.style;
+ style.position = "fixed";
+ style.top = style.left = style.right = style.margin = style.padding = 0;
+ style.zIndex = 100001;
+ style.display = "none";
+ if (options.className) canvas.classList.add(options.className);
+ document.body.appendChild(canvas);
+ addEvent(window, "resize", repaint);
+ },
+ topbar = {
+ config: function (opts) {
+ for (var key in opts)
+ if (options.hasOwnProperty(key)) options[key] = opts[key];
+ },
+ show: function () {
+ if (showing) return;
+ showing = true;
+ if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId);
+ if (!canvas) createCanvas();
+ canvas.style.opacity = 1;
+ canvas.style.display = "block";
+ topbar.progress(0);
+ if (options.autoRun) {
+ (function loop() {
+ progressTimerId = window.requestAnimationFrame(loop);
+ topbar.progress(
+ "+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2)
+ );
+ })();
+ }
+ },
+ progress: function (to) {
+ if (typeof to === "undefined") return currentProgress;
+ if (typeof to === "string") {
+ to =
+ (to.indexOf("+") >= 0 || to.indexOf("-") >= 0
+ ? currentProgress
+ : 0) + parseFloat(to);
+ }
+ currentProgress = to > 1 ? 1 : to;
+ repaint();
+ return currentProgress;
+ },
+ hide: function () {
+ if (!showing) return;
+ showing = false;
+ if (progressTimerId != null) {
+ window.cancelAnimationFrame(progressTimerId);
+ progressTimerId = null;
+ }
+ (function loop() {
+ if (topbar.progress("+.1") >= 1) {
+ canvas.style.opacity -= 0.05;
+ if (canvas.style.opacity <= 0.05) {
+ canvas.style.display = "none";
+ fadeTimerId = null;
+ return;
+ }
+ }
+ fadeTimerId = window.requestAnimationFrame(loop);
+ })();
+ },
+ };
+
+ if (typeof module === "object" && typeof module.exports === "object") {
+ module.exports = topbar;
+ } else if (typeof define === "function" && define.amd) {
+ define(function () {
+ return topbar;
+ });
+ } else {
+ this.topbar = topbar;
+ }
+}.call(this, window, document));
diff --git a/config/config.exs b/config/config.exs
new file mode 100644
index 0000000..a38746e
--- /dev/null
+++ b/config/config.exs
@@ -0,0 +1,52 @@
+# This file is responsible for configuring your application
+# and its dependencies with the aid of the Config module.
+#
+# This configuration file is loaded before any dependency and
+# is restricted to this project.
+
+# General application configuration
+import Config
+
+config :demo,
+ ecto_repos: [Demo.Repo]
+
+# Configures the endpoint
+config :demo, DemoWeb.Endpoint,
+ url: [host: "localhost"],
+ render_errors: [view: DemoWeb.ErrorView, accepts: ~w(html json), layout: false],
+ pubsub_server: Demo.PubSub,
+ live_view: [signing_salt: "QHnkraNV"]
+
+# Configures the mailer
+#
+# By default it uses the "Local" adapter which stores the emails
+# locally. You can see the emails in your browser, at "/dev/mailbox".
+#
+# For production it's recommended to configure a different adapter
+# at the `config/runtime.exs`.
+config :demo, Demo.Mailer, adapter: Swoosh.Adapters.Local
+
+# Swoosh API client is needed for adapters other than SMTP.
+config :swoosh, :api_client, false
+
+# Configure esbuild (the version is required)
+config :esbuild,
+ version: "0.12.18",
+ default: [
+ args:
+ ~w(js/app.js --bundle --target=es2016 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
+ cd: Path.expand("../assets", __DIR__),
+ env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
+ ]
+
+# Configures Elixir's Logger
+config :logger, :console,
+ format: "$time $metadata[$level] $message\n",
+ metadata: [:request_id]
+
+# Use Jason for JSON parsing in Phoenix
+config :phoenix, :json_library, Jason
+
+# Import environment specific config. This must remain at the bottom
+# of this file so it overrides the configuration defined above.
+import_config "#{config_env()}.exs"
diff --git a/config/dev.exs b/config/dev.exs
new file mode 100644
index 0000000..c11456a
--- /dev/null
+++ b/config/dev.exs
@@ -0,0 +1,71 @@
+import Config
+
+# Configure your database
+config :demo, Demo.Repo,
+ database: Path.expand("../demo_dev.db", Path.dirname(__ENV__.file)),
+ pool_size: 5,
+ show_sensitive_data_on_connection_error: true
+
+# For development, we disable any cache and enable
+# debugging and code reloading.
+#
+# The watchers configuration can be used to run external
+# watchers to your application. For example, we use it
+# with esbuild to bundle .js and .css sources.
+config :demo, DemoWeb.Endpoint,
+ # Binding to loopback ipv4 address prevents access from other machines.
+ # Change to `ip: {0, 0, 0, 0}` to allow access from other machines.
+ http: [ip: {127, 0, 0, 1}, port: 4000],
+ check_origin: false,
+ code_reloader: true,
+ debug_errors: true,
+ secret_key_base: "prE6s5wRZ0MQol4OMrC3vsgep2ldrfW0ecSE7tgMFhUr4iHOvYAkF4YNPJ+hE914",
+ watchers: [
+ # Start the esbuild watcher by calling Esbuild.install_and_run(:default, args)
+ esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]}
+ ]
+
+# ## SSL Support
+#
+# In order to use HTTPS in development, a self-signed
+# certificate can be generated by running the following
+# Mix task:
+#
+# mix phx.gen.cert
+#
+# Note that this task requires Erlang/OTP 20 or later.
+# Run `mix help phx.gen.cert` for more information.
+#
+# The `http:` config above can be replaced with:
+#
+# https: [
+# port: 4001,
+# cipher_suite: :strong,
+# keyfile: "priv/cert/selfsigned_key.pem",
+# certfile: "priv/cert/selfsigned.pem"
+# ],
+#
+# If desired, both `http:` and `https:` keys can be
+# configured to run both http and https servers on
+# different ports.
+
+# Watch static and templates for browser reloading.
+config :demo, DemoWeb.Endpoint,
+ live_reload: [
+ patterns: [
+ ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
+ ~r"priv/gettext/.*(po)$",
+ ~r"lib/demo_web/(live|views)/.*(ex)$",
+ ~r"lib/demo_web/templates/.*(eex)$"
+ ]
+ ]
+
+# Do not include metadata nor timestamps in development logs
+config :logger, :console, format: "[$level] $message\n"
+
+# Set a higher stacktrace during development. Avoid configuring such
+# in production as building large stacktraces may be expensive.
+config :phoenix, :stacktrace_depth, 20
+
+# Initialize plugs at runtime for faster development compilation
+config :phoenix, :plug_init_mode, :runtime
diff --git a/config/prod.exs b/config/prod.exs
new file mode 100644
index 0000000..9f53a7d
--- /dev/null
+++ b/config/prod.exs
@@ -0,0 +1,51 @@
+import Config
+
+# For production, don't forget to configure the url host
+# to something meaningful, Phoenix uses this information
+# when generating URLs.
+#
+# Note we also include the path to a cache manifest
+# containing the digested version of static files. This
+# manifest is generated by the `mix phx.digest` task,
+# which you should run after static files are built and
+# before starting your production server.
+config :demo, DemoWeb.Endpoint,
+ url: [host: "example.com", port: 80],
+ cache_static_manifest: "priv/static/cache_manifest.json"
+
+# Do not print debug messages in production
+config :logger, level: :info
+
+# ## SSL Support
+#
+# To get SSL working, you will need to add the `https` key
+# to the previous section and set your `:url` port to 443:
+#
+# config :demo, DemoWeb.Endpoint,
+# ...,
+# url: [host: "example.com", port: 443],
+# https: [
+# ...,
+# port: 443,
+# cipher_suite: :strong,
+# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
+# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
+# ]
+#
+# The `cipher_suite` is set to `:strong` to support only the
+# latest and more secure SSL ciphers. This means old browsers
+# and clients may not be supported. You can set it to
+# `:compatible` for wider support.
+#
+# `:keyfile` and `:certfile` expect an absolute path to the key
+# and cert in disk or a relative path inside priv, for example
+# "priv/ssl/server.key". For all supported SSL configuration
+# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
+#
+# We also recommend setting `force_ssl` in your endpoint, ensuring
+# no data is ever sent via http, always redirecting to https:
+#
+# config :demo, DemoWeb.Endpoint,
+# force_ssl: [hsts: true]
+#
+# Check `Plug.SSL` for all available options in `force_ssl`.
diff --git a/config/runtime.exs b/config/runtime.exs
new file mode 100644
index 0000000..3a6dc16
--- /dev/null
+++ b/config/runtime.exs
@@ -0,0 +1,71 @@
+import Config
+
+# config/runtime.exs is executed for all environments, including
+# during releases. It is executed after compilation and before the
+# system starts, so it is typically used to load production configuration
+# and secrets from environment variables or elsewhere. Do not define
+# any compile-time configuration in here, as it won't be applied.
+# The block below contains prod specific runtime configuration.
+if config_env() == :prod do
+ database_path =
+ System.get_env("DATABASE_PATH") ||
+ raise """
+ environment variable DATABASE_PATH is missing.
+ For example: /etc/demo/demo.db
+ """
+
+ config :demo, Demo.Repo,
+ database: database_path,
+ pool_size: String.to_integer(System.get_env("POOL_SIZE") || "5")
+
+ # The secret key base is used to sign/encrypt cookies and other secrets.
+ # A default value is used in config/dev.exs and config/test.exs but you
+ # want to use a different value for prod and you most likely don't want
+ # to check this value into version control, so we use an environment
+ # variable instead.
+ secret_key_base =
+ System.get_env("SECRET_KEY_BASE") ||
+ raise """
+ environment variable SECRET_KEY_BASE is missing.
+ You can generate one by calling: mix phx.gen.secret
+ """
+
+ config :demo, DemoWeb.Endpoint,
+ http: [
+ # Enable IPv6 and bind on all interfaces.
+ # Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
+ # See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html
+ # for details about using IPv6 vs IPv4 and loopback vs public addresses.
+ ip: {0, 0, 0, 0, 0, 0, 0, 0},
+ port: String.to_integer(System.get_env("PORT") || "4000")
+ ],
+ secret_key_base: secret_key_base
+
+ # ## Using releases
+ #
+ # If you are doing OTP releases, you need to instruct Phoenix
+ # to start each relevant endpoint:
+ #
+ # config :demo, DemoWeb.Endpoint, server: true
+ #
+ # Then you can assemble a release by calling `mix release`.
+ # See `mix help release` for more information.
+
+ # ## Configuring the mailer
+ #
+ # In production you need to configure the mailer to use a different adapter.
+ # Also, you may need to configure the Swoosh API client of your choice if you
+ # are not using SMTP. Here is an example of the configuration:
+ #
+ # config :demo, Demo.Mailer,
+ # adapter: Swoosh.Adapters.Mailgun,
+ # api_key: System.get_env("MAILGUN_API_KEY"),
+ # domain: System.get_env("MAILGUN_DOMAIN")
+ #
+ # For this example you need include a HTTP client required by Swoosh API client.
+ # Swoosh supports Hackney and Finch out of the box:
+ #
+ # config :swoosh, :api_client, Swoosh.ApiClient.Hackney
+ #
+ # See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details.
+end
diff --git a/config/test.exs b/config/test.exs
new file mode 100644
index 0000000..02ef519
--- /dev/null
+++ b/config/test.exs
@@ -0,0 +1,27 @@
+import Config
+
+# Configure your database
+#
+# The MIX_TEST_PARTITION environment variable can be used
+# to provide built-in test partitioning in CI environment.
+# Run `mix help test` for more information.
+config :demo, Demo.Repo,
+ database: Path.expand("../demo_test.db", Path.dirname(__ENV__.file)),
+ pool_size: 5,
+ pool: Ecto.Adapters.SQL.Sandbox
+
+# We don't run a server during test. If one is required,
+# you can enable the server option below.
+config :demo, DemoWeb.Endpoint,
+ http: [ip: {127, 0, 0, 1}, port: 4002],
+ secret_key_base: "GRYvf8VgwceR9gi/nZ3XKOezlyRyZRQH/SDK60DsXXahHjfcdmfaPUZQaxkRBVTg",
+ server: false
+
+# In test we don't send emails.
+config :demo, Demo.Mailer, adapter: Swoosh.Adapters.Test
+
+# Print only warnings and errors during test
+config :logger, level: :warn
+
+# Initialize plugs at runtime for faster test compilation
+config :phoenix, :plug_init_mode, :runtime
diff --git a/lib/demo.ex b/lib/demo.ex
new file mode 100644
index 0000000..3f1ac75
--- /dev/null
+++ b/lib/demo.ex
@@ -0,0 +1,9 @@
+defmodule Demo do
+ @moduledoc """
+ Demo keeps the contexts that define your domain
+ and business logic.
+
+ Contexts are also responsible for managing your data, regardless
+ if it comes from the database, an external API or others.
+ """
+end
diff --git a/lib/demo/application.ex b/lib/demo/application.ex
new file mode 100644
index 0000000..c7e4171
--- /dev/null
+++ b/lib/demo/application.ex
@@ -0,0 +1,36 @@
+defmodule Demo.Application do
+ # See https://hexdocs.pm/elixir/Application.html
+ # for more information on OTP Applications
+ @moduledoc false
+
+ use Application
+
+ @impl true
+ def start(_type, _args) do
+ children = [
+ # Start the Ecto repository
+ Demo.Repo,
+ # Start the Telemetry supervisor
+ DemoWeb.Telemetry,
+ # Start the PubSub system
+ {Phoenix.PubSub, name: Demo.PubSub},
+ # Start the Endpoint (http/https)
+ DemoWeb.Endpoint
+ # Start a worker by calling: Demo.Worker.start_link(arg)
+ # {Demo.Worker, arg}
+ ]
+
+ # See https://hexdocs.pm/elixir/Supervisor.html
+ # for other strategies and supported options
+ opts = [strategy: :one_for_one, name: Demo.Supervisor]
+ Supervisor.start_link(children, opts)
+ end
+
+ # Tell Phoenix to update the endpoint configuration
+ # whenever the application is updated.
+ @impl true
+ def config_change(changed, _new, removed) do
+ DemoWeb.Endpoint.config_change(changed, removed)
+ :ok
+ end
+end
diff --git a/lib/demo/funcs.ex b/lib/demo/funcs.ex
new file mode 100644
index 0000000..f2e3cea
--- /dev/null
+++ b/lib/demo/funcs.ex
@@ -0,0 +1,15 @@
+defmodule Funcs do
+
+ # Naive, slow and buggy implementation:
+ def fib(0), do: 0
+ def fib(1), do: 1
+ def fib(n), do: fib(n-1) + fib(n-2)
+
+ # Fast version:
+ # def fib(n) when not is_number(n) or n < 0, do: raise("arg!")
+ # def fib(n), do: fib(0, 1, n)
+ #
+ # def fib(a, b, 0), do: a
+ # def fib(a, b, n), do: fib(b, a+b, n-1)
+
+end
diff --git a/lib/demo/funcs.ex~ b/lib/demo/funcs.ex~
new file mode 100644
index 0000000..9744681
--- /dev/null
+++ b/lib/demo/funcs.ex~
@@ -0,0 +1,10 @@
+defmodule Funcs do
+
+ def fib(n) when not is_number(n) or n < 0, do: raise("arg!")
+ def fib(n), do: fib(0, 1, n)
+
+ def fib(a, b, 0), do: a
+ def fib(a, b, n), do: fib(b, a+b, n-1)
+
+
+end
diff --git a/lib/demo/mailer.ex b/lib/demo/mailer.ex
new file mode 100644
index 0000000..c23e8ba
--- /dev/null
+++ b/lib/demo/mailer.ex
@@ -0,0 +1,3 @@
+defmodule Demo.Mailer do
+ use Swoosh.Mailer, otp_app: :demo
+end
diff --git a/lib/demo/repo.ex b/lib/demo/repo.ex
new file mode 100644
index 0000000..5bd732f
--- /dev/null
+++ b/lib/demo/repo.ex
@@ -0,0 +1,5 @@
+defmodule Demo.Repo do
+ use Ecto.Repo,
+ otp_app: :demo,
+ adapter: Ecto.Adapters.SQLite3
+end
diff --git a/lib/demo_web.ex b/lib/demo_web.ex
new file mode 100644
index 0000000..70ee827
--- /dev/null
+++ b/lib/demo_web.ex
@@ -0,0 +1,102 @@
+defmodule DemoWeb do
+ @moduledoc """
+ The entrypoint for defining your web interface, such
+ as controllers, views, channels and so on.
+
+ This can be used in your application as:
+
+ use DemoWeb, :controller
+ use DemoWeb, :view
+
+ The definitions below will be executed for every view,
+ controller, etc, so keep them short and clean, focused
+ on imports, uses and aliases.
+
+ Do NOT define functions inside the quoted expressions
+ below. Instead, define any helper function in modules
+ and import those modules here.
+ """
+
+ def controller do
+ quote do
+ use Phoenix.Controller, namespace: DemoWeb
+
+ import Plug.Conn
+ import DemoWeb.Gettext
+ alias DemoWeb.Router.Helpers, as: Routes
+ end
+ end
+
+ def view do
+ quote do
+ use Phoenix.View,
+ root: "lib/demo_web/templates",
+ namespace: DemoWeb
+
+ # Import convenience functions from controllers
+ import Phoenix.Controller,
+ only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1]
+
+ # Include shared imports and aliases for views
+ unquote(view_helpers())
+ end
+ end
+
+ def live_view do
+ quote do
+ use Phoenix.LiveView,
+ layout: {DemoWeb.LayoutView, "live.html"}
+
+ unquote(view_helpers())
+ end
+ end
+
+ def live_component do
+ quote do
+ use Phoenix.LiveComponent
+
+ unquote(view_helpers())
+ end
+ end
+
+ def router do
+ quote do
+ use Phoenix.Router
+
+ import Plug.Conn
+ import Phoenix.Controller
+ import Phoenix.LiveView.Router
+ end
+ end
+
+ def channel do
+ quote do
+ use Phoenix.Channel
+ import DemoWeb.Gettext
+ end
+ end
+
+ defp view_helpers do
+ quote do
+ # Use all HTML functionality (forms, tags, etc)
+ use Phoenix.HTML
+
+ # Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc)
+ import Phoenix.LiveView.Helpers
+
+ # Import basic rendering functionality (render, render_layout, etc)
+ import Phoenix.View
+
+ import DemoWeb.ErrorHelpers
+ import DemoWeb.Gettext
+ alias DemoWeb.Router.Helpers, as: Routes
+ end
+ end
+
+ @doc """
+ When used, dispatch to the appropriate controller/view/etc.
+ """
+ defmacro __using__(which) when is_atom(which) do
+ apply(__MODULE__, which, [])
+ end
+end
diff --git a/lib/demo_web/channels/room_channel.ex b/lib/demo_web/channels/room_channel.ex
new file mode 100644
index 0000000..3e6f0b5
--- /dev/null
+++ b/lib/demo_web/channels/room_channel.ex
@@ -0,0 +1,62 @@
+defmodule DemoWeb.RoomChannel do
+ use DemoWeb, :channel
+ require Logger
+
+ @impl true
+ def join("room:lobby", payload, socket) do
+ if authorized?(payload) do
+ {:ok, socket}
+ else
+ {:error, %{reason: "unauthorized"}}
+ end
+ end
+
+ # Channels can be used in a request/response fashion
+ # by sending replies to requests from the client
+ @impl true
+ def handle_in("ping", payload, socket) do
+ {:reply, {:ok, payload}, socket}
+ end
+
+ #
+ # Here is recieved the requests from the client
+ # we spawn a new process to compute the result, which
+ # is sent back in a new message when the task is finished
+ # The new process PID is used as a key for the client to
+ # associate the result to its request.
+ # the key(id) is immediatly returned to the client.
+ #
+ @impl true
+ def handle_in("fib", payload, socket) do
+ me = self()
+ id = spawn(fn ->
+ result = Funcs.fib(String.to_integer(payload["query"]))
+ send(me, {:response, %{id: Kernel.inspect(self()),
+ query: payload["query"],
+ result: result}})
+ end)
+ {:reply, {:ok, %{id: Kernel.inspect(id)}}, socket}
+ end
+
+ # It is also common to receive messages from the client and
+ # broadcast to everyone in the current topic (room:lobby).
+ @impl true
+ def handle_in("shout", payload, socket) do
+ broadcast(socket, "shout", payload)
+ {:noreply, socket}
+ end
+
+ # Add authorization logic here as required.
+ defp authorized?(_payload) do
+ true
+ end
+
+ @impl true
+ def handle_info({:response, map}, socket) do
+ Logger.debug("send response #{Kernel.inspect map}")
+ push(socket, "response", map)
+ {:noreply, socket}
+ end
+
+
+end
diff --git a/lib/demo_web/channels/user_socket.ex b/lib/demo_web/channels/user_socket.ex
new file mode 100644
index 0000000..c2d3cb3
--- /dev/null
+++ b/lib/demo_web/channels/user_socket.ex
@@ -0,0 +1,41 @@
+defmodule DemoWeb.UserSocket do
+ use Phoenix.Socket
+
+ # A Socket handler
+ #
+ # It's possible to control the websocket connection and
+ # assign values that can be accessed by your channel topics.
+
+ ## Channels
+
+ channel "room:*", DemoWeb.RoomChannel
+
+ # Socket params are passed from the client and can
+ # be used to verify and authenticate a user. After
+ # verification, you can put default assigns into
+ # the socket that will be set for all channels, ie
+ #
+ # {:ok, assign(socket, :user_id, verified_user_id)}
+ #
+ # To deny connection, return `:error`.
+ #
+ # See `Phoenix.Token` documentation for examples in
+ # performing token verification on connect.
+ @impl true
+ def connect(_params, socket, _connect_info) do
+ {:ok, socket}
+ end
+
+ # Socket id's are topics that allow you to identify all sockets for a given user:
+ #
+ # def id(socket), do: "user_socket:#{socket.assigns.user_id}"
+ #
+ # Would allow you to broadcast a "disconnect" event and terminate
+ # all active sockets and channels for a given user:
+ #
+ # Elixir.DemoWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
+ #
+ # Returning `nil` makes this socket anonymous.
+ @impl true
+ def id(_socket), do: nil
+end
diff --git a/lib/demo_web/controllers/page_controller.ex b/lib/demo_web/controllers/page_controller.ex
new file mode 100644
index 0000000..fe0fb62
--- /dev/null
+++ b/lib/demo_web/controllers/page_controller.ex
@@ -0,0 +1,7 @@
+defmodule DemoWeb.PageController do
+ use DemoWeb, :controller
+
+ def index(conn, _params) do
+ render(conn, "index.html")
+ end
+end
diff --git a/lib/demo_web/endpoint.ex b/lib/demo_web/endpoint.ex
new file mode 100644
index 0000000..4713a37
--- /dev/null
+++ b/lib/demo_web/endpoint.ex
@@ -0,0 +1,55 @@
+defmodule DemoWeb.Endpoint do
+ use Phoenix.Endpoint, otp_app: :demo
+
+ # The session will be stored in the cookie and signed,
+ # this means its contents can be read but not tampered with.
+ # Set :encryption_salt if you would also like to encrypt it.
+ @session_options [
+ store: :cookie,
+ key: "_demo_key",
+ signing_salt: "AZgmTvLs"
+ ]
+
+ socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
+
+ # Serve at "/" the static files from "priv/static" directory.
+ #
+ # You should set gzip to true if you are running phx.digest
+ # when deploying your static files in production.
+ plug Plug.Static,
+ at: "/",
+ from: :demo,
+ gzip: false,
+ only: ~w(assets fonts images favicon.ico robots.txt)
+
+ # Code reloading can be explicitly enabled under the
+ # :code_reloader configuration of your endpoint.
+ if code_reloading? do
+ socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
+ plug Phoenix.LiveReloader
+ plug Phoenix.CodeReloader
+ plug Phoenix.Ecto.CheckRepoStatus, otp_app: :demo
+ end
+
+ plug Phoenix.LiveDashboard.RequestLogger,
+ param_key: "request_logger",
+ cookie_key: "request_logger"
+
+ plug Plug.RequestId
+ plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
+
+ plug Plug.Parsers,
+ parsers: [:urlencoded, :multipart, :json],
+ pass: ["*/*"],
+ json_decoder: Phoenix.json_library()
+
+ plug Plug.MethodOverride
+ plug Plug.Head
+ plug Plug.Session, @session_options
+ plug DemoWeb.Router
+
+ socket "/socket", DemoWeb.UserSocket,
+ websocket: true,
+ longpoll: false
+
+end
diff --git a/lib/demo_web/gettext.ex b/lib/demo_web/gettext.ex
new file mode 100644
index 0000000..01f45dc
--- /dev/null
+++ b/lib/demo_web/gettext.ex
@@ -0,0 +1,24 @@
+defmodule DemoWeb.Gettext do
+ @moduledoc """
+ A module providing Internationalization with a gettext-based API.
+
+ By using [Gettext](https://hexdocs.pm/gettext),
+ your module gains a set of macros for translations, for example:
+
+ import DemoWeb.Gettext
+
+ # Simple translation
+ gettext("Here is the string to translate")
+
+ # Plural translation
+ ngettext("Here is the string to translate",
+ "Here are the strings to translate",
+ 3)
+
+ # Domain-based translation
+ dgettext("errors", "Here is the error message to translate")
+
+ See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
+ """
+ use Gettext, otp_app: :demo
+end
diff --git a/lib/demo_web/router.ex b/lib/demo_web/router.ex
new file mode 100644
index 0000000..4ab16be
--- /dev/null
+++ b/lib/demo_web/router.ex
@@ -0,0 +1,55 @@
+defmodule DemoWeb.Router do
+ use DemoWeb, :router
+
+ pipeline :browser do
+ plug :accepts, ["html"]
+ plug :fetch_session
+ plug :fetch_live_flash
+ plug :put_root_layout, {DemoWeb.LayoutView, :root}
+ plug :protect_from_forgery
+ plug :put_secure_browser_headers
+ end
+
+ pipeline :api do
+ plug :accepts, ["json"]
+ end
+
+ scope "/", DemoWeb do
+ pipe_through :browser
+
+ get "/", PageController, :index
+ end
+
+ # Other scopes may use custom stacks.
+ # scope "/api", DemoWeb do
+ # pipe_through :api
+ # end
+
+ # Enables LiveDashboard only for development
+ #
+ # If you want to use the LiveDashboard in production, you should put
+ # it behind authentication and allow only admins to access it.
+ # If your application does not have an admins-only section yet,
+ # you can use Plug.BasicAuth to set up some basic authentication
+ # as long as you are also using SSL (which you should anyway).
+ if Mix.env() in [:dev, :test] do
+ import Phoenix.LiveDashboard.Router
+
+ scope "/" do
+ pipe_through :browser
+ live_dashboard "/dashboard", metrics: DemoWeb.Telemetry
+ end
+ end
+
+ # Enables the Swoosh mailbox preview in development.
+ #
+ # Note that preview only shows emails that were sent by the same
+ # node running the Phoenix server.
+ if Mix.env() == :dev do
+ scope "/dev" do
+ pipe_through :browser
+
+ forward "/mailbox", Plug.Swoosh.MailboxPreview
+ end
+ end
+end
diff --git a/lib/demo_web/telemetry.ex b/lib/demo_web/telemetry.ex
new file mode 100644
index 0000000..b11369c
--- /dev/null
+++ b/lib/demo_web/telemetry.ex
@@ -0,0 +1,71 @@
+defmodule DemoWeb.Telemetry do
+ use Supervisor
+ import Telemetry.Metrics
+
+ def start_link(arg) do
+ Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
+ end
+
+ @impl true
+ def init(_arg) do
+ children = [
+ # Telemetry poller will execute the given period measurements
+ # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics
+ {:telemetry_poller, measurements: periodic_measurements(), period: 10_000}
+ # Add reporters as children of your supervision tree.
+ # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()}
+ ]
+
+ Supervisor.init(children, strategy: :one_for_one)
+ end
+
+ def metrics do
+ [
+ # Phoenix Metrics
+ summary("phoenix.endpoint.stop.duration",
+ unit: {:native, :millisecond}
+ ),
+ summary("phoenix.router_dispatch.stop.duration",
+ tags: [:route],
+ unit: {:native, :millisecond}
+ ),
+
+ # Database Metrics
+ summary("demo.repo.query.total_time",
+ unit: {:native, :millisecond},
+ description: "The sum of the other measurements"
+ ),
+ summary("demo.repo.query.decode_time",
+ unit: {:native, :millisecond},
+ description: "The time spent decoding the data received from the database"
+ ),
+ summary("demo.repo.query.query_time",
+ unit: {:native, :millisecond},
+ description: "The time spent executing the query"
+ ),
+ summary("demo.repo.query.queue_time",
+ unit: {:native, :millisecond},
+ description: "The time spent waiting for a database connection"
+ ),
+ summary("demo.repo.query.idle_time",
+ unit: {:native, :millisecond},
+ description:
+ "The time the connection spent waiting before being checked out for the query"
+ ),
+
+ # VM Metrics
+ summary("vm.memory.total", unit: {:byte, :kilobyte}),
+ summary("vm.total_run_queue_lengths.total"),
+ summary("vm.total_run_queue_lengths.cpu"),
+ summary("vm.total_run_queue_lengths.io")
+ ]
+ end
+
+ defp periodic_measurements do
+ [
+ # A module, function and arguments to be invoked periodically.
+ # This function must call :telemetry.execute/3 and a metric must be added above.
+ # {DemoWeb, :count_users, []}
+ ]
+ end
+end
diff --git a/lib/demo_web/templates/layout/app.html.heex b/lib/demo_web/templates/layout/app.html.heex
new file mode 100644
index 0000000..169aed9
--- /dev/null
+++ b/lib/demo_web/templates/layout/app.html.heex
@@ -0,0 +1,5 @@
+ <%= get_flash(@conn, :info) %> <%= get_flash(@conn, :error) %> <%= live_flash(@flash, :info) %> <%= live_flash(@flash, :error) %>
Peace of mind from prototype to production
+