Skip to content

Commit

Permalink
book/8-end redirects after login, websockets
Browse files Browse the repository at this point in the history
  • Loading branch information
tima101 committed Jul 31, 2020
1 parent 248dd03 commit ba574d4
Show file tree
Hide file tree
Showing 9 changed files with 213 additions and 297 deletions.
2 changes: 1 addition & 1 deletion book/8-end/api/server/google-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ function setupGoogle({ server }) {
if (req.user && !req.user.defaultTeamSlug) {
redirectUrlAfterLogin = '/create-team';
} else {
redirectUrlAfterLogin = `/your-settings`;
redirectUrlAfterLogin = `/team/${req.user.defaultTeamSlug}/discussions`;
}

res.redirect(`${process.env.URL_APP}${redirectUrlAfterLogin}`);
Expand Down
2 changes: 1 addition & 1 deletion book/8-end/api/server/passwordless-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ function setupPasswordless({ server }) {
if (req.user && !req.user.defaultTeamSlug) {
redirectUrlAfterLogin = '/create-team';
} else {
redirectUrlAfterLogin = `/your-settings`;
redirectUrlAfterLogin = `/team/${req.user.defaultTeamSlug}/discussions`;
}

res.redirect(`${process.env.URL_APP}${redirectUrlAfterLogin}`);
Expand Down
29 changes: 1 addition & 28 deletions book/8-end/api/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,33 +61,6 @@ server.get('*', (_, res) => {
res.sendStatus(403);
});

server.listen(process.env.PORT_API, (err) => {
if (err) {
throw err;
}
http.listen(process.env.PORT_API, () => {
console.log(`> Ready on ${process.env.URL_API}`);
});

// import './env';
// import * as express from 'express';

// import api from './api';

// import logger from './logs';

// const server = express();

// server.use(express.json());

// api(server);

// server.get('*', (_, res) => {
// res.sendStatus(403);
// });

// server.listen(process.env.PORT_API, (err) => {
// if (err) {
// throw err;
// }
// logger.info(`> Ready on ${process.env.URL_API}`);
// });
18 changes: 11 additions & 7 deletions book/8-end/api/server/sockets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,17 @@ import { DiscussionDocument } from './models/Discussion';
import { PostDocument } from './models/Post';

let io: socketio.Server = null;
// const dev = process.env.NODE_ENV !== 'production';

function setup({ http, origin, sessionMiddleware }) {
if (io === null) {
io = socketio(http, {
origins: `${origin}:443`,
serveClient: false,
});
io = socketio(http, { origins: origin, serveClient: false });

// if (dev) {
// io.origins(origin);
// } else {
// io.origins(`${origin}:443`);
// }

io.use((socket, next) => sessionMiddleware(socket.request, {} as Response, next));

Expand All @@ -32,8 +36,8 @@ function setup({ http, origin, sessionMiddleware }) {
socket.join(`teamRoom-${teamId}`);
});

socket.on('leaveTeam', (teamId) => {
console.log(`** leaveTeam ${teamId}`);
socket.on('leaveTeamRoom', (teamId) => {
console.log(`** leaveTeamRoom ${teamId}`);
socket.leave(`teamRoom-${teamId}`);
});

Expand Down Expand Up @@ -62,7 +66,7 @@ function getSockets(socketId?: string) {
if (socketId && io.sockets.connected[socketId]) {
return io.sockets.connected[socketId].broadcast;
} else {
return io.sockets;
return io;
}
}

Expand Down
73 changes: 0 additions & 73 deletions book/8-end/app/components/posts/PostContent.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,5 @@
import React from 'react';

function addPlaceholder(elm) {
const body = elm.querySelector('.lazy-load-image-body');
const image = elm.querySelector('.s3-image') as HTMLImageElement;
if (!body || !image || !image.dataset.src) {
return;
}

image.style.display = 'none';
const div = window.document.createElement('div');
div.className = 'image-placeholder';
div.style.width = `${image.dataset.width}px`;
div.style.height = `${image.dataset.height}px`;
div.innerHTML = '<p class="image-placeholder-text">loading ...</p>';
body.appendChild(div);
}

type Props = { html: string };

class PostContent extends React.Component<Props> {
Expand All @@ -24,68 +8,11 @@ class PostContent extends React.Component<Props> {

return (
<div
ref={(elm) => (this.postBodyElm = elm)}
style={{ fontSize: '15px', lineHeight: '2em', fontWeight: 300, wordBreak: 'break-all' }}
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}

public postBodyElm: HTMLDivElement;

public componentDidMount() {
this.initializeFileUIandEvent();
}

public componentDidUpdate() {
this.initializeFileUIandEvent();
}

public componentWillUnmount() {
const imgContainers = this.postBodyElm.getElementsByClassName('lazy-load-image');

for (let i = 0; i < imgContainers.length; i++) {
const elm = imgContainers.item(i);
elm.removeEventListener('toggle', this.lazyLoadImage);
}
}

public initializeFileUIandEvent() {
const imgContainers = this.postBodyElm.querySelectorAll('.lazy-load-image');

for (let i = 0; i < imgContainers.length; i++) {
const elm = imgContainers.item(i);
elm.removeEventListener('toggle', this.lazyLoadImage);
elm.addEventListener('toggle', this.lazyLoadImage);

addPlaceholder(elm);
}
}

public lazyLoadImage = (event) => {
const target: HTMLDetailsElement = event.currentTarget;

if (!target.open) {
return;
}

const image = target.querySelector('.s3-image') as HTMLImageElement;
if (!image || image.hasAttribute('loaded') || !image.dataset.src) {
return;
}

const placeholder = target.getElementsByClassName('image-placeholder').item(0);
image.onload = () => {
if (placeholder) {
placeholder.remove();
}

image.style.display = 'inline';
};

image.setAttribute('src', image.dataset.src);
image.setAttribute('loaded', '1');
};
}

export default PostContent;
162 changes: 80 additions & 82 deletions book/8-end/app/lib/store/discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,86 +127,86 @@ class Discussion {
});
}

// public handleDiscussionRealtimeEvent = (data) => {
// console.log('discussion realtime event', data);
// const { action: actionName } = data;

// if (actionName === 'added') {
// this.addDiscussionToLocalCache(data.discussion);
// } else if (actionName === 'edited') {
// this.editDiscussionFromLocalCache(data.discussion);
// } else if (actionName === 'deleted') {
// this.removeDiscussionFromLocalCache(data.id);
// }
// };

// public addDiscussionToLocalCache(data): Discussion {
// const obj = new Discussion({ team: this.team, store: this.store, ...data });

// if (obj.memberIds.includes(this.store.currentUser._id)) {
// this.team.discussions.push(obj);
// }

// return obj;
// }

// public editDiscussionFromLocalCache(data) {
// const discussion = this.team.discussions.find((item) => item._id === data._id);
// if (discussion) {
// if (data.memberIds && data.memberIds.includes(this.store.currentUser._id)) {
// discussion.changeLocalCache(data);
// } else {
// this.removeDiscussionFromLocalCache(data._id);
// }
// } else if (data.memberIds && data.memberIds.includes(this.store.currentUser._id)) {
// this.addDiscussionToLocalCache(data);
// }
// }

// public removeDiscussionFromLocalCache(discussionId: string) {
// const discussion = this.team.discussions.find((item) => item._id === discussionId);
// this.team.discussions.remove(discussion);
// }

// public handlePostRealtimeEvent(data) {
// const { action: actionName } = data;

// if (actionName === 'added') {
// this.addPostToLocalCache(data.post);
// } else if (actionName === 'edited') {
// this.editPostFromLocalCache(data.post);
// } else if (actionName === 'deleted') {
// this.removePostFromLocalCache(data.id);
// }
// }

// public editPostFromLocalCache(data) {
// const post = this.posts.find((t) => t._id === data._id);
// if (post) {
// post.changeLocalCache(data);
// }
// }

// public deletePostFromLocalCache(postId) {
// const post = this.posts.find((t) => t._id === postId);
// this.posts.remove(post);
// }

// public joinSocketRooms() {
// if (this.store.socket) {
// console.log('joining socket discussion room', this.name);
// this.store.socket.emit('joinTeam', this.team._id);
// this.store.socket.emit('joinDiscussion', this._id);
// }
// }

// public leaveSocketRoom() {
// if (this.store.socket) {
// console.log('leaving socket discussion room', this.name);
// this.store.socket.emit('leaveTeam', this.team._id);
// this.store.socket.emit('leaveDiscussion', this._id);
// }
// }
public joinSocketRooms() {
if (this.store.socket) {
console.log('joining socket discussion room', this.name);
this.store.socket.emit('joinTeamRoom', this.team._id);
this.store.socket.emit('joinDiscussionRoom', this._id);
}
}

public leaveSocketRooms() {
if (this.store.socket) {
console.log('leaving socket discussion room', this.name);
this.store.socket.emit('leaveTeamRoom', this.team._id);
this.store.socket.emit('leaveDiscussionRoom', this._id);
}
}

public handleDiscussionRealtimeEvent = (data) => {
console.log('discussion realtime event', data);
const { action: actionName } = data;

if (actionName === 'added') {
this.addDiscussionToLocalCache(data.discussion);
} else if (actionName === 'edited') {
this.editDiscussionFromLocalCache(data.discussion);
} else if (actionName === 'deleted') {
this.removeDiscussionFromLocalCache(data.id);
}
};

public addDiscussionToLocalCache(data): Discussion {
const obj = new Discussion({ team: this.team, store: this.store, ...data });

if (obj.memberIds.includes(this.store.currentUser._id)) {
this.team.discussions.push(obj);
}

return obj;
}

public editDiscussionFromLocalCache(data) {
const discussion = this.team.discussions.find((item) => item._id === data._id);
if (discussion) {
if (data.memberIds && data.memberIds.includes(this.store.currentUser._id)) {
discussion.changeLocalCache(data);
} else {
this.removeDiscussionFromLocalCache(data._id);
}
} else if (data.memberIds && data.memberIds.includes(this.store.currentUser._id)) {
this.addDiscussionToLocalCache(data);
}
}

public removeDiscussionFromLocalCache(discussionId: string) {
const discussion = this.team.discussions.find((item) => item._id === discussionId);
this.team.discussions.remove(discussion);
}

public handlePostRealtimeEvent(data) {
const { action: actionName } = data;

if (actionName === 'added') {
this.addPostToLocalCache(data.post);
} else if (actionName === 'edited') {
this.editPostFromLocalCache(data.post);
} else if (actionName === 'deleted') {
this.deletePostFromLocalCache(data.id);
}
}

public editPostFromLocalCache(data) {
const post = this.posts.find((t) => t._id === data._id);
if (post) {
post.changeLocalCache(data);
}
}

public deletePostFromLocalCache(postId) {
const post = this.posts.find((t) => t._id === postId);
this.posts.remove(post);
}
}

decorate(Discussion, {
Expand All @@ -227,8 +227,6 @@ decorate(Discussion, {
// addDiscussionToLocalCache: action,
// editDiscussionFromLocalCache: action,
// removeDiscussionFromLocalCache: action,


// editPostFromLocalCache: action,
// removePostFromLocalCache: action,

Expand Down
15 changes: 14 additions & 1 deletion book/8-end/app/lib/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ class Store {
}

this.socket = socket;

if (socket) {
socket.on('disconnect', () => {
console.log('socket: ## disconnected');
});

socket.on('reconnect', (attemptNumber) => {
console.log('socket: $$ reconnected', attemptNumber);

this.socket.emit('joinTeamRoom', this.currentTeam._id);
this.socket.emit('joinDiscussionRoom', this.currentTeam.currentDiscussion._id);
});
}
}

public changeCurrentUrl(url: string) {
Expand Down Expand Up @@ -143,7 +156,7 @@ let store: Store = null;
function initializeStore(initialState = {}) {
const isServer = typeof window === 'undefined';

const socket = io(process.env.URL_API);
const socket = isServer ? null : io(process.env.URL_API);

const _store = (store !== null && store !== undefined) ? store : new Store({ initialState, isServer, socket });

Expand Down
Loading

0 comments on commit ba574d4

Please sign in to comment.