- 
          
 - 
                Notifications
    
You must be signed in to change notification settings  - Fork 63
 
Integrated Socket.io | Updated Readme.md #146
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            TheAdich
  wants to merge
  13
  commits into
  DhanushNehru:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
TheAdich:main
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from 11 commits
      Commits
    
    
            Show all changes
          
          
            13 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      2e68b8e
              
                save
              
              
                TheAdich 5aa616e
              
                socket.io
              
              
                TheAdich f6d70ea
              
                final_changes
              
              
                TheAdich d01bdf8
              
                final_changes
              
              
                TheAdich db93d4f
              
                final_changes
              
              
                TheAdich a262a39
              
                final_changes
              
              
                TheAdich 5f40cd4
              
                updated_env
              
              
                TheAdich 0b0fe7d
              
                resolved_merge_conflicts
              
              
                TheAdich 2c1012a
              
                resolved_merge_conflicts
              
              
                TheAdich 303d3dc
              
                minor_changes
              
              
                TheAdich f60f294
              
                final_changes
              
              
                TheAdich ff35e52
              
                added_env
              
              
                TheAdich bc515b6
              
                added-env
              
              
                TheAdich File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              This file was deleted.
      
      Oops, something went wrong.
      
    
  
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              Large diffs are not rendered by default.
      
      Oops, something went wrong.
      
    
  
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1 @@ | ||
| /node_modules | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| const Code=require('../models/Code'); | ||
| 
     | 
||
| const getCode=async(req,res)=>{ | ||
| try{ | ||
| const {id,language}=req.query; | ||
| console.log(decodeURIComponent(language)); | ||
| const code=await Code.findOne({room:id,language:language}); | ||
| if(!code){ | ||
| let codeValue=''; | ||
| if(language==='javascript'){ | ||
| codeValue="console.log('Hello Worlds')"; | ||
| } | ||
| else if(language==='python'){ | ||
| codeValue="print('Hello World')"; | ||
| } | ||
| else if(language==='java'){ | ||
| codeValue="public class HelloWorld{public static void main(String[] args){System.out.println('Hello World');}}"; | ||
| } | ||
| else if(language==="C++(Clang 7.0.1)"){ | ||
| codeValue="#include<iostream>using namespace std;int main(){cout<<'Hello World'<<endl;return 0;}"; | ||
| } | ||
| const newCode=await Code.create({ | ||
| room:id, | ||
| language:language, | ||
| code:codeValue | ||
| }) | ||
| return res.status(201).json({code:newCode}); | ||
| } | ||
| return res.status(200).json({code}); | ||
| }catch(err){ | ||
| console.log(err); | ||
| return res.status(400).json({msg:"Error in fetching the code"}) | ||
| } | ||
| } | ||
| 
     | 
||
| module.exports={getCode}; | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| const Room = require('../models/Room'); | ||
| 
     | 
||
| const createRoom = async (req, res) => { | ||
| const { roomName } = req.body; | ||
| if (!roomName ) return res.status(400).json({ msg: "Enter all Fields" }); | ||
| try { | ||
| // add the user who has created this room automatically | ||
| // const user = req.user; | ||
| const newRoom = await Room.create({ roomName }) | ||
| return res.status(200).json({ newRoom }) | ||
| } catch (err) { | ||
| console.log(err); | ||
| res.status(500).json({ msg: "Error in creating room" }); | ||
| } | ||
| } | ||
| 
     | 
||
| const joinRoom = async (req, res) => { | ||
| const { roomId } = req.body; | ||
| try { | ||
| //const user = req.user; | ||
| const room = await Room.findById({ _id: roomId }) | ||
| if (!room) return res.status(404).json({ msg: "Room not found" }); | ||
| 
     | 
||
| return res.status(200).json({ room }); | ||
| } catch (err) { | ||
| console.log(err); | ||
| res.status(400).json({ msg: "Error in joining room" }); | ||
| } | ||
| } | ||
| 
     | 
||
| const getAllRoom=async(req,res)=>{ | ||
| try { | ||
| const rooms = await Room.find({}).sort({ createdAt: -1 });; | ||
| return res.status(200).json({ rooms }); | ||
| } catch (err) { | ||
| console.log(err); | ||
| res.status(400).json({ msg: "Error in getting all rooms" }); | ||
| } | ||
| } | ||
| 
     | 
||
| const getRoomById=async(req,res)=>{ | ||
| try{ | ||
| const {id,language}=req.query | ||
| const room=await Room.findOne({_id:id,language:language}); | ||
| if(!room) return res.status(404).json({ msg: "Room not found" }); | ||
| return res.status(200).json({ room }); | ||
| }catch(err){ | ||
| console.log(err); | ||
| res.status(400).json({ msg: "Error in getting room by id" }); | ||
| } | ||
| } | ||
| 
     | 
||
| 
     | 
||
| module.exports = { joinRoom, createRoom,getAllRoom,getRoomById } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| const express = require('express'); | ||
| const mongoose = require('mongoose'); | ||
| const cookieParser = require('cookie-parser'); | ||
| const cors = require('cors'); | ||
| const http = require('http'); | ||
| const { Server } = require("socket.io"); | ||
| const Room = require('./models/Room'); | ||
| const Code = require('./models/Code') | ||
| //routers | ||
| 
     | 
||
| const roomRouter = require('./routes/roomRoute'); | ||
| const codeRouter = require('./routes/codeRoute'); | ||
| 
     | 
||
| const port = 5000; | ||
| 
     | 
||
| const app = express(); | ||
| const server = http.createServer(app); | ||
| 
     | 
||
| app.use(express.json()); | ||
| app.use(express.urlencoded({ extended: false })); | ||
| app.use(cookieParser()); | ||
| app.use(cors({ | ||
| origin: "http://localhost:3000", | ||
| credentials: true, | ||
| allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Authorization"] | ||
| })); | ||
| 
     | 
||
| 
     | 
||
| app.use('/api/room', roomRouter); | ||
| app.use('/api/code',codeRouter); | ||
| 
     | 
||
| 
     | 
||
| mongoose.connect("mongodb+srv://testing_node:test1234@cluster0.jriry7x.mongodb.net/customDb?retryWrites=true&w=majority&appName=Cluster0") | ||
| .then((success) => console.log("Connected to MongoDB")) | ||
| .catch(err => console.log("Error connecting")); | ||
| 
     | 
||
| server.listen(port, () => { | ||
| console.log(`Running on port ${port}`); | ||
| }) | ||
| 
     | 
||
| const io = new Server(server, { | ||
| cors: { | ||
| origin: "http://localhost:3000", | ||
| credentials: true, | ||
| allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Authorization"] | ||
| } | ||
| }) | ||
| 
     | 
||
| //Mapping room to the list of socket user | ||
| let userRoomMap = new Map(); | ||
| let socketIdMap = new Map(); | ||
| 
     | 
||
| 
     | 
||
| io.on('connection', (socket) => { | ||
| console.log(`${socket.id} connected`); | ||
| socket.on('joinroom', async ({ roomId }) => { | ||
| if (!userRoomMap.get(roomId)) { | ||
| userRoomMap.set(roomId, [socket.id]); | ||
| socketIdMap.set(socket.id, roomId); | ||
| socket.join(roomId); | ||
| } | ||
| else { | ||
| const socketIds = userRoomMap.get(roomId); | ||
| if (!socketIds.includes(socket.id)) { | ||
| socketIds.push(socket.id); | ||
| socketIdMap.set(socket.id, roomId); | ||
| socket.join(roomId); | ||
| } | ||
| } | ||
| socket.emit('welcomeToRoom', { userlist: userRoomMap.get(roomId) }) | ||
| //console.log(userRoomMap); | ||
| }) | ||
| 
     | 
||
| socket.on('codeChange', async ({ roomId, code, lang }) => { | ||
| const decodedLang=decodeURIComponent(lang); | ||
| await Code.findOneAndUpdate({ room: roomId,language:decodedLang}, | ||
| 
     | 
||
| { $set: { code: code } }, | ||
| { new: true } | ||
| ) | ||
| socket.to(roomId).emit('syncCode', { code }); | ||
| }) | ||
| 
     | 
||
| 
     | 
||
| socket.on('disconnect', async () => { | ||
| 
     | 
||
| const roomId = socketIdMap.get(socket.id); | ||
| 
     | 
||
| if (userRoomMap.get(roomId)) { | ||
| const arr = userRoomMap.get(roomId); | ||
| userRoomMap.set(roomId, arr.filter(id => id != socket.id)) | ||
| } | ||
| //console.log(userRoomMap); | ||
| }) | ||
| }) | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| const mongoose=require('mongoose'); | ||
| const CodeSchema=mongoose.Schema({ | ||
| language:{ | ||
| type:String, | ||
| required:true | ||
| }, | ||
| code:{ | ||
| type:String, | ||
| }, | ||
| room:{ | ||
| type:mongoose.Schema.Types.ObjectId, | ||
| ref:'Room' | ||
| } | ||
| },{timestamps:true}) | ||
| 
     | 
||
| const Code=mongoose.model('Code',CodeSchema); | ||
| 
     | 
||
| module.exports=Code; | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| const mongoose=require('mongoose'); | ||
| 
     | 
||
| const RoomSchema=mongoose.Schema({ | ||
| roomName:{ | ||
| type:String, | ||
| required:true | ||
| }, | ||
| 
     | 
||
| 
     | 
||
| },{ timestamps: true }) | ||
| 
     | 
||
| const Room=mongoose.model('Room',RoomSchema); | ||
| module.exports= Room; | 
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also why the mongo connection string is hard coded ?
It could be from .env