From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: alina sireneva <alina@tei.su>
Date: Mon, 1 Jun 2026 18:26:33 +0400
Subject: hopefully fix video ads leak

---
 .../telegram/messenger/video/VideoAds.java    | 27 ++++++++++++++++---
 1 file changed, 23 insertions(+), 4 deletions(-)

diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/video/VideoAds.java b/TMessagesProj/src/main/java/org/telegram/messenger/video/VideoAds.java
index 0000000..0000000 100644
--- a/TMessagesProj/src/main/java/org/telegram/messenger/video/VideoAds.java
+++ b/TMessagesProj/src/main/java/org/telegram/messenger/video/VideoAds.java
@@ -108,13 +108,20 @@ public class VideoAds {
         }
     }
 
-//    private static LruCache<VideoAdsLocation, VideoAds> cached = new LruCache<>(3);
-    private static HashMap<VideoAdsLocation, VideoAds> cached = new HashMap<>();
+    private static LruCache<VideoAdsLocation, VideoAds> cached = new LruCache<VideoAdsLocation, VideoAds>(3) {
+        @Override
+        protected void entryRemoved(boolean evicted, VideoAdsLocation key, VideoAds oldValue, VideoAds newValue) {
+            if (oldValue != null && oldValue != newValue) {
+                oldValue.destroy();
+            }
+        }
+    };
 
     public static void dropCache() {
-        cached.clear();
+        cached.evictAll();
     }
 
+
     public static VideoAds make(
         int currentAccount,
         long dialogId,
@@ -245,7 +252,7 @@ public class VideoAds {
     private float currentMenuTranslationY;
 
     private void show() {
-        if (ads.isEmpty()) return;
+        if (ads.isEmpty() || bulletinFactory == null) return;
         final TLRPC.TL_sponsoredMessage ad = ads.get(0);
         final long showTime = System.currentTimeMillis() - currentBulletinPassedTime;
         bulletinShowTime = showTime;
@@ -551,6 +558,7 @@ public class VideoAds {
     }
 
     public void stop() {
+        onPopupCallback = null;
         if (bulletin != null) {
             currentBulletinPassedTime = System.currentTimeMillis() - bulletinShowTime;
             if (!ads.isEmpty()) {
@@ -570,6 +578,10 @@ public class VideoAds {
             currentMenu.dismiss();
             currentMenu = null;
         }
+        if (premiumSheet != null) {
+            premiumSheet.dismiss();
+            premiumSheet = null;
+        }
         bulletin = null;
         if (loading) {
             ConnectionsManager.getInstance(currentAccount).cancelRequest(requestId, true);
@@ -578,6 +590,13 @@ public class VideoAds {
         }
         AndroidUtilities.cancelRunOnUIThread(showRunnable);
         setWaitingPaused(true);
+        bulletinFactory = null;
+    }
+
+    private void destroy() {
+        stop();
+        ads.clear();
+        loaded = false;
     }
 
     public static class AdOptionsDrawable extends Drawable {
