ReferenceError: musicians is not defined
    at C:\Users\Ilya\Downloads\GOVNOZHOPA1111\app.js:210:21

app.js:

const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');


const connection = mysql.createConnection({
  host: 'localhost',
  user: 'music', // замените на свой логин
  password: 'password', // замените на свой пароль
  database: 'music' // замените на свою базу данных
});

connection.connect((err) => {
  if (err) {
    console.error('Ошибка подключения к базе данных: ', err);
  } else {
    console.log('Подключение к базе данных успешно');
  }
});



app.set("view engine", "ejs");
app.use(express.static("public"));

app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
  secret: "mysecretkey",
  resave: false,
  saveUninitialized: false
}));

const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));

connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
    if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];

// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}

function getLastNUploadedTracks(N, callback) {
  connection.query("SELECT * FROM tracks ORDER BY uploaded_at DESC LIMIT ?", [N], (err, result) => {
    if (err) {
      console.error("Ошибка при получении последних загруженных треков: ", err);
      return callback(err);
    } else {
      return callback(null, result);
    }
  });
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
    connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
        if (err) {
            console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
            return typeof callback === 'function' && callback(err);
        } else {
            return typeof callback === 'function' && callback(null, result);
        }
    });
}

function getMusicians(callback) {
  connection.query("SELECT * FROM users", (err, result) => {
    if (err) {
      console.error("Ошибка при получении списка музыкантов: ", err);
      return callback(err);
    } else {
      return callback(null, result);
    }
  });
}

// Функция для получения музыканта по id
function getMusicianById(id, callback) {
  connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
    if (err) {
      console.error("Ошибка при получении музыканта с id ${id}: ", err);
      return typeof callback === 'function' && callback(err);
    } else {
      return typeof callback === 'function' && callback(null, result[0]);
    }
  });
}

function requireLogin(req, res, next) {
  if (req.session.musicianId) {
    next();
  } else {
    res.redirect("/login");
  }
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];

// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}

// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});

// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);

// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;

if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}

// Сортировка по score (убывающая)
return scoreB - scoreA;
});

// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}

app.use((req, res, next) => {
  if (req.session.musicianId) {
    getMusicianById(req.session.musicianId, (err, musician) => {
      if (err) {
        console.error("Ошибка при получении current user: ", err);
        res.locals.userLoggedIn = false;
      } else {
        res.locals.musician = musician;
        res.locals.userLoggedIn = true;
        res.locals.username = musician.name;
      }
      next();
    });
  } else {
    res.locals.userLoggedIn = false;
    next();
  }
});

app.get("/", (req, res) => {
 getLastNUploadedTracks(12, (err, lastUploadedTracks) => {
    if (err) {
      console.error("Ошибка при получении последних загруженных треков: ", err);
      res.status(500).send("Ошибка получения данных");
    } else {
res.render("index", { tracks: lastUploadedTracks, query:'',city:'',role:'',genre:''});
}
});
});

app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;

connection.query(
"SELECT DISTINCT city FROM users WHERE city LIKE ?",
[searchString + '%'],
(error, results, fields) => {
if (error) {
console.error("Ошибка выполнения запроса: ", error);
res.status(500).send("Ошибка выполнения запроса");
} else {
const cities = results.map(row => row.city);
res.json(cities);
}
}
);
});

app.get("/register", (req, res) => {
  if (req.session.musicianId) {
    const musician = getMusicianById(req.session.musicianId);
    res.redirect("/profile/" + musicianId);
  } else {
	  
	  
	  
    res.render("register", { citiesAndRegions, city:'', query:'',role:'' });
  }
});

app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {

// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login,
};

if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}

connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});

app.get("/profile/:id", (req, res) => {
    getMusicianById(parseInt(req.params.id), (err, musician) => {
        if (err) {
            console.error("Ошибка при получении музыканта: ", err);
            res.status(500).send("Ошибка при получении данных");
        } else {
            if (musician) {
                getMusicianTracks(musician.id, (err, tracks) => {
                    if(err) {
                        console.error("Ошибка при получении треков для профиля: ", err);
                        res.status(500).send("Ошибка при получении данных");
                    } else {
                        res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''});
                    }
                });
            } else {
                res.status(404).send("Musician not found");
            }
        }
    });
});

app.get("/login", (req, res) => {
  res.render("login");
});

app.post("/login", (req, res) => {
  connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
      if (err) {
        console.error("Ошибка при входе: ", err);
        res.status(500).send("Ошибка при входе");
      } else {
        if (result.length > 0) {
          req.session.musicianId = result[0].id;
          res.redirect("/profile/" + result[0].id);
        } else {
          res.render("login", { error: "Invalid login or password" });
        }
      }
    }
);
});

app.get("/logout", (req, res) => {
  req.session.destroy();
  res.redirect("/");
});

app.get('/search', (req, res) => {
  let query = req.query.query || '';
  const role = req.query.role || '';
  const city = req.query.city || '';
  const genre = req.query.genre || '';

  if (query || role || city || genre) {
    search(query, role, city, genre, (err, musicians) => {
      if (err) {
        res.status(500).send("Ошибка при выполнении поиска");
      } else {
        app.locals.JSON = JSON;
        res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
      }
    });
  } else {
    // Use the getMusicians function instead of reading from musicians.json
    getMusicians((err, musiciansList) => {
      if (err) {
        res.status(500).send("Ошибка при получении списка музыкантов");
      } else {
        const musicians = musiciansList.map(musician => {
          return {
            name: musician.name,
            genre: musician.genre,
            originalName: musician.name,
            profileLink: `/profile/${musician.id}`,
            thumbnail: musician.thumbnail,
            soundcloud: musician.soundcloud,
            role: musician.role,
            city: musician.city
          };
        });

        app.locals.JSON = JSON;
        res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
      }
    });
  }
});


app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
}
});
});





app.post("/profile/:id/edit", requireLogin, (req, res) => {
const musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});

//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, async (req, res) => {
    const musicianId = req.session.musicianId;
    if (!req.files) {
        res.status(400).send("No files were uploaded.");
        return;
    }
    const trackFile = req.files.track;
    if (!trackFile) {
        res.status(400).send("No track file was uploaded.");
        return;
    }
	
	if (trackFile && !trackFile.name.endsWith(".mp3")) {
res.status(400).send("Only .mp3 files can be uploaded.");
return;
}

// Set a maximum file size of 10MB for uploaded files
const maxSizeInBytes = 11000000; // 11MB
if (trackFile && trackFile.size > maxSizeInBytes) {
res.status(400).send("File size exceeds 10MB limit.");
return;
}
    const trackFilename = "track_" + musicianId + "" + trackFile.name;
	const tmpPath = './public/tracks/tmp_' + trackFilename;
    trackFile.mv("./public/tracks/" + trackFilename);

    const title = req.body.title;
    const album_title = req.body.albumTitle;

    const track = {
        musician_id: musicianId,
        title,
        album_title,
        filename: trackFilename,
    };

    if (req.files.image) {
        const imageFile = req.files.image;
        const imageFilename = "image" + musicianId + "_" + imageFile.name;
        imageFile.mv("./public/img/" + imageFilename);
        track.image_filename = imageFilename;
    }

    connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
        if (err) {
            console.error("Ошибка при добавлении трека: ", err);
            res.status(500).send("Ошибка при добавлении трека");
        } else {
            res.redirect("/profile/" + musicianId);
        }
    });
});

function isValidSoundCloudUrl(url) {
  return url.startsWith('https://soundcloud.com/');
}

app.listen(3000, () => {
  console.log("Server started on port 3000");
});

index.ejs:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="/css/main.css" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
	<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
    <title>Home</title>
  </head>
  <body>
    <header>
      <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="/">My Musician Site</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
              <a class="nav-link" href="/">Home</a>
            </li>
            <% if (userLoggedIn) { %>
            <li class="nav-item">
              <a class="nav-link" href="/profile/<%= musician.id %>">Hello, <%= username %></a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="/logout">Logout</a>
            </li>
            <% } else { %>
            <li class="nav-item">
              <a class="nav-link" href="/register">Register</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="/login">Login</a>
            </li>
            <% } %>
          </ul>
        </div>
      </nav>
    </header>
    <main class="container mt-5">
      <div class="row">
        <div class="col-md-8">
        <!-- добавляет форму с поиском музыкантом -->
       <!--  <form method="get" action="/search">
          <div class="form-group">
            <label for="query">Search by name or genre:</label>
            <div class="input-group">
              <input id="query" name="query" type="text" class="form-control" value="<%= query %>">
              <div class="input-group-append">
                <button type="submit" class="btn btn-primary">Search</button>
              </div>
            </div>
          </div> -->
          <div class="form-row">
            <div class="form-group col-md-4">
              <label for="role">Search by role:</label>
              <select id="role" name="role" class="form-control">
                <option value="">
                  All
                </option>
                <option value="Band">
                  Band
                </option>
                <option value="Artist">
                  Artist
                </option>
              </select>
            </div>
            <div class="form-group col-md-4">
              <label for="genre">Search by genre:</label>
              <select id="genre" name="genre" class="form-control">
                <option value="">
                  All
                </option>
                <option value="Rock">
                  Rock
                </option>
                <option value="Pop">
                  Pop
                </option>
              </select>
            </div>
            <div class="form-group col-md-4">
              <label for="city">Search by location:</label>
              <input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value="">
            </div>
          </div>
        </form>
        <%if (musicians.length > 0) { %>
        <h2 class="mt-5">Results:</h2>
        <ul class="list-unstyled">
        <% musicians.forEach(musician => { %>
          <li class="media my-4">
            <a href="/profile/<%= musician.id %>">
              <img src="/img/<%= musician.thumbnail || 'avatar.jpg'%>" class="mr-3" alt="Musician profile picture">
            </a>
            <div class="media-body">
              <h5 class="mt-0 mb-1"><a href="/profile/<%= musician.id %>"><%= musician.name %></h5></a>
              <p><strong>Role:</strong> <%= musician.role %></p>
              <p><strong>Genre:</strong> <%= musician.genre %></p>
              <p><strong>Location:</strong> <%= musician.city %></p>
              <p><strong>Available for gigs:</strong> <%= musician.availableForGigs ? 'Yes' : 'No' %></p>
            </div>
          </li>
        <% }) %>
        </ul>
        <% } else { %>
        <h2 class="mt-5">No results found</h2>
        <% } %>
        </div>
        <div class="col-md-4">
          <h2>About this site</h2>
          <p>Welcome to My Musician Site! This is a platform for musicians to connect with each other and find potential bandmates or collaborators. You can search for musicians by name, location, role, and genre. If you're a musician yourself, make sure to create a profile so others can find you too!</p>
          <p>If you have any questions or feedback, please don't hesitate to contact us at <a href="mailto:contact@mymusiciansite.com">contact@mymusiciansite.com</a>.</p>
        </div>
      </div>
    </main>
    <script src="/jquery/jquery.min.js"></script>
    <script src="/jquery-ui/jquery-ui.min.js"></script>
    
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1r RibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
	<script>
	$("#city").autocomplete({
    source: '/autocomplete/cities',
    minLength: 1,
  });

  const queryInput = document.querySelector("#query");
  const roleInput = document.querySelector("#role");
  const cityInput = document.querySelector("#city");

  queryInput.value = "<%= query %>";
  roleInput.value = "<%= role %>";
  cityInput.value = cityInput.getAttribute('data-value');

  const query = queryInput.value;
  const role = roleInput.value;
  const city = cityInput.value;
	</script>
  </body>
</html>