Optimizations

This commit is contained in:
ポール ウェッブ 2019-02-04 17:42:52 -06:00
parent 23696abdb7
commit 2777e68134
15 changed files with 155 additions and 93 deletions

View file

@ -0,0 +1,11 @@
"use strict"; /* global document, send */
document.getElementById("get-started").addEventListener("click", event => {
event.preventDefault();
send({
message: "auth me with github"
});
});

View file

@ -111,7 +111,8 @@ function debounce(func, wait, immediate) {
const later = () => { const later = () => {
timeout = null; timeout = null;
if (!immediate) func.apply(context, args); if (!immediate)
func.apply(context, args);
}; };
const callNow = immediate && !timeout; const callNow = immediate && !timeout;
@ -119,7 +120,8 @@ function debounce(func, wait, immediate) {
clearTimeout(timeout); clearTimeout(timeout);
timeout = setTimeout(later, wait); timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args); if (callNow)
func.apply(context, args);
}; };
} }
@ -139,7 +141,8 @@ function initializePlayground() {
} }
function fetchMetadata(exampleNumber, data) { function fetchMetadata(exampleNumber, data) {
if (!exampleNumber) return; if (!exampleNumber)
return;
switch(exampleNumber) { switch(exampleNumber) {
case 1: case 1:

View file

@ -26,6 +26,9 @@ if (
// Smooth scroll // Smooth scroll
document.querySelectorAll("a[href^='#']").forEach(anchor => { document.querySelectorAll("a[href^='#']").forEach(anchor => {
if (anchor.classList.contains("no-smooth")) // Ignore smooth scroll functionality
return;
anchor.addEventListener("click", event => { anchor.addEventListener("click", event => {
event.preventDefault(); event.preventDefault();

View file

@ -224,7 +224,7 @@
;(function(doc, proto) { ;(function(doc, proto) {
try { try {
doc.querySelector(":scope body"); doc.querySelector(":scope body");
} catch (err) { } catch(err) {
["querySelector", "querySelectorAll"].forEach(method => { ["querySelector", "querySelectorAll"].forEach(method => {
const nativ = proto[method]; const nativ = proto[method];

View file

@ -12,22 +12,22 @@ document.addEventListener("DOMContentLoaded", () => {
let ws = null; let ws = null;
function checkWebSocketConnection() { function checkWebSocketConnection() {
if (!ws || ws.readyState === 3) initializeWebSocketConnection(); if (!ws || ws.readyState === 3)
initializeWebSocketConnection();
} }
function initializeWebSocketConnection() { function initializeWebSocketConnection() {
ws = new WebSocket(location.origin.replace(/^http/, "ws")); ws = new WebSocket(location.origin.replace(/^http/, "ws"));
ws.onopen = () => { ws.onopen = () => console.log("WebSocket connection established"); // eslint-disable-line
console.log("WebSocket connection established"); // eslint-disable-line
};
ws.onmessage = socket => { ws.onmessage = socket => {
const data = JSON.parse(socket.data); const data = JSON.parse(socket.data);
switch(true) { switch(true) {
case data.message === "show result": case data.message === "show result":
if (!data.example) return; if (!data.example)
return;
document.querySelector(data.selector).innerHTML = data.html; document.querySelector(data.selector).innerHTML = data.html;
@ -60,8 +60,8 @@ function initializeWebSocketConnection() {
} }
if (data.example === 2) { if (data.example === 2) {
detectLanguageAndUpdate(); // eslint-disable-line detectLanguageAndUpdate(); // eslint-disable-line no-undef
initCanvas(); // eslint-disable-line initCanvas(); // eslint-disable-line no-undef
setTimeout(() => { setTimeout(() => {
document.querySelector(".playground-content__meme__canvas__thumbnail").click(); document.querySelector(".playground-content__meme__canvas__thumbnail").click();
@ -94,25 +94,23 @@ function initializeWebSocketConnection() {
break; break;
default: default:
console.log(data); // eslint-disable-line console.log(data); // eslint-disable-line no-console
break; break;
} }
}; };
ws.onclose = () => { ws.onclose = () => checkWebSocketConnection(); // reconnect now
console.log("WebSocket connection lost"); // eslint-disable-line
checkWebSocketConnection(); // reconnect now
};
} }
function send(msg) { // eslint-disable-line function send(msg) { // eslint-disable-line no-unused-vars
socketReady(ws, () => ws.send(msg)); socketReady(ws, () => ws.send(JSON.stringify(msg)));
} }
function socketReady(socket, callback) { function socketReady(socket, callback) {
setTimeout(() => { setTimeout(() => {
if (socket && socket.readyState === 1) { if (socket && socket.readyState === 1) {
if (callback !== undefined) callback(); if (callback !== undefined)
callback();
return; return;
} }

View file

@ -11,16 +11,16 @@ import stringifyObject from "stringify-object";
// U T I L S // U T I L S
import randomString from "./random-string";
import messageSlack from "./slack"; import messageSlack from "./slack";
import publishMeme from "./publish-meme"; import publishMeme from "./publish-meme";
import randomString from "./random-string";
import { send } from "@socket";
import uploadImage from "./upload-image"; import uploadImage from "./upload-image";
const allowedQueryMethods = [ const allowedQueryMethods = [
"claim_tip",
"publish", "publish",
"resolve", "resolve"
"claim_tip"
]; ];
const approvedContentIdsForTipping = [ const approvedContentIdsForTipping = [
@ -60,11 +60,11 @@ export default async(data, socket) => {
const resolveMethod = data.method; const resolveMethod = data.method;
if (allowedQueryMethods.indexOf(resolveMethod) < 0) { if (allowedQueryMethods.indexOf(resolveMethod) < 0) {
return socket.send(JSON.stringify({ return send(socket, {
details: "Unallowed resolve method for tutorial", details: "Unallowed resolve method for tutorial",
message: "notification", message: "notification",
type: "error" type: "error"
})); });
} }
body.authorization = process.env.LBRY_DAEMON_ACCESS_TOKEN; body.authorization = process.env.LBRY_DAEMON_ACCESS_TOKEN;
@ -77,7 +77,7 @@ export default async(data, socket) => {
// E X A M P L E // E X A M P L E
case resolveMethod === "claim_tip": case resolveMethod === "claim_tip":
if (!approvedContentIdsForTipping.includes(claimAddress)) { if (!approvedContentIdsForTipping.includes(claimAddress)) {
return socket.send(JSON.stringify({ return send(socket, {
example: data.example, example: data.example,
html: raw(` html: raw(`
<h3>Response</h3> <h3>Response</h3>
@ -85,7 +85,7 @@ export default async(data, socket) => {
`), `),
message: "show result", message: "show result",
selector: `#example${data.example}-result` selector: `#example${data.example}-result`
})); });
} }
apiRequestMethod = "POST"; apiRequestMethod = "POST";
@ -140,7 +140,7 @@ export default async(data, socket) => {
"json" "json"
); );
return socket.send(JSON.stringify({ return send(socket, {
example: data.example, example: data.example,
html: raw(` html: raw(`
<h3>Response</h3> <h3>Response</h3>
@ -149,15 +149,15 @@ export default async(data, socket) => {
`), `),
message: "show result", message: "show result",
selector: `#example${data.example}-result` selector: `#example${data.example}-result`
})); });
} }
catch(memePublishError) { catch(memePublishError) {
socket.send(JSON.stringify({ send(socket, {
details: "Meme publish failed", details: "Meme publish failed",
message: "notification", message: "notification",
type: "error" type: "error"
})); });
if (process.env.NODE_ENV !== "development") { if (process.env.NODE_ENV !== "development") {
messageSlack({ messageSlack({
@ -172,11 +172,11 @@ export default async(data, socket) => {
} }
catch(imageUploadError) { catch(imageUploadError) {
socket.send(JSON.stringify({ send(socket, {
details: "Image upload failed", details: "Image upload failed",
message: "notification", message: "notification",
type: "error" type: "error"
})); });
if (process.env.NODE_ENV !== "development") { if (process.env.NODE_ENV !== "development") {
messageSlack({ messageSlack({
@ -241,7 +241,7 @@ export default async(data, socket) => {
"json" "json"
); );
return socket.send(JSON.stringify({ return send(socket, {
example: data.example, example: data.example,
html: raw(` html: raw(`
<h3>Response</h3> <h3>Response</h3>
@ -250,7 +250,7 @@ export default async(data, socket) => {
`), `),
message: "show result", message: "show result",
selector: `#example${data.example}-result` selector: `#example${data.example}-result`
})); });
} }
return response.body.result[Object.keys(response.body.result)[0]].claim; return response.body.result[Object.keys(response.body.result)[0]].claim;

View file

@ -336,6 +336,15 @@ function generateUrl(type, event) {
} }
} }
function getGitHubUserToken() {
// const clientWithAuth = new Octokit({
// auth: `token ${GITHUB_APP_TOKEN}`
// });
// console.log(clientWithAuth);
// console.log("—————");
}
function updateGithubFeed() { function updateGithubFeed() {
octokit.activity.listPublicEventsForOrg({ octokit.activity.listPublicEventsForOrg({
org: "lbryio", org: "lbryio",
@ -377,5 +386,6 @@ export {
generateEvent, generateEvent,
generateGitHubFeed, generateGitHubFeed,
generateUrl, generateUrl,
getGitHubUserToken,
updateGithubFeed updateGithubFeed
}; };

View file

@ -28,7 +28,7 @@ export default async(publishMetadata) => {
try { try {
const response = await got.put(queryUrl, options); const response = await got.put(queryUrl, options);
return response.body; // eslint-disable-line padding-line-between-statements return response.body; // eslint-disable-line padding-line-between-statements
} catch (error) { } catch(error) {
return error; return error;
} }
}; };

View file

@ -28,7 +28,7 @@ export default async(imageSource) => {
try { try {
const response = await got.post(queryUrl, options); const response = await got.post(queryUrl, options);
return response.body; // eslint-disable-line padding-line-between-statements return response.body; // eslint-disable-line padding-line-between-statements
} catch (error) { } catch(error) {
return error; return error;
} }
}; };

View file

@ -18,7 +18,10 @@ import messageSlack from "@helper/slack";
// P R O G R A M // P R O G R A M
export default (socket, action) => { export default (socket, action) => {
if (typeof socket !== "object" && typeof action !== "object") return; if (typeof socket !== "object" && typeof action !== "object")
return;
action = JSON.parse(action);
switch(true) { switch(true) {
case action.message === "fetch metadata": case action.message === "fetch metadata":
@ -27,31 +30,31 @@ export default (socket, action) => {
case action.message === "landed on homepage": case action.message === "landed on homepage":
generateGitHubFeed(result => { generateGitHubFeed(result => {
socket.send(JSON.stringify({ send(socket, {
html: result, html: result,
message: "updated html", message: "updated html",
selector: "#github-feed" selector: "#github-feed"
})); });
}); });
break; break;
case action.message === "landed on playground": case action.message === "landed on playground":
generateContent(1, result => { generateContent(1, result => {
socket.send(JSON.stringify({ send(socket, {
html: result, html: result,
message: "updated html", message: "updated html",
selector: "#playground-loader" selector: "#playground-loader"
})); });
}); });
break; break;
case action.message === "request for playground, example 1": case action.message === "request for playground, example 1":
generateContent(1, result => { generateContent(1, result => {
socket.send(JSON.stringify({ send(socket, {
html: result, html: result,
message: "updated html", message: "updated html",
selector: "#playground-loader" selector: "#playground-loader"
})); });
}); });
break; break;
@ -61,11 +64,11 @@ export default (socket, action) => {
case action.message === "request for playground, example 3": case action.message === "request for playground, example 3":
generateContent(3, result => { generateContent(3, result => {
socket.send(JSON.stringify({ send(socket, {
html: result, html: result,
message: "updated html", message: "updated html",
selector: "#playground-loader" selector: "#playground-loader"
})); });
}); });
break; break;
@ -85,15 +88,19 @@ export default (socket, action) => {
function generateContent(exampleNumber, displayTrendingContent) { function generateContent(exampleNumber, displayTrendingContent) {
if (exampleNumber === 1) { if (exampleNumber === 1) {
return getTrendingContent().then(response => { return getTrendingContent().then(response => {
if (!response || !response.success || response.success !== true || !response.data) return ""; if (!response || !response.success || response.success !== true || !response.data)
return "";
const rawContentCollection = []; const rawContentCollection = [];
const renderedContentCollection = []; const renderedContentCollection = [];
const trendingContentData = response.data; const trendingContentData = response.data;
for (const data of trendingContentData) { for (const data of trendingContentData)
rawContentCollection.push(fetchMetadata({ claim: data.url, method: "resolve", example: exampleNumber })); rawContentCollection.push(fetchMetadata({
} claim: data.url,
example: exampleNumber,
method: "resolve"
}));
Promise.all(rawContentCollection).then(collection => { Promise.all(rawContentCollection).then(collection => {
for (const part of collection) { for (const part of collection) {
@ -116,7 +123,7 @@ function generateContent(exampleNumber, displayTrendingContent) {
</div> </div>
</section> </section>
`); `);
} catch (err) { } catch(err) {
return; // TODO: Return nice error message return; // TODO: Return nice error message
} }
} }
@ -315,19 +322,19 @@ function generateMemeCreator(socket) {
</form> </form>
`; `;
return socket.send(JSON.stringify({ return send(socket, {
example: 2, example: 2,
html: memeCreator, html: memeCreator,
message: "updated html", message: "updated html",
selector: "#playground-loader" selector: "#playground-loader"
})); });
} }
async function getTrendingContent() { async function getTrendingContent() {
try { try {
const response = await got("https://api.lbry.io/file/list_trending"); const response = await got("https://api.lbry.io/file/list_trending");
return JSON.parse(response.body); // eslint-disable-line padding-line-between-statements return JSON.parse(response.body); // eslint-disable-line padding-line-between-statements
} catch (error) { } catch(error) {
return error; return error;
} }
} }
@ -344,22 +351,24 @@ function makeImageSourceSecure(url) {
async function newsletterSubscribe(data, socket) { async function newsletterSubscribe(data, socket) {
const email = data.email; const email = data.email;
if (!validateEmail(email)) return socket.send(JSON.stringify({ if (!validateEmail(email)) {
send(socket, {
class: "error", class: "error",
html: "Your email address is invalid", html: "Your email address is invalid",
message: "updated html", message: "updated html",
selector: "#emailMessage" selector: "#emailMessage"
})); });
}
try { try {
await got.post(`https://api.lbry.io/list/subscribe?email=${encodeURIComponent(email)}&tag=developer`); await got.post(`https://api.lbry.io/list/subscribe?email=${encodeURIComponent(email)}&tag=developer`);
return socket.send(JSON.stringify({ return send(socket, {
html: "Thank you! Please confirm subscription in your inbox.", html: "Thank you! Please confirm subscription in your inbox.",
message: "updated html", message: "updated html",
selector: "#emailMessage" selector: "#emailMessage"
})); });
} catch (error) { } catch(error) {
const response = JSON.parse(error.body); const response = JSON.parse(error.body);
if (!response.success) { if (!response.success) {
@ -369,12 +378,12 @@ async function newsletterSubscribe(data, socket) {
`> _Cause: ${email} interacted with the form_\n` `> _Cause: ${email} interacted with the form_\n`
); );
return socket.send(JSON.stringify({ return send(socket, {
class: "error", class: "error",
html: response.error, html: response.error,
message: "updated html", message: "updated html",
selector: "#emailMessage" selector: "#emailMessage"
})); });
} }
messageSlack( messageSlack(
@ -383,15 +392,19 @@ async function newsletterSubscribe(data, socket) {
`> _Cause: ${email} interacted with the form_\n` `> _Cause: ${email} interacted with the form_\n`
); );
return socket.send(JSON.stringify({ return send(socket, {
class: "error", class: "error",
html: "Something is terribly wrong", html: "Something is terribly wrong",
message: "updated html", message: "updated html",
selector: "#emailMessage" selector: "#emailMessage"
})); });
} }
} }
export function send(transport, data) {
return transport.send(JSON.stringify(data));
}
function validateEmail(email) { function validateEmail(email) {
const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\\.,;:\s@"]{2,})$/i; const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\\.,;:\s@"]{2,})$/i;
return emailRegex.test(String(email)); // eslint-disable-line padding-line-between-statements return emailRegex.test(String(email)); // eslint-disable-line padding-line-between-statements

View file

@ -15,22 +15,27 @@ export default () => html`
<header class="page__header"> <header class="page__header">
<div class="page__header-wrap"> <div class="page__header-wrap">
<div class="inner-wrap"> <div class="inner-wrap">
<h1 class="page__header__title" itemprop="name headline">Dev Program</h1> <h1 class="page__header__title" itemprop="name headline">Developer Program</h1>
</div> </div>
</div> </div>
</header> </header>
<section class="page__content" itemprop="articleBody"> <section class="page__content page__markup" itemprop="articleBody">
<div class="inner-wrap"> <div class="inner-wrap">
<p>...</p> <p>When developing for LBRY, having LBC (LBRY credits) makes it easier to develop applications and interface with our APIs.</p>
<p>To qualify for free LBC you must:</p>
<ul>
<li>have a GitHub account, and</li>
<li>have a public PR (pull request) in the past year</li>
</ul>
<p>If this sounds like you, <a href="#" class="no-smooth" id="get-started">get started here</a>!</p>
<p><small>
If you have not downloaded our SDK yet, <a href="">you should</a> and generate a wallet address so we know where to send your LBC!
</small></p>
</div> </div>
</section> </section>
</article> </article>
`; `;
// TODO:
// Provide flow where user logs in with GitHub:
// - get access token
// - show field for user to enter their wallet address
// - send access token and wallet address to API
// - parse response

View file

@ -96,9 +96,7 @@ export default () => html`
<script> <script>
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
send(JSON.stringify({ send({ message: "landed on homepage" });
"message": "landed on homepage"
}));
}); });
document.getElementsByTagName("body")[0].classList.add("home"); // TODO: make this happen in components/layout document.getElementsByTagName("body")[0].classList.add("home"); // TODO: make this happen in components/layout

View file

@ -45,29 +45,23 @@ export default (state, emit) => { // eslint-disable-line
state.lbry = customMetadata; state.lbry = customMetadata;
} }
// below should be refactored into components
let pageScript = ""; let pageScript = "";
switch(true) { switch(true) {
case partialPath === "developer-program":
pageScript = renderClientScript("devprogram-scripts");
break;
case partialPath === "glossary": case partialPath === "glossary":
pageScript = pageScript = renderClientScript("glossary-scripts");
"<script>" +
fs.readFileSync(`${process.cwd()}/app/components/client/glossary-scripts.js`, "utf-8") +
"</script>";
break; break;
case partialPath === "overview": case partialPath === "overview":
pageScript = pageScript = renderClientScript("ecosystem-scripts");
"<script>" +
fs.readFileSync(`${process.cwd()}/app/components/client/ecosystem-scripts.js`, "utf-8") +
"</script>";
break; break;
case partialPath === "playground": case partialPath === "playground":
pageScript = pageScript = renderClientScript("playground-scripts");
"<script>" +
fs.readFileSync(`${process.cwd()}/app/components/client/playground-scripts.js`, "utf-8") +
"</script>";
break; break;
default: default:
@ -93,3 +87,15 @@ export default (state, emit) => { // eslint-disable-line
</article> </article>
`; `;
}; };
// H E L P E R
function renderClientScript(clientScriptFileName) {
return `
<script>
${fs.readFileSync((`${process.cwd()}/app/components/client/${clientScriptFileName}.js`), "utf-8")}
</script>
`;
}

View file

@ -0,0 +1,14 @@
---
title: Developer Program
---
When developing for LBRY, having LBC (LBRY credits) makes it easier to develop applications and interface with our APIs.
To qualify for free LBC you must:
- have a GitHub account, and
- have a public PR (pull request) in the past year
If this sounds like you, <a href="#" class="no-smooth" id="get-started">get started here</a>!
If you have not downloaded our SDK yet, [you should]() and generate a wallet address so we know where to send your LBC!

View file

@ -5,6 +5,7 @@
"@helper": "app/helpers", "@helper": "app/helpers",
"@module": "app/modules", "@module": "app/modules",
"@root": ".", "@root": ".",
"@socket": "app/sockets.js",
"@view": "app/views" "@view": "app/views"
}, },
"author": "LBRY Team", "author": "LBRY Team",