Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Hubs/CalendarHub.cs @ 14615

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

#2582 Start angular OKB manager, data loaded

File size: 13.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22
23using HeuristicLab.Clients.Hive.WebJobManager.Services;
24using HeuristicLab.Clients.Hive.WebJobManager.Services.Imports;
25using HeuristicLab.Clients.Hive.WebJobManager.ViewModels.User;
26using Microsoft.AspNetCore.SignalR;
27using Newtonsoft.Json;
28using System;
29using System.Collections.Generic;
30using System.Linq;
31using System.Threading;
32
33namespace HeuristicLab.Clients.Hive.WebJobManager.Hubs
34{
35    /// <summary>
36    /// SignalR Hub that manages all resource management.
37    /// </summary>
38    public class CalendarHub : Hub
39    {
40        private WebLoginService weblog;
41        private Guid userId;
42        private HiveAdminClientWeb adminClient;
43        private HiveServiceLocatorWeb servloc;
44        private AccessAdministrationClient accessClient;
45        /// <summary>
46        /// Loads up the services for the client (Instance is only created upon a call from a client)
47        /// </summary>
48        private void loader()
49        {
50            weblog = WebLoginService.Instance;
51            string uid = Context.QueryString["userid"];
52            if (uid == null || uid == "" || Guid.Parse(uid) == Guid.Empty)
53            {
54                userId = Guid.Empty;
55            }
56            else
57            {
58                userId = Guid.Parse(uid);
59                adminClient = weblog.getAdminClient(userId);
60                servloc = weblog.getServiceLocator(userId);
61                accessClient = weblog.getAccessAdminClient(userId);
62            }
63        }
64        /// <summary>
65        /// Initial client request for all user, group and resource information
66        /// </summary>
67        public void requestInfo()
68        {
69            loader();
70            adminClient.Refresh();
71            UserViewModel vm = new UserViewModel(accessClient, weblog.getCurrentUser(userId)).refreshAll();
72
73            var users = JsonConvert.SerializeObject(vm.users);
74            var groups = JsonConvert.SerializeObject(vm.ugroups);
75            var res = JsonConvert.SerializeObject(adminClient.Resources);
76            Clients.Caller.processData(res, users, groups);
77        }
78        /// <summary>
79        /// Request for the downtimes of a specific resource
80        /// </summary>
81        /// <param name="id">Resource ID</param>
82        public void requestDownTime(string id)
83        {
84            loader();
85            adminClient.Refresh();
86            Guid t = Guid.Parse(id);
87
88            //Loads up the downtimes for the set resource ID
89            adminClient.DowntimeForResourceId = t;
90            adminClient.RefreshCalendar();
91           
92            var down = JsonConvert.SerializeObject(adminClient.Downtimes);
93            Clients.Caller.processDowntime(id, down);
94        }
95        /// <summary>
96        /// Request for permissions of a specific resource (refreshable by recall)
97        /// </summary>
98        /// <param name="id">Resource ID</param>
99        public void requestPermissions(string id)
100        {
101            loader();
102            Guid r = Guid.Parse(id);
103            var perm = servloc.CallHiveService(x => x.GetResourcePermissions(r));
104            Clients.Caller.processPermissions(id, JsonConvert.SerializeObject(perm));
105        }
106
107        /// <summary>
108        /// Edit permissions for a resource
109        /// </summary>
110        /// <param name="perms">Permissions ID's</param>
111        /// <param name="idresource">Resource ID</param>
112        public void changePermissions(string[] perms, string idresource)
113        {
114            loader();
115            var res = Guid.Parse(idresource);
116
117            //Collect current permissions
118            var exist = servloc.CallHiveService(x => x.GetResourcePermissions(res));
119
120            //Separate list for new and to remove permissions
121            List<Guid> newPerms = new List<Guid>();
122            List<Guid> revokePerms = new List<Guid>();
123
124            for (var i = 0; i < perms.Length; i++)
125            {
126                var p = Guid.Parse(perms[i]);
127                var elemid = exist.FindIndex(x => x.GrantedUserId == p);
128                if (elemid != -1)
129                {//If it already exists => Scramble up Guid (checked further)
130                    exist[elemid].GrantedUserId = Guid.Empty;
131                }
132                else
133                {//If it's not in the list, add to new permissions
134                    newPerms.Add(p);
135                }
136            }
137            //Adds the new permissions to the resource
138            servloc.CallHiveService(x => x.GrantResourcePermissions(res, newPerms));
139            foreach (var ex in exist)
140            {//Checks for intact ID's and adds them to the revoke list
141                if(ex.GrantedUserId != Guid.Empty)
142                {
143                    revokePerms.Add(ex.GrantedUserId);
144                }
145            }
146            //Revokes all permissions that were deselected by the user
147            servloc.CallHiveService(x => x.RevokeResourcePermissions(res, revokePerms));
148            //Live reload the view for the resource
149            requestPermissions(idresource);
150        }
151        /// <summary>
152        /// Toggles the disposable setting for a resource
153        /// </summary>
154        /// <param name="id">Resource ID</param>
155        public void toggleDisposable(string id)
156        {
157            loader();
158            adminClient.Refresh();
159            Guid c = Guid.Parse(id);
160            var obj = adminClient.Resources.ToList().Find(x => x.Id == c);
161
162            //Toggle
163            ((Slave)(obj)).IsDisposable = !((Slave)(obj)).IsDisposable;
164
165            adminClient.Store(obj, CancellationToken.None);
166
167            //Notify client of successful saving
168            Clients.Caller.processDispose( ((Slave)(obj)).IsDisposable);
169
170        }
171        /// <summary>
172        /// Saves changes to a resource calendar
173        /// </summary>
174        /// <param name="id">Resource id</param>
175        /// <param name="del">To delete downtimes</param>
176        /// <param name="add">New downtimes</param>
177        /// <param name="upd">Downtimes to update</param>
178        /// <param name="fresh">Check if refresh should be sent (Save all current graph or Save current graph)</param>
179        /// <param name="last">Check for last request (Save all)</param>
180        public void saveCalendar(string id, string[] del, string[][] add, string[][] upd, bool fresh, bool last)
181        {
182            loader();
183            var calid = Guid.Parse(id);
184           
185            //Load up calendar
186            adminClient.Refresh();
187            adminClient.DowntimeForResourceId = calid;
188            adminClient.RefreshCalendar();
189
190            var downlist = adminClient.Downtimes.ToList();
191            foreach(var s in del)
192            {//Deletes downtimes
193                var gu = Guid.Parse(s);
194                var el = downlist.Find(x => x.Id == gu);
195                adminClient.Delete(el);
196            }
197            foreach (var s in add)
198            {//Adds new downtimes
199                //init
200                var obj = new Downtime();
201                obj.Id = Guid.Empty;
202                if (s[0] == "Unavailable")
203                    obj.DowntimeType = DowntimeType.Offline;
204                else
205                    obj.DowntimeType = DowntimeType.Shutdown;
206                obj.StartDate = (new DateTime(1970, 1, 1)).AddMilliseconds(double.Parse(s[1]));
207                obj.EndDate = (new DateTime(1970, 1, 1)).AddMilliseconds(double.Parse(s[2]));
208                if (s[3] == "true")
209                    obj.AllDayEvent = true;
210                else
211                    obj.AllDayEvent = false;
212                obj.ResourceId = Guid.Parse(s[4]);
213
214                //Recurrency check
215                if (s[5] == "true")
216                {//Recurrency set
217                    obj.Recurring = true;
218                    if (s[6] == "0")
219                    {//new Recur
220                        var dayarr = s[9].Split(',');
221                        var start = (new DateTime(1970, 1, 1)).AddMilliseconds(double.Parse(s[7]));
222                        var end = (new DateTime(1970, 1, 1)).AddMilliseconds(double.Parse(s[8]));
223                        loopAddDowns(start, end, dayarr, obj);//Loop creation of recurrency. Start to end date
224                    }
225                    else
226                    {//Existing recurrency (only edits current element, client handles the creation of the other events)
227                        obj.RecurringId = Guid.Parse(s[6]);
228                        adminClient.Store(obj, CancellationToken.None);
229                    }
230                }
231                else { //No recurrency
232                    obj.Recurring = false;
233                    adminClient.Store(obj, CancellationToken.None);
234                }
235               
236               
237            }
238            foreach(var s in upd)
239            {//Update existing downtime
240                 var obj = downlist.Find(x => x.Id == Guid.Parse(s[0]));
241                if (s[1] == "Unavailable")
242                    obj.DowntimeType = DowntimeType.Offline;
243                else
244                    obj.DowntimeType = DowntimeType.Shutdown;
245                obj.StartDate = (new DateTime(1970, 1, 1)).AddMilliseconds(double.Parse(s[2]));
246                obj.EndDate = (new DateTime(1970, 1, 1)).AddMilliseconds(double.Parse(s[3]));
247                if (s[4] == "true")
248                    obj.AllDayEvent = true;
249                else
250                    obj.AllDayEvent = false;
251                if (s[5] == "true" && !obj.Recurring)
252                {//Recurrence set
253                    obj.Recurring = true;
254                    if (s[6] == "00000000-0000-0000-0000-000000000000")
255                    {//Creates new recurrence
256                        var dayarr = s[9].Split(',');
257                        var start = (new DateTime(1970, 1, 1)).AddMilliseconds(double.Parse(s[7]));
258                        var end = (new DateTime(1970, 1, 1)).AddMilliseconds(double.Parse(s[8]));
259                        loopAddDowns(start, end, dayarr, obj);
260                        adminClient.Delete(obj);
261                        //Delete needed to prevent doubles in the creation of the recurrency
262                        //Why: event could be on not included day of the week => loop cannot find that.
263                    }
264                    else
265                    {
266                        obj.RecurringId = Guid.Parse(s[6]);
267                        //adminClient.Store(obj, CancellationToken.None); //Throws error
268                    }
269                }
270                else
271                {
272                    //adminClient.Store(obj, CancellationToken.None); //Throws error
273                }
274               
275
276            }
277            if( last)
278            {//Last element from save all => Notify client
279                Clients.Caller.savingAllDone();
280            }
281            else if (fresh)
282            {//Refresh for graph needed
283                Clients.Caller.savingCurrentDone();
284            }
285        }
286        /// <summary>
287        /// Creates downtimes for a new recurrency
288        /// </summary>
289        /// <param name="start">Start date</param>
290        /// <param name="end">End date</param>
291        /// <param name="dayarr">Boolean day array (sun = 0,...)</param>
292        /// <param name="obj">Downtime to recur</param>
293        private void loopAddDowns(DateTime start, DateTime end, string[] dayarr, Downtime obj)
294        {
295            var rid = Guid.NewGuid();
296            while (start < end)
297            {
298                if (dayarr[(int)(start.DayOfWeek)] == "true")
299                {//Check for day of the week
300                    //Set setting for the downtime to add
301                    var temp = new Downtime();
302                    temp.StartDate = start.AddHours(obj.StartDate.Hour - start.Hour)
303                        .AddMinutes(obj.StartDate.Minute - start.Minute);
304                    temp.EndDate = start.AddHours(obj.EndDate.Hour - start.Hour)
305                        .AddMinutes(obj.EndDate.Minute - start.Minute);
306                    temp.Id = Guid.Empty;
307                    temp.DowntimeType = obj.DowntimeType;
308                    temp.AllDayEvent = obj.AllDayEvent;
309                    temp.ResourceId = obj.ResourceId;
310                    temp.Recurring = obj.Recurring;
311                    temp.RecurringId = rid;
312                    adminClient.Store(temp, CancellationToken.None);
313                }
314                start = start.AddDays(1);
315            }
316        }
317    }
318}
Note: See TracBrowser for help on using the repository browser.