-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTripController.cs
More file actions
303 lines (265 loc) · 11.7 KB
/
Copy pathTripController.cs
File metadata and controls
303 lines (265 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Duber.Domain.Driver.Model;
using Duber.Domain.Driver.Repository;
using Duber.Domain.SharedKernel.Chaos;
using Duber.Domain.User.Model;
using Duber.Domain.User.Repository;
using Duber.Infrastructure.Chaos;
using Duber.Infrastructure.Http;
using Duber.Infrastructure.Resilience.Http;
using Duber.WebSite.Extensions;
using Duber.WebSite.Hubs;
using Duber.WebSite.Infrastructure.Repository;
using Duber.WebSite.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Polly;
// ReSharper disable ForCanBeConvertedToForeach
namespace Duber.WebSite.Controllers
{
public class TripController : Controller
{
private GeneralChaosSetting _generalChaosSetting;
private readonly IMemoryCache _cache;
private readonly IUserRepository _userRepository;
private readonly ResilientHttpClient _httpClient;
private readonly IHubContext<TripHub> _hubContext;
private readonly IDriverRepository _driverRepository;
private readonly Lazy<Task<GeneralChaosSetting>> _generalChaosSettingFactory;
private readonly IReportingRepository _reportingRepository;
private readonly IOptions<TripApiSettings> _tripApiSettings;
private readonly Dictionary<SelectListItem, LocationModel> _originsAndDestinations;
public TripController(IUserRepository userRepository,
IDriverRepository driverRepository,
IMemoryCache cache,
ResilientHttpClient httpClient,
IOptions<TripApiSettings> tripApiSettings,
IHubContext<TripHub> hubContext,
IReportingRepository reportingRepository,
Lazy<Task<GeneralChaosSetting>> generalChaosSettingFactory)
{
_userRepository = userRepository;
_driverRepository = driverRepository;
_cache = cache;
_httpClient = httpClient;
_tripApiSettings = tripApiSettings;
_hubContext = hubContext;
_reportingRepository = reportingRepository;
_generalChaosSettingFactory = generalChaosSettingFactory;
_originsAndDestinations = new Dictionary<SelectListItem, LocationModel>
{
{
new SelectListItem { Text = "Poblado's Park" },
new LocationModel { Latitude = 6.210292869847029, Longitude = -75.57115852832794, Description = "Poblado's Park" }
},
{
new SelectListItem { Text = "Lleras Park" },
new LocationModel { Latitude = 6.2087793817882515, Longitude = -75.56776275426228, Description = "Lleras Park" }
},
{
new SelectListItem { Text = "Sabaneta Park" },
new LocationModel { Latitude = 6.151584634798451, Longitude = -75.61546325683594, Description = "Sabaneta Park" }
},
{
new SelectListItem { Text = "The executive bar" },
new LocationModel { Latitude = 6.252063572976704, Longitude = -75.56599313040351, Description = "The executive bar" }
},
};
}
public async Task<IActionResult> Index()
{
var drivers = await GetDrivers();
var users = await GetUsers();
var model = new TripRequestModel
{
Drivers = drivers.ToSelectList(),
Users = users.ToSelectList(),
User = users.FirstOrDefault()?.Id.ToString(),
Driver = drivers.FirstOrDefault()?.Id.ToString(),
Origins = _originsAndDestinations.Keys.Select(x => x).ToList(),
Destinations = _originsAndDestinations.Keys.Select(x => x).ToList(),
From = _originsAndDestinations.Keys.Select(x => x).ToList().FirstOrDefault()?.Text,
To = _originsAndDestinations.Keys.Select(x => x).ToList().LastOrDefault()?.Text,
Places = _originsAndDestinations.Values.Select(x => x).ToList()
};
return View(model);
}
[HttpPost]
public async Task<IActionResult> SimulateTrip(TripRequestModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState.AllErrors());
_generalChaosSetting = await _generalChaosSettingFactory.Value;
var tripID = await CreateTrip(model);
await _hubContext.Clients.All.SendAsync("NotifyTrip", "Created");
await AcceptOrStartTrip(_tripApiSettings.Value.AcceptUrl, tripID);
await _hubContext.Clients.All.SendAsync("NotifyTrip", "Accepted");
await AcceptOrStartTrip(_tripApiSettings.Value.StartUrl, tripID);
await _hubContext.Clients.All.SendAsync("NotifyTrip", "Started");
for (var index = 0; index < model.Directions.Count; index += 5)
{
var direction = model.Directions[index];
if (index + 5 >= model.Directions.Count)
direction = _originsAndDestinations.Values.SingleOrDefault(x => x.Description == model.To);
await UpdateTripLocation(tripID, direction);
await _hubContext.Clients.All.SendAsync("UpdateCurrentPosition", direction);
}
await _hubContext.Clients.All.SendAsync("NotifyTrip", "Finished");
return Ok();
}
public async Task<IActionResult> TripsByUser()
{
var users = await GetUsers();
var usersModel = users.Select(x => new UserModel
{
Id = x.Id,
Email = x.Email,
Name = x.Name,
NumberPhone = x.NumberPhone
});
return View(usersModel.ToList());
}
public async Task<IActionResult> TripsByUserId(int id)
{
try
{
var trips = await _reportingRepository.GetTripsByUserAsync(id);
return View("UserTrips", trips.ToList());
}
finally
{
_reportingRepository.Dispose();
}
}
public async Task<IActionResult> TripById(Guid id)
{
try
{
var trip = await _reportingRepository.GetTripAsync(id);
return View("TripDetails", trip);
}
finally
{
_reportingRepository.Dispose();
}
}
public async Task<IActionResult> TripsByDriver()
{
var drivers = await GetDrivers();
var driversModel = drivers.Select(x => new DriverModel()
{
Id = x.Id,
Email = x.Email,
Name = x.Name,
NumberPhone = x.PhoneNumber
});
return View(driversModel.ToList());
}
public async Task<IActionResult> TripsByDriverId(int id)
{
try
{
var trips = await _reportingRepository.GetTripsByDriverAsync(id);
return View("DriverTrips", trips.ToList());
}
finally
{
_reportingRepository.Dispose();
}
}
public async Task<IActionResult> Test()
{
var model = new TripRequestModel
{
Driver = (await GetDrivers()).FirstOrDefault()?.Id.ToString(),
User = (await GetUsers()).FirstOrDefault()?.Id.ToString(),
From = "Poblado's Park",
To = "Sabaneta Park"
};
await CreateTrip(model);
return Ok();
}
private async Task<IList<Driver>> GetDrivers()
{
var drivers = await GetDataFromCache("drivers", () => _driverRepository.GetDriversAsync());
return drivers;
}
private async Task<IList<User>> GetUsers()
{
var users = await GetDataFromCache("users", () => _userRepository.GetUsersAsync());
return users;
}
private async Task<T> GetDataFromCache<T>(string cacheKey, Func<Task<T>> action)
{
if (!_cache.TryGetValue(cacheKey, out T result))
{
result = await action();
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(5));
_cache.Set(cacheKey, result, cacheEntryOptions);
}
return result;
}
private async Task<Guid> CreateTrip(TripRequestModel model)
{
var drivers = await GetDrivers();
var users = await GetUsers();
var driverInfo = drivers.SingleOrDefault(x => x.Id == int.Parse(model.Driver));
var userInfo = users.SingleOrDefault(x => x.Id == int.Parse(model.User));
var uri = new Uri(new Uri(_tripApiSettings.Value.BaseUrl), _tripApiSettings.Value.CreateUrl);
var request = new HttpRequestMessage(HttpMethod.Post, uri)
{
Content = new JsonContent(new
{
userId = int.Parse(model.User),
driverId = int.Parse(model.Driver),
from = _originsAndDestinations.Values.SingleOrDefault(x => x.Description == model.From),
to = _originsAndDestinations.Values.SingleOrDefault(x => x.Description == model.To),
plate = driverInfo?.CurrentVehicle.Plate,
brand = driverInfo?.CurrentVehicle.Brand,
model = driverInfo?.CurrentVehicle.Model,
paymentMethod = userInfo?.PaymentMethod
})
};
var context = new Context(OperationKeys.TripApiCreate.ToString()).WithChaosSettings(_generalChaosSetting);
var response = await _httpClient.SendAsync(request, context);
response.EnsureSuccessStatusCode();
return JsonConvert.DeserializeObject<Guid>(await response.Content.ReadAsStringAsync());
}
private async Task AcceptOrStartTrip(string action, Guid tripId)
{
var uri = new Uri(new Uri(_tripApiSettings.Value.BaseUrl), action);
var request = new HttpRequestMessage(HttpMethod.Put, uri)
{
Content = new JsonContent(new { id = tripId.ToString() })
};
var operationKey = action.Contains("start") ? OperationKeys.TripApiStart.ToString() : OperationKeys.TripApiAccept.ToString();
var context = new Context(operationKey).WithChaosSettings(_generalChaosSetting);
var response = await _httpClient.SendAsync(request, context);
response.EnsureSuccessStatusCode();
}
private async Task UpdateTripLocation(Guid tripId, LocationModel location)
{
var uri = new Uri(new Uri(_tripApiSettings.Value.BaseUrl), _tripApiSettings.Value.UpdateCurrentLocationUrl);
var request = new HttpRequestMessage(HttpMethod.Put, uri)
{
Content = new JsonContent(new
{
id = tripId,
currentLocation = new { latitude = location.Latitude, longitude = location.Longitude }
})
};
var context = new Context(OperationKeys.TripApiUpdateCurrentLocation.ToString()).WithChaosSettings(_generalChaosSetting);
var response = await _httpClient.SendAsync(request, context);
response.EnsureSuccessStatusCode();
}
}
}