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

Last change on this file since 13805 was 13805, checked in by jlodewyc, 5 years ago

#2582 Bugfixing, email setup password and code commenting

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