diff --git a/src/PeerManager.ts b/src/PeerManager.ts index e545dfe..3887eb9 100644 --- a/src/PeerManager.ts +++ b/src/PeerManager.ts @@ -43,7 +43,7 @@ export class PeerManager { return; } - log("<-signaler:", message); + console.log.apply(null, log("<-signaler:", message)); this.websocket.send(messageJSON); } @@ -60,7 +60,7 @@ export class PeerManager { throw new Error(); } - log("->signaler:", message); + console.log.apply(null, log("->signaler:", message)); 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. 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(); this.peers.delete(message.from); peerConnection = undefined; @@ -94,7 +94,7 @@ export class PeerManager { 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; } @@ -116,12 +116,13 @@ export class PeerManager { async onHello2Received(bootstrapPeerID: string) { if (this.isBootstrapPeer) { + this.connectPromise?.resolve(); return; } if (!bootstrapPeerID) { - log("Didn't get bootstrap peer, waiting 10 seconds..."); - setTimeout(async (e:Event)=>{await this.sendHello2()}, 10_000); + console.log.apply(null, log("Didn't get bootstrap peer, waiting 10 seconds...")); + setTimeout(async (e: Event) => { await this.sendHello2() }, 10_000); return; } @@ -184,7 +185,7 @@ export class PeerManager { } this.websocket.onopen = async (event) => { - log("PeerManager:ws:onopen"); + console.log.apply(null, log("peermanager:ws:onopen")); this.sendHello2(); }; @@ -234,15 +235,13 @@ export class PeerManager { this.bootstrapPeerConnection = null; } - - } async disconnect(remotePeerID: string) { let peer = this.peers.get(remotePeerID); if (!peer) { - log(`PeerManager.disconnect: couln't find peer ${remotePeerID}`); + console.log.apply(null, log(`PeerManager.disconnect: couln't find peer ${remotePeerID}`)); return; } @@ -254,7 +253,7 @@ export class PeerManager { let peer = this.peers.get(peerID); if (!peer) { - log(`Can't find peer ${peerID}`); + console.log.apply(null, log(`Can't find peer ${peerID}`)); return; } @@ -265,7 +264,7 @@ export class PeerManager { let func = this.RPC_remote.get(functionName); if (!func) { - throw new Error(); + throw new Error(`callFromRemote: got RPC we don't know about: ${functionName}, ${args}`); } return func(args); @@ -292,7 +291,7 @@ export class PeerManager { } 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) => { -// log("signaler:ws:onopen"); +// console.log.apply(null, log("signaler:ws:onopen"); // await this.sendHello2(); // }; @@ -361,11 +360,11 @@ interface Message { // try { // message = JSON.parse(messageJSON); // } catch (e) { -// log(e); +// console.log.apply(null, log(e); // throw new Error(); // } -// log("->signaler:", message); +// console.log.apply(null, log("->signaler:", message); // if (message.type === "hello2") { @@ -384,7 +383,7 @@ interface Message { // let connection = this.peerRoutes.get(message.from_peer); // 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; // } // connection.onSignalerMessage(message); @@ -463,11 +462,11 @@ class PeerConnection { if (!this.dataChannel) { throw new Error(); } - log("data channel is open!"); - this.send({ type: "hello datachannel", from: this.peerManager.peerID }); + console.log.apply(null, log("data channel is open!")); + this.send({ type: "hello datachannel", from: this.peerManager.peerID, to: this.remotePeerID}); // 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) { 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) => { - log("data channel message: ", e.data) + console.log.apply(null, log("->datachannel: ", e.data)) this.onMessage(e.data); } } @@ -488,15 +487,17 @@ class PeerConnection { this.rtcPeer = new RTCPeerConnection(PeerConnection.config); 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) { throw new Error("onconnectionstatechange"); } - + // When the connection is closed, tell the peer manager that this connection has gone away if (this.rtcPeer.connectionState === "disconnected") { this.peerManager.onPeerDisconnected(this.remotePeerID); + + // window.setTimeout(async () => { await this.peerManager.connectToPeer(this.remotePeerID) }, 10_000); } if (this.rtcPeer.connectionState === "connected") { @@ -512,7 +513,7 @@ class PeerConnection { let localCandidate = stats.get(candidatePair.localCandidateId); 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 }) => log(candidate); + // this.rtcPeer.onicecandidate = ({ candidate }) => console.log.apply(null, log(candidate); this.rtcPeer.onicecandidate = ({ candidate }) => { - log(candidate); + console.log.apply(null, log(candidate)); this.sendPeerMessage(this.remotePeerID, { type: "rtc_candidate", candidate: candidate }); } this.rtcPeer.onnegotiationneeded = async (event) => { - log("on negotiation needed fired"); + console.log.apply(null, log("on negotiation needed fired")); if (!this.rtcPeer) { throw new Error(); @@ -644,7 +645,7 @@ class PeerConnection { } 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); this.dataChannel?.send(messageJSON); @@ -678,10 +679,10 @@ class PeerConnection { try { message = JSON.parse(messageJSON); } 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; 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); } } diff --git a/src/log.ts b/src/log.ts index 1b42c25..e7b7aac 100644 --- a/src/log.ts +++ b/src/log.ts @@ -1,5 +1,5 @@ let logLines: string[] = []; -let logLength = 30; +let logLength = 100; let logVisible = false; export function setLogVisibility(visible:boolean) { @@ -18,8 +18,8 @@ export function renderLog() { log.innerText = logLines.join("\n"); } -export function log(...args: any[]): void { - console.log(...args); +export function log(...args: any[]): any { + // console.log(...args); let logLine = `[${new Date().toLocaleTimeString()}]: `; for (let arg of args) { @@ -32,4 +32,6 @@ export function log(...args: any[]): void { } renderLog(); + + return [...args]; } \ No newline at end of file diff --git a/src/main2.ts b/src/main2.ts index c51623e..18e2157 100644 --- a/src/main2.ts +++ b/src/main2.ts @@ -116,7 +116,7 @@ function logID(ID: string) { // function log(message:string) { -// console.log(message); +// console.log.apply(null, log(message); // let log = document.getElementById("log"); // let newlog = document.createElement('span'); // newlog.innerHTML = `
${message}
`; @@ -175,8 +175,8 @@ window.addEventListener('scroll', () => { // Check if scrolled to bottom if (scrollPoint >= totalPageHeight) { - console.log('Scrolled to the bottom!'); - console.log(scrollPoint, totalPageHeight); + console.log.apply(null, log('Scrolled to the bottom!')); + console.log.apply(null, log(scrollPoint, totalPageHeight)); } }); @@ -268,20 +268,20 @@ interface PeerMessage { // try { // this.websocket = new WebSocket(`wss://${window.location.hostname}:${window.location.port}/ws`); // } catch (error: any) { -// console.log(error.message); +// console.log.apply(null, log(error.message); // return; // } // this.websocket.onopen = async (event) => { -// log("ws:connected"); +// console.log.apply(null, log("ws:connected"));; // await this.sendHello(); // // If we're running as a headless peer, send a hello message every N seconds to refresh the posts we have. // let helloRefreshIntervalPeriod = 120; // 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(() => { -// console.log("wsConnection: Hello refresh.") +// console.log.apply(null, log("wsConnection: Hello refresh.") // if (!navigator.onLine) { // return; @@ -299,9 +299,9 @@ interface PeerMessage { // }; // this.websocket.onclose = (event) => { -// log("ws:disconnected"); +// console.log.apply(null, log("ws:disconnected"));; // // 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); // }; @@ -322,7 +322,7 @@ interface PeerMessage { // }; // this.websocket.onerror = (event) => { -// log('ws:error: ' + event); +// console.log.apply(null, log('ws:error: ' + event));; // }; // } // } @@ -403,9 +403,9 @@ class wsConnection { let json = "" try { 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) { - 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)}`) this.websocket!.send(json); @@ -418,7 +418,7 @@ class wsConnection { async sendWebRTCDescription(description: RTCSessionDescription | null) { - console.log("description:", description); + console.log.apply(null, log("description:", description)); this.send({ type: "rtc_session_description", description: description }); } @@ -426,19 +426,19 @@ class wsConnection { // log(`getPostsForUserResponse: ${data}`) 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 postIds = await checkPostIds(message.user_id, message.post_ids); - 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(`ID Check for user ${logID(message.user_id)} took ${app.timerDelta().toFixed(2)}ms`));; + console.log.apply(null, log(`Need ${postIds.length} posts for user ${logID(message.user_id)} from peer ${logID(data.from)}`));; if (postIds.length === 0) { 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 } } this.send(responseMessage); @@ -472,10 +472,10 @@ class wsConnection { let postIds = await getAllIds(message.user_id) ?? []; postIds = postIds.filter((postID: string) => !this.postBlockList.has(postID)); 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; } - 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 } } this.send(responseMessage); @@ -489,7 +489,7 @@ class wsConnection { } 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]) } @@ -519,18 +519,18 @@ class wsConnection { let message = data.message; 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(); let output = []; - console.log("Serializing images"); + console.log.apply(null, log("Serializing images")); for (let post of posts) { let newPost = (post as any).data; if (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! // 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; - // 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); } 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); 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) { app.timerStart(); 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) { // 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. 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; } @@ -579,12 +579,12 @@ class wsConnection { 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); 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)) { @@ -644,7 +644,7 @@ class wsConnection { .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. - 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 }); } @@ -656,7 +656,7 @@ class wsConnection { let users = []; 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 { let preferentialUserID = app.getPreferentialUserID(); @@ -664,7 +664,7 @@ class wsConnection { users.push([preferentialUserID, currentUserPeers]); delete data.userPeers[preferentialUserID]; } catch (e) { - console.log('helloResponseHandler', e); + console.log.apply(null, log('helloResponseHandler', e)); } let getAllUsers = app.router.route !== App.Route.USER @@ -676,7 +676,7 @@ class wsConnection { for (let [userID, peerIDs] of users) { if (this.userBlockList.has(userID)) { - console.log("Skipping user on blocklist:", userID) + console.log.apply(null, log("Skipping user on blocklist:", userID)); continue; } @@ -687,7 +687,7 @@ class wsConnection { 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({ type: "peer_message", from: this.peerID, @@ -711,20 +711,20 @@ class wsConnection { try { this.websocket = new WebSocket(`wss://${window.location.hostname}:${window.location.port}/ws`); } catch (error: any) { - console.log(error.message); + console.log.apply(null, log(error.message)); return; } this.websocket.onopen = async (event) => { - log("ws:connected"); + console.log.apply(null, log("ws:connected"));; await this.sendHello2(); // If we're running as a headless peer, send a hello message every N seconds to refresh the posts we have. // let helloRefreshIntervalPeriod = 120; // 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(() => { - // console.log("wsConnection: Hello refresh.") + // console.log.apply(null, log("wsConnection: Hello refresh.") // if (!navigator.onLine) { // return; @@ -742,15 +742,15 @@ class wsConnection { }; // this.websocket.onopen = async (event) => { - // log("ws:connected"); + // console.log.apply(null, log("ws:connected"));; // await this.sendHello(); // // If we're running as a headless peer, send a hello message every N seconds to refresh the posts we have. // let helloRefreshIntervalPeriod = 120; // 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(() => { - // console.log("wsConnection: Hello refresh.") + // console.log.apply(null, log("wsConnection: Hello refresh.") // if (!navigator.onLine) { // return; @@ -768,9 +768,9 @@ class wsConnection { // }; this.websocket.onclose = (event) => { - log("ws:disconnected"); + console.log.apply(null, log("ws:disconnected"));; // 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); }; @@ -791,7 +791,7 @@ class wsConnection { }; this.websocket.onerror = (event) => { - log('ws:error: ' + event); + console.log.apply(null, log('ws:error: ' + event));; }; } @@ -821,7 +821,8 @@ class App { async connect() { 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 // and the datachannel is open. @@ -836,17 +837,16 @@ class App { }); await this.peerManager.connect(); - log("*************** after peerManager.connect"); + console.log.apply(null, log("*************** after peerManager.connect"));; if (!this.isBootstrapPeer) { 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() { @@ -964,7 +964,7 @@ class App { let output = []; - console.log("Serializing images"); + console.log.apply(null, log("Serializing images")); for (let post of posts) { let newPost = (post as any).data; @@ -990,7 +990,7 @@ class App { } async importTweetArchive(userID: string, tweetArchive: any[]) { - log("Importing tweet archive") + console.log.apply(null, log("Importing tweet archive")); let postsTestData: any[] = []; // let response = await fetch("./tweets.js"); @@ -1022,9 +1022,9 @@ class App { // if (response.status === 200) { // imageData = await response.arrayBuffer(); // } - // console.log(imageData); + // console.log.apply(null, log(imageData); // } catch (e) { - // console.log(e); + // console.log.apply(null, log(e); // } // } @@ -1037,7 +1037,7 @@ class App { count++; if (count % 100 === 0) { - log(`Imported ${count} posts...`); + console.log.apply(null, log(`Imported ${count} posts...`));; // render(postsTestData); } @@ -1062,14 +1062,14 @@ class App { let registrations = await navigator.serviceWorker.getRegistrations(); if (registrations.length > 0) { - console.log("Service worker already registered."); + console.log.apply(null, log("Service worker already registered.")); return registrations[0]; } navigator.serviceWorker .register("/sw.js") .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; }) .catch((error) => { @@ -1079,7 +1079,7 @@ class App { async compressImage(imageData: ArrayBuffer, mimeType: string, quality = 0.5): Promise { 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 { // Convert ArrayBuffer to Blob @@ -1145,7 +1145,7 @@ class App { let compressedByteLength = compressedArrayBuffer.byteLength; 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; } catch (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") { if ((typeof postText !== "string") || postText.length === 0) { - log("Not posting an empty string...") + console.log.apply(null, log("Not posting an empty string...")); return; } @@ -1183,7 +1183,7 @@ class App { let id = localStorage.getItem("peer_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(); localStorage.setItem("peer_id", id); } @@ -1195,7 +1195,7 @@ class App { let id = localStorage.getItem("dandelion_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(); localStorage.setItem("dandelion_id", id); } @@ -1270,17 +1270,17 @@ class App { initOffline(connection: wsConnection) { // Event listener for going offline window.addEventListener('offline', () => { - log("offline") + console.log.apply(null, log("offline")); }); // Event listener for going online window.addEventListener('online', async () => { - log("online") - connection.connect(); + console.log.apply(null, log("online")); + // connection.connect(); 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'); filePickerLabel?.addEventListener('click', () => { - console.log("Add pic...") + console.log.apply(null, log("Add pic...")); }) @@ -1436,7 +1436,7 @@ class App { // importTweetsButton.addEventListener('click', async () => { // let file = await this.selectFile('text/*'); - // console.log(file); + // console.log.apply(null, log(file); // if (file == null) { // return; // } @@ -1496,7 +1496,7 @@ class App { let posts: StoragePost[] = []; for (let followedID of this.following.keys()) { posts = posts.concat(await getData(followedID, new Date(2022, 8), new Date())); - // console.log(followedID); + // console.log.apply(null, log(followedID); } // @ts-ignore @@ -1551,7 +1551,7 @@ class App { posts = await getData(userID, new Date(2022, 8), new Date()); 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; } @@ -1576,14 +1576,14 @@ class App { // let ids = await getAllIds(userID); // if (ids.length === 0) { - // console.log(`Purging user ${userID}`); + // console.log.apply(null, log(`Purging user ${userID}`); // indexedDB.deleteDatabase(`user_${userID}`); // 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) => { - return {id:this.peerID}; + return {id:this.peerID, user:this.userID, user_name:this.username, peer_name:this.peername}; }); if (!this.isBootstrapPeer) { 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"); - 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); @@ -1656,7 +1656,7 @@ class App { this.isHeadless = /\bHeadlessChrome\//.test(navigator.userAgent); this.isBootstrapPeer = urlParams.has("bootstrap"); if (this.isBootstrapPeer) { - log(`This is a bootstrap peer`); + console.log.apply(null, log(`This is a bootstrap peer`));; } this.peerID = this.getPeerID(); @@ -1666,7 +1666,7 @@ class App { this.connect(); - this.registerRPCs(); + // this.registerRPCs(); // this.testPeerManager(); // 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.onnegotiationneeded = async (event) => { - // log("on negotiation needed fired"); + // console.log.apply(null, log("on negotiation needed fired"));; // let makingOffer = false; @@ -1722,7 +1722,7 @@ class App { // peer.createOffer().then((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(); 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.removeItem("dandelion_username"); } @@ -1775,7 +1775,7 @@ class App { // if (!isPersisted) { // debugger; // 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()}`); @@ -1784,7 +1784,7 @@ class App { // let main = await fetch("/main.js"); // let code = await main.text(); - // console.log(code); + // console.log.apply(null, log(code); // registration.active.postMessage({type:"updateMain", code:code}); // this.posts = await this.loadPosts(userID) ?? []; @@ -1794,7 +1794,7 @@ class App { await this.render(); // , (postID:string)=>{this.deletePost(userID, postID)} 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) { @@ -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(); @@ -1860,7 +1860,7 @@ class App { async render() { if (this.isHeadless) { - console.log('Headless so skipping render...'); + console.log.apply(null, log('Headless so skipping render...')); return; } @@ -1906,7 +1906,7 @@ class App { break; } 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) ?? []; 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(); @@ -1972,14 +1972,14 @@ class App { 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.measure('render-time', 'render-start', 'render-end'); // 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() { 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\-]+))"; @@ -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/ // post = /user//post/ diff --git a/static/db.js b/static/db.js index 9a1f7f2..92feacc 100644 --- a/static/db.js +++ b/static/db.js @@ -345,4 +345,3 @@ export async function getPostsByIds(userID, postIDs) { } return posts; // Return the array of posts } -//# sourceMappingURL=db.js.map \ No newline at end of file diff --git a/static/main.js b/static/main.js index 53b4886..dd24e41 100644 --- a/static/main.js +++ b/static/main.js @@ -1577,4 +1577,3 @@ class App { })(App || (App = {})); let app = new App(); window.addEventListener("load", app.main.bind(app)); -//# sourceMappingURL=main.js.map \ No newline at end of file diff --git a/static/sw.js b/static/sw.js index e14579b..f10da19 100644 --- a/static/sw.js +++ b/static/sw.js @@ -116,4 +116,3 @@ addEventListener("message", async (e) => { break; } }); -//# sourceMappingURL=sw.js.map \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index d922b63..4b399fc 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,7 +12,7 @@ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */ // "declaration": true, /* Generates 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. */ "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. */