using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Dpz.Core.EnumLibrary;
using Dpz.Core.Public.ViewModel.V4;
using Dpz.Core.Service.ObjectStorage.Services;
using Dpz.Core.Service.V4.Services;
using Dpz.Core.Web.Library;
using Dpz.Core.Web.Library.Filter;
using Dpz.Core.Web.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
namespace Dpz.Core.Web.Controllers
{
public class AudioController : Controller
{
private readonly IAudioService _audioService;
private readonly IObjectStorageOperation _objectStorageService;
public AudioController(IAudioService audioService,
IObjectStorageOperation objectStorageService)
{
_audioService = audioService;
_objectStorageService = objectStorageService;
}
[CheckAuthorize]
public async Task<IActionResult> Upload(IFormFile? record)
{
if (record == null || record.Length == 0)
{
return Json(new ResultInfo("请上传音乐!"));
}
var audioExtensions = new[] { ".mp3", ".flac", ".wav" };
if (!audioExtensions.Contains(Path.GetExtension(record.FileName).ToLower()))
{
return Json(new ResultInfo($"目前只支持{string.Join("、", audioExtensions)}格式的音频!"));
}
var stream = record.OpenReadStream();
var result = await _objectStorageService.UploadAsync(stream,
new[] { "audio", DateTime.Now.ToString("yyyyMMdd") },
$"{ObjectId.GenerateNewId()}.wav");
var viewModel = new VmAudio
{
AccessUrl = result.AccessUrl,
Duration = new TimeSpan(),
Size = stream.Length,
Uploader = User.GetIdentity(),
UploadTime = DateTime.Now
};
var added = await _audioService.AddAsync(viewModel);
return Json(new ResultInfo(added));
}
[CheckAuthorize, HttpPost]
public async Task<IActionResult> Delete(string id)
{
var audio = await _audioService.FindAsync(id);
var user = User.GetIdentity();
if (audio == null || audio.Uploader.Id != user.Id)
{
return Json(new ResultInfo("未知音频或没有权限删除!"));
}
await _audioService.DeleteAsync(id);
return Json(new ResultInfo(true));
}
// [ResponseCache(Duration = 60 * 60 * 24 * 30, VaryByQueryKeys = new[] { "id" })]
// public async Task<IActionResult> Result(string id = "")
// {
// if (string.IsNullOrEmpty(id)) return NotFound();
// var result = await _audioService.GetAudioAsync(id);
// if (result == null) return NotFound();
// return File(result.Value.stream, "audio/mpeg", result.Value.fileName, true);
// }
[CheckAuthorize]
public async Task<IActionResult> MyAudio(int pageIndex, int pageSize = 20)
{
var user = User.GetIdentity();
var source = await _audioService.GetPagesAsync(pageIndex, pageSize,user);
return Json(source);
}
[CheckAuthorize(Permissions = Permissions.System)]
public async Task<IActionResult> AudioPager(int pageIndex, int pageSize)
{
var source = await _audioService.GetPagesAsync(pageIndex, pageSize);
return Json(source);
}
}
}