using Google.Apis.Customsearch.v1; using Google.Apis.Services; using Newtonsoft.Json; using Serwer.Core.Repositories; using Serwer.Infrastructure.DTO; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace Serwer.Infrastructure.Services { public class SearchService : ISearchService { private readonly IImageHandler _imageHandler; private readonly IHistoryRepository _historyRepository; private readonly IUserRepository _userRepository; private const string apiKey = "AIzaSyCagG6QyQyBuJNb1YDuK25qSzoC0Rrjo0c"; private const string searchEngineId = "17b946686537c46e3"; public SearchService(IImageHandler imageHandler, IHistoryRepository historyRepository, IUserRepository userRepository) { _imageHandler = imageHandler; _historyRepository = historyRepository; _userRepository = userRepository; } public async Task> Search(Guid userId, string query) { var user = await _userRepository.GetAsync(userId); if(user == null) { throw new Exception("Coś poszło nie tak."); } await _historyRepository.AddAsync(user, query); WebRequest webRequest = WebRequest.Create($"https://www.googleapis.com/customsearch/v1?key={apiKey}&cx={searchEngineId}&q={query}"); using (var stream = new StreamReader(webRequest.GetResponse().GetResponseStream())) { var response = await stream.ReadToEndAsync(); dynamic jsonData = JsonConvert.DeserializeObject(response); var results = new List(); foreach(var item in jsonData.items) { results.Add(new SearchResultDTO { Title = item.title, Link = item.link, Snippet = item.snippet }); } return results; } } } }