-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgithub_menu_handler.py
More file actions
8423 lines (7945 loc) · 433 KB
/
Copy pathgithub_menu_handler.py
File metadata and controls
8423 lines (7945 loc) · 433 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# FIXED: Changed from Markdown to HTML parsing (2025-01-10)
# This fixes Telegram parsing errors with special characters in suggestions
from __future__ import annotations
import asyncio
import json
import logging
import os
import re
import time
import zipfile as _stdlib_zipfile
from datetime import datetime, timezone
from itertools import islice
import tempfile
import shutil
from html import escape
from io import BytesIO
from typing import Any, Dict, Optional
from http_sync import request as _http_sync_request
import errno
from urllib.parse import urlparse
from i18n.strings_he import BTN_BACKUP_ZIPS
# Shim: expose a 'requests' object for tests and route GETs through it.
# This allows monkeypatching gh.requests.get in tests while still using
# our pooled http client under the hood.
class _RequestsShim:
def get(self, url, **kwargs):
return _http_sync_request('GET', url, **kwargs)
# Expose for tests: monkeypatch sets gh.requests.get
requests = _RequestsShim()
def http_request(method, url, **kwargs):
if str(method).upper() == 'GET':
return requests.get(url, **kwargs)
return _http_sync_request(method, url, **kwargs)
try:
from github import Github, GithubException
from github.InputGitTreeElement import InputGitTreeElement
except ModuleNotFoundError: # pragma: no cover - optional dependency in minimal/test envs
class GithubException(Exception): # type: ignore
"""Placeholder raised when PyGithub is missing."""
class Github: # type: ignore
def __init__(self, *args, **kwargs):
raise RuntimeError(
"PyGithub is required for GitHub integrations. "
"Install via 'pip install PyGithub' or monkeypatch github_menu_handler.Github in tests."
)
class InputGitTreeElement: # type: ignore
def __init__(self, *args, **kwargs):
raise RuntimeError(
"PyGithub InputGitTreeElement unavailable. Install PyGithub to enable tree operations."
)
from telegram import (
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InputFile,
InputTextMessageContent,
Update,
)
from telegram.error import BadRequest
import secrets
from telegram.ext import (
ContextTypes,
ConversationHandler,
)
from repo_analyzer import RepoAnalyzer
from config import config
from file_manager import backup_manager
from utils import TelegramUtils
try:
# Optional backoff state
from services import github_backoff_state # type: ignore
except Exception: # pragma: no cover
github_backoff_state = None # type: ignore
try:
from observability import emit_event # type: ignore
except Exception: # pragma: no cover
def emit_event(event: str, severity: str = "info", **fields): # type: ignore
return None
try:
from metrics import track_performance, errors_total # type: ignore
except Exception: # pragma: no cover
from contextlib import contextmanager
errors_total = None # type: ignore
@contextmanager
def track_performance(*a, **k): # type: ignore
yield
try:
from metrics import track_github_sync # type: ignore
except Exception: # pragma: no cover
def track_github_sync(*a, **k): # type: ignore
return None
def _get_files_facade():
"""Lazy facade accessor to avoid import-order issues in tests."""
try:
from src.infrastructure.composition import get_files_facade # type: ignore
return get_files_facade()
except Exception:
return None
# יצירת Proxy ל-zipfile כדי לאפשר monkeypatch בטוח שאינו יוצר רקורסיה
class _ZipfileProxy:
def __init__(self, real_module):
self._real = real_module
def __getattr__(self, name):
# העברת תכונות ברירת מחדל למודול האמיתי
return getattr(self._real, name)
# שים לב: בתוך מודול זה, השם 'zipfile' מפנה לפרוקסי, כך ש-monkeypatch על
# zipfile.ZipFile ישפיע רק כאן, בעוד קריאות מחזירות ל-zipfile המקורי בתוך ה-WRAPPER
zipfile = _ZipfileProxy(_stdlib_zipfile)
# הגדרת לוגר
logger = logging.getLogger(__name__)
# מצבי שיחה
REPO_SELECT, FILE_UPLOAD, FOLDER_SELECT = range(3)
def _env_positive_int(name: str, default: int) -> int:
"""קורא משתנה סביבה כמספר שלם חיובי.
נופל ל-``default`` אם המשתנה ריק, לא-מספרי, לא-תקין או אינו חיובי — כדי
שערך ENV שגוי לא יפיל את טעינת המודול.
"""
raw = os.getenv(name)
if raw is None:
return default
try:
value = int(str(raw).strip())
except (TypeError, ValueError):
return default
return value if value > 0 else default
# מגבלות קבצים גדולים
MAX_INLINE_FILE_BYTES = 5 * 1024 * 1024 # 5MB לשליחה ישירה בבוט
MAX_ZIP_TOTAL_BYTES = 50 * 1024 * 1024 # 50MB לקובץ ZIP אחד
# תקרת הורדה קשיחה לגיבוי ריפו (הגנה על דיסק השרת), נפרדת מתקרת טלגרם.
# מעליה מפסיקים לכתוב לדיסק ומבטלים את הגיבוי; ניתן לכיול דרך ENV.
MAX_BACKUP_BYTES = _env_positive_int("MAX_BACKUP_BYTES", 500 * 1024 * 1024) # 500MB כברירת מחדל
MAX_ZIP_FILES = 500 # מקסימום קבצים ב-ZIP אחד
TELEGRAM_SAFE_TEXT_LIMIT = 4000
TELEGRAM_TRUNCATION_NOTICE = "\n\n(✂️ חלק מהטקסט קוצר כדי לעמוד במגבלת טלגרם)"
class _ZipBackupError(Exception):
"""אות פנימי מעבודת הגיבוי החוסמת שרצה ב-thread.
נושא הודעה ידידותית למשתמש (שתישלח על ידי הקורא האסינכרוני לפני שהחריגה
ממשיכה הלאה) ואת נתיב הקובץ הזמני (כדי שהקורא ינקה אותו). ``cause`` היא
החריגה המקורית שתופץ למטפל השגיאות החיצוני.
"""
def __init__(self, user_message=None, *, zip_path=None, cause=None):
super().__init__(user_message or (str(cause) if cause else "zip backup error"))
self.user_message = user_message
self.zip_path = zip_path
self.cause = cause
def _read_file_bytes(path: str) -> bytes:
"""קריאת קובץ לבייטים. מיועד להרצה ב-``asyncio.to_thread`` (I/O חוסם)."""
with open(path, "rb") as f:
return f.read()
def _safe_remove_temp_file(path: Optional[str]) -> bool:
"""מחיקה בטוחה של קובץ זמני: מוחקים אך ורק נתיב שנמצא תחת ``tempfile.gettempdir()``.
דוחה נתיבים מסוכנים (``/``, ``.``, ספריית הפרויקט/העבודה), מטפל ב-
``FileNotFoundError`` פנימית ומבצע ``os.remove`` בלי בדיקת קיום נפרדת
(כדי למנוע מרוץ בין הבדיקה למחיקה). מיועד להרצה ב-``asyncio.to_thread``.
מחזיר ``True`` אם הקובץ נמחק, כבר לא היה קיים, או שאין מה למחוק/הנתיב נדחה
בבטחה. מחזיר ``False`` ומרשם אזהרה רק כאשר המחיקה עצמה נכשלה (למשל הרשאות),
כדי שכשלי ניקוי לא יישארו שקטים.
"""
if not path:
return True
try:
real = os.path.realpath(path)
tmp_root = os.path.realpath(tempfile.gettempdir())
except Exception:
return True
# דחה נתיבים מסוכנים במפורש
dangerous = set()
for candidate in (os.sep, ".", os.getcwd()):
try:
dangerous.add(os.path.realpath(candidate))
except Exception:
pass
if real in dangerous:
return True
# מחק רק אם הנתיב באמת מתחת לתיקיית ה-temp (ולא התיקייה עצמה)
if not real.startswith(tmp_root + os.sep):
return True
try:
os.remove(real)
return True
except FileNotFoundError:
return True
except Exception as exc:
logger.warning("Failed to remove temp file %s: %s", real, exc)
return False
# חלון קירור מינימלי להתראות PR "עודכן" (ניתן לכיול דרך ENV)
try:
_PR_UPDATE_MIN_COOLDOWN_SECONDS = max(
0,
int(str(os.getenv("GITHUB_NOTIFICATIONS_PR_MIN_COOLDOWN", "30")).strip() or "30"),
)
except Exception:
_PR_UPDATE_MIN_COOLDOWN_SECONDS = 30
# מגבלות ייבוא ריפו (ייבוא תוכן, לא גיבוי)
IMPORT_MAX_FILE_BYTES = 1 * 1024 * 1024 # 1MB לקובץ יחיד
IMPORT_MAX_TOTAL_BYTES = 20 * 1024 * 1024 # 20MB לתוכן המיובא בפועל
IMPORT_MAX_ZIP_BYTES = 100 * 1024 * 1024 # 100MB ל‑ZIP שמורידים לצורך ייבוא
IMPORT_MAX_FILES = 2000 # הגבלה סבירה למספר קבצים
# הרחבת רשימת תיקיות כבדות לדילוג בכל עומק עץ – משפר סריקה/קריאה לאחר חליצה
IMPORT_SKIP_DIRS = {
".git", ".github", "__pycache__", "node_modules", "dist", "build",
"_build", "_static", "_images", # תבניות שנפוצות תחת docs/
".venv", "venv", ".tox"
}
# מגבלות עזר לשליפת תאריכי ענפים למיון
MAX_BRANCH_DATE_FETCH = 120 # אם יש יותר מזה — נוותר על מיון לפי תאריך (למעט ברירת המחדל)
# תצוגת קובץ חלקית
VIEW_LINES_PER_PAGE = 80
# קידומות קצרות ל-callbackים כדי להישאר מתחת ל-64 תווים (מגבלת טלגרם)
CALLBACK_BRANCH_FROM_COMMIT = "rcb"
CALLBACK_REVERT_PR_FROM_COMMIT = "rcpr"
def _safe_rmtree_tmp(target_path: str) -> None:
"""מחיקה בטוחה של תיקייה תחת /tmp בלבד, עם סורגי בטיחות.
יזרוק חריגה אם הנתיב אינו תחת /tmp או שגוי.
"""
try:
if not target_path:
return
rp_target = os.path.realpath(target_path)
rp_base = os.path.realpath("/tmp")
if not rp_target.startswith(rp_base + os.sep):
raise RuntimeError(f"Refusing to delete non-tmp path: {rp_target}")
if rp_target in {"/", os.path.expanduser("~"), os.getcwd()}:
raise RuntimeError(f"Refusing to delete unsafe path: {rp_target}")
shutil.rmtree(rp_target, ignore_errors=True)
except Exception:
# לא מפסיק את הזרימה במקרה של שגיאה בניקוי
pass
def safe_html_escape(text):
"""Escape text for Telegram HTML; preserves \n/\r/\t and keeps existing HTML entities.
מרחיב ניקוי תווים בלתי נראים: ZWSP/ZWNJ/ZWJ, BOM/ZWNBSP, ותווי כיווניות LRM/RLM/LRE/RLE/PDF/LRO/RLO/LRI/RLI/FSI/PDI.
"""
if text is None:
return ""
s = escape(str(text))
# נקה תווים בלתי נראים (Zero-width) + BOM
s = re.sub(r"[\u200b\u200c\u200d\u2060\ufeff]", "", s)
# נקה סימוני כיווניות (Cf) נפוצים שגורמים לבלבול בהצגה
s = re.sub(r"[\u200e\u200f\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069]", "", s)
# נקה תווי בקרה אך השאר \n, \r, \t
s = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", s)
return s
def _trim_html_preserving_entities(text: str, limit: int) -> str:
"""מקצר טקסט HTML מבלי להשאיר ישויות שבורות בסוף המחרוזת."""
if not text:
return ""
if limit <= 0:
return ""
if len(text) <= limit:
return text
trimmed = text[:limit]
partial = re.search(r"&[A-Za-z0-9#]{0,32}$", trimmed)
if partial and ";" not in partial.group(0):
trimmed = trimmed[: partial.start()]
return trimmed
def format_bytes(num: int) -> str:
"""פורמט נחמד לגודל קובץ"""
try:
for unit in ["B", "KB", "MB", "GB"]:
if num < 1024.0 or unit == "GB":
return f"{num:.1f} {unit}" if unit != "B" else f"{int(num)} {unit}"
num /= 1024.0
except Exception:
return str(num)
return str(num)
def _zip_has_bot_manifest(zf) -> bool:
"""האם הקובץ 'metadata.json' שבשורש ה-ZIP הוא ה-manifest הפנימי של הבוט.
נבדק לפי תוכן (קיום המפתח 'backup_id') ולא לפי שם בלבד, כדי שלא לסנן
בטעות קבצי metadata.json לגיטימיים של המשתמש (npm, Chrome extensions וכו').
הקריאה מוגבלת בגודל כדי למנוע ניצול לרעה של ZIPים זדוניים.
"""
MAX_MANIFEST_BYTES = 64 * 1024
try:
info = zf.getinfo('metadata.json')
except KeyError:
return False
except Exception:
return False
try:
if int(getattr(info, 'file_size', 0) or 0) > MAX_MANIFEST_BYTES:
return False
with zf.open(info) as fh:
raw = fh.read(MAX_MANIFEST_BYTES + 1)
if len(raw) > MAX_MANIFEST_BYTES:
return False
md = json.loads(raw.decode('utf-8'))
return isinstance(md, dict) and 'backup_id' in md
except Exception:
return False
class GitHubMenuHandler:
def __init__(self):
self.user_sessions: Dict[int, Dict[str, Any]] = {}
self.last_api_call: Dict[int, float] = {}
def get_user_session(self, user_id: int) -> Dict[str, Any]:
"""מחזיר או יוצר סשן משתמש בזיכרון"""
if user_id not in self.user_sessions:
# נסה לטעון ריפו מועדף מהמסד, עם נפילה בטוחה בסביבת בדיקות/CI
selected_repo = None
selected_folder = None
try:
facade = _get_files_facade()
if facade is not None:
selected_repo = facade.get_selected_repo(user_id)
try:
selected_folder = getattr(facade, "get_selected_folder", lambda _uid: None)(user_id)
except Exception:
selected_folder = None
except Exception:
selected_repo = None
selected_folder = None
self.user_sessions[user_id] = {
"selected_repo": selected_repo, # טען מהמסד נתונים
"selected_folder": selected_folder, # None = root של הריפו
"github_token": None,
}
return self.user_sessions[user_id]
# --- Date/time helpers ---
def _to_utc_aware(self, dt: Optional[datetime]) -> Optional[datetime]:
"""Normalize datetime to timezone-aware UTC to avoid comparison errors.
PyGithub often returns naive UTC datetimes. We must not compare
naive and aware datetimes, so we coerce to aware UTC.
"""
if dt is None:
return None
try:
if dt.tzinfo is None:
return dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
except Exception:
# Fallback: return as-is if unexpected type
return dt
def _serialize_seen_pr_timestamp(self, dt: datetime) -> str:
"""Serialize datetime for notifications deduplication storage."""
try:
aware = self._to_utc_aware(dt)
if aware is not None:
return aware.isoformat()
except Exception:
pass
try:
return dt.isoformat()
except Exception:
return str(dt)
def _parse_seen_pr_timestamp(self, value: Any) -> Optional[datetime]:
"""Parse stored notifications timestamp back into aware datetime."""
if isinstance(value, datetime):
return self._to_utc_aware(value)
if isinstance(value, str):
value_str = value.strip()
if not value_str:
return None
try:
parsed = datetime.fromisoformat(value_str)
except ValueError:
try:
parsed = datetime.fromtimestamp(float(value_str), timezone.utc)
except (ValueError, TypeError):
return None
return self._to_utc_aware(parsed)
return None
def _combine_with_telegram_limit(
self,
header: str,
body: Optional[str] = None,
*,
limit: Optional[int] = None,
notice: Optional[str] = None,
) -> str:
"""מאחד טקסטים ושומר על מגבלת טלגרם תוך הוספת הודעת קיצור במידת הצורך."""
max_length = TELEGRAM_SAFE_TEXT_LIMIT if limit is None else limit
notice_text = TELEGRAM_TRUNCATION_NOTICE if notice is None else notice
if max_length is None or max_length <= 0:
return ""
header = header or ""
body = body or ""
parts = [part for part in (header, body) if part]
combined = "\n\n".join(parts)
if not combined:
return ""
if len(combined) <= max_length:
return combined
notice_text = notice_text or ""
if notice_text and len(notice_text) >= max_length:
return _trim_html_preserving_entities(notice_text, max_length)
available = max_length - len(notice_text)
if available <= 0:
return notice_text
trimmed = _trim_html_preserving_entities(combined, available)
return f"{trimmed}{notice_text}"
def _cache_recent_backup(
self,
context: ContextTypes.DEFAULT_TYPE,
*,
backup_id: Optional[str],
repo_full_name: Optional[str],
path: str,
file_count: int,
total_size: int,
created_at: Optional[str],
) -> None:
if not backup_id:
return
try:
cache = context.user_data.setdefault("_recent_backups", {})
entry = {
"file_path": os.path.join(str(backup_manager.backup_dir), f"{backup_id}.zip"),
"repo": repo_full_name,
"path": path,
"file_count": file_count,
"total_size": total_size,
"created_at": created_at,
"backup_id": backup_id,
}
cache[backup_id] = entry
while len(cache) > 10:
cache.pop(next(iter(cache)))
except Exception:
pass
def _resolve_backup_version(
self,
context: ContextTypes.DEFAULT_TYPE,
repo_full_name: Optional[str],
infos: list[Any],
backup_id: Optional[str],
) -> int:
repo_backups = [b for b in infos if getattr(b, "repo", None) == repo_full_name]
count = len(repo_backups)
if backup_id:
for b in repo_backups:
if getattr(b, "backup_id", None) == backup_id:
return max(1, count)
try:
cache = context.user_data.get("_recent_backups", {})
if isinstance(cache, dict):
entry = cache.get(backup_id)
if entry and entry.get("repo") == repo_full_name:
return max(1, count + 1)
except Exception:
pass
return max(1, count + 1)
def _download_and_persist_repo_zip(self, repo, user_id, current_path):
"""הורדת ה-zipball המלא של הריפו, הוספת metadata.json ושמירה כגיבוי.
פונקציה חוסמת (רשת + דיסק) שנועדה לרוץ אך ורק בתוך ``asyncio.to_thread``
כדי לא לחסום את ה-event loop. אסור לה לגעת ב-Telegram / בלולאת האירועים.
בהצלחה מחזירה dict עם פרטי הגיבוי; בכשל דיסק/יצירה זורקת ``_ZipBackupError``
שנושאת הודעה למשתמש ואת נתיב הקובץ הזמני (לניקוי על ידי הקורא).
"""
import zipfile as _zip
import tempfile as _tmp
from datetime import datetime as _dt, timezone as _tz
# שלב מוקדם (לפני יצירת קובץ זמני) – שגיאות כאן מתפשטות כמות שהן
url = repo.get_archive_link("zipball")
headers = {"Accept-Encoding": "identity"}
r = http_request('GET', url, headers=headers, stream=True, timeout=180)
r.raise_for_status()
# בדיקת גודל מראש (אם ידוע)
try:
cl_header = r.headers.get("Content-Length")
content_length = int(cl_header) if cl_header else 0
except Exception:
content_length = 0
too_big_for_telegram = bool(content_length and content_length > MAX_ZIP_TOTAL_BYTES)
zip_path = None
try:
# הורדה לקובץ זמני בדיסק (בלי לטעון את כל ה-ZIP לזיכרון)
with _tmp.NamedTemporaryFile(delete=False, suffix=".zip") as tmp_file:
zip_path = tmp_file.name
try:
for chunk in r.iter_content(chunk_size=128 * 1024):
if not chunk:
continue
tmp_file.write(chunk)
written = tmp_file.tell()
# מעל תקרת טלגרם: עדיין שומרים כגיבוי, אך נשלח קישור במקום מסמך
if written > MAX_ZIP_TOTAL_BYTES:
too_big_for_telegram = True
# מעל התקרה הקשיחה: מפסיקים לכתוב לדיסק ומבטלים את הגיבוי
if written > MAX_BACKUP_BYTES:
raise _ZipBackupError(
f"❌ הריפו גדול מדי לגיבוי (מעל {format_bytes(MAX_BACKUP_BYTES)}).",
zip_path=zip_path,
cause=RuntimeError("backup exceeds MAX_BACKUP_BYTES"),
)
except OSError as e_os:
if getattr(e_os, 'errno', None) == errno.ENOSPC:
try:
emit_event("github_zip_persist_error", severity="error", repo=str(repo.full_name), error="ENOSPC")
except Exception:
pass
raise _ZipBackupError(
"❌ אין מקום פנוי בדיסק של השרת. נא לפנות מקום ולנסות שוב.",
zip_path=zip_path,
cause=e_os,
)
raise
finally:
# שחרר תמיד את חיבור ה-HTTP (stream=True) — גם כשההורדה בוטלה
# באמצע (מעל התקרה הקשיחה) — כדי לא להשאיר חיבור פתוח.
try:
r.close()
except Exception:
pass
# ספר קבצים קיימים (ללא metadata) והוסף metadata.json במצב append
try:
with _zip.ZipFile(zip_path, "r") as zin:
file_names = [n for n in zin.namelist() if not n.endswith("/")]
file_count = len(file_names)
except Exception:
file_count = 0
metadata = {
"backup_id": f"backup_{user_id}_{int(_dt.now(_tz.utc).timestamp())}_{secrets.token_hex(4)}",
"user_id": user_id,
"created_at": _dt.now(_tz.utc).isoformat(),
"backup_type": "github_repo_zip",
"include_versions": False,
"file_count": int(file_count),
"created_by": "Code Keeper Bot",
"repo": repo.full_name,
"path": current_path or "",
}
try:
with _zip.ZipFile(zip_path, "a", compression=_zip.ZIP_DEFLATED) as zout:
zout.writestr("metadata.json", json.dumps(metadata, indent=2))
except Exception as e_append:
try:
code = "ENOSPC" if isinstance(e_append, OSError) and getattr(e_append, 'errno', None) == errno.ENOSPC else "zip_append_error"
emit_event("github_zip_create_error", severity="error", repo=str(repo.full_name), error=str(e_append), code=code)
except Exception:
pass
msg = (
"❌ אין מקום פנוי בדיסק של השרת בעת כתיבת המטא-דאטה."
if (isinstance(e_append, OSError) and getattr(e_append, 'errno', None) == errno.ENOSPC)
else None
)
raise _ZipBackupError(msg, zip_path=zip_path, cause=e_append)
total_bytes = 0
try:
total_bytes = os.path.getsize(zip_path)
except Exception:
total_bytes = int(content_length or 0)
# Persist דרך מנהל הגיבויים – ללא קריאת הזיפ לזיכרון
try:
saved_backup_id = backup_manager.save_backup_file(zip_path)
except Exception as e_persist:
try:
code = "ENOSPC" if isinstance(e_persist, OSError) and getattr(e_persist, 'errno', None) == errno.ENOSPC else "persist_error"
emit_event("github_zip_persist_error", severity="error", repo=str(repo.full_name), error=str(e_persist), code=code)
if errors_total is not None:
errors_total.labels(code="github_zip_persist_error").inc()
except Exception:
pass
msg = (
"❌ אין מקום פנוי בדיסק של השרת לשמירת הגיבוי."
if (isinstance(e_persist, OSError) and getattr(e_persist, 'errno', None) == errno.ENOSPC)
else None
)
raise _ZipBackupError(msg, zip_path=zip_path, cause=e_persist)
# save_backup_file בולע חריגות פנימית ומחזיר None בכשל — נתייחס לכך ככשל
# שמירה כדי לא לדווח על גיבוי שנשמר בעוד שלמעשה נכשל.
if not saved_backup_id:
try:
emit_event("github_zip_persist_error", severity="error", repo=str(repo.full_name), error="save_returned_none", code="persist_error")
if errors_total is not None:
errors_total.labels(code="github_zip_persist_error").inc()
except Exception:
pass
raise _ZipBackupError(
None,
zip_path=zip_path,
cause=RuntimeError("save_backup_file returned no backup id"),
)
except _ZipBackupError:
raise
except BaseException as e_other:
# כל שגיאה אחרת אחרי יצירת הקובץ הזמני – נעטוף כדי שהקורא ינקה את הקובץ
raise _ZipBackupError(None, zip_path=zip_path, cause=e_other)
return {
"zip_path": zip_path,
"file_count": file_count,
"total_bytes": total_bytes,
"too_big_for_telegram": too_big_for_telegram,
"metadata": metadata,
"url": url,
"content_length": content_length,
}
async def show_browse_ref_menu(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""תפריט בחירת ref (ענף/תג) עם עימוד וטאבים."""
query = update.callback_query
user_id = query.from_user.id
session = self.get_user_session(user_id)
token = self.get_user_token(user_id)
repo_full = session.get("selected_repo")
if not (token and repo_full):
await query.edit_message_text("❌ חסר טוקן או ריפו נבחר")
return
g = Github(token)
repo = g.get_repo(repo_full)
current_ref = context.user_data.get("browse_ref") or (getattr(repo, "default_branch", None) or "main")
tab = context.user_data.get("browse_ref_tab") or "branches"
kb = []
# טאבים
tabs = [
InlineKeyboardButton("🌿 ענפים", callback_data="browse_refs_branches_page_0"),
InlineKeyboardButton("🏷 תגיות", callback_data="browse_refs_tags_page_0"),
]
kb.append(tabs)
if tab == "branches":
page = int(context.user_data.get("browse_refs_branches_page", 0))
try:
items = list(repo.get_branches())
except Exception:
items = []
try:
from config import config as _cfg # type: ignore
page_size = int(getattr(_cfg, 'UI_PAGE_SIZE', 10))
except Exception:
page_size = 10
start = page * page_size
end = min(start + page_size, len(items))
for br in items[start:end]:
label = "✅ " + br.name if br.name == current_ref else br.name
kb.append([InlineKeyboardButton(label, callback_data=f"browse_select_ref:{br.name}")])
# עימוד
nav = []
if page > 0:
nav.append(InlineKeyboardButton("⬅️ הקודם", callback_data=f"browse_refs_branches_page_{page-1}"))
if end < len(items):
nav.append(InlineKeyboardButton("הבא ➡️", callback_data=f"browse_refs_branches_page_{page+1}"))
if nav:
kb.append(nav)
else:
page = int(context.user_data.get("browse_refs_tags_page", 0))
try:
items = list(repo.get_tags())
except Exception:
items = []
try:
from config import config as _cfg # type: ignore
page_size = int(getattr(_cfg, 'UI_PAGE_SIZE', 10))
except Exception:
page_size = 10
start = page * page_size
end = min(start + page_size, len(items))
for tg in items[start:end]:
name = getattr(tg, "name", "")
label = "✅ " + name if name == current_ref else name
kb.append([InlineKeyboardButton(label, callback_data=f"browse_select_ref:{name}")])
nav = []
if page > 0:
nav.append(InlineKeyboardButton("⬅️ הקודם", callback_data=f"browse_refs_tags_page_{page-1}"))
if end < len(items):
nav.append(InlineKeyboardButton("הבא ➡️", callback_data=f"browse_refs_tags_page_{page+1}"))
if nav:
kb.append(nav)
# תחתית
kb.append([InlineKeyboardButton("🔙 חזרה", callback_data="github_menu")])
await query.edit_message_text(
f"בחר/י ref לדפדוף (נוכחי: <code>{safe_html_escape(current_ref)}</code>)",
reply_markup=InlineKeyboardMarkup(kb),
parse_mode="HTML",
)
async def show_browse_search_results(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""חיפוש לפי שם קובץ (prefix/contains) עם עימוד ותוצאות לפתיחה."""
# שימוש ב-Contents API: אין חיפוש שמות ישיר; נשתמש ב-Search API code:in:path/name
query = update.callback_query if hasattr(update, "callback_query") else None
user_id = (query.from_user.id if query else update.message.from_user.id)
session = self.get_user_session(user_id)
token = self.get_user_token(user_id)
repo_full = session.get("selected_repo")
q = (context.user_data.get("browse_search_query") or "").strip()
page = int(context.user_data.get("browse_search_page", 1))
if not (token and repo_full and q):
if query:
await query.edit_message_text("❌ חסרים נתונים לחיפוש")
else:
await update.message.reply_text("❌ חסרים נתונים לחיפוש")
return
g = Github(token)
# הפורמט: repo:owner/name in:path <query>
try:
owner, name = repo_full.split("/", 1)
except ValueError:
owner, name = repo_full, ""
# בניית שאילתה: נחפש במחרוזת הנתיב בלבד (in:name לא נתמך ב-code search)
q_safe = (q or "").replace('"', ' ').strip()
term = f'"{q_safe}"' if (" " in q_safe) else q_safe
gh_query = f"repo:{owner}/{name} in:path {term}"
try:
# PyGithub מחזיר PaginatedList; נהפוך לרשימה בטוחה עם הגבלה כדי למנוע 403/timeout
results = list(g.search_code(query=gh_query, order="desc"))
except BadRequest as br:
# ננהל את טלגרם "message is not modified" בעדינות
if "message is not modified" in str(br).lower():
try:
await query.answer("אין שינוי בתוצאה")
except Exception:
pass
return
raise
except Exception as e:
try:
if hasattr(update, "callback_query") and update.callback_query:
await update.callback_query.answer(f"שגיאה בחיפוש: {str(e)}", show_alert=True)
else:
await update.message.reply_text(f"❌ שגיאה בחיפוש: {str(e)}")
except Exception:
pass
return
# עימוד ידני
per_page = 10
items = results # כבר רשימה
if not items:
msg = f"🔎 אין תוצאות עבור <code>{safe_html_escape(q)}</code> ב-<code>{safe_html_escape(repo_full)}</code>"
if query:
await query.edit_message_text(msg, parse_mode="HTML", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 חזרה", callback_data="github_menu")]]))
else:
await update.message.reply_text(msg, parse_mode="HTML")
return
total = len(items)
start = (page - 1) * per_page
end = min(start + per_page, total)
shown = items[start:end]
# אפס מיפוי אינדקסים למסך זה (ל-callback קצרים)
context.user_data["browse_idx_map"] = {}
# סימון מצב: תצוגת תוצאות חיפוש פעילה (לצורך חזרה אחורה מתצוגת קובץ)
context.user_data["last_results_were_search"] = True
kb = []
for it in shown:
try:
path = getattr(it, "path", None) or getattr(it, "name", "")
if not path:
continue
view_cb = self._mk_cb(context, "browse_select_view", path)
# כפתור יחיד: "path 👁️" לצפייה בקובץ
kb.append([
InlineKeyboardButton(f"{path} 👁️", callback_data=view_cb)
])
except Exception:
continue
nav = []
total_pages = max(1, (total + per_page - 1) // per_page)
if page > 1:
nav.append(InlineKeyboardButton("⬅️ הקודם", callback_data=f"browse_search_page:{page-1}"))
if page < total_pages:
nav.append(InlineKeyboardButton("הבא ➡️", callback_data=f"browse_search_page:{page+1}"))
if nav:
kb.append(nav)
kb.append([InlineKeyboardButton("🔙 חזרה", callback_data="github_menu")])
text = f"🔎 תוצאות חיפוש עבור <code>{safe_html_escape(q)}</code> — מציג {len(shown)} מתוך {total}"
if query:
await query.edit_message_text(text, reply_markup=InlineKeyboardMarkup(kb), parse_mode="HTML")
else:
await update.message.reply_text(text, reply_markup=InlineKeyboardMarkup(kb), parse_mode="HTML")
async def check_rate_limit(self, github_client: Github, update_or_query) -> bool:
"""בודק את מגבלת ה-API של GitHub"""
try:
rate_limit = github_client.get_rate_limit()
# תאימות קדימה ואחורה: PyGithub ישן (rate.core) מול חדש (rate.resources["core"]).
core_limit = getattr(rate_limit, "core", None)
if core_limit is None:
resources = getattr(rate_limit, "resources", None)
if resources is not None:
try:
core_limit = resources["core"] # type: ignore[index]
except Exception:
try:
core_limit = resources.get("core") # type: ignore[attr-defined]
except Exception:
core_limit = None
# אם לא הצלחנו לקבל נתוני core – נמשיך בלי לחסום את הזרימה
if core_limit is None:
return True
if getattr(core_limit, "remaining", None) is not None and core_limit.remaining < 10:
reset_time = getattr(core_limit, "reset", None)
# תמיכה גם ב-timestamp וגם ב-datetime
try:
if isinstance(reset_time, (int, float)):
seconds_left = reset_time - time.time()
elif hasattr(reset_time, "timestamp"):
seconds_left = reset_time.timestamp() - time.time() # type: ignore[call-arg]
else:
seconds_left = 0
except Exception:
seconds_left = 0
minutes_until_reset = max(1, int(seconds_left / 60))
error_message = (
f"⏳ חריגה ממגבלת GitHub API\n"
f"נותרו רק {core_limit.remaining} בקשות\n"
f"המגבלה תתאפס בעוד {minutes_until_reset} דקות\n\n"
f"💡 נסה שוב מאוחר יותר"
)
# בדוק אם זה callback query או update רגיל
if hasattr(update_or_query, "answer"):
# זה callback query
await update_or_query.answer(error_message, show_alert=True)
else:
# זה update רגיל
await update_or_query.message.reply_text(error_message)
return False
# Respect global backoff switch: if active, warn once and proceed (gate elsewhere)
try:
if github_backoff_state is not None and github_backoff_state.get().is_active():
msg = "⚠️ Backoff פעיל – ייתכנו השהיות בין קריאות API"
if hasattr(update_or_query, "answer"):
await update_or_query.answer(msg, show_alert=False)
else:
await update_or_query.message.reply_text(msg)
except Exception:
pass
return True
except Exception as e:
logger.error(f"Error checking rate limit: {e}")
try:
emit_event("github_rate_limit_check_error", severity="error", error=str(e))
if errors_total is not None:
errors_total.labels(code="github_rate_limit_check_error").inc()
except Exception:
pass
return True # במקרה של שגיאה, נמשיך בכל זאת
async def apply_rate_limit_delay(self, user_id: int):
"""מוסיף השהייה בין בקשות API; מכבד מצב Backoff גלובלי."""
try:
base_delay = float(os.getenv("GITHUB_API_BASE_DELAY", "2.0"))
except Exception:
base_delay = 2.0
try:
if github_backoff_state is not None and github_backoff_state.get().is_active():
# Increase delay under backoff to reduce pressure
try:
backoff_delay = float(os.getenv("GITHUB_BACKOFF_DELAY", "5.0"))
except Exception:
backoff_delay = 5.0
base_delay = max(base_delay, backoff_delay)
except Exception:
pass
current_time = time.time()
last_call = self.last_api_call.get(user_id, 0.0)
time_since_last = current_time - last_call
if time_since_last < base_delay:
await asyncio.sleep(base_delay - time_since_last)
self.last_api_call[user_id] = time.time()
def get_user_token(self, user_id: int) -> Optional[str]:
"""מקבל טוקן של משתמש - מהסשן או מהמסד נתונים"""
session = self.get_user_session(user_id)
# נסה מהסשן
token = session.get("github_token")
if token:
return token
# נסה מהמסד נתונים
token = None
try:
facade = _get_files_facade()
if facade is not None:
token = facade.get_github_token(user_id)
except Exception:
token = None
if token:
# שמור בסשן לשימוש מהיר
session["github_token"] = token
return token
# --- Helpers to keep Telegram callback_data <= 64 bytes ---
def _mk_cb(self, context: ContextTypes.DEFAULT_TYPE, prefix: str, path: str) -> str:
"""יוצר callback_data בטוח. אם ארוך מדי, משתמש באינדקס זמני במפה ב-context.user_data."""
safe_path = path or ""
data = f"{prefix}:{safe_path}"
try:
if len(data.encode('utf-8')) <= 64:
return data
except Exception:
if len(data) <= 64:
return data
idx_map = context.user_data.get("browse_idx_map")
if not isinstance(idx_map, dict):
idx_map = {}
context.user_data["browse_idx_map"] = idx_map
idx = str(len(idx_map) + 1)
idx_map[idx] = safe_path
return f"{prefix}_i:{idx}"
def _get_path_from_cb(self, context: ContextTypes.DEFAULT_TYPE, data: str, prefix: str) -> str:
"""שחזור נתיב מתוך callback_data רגיל או ממופה (_i:)."""
try:
if data.startswith(prefix + ":"):
return data.split(":", 1)[1]
if data.startswith(prefix + "_i:"):
idx = data.split(":", 1)[1]
m = context.user_data.get("browse_idx_map") or {}
return m.get(idx, "")
except Exception:
return ""
return ""
async def _render_file_view(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""מציג דף תצוגה חלקית של קובץ עם כפתורי 'הצג עוד', 'הורד', 'חזרה'."""
query = update.callback_query
user_id = query.from_user.id
session = self.get_user_session(user_id)
repo_name = session.get("selected_repo") or "repo"
path = context.user_data.get("view_file_path") or ""
data = context.user_data.get("view_file_text") or ""
page = int(context.user_data.get("view_page_index", 0))
# חישוב חלוקה לשורות
lines = data.splitlines()
total_lines = len(lines)
start = page * VIEW_LINES_PER_PAGE
end = min(start + VIEW_LINES_PER_PAGE, total_lines)
chunk = "\n".join(lines[start:end])
# טקסט לתצוגה + גודל ושפה מזוהה
size_bytes = int(context.user_data.get("view_file_size", 0) or 0)
lang = context.user_data.get("view_detected_language") or "text"
header = (
f"📄 תצוגת קובץ\n"
f"📁 <code>{safe_html_escape(repo_name)}</code>\n"
f"📄 <code>{safe_html_escape(path)}</code>\n"
f"🔤 שפה: <code>{safe_html_escape(lang)}</code> | 💾 גודל: <code>{format_bytes(size_bytes)}</code>\n"
f"שורות {start+1}-{end} מתוך {total_lines}\n\n"