127.0.0.1:8000 watch-together / master server / websocket / messages / start-watching.js
master

Tree @master (Download .tar.gz)

start-watching.js @masterraw · history · blame

const utils = require('../../utils');
const ws_utils = require('../utils');
const watchrooms = require('../../utils/watchrooms');
const broadcast = require('../broadcast');

module.exports = function(user_id, video_id, respond) {
    let watchroom = watchrooms.get(video_id);
    utils.query("SELECT display_name FROM users WHERE ?", {
        user_id: user_id
    }).catch(utils.handle_err.sql(ws_utils.log)).then(function([user]) {
        return user.display_name;
    }).then(function(display_name) {
        if (watchroom) {
            ws_utils.log.v("watchroom already exists");
            watchrooms.join(user_id, display_name, video_id);
            respond({
                video_id: video_id,
                user_id: user_id,
                viewers: watchroom.viewers
            });

            if (!watchroom.state.paused) {
                ws_utils.log.v(`Pause video for everyone to let new viewer ${user_id} sync state`);
                ws_utils.server_update_state(video_id, {
                    paused: true
                });
            }

            broadcast({
                command: "announce",
                data: {
                    target: "watchroom",
                    type: "viewer-update",
                    viewer: watchroom.viewers[user_id]
                }
            }, watchroom.viewers);
        } else {
            ws_utils.log.v("create new watchroom");
            watchroom = watchrooms.create(user_id, display_name, video_id);
            respond({
                video_id: video_id,
                user_id: user_id,
                viewers: watchroom.viewers
            });
            broadcast({
                command: "announce",
                data: {
                    target: "all",
                    type: "watchroom-open",
                    video_id: video_id,
                    host: watchroom.viewers[user_id]
                }
            });

            utils.query("SELECT name FROM videos WHERE ?", {
                video_id: video_id
            }).then(function([video]) {
                broadcast({
                    command: "announce-message",
                    data: `${display_name} has started watching ${video.name}`
                });
            }).catch(utils.handle_err.sql(ws_utils.log, true))
        }
    }).catch(ws_utils.handle_err.res(
        respond, "Error joining watchroom"
    ));
}