-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.py
167 lines (132 loc) · 5.38 KB
/
database.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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
from datetime import datetime, timedelta
from motor.motor_asyncio import AsyncIOMotorClient
from functools import wraps
from pymongo import InsertOne, UpdateOne
def singleton(cls):
instance = None
@wraps(cls)
def wrapper(*args, **kwargs):
nonlocal instance
if instance is None:
instance = cls(*args, **kwargs)
return instance
return wrapper
@singleton
class MongoDB:
def __init__(self, username, password, host, port, database):
mongodb_string = f"mongodb://{host}:{port}"
if username != "":
mongodb_string = f"mongodb://{username}:{password}@{host}:{port}"
self.client = AsyncIOMotorClient(mongodb_string)
self.db = self.client[database]
async def get_all_institutes(self):
response = await self.db.schedule.distinct("institute_local_name")
response.sort()
return response
async def get_file_names(self, institute_local_name):
sort_field = "file_name"
sort_direction = 1
sort_spec = {sort_field: sort_direction}
response = self.db.schedule.find(
{"institute_local_name": institute_local_name},
sort=sort_spec,
projection=["file_name"],
)
result = []
async for document in response:
result.append(document["file_name"])
return result
async def get_document_by_institute_local_name_and_file_name(
self, institute_local_name, file_name
):
response = await self.db.schedule.find_one(
{"institute_local_name": institute_local_name, "file_name": file_name}
)
return response
async def upsert_schedule(self, documents, time_limit):
requests = []
updated_documents = []
current_timestamp = datetime.now().timestamp()
for document in documents:
if document is None:
continue
collection_filter = {"file_link": document["file_link"]}
existing_doc = await self.db.schedule.find_one(collection_filter)
if (
existing_doc
and float(existing_doc["file_last_modified"])
< document["file_last_modified"]
):
requests.append(
UpdateOne(
collection_filter,
{
"$set": {
"file_last_modified": document["file_last_modified"],
"timestamp": document["timestamp"],
}
},
upsert=True,
)
)
updated_documents.append(document)
elif (
existing_doc
and existing_doc["timestamp"] + time_limit > current_timestamp
):
requests.append(
UpdateOne(
collection_filter,
{"$set": {"timestamp": document["timestamp"]}},
upsert=True,
)
)
elif not existing_doc:
requests.append(InsertOne(document))
if len(requests) == 0:
return []
await self.db.schedule.bulk_write(requests)
return updated_documents
async def delete_old_documents(self, time_limit):
now = datetime.now()
threshold = (now - timedelta(seconds=time_limit)).timestamp()
collection_filter = {"timestamp": {"$lt": threshold}}
response = self.db.schedule.find(collection_filter)
deleted_documents = []
async for document in response:
deleted_documents.append(document)
await self.db.schedule.delete_many(collection_filter)
return deleted_documents
async def subscribe_user(self, user_id, document_id):
collection_filter = {"_id": document_id}
update = {"$addToSet": {"subscribers": user_id}}
result = await self.db.schedule.update_one(collection_filter, update)
return result.modified_count == 1
async def check_is_user_subscribed(self, user_id, document_id):
collection_filter = {"_id": document_id}
document = await self.db.schedule.find_one(collection_filter)
if "subscribers" in document:
if user_id in document["subscribers"]:
return True
return False
async def unsubscribe_user(self, user_id, document_id):
collection_filter = {"_id": document_id}
update = {"$pull": {"subscribers": user_id}}
result = await self.db.schedule.update_one(collection_filter, update)
return result.modified_count == 1
async def get_document_by_id(self, document_id):
response = await self.db.schedule.find_one({"_id": document_id})
return response
async def get_documents_by_user_id(self, user_id):
collection_filter = {"subscribers": {"$in": [user_id]}}
sort_field = "institute_local_name"
sort_direction = 1
sort_spec = {sort_field: sort_direction}
# Выполняем запрос к базе данных
response = self.db.schedule.find(collection_filter, sort=sort_spec)
result = []
async for document in response:
result.append(document)
return result
def close_connection(self):
self.client.close()