-
Notifications
You must be signed in to change notification settings - Fork 2
/
tgviewer.py
128 lines (108 loc) · 3.46 KB
/
tgviewer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/bin/env python
import logging
import os
import glob
import asyncio
import zipfile
import shutil
from fastapi import FastAPI, Response, UploadFile
from pydantic import BaseModel
from typing import Optional
from fastapi.middleware.cors import CORSMiddleware
from tgindex import TgIndex
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
elasticsearch_url = os.environ["ELASTICSEARCH_URL"]
archives_base_dir = os.environ["ARCHIVES_BASE_DIR"]
app = FastAPI()
index = TgIndex(elasticsearch_url, archives_base_dir)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"], # for development purposes
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/sites")
async def list_sites():
return index.sites
class SearchRequest(BaseModel):
site_id: Optional[str] = None
query: str
sort: str
skip: Optional[int] = None
min_date: Optional[str] = None
class IndexRequest(BaseModel):
file_name: str
class UploadRequest(BaseModel):
url: str
file_name: str
@app.post("/search")
async def search(req: SearchRequest):
query = {"bool": {}}
if req.site_id is not None:
query["bool"]["filter"] = [{
"term": {
"site_id": req.site_id
}
}]
if req.query != '*':
query["bool"]["must"] =[
{
"query_string": {
"query": req.query,
"default_field": "text",
"analyzer": "russian"
}
}
]
if req.sort == 'relevance':
sort = ['_score']
elif req.sort == 'date':
sort = [{'date': {'order': 'desc'}}, '_score']
else:
raise Exception("Wrong sorting type")
logging.info("Requesting data for query: %s" % query)
resp = await index.es_client.search(
index=index.DATA_INDEX_NAME,
highlight={
"fields": {
"text": {
'fragmenter': 'simple'
}
}
},
query=query,
sort=sort,
size=10,
from_=req.skip
)
def format_message(x):
obj = x['_source']
obj['id'] = x['_id']
if 'highlight' in x:
obj['highlight'] = x['highlight']['text']
return obj
total = resp['hits']['total']['value']
return {'total': total, 'messages': list(map(format_message, resp['hits']['hits']))}
@app.get("/content/{site_id}/{media_type}/{media_name}")
async def get_media(site_id, media_type, media_name):
logging.info("Requested media %s %s from %s" % (media_type, media_name, site_id))
filename = index.sites_map[site_id]
if not filename.startswith("/"):
filename = index.working_dir + "/" + filename
with zipfile.ZipFile(filename, 'r') as archive:
with archive.open("%s/%s" % (media_type, media_name)) as src:
return Response(content=src.read())
@app.get("/admin/archives")
async def admin_list_archives():
return list(map(lambda x: {
'name': os.path.basename(x),
'size': os.path.getsize(x),
'info': index.index_info.get(os.path.basename(x), {})
}, glob.glob("%s/*zip" % archives_base_dir)))
@app.post("/admin/reindex")
async def admin_reindex(req: IndexRequest):
index.index_background(req.file_name)
@app.post("/admin/download")
async def admin_download(req: UploadRequest):
index.download(req.url, req.file_name)