nova-api/api/db/providerkeys.py

107 lines
3.1 KiB
Python
Raw Normal View History

2023-10-04 23:24:55 +02:00
import os
import time
2023-10-06 23:05:38 +02:00
import random
2023-10-04 23:24:55 +02:00
import asyncio
2023-10-06 09:37:16 +02:00
import aiofiles
import aiofiles.os
2023-10-06 23:05:38 +02:00
from aiocache import cached
2023-10-04 23:24:55 +02:00
from dotenv import load_dotenv
2023-10-06 23:05:38 +02:00
from cachetools import TTLCache
2023-10-04 23:24:55 +02:00
from motor.motor_asyncio import AsyncIOMotorClient
load_dotenv()
2023-10-06 23:05:38 +02:00
cache = TTLCache(maxsize=100, ttl=10)
2023-10-04 23:24:55 +02:00
class KeyManager:
def __init__(self):
self.conn = AsyncIOMotorClient(os.environ['MONGO_URI'])
async def _get_collection(self, collection_name: str):
return self.conn['nova-core'][collection_name]
2023-10-04 23:24:55 +02:00
async def add_key(self, provider: str, key: str, source: str='?'):
db = await self._get_collection('providerkeys')
await db.insert_one({
'provider': provider,
'key': key,
'rate_limited_since': None,
'inactive_reason': None,
'source': source,
})
2023-10-06 23:05:38 +02:00
async def get_possible_keys(self, provider: str):
2023-10-04 23:24:55 +02:00
db = await self._get_collection('providerkeys')
2023-10-06 23:05:38 +02:00
keys = await db.find({
2023-10-04 23:24:55 +02:00
'provider': provider,
'inactive_reason': None,
'$or': [
2023-10-06 23:05:38 +02:00
{'rate_limited_until': None},
{'rate_limited_until': {'$lte': time.time()}}
2023-10-04 23:24:55 +02:00
]
2023-10-06 23:05:38 +02:00
}).to_list(length=None)
return keys
2023-10-04 23:24:55 +02:00
2023-10-06 23:05:38 +02:00
async def get_key(self, provider: str):
keys = await self.get_possible_keys(provider)
if not keys:
return '--NO_KEY--'
2023-10-04 23:24:55 +02:00
2023-10-06 23:05:38 +02:00
key = random.choice(keys)
api_key = key['key']
return api_key
2023-10-04 23:24:55 +02:00
2023-10-06 23:05:38 +02:00
async def rate_limit_key(self, provider: str, key: str, duration: int):
2023-10-04 23:24:55 +02:00
db = await self._get_collection('providerkeys')
await db.update_one({'provider': provider, 'key': key}, {
'$set': {
2023-10-06 23:05:38 +02:00
'rate_limited_until': time.time() + duration
2023-10-04 23:24:55 +02:00
}
})
async def deactivate_key(self, provider: str, key: str, reason: str):
db = await self._get_collection('providerkeys')
await db.update_one({'provider': provider, 'key': key}, {
'$set': {
'inactive_reason': reason
}
})
async def import_all(self):
db = await self._get_collection('providerkeys')
num = 0
2023-10-06 09:37:16 +02:00
for filename in await aiofiles.os.listdir(os.path.join('api', 'secret')):
2023-10-04 23:24:55 +02:00
if filename.endswith('.txt'):
2023-10-06 09:37:16 +02:00
async with aiofiles.open(os.path.join('api', 'secret', 'filename')) as f:
async for line in f:
2023-10-04 23:24:55 +02:00
if not line.strip():
continue
await db.insert_one({
'provider': filename.split('.')[0],
'key': line.strip(),
'source': 'import'
})
num += 1
print(f'[+] Imported {num} keys')
print('[+] Done importing keys!')
async def delete_empty_keys(self):
db = await self._get_collection('providerkeys')
await db.delete_many({'key': ''})
manager = KeyManager()
2023-10-06 23:05:38 +02:00
async def main():
keys = await manager.get_possible_keys('closed')
print(len(keys))
2023-10-04 23:24:55 +02:00
if __name__ == '__main__':
2023-10-06 23:05:38 +02:00
asyncio.run(main())