2022-10-04 00:32:29 +00:00
|
|
|
import asyncio
|
2022-11-17 19:53:58 +00:00
|
|
|
import json
|
2023-12-17 20:30:20 +00:00
|
|
|
from typing import List
|
|
|
|
|
2023-11-29 07:23:41 +00:00
|
|
|
import aiohttp
|
2023-12-17 20:30:20 +00:00
|
|
|
|
2023-10-05 20:31:21 +00:00
|
|
|
from orm.shout import Shout
|
2023-12-17 20:30:20 +00:00
|
|
|
from services.rediscache import redis
|
2022-10-04 00:32:29 +00:00
|
|
|
|
|
|
|
|
|
|
|
class SearchService:
|
|
|
|
lock = asyncio.Lock()
|
|
|
|
cache = {}
|
|
|
|
|
|
|
|
@staticmethod
|
2022-10-04 09:25:59 +00:00
|
|
|
async def init(session):
|
|
|
|
async with SearchService.lock:
|
2023-11-24 01:53:30 +00:00
|
|
|
print("[services.search] did nothing")
|
2022-10-04 09:25:59 +00:00
|
|
|
SearchService.cache = {}
|
2022-10-04 00:32:29 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2023-12-17 20:30:20 +00:00
|
|
|
async def search(text, limit: int = 50, offset: int = 0) -> List[Shout]:
|
2022-11-17 20:29:04 +00:00
|
|
|
cached = await redis.execute("GET", text)
|
2022-11-17 19:53:58 +00:00
|
|
|
if not cached:
|
|
|
|
async with SearchService.lock:
|
2023-11-29 07:23:41 +00:00
|
|
|
# Use aiohttp to send a request to ElasticSearch
|
2023-12-17 20:30:20 +00:00
|
|
|
# TODO: add limit offset usage
|
2023-11-29 07:23:41 +00:00
|
|
|
async with aiohttp.ClientSession() as session:
|
2023-11-23 23:00:28 +00:00
|
|
|
search_url = f"https://search.discours.io/search?q={text}"
|
2023-11-29 07:23:41 +00:00
|
|
|
async with session.get(search_url) as response:
|
|
|
|
if response.status == 200:
|
|
|
|
payload = await response.json()
|
|
|
|
await redis.execute("SET", text, json.dumps(payload))
|
|
|
|
return payload
|
2022-11-17 19:53:58 +00:00
|
|
|
else:
|
|
|
|
return json.loads(cached)
|