Poszukiwacz/Serwer/Serwer.Infrastructure/Services/SearchService.cs
2021-01-16 18:45:20 +01:00

90 lines
3.1 KiB
C#

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<IList<SearchResultDTO>> 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);
var queries = query.Split('.').ToList();
if (queries.Count > 2)
{
var q0 = queries[0].Split(' ');
if (q0.Length < 3)
{
queries.RemoveAt(0);
}
if(queries.Last().Length < 5)
{
queries.RemoveAt(queries.Count - 1);
}
}
query = String.Join(".", queries);
var result = await sendRequest(query);
if(result.Count == 0)
{
result = await sendRequest(queries.Last());
}
return result;
}
private async Task<List<SearchResultDTO>> sendRequest(string 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<SearchResultDTO>();
try
{
foreach (var item in jsonData.items)
{
results.Add(new SearchResultDTO
{
Title = item.title,
Link = item.link,
Snippet = item.snippet
});
}
return results;
}
catch(Exception)
{
return results;
}
}
}
}
}