Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Controllers/JobController.cs @ 13740

Last change on this file since 13740 was 13740, checked in by jlodewyc, 8 years ago

#2582 Job Manager done. Start user management

File size: 14.2 KB
Line 
1using Microsoft.AspNet.Mvc;
2using HeuristicLab.Clients.Hive.WebJobManager.Services;
3using System;
4using System.Collections.Generic;
5using System.Linq;
6using System.Threading.Tasks;
7using HeuristicLab.Clients.Hive.WebJobManager.ViewModels;
8using System.ServiceModel.Security;
9using Microsoft.AspNet.Http;
10using System.IO;
11using Microsoft.Net.Http.Headers;
12using Microsoft.AspNet.Hosting;
13using HeuristicLab.Common;
14using HeuristicLab.Core;
15using HeuristicLab.Optimization;
16using System.Threading;
17
18namespace HeuristicLab.Clients.Hive.WebJobManager.Controllers
19{
20    /// <summary>
21    /// Controller for everything Job related (includes uploads and uploader)
22    /// </summary>
23    public class JobController : Controller
24    {
25        private WebLoginService weblog;
26
27        private HiveServiceLocatorWeb serviceLocator;
28        private HiveServiceClient serviceClient;
29        private HiveClientWeb clientWeb;
30        private Guid userId;
31
32        private JobViewModel vm;
33        private IHostingEnvironment _environment;
34
35
36
37        public JobController(IHostingEnvironment env)
38        {
39            weblog = WebLoginService.Instance;
40            vm = new JobViewModel();
41            _environment = env;
42        }
43
44        /// <summary>
45        /// initializes the connection for the right user. Not constructor because httpcontext is needed.
46        /// </summary>
47        private void init()
48        {
49            var u = HttpContext.Session.GetString("UserId");
50            if (u == null || u == "" || Guid.Parse(u) == Guid.Empty)
51            {
52                userId = Guid.Empty;
53                serviceLocator = new HiveServiceLocatorWeb();
54                serviceClient = serviceLocator.getHiveServiceClient();
55                clientWeb = new HiveClientWeb(serviceLocator, userId);
56            }
57            else
58            {
59                userId = Guid.Parse(u);
60                serviceLocator = weblog.getServiceLocator(userId);
61                serviceClient = serviceLocator.getHiveServiceClient();
62                clientWeb = weblog.getClientWeb(userId);
63            }
64        }
65
66        #region Jobs
67        /// <summary>
68        /// initial job page, shows all jobs
69        /// </summary>
70        /// <returns></returns>
71        public IActionResult Index()
72        {
73            try
74            {
75                init();
76                clientWeb.Refresh();
77                vm.userJobs = clientWeb.Jobs.ToList();
78            }
79            catch (Exception e)
80            {
81                if (e is MessageSecurityException || e is InvalidOperationException)
82                {
83                    return RedirectToAction("Index", "Home");
84                }
85                throw;
86            }
87            ViewBag.SessionId = HttpContext.Session.GetString("UserId");
88            ViewBag.Title = "Jobs";
89            return View(vm);
90        }
91        /// <summary>
92        /// Initial page and a selected job
93        /// </summary>
94        /// <param name="id">Job id selected</param>
95        /// <returns></returns>
96        public IActionResult Selected(Guid id)
97        {
98            init();
99            if (serviceLocator.CheckLogin())
100            {
101                clientWeb.Refresh();
102
103                vm.userJobs = clientWeb.Jobs.ToList();
104                foreach (var j in vm.userJobs)
105                {
106                    if (j.Id == id)
107                    {
108                        vm.selectedJob = j;
109                    }
110                }
111                //vm.selectedJob.RefreshAutomatically = true;
112                clientWeb.LoadJob(vm.selectedJob);
113                weblog.getFileOpener(userId).NewModel();
114                weblog.getFileOpener(userId).Job = vm.selectedJob;
115                ViewBag.Title = vm.selectedJob.Job.Name + " - Jobs";
116                ViewBag.SessionId = HttpContext.Session.GetString("UserId");
117                return View("Index", vm);
118            }
119            else
120            {
121                return RedirectToAction("Index", "Home");
122            }
123        }
124        /// <summary>
125        /// Deletes a job
126        /// </summary>
127        /// <param name="id">Job id</param>
128        /// <returns></returns>
129        public IActionResult Delete(Guid id)
130        {
131            init();
132            if (serviceLocator.CheckLogin())
133            {
134
135                vm.message = serviceClient.GetJob(id).Name + " deleted";
136                serviceClient.DeleteJob(id);
137                clientWeb.Refresh();
138
139                vm.userJobs = clientWeb.Jobs.ToList();
140                ViewBag.Title = vm.message + " - Jobs";
141                return View("Index", vm);
142            }
143            else
144            {
145                return RedirectToAction("Index", "Home");
146            }
147        }
148        #endregion
149
150        #region Uploads
151        /// <summary>
152        /// Shows the uploaded directories
153        /// </summary>
154        /// <returns></returns>
155        public IActionResult Uploads()
156        {
157            init();
158            if (serviceLocator.CheckLogin())
159            {
160                UploadedJobViewModel upper = new UploadedJobViewModel();
161                fillUploadsPaths(upper, -1);
162                ViewBag.Name = serviceClient.ClientCredentials.UserName.UserName;
163                ViewBag.Title = "Uploads";
164                return View("Uploads", upper);
165            }
166            else
167            {
168                return RedirectToAction("Index", "Home");
169            }
170        }
171        /// <summary>
172        /// //Shows content of selected dir
173        /// </summary>
174        /// <param name="index">Array index selected directory</param>
175        /// <returns></returns>
176        public IActionResult UploadDir(int index)
177        {
178            init();
179            if (serviceLocator.CheckLogin())
180            {
181                UploadedJobViewModel upper = new UploadedJobViewModel();
182                fillUploadsPaths(upper, index);
183                if(index != -1)
184                    ViewBag.Title = upper.DisplayDatePaths[index] + " - Uploads";
185                else
186                    ViewBag.Title = "Add files - Uploads";
187                return View("Uploads", upper);
188            }
189            else
190            {
191                return RedirectToAction("Index", "Home");
192            }
193        }
194        /// <summary>
195        /// Loads all the paths from the selected uploads folder
196        /// </summary>
197        /// <param name="vm">Viewmodel to save every directory path</param>
198        /// <param name="index">Index selected directory</param>
199        private void fillUploadsPaths(UploadedJobViewModel vm, int index)
200        {
201            var tempdex = index; //Fix when maps gets deleted
202            var start = Path.Combine(_environment.WebRootPath, "uploads", serviceClient.ClientCredentials.UserName.UserName);
203            var dirs = Directory.GetDirectories(start);
204            foreach (string dir in dirs)
205            {
206                if (Directory.GetFiles(dir).Length == 0 && Directory.GetDirectories(dir).Length == 0)
207                {
208                    Directory.Delete(dir, false);
209                    tempdex = -1;
210                }
211                else {
212                    vm.FullDatePaths.Add(dir);
213                    var temp = dir.Split('\\');
214                    vm.DisplayDatePaths.Add(temp[temp.Length - 1]);
215                }
216            }
217            if (tempdex != -1)
218            {
219                vm.SelectedIndex = tempdex;
220                dirs = Directory.GetFiles(vm.FullDatePaths[tempdex]);
221                foreach (string dir in dirs)
222                {
223                    vm.FullFilesPaths.Add(dir);
224                    var temp = dir.Split('\\');
225                    vm.DisplayFilesPaths.Add(temp[temp.Length - 1]);
226                }
227            }
228        }
229        /// <summary>
230        /// Deletes a file
231        /// </summary>
232        /// <param name="index">Index directory</param>
233        /// <param name="filedex">Index file to delete</param>
234        /// <returns></returns>
235        public IActionResult DeleteFile(int index, int filedex)
236        {
237            init();
238            if (serviceLocator.CheckLogin())
239            {
240                UploadedJobViewModel upper = new UploadedJobViewModel();
241                fillUploadsPaths(upper, index);
242                System.IO.File.Delete(upper.FullFilesPaths[filedex]);
243                var message = upper.DisplayFilesPaths[filedex] + " has been deleted";
244
245                upper = new UploadedJobViewModel();
246                fillUploadsPaths(upper, index);
247                upper.message = message;
248                ViewBag.Title = "File deleted - Uploads";
249
250                return View("Uploads", upper);
251            }
252            else
253            {
254                return RedirectToAction("Index", "Home");
255            }
256        }
257        /// <summary>
258        /// Opens a selected file
259        /// </summary>
260        /// <param name="index">Index directory</param>
261        /// <param name="filedex">Index selected file</param>
262        /// <returns></returns>
263        public IActionResult OpenFile(int index, int filedex)
264        {
265            init();
266            if (serviceLocator.CheckLogin())
267            {
268                UploadedJobViewModel upper = new UploadedJobViewModel();
269                fillUploadsPaths(upper, index);
270
271                var serve = weblog.getFileOpener(userId);
272                serve.NewModel();
273                serve.env = _environment;
274
275                var ioptimizer = ContentManager.Load(upper.FullFilesPaths[filedex]);
276
277                serve.vm.SelectedTask = new OptimizerHiveTask((IOptimizer)ioptimizer);
278                if (serve.vm.SelectedTask.ItemTask.Item is IAlgorithm)
279                {
280                    serve.vm.SelectedAlgorithm = (IAlgorithm)serve.vm.SelectedTask.ItemTask.Item;
281                }
282                else if (serve.vm.SelectedTask.ItemTask.Item is BatchRun)
283                {
284                    serve.vm.SelectedBatchRun = (BatchRun)serve.vm.SelectedTask.ItemTask.Item;
285                }
286                else if (serve.vm.SelectedTask.ItemTask.Item is Experiment)
287                {
288                    serve.vm.SelectedExperiment = (Experiment)serve.vm.SelectedTask.ItemTask.Item;
289                }
290                serve.setTasks();
291                ViewBag.JobsCount = serve.Job.Job.JobCount;
292                ViewBag.Title = serve.vm.SelectedTask.ItemTask.Name + " - Uploads";
293                ViewBag.SessionId = HttpContext.Session.GetString("UserId");
294                return View("OpenFile", serve.vm);
295            }
296            else
297            {
298                return RedirectToAction("Index", "Home");
299            }
300        }
301        /// <summary>
302        /// Adds current opened file to hive, uses FileOpeningService singleton
303        /// </summary>
304        /// <returns></returns>
305        public IActionResult AddToHive()
306        {
307            init();
308            if (serviceLocator.CheckLogin())
309            {
310                var job = weblog.getFileOpener(userId).AddCurrentModelToHive();
311                while (job.Progress.ProgressValue != 1)
312                { }
313
314                Thread.Sleep(1000);
315                job.Progress.Status = "Upload finished";
316                Thread.Sleep(2000);
317                return RedirectToAction("Index", "Job");
318            }
319            else
320            {
321                return RedirectToAction("Index", "Home");
322            }
323        }
324        //TODO Work in progress
325        /* public async Task<IActionResult> DownloadFile(int index, int filedex)
326         {
327             if (((HiveServiceLocatorWeb)(HiveServiceLocatorWeb.Instance)).CheckLogin())
328             {
329                 UploadedJobViewModel upper = new UploadedJobViewModel();
330                 fillUploadsPaths(upper, index);
331
332                HttpContext.Response.ContentType = "APPLICATION/OCTET-STREAM";
333                 String Header = "Attachment; Filename=" + upper.DisplayFilesPaths[filedex];
334                 HttpContext.Response.Headers.Add("Content-Disposition", Header);
335                 System.IO.FileInfo Dfile = new System.IO.FileInfo(upper.FullFilesPaths[filedex]);
336                 await HttpContext.Response.WriteAsync(Dfile.FullName);
337                 //HttpContext.Response.End();
338
339                 var message = upper.DisplayFilesPaths[filedex] + " has been downloaded";
340
341                 upper.message = message;
342                 ViewBag.Title = "Downloaded file";
343
344                 return View("Uploads", upper);
345             }
346             else
347             {
348                 HiveServiceLocatorWeb.SetLoginErrorMessage();
349                 return RedirectToAction("Index", "Home");
350             }
351         }*/
352
353        #endregion
354
355        #region Uploader
356
357        /// <summary>
358        /// Uploads file onto server directory
359        /// </summary>
360        /// <param name="files">Files</param>
361        /// <param name="directory">Directory path for server</param>
362        /// <returns></returns>
363        [HttpPost]
364        public async Task<IActionResult> Uploader(ICollection<IFormFile> files, string directory)
365        {
366            init();
367            UploadedJobViewModel upper = new UploadedJobViewModel();
368            var uploads = Path.Combine(_environment.WebRootPath, "uploads", serviceClient.ClientCredentials.UserName.UserName,
369                directory);
370            Directory.CreateDirectory(uploads);
371            foreach (var file in files)
372            {
373                if (file.Length > 0)
374                {
375                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
376                    await file.SaveAsAsync(Path.Combine(uploads, fileName));
377                    // var ioptimizer = ContentManager.Load(Path.Combine(uploads, fileName));
378                    //OptimizerHiveTask task = new OptimizerHiveTask((IOptimizer)ioptimizer);
379                    //upper.Tasks.Add(task);
380                }
381            }
382            ViewBag.Title = "Upload complete - Uploads";
383            return RedirectToAction("Uploads", "Job");
384
385        }
386        #endregion
387    }
388}
Note: See TracBrowser for help on using the repository browser.