Skip to content

Commit

Permalink
date.now replacement
Browse files Browse the repository at this point in the history
  • Loading branch information
howardchung committed Dec 23, 2024
1 parent dfbb037 commit 1658c1f
Show file tree
Hide file tree
Showing 11 changed files with 32 additions and 39 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"webtorrent": "^2.1.34"
},
"scripts": {
"react": "vite --host",
"ui": "vite --host",
"build": "npm run buildReact && npm run buildServer",
"buildReact": "vite build && npm run typecheck",
"buildServer": "tsc --project server/tsconfig.json",
Expand Down
4 changes: 2 additions & 2 deletions server/room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ export class Room {
// Force a save because this might change in unattended rooms
this.saveRoom();
if (redis && assignTime) {
await redis.lpush('vBrowserSessionMS', Number(new Date()) - assignTime);
await redis.lpush('vBrowserSessionMS', Date.now() - assignTime);
await redis.ltrim('vBrowserSessionMS', 0, 24);
}

Expand Down Expand Up @@ -1004,7 +1004,7 @@ export class Room {
this.vBrowser.controllerClient = clientId;
this.vBrowser.creatorUID = uid;
this.vBrowser.creatorClientID = clientId;
const assignEnd = Number(new Date());
const assignEnd = Date.now();
const assignElapsed = assignEnd - Number(queueTime);
await redis?.lpush('vBrowserStartMS', assignElapsed);
await redis?.ltrim('vBrowserStartMS', 0, 24);
Expand Down
7 changes: 3 additions & 4 deletions server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ if (config.SSL_KEY_FILE && config.SSL_CRT_FILE) {
}
const io = new Server(server, { cors: {}, transports: ['websocket'] });

const launchTime = Number(new Date());
const rooms = new Map<string, Room>();
init();

Expand Down Expand Up @@ -621,7 +620,7 @@ async function release() {
const room = roomArr[i];
if (room.vBrowser && room.vBrowser.assignTime) {
const maxTime = getSessionLimitSeconds(room.vBrowser.large) * 1000;
const elapsed = Number(new Date()) - room.vBrowser.assignTime;
const elapsed = Date.now() - room.vBrowser.assignTime;
const ttl = maxTime - elapsed;
const isTimedOut = ttl && ttl < releaseInterval;
const isAlmostTimedOut = ttl && ttl < releaseInterval * 2;
Expand Down Expand Up @@ -727,7 +726,7 @@ async function getAllRooms() {

async function getStats() {
// Per-shard data is prefixed with "current"
const now = Number(new Date());
const now = Date.now();
let currentUsers = 0;
let currentHttp = 0;
let currentVBrowser = 0;
Expand Down Expand Up @@ -826,7 +825,7 @@ async function getStats() {
.filter(Boolean);

// Per-shard data that we want to see in an array
const currentUptime = [Number(new Date()) - launchTime];
const currentUptime = process.uptime();
const currentMemUsage = [process.memoryUsage().rss];

// Singleton stats below (same for all shards so don't combine)
Expand Down
6 changes: 3 additions & 3 deletions server/utils/time.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
export function getStartOfDay() {
const now = Number(new Date());
const now = Date.now();
return now - (now % 86400000);
}

export function getStartOfHour() {
const now = Number(new Date());
const now = Date.now();
return now - (now % 3600000);
}

export function getStartOfMinute() {
const now = Number(new Date());
const now = Date.now();
return now - (now % 60000);
}
2 changes: 1 addition & 1 deletion server/vm/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export abstract class VMManager {
if (!vm) {
return;
}
return { ...vm, pass, assignTime: Number(new Date()) };
return { ...vm, pass, assignTime: Date.now() };
};

public resetVM = async (vmid: string, roomId?: string): Promise<void> => {
Expand Down
23 changes: 10 additions & 13 deletions src/components/App/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
serverPath,
testAutoplay,
openFileSelector,
getAndSaveClientId,
getOrCreateClientId,
calculateMedian,
getUserImage,
getColorForString,
Expand Down Expand Up @@ -167,7 +167,7 @@ export default class App extends React.Component<AppProps, AppState> {
roomSubtitle: '',
roomLoop: false,
participants: [],
rosterUpdateTS: Number(new Date()),
rosterUpdateTS: Date.now(),
chat: [],
playlist: [],
tsMap: {},
Expand Down Expand Up @@ -318,7 +318,7 @@ export default class App extends React.Component<AppProps, AppState> {
const socket = io(serverPath + roomId, {
transports: ['websocket'],
query: {
clientId: getAndSaveClientId(),
clientId: getOrCreateClientId(),
password,
shard,
},
Expand Down Expand Up @@ -666,7 +666,7 @@ export default class App extends React.Component<AppProps, AppState> {
this.state.chat.push(data);
this.setState({
chat: this.state.chat,
scrollTimestamp: Number(new Date()),
scrollTimestamp: Date.now(),
unreadCount:
this.state.currentTab === 'chat'
? this.state.unreadCount
Expand Down Expand Up @@ -755,15 +755,12 @@ export default class App extends React.Component<AppProps, AppState> {
this.setState({ roomLock: data });
});
socket.on('roster', (data: User[]) => {
this.setState(
{ participants: data, rosterUpdateTS: Number(new Date()) },
() => {
this.setupRTCConnections();
},
);
this.setState({ participants: data, rosterUpdateTS: Date.now() }, () => {
this.setupRTCConnections();
});
});
socket.on('chatinit', (data: ChatMessage[]) => {
this.setState({ chat: data, scrollTimestamp: Number(new Date()) });
this.setState({ chat: data, scrollTimestamp: Date.now() });
});
socket.on('playlist', (data: PlaylistVideo[]) => {
this.setState({ playlist: data });
Expand Down Expand Up @@ -1417,7 +1414,7 @@ export default class App extends React.Component<AppProps, AppState> {
return;
}
const sharer = this.state.participants.find((p) => p.isScreenShare);
const selfId = getAndSaveClientId();
const selfId = getOrCreateClientId();
const localTrack = this.localStreamToPublish?.getVideoTracks()[0];
if (localTrack && !localTrack.onended) {
// Stop sharing if the local stream stops
Expand Down Expand Up @@ -1864,7 +1861,7 @@ export default class App extends React.Component<AppProps, AppState> {
};

refreshControls = () => {
this.setState({ controlsTimestamp: Number(new Date()) });
this.setState({ controlsTimestamp: Date.now() });
};

render() {
Expand Down
4 changes: 2 additions & 2 deletions src/components/ComboBox/ComboBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class ComboBox extends React.Component<ComboBoxProps> {
inputMedia: undefined as string | undefined,
results: undefined as JSX.Element[] | undefined,
loading: false,
lastResultTimestamp: Number(new Date()),
lastResultTimestamp: Date.now(),
};
debounced: any = null;

Expand All @@ -55,7 +55,7 @@ export class ComboBox extends React.Component<ComboBoxProps> {
this.debounced = debounce(async () => {
this.setState({ loading: true });
const query: string = this.state.inputMedia || '';
let timestamp = Number(new Date());
let timestamp = Date.now();
let results: JSX.Element[] | undefined = undefined;
if (
query === '' ||
Expand Down
11 changes: 4 additions & 7 deletions src/components/SearchComponent/SearchComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ export class SearchComponent extends React.Component<SearchComponentProps> {
declare context: React.ContextType<typeof MetadataContext>;
state = {
results: [] as SearchResult[],
resetDropdown: Number(new Date()),
resetDropdown: Date.now(),
loading: false,
lastResultTimestamp: Number(new Date()),
lastResultTimestamp: Date.now(),
inputMedia: undefined,
};
debounced: any = null;
Expand All @@ -35,7 +35,7 @@ export class SearchComponent extends React.Component<SearchComponentProps> {
this.setState({ loading: true });
let query = this.state.inputMedia || '';
let results: SearchResult[] = [];
let timestamp = Number(new Date());
let timestamp = Date.now();
if (this.props.type === 'youtube') {
results = await getYouTubeResults(query);
} else if (this.props.type === 'stream' && this.context.streamPath) {
Expand All @@ -58,10 +58,7 @@ export class SearchComponent extends React.Component<SearchComponentProps> {
};

setMedia = (e: any, data: DropdownProps) => {
window.setTimeout(
() => this.setState({ resetDropdown: Number(new Date()) }),
300,
);
window.setTimeout(() => this.setState({ resetDropdown: Date.now() }), 300);
this.props.setMedia(e, data);
};

Expand Down
2 changes: 1 addition & 1 deletion src/components/Settings/SettingsTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ export const SettingsTab = ({
disableChatSound: data.checked,
}),
);
setUpdateTS(Number(new Date()));
setUpdateTS(Date.now());
}}
/>
</div>
Expand Down
6 changes: 3 additions & 3 deletions src/components/VideoChat/VideoChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Socket } from 'socket.io-client';

import {
formatTimestamp,
getAndSaveClientId,
getOrCreateClientId,
getColorForStringHex,
getDefaultPicture,
iceServers,
Expand Down Expand Up @@ -161,7 +161,7 @@ export class VideoChat extends React.Component<VideoChatProps> {
// We haven't started video chat, exit
return;
}
const selfId = getAndSaveClientId();
const selfId = getOrCreateClientId();

// Delete and close any connections that aren't in the current member list (maybe someone disconnected)
// This allows them to rejoin later
Expand Down Expand Up @@ -235,7 +235,7 @@ export class VideoChat extends React.Component<VideoChatProps> {
borderRadius: '4px',
objectFit: 'contain' as any, // ObjectFit
};
const selfId = getAndSaveClientId();
const selfId = getOrCreateClientId();
return (
<div
style={{
Expand Down
4 changes: 2 additions & 2 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ export const iceServers = () => [
username: 'username',
credential: 'password',
},
{
{
urls: 'turn:5.223.48.157:3478',
username: 'username',
credential: 'password',
Expand Down Expand Up @@ -339,7 +339,7 @@ export async function openFileSelector(accept?: string) {
});
}

export function getAndSaveClientId() {
export function getOrCreateClientId() {
let clientId = window.localStorage.getItem('watchparty-clientid');
if (!clientId) {
// Generate a new clientID and save it
Expand Down

0 comments on commit 1658c1f

Please sign in to comment.