PharaghY-codal 0.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pharaghy_codal/__init__.py +130 -0
- pharaghy_codal/client.py +417 -0
- pharaghy_codal/company.py +134 -0
- pharaghy_codal/constants.py +196 -0
- pharaghy_codal/financials.py +369 -0
- pharaghy_codal/letter.py +746 -0
- pharaghy_codal/models.py +102 -0
- pharaghy_codal/monthly.py +274 -0
- pharaghy_codal/search.py +355 -0
- pharaghy_codal/types.py +79 -0
- pharaghy_codal/utils.py +73 -0
- pharaghy_codal-0.3.1.dist-info/METADATA +262 -0
- pharaghy_codal-0.3.1.dist-info/RECORD +15 -0
- pharaghy_codal-0.3.1.dist-info/WHEEL +4 -0
- pharaghy_codal-0.3.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PharaghY_Codal
|
|
3
|
+
==============
|
|
4
|
+
|
|
5
|
+
کتابخانهٔ غیررسمی پایتون برای خواندن اطلاعیهها و گزارشهای سامانهٔ کدال
|
|
6
|
+
(https://www.codal.ir).
|
|
7
|
+
|
|
8
|
+
نقطهٔ ورود پیشنهادی::
|
|
9
|
+
|
|
10
|
+
import pharaghy_codal as fpyc
|
|
11
|
+
|
|
12
|
+
company = fpyc.get_company("شپنا")
|
|
13
|
+
items = fpyc.search_by_notice_code("خودرو", "ن-42")
|
|
14
|
+
letter = fpyc.get_letter(items[0].tracing_no)
|
|
15
|
+
fpyc.download_all_files(items[0].tracing_no, "out")
|
|
16
|
+
|
|
17
|
+
گروههای اصلی API
|
|
18
|
+
-----------------
|
|
19
|
+
* شرکت: ``get_company``, ``get_financial_years``
|
|
20
|
+
* جستجو: ``search_letters``, ``search_all``, ``search_by_notice_code``, ...
|
|
21
|
+
* خواندن: ``get_letter``, ``list_files``, ``letter_content_kind``
|
|
22
|
+
* دانلود: ``download_excel``, ``download_pdf``, ``download_attachments``, ``download_all_files``
|
|
23
|
+
* مالی/ماهانه: ``get_income_statement``, ``get_monthly_activity``, ...
|
|
24
|
+
* تنظیمات شبکه: ``configure_client``, ``CodalClient``, ``CodalError``
|
|
25
|
+
|
|
26
|
+
کدال معمولاً فقط از داخل ایران یا با پروکسی ایرانی پاسخ میدهد.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
from . import constants
|
|
32
|
+
from .client import CodalClient, CodalError, configure_client
|
|
33
|
+
from .company import get_company, get_financial_years
|
|
34
|
+
from .constants import (
|
|
35
|
+
NOTICE_CODES,
|
|
36
|
+
NOTICE_GROUPS,
|
|
37
|
+
list_notice_codes,
|
|
38
|
+
notice_group_of,
|
|
39
|
+
notice_title,
|
|
40
|
+
)
|
|
41
|
+
from .financials import (
|
|
42
|
+
get_income_statement,
|
|
43
|
+
get_letter_tables_as_frames,
|
|
44
|
+
list_financial_letters,
|
|
45
|
+
table_to_dataframe,
|
|
46
|
+
)
|
|
47
|
+
from .letter import (
|
|
48
|
+
download_all_files,
|
|
49
|
+
download_attachments,
|
|
50
|
+
download_excel,
|
|
51
|
+
download_file,
|
|
52
|
+
download_pdf,
|
|
53
|
+
get_letter,
|
|
54
|
+
letter_content_kind,
|
|
55
|
+
list_files,
|
|
56
|
+
)
|
|
57
|
+
from .models import Company, Letter, LetterSummary, LetterType, SearchResult
|
|
58
|
+
from .monthly import (
|
|
59
|
+
find_monthly_letter,
|
|
60
|
+
get_monthly_activity,
|
|
61
|
+
get_monthly_materials,
|
|
62
|
+
get_monthly_production_sales,
|
|
63
|
+
list_monthly_letters,
|
|
64
|
+
)
|
|
65
|
+
from .search import (
|
|
66
|
+
iter_letters,
|
|
67
|
+
normalize_letter_code,
|
|
68
|
+
search_all,
|
|
69
|
+
search_by_letter_type,
|
|
70
|
+
search_by_notice_code,
|
|
71
|
+
search_letters,
|
|
72
|
+
)
|
|
73
|
+
from .types import get_letter_groups, get_letter_types
|
|
74
|
+
|
|
75
|
+
__version__ = "0.3.1"
|
|
76
|
+
|
|
77
|
+
# API پایدار برای import عمومی — تا 1.0 تا حد ممکن حفظ میشود
|
|
78
|
+
__all__ = [
|
|
79
|
+
# meta
|
|
80
|
+
"__version__",
|
|
81
|
+
"constants",
|
|
82
|
+
# errors / client
|
|
83
|
+
"CodalClient",
|
|
84
|
+
"CodalError",
|
|
85
|
+
"configure_client",
|
|
86
|
+
# models
|
|
87
|
+
"Company",
|
|
88
|
+
"Letter",
|
|
89
|
+
"LetterSummary",
|
|
90
|
+
"LetterType",
|
|
91
|
+
"SearchResult",
|
|
92
|
+
# company
|
|
93
|
+
"get_company",
|
|
94
|
+
"get_financial_years",
|
|
95
|
+
# taxonomy
|
|
96
|
+
"NOTICE_CODES",
|
|
97
|
+
"NOTICE_GROUPS",
|
|
98
|
+
"list_notice_codes",
|
|
99
|
+
"notice_group_of",
|
|
100
|
+
"notice_title",
|
|
101
|
+
"get_letter_groups",
|
|
102
|
+
"get_letter_types",
|
|
103
|
+
"normalize_letter_code",
|
|
104
|
+
# search
|
|
105
|
+
"search_letters",
|
|
106
|
+
"iter_letters",
|
|
107
|
+
"search_all",
|
|
108
|
+
"search_by_letter_type",
|
|
109
|
+
"search_by_notice_code",
|
|
110
|
+
# read
|
|
111
|
+
"get_letter",
|
|
112
|
+
"list_files",
|
|
113
|
+
"letter_content_kind",
|
|
114
|
+
# download
|
|
115
|
+
"download_excel",
|
|
116
|
+
"download_pdf",
|
|
117
|
+
"download_file",
|
|
118
|
+
"download_attachments",
|
|
119
|
+
"download_all_files",
|
|
120
|
+
# financial / monthly helpers
|
|
121
|
+
"list_financial_letters",
|
|
122
|
+
"get_income_statement",
|
|
123
|
+
"get_letter_tables_as_frames",
|
|
124
|
+
"table_to_dataframe",
|
|
125
|
+
"list_monthly_letters",
|
|
126
|
+
"find_monthly_letter",
|
|
127
|
+
"get_monthly_activity",
|
|
128
|
+
"get_monthly_materials",
|
|
129
|
+
"get_monthly_production_sales",
|
|
130
|
+
]
|
pharaghy_codal/client.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
"""
|
|
2
|
+
لایهٔ HTTP برای ارتباط با کدال.
|
|
3
|
+
|
|
4
|
+
- فاصله بین درخواستها + retry روی timeout / قطع اتصال / HTTP 429
|
|
5
|
+
- پروکسی: PHARAGHY_CODAL_PROXY
|
|
6
|
+
- تنظیمات اختیاری از محیط:
|
|
7
|
+
PHARAGHY_CODAL_TIMEOUT, PHARAGHY_CODAL_MIN_INTERVAL,
|
|
8
|
+
PHARAGHY_CODAL_MAX_RETRIES, PHARAGHY_CODAL_CACHE_DIR
|
|
9
|
+
- کش حافظه + کش دیسک اختیاری
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import copy
|
|
15
|
+
import os
|
|
16
|
+
import random
|
|
17
|
+
import time
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
|
|
22
|
+
SEARCH = "https://search.codal.ir/api/search"
|
|
23
|
+
WWW = "https://www.codal.ir"
|
|
24
|
+
EXCEL = "https://excel.codal.ir"
|
|
25
|
+
|
|
26
|
+
MIN_INTERVAL = 2.0
|
|
27
|
+
JITTER = (0.2, 0.8)
|
|
28
|
+
BLOCK_COOLDOWN = 60
|
|
29
|
+
MAX_RATE_LIMIT_RETRIES = 3 # چند بار بعد از 429 صبر و تکرار
|
|
30
|
+
CACHE_MAX = 64
|
|
31
|
+
MAX_BODY = 8_000_000
|
|
32
|
+
MAX_RETRIES = 3
|
|
33
|
+
RETRY_BACKOFF = (2.0, 4.0, 8.0) # seconds between network retries
|
|
34
|
+
|
|
35
|
+
HEADERS = {
|
|
36
|
+
"Accept-Language": "fa-IR,fa;q=0.9,en;q=0.8",
|
|
37
|
+
"User-Agent": (
|
|
38
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
|
39
|
+
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
|
40
|
+
"Chrome/120.0.0.0 Safari/537.36"
|
|
41
|
+
),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
PAGE_HEADERS = {
|
|
45
|
+
**HEADERS,
|
|
46
|
+
"Accept": (
|
|
47
|
+
"text/html,application/xhtml+xml,application/xml;q=0.9,"
|
|
48
|
+
"image/avif,image/webp,image/apng,*/*;q=0.8"
|
|
49
|
+
),
|
|
50
|
+
"Upgrade-Insecure-Requests": "1",
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class CodalError(Exception):
|
|
55
|
+
"""خطای ارتباط با کدال یا پاسخ نامعتبر."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, message: str, status: int | None = None):
|
|
58
|
+
super().__init__(message)
|
|
59
|
+
self.status = status
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class CodalClient:
|
|
63
|
+
"""کلاینت همگام برای API و صفحات کدال."""
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
proxy: str | None = None,
|
|
68
|
+
min_interval: float | None = None,
|
|
69
|
+
timeout: float | None = None,
|
|
70
|
+
max_retries: int | None = None,
|
|
71
|
+
cache_dir: str | None = None,
|
|
72
|
+
):
|
|
73
|
+
"""
|
|
74
|
+
Parameters
|
|
75
|
+
----------
|
|
76
|
+
proxy :
|
|
77
|
+
آدرس پروکسی؛ پیشفرض از PHARAGHY_CODAL_PROXY
|
|
78
|
+
min_interval :
|
|
79
|
+
حداقل ثانیه بین دو درخواست (پیشفرض ۲ یا env)
|
|
80
|
+
timeout :
|
|
81
|
+
مهلت کل درخواست به ثانیه (پیشفرض ۴۵ یا env)
|
|
82
|
+
max_retries :
|
|
83
|
+
تعداد تلاش مجدد شبکه (پیشفرض ۳ یا env)
|
|
84
|
+
cache_dir :
|
|
85
|
+
اگر مسیر بدهی، پاسخهای JSON/متن روی دیسک هم کش میشوند
|
|
86
|
+
"""
|
|
87
|
+
env_proxy = os.environ.get("PHARAGHY_CODAL_PROXY", "").strip()
|
|
88
|
+
self._proxy = proxy or env_proxy or None
|
|
89
|
+
|
|
90
|
+
def _env_float(name: str, default: float) -> float:
|
|
91
|
+
raw = os.environ.get(name, "").strip()
|
|
92
|
+
if not raw:
|
|
93
|
+
return default
|
|
94
|
+
try:
|
|
95
|
+
return float(raw)
|
|
96
|
+
except ValueError:
|
|
97
|
+
return default
|
|
98
|
+
|
|
99
|
+
def _env_int(name: str, default: int) -> int:
|
|
100
|
+
raw = os.environ.get(name, "").strip()
|
|
101
|
+
if not raw:
|
|
102
|
+
return default
|
|
103
|
+
try:
|
|
104
|
+
return int(raw)
|
|
105
|
+
except ValueError:
|
|
106
|
+
return default
|
|
107
|
+
|
|
108
|
+
self._min_interval = (
|
|
109
|
+
MIN_INTERVAL if min_interval is None else float(min_interval)
|
|
110
|
+
)
|
|
111
|
+
if min_interval is None:
|
|
112
|
+
self._min_interval = _env_float("PHARAGHY_CODAL_MIN_INTERVAL", MIN_INTERVAL)
|
|
113
|
+
|
|
114
|
+
self._timeout = 45.0 if timeout is None else float(timeout)
|
|
115
|
+
if timeout is None:
|
|
116
|
+
self._timeout = _env_float("PHARAGHY_CODAL_TIMEOUT", 45.0)
|
|
117
|
+
|
|
118
|
+
self._max_retries = MAX_RETRIES if max_retries is None else int(max_retries)
|
|
119
|
+
if max_retries is None:
|
|
120
|
+
self._max_retries = _env_int("PHARAGHY_CODAL_MAX_RETRIES", MAX_RETRIES)
|
|
121
|
+
|
|
122
|
+
env_cache = os.environ.get("PHARAGHY_CODAL_CACHE_DIR", "").strip()
|
|
123
|
+
self._cache_dir = cache_dir or env_cache or None
|
|
124
|
+
if self._cache_dir:
|
|
125
|
+
os.makedirs(self._cache_dir, exist_ok=True)
|
|
126
|
+
|
|
127
|
+
self._last = 0.0
|
|
128
|
+
self._blocked_until = 0.0
|
|
129
|
+
self._cache: dict[tuple, tuple[float, float, Any]] = {}
|
|
130
|
+
self._client: httpx.Client | None = None
|
|
131
|
+
|
|
132
|
+
def _get_client(self) -> httpx.Client:
|
|
133
|
+
if self._client is None:
|
|
134
|
+
self._client = httpx.Client(
|
|
135
|
+
headers=HEADERS,
|
|
136
|
+
timeout=httpx.Timeout(self._timeout, connect=20.0),
|
|
137
|
+
proxy=self._proxy,
|
|
138
|
+
follow_redirects=True,
|
|
139
|
+
trust_env=False,
|
|
140
|
+
)
|
|
141
|
+
return self._client
|
|
142
|
+
|
|
143
|
+
def close(self) -> None:
|
|
144
|
+
if self._client is not None:
|
|
145
|
+
self._client.close()
|
|
146
|
+
self._client = None
|
|
147
|
+
|
|
148
|
+
def __enter__(self) -> CodalClient:
|
|
149
|
+
return self
|
|
150
|
+
|
|
151
|
+
def __exit__(self, *args: object) -> None:
|
|
152
|
+
self.close()
|
|
153
|
+
|
|
154
|
+
def _wait(self) -> None:
|
|
155
|
+
"""صبر برای فاصله بین درخواستها و پایان cooldown مربوط به 429."""
|
|
156
|
+
now = time.monotonic()
|
|
157
|
+
if self._blocked_until > now:
|
|
158
|
+
time.sleep(self._blocked_until - now + random.uniform(0.2, 1.0))
|
|
159
|
+
now = time.monotonic()
|
|
160
|
+
wait = self._last + self._min_interval + random.uniform(*JITTER) - now
|
|
161
|
+
if wait > 0:
|
|
162
|
+
time.sleep(wait)
|
|
163
|
+
|
|
164
|
+
def _cache_key_str(self, key: tuple) -> str:
|
|
165
|
+
import hashlib
|
|
166
|
+
import json
|
|
167
|
+
|
|
168
|
+
raw = json.dumps(key, ensure_ascii=False, sort_keys=True, default=str)
|
|
169
|
+
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:40]
|
|
170
|
+
|
|
171
|
+
def _cache_get(self, key: tuple) -> Any | None:
|
|
172
|
+
hit = self._cache.get(key)
|
|
173
|
+
if hit and time.monotonic() - hit[0] < hit[1]:
|
|
174
|
+
return copy.deepcopy(hit[2])
|
|
175
|
+
if self._cache_dir:
|
|
176
|
+
import json
|
|
177
|
+
from pathlib import Path
|
|
178
|
+
|
|
179
|
+
path = Path(self._cache_dir) / f"{self._cache_key_str(key)}.json"
|
|
180
|
+
if path.is_file():
|
|
181
|
+
try:
|
|
182
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
183
|
+
saved_at = float(payload.get("saved_at") or 0)
|
|
184
|
+
ttl = float(payload.get("ttl") or 0)
|
|
185
|
+
if time.time() - saved_at < ttl:
|
|
186
|
+
body = payload.get("body")
|
|
187
|
+
self._cache[key] = (time.monotonic(), ttl, copy.deepcopy(body))
|
|
188
|
+
return copy.deepcopy(body)
|
|
189
|
+
except Exception:
|
|
190
|
+
return None
|
|
191
|
+
return None
|
|
192
|
+
|
|
193
|
+
def _cache_set(self, key: tuple, ttl: float, body: Any) -> None:
|
|
194
|
+
if len(self._cache) >= CACHE_MAX:
|
|
195
|
+
self._cache.pop(next(iter(self._cache)))
|
|
196
|
+
self._cache[key] = (time.monotonic(), ttl, copy.deepcopy(body))
|
|
197
|
+
if self._cache_dir:
|
|
198
|
+
import json
|
|
199
|
+
from pathlib import Path
|
|
200
|
+
|
|
201
|
+
path = Path(self._cache_dir) / f"{self._cache_key_str(key)}.json"
|
|
202
|
+
try:
|
|
203
|
+
path.write_text(
|
|
204
|
+
json.dumps(
|
|
205
|
+
{"saved_at": time.time(), "ttl": ttl, "body": body},
|
|
206
|
+
ensure_ascii=False,
|
|
207
|
+
default=str,
|
|
208
|
+
),
|
|
209
|
+
encoding="utf-8",
|
|
210
|
+
)
|
|
211
|
+
except Exception:
|
|
212
|
+
pass
|
|
213
|
+
|
|
214
|
+
def _request(
|
|
215
|
+
self,
|
|
216
|
+
method: str,
|
|
217
|
+
url: str,
|
|
218
|
+
*,
|
|
219
|
+
params: dict[str, Any] | None = None,
|
|
220
|
+
headers: dict[str, str] | None = None,
|
|
221
|
+
stream: bool = False,
|
|
222
|
+
) -> httpx.Response:
|
|
223
|
+
"""
|
|
224
|
+
درخواست با:
|
|
225
|
+
- فاصله بین درخواستها
|
|
226
|
+
- retry روی timeout / قطع اتصال
|
|
227
|
+
- صبر + تکرار روی HTTP 429 (rate-limit کدال)
|
|
228
|
+
"""
|
|
229
|
+
last_err: Exception | None = None
|
|
230
|
+
rate_limit_hits = 0
|
|
231
|
+
|
|
232
|
+
for attempt in range(self._max_retries + 1 + MAX_RATE_LIMIT_RETRIES):
|
|
233
|
+
self._wait()
|
|
234
|
+
client = self._get_client()
|
|
235
|
+
try:
|
|
236
|
+
if stream:
|
|
237
|
+
r = client.stream(method, url, params=params, headers=headers)
|
|
238
|
+
self._last = time.monotonic()
|
|
239
|
+
return r # type: ignore[return-value]
|
|
240
|
+
r = client.request(method, url, params=params, headers=headers)
|
|
241
|
+
self._last = time.monotonic()
|
|
242
|
+
|
|
243
|
+
# rate-limit: صبر و تکرار
|
|
244
|
+
if r.status_code == 429:
|
|
245
|
+
rate_limit_hits += 1
|
|
246
|
+
self._blocked_until = time.monotonic() + BLOCK_COOLDOWN
|
|
247
|
+
if rate_limit_hits > MAX_RATE_LIMIT_RETRIES:
|
|
248
|
+
raise CodalError(
|
|
249
|
+
f"کدال پس از {MAX_RATE_LIMIT_RETRIES} بار صبر و تکرار "
|
|
250
|
+
f"(هر بار حدود {BLOCK_COOLDOWN} ثانیه) هنوز rate-limit میکند. "
|
|
251
|
+
"چند دقیقه بعد دوباره تلاش کنید.",
|
|
252
|
+
status=429,
|
|
253
|
+
)
|
|
254
|
+
# صبر اجباری؛ _wait بعدی هم _blocked_until را رعایت میکند
|
|
255
|
+
time.sleep(BLOCK_COOLDOWN + random.uniform(1.0, 3.0))
|
|
256
|
+
continue
|
|
257
|
+
|
|
258
|
+
return r
|
|
259
|
+
|
|
260
|
+
except CodalError:
|
|
261
|
+
raise
|
|
262
|
+
except (httpx.TimeoutException, httpx.ConnectError, httpx.ReadError) as e:
|
|
263
|
+
self._last = time.monotonic()
|
|
264
|
+
last_err = e
|
|
265
|
+
self.close()
|
|
266
|
+
if attempt >= self._max_retries:
|
|
267
|
+
break
|
|
268
|
+
delay = RETRY_BACKOFF[min(attempt, len(RETRY_BACKOFF) - 1)]
|
|
269
|
+
time.sleep(delay + random.uniform(0.1, 0.5))
|
|
270
|
+
except httpx.RequestError as e:
|
|
271
|
+
self._last = time.monotonic()
|
|
272
|
+
last_err = e
|
|
273
|
+
self.close()
|
|
274
|
+
if attempt >= self._max_retries:
|
|
275
|
+
break
|
|
276
|
+
delay = RETRY_BACKOFF[min(attempt, len(RETRY_BACKOFF) - 1)]
|
|
277
|
+
time.sleep(delay)
|
|
278
|
+
|
|
279
|
+
raise CodalError(
|
|
280
|
+
f"اتصال به کدال برقرار نشد پس از چند تلاش "
|
|
281
|
+
f"({type(last_err).__name__ if last_err else 'unknown'}). "
|
|
282
|
+
"کمی صبر کنید یا PHARAGHY_CODAL_PROXY را تنظیم کنید."
|
|
283
|
+
) from last_err
|
|
284
|
+
|
|
285
|
+
def fetch_json(
|
|
286
|
+
self,
|
|
287
|
+
url: str,
|
|
288
|
+
params: dict[str, Any] | None = None,
|
|
289
|
+
ttl: float = 120.0,
|
|
290
|
+
) -> Any:
|
|
291
|
+
"""GET و پارس JSON."""
|
|
292
|
+
query = {k: v for k, v in (params or {}).items() if v is not None}
|
|
293
|
+
key = (url, tuple(sorted(query.items())), False)
|
|
294
|
+
cached = self._cache_get(key)
|
|
295
|
+
if cached is not None:
|
|
296
|
+
return cached
|
|
297
|
+
|
|
298
|
+
headers = {
|
|
299
|
+
"Referer": f"{WWW}/",
|
|
300
|
+
"Accept": "application/json, text/plain, */*",
|
|
301
|
+
"Origin": WWW,
|
|
302
|
+
}
|
|
303
|
+
r = self._request("GET", url, params=query, headers=headers)
|
|
304
|
+
|
|
305
|
+
if r.status_code >= 400:
|
|
306
|
+
raise CodalError(f"کدال خطای HTTP {r.status_code} برگرداند.", status=r.status_code)
|
|
307
|
+
|
|
308
|
+
try:
|
|
309
|
+
body = r.json()
|
|
310
|
+
except ValueError as e:
|
|
311
|
+
raise CodalError("پاسخ کدال JSON معتبر نبود.") from e
|
|
312
|
+
|
|
313
|
+
self._cache_set(key, ttl, body)
|
|
314
|
+
return body
|
|
315
|
+
|
|
316
|
+
def fetch_text(
|
|
317
|
+
self,
|
|
318
|
+
url: str,
|
|
319
|
+
params: dict[str, Any] | None = None,
|
|
320
|
+
ttl: float = 3600.0,
|
|
321
|
+
) -> str:
|
|
322
|
+
"""GET صفحهٔ HTML."""
|
|
323
|
+
query = {k: v for k, v in (params or {}).items() if v is not None}
|
|
324
|
+
key = (url, tuple(sorted(query.items())), True)
|
|
325
|
+
cached = self._cache_get(key)
|
|
326
|
+
if cached is not None:
|
|
327
|
+
return cached
|
|
328
|
+
|
|
329
|
+
# captcha ممکن است با 200 برگردد؛ چند بار تکرار میکنیم
|
|
330
|
+
for captcha_try in range(MAX_RATE_LIMIT_RETRIES + 1):
|
|
331
|
+
r = self._request("GET", url, params=query, headers=PAGE_HEADERS)
|
|
332
|
+
content = r.content
|
|
333
|
+
if len(content) > MAX_BODY:
|
|
334
|
+
raise CodalError("پاسخ کدال بیش از حد بزرگ بود.")
|
|
335
|
+
if b"Captcha.aspx/GetCaptchaImage" in content:
|
|
336
|
+
self._blocked_until = time.monotonic() + BLOCK_COOLDOWN
|
|
337
|
+
if captcha_try >= MAX_RATE_LIMIT_RETRIES:
|
|
338
|
+
raise CodalError(
|
|
339
|
+
f"کدال captcha نشان داد و پس از {MAX_RATE_LIMIT_RETRIES} بار "
|
|
340
|
+
f"صبر و تکرار برطرف نشد.",
|
|
341
|
+
status=429,
|
|
342
|
+
)
|
|
343
|
+
time.sleep(BLOCK_COOLDOWN + random.uniform(1.0, 3.0))
|
|
344
|
+
continue
|
|
345
|
+
if r.status_code >= 400:
|
|
346
|
+
raise CodalError(
|
|
347
|
+
f"کدال خطای HTTP {r.status_code} برگرداند.", status=r.status_code
|
|
348
|
+
)
|
|
349
|
+
text = content.decode("utf-8", "replace")
|
|
350
|
+
self._cache_set(key, ttl, text)
|
|
351
|
+
return text
|
|
352
|
+
|
|
353
|
+
raise CodalError("کدال پاسخ HTML معتبر نداد.", status=429)
|
|
354
|
+
|
|
355
|
+
def fetch_bytes(self, url: str) -> bytes:
|
|
356
|
+
"""دانلود محتوای باینری/HTML (مثلاً اکسل یا PDF کدال) با retry."""
|
|
357
|
+
headers = {
|
|
358
|
+
**PAGE_HEADERS,
|
|
359
|
+
"Referer": f"{WWW}/",
|
|
360
|
+
}
|
|
361
|
+
r = self._request("GET", url, headers=headers)
|
|
362
|
+
if r.status_code >= 400:
|
|
363
|
+
raise CodalError(f"دانلود ناموفق بود (HTTP {r.status_code}).", r.status_code)
|
|
364
|
+
if len(r.content) > MAX_BODY:
|
|
365
|
+
raise CodalError("فایل دانلودشده بیش از حد بزرگ بود.")
|
|
366
|
+
return r.content
|
|
367
|
+
|
|
368
|
+
def download(self, url: str, path: str) -> str:
|
|
369
|
+
"""دانلود فایل و ذخیره در path."""
|
|
370
|
+
data = self.fetch_bytes(url)
|
|
371
|
+
with open(path, "wb") as f:
|
|
372
|
+
f.write(data)
|
|
373
|
+
return path
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
# کلاینت پیشفرض سراسری (lazy)
|
|
377
|
+
_default: CodalClient | None = None
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def get_default_client() -> CodalClient:
|
|
381
|
+
global _default
|
|
382
|
+
if _default is None:
|
|
383
|
+
_default = CodalClient()
|
|
384
|
+
return _default
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def set_default_client(client: CodalClient | None) -> None:
|
|
388
|
+
global _default
|
|
389
|
+
if _default is not None:
|
|
390
|
+
_default.close()
|
|
391
|
+
_default = client
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def configure_client(
|
|
395
|
+
*,
|
|
396
|
+
proxy: str | None = None,
|
|
397
|
+
min_interval: float | None = None,
|
|
398
|
+
timeout: float | None = None,
|
|
399
|
+
max_retries: int | None = None,
|
|
400
|
+
cache_dir: str | None = None,
|
|
401
|
+
) -> CodalClient:
|
|
402
|
+
"""
|
|
403
|
+
کلاینت پیشفرض را با تنظیمات جدید جایگزین میکند و همان را برمیگرداند.
|
|
404
|
+
|
|
405
|
+
مثال::
|
|
406
|
+
|
|
407
|
+
configure_client(timeout=60, min_interval=2.5, cache_dir=".codal_cache")
|
|
408
|
+
"""
|
|
409
|
+
client = CodalClient(
|
|
410
|
+
proxy=proxy,
|
|
411
|
+
min_interval=min_interval,
|
|
412
|
+
timeout=timeout,
|
|
413
|
+
max_retries=max_retries,
|
|
414
|
+
cache_dir=cache_dir,
|
|
415
|
+
)
|
|
416
|
+
set_default_client(client)
|
|
417
|
+
return client
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""جستجوی شرکت و سالهای مالی."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .client import SEARCH, CodalClient, CodalError, get_default_client
|
|
8
|
+
from .models import Company
|
|
9
|
+
from .utils import normalize_key, normalize_symbol, to_ascii
|
|
10
|
+
|
|
11
|
+
LOOKUP_TTL = 12 * 3600
|
|
12
|
+
|
|
13
|
+
MARKETS = {
|
|
14
|
+
0: "بورس تهران",
|
|
15
|
+
1: "فرابورس",
|
|
16
|
+
2: "ثبتشده پذیرفتهنشده",
|
|
17
|
+
3: "ثبتنشده نزد سازمان",
|
|
18
|
+
4: "بورس کالا",
|
|
19
|
+
5: "بورس انرژی",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
KINDS = {
|
|
23
|
+
1: "ناشر",
|
|
24
|
+
2: "کارگزار",
|
|
25
|
+
3: "نهاد مالی / صندوق",
|
|
26
|
+
4: "نهاد عمومی",
|
|
27
|
+
5: "شرکت دولتی",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
REPORTING = {
|
|
31
|
+
1000000: "تولیدی",
|
|
32
|
+
1000001: "ساختمانی",
|
|
33
|
+
1000002: "سرمایهگذاری",
|
|
34
|
+
1000003: "بانک",
|
|
35
|
+
1000004: "لیزینگ",
|
|
36
|
+
1000005: "خدماتی",
|
|
37
|
+
1000006: "بیمه",
|
|
38
|
+
1000007: "حملونقل دریایی",
|
|
39
|
+
1000008: "کشاورزی",
|
|
40
|
+
1000009: "تأمین سرمایه",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _companies(client: CodalClient) -> list[dict[str, Any]]:
|
|
45
|
+
body = client.fetch_json(f"{SEARCH}/v1/companies", ttl=LOOKUP_TTL)
|
|
46
|
+
if not isinstance(body, list) or not body:
|
|
47
|
+
raise CodalError("کدال لیست شرکتها را برنگرداند.")
|
|
48
|
+
return [c for c in body if isinstance(c, dict)]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def get_company(
|
|
52
|
+
query: str,
|
|
53
|
+
limit: int = 10,
|
|
54
|
+
*,
|
|
55
|
+
client: CodalClient | None = None,
|
|
56
|
+
) -> Company | list[Company]:
|
|
57
|
+
"""
|
|
58
|
+
پیدا کردن شرکت با نماد یا بخشی از نام.
|
|
59
|
+
|
|
60
|
+
اگر دقیقاً یک نتیجه با نماد برابر باشد، همان Company برگردانده میشود؛
|
|
61
|
+
در غیر این صورت لیست Companyها (حداکثر limit).
|
|
62
|
+
"""
|
|
63
|
+
c = client or get_default_client()
|
|
64
|
+
q = normalize_key(query)
|
|
65
|
+
if not q:
|
|
66
|
+
raise CodalError("query نباید خالی باشد.")
|
|
67
|
+
|
|
68
|
+
companies = _companies(c)
|
|
69
|
+
groups = c.fetch_json(f"{SEARCH}/v1/IndustryGroup", ttl=LOOKUP_TTL)
|
|
70
|
+
industry = (
|
|
71
|
+
{g.get("Id"): g.get("Name") for g in groups if isinstance(g, dict)}
|
|
72
|
+
if isinstance(groups, list)
|
|
73
|
+
else {}
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
ranked: list[tuple] = []
|
|
77
|
+
for row in companies:
|
|
78
|
+
sy = normalize_key(str(row.get("sy") or ""))
|
|
79
|
+
name = normalize_key(str(row.get("n") or ""))
|
|
80
|
+
if q == sy or q == name:
|
|
81
|
+
rank = 0
|
|
82
|
+
elif sy.startswith(q):
|
|
83
|
+
rank = 1
|
|
84
|
+
elif q in name:
|
|
85
|
+
rank = 2
|
|
86
|
+
elif q in sy:
|
|
87
|
+
rank = 3
|
|
88
|
+
else:
|
|
89
|
+
continue
|
|
90
|
+
# شرکتهای بورسی/فرابورسی اول
|
|
91
|
+
listed = row.get("st") not in (0, 1, 4, 5)
|
|
92
|
+
ranked.append((rank, listed, len(sy), row))
|
|
93
|
+
|
|
94
|
+
ranked.sort(key=lambda r: r[:3])
|
|
95
|
+
results: list[Company] = []
|
|
96
|
+
for *_, row in ranked[:limit]:
|
|
97
|
+
results.append(
|
|
98
|
+
Company(
|
|
99
|
+
symbol=to_ascii(row.get("sy")),
|
|
100
|
+
name=to_ascii(row.get("n")),
|
|
101
|
+
isic=to_ascii(row.get("i")) or None,
|
|
102
|
+
market=MARKETS.get(row.get("st")),
|
|
103
|
+
kind=KINDS.get(row.get("t")),
|
|
104
|
+
industry=to_ascii(industry.get(row.get("IG"))) or None,
|
|
105
|
+
reporting_type=REPORTING.get(row.get("RT")),
|
|
106
|
+
)
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
if not results:
|
|
110
|
+
raise CodalError(f"شرکتی با عبارت {query!r} پیدا نشد.")
|
|
111
|
+
|
|
112
|
+
# اگر دقیقاً یک match با نماد برابر باشد، همان را برگردان
|
|
113
|
+
exact = [r for r in results if normalize_key(r.symbol) == q]
|
|
114
|
+
if len(exact) == 1:
|
|
115
|
+
return exact[0]
|
|
116
|
+
if len(results) == 1:
|
|
117
|
+
return results[0]
|
|
118
|
+
return results
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def get_financial_years(
|
|
122
|
+
symbol: str,
|
|
123
|
+
*,
|
|
124
|
+
client: CodalClient | None = None,
|
|
125
|
+
) -> list[str]:
|
|
126
|
+
"""لیست پایان سالهای مالی شرکت (شمسی، جدیدترین اول)."""
|
|
127
|
+
c = client or get_default_client()
|
|
128
|
+
sy = normalize_symbol(symbol)
|
|
129
|
+
if not sy:
|
|
130
|
+
raise CodalError("symbol نباید خالی باشد.")
|
|
131
|
+
body = c.fetch_json(f"{SEARCH}/v1/financialYears", {"Symbol": sy}, ttl=LOOKUP_TTL)
|
|
132
|
+
if not isinstance(body, list):
|
|
133
|
+
raise CodalError("کدال سالهای مالی را برنگرداند.")
|
|
134
|
+
return [to_ascii(y) for y in body]
|