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 = () => {
timeout = null;
if (!immediate) func.apply(context, args);
if (!immediate)
func.apply(context, args);
};
const callNow = immediate && !timeout;
@ -119,7 +120,8 @@ function debounce(func, wait, immediate) {
clearTimeout(timeout);
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) {
if (!exampleNumber) return;
if (!exampleNumber)
return;
switch(exampleNumber) {
case 1:

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -18,7 +18,10 @@ import messageSlack from "@helper/slack";
// P R O G R A M
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) {
case action.message === "fetch metadata":
@ -27,31 +30,31 @@ export default (socket, action) => {
case action.message === "landed on homepage":
generateGitHubFeed(result => {
socket.send(JSON.stringify({
send(socket, {
html: result,
message: "updated html",
selector: "#github-feed"
}));
});
});
break;
case action.message === "landed on playground":
generateContent(1, result => {
socket.send(JSON.stringify({
send(socket, {
html: result,
message: "updated html",
selector: "#playground-loader"
}));
});
});
break;
case action.message === "request for playground, example 1":
generateContent(1, result => {
socket.send(JSON.stringify({
send(socket, {
html: result,
message: "updated html",
selector: "#playground-loader"
}));
});
});
break;
@ -61,11 +64,11 @@ export default (socket, action) => {
case action.message === "request for playground, example 3":
generateContent(3, result => {
socket.send(JSON.stringify({
send(socket, {
html: result,
message: "updated html",
selector: "#playground-loader"
}));
});
});
break;
@ -85,15 +88,19 @@ export default (socket, action) => {
function generateContent(exampleNumber, displayTrendingContent) {
if (exampleNumber === 1) {
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 renderedContentCollection = [];
const trendingContentData = response.data;
for (const data of trendingContentData) {
rawContentCollection.push(fetchMetadata({ claim: data.url, method: "resolve", example: exampleNumber }));
}
for (const data of trendingContentData)
rawContentCollection.push(fetchMetadata({
claim: data.url,
example: exampleNumber,
method: "resolve"
}));
Promise.all(rawContentCollection).then(collection => {
for (const part of collection) {
@ -116,7 +123,7 @@ function generateContent(exampleNumber, displayTrendingContent) {
</div>
</section>
`);
} catch (err) {
} catch(err) {
return; // TODO: Return nice error message
}
}
@ -315,19 +322,19 @@ function generateMemeCreator(socket) {
</form>
`;
return socket.send(JSON.stringify({
return send(socket, {
example: 2,
html: memeCreator,
message: "updated html",
selector: "#playground-loader"
}));
});
}
async function getTrendingContent() {
try {
const response = await got("https://api.lbry.io/file/list_trending");
return JSON.parse(response.body); // eslint-disable-line padding-line-between-statements
} catch (error) {
} catch(error) {
return error;
}
}
@ -344,22 +351,24 @@ function makeImageSourceSecure(url) {
async function newsletterSubscribe(data, socket) {
const email = data.email;
if (!validateEmail(email)) return socket.send(JSON.stringify({
class: "error",
html: "Your email address is invalid",
message: "updated html",
selector: "#emailMessage"
}));
if (!validateEmail(email)) {
send(socket, {
class: "error",
html: "Your email address is invalid",
message: "updated html",
selector: "#emailMessage"
});
}
try {
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.",
message: "updated html",
selector: "#emailMessage"
}));
} catch (error) {
});
} catch(error) {
const response = JSON.parse(error.body);
if (!response.success) {
@ -369,12 +378,12 @@ async function newsletterSubscribe(data, socket) {
`> _Cause: ${email} interacted with the form_\n`
);
return socket.send(JSON.stringify({
return send(socket, {
class: "error",
html: response.error,
message: "updated html",
selector: "#emailMessage"
}));
});
}
messageSlack(
@ -383,15 +392,19 @@ async function newsletterSubscribe(data, socket) {
`> _Cause: ${email} interacted with the form_\n`
);
return socket.send(JSON.stringify({
return send(socket, {
class: "error",
html: "Something is terribly wrong",
message: "updated html",
selector: "#emailMessage"
}));
});
}
}
export function send(transport, data) {
return transport.send(JSON.stringify(data));
}
function validateEmail(email) {
const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\\.,;:\s@"]{2,})$/i;
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">
<div class="page__header-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>
</header>
<section class="page__content" itemprop="articleBody">
<section class="page__content page__markup" itemprop="articleBody">
<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>
</section>
</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>
document.addEventListener("DOMContentLoaded", () => {
send(JSON.stringify({
"message": "landed on homepage"
}));
send({ message: "landed on homepage" });
});
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;
}
// below should be refactored into components
let pageScript = "";
switch(true) {
case partialPath === "developer-program":
pageScript = renderClientScript("devprogram-scripts");
break;
case partialPath === "glossary":
pageScript =
"<script>" +
fs.readFileSync(`${process.cwd()}/app/components/client/glossary-scripts.js`, "utf-8") +
"</script>";
pageScript = renderClientScript("glossary-scripts");
break;
case partialPath === "overview":
pageScript =
"<script>" +
fs.readFileSync(`${process.cwd()}/app/components/client/ecosystem-scripts.js`, "utf-8") +
"</script>";
pageScript = renderClientScript("ecosystem-scripts");
break;
case partialPath === "playground":
pageScript =
"<script>" +
fs.readFileSync(`${process.cwd()}/app/components/client/playground-scripts.js`, "utf-8") +
"</script>";
pageScript = renderClientScript("playground-scripts");
break;
default:
@ -93,3 +87,15 @@ export default (state, emit) => { // eslint-disable-line
</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",
"@module": "app/modules",
"@root": ".",
"@socket": "app/sockets.js",
"@view": "app/views"
},
"author": "LBRY Team",