-
Notifications
You must be signed in to change notification settings - Fork 0
/
odoa.py
77 lines (59 loc) · 2.63 KB
/
odoa.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
import random
import httpx
from httpx import Response
class ODOAException(Exception):
def __init__(self, message):
super().__init__(message)
class Quran(object):
__slots__ = ['ayah', 'desc', 'translate', 'sound']
def __init__(self, ayah: str, desc: str, translate: str, sound: str):
self.ayah = ayah
self.desc = desc
self.translate = translate
self.sound = sound
def __repr__(self):
return f'<{self.__class__.__name__}: {self.desc}>'
class ODOA(object):
__slots__ = ['__TOTAL_SURAH', '__BASE_API', '__SUPPORTED_LANGUAGES']
def __init__(self) -> None:
self.__TOTAL_SURAH = 114 # https://en.wikipedia.org/wiki/List_of_surahs_in_the_Quran
self.__BASE_API = 'https://raw.githubusercontent.com/argaghulamahmad/quranjson/master/source'
self.__SUPPORTED_LANGUAGES = ['id', 'en']
async def get_random_surah(self, lang: str = 'id') -> Quran:
if lang not in self.__SUPPORTED_LANGUAGES:
message = 'Currently your selected language not supported yet.'
raise ODOAException(message)
rand_surah = random.randint(1, self.__TOTAL_SURAH)
surah_url = f'{self.__BASE_API}/surah/surah_{rand_surah}.json'
try:
response = await self.__fetch(surah_url)
data = response.json()
except IOError:
raise ODOAException(f'Failed fetch surah {surah_url}')
else:
random_ayah = random.randint(1, int(data.get('count')))
ayah_key = f'verse_{random_ayah}'
ayah = data['verse'][ayah_key]
surah_index = data.get('index')
surah_name = data.get('name')
translation = await self.__get_translation(surah_index, ayah_key, lang)
sound = self.__get_sound(surah_index, random_ayah)
desc = f'{surah_name}:{random_ayah}'
return Quran(ayah, desc, translation, sound)
async def __get_translation(self, surah: int, ayah, lang: str) -> str:
url = f'{self.__BASE_API}/translation/{lang}/{lang}_translation_{int(surah)}.json'
try:
response = await self.__fetch(url)
data = response.json()
return data['verse'][ayah]
except ODOAException as e:
raise e
def __get_sound(self, surah: int, ayah: int) -> str:
format_ayah = str(ayah).zfill(3)
return f'{self.__BASE_API}/audio/{surah}/{format_ayah}.mp3'
@staticmethod
async def __fetch(url: str) -> Response:
async with httpx.AsyncClient() as client:
return await client.get(url)
def __repr__(self):
return f'<{self.__class__.__name__}>'