Poszukiwacz/Serwer/Serwer.Infrastructure/Services/SearchService.cs

90 lines
3.1 KiB
C#
Raw Permalink Normal View History

using Google.Apis.Customsearch.v1;
using Google.Apis.Services;
using Newtonsoft.Json;
2021-01-09 14:44:14 +01:00
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;
2021-01-09 14:44:14 +01:00
private readonly IHistoryRepository _historyRepository;
private readonly IUserRepository _userRepository;
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)
{
_imageHandler = imageHandler;
2021-01-09 14:44:14 +01:00
_historyRepository = historyRepository;
_userRepository = userRepository;
}
2021-01-09 14:44:14 +01:00
public async Task<IList<SearchResultDTO>> Search(Guid userId, string query)
{
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);
2021-01-16 18:45:20 +01:00
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>();
2021-01-16 18:45:20 +01:00
try
{
2021-01-16 18:45:20 +01:00
foreach (var item in jsonData.items)
{
2021-01-16 18:45:20 +01:00
results.Add(new SearchResultDTO
{
Title = item.title,
Link = item.link,
Snippet = item.snippet
});
}
return results;
}
catch(Exception)
{
return results;
}
}
}
}
}