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