Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "join lobby"-button #39

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 31 additions & 8 deletions wikiweaver-ext/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,16 +130,23 @@ async function HandleMessageConnect(msg) {
const userid = await GetUserIdForLobby(options.code);

const body = {
code: options.code,
username: options.username,
code: msg.code,
username: msg.username,
userid: userid,
};

const response = await SendPOSTRequestToServer(options.url, "/api/ext/join", body);

if (response.Success) {
await SetPageCount(0);
await SetUserIdForLobby(options.code, response.UserID);
await SetUserIdForLobby(response.Code, response.UserID);

await chrome.storage.local.set(
{
code: response.Code,
username: response.Username,
}
);
}

await UpdateBadge(response.Success);
Expand Down Expand Up @@ -170,9 +177,6 @@ chrome.runtime.onMessage.addListener(async (msg) => {
async function SendPOSTRequestToServer(url, endpoint, body) {
console.log("sent:", body);

if (url === "") {
url = defaultdomain;
}
let response = await fetch(`${url}${endpoint}`, {
method: "POST",
body: JSON.stringify(body),
Expand Down Expand Up @@ -214,14 +218,14 @@ async function SearchForWikipediaTitle(title) {
};

url = url + "?origin=*";
Object.keys(params).forEach(function (key) {
Object.keys(params).forEach(function(key) {
url += "&" + key + "=" + params[key];
});

response = await fetch(url)
.then((response) => response.json())
.then((json) => json)
.catch(function (error) {
.catch(function(error) {
return { error: error };
});

Expand Down Expand Up @@ -317,3 +321,22 @@ async function UpdateBadge(success) {
chrome.action.setBadgeBackgroundColor({ color: color });
chrome.action.setBadgeText({ text: String(await GetPageCount()) });
}

chrome.runtime.onInstalled.addListener(async () => {
let options = await chrome.storage.local.get();

const url = options.url || defaultdomain;
await chrome.storage.local.set({ url });

if ((await chrome.scripting.getRegisteredContentScripts({ ids: ["join-lobby"] })).length <= 0) {
const scripts = [
{
id: "join-lobby",
js: ["/content/join-lobby.js"],
matches: [`${url}/*`],
}
]

await chrome.scripting.registerContentScripts(scripts);
}
});
15 changes: 15 additions & 0 deletions wikiweaver-ext/content/join-lobby.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const btn = document.getElementById("join-button");
btn.onclick = HandleJoinLobbyClicked;
btn.hidden = false;

async function HandleJoinLobbyClicked() {
const { username } = await chrome.storage.local.get();

let code = window.location.hash.replace("#", "").toLocaleLowerCase().trim();

await chrome.runtime.sendMessage({
type: "connect",
code,
username,
});
}
6 changes: 5 additions & 1 deletion wikiweaver-ext/manifest-chrome.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@
"webNavigation"
],
"host_permissions": [
"*://*.wikipedia.org/*"
"*://*.wikipedia.org/*",
"https://wikiweaver.stuffontheinter.net"
],
"optional_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "background.js"
Expand Down
6 changes: 5 additions & 1 deletion wikiweaver-ext/manifest-firefox.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@
"webNavigation"
],
"host_permissions": [
"*://*.wikipedia.org/*"
"*://*.wikipedia.org/*",
"https://wikiweaver.stuffontheinter.net/*"
],
"optional_permissions": [
"<all_urls>"
],
"background": {
"scripts": [
Expand Down
44 changes: 38 additions & 6 deletions wikiweaver-ext/options/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,48 @@ async function init(e) {

async function restore() {
const options = await chrome.storage.local.get()
document.querySelector("#url").value = options.url || "";
document.querySelector("#url").value = options.url;
}

async function save(e) {
e.preventDefault();
await chrome.storage.local.set({
url: document.querySelector("#url").value.toLowerCase(),
});
// todo: show saved succeeded in some way

const urlElem = document.querySelector("#url");
const url = new URL(urlElem.value.toLowerCase() || urlElem.placeholder);

// For some reason keeping the port here made it so the script was not
// injected at localhost, when the server was set to http://localhost:3000
const port = url.port;
url.port = "";

const host = `${url.origin}/*`;

// We must request permissions as the first async function we call in this
// user input handler for it to work.
// See https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/permissions/request
// and https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/User_actions
await chrome.permissions.request({ origins: [host] });

// What a mess...
url.port = port;
await chrome.storage.local.set({ url: url.origin });

if ((await chrome.scripting.getRegisteredContentScripts({ ids: ["join-lobby"] })).length > 0) {
await chrome.scripting.unregisterContentScripts({ ids: ["join-lobby"] });
}

const scripts = [
{
id: "join-lobby",
js: ["/content/join-lobby.js"],
matches: [host],
}
]

await chrome.scripting.registerContentScripts(scripts);

// TODO: show saved succeeded in some way
}

document.addEventListener("DOMContentLoaded", () => init(), false);
document.querySelector("form").addEventListener("submit", save);
document.querySelector("#submit").addEventListener("click", save);
20 changes: 17 additions & 3 deletions wikiweaver-ext/popup/popup.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,16 @@ async function HandleJoinClicked(e) {
});

IndicateConnectionStatus({ status: "pending" });
await chrome.runtime.sendMessage({ type: "connect" });

const { code, username } = await chrome.storage.local.get();

await chrome.runtime.sendMessage(
{
type: "connect",
code,
username,
}
);
}

async function HandleLeaveClicked(e) {
Expand Down Expand Up @@ -118,6 +127,9 @@ async function HandleMessageConnect(msg) {
} else {
await UnregisterContentScripts();
}

document.getElementById("code").textContent = msg.Code;
document.getElementById("username").textContent = msg.Username;
}

chrome.runtime.onMessage.addListener(async (msg) => {
Expand All @@ -143,13 +155,15 @@ const ContentScripts = [
];

async function RegisterContentScripts() {
if ((await chrome.scripting.getRegisteredContentScripts()).length <= 0) {
if ((await chrome.scripting.getRegisteredContentScripts({ ids: ["content"] })).length <= 0) {
await chrome.scripting.registerContentScripts(ContentScripts);
}
}

async function UnregisterContentScripts() {
await chrome.scripting.unregisterContentScripts();
if ((await chrome.scripting.getRegisteredContentScripts({ ids: ["content"] })).length > 0) {
await chrome.scripting.unregisterContentScripts({ ids: ["content"] });
}
}

function EnableElements(elements) {
Expand Down
6 changes: 6 additions & 0 deletions wikiweaver-server/cmd/main/wikiweaver-server.go
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,8 @@ type JoinFromExtRequest struct {

type JoinToExtResponse struct {
Success bool
Code string
Username string
UserID string
AlreadyInLobby bool
}
Expand Down Expand Up @@ -713,6 +715,8 @@ func handleExtJoin(w http.ResponseWriter, r *http.Request) {
if otherWithSameUsername.UserID == request.UserID || globalState.Dev {
successResponse := JoinToExtResponse{
Success: true,
Code: lobby.Code,
Username: otherWithSameUsername.Username,
UserID: request.UserID,
AlreadyInLobby: true,
}
Expand Down Expand Up @@ -777,6 +781,8 @@ func handleExtJoin(w http.ResponseWriter, r *http.Request) {

successResponse := JoinToExtResponse{
Success: true,
Code: lobby.Code,
Username: extClient.Username,
UserID: userID,
AlreadyInLobby: false,
}
Expand Down
5 changes: 4 additions & 1 deletion wikiweaver-web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@
<button id="redraw-button" class="button box text" onclick="HandleRedrawClicked()">redraw</button>
<button id="export-button" class="button box text" onclick="HandleExportClicked()">export</button>
</div>
<div class="flex-horizontal-container">
<button id="join-button" class="button box text" hidden>join</button>
</div>
<div id="leaderboard-wrapper">
<table id="leaderboard" class="text">
<tr>
Expand Down Expand Up @@ -87,4 +90,4 @@
</div>
</body>

</html>
</html>
7 changes: 6 additions & 1 deletion wikiweaver-web/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,11 @@ img {
background: var(--blue);
}

#join-button {
background: var(--green);
margin-top: 0.5rem;
}

#leaderboard-wrapper {
overflow-x: auto;
flex-shrink: 0;
Expand Down Expand Up @@ -230,4 +235,4 @@ img {

.button:hover {
filter: brightness(85%);
}
}