|
| 1 | +import collaboration from "../Models/collaboration.model.js" |
| 2 | +import Project from "../Models/project.model.js"; |
| 3 | +import crypto from "crypto"; |
| 4 | +import User from "../Models/user.model.js"; |
| 5 | +import transporter from "../config/nodemailer.js"; |
| 6 | +import localtunnel from "localtunnel"; |
| 7 | + |
| 8 | + |
| 9 | +export const invitationToCollaborate = async(req, res)=>{ |
| 10 | + const userid = req.user; |
| 11 | + const {project_id} = req.body; |
| 12 | + |
| 13 | + try { |
| 14 | + const user = await User.findById(userid); |
| 15 | + if(!user) return res.status(404).json({error: "User not found!"}); |
| 16 | + const projectToCollaborate = await Project.findOne({project_id: project_id}).populate("author", "personal_info.email"); |
| 17 | + if(!projectToCollaborate) return res.status(404).json({error: "Project not found!"}); |
| 18 | + |
| 19 | + const authorEmail = projectToCollaborate.author.personal_info.email; |
| 20 | + const token = crypto.randomBytes(16).toString('hex'); |
| 21 | + |
| 22 | + // const baseUrl = global.publicUrl || `http://localhost:${process.env.PORT || 8000}`; |
| 23 | + const baseUrl = process.env.COLLABORATION_PUBLIC_URL; |
| 24 | + |
| 25 | + const acceptLink = `${baseUrl}/api/collaborate/accept/${token}`; |
| 26 | + const rejectLink = `${baseUrl}/api/collaborate/reject/${token}`; |
| 27 | + console.log(acceptLink, rejectLink); |
| 28 | + const mailOptions = { |
| 29 | + from: process.env.EMAIL_USER, |
| 30 | + to: authorEmail, |
| 31 | + subject: "Collaboration Invitation", |
| 32 | + html: `<p>Hi,</p> |
| 33 | + <p>${user.personal_info.fullname} has requested to collaborate on your project "${projectToCollaborate.title}".</p> |
| 34 | + <p><a href="${acceptLink}">Accept Invitation</a> | <a href="${rejectLink}">Reject Invitation</a></p> |
| 35 | + <p>Thank you!</p>` |
| 36 | + |
| 37 | + }; |
| 38 | + await transporter.sendMail(mailOptions, (error, info)=>{ |
| 39 | + if(error){ |
| 40 | + console.error("Error sending email:", error); |
| 41 | + return res.status(500).json({error: "Failed to send invitation email"}); |
| 42 | + } |
| 43 | + console.log("Email sent:", info.response); |
| 44 | + }) |
| 45 | + const collaborationData = new collaboration({ |
| 46 | + user_id: userid, |
| 47 | + project_id: project_id, |
| 48 | + author_id: projectToCollaborate.author, |
| 49 | + status: "pending", |
| 50 | + token : token |
| 51 | + }) |
| 52 | + await collaborationData.save(); |
| 53 | + return res.status(200).json({message: "Invitation sent successfully!"}); |
| 54 | + |
| 55 | + } catch (error) { |
| 56 | + console.log(error); |
| 57 | + return res.status(500).json({error: "Internal Server Error"}); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
0 commit comments