2020-12-20 18:03:20 +01:00
|
|
|
|
using Google.Apis.Customsearch.v1;
|
|
|
|
|
using Google.Apis.Services;
|
|
|
|
|
using Newtonsoft.Json;
|
2021-01-09 14:44:14 +01:00
|
|
|
|
using Serwer.Core.Repositories;
|
2020-12-20 18:03:20 +01:00
|
|
|
|
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;
|
2021-01-09 14:44:14 +01:00
|
|
|
|
private readonly IHistoryRepository _historyRepository;
|
|
|
|
|
private readonly IUserRepository _userRepository;
|
2020-12-20 18:03:20 +01:00
|
|
|
|
private const string apiKey = "AIzaSyCagG6QyQyBuJNb1YDuK25qSzoC0Rrjo0c";
|
|
|
|
|
private const string searchEngineId = "17b946686537c46e3";
|
2021-01-09 14:44:14 +01:00
|
|
|
|
public SearchService(IImageHandler imageHandler, IHistoryRepository historyRepository, IUserRepository userRepository)
|
2020-12-20 18:03:20 +01:00
|
|
|
|
{
|
|
|
|
|
_imageHandler = imageHandler;
|
2021-01-09 14:44:14 +01:00
|
|
|
|
_historyRepository = historyRepository;
|
|
|
|
|
_userRepository = userRepository;
|
2020-12-20 18:03:20 +01:00
|
|
|
|
}
|
2021-01-09 14:44:14 +01:00
|
|
|
|
public async Task<IList<SearchResultDTO>> Search(Guid userId, string query)
|
2020-12-20 18:03:20 +01:00
|
|
|
|
{
|
2021-01-09 14:44:14 +01:00
|
|
|
|
var user = await _userRepository.GetAsync(userId);
|
|
|
|
|
if(user == null)
|
|
|
|
|
{
|
|
|
|
|
throw new Exception("Coś poszło nie tak.");
|
|
|
|
|
}
|
|
|
|
|
await _historyRepository.AddAsync(user, query);
|
|
|
|
|
|
2020-12-20 18:03:20 +01:00
|
|
|
|
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<SearchResultDTO>();
|
|
|
|
|
foreach(var item in jsonData.items)
|
|
|
|
|
{
|
|
|
|
|
results.Add(new SearchResultDTO
|
|
|
|
|
{
|
|
|
|
|
Title = item.title,
|
|
|
|
|
Link = item.link,
|
|
|
|
|
Snippet = item.snippet
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
return results;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|