22
33namespace TelegramRSS \AccessControl ;
44
5+ use TelegramRSS \Client ;
56use TelegramRSS \Config ;
67
78final class ForbiddenPeers
89{
9- private static ?string $ regex = null ;
1010
11- private static $ errorTypes = [
12- 'USERNAME_INVALID ' ,
13- 'CHANNEL_PRIVATE ' ,
14- 'This peer is not present in the internal peer database ' ,
15- ];
11+ private static ?string $ regex = null ;
1612
1713 /** @var array<string, string> */
18- private static array $ peers = [];
14+ private static ?array $ peers = null ;
15+
16+ private const FILE = ROOT_DIR . '/cache/forbidden-peers.csv ' ;
17+ /** @var resource|null */
18+ private static $ filePointer = null ;
1919
2020 public static function add (string $ peer , string $ error ): void {
21+ if (
22+ $ error === Client::MESSAGE_CLIENT_UNAVAILABLE ||
23+ $ error === 'Empty message ' ||
24+ $ error === 'Connection closed unexpectedly ' ||
25+ stripos ($ error , Client::MESSAGE_FLOOD_WAIT ) !== false ||
26+ stripos ($ error , 'Media ' ) !== false
27+ ) {
28+ return ;
29+ }
30+
2131 $ peer = mb_strtolower ($ peer );
2232
23- foreach (self ::$ errorTypes as $ errorType ) {
24- if ($ errorType === $ error ) {
25- self ::$ peers [$ peer ] = $ error ;
26- break ;
27- }
28- }
33+ self ::$ peers [$ peer ] = $ error ;
34+ fputcsv (self ::getFilePointer (), [$ peer , $ error ]);
2935 }
3036
3137 /**
@@ -42,11 +48,34 @@ public static function check(string $peer): ?string {
4248 self ::$ regex = (string )Config::getInstance ()->get ('access.forbidden_peer_regex ' );
4349 }
4450
51+ if (self ::$ peers === null ) {
52+ if (file_exists (self ::FILE )) {
53+ $ file = self ::getFilePointer ();
54+ while (!feof ($ file )){
55+ [$ oldPeer , $ error ] = fgetcsv ($ file );
56+ if ($ oldPeer && $ error ) {
57+ self ::$ peers [$ oldPeer ] = $ error ;
58+ }
59+ }
60+ }
61+ }
62+
4563 $ regex = self ::$ regex ;
4664 if ($ regex && preg_match ("/ {$ regex }/i " , $ peer )) {
4765 return "PEER NOT ALLOWED " ;
4866 }
4967
5068 return self ::$ peers [$ peer ] ?? null ;
5169 }
70+
71+ /**
72+ * @return false|resource|null
73+ */
74+ private static function getFilePointer () {
75+ if (self ::$ filePointer === null ) {
76+ self ::$ filePointer = fopen (self ::FILE , 'cb+ ' );
77+ }
78+
79+ return self ::$ filePointer ;
80+ }
5281}
0 commit comments