fix logging console function names. Attempt to connect to initial peers
This commit is contained in:
@@ -43,7 +43,7 @@ export class PeerManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
log("<-signaler:", message);
|
console.log.apply(null, log("<-signaler:", message));
|
||||||
|
|
||||||
this.websocket.send(messageJSON);
|
this.websocket.send(messageJSON);
|
||||||
}
|
}
|
||||||
@@ -60,7 +60,7 @@ export class PeerManager {
|
|||||||
throw new Error();
|
throw new Error();
|
||||||
}
|
}
|
||||||
|
|
||||||
log("->signaler:", message);
|
console.log.apply(null, log("->signaler:", message));
|
||||||
|
|
||||||
if (message.type === "hello2") {
|
if (message.type === "hello2") {
|
||||||
|
|
||||||
@@ -81,7 +81,7 @@ export class PeerManager {
|
|||||||
|
|
||||||
// // We're already connected, so delete the existing connection and make a new one.
|
// // We're already connected, so delete the existing connection and make a new one.
|
||||||
if (peerConnection?.rtcPeer?.connectionState === "connected") {
|
if (peerConnection?.rtcPeer?.connectionState === "connected") {
|
||||||
log("Connecting peer is already connected. Deleting existing peer connection and reconnecting.");
|
console.log.apply(null, log("Connecting peer is already connected. Deleting existing peer connection and reconnecting."));
|
||||||
peerConnection.disconnect();
|
peerConnection.disconnect();
|
||||||
this.peers.delete(message.from);
|
this.peers.delete(message.from);
|
||||||
peerConnection = undefined;
|
peerConnection = undefined;
|
||||||
@@ -94,7 +94,7 @@ export class PeerManager {
|
|||||||
|
|
||||||
|
|
||||||
if (!peerConnection) {
|
if (!peerConnection) {
|
||||||
log("Can't find peer for peer message:", message);
|
console.log.apply(null, log("Can't find peer for peer message:", message));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,11 +116,12 @@ export class PeerManager {
|
|||||||
async onHello2Received(bootstrapPeerID: string) {
|
async onHello2Received(bootstrapPeerID: string) {
|
||||||
|
|
||||||
if (this.isBootstrapPeer) {
|
if (this.isBootstrapPeer) {
|
||||||
|
this.connectPromise?.resolve();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!bootstrapPeerID) {
|
if (!bootstrapPeerID) {
|
||||||
log("Didn't get bootstrap peer, waiting 10 seconds...");
|
console.log.apply(null, log("Didn't get bootstrap peer, waiting 10 seconds..."));
|
||||||
setTimeout(async (e: Event) => { await this.sendHello2() }, 10_000);
|
setTimeout(async (e: Event) => { await this.sendHello2() }, 10_000);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -184,7 +185,7 @@ export class PeerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.websocket.onopen = async (event) => {
|
this.websocket.onopen = async (event) => {
|
||||||
log("PeerManager:ws:onopen");
|
console.log.apply(null, log("peermanager:ws:onopen"));
|
||||||
this.sendHello2();
|
this.sendHello2();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -234,15 +235,13 @@ export class PeerManager {
|
|||||||
this.bootstrapPeerConnection = null;
|
this.bootstrapPeerConnection = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async disconnect(remotePeerID: string) {
|
async disconnect(remotePeerID: string) {
|
||||||
let peer = this.peers.get(remotePeerID);
|
let peer = this.peers.get(remotePeerID);
|
||||||
|
|
||||||
if (!peer) {
|
if (!peer) {
|
||||||
log(`PeerManager.disconnect: couln't find peer ${remotePeerID}`);
|
console.log.apply(null, log(`PeerManager.disconnect: couln't find peer ${remotePeerID}`));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,7 +253,7 @@ export class PeerManager {
|
|||||||
let peer = this.peers.get(peerID);
|
let peer = this.peers.get(peerID);
|
||||||
|
|
||||||
if (!peer) {
|
if (!peer) {
|
||||||
log(`Can't find peer ${peerID}`);
|
console.log.apply(null, log(`Can't find peer ${peerID}`));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,7 +264,7 @@ export class PeerManager {
|
|||||||
let func = this.RPC_remote.get(functionName);
|
let func = this.RPC_remote.get(functionName);
|
||||||
|
|
||||||
if (!func) {
|
if (!func) {
|
||||||
throw new Error();
|
throw new Error(`callFromRemote: got RPC we don't know about: ${functionName}, ${args}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return func(args);
|
return func(args);
|
||||||
@@ -292,7 +291,7 @@ export class PeerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onMessage(remotePeerID: string, message: any) {
|
onMessage(remotePeerID: string, message: any) {
|
||||||
log(remotePeerID, message);
|
console.log.apply(null, log(remotePeerID, message));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -339,7 +338,7 @@ interface Message {
|
|||||||
// }
|
// }
|
||||||
|
|
||||||
// this.websocket.onopen = async (event) => {
|
// this.websocket.onopen = async (event) => {
|
||||||
// log("signaler:ws:onopen");
|
// console.log.apply(null, log("signaler:ws:onopen");
|
||||||
// await this.sendHello2();
|
// await this.sendHello2();
|
||||||
// };
|
// };
|
||||||
|
|
||||||
@@ -361,11 +360,11 @@ interface Message {
|
|||||||
// try {
|
// try {
|
||||||
// message = JSON.parse(messageJSON);
|
// message = JSON.parse(messageJSON);
|
||||||
// } catch (e) {
|
// } catch (e) {
|
||||||
// log(e);
|
// console.log.apply(null, log(e);
|
||||||
// throw new Error();
|
// throw new Error();
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// log("->signaler:", message);
|
// console.log.apply(null, log("->signaler:", message);
|
||||||
|
|
||||||
// if (message.type === "hello2") {
|
// if (message.type === "hello2") {
|
||||||
|
|
||||||
@@ -384,7 +383,7 @@ interface Message {
|
|||||||
|
|
||||||
// let connection = this.peerRoutes.get(message.from_peer);
|
// let connection = this.peerRoutes.get(message.from_peer);
|
||||||
// if (!connection) {
|
// if (!connection) {
|
||||||
// log("Can't find peer for peer message:", message);
|
// console.log.apply(null, log("Can't find peer for peer message:", message);
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
// connection.onSignalerMessage(message);
|
// connection.onSignalerMessage(message);
|
||||||
@@ -463,11 +462,11 @@ class PeerConnection {
|
|||||||
if (!this.dataChannel) {
|
if (!this.dataChannel) {
|
||||||
throw new Error();
|
throw new Error();
|
||||||
}
|
}
|
||||||
log("data channel is open!");
|
console.log.apply(null, log("data channel is open!"));
|
||||||
this.send({ type: "hello datachannel", from: this.peerManager.peerID });
|
this.send({ type: "hello datachannel", from: this.peerManager.peerID, to: this.remotePeerID});
|
||||||
// this.dataChannel?.send(`{typeHello datachannel from: ${this.peerManager.peerID}`);
|
// this.dataChannel?.send(`{typeHello datachannel from: ${this.peerManager.peerID}`);
|
||||||
|
|
||||||
log([...this.peerManager.peers.keys()]);
|
console.log.apply(null, log([...this.peerManager.peers.keys()]));
|
||||||
|
|
||||||
if (this.peerManager.isBootstrapPeer) {
|
if (this.peerManager.isBootstrapPeer) {
|
||||||
this.send({ type: 'initial_peers', from: this.peerManager.peerID, peers: [...this.peerManager.peers.keys()].filter(entry => entry !== this.remotePeerID) })
|
this.send({ type: 'initial_peers', from: this.peerManager.peerID, peers: [...this.peerManager.peers.keys()].filter(entry => entry !== this.remotePeerID) })
|
||||||
@@ -478,7 +477,7 @@ class PeerConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.dataChannel.onmessage = (e: MessageEvent) => {
|
this.dataChannel.onmessage = (e: MessageEvent) => {
|
||||||
log("data channel message: ", e.data)
|
console.log.apply(null, log("->datachannel: ", e.data))
|
||||||
this.onMessage(e.data);
|
this.onMessage(e.data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -488,7 +487,7 @@ class PeerConnection {
|
|||||||
this.rtcPeer = new RTCPeerConnection(PeerConnection.config);
|
this.rtcPeer = new RTCPeerConnection(PeerConnection.config);
|
||||||
|
|
||||||
this.rtcPeer.onconnectionstatechange = async (e: any) => {
|
this.rtcPeer.onconnectionstatechange = async (e: any) => {
|
||||||
log(`rtcPeer: onconnectionstatechange: ${this.rtcPeer?.connectionState}: ${this.remotePeerID}`);
|
console.log.apply(null, log(`rtcPeer: onconnectionstatechange: ${this.rtcPeer?.connectionState}: ${this.remotePeerID}`));
|
||||||
|
|
||||||
if (!this.rtcPeer) {
|
if (!this.rtcPeer) {
|
||||||
throw new Error("onconnectionstatechange");
|
throw new Error("onconnectionstatechange");
|
||||||
@@ -497,6 +496,8 @@ class PeerConnection {
|
|||||||
// When the connection is closed, tell the peer manager that this connection has gone away
|
// When the connection is closed, tell the peer manager that this connection has gone away
|
||||||
if (this.rtcPeer.connectionState === "disconnected") {
|
if (this.rtcPeer.connectionState === "disconnected") {
|
||||||
this.peerManager.onPeerDisconnected(this.remotePeerID);
|
this.peerManager.onPeerDisconnected(this.remotePeerID);
|
||||||
|
|
||||||
|
// window.setTimeout(async () => { await this.peerManager.connectToPeer(this.remotePeerID) }, 10_000);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.rtcPeer.connectionState === "connected") {
|
if (this.rtcPeer.connectionState === "connected") {
|
||||||
@@ -512,7 +513,7 @@ class PeerConnection {
|
|||||||
let localCandidate = stats.get(candidatePair.localCandidateId);
|
let localCandidate = stats.get(candidatePair.localCandidateId);
|
||||||
let remoteCandidate = stats.get(candidatePair.remoteCandidateId);
|
let remoteCandidate = stats.get(candidatePair.remoteCandidateId);
|
||||||
|
|
||||||
log("Connected candidates\n", localCandidate, remoteCandidate);
|
console.log.apply(null, log("Connected candidates\n", localCandidate, remoteCandidate));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -537,16 +538,16 @@ class PeerConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// this.rtcPeer.onicecandidate = ({ candidate }) => this.signaler.send(JSON.stringify({ candidate }));
|
// this.rtcPeer.onicecandidate = ({ candidate }) => this.signaler.send(JSON.stringify({ candidate }));
|
||||||
// this.rtcPeer.onicecandidate = ({ candidate }) => log(candidate);
|
// this.rtcPeer.onicecandidate = ({ candidate }) => console.log.apply(null, log(candidate);
|
||||||
|
|
||||||
|
|
||||||
this.rtcPeer.onicecandidate = ({ candidate }) => {
|
this.rtcPeer.onicecandidate = ({ candidate }) => {
|
||||||
log(candidate);
|
console.log.apply(null, log(candidate));
|
||||||
this.sendPeerMessage(this.remotePeerID, { type: "rtc_candidate", candidate: candidate });
|
this.sendPeerMessage(this.remotePeerID, { type: "rtc_candidate", candidate: candidate });
|
||||||
}
|
}
|
||||||
|
|
||||||
this.rtcPeer.onnegotiationneeded = async (event) => {
|
this.rtcPeer.onnegotiationneeded = async (event) => {
|
||||||
log("on negotiation needed fired");
|
console.log.apply(null, log("on negotiation needed fired"));
|
||||||
|
|
||||||
if (!this.rtcPeer) {
|
if (!this.rtcPeer) {
|
||||||
throw new Error();
|
throw new Error();
|
||||||
@@ -644,7 +645,7 @@ class PeerConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
send(message: any) {
|
send(message: any) {
|
||||||
this.messageSuperlog && log("<-", message.type, message);
|
this.messageSuperlog && console.log.apply(null, log("<-datachannel:", message.type, message));
|
||||||
|
|
||||||
let messageJSON = JSON.stringify(message);
|
let messageJSON = JSON.stringify(message);
|
||||||
this.dataChannel?.send(messageJSON);
|
this.dataChannel?.send(messageJSON);
|
||||||
@@ -678,10 +679,10 @@ class PeerConnection {
|
|||||||
try {
|
try {
|
||||||
message = JSON.parse(messageJSON);
|
message = JSON.parse(messageJSON);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log("PeerConnection.onMessage:", e);
|
console.log.apply(null, log("PeerConnection.onMessage:", e));
|
||||||
}
|
}
|
||||||
|
|
||||||
this.messageSuperlog && log("->", message.type, message);
|
this.messageSuperlog && console.log.apply(null, log("->", message.type, message));
|
||||||
let type = message.type;
|
let type = message.type;
|
||||||
|
|
||||||
if (type === "rpc_response") {
|
if (type === "rpc_response") {
|
||||||
@@ -704,6 +705,13 @@ class PeerConnection {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (type === "initial_peers") {
|
||||||
|
for (let peerID of message.peers) {
|
||||||
|
console.log(log("Connecting to initial peer ", peerID));
|
||||||
|
this.peerManager.connectToPeer(peerID);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// this.peerManger.onMessage(this.remotePeerID, message);
|
// this.peerManger.onMessage(this.remotePeerID, message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
let logLines: string[] = [];
|
let logLines: string[] = [];
|
||||||
let logLength = 30;
|
let logLength = 100;
|
||||||
let logVisible = false;
|
let logVisible = false;
|
||||||
|
|
||||||
export function setLogVisibility(visible:boolean) {
|
export function setLogVisibility(visible:boolean) {
|
||||||
@@ -18,8 +18,8 @@ export function renderLog() {
|
|||||||
log.innerText = logLines.join("\n");
|
log.innerText = logLines.join("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
export function log(...args: any[]): void {
|
export function log(...args: any[]): any {
|
||||||
console.log(...args);
|
// console.log(...args);
|
||||||
|
|
||||||
let logLine = `[${new Date().toLocaleTimeString()}]: `;
|
let logLine = `[${new Date().toLocaleTimeString()}]: `;
|
||||||
for (let arg of args) {
|
for (let arg of args) {
|
||||||
@@ -32,4 +32,6 @@ export function log(...args: any[]): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
renderLog();
|
renderLog();
|
||||||
|
|
||||||
|
return [...args];
|
||||||
}
|
}
|
||||||
182
src/main2.ts
182
src/main2.ts
@@ -116,7 +116,7 @@ function logID(ID: string) {
|
|||||||
|
|
||||||
|
|
||||||
// function log(message:string) {
|
// function log(message:string) {
|
||||||
// console.log(message);
|
// console.log.apply(null, log(message);
|
||||||
// let log = document.getElementById("log");
|
// let log = document.getElementById("log");
|
||||||
// let newlog = document.createElement('span');
|
// let newlog = document.createElement('span');
|
||||||
// newlog.innerHTML = `<pre>${message}</pre>`;
|
// newlog.innerHTML = `<pre>${message}</pre>`;
|
||||||
@@ -175,8 +175,8 @@ window.addEventListener('scroll', () => {
|
|||||||
|
|
||||||
// Check if scrolled to bottom
|
// Check if scrolled to bottom
|
||||||
if (scrollPoint >= totalPageHeight) {
|
if (scrollPoint >= totalPageHeight) {
|
||||||
console.log('Scrolled to the bottom!');
|
console.log.apply(null, log('Scrolled to the bottom!'));
|
||||||
console.log(scrollPoint, totalPageHeight);
|
console.log.apply(null, log(scrollPoint, totalPageHeight));
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
@@ -268,20 +268,20 @@ interface PeerMessage {
|
|||||||
// try {
|
// try {
|
||||||
// this.websocket = new WebSocket(`wss://${window.location.hostname}:${window.location.port}/ws`);
|
// this.websocket = new WebSocket(`wss://${window.location.hostname}:${window.location.port}/ws`);
|
||||||
// } catch (error: any) {
|
// } catch (error: any) {
|
||||||
// console.log(error.message);
|
// console.log.apply(null, log(error.message);
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// this.websocket.onopen = async (event) => {
|
// this.websocket.onopen = async (event) => {
|
||||||
// log("ws:connected");
|
// console.log.apply(null, log("ws:connected"));;
|
||||||
// await this.sendHello();
|
// await this.sendHello();
|
||||||
|
|
||||||
// // If we're running as a headless peer, send a hello message every N seconds to refresh the posts we have.
|
// // If we're running as a headless peer, send a hello message every N seconds to refresh the posts we have.
|
||||||
// let helloRefreshIntervalPeriod = 120;
|
// let helloRefreshIntervalPeriod = 120;
|
||||||
// if (app.isHeadless) {
|
// if (app.isHeadless) {
|
||||||
// console.log("wsConnection: Setting hello refresh interval to ", helloRefreshIntervalPeriod)
|
// console.log.apply(null, log("wsConnection: Setting hello refresh interval to ", helloRefreshIntervalPeriod)
|
||||||
// this.helloRefreshInterval = window.setInterval(() => {
|
// this.helloRefreshInterval = window.setInterval(() => {
|
||||||
// console.log("wsConnection: Hello refresh.")
|
// console.log.apply(null, log("wsConnection: Hello refresh.")
|
||||||
|
|
||||||
// if (!navigator.onLine) {
|
// if (!navigator.onLine) {
|
||||||
// return;
|
// return;
|
||||||
@@ -299,9 +299,9 @@ interface PeerMessage {
|
|||||||
// };
|
// };
|
||||||
|
|
||||||
// this.websocket.onclose = (event) => {
|
// this.websocket.onclose = (event) => {
|
||||||
// log("ws:disconnected");
|
// console.log.apply(null, log("ws:disconnected"));;
|
||||||
// // this.retry *= 2;
|
// // this.retry *= 2;
|
||||||
// log(`Retrying in ${this.retry} seconds`);
|
// console.log.apply(null, log(`Retrying in ${this.retry} seconds`));;
|
||||||
// window.setTimeout(() => { this.connect(); }, this.retry * 1000);
|
// window.setTimeout(() => { this.connect(); }, this.retry * 1000);
|
||||||
// };
|
// };
|
||||||
|
|
||||||
@@ -322,7 +322,7 @@ interface PeerMessage {
|
|||||||
// };
|
// };
|
||||||
|
|
||||||
// this.websocket.onerror = (event) => {
|
// this.websocket.onerror = (event) => {
|
||||||
// log('ws:error: ' + event);
|
// console.log.apply(null, log('ws:error: ' + event));;
|
||||||
// };
|
// };
|
||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
@@ -403,9 +403,9 @@ class wsConnection {
|
|||||||
let json = ""
|
let json = ""
|
||||||
try {
|
try {
|
||||||
json = JSON.stringify(message);
|
json = JSON.stringify(message);
|
||||||
// console.log("*******", (await compressString(json)).byteLength, json.length);
|
// console.log.apply(null, log("*******", (await compressString(json)).byteLength, json.length);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log(e, "wsConnection send: Couldn't serialize message", message);
|
console.log.apply(null, log(e, "wsConnection send: Couldn't serialize message", message));
|
||||||
}
|
}
|
||||||
// log(`ws->${json.slice(0, 240)}`)
|
// log(`ws->${json.slice(0, 240)}`)
|
||||||
this.websocket!.send(json);
|
this.websocket!.send(json);
|
||||||
@@ -418,7 +418,7 @@ class wsConnection {
|
|||||||
|
|
||||||
async sendWebRTCDescription(description: RTCSessionDescription | null) {
|
async sendWebRTCDescription(description: RTCSessionDescription | null) {
|
||||||
|
|
||||||
console.log("description:", description);
|
console.log.apply(null, log("description:", description));
|
||||||
this.send({ type: "rtc_session_description", description: description });
|
this.send({ type: "rtc_session_description", description: description });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -426,19 +426,19 @@ class wsConnection {
|
|||||||
// log(`getPostsForUserResponse: ${data}`)
|
// log(`getPostsForUserResponse: ${data}`)
|
||||||
|
|
||||||
let message = data.message;
|
let message = data.message;
|
||||||
log(`Net: got ${message.post_ids.length} post IDs for user ${logID(message.user_id)} from peer ${logID(data.from)}`);
|
console.log.apply(null, log(`Net: got ${message.post_ids.length} post IDs for user ${logID(message.user_id)} from peer ${logID(data.from)}`));;
|
||||||
|
|
||||||
|
|
||||||
let startTime = app.timerStart();
|
let startTime = app.timerStart();
|
||||||
let postIds = await checkPostIds(message.user_id, message.post_ids);
|
let postIds = await checkPostIds(message.user_id, message.post_ids);
|
||||||
log(`ID Check for user ${logID(message.user_id)} took ${app.timerDelta().toFixed(2)}ms`);
|
console.log.apply(null, log(`ID Check for user ${logID(message.user_id)} took ${app.timerDelta().toFixed(2)}ms`));;
|
||||||
log(`Need ${postIds.length} posts for user ${logID(message.user_id)} from peer ${logID(data.from)}`);
|
console.log.apply(null, log(`Need ${postIds.length} posts for user ${logID(message.user_id)} from peer ${logID(data.from)}`));;
|
||||||
|
|
||||||
if (postIds.length === 0) {
|
if (postIds.length === 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
log(`Net: Req ${postIds.length} posts for user ${logID(message.user_id)} from peer ${logID(data.from)}`)
|
console.log.apply(null, log(`Net: Req ${postIds.length} posts for user ${logID(message.user_id)} from peer ${logID(data.from)}`));
|
||||||
let responseMessage = { type: "peer_message", from: app.peerID, to: data.from, from_username: app.username, from_peername: app.peername, message: { type: "get_posts_for_user", post_ids: postIds, user_id: message.user_id } }
|
let responseMessage = { type: "peer_message", from: app.peerID, to: data.from, from_username: app.username, from_peername: app.peername, message: { type: "get_posts_for_user", post_ids: postIds, user_id: message.user_id } }
|
||||||
|
|
||||||
this.send(responseMessage);
|
this.send(responseMessage);
|
||||||
@@ -472,10 +472,10 @@ class wsConnection {
|
|||||||
let postIds = await getAllIds(message.user_id) ?? [];
|
let postIds = await getAllIds(message.user_id) ?? [];
|
||||||
postIds = postIds.filter((postID: string) => !this.postBlockList.has(postID));
|
postIds = postIds.filter((postID: string) => !this.postBlockList.has(postID));
|
||||||
if (postIds.length === 0) {
|
if (postIds.length === 0) {
|
||||||
log(`Net: I know about user ${logID(message.user_id)} but I have 0 posts, so I'm not sending any to to peer ${logID(data.from)}`);
|
console.log.apply(null, log(`Net: I know about user ${logID(message.user_id)} but I have 0 posts, so I'm not sending any to to peer ${logID(data.from)}`));;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
log(`Net: Sending ${postIds.length} post Ids for user ${logID(message.user_id)} to peer ${logID(data.from)}`)
|
console.log.apply(null, log(`Net: Sending ${postIds.length} post Ids for user ${logID(message.user_id)} to peer ${logID(data.from)}`));
|
||||||
|
|
||||||
let responseMessage = { type: "peer_message", from: app.peerID, to: data.from, from_username: app.username, from_peername: app.peername, message: { type: "get_post_ids_for_user_response", post_ids: postIds, user_id: message.user_id } }
|
let responseMessage = { type: "peer_message", from: app.peerID, to: data.from, from_username: app.username, from_peername: app.peername, message: { type: "get_post_ids_for_user_response", post_ids: postIds, user_id: message.user_id } }
|
||||||
this.send(responseMessage);
|
this.send(responseMessage);
|
||||||
@@ -489,7 +489,7 @@ class wsConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (let [peerID, peerInfo] of this.seenPeers.entries()) {
|
for (let [peerID, peerInfo] of this.seenPeers.entries()) {
|
||||||
log(`broadcastNewPost: sending new post to ${logID(peerID)}:${peerInfo.peerName}:${peerInfo.userName}`);
|
console.log.apply(null, log(`broadcastNewPost: sending new post to ${logID(peerID)}:${peerInfo.peerName}:${peerInfo.userName}`));;
|
||||||
|
|
||||||
this.sendPostsForUser(peerID, app.userID, [newPost])
|
this.sendPostsForUser(peerID, app.userID, [newPost])
|
||||||
}
|
}
|
||||||
@@ -519,18 +519,18 @@ class wsConnection {
|
|||||||
let message = data.message;
|
let message = data.message;
|
||||||
let posts = await getPostsByIds(message.user_id, message.post_ids) ?? [];
|
let posts = await getPostsByIds(message.user_id, message.post_ids) ?? [];
|
||||||
|
|
||||||
log(`Net: Sending ${posts.length} posts for user ${logID(message.user_id)} to peer ${logID(data.from)}`);
|
console.log.apply(null, log(`Net: Sending ${posts.length} posts for user ${logID(message.user_id)} to peer ${logID(data.from)}`));;
|
||||||
|
|
||||||
app.timerStart();
|
app.timerStart();
|
||||||
let output = [];
|
let output = [];
|
||||||
|
|
||||||
console.log("Serializing images");
|
console.log.apply(null, log("Serializing images"));
|
||||||
for (let post of posts) {
|
for (let post of posts) {
|
||||||
let newPost = (post as any).data;
|
let newPost = (post as any).data;
|
||||||
|
|
||||||
if (newPost.image_data) {
|
if (newPost.image_data) {
|
||||||
// let compressedData = await wsConnection.compressArrayBuffer(newPost.image_data);
|
// let compressedData = await wsConnection.compressArrayBuffer(newPost.image_data);
|
||||||
// console.log((newPost.image_data.byteLength - compressedData.byteLength) / 1024 / 1024);
|
// console.log.apply(null, log((newPost.image_data.byteLength - compressedData.byteLength) / 1024 / 1024);
|
||||||
|
|
||||||
// TODO don't do this, use Blobs direclty!
|
// TODO don't do this, use Blobs direclty!
|
||||||
// https://developer.chrome.com/blog/blob-support-for-Indexeddb-landed-on-chrome-dev
|
// https://developer.chrome.com/blog/blob-support-for-Indexeddb-landed-on-chrome-dev
|
||||||
@@ -540,16 +540,16 @@ class wsConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// let megs = JSON.stringify(newPost).length/1024/1024;
|
// let megs = JSON.stringify(newPost).length/1024/1024;
|
||||||
// console.log(`getPostsForUserHandler id:${newPost.post_id} post length:${megs}`);
|
// console.log.apply(null, log(`getPostsForUserHandler id:${newPost.post_id} post length:${megs}`);
|
||||||
output.push(newPost);
|
output.push(newPost);
|
||||||
}
|
}
|
||||||
|
|
||||||
let responseMessage = { type: "peer_message", from: app.peerID, to: data.from, from_username: app.username, from_peername: app.peername, message: { type: "get_posts_for_user_response", posts: output, user_id: message.user_id } }
|
let responseMessage = { type: "peer_message", from: app.peerID, to: data.from, from_username: app.username, from_peername: app.peername, message: { type: "get_posts_for_user_response", posts: output, user_id: message.user_id } }
|
||||||
|
|
||||||
console.log("Sending posts");
|
console.log.apply(null, log("Sending posts"));
|
||||||
await this.sendPostsForUser(data.from, message.user_id, output);
|
await this.sendPostsForUser(data.from, message.user_id, output);
|
||||||
let sendTime = app.timerDelta();
|
let sendTime = app.timerDelta();
|
||||||
log(`getPostsForUserHandler send took: ${sendTime.toFixed(2)}ms`);
|
console.log.apply(null, log(`getPostsForUserHandler send took: ${sendTime.toFixed(2)}ms`));;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -559,13 +559,13 @@ class wsConnection {
|
|||||||
async getPostsForUserReponseHandler(data: any) {
|
async getPostsForUserReponseHandler(data: any) {
|
||||||
app.timerStart();
|
app.timerStart();
|
||||||
let message = data.message;
|
let message = data.message;
|
||||||
console.log(`Net: got ${message.posts.length} posts for user ${logID(message.user_id)} from peer ${logID(data.from)}`);
|
console.log.apply(null, log(`Net: got ${message.posts.length} posts for user ${logID(message.user_id)} from peer ${logID(data.from)}`));
|
||||||
for (let post of message.posts) {
|
for (let post of message.posts) {
|
||||||
|
|
||||||
// HACK: Some posts have insanely large images, so I'm gonna skip them.
|
// HACK: Some posts have insanely large images, so I'm gonna skip them.
|
||||||
// Once we support delete then we we could delete these posts in a sensible way.
|
// Once we support delete then we we could delete these posts in a sensible way.
|
||||||
if (this.postBlockList.has(post.post_id)) {
|
if (this.postBlockList.has(post.post_id)) {
|
||||||
log(`Skipping blocked post: ${post.post_id}`);
|
console.log.apply(null, log(`Skipping blocked post: ${post.post_id}`));;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -579,12 +579,12 @@ class wsConnection {
|
|||||||
post.image_data = await base64ToArrayBuffer(post.image_data);
|
post.image_data = await base64ToArrayBuffer(post.image_data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.log(`Merging same user peer posts...`)
|
console.log.apply(null, log(`Merging same user peer posts...`));
|
||||||
await mergeDataArray(message.user_id, data.message.posts);
|
await mergeDataArray(message.user_id, data.message.posts);
|
||||||
|
|
||||||
let receiveTime = app.timerDelta();
|
let receiveTime = app.timerDelta();
|
||||||
|
|
||||||
log(`getPostsForUserReponseHandler receive took: ${receiveTime.toFixed(2)}ms`);
|
console.log.apply(null, log(`getPostsForUserReponseHandler receive took: ${receiveTime.toFixed(2)}ms`));;
|
||||||
|
|
||||||
|
|
||||||
if (message.user_id === app.getPreferentialUserID() || app.following.has(message.user_id)) {
|
if (message.user_id === app.getPreferentialUserID() || app.following.has(message.user_id)) {
|
||||||
@@ -644,7 +644,7 @@ class wsConnection {
|
|||||||
.filter(userID => !this.userBlockList.has(userID))
|
.filter(userID => !this.userBlockList.has(userID))
|
||||||
.filter(async userID => (await getAllIds(userID)).length > 0); // TODO:EASYOPT getting all the IDs is unecessary, replace it with a test to get a single ID.
|
.filter(async userID => (await getAllIds(userID)).length > 0); // TODO:EASYOPT getting all the IDs is unecessary, replace it with a test to get a single ID.
|
||||||
|
|
||||||
console.log('Net: Sending known users', knownUsers.map(userID => logID(userID ?? "")));
|
console.log.apply(null, log('Net: Sending known users', knownUsers.map(userID => logID(userID ?? ""))));
|
||||||
return await this.send({ type: "hello", user_id: this.userID, user_name: app.username, peer_id: this.peerID, peer_name: app.peername, known_users: knownUsers });
|
return await this.send({ type: "hello", user_id: this.userID, user_name: app.username, peer_id: this.peerID, peer_name: app.peername, known_users: knownUsers });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -656,7 +656,7 @@ class wsConnection {
|
|||||||
|
|
||||||
let users = [];
|
let users = [];
|
||||||
let receivedUsers = Object.entries(data.userPeers);
|
let receivedUsers = Object.entries(data.userPeers);
|
||||||
log(`Net: got ${receivedUsers.length} users from bootstrap peer.`)
|
console.log.apply(null, log(`Net: got ${receivedUsers.length} users from bootstrap peer.`));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let preferentialUserID = app.getPreferentialUserID();
|
let preferentialUserID = app.getPreferentialUserID();
|
||||||
@@ -664,7 +664,7 @@ class wsConnection {
|
|||||||
users.push([preferentialUserID, currentUserPeers]);
|
users.push([preferentialUserID, currentUserPeers]);
|
||||||
delete data.userPeers[preferentialUserID];
|
delete data.userPeers[preferentialUserID];
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log('helloResponseHandler', e);
|
console.log.apply(null, log('helloResponseHandler', e));
|
||||||
}
|
}
|
||||||
|
|
||||||
let getAllUsers = app.router.route !== App.Route.USER
|
let getAllUsers = app.router.route !== App.Route.USER
|
||||||
@@ -676,7 +676,7 @@ class wsConnection {
|
|||||||
|
|
||||||
for (let [userID, peerIDs] of users) {
|
for (let [userID, peerIDs] of users) {
|
||||||
if (this.userBlockList.has(userID)) {
|
if (this.userBlockList.has(userID)) {
|
||||||
console.log("Skipping user on blocklist:", userID)
|
console.log.apply(null, log("Skipping user on blocklist:", userID));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -687,7 +687,7 @@ class wsConnection {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
log(`Net: Req post IDs for user ${logID(userID)} from peer ${logID(peerID)}`);
|
console.log.apply(null, log(`Net: Req post IDs for user ${logID(userID)} from peer ${logID(peerID)}`));;
|
||||||
this.send({
|
this.send({
|
||||||
type: "peer_message",
|
type: "peer_message",
|
||||||
from: this.peerID,
|
from: this.peerID,
|
||||||
@@ -711,20 +711,20 @@ class wsConnection {
|
|||||||
try {
|
try {
|
||||||
this.websocket = new WebSocket(`wss://${window.location.hostname}:${window.location.port}/ws`);
|
this.websocket = new WebSocket(`wss://${window.location.hostname}:${window.location.port}/ws`);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.log(error.message);
|
console.log.apply(null, log(error.message));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.websocket.onopen = async (event) => {
|
this.websocket.onopen = async (event) => {
|
||||||
log("ws:connected");
|
console.log.apply(null, log("ws:connected"));;
|
||||||
await this.sendHello2();
|
await this.sendHello2();
|
||||||
|
|
||||||
// If we're running as a headless peer, send a hello message every N seconds to refresh the posts we have.
|
// If we're running as a headless peer, send a hello message every N seconds to refresh the posts we have.
|
||||||
// let helloRefreshIntervalPeriod = 120;
|
// let helloRefreshIntervalPeriod = 120;
|
||||||
// if (app.isHeadless) {
|
// if (app.isHeadless) {
|
||||||
// console.log("wsConnection: Setting hello refresh interval to ", helloRefreshIntervalPeriod)
|
// console.log.apply(null, log("wsConnection: Setting hello refresh interval to ", helloRefreshIntervalPeriod)
|
||||||
// this.helloRefreshInterval = window.setInterval(() => {
|
// this.helloRefreshInterval = window.setInterval(() => {
|
||||||
// console.log("wsConnection: Hello refresh.")
|
// console.log.apply(null, log("wsConnection: Hello refresh.")
|
||||||
|
|
||||||
// if (!navigator.onLine) {
|
// if (!navigator.onLine) {
|
||||||
// return;
|
// return;
|
||||||
@@ -742,15 +742,15 @@ class wsConnection {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// this.websocket.onopen = async (event) => {
|
// this.websocket.onopen = async (event) => {
|
||||||
// log("ws:connected");
|
// console.log.apply(null, log("ws:connected"));;
|
||||||
// await this.sendHello();
|
// await this.sendHello();
|
||||||
|
|
||||||
// // If we're running as a headless peer, send a hello message every N seconds to refresh the posts we have.
|
// // If we're running as a headless peer, send a hello message every N seconds to refresh the posts we have.
|
||||||
// let helloRefreshIntervalPeriod = 120;
|
// let helloRefreshIntervalPeriod = 120;
|
||||||
// if (app.isHeadless) {
|
// if (app.isHeadless) {
|
||||||
// console.log("wsConnection: Setting hello refresh interval to ", helloRefreshIntervalPeriod)
|
// console.log.apply(null, log("wsConnection: Setting hello refresh interval to ", helloRefreshIntervalPeriod)
|
||||||
// this.helloRefreshInterval = window.setInterval(() => {
|
// this.helloRefreshInterval = window.setInterval(() => {
|
||||||
// console.log("wsConnection: Hello refresh.")
|
// console.log.apply(null, log("wsConnection: Hello refresh.")
|
||||||
|
|
||||||
// if (!navigator.onLine) {
|
// if (!navigator.onLine) {
|
||||||
// return;
|
// return;
|
||||||
@@ -768,9 +768,9 @@ class wsConnection {
|
|||||||
// };
|
// };
|
||||||
|
|
||||||
this.websocket.onclose = (event) => {
|
this.websocket.onclose = (event) => {
|
||||||
log("ws:disconnected");
|
console.log.apply(null, log("ws:disconnected"));;
|
||||||
// this.retry *= 2;
|
// this.retry *= 2;
|
||||||
log(`Retrying in ${this.retry} seconds`);
|
console.log.apply(null, log(`Retrying in ${this.retry} seconds`));;
|
||||||
window.setTimeout(() => { this.connect(); }, this.retry * 1000);
|
window.setTimeout(() => { this.connect(); }, this.retry * 1000);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -791,7 +791,7 @@ class wsConnection {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.websocket.onerror = (event) => {
|
this.websocket.onerror = (event) => {
|
||||||
log('ws:error: ' + event);
|
console.log.apply(null, log('ws:error: ' + event));;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -821,7 +821,8 @@ class App {
|
|||||||
|
|
||||||
async connect() {
|
async connect() {
|
||||||
this.peerManager = new PeerManager(this.userID, this.peerID, this.isBootstrapPeer);
|
this.peerManager = new PeerManager(this.userID, this.peerID, this.isBootstrapPeer);
|
||||||
log("*************** before peerManager.connect");
|
this.registerRPCs();
|
||||||
|
console.log.apply(null, log("*************** before peerManager.connect"));;
|
||||||
|
|
||||||
// We use promises here to only return from this call once we're connected to the boostrap peer
|
// We use promises here to only return from this call once we're connected to the boostrap peer
|
||||||
// and the datachannel is open.
|
// and the datachannel is open.
|
||||||
@@ -836,17 +837,16 @@ class App {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await this.peerManager.connect();
|
await this.peerManager.connect();
|
||||||
log("*************** after peerManager.connect");
|
console.log.apply(null, log("*************** after peerManager.connect"));;
|
||||||
|
|
||||||
|
|
||||||
if (!this.isBootstrapPeer) {
|
if (!this.isBootstrapPeer) {
|
||||||
let postIDs = await this.peerManager.rpc.getPostIDsForUser(this.peerManager.bootstrapPeerID, this.userID);
|
let postIDs = await this.peerManager.rpc.getPostIDsForUser(this.peerManager.bootstrapPeerID, this.userID);
|
||||||
console.log("peerManager.rpc.getPostIDsForUser", postIDs);
|
console.log.apply(null, log("peerManager.rpc.getPostIDsForUser", postIDs));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getPreferentialUserID() {
|
getPreferentialUserID() {
|
||||||
@@ -964,7 +964,7 @@ class App {
|
|||||||
|
|
||||||
let output = [];
|
let output = [];
|
||||||
|
|
||||||
console.log("Serializing images");
|
console.log.apply(null, log("Serializing images"));
|
||||||
for (let post of posts) {
|
for (let post of posts) {
|
||||||
let newPost = (post as any).data;
|
let newPost = (post as any).data;
|
||||||
|
|
||||||
@@ -990,7 +990,7 @@ class App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async importTweetArchive(userID: string, tweetArchive: any[]) {
|
async importTweetArchive(userID: string, tweetArchive: any[]) {
|
||||||
log("Importing tweet archive")
|
console.log.apply(null, log("Importing tweet archive"));
|
||||||
let postsTestData: any[] = [];
|
let postsTestData: any[] = [];
|
||||||
|
|
||||||
// let response = await fetch("./tweets.js");
|
// let response = await fetch("./tweets.js");
|
||||||
@@ -1022,9 +1022,9 @@ class App {
|
|||||||
// if (response.status === 200) {
|
// if (response.status === 200) {
|
||||||
// imageData = await response.arrayBuffer();
|
// imageData = await response.arrayBuffer();
|
||||||
// }
|
// }
|
||||||
// console.log(imageData);
|
// console.log.apply(null, log(imageData);
|
||||||
// } catch (e) {
|
// } catch (e) {
|
||||||
// console.log(e);
|
// console.log.apply(null, log(e);
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// }
|
// }
|
||||||
@@ -1037,7 +1037,7 @@ class App {
|
|||||||
|
|
||||||
count++;
|
count++;
|
||||||
if (count % 100 === 0) {
|
if (count % 100 === 0) {
|
||||||
log(`Imported ${count} posts...`);
|
console.log.apply(null, log(`Imported ${count} posts...`));;
|
||||||
// render(postsTestData);
|
// render(postsTestData);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1062,14 +1062,14 @@ class App {
|
|||||||
|
|
||||||
let registrations = await navigator.serviceWorker.getRegistrations();
|
let registrations = await navigator.serviceWorker.getRegistrations();
|
||||||
if (registrations.length > 0) {
|
if (registrations.length > 0) {
|
||||||
console.log("Service worker already registered.");
|
console.log.apply(null, log("Service worker already registered."));
|
||||||
return registrations[0];
|
return registrations[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
navigator.serviceWorker
|
navigator.serviceWorker
|
||||||
.register("/sw.js")
|
.register("/sw.js")
|
||||||
.then((registration) => {
|
.then((registration) => {
|
||||||
console.log("Service Worker registered with scope:", registration.scope);
|
console.log.apply(null, log("Service Worker registered with scope:", registration.scope));
|
||||||
return registration;
|
return registration;
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
@@ -1079,7 +1079,7 @@ class App {
|
|||||||
|
|
||||||
async compressImage(imageData: ArrayBuffer, mimeType: string, quality = 0.5): Promise<ArrayBuffer | null> {
|
async compressImage(imageData: ArrayBuffer, mimeType: string, quality = 0.5): Promise<ArrayBuffer | null> {
|
||||||
let uncompressedByteLength = imageData.byteLength;
|
let uncompressedByteLength = imageData.byteLength;
|
||||||
log(`compressImage input:${mimeType} size:${(uncompressedByteLength / 1024).toFixed(2)}KBi quality:${quality}`);
|
console.log.apply(null, log(`compressImage input:${mimeType} size:${(uncompressedByteLength / 1024).toFixed(2)}KBi quality:${quality}`));;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Convert ArrayBuffer to Blob
|
// Convert ArrayBuffer to Blob
|
||||||
@@ -1145,7 +1145,7 @@ class App {
|
|||||||
let compressedByteLength = compressedArrayBuffer.byteLength;
|
let compressedByteLength = compressedArrayBuffer.byteLength;
|
||||||
|
|
||||||
let percent = (uncompressedByteLength / compressedByteLength)
|
let percent = (uncompressedByteLength / compressedByteLength)
|
||||||
log(`compressImage: compressedSize:${(compressedArrayBuffer.byteLength / 1024).toFixed(2)}KBi ${percent.toFixed(2)}:1 compression`);
|
console.log.apply(null, log(`compressImage: compressedSize:${(compressedArrayBuffer.byteLength / 1024).toFixed(2)}KBi ${percent.toFixed(2)}:1 compression`));;
|
||||||
return compressedArrayBuffer;
|
return compressedArrayBuffer;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
@@ -1155,7 +1155,7 @@ class App {
|
|||||||
|
|
||||||
async createNewPost(userID: string, postText: string, mediaData?: ArrayBuffer, mimeType?: "image/png" | "image/gif" | "image/jpg" | "image/jpeg" | "video/mp4") {
|
async createNewPost(userID: string, postText: string, mediaData?: ArrayBuffer, mimeType?: "image/png" | "image/gif" | "image/jpg" | "image/jpeg" | "video/mp4") {
|
||||||
if ((typeof postText !== "string") || postText.length === 0) {
|
if ((typeof postText !== "string") || postText.length === 0) {
|
||||||
log("Not posting an empty string...")
|
console.log.apply(null, log("Not posting an empty string..."));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1183,7 +1183,7 @@ class App {
|
|||||||
let id = localStorage.getItem("peer_id");
|
let id = localStorage.getItem("peer_id");
|
||||||
|
|
||||||
if (!id) {
|
if (!id) {
|
||||||
log(`Didn't find a peer ID, generating one`);
|
console.log.apply(null, log(`Didn't find a peer ID, generating one`));;
|
||||||
id = generateID();
|
id = generateID();
|
||||||
localStorage.setItem("peer_id", id);
|
localStorage.setItem("peer_id", id);
|
||||||
}
|
}
|
||||||
@@ -1195,7 +1195,7 @@ class App {
|
|||||||
let id = localStorage.getItem("dandelion_id");
|
let id = localStorage.getItem("dandelion_id");
|
||||||
|
|
||||||
if (!id) {
|
if (!id) {
|
||||||
log(`Didn't find a user ID, generating one`);
|
console.log.apply(null, log(`Didn't find a user ID, generating one`));;
|
||||||
id = generateID();
|
id = generateID();
|
||||||
localStorage.setItem("dandelion_id", id);
|
localStorage.setItem("dandelion_id", id);
|
||||||
}
|
}
|
||||||
@@ -1270,17 +1270,17 @@ class App {
|
|||||||
initOffline(connection: wsConnection) {
|
initOffline(connection: wsConnection) {
|
||||||
// Event listener for going offline
|
// Event listener for going offline
|
||||||
window.addEventListener('offline', () => {
|
window.addEventListener('offline', () => {
|
||||||
log("offline")
|
console.log.apply(null, log("offline"));
|
||||||
});
|
});
|
||||||
|
|
||||||
// Event listener for going online
|
// Event listener for going online
|
||||||
window.addEventListener('online', async () => {
|
window.addEventListener('online', async () => {
|
||||||
log("online")
|
console.log.apply(null, log("online"));
|
||||||
connection.connect();
|
// connection.connect();
|
||||||
this.render();
|
this.render();
|
||||||
});
|
});
|
||||||
|
|
||||||
log(`Online status: ${navigator.onLine ? "online" : "offline"}`)
|
console.log.apply(null, log(`Online status: ${navigator.onLine ? "online" : "offline"}`));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1423,7 +1423,7 @@ class App {
|
|||||||
|
|
||||||
let filePickerLabel = document.getElementById('file-input-label');
|
let filePickerLabel = document.getElementById('file-input-label');
|
||||||
filePickerLabel?.addEventListener('click', () => {
|
filePickerLabel?.addEventListener('click', () => {
|
||||||
console.log("Add pic...")
|
console.log.apply(null, log("Add pic..."));
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@@ -1436,7 +1436,7 @@ class App {
|
|||||||
// importTweetsButton.addEventListener('click', async () => {
|
// importTweetsButton.addEventListener('click', async () => {
|
||||||
// let file = await this.selectFile('text/*');
|
// let file = await this.selectFile('text/*');
|
||||||
|
|
||||||
// console.log(file);
|
// console.log.apply(null, log(file);
|
||||||
// if (file == null) {
|
// if (file == null) {
|
||||||
// return;
|
// return;
|
||||||
// }
|
// }
|
||||||
@@ -1496,7 +1496,7 @@ class App {
|
|||||||
let posts: StoragePost[] = [];
|
let posts: StoragePost[] = [];
|
||||||
for (let followedID of this.following.keys()) {
|
for (let followedID of this.following.keys()) {
|
||||||
posts = posts.concat(await getData(followedID, new Date(2022, 8), new Date()));
|
posts = posts.concat(await getData(followedID, new Date(2022, 8), new Date()));
|
||||||
// console.log(followedID);
|
// console.log.apply(null, log(followedID);
|
||||||
}
|
}
|
||||||
|
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
@@ -1551,7 +1551,7 @@ class App {
|
|||||||
posts = await getData(userID, new Date(2022, 8), new Date());
|
posts = await getData(userID, new Date(2022, 8), new Date());
|
||||||
|
|
||||||
if (posts.length > 0) {
|
if (posts.length > 0) {
|
||||||
log(`Loaded ${posts.length} posts in ${this.timerDelta().toFixed(2)}ms`);
|
console.log.apply(null, log(`Loaded ${posts.length} posts in ${this.timerDelta().toFixed(2)}ms`));;
|
||||||
return posts;
|
return posts;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1576,14 +1576,14 @@ class App {
|
|||||||
|
|
||||||
// let ids = await getAllIds(userID);
|
// let ids = await getAllIds(userID);
|
||||||
// if (ids.length === 0) {
|
// if (ids.length === 0) {
|
||||||
// console.log(`Purging user ${userID}`);
|
// console.log.apply(null, log(`Purging user ${userID}`);
|
||||||
// indexedDB.deleteDatabase(`user_${userID}`);
|
// indexedDB.deleteDatabase(`user_${userID}`);
|
||||||
// continue;
|
// continue;
|
||||||
// }
|
// }
|
||||||
|
|
||||||
console.log(`${document.location.origin}/user/${userID}`);
|
console.log.apply(null, log(`${document.location.origin}/user/${userID}`));
|
||||||
|
|
||||||
// console.log(`https://ddln.app/${this.username}/${uuidToBase58(userID)}`, userID);
|
// console.log.apply(null, log(`https://ddln.app/${this.username}/${uuidToBase58(userID)}`, userID);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1608,12 +1608,12 @@ class App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.peerManager.registerRPC('ping', (args: any) => {
|
this.peerManager.registerRPC('ping', (args: any) => {
|
||||||
return {id:this.peerID};
|
return {id:this.peerID, user:this.userID, user_name:this.username, peer_name:this.peername};
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!this.isBootstrapPeer) {
|
if (!this.isBootstrapPeer) {
|
||||||
let pong = await this.peerManager.rpc.ping(this.peerManager.bootstrapPeerID);
|
let pong = await this.peerManager.rpc.ping(this.peerManager.bootstrapPeerID);
|
||||||
console.log(pong);
|
console.log.apply(null, log('pong from: ', pong));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -1636,7 +1636,7 @@ class App {
|
|||||||
|
|
||||||
let postIDs = await this.peerManager.rpc.getPostIDsForUser("dummy_peer", "bloop");
|
let postIDs = await this.peerManager.rpc.getPostIDsForUser("dummy_peer", "bloop");
|
||||||
|
|
||||||
console.log("peerManager.rpc.getPostIDsForUser", postIDs);
|
console.log.apply(null, log("peerManager.rpc.getPostIDsForUser", postIDs));
|
||||||
|
|
||||||
// this.peerManager.registerSearchQuery('find_peers_for_user', this.query_findPeersForUser);
|
// this.peerManager.registerSearchQuery('find_peers_for_user', this.query_findPeersForUser);
|
||||||
|
|
||||||
@@ -1656,7 +1656,7 @@ class App {
|
|||||||
this.isHeadless = /\bHeadlessChrome\//.test(navigator.userAgent);
|
this.isHeadless = /\bHeadlessChrome\//.test(navigator.userAgent);
|
||||||
this.isBootstrapPeer = urlParams.has("bootstrap");
|
this.isBootstrapPeer = urlParams.has("bootstrap");
|
||||||
if (this.isBootstrapPeer) {
|
if (this.isBootstrapPeer) {
|
||||||
log(`This is a bootstrap peer`);
|
console.log.apply(null, log(`This is a bootstrap peer`));;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.peerID = this.getPeerID();
|
this.peerID = this.getPeerID();
|
||||||
@@ -1666,7 +1666,7 @@ class App {
|
|||||||
|
|
||||||
this.connect();
|
this.connect();
|
||||||
|
|
||||||
this.registerRPCs();
|
// this.registerRPCs();
|
||||||
// this.testPeerManager();
|
// this.testPeerManager();
|
||||||
|
|
||||||
// let peer: RTCPeerConnection | null = null;
|
// let peer: RTCPeerConnection | null = null;
|
||||||
@@ -1687,7 +1687,7 @@ class App {
|
|||||||
|
|
||||||
// peer.onicecandidate = ({ candidate }) => { log(`WRTC:${candidate?.address} ${candidate?.protocol} ${candidate?.type} ${(candidate as any)?.url}`) };
|
// peer.onicecandidate = ({ candidate }) => { log(`WRTC:${candidate?.address} ${candidate?.protocol} ${candidate?.type} ${(candidate as any)?.url}`) };
|
||||||
// peer.onnegotiationneeded = async (event) => {
|
// peer.onnegotiationneeded = async (event) => {
|
||||||
// log("on negotiation needed fired");
|
// console.log.apply(null, log("on negotiation needed fired"));;
|
||||||
|
|
||||||
// let makingOffer = false;
|
// let makingOffer = false;
|
||||||
|
|
||||||
@@ -1722,7 +1722,7 @@ class App {
|
|||||||
|
|
||||||
// peer.createOffer().then((description)=>{
|
// peer.createOffer().then((description)=>{
|
||||||
// peer.setLocalDescription(description)
|
// peer.setLocalDescription(description)
|
||||||
// log("RTC: " + description.sdp + description.type);
|
// console.log.apply(null, log("RTC: " + description.sdp + description.type));;
|
||||||
// });
|
// });
|
||||||
|
|
||||||
// }
|
// }
|
||||||
@@ -1749,7 +1749,7 @@ class App {
|
|||||||
this.getRoute();
|
this.getRoute();
|
||||||
|
|
||||||
if (this.router.route === App.Route.CONNECT) {
|
if (this.router.route === App.Route.CONNECT) {
|
||||||
console.log('connect', this.router.userID);
|
console.log.apply(null, log('connect', this.router.userID));
|
||||||
localStorage.setItem("dandelion_id", this.router.userID);
|
localStorage.setItem("dandelion_id", this.router.userID);
|
||||||
localStorage.removeItem("dandelion_username");
|
localStorage.removeItem("dandelion_username");
|
||||||
}
|
}
|
||||||
@@ -1775,7 +1775,7 @@ class App {
|
|||||||
// if (!isPersisted) {
|
// if (!isPersisted) {
|
||||||
// debugger;
|
// debugger;
|
||||||
// const isPersisted = await navigator.storage.persist();
|
// const isPersisted = await navigator.storage.persist();
|
||||||
// log(`Persisted storage granted: ${isPersisted}`);
|
// console.log.apply(null, log(`Persisted storage granted: ${isPersisted}`));;
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// log(`Persisted: ${(await navigator?.storage?.persisted())?.toString()}`);
|
// log(`Persisted: ${(await navigator?.storage?.persisted())?.toString()}`);
|
||||||
@@ -1784,7 +1784,7 @@ class App {
|
|||||||
|
|
||||||
// let main = await fetch("/main.js");
|
// let main = await fetch("/main.js");
|
||||||
// let code = await main.text();
|
// let code = await main.text();
|
||||||
// console.log(code);
|
// console.log.apply(null, log(code);
|
||||||
// registration.active.postMessage({type:"updateMain", code:code});
|
// registration.active.postMessage({type:"updateMain", code:code});
|
||||||
|
|
||||||
// this.posts = await this.loadPosts(userID) ?? [];
|
// this.posts = await this.loadPosts(userID) ?? [];
|
||||||
@@ -1794,7 +1794,7 @@ class App {
|
|||||||
await this.render(); // , (postID:string)=>{this.deletePost(userID, postID)}
|
await this.render(); // , (postID:string)=>{this.deletePost(userID, postID)}
|
||||||
|
|
||||||
if ((performance as any)?.memory) {
|
if ((performance as any)?.memory) {
|
||||||
log(`memory used: ${((performance as any).memory.usedJSHeapSize / 1024 / 1024).toFixed(2)}Mb`)
|
console.log.apply(null, log(`memory used: ${((performance as any).memory.usedJSHeapSize / 1024 / 1024).toFixed(2)}Mb`));
|
||||||
}
|
}
|
||||||
|
|
||||||
// if (navigator?.storage) {
|
// if (navigator?.storage) {
|
||||||
@@ -1815,7 +1815,7 @@ class App {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
log(`username:${this.username} user:${this.userID} peername:${this.peername} peer:${this.peerID}`);
|
console.log.apply(null, log(`username:${this.username} user:${this.userID} peername:${this.peername} peer:${this.peerID}`));;
|
||||||
|
|
||||||
// await this.purgeEmptyUsers();
|
// await this.purgeEmptyUsers();
|
||||||
|
|
||||||
@@ -1860,7 +1860,7 @@ class App {
|
|||||||
|
|
||||||
async render() {
|
async render() {
|
||||||
if (this.isHeadless) {
|
if (this.isHeadless) {
|
||||||
console.log('Headless so skipping render...');
|
console.log.apply(null, log('Headless so skipping render...'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1906,7 +1906,7 @@ class App {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default: {
|
default: {
|
||||||
console.log("Render: got a route I didn't understand. Rendering HOME:", this.router.route);
|
console.log.apply(null, log("Render: got a route I didn't understand. Rendering HOME:", this.router.route));
|
||||||
this.posts = await this.loadPostsFromStorage(this.userID) ?? [];
|
this.posts = await this.loadPostsFromStorage(this.userID) ?? [];
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -1938,7 +1938,7 @@ class App {
|
|||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// console.log("added:", addedPosts, "removed:", deletedPosts);
|
// console.log.apply(null, log("added:", addedPosts, "removed:", deletedPosts);
|
||||||
|
|
||||||
const fragment = document.createDocumentFragment();
|
const fragment = document.createDocumentFragment();
|
||||||
|
|
||||||
@@ -1972,14 +1972,14 @@ class App {
|
|||||||
|
|
||||||
let renderTime = this.timerDelta();
|
let renderTime = this.timerDelta();
|
||||||
|
|
||||||
log(`render took: ${renderTime.toFixed(2)}ms`);
|
console.log.apply(null, log(`render took: ${renderTime.toFixed(2)}ms`));;
|
||||||
performance.mark("render-end");
|
performance.mark("render-end");
|
||||||
performance.measure('render-time', 'render-start', 'render-end');
|
performance.measure('render-time', 'render-start', 'render-end');
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// if ((performance as any)?.memory) {
|
// if ((performance as any)?.memory) {
|
||||||
// log(`memory used: ${((performance as any).memory.usedJSHeapSize / 1024 / 1024).toFixed(2)}Mb`)
|
// console.log.apply(null, log(`memory used: ${((performance as any).memory.usedJSHeapSize / 1024 / 1024).toFixed(2)}Mb`));
|
||||||
// }
|
// }
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -2092,7 +2092,7 @@ class App {
|
|||||||
|
|
||||||
getRoute() {
|
getRoute() {
|
||||||
let path = document.location.pathname;
|
let path = document.location.pathname;
|
||||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>", path);
|
console.log.apply(null, log("router: path ", path));
|
||||||
|
|
||||||
const regex = "(user/([a-zA-Z0-9\-]+)/?(post/([a-zA-Z0-9\-]+)?/?)?(media/([0-9]+)?)?)|(connect/([a-zA-Z0-9\-]+))";
|
const regex = "(user/([a-zA-Z0-9\-]+)/?(post/([a-zA-Z0-9\-]+)?/?)?(media/([0-9]+)?)?)|(connect/([a-zA-Z0-9\-]+))";
|
||||||
|
|
||||||
@@ -2118,7 +2118,7 @@ class App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>", this.router.userID, this.router.postID, this.router.mediaID, App.Route[this.router.route]);
|
console.log.apply(null, log("router: ", this.router.userID, this.router.postID, this.router.mediaID, App.Route[this.router.route]));
|
||||||
|
|
||||||
// user = /user/<ID>
|
// user = /user/<ID>
|
||||||
// post = /user/<ID>/post/<ID>
|
// post = /user/<ID>/post/<ID>
|
||||||
|
|||||||
@@ -345,4 +345,3 @@ export async function getPostsByIds(userID, postIDs) {
|
|||||||
}
|
}
|
||||||
return posts; // Return the array of posts
|
return posts; // Return the array of posts
|
||||||
}
|
}
|
||||||
//# sourceMappingURL=db.js.map
|
|
||||||
@@ -1577,4 +1577,3 @@ class App {
|
|||||||
})(App || (App = {}));
|
})(App || (App = {}));
|
||||||
let app = new App();
|
let app = new App();
|
||||||
window.addEventListener("load", app.main.bind(app));
|
window.addEventListener("load", app.main.bind(app));
|
||||||
//# sourceMappingURL=main.js.map
|
|
||||||
@@ -116,4 +116,3 @@ addEventListener("message", async (e) => {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
//# sourceMappingURL=sw.js.map
|
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
|
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
|
||||||
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
// "declaration": true, /* Generates corresponding '.d.ts' file. */
|
||||||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
||||||
"sourceMap": true, /* Generates corresponding '.map' file. */
|
"sourceMap": false, /* Generates corresponding '.map' file. */
|
||||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||||
"outDir": "./static", /* Redirect output structure to the directory. */
|
"outDir": "./static", /* Redirect output structure to the directory. */
|
||||||
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||||
|
|||||||
Reference in New Issue
Block a user