| | | 1 | | using System.Net; |
| | | 2 | | using AngleSharp; |
| | | 3 | | using AngleSharp.Dom; |
| | | 4 | | using AngleSharp.Html.Dom; |
| | | 5 | | using EHonda.KicktippAi.Core; |
| | | 6 | | using Microsoft.Extensions.Caching.Memory; |
| | | 7 | | using Microsoft.Extensions.Logging; |
| | | 8 | | using NodaTime; |
| | | 9 | | using NodaTime.Extensions; |
| | | 10 | | |
| | | 11 | | namespace KicktippIntegration; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Implementation of IKicktippClient for interacting with kicktipp.de website |
| | | 15 | | /// Authentication is handled automatically via KicktippAuthenticationHandler |
| | | 16 | | /// </summary> |
| | | 17 | | public class KicktippClient : IKicktippClient, IDisposable |
| | | 18 | | { |
| | | 19 | | private readonly HttpClient _httpClient; |
| | | 20 | | private readonly ILogger<KicktippClient> _logger; |
| | | 21 | | private readonly IBrowsingContext _browsingContext; |
| | | 22 | | private readonly IMemoryCache _cache; |
| | | 23 | | |
| | 1 | 24 | | public KicktippClient(HttpClient httpClient, ILogger<KicktippClient> logger, IMemoryCache cache) |
| | | 25 | | { |
| | 1 | 26 | | _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); |
| | 1 | 27 | | _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| | 1 | 28 | | _cache = cache ?? throw new ArgumentNullException(nameof(cache)); |
| | | 29 | | |
| | 1 | 30 | | var config = Configuration.Default.WithDefaultLoader(); |
| | 1 | 31 | | _browsingContext = BrowsingContext.New(config); |
| | 1 | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <inheritdoc /> |
| | | 35 | | public async Task<List<Match>> GetOpenPredictionsAsync(string community) |
| | | 36 | | { |
| | | 37 | | try |
| | | 38 | | { |
| | 1 | 39 | | var url = $"{community}/tippabgabe"; |
| | 1 | 40 | | var response = await _httpClient.GetAsync(url); |
| | | 41 | | |
| | 1 | 42 | | if (!response.IsSuccessStatusCode) |
| | | 43 | | { |
| | 1 | 44 | | _logger.LogError("Failed to fetch tippabgabe page. Status: {StatusCode}", response.StatusCode); |
| | 1 | 45 | | return new List<Match>(); |
| | | 46 | | } |
| | | 47 | | |
| | 1 | 48 | | var content = await response.Content.ReadAsStringAsync(); |
| | 1 | 49 | | var document = await _browsingContext.OpenAsync(req => req.Content(content)); |
| | | 50 | | |
| | 1 | 51 | | var matches = new List<Match>(); |
| | | 52 | | |
| | | 53 | | // Extract matchday from the page |
| | 1 | 54 | | var currentMatchday = ExtractMatchdayFromPage(document); |
| | 1 | 55 | | _logger.LogDebug("Extracted matchday: {Matchday}", currentMatchday); |
| | | 56 | | |
| | | 57 | | // Parse matches from the tippabgabe table |
| | 1 | 58 | | var matchTable = document.QuerySelector("#tippabgabeSpiele tbody"); |
| | 1 | 59 | | if (matchTable == null) |
| | | 60 | | { |
| | 1 | 61 | | _logger.LogWarning("Could not find tippabgabe table"); |
| | 1 | 62 | | return matches; |
| | | 63 | | } |
| | | 64 | | |
| | 1 | 65 | | var matchRows = matchTable.QuerySelectorAll("tr"); |
| | 1 | 66 | | _logger.LogDebug("Found {MatchRowCount} potential match rows", matchRows.Length); |
| | | 67 | | |
| | 1 | 68 | | string lastValidTimeText = ""; // Track the last valid date/time for inheritance |
| | | 69 | | |
| | 1 | 70 | | foreach (var row in matchRows) |
| | | 71 | | { |
| | | 72 | | try |
| | | 73 | | { |
| | 1 | 74 | | var cells = row.QuerySelectorAll("td"); |
| | 1 | 75 | | if (cells.Length >= 4) |
| | | 76 | | { |
| | | 77 | | // Extract match details from table cells |
| | 1 | 78 | | var timeText = cells[0].TextContent?.Trim() ?? ""; |
| | 1 | 79 | | var homeTeam = cells[1].TextContent?.Trim() ?? ""; |
| | 1 | 80 | | var awayTeam = cells[2].TextContent?.Trim() ?? ""; |
| | | 81 | | |
| | | 82 | | // Check if match is cancelled ("Abgesagt" in German) |
| | | 83 | | // Cancelled matches still accept predictions on Kicktipp, so we process them. |
| | | 84 | | // See docs/features/cancelled-matches.md for design rationale. |
| | 1 | 85 | | var isCancelled = IsCancelledTimeText(timeText); |
| | | 86 | | |
| | | 87 | | // Handle date inheritance: if timeText is empty or cancelled, use the last valid time |
| | | 88 | | // This preserves database key consistency (startsAt is part of the composite key) |
| | 1 | 89 | | if (string.IsNullOrWhiteSpace(timeText) || isCancelled) |
| | | 90 | | { |
| | 1 | 91 | | if (!string.IsNullOrWhiteSpace(lastValidTimeText)) |
| | | 92 | | { |
| | 1 | 93 | | if (isCancelled) |
| | | 94 | | { |
| | 1 | 95 | | _logger.LogWarning( |
| | 1 | 96 | | "Match {HomeTeam} vs {AwayTeam} is cancelled (Abgesagt). Using inherited time '{ |
| | 1 | 97 | | "Predictions can still be placed but may need to be re-evaluated when the match |
| | 1 | 98 | | homeTeam, awayTeam, lastValidTimeText); |
| | | 99 | | } |
| | | 100 | | else |
| | | 101 | | { |
| | 1 | 102 | | _logger.LogDebug("Using inherited time for {HomeTeam} vs {AwayTeam}: '{InheritedTime |
| | | 103 | | } |
| | 1 | 104 | | timeText = lastValidTimeText; |
| | | 105 | | } |
| | | 106 | | else |
| | | 107 | | { |
| | 0 | 108 | | _logger.LogWarning("No previous valid time to inherit for {HomeTeam} vs {AwayTeam}{Cance |
| | 0 | 109 | | homeTeam, awayTeam, isCancelled ? " (cancelled match)" : ""); |
| | | 110 | | } |
| | | 111 | | } |
| | | 112 | | else |
| | | 113 | | { |
| | | 114 | | // Update the last valid time for future inheritance |
| | 1 | 115 | | lastValidTimeText = timeText; |
| | 1 | 116 | | _logger.LogDebug("Updated last valid time to: '{TimeText}'", timeText); |
| | | 117 | | } |
| | | 118 | | |
| | | 119 | | // Check if this row has betting inputs (indicates open match) |
| | 1 | 120 | | var bettingInputs = cells[3].QuerySelectorAll("input[type='text']"); |
| | 1 | 121 | | if (bettingInputs.Length >= 2) |
| | | 122 | | { |
| | 1 | 123 | | _logger.LogDebug("Found open match: {HomeTeam} vs {AwayTeam} at {Time}{Cancelled}", |
| | 1 | 124 | | homeTeam, awayTeam, timeText, isCancelled ? " (CANCELLED)" : ""); |
| | | 125 | | |
| | | 126 | | // Parse the date/time - for now use a simple approach |
| | | 127 | | // Format appears to be "08.07.25 21:00" |
| | 1 | 128 | | var startsAt = ParseMatchDateTime(timeText); |
| | | 129 | | |
| | 1 | 130 | | matches.Add(new Match(homeTeam, awayTeam, startsAt, currentMatchday, isCancelled)); |
| | | 131 | | } |
| | | 132 | | } |
| | 1 | 133 | | } |
| | 0 | 134 | | catch (Exception ex) |
| | | 135 | | { |
| | 0 | 136 | | _logger.LogWarning(ex, "Error parsing match row"); |
| | 0 | 137 | | continue; |
| | | 138 | | } |
| | | 139 | | } |
| | | 140 | | |
| | 1 | 141 | | _logger.LogInformation("Successfully parsed {MatchCount} open matches", matches.Count); |
| | 1 | 142 | | return matches; |
| | | 143 | | } |
| | 0 | 144 | | catch (Exception ex) |
| | | 145 | | { |
| | 0 | 146 | | _logger.LogError(ex, "Exception in GetOpenPredictionsAsync"); |
| | 0 | 147 | | return new List<Match>(); |
| | | 148 | | } |
| | 1 | 149 | | } |
| | | 150 | | |
| | | 151 | | /// <inheritdoc /> |
| | | 152 | | public async Task<bool> PlaceBetAsync(string community, Match match, BetPrediction prediction, bool overrideBet = fa |
| | | 153 | | { |
| | | 154 | | try |
| | | 155 | | { |
| | 1 | 156 | | var url = $"{community}/tippabgabe"; |
| | 1 | 157 | | var response = await _httpClient.GetAsync(url); |
| | | 158 | | |
| | 1 | 159 | | if (!response.IsSuccessStatusCode) |
| | | 160 | | { |
| | 1 | 161 | | _logger.LogError("Failed to access betting page. Status: {StatusCode}", response.StatusCode); |
| | 1 | 162 | | return false; |
| | | 163 | | } |
| | | 164 | | |
| | 1 | 165 | | var pageContent = await response.Content.ReadAsStringAsync(); |
| | 1 | 166 | | var document = await _browsingContext.OpenAsync(req => req.Content(pageContent)); |
| | | 167 | | |
| | | 168 | | // Find the bet form |
| | 1 | 169 | | var betForm = document.QuerySelector("form") as IHtmlFormElement; |
| | 1 | 170 | | if (betForm == null) |
| | | 171 | | { |
| | 1 | 172 | | _logger.LogWarning("Could not find betting form on the page"); |
| | 1 | 173 | | return false; |
| | | 174 | | } |
| | | 175 | | |
| | | 176 | | // Find the main content area |
| | 1 | 177 | | var contentArea = document.QuerySelector("#kicktipp-content"); |
| | 1 | 178 | | if (contentArea == null) |
| | | 179 | | { |
| | 1 | 180 | | _logger.LogWarning("Could not find content area on the betting page"); |
| | 1 | 181 | | return false; |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | // Find the table with predictions |
| | 1 | 185 | | var tbody = contentArea.QuerySelector("tbody"); |
| | 1 | 186 | | if (tbody == null) |
| | | 187 | | { |
| | 1 | 188 | | _logger.LogWarning("No betting table found"); |
| | 1 | 189 | | return false; |
| | | 190 | | } |
| | | 191 | | |
| | 1 | 192 | | var rows = tbody.QuerySelectorAll("tr"); |
| | 1 | 193 | | var formData = new List<KeyValuePair<string, string>>(); |
| | 1 | 194 | | var matchFound = false; |
| | | 195 | | |
| | | 196 | | // Copy hidden inputs from the original form |
| | 1 | 197 | | var hiddenInputs = betForm.QuerySelectorAll("input[type='hidden']"); |
| | 1 | 198 | | foreach (var hiddenInput in hiddenInputs.Cast<IHtmlInputElement>()) |
| | | 199 | | { |
| | 1 | 200 | | if (!string.IsNullOrEmpty(hiddenInput.Name) && hiddenInput.Value != null) |
| | | 201 | | { |
| | 1 | 202 | | formData.Add(new KeyValuePair<string, string>(hiddenInput.Name, hiddenInput.Value)); |
| | | 203 | | } |
| | | 204 | | } |
| | | 205 | | |
| | | 206 | | // Find the specific match in the form and set its bet |
| | 1 | 207 | | foreach (var row in rows) |
| | | 208 | | { |
| | 1 | 209 | | var cells = row.QuerySelectorAll("td"); |
| | 1 | 210 | | if (cells.Length < 4) continue; // Need at least date, home team, road team, and bet inputs |
| | | 211 | | |
| | | 212 | | try |
| | | 213 | | { |
| | 1 | 214 | | var homeTeam = cells[1].TextContent?.Trim() ?? ""; |
| | 1 | 215 | | var roadTeam = cells[2].TextContent?.Trim() ?? ""; |
| | | 216 | | |
| | 1 | 217 | | if (string.IsNullOrEmpty(homeTeam) || string.IsNullOrEmpty(roadTeam)) |
| | 0 | 218 | | continue; |
| | | 219 | | |
| | | 220 | | // Check if this is the match we want to bet on |
| | 1 | 221 | | if (homeTeam == match.HomeTeam && roadTeam == match.AwayTeam) |
| | | 222 | | { |
| | | 223 | | // Find bet input fields in the row |
| | 1 | 224 | | var homeInput = cells[3].QuerySelector("input[id$='_heimTipp']") as IHtmlInputElement; |
| | 1 | 225 | | var awayInput = cells[3].QuerySelector("input[id$='_gastTipp']") as IHtmlInputElement; |
| | | 226 | | |
| | 1 | 227 | | if (homeInput == null || awayInput == null) |
| | | 228 | | { |
| | 1 | 229 | | _logger.LogWarning("No betting inputs found for {Match}, skipping", match); |
| | 1 | 230 | | continue; |
| | | 231 | | } |
| | | 232 | | |
| | | 233 | | // Check if bets are already placed |
| | 1 | 234 | | var hasExistingHomeBet = !string.IsNullOrEmpty(homeInput.Value); |
| | 1 | 235 | | var hasExistingAwayBet = !string.IsNullOrEmpty(awayInput.Value); |
| | | 236 | | |
| | 1 | 237 | | if ((hasExistingHomeBet || hasExistingAwayBet) && !overrideBet) |
| | | 238 | | { |
| | 1 | 239 | | var existingBet = $"{homeInput.Value ?? ""}:{awayInput.Value ?? ""}"; |
| | 1 | 240 | | _logger.LogInformation("{Match} - skipped, already placed {ExistingBet}", match, existingBet |
| | 1 | 241 | | return true; // Consider this successful - bet already exists |
| | | 242 | | } |
| | | 243 | | |
| | | 244 | | // Add bet to form data |
| | 1 | 245 | | if (!string.IsNullOrEmpty(homeInput.Name) && !string.IsNullOrEmpty(awayInput.Name)) |
| | | 246 | | { |
| | 1 | 247 | | formData.Add(new KeyValuePair<string, string>(homeInput.Name, prediction.HomeGoals.ToString( |
| | 1 | 248 | | formData.Add(new KeyValuePair<string, string>(awayInput.Name, prediction.AwayGoals.ToString( |
| | 1 | 249 | | matchFound = true; |
| | 1 | 250 | | _logger.LogInformation("{Match} - betting {Prediction}", match, prediction); |
| | | 251 | | } |
| | | 252 | | else |
| | | 253 | | { |
| | 0 | 254 | | _logger.LogWarning("{Match} - input field names are missing, skipping", match); |
| | 0 | 255 | | continue; |
| | | 256 | | } |
| | | 257 | | |
| | 1 | 258 | | break; // Found our match, no need to continue |
| | | 259 | | } |
| | 1 | 260 | | } |
| | 0 | 261 | | catch (Exception ex) |
| | | 262 | | { |
| | 0 | 263 | | _logger.LogError(ex, "Error processing betting row"); |
| | 0 | 264 | | continue; |
| | | 265 | | } |
| | | 266 | | } |
| | | 267 | | |
| | 1 | 268 | | if (!matchFound) |
| | | 269 | | { |
| | 1 | 270 | | _logger.LogWarning("Match {Match} not found in betting form", match); |
| | 1 | 271 | | return false; |
| | | 272 | | } |
| | | 273 | | |
| | | 274 | | // Add other input fields that might have existing values |
| | 1 | 275 | | var allInputs = betForm.QuerySelectorAll("input[type=text], input[type=number]").OfType<IHtmlInputElement>() |
| | 1 | 276 | | foreach (var input in allInputs) |
| | | 277 | | { |
| | 1 | 278 | | if (!string.IsNullOrEmpty(input.Name) && !string.IsNullOrEmpty(input.Value)) |
| | | 279 | | { |
| | | 280 | | // Only add if we haven't already added this field |
| | 1 | 281 | | if (!formData.Any(kv => kv.Key == input.Name)) |
| | | 282 | | { |
| | 1 | 283 | | formData.Add(new KeyValuePair<string, string>(input.Name, input.Value)); |
| | | 284 | | } |
| | | 285 | | } |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | // Find submit button |
| | 1 | 289 | | var submitButton = betForm.QuerySelector("input[type=submit], button[type=submit]") as IHtmlElement; |
| | 1 | 290 | | var submitName = "submitbutton"; // Default from Python |
| | | 291 | | |
| | 1 | 292 | | if (submitButton != null) |
| | | 293 | | { |
| | 1 | 294 | | if (submitButton is IHtmlInputElement inputSubmit && !string.IsNullOrEmpty(inputSubmit.Name)) |
| | | 295 | | { |
| | 1 | 296 | | submitName = inputSubmit.Name; |
| | 1 | 297 | | formData.Add(new KeyValuePair<string, string>(submitName, inputSubmit.Value ?? "Submit")); |
| | | 298 | | } |
| | 1 | 299 | | else if (submitButton is IHtmlButtonElement buttonSubmit && !string.IsNullOrEmpty(buttonSubmit.Name)) |
| | | 300 | | { |
| | 1 | 301 | | submitName = buttonSubmit.Name; |
| | 1 | 302 | | formData.Add(new KeyValuePair<string, string>(submitName, buttonSubmit.Value ?? "Submit")); |
| | | 303 | | } |
| | | 304 | | } |
| | | 305 | | else |
| | | 306 | | { |
| | | 307 | | // Fallback to default submit button name |
| | 1 | 308 | | formData.Add(new KeyValuePair<string, string>("submitbutton", "Submit")); |
| | | 309 | | } |
| | | 310 | | |
| | | 311 | | // Submit form |
| | 1 | 312 | | var formActionUrl = string.IsNullOrEmpty(betForm.Action) ? url : |
| | 1 | 313 | | (betForm.Action.StartsWith("http") ? betForm.Action : |
| | 1 | 314 | | betForm.Action.StartsWith("/") ? betForm.Action : |
| | 1 | 315 | | $"{community}/{betForm.Action}"); |
| | | 316 | | |
| | 1 | 317 | | var formContent = new FormUrlEncodedContent(formData); |
| | 1 | 318 | | var submitResponse = await _httpClient.PostAsync(formActionUrl, formContent); |
| | | 319 | | |
| | 1 | 320 | | if (submitResponse.IsSuccessStatusCode) |
| | | 321 | | { |
| | 1 | 322 | | _logger.LogInformation("✓ Successfully submitted bet for {Match}!", match); |
| | 1 | 323 | | return true; |
| | | 324 | | } |
| | | 325 | | else |
| | | 326 | | { |
| | 1 | 327 | | _logger.LogError("✗ Failed to submit bet. Status: {StatusCode}", submitResponse.StatusCode); |
| | 1 | 328 | | return false; |
| | | 329 | | } |
| | | 330 | | } |
| | 0 | 331 | | catch (Exception ex) |
| | | 332 | | { |
| | 0 | 333 | | _logger.LogError(ex, "Exception during bet placement"); |
| | 0 | 334 | | return false; |
| | | 335 | | } |
| | 1 | 336 | | } |
| | | 337 | | |
| | | 338 | | /// <inheritdoc /> |
| | | 339 | | public async Task<bool> PlaceBetsAsync(string community, Dictionary<Match, BetPrediction> bets, bool overrideBets = |
| | | 340 | | { |
| | | 341 | | try |
| | | 342 | | { |
| | 1 | 343 | | var url = $"{community}/tippabgabe"; |
| | 1 | 344 | | var response = await _httpClient.GetAsync(url); |
| | | 345 | | |
| | 1 | 346 | | if (!response.IsSuccessStatusCode) |
| | | 347 | | { |
| | 1 | 348 | | _logger.LogError("Failed to access betting page. Status: {StatusCode}", response.StatusCode); |
| | 1 | 349 | | return false; |
| | | 350 | | } |
| | | 351 | | |
| | 1 | 352 | | var pageContent = await response.Content.ReadAsStringAsync(); |
| | 1 | 353 | | var document = await _browsingContext.OpenAsync(req => req.Content(pageContent)); |
| | | 354 | | |
| | | 355 | | // Find the bet form |
| | 1 | 356 | | var betForm = document.QuerySelector("form") as IHtmlFormElement; |
| | 1 | 357 | | if (betForm == null) |
| | | 358 | | { |
| | 1 | 359 | | _logger.LogWarning("Could not find betting form on the page"); |
| | 1 | 360 | | return false; |
| | | 361 | | } |
| | | 362 | | |
| | | 363 | | // Find the main content area |
| | 1 | 364 | | var contentArea = document.QuerySelector("#kicktipp-content"); |
| | 1 | 365 | | if (contentArea == null) |
| | | 366 | | { |
| | 1 | 367 | | _logger.LogWarning("Could not find content area on the betting page"); |
| | 1 | 368 | | return false; |
| | | 369 | | } |
| | | 370 | | |
| | | 371 | | // Find the table with predictions |
| | 1 | 372 | | var tbody = contentArea.QuerySelector("tbody"); |
| | 1 | 373 | | if (tbody == null) |
| | | 374 | | { |
| | 1 | 375 | | _logger.LogWarning("No betting table found"); |
| | 1 | 376 | | return false; |
| | | 377 | | } |
| | | 378 | | |
| | 1 | 379 | | var rows = tbody.QuerySelectorAll("tr"); |
| | 1 | 380 | | var formData = new List<KeyValuePair<string, string>>(); |
| | 1 | 381 | | var betsPlaced = 0; |
| | 1 | 382 | | var betsSkipped = 0; |
| | | 383 | | |
| | | 384 | | // Add hidden fields from the form |
| | 1 | 385 | | var hiddenInputs = betForm.QuerySelectorAll("input[type=hidden]").OfType<IHtmlInputElement>(); |
| | 1 | 386 | | foreach (var input in hiddenInputs) |
| | | 387 | | { |
| | 1 | 388 | | if (!string.IsNullOrEmpty(input.Name) && input.Value != null) |
| | | 389 | | { |
| | 1 | 390 | | formData.Add(new KeyValuePair<string, string>(input.Name, input.Value)); |
| | | 391 | | } |
| | | 392 | | } |
| | | 393 | | |
| | | 394 | | // Process all matches in the form |
| | 1 | 395 | | foreach (var row in rows) |
| | | 396 | | { |
| | 1 | 397 | | var cells = row.QuerySelectorAll("td"); |
| | 1 | 398 | | if (cells.Length < 4) continue; // Need at least date, home team, road team, and bet inputs |
| | | 399 | | |
| | | 400 | | try |
| | | 401 | | { |
| | 1 | 402 | | var homeTeam = cells[1].TextContent?.Trim() ?? ""; |
| | 1 | 403 | | var roadTeam = cells[2].TextContent?.Trim() ?? ""; |
| | | 404 | | |
| | 1 | 405 | | if (string.IsNullOrEmpty(homeTeam) || string.IsNullOrEmpty(roadTeam)) |
| | 1 | 406 | | continue; |
| | | 407 | | |
| | | 408 | | // Check if we have a bet for this match |
| | 1 | 409 | | var matchKey = bets.Keys.FirstOrDefault(m => m.HomeTeam == homeTeam && m.AwayTeam == roadTeam); |
| | 1 | 410 | | if (matchKey == null) |
| | | 411 | | { |
| | | 412 | | // Add existing bet values to maintain form state |
| | 1 | 413 | | var existingHomeInput = cells[3].QuerySelector("input[id$='_heimTipp']") as IHtmlInputElement; |
| | 1 | 414 | | var existingAwayInput = cells[3].QuerySelector("input[id$='_gastTipp']") as IHtmlInputElement; |
| | | 415 | | |
| | 1 | 416 | | if (existingHomeInput != null && existingAwayInput != null && |
| | 1 | 417 | | !string.IsNullOrEmpty(existingHomeInput.Name) && !string.IsNullOrEmpty(existingAwayInput.Nam |
| | | 418 | | { |
| | 1 | 419 | | formData.Add(new KeyValuePair<string, string>(existingHomeInput.Name, existingHomeInput.Valu |
| | 1 | 420 | | formData.Add(new KeyValuePair<string, string>(existingAwayInput.Name, existingAwayInput.Valu |
| | | 421 | | } |
| | 1 | 422 | | continue; |
| | | 423 | | } |
| | | 424 | | |
| | 1 | 425 | | var prediction = bets[matchKey]; |
| | | 426 | | |
| | | 427 | | // Find bet input fields in the row |
| | 1 | 428 | | var homeInput = cells[3].QuerySelector("input[id$='_heimTipp']") as IHtmlInputElement; |
| | 1 | 429 | | var awayInput = cells[3].QuerySelector("input[id$='_gastTipp']") as IHtmlInputElement; |
| | | 430 | | |
| | 1 | 431 | | if (homeInput == null || awayInput == null) |
| | | 432 | | { |
| | 1 | 433 | | _logger.LogWarning("No betting inputs found for {MatchKey}, skipping", matchKey); |
| | 1 | 434 | | continue; |
| | | 435 | | } |
| | | 436 | | |
| | | 437 | | // Check if bets are already placed |
| | 1 | 438 | | var hasExistingHomeBet = !string.IsNullOrEmpty(homeInput.Value); |
| | 1 | 439 | | var hasExistingAwayBet = !string.IsNullOrEmpty(awayInput.Value); |
| | | 440 | | |
| | 1 | 441 | | if ((hasExistingHomeBet || hasExistingAwayBet) && !overrideBets) |
| | | 442 | | { |
| | 1 | 443 | | var existingBet = $"{homeInput.Value ?? ""}:{awayInput.Value ?? ""}"; |
| | 1 | 444 | | _logger.LogInformation("{MatchKey} - skipped, already placed {ExistingBet}", matchKey, existingB |
| | 1 | 445 | | betsSkipped++; |
| | | 446 | | |
| | | 447 | | // Keep existing values |
| | 1 | 448 | | if (!string.IsNullOrEmpty(homeInput.Name) && !string.IsNullOrEmpty(awayInput.Name)) |
| | | 449 | | { |
| | 1 | 450 | | formData.Add(new KeyValuePair<string, string>(homeInput.Name, homeInput.Value ?? "")); |
| | 1 | 451 | | formData.Add(new KeyValuePair<string, string>(awayInput.Name, awayInput.Value ?? "")); |
| | | 452 | | } |
| | 1 | 453 | | continue; |
| | | 454 | | } |
| | | 455 | | |
| | | 456 | | // Add bet to form data |
| | 1 | 457 | | if (!string.IsNullOrEmpty(homeInput.Name) && !string.IsNullOrEmpty(awayInput.Name)) |
| | | 458 | | { |
| | 1 | 459 | | formData.Add(new KeyValuePair<string, string>(homeInput.Name, prediction.HomeGoals.ToString())); |
| | 1 | 460 | | formData.Add(new KeyValuePair<string, string>(awayInput.Name, prediction.AwayGoals.ToString())); |
| | 1 | 461 | | betsPlaced++; |
| | 1 | 462 | | _logger.LogInformation("{MatchKey} - betting {Prediction}", matchKey, prediction); |
| | | 463 | | } |
| | | 464 | | else |
| | | 465 | | { |
| | 0 | 466 | | _logger.LogWarning("{MatchKey} - input field names are missing, skipping", matchKey); |
| | | 467 | | continue; |
| | | 468 | | } |
| | 1 | 469 | | } |
| | 0 | 470 | | catch (Exception ex) |
| | | 471 | | { |
| | 0 | 472 | | _logger.LogError(ex, "Error processing betting row"); |
| | 0 | 473 | | continue; |
| | | 474 | | } |
| | | 475 | | } |
| | | 476 | | |
| | 1 | 477 | | _logger.LogInformation("Summary: {BetsPlaced} bets to place, {BetsSkipped} skipped", betsPlaced, betsSkipped |
| | | 478 | | |
| | 1 | 479 | | if (betsPlaced == 0) |
| | | 480 | | { |
| | 1 | 481 | | _logger.LogInformation("No bets to place"); |
| | 1 | 482 | | return true; |
| | | 483 | | } |
| | | 484 | | |
| | | 485 | | // Find submit button |
| | 1 | 486 | | var submitButton = betForm.QuerySelector("input[type=submit], button[type=submit]") as IHtmlElement; |
| | 1 | 487 | | var submitName = "submitbutton"; // Default from Python |
| | | 488 | | |
| | 1 | 489 | | if (submitButton != null) |
| | | 490 | | { |
| | 1 | 491 | | if (submitButton is IHtmlInputElement inputSubmit && !string.IsNullOrEmpty(inputSubmit.Name)) |
| | | 492 | | { |
| | 1 | 493 | | submitName = inputSubmit.Name; |
| | 1 | 494 | | formData.Add(new KeyValuePair<string, string>(submitName, inputSubmit.Value ?? "Submit")); |
| | | 495 | | } |
| | 1 | 496 | | else if (submitButton is IHtmlButtonElement buttonSubmit && !string.IsNullOrEmpty(buttonSubmit.Name)) |
| | | 497 | | { |
| | 1 | 498 | | submitName = buttonSubmit.Name; |
| | 1 | 499 | | formData.Add(new KeyValuePair<string, string>(submitName, buttonSubmit.Value ?? "Submit")); |
| | | 500 | | } |
| | | 501 | | } |
| | | 502 | | else |
| | | 503 | | { |
| | | 504 | | // Fallback to default submit button name |
| | 1 | 505 | | formData.Add(new KeyValuePair<string, string>("submitbutton", "Submit")); |
| | | 506 | | } |
| | | 507 | | |
| | | 508 | | // Submit form |
| | 1 | 509 | | var formActionUrl = string.IsNullOrEmpty(betForm.Action) ? url : |
| | 1 | 510 | | (betForm.Action.StartsWith("http") ? betForm.Action : |
| | 1 | 511 | | betForm.Action.StartsWith("/") ? betForm.Action : |
| | 1 | 512 | | $"{community}/{betForm.Action}"); |
| | | 513 | | |
| | 1 | 514 | | var formContent = new FormUrlEncodedContent(formData); |
| | 1 | 515 | | var submitResponse = await _httpClient.PostAsync(formActionUrl, formContent); |
| | | 516 | | |
| | 1 | 517 | | if (submitResponse.IsSuccessStatusCode) |
| | | 518 | | { |
| | 1 | 519 | | _logger.LogInformation("✓ Successfully submitted {BetsPlaced} bets!", betsPlaced); |
| | 1 | 520 | | return true; |
| | | 521 | | } |
| | | 522 | | else |
| | | 523 | | { |
| | 1 | 524 | | _logger.LogError("✗ Failed to submit bets. Status: {StatusCode}", submitResponse.StatusCode); |
| | 1 | 525 | | return false; |
| | | 526 | | } |
| | | 527 | | } |
| | 0 | 528 | | catch (Exception ex) |
| | | 529 | | { |
| | 0 | 530 | | _logger.LogError(ex, "Exception during bet placement"); |
| | 0 | 531 | | return false; |
| | | 532 | | } |
| | 1 | 533 | | } |
| | | 534 | | |
| | | 535 | | /// <inheritdoc /> |
| | | 536 | | public async Task<List<TeamStanding>> GetStandingsAsync(string community) |
| | | 537 | | { |
| | | 538 | | // Create cache key based on community |
| | 1 | 539 | | var cacheKey = $"standings_{community}"; |
| | | 540 | | |
| | | 541 | | // Try to get from cache first |
| | 1 | 542 | | if (_cache.TryGetValue(cacheKey, out List<TeamStanding>? cachedStandings)) |
| | | 543 | | { |
| | 1 | 544 | | _logger.LogDebug("Retrieved standings for {Community} from cache", community); |
| | 1 | 545 | | return cachedStandings!; |
| | | 546 | | } |
| | | 547 | | |
| | | 548 | | try |
| | | 549 | | { |
| | 1 | 550 | | var url = $"{community}/tabellen"; |
| | 1 | 551 | | var response = await _httpClient.GetAsync(url); |
| | | 552 | | |
| | 1 | 553 | | if (!response.IsSuccessStatusCode) |
| | | 554 | | { |
| | 1 | 555 | | _logger.LogError("Failed to fetch standings page. Status: {StatusCode}", response.StatusCode); |
| | 1 | 556 | | return new List<TeamStanding>(); |
| | | 557 | | } |
| | | 558 | | |
| | 1 | 559 | | var content = await response.Content.ReadAsStringAsync(); |
| | 1 | 560 | | var document = await _browsingContext.OpenAsync(req => req.Content(content)); |
| | | 561 | | |
| | 1 | 562 | | var standings = new List<TeamStanding>(); |
| | | 563 | | |
| | | 564 | | // Find the standings table |
| | 1 | 565 | | var standingsTable = document.QuerySelector("table.sporttabelle tbody"); |
| | 1 | 566 | | if (standingsTable == null) |
| | | 567 | | { |
| | 1 | 568 | | _logger.LogWarning("Could not find standings table"); |
| | 1 | 569 | | return standings; |
| | | 570 | | } |
| | | 571 | | |
| | 1 | 572 | | var rows = standingsTable.QuerySelectorAll("tr"); |
| | 1 | 573 | | _logger.LogDebug("Found {RowCount} team rows in standings table", rows.Length); |
| | | 574 | | |
| | 1 | 575 | | foreach (var row in rows) |
| | | 576 | | { |
| | | 577 | | try |
| | | 578 | | { |
| | 1 | 579 | | var cells = row.QuerySelectorAll("td"); |
| | 1 | 580 | | if (cells.Length >= 9) // Need at least 9 columns for all data |
| | | 581 | | { |
| | | 582 | | // Extract data from table cells |
| | 1 | 583 | | var positionText = cells[0].TextContent?.Trim().TrimEnd('.') ?? ""; |
| | 1 | 584 | | var teamNameElement = cells[1].QuerySelector("div"); |
| | 1 | 585 | | var teamName = teamNameElement?.TextContent?.Trim() ?? ""; |
| | 1 | 586 | | var gamesPlayedText = cells[2].TextContent?.Trim() ?? ""; |
| | 1 | 587 | | var pointsText = cells[3].TextContent?.Trim() ?? ""; |
| | 1 | 588 | | var goalsText = cells[4].TextContent?.Trim() ?? ""; |
| | 1 | 589 | | var goalDifferenceText = cells[5].TextContent?.Trim() ?? ""; |
| | 1 | 590 | | var winsText = cells[6].TextContent?.Trim() ?? ""; |
| | 1 | 591 | | var drawsText = cells[7].TextContent?.Trim() ?? ""; |
| | 1 | 592 | | var lossesText = cells[8].TextContent?.Trim() ?? ""; |
| | | 593 | | |
| | | 594 | | // Parse numeric values |
| | 1 | 595 | | if (int.TryParse(positionText, out var position) && |
| | 1 | 596 | | int.TryParse(gamesPlayedText, out var gamesPlayed) && |
| | 1 | 597 | | int.TryParse(pointsText, out var points) && |
| | 1 | 598 | | int.TryParse(goalDifferenceText, out var goalDifference) && |
| | 1 | 599 | | int.TryParse(winsText, out var wins) && |
| | 1 | 600 | | int.TryParse(drawsText, out var draws) && |
| | 1 | 601 | | int.TryParse(lossesText, out var losses)) |
| | | 602 | | { |
| | | 603 | | // Parse goals (format: "15:8") |
| | 1 | 604 | | var goalsParts = goalsText.Split(':'); |
| | 1 | 605 | | var goalsFor = 0; |
| | 1 | 606 | | var goalsAgainst = 0; |
| | | 607 | | |
| | 1 | 608 | | if (goalsParts.Length == 2) |
| | | 609 | | { |
| | 1 | 610 | | int.TryParse(goalsParts[0], out goalsFor); |
| | 1 | 611 | | int.TryParse(goalsParts[1], out goalsAgainst); |
| | | 612 | | } |
| | | 613 | | |
| | 1 | 614 | | var teamStanding = new TeamStanding( |
| | 1 | 615 | | position, |
| | 1 | 616 | | teamName, |
| | 1 | 617 | | gamesPlayed, |
| | 1 | 618 | | points, |
| | 1 | 619 | | goalsFor, |
| | 1 | 620 | | goalsAgainst, |
| | 1 | 621 | | goalDifference, |
| | 1 | 622 | | wins, |
| | 1 | 623 | | draws, |
| | 1 | 624 | | losses); |
| | | 625 | | |
| | 1 | 626 | | standings.Add(teamStanding); |
| | 1 | 627 | | _logger.LogDebug("Parsed team standing: {Position}. {TeamName} - {Points} points", |
| | 1 | 628 | | position, teamName, points); |
| | | 629 | | } |
| | | 630 | | else |
| | | 631 | | { |
| | 1 | 632 | | _logger.LogWarning("Failed to parse numeric values for team row"); |
| | | 633 | | } |
| | | 634 | | } |
| | 1 | 635 | | } |
| | 0 | 636 | | catch (Exception ex) |
| | | 637 | | { |
| | 0 | 638 | | _logger.LogWarning(ex, "Error parsing standings row"); |
| | 0 | 639 | | continue; |
| | | 640 | | } |
| | | 641 | | } |
| | | 642 | | |
| | 1 | 643 | | _logger.LogInformation("Successfully parsed {StandingsCount} team standings", standings.Count); |
| | | 644 | | |
| | | 645 | | // Cache the results for 20 minutes (standings change relatively infrequently) |
| | 1 | 646 | | var cacheOptions = new MemoryCacheEntryOptions |
| | 1 | 647 | | { |
| | 1 | 648 | | AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(20), |
| | 1 | 649 | | SlidingExpiration = TimeSpan.FromMinutes(10) // Reset timer if accessed within 10 minutes |
| | 1 | 650 | | }; |
| | 1 | 651 | | _cache.Set(cacheKey, standings, cacheOptions); |
| | 1 | 652 | | _logger.LogDebug("Cached standings for {Community} for 20 minutes", community); |
| | | 653 | | |
| | 1 | 654 | | return standings; |
| | | 655 | | } |
| | 0 | 656 | | catch (Exception ex) |
| | | 657 | | { |
| | 0 | 658 | | _logger.LogError(ex, "Exception in GetStandingsAsync"); |
| | 0 | 659 | | return new List<TeamStanding>(); |
| | | 660 | | } |
| | 1 | 661 | | } |
| | | 662 | | |
| | | 663 | | /// <inheritdoc /> |
| | | 664 | | public async Task<List<MatchWithHistory>> GetMatchesWithHistoryAsync(string community) |
| | | 665 | | { |
| | | 666 | | // Create cache key based on community |
| | 1 | 667 | | var cacheKey = $"matches_history_{community}"; |
| | | 668 | | |
| | | 669 | | // Try to get from cache first |
| | 1 | 670 | | if (_cache.TryGetValue(cacheKey, out List<MatchWithHistory>? cachedMatches)) |
| | | 671 | | { |
| | 1 | 672 | | _logger.LogDebug("Retrieved matches with history for {Community} from cache", community); |
| | 1 | 673 | | return cachedMatches!; |
| | | 674 | | } |
| | | 675 | | |
| | | 676 | | try |
| | | 677 | | { |
| | 1 | 678 | | var matches = new List<MatchWithHistory>(); |
| | | 679 | | |
| | | 680 | | // First, get the tippabgabe page to find the link to spielinfos |
| | 1 | 681 | | var tippabgabeUrl = $"{community}/tippabgabe"; |
| | 1 | 682 | | var response = await _httpClient.GetAsync(tippabgabeUrl); |
| | | 683 | | |
| | 1 | 684 | | if (!response.IsSuccessStatusCode) |
| | | 685 | | { |
| | 1 | 686 | | _logger.LogError("Failed to fetch tippabgabe page. Status: {StatusCode}", response.StatusCode); |
| | 1 | 687 | | return matches; |
| | | 688 | | } |
| | | 689 | | |
| | 1 | 690 | | var content = await response.Content.ReadAsStringAsync(); |
| | 1 | 691 | | var document = await _browsingContext.OpenAsync(req => req.Content(content)); |
| | | 692 | | |
| | | 693 | | // Extract matchday from the tippabgabe page |
| | 1 | 694 | | var currentMatchday = ExtractMatchdayFromPage(document); |
| | 1 | 695 | | _logger.LogDebug("Extracted matchday for history extraction: {Matchday}", currentMatchday); |
| | | 696 | | |
| | | 697 | | // Find the "Tippabgabe mit Spielinfos" link |
| | 1 | 698 | | var spielinfoLink = document.QuerySelector("a[href*='spielinfo']"); |
| | 1 | 699 | | if (spielinfoLink == null) |
| | | 700 | | { |
| | 1 | 701 | | _logger.LogWarning("Could not find Spielinfo link on tippabgabe page"); |
| | 1 | 702 | | return matches; |
| | | 703 | | } |
| | | 704 | | |
| | 1 | 705 | | var spielinfoUrl = spielinfoLink.GetAttribute("href"); |
| | 1 | 706 | | if (string.IsNullOrEmpty(spielinfoUrl)) |
| | | 707 | | { |
| | 0 | 708 | | _logger.LogWarning("Spielinfo link has no href attribute"); |
| | 0 | 709 | | return matches; |
| | | 710 | | } |
| | | 711 | | |
| | | 712 | | // Make URL absolute if it's relative |
| | 1 | 713 | | if (spielinfoUrl.StartsWith("/")) |
| | | 714 | | { |
| | 1 | 715 | | spielinfoUrl = spielinfoUrl.Substring(1); // Remove leading slash |
| | | 716 | | } |
| | | 717 | | |
| | 1 | 718 | | _logger.LogInformation("Starting to fetch match details from spielinfo pages..."); |
| | | 719 | | |
| | | 720 | | // Navigate through all matches using the right arrow navigation |
| | 1 | 721 | | var currentUrl = spielinfoUrl; |
| | 1 | 722 | | var matchCount = 0; |
| | | 723 | | |
| | 1 | 724 | | while (!string.IsNullOrEmpty(currentUrl)) |
| | | 725 | | { |
| | | 726 | | try |
| | | 727 | | { |
| | 1 | 728 | | var spielinfoResponse = await _httpClient.GetAsync(currentUrl); |
| | 1 | 729 | | if (!spielinfoResponse.IsSuccessStatusCode) |
| | | 730 | | { |
| | 1 | 731 | | _logger.LogWarning("Failed to fetch spielinfo page: {Url}. Status: {StatusCode}", currentUrl, sp |
| | 1 | 732 | | break; |
| | | 733 | | } |
| | | 734 | | |
| | 1 | 735 | | var spielinfoContent = await spielinfoResponse.Content.ReadAsStringAsync(); |
| | 1 | 736 | | var spielinfoDocument = await _browsingContext.OpenAsync(req => req.Content(spielinfoContent)); |
| | | 737 | | |
| | | 738 | | // Extract match information |
| | 1 | 739 | | var matchWithHistory = ExtractMatchWithHistoryFromSpielinfoPage(spielinfoDocument, currentMatchday); |
| | 1 | 740 | | if (matchWithHistory != null) |
| | | 741 | | { |
| | 1 | 742 | | matches.Add(matchWithHistory); |
| | 1 | 743 | | matchCount++; |
| | 1 | 744 | | _logger.LogDebug("Extracted match {Count}: {Match}", matchCount, matchWithHistory.Match); |
| | | 745 | | } |
| | | 746 | | |
| | | 747 | | // Find the next match link (right arrow) |
| | 1 | 748 | | var nextLink = FindNextMatchLink(spielinfoDocument); |
| | 1 | 749 | | if (nextLink != null) |
| | | 750 | | { |
| | 1 | 751 | | currentUrl = nextLink; |
| | 1 | 752 | | if (currentUrl.StartsWith("/")) |
| | | 753 | | { |
| | 1 | 754 | | currentUrl = currentUrl.Substring(1); // Remove leading slash |
| | | 755 | | } |
| | | 756 | | } |
| | | 757 | | else |
| | | 758 | | { |
| | | 759 | | // No more matches |
| | 1 | 760 | | break; |
| | | 761 | | } |
| | 1 | 762 | | } |
| | 0 | 763 | | catch (Exception ex) |
| | | 764 | | { |
| | 0 | 765 | | _logger.LogError(ex, "Error processing spielinfo page: {Url}", currentUrl); |
| | 0 | 766 | | break; |
| | | 767 | | } |
| | | 768 | | } |
| | | 769 | | |
| | 1 | 770 | | _logger.LogInformation("Successfully extracted {MatchCount} matches with history", matches.Count); |
| | | 771 | | |
| | | 772 | | // Cache the results for 15 minutes (match info changes less frequently than live scores) |
| | 1 | 773 | | var cacheOptions = new MemoryCacheEntryOptions |
| | 1 | 774 | | { |
| | 1 | 775 | | AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15), |
| | 1 | 776 | | SlidingExpiration = TimeSpan.FromMinutes(7) // Reset timer if accessed within 7 minutes |
| | 1 | 777 | | }; |
| | 1 | 778 | | _cache.Set(cacheKey, matches, cacheOptions); |
| | 1 | 779 | | _logger.LogDebug("Cached matches with history for {Community} for 15 minutes", community); |
| | | 780 | | |
| | 1 | 781 | | return matches; |
| | | 782 | | } |
| | 0 | 783 | | catch (Exception ex) |
| | | 784 | | { |
| | 0 | 785 | | _logger.LogError(ex, "Exception in GetMatchesWithHistoryAsync"); |
| | 0 | 786 | | return new List<MatchWithHistory>(); |
| | | 787 | | } |
| | 1 | 788 | | } |
| | | 789 | | |
| | | 790 | | /// <inheritdoc /> |
| | | 791 | | public async Task<(List<MatchResult> homeTeamHomeHistory, List<MatchResult> awayTeamAwayHistory)> GetHomeAwayHistory |
| | | 792 | | { |
| | | 793 | | try |
| | | 794 | | { |
| | | 795 | | // First, get the tippabgabe page to find the link to spielinfos |
| | 1 | 796 | | var tippabgabeUrl = $"{community}/tippabgabe"; |
| | 1 | 797 | | var response = await _httpClient.GetAsync(tippabgabeUrl); |
| | | 798 | | |
| | 1 | 799 | | if (!response.IsSuccessStatusCode) |
| | | 800 | | { |
| | 1 | 801 | | _logger.LogError("Failed to fetch tippabgabe page. Status: {StatusCode}", response.StatusCode); |
| | 1 | 802 | | return (new List<MatchResult>(), new List<MatchResult>()); |
| | | 803 | | } |
| | | 804 | | |
| | 1 | 805 | | var content = await response.Content.ReadAsStringAsync(); |
| | 1 | 806 | | var document = await _browsingContext.OpenAsync(req => req.Content(content)); |
| | | 807 | | |
| | | 808 | | // Find the "Tippabgabe mit Spielinfos" link |
| | 1 | 809 | | var spielinfoLink = document.QuerySelector("a[href*='spielinfo']"); |
| | 1 | 810 | | if (spielinfoLink == null) |
| | | 811 | | { |
| | 1 | 812 | | _logger.LogWarning("Could not find Spielinfo link on tippabgabe page"); |
| | 1 | 813 | | return (new List<MatchResult>(), new List<MatchResult>()); |
| | | 814 | | } |
| | | 815 | | |
| | 1 | 816 | | var spielinfoUrl = spielinfoLink.GetAttribute("href"); |
| | 1 | 817 | | if (string.IsNullOrEmpty(spielinfoUrl)) |
| | | 818 | | { |
| | 0 | 819 | | _logger.LogWarning("Spielinfo link has no href attribute"); |
| | 0 | 820 | | return (new List<MatchResult>(), new List<MatchResult>()); |
| | | 821 | | } |
| | | 822 | | |
| | | 823 | | // Make URL absolute if it's relative |
| | 1 | 824 | | if (spielinfoUrl.StartsWith("/")) |
| | | 825 | | { |
| | 1 | 826 | | spielinfoUrl = spielinfoUrl.Substring(1); // Remove leading slash |
| | | 827 | | } |
| | | 828 | | |
| | | 829 | | // Navigate through all matches using the right arrow navigation |
| | 1 | 830 | | var currentUrl = spielinfoUrl; |
| | | 831 | | |
| | 1 | 832 | | while (!string.IsNullOrEmpty(currentUrl)) |
| | | 833 | | { |
| | | 834 | | try |
| | | 835 | | { |
| | | 836 | | // Add ansicht=2 parameter for home/away history |
| | 1 | 837 | | var homeAwayUrl = currentUrl.Contains('?') |
| | 1 | 838 | | ? $"{currentUrl}&ansicht=2" |
| | 1 | 839 | | : $"{currentUrl}?ansicht=2"; |
| | | 840 | | |
| | 1 | 841 | | var spielinfoResponse = await _httpClient.GetAsync(homeAwayUrl); |
| | 1 | 842 | | if (!spielinfoResponse.IsSuccessStatusCode) |
| | | 843 | | { |
| | 1 | 844 | | _logger.LogWarning("Failed to fetch spielinfo page: {Url}. Status: {StatusCode}", homeAwayUrl, s |
| | 1 | 845 | | break; |
| | | 846 | | } |
| | | 847 | | |
| | 1 | 848 | | var spielinfoContent = await spielinfoResponse.Content.ReadAsStringAsync(); |
| | 1 | 849 | | var spielinfoDocument = await _browsingContext.OpenAsync(req => req.Content(spielinfoContent)); |
| | | 850 | | |
| | | 851 | | // Check if this page contains our match |
| | 1 | 852 | | if (IsMatchOnPage(spielinfoDocument, homeTeam, awayTeam)) |
| | | 853 | | { |
| | | 854 | | // Extract home team home history |
| | 1 | 855 | | var homeTeamHomeHistory = ExtractTeamHistory(spielinfoDocument, "spielinfoHeim"); |
| | | 856 | | |
| | | 857 | | // Extract away team away history |
| | 1 | 858 | | var awayTeamAwayHistory = ExtractTeamHistory(spielinfoDocument, "spielinfoGast"); |
| | | 859 | | |
| | 1 | 860 | | return (homeTeamHomeHistory, awayTeamAwayHistory); |
| | | 861 | | } |
| | | 862 | | |
| | | 863 | | // Find the next match link (right arrow) |
| | 1 | 864 | | var nextLink = FindNextMatchLink(spielinfoDocument); |
| | 1 | 865 | | if (nextLink != null) |
| | | 866 | | { |
| | 1 | 867 | | currentUrl = nextLink; |
| | 1 | 868 | | if (currentUrl.StartsWith("/")) |
| | | 869 | | { |
| | 1 | 870 | | currentUrl = currentUrl.Substring(1); // Remove leading slash |
| | | 871 | | } |
| | | 872 | | } |
| | | 873 | | else |
| | | 874 | | { |
| | | 875 | | // No more matches |
| | 1 | 876 | | break; |
| | | 877 | | } |
| | 1 | 878 | | } |
| | 0 | 879 | | catch (Exception ex) |
| | | 880 | | { |
| | 0 | 881 | | _logger.LogError(ex, "Error processing spielinfo page for home/away history: {CurrentUrl}", currentU |
| | 0 | 882 | | break; |
| | | 883 | | } |
| | | 884 | | } |
| | | 885 | | |
| | 1 | 886 | | _logger.LogWarning("Could not find match {HomeTeam} vs {AwayTeam} in spielinfo pages", homeTeam, awayTeam); |
| | 1 | 887 | | return (new List<MatchResult>(), new List<MatchResult>()); |
| | | 888 | | } |
| | 0 | 889 | | catch (Exception ex) |
| | | 890 | | { |
| | 0 | 891 | | _logger.LogError(ex, "Exception in GetHomeAwayHistoryAsync for {HomeTeam} vs {AwayTeam}", homeTeam, awayTeam |
| | 0 | 892 | | return (new List<MatchResult>(), new List<MatchResult>()); |
| | | 893 | | } |
| | 1 | 894 | | } |
| | | 895 | | |
| | | 896 | | /// <inheritdoc /> |
| | | 897 | | public async Task<List<MatchResult>> GetHeadToHeadHistoryAsync(string community, string homeTeam, string awayTeam) |
| | | 898 | | { |
| | | 899 | | try |
| | | 900 | | { |
| | | 901 | | // First, get the tippabgabe page to find the link to spielinfos |
| | 1 | 902 | | var tippabgabeUrl = $"{community}/tippabgabe"; |
| | 1 | 903 | | var response = await _httpClient.GetAsync(tippabgabeUrl); |
| | | 904 | | |
| | 1 | 905 | | if (!response.IsSuccessStatusCode) |
| | | 906 | | { |
| | 1 | 907 | | _logger.LogError("Failed to fetch tippabgabe page. Status: {StatusCode}", response.StatusCode); |
| | 1 | 908 | | return new List<MatchResult>(); |
| | | 909 | | } |
| | | 910 | | |
| | 1 | 911 | | var content = await response.Content.ReadAsStringAsync(); |
| | 1 | 912 | | var document = await _browsingContext.OpenAsync(req => req.Content(content)); |
| | | 913 | | |
| | | 914 | | // Find the "Tippabgabe mit Spielinfos" link |
| | 1 | 915 | | var spielinfoLink = document.QuerySelector("a[href*='spielinfo']"); |
| | 1 | 916 | | if (spielinfoLink == null) |
| | | 917 | | { |
| | 1 | 918 | | _logger.LogWarning("Could not find Spielinfo link on tippabgabe page"); |
| | 1 | 919 | | return new List<MatchResult>(); |
| | | 920 | | } |
| | | 921 | | |
| | 1 | 922 | | var spielinfoUrl = spielinfoLink.GetAttribute("href"); |
| | 1 | 923 | | if (string.IsNullOrEmpty(spielinfoUrl)) |
| | | 924 | | { |
| | 0 | 925 | | _logger.LogWarning("Spielinfo link has no href attribute"); |
| | 0 | 926 | | return new List<MatchResult>(); |
| | | 927 | | } |
| | | 928 | | |
| | | 929 | | // Make URL absolute if it's relative |
| | 1 | 930 | | if (spielinfoUrl.StartsWith("/")) |
| | | 931 | | { |
| | 1 | 932 | | spielinfoUrl = spielinfoUrl.Substring(1); // Remove leading slash |
| | | 933 | | } |
| | | 934 | | |
| | | 935 | | // Navigate through all matches using the right arrow navigation |
| | 1 | 936 | | var currentUrl = spielinfoUrl; |
| | | 937 | | |
| | 1 | 938 | | while (!string.IsNullOrEmpty(currentUrl)) |
| | | 939 | | { |
| | | 940 | | try |
| | | 941 | | { |
| | | 942 | | // Add ansicht=3 parameter for head-to-head history |
| | 1 | 943 | | var headToHeadUrl = currentUrl.Contains('?') |
| | 1 | 944 | | ? $"{currentUrl}&ansicht=3" |
| | 1 | 945 | | : $"{currentUrl}?ansicht=3"; |
| | | 946 | | |
| | 1 | 947 | | var spielinfoResponse = await _httpClient.GetAsync(headToHeadUrl); |
| | 1 | 948 | | if (!spielinfoResponse.IsSuccessStatusCode) |
| | | 949 | | { |
| | 1 | 950 | | _logger.LogWarning("Failed to fetch spielinfo page: {Url}. Status: {StatusCode}", headToHeadUrl, |
| | 1 | 951 | | break; |
| | | 952 | | } |
| | | 953 | | |
| | 1 | 954 | | var spielinfoContent = await spielinfoResponse.Content.ReadAsStringAsync(); |
| | 1 | 955 | | var spielinfoDocument = await _browsingContext.OpenAsync(req => req.Content(spielinfoContent)); |
| | | 956 | | |
| | | 957 | | // Check if this page contains our match |
| | 1 | 958 | | if (IsMatchOnPage(spielinfoDocument, homeTeam, awayTeam)) |
| | | 959 | | { |
| | | 960 | | // Extract head-to-head history |
| | 1 | 961 | | return ExtractTeamHistory(spielinfoDocument, "spielinfoDirekterVergleich"); |
| | | 962 | | } |
| | | 963 | | |
| | | 964 | | // Find the next match link (right arrow) |
| | 1 | 965 | | var nextLink = FindNextMatchLink(spielinfoDocument); |
| | 1 | 966 | | if (nextLink != null) |
| | | 967 | | { |
| | 1 | 968 | | currentUrl = nextLink; |
| | 1 | 969 | | if (currentUrl.StartsWith("/")) |
| | | 970 | | { |
| | 1 | 971 | | currentUrl = currentUrl.Substring(1); // Remove leading slash |
| | | 972 | | } |
| | | 973 | | } |
| | | 974 | | else |
| | | 975 | | { |
| | | 976 | | // No more matches |
| | 1 | 977 | | break; |
| | | 978 | | } |
| | 1 | 979 | | } |
| | 0 | 980 | | catch (Exception ex) |
| | | 981 | | { |
| | 0 | 982 | | _logger.LogError(ex, "Error processing spielinfo page for head-to-head history: {CurrentUrl}", curre |
| | 0 | 983 | | break; |
| | | 984 | | } |
| | | 985 | | } |
| | | 986 | | |
| | 1 | 987 | | _logger.LogWarning("Could not find match {HomeTeam} vs {AwayTeam} in spielinfo pages", homeTeam, awayTeam); |
| | 1 | 988 | | return new List<MatchResult>(); |
| | | 989 | | } |
| | 0 | 990 | | catch (Exception ex) |
| | | 991 | | { |
| | 0 | 992 | | _logger.LogError(ex, "Exception in GetHeadToHeadHistoryAsync for {HomeTeam} vs {AwayTeam}", homeTeam, awayTe |
| | 0 | 993 | | return new List<MatchResult>(); |
| | | 994 | | } |
| | 1 | 995 | | } |
| | | 996 | | |
| | | 997 | | /// <inheritdoc /> |
| | | 998 | | public async Task<List<HeadToHeadResult>> GetHeadToHeadDetailedHistoryAsync(string community, string homeTeam, strin |
| | | 999 | | { |
| | | 1000 | | try |
| | | 1001 | | { |
| | | 1002 | | // First, get the tippabgabe page to find the link to spielinfos |
| | 1 | 1003 | | var tippabgabeUrl = $"{community}/tippabgabe"; |
| | 1 | 1004 | | var response = await _httpClient.GetAsync(tippabgabeUrl); |
| | | 1005 | | |
| | 1 | 1006 | | if (!response.IsSuccessStatusCode) |
| | | 1007 | | { |
| | 1 | 1008 | | _logger.LogError("Failed to fetch tippabgabe page. Status: {StatusCode}", response.StatusCode); |
| | 1 | 1009 | | return new List<HeadToHeadResult>(); |
| | | 1010 | | } |
| | | 1011 | | |
| | 1 | 1012 | | var content = await response.Content.ReadAsStringAsync(); |
| | 1 | 1013 | | var document = await _browsingContext.OpenAsync(req => req.Content(content)); |
| | | 1014 | | |
| | | 1015 | | // Find the "Tippabgabe mit Spielinfos" link |
| | 1 | 1016 | | var spielinfoLink = document.QuerySelector("a[href*='spielinfo']"); |
| | 1 | 1017 | | if (spielinfoLink == null) |
| | | 1018 | | { |
| | 1 | 1019 | | _logger.LogWarning("Could not find Spielinfo link on tippabgabe page"); |
| | 1 | 1020 | | return new List<HeadToHeadResult>(); |
| | | 1021 | | } |
| | | 1022 | | |
| | 1 | 1023 | | var spielinfoUrl = spielinfoLink.GetAttribute("href"); |
| | 1 | 1024 | | if (string.IsNullOrEmpty(spielinfoUrl)) |
| | | 1025 | | { |
| | 0 | 1026 | | _logger.LogWarning("Spielinfo link has no href attribute"); |
| | 0 | 1027 | | return new List<HeadToHeadResult>(); |
| | | 1028 | | } |
| | | 1029 | | |
| | | 1030 | | // Make URL absolute if it's relative |
| | 1 | 1031 | | if (spielinfoUrl.StartsWith("/")) |
| | | 1032 | | { |
| | 1 | 1033 | | spielinfoUrl = spielinfoUrl.Substring(1); // Remove leading slash |
| | | 1034 | | } |
| | | 1035 | | |
| | | 1036 | | // Navigate through all matches using the right arrow navigation |
| | 1 | 1037 | | var currentUrl = spielinfoUrl; |
| | | 1038 | | |
| | 1 | 1039 | | while (!string.IsNullOrEmpty(currentUrl)) |
| | | 1040 | | { |
| | | 1041 | | try |
| | | 1042 | | { |
| | | 1043 | | // Append ansicht=3 to get head-to-head view |
| | 1 | 1044 | | var urlWithAnsicht = currentUrl.Contains('?') ? $"{currentUrl}&ansicht=3" : $"{currentUrl}?ansicht=3 |
| | 1 | 1045 | | var spielinfoResponse = await _httpClient.GetAsync(urlWithAnsicht); |
| | | 1046 | | |
| | 1 | 1047 | | if (!spielinfoResponse.IsSuccessStatusCode) |
| | | 1048 | | { |
| | 1 | 1049 | | _logger.LogWarning("Failed to fetch spielinfo page: {Url}. Status: {StatusCode}", urlWithAnsicht |
| | 1 | 1050 | | break; |
| | | 1051 | | } |
| | | 1052 | | |
| | 1 | 1053 | | var spielinfoContent = await spielinfoResponse.Content.ReadAsStringAsync(); |
| | 1 | 1054 | | var spielinfoDocument = await _browsingContext.OpenAsync(req => req.Content(spielinfoContent)); |
| | | 1055 | | |
| | | 1056 | | // Check if this page contains our match |
| | 1 | 1057 | | if (IsMatchOnPage(spielinfoDocument, homeTeam, awayTeam)) |
| | | 1058 | | { |
| | | 1059 | | // Extract head-to-head history from this page |
| | 1 | 1060 | | return ExtractHeadToHeadHistory(spielinfoDocument); |
| | | 1061 | | } |
| | | 1062 | | |
| | | 1063 | | // Find the next match link (right arrow) |
| | 1 | 1064 | | var nextLink = FindNextMatchLink(spielinfoDocument); |
| | 1 | 1065 | | if (nextLink != null) |
| | | 1066 | | { |
| | 1 | 1067 | | currentUrl = nextLink; |
| | 1 | 1068 | | if (currentUrl.StartsWith("/")) |
| | | 1069 | | { |
| | 1 | 1070 | | currentUrl = currentUrl.Substring(1); // Remove leading slash |
| | | 1071 | | } |
| | | 1072 | | } |
| | | 1073 | | else |
| | | 1074 | | { |
| | 1 | 1075 | | break; |
| | | 1076 | | } |
| | 1 | 1077 | | } |
| | 0 | 1078 | | catch (Exception ex) |
| | | 1079 | | { |
| | 0 | 1080 | | _logger.LogWarning(ex, "Error processing spielinfo page: {Url}", currentUrl); |
| | 0 | 1081 | | break; |
| | | 1082 | | } |
| | | 1083 | | } |
| | | 1084 | | |
| | 1 | 1085 | | _logger.LogWarning("Could not find match {HomeTeam} vs {AwayTeam} in spielinfo pages", homeTeam, awayTeam); |
| | 1 | 1086 | | return new List<HeadToHeadResult>(); |
| | | 1087 | | } |
| | 0 | 1088 | | catch (Exception ex) |
| | | 1089 | | { |
| | 0 | 1090 | | _logger.LogError(ex, "Exception in GetHeadToHeadDetailedHistoryAsync for {HomeTeam} vs {AwayTeam}", homeTeam |
| | 0 | 1091 | | return new List<HeadToHeadResult>(); |
| | | 1092 | | } |
| | 1 | 1093 | | } |
| | | 1094 | | private bool IsMatchOnPage(IDocument document, string homeTeam, string awayTeam) |
| | | 1095 | | { |
| | | 1096 | | try |
| | | 1097 | | { |
| | | 1098 | | // Look for the match in the tippabgabe table |
| | 1 | 1099 | | var matchRows = document.QuerySelectorAll("table.tippabgabe tbody tr"); |
| | | 1100 | | |
| | 1 | 1101 | | foreach (var row in matchRows) |
| | | 1102 | | { |
| | 1 | 1103 | | var cells = row.QuerySelectorAll("td"); |
| | 1 | 1104 | | if (cells.Length >= 3) |
| | | 1105 | | { |
| | 1 | 1106 | | var pageHomeTeam = cells[1].TextContent?.Trim() ?? ""; |
| | 1 | 1107 | | var pageAwayTeam = cells[2].TextContent?.Trim() ?? ""; |
| | | 1108 | | |
| | 1 | 1109 | | if (pageHomeTeam == homeTeam && pageAwayTeam == awayTeam) |
| | | 1110 | | { |
| | 1 | 1111 | | return true; |
| | | 1112 | | } |
| | | 1113 | | } |
| | | 1114 | | } |
| | | 1115 | | |
| | 1 | 1116 | | return false; |
| | | 1117 | | } |
| | 0 | 1118 | | catch (Exception ex) |
| | | 1119 | | { |
| | 0 | 1120 | | _logger.LogDebug(ex, "Error checking if match is on page"); |
| | 0 | 1121 | | return false; |
| | | 1122 | | } |
| | 1 | 1123 | | } |
| | | 1124 | | |
| | | 1125 | | private MatchWithHistory? ExtractMatchWithHistoryFromSpielinfoPage(IDocument document, int matchday) |
| | | 1126 | | { |
| | | 1127 | | try |
| | | 1128 | | { |
| | | 1129 | | // Extract match information from the tippabgabe table |
| | | 1130 | | // Look for all rows in the table, not just the first one |
| | 1 | 1131 | | var matchRows = document.QuerySelectorAll("table.tippabgabe tbody tr"); |
| | 1 | 1132 | | if (matchRows.Length == 0) |
| | | 1133 | | { |
| | 0 | 1134 | | _logger.LogWarning("Could not find any match rows in tippabgabe table on spielinfo page"); |
| | 0 | 1135 | | return null; |
| | | 1136 | | } |
| | | 1137 | | |
| | 1 | 1138 | | _logger.LogDebug("Found {RowCount} rows in tippabgabe table", matchRows.Length); |
| | | 1139 | | |
| | | 1140 | | // Find the row that contains match data (has input fields for betting) |
| | 1 | 1141 | | IElement? matchRow = null; |
| | 1 | 1142 | | foreach (var row in matchRows) |
| | | 1143 | | { |
| | 1 | 1144 | | var rowCells = row.QuerySelectorAll("td"); |
| | 1 | 1145 | | if (rowCells.Length >= 4) |
| | | 1146 | | { |
| | | 1147 | | // Check if this row has betting inputs (indicates it's the match row) |
| | 1 | 1148 | | var bettingInputs = rowCells[3].QuerySelectorAll("input[type='text']"); |
| | 1 | 1149 | | if (bettingInputs.Length >= 2) |
| | | 1150 | | { |
| | 1 | 1151 | | matchRow = row; |
| | 1 | 1152 | | break; |
| | | 1153 | | } |
| | | 1154 | | } |
| | | 1155 | | } |
| | | 1156 | | |
| | 1 | 1157 | | if (matchRow == null) |
| | | 1158 | | { |
| | 1 | 1159 | | _logger.LogWarning("Could not find match row with betting inputs in tippabgabe table"); |
| | 1 | 1160 | | return null; |
| | | 1161 | | } |
| | | 1162 | | |
| | 1 | 1163 | | var cells = matchRow.QuerySelectorAll("td"); |
| | 1 | 1164 | | if (cells.Length < 4) |
| | | 1165 | | { |
| | 0 | 1166 | | _logger.LogWarning("Match row does not have enough cells"); |
| | 0 | 1167 | | return null; |
| | | 1168 | | } |
| | | 1169 | | |
| | 1 | 1170 | | _logger.LogDebug("Found {CellCount} cells in match row", cells.Length); |
| | 1 | 1171 | | for (int i = 0; i < Math.Min(cells.Length, 5); i++) |
| | | 1172 | | { |
| | 1 | 1173 | | _logger.LogDebug("Cell[{Index}]: '{Content}' (Class: '{Class}')", i, cells[i].TextContent?.Trim(), cells |
| | | 1174 | | } |
| | | 1175 | | |
| | 1 | 1176 | | var timeText = cells[0].TextContent?.Trim() ?? ""; |
| | 1 | 1177 | | var homeTeam = cells[1].TextContent?.Trim() ?? ""; |
| | 1 | 1178 | | var awayTeam = cells[2].TextContent?.Trim() ?? ""; |
| | | 1179 | | |
| | 1 | 1180 | | _logger.LogDebug("Extracted from spielinfo page - Time: '{TimeText}', Home: '{HomeTeam}', Away: '{AwayTeam}' |
| | | 1181 | | |
| | 1 | 1182 | | if (string.IsNullOrEmpty(homeTeam) || string.IsNullOrEmpty(awayTeam)) |
| | | 1183 | | { |
| | 0 | 1184 | | _logger.LogWarning("Could not extract team names from match table"); |
| | 0 | 1185 | | return null; |
| | | 1186 | | } |
| | | 1187 | | |
| | | 1188 | | // Check if match is cancelled ("Abgesagt" in German) |
| | | 1189 | | // Note: On spielinfo pages, cancelled matches may still show - process them with IsCancelled flag |
| | 1 | 1190 | | var isCancelled = IsCancelledTimeText(timeText); |
| | 1 | 1191 | | if (isCancelled) |
| | | 1192 | | { |
| | 0 | 1193 | | _logger.LogWarning( |
| | 0 | 1194 | | "Match {HomeTeam} vs {AwayTeam} is cancelled (Abgesagt) on spielinfo page. " + |
| | 0 | 1195 | | "Using current time as fallback since spielinfo doesn't provide time inheritance context.", |
| | 0 | 1196 | | homeTeam, awayTeam); |
| | | 1197 | | } |
| | | 1198 | | |
| | 1 | 1199 | | var startsAt = ParseMatchDateTime(timeText); |
| | 1 | 1200 | | var match = new Match(homeTeam, awayTeam, startsAt, matchday, isCancelled); |
| | | 1201 | | |
| | | 1202 | | // Extract home team history |
| | 1 | 1203 | | var homeTeamHistory = ExtractTeamHistory(document, "spielinfoHeim"); |
| | | 1204 | | |
| | | 1205 | | // Extract away team history |
| | 1 | 1206 | | var awayTeamHistory = ExtractTeamHistory(document, "spielinfoGast"); |
| | | 1207 | | |
| | 1 | 1208 | | return new MatchWithHistory(match, homeTeamHistory, awayTeamHistory); |
| | | 1209 | | } |
| | 0 | 1210 | | catch (Exception ex) |
| | | 1211 | | { |
| | 0 | 1212 | | _logger.LogError(ex, "Error extracting match with history from spielinfo page"); |
| | 0 | 1213 | | return null; |
| | | 1214 | | } |
| | 1 | 1215 | | } |
| | | 1216 | | |
| | | 1217 | | private List<MatchResult> ExtractTeamHistory(IDocument document, string tableClass) |
| | | 1218 | | { |
| | 1 | 1219 | | var results = new List<MatchResult>(); |
| | | 1220 | | |
| | | 1221 | | try |
| | | 1222 | | { |
| | 1 | 1223 | | var table = document.QuerySelector($"table.{tableClass} tbody"); |
| | 1 | 1224 | | if (table == null) |
| | | 1225 | | { |
| | 0 | 1226 | | _logger.LogDebug("Could not find team history table with class: {TableClass}", tableClass); |
| | 0 | 1227 | | return results; |
| | | 1228 | | } |
| | | 1229 | | |
| | 1 | 1230 | | var rows = table.QuerySelectorAll("tr"); |
| | 1 | 1231 | | foreach (var row in rows) |
| | | 1232 | | { |
| | | 1233 | | try |
| | | 1234 | | { |
| | 1 | 1235 | | var cells = row.QuerySelectorAll("td"); |
| | | 1236 | | |
| | | 1237 | | // Handle different table formats |
| | | 1238 | | string competition, homeTeam, awayTeam; |
| | 1 | 1239 | | var resultCell = cells.Last(); // Result is always in the last cell |
| | 1 | 1240 | | var homeGoals = (int?)null; |
| | 1 | 1241 | | var awayGoals = (int?)null; |
| | 1 | 1242 | | var outcome = MatchOutcome.Pending; |
| | 1 | 1243 | | string? annotation = null; |
| | | 1244 | | |
| | 1 | 1245 | | if (tableClass == "spielinfoDirekterVergleich") |
| | | 1246 | | { |
| | | 1247 | | // Direct comparison format: Season | Matchday | Date | Home | Away | Result |
| | 1 | 1248 | | if (cells.Length < 6) |
| | 0 | 1249 | | continue; |
| | | 1250 | | |
| | 1 | 1251 | | competition = $"{cells[0].TextContent?.Trim()} {cells[1].TextContent?.Trim()}"; |
| | 1 | 1252 | | homeTeam = cells[3].TextContent?.Trim() ?? ""; |
| | 1 | 1253 | | awayTeam = cells[4].TextContent?.Trim() ?? ""; |
| | | 1254 | | } |
| | | 1255 | | else |
| | | 1256 | | { |
| | | 1257 | | // Standard format: Competition | Home | Away | Result |
| | 1 | 1258 | | if (cells.Length < 4) |
| | 0 | 1259 | | continue; |
| | | 1260 | | |
| | 1 | 1261 | | competition = cells[0].TextContent?.Trim() ?? ""; |
| | 1 | 1262 | | homeTeam = cells[1].TextContent?.Trim() ?? ""; |
| | 1 | 1263 | | awayTeam = cells[2].TextContent?.Trim() ?? ""; |
| | | 1264 | | } |
| | | 1265 | | |
| | | 1266 | | // Parse the score from the result cell |
| | 1 | 1267 | | var scoreElements = resultCell.QuerySelectorAll(".kicktipp-heim, .kicktipp-gast"); |
| | 1 | 1268 | | if (scoreElements.Length >= 2) |
| | | 1269 | | { |
| | 1 | 1270 | | var homeScoreText = scoreElements[0].TextContent?.Trim() ?? ""; |
| | 1 | 1271 | | var awayScoreText = scoreElements[1].TextContent?.Trim() ?? ""; |
| | | 1272 | | |
| | 1 | 1273 | | if (homeScoreText != "-" && awayScoreText != "-") |
| | | 1274 | | { |
| | 1 | 1275 | | if (int.TryParse(homeScoreText, out var homeScore) && int.TryParse(awayScoreText, out var aw |
| | | 1276 | | { |
| | 1 | 1277 | | homeGoals = homeScore; |
| | 1 | 1278 | | awayGoals = awayScore; |
| | | 1279 | | |
| | | 1280 | | // Determine outcome from team's perspective based on CSS classes |
| | 1 | 1281 | | var homeTeamCell = tableClass == "spielinfoDirekterVergleich" ? cells[3] : cells[1]; |
| | 1 | 1282 | | var awayTeamCell = tableClass == "spielinfoDirekterVergleich" ? cells[4] : cells[2]; |
| | | 1283 | | |
| | 1 | 1284 | | var isHomeTeam = homeTeamCell.ClassList.Contains("sieg") || homeTeamCell.ClassList.Conta |
| | 1 | 1285 | | var isAwayTeam = awayTeamCell.ClassList.Contains("sieg") || awayTeamCell.ClassList.Conta |
| | | 1286 | | |
| | 1 | 1287 | | if (isHomeTeam) |
| | | 1288 | | { |
| | 1 | 1289 | | outcome = homeScore > awayScore ? MatchOutcome.Win : |
| | 1 | 1290 | | homeScore < awayScore ? MatchOutcome.Loss : MatchOutcome.Draw; |
| | | 1291 | | } |
| | 1 | 1292 | | else if (isAwayTeam) |
| | | 1293 | | { |
| | 1 | 1294 | | outcome = awayScore > homeScore ? MatchOutcome.Win : |
| | 1 | 1295 | | awayScore < homeScore ? MatchOutcome.Loss : MatchOutcome.Draw; |
| | | 1296 | | } |
| | | 1297 | | else |
| | | 1298 | | { |
| | | 1299 | | // Fallback: determine from score (neutral perspective) |
| | 1 | 1300 | | outcome = homeScore == awayScore ? MatchOutcome.Draw : |
| | 1 | 1301 | | homeScore > awayScore ? MatchOutcome.Win : MatchOutcome.Loss; |
| | | 1302 | | } |
| | | 1303 | | } |
| | | 1304 | | } |
| | | 1305 | | } |
| | | 1306 | | |
| | | 1307 | | // Extract annotation if present (e.g., "n.E." for penalty shootout) |
| | 1 | 1308 | | var annotationElement = resultCell.QuerySelector(".kicktipp-zusatz"); |
| | 1 | 1309 | | if (annotationElement != null) |
| | | 1310 | | { |
| | 1 | 1311 | | annotation = ExpandAnnotation(annotationElement.TextContent?.Trim()); |
| | | 1312 | | } |
| | | 1313 | | |
| | 1 | 1314 | | var matchResult = new MatchResult(competition, homeTeam, awayTeam, homeGoals, awayGoals, outcome, an |
| | 1 | 1315 | | results.Add(matchResult); |
| | 1 | 1316 | | } |
| | 0 | 1317 | | catch (Exception ex) |
| | | 1318 | | { |
| | 0 | 1319 | | _logger.LogDebug(ex, "Error parsing team history row"); |
| | 0 | 1320 | | continue; |
| | | 1321 | | } |
| | | 1322 | | } |
| | 1 | 1323 | | } |
| | 0 | 1324 | | catch (Exception ex) |
| | | 1325 | | { |
| | 0 | 1326 | | _logger.LogError(ex, "Error extracting team history for table class: {TableClass}", tableClass); |
| | 0 | 1327 | | } |
| | | 1328 | | |
| | 1 | 1329 | | return results; |
| | 0 | 1330 | | } |
| | | 1331 | | |
| | | 1332 | | private List<HeadToHeadResult> ExtractHeadToHeadHistory(IDocument document) |
| | | 1333 | | { |
| | 1 | 1334 | | var results = new List<HeadToHeadResult>(); |
| | | 1335 | | |
| | | 1336 | | try |
| | | 1337 | | { |
| | 1 | 1338 | | var table = document.QuerySelector("table.spielinfoDirekterVergleich tbody"); |
| | 1 | 1339 | | if (table == null) |
| | | 1340 | | { |
| | 0 | 1341 | | _logger.LogDebug("Could not find head-to-head table with class: spielinfoDirekterVergleich"); |
| | 0 | 1342 | | return results; |
| | | 1343 | | } |
| | | 1344 | | |
| | 1 | 1345 | | var rows = table.QuerySelectorAll("tr"); |
| | 1 | 1346 | | foreach (var row in rows) |
| | | 1347 | | { |
| | | 1348 | | try |
| | | 1349 | | { |
| | 1 | 1350 | | var cells = row.QuerySelectorAll("td"); |
| | | 1351 | | |
| | | 1352 | | // Direct comparison format: Season | Matchday | Date | Home | Away | Result |
| | 1 | 1353 | | if (cells.Length < 6) |
| | 0 | 1354 | | continue; |
| | | 1355 | | |
| | 1 | 1356 | | var league = cells[0].TextContent?.Trim() ?? ""; |
| | 1 | 1357 | | var matchday = cells[1].TextContent?.Trim() ?? ""; |
| | 1 | 1358 | | var playedAt = cells[2].TextContent?.Trim() ?? ""; |
| | 1 | 1359 | | var homeTeam = cells[3].TextContent?.Trim() ?? ""; |
| | 1 | 1360 | | var awayTeam = cells[4].TextContent?.Trim() ?? ""; |
| | | 1361 | | |
| | | 1362 | | // Extract score from the result cell |
| | 1 | 1363 | | var resultCell = cells[5]; |
| | 1 | 1364 | | var score = ""; |
| | 1 | 1365 | | string? annotation = null; |
| | | 1366 | | |
| | 1 | 1367 | | var scoreElements = resultCell.QuerySelectorAll(".kicktipp-heim, .kicktipp-gast"); |
| | 1 | 1368 | | if (scoreElements.Length >= 2) |
| | | 1369 | | { |
| | 1 | 1370 | | var homeScoreText = scoreElements[0].TextContent?.Trim() ?? ""; |
| | 1 | 1371 | | var awayScoreText = scoreElements[1].TextContent?.Trim() ?? ""; |
| | | 1372 | | |
| | 1 | 1373 | | if (homeScoreText != "-" && awayScoreText != "-") |
| | | 1374 | | { |
| | 1 | 1375 | | score = $"{homeScoreText}:{awayScoreText}"; |
| | | 1376 | | } |
| | | 1377 | | } |
| | | 1378 | | |
| | | 1379 | | // Extract annotation if present (e.g., "n.E." for penalty shootout) |
| | 1 | 1380 | | var annotationElement = resultCell.QuerySelector(".kicktipp-zusatz"); |
| | 1 | 1381 | | if (annotationElement != null) |
| | | 1382 | | { |
| | 1 | 1383 | | annotation = ExpandAnnotation(annotationElement.TextContent?.Trim()); |
| | | 1384 | | } |
| | | 1385 | | |
| | 1 | 1386 | | var headToHeadResult = new HeadToHeadResult(league, matchday, playedAt, homeTeam, awayTeam, score, a |
| | 1 | 1387 | | results.Add(headToHeadResult); |
| | 1 | 1388 | | } |
| | 0 | 1389 | | catch (Exception ex) |
| | | 1390 | | { |
| | 0 | 1391 | | _logger.LogDebug(ex, "Error parsing head-to-head row"); |
| | 0 | 1392 | | continue; |
| | | 1393 | | } |
| | | 1394 | | } |
| | 1 | 1395 | | } |
| | 0 | 1396 | | catch (Exception ex) |
| | | 1397 | | { |
| | 0 | 1398 | | _logger.LogError(ex, "Error extracting head-to-head history"); |
| | 0 | 1399 | | } |
| | | 1400 | | |
| | 1 | 1401 | | return results; |
| | 0 | 1402 | | } |
| | | 1403 | | |
| | | 1404 | | private string? FindNextMatchLink(IDocument document) |
| | | 1405 | | { |
| | | 1406 | | try |
| | | 1407 | | { |
| | | 1408 | | // Look for the right arrow button in the match navigation |
| | 1 | 1409 | | var nextButton = document.QuerySelector(".prevnextNext a"); |
| | 1 | 1410 | | if (nextButton == null) |
| | | 1411 | | { |
| | 1 | 1412 | | _logger.LogDebug("No next match button found"); |
| | 1 | 1413 | | return null; |
| | | 1414 | | } |
| | | 1415 | | |
| | | 1416 | | // Check if the button is disabled |
| | 1 | 1417 | | var parentDiv = nextButton.ParentElement; |
| | 1 | 1418 | | if (parentDiv?.ClassList.Contains("disabled") == true) |
| | | 1419 | | { |
| | 1 | 1420 | | _logger.LogDebug("Next match button is disabled - reached end of matches"); |
| | 1 | 1421 | | return null; |
| | | 1422 | | } |
| | | 1423 | | |
| | 1 | 1424 | | var href = nextButton.GetAttribute("href"); |
| | 1 | 1425 | | if (string.IsNullOrEmpty(href)) |
| | | 1426 | | { |
| | 0 | 1427 | | _logger.LogDebug("Next match button has no href"); |
| | 0 | 1428 | | return null; |
| | | 1429 | | } |
| | | 1430 | | |
| | 1 | 1431 | | _logger.LogDebug("Found next match link: {Href}", href); |
| | 1 | 1432 | | return href; |
| | | 1433 | | } |
| | 0 | 1434 | | catch (Exception ex) |
| | | 1435 | | { |
| | 0 | 1436 | | _logger.LogError(ex, "Error finding next match link"); |
| | 0 | 1437 | | return null; |
| | | 1438 | | } |
| | 1 | 1439 | | } |
| | | 1440 | | |
| | | 1441 | | private ZonedDateTime ParseMatchDateTime(string timeText) |
| | | 1442 | | { |
| | | 1443 | | try |
| | | 1444 | | { |
| | | 1445 | | // Handle empty or null time text |
| | | 1446 | | // Use MinValue to ensure database key consistency and prevent orphaned predictions |
| | | 1447 | | // See docs/features/cancelled-matches.md for design rationale |
| | 1 | 1448 | | if (string.IsNullOrWhiteSpace(timeText)) |
| | | 1449 | | { |
| | 1 | 1450 | | _logger.LogWarning("Match time text is empty, using MinValue for database consistency"); |
| | 1 | 1451 | | return DateTimeOffset.MinValue.ToZonedDateTime(); |
| | | 1452 | | } |
| | | 1453 | | |
| | | 1454 | | // Expected format: "22.08.25 20:30" |
| | 1 | 1455 | | _logger.LogDebug("Attempting to parse time: '{TimeText}'", timeText); |
| | 1 | 1456 | | if (DateTime.TryParseExact(timeText, "dd.MM.yy HH:mm", null, System.Globalization.DateTimeStyles.None, out v |
| | | 1457 | | { |
| | 1 | 1458 | | _logger.LogDebug("Successfully parsed time: {DateTime}", dateTime); |
| | | 1459 | | // Convert to DateTimeOffset and then to ZonedDateTime |
| | | 1460 | | // Assume Central European Time (Germany) |
| | 1 | 1461 | | var dateTimeOffset = new DateTimeOffset(dateTime, TimeSpan.FromHours(1)); // CET offset |
| | 1 | 1462 | | return dateTimeOffset.ToZonedDateTime(); |
| | | 1463 | | } |
| | | 1464 | | |
| | | 1465 | | // Fallback to MinValue if parsing fails - ensures database key consistency |
| | | 1466 | | // and prevents orphaned predictions from being created with varying timestamps |
| | | 1467 | | // See docs/features/cancelled-matches.md for design rationale |
| | 0 | 1468 | | _logger.LogWarning("Could not parse match time: '{TimeText}', using MinValue for database consistency", time |
| | 0 | 1469 | | return DateTimeOffset.MinValue.ToZonedDateTime(); |
| | | 1470 | | } |
| | 0 | 1471 | | catch (Exception ex) |
| | | 1472 | | { |
| | 0 | 1473 | | _logger.LogError(ex, "Error parsing match time '{TimeText}'", timeText); |
| | 0 | 1474 | | return DateTimeOffset.MinValue.ToZonedDateTime(); |
| | | 1475 | | } |
| | 1 | 1476 | | } |
| | | 1477 | | |
| | | 1478 | | /// <summary> |
| | | 1479 | | /// Determines if the given time text indicates a cancelled match. |
| | | 1480 | | /// </summary> |
| | | 1481 | | /// <param name="timeText">The time text from the Kicktipp page.</param> |
| | | 1482 | | /// <returns>True if the match is cancelled ("Abgesagt" in German), false otherwise.</returns> |
| | | 1483 | | /// <remarks> |
| | | 1484 | | /// <para> |
| | | 1485 | | /// Cancelled matches on Kicktipp display "Abgesagt" instead of a date/time in the schedule. |
| | | 1486 | | /// These matches can still receive predictions, so we continue processing them rather than skipping. |
| | | 1487 | | /// </para> |
| | | 1488 | | /// <para> |
| | | 1489 | | /// <b>Design Decision:</b> We treat "Abgesagt" similar to an empty time cell and inherit the |
| | | 1490 | | /// previous valid time. This preserves database key consistency since the composite key |
| | | 1491 | | /// (HomeTeam, AwayTeam, StartsAt, ...) must remain stable across prediction operations. |
| | | 1492 | | /// </para> |
| | | 1493 | | /// <para> |
| | | 1494 | | /// See <c>docs/features/cancelled-matches.md</c> for complete design rationale. |
| | | 1495 | | /// </para> |
| | | 1496 | | /// </remarks> |
| | | 1497 | | private static bool IsCancelledTimeText(string timeText) |
| | | 1498 | | { |
| | 1 | 1499 | | return string.Equals(timeText, "Abgesagt", StringComparison.OrdinalIgnoreCase); |
| | | 1500 | | } |
| | | 1501 | | |
| | | 1502 | | /// <inheritdoc /> |
| | | 1503 | | public async Task<Dictionary<Match, BetPrediction?>> GetPlacedPredictionsAsync(string community) |
| | | 1504 | | { |
| | | 1505 | | try |
| | | 1506 | | { |
| | 1 | 1507 | | var url = $"{community}/tippabgabe"; |
| | 1 | 1508 | | var response = await _httpClient.GetAsync(url); |
| | | 1509 | | |
| | 1 | 1510 | | if (!response.IsSuccessStatusCode) |
| | | 1511 | | { |
| | 1 | 1512 | | _logger.LogError("Failed to fetch tippabgabe page. Status: {StatusCode}", response.StatusCode); |
| | 1 | 1513 | | return new Dictionary<Match, BetPrediction?>(); |
| | | 1514 | | } |
| | | 1515 | | |
| | 1 | 1516 | | var content = await response.Content.ReadAsStringAsync(); |
| | 1 | 1517 | | var document = await _browsingContext.OpenAsync(req => req.Content(content)); |
| | | 1518 | | |
| | 1 | 1519 | | var placedPredictions = new Dictionary<Match, BetPrediction?>(); |
| | | 1520 | | |
| | | 1521 | | // Extract matchday from the page |
| | 1 | 1522 | | var currentMatchday = ExtractMatchdayFromPage(document); |
| | 1 | 1523 | | _logger.LogDebug("Extracted matchday for placed predictions: {Matchday}", currentMatchday); |
| | | 1524 | | |
| | | 1525 | | // Parse matches from the tippabgabe table |
| | 1 | 1526 | | var matchTable = document.QuerySelector("#tippabgabeSpiele tbody"); |
| | 1 | 1527 | | if (matchTable == null) |
| | | 1528 | | { |
| | 1 | 1529 | | _logger.LogWarning("Could not find tippabgabe table"); |
| | 1 | 1530 | | return placedPredictions; |
| | | 1531 | | } |
| | | 1532 | | |
| | 1 | 1533 | | var matchRows = matchTable.QuerySelectorAll("tr"); |
| | 1 | 1534 | | _logger.LogDebug("Found {MatchRowCount} potential match rows", matchRows.Length); |
| | | 1535 | | |
| | 1 | 1536 | | string lastValidTimeText = ""; // Track the last valid date/time for inheritance |
| | | 1537 | | |
| | 1 | 1538 | | foreach (var row in matchRows) |
| | | 1539 | | { |
| | | 1540 | | try |
| | | 1541 | | { |
| | 1 | 1542 | | var cells = row.QuerySelectorAll("td"); |
| | 1 | 1543 | | if (cells.Length >= 4) |
| | | 1544 | | { |
| | | 1545 | | // Extract match details from table cells |
| | 1 | 1546 | | var timeText = cells[0].TextContent?.Trim() ?? ""; |
| | 1 | 1547 | | var homeTeam = cells[1].TextContent?.Trim() ?? ""; |
| | 1 | 1548 | | var awayTeam = cells[2].TextContent?.Trim() ?? ""; |
| | | 1549 | | |
| | 1 | 1550 | | _logger.LogDebug("Raw time text for {HomeTeam} vs {AwayTeam}: '{TimeText}'", homeTeam, awayTeam, |
| | | 1551 | | |
| | | 1552 | | // Check if match is cancelled ("Abgesagt" in German) |
| | | 1553 | | // Cancelled matches still accept predictions on Kicktipp, so we process them. |
| | | 1554 | | // See docs/features/cancelled-matches.md for design rationale. |
| | 1 | 1555 | | var isCancelled = IsCancelledTimeText(timeText); |
| | | 1556 | | |
| | | 1557 | | // Handle date inheritance: if timeText is empty or cancelled, use the last valid time |
| | | 1558 | | // This preserves database key consistency (startsAt is part of the composite key) |
| | 1 | 1559 | | if (string.IsNullOrWhiteSpace(timeText) || isCancelled) |
| | | 1560 | | { |
| | 1 | 1561 | | if (!string.IsNullOrWhiteSpace(lastValidTimeText)) |
| | | 1562 | | { |
| | 1 | 1563 | | if (isCancelled) |
| | | 1564 | | { |
| | 1 | 1565 | | _logger.LogWarning( |
| | 1 | 1566 | | "Match {HomeTeam} vs {AwayTeam} is cancelled (Abgesagt). Using inherited time '{ |
| | 1 | 1567 | | "Predictions can still be placed but may need to be re-evaluated when the match |
| | 1 | 1568 | | homeTeam, awayTeam, lastValidTimeText); |
| | | 1569 | | } |
| | | 1570 | | else |
| | | 1571 | | { |
| | 1 | 1572 | | _logger.LogDebug("Using inherited time for {HomeTeam} vs {AwayTeam}: '{InheritedTime |
| | | 1573 | | } |
| | 1 | 1574 | | timeText = lastValidTimeText; |
| | | 1575 | | } |
| | | 1576 | | else |
| | | 1577 | | { |
| | 1 | 1578 | | _logger.LogWarning("No previous valid time to inherit for {HomeTeam} vs {AwayTeam}{Cance |
| | 1 | 1579 | | homeTeam, awayTeam, isCancelled ? " (cancelled match)" : ""); |
| | | 1580 | | } |
| | | 1581 | | } |
| | | 1582 | | else |
| | | 1583 | | { |
| | | 1584 | | // Update the last valid time for future inheritance |
| | 1 | 1585 | | lastValidTimeText = timeText; |
| | 1 | 1586 | | _logger.LogDebug("Updated last valid time to: '{TimeText}'", timeText); |
| | | 1587 | | } |
| | | 1588 | | |
| | | 1589 | | // Look for betting inputs to get placed predictions |
| | 1 | 1590 | | var bettingInputs = cells[3].QuerySelectorAll("input[type='text']"); |
| | 1 | 1591 | | if (bettingInputs.Length >= 2) |
| | | 1592 | | { |
| | 1 | 1593 | | var homeInput = bettingInputs[0] as IHtmlInputElement; |
| | 1 | 1594 | | var awayInput = bettingInputs[1] as IHtmlInputElement; |
| | | 1595 | | |
| | | 1596 | | // Parse the date/time |
| | 1 | 1597 | | var startsAt = ParseMatchDateTime(timeText); |
| | 1 | 1598 | | var match = new Match(homeTeam, awayTeam, startsAt, currentMatchday, isCancelled); |
| | | 1599 | | |
| | | 1600 | | // Check if predictions are placed (inputs have values) |
| | 1 | 1601 | | var homeValue = homeInput?.Value?.Trim(); |
| | 1 | 1602 | | var awayValue = awayInput?.Value?.Trim(); |
| | | 1603 | | |
| | 1 | 1604 | | BetPrediction? prediction = null; |
| | 1 | 1605 | | if (!string.IsNullOrEmpty(homeValue) && !string.IsNullOrEmpty(awayValue)) |
| | | 1606 | | { |
| | 1 | 1607 | | if (int.TryParse(homeValue, out var homeGoals) && int.TryParse(awayValue, out var awayGo |
| | | 1608 | | { |
| | 1 | 1609 | | prediction = new BetPrediction(homeGoals, awayGoals); |
| | 1 | 1610 | | _logger.LogDebug("Found placed prediction: {HomeTeam} vs {AwayTeam} = {Prediction}", |
| | | 1611 | | } |
| | | 1612 | | else |
| | | 1613 | | { |
| | 1 | 1614 | | _logger.LogWarning("Could not parse prediction values for {HomeTeam} vs {AwayTeam}: |
| | | 1615 | | } |
| | | 1616 | | } |
| | | 1617 | | else |
| | | 1618 | | { |
| | 1 | 1619 | | _logger.LogDebug("No prediction placed for {HomeTeam} vs {AwayTeam}", homeTeam, awayTeam |
| | | 1620 | | } |
| | | 1621 | | |
| | 1 | 1622 | | placedPredictions[match] = prediction; |
| | | 1623 | | } |
| | | 1624 | | } |
| | 1 | 1625 | | } |
| | 0 | 1626 | | catch (Exception ex) |
| | | 1627 | | { |
| | 0 | 1628 | | _logger.LogWarning(ex, "Error parsing match row"); |
| | 0 | 1629 | | continue; |
| | | 1630 | | } |
| | | 1631 | | } |
| | | 1632 | | |
| | 1 | 1633 | | _logger.LogInformation("Successfully parsed {MatchCount} matches with {PlacedCount} placed predictions", |
| | 1 | 1634 | | placedPredictions.Count, placedPredictions.Values.Count(p => p != null)); |
| | 1 | 1635 | | return placedPredictions; |
| | | 1636 | | } |
| | 0 | 1637 | | catch (Exception ex) |
| | | 1638 | | { |
| | 0 | 1639 | | _logger.LogError(ex, "Exception in GetPlacedPredictionsAsync"); |
| | 0 | 1640 | | return new Dictionary<Match, BetPrediction?>(); |
| | | 1641 | | } |
| | 1 | 1642 | | } |
| | | 1643 | | |
| | | 1644 | | private int ExtractMatchdayFromPage(IDocument document) |
| | | 1645 | | { |
| | | 1646 | | try |
| | | 1647 | | { |
| | | 1648 | | // Try to extract from the navigation title (e.g., "1. Spieltag") |
| | 1 | 1649 | | var titleElement = document.QuerySelector(".prevnextTitle a"); |
| | 1 | 1650 | | if (titleElement != null) |
| | | 1651 | | { |
| | 1 | 1652 | | var titleText = titleElement.TextContent?.Trim(); |
| | 1 | 1653 | | if (!string.IsNullOrEmpty(titleText)) |
| | | 1654 | | { |
| | | 1655 | | // Extract number from text like "1. Spieltag" |
| | 1 | 1656 | | var match = System.Text.RegularExpressions.Regex.Match(titleText, @"(\d+)\.\s*Spieltag"); |
| | 1 | 1657 | | if (match.Success && int.TryParse(match.Groups[1].Value, out var matchday)) |
| | | 1658 | | { |
| | 1 | 1659 | | _logger.LogDebug("Extracted matchday from title: {Matchday}", matchday); |
| | 1 | 1660 | | return matchday; |
| | | 1661 | | } |
| | | 1662 | | } |
| | | 1663 | | } |
| | | 1664 | | |
| | | 1665 | | // Fallback: try to extract from hidden input |
| | 1 | 1666 | | var spieltagInput = document.QuerySelector("input[name='spieltagIndex']") as IHtmlInputElement; |
| | 1 | 1667 | | if (spieltagInput?.Value != null && int.TryParse(spieltagInput.Value, out var matchdayFromInput)) |
| | | 1668 | | { |
| | 1 | 1669 | | _logger.LogDebug("Extracted matchday from hidden input: {Matchday}", matchdayFromInput); |
| | 1 | 1670 | | return matchdayFromInput; |
| | | 1671 | | } |
| | | 1672 | | |
| | 1 | 1673 | | _logger.LogWarning("Could not extract matchday from page, defaulting to 1"); |
| | 1 | 1674 | | return 1; |
| | | 1675 | | } |
| | 0 | 1676 | | catch (Exception ex) |
| | | 1677 | | { |
| | 0 | 1678 | | _logger.LogError(ex, "Error extracting matchday from page, defaulting to 1"); |
| | 0 | 1679 | | return 1; |
| | | 1680 | | } |
| | 1 | 1681 | | } |
| | | 1682 | | |
| | | 1683 | | /// <inheritdoc /> |
| | | 1684 | | public async Task<List<BonusQuestion>> GetOpenBonusQuestionsAsync(string community) |
| | | 1685 | | { |
| | | 1686 | | try |
| | | 1687 | | { |
| | 1 | 1688 | | var url = $"{community}/tippabgabe?bonus=true"; |
| | 1 | 1689 | | var response = await _httpClient.GetAsync(url); |
| | | 1690 | | |
| | 1 | 1691 | | if (!response.IsSuccessStatusCode) |
| | | 1692 | | { |
| | 1 | 1693 | | _logger.LogError("Failed to fetch tippabgabe page for bonus questions. Status: {StatusCode}", response.S |
| | 1 | 1694 | | return new List<BonusQuestion>(); |
| | | 1695 | | } |
| | | 1696 | | |
| | 1 | 1697 | | var content = await response.Content.ReadAsStringAsync(); |
| | 1 | 1698 | | var document = await _browsingContext.OpenAsync(req => req.Content(content)); |
| | | 1699 | | |
| | 1 | 1700 | | var bonusQuestions = new List<BonusQuestion>(); |
| | | 1701 | | |
| | | 1702 | | // Parse bonus questions from the tippabgabeFragen table |
| | 1 | 1703 | | var bonusTable = document.QuerySelector("#tippabgabeFragen tbody"); |
| | 1 | 1704 | | if (bonusTable == null) |
| | | 1705 | | { |
| | 1 | 1706 | | _logger.LogDebug("No bonus questions table found - this is normal if no bonus questions are available"); |
| | 1 | 1707 | | return bonusQuestions; |
| | | 1708 | | } |
| | | 1709 | | |
| | 1 | 1710 | | var questionRows = bonusTable.QuerySelectorAll("tr"); |
| | 1 | 1711 | | _logger.LogDebug("Found {QuestionRowCount} potential bonus question rows", questionRows.Length); |
| | | 1712 | | |
| | 1 | 1713 | | foreach (var row in questionRows) |
| | | 1714 | | { |
| | 1 | 1715 | | var cells = row.QuerySelectorAll("td"); |
| | 1 | 1716 | | if (cells.Length < 3) continue; |
| | | 1717 | | |
| | | 1718 | | // Extract deadline and question text |
| | 1 | 1719 | | var deadlineText = cells[0]?.TextContent?.Trim(); |
| | 1 | 1720 | | var questionText = cells[1]?.TextContent?.Trim(); |
| | | 1721 | | |
| | 1 | 1722 | | if (string.IsNullOrEmpty(questionText)) continue; |
| | | 1723 | | |
| | | 1724 | | // Parse deadline |
| | 1 | 1725 | | var deadline = ParseMatchDateTime(deadlineText ?? ""); |
| | | 1726 | | |
| | | 1727 | | // Extract options from select elements |
| | 1 | 1728 | | var tipCell = cells[2]; |
| | 1 | 1729 | | var selectElements = tipCell?.QuerySelectorAll("select"); |
| | 1 | 1730 | | var options = new List<BonusQuestionOption>(); |
| | 1 | 1731 | | string? formFieldName = null; |
| | 1 | 1732 | | int maxSelections = 1; // Default to single selection |
| | | 1733 | | |
| | 1 | 1734 | | if (selectElements != null && selectElements.Length > 0) |
| | | 1735 | | { |
| | | 1736 | | // The number of select elements indicates how many selections are allowed |
| | 1 | 1737 | | maxSelections = selectElements.Length; |
| | | 1738 | | |
| | | 1739 | | // Use the first select element to get the available options |
| | 1 | 1740 | | var firstSelect = selectElements[0] as IHtmlSelectElement; |
| | 1 | 1741 | | formFieldName = firstSelect?.Name; |
| | | 1742 | | |
| | 1 | 1743 | | var optionElements = firstSelect?.QuerySelectorAll("option"); |
| | 1 | 1744 | | if (optionElements != null) |
| | | 1745 | | { |
| | 1 | 1746 | | foreach (var option in optionElements.Cast<IHtmlOptionElement>()) |
| | | 1747 | | { |
| | 1 | 1748 | | if (option.Value != "-1" && !string.IsNullOrEmpty(option.Text)) |
| | | 1749 | | { |
| | 1 | 1750 | | options.Add(new BonusQuestionOption(option.Value, option.Text.Trim())); |
| | | 1751 | | } |
| | | 1752 | | } |
| | | 1753 | | } |
| | | 1754 | | } |
| | | 1755 | | |
| | 1 | 1756 | | if (options.Any()) |
| | | 1757 | | { |
| | 1 | 1758 | | bonusQuestions.Add(new BonusQuestion( |
| | 1 | 1759 | | Text: questionText, |
| | 1 | 1760 | | Deadline: deadline, |
| | 1 | 1761 | | Options: options, |
| | 1 | 1762 | | MaxSelections: maxSelections, |
| | 1 | 1763 | | FormFieldName: formFieldName |
| | 1 | 1764 | | )); |
| | | 1765 | | } |
| | | 1766 | | } |
| | | 1767 | | |
| | 1 | 1768 | | _logger.LogInformation("Successfully parsed {QuestionCount} bonus questions", bonusQuestions.Count); |
| | 1 | 1769 | | return bonusQuestions; |
| | | 1770 | | } |
| | 0 | 1771 | | catch (Exception ex) |
| | | 1772 | | { |
| | 0 | 1773 | | _logger.LogError(ex, "Exception in GetOpenBonusQuestionsAsync"); |
| | 0 | 1774 | | return new List<BonusQuestion>(); |
| | | 1775 | | } |
| | 1 | 1776 | | } |
| | | 1777 | | |
| | | 1778 | | /// <inheritdoc /> |
| | | 1779 | | public async Task<Dictionary<string, BonusPrediction?>> GetPlacedBonusPredictionsAsync(string community) |
| | | 1780 | | { |
| | | 1781 | | try |
| | | 1782 | | { |
| | 1 | 1783 | | var url = $"{community}/tippabgabe?bonus=true"; |
| | 1 | 1784 | | var response = await _httpClient.GetAsync(url); |
| | | 1785 | | |
| | 1 | 1786 | | if (!response.IsSuccessStatusCode) |
| | | 1787 | | { |
| | 1 | 1788 | | _logger.LogError("Failed to fetch tippabgabe page for placed bonus predictions. Status: {StatusCode}", r |
| | 1 | 1789 | | return new Dictionary<string, BonusPrediction?>(); |
| | | 1790 | | } |
| | | 1791 | | |
| | 1 | 1792 | | var content = await response.Content.ReadAsStringAsync(); |
| | 1 | 1793 | | var document = await _browsingContext.OpenAsync(req => req.Content(content)); |
| | | 1794 | | |
| | 1 | 1795 | | var placedPredictions = new Dictionary<string, BonusPrediction?>(); |
| | | 1796 | | |
| | | 1797 | | // Parse bonus questions from the tippabgabeFragen table |
| | 1 | 1798 | | var bonusTable = document.QuerySelector("#tippabgabeFragen tbody"); |
| | 1 | 1799 | | if (bonusTable == null) |
| | | 1800 | | { |
| | 1 | 1801 | | _logger.LogDebug("No bonus questions table found - this is normal if no bonus questions are available"); |
| | 1 | 1802 | | return placedPredictions; |
| | | 1803 | | } |
| | | 1804 | | |
| | 1 | 1805 | | var questionRows = bonusTable.QuerySelectorAll("tr"); |
| | 1 | 1806 | | _logger.LogDebug("Found {QuestionRowCount} potential bonus question rows for placed predictions", questionRo |
| | | 1807 | | |
| | 1 | 1808 | | foreach (var row in questionRows) |
| | | 1809 | | { |
| | 1 | 1810 | | var cells = row.QuerySelectorAll("td"); |
| | 1 | 1811 | | if (cells.Length < 3) continue; |
| | | 1812 | | |
| | | 1813 | | // Extract question text |
| | 1 | 1814 | | var questionText = cells[1]?.TextContent?.Trim(); |
| | 1 | 1815 | | if (string.IsNullOrEmpty(questionText)) continue; |
| | | 1816 | | |
| | | 1817 | | // Extract current selections from select elements |
| | 1 | 1818 | | var tipCell = cells[2]; |
| | 1 | 1819 | | var selectElements = tipCell?.QuerySelectorAll("select"); |
| | | 1820 | | |
| | 1 | 1821 | | if (selectElements != null && selectElements.Length > 0) |
| | | 1822 | | { |
| | | 1823 | | // Extract form field name from the first select element |
| | 1 | 1824 | | var firstSelect = selectElements[0] as IHtmlSelectElement; |
| | 1 | 1825 | | var formFieldName = firstSelect?.Name; |
| | | 1826 | | |
| | 1 | 1827 | | var selectedOptionIds = new List<string>(); |
| | | 1828 | | |
| | | 1829 | | // Check each select element for its current selection |
| | 1 | 1830 | | foreach (var selectElement in selectElements.Cast<IHtmlSelectElement>()) |
| | | 1831 | | { |
| | 1 | 1832 | | var selectedOption = selectElement.SelectedOptions.FirstOrDefault(); |
| | 1 | 1833 | | if (selectedOption != null && selectedOption.Value != "-1" && !string.IsNullOrEmpty(selectedOpti |
| | | 1834 | | { |
| | 1 | 1835 | | selectedOptionIds.Add(selectedOption.Value); |
| | | 1836 | | } |
| | | 1837 | | } |
| | | 1838 | | |
| | | 1839 | | // Use form field name as key, fall back to question text |
| | 1 | 1840 | | var dictionaryKey = formFieldName ?? questionText; |
| | | 1841 | | |
| | | 1842 | | // Only create a prediction if there are actual selections |
| | 1 | 1843 | | if (selectedOptionIds.Any()) |
| | | 1844 | | { |
| | 1 | 1845 | | placedPredictions[dictionaryKey] = new BonusPrediction(selectedOptionIds); |
| | | 1846 | | } |
| | | 1847 | | else |
| | | 1848 | | { |
| | 1 | 1849 | | placedPredictions[dictionaryKey] = null; // No prediction placed |
| | | 1850 | | } |
| | | 1851 | | } |
| | | 1852 | | } |
| | | 1853 | | |
| | 1 | 1854 | | _logger.LogInformation("Successfully retrieved placed predictions for {QuestionCount} bonus questions", plac |
| | 1 | 1855 | | return placedPredictions; |
| | | 1856 | | } |
| | 0 | 1857 | | catch (Exception ex) |
| | | 1858 | | { |
| | 0 | 1859 | | _logger.LogError(ex, "Exception in GetPlacedBonusPredictionsAsync"); |
| | 0 | 1860 | | return new Dictionary<string, BonusPrediction?>(); |
| | | 1861 | | } |
| | 1 | 1862 | | } |
| | | 1863 | | |
| | | 1864 | | /// <inheritdoc /> |
| | | 1865 | | public async Task<bool> PlaceBonusPredictionsAsync(string community, Dictionary<string, BonusPrediction> predictions |
| | | 1866 | | { |
| | | 1867 | | try |
| | | 1868 | | { |
| | 1 | 1869 | | if (!predictions.Any()) |
| | | 1870 | | { |
| | 1 | 1871 | | _logger.LogInformation("No bonus predictions to place"); |
| | 1 | 1872 | | return true; |
| | | 1873 | | } |
| | | 1874 | | |
| | 1 | 1875 | | var url = $"{community}/tippabgabe?bonus=true"; |
| | 1 | 1876 | | var response = await _httpClient.GetAsync(url); |
| | | 1877 | | |
| | 1 | 1878 | | if (!response.IsSuccessStatusCode) |
| | | 1879 | | { |
| | 1 | 1880 | | _logger.LogError("Failed to access betting page for bonus predictions. Status: {StatusCode}", response.S |
| | 1 | 1881 | | return false; |
| | | 1882 | | } |
| | | 1883 | | |
| | 1 | 1884 | | var pageContent = await response.Content.ReadAsStringAsync(); |
| | 1 | 1885 | | var document = await _browsingContext.OpenAsync(req => req.Content(pageContent)); |
| | | 1886 | | |
| | | 1887 | | // Find the bet form |
| | 1 | 1888 | | var betForm = document.QuerySelector("form") as IHtmlFormElement; |
| | 1 | 1889 | | if (betForm == null) |
| | | 1890 | | { |
| | 1 | 1891 | | _logger.LogWarning("Could not find betting form on the page"); |
| | 1 | 1892 | | return false; |
| | | 1893 | | } |
| | | 1894 | | |
| | 1 | 1895 | | var formData = new List<KeyValuePair<string, string>>(); |
| | | 1896 | | |
| | | 1897 | | // Copy hidden inputs from the original form |
| | 1 | 1898 | | var hiddenInputs = betForm.QuerySelectorAll("input[type='hidden']"); |
| | 1 | 1899 | | foreach (var hiddenInput in hiddenInputs.Cast<IHtmlInputElement>()) |
| | | 1900 | | { |
| | 1 | 1901 | | if (!string.IsNullOrEmpty(hiddenInput.Name) && hiddenInput.Value != null) |
| | | 1902 | | { |
| | 1 | 1903 | | formData.Add(new KeyValuePair<string, string>(hiddenInput.Name, hiddenInput.Value)); |
| | | 1904 | | } |
| | | 1905 | | } |
| | | 1906 | | |
| | | 1907 | | // Copy existing match predictions to avoid overwriting them |
| | 1 | 1908 | | var allInputs = betForm.QuerySelectorAll("input[type=text], input[type=number]").OfType<IHtmlInputElement>() |
| | 1 | 1909 | | foreach (var input in allInputs) |
| | | 1910 | | { |
| | 1 | 1911 | | if (!string.IsNullOrEmpty(input.Name) && !string.IsNullOrEmpty(input.Value)) |
| | | 1912 | | { |
| | 0 | 1913 | | formData.Add(new KeyValuePair<string, string>(input.Name, input.Value)); |
| | | 1914 | | } |
| | | 1915 | | } |
| | | 1916 | | |
| | | 1917 | | // Add bonus predictions |
| | 1 | 1918 | | var bonusTable = document.QuerySelector("#tippabgabeFragen tbody"); |
| | 1 | 1919 | | if (bonusTable != null) |
| | | 1920 | | { |
| | 1 | 1921 | | var questionRows = bonusTable.QuerySelectorAll("tr"); |
| | | 1922 | | |
| | 1 | 1923 | | foreach (var row in questionRows) |
| | | 1924 | | { |
| | 1 | 1925 | | var cells = row.QuerySelectorAll("td"); |
| | 1 | 1926 | | if (cells.Length < 3) continue; |
| | | 1927 | | |
| | 1 | 1928 | | var tipCell = cells[2]; |
| | 1 | 1929 | | var selectElements = tipCell?.QuerySelectorAll("select"); |
| | | 1930 | | |
| | 1 | 1931 | | if (selectElements != null) |
| | | 1932 | | { |
| | 1 | 1933 | | var selectArray = selectElements.Cast<IHtmlSelectElement>().ToArray(); |
| | | 1934 | | |
| | | 1935 | | // Check if we have a prediction for this question based on form field name match |
| | 1 | 1936 | | var matchingPrediction = predictions.FirstOrDefault(p => |
| | 1 | 1937 | | selectArray.Any(sel => sel.Name == p.Key) || |
| | 1 | 1938 | | selectArray.Any(sel => sel.Name?.Contains(p.Key) == true)); |
| | | 1939 | | |
| | 1 | 1940 | | if (matchingPrediction.Value != null && matchingPrediction.Value.SelectedOptionIds.Any()) |
| | | 1941 | | { |
| | 1 | 1942 | | var selectedOptions = matchingPrediction.Value.SelectedOptionIds; |
| | | 1943 | | |
| | | 1944 | | // For multi-selection questions, we need to fill multiple select elements |
| | 1 | 1945 | | for (int i = 0; i < Math.Min(selectArray.Length, selectedOptions.Count); i++) |
| | | 1946 | | { |
| | 1 | 1947 | | var selectElement = selectArray[i]; |
| | 1 | 1948 | | var fieldName = selectElement.Name; |
| | 1 | 1949 | | if (string.IsNullOrEmpty(fieldName)) continue; |
| | | 1950 | | |
| | 1 | 1951 | | var selectedOptionId = selectedOptions[i]; |
| | | 1952 | | |
| | | 1953 | | // Check if this option exists in the select element |
| | 1 | 1954 | | var optionExists = selectElement.QuerySelectorAll("option") |
| | 1 | 1955 | | .Cast<IHtmlOptionElement>() |
| | 1 | 1956 | | .Any(opt => opt.Value == selectedOptionId); |
| | | 1957 | | |
| | 1 | 1958 | | if (optionExists) |
| | | 1959 | | { |
| | 1 | 1960 | | formData.Add(new KeyValuePair<string, string>(fieldName, selectedOptionId)); |
| | 1 | 1961 | | _logger.LogDebug("Added bonus prediction for field {FieldName}: {OptionId} (selectio |
| | 1 | 1962 | | fieldName, selectedOptionId, i + 1); |
| | | 1963 | | } |
| | | 1964 | | else |
| | | 1965 | | { |
| | 0 | 1966 | | _logger.LogWarning("Option {OptionId} not found for field {FieldName}", selectedOpti |
| | | 1967 | | } |
| | | 1968 | | } |
| | | 1969 | | } |
| | | 1970 | | } |
| | | 1971 | | } |
| | | 1972 | | } |
| | | 1973 | | |
| | | 1974 | | // Find submit button |
| | 1 | 1975 | | var submitButton = betForm.QuerySelector("input[type=submit], button[type=submit]") as IHtmlElement; |
| | 1 | 1976 | | if (submitButton != null) |
| | | 1977 | | { |
| | 1 | 1978 | | if (submitButton is IHtmlInputElement inputSubmit && !string.IsNullOrEmpty(inputSubmit.Name)) |
| | | 1979 | | { |
| | 1 | 1980 | | formData.Add(new KeyValuePair<string, string>(inputSubmit.Name, inputSubmit.Value ?? "Submit")); |
| | | 1981 | | } |
| | 1 | 1982 | | else if (submitButton is IHtmlButtonElement buttonSubmit && !string.IsNullOrEmpty(buttonSubmit.Name)) |
| | | 1983 | | { |
| | 1 | 1984 | | formData.Add(new KeyValuePair<string, string>(buttonSubmit.Name, buttonSubmit.Value ?? "Submit")); |
| | | 1985 | | } |
| | | 1986 | | } |
| | | 1987 | | else |
| | | 1988 | | { |
| | | 1989 | | // Fallback to default submit button name |
| | 0 | 1990 | | formData.Add(new KeyValuePair<string, string>("submitbutton", "Submit")); |
| | | 1991 | | } |
| | | 1992 | | |
| | | 1993 | | // Submit form |
| | 1 | 1994 | | var formActionUrl = string.IsNullOrEmpty(betForm.Action) ? url : |
| | 1 | 1995 | | (betForm.Action.StartsWith("http") ? betForm.Action : |
| | 1 | 1996 | | betForm.Action.StartsWith("/") ? betForm.Action : |
| | 1 | 1997 | | $"{community}/{betForm.Action}"); |
| | | 1998 | | |
| | 1 | 1999 | | var formContent = new FormUrlEncodedContent(formData); |
| | 1 | 2000 | | var submitResponse = await _httpClient.PostAsync(formActionUrl, formContent); |
| | | 2001 | | |
| | 1 | 2002 | | if (submitResponse.IsSuccessStatusCode) |
| | | 2003 | | { |
| | 1 | 2004 | | _logger.LogInformation("✓ Successfully submitted {PredictionCount} bonus predictions!", predictions.Coun |
| | 1 | 2005 | | return true; |
| | | 2006 | | } |
| | | 2007 | | else |
| | | 2008 | | { |
| | 1 | 2009 | | _logger.LogError("✗ Failed to submit bonus predictions. Status: {StatusCode}", submitResponse.StatusCode |
| | 1 | 2010 | | return false; |
| | | 2011 | | } |
| | | 2012 | | } |
| | 0 | 2013 | | catch (Exception ex) |
| | | 2014 | | { |
| | 0 | 2015 | | _logger.LogError(ex, "Exception during bonus prediction placement"); |
| | 0 | 2016 | | return false; |
| | | 2017 | | } |
| | 1 | 2018 | | } |
| | | 2019 | | |
| | | 2020 | | /// <summary> |
| | | 2021 | | /// Expands match annotation abbreviations to their full text. |
| | | 2022 | | /// </summary> |
| | | 2023 | | /// <param name="annotation">The abbreviated annotation (e.g., "n.E.", "n.V.")</param> |
| | | 2024 | | /// <returns>The expanded annotation or null if empty</returns> |
| | | 2025 | | private static string? ExpandAnnotation(string? annotation) |
| | | 2026 | | { |
| | 1 | 2027 | | if (string.IsNullOrWhiteSpace(annotation)) |
| | 0 | 2028 | | return null; |
| | | 2029 | | |
| | 1 | 2030 | | return annotation.Trim() switch |
| | 1 | 2031 | | { |
| | 1 | 2032 | | "n.E." => "nach Elfmeterschießen", |
| | 1 | 2033 | | "n.V." => "nach Verlängerung", |
| | 0 | 2034 | | _ => annotation.Trim() // Return as-is if not recognized |
| | 1 | 2035 | | }; |
| | | 2036 | | } |
| | | 2037 | | |
| | | 2038 | | public void Dispose() |
| | | 2039 | | { |
| | 0 | 2040 | | _httpClient?.Dispose(); |
| | 0 | 2041 | | _browsingContext?.Dispose(); |
| | 0 | 2042 | | } |
| | | 2043 | | } |