using System.Collections.Generic;
using System.IO;
using System.Linq;
using _0_Framework.Application;
using AccountManagement.Application.Contracts.Media;
using AccountManagement.Domain.MediaAgg;
using Microsoft.AspNetCore.Http;
namespace AccountManagement.Application
{
public class MediaApplication : IMediaApplication
{
private const string _basePath = "Medias";
private readonly IMediaRepository _mediaRepository;
public MediaApplication(IMediaRepository mediaRepository)
{
_mediaRepository = mediaRepository;
}
///
/// دریافت فایل و نوشتن آن در مسیر داده شده، و ثبت مدیا
///
/// فایل
/// برچسب فایل که در نام فایل ظاهر می شود
/// مسیر فایل
/// حداکثر حجم فایل به مگابایت
/// [.png,.jpg,.jpeg] پسوند های مجاز مثلا
///
///
public OperationResult UploadFile(IFormFile file, string fileLabel, string relativePath, int maximumFileLength,
List allowedExtensions, string category)
{
return _mediaRepository.UploadFile(file, fileLabel, relativePath, maximumFileLength, allowedExtensions, category);
}
///
/// حذف فایل
///
public OperationResult DeleteFile(long mediaId)
{
OperationResult op = new();
var media = _mediaRepository.Get(mediaId);
if (media == null)
return op.Failed("رکورد مورد نظر یافت نشد");
try
{
if (File.Exists(media.Path))
File.Delete(media.Path);
else
return op.Failed("فایل یافت نشد");
}
catch
{
return op.Failed("خطایی در حذف فایل رخ داده است");
}
_mediaRepository.Remove(media.id);
_mediaRepository.SaveChanges();
return op.Succcedded();
}
///
/// جابجا کردن فایل
///
public OperationResult MoveFile(long mediaId, string newRelativePath)
{
OperationResult op = new();
var media = _mediaRepository.Get(mediaId);
var oldPath = media.Path;
var path = Path.Combine(_basePath, newRelativePath);
Directory.CreateDirectory(path);
string filepath = Path.Combine(path, Path.GetFileName(oldPath));
try
{
File.Move(oldPath, filepath);
}
catch
{
return op.Failed("در جابجایی فایل خطایی رخ داده است");
}
media.Edit(filepath, media.Type, media.Category);
_mediaRepository.SaveChanges();
return op.Succcedded();
}
public MediaViewModel Get(long id)
{
var media = _mediaRepository.Get(id);
if (media == null)
return new();
return new MediaViewModel()
{
Category = media.Category,
Path = media.Path,
Id = media.id,
Type = media.Type
};
}
public List GetRange(IEnumerable ids)
{
var medias = _mediaRepository.GetRange(ids);
return medias.Select(x => new MediaViewModel()
{
Category = x.Category,
Path = x.Path,
Id = x.id,
Type = x.Type,
}).ToList();
}
}
}