Repository navigation
Expand file tree
/
Copy pathintegrations.py
More file actions
826 lines (694 loc) · 33.9 KB
/
Copy pathintegrations.py
File metadata and controls
826 lines (694 loc) · 33.9 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
"""
אינטגרציות עם שירותים חיצוניים - GitHub Gist, Pastebin, ועוד
External Integrations - GitHub Gist, Pastebin, and more
"""
import asyncio
import base64
import hashlib
import json
import logging
import secrets
from datetime import datetime, timezone, timedelta
import os
from typing import Any, Dict, List, NamedTuple, Optional
import requests
from github import Github, InputFileContent
from github.GithubException import (
BadCredentialsException,
GithubException,
RateLimitExceededException,
TwoFactorException,
)
from config import config
# מודול שורש טהור: כתובת ה-WebApp, בלי ברירת מחדל — ``None`` כשהמשתנה חסר או פגום.
from webapp_url import webapp_base_url
logger = logging.getLogger(__name__)
try:
from observability_instrumentation import traced, set_current_span_attributes
except Exception: # pragma: no cover
def traced(*_a, **_k): # type: ignore
def _inner(f):
return f
return _inner
def set_current_span_attributes(*_a, **_k): # type: ignore
return None
def set_span_attrs_quietly(attrs: Dict[str, Any]) -> None:
"""רישום מאפייני span שלא אמור להפיל את הזרימה העסקית.
נקודת הכשל היחידה של הטלמטריה בקובץ הזה. כשל בה נרשם ל-debug ונבלע,
אבל לא בשקט מוחלט — ``except: pass`` מסתיר גם באגים בקוד המדידה עצמו.
"""
try:
set_current_span_attributes(attrs)
except Exception:
logger.debug("failed to set span attributes", exc_info=True)
def _get_github_token() -> Optional[str]:
"""השג את טוקן ה-GitHub בצורה חסינה גם כשאין שדה על האובייקט."""
token = getattr(config, "GITHUB_TOKEN", None)
if token:
return token
# תאימות לאחור: ייתכן שטסטים מזריקים רק משתני סביבה ללא שדה בקונפיג
return os.getenv("GITHUB_TOKEN")
def _get_pastebin_api_key() -> Optional[str]:
"""השג את מפתח ה-API של Pastebin גם כשאין שדה ישיר על האובייקט."""
api_key = getattr(config, "PASTEBIN_API_KEY", None)
if api_key:
return api_key
# תאימות לאחור: תמיכה בטסטים שמגדירים רק משתנה סביבה
return os.getenv("PASTEBIN_API_KEY")
class GitHubGistIntegration:
"""אינטגרציה עם GitHub Gist.
``token`` מאפשר לעבוד בשם משתמש מסוים. בלעדיו נופלים לטוקן הגלובלי,
שנשאר לשימושים תפעוליים בלבד — Gist שנוצר בשם משתמש חייב לעבור דרך
``resolve_gist_for_user`` כדי שלא ייווצר תחת חשבון המערכת.
"""
# סטטוסים שמשמעותם "הטוקן עצמו פסול". חשוב לקרוא אותם רק אחרי שנשללו
# החריגות הייעודיות של PyGithub: 403 הוא גם הסטטוס של הגבלת קצב, ושם
# הטוקן דווקא תקין. סיווג לפי המספר בלבד היה שולח משתמש שמיצה מכסה
# לייצר טוקן חדש בגלל בעיה חולפת.
_AUTH_FAILURE_STATUSES = frozenset({401, 403, 404})
def __init__(self, token: Optional[str] = None):
self.github = None
self.user = None
# ``None`` = לא ניסינו, או שהצלחנו. ``True`` = הטוקן פסול.
# ``False`` = הכשל היה זמני (GitHub נפל / הגבלת קצב).
self.auth_failed: Optional[bool] = None
token = token or _get_github_token()
if token:
try:
self.github = Github(token)
user = self.github.get_user()
# ``get_user()`` מחזיר אובייקט עצל: PyGithub לא פונה ל-API עד
# שניגשים לשדה. בלי הגישה הזו טוקן שנשלל היה "מתחבר" בהצלחה,
# והכשל היה מתגלה רק בניסיון ליצור Gist. הערך עצמו לא נרשם —
# ``login`` הוא מזהה אישי.
_ = user.login
self.user = user
logger.debug("GitHub Gist integration ready")
except GithubException as e:
self.auth_failed = self._is_auth_failure(e)
logger.error(
"שגיאה בהתחברות ל-GitHub (type=%s, status=%s, auth_failure=%s)",
type(e).__name__,
getattr(e, "status", None),
self.auth_failed,
)
@classmethod
def _is_auth_failure(cls, error: GithubException) -> bool:
"""האם הכשל הוא בטוקן עצמו, או תקלה חולפת בצד GitHub.
PyGithub כבר מסווג את התגובה לתת-מחלקות (``createException``), אז
נשענים על הסיווג שלו במקום לנחש לפי קוד הסטטוס.
"""
if isinstance(error, RateLimitExceededException):
return False # הטוקן תקין, המכסה נגמרה
if isinstance(error, (BadCredentialsException, TwoFactorException)):
return True
return getattr(error, "status", None) in cls._AUTH_FAILURE_STATUSES
def is_available(self) -> bool:
"""בדיקה אם האינטגרציה זמינה"""
return self.github is not None and self.user is not None
@traced("integration.github.create_gist")
def create_gist(self, file_name: str, code: str, language: str,
description: str = "", public: bool = True) -> Optional[Dict[str, Any]]:
"""יצירת Gist חדש"""
if not self.is_available():
logger.error("GitHub Gist לא זמין - אין טוקן או שגיאה בהתחברות")
set_span_attrs_quietly({"status": "error", "reason": "unavailable"})
return None
try:
set_span_attrs_quietly({
"file_name": str(file_name or ""),
"language": str(language or ""),
"public": bool(public),
})
# הכנת תיאור
if not description:
description = f"קטע קוד {language} - {file_name}"
# יצירת הקבצים עבור ה-Gist
files = {file_name: InputFileContent(code)}
# יצירת ה-Gist
gist = self.user.create_gist(
public=public,
files=files,
description=description
)
result = {
"id": gist.id,
"url": gist.html_url,
"git_pull_url": gist.git_pull_url,
"git_push_url": gist.git_push_url,
"created_at": gist.created_at.isoformat(),
"description": gist.description,
"public": gist.public,
"files": {}
}
# הוספת מידע על הקבצים
for name, file_obj in gist.files.items():
result["files"][name] = {
"filename": file_obj.filename,
"type": file_obj.type,
"language": file_obj.language,
"size": file_obj.size,
"raw_url": file_obj.raw_url
}
logger.info(f"נוצר Gist בהצלחה: {gist.html_url}")
return result
except GithubException as e:
logger.error(f"שגיאה ביצירת Gist: {e}")
set_span_attrs_quietly({"status": "error", "error_signature": type(e).__name__})
return None
except Exception as e:
logger.error(f"שגיאה כללית ביצירת Gist: {e}")
set_span_attrs_quietly({"status": "error", "error_signature": type(e).__name__})
return None
@traced("integration.github.create_gist_multi")
def create_gist_multi(self, files_map: Dict[str, str], description: str = "", public: bool = True) -> Optional[Dict[str, Any]]:
"""יצירת Gist עם מספר קבצים"""
if not self.is_available():
logger.error("GitHub Gist לא זמין - אין טוקן או שגיאה בהתחברות")
set_span_attrs_quietly({"status": "error", "reason": "unavailable"})
return None
try:
if not description:
description = f"שיתוף קוד מרובה קבצים ({len(files_map)})"
files: Dict[str, InputFileContent] = {}
for name, content in files_map.items():
files[name] = InputFileContent(content)
gist = self.user.create_gist(
public=public,
files=files,
description=description
)
result: Dict[str, Any] = {
"id": gist.id,
"url": gist.html_url,
"git_pull_url": gist.git_pull_url,
"git_push_url": gist.git_push_url,
"created_at": gist.created_at.isoformat(),
"description": gist.description,
"public": gist.public,
"files": {}
}
for name, file_obj in gist.files.items():
result["files"][name] = {
"filename": file_obj.filename,
"type": file_obj.type,
"language": file_obj.language,
"size": file_obj.size,
"raw_url": file_obj.raw_url
}
logger.info(f"נוצר Gist מרובה קבצים בהצלחה: {gist.html_url}")
return result
except GithubException as e:
logger.error(f"שגיאה ביצירת Gist מרובה קבצים: {e}")
set_span_attrs_quietly({"status": "error", "error_signature": type(e).__name__})
return None
except Exception as e:
logger.error(f"שגיאה כללית ביצירת Gist מרובה קבצים: {e}")
set_span_attrs_quietly({"status": "error", "error_signature": type(e).__name__})
return None
def update_gist(self, gist_id: str, file_name: str, new_code: str) -> Optional[Dict[str, Any]]:
"""עדכון Gist קיים"""
if not self.is_available():
return None
try:
gist = self.github.get_gist(gist_id)
# עדכון הקובץ
files = {
file_name: {
"content": new_code
}
}
gist.edit(files=files)
logger.info(f"עודכן Gist: {gist.html_url}")
return {
"id": gist.id,
"url": gist.html_url,
"updated_at": datetime.now(timezone.utc).isoformat()
}
except GithubException as e:
logger.error(f"שגיאה בעדכון Gist: {e}")
return None
def get_user_gists(self, limit: int = 50) -> List[Dict[str, Any]]:
"""קבלת כל ה-Gists של המשתמש"""
if not self.is_available():
return []
try:
gists = []
for gist in self.user.get_gists()[:limit]:
gist_data = {
"id": gist.id,
"description": gist.description,
"url": gist.html_url,
"public": gist.public,
"created_at": gist.created_at.isoformat(),
"updated_at": gist.updated_at.isoformat(),
"files": list(gist.files.keys())
}
gists.append(gist_data)
logger.info(f"נמצאו {len(gists)} Gists")
return gists
except GithubException as e:
logger.error(f"שגיאה בקבלת Gists: {e}")
return []
def delete_gist(self, gist_id: str) -> bool:
"""מחיקת Gist"""
if not self.is_available():
return False
try:
gist = self.github.get_gist(gist_id)
gist.delete()
logger.info(f"נמחק Gist: {gist_id}")
return True
except GithubException as e:
logger.error(f"שגיאה במחיקת Gist: {e}")
return False
class PastebinIntegration:
"""אינטגרציה עם Pastebin"""
def __init__(self):
self.api_key = _get_pastebin_api_key()
self.base_url = "https://pastebin.com/api"
def is_available(self) -> bool:
"""בדיקה אם האינטגרציה זמינה"""
return bool(self.api_key)
@traced("integration.pastebin.create")
async def create_paste(self, code: str, file_name: str, language: str = None,
private: bool = True, expire: str = "1M") -> Optional[Dict[str, Any]]:
"""יצירת paste חדש"""
if not self.is_available():
logger.error("Pastebin לא זמין - אין API key")
set_span_attrs_quietly({"status": "error", "reason": "unavailable"})
return None
# מיפוי שפות ל-Pastebin format
language_map = {
'python': 'python',
'javascript': 'javascript',
'java': 'java',
'cpp': 'cpp',
'c': 'c',
'php': 'php',
'html': 'html5',
'css': 'css',
'sql': 'mysql',
'bash': 'bash',
'json': 'json',
'xml': 'xml',
'yaml': 'yaml',
'text': 'text'
}
pastebin_format = language_map.get(language, 'text')
# הכנת הפרמטרים
data = {
'api_dev_key': self.api_key,
'api_option': 'paste',
'api_paste_code': code,
'api_paste_name': file_name,
'api_paste_format': pastebin_format,
'api_paste_private': '1' if private else '0', # 0=public, 1=unlisted, 2=private
'api_paste_expire_date': expire # N=Never, 10M=10Minutes, 1H=1Hour, 1D=1Day, 1W=1Week, 2W=2Weeks, 1M=1Month, 6M=6Months, 1Y=1Year
}
try:
set_span_attrs_quietly({
"file_name": str(file_name or ""),
"language": str(language or ""),
"private": bool(private),
"expire": str(expire or ""),
})
from http_async import request as async_request # lazy import להימנע מתלויות מעגליות
async with async_request(
"POST",
f"{self.base_url}/api_post.php",
data=data,
service="pastebin",
endpoint="create_paste",
) as response:
result = await response.text()
if response.status == 200 and result.startswith('https://pastebin.com/'):
logger.info(f"נוצר Pastebin paste: {result}")
# חילוץ ID מה-URL
paste_id = result.split('/')[-1]
return {
"id": paste_id,
"url": result,
"raw_url": f"https://pastebin.com/raw/{paste_id}",
"created_at": datetime.now(timezone.utc).isoformat(),
"private": private,
"expire": expire,
"language": pastebin_format
}
else:
logger.error(f"שגיאה ביצירת Pastebin paste: {result}")
set_span_attrs_quietly({"status": "error", "error_signature": "PastebinError"})
return None
except Exception as e:
logger.error(f"שגיאה כללית ב-Pastebin: {e}")
set_span_attrs_quietly({"status": "error", "error_signature": type(e).__name__})
return None
@traced("integration.pastebin.get_content")
async def get_paste_content(self, paste_id: str) -> Optional[str]:
"""קבלת תוכן paste"""
try:
raw_url = f"https://pastebin.com/raw/{paste_id}"
from http_async import request as async_request
async with async_request(
"GET",
raw_url,
service="pastebin",
endpoint="get_content",
) as response:
if response.status == 200:
content = await response.text()
logger.info(f"נשלף תוכן מ-Pastebin: {paste_id}")
return content
else:
logger.error(f"שגיאה בשליפת תוכן מ-Pastebin: {response.status}")
set_span_attrs_quietly({"status": "error", "http.status_code": int(response.status)})
return None
except Exception as e:
logger.error(f"שגיאה בשליפת תוכן מ-Pastebin: {e}")
set_span_attrs_quietly({"status": "error", "error_signature": type(e).__name__})
return None
class CodeSharingService:
"""שירות משולב לשיתוף קוד"""
def __init__(self):
# אין כאן ``GitHubGistIntegration``: Gist נוצר תמיד בשם משתמש מסוים,
# דרך ``resolve_gist_for_user``. אינסטנס משותף כאן היה יוצר Gists של
# כל המשתמשים תחת חשבון המערכת — בדיוק הבאג שהפרדה הזו סוגרת.
self.pastebin = PastebinIntegration()
self.internal_shares = {} # לשיתוף פנימי בזיכרון (fallback)
def get_available_services(self) -> List[str]:
"""קבלת רשימת שירותים זמינים (Gist לא כאן — הוא לכל משתמש בנפרד)"""
services = []
if self.pastebin.is_available():
services.append("pastebin")
services.append("internal") # תמיד זמין
return services
@traced("integration.share_code")
async def share_code(self, service: str, file_name: str, code: str,
language: str, description: str = "", **kwargs) -> Optional[Dict[str, Any]]:
"""שיתוף קוד בשירות נבחר"""
set_span_attrs_quietly({
"service": str(service or ""),
"language": str(language or ""),
"file_name": str(file_name or ""),
})
if service == "gist":
# מסלול חסום בכוונה: השירות המשולב אינו מחזיק טוקן של משתמש,
# ושיתוף Gist חייב לעבור דרך ``resolve_gist_for_user``.
logger.error("share_code('gist') לא נתמך — יש להשתמש ב-resolve_gist_for_user")
set_span_attrs_quietly({"status": "error", "reason": "gist_requires_user_token"})
return None
elif service == "pastebin" and self.pastebin.is_available():
return await self.pastebin.create_paste(code, file_name, language, **kwargs)
elif service == "internal":
return self._create_internal_share(file_name, code, language, description)
else:
logger.error(f"שירות שיתוף לא זמין: {service}")
set_span_attrs_quietly({"status": "error", "reason": "service_unavailable"})
return None
def _create_internal_share(self, file_name: str, code: str,
language: str, description: str) -> Dict[str, Any]:
"""יצירת שיתוף פנימי ושמירתו במסד נתונים (עם TTL),
ונפילה לזיכרון אם ה-DB לא זמין."""
share_id = secrets.token_urlsafe(12)
now = datetime.now(timezone.utc)
# ברירת מחדל: שבוע
expires_at = now + timedelta(days=7)
stored_ok = False
try:
from database import db as _db
coll = _db.internal_shares_collection if hasattr(_db, 'internal_shares_collection') else None
# DatabaseManager חושף collection דרך manager; גישה עקיפה:
try:
coll = _db.internal_shares_collection or _db.db.internal_shares
except Exception:
try:
coll = _db.db.internal_shares
except Exception:
coll = None
if coll is None:
raise RuntimeError("internal_shares collection not available")
doc = {
"share_id": share_id,
"file_name": file_name,
"code": code,
"language": language,
"description": description,
"created_at": now,
"views": 0,
"expires_at": expires_at, # Date לשימוש ב-TTL
}
coll.insert_one(doc)
stored_ok = True
except Exception as e:
logger.warning(f"DB not available for internal share; using memory store. Error: {e}")
self.internal_shares[share_id] = {
"id": share_id,
"file_name": file_name,
"code": code,
"language": language,
"description": description,
"created_at": now.isoformat(),
"views": 0,
"expires_at": expires_at.isoformat(),
}
# ה-WebApp מגיש את /share/<id> מאותו אוסף (internal_shares). בלי כתובת — נתיב יחסי, שהקורא
# (``bot_handlers``) לא מציג כקישור. הכתובת כבר נבדקה ל-https ובלי / בסוף (``webapp_url.py``).
base = webapp_base_url()
internal_url = f"{base}/share/{share_id}" if base else f"/share/{share_id}"
result = {
"id": share_id,
"url": internal_url,
"created_at": (now.isoformat()),
"expires_at": expires_at.isoformat(),
"service": "internal",
}
logger.info(f"נוצר שיתוף פנימי: {share_id} (stored_in_db={stored_ok})")
return result
def get_internal_share(self, share_id: str) -> Optional[Dict[str, Any]]:
"""קבלת שיתוף פנימי מה-DB (אם קיים), אחרת מזיכרון."""
# קודם נסה DB
try:
from database import db as _db
coll = None
try:
coll = _db.internal_shares_collection or _db.db.internal_shares
except Exception:
coll = _db.db.internal_shares
if coll is not None:
doc = coll.find_one({"share_id": share_id})
if doc:
# TTL ימחק רשומות פגות, אז אם קיים — עדיין בתוקף
try:
coll.update_one({"_id": doc["_id"]}, {"$inc": {"views": 1}})
except Exception:
pass
# החזר מבנה אחיד
return {
"id": doc.get("share_id"),
"file_name": doc.get("file_name"),
"code": doc.get("code"),
"language": doc.get("language"),
"description": doc.get("description"),
"created_at": (doc.get("created_at").isoformat() if isinstance(doc.get("created_at"), datetime) else doc.get("created_at")),
"expires_at": (doc.get("expires_at").isoformat() if isinstance(doc.get("expires_at"), datetime) else doc.get("expires_at")),
"views": int(doc.get("views") or 0),
}
except Exception as e:
logger.warning(f"DB get_internal_share failed; trying memory. Error: {e}")
# נפילה לזיכרון
share_data = self.internal_shares.get(share_id)
if not share_data:
return None
# בדיקת תפוגה
try:
exp = share_data.get("expires_at")
exp_dt = datetime.fromisoformat(exp) if isinstance(exp, str) else exp
if datetime.now(timezone.utc) > exp_dt:
try:
del self.internal_shares[share_id]
except Exception:
pass
return None
except Exception:
pass
try:
share_data["views"] = int(share_data.get("views", 0)) + 1
except Exception:
pass
return share_data
class GitRepositoryIntegration:
"""אינטגרציה עם Git repositories (למשתמשים מתקדמים)"""
def __init__(self):
self.github = None
token = _get_github_token()
if token:
try:
self.github = Github(token)
except Exception as e:
logger.error(f"שגיאה בהתחברות ל-GitHub: {e}")
def is_available(self) -> bool:
"""בדיקה אם האינטגרציה זמינה"""
return self.github is not None
def create_repository_file(self, repo_name: str, file_path: str,
content: str, commit_message: str = None) -> Optional[Dict[str, Any]]:
"""יצירת קובץ ב-repository"""
if not self.is_available():
return None
try:
user = self.github.get_user()
repo = user.get_repo(repo_name)
if not commit_message:
commit_message = f"Add {file_path}"
# יצירת הקובץ
result = repo.create_file(
path=file_path,
message=commit_message,
content=content
)
return {
"sha": result["commit"].sha,
"url": result["content"].html_url,
"download_url": result["content"].download_url,
"commit_url": result["commit"].html_url
}
except Exception as e:
logger.error(f"שגיאה ביצירת קובץ ב-repository: {e}")
return None
def get_user_repositories(self, limit: int = 50) -> List[Dict[str, Any]]:
"""קבלת repositories של המשתמש"""
if not self.is_available():
return []
try:
user = self.github.get_user()
repos = []
for repo in user.get_repos()[:limit]:
repos.append({
"name": repo.name,
"full_name": repo.full_name,
"description": repo.description,
"url": repo.html_url,
"private": repo.private,
"language": repo.language,
"stars": repo.stargazers_count,
"forks": repo.forks_count,
"created_at": repo.created_at.isoformat(),
"updated_at": repo.updated_at.isoformat()
})
return repos
except Exception as e:
logger.error(f"שגיאה בקבלת repositories: {e}")
return []
class WebhookIntegration:
"""אינטגרציה עם webhooks (להתראות ועדכונים)"""
def __init__(self):
self.webhooks = {}
def register_webhook(self, user_id: int, webhook_url: str,
events: List[str] = None) -> str:
"""רישום webhook"""
if events is None:
events = ["file_created", "file_updated", "file_deleted"]
webhook_id = secrets.token_urlsafe(16)
self.webhooks[webhook_id] = {
"user_id": user_id,
"url": webhook_url,
"events": events,
"created_at": datetime.now(timezone.utc).isoformat(),
"active": True
}
logger.info(f"נרשם webhook: {webhook_id} עבור משתמש {user_id}")
return webhook_id
async def trigger_webhook(self, user_id: int, event: str, data: Dict[str, Any]):
"""הפעלת webhook"""
# מציאת webhooks רלוונטיים
relevant_webhooks = [
webhook for webhook in self.webhooks.values()
if webhook["user_id"] == user_id and event in webhook["events"] and webhook["active"]
]
if not relevant_webhooks:
return
# שליחת נתונים לכל webhook
payload = {
"event": event,
"timestamp": datetime.now(timezone.utc).isoformat(),
"user_id": user_id,
"data": data
}
from http_async import request as async_request
for webhook in relevant_webhooks:
try:
async with async_request(
"POST",
webhook["url"],
json=payload,
headers={"Content-Type": "application/json"},
service="webhook",
endpoint="trigger",
) as response:
if response.status == 200:
logger.info(f"Webhook נשלח בהצלחה: {webhook['url']}")
else:
logger.warning(f"Webhook החזיר שגיאה {response.status}: {webhook['url']}")
except asyncio.TimeoutError:
logger.warning(f"Webhook timeout: {webhook['url']}")
except Exception as e:
logger.error(f"שגיאה בשליחת webhook: {e}")
GIST_NEEDS_GITHUB_MESSAGE = (
"🔗 כדי לשתף ב-Gist צריך לחבר את חשבון ה-GitHub שלך.\n\n"
"ה-Gist ייווצר תחת החשבון שלך — כך הוא נשאר שלך ומופיע ברשימת ה-Gists שלך.\n\n"
"לחיבור: תפריט ראשי ← 🔧 GitHub\n"
"לחלופין אפשר לשתף דרך 📋 Pastebin, שלא דורש חיבור."
)
# תקלה טכנית היא לא "לא חיברת GitHub". משתמש מחובר שה-DB נפל לרגע אמור לראות
# "נסה שוב", לא הנחיה לחבר חשבון שכבר מחובר — ולכן שתי ההודעות נפרדות.
GIST_TEMPORARY_FAILURE_MESSAGE = (
"❌ לא הצלחנו לגשת לחיבור ה-GitHub שלך כרגע. נסה שוב בעוד רגע."
)
class GistResolution(NamedTuple):
"""תוצאת ניסיון לבנות אינטגרציית Gist בשם משתמש.
``integration`` קיים רק כשהכול תקין. אחרת ``error_message`` מכיל את
ההודעה שצריך להציג למשתמש — והיא שונה בין "לא חיברת" ל"תקלה זמנית".
"""
integration: Optional["GitHubGistIntegration"]
error_message: Optional[str]
def resolve_gist_for_user(user_id: int) -> GistResolution:
"""בונה אינטגרציית Gist שפועלת בשם המשתמש.
ה-Gist נוצר תחת החשבון שהטוקן שייך לו. שימוש בטוקן הגלובלי היה יוצר
את כל ה-Gists של כל המשתמשים תחת חשבון המערכת — ולכן כאן אין נפילה
אליו בשום מסלול, גם לא בכשל.
הקריאה חוסמת (DB + רשת), ולכן מתוך handler אסינכרוני יש לקרוא לה דרך
``asyncio.to_thread`` כדי לא לתקוע את ה-event loop.
"""
if not user_id:
return GistResolution(None, GIST_NEEDS_GITHUB_MESSAGE)
try:
from database import db as _db
token = _db.get_github_token(int(user_id))
except Exception:
# fail-closed מכוון, ורחב במכוון: כל כשל בטעינת הטוקן — תקלת DB,
# שינוי API, באג בקוד — מסתיים באי-יצירת Gist ולא בנפילה לטוקן
# המערכת. ה-``logger.exception`` הוא מה שמונע בליעה שקטה: הבאג מגיע
# ל-Sentry עם ה-traceback, גם כשהמשתמש רואה רק "נסה שוב".
logger.exception("failed to load user github token for gist")
return GistResolution(None, GIST_TEMPORARY_FAILURE_MESSAGE)
if not token:
return GistResolution(None, GIST_NEEDS_GITHUB_MESSAGE)
try:
integration = GitHubGistIntegration(token=token)
except Exception:
logger.exception("failed to build gist integration for user")
return GistResolution(None, GIST_TEMPORARY_FAILURE_MESSAGE)
if not integration.is_available():
# יש טוקן שמור אבל ההתחברות נכשלה. אם GitHub דחה את הטוקן — צריך
# לחבר מחדש; אם GitHub נפל או הגביל קצב — הטוקן בסדר וצריך רק לנסות
# שוב. שליחת "חבר מחדש" על 500 שולחת את המשתמש לתקן משהו תקין.
if integration.auth_failed is False:
return GistResolution(None, GIST_TEMPORARY_FAILURE_MESSAGE)
return GistResolution(None, GIST_NEEDS_GITHUB_MESSAGE)
return GistResolution(integration, None)
# יצירת אינסטנסים גלובליים. אין כאן ``gist_integration``: אינסטנס גלובלי היה
# נבנה עם הטוקן של המערכת, וכל שימוש בו היה יוצר Gist תחת חשבון הבוט —
# ל-Gist של משתמש יש להשתמש ב-``resolve_gist_for_user``.
pastebin_integration = PastebinIntegration()
code_sharing = CodeSharingService()
git_integration = GitRepositoryIntegration()
webhook_integration = WebhookIntegration()