protected function fromMultipleSongs(Collection $songs)
{
if ($songs->count() === 1) {
return $this->fromSong($songs->first());
}
if (!class_exists('ZipArchive')) {
throw new Exception('Downloading multiple files requires ZipArchive module.');
}
// Start gathering the songs into a zip file.
$zip = new ZipArchive();
// We use system's temp dir instead of storage_path() here, so that the generated files
// can be cleaned up automatically after server reboot.
$filename = rtrim(sys_get_temp_dir(), '/') . '/koel-download-' . uniqid() . '.zip';
if ($zip->open($filename, ZipArchive::CREATE) !== true) {
throw new Exception('Cannot create zip file.');
}
$localNames = [];
$songs->each(function ($s) use($zip, &$localNames) {
try {
$path = $this->fromSong($s);
// We add all files into the zip archive as a flat structure.
// As a result, there can be duplicate file names.
// The following several lines are to make sure each file name is unique.
$name = basename($path);
if (array_key_exists($name, $localNames)) {
++$localNames[$name];
$parts = explode('.', $name);
$ext = $parts[count($parts) - 1];
$parts[count($parts) - 1] = $localNames[$name] . ".{$ext}";
$name = implode('.', $parts);
} else {
$localNames[$name] = 1;
}
$zip->addFile($path, $name);
} catch (Exception $e) {
Log::error($e);
}
});
$zip->close();
return $filename;
}