using Microsoft.AspNet.Mvc;
using HeuristicLab.Clients.Hive.WebJobManager.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HeuristicLab.Clients.Hive.WebJobManager.ViewModels;
using System.ServiceModel.Security;
using Microsoft.AspNet.Http;
using System.IO;
using Microsoft.Net.Http.Headers;
using Microsoft.AspNet.Hosting;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Optimization;
using System.Threading;
namespace HeuristicLab.Clients.Hive.WebJobManager.Controllers
{
///
/// Controller for everything Job related (includes uploads and uploader)
///
public class JobController : Controller
{
private WebLoginService weblog;
private HiveServiceLocatorWeb serviceLocator;
private HiveServiceClient serviceClient;
private HiveClientWeb clientWeb;
private Guid userId;
private JobViewModel vm;
private IHostingEnvironment _environment;
public JobController(IHostingEnvironment env)
{
weblog = WebLoginService.Instance;
vm = new JobViewModel();
_environment = env;
}
///
/// initializes the connection for the right user. Not constructor because httpcontext is needed.
///
private bool init()
{
var u = HttpContext.Session.GetString("UserId");
if (u == null || u == "" || Guid.Parse(u) == Guid.Empty)
{
return false;
}
else
{
userId = Guid.Parse(u);
serviceLocator = weblog.getServiceLocator(userId);
serviceClient = serviceLocator.getHiveServiceClient();
clientWeb = weblog.getClientWeb(userId);
return serviceLocator.CheckLogin();
}
}
#region Jobs
///
/// initial job page, shows all jobs
///
///
public IActionResult Index()
{
if (init())
{
clientWeb.Refresh();
vm.userJobs = clientWeb.Jobs.ToList();
ViewBag.SessionId = HttpContext.Session.GetString("UserId");
ViewBag.Title = "Jobs";
return View(vm);
}
else
{
return RedirectToAction("Index", "Home");
}
}
///
/// Initial page and a selected job
///
/// Job id selected
///
public IActionResult Selected(Guid id)
{
if (init())
{
clientWeb.Refresh();
vm.userJobs = clientWeb.Jobs.ToList();
foreach (var j in vm.userJobs)
{
if (j.Id == id)
{
vm.selectedJob = j;
}
}
//vm.selectedJob.RefreshAutomatically = true;
clientWeb.LoadJob(vm.selectedJob);
weblog.getFileOpener(userId).NewModel();
weblog.getFileOpener(userId).Job = vm.selectedJob;
ViewBag.Title = vm.selectedJob.Job.Name + " - Jobs";
ViewBag.SessionId = HttpContext.Session.GetString("UserId");
return View("Index", vm);
}
else
{
return RedirectToAction("Index", "Home");
}
}
///
/// Deletes a job
///
/// Job id
///
public IActionResult Delete(Guid id)
{
if (init())
{
vm.message = serviceClient.GetJob(id).Name + " deleted";
serviceClient.DeleteJob(id);
clientWeb.Refresh();
vm.userJobs = clientWeb.Jobs.ToList();
ViewBag.Title = vm.message + " - Jobs";
return View("Index", vm);
}
else
{
return RedirectToAction("Index", "Home");
}
}
#endregion
#region Uploads
///
/// Shows the uploaded directories
///
///
public IActionResult Uploads()
{
if (init())
{
UploadedJobViewModel upper = new UploadedJobViewModel();
fillUploadsPaths(upper, -1);
ViewBag.Name = serviceClient.ClientCredentials.UserName.UserName;
ViewBag.Title = "Uploads";
return View("Uploads", upper);
}
else
{
return RedirectToAction("Index", "Home");
}
}
///
/// //Shows content of selected dir
///
/// Array index selected directory
///
public IActionResult UploadDir(int index)
{
if (init())
{
UploadedJobViewModel upper = new UploadedJobViewModel();
fillUploadsPaths(upper, index);
if (index != -1)
ViewBag.Title = upper.DisplayDatePaths[index] + " - Uploads";
else
ViewBag.Title = "Add files - Uploads";
return View("Uploads", upper);
}
else
{
return RedirectToAction("Index", "Home");
}
}
///
/// Loads all the paths from the selected uploads folder
///
/// Viewmodel to save every directory path
/// Index selected directory
private void fillUploadsPaths(UploadedJobViewModel vm, int index)
{
var tempdex = index; //Fix when maps gets deleted
var start = Path.Combine(_environment.WebRootPath, "uploads", serviceClient.ClientCredentials.UserName.UserName);
var dirs = Directory.GetDirectories(start);
foreach (string dir in dirs)
{
if (Directory.GetFiles(dir).Length == 0 && Directory.GetDirectories(dir).Length == 0)
{
Directory.Delete(dir, false);
tempdex = -1;
}
else
{
vm.FullDatePaths.Add(dir);
var temp = dir.Split('\\');
vm.DisplayDatePaths.Add(temp[temp.Length - 1]);
}
}
if (tempdex != -1)
{
vm.SelectedIndex = tempdex;
dirs = Directory.GetFiles(vm.FullDatePaths[tempdex]);
foreach (string dir in dirs)
{
vm.FullFilesPaths.Add(dir);
var temp = dir.Split('\\');
vm.DisplayFilesPaths.Add(temp[temp.Length - 1]);
}
}
}
///
/// Deletes a file
///
/// Index directory
/// Index file to delete
///
public IActionResult DeleteFile(int index, int filedex)
{
if (init())
{
UploadedJobViewModel upper = new UploadedJobViewModel();
fillUploadsPaths(upper, index);
System.IO.File.Delete(upper.FullFilesPaths[filedex]);
var message = upper.DisplayFilesPaths[filedex] + " has been deleted";
upper = new UploadedJobViewModel();
fillUploadsPaths(upper, index);
upper.message = message;
ViewBag.Title = "File deleted - Uploads";
return View("Uploads", upper);
}
else
{
return RedirectToAction("Index", "Home");
}
}
///
/// Opens a selected file
///
/// Index directory
/// Index selected file
///
public IActionResult OpenFile(int index, int filedex)
{
if (init())
{
UploadedJobViewModel upper = new UploadedJobViewModel();
fillUploadsPaths(upper, index);
var serve = weblog.getFileOpener(userId);
serve.NewModel();
serve.env = _environment;
var ioptimizer = ContentManager.Load(upper.FullFilesPaths[filedex]);
serve.vm.SelectedTask = new OptimizerHiveTask((IOptimizer)ioptimizer);
if (serve.vm.SelectedTask.ItemTask.Item is IAlgorithm)
{
serve.vm.SelectedAlgorithm = (IAlgorithm)serve.vm.SelectedTask.ItemTask.Item;
}
else if (serve.vm.SelectedTask.ItemTask.Item is BatchRun)
{
serve.vm.SelectedBatchRun = (BatchRun)serve.vm.SelectedTask.ItemTask.Item;
}
else if (serve.vm.SelectedTask.ItemTask.Item is Experiment)
{
serve.vm.SelectedExperiment = (Experiment)serve.vm.SelectedTask.ItemTask.Item;
}
serve.setTasks();
ViewBag.JobsCount = serve.Job.Job.JobCount;
ViewBag.Title = serve.vm.SelectedTask.ItemTask.Name + " - Uploads";
ViewBag.SessionId = HttpContext.Session.GetString("UserId");
return View("OpenFile", serve.vm);
}
else
{
return RedirectToAction("Index", "Home");
}
}
///
/// Adds current opened file to hive, uses FileOpeningService singleton
///
///
public IActionResult AddToHive()
{
if (init())
{
var job = weblog.getFileOpener(userId).AddCurrentModelToHive();
while (job.Progress.ProgressValue != 1)
{ }
Thread.Sleep(1000);
job.Progress.Status = "Upload finished";
Thread.Sleep(2000);
return RedirectToAction("Index", "Job");
}
else
{
return RedirectToAction("Index", "Home");
}
}
[HttpPost]
public IActionResult saveToFile(string fname)
{
if (init())
{
weblog.getFileOpener(userId).SaveToFile(fname);
return RedirectToAction("Uploads", "Job");
}
else
{
return RedirectToAction("Index", "Home");
}
}
public FileResult DownloadFile(int index, int filedex)
{
if (init())
{
UploadedJobViewModel upper = new UploadedJobViewModel();
fillUploadsPaths(upper, index);
System.IO.FileInfo Dfile = new System.IO.FileInfo(upper.FullFilesPaths[filedex]);
var fileName = Dfile.Name;
byte[] fileBytes = System.IO.File.ReadAllBytes(upper.FullFilesPaths[filedex]);
return File(fileBytes, "application/x-msdownload", fileName);
}
else
{
return null;
}
}
#endregion
#region Uploader
///
/// Uploads file onto server directory
///
/// Files
/// Directory path for server
///
[HttpPost]
public async Task Uploader(ICollection files, string directory)
{
if (init())
{
UploadedJobViewModel upper = new UploadedJobViewModel();
var uploads = Path.Combine(_environment.WebRootPath, "uploads", serviceClient.ClientCredentials.UserName.UserName,
directory);
Directory.CreateDirectory(uploads);
foreach (var file in files)
{
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
await file.SaveAsAsync(Path.Combine(uploads, fileName));
// var ioptimizer = ContentManager.Load(Path.Combine(uploads, fileName));
//OptimizerHiveTask task = new OptimizerHiveTask((IOptimizer)ioptimizer);
//upper.Tasks.Add(task);
}
}
ViewBag.Title = "Upload complete - Uploads";
return RedirectToAction("Uploads", "Job");
}
else
{
return RedirectToAction("Index", "Home");
}
}
#endregion
}
}