using InstaVibe.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using InstaVibe.Services; public class NotesController : Controller { private readonly string connectionString = ConfigurationManager.ConnectionStrings["InstaVibe"].ConnectionString; // Show all uploaded notes + subjects & semesters dropdown public ActionResult AllNotes() { var notes = GetAllNotes(); ViewBag.Subjects = new List { "Mathematics", "Physics", "Chemistry", "Biology", "Botany", "Zoology", "English", "Urdu", "Economics", "Psychology", "Sociology", "History", "Computer Science", "Political Science", "Education", "Statistics" }; ViewBag.Semesters = new List { "1st Semester", "2nd Semester", "3rd Semester", "4th Semester", "5th Semester", "6th Semester", "7th Semester", "8th Semester" }; return View(notes); } public ActionResult SmartNotes() { return View(GetAllNotes()); } // ======== Upload new note============== [HttpPost] [ValidateAntiForgeryToken] public ActionResult UploadNote(HttpPostedFileBase file, string title, string courseCode, string subject, string semester) { if (Session["UserId"] == null) { TempData["Error"] = "You must be logged in to upload notes."; return RedirectToAction("Login", "Account"); } int uploadedBy = Convert.ToInt32(Session["UserId"]); if (file == null || file.ContentLength == 0) { TempData["Error"] = "Please select a file."; return RedirectToAction("AllNotes"); } var allowedExt = new[] { ".pdf", ".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx", ".txt" }; var ext = Path.GetExtension(file.FileName)?.ToLowerInvariant(); if (!allowedExt.Contains(ext)) { TempData["Error"] = "File type not allowed."; return RedirectToAction("AllNotes"); } if (file.ContentLength > 50 * 1024 * 1024) { TempData["Error"] = "File too large (max 50 MB)."; return RedirectToAction("AllNotes"); } string tempPath = Path.GetTempFileName(); try { file.SaveAs(tempPath); var scan = WindowsDefender.ScanFile(tempPath); if (scan.Result != AvScanResult.Clean) { System.IO.File.Delete(tempPath); TempData["Error"] = (scan.Result == AvScanResult.Infected) ? "Upload blocked: the file appears to contain a virus." : "Could not scan the file. Please try again."; return RedirectToAction("AllNotes"); } var uploadsDir = Server.MapPath("~/UploadedNotes"); Directory.CreateDirectory(uploadsDir); string safeFileName = $"{Guid.NewGuid():N}{ext}"; string finalPath = Path.Combine(uploadsDir, safeFileName); System.IO.File.Move(tempPath, finalPath); string virtualPath = Url.Content("~/UploadedNotes/" + safeFileName); using (var conn = new SqlConnection(connectionString)) using (var cmd = new SqlCommand(@" INSERT INTO Notes (Title, CourseCode, Subject, Semester, FilePath, UploadedBy, UploadedAt) VALUES (@Title, @CourseCode, @Subject, @Semester, @FilePath, @UploadedBy, GETDATE()); ", conn)) { cmd.Parameters.AddWithValue("@Title", title); cmd.Parameters.AddWithValue("@CourseCode", courseCode); cmd.Parameters.AddWithValue("@Subject", subject); cmd.Parameters.AddWithValue("@Semester", semester); cmd.Parameters.AddWithValue("@FilePath", virtualPath); cmd.Parameters.AddWithValue("@UploadedBy", uploadedBy); conn.Open(); cmd.ExecuteNonQuery(); } TempData["Success"] = "File uploaded successfully!"; return RedirectToAction("AllNotes"); } catch (Exception ex) { if (System.IO.File.Exists(tempPath)) System.IO.File.Delete(tempPath); TempData["Error"] = "Upload failed: " + ex.Message; return RedirectToAction("AllNotes"); } } // ========== Search notes ============ public JsonResult SearchNotes(string keyword, string subject, string semester) { var notes = new List(); using (var conn = new SqlConnection(connectionString)) { conn.Open(); string query = "SELECT * FROM Notes WHERE 1=1"; if (!string.IsNullOrEmpty(keyword)) query += " AND (Title LIKE @Keyword OR Subject LIKE @Keyword OR Semester LIKE @Keyword OR CourseCode LIKE @Keyword)"; if (!string.IsNullOrEmpty(subject) && subject != "All") query += " AND Subject = @Subject"; if (!string.IsNullOrEmpty(semester) && semester != "All") query += " AND Semester = @Semester"; using (var cmd = new SqlCommand(query, conn)) { if (!string.IsNullOrEmpty(keyword)) cmd.Parameters.AddWithValue("@Keyword", "%" + keyword + "%"); if (!string.IsNullOrEmpty(subject) && subject != "All") cmd.Parameters.AddWithValue("@Subject", subject); if (!string.IsNullOrEmpty(semester) && semester != "All") cmd.Parameters.AddWithValue("@Semester", semester); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { notes.Add(new NotesModel { Id = Convert.ToInt32(reader["Id"]), Title = reader["Title"].ToString(), FilePath = reader["FilePath"].ToString(), Subject = reader["Subject"].ToString(), Semester = reader["Semester"].ToString(), CourseCode = reader["CourseCode"].ToString(), UploadedBy = Convert.ToInt32(reader["UploadedBy"]), UploadedAt = Convert.ToDateTime(reader["UploadedAt"]) }); } } } } return Json(notes, JsonRequestBehavior.AllowGet); } // ========== Helper to get all notes ============ private List GetAllNotes() { var notes = new List(); using (var conn = new SqlConnection(connectionString)) { conn.Open(); string query = "SELECT * FROM Notes ORDER BY UploadedAt DESC"; using (var cmd = new SqlCommand(query, conn)) using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { notes.Add(new NotesModel { Id = Convert.ToInt32(reader["Id"]), Title = reader["Title"].ToString(), FilePath = reader["FilePath"].ToString(), Subject = reader["Subject"].ToString(), Semester = reader["Semester"].ToString(), CourseCode = reader["CourseCode"].ToString(), UploadedBy = Convert.ToInt32(reader["UploadedBy"]), UploadedAt = Convert.ToDateTime(reader["UploadedAt"]) }); } } } return notes; } public ActionResult Logout() { if (Session["UserId"] != null) { int userId = Convert.ToInt32(Session["UserId"]); using (var con = new SqlConnection(connectionString)) { con.Open(); string query = "UPDATE Users SET is_online = 0 WHERE user_id = @userId"; using (var cmd = new SqlCommand(query, con)) { cmd.Parameters.AddWithValue("@userId", userId); cmd.ExecuteNonQuery(); } } } Session.Clear(); Session.Abandon(); return RedirectToAction("Login", "Account"); } }