Skip to content

Commit

Permalink
Refactor shorten.go to use GenerateShortCode function for shortURL an…
Browse files Browse the repository at this point in the history
…d shortCode
  • Loading branch information
abdealijaroli committed Sep 30, 2024
1 parent 4dad7c1 commit d2d6702
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 57 deletions.
3 changes: 1 addition & 2 deletions cmd/shorten.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import (
)

func ShortenURL(longURL string, store *store.PostgresStore) (string, error) {
shortCode := utils.GenerateShortCode(longURL)
shortURL := fmt.Sprintf("https://jaroli.me/%s", shortCode)
shortURL, shortCode := utils.GenerateShortCode(longURL)

store.AddShortURLToDB(longURL, shortCode, false)

Expand Down
39 changes: 16 additions & 23 deletions cmd/signaling/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ var (
return true
},
}
rooms = make(map[string]*Room)
roomsMu sync.Mutex
Rooms = make(map[string]*Room)
RoomsMu sync.Mutex
)

// HandleSignaling manages WebSocket connections, handles messages, and room lifecycle.
Expand Down Expand Up @@ -82,16 +82,16 @@ func HandleSignaling(w http.ResponseWriter, r *http.Request) {

// handleCreate handles room creation by the sender.
func handleCreate(conn *websocket.Conn, roomID string) {
roomsMu.Lock()
defer roomsMu.Unlock()
RoomsMu.Lock()
defer RoomsMu.Unlock()

if _, exists := rooms[roomID]; exists {
if _, exists := Rooms[roomID]; exists {
conn.WriteJSON(map[string]string{"type": "error", "message": "Room already exists"})
return
}

room := &Room{Sender: conn}
rooms[roomID] = room
Rooms[roomID] = room
log.Printf("Room created: %s", roomID)

response := map[string]string{"type": "room-created", "room": roomID}
Expand All @@ -104,9 +104,9 @@ func handleCreate(conn *websocket.Conn, roomID string) {
func handleJoin(conn *websocket.Conn, roomID string) {
log.Printf("Attempting to join room: %s", roomID)

roomsMu.Lock()
room, exists := rooms[roomID]
roomsMu.Unlock()
RoomsMu.Lock()
room, exists := Rooms[roomID]
RoomsMu.Unlock()

if !exists {
log.Printf("Room not found: %s", roomID)
Expand Down Expand Up @@ -139,9 +139,9 @@ func handleJoin(conn *websocket.Conn, roomID string) {
func handleSignaling(conn *websocket.Conn, msg map[string]interface{}) {
roomID := msg["room"].(string)

roomsMu.Lock()
room, exists := rooms[roomID]
roomsMu.Unlock()
RoomsMu.Lock()
room, exists := Rooms[roomID]
RoomsMu.Unlock()

if !exists {
conn.WriteJSON(map[string]string{"type": "error", "message": "Room not found"})
Expand Down Expand Up @@ -169,10 +169,10 @@ func handleSignaling(conn *websocket.Conn, msg map[string]interface{}) {

// handleDisconnect cleans up the room if one of the peers disconnects.
func handleDisconnect(conn *websocket.Conn) {
roomsMu.Lock()
defer roomsMu.Unlock()
RoomsMu.Lock()
defer RoomsMu.Unlock()

for roomID, room := range rooms {
for roomID, room := range Rooms {
room.mu.Lock()

// Check if the disconnecting connection is the sender or receiver
Expand All @@ -186,17 +186,10 @@ func handleDisconnect(conn *websocket.Conn) {

// If both the sender and receiver are nil, remove the room
if room.Sender == nil && room.Receiver == nil {
delete(rooms, roomID)
delete(Rooms, roomID)
log.Printf("Room %s deleted", roomID)
}

room.mu.Unlock()
}
}

func cleanupRoom(roomID string) {
roomsMu.Lock()
delete(rooms, roomID)
roomsMu.Unlock()
log.Printf("Room %s cleaned up", roomID)
}
62 changes: 44 additions & 18 deletions cmd/transfer.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,60 @@
package cmd

import (
"fmt"
"log"
"os"

"github.com/skip2/go-qrcode"
"github.com/gorilla/websocket"

"github.com/abdealijaroli/jaro/cmd/stream"
"github.com/abdealijaroli/jaro/cmd/utils"
"github.com/abdealijaroli/jaro/cmd/webrtcconn"
"github.com/abdealijaroli/jaro/store"
)

func TransferFile(filePath string, store *store.PostgresStore) {
file, err := os.Open(filePath)
if err != nil {
log.Printf("Error opening file: %v\n", err)
return
}
defer file.Close()
shortURL, roomID := utils.GenerateShortCode(filePath)
utils.GenerateQRCode(shortURL)

shortURL := stream.InitiateTransfer(filePath, store)
pc := webrtcconn.CreatePeerConnection()
log.Printf("Peer connection created for %s\n", roomID)

qr, err := qrcode.New(shortURL, qrcode.Medium)
if err != nil {
log.Printf("Error generating QR code: %v\n", err)
return
}
offer, err := pc.CreateOffer(nil)
if err != nil {
log.Fatalf("Failed to create offer: %v", err)
}

fmt.Println("QR Code for your shareable file link: ")
fmt.Println(qr.ToSmallString(false))
err = pc.SetLocalDescription(offer)
if err != nil {
log.Fatalf("Failed to set local description: %v", err)
}

fmt.Printf("Your shareable file link is: %s\n", shortURL)
log.Printf("Local description set for %s\n", roomID)

// Establish WebSocket connection for signaling
conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080/ws", nil)
if err != nil {
log.Fatalf("Failed to connect to signaling server: %v", err)
}
defer conn.Close()

// Create the room on the signaling server
err = stream.CreateRoom(conn, roomID)
if err != nil {
log.Fatalf("Failed to create room: %v", err)
}

// Send the offer to the signaling server
conn.WriteJSON(map[string]string{"type": "offer", "room": roomID, "sdp": offer.SDP})

log.Printf("Signaling connection established for %s\n", roomID)

// Handle signaling messages
go webrtcconn.HandleSignaling(pc, roomID)



// stream.InitiateTransfer(conn, filePath, roomID, store)
}
// func ReceiveFile(roomID string) {
// stream.ReceiveFile(roomID)
// }
52 changes: 38 additions & 14 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,20 @@ package main
import (
"log"
"net/http"

"os"

"github.com/abdealijaroli/jaro/cmd"
"github.com/abdealijaroli/jaro/cmd/signaling"
"github.com/abdealijaroli/jaro/cmd/stream"
"github.com/abdealijaroli/jaro/store"
"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Allow all origins for this example
},
}

func main() {
storage, err := store.NewPostgresStore()
if err != nil {
Expand Down Expand Up @@ -48,21 +54,39 @@ func main() {
http.Redirect(w, r, originalURL, http.StatusFound)
})

http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
roomID := r.URL.Query().Get("room")
if roomID == "" {
http.Error(w, "Missing room ID", http.StatusBadRequest)
return
}

// Upgrade HTTP connection to WebSocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Error upgrading to WebSocket: %v", err)
return
}
defer conn.Close()

//Retrieve the file path associated with this room ID from your database
filePath, err := storage.GetOriginalURL(roomID)
if err != nil {
log.Printf("Error getting file path for room %s: %v", roomID, err)
conn.WriteMessage(websocket.TextMessage, []byte("Error: File not found"))
return
}

// Initiate the file transfer
stream.HandleTransferRequest(conn, filePath)
})

if len(os.Args) > 1 {
cmd.Execute()
}

go func() {
log.Println("HTTP server running on :8008")
if err := http.ListenAndServe(":8008", nil); err != nil {
log.Fatalf("HTTP server error: %v", err)
}
}()

// Start the WebSocket server on port 8080
http.HandleFunc("/ws", signaling.HandleSignaling)
log.Println("WebSocket server running on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("WebSocket server error: %v", err)
log.Println("Server starting on :8008")
if err := http.ListenAndServe(":8008", nil); err != nil {
log.Fatalf("Error starting server: %v", err)
}
}

0 comments on commit d2d6702

Please sign in to comment.