diff --git a/TMessagesProj/build.gradle b/TMessagesProj/build.gradle
index 5fbedf976..7aa13b57d 100644
--- a/TMessagesProj/build.gradle
+++ b/TMessagesProj/build.gradle
@@ -3,7 +3,7 @@ buildscript {
mavenCentral()
}
dependencies {
- classpath 'com.android.tools.build:gradle:1.0.0'
+ classpath 'com.android.tools.build:gradle:1.1.3'
}
}
apply plugin: 'com.android.application'
@@ -13,7 +13,7 @@ repositories {
}
dependencies {
- compile 'com.android.support:support-v4:21.0.+'
+ compile 'com.android.support:support-v4:22.0.+'
compile 'com.google.android.gms:play-services:3.2.+'
compile 'net.hockeyapp.android:HockeySDK:3.5.+'
compile 'com.googlecode.mp4parser:isoparser:1.0.+'
@@ -21,8 +21,8 @@ dependencies {
}
android {
- compileSdkVersion 21
- buildToolsVersion '21.1.2'
+ compileSdkVersion 22
+ buildToolsVersion '22.0.1'
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
@@ -81,8 +81,8 @@ android {
defaultConfig {
minSdkVersion 8
- targetSdkVersion 21
- versionCode 423
- versionName "2.4.0"
+ targetSdkVersion 22
+ versionCode 492
+ versionName "2.7.0"
}
}
diff --git a/TMessagesProj/config/debug/AndroidManifest.xml b/TMessagesProj/config/debug/AndroidManifest.xml
index 7836674f2..a9ed995de 100644
--- a/TMessagesProj/config/debug/AndroidManifest.xml
+++ b/TMessagesProj/config/debug/AndroidManifest.xml
@@ -24,7 +24,7 @@
android:label="@string/AppName"
android:theme="@style/Theme.TMessages.Start"
android:name=".ApplicationLoader"
- android:hardwareAccelerated="true"
+ android:hardwareAccelerated="@bool/useHardwareAcceleration"
android:largeHeap="true">
diff --git a/TMessagesProj/config/foss/AndroidManifest.xml b/TMessagesProj/config/foss/AndroidManifest.xml
index df2d1e24b..59b2f53b4 100644
--- a/TMessagesProj/config/foss/AndroidManifest.xml
+++ b/TMessagesProj/config/foss/AndroidManifest.xml
@@ -9,7 +9,7 @@
android:label="@string/AppName"
android:theme="@style/Theme.TMessages.Start"
android:name=".ApplicationLoader"
- android:hardwareAccelerated="true"
+ android:hardwareAccelerated="@bool/useHardwareAcceleration"
android:largeHeap="true">
diff --git a/TMessagesProj/config/release/AndroidManifest.xml b/TMessagesProj/config/release/AndroidManifest.xml
index 17c2c2458..f2b0b5627 100644
--- a/TMessagesProj/config/release/AndroidManifest.xml
+++ b/TMessagesProj/config/release/AndroidManifest.xml
@@ -24,7 +24,7 @@
android:label="@string/AppName"
android:theme="@style/Theme.TMessages.Start"
android:name=".ApplicationLoader"
- android:hardwareAccelerated="true"
+ android:hardwareAccelerated="@bool/useHardwareAcceleration"
android:largeHeap="true">
diff --git a/TMessagesProj/jni/Android.mk b/TMessagesProj/jni/Android.mk
index 88b4e6394..f9b84ba96 100755
--- a/TMessagesProj/jni/Android.mk
+++ b/TMessagesProj/jni/Android.mk
@@ -104,7 +104,7 @@ include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_PRELINK_MODULE := false
LOCAL_STATIC_LIBRARIES := webp sqlite
-LOCAL_MODULE := tmessages.5
+LOCAL_MODULE := tmessages.7
LOCAL_CFLAGS := -w -std=gnu99 -O2 -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64
LOCAL_CFLAGS += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT -DUSE_ALLOCA -DHAVE_LRINT -DHAVE_LRINTF -fno-math-errno
LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT -ffast-math
diff --git a/TMessagesProj/jni/image.c b/TMessagesProj/jni/image.c
index 1532095b2..85a859007 100644
--- a/TMessagesProj/jni/image.c
+++ b/TMessagesProj/jni/image.c
@@ -21,6 +21,9 @@ jmethodID jclass_Bitmap_createBitmap;
jclass jclass_Config;
jfieldID jclass_Config_ARGB_8888;
+const uint32_t PGPhotoEnhanceHistogramBins = 256;
+const uint32_t PGPhotoEnhanceSegments = 4;
+
jclass createGlobarRef(JNIEnv *env, jclass class) {
if (class) {
return (*env)->NewGlobalRef(env, class);
@@ -312,6 +315,115 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_blurBitmap(JNIEnv *env, jcl
AndroidBitmap_unlockPixels(env, bitmap);
}
+JNIEXPORT void Java_org_telegram_messenger_Utilities_calcCDT(JNIEnv *env, jclass class, jobject hsvBuffer, int width, int height, jobject buffer) {
+ float imageWidth = width;
+ float imageHeight = height;
+ float _clipLimit = 1.25f;
+
+ uint32_t totalSegments = PGPhotoEnhanceSegments * PGPhotoEnhanceSegments;
+ uint32_t tileArea = (uint32_t)(floorf(imageWidth / PGPhotoEnhanceSegments) * floorf(imageHeight / PGPhotoEnhanceSegments));
+ uint32_t clipLimit = (uint32_t)max(1, _clipLimit * tileArea / (float) PGPhotoEnhanceHistogramBins);
+ float scale = 255.0f / (float) tileArea;
+
+
+ unsigned char *bytes = (*env)->GetDirectBufferAddress(env, hsvBuffer);
+
+ uint32_t **hist = calloc(totalSegments, sizeof(uint32_t *));
+ uint32_t **cdfs = calloc(totalSegments, sizeof(uint32_t *));
+ uint32_t *cdfsMin = calloc(totalSegments, sizeof(uint32_t));
+ uint32_t *cdfsMax = calloc(totalSegments, sizeof(uint32_t));
+
+ for (uint32_t a = 0; a < totalSegments; a++) {
+ hist[a] = calloc(PGPhotoEnhanceHistogramBins, sizeof(uint32_t));
+ cdfs[a] = calloc(PGPhotoEnhanceHistogramBins, sizeof(uint32_t));
+ }
+
+ float xMul = PGPhotoEnhanceSegments / imageWidth;
+ float yMul = PGPhotoEnhanceSegments / imageHeight;
+
+ for (uint32_t y = 0; y < imageHeight; y++) {
+ uint32_t yOffset = y * width * 4;
+ for (uint32_t x = 0; x < imageWidth; x++) {
+ uint32_t index = x * 4 + yOffset;
+
+ uint32_t tx = (uint32_t)(x * xMul);
+ uint32_t ty = (uint32_t)(y * yMul);
+ uint32_t t = ty * PGPhotoEnhanceSegments + tx;
+
+ hist[t][bytes[index + 2]]++;
+ }
+ }
+
+ for (uint32_t i = 0; i < totalSegments; i++) {
+ if (clipLimit > 0) {
+ uint32_t clipped = 0;
+ for (uint32_t j = 0; j < PGPhotoEnhanceHistogramBins; ++j) {
+ if (hist[i][j] > clipLimit) {
+ clipped += hist[i][j] - clipLimit;
+ hist[i][j] = clipLimit;
+ }
+ }
+
+ uint32_t redistBatch = clipped / PGPhotoEnhanceHistogramBins;
+ uint32_t residual = clipped - redistBatch * PGPhotoEnhanceHistogramBins;
+
+ for (uint32_t j = 0; j < PGPhotoEnhanceHistogramBins; ++j) {
+ hist[i][j] += redistBatch;
+ }
+
+ for (uint32_t j = 0; j < residual; ++j) {
+ hist[i][j]++;
+ }
+ }
+ memcpy(cdfs[i], hist[i], PGPhotoEnhanceHistogramBins * sizeof(uint32_t));
+
+ uint32_t hMin = PGPhotoEnhanceHistogramBins - 1;
+ for (uint32_t j = 0; j < hMin; ++j) {
+ if (cdfs[j] != 0) {
+ hMin = j;
+ }
+ }
+
+ uint32_t cdf = 0;
+ for (uint32_t j = hMin; j < PGPhotoEnhanceHistogramBins; ++j) {
+ cdf += cdfs[i][j];
+ cdfs[i][j] = (uint8_t) min(255, cdf * scale);
+ }
+
+ cdfsMin[i] = cdfs[i][hMin];
+ cdfsMax[i] = cdfs[i][PGPhotoEnhanceHistogramBins - 1];
+ }
+
+ uint32_t resultSize = 4 * PGPhotoEnhanceHistogramBins * totalSegments;
+ uint32_t resultBytesPerRow = 4 * PGPhotoEnhanceHistogramBins;
+
+ unsigned char *result = (*env)->GetDirectBufferAddress(env, buffer);
+ for (uint32_t tile = 0; tile < totalSegments; tile++) {
+ uint32_t yOffset = tile * resultBytesPerRow;
+ for (uint32_t i = 0; i < PGPhotoEnhanceHistogramBins; i++) {
+ uint32_t index = i * 4 + yOffset;
+ result[index] = (uint8_t)cdfs[tile][i];
+ result[index + 1] = (uint8_t)cdfsMin[tile];
+ result[index + 2] = (uint8_t)cdfsMax[tile];
+ result[index + 3] = 255;
+ }
+ }
+
+ for (uint32_t a = 0; a < totalSegments; a++) {
+ free(hist[a]);
+ free(cdfs[a]);
+ }
+ free(hist);
+ free(cdfs);
+ free(cdfsMax);
+ free(cdfsMin);
+}
+
+JNIEXPORT int Java_org_telegram_messenger_Utilities_pinBitmap(JNIEnv *env, jclass class, jobject bitmap) {
+ unsigned char *pixels;
+ return AndroidBitmap_lockPixels(env, bitmap, &pixels) >= 0 ? 1 : 0;
+}
+
JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jclass class, jstring path, jobject bitmap, int scale, int width, int height, int stride) {
AndroidBitmapInfo info;
diff --git a/TMessagesProj/libs/armeabi-v7a/libtmessages.5.so b/TMessagesProj/libs/armeabi-v7a/libtmessages.7.so
similarity index 85%
rename from TMessagesProj/libs/armeabi-v7a/libtmessages.5.so
rename to TMessagesProj/libs/armeabi-v7a/libtmessages.7.so
index 132154abf..c086f4a98 100755
Binary files a/TMessagesProj/libs/armeabi-v7a/libtmessages.5.so and b/TMessagesProj/libs/armeabi-v7a/libtmessages.7.so differ
diff --git a/TMessagesProj/libs/armeabi/libtmessages.5.so b/TMessagesProj/libs/armeabi/libtmessages.7.so
similarity index 77%
rename from TMessagesProj/libs/armeabi/libtmessages.5.so
rename to TMessagesProj/libs/armeabi/libtmessages.7.so
index 3e08cd8f7..42ad265ae 100755
Binary files a/TMessagesProj/libs/armeabi/libtmessages.5.so and b/TMessagesProj/libs/armeabi/libtmessages.7.so differ
diff --git a/TMessagesProj/libs/x86/libtmessages.5.so b/TMessagesProj/libs/x86/libtmessages.7.so
similarity index 72%
rename from TMessagesProj/libs/x86/libtmessages.5.so
rename to TMessagesProj/libs/x86/libtmessages.7.so
index 326a064f8..aaa768eac 100755
Binary files a/TMessagesProj/libs/x86/libtmessages.5.so and b/TMessagesProj/libs/x86/libtmessages.7.so differ
diff --git a/TMessagesProj/src/main/AndroidManifest.xml b/TMessagesProj/src/main/AndroidManifest.xml
index 5ca90c91e..dd3c5fc25 100644
--- a/TMessagesProj/src/main/AndroidManifest.xml
+++ b/TMessagesProj/src/main/AndroidManifest.xml
@@ -43,7 +43,7 @@
diff --git a/TMessagesProj/src/main/java/jawnae/pyronet/ByteStream.java b/TMessagesProj/src/main/java/jawnae/pyronet/ByteStream.java
index 39966ac18..878a92acd 100755
--- a/TMessagesProj/src/main/java/jawnae/pyronet/ByteStream.java
+++ b/TMessagesProj/src/main/java/jawnae/pyronet/ByteStream.java
@@ -28,7 +28,7 @@ public class ByteStream {
private final ArrayList queue;
public ByteStream() {
- this.queue = new ArrayList();
+ this.queue = new ArrayList<>();
}
public void append(ByteBufferDesc buf) {
diff --git a/TMessagesProj/src/main/java/jawnae/pyronet/PyroClientListener.java b/TMessagesProj/src/main/java/jawnae/pyronet/PyroClientListener.java
index 117cb1b83..a24913a13 100755
--- a/TMessagesProj/src/main/java/jawnae/pyronet/PyroClientListener.java
+++ b/TMessagesProj/src/main/java/jawnae/pyronet/PyroClientListener.java
@@ -22,17 +22,17 @@ import java.io.IOException;
import java.nio.ByteBuffer;
public interface PyroClientListener {
- public void connectedClient(PyroClient client);
+ void connectedClient(PyroClient client);
- public void unconnectableClient(PyroClient client, Exception cause);
+ void unconnectableClient(PyroClient client, Exception cause);
- public void droppedClient(PyroClient client, IOException cause);
+ void droppedClient(PyroClient client, IOException cause);
- public void disconnectedClient(PyroClient client);
+ void disconnectedClient(PyroClient client);
//
- public void receivedData(PyroClient client, ByteBuffer data);
+ void receivedData(PyroClient client, ByteBuffer data);
- public void sentData(PyroClient client, int bytes);
+ void sentData(PyroClient client, int bytes);
}
diff --git a/TMessagesProj/src/main/java/org/telegram/PhoneFormat/PhoneFormat.java b/TMessagesProj/src/main/java/org/telegram/PhoneFormat/PhoneFormat.java
index a6dbff0ac..63081ef8b 100644
--- a/TMessagesProj/src/main/java/org/telegram/PhoneFormat/PhoneFormat.java
+++ b/TMessagesProj/src/main/java/org/telegram/PhoneFormat/PhoneFormat.java
@@ -25,6 +25,7 @@
package org.telegram.PhoneFormat;
import org.telegram.messenger.ApplicationLoader;
+import org.telegram.messenger.FileLog;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
@@ -97,9 +98,11 @@ public class PhoneFormat {
}
public void init(String countryCode) {
+ InputStream stream = null;
+ ByteArrayOutputStream bos = null;
try {
- InputStream stream = ApplicationLoader.applicationContext.getAssets().open("PhoneFormats.dat");
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ stream = ApplicationLoader.applicationContext.getAssets().open("PhoneFormats.dat");
+ bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = stream.read(buf, 0, 1024)) != -1) {
@@ -111,6 +114,21 @@ public class PhoneFormat {
} catch (Exception e) {
e.printStackTrace();
return;
+ } finally {
+ try {
+ if (bos != null) {
+ bos.close();
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ try {
+ if (stream != null) {
+ stream.close();
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
}
if (countryCode != null && countryCode.length() != 0) {
@@ -119,10 +137,10 @@ public class PhoneFormat {
Locale loc = Locale.getDefault();
defaultCountry = loc.getCountry().toLowerCase();
}
- callingCodeOffsets = new HashMap(255);
- callingCodeCountries = new HashMap>(255);
- callingCodeData = new HashMap(10);
- countryCallingCode = new HashMap(255);
+ callingCodeOffsets = new HashMap<>(255);
+ callingCodeCountries = new HashMap<>(255);
+ callingCodeData = new HashMap<>(10);
+ countryCallingCode = new HashMap<>(255);
parseDataHeader();
initialzed = true;
@@ -293,7 +311,7 @@ public class PhoneFormat {
offset += 2;
- ArrayList strs = new ArrayList(5);
+ ArrayList strs = new ArrayList<>(5);
String str;
while ((str = valueString(offset)).length() != 0) {
strs.add(str);
@@ -302,14 +320,14 @@ public class PhoneFormat {
res.trunkPrefixes = strs;
offset++;
- strs = new ArrayList(5);
+ strs = new ArrayList<>(5);
while ((str = valueString(offset)).length() != 0) {
strs.add(str);
offset += str.length() + 1;
}
res.intlPrefixes = strs;
- ArrayList ruleSets = new ArrayList(setCnt);
+ ArrayList ruleSets = new ArrayList<>(setCnt);
offset = start + block1Len;
for (int s = 0; s < setCnt; s++) {
RuleSet ruleSet = new RuleSet();
@@ -317,7 +335,7 @@ public class PhoneFormat {
offset += 2;
int ruleCnt = value16(offset);
offset += 2;
- ArrayList rules = new ArrayList(ruleCnt);
+ ArrayList rules = new ArrayList<>(ruleCnt);
for (int r = 0; r < ruleCnt; r++) {
PhoneRule rule = new PhoneRule();
rule.minVal = value32(offset);
@@ -380,7 +398,7 @@ public class PhoneFormat {
callingCodeOffsets.put(callingCode, offset);
ArrayList countries = callingCodeCountries.get(callingCode);
if (countries == null) {
- countries = new ArrayList();
+ countries = new ArrayList<>();
callingCodeCountries.put(callingCode, countries);
}
countries.add(country);
diff --git a/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java b/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java
index 4455445f2..b14c401b2 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/AndroidUtilities.java
@@ -14,6 +14,7 @@ import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
+import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
@@ -23,6 +24,8 @@ import android.os.Environment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
+import android.text.style.ForegroundColorSpan;
+import android.util.DisplayMetrics;
import android.util.StateSet;
import android.view.Display;
import android.view.Surface;
@@ -33,12 +36,20 @@ import android.widget.AbsListView;
import android.widget.EdgeEffect;
import android.widget.EditText;
import android.widget.ListView;
+import android.widget.ProgressBar;
import android.widget.TextView;
+import org.telegram.messenger.ConnectionsManager;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.ApplicationLoader;
+import org.telegram.messenger.UserConfig;
+import org.telegram.ui.AnimationCompat.AnimatorListenerAdapterProxy;
+import org.telegram.ui.AnimationCompat.AnimatorSetProxy;
+import org.telegram.ui.AnimationCompat.ObjectAnimatorProxy;
+import org.telegram.ui.AnimationCompat.ViewProxy;
+import org.telegram.ui.Components.ForegroundDetector;
import org.telegram.ui.Components.NumberPicker;
import org.telegram.ui.Components.TypefaceSpan;
@@ -59,15 +70,18 @@ public class AndroidUtilities {
public static float density = 1;
public static Point displaySize = new Point();
public static Integer photoSize = null;
+ public static DisplayMetrics displayMetrics = new DisplayMetrics();
+ public static int leftBaseline;
private static Boolean isTablet = null;
static {
density = ApplicationLoader.applicationContext.getResources().getDisplayMetrics().density;
+ leftBaseline = isTablet() ? 80 : 72;
checkDisplaySize();
}
public static void lockOrientation(Activity activity) {
- if (activity == null || prevOrientation != -10) {
+ if (activity == null || prevOrientation != -10 || Build.VERSION.SDK_INT < 9) {
return;
}
try {
@@ -115,7 +129,7 @@ public class AndroidUtilities {
}
public static void unlockOrientation(Activity activity) {
- if (activity == null) {
+ if (activity == null || Build.VERSION.SDK_INT < 9) {
return;
}
try {
@@ -163,8 +177,6 @@ public class AndroidUtilities {
}
InputMethodManager inputManager = (InputMethodManager)view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
-
- ((InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(view, 0);
}
public static boolean isKeyboardShowed(View view) {
@@ -228,12 +240,13 @@ public class AndroidUtilities {
if (manager != null) {
Display display = manager.getDefaultDisplay();
if (display != null) {
+ display.getMetrics(displayMetrics);
if(android.os.Build.VERSION.SDK_INT < 13) {
displaySize.set(display.getWidth(), display.getHeight());
} else {
display.getSize(displaySize);
}
- FileLog.e("tmessages", "display size = " + displaySize.x + " " + displaySize.y);
+ FileLog.e("tmessages", "display size = " + displaySize.x + " " + displaySize.y + " " + displayMetrics.xdpi + "x" + displayMetrics.ydpi);
}
}
} catch (Exception e) {
@@ -241,6 +254,10 @@ public class AndroidUtilities {
}
}
+ public static float getPixelsInCM(float cm, boolean isX) {
+ return (cm / 2.54f) * (isX ? displayMetrics.xdpi : displayMetrics.ydpi);
+ }
+
public static long makeBroadcastId(int id) {
return 0x0000000100000000L | ((long)id & 0x00000000FFFFFFFFL);
}
@@ -421,6 +438,19 @@ public class AndroidUtilities {
}
}
+ public static void setProgressBarAnimationDuration(ProgressBar progressBar, int duration) {
+ if (progressBar == null) {
+ return;
+ }
+ try {
+ Field mCursorDrawableRes = ProgressBar.class.getDeclaredField("mDuration");
+ mCursorDrawableRes.setAccessible(true);
+ mCursorDrawableRes.setInt(progressBar, duration);
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
+
public static int getViewInset(View view) {
if (view == null || Build.VERSION.SDK_INT < 21) {
return 0;
@@ -514,20 +544,133 @@ public class AndroidUtilities {
}
}
- public static Spannable replaceBold(String str) {
- int start;
- ArrayList bolds = new ArrayList<>();
- while ((start = str.indexOf("")) != -1) {
- int end = str.indexOf("") - 3;
- str = str.replaceFirst("", "").replaceFirst("", "");
- bolds.add(start);
- bolds.add(end);
+ public static Spannable replaceTags(String str) {
+ try {
+ int start = -1;
+ int startColor = -1;
+ int end = -1;
+ StringBuilder stringBuilder = new StringBuilder(str);
+ while ((start = stringBuilder.indexOf("
")) != -1) {
+ stringBuilder.replace(start, start + 4, "\n");
+ }
+ while ((start = stringBuilder.indexOf("
")) != -1) {
+ stringBuilder.replace(start, start + 5, "\n");
+ }
+ ArrayList bolds = new ArrayList<>();
+ ArrayList colors = new ArrayList<>();
+ while ((start = stringBuilder.indexOf("")) != -1 || (startColor = stringBuilder.indexOf("");
+ stringBuilder.replace(end, end + 4, "");
+ bolds.add(start);
+ bolds.add(end);
+ } else if (startColor != -1) {
+ stringBuilder.replace(startColor, startColor + 2, "");
+ end = stringBuilder.indexOf(">", startColor);
+ int color = Color.parseColor(stringBuilder.substring(startColor, end));
+ stringBuilder.replace(startColor, end + 1, "");
+ end = stringBuilder.indexOf("");
+ stringBuilder.replace(end, end + 4, "");
+ colors.add(startColor);
+ colors.add(end);
+ colors.add(color);
+ }
+ }
+ SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder);
+ for (int a = 0; a < bolds.size() / 2; a++) {
+ spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+ }
+ for (int a = 0; a < colors.size() / 3; a++) {
+ spannableStringBuilder.setSpan(new ForegroundColorSpan(colors.get(a * 3 + 2)), colors.get(a * 3), colors.get(a * 3 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
+ }
+ return spannableStringBuilder;
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
}
- SpannableStringBuilder stringBuilder = new SpannableStringBuilder(str);
- for (int a = 0; a < bolds.size() / 2; a++) {
- TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
- stringBuilder.setSpan(span, bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
- }
- return stringBuilder;
+ return new SpannableStringBuilder(str);
}
+
+ public static boolean needShowPasscode(boolean reset) {
+ boolean wasInBackground;
+ if (Build.VERSION.SDK_INT >= 14) {
+ wasInBackground = ForegroundDetector.getInstance().isWasInBackground(reset);
+ if (reset) {
+ ForegroundDetector.getInstance().resetBackgroundVar();
+ }
+ } else {
+ wasInBackground = UserConfig.lastPauseTime != 0;
+ }
+ return UserConfig.passcodeHash.length() > 0 && wasInBackground &&
+ (UserConfig.appLocked || UserConfig.autoLockIn != 0 && UserConfig.lastPauseTime != 0 && !UserConfig.appLocked && (UserConfig.lastPauseTime + UserConfig.autoLockIn) <= ConnectionsManager.getInstance().getCurrentTime());
+ }
+
+ public static void shakeTextView(final TextView textView, final float x, final int num) {
+ if (num == 6) {
+ ViewProxy.setTranslationX(textView, 0);
+ textView.clearAnimation();
+ return;
+ }
+ AnimatorSetProxy animatorSetProxy = new AnimatorSetProxy();
+ animatorSetProxy.playTogether(ObjectAnimatorProxy.ofFloat(textView, "translationX", AndroidUtilities.dp(x)));
+ animatorSetProxy.setDuration(50);
+ animatorSetProxy.addListener(new AnimatorListenerAdapterProxy() {
+ @Override
+ public void onAnimationEnd(Object animation) {
+ shakeTextView(textView, num == 5 ? 0 : -x, num + 1);
+ }
+ });
+ animatorSetProxy.start();
+ }
+
+
+
+ /*public static String ellipsize(String text, int maxLines, int maxWidth, TextPaint paint) {
+ if (text == null || paint == null) {
+ return null;
+ }
+ int count;
+ int offset = 0;
+ StringBuilder result = null;
+ TextView
+ for (int a = 0; a < maxLines; a++) {
+ count = paint.breakText(text, true, maxWidth, null);
+ if (a != maxLines - 1) {
+ if (result == null) {
+ result = new StringBuilder(count * maxLines + 1);
+ }
+ boolean foundSpace = false;
+ for (int c = count - 1; c >= offset; c--) {
+ if (text.charAt(c) == ' ') {
+ foundSpace = true;
+ result.append(text.substring(offset, c - 1));
+ offset = c - 1;
+ }
+ }
+ if (!foundSpace) {
+ offset = count;
+ }
+ text = text.substring(0, offset);
+ } else if (maxLines == 1) {
+ return text.substring(0, count);
+ } else {
+ result.append(text.substring(0, count));
+ }
+ }
+ return result.toString();
+ }*/
+
+ /*public static void turnOffHardwareAcceleration(Window window) {
+ if (window == null || Build.MODEL == null || Build.VERSION.SDK_INT < 11) {
+ return;
+ }
+ if (Build.MODEL.contains("GT-S5301") ||
+ Build.MODEL.contains("GT-S5303") ||
+ Build.MODEL.contains("GT-B5330") ||
+ Build.MODEL.contains("GT-S5302") ||
+ Build.MODEL.contains("GT-S6012B") ||
+ Build.MODEL.contains("MegaFon_SP-AI")) {
+ window.clearFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
+ }
+ }*/
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java b/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java
index 75cb7bcbc..84ac04327 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/ContactsController.java
@@ -54,6 +54,7 @@ public class ContactsController {
private ArrayList delayedContactsUpdate = new ArrayList<>();
private String inviteText;
private boolean updatingInviteText = false;
+ private HashMap sectionsToReplace = new HashMap<>();
private int loadingDeleteInfo = 0;
private int deleteAccountTTL;
@@ -114,6 +115,28 @@ public class ContactsController {
if (preferences.getBoolean("needGetStatuses", false)) {
reloadContactsStatuses();
}
+
+ sectionsToReplace.put("À", "A");
+ sectionsToReplace.put("Á", "A");
+ sectionsToReplace.put("Ä", "A");
+ sectionsToReplace.put("Ù", "U");
+ sectionsToReplace.put("Ú", "U");
+ sectionsToReplace.put("Ü", "U");
+ sectionsToReplace.put("Ì", "I");
+ sectionsToReplace.put("Í", "I");
+ sectionsToReplace.put("Ï", "I");
+ sectionsToReplace.put("È", "E");
+ sectionsToReplace.put("É", "E");
+ sectionsToReplace.put("Ê", "E");
+ sectionsToReplace.put("Ë", "E");
+ sectionsToReplace.put("Ò", "O");
+ sectionsToReplace.put("Ó", "O");
+ sectionsToReplace.put("Ö", "O");
+ sectionsToReplace.put("Ç", "C");
+ sectionsToReplace.put("Ñ", "N");
+ sectionsToReplace.put("Ÿ", "Y");
+ sectionsToReplace.put("Ý", "Y");
+ sectionsToReplace.put("Ţ", "Y");
}
public void cleanup() {
@@ -514,10 +537,10 @@ public class ContactsController {
checkContactsInternal();
}
final HashMap contactsMap = readContactsFromPhoneBook();
- final HashMap contactsBookShort = new HashMap();
+ final HashMap contactsBookShort = new HashMap<>();
int oldCount = contactHashMap.size();
- ArrayList toImport = new ArrayList();
+ ArrayList toImport = new ArrayList<>();
if (!contactHashMap.isEmpty()) {
for (HashMap.Entry pair : contactsMap.entrySet()) {
Integer id = pair.getKey();
@@ -619,10 +642,10 @@ public class ContactsController {
}
}
- final ArrayList toDelete = new ArrayList();
+ final ArrayList toDelete = new ArrayList<>();
if (contactHashMap != null && !contactHashMap.isEmpty()) {
try {
- final HashMap contactsPhonesShort = new HashMap();
+ final HashMap contactsPhonesShort = new HashMap<>();
for (TLRPC.TL_contact value : contacts) {
TLRPC.User user = MessagesController.getInstance().getUser(value.user_id);
@@ -692,7 +715,7 @@ public class ContactsController {
}
final int count = (int)Math.ceil(toImport.size() / 500.0f);
for (int a = 0; a < count; a++) {
- ArrayList finalToImport = new ArrayList();
+ ArrayList finalToImport = new ArrayList<>();
finalToImport.addAll(toImport.subList(a * 500, Math.min((a + 1) * 500, toImport.size())));
TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
req.contacts = finalToImport;
@@ -713,7 +736,7 @@ public class ContactsController {
// }
}
MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true);
- ArrayList cArr = new ArrayList();
+ ArrayList cArr = new ArrayList<>();
for (TLRPC.TL_importedContact c : res.imported) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
contact.user_id = c.user_id;
@@ -848,7 +871,7 @@ public class ContactsController {
public void run() {
MessagesController.getInstance().putUsers(usersArr, from == 1);
- final HashMap usersDict = new HashMap();
+ final HashMap usersDict = new HashMap<>();
final boolean isEmpty = contactsArr.isEmpty();
@@ -933,9 +956,9 @@ public class ContactsController {
}
});
- final SparseArray contactsDictionary = new SparseArray();
- final HashMap> sectionsDict = new HashMap>();
- final ArrayList sortedSectionsArray = new ArrayList();
+ final SparseArray contactsDictionary = new SparseArray<>();
+ final HashMap> sectionsDict = new HashMap<>();
+ final ArrayList sortedSectionsArray = new ArrayList<>();
HashMap contactsByPhonesDict = null;
if (!contactsBookLoaded) {
@@ -958,13 +981,17 @@ public class ContactsController {
if (key == null || key.length() == 0) {
key = user.last_name;
}
+ if (key.length() > 1) {
+ key = key.substring(0, 1);
+ }
if (key.length() == 0) {
key = "#";
} else {
key = key.toUpperCase();
}
- if (key.length() > 1) {
- key = key.substring(0, 1);
+ String replace = sectionsToReplace.get(key);
+ if (replace != null) {
+ key = replace;
}
ArrayList arr = sectionsDict.get(key);
if (arr == null) {
@@ -1067,7 +1094,7 @@ public class ContactsController {
}
private void updateUnregisteredContacts(final ArrayList contactsArr) {
- final HashMap contactsPhonesShort = new HashMap();
+ final HashMap contactsPhonesShort = new HashMap<>();
for (TLRPC.TL_contact value : contactsArr) {
TLRPC.User user = MessagesController.getInstance().getUser(value.user_id);
@@ -1077,7 +1104,7 @@ public class ContactsController {
contactsPhonesShort.put(user.phone, value);
}
- final ArrayList sortedPhoneBookContacts = new ArrayList();
+ final ArrayList sortedPhoneBookContacts = new ArrayList<>();
for (HashMap.Entry pair : contactsBook.entrySet()) {
Contact value = pair.getValue();
int id = pair.getKey();
@@ -1135,8 +1162,8 @@ public class ContactsController {
}
StringBuilder ids = new StringBuilder();
- final HashMap> sectionsDict = new HashMap>();
- final ArrayList sortedSectionsArray = new ArrayList();
+ final HashMap> sectionsDict = new HashMap<>();
+ final ArrayList sortedSectionsArray = new ArrayList<>();
for (TLRPC.TL_contact value : contacts) {
TLRPC.User user = MessagesController.getInstance().getUser(value.user_id);
@@ -1148,17 +1175,21 @@ public class ContactsController {
if (key == null || key.length() == 0) {
key = user.last_name;
}
+ if (key.length() > 1) {
+ key = key.substring(0, 1);
+ }
if (key.length() == 0) {
key = "#";
} else {
key = key.toUpperCase();
}
- if (key.length() > 1) {
- key = key.substring(0, 1);
+ String replace = sectionsToReplace.get(key);
+ if (replace != null) {
+ key = replace;
}
ArrayList arr = sectionsDict.get(key);
if (arr == null) {
- arr = new ArrayList();
+ arr = new ArrayList<>();
sectionsDict.put(key, arr);
sortedSectionsArray.add(key);
}
@@ -1193,7 +1224,7 @@ public class ContactsController {
try {
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, currentAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, currentAccount.type).build();
Cursor c1 = ApplicationLoader.applicationContext.getContentResolver().query(rawContactUri, new String[]{BaseColumns._ID, ContactsContract.RawContacts.SYNC2}, null, null, null);
- HashMap bookContacts = new HashMap();
+ HashMap bookContacts = new HashMap<>();
if (c1 != null) {
while (c1.moveToNext()) {
bookContacts.put(c1.getInt(1), c1.getLong(0));
@@ -1213,7 +1244,7 @@ public class ContactsController {
}
private void performWriteContactsToPhoneBook() {
- final ArrayList contactsArray = new ArrayList();
+ final ArrayList contactsArray = new ArrayList<>();
contactsArray.addAll(contacts);
Utilities.photoBookQueue.postRunnable(new Runnable() {
@Override
@@ -1225,8 +1256,8 @@ public class ContactsController {
private void applyContactsUpdates(ArrayList ids, ConcurrentHashMap userDict, ArrayList newC, ArrayList contactsTD) {
if (newC == null || contactsTD == null) {
- newC = new ArrayList();
- contactsTD = new ArrayList();
+ newC = new ArrayList<>();
+ contactsTD = new ArrayList<>();
for (Integer uid : ids) {
if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
@@ -1351,8 +1382,8 @@ public class ContactsController {
}
public void processContactsUpdates(ArrayList ids, ConcurrentHashMap userDict) {
- final ArrayList newContacts = new ArrayList();
- final ArrayList contactsToDelete = new ArrayList();
+ final ArrayList newContacts = new ArrayList<>();
+ final ArrayList contactsToDelete = new ArrayList<>();
for (Integer uid : ids) {
if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
@@ -1406,7 +1437,7 @@ public class ContactsController {
}
}
- ArrayList query = new ArrayList();
+ ArrayList query = new ArrayList<>();
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
builder.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, currentAccount.name);
@@ -1471,7 +1502,7 @@ public class ContactsController {
}
TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
- ArrayList contactsParams = new ArrayList();
+ ArrayList contactsParams = new ArrayList<>();
TLRPC.TL_inputPhoneContact c = new TLRPC.TL_inputPhoneContact();
c.phone = user.phone;
if (!c.phone.startsWith("+")) {
@@ -1510,7 +1541,7 @@ public class ContactsController {
});
TLRPC.TL_contact newContact = new TLRPC.TL_contact();
newContact.user_id = u.id;
- ArrayList arrayList = new ArrayList();
+ ArrayList arrayList = new ArrayList<>();
arrayList.add(newContact);
MessagesStorage.getInstance().putContacts(arrayList, false);
@@ -1552,7 +1583,7 @@ public class ContactsController {
return;
}
TLRPC.TL_contacts_deleteContacts req = new TLRPC.TL_contacts_deleteContacts();
- final ArrayList uids = new ArrayList();
+ final ArrayList uids = new ArrayList<>();
for (TLRPC.User user : users) {
TLRPC.InputUser inputUser = MessagesController.getInputUser(user);
if (inputUser == null) {
@@ -1631,7 +1662,7 @@ public class ContactsController {
editor.remove("needGetStatuses").commit();
TLRPC.Vector vector = (TLRPC.Vector) response;
if (!vector.objects.isEmpty()) {
- ArrayList dbUsersStatus = new ArrayList();
+ ArrayList dbUsersStatus = new ArrayList<>();
for (Object object : vector.objects) {
TLRPC.User toDbUser = new TLRPC.User();
TLRPC.TL_contactStatus status = (TLRPC.TL_contactStatus) object;
@@ -1741,7 +1772,7 @@ public class ContactsController {
}
public static String formatName(String firstName, String lastName) {
- String result = null;
+ String result = "";
if (LocaleController.nameDisplayOrder == 1) {
result = firstName;
if (result == null || result.length() == 0) {
diff --git a/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java b/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java
index 1e9a454a7..fb6363697 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/ImageLoader.java
@@ -344,7 +344,7 @@ public class ImageLoader {
});
}
});
- AndroidUtilities.runOnUIThread(new Runnable() {
+ imageLoadQueue.postRunnable(new Runnable() {
@Override
public void run() {
runHttpTasks(true);
@@ -354,7 +354,7 @@ public class ImageLoader {
@Override
protected void onCancelled() {
- AndroidUtilities.runOnUIThread(new Runnable() {
+ imageLoadQueue.postRunnable(new Runnable() {
@Override
public void run() {
runHttpTasks(true);
@@ -449,6 +449,11 @@ public class ImageLoader {
originalBitmap = scaledBitmap;
FileOutputStream stream = new FileOutputStream(thumbFile);
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
+ try {
+ stream.close();
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
final BitmapDrawable bitmapDrawable = new BitmapDrawable(originalBitmap);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
@@ -615,7 +620,9 @@ public class ImageLoader {
if (mediaId != null) {
MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId, MediaStore.Images.Thumbnails.MINI_KIND, opts);
} else {
- BitmapFactory.decodeFile(cacheImage.finalFilePath.getAbsolutePath(), opts);
+ FileInputStream is = new FileInputStream(cacheFileFinal);
+ image = BitmapFactory.decodeStream(is, null, opts);
+ is.close();
}
float photoW = opts.outWidth;
@@ -633,14 +640,18 @@ public class ImageLoader {
}
}
- if (cacheImage.filter == null || blur) {
+ if (cacheImage.filter == null || blur || cacheImage.httpUrl != null) {
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
} else {
opts.inPreferredConfig = Bitmap.Config.RGB_565;
}
+ //if (Build.VERSION.SDK_INT < 21) {
+ // opts.inPurgeable = true;
+ //}
+
opts.inDither = false;
if (mediaId != null) {
- image = MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId, MediaStore.Images.Thumbnails.MINI_KIND, null);
+ image = MediaStore.Images.Thumbnails.getThumbnail(ApplicationLoader.applicationContext.getContentResolver(), mediaId, MediaStore.Images.Thumbnails.MINI_KIND, opts);
}
if (image == null) {
if (isWebp) {
@@ -1057,6 +1068,12 @@ public class ImageLoader {
FileLog.e("tmessages", e);
}
}
+ try {
+ new File(cachePath, ".nomedia").createNewFile();
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+
mediaDirs.put(FileLoader.MEDIA_DIR_CACHE, cachePath);
FileLog.e("tmessages", "cache path = " + cachePath);
@@ -1678,42 +1695,47 @@ public class ImageLoader {
runHttpFileLoadTasks(null, 0);
}
- private void runHttpFileLoadTasks(HttpFileTask oldTask, int reason) {
- if (oldTask != null) {
- currentHttpFileLoadTasksCount--;
- }
- if (oldTask != null) {
- if (reason == 1) {
- if (oldTask.canRetry) {
- final HttpFileTask newTask = new HttpFileTask(oldTask.url, oldTask.tempFile, oldTask.ext);
- Runnable runnable = new Runnable() {
- @Override
- public void run() {
- httpFileLoadTasks.add(newTask);
- runHttpFileLoadTasks(null, 0);
- }
- };
- retryHttpsTasks.put(oldTask.url, runnable);
- AndroidUtilities.runOnUIThread(runnable, 1000);
- } else {
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidFailedLoad, oldTask.url);
+ private void runHttpFileLoadTasks(final HttpFileTask oldTask, final int reason) {
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ if (oldTask != null) {
+ currentHttpFileLoadTasksCount--;
+ }
+ if (oldTask != null) {
+ if (reason == 1) {
+ if (oldTask.canRetry) {
+ final HttpFileTask newTask = new HttpFileTask(oldTask.url, oldTask.tempFile, oldTask.ext);
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ httpFileLoadTasks.add(newTask);
+ runHttpFileLoadTasks(null, 0);
+ }
+ };
+ retryHttpsTasks.put(oldTask.url, runnable);
+ AndroidUtilities.runOnUIThread(runnable, 1000);
+ } else {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidFailedLoad, oldTask.url);
+ }
+ } else if (reason == 2) {
+ httpFileLoadTasksByKeys.remove(oldTask.url);
+ File file = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(oldTask.url) + "." + oldTask.ext);
+ String result = oldTask.tempFile.renameTo(file) ? file.toString() : oldTask.tempFile.toString();
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidLoaded, oldTask.url, result);
+ }
+ }
+ while (currentHttpFileLoadTasksCount < 2 && !httpFileLoadTasks.isEmpty()) {
+ HttpFileTask task = httpFileLoadTasks.poll();
+ if (android.os.Build.VERSION.SDK_INT >= 11) {
+ task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
+ } else {
+ task.execute(null, null, null);
+ }
+ currentHttpFileLoadTasksCount++;
}
- } else if (reason == 2) {
- httpFileLoadTasksByKeys.remove(oldTask.url);
- File file = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(oldTask.url) + "." + oldTask.ext);
- String result = oldTask.tempFile.renameTo(file) ? file.toString() : oldTask.tempFile.toString();
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.httpFileDidLoaded, oldTask.url, result);
}
- }
- while (currentHttpFileLoadTasksCount < 2 && !httpFileLoadTasks.isEmpty()) {
- HttpFileTask task = httpFileLoadTasks.poll();
- if (android.os.Build.VERSION.SDK_INT >= 11) {
- task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
- } else {
- task.execute(null, null, null);
- }
- currentHttpFileLoadTasksCount++;
- }
+ });
}
public static Bitmap loadBitmap(String path, Uri uri, float maxWidth, float maxHeight, boolean useMaxScale) {
@@ -1963,6 +1985,15 @@ public class ImageLoader {
}
}
}
+ } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
+ if (message.media.webpage.photo != null) {
+ for (TLRPC.PhotoSize size : message.media.webpage.photo.sizes) {
+ if (size instanceof TLRPC.TL_photoCachedSize) {
+ photoSize = size;
+ break;
+ }
+ }
+ }
}
if (photoSize != null && photoSize.bytes != null && photoSize.bytes.length != 0) {
if (photoSize.location instanceof TLRPC.TL_fileLocationUnavailable) {
@@ -2000,6 +2031,13 @@ public class ImageLoader {
message.media.video.thumb = newPhotoSize;
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
message.media.document.thumb = newPhotoSize;
+ } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
+ for (int a = 0; a < message.media.webpage.photo.sizes.size(); a++) {
+ if (message.media.webpage.photo.sizes.get(a) instanceof TLRPC.TL_photoCachedSize) {
+ message.media.webpage.photo.sizes.set(a, newPhotoSize);
+ break;
+ }
+ }
}
}
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java b/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java
index 9c467f72b..6f50bdc59 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/ImageReceiver.java
@@ -29,8 +29,8 @@ import org.telegram.messenger.Utilities;
public class ImageReceiver implements NotificationCenter.NotificationCenterDelegate {
- public static interface ImageReceiverDelegate {
- public void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb);
+ public interface ImageReceiverDelegate {
+ void didSetImage(ImageReceiver imageReceiver, boolean set, boolean thumb);
}
private View parentView;
@@ -68,7 +68,8 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
private Matrix shaderMatrix;
private int alpha = 255;
private boolean isPressed;
- private boolean disableRecycle;
+ private int orientation;
+ private boolean centerRotation;
private ImageReceiverDelegate delegate;
public ImageReceiver() {
@@ -209,12 +210,17 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return isPressed;
}
- public void setImageBitmap(Bitmap bitmap) {
- setImageBitmap(bitmap != null ? new BitmapDrawable(null, bitmap) : null);
+ public void setOrientation(int angle, boolean center) {
+ orientation = angle;
+ centerRotation = center;
}
- public void setDisableRecycle(boolean value) {
- disableRecycle = value;
+ public int getOrientation() {
+ return orientation;
+ }
+
+ public void setImageBitmap(Bitmap bitmap) {
+ setImageBitmap(bitmap != null ? new BitmapDrawable(null, bitmap) : null);
}
public void setImageBitmap(Drawable bitmap) {
@@ -280,8 +286,17 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.drawRoundRect(roundRect, roundRadius, roundRadius, roundPaint);
}
} else {
- int bitmapW = bitmapDrawable.getIntrinsicWidth();
- int bitmapH = bitmapDrawable.getIntrinsicHeight();
+ int bitmapW;
+ int bitmapH;
+ int originalW = bitmapDrawable.getIntrinsicWidth();
+ int originalH = bitmapDrawable.getIntrinsicHeight();
+ if (orientation == 90 || orientation == 270) {
+ bitmapW = bitmapDrawable.getIntrinsicHeight();
+ bitmapH = bitmapDrawable.getIntrinsicWidth();
+ } else {
+ bitmapW = bitmapDrawable.getIntrinsicWidth();
+ bitmapH = bitmapDrawable.getIntrinsicHeight();
+ }
float scaleW = bitmapW / (float) imageW;
float scaleH = bitmapH / (float) imageH;
@@ -312,14 +327,32 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.save();
canvas.clipRect(imageX, imageY, imageX + imageW, imageY + imageH);
+ if (orientation != 0) {
+ if (centerRotation) {
+ canvas.rotate(orientation, imageW / 2, imageH / 2);
+ } else {
+ canvas.rotate(orientation, 0, 0);
+ }
+ }
+
if (bitmapW / scaleH > imageW) {
bitmapW /= scaleH;
+ originalW /= scaleH;
drawRegion.set(imageX - (bitmapW - imageW) / 2, imageY, imageX + (bitmapW + imageW) / 2, imageY + imageH);
} else {
bitmapH /= scaleW;
+ originalH /= scaleW;
drawRegion.set(imageX, imageY - (bitmapH - imageH) / 2, imageX + imageW, imageY + (bitmapH + imageH) / 2);
}
- bitmapDrawable.setBounds(drawRegion);
+ if (orientation == 90 || orientation == 270) {
+ int width = (drawRegion.right - drawRegion.left) / 2;
+ int height = (drawRegion.bottom - drawRegion.top) / 2;
+ int centerX = (drawRegion.right + drawRegion.left) / 2;
+ int centerY = (drawRegion.top + drawRegion.bottom) / 2;
+ bitmapDrawable.setBounds(centerX - height, centerY - width, centerX + height, centerY + width);
+ } else {
+ bitmapDrawable.setBounds(drawRegion);
+ }
if (isVisible) {
try {
bitmapDrawable.setAlpha(alpha);
@@ -339,8 +372,24 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.restore();
} else {
+ canvas.save();
+ if (orientation != 0) {
+ if (centerRotation) {
+ canvas.rotate(orientation, imageW / 2, imageH / 2);
+ } else {
+ canvas.rotate(orientation, 0, 0);
+ }
+ }
drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH);
- bitmapDrawable.setBounds(drawRegion);
+ if (orientation == 90 || orientation == 270) {
+ int width = (drawRegion.right - drawRegion.left) / 2;
+ int height = (drawRegion.bottom - drawRegion.top) / 2;
+ int centerX = (drawRegion.right + drawRegion.left) / 2;
+ int centerY = (drawRegion.top + drawRegion.bottom) / 2;
+ bitmapDrawable.setBounds(centerX - height, centerY - width, centerX + height, centerY + width);
+ } else {
+ bitmapDrawable.setBounds(drawRegion);
+ }
if (isVisible) {
try {
bitmapDrawable.setAlpha(alpha);
@@ -357,6 +406,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
FileLog.e("tmessages", e);
}
}
+ canvas.restore();
}
}
}
@@ -391,6 +441,16 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return null;
}
+ public int getBitmapWidth() {
+ Bitmap bitmap = getBitmap();
+ return orientation == 0 || orientation == 180 ? bitmap.getWidth() : bitmap.getHeight();
+ }
+
+ public int getBitmapHeight() {
+ Bitmap bitmap = getBitmap();
+ return orientation == 0 || orientation == 180 ? bitmap.getHeight() : bitmap.getWidth();
+ }
+
public void setVisible(boolean value, boolean invalidate) {
if (isVisible == value) {
return;
@@ -432,10 +492,18 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
return imageX;
}
+ public int getImageX2() {
+ return imageX + imageW;
+ }
+
public int getImageY() {
return imageY;
}
+ public int getImageY2() {
+ return imageY + imageH;
+ }
+
public int getImageWidth() {
return imageW;
}
@@ -617,7 +685,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
if (newKey != null) {
newBitmap = ImageLoader.getInstance().getImageFromMemory(newKey);
}
- if (key == null || image == null || image == newBitmap || disableRecycle) {
+ if (key == null || image == null || image == newBitmap) {
return;
}
Bitmap bitmap = image.getBitmap();
diff --git a/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java b/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java
index db7b228b3..1d2094bc8 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/LocaleController.java
@@ -54,6 +54,7 @@ public class LocaleController {
public static FastDateFormat formatterWeek;
public static FastDateFormat formatterMonth;
public static FastDateFormat formatterYear;
+ public static FastDateFormat formatterMonthYear;
public static FastDateFormat formatterYearMax;
public static FastDateFormat chatDate;
public static FastDateFormat chatFullDate;
@@ -135,7 +136,7 @@ public class LocaleController {
addRules(new String[]{"bem", "brx", "da", "de", "el", "en", "eo", "es", "et", "fi", "fo", "gl", "he", "iw", "it", "nb",
"nl", "nn", "no", "sv", "af", "bg", "bn", "ca", "eu", "fur", "fy", "gu", "ha", "is", "ku",
"lb", "ml", "mr", "nah", "ne", "om", "or", "pa", "pap", "ps", "so", "sq", "sw", "ta", "te",
- "tk", "ur", "zu", "mn", "gsw", "chr", "rm", "pt"}, new PluralRules_One());
+ "tk", "ur", "zu", "mn", "gsw", "chr", "rm", "pt", "an", "ast"}, new PluralRules_One());
addRules(new String[]{"cs", "sk"}, new PluralRules_Czech());
addRules(new String[]{"ff", "fr", "kab"}, new PluralRules_French());
addRules(new String[]{"hr", "ru", "sr", "uk", "be", "bs", "sh"}, new PluralRules_Balkan());
@@ -443,10 +444,12 @@ public class LocaleController {
}
private HashMap getLocaleFileStrings(File file) {
+ FileInputStream stream = null;
try {
HashMap stringMap = new HashMap<>();
XmlPullParser parser = Xml.newPullParser();
- parser.setInput(new FileInputStream(file), "UTF-8");
+ stream = new FileInputStream(file);
+ parser.setInput(stream, "UTF-8");
int eventType = parser.getEventType();
String name = null;
String value = null;
@@ -483,6 +486,15 @@ public class LocaleController {
return stringMap;
} catch (Exception e) {
FileLog.e("tmessages", e);
+ } finally {
+ try {
+ if (stream != null) {
+ stream.close();
+ stream = null;
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
}
return null;
}
@@ -544,6 +556,9 @@ public class LocaleController {
currentLocale = newLocale;
currentLocaleInfo = localeInfo;
currentPluralRules = allRules.get(currentLocale.getLanguage());
+ if (currentPluralRules == null) {
+ currentPluralRules = allRules.get("en");
+ }
changingConfiguration = true;
Locale.setDefault(currentLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
@@ -571,6 +586,9 @@ public class LocaleController {
if (value == null) {
value = ApplicationLoader.applicationContext.getString(res);
}
+ if (value == null) {
+ value = "LOC_ERR:" + key;
+ }
return value;
}
@@ -638,6 +656,9 @@ public class LocaleController {
}
currentLocale = newLocale;
currentPluralRules = allRules.get(currentLocale.getLanguage());
+ if (currentPluralRules == null) {
+ currentPluralRules = allRules.get("en");
+ }
}
}
}
@@ -695,6 +716,20 @@ public class LocaleController {
}
}
+ private FastDateFormat createFormatter(Locale locale, String format, String defaultFormat) {
+ if (format == null || format.length() == 0) {
+ format = defaultFormat;
+ }
+ FastDateFormat formatter = null;
+ try {
+ formatter = FastDateFormat.getInstance(format, locale);
+ } catch (Exception e) {
+ format = defaultFormat;
+ formatter = FastDateFormat.getInstance(format, locale);
+ }
+ return formatter;
+ }
+
public void recreateFormatters() {
Locale locale = currentLocale;
if (locale == null) {
@@ -706,59 +741,15 @@ public class LocaleController {
}
isRTL = lang.toLowerCase().equals("ar");
nameDisplayOrder = lang.toLowerCase().equals("ko") ? 2 : 1;
- String formatString = getStringInternal("formatterMonth", R.string.formatterMonth);
- if (formatString == null || formatString.length() == 0) {
- formatString = "dd MMM";
- }
- formatterMonth = FastDateFormat.getInstance(formatString, locale);
- formatString = getStringInternal("formatterYear", R.string.formatterYear);
- if (formatString == null || formatString.length() == 0) {
- formatString = "dd.MM.yy";
- }
- formatterYear = FastDateFormat.getInstance(formatString, locale);
-
- formatString = getStringInternal("formatterYearMax", R.string.formatterYearMax);
- if (formatString == null || formatString.length() == 0) {
- formatString = "dd.MM.yyyy";
- }
- formatterYearMax = FastDateFormat.getInstance(formatString, locale);
-
- formatString = getStringInternal("chatDate", R.string.chatDate);
- if (formatString == null || formatString.length() == 0) {
- formatString = "d MMMM";
- }
- chatDate = FastDateFormat.getInstance(formatString, locale);
-
- formatString = getStringInternal("chatFullDate", R.string.chatFullDate);
- if (formatString == null || formatString.length() == 0) {
- formatString = "d MMMM yyyy";
- }
- chatFullDate = FastDateFormat.getInstance(formatString, locale);
-
- formatString = getStringInternal("formatterWeek", R.string.formatterWeek);
- if (formatString == null || formatString.length() == 0) {
- formatString = "EEE";
- }
- formatterWeek = FastDateFormat.getInstance(formatString, locale);
-
- if (is24HourFormat) {
- formatString = getStringInternal("formatterDay24H", R.string.formatterDay24H);
- } else {
- formatString = getStringInternal("formatterDay12H", R.string.formatterDay12H);
- }
- if (formatString == null || formatString.length() == 0) {
- if (is24HourFormat) {
- formatString = "HH:mm";
- } else {
- formatString = "h:mm a";
- }
- }
- if (lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko")) {
- formatterDay = FastDateFormat.getInstance(formatString, locale);
- } else {
- formatterDay = FastDateFormat.getInstance(formatString, Locale.US);
- }
+ formatterMonth = createFormatter(locale, getStringInternal("formatterMonth", R.string.formatterMonth), "dd MMM");
+ formatterYear = createFormatter(locale, getStringInternal("formatterYear", R.string.formatterYear), "dd.MM.yy");
+ formatterYearMax = createFormatter(locale, getStringInternal("formatterYearMax", R.string.formatterYearMax), "dd.MM.yyyy");
+ chatDate = createFormatter(locale, getStringInternal("chatDate", R.string.chatDate), "d MMMM");
+ chatFullDate = createFormatter(locale, getStringInternal("chatFullDate", R.string.chatFullDate), "d MMMM yyyy");
+ formatterWeek = createFormatter(locale, getStringInternal("formatterWeek", R.string.formatterWeek), "EEE");
+ formatterMonthYear = createFormatter(locale, getStringInternal("formatterMonthYear", R.string.formatterMonthYear), "MMMM yyyy");
+ formatterDay = createFormatter(lang.toLowerCase().equals("ar") || lang.toLowerCase().equals("ko") ? locale : Locale.US, is24HourFormat ? getStringInternal("formatterDay24H", R.string.formatterDay24H) : getStringInternal("formatterDay12H", R.string.formatterDay12H), is24HourFormat ? "HH:mm" : "h:mm a");
}
public static String stringForMessageListDate(long date) {
diff --git a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java
index efa53b092..629268341 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/MediaController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/MediaController.java
@@ -87,12 +87,12 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
public static int[] readArgs = new int[3];
- public static interface FileDownloadProgressListener {
- public void onFailedDownload(String fileName);
- public void onSuccessDownload(String fileName);
- public void onProgressDownload(String fileName, float progress);
- public void onProgressUpload(String fileName, float progress, boolean isEncrypted);
- public int getObserverTag();
+ public interface FileDownloadProgressListener {
+ void onFailedDownload(String fileName);
+ void onSuccessDownload(String fileName);
+ void onProgressDownload(String fileName, float progress);
+ void onProgressUpload(String fileName, float progress, boolean isEncrypted);
+ int getObserverTag();
}
private class AudioBuffer {
@@ -165,6 +165,8 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
public int size;
public int type;
public int date;
+ public String thumbPath;
+ public String imagePath;
}
public final static String MIME_TYPE = "video/avc";
@@ -232,6 +234,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
private long recordStartTime;
private long recordTimeCount;
private long recordDialogId;
+ private MessageObject recordReplyingMessageObject;
private DispatchQueue fileDecodingQueue;
private DispatchQueue playerQueue;
private ArrayList usedPlayerBuffers = new ArrayList<>();
@@ -507,7 +510,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
lastProgress = progress;
playingMessageObject.audioProgress = value;
playingMessageObject.audioProgressSec = lastProgress / 1000;
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioProgressDidChanged, playingMessageObject.messageOwner.id, value);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioProgressDidChanged, playingMessageObject.getId(), value);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
@@ -975,7 +978,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
} else if (id == NotificationCenter.messagesDeleted) {
if (playingMessageObject != null) {
ArrayList markAsDeletedMessages = (ArrayList)args[0];
- if (markAsDeletedMessages.contains(playingMessageObject.messageOwner.id)) {
+ if (markAsDeletedMessages.contains(playingMessageObject.getId())) {
clenupPlayer(false);
}
}
@@ -1102,8 +1105,16 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
if (proximitySensor != null && audioTrackPlayer == null && audioPlayer == null || isPaused || (useFrontSpeaker == (event.values[0] < proximitySensor.getMaximumRange() / 10))) {
return;
}
+ boolean newValue = event.values[0] < proximitySensor.getMaximumRange() / 10;
+ try {
+ if (newValue && NotificationsController.getInstance().audioManager.isWiredHeadsetOn()) {
+ return;
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
ignoreProximity = true;
- useFrontSpeaker = event.values[0] < proximitySensor.getMaximumRange() / 10;
+ useFrontSpeaker = newValue;
NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioRouteChanged, useFrontSpeaker);
MessageObject currentMessageObject = playingMessageObject;
float progress = playingMessageObject.audioProgress;
@@ -1185,7 +1196,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
playingMessageObject.audioProgressSec = 0;
playingMessageObject = null;
if (notify) {
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioDidReset, lastFile.messageOwner.id);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioDidReset, lastFile.getId());
}
}
}
@@ -1225,7 +1236,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
}
public boolean seekToProgress(MessageObject messageObject, float progress) {
- if (audioTrackPlayer == null && audioPlayer == null || messageObject == null || playingMessageObject == null || playingMessageObject != null && playingMessageObject.messageOwner.id != messageObject.messageOwner.id) {
+ if (audioTrackPlayer == null && audioPlayer == null || messageObject == null || playingMessageObject == null || playingMessageObject != null && playingMessageObject.getId() != messageObject.getId()) {
return false;
}
try {
@@ -1247,7 +1258,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
if (messageObject == null) {
return false;
}
- if ((audioTrackPlayer != null || audioPlayer != null) && playingMessageObject != null && messageObject.messageOwner.id == playingMessageObject.messageOwner.id) {
+ if ((audioTrackPlayer != null || audioPlayer != null) && playingMessageObject != null && messageObject.getId() == playingMessageObject.getId()) {
if (isPaused) {
resumeAudio(messageObject);
}
@@ -1410,7 +1421,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
public boolean pauseAudio(MessageObject messageObject) {
stopProximitySensor();
- if (audioTrackPlayer == null && audioPlayer == null || messageObject == null || playingMessageObject == null || playingMessageObject != null && playingMessageObject.messageOwner.id != messageObject.messageOwner.id) {
+ if (audioTrackPlayer == null && audioPlayer == null || messageObject == null || playingMessageObject == null || playingMessageObject != null && playingMessageObject.getId() != messageObject.getId()) {
return false;
}
try {
@@ -1430,7 +1441,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
public boolean resumeAudio(MessageObject messageObject) {
startProximitySensor();
- if (audioTrackPlayer == null && audioPlayer == null || messageObject == null || playingMessageObject == null || playingMessageObject != null && playingMessageObject.messageOwner.id != messageObject.messageOwner.id) {
+ if (audioTrackPlayer == null && audioPlayer == null || messageObject == null || playingMessageObject == null || playingMessageObject != null && playingMessageObject.getId() != messageObject.getId()) {
return false;
}
try {
@@ -1449,14 +1460,14 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
}
public boolean isPlayingAudio(MessageObject messageObject) {
- return !(audioTrackPlayer == null && audioPlayer == null || messageObject == null || playingMessageObject == null || playingMessageObject != null && playingMessageObject.messageOwner.id != messageObject.messageOwner.id);
+ return !(audioTrackPlayer == null && audioPlayer == null || messageObject == null || playingMessageObject == null || playingMessageObject != null && playingMessageObject.getId() != messageObject.getId());
}
public boolean isAudioPaused() {
return isPaused;
}
- public void startRecording(final long dialog_id) {
+ public void startRecording(final long dialog_id, final MessageObject reply_to_msg) {
clenupPlayer(true);
try {
@@ -1503,6 +1514,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
recordStartTime = System.currentTimeMillis();
recordTimeCount = 0;
recordDialogId = dialog_id;
+ recordReplyingMessageObject = reply_to_msg;
fileBuffer.rewind();
audioRecorder.startRecording();
@@ -1555,11 +1567,11 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
long duration = recordTimeCount;
audioToSend.duration = (int) (duration / 1000);
if (duration > 700) {
- SendMessagesHelper.getInstance().sendMessage(audioToSend, recordingAudioFileToSend.getAbsolutePath(), recordDialogId);
+ SendMessagesHelper.getInstance().sendMessage(audioToSend, recordingAudioFileToSend.getAbsolutePath(), recordDialogId, recordReplyingMessageObject);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioDidSent);
} else {
recordingAudioFileToSend.delete();
}
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.audioDidSent);
}
});
}
@@ -1696,10 +1708,10 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
FileLog.e("tmessages", e);
result = false;
} finally {
- if(source != null) {
+ if (source != null) {
source.close();
}
- if(destination != null) {
+ if (destination != null) {
destination.close();
}
}
@@ -1737,7 +1749,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
return null;
}
- if (currentGifDrawable != null && currentGifMessageObject != null && messageObject.messageOwner.id == currentGifMessageObject.messageOwner.id) {
+ if (currentGifDrawable != null && currentGifMessageObject != null && messageObject.getId() == currentGifMessageObject.getId()) {
currentMediaCell = cell;
currentGifDrawable.parentView = new WeakReference(cell);
return currentGifDrawable;
@@ -1786,7 +1798,7 @@ public class MediaController implements NotificationCenter.NotificationCenterDel
return;
}
- if (currentGifMessageObject != null && messageObject.messageOwner.id == currentGifMessageObject.messageOwner.id) {
+ if (currentGifMessageObject != null && messageObject.getId() == currentGifMessageObject.getId()) {
if (currentGifDrawable != null) {
currentGifDrawable.stop();
currentGifDrawable.recycle();
diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java b/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java
index 1c6c0dd48..525c91eba 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/MessageObject.java
@@ -30,6 +30,8 @@ import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
public class MessageObject {
@@ -39,9 +41,12 @@ public class MessageObject {
public TLRPC.Message messageOwner;
public CharSequence messageText;
+ public CharSequence linkDescription;
+ public MessageObject replyMessageObject;
public int type;
public int contentType;
public String dateKey;
+ public String monthKey;
public boolean deleted = false;
public float audioProgress;
public int audioProgressSec;
@@ -75,6 +80,10 @@ public class MessageObject {
messageOwner = message;
+ if (message.replyMessage != null) {
+ replyMessageObject = new MessageObject(message.replyMessage, users, false);
+ }
+
if (message instanceof TLRPC.TL_messageService) {
if (message.action != null) {
TLRPC.User fromUser = null;
@@ -85,7 +94,7 @@ public class MessageObject {
fromUser = MessagesController.getInstance().getUser(message.from_id);
}
if (message.action instanceof TLRPC.TL_messageActionChatCreate) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.getString("ActionYouCreateGroup", R.string.ActionYouCreateGroup);
} else {
if (fromUser != null) {
@@ -96,7 +105,7 @@ public class MessageObject {
}
} else if (message.action instanceof TLRPC.TL_messageActionChatDeleteUser) {
if (message.action.user_id == message.from_id) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.getString("ActionYouLeftUser", R.string.ActionYouLeftUser);
} else {
if (fromUser != null) {
@@ -114,7 +123,7 @@ public class MessageObject {
whoUser = MessagesController.getInstance().getUser(message.action.user_id);
}
if (whoUser != null && fromUser != null) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = replaceWithLink(LocaleController.getString("ActionYouKickUser", R.string.ActionYouKickUser), "un2", whoUser);
} else if (message.action.user_id == UserConfig.getClientUserId()) {
messageText = replaceWithLink(LocaleController.getString("ActionKickUserYou", R.string.ActionKickUserYou), "un1", fromUser);
@@ -135,7 +144,7 @@ public class MessageObject {
whoUser = MessagesController.getInstance().getUser(message.action.user_id);
}
if (whoUser != null && fromUser != null) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = replaceWithLink(LocaleController.getString("ActionYouAddUser", R.string.ActionYouAddUser), "un2", whoUser);
} else if (message.action.user_id == UserConfig.getClientUserId()) {
messageText = replaceWithLink(LocaleController.getString("ActionAddUserYou", R.string.ActionAddUserYou), "un1", fromUser);
@@ -147,7 +156,7 @@ public class MessageObject {
messageText = LocaleController.getString("ActionAddUser", R.string.ActionAddUser).replace("un2", "").replace("un1", "");
}
} else if (message.action instanceof TLRPC.TL_messageActionChatEditPhoto) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.getString("ActionYouChangedPhoto", R.string.ActionYouChangedPhoto);
} else {
if (fromUser != null) {
@@ -157,7 +166,7 @@ public class MessageObject {
}
}
} else if (message.action instanceof TLRPC.TL_messageActionChatEditTitle) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.getString("ActionYouChangedTitle", R.string.ActionYouChangedTitle).replace("un2", message.action.title);
} else {
if (fromUser != null) {
@@ -167,7 +176,7 @@ public class MessageObject {
}
}
} else if (message.action instanceof TLRPC.TL_messageActionChatDeletePhoto) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.getString("ActionYouRemovedPhoto", R.string.ActionYouRemovedPhoto);
} else {
if (fromUser != null) {
@@ -178,7 +187,7 @@ public class MessageObject {
}
} else if (message.action instanceof TLRPC.TL_messageActionTTLChange) {
if (message.action.ttl != 0) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.formatString("MessageLifetimeChangedOutgoing", R.string.MessageLifetimeChangedOutgoing, AndroidUtilities.formatTTLString(message.action.ttl));
} else {
if (fromUser != null) {
@@ -188,7 +197,7 @@ public class MessageObject {
}
}
} else {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.getString("MessageLifetimeYouRemoved", R.string.MessageLifetimeYouRemoved);
} else {
if (fromUser != null) {
@@ -199,7 +208,7 @@ public class MessageObject {
}
}
} else if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
- String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(((long)message.date) * 1000), LocaleController.formatterDay.format(((long)message.date) * 1000));
+ String date = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.formatterYear.format(((long) message.date) * 1000), LocaleController.formatterDay.format(((long) message.date) * 1000));
TLRPC.User to_user = UserConfig.getCurrentUser();
if (to_user == null) {
if (users != null) {
@@ -228,7 +237,7 @@ public class MessageObject {
}
} else if (message.action instanceof TLRPC.TL_messageEncryptedAction) {
if (message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionScreenshotMessages) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.formatString("ActionTakeScreenshootYou", R.string.ActionTakeScreenshootYou);
} else {
if (fromUser != null) {
@@ -240,7 +249,7 @@ public class MessageObject {
} else if (message.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) {
TLRPC.TL_decryptedMessageActionSetMessageTTL action = (TLRPC.TL_decryptedMessageActionSetMessageTTL) message.action.encryptedAction;
if (action.ttl_seconds != 0) {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.formatString("MessageLifetimeChangedOutgoing", R.string.MessageLifetimeChangedOutgoing, AndroidUtilities.formatTTLString(action.ttl_seconds));
} else {
if (fromUser != null) {
@@ -250,7 +259,7 @@ public class MessageObject {
}
}
} else {
- if (isFromMe()) {
+ if (isOut()) {
messageText = LocaleController.getString("MessageLifetimeYouRemoved", R.string.MessageLifetimeYouRemoved);
} else {
if (fromUser != null) {
@@ -265,7 +274,7 @@ public class MessageObject {
messageText = LocaleController.formatString("YouCreatedBroadcastList", R.string.YouCreatedBroadcastList);
}
}
- } else if (message.media != null && !(message.media instanceof TLRPC.TL_messageMediaEmpty)) {
+ } else if (!isMediaEmpty()) {
if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
messageText = LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
@@ -278,9 +287,19 @@ public class MessageObject {
messageText = LocaleController.getString("UnsuppotedMedia", R.string.UnsuppotedMedia);
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
if (isSticker()) {
- messageText = LocaleController.getString("AttachSticker", R.string.AttachSticker);
+ String sch = getStrickerChar();
+ if (sch != null && sch.length() > 0) {
+ messageText = String.format("%s %s", sch, LocaleController.getString("AttachSticker", R.string.AttachSticker));
+ } else {
+ messageText = LocaleController.getString("AttachSticker", R.string.AttachSticker);
+ }
} else {
- messageText = LocaleController.getString("AttachDocument", R.string.AttachDocument);
+ String name = FileLoader.getDocumentFileName(message.media.document);
+ if (name != null && name.length() > 0) {
+ messageText = name;
+ } else {
+ messageText = LocaleController.getString("AttachDocument", R.string.AttachDocument);
+ }
}
} else if (message.media instanceof TLRPC.TL_messageMediaAudio) {
messageText = LocaleController.getString("AttachAudio", R.string.AttachAudio);
@@ -290,23 +309,23 @@ public class MessageObject {
}
messageText = Emoji.replaceEmoji(messageText, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20));
- if (message instanceof TLRPC.TL_message || message instanceof TLRPC.TL_messageForwarded) {
- if (message.media == null || message.media instanceof TLRPC.TL_messageMediaEmpty) {
+ if (message instanceof TLRPC.TL_message || message instanceof TLRPC.TL_messageForwarded_old2) {
+ if (isMediaEmpty()) {
contentType = type = 0;
- } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaPhoto) {
+ } else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
contentType = type = 1;
- } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaGeo) {
+ } else if (message.media instanceof TLRPC.TL_messageMediaGeo) {
contentType = 1;
type = 4;
- } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaVideo) {
+ } else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
contentType = 1;
type = 3;
- } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaContact) {
+ } else if (message.media instanceof TLRPC.TL_messageMediaContact) {
contentType = 3;
type = 12;
- } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaUnsupported) {
+ } else if (message.media instanceof TLRPC.TL_messageMediaUnsupported) {
contentType = type = 0;
- } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaDocument) {
+ } else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
contentType = 1;
if (message.media.document.mime_type != null) {
if (message.media.document.mime_type.equals("image/gif") && message.media.document.thumb != null && !(message.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty)) {
@@ -322,7 +341,7 @@ public class MessageObject {
} else {
type = 9;
}
- } else if (message.media != null && message.media instanceof TLRPC.TL_messageMediaAudio) {
+ } else if (message.media instanceof TLRPC.TL_messageMediaAudio) {
contentType = type = 2;
}
} else if (message instanceof TLRPC.TL_messageService) {
@@ -346,11 +365,14 @@ public class MessageObject {
}
Calendar rightNow = new GregorianCalendar();
- rightNow.setTimeInMillis((long)(messageOwner.date) * 1000);
+ rightNow.setTimeInMillis((long) (messageOwner.date) * 1000);
int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);
int dateYear = rightNow.get(Calendar.YEAR);
int dateMonth = rightNow.get(Calendar.MONTH);
dateKey = String.format("%d_%02d_%02d", dateYear, dateMonth, dateDay);
+ if (contentType == 1 || contentType == 2) {
+ monthKey = String.format("%d_%02d", dateYear, dateMonth);
+ }
if (generateLayout) {
generateLayout();
@@ -412,6 +434,24 @@ public class MessageObject {
photoObject.location = messageOwner.media.document.thumb.location;
}
}
+ } else if (messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
+ if (messageOwner.media.webpage.photo != null) {
+ if (!update || photoThumbs == null) {
+ photoThumbs = new ArrayList<>(messageOwner.media.webpage.photo.sizes);
+ } else if (photoThumbs != null && !photoThumbs.isEmpty()) {
+ for (TLRPC.PhotoSize photoObject : photoThumbs) {
+ for (TLRPC.PhotoSize size : messageOwner.media.webpage.photo.sizes) {
+ if (size instanceof TLRPC.TL_photoSizeEmpty) {
+ continue;
+ }
+ if (size.type.equals(photoObject.type)) {
+ photoObject.location = size.location;
+ break;
+ }
+ }
+ }
+ }
+ }
}
}
}
@@ -483,6 +523,9 @@ public class MessageObject {
} else if (!(c != ' ' && digitsInRow > 0)) {
digitsInRow = 0;
}
+ if ((c == '@' || c == '#') && i == 0 || i != 0 && (message.charAt(i - 1) == ' ' || message.charAt(i - 1) == '\n')) {
+ return true;
+ }
if (c == ':') {
if (schemeSequence == 0) {
schemeSequence = 1;
@@ -514,11 +557,24 @@ public class MessageObject {
return false;
}
+ public void generateLinkDescription() {
+ if (linkDescription != null) {
+ return;
+ }
+ if (messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageOwner.media.webpage instanceof TLRPC.TL_webPage && messageOwner.media.webpage.description != null) {
+ linkDescription = Spannable.Factory.getInstance().newSpannable(messageOwner.media.webpage.description);
+ if (containsUrls(linkDescription)) {
+ Linkify.addLinks((Spannable) linkDescription, Linkify.WEB_URLS);
+ }
+ }
+ }
+
private void generateLayout() {
if (type != 0 || messageOwner.to_id == null || messageText == null || messageText.length() == 0) {
return;
}
+ generateLinkDescription();
textLayoutBlocks = new ArrayList<>();
if (messageText instanceof Spannable && containsUrls(messageText)) {
@@ -527,17 +583,33 @@ public class MessageObject {
} else {
Linkify.addLinks((Spannable) messageText, Linkify.WEB_URLS);
}
+
+ try {
+ Pattern pattern = Pattern.compile("(^|\\s)@[a-zA-Z\\d_]{5,32}|(^|\\s)#[\\w\\.]+");
+ Matcher matcher = pattern.matcher(messageText);
+ while (matcher.find()) {
+ int start = matcher.start();
+ int end = matcher.end();
+ if (messageText.charAt(start) != '@' && messageText.charAt(start) != '#') {
+ start++;
+ }
+ URLSpanNoUnderline url = new URLSpanNoUnderline(messageText.subSequence(start, end).toString());
+ ((Spannable) messageText).setSpan(url, start, end, 0);
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
}
int maxWidth;
if (AndroidUtilities.isTablet()) {
- if (messageOwner.to_id.chat_id != 0) {
+ if (messageOwner.to_id.chat_id != 0 && !isOut()) {
maxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(122);
} else {
maxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(80);
}
} else {
- if (messageOwner.to_id.chat_id != 0) {
+ if (messageOwner.to_id.chat_id != 0 && !isOut()) {
maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122);
} else {
maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(80);
@@ -556,7 +628,7 @@ public class MessageObject {
textHeight = textLayout.getHeight();
int linesCount = textLayout.getLineCount();
- int blocksCount = (int)Math.ceil((float)linesCount / LINES_PER_BLOCK);
+ int blocksCount = (int) Math.ceil((float) linesCount / LINES_PER_BLOCK);
int linesOffset = 0;
float prevOffset = 0;
@@ -581,7 +653,7 @@ public class MessageObject {
block.textLayout = new StaticLayout(str, textPaint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
block.textYOffset = textLayout.getLineTop(linesOffset);
if (a != 0) {
- blockHeight = Math.min(blockHeight, (int)(block.textYOffset - prevOffset));
+ blockHeight = Math.min(blockHeight, (int) (block.textYOffset - prevOffset));
}
prevOffset = block.textYOffset;
/*if (a != blocksCount - 1) {
@@ -613,7 +685,7 @@ public class MessageObject {
FileLog.e("tmessages", e);
}
- int linesMaxWidth = (int)Math.ceil(lastLine);
+ int linesMaxWidth = (int) Math.ceil(lastLine);
int lastLineWidthWithLeft;
int linesMaxWidthWithLeft;
boolean hasNonRTL = false;
@@ -622,7 +694,7 @@ public class MessageObject {
lastLineWidth = linesMaxWidth;
}
- linesMaxWidthWithLeft = lastLineWidthWithLeft = (int)Math.ceil(lastLine + lastLeft);
+ linesMaxWidthWithLeft = lastLineWidthWithLeft = (int) Math.ceil(lastLine + lastLeft);
if (lastLeft == 0) {
hasNonRTL = true;
}
@@ -655,8 +727,8 @@ public class MessageObject {
}
textRealMaxWidth = Math.max(textRealMaxWidth, lineWidth);
textRealMaxWidthWithLeft = Math.max(textRealMaxWidthWithLeft, lineWidth + lineLeft);
- linesMaxWidth = Math.max(linesMaxWidth, (int)Math.ceil(lineWidth));
- linesMaxWidthWithLeft = Math.max(linesMaxWidthWithLeft, (int)Math.ceil(lineWidth + lineLeft));
+ linesMaxWidth = Math.max(linesMaxWidth, (int) Math.ceil(lineWidth));
+ linesMaxWidthWithLeft = Math.max(linesMaxWidthWithLeft, (int) Math.ceil(lineWidth + lineLeft));
}
if (hasNonRTL) {
textRealMaxWidth = textRealMaxWidthWithLeft;
@@ -667,7 +739,7 @@ public class MessageObject {
} else if (a == blocksCount - 1) {
lastLineWidth = linesMaxWidth;
}
- textWidth = Math.max(textWidth, (int)Math.ceil(textRealMaxWidth));
+ textWidth = Math.max(textWidth, (int) Math.ceil(textRealMaxWidth));
} else {
textWidth = Math.max(textWidth, Math.min(maxWidth, linesMaxWidth));
}
@@ -687,16 +759,16 @@ public class MessageObject {
return (messageOwner.flags & TLRPC.MESSAGE_FLAG_OUT) != 0;
}
- public boolean isFromMe() {
- return messageOwner.from_id == UserConfig.getClientUserId();
- }
-
public boolean isUnread() {
return (messageOwner.flags & TLRPC.MESSAGE_FLAG_UNREAD) != 0;
}
public void setIsRead() {
- messageOwner.flags &=~ TLRPC.MESSAGE_FLAG_UNREAD;
+ messageOwner.flags &= ~TLRPC.MESSAGE_FLAG_UNREAD;
+ }
+
+ public int getId() {
+ return messageOwner.id;
}
public boolean isSecretPhoto() {
@@ -706,15 +778,15 @@ public class MessageObject {
public boolean isSecretMedia() {
return messageOwner instanceof TLRPC.TL_message_secret &&
(messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && messageOwner.ttl != 0 && messageOwner.ttl <= 60 ||
- messageOwner.media instanceof TLRPC.TL_messageMediaAudio ||
- messageOwner.media instanceof TLRPC.TL_messageMediaVideo);
+ messageOwner.media instanceof TLRPC.TL_messageMediaAudio ||
+ messageOwner.media instanceof TLRPC.TL_messageMediaVideo);
}
public static void setIsUnread(TLRPC.Message message, boolean unread) {
if (unread) {
message.flags |= TLRPC.MESSAGE_FLAG_UNREAD;
} else {
- message.flags &=~ TLRPC.MESSAGE_FLAG_UNREAD;
+ message.flags &= ~TLRPC.MESSAGE_FLAG_UNREAD;
}
}
@@ -732,7 +804,7 @@ public class MessageObject {
} else {
if (messageOwner.to_id.chat_id != 0) {
return -messageOwner.to_id.chat_id;
- } else if (isFromMe()) {
+ } else if (isOut()) {
return messageOwner.to_id.user_id;
} else {
return messageOwner.from_id;
@@ -741,7 +813,7 @@ public class MessageObject {
}
public boolean isSending() {
- return messageOwner.send_state == MESSAGE_SEND_STATE_SENDING;
+ return messageOwner.send_state == MESSAGE_SEND_STATE_SENDING && messageOwner.id < 0;
}
public boolean isSendError() {
@@ -749,7 +821,7 @@ public class MessageObject {
}
public boolean isSent() {
- return messageOwner.send_state == MESSAGE_SEND_STATE_SENT;
+ return messageOwner.send_state == MESSAGE_SEND_STATE_SENT || messageOwner.id > 0;
}
public String getSecretTimeString() {
@@ -787,7 +859,129 @@ public class MessageObject {
return false;
}
+ public String getStrickerChar() {
+ if (messageOwner.media != null && messageOwner.media.document != null) {
+ for (TLRPC.DocumentAttribute attribute : messageOwner.media.document.attributes) {
+ if (attribute instanceof TLRPC.TL_documentAttributeSticker) {
+ return attribute.alt;
+ }
+ }
+ }
+ return null;
+ }
+
+ public int getApproximateHeight() {
+ if (type == 0) {
+ return textHeight;
+ } else if (contentType == 2) {
+ return AndroidUtilities.dp(68);
+ } else if (contentType == 3) {
+ return AndroidUtilities.dp(71);
+ } else if (type == 9) {
+ return AndroidUtilities.dp(100);
+ } else if (type == 4) {
+ return AndroidUtilities.dp(114);
+ } else if (type == 13) {
+ float maxHeight = AndroidUtilities.displaySize.y * 0.4f;
+ float maxWidth;
+ if (AndroidUtilities.isTablet()) {
+ maxWidth = AndroidUtilities.getMinTabletSide() * 0.5f;
+ } else {
+ maxWidth = AndroidUtilities.displaySize.x * 0.5f;
+ }
+ int photoHeight = 0;
+ int photoWidth = 0;
+ for (TLRPC.DocumentAttribute attribute : messageOwner.media.document.attributes) {
+ if (attribute instanceof TLRPC.TL_documentAttributeImageSize) {
+ photoWidth = attribute.w;
+ photoHeight = attribute.h;
+ break;
+ }
+ }
+ if (photoWidth == 0) {
+ photoHeight = (int) maxHeight;
+ photoWidth = photoHeight + AndroidUtilities.dp(100);
+ }
+ if (photoHeight > maxHeight) {
+ photoWidth *= maxHeight / photoHeight;
+ photoHeight = (int)maxHeight;
+ }
+ if (photoWidth > maxWidth) {
+ photoHeight *= maxWidth / photoWidth;
+ }
+ return photoHeight + AndroidUtilities.dp(14);
+ } else {
+ int photoHeight = 0;
+ int photoWidth = 0;
+
+ if (AndroidUtilities.isTablet()) {
+ photoWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.7f);
+ } else {
+ photoWidth = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f);
+ }
+ photoHeight = photoWidth + AndroidUtilities.dp(100);
+ if (photoWidth > AndroidUtilities.getPhotoSize()) {
+ photoWidth = AndroidUtilities.getPhotoSize();
+ }
+ if (photoHeight > AndroidUtilities.getPhotoSize()) {
+ photoHeight = AndroidUtilities.getPhotoSize();
+ }
+ TLRPC.PhotoSize currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(photoThumbs, AndroidUtilities.getPhotoSize());
+
+ if (currentPhotoObject != null) {
+ float scale = (float) currentPhotoObject.w / (float) photoWidth;
+ int w = (int) (currentPhotoObject.w / scale);
+ int h = (int) (currentPhotoObject.h / scale);
+ if (w == 0) {
+ w = AndroidUtilities.dp(100);
+ }
+ if (h == 0) {
+ h = AndroidUtilities.dp(100);
+ }
+ if (h > photoHeight) {
+ float scale2 = h;
+ h = photoHeight;
+ scale2 /= h;
+ w = (int) (w / scale2);
+ } else if (h < AndroidUtilities.dp(120)) {
+ h = AndroidUtilities.dp(120);
+ float hScale = (float) currentPhotoObject.h / h;
+ if (currentPhotoObject.w / hScale < photoWidth) {
+ w = (int) (currentPhotoObject.w / hScale);
+ }
+ }
+ if (isSecretPhoto()) {
+ if (AndroidUtilities.isTablet()) {
+ w = h = (int) (AndroidUtilities.getMinTabletSide() * 0.5f);
+ } else {
+ w = h = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.5f);
+ }
+ }
+
+ photoWidth = w;
+ photoHeight = h;
+ }
+ return photoHeight + AndroidUtilities.dp(14);
+ }
+ }
+
public boolean isSticker() {
return isStickerMessage(messageOwner);
}
+
+ public boolean isForwarded() {
+ return (messageOwner.flags & TLRPC.MESSAGE_FLAG_FWD) != 0;
+ }
+
+ public boolean isReply() {
+ return !(replyMessageObject != null && replyMessageObject.messageOwner instanceof TLRPC.TL_messageEmpty) && messageOwner.reply_to_msg_id != 0 && (messageOwner.flags & TLRPC.MESSAGE_FLAG_REPLY) != 0;
+ }
+
+ public boolean isMediaEmpty() {
+ return isMediaEmpty(messageOwner);
+ }
+
+ public static boolean isMediaEmpty(TLRPC.Message message) {
+ return message == null || message.media == null || message.media instanceof TLRPC.TL_messageMediaEmpty || message.media instanceof TLRPC.TL_messageMediaWebPage;
+ }
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java
index 71bd216e9..6d2b29972 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesController.java
@@ -9,10 +9,11 @@
package org.telegram.android;
import android.app.Activity;
+import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Build;
-import android.text.Html;
+import android.util.Base64;
import android.util.SparseArray;
import org.telegram.messenger.ConnectionsManager;
@@ -20,11 +21,14 @@ import org.telegram.messenger.FileLoader;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
+import org.telegram.messenger.SerializedData;
+import org.telegram.messenger.TLClassStore;
import org.telegram.messenger.TLObject;
import org.telegram.messenger.TLRPC;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.ApplicationLoader;
+import org.telegram.ui.ActionBar.BaseFragment;
import java.util.ArrayList;
import java.util.Collections;
@@ -39,6 +43,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
private ConcurrentHashMap chats = new ConcurrentHashMap<>(100, 1.0f, 2);
private ConcurrentHashMap encryptedChats = new ConcurrentHashMap<>(10, 1.0f, 2);
private ConcurrentHashMap users = new ConcurrentHashMap<>(100, 1.0f, 2);
+ private ConcurrentHashMap usersByUsernames = new ConcurrentHashMap<>(100, 1.0f, 2);
public ArrayList dialogs = new ArrayList<>();
public ArrayList dialogsServerOnly = new ArrayList<>();
@@ -53,8 +58,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public boolean loadingBlockedUsers = false;
public ArrayList blockedUsers = new ArrayList<>();
- private ArrayList updatesQueue = new ArrayList<>();
- private long updatesStartWaitTime = 0;
+ private ArrayList updatesQueueSeq = new ArrayList<>();
+ private ArrayList updatesQueuePts = new ArrayList<>();
+ private ArrayList updatesQueueQts = new ArrayList<>();
+ private long updatesStartWaitTimeSeq = 0;
+ private long updatesStartWaitTimePts = 0;
+ private long updatesStartWaitTimeQts = 0;
private ArrayList loadingFullUsers = new ArrayList<>();
private ArrayList loadedFullUsers = new ArrayList<>();
private ArrayList loadingFullChats = new ArrayList<>();
@@ -86,8 +95,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public int fontSize = AndroidUtilities.dp(16);
public int maxGroupCount = 200;
public int maxBroadcastCount = 100;
+ public int groupBigSize;
+ private ArrayList disabledFeatures = new ArrayList<>();
- private class UserActionUpdates extends TLRPC.Updates {
+ private class UserActionUpdatesSeq extends TLRPC.Updates {
+
+ }
+
+ private class UserActionUpdatesPts extends TLRPC.Updates {
}
@@ -102,6 +117,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public static final int UPDATE_MASK_READ_DIALOG_MESSAGE = 256;
public static final int UPDATE_MASK_SELECT_DIALOG = 512;
public static final int UPDATE_MASK_PHONE = 1024;
+ public static final int UPDATE_MASK_NEW_MESSAGE = 2048;
+ public static final int UPDATE_MASK_SEND_STATE = 4096;
public static final int UPDATE_MASK_ALL = UPDATE_MASK_AVATAR | UPDATE_MASK_STATUS | UPDATE_MASK_NAME | UPDATE_MASK_CHAT_AVATAR | UPDATE_MASK_CHAT_NAME | UPDATE_MASK_CHAT_MEMBERS | UPDATE_MASK_USER_PRINT | UPDATE_MASK_USER_PHONE | UPDATE_MASK_READ_DIALOG_MESSAGE | UPDATE_MASK_PHONE;
public static class PrintingUser {
@@ -138,24 +155,80 @@ public class MessagesController implements NotificationCenter.NotificationCenter
preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
maxGroupCount = preferences.getInt("maxGroupCount", 200);
maxBroadcastCount = preferences.getInt("maxBroadcastCount", 100);
+ groupBigSize = preferences.getInt("groupBigSize", 10);
fontSize = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16);
+ String disabledFeaturesString = preferences.getString("disabledFeatures", null);
+ if (disabledFeaturesString != null && disabledFeaturesString.length() != 0) {
+ try {
+ byte[] bytes = Base64.decode(disabledFeaturesString, Base64.DEFAULT);
+ if (bytes != null) {
+ SerializedData data = new SerializedData(bytes);
+ int count = data.readInt32();
+ for (int a = 0; a < count; a++) {
+ TLRPC.TL_disabledFeature feature = (TLRPC.TL_disabledFeature) TLClassStore.Instance().TLdeserialize(data, data.readInt32());
+ if (feature != null && feature.feature != null && feature.description != null) {
+ disabledFeatures.add(feature);
+ }
+ }
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
}
public void updateConfig(final TLRPC.TL_config config) {
- AndroidUtilities.runOnUIThread(new Runnable() {
+ AndroidUtilities.runOnUIThread(new Runnable() { //TODO use new config params
@Override
public void run() {
maxBroadcastCount = config.broadcast_size_max;
maxGroupCount = config.chat_size_max;
+ groupBigSize = config.chat_big_size;
+ disabledFeatures = config.disabled_features;
+
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("maxGroupCount", maxGroupCount);
editor.putInt("maxBroadcastCount", maxBroadcastCount);
+ editor.putInt("groupBigSize", groupBigSize);
+ try {
+ SerializedData data = new SerializedData();
+ data.writeInt32(disabledFeatures.size());
+ for (TLRPC.TL_disabledFeature disabledFeature : disabledFeatures) {
+ disabledFeature.serializeToStream(data);
+ }
+ String string = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);
+ if (string != null && string.length() != 0) {
+ editor.putString("disabledFeatures", string);
+ }
+ } catch (Exception e) {
+ editor.remove("disabledFeatures");
+ FileLog.e("tmessages", e);
+ }
editor.commit();
}
});
}
+ public static boolean isFeatureEnabled(String feature, BaseFragment fragment) {
+ if (feature == null || feature.length() == 0 || getInstance().disabledFeatures.isEmpty() || fragment == null) {
+ return true;
+ }
+ for (TLRPC.TL_disabledFeature disabledFeature : getInstance().disabledFeatures) {
+ if (disabledFeature.feature.equals(feature)) {
+ if (fragment.getParentActivity() != null) {
+ AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());
+ builder.setTitle("Oops!");
+ builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
+ builder.setMessage(disabledFeature.description);
+ fragment.showAlertDialog(builder);
+ }
+ return false;
+ }
+ }
+ return true;
+ }
+
public void addSupportUser() {
TLRPC.TL_userForeign user = new TLRPC.TL_userForeign();
user.phone = "333";
@@ -302,6 +375,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialogs.clear();
dialogsServerOnly.clear();
users.clear();
+ usersByUsernames.clear();
chats.clear();
dialogMessage.clear();
printingUsers.clear();
@@ -309,7 +383,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
onlinePrivacy.clear();
totalDialogsCount = 0;
lastPrintingStringCount = 0;
- updatesQueue.clear();
+ updatesQueueSeq.clear();
+ updatesQueuePts.clear();
+ updatesQueueQts.clear();
blockedUsers.clear();
sendingTypings.clear();
loadingFullUsers.clear();
@@ -318,7 +394,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
loadingFullChats.clear();
loadedFullChats.clear();
- updatesStartWaitTime = 0;
+ updatesStartWaitTimeSeq = 0;
+ updatesStartWaitTimePts = 0;
+ updatesStartWaitTimeQts = 0;
currentDeletingTaskTime = 0;
currentDeletingTaskMids = null;
gettingNewDeleteTask = false;
@@ -348,6 +426,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return users.get(id);
}
+ public TLRPC.User getUser(String username) {
+ return usersByUsernames.get(username);
+ }
+
+ public ConcurrentHashMap getUsers() {
+ return users;
+ }
+
public TLRPC.Chat getChat(Integer id) {
return chats.get(id);
}
@@ -383,6 +469,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
fromCache = fromCache && user.id / 1000 != 333 && user.id != 777000;
TLRPC.User oldUser = users.get(user.id);
+ if (oldUser != null && oldUser.username != null && oldUser.username.length() > 0) {
+ usersByUsernames.remove(oldUser.username);
+ }
+ if (user.username != null && user.username.length() > 0) {
+ usersByUsernames.put(user.username, user);
+ }
if (!fromCache) {
users.put(user.id, user);
if (user.id == UserConfig.getClientUserId()) {
@@ -593,28 +685,48 @@ public class MessagesController implements NotificationCenter.NotificationCenter
});
}
- protected void processNewDifferenceParams(int seq, int pts, int date) {
- if (MessagesStorage.lastSeqValue + 1 == seq) {
- if (seq != -1) {
- MessagesStorage.lastSeqValue = seq;
- }
- if (date != -1) {
- MessagesStorage.lastDateValue = date;
- }
- if (pts != -1) {
+ protected void processNewDifferenceParams(int seq, int pts, int date, int pts_count) {
+ FileLog.e("tmessages", "processNewDifferenceParams seq = " + seq + " pts = " + pts + " date = " + date + " pts_count = " + pts_count);
+ if (pts != -1) {
+ if (MessagesStorage.lastPtsValue + pts_count == pts) {
+ FileLog.e("tmessages", "APPLY PTS");
MessagesStorage.lastPtsValue = pts;
- }
- MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);
- } else if (MessagesStorage.lastSeqValue != seq) {
- if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) {
- if (updatesStartWaitTime == 0) {
- updatesStartWaitTime = System.currentTimeMillis();
+ MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);
+ } else if (MessagesStorage.lastPtsValue != pts) {
+ if (gettingDifference || updatesStartWaitTimePts == 0 || updatesStartWaitTimePts != 0 && updatesStartWaitTimePts + 1500 > System.currentTimeMillis()) {
+ FileLog.e("tmessages", "ADD UPDATE TO QUEUE pts = " + pts + " pts_count = " + pts_count);
+ if (updatesStartWaitTimePts == 0) {
+ updatesStartWaitTimePts = System.currentTimeMillis();
+ }
+ UserActionUpdatesPts updates = new UserActionUpdatesPts();
+ updates.pts = pts;
+ updates.pts_count = pts_count;
+ updatesQueuePts.add(updates);
+ } else {
+ getDifference();
+ }
+ }
+ }
+ if (seq != -1) {
+ if (MessagesStorage.lastSeqValue + 1 == seq) {
+ FileLog.e("tmessages", "APPLY SEQ");
+ MessagesStorage.lastSeqValue = seq;
+ if (date != -1) {
+ MessagesStorage.lastDateValue = date;
+ }
+ MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);
+ } else if (MessagesStorage.lastSeqValue != seq) {
+ if (gettingDifference || updatesStartWaitTimeSeq == 0 || updatesStartWaitTimeSeq != 0 && updatesStartWaitTimeSeq + 1500 > System.currentTimeMillis()) {
+ FileLog.e("tmessages", "ADD UPDATE TO QUEUE seq = " + seq);
+ if (updatesStartWaitTimeSeq == 0) {
+ updatesStartWaitTimeSeq = System.currentTimeMillis();
+ }
+ UserActionUpdatesSeq updates = new UserActionUpdatesSeq();
+ updates.seq = seq;
+ updatesQueueSeq.add(updates);
+ } else {
+ getDifference();
}
- UserActionUpdates updates = new UserActionUpdates();
- updates.seq = seq;
- updatesQueue.add(updates);
- } else {
- getDifference();
}
}
}
@@ -760,7 +872,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (user == null) {
return;
}
- blockedUsers.remove((Integer)user.id);
+ blockedUsers.remove((Integer) user.id);
req.id = MessagesController.getInputUser(user);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded);
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@@ -859,10 +971,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter
ArrayList users = new ArrayList<>();
users.add(user);
MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);
- user.photo = (TLRPC.UserProfilePhoto)response;
+ user.photo = (TLRPC.UserProfilePhoto) response;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
UserConfig.saveConfig(true);
}
@@ -938,16 +1051,15 @@ public class MessagesController implements NotificationCenter.NotificationCenter
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
-
+ if (error == null) {
+ TLRPC.TL_messages_affectedMessages res = (TLRPC.TL_messages_affectedMessages) response;
+ processNewDifferenceParams(-1, res.pts, -1, res.pts_count);
+ }
}
});
}
public void deleteDialog(final long did, int offset, final boolean onlyHistory) {
- if (offset == 0) {
- MessagesStorage.getInstance().deleteDialog(did, onlyHistory);
- }
-
int lower_part = (int)did;
int high_id = (int)(did >> 32);
@@ -963,7 +1075,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialog.unread_count = 0;
}
dialogMessage.remove(dialog.top_message);
+ dialog.top_message = 0;
}
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
@@ -978,8 +1093,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
});
}
});
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+
+ MessagesStorage.getInstance().deleteDialog(did, onlyHistory);
}
if (high_id == 1) {
@@ -1010,7 +1125,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (res.offset > 0) {
deleteDialog(did, res.offset, onlyHistory);
}
- processNewDifferenceParams(res.seq, res.pts, -1);
+ processNewDifferenceParams(-1, res.pts, -1, res.pts_count);
}
}
});
@@ -1096,9 +1211,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter
});
}
- if (updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 < currentTime) {
- FileLog.e("tmessages", "UPDATES WAIT TIMEOUT - CHECK QUEUE");
- processUpdatesQueue(0);
+ for (int a = 0; a < 3; a++) {
+ if (getUpdatesStartTime(a) != 0 && getUpdatesStartTime(a) + 1500 < currentTime) {
+ FileLog.e("tmessages", a + " QUEUE UPDATES WAIT TIMEOUT - CHECK QUEUE");
+ processUpdatesQueue(a, 0);
+ }
}
}
if (!onlinePrivacy.isEmpty()) {
@@ -1175,7 +1292,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (label.length() != 0) {
label += ", ";
}
- label += ContactsController.formatName(user.first_name, user.last_name);
+ if (user.first_name != null && user.first_name.length() > 0) {
+ label += user.first_name;
+ } else if (user.last_name != null && user.last_name.length() > 0) {
+ label += user.last_name;
+ }
count++;
}
if (count == 2) {
@@ -1185,12 +1306,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (label.length() != 0) {
if (count > 1) {
if (arr.size() > 2) {
- newPrintingStrings.put(key, Html.fromHtml(String.format("%s %s", label, LocaleController.formatPluralString("AndMoreTyping", arr.size() - 2))));
+ newPrintingStrings.put(key, String.format("%s %s", label, LocaleController.formatPluralString("AndMoreTyping", arr.size() - 2)));
} else {
- newPrintingStrings.put(key, Html.fromHtml(String.format("%s %s", label, LocaleController.getString("AreTyping", R.string.AreTyping))));
+ newPrintingStrings.put(key, String.format("%s %s", label, LocaleController.getString("AreTyping", R.string.AreTyping)));
}
} else {
- newPrintingStrings.put(key, Html.fromHtml(String.format("%s %s", label, LocaleController.getString("IsTyping", R.string.IsTyping))));
+ newPrintingStrings.put(key, String.format("%s %s", label, LocaleController.getString("IsTyping", R.string.IsTyping)));
}
}
}
@@ -1324,8 +1445,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
- int lower_id = (int)dialog_id;
- int high_id = (int)(dialog_id >> 32);
+ int lower_id = (int) dialog_id;
+ int high_id = (int) (dialog_id >> 32);
if (!isCache) {
ImageLoader.saveMessagesThumbs(messagesRes.messages);
}
@@ -1350,12 +1471,21 @@ public class MessagesController implements NotificationCenter.NotificationCenter
for (TLRPC.Message message : messagesRes.messages) {
message.dialog_id = dialog_id;
objects.add(new MessageObject(message, usersLocal, true));
- if (isCache && message.media instanceof TLRPC.TL_messageMediaUnsupported) {
- if (message.media.bytes.length == 0 || message.media.bytes.length == 1 && message.media.bytes[0] < TLRPC.LAYER) {
- if (messagesToReload == null) {
- messagesToReload = new ArrayList<>();
+ if (isCache) {
+ if (message.media instanceof TLRPC.TL_messageMediaUnsupported) {
+ if (message.media.bytes.length == 0 || message.media.bytes.length == 1 && message.media.bytes[0] < TLRPC.LAYER) {
+ if (messagesToReload == null) {
+ messagesToReload = new ArrayList<>();
+ }
+ messagesToReload.add(message.id);
+ }
+ } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
+ if (message.media.webpage instanceof TLRPC.TL_webPagePending && message.media.webpage.date <= ConnectionsManager.getInstance().getCurrentTime()) {
+ if (messagesToReload == null) {
+ messagesToReload = new ArrayList<>();
+ }
+ messagesToReload.add(message.id);
}
- messagesToReload.add(message.id);
}
}
}
@@ -1437,8 +1567,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
currentDialog.unread_count = entry.getValue();
}
}
- NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
}
});
}
@@ -1497,7 +1627,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (oldMsg != null && oldMsg.deleted || value.top_message > currentDialog.top_message) {
dialogs_dict.put(key, value);
if (oldMsg != null) {
- dialogMessage.remove(oldMsg.messageOwner.id);
+ dialogMessage.remove(oldMsg.getId());
}
dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));
}
@@ -1505,7 +1635,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessageObject newMsg = new_dialogMessage.get(value.top_message);
if (oldMsg.deleted || newMsg == null || newMsg.messageOwner.date > oldMsg.messageOwner.date) {
dialogs_dict.put(key, value);
- dialogMessage.remove(oldMsg.messageOwner.id);
+ dialogMessage.remove(oldMsg.getId());
dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));
}
}
@@ -1528,16 +1658,16 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
});
for (TLRPC.TL_dialog d : dialogs) {
- int high_id = (int)(d.id >> 32);
- if ((int)d.id != 0 && high_id != 1) {
+ int high_id = (int) (d.id >> 32);
+ if ((int) d.id != 0 && high_id != 1) {
dialogsServerOnly.add(d);
}
}
- NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate);
}
});
- }
+ }
});
}
@@ -1554,8 +1684,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (resetEnd) {
dialogsEndReached = false;
}
- loadDialogs(offset, serverOffset, count, false);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ loadDialogs(offset, serverOffset, count, false);
}
});
return;
@@ -1571,7 +1701,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
if (dialogsRes instanceof TLRPC.TL_messages_dialogsSlice) {
- TLRPC.TL_messages_dialogsSlice slice = (TLRPC.TL_messages_dialogsSlice)dialogsRes;
+ TLRPC.TL_messages_dialogsSlice slice = (TLRPC.TL_messages_dialogsSlice) dialogsRes;
new_totalDialogsCount = slice.count;
} else {
new_totalDialogsCount = dialogsRes.dialogs.size();
@@ -1633,7 +1763,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (oldMsg == null || currentDialog.top_message > 0) {
if (oldMsg != null && oldMsg.deleted || value.top_message > currentDialog.top_message) {
if (oldMsg != null) {
- dialogMessage.remove(oldMsg.messageOwner.id);
+ dialogMessage.remove(oldMsg.getId());
}
dialogs_dict.put(key, value);
dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));
@@ -1641,7 +1771,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} else {
MessageObject newMsg = new_dialogMessage.get(value.top_message);
if (oldMsg.deleted || newMsg == null || newMsg.messageOwner.date > oldMsg.messageOwner.date) {
- dialogMessage.remove(oldMsg.messageOwner.id);
+ dialogMessage.remove(oldMsg.getId());
dialogs_dict.put(key, value);
dialogMessage.put(value.top_message, new_dialogMessage.get(value.top_message));
}
@@ -1665,8 +1795,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
});
for (TLRPC.TL_dialog d : dialogs) {
- int high_id = (int)(d.id >> 32);
- if ((int)d.id != 0 && high_id != 1) {
+ int high_id = (int) (d.id >> 32);
+ if ((int) d.id != 0 && high_id != 1) {
dialogsServerOnly.add(d);
}
}
@@ -1713,6 +1843,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
req.peer.chat_id = -lower_part;
} else {
TLRPC.User user = getUser(lower_part);
+ if (user == null) {
+ return;
+ }
if (user instanceof TLRPC.TL_userForeign || user instanceof TLRPC.TL_userRequest) {
req.peer = new TLRPC.TL_inputPeerForeign();
req.peer.user_id = user.id;
@@ -1724,7 +1857,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
req.max_id = max_positive_id;
req.offset = offset;
- req.read_contents = true;
if (offset == 0) {
MessagesStorage.getInstance().processPendingRead(dialog_id, max_positive_id, max_date, false);
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@@ -1764,7 +1896,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (res.offset > 0) {
markDialogAsRead(dialog_id, 0, max_positive_id, res.offset, max_date, was, popup);
}
- processNewDifferenceParams(res.seq, res.pts, -1);
+ processNewDifferenceParams(-1, res.pts, -1, res.pts_count);
}
}
});
@@ -1817,7 +1949,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
}
- public long createChat(String title, ArrayList selectedContacts, final TLRPC.InputFile uploadedAvatar, boolean isBroadcast) {
+ public long createChat(String title, ArrayList selectedContacts, boolean isBroadcast) {
if (isBroadcast) {
TLRPC.TL_chat chat = new TLRPC.TL_chat();
chat.id = UserConfig.lastBroadcastId;
@@ -1865,8 +1997,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true, false, 0);
updateInterfaceWithMessages(newMsg.dialog_id, objArr);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
return 0;
} else {
@@ -1891,30 +2023,21 @@ public class MessagesController implements NotificationCenter.NotificationCenter
});
return;
}
- final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;
- MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);
-
+ final TLRPC.Updates updates = (TLRPC.Updates) response;
+ processUpdates(updates, false);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
- putUsers(res.users, false);
- putChats(res.chats, false);
- final ArrayList messagesObj = new ArrayList<>();
- messagesObj.add(new MessageObject(res.message, users, true));
- TLRPC.Chat chat = res.chats.get(0);
- updateInterfaceWithMessages(-chat.id, messagesObj);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, chat.id);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
- if (uploadedAvatar != null) {
- changeChatAvatar(chat.id, uploadedAvatar);
+ putUsers(updates.users, false);
+ putChats(updates.chats, false);
+ TLRPC.Chat chat = null;
+ if (updates.chats != null && !updates.chats.isEmpty()) {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidCreated, updates.chats.get(0).id);
+ } else {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidFailCreate);
}
}
});
-
- final ArrayList messages = new ArrayList<>();
- messages.add(res.message);
- MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);
- processNewDifferenceParams(res.seq, res.pts, -1);
}
});
}
@@ -1937,43 +2060,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (error != null) {
return;
}
-
- final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;
- MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);
-
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- putUsers(res.users, false);
- putChats(res.chats, false);
- final ArrayList messagesObj = new ArrayList<>();
- messagesObj.add(new MessageObject(res.message, users, true));
- TLRPC.Chat chat = res.chats.get(0);
- updateInterfaceWithMessages(-chat.id, messagesObj);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
-
- if (info != null) {
- for (TLRPC.TL_chatParticipant p : info.participants) {
- if (p.user_id == user.id) {
- return;
- }
- }
- TLRPC.TL_chatParticipant newPart = new TLRPC.TL_chatParticipant();
- newPart.user_id = user.id;
- newPart.inviter_id = UserConfig.getClientUserId();
- newPart.date = ConnectionsManager.getInstance().getCurrentTime();
- info.participants.add(0, newPart);
- MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info);
- }
- }
- });
-
- final ArrayList messages = new ArrayList<>();
- messages.add(res.message);
- MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);
- processNewDifferenceParams(res.seq, res.pts, -1);
+ processUpdates((TLRPC.Updates) response, false);
}
});
} else {
@@ -2016,53 +2103,16 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (error != null) {
return;
}
- final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;
+ final TLRPC.Updates updates = (TLRPC.Updates) response;
+ processUpdates(updates, false);
if (user.id == UserConfig.getClientUserId()) {
- res.chats = null;
- }
- MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);
-
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- putUsers(res.users, false);
- putChats(res.chats, false);
- if (user.id != UserConfig.getClientUserId()) {
- final ArrayList messagesObj = new ArrayList<>();
- messagesObj.add(new MessageObject(res.message, users, true));
- TLRPC.Chat chat = res.chats.get(0);
- updateInterfaceWithMessages(-chat.id, messagesObj);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ MessagesController.getInstance().deleteDialog(-chat_id, 0, false);
}
- boolean changed = false;
- if (info != null) {
- for (int a = 0; a < info.participants.size(); a++) {
- TLRPC.TL_chatParticipant p = info.participants.get(a);
- if (p.user_id == user.id) {
- info.participants.remove(a);
- changed = true;
- break;
- }
- }
- if (changed) {
- MessagesStorage.getInstance().updateChatInfo(chat_id, info, true);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatInfoDidLoaded, info.chat_id, info);
- } else {
- MessagesStorage.getInstance().updateChatInfo(chat_id, user.id, true, 0, 0);
- }
- } else {
- MessagesStorage.getInstance().updateChatInfo(chat_id, user.id, true, 0, 0);
- }
- }
- });
-
- if (user.id != UserConfig.getClientUserId()) {
- final ArrayList messages = new ArrayList<>();
- messages.add(res.message);
- MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);
+ });
}
- processNewDifferenceParams(res.seq, res.pts, -1);
}
});
} else {
@@ -2104,27 +2154,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (error != null) {
return;
}
- final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;
- MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);
-
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- putUsers(res.users, false);
- putChats(res.chats, false);
- final ArrayList messagesObj = new ArrayList<>();
- messagesObj.add(new MessageObject(res.message, users, true));
- TLRPC.Chat chat = res.chats.get(0);
- updateInterfaceWithMessages(-chat.id, messagesObj);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_NAME);
- }
- });
-
- final ArrayList messages = new ArrayList<>();
- messages.add(res.message);
- MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);
- processNewDifferenceParams(res.seq, res.pts, -1);
+ processUpdates((TLRPC.Updates) response, false);
}
});
} else {
@@ -2154,29 +2184,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (error != null) {
return;
}
- final TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;
- MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);
-
- final ArrayList messages = new ArrayList<>();
- messages.add(res.message);
- ImageLoader.saveMessagesThumbs(messages);
-
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- putUsers(res.users, false);
- putChats(res.chats, false);
- final ArrayList messagesObj = new ArrayList<>();
- messagesObj.add(new MessageObject(res.message, users, true));
- TLRPC.Chat chat = res.chats.get(0);
- updateInterfaceWithMessages(-chat.id, messagesObj);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_CHAT_AVATAR);
- }
- });
-
- MessagesStorage.getInstance().putMessages(messages, true, true, false, 0);
- processNewDifferenceParams(res.seq, res.pts, -1);
+ processUpdates((TLRPC.Updates) response, false);
}
});
}
@@ -2288,7 +2296,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.lastPtsValue = res.pts;
MessagesStorage.lastSeqValue = res.seq;
MessagesStorage.lastQtsValue = res.qts;
- processUpdatesQueue(2);
+ for (int a = 0; a < 3; a++) {
+ processUpdatesQueue(a, 2);
+ }
MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);
} else {
if (error.code != 401) {
@@ -2307,8 +2317,61 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
}
- private void processUpdatesQueue(int state) {
- if (!updatesQueue.isEmpty()) {
+ private void setUpdatesStartTime(int type, long time) {
+ if (type == 0) {
+ updatesStartWaitTimeSeq = time;
+ } else if (type == 1) {
+ updatesStartWaitTimePts = time;
+ } else if (type == 2) {
+ updatesStartWaitTimeQts = time;
+ }
+ }
+
+ public long getUpdatesStartTime(int type) {
+ if (type == 0) {
+ return updatesStartWaitTimeSeq;
+ } else if (type == 1) {
+ return updatesStartWaitTimePts;
+ } else if (type == 2) {
+ return updatesStartWaitTimeQts;
+ }
+ return 0;
+ }
+
+ private int isValidUpdate(TLRPC.Updates updates, int type) {
+ if (type == 0) {
+ int seq = getUpdateSeq(updates);
+ if (MessagesStorage.lastSeqValue + 1 == seq || MessagesStorage.lastSeqValue == seq) {
+ return 0;
+ } else if (MessagesStorage.lastSeqValue < seq) {
+ return 1;
+ } else {
+ return 2;
+ }
+ } else if (type == 1) {
+ if (updates.pts <= MessagesStorage.lastPtsValue) {
+ return 2;
+ } else if (MessagesStorage.lastPtsValue + updates.pts_count == updates.pts) {
+ return 0;
+ } else {
+ return 1;
+ }
+ } else if (type == 2) {
+ if (updates.qts <= MessagesStorage.lastQtsValue) {
+ return 2;
+ } else if (MessagesStorage.lastQtsValue + 1 == updates.qts) {
+ return 0;
+ } else {
+ return 1;
+ }
+ }
+ return 0;
+ }
+
+ private boolean processUpdatesQueue(int type, int state) {
+ ArrayList updatesQueue = null;
+ if (type == 0) {
+ updatesQueue = updatesQueueSeq;
Collections.sort(updatesQueue, new Comparator() {
@Override
public int compare(TLRPC.Updates updates, TLRPC.Updates updates2) {
@@ -2322,32 +2385,66 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return -1;
}
});
+ } else if (type == 1) {
+ updatesQueue = updatesQueuePts;
+ Collections.sort(updatesQueue, new Comparator() {
+ @Override
+ public int compare(TLRPC.Updates updates, TLRPC.Updates updates2) {
+ if (updates.pts == updates2.pts) {
+ return 0;
+ } else if (updates.pts > updates2.pts) {
+ return 1;
+ }
+ return -1;
+ }
+ });
+ } else if (type == 2) {
+ updatesQueue = updatesQueueQts;
+ Collections.sort(updatesQueue, new Comparator() {
+ @Override
+ public int compare(TLRPC.Updates updates, TLRPC.Updates updates2) {
+ if (updates.qts == updates2.qts) {
+ return 0;
+ } else if (updates.qts > updates2.qts) {
+ return 1;
+ }
+ return -1;
+ }
+ });
+ }
+ if (!updatesQueue.isEmpty()) {
boolean anyProceed = false;
if (state == 2) {
TLRPC.Updates updates = updatesQueue.get(0);
- MessagesStorage.lastSeqValue = getUpdateSeq(updates);
+ if (type == 0) {
+ MessagesStorage.lastSeqValue = getUpdateSeq(updates);
+ } else if (type == 1) {
+ MessagesStorage.lastPtsValue = updates.pts;
+ } else if (type == 2) {
+ MessagesStorage.lastQtsValue = updates.qts;
+ }
}
for (int a = 0; a < updatesQueue.size(); a++) {
TLRPC.Updates updates = updatesQueue.get(a);
- int seq = getUpdateSeq(updates);
- if (MessagesStorage.lastSeqValue + 1 == seq || MessagesStorage.lastSeqValue == seq) {
+ int updateState = isValidUpdate(updates, type);
+ if (updateState == 0) {
processUpdates(updates, true);
anyProceed = true;
updatesQueue.remove(a);
a--;
- } else if (MessagesStorage.lastSeqValue < seq) {
- if (updatesStartWaitTime != 0 && (anyProceed || updatesStartWaitTime + 1500 > System.currentTimeMillis())) {
+ } else if (updateState == 1) {
+ if (getUpdatesStartTime(type) != 0 && (anyProceed || getUpdatesStartTime(type) + 1500 > System.currentTimeMillis())) {
FileLog.e("tmessages", "HOLE IN UPDATES QUEUE - will wait more time");
if (anyProceed) {
- updatesStartWaitTime = System.currentTimeMillis();
+ setUpdatesStartTime(type, System.currentTimeMillis());
}
- return;
+ return false;
} else {
FileLog.e("tmessages", "HOLE IN UPDATES QUEUE - getDifference");
- updatesStartWaitTime = 0;
+ setUpdatesStartTime(type, 0);
updatesQueue.clear();
getDifference();
- return;
+ return false;
}
} else {
updatesQueue.remove(a);
@@ -2356,34 +2453,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
updatesQueue.clear();
FileLog.e("tmessages", "UPDATES QUEUE PROCEED - OK");
- updatesStartWaitTime = 0;
- if (state == 1) {
- final int stateCopy = ConnectionsManager.getInstance().getConnectionState();
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy);
- }
- });
- }
- } else {
- if (state == 1) {
- final int stateCopy = ConnectionsManager.getInstance().getConnectionState();
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy);
- }
- });
- } else {
- updatesStartWaitTime = 0;
- }
}
+ setUpdatesStartTime(type, 0);
+ return true;
}
public void getDifference() {
registerForPush(UserConfig.pushString);
- if (MessagesStorage.lastDateValue == 0) {
+ if (MessagesStorage.lastPtsValue == 0) {
loadCurrentState();
return;
}
@@ -2399,6 +2476,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
req.pts = MessagesStorage.lastPtsValue;
req.date = MessagesStorage.lastDateValue;
req.qts = MessagesStorage.lastQtsValue;
+ if (req.date == 0) {
+ req.date = ConnectionsManager.getInstance().getCurrentTime();
+ }
FileLog.e("tmessages", "start getDifference with date = " + MessagesStorage.lastDateValue + " pts = " + MessagesStorage.lastPtsValue + " seq = " + MessagesStorage.lastSeqValue);
if (ConnectionsManager.getInstance().getConnectionState() == 0) {
ConnectionsManager.getInstance().setConnectionState(3);
@@ -2463,7 +2543,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
Integer oldId = entry.getKey();
SendMessagesHelper.getInstance().processSentMessage(oldId);
Integer newId = entry.getValue();
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newId, null);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newId, null, false);
}
}
});
@@ -2499,7 +2579,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
}
- if (!obj.isFromMe() && obj.isUnread()) {
+ if (!obj.isOut() && obj.isUnread()) {
pushMessages.add(obj);
}
@@ -2567,7 +2647,21 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.lastPtsValue = res.state.pts;
MessagesStorage.lastQtsValue = res.state.qts;
ConnectionsManager.getInstance().setConnectionState(0);
- processUpdatesQueue(1);
+ boolean done = true;
+ for (int a = 0; a < 3; a++) {
+ if (!processUpdatesQueue(a, 1)) {
+ done = false;
+ }
+ }
+ if (done) {
+ final int stateCopy = ConnectionsManager.getInstance().getConnectionState();
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy);
+ }
+ });
+ }
} else if (res instanceof TLRPC.TL_updates_differenceSlice) {
MessagesStorage.lastDateValue = res.intermediate_state.date;
MessagesStorage.lastPtsValue = res.intermediate_state.pts;
@@ -2578,7 +2672,21 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.lastSeqValue = res.seq;
MessagesStorage.lastDateValue = res.date;
ConnectionsManager.getInstance().setConnectionState(0);
- processUpdatesQueue(1);
+ boolean done = true;
+ for (int a = 0; a < 3; a++) {
+ if (!processUpdatesQueue(a, 1)) {
+ done = false;
+ }
+ }
+ if (done) {
+ final int stateCopy = ConnectionsManager.getInstance().getConnectionState();
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState, stateCopy);
+ }
+ });
+ }
}
MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);
FileLog.e("tmessages", "received difference with date = " + MessagesStorage.lastDateValue + " pts = " + MessagesStorage.lastPtsValue + " seq = " + MessagesStorage.lastSeqValue);
@@ -2605,131 +2713,120 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public void processUpdates(final TLRPC.Updates updates, boolean fromQueue) {
boolean needGetDiff = false;
boolean needReceivedQueue = false;
- boolean addedToQueue = false;
boolean updateStatus = false;
if (updates instanceof TLRPC.TL_updateShort) {
ArrayList arr = new ArrayList<>();
arr.add(updates.update);
processUpdateArray(arr, null, null);
- } else if (updates instanceof TLRPC.TL_updateShortChatMessage) {
- TLRPC.User user = getUser(updates.from_id);
- if (user != null && user.status != null && user.status.expires <= 0) {
- onlinePrivacy.put(user.id, ConnectionsManager.getInstance().getCurrentTime());
- updateStatus = true;
- }
- boolean missingData = getChat(updates.chat_id) == null || user == null;
- if (missingData) {
- needGetDiff = true;
- } else {
- if (MessagesStorage.lastSeqValue + 1 == updates.seq) {
- TLRPC.TL_message message = new TLRPC.TL_message();
- message.from_id = updates.from_id;
- message.id = updates.id;
- message.to_id = new TLRPC.TL_peerChat();
- message.to_id.chat_id = updates.chat_id;
- message.message = updates.message;
- message.date = updates.date;
- message.flags = TLRPC.MESSAGE_FLAG_UNREAD;
- message.media = new TLRPC.TL_messageMediaEmpty();
- MessagesStorage.lastSeqValue = updates.seq;
- MessagesStorage.lastPtsValue = updates.pts;
- final MessageObject obj = new MessageObject(message, null, true);
- final ArrayList objArr = new ArrayList<>();
- objArr.add(obj);
- ArrayList arr = new ArrayList<>();
- arr.add(message);
- final boolean printUpdate = updatePrintingUsersWithNewMessages(-updates.chat_id, objArr);
- if (printUpdate) {
- updatePrintingStrings();
- }
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- if (printUpdate) {
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT);
- }
+ } else if (updates instanceof TLRPC.TL_updateShortChatMessage || updates instanceof TLRPC.TL_updateShortMessage) {
+ TLRPC.User user = getUser(updates.user_id);
+ TLRPC.User user2 = null;
- updateInterfaceWithMessages(-updates.chat_id, objArr);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
- }
- });
- MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
- @Override
- public void run() {
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- if (!obj.isFromMe() && obj.isUnread()) {
- NotificationsController.getInstance().processNewMessages(objArr, true);
- }
- }
- });
- }
- });
- MessagesStorage.getInstance().putMessages(arr, false, true, false, 0);
- } else if (MessagesStorage.lastSeqValue != updates.seq) {
- FileLog.e("tmessages", "need get diff TL_updateShortChatMessage, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq);
- if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) {
- if (updatesStartWaitTime == 0) {
- updatesStartWaitTime = System.currentTimeMillis();
- }
- FileLog.e("tmessages", "add TL_updateShortChatMessage to queue");
- updatesQueue.add(updates);
- addedToQueue = true;
- } else {
- needGetDiff = true;
- }
- }
+ if (user == null) {
+ user = MessagesStorage.getInstance().getUserSync(updates.user_id);
+ putUser(user, true);
+ }
+
+ boolean needFwdUser = false;
+ if (updates.fwd_from_id != 0) {
+ user2 = getUser(updates.fwd_from_id);
+ if (user2 == null) {
+ user2 = MessagesStorage.getInstance().getUserSync(updates.fwd_from_id);
+ putUser(user2, true);
+ }
+ needFwdUser = true;
+ }
+
+ boolean missingData = false;
+ if (updates instanceof TLRPC.TL_updateShortMessage) {
+ missingData = user == null || needFwdUser && user2 == null;
+ } else {
+ TLRPC.Chat chat = getChat(updates.chat_id);
+ if (chat == null) {
+ chat = MessagesStorage.getInstance().getChatSync(updates.chat_id);
+ putChat(chat, true);
+ }
+ missingData = chat == null || user == null || needFwdUser && user2 == null;
}
- } else if (updates instanceof TLRPC.TL_updateShortMessage) {
- TLRPC.User user = getUser(updates.from_id);
if (user != null && user.status != null && user.status.expires <= 0) {
onlinePrivacy.put(user.id, ConnectionsManager.getInstance().getCurrentTime());
updateStatus = true;
}
- boolean missingData = user == null;
+
if (missingData) {
needGetDiff = true;
} else {
- if (MessagesStorage.lastSeqValue + 1 == updates.seq) {
+ if (MessagesStorage.lastPtsValue + updates.pts_count == updates.pts) {
TLRPC.TL_message message = new TLRPC.TL_message();
- message.from_id = updates.from_id;
message.id = updates.id;
- message.to_id = new TLRPC.TL_peerUser();
- message.to_id.user_id = updates.from_id;
+ if (updates instanceof TLRPC.TL_updateShortMessage) {
+ if ((updates.flags & TLRPC.MESSAGE_FLAG_OUT) != 0) {
+ message.from_id = UserConfig.getClientUserId();
+ } else {
+ message.from_id = updates.user_id;
+ }
+ message.to_id = new TLRPC.TL_peerUser();
+ message.to_id.user_id = updates.user_id;
+ message.dialog_id = updates.user_id;
+ } else {
+ message.from_id = updates.user_id;
+ message.to_id = new TLRPC.TL_peerChat();
+ message.to_id.chat_id = updates.chat_id;
+ message.dialog_id = -updates.chat_id;
+ }
message.message = updates.message;
message.date = updates.date;
- message.flags = TLRPC.MESSAGE_FLAG_UNREAD;
+ message.flags = updates.flags;
+ message.fwd_from_id = updates.fwd_from_id;
+ message.fwd_date = updates.fwd_date;
+ message.reply_to_msg_id = updates.reply_to_msg_id;
message.media = new TLRPC.TL_messageMediaEmpty();
- MessagesStorage.lastSeqValue = updates.seq;
MessagesStorage.lastPtsValue = updates.pts;
- MessagesStorage.lastDateValue = updates.date;
final MessageObject obj = new MessageObject(message, null, true);
final ArrayList objArr = new ArrayList<>();
objArr.add(obj);
ArrayList arr = new ArrayList<>();
arr.add(message);
- final boolean printUpdate = updatePrintingUsersWithNewMessages(updates.from_id, objArr);
- if (printUpdate) {
- updatePrintingStrings();
- }
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
- if (printUpdate) {
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT);
- }
- updateInterfaceWithMessages(updates.from_id, objArr);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ if (updates instanceof TLRPC.TL_updateShortMessage) {
+ final boolean printUpdate = (updates.flags & TLRPC.MESSAGE_FLAG_OUT) == 0 && updatePrintingUsersWithNewMessages(updates.user_id, objArr);
+ if (printUpdate) {
+ updatePrintingStrings();
}
- });
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ if (printUpdate) {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT);
+ }
+ updateInterfaceWithMessages(updates.user_id, objArr);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ }
+ });
+ } else {
+ final boolean printUpdate = updatePrintingUsersWithNewMessages(-updates.chat_id, objArr);
+ if (printUpdate) {
+ updatePrintingStrings();
+ }
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ if (printUpdate) {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT);
+ }
+
+ updateInterfaceWithMessages(-updates.chat_id, objArr);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ }
+ });
+ }
+
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
- if (!obj.isFromMe() && obj.isUnread()) {
+ if (!obj.isOut()) {
NotificationsController.getInstance().processNewMessages(objArr, true);
}
}
@@ -2737,78 +2834,103 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
});
MessagesStorage.getInstance().putMessages(arr, false, true, false, 0);
- } else if (MessagesStorage.lastSeqValue != updates.seq) {
- FileLog.e("tmessages", "need get diff TL_updateShortMessage, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq);
- if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) {
- if (updatesStartWaitTime == 0) {
- updatesStartWaitTime = System.currentTimeMillis();
+ } else if (MessagesStorage.lastPtsValue != updates.pts) {
+ FileLog.e("tmessages", "need get diff short message, pts: " + MessagesStorage.lastPtsValue + " " + updates.pts + " count = " + updates.pts_count);
+ if (gettingDifference || updatesStartWaitTimePts == 0 || updatesStartWaitTimePts != 0 && updatesStartWaitTimePts + 1500 > System.currentTimeMillis()) {
+ if (updatesStartWaitTimePts == 0) {
+ updatesStartWaitTimePts = System.currentTimeMillis();
}
- FileLog.e("tmessages", "add TL_updateShortMessage to queue");
- updatesQueue.add(updates);
- addedToQueue = true;
+ FileLog.e("tmessages", "add short message to queue");
+ updatesQueuePts.add(updates);
} else {
needGetDiff = true;
}
}
}
- } else if (updates instanceof TLRPC.TL_updatesCombined) {
- if (MessagesStorage.lastSeqValue + 1 == updates.seq_start || MessagesStorage.lastSeqValue == updates.seq_start) {
- MessagesStorage.getInstance().putUsersAndChats(updates.users, updates.chats, true, true);
- int lastPtsValue = MessagesStorage.lastPtsValue;
- int lastQtsValue = MessagesStorage.lastQtsValue;
- if (!processUpdateArray(updates.updates, updates.users, updates.chats)) {
- MessagesStorage.lastPtsValue = lastPtsValue;
- MessagesStorage.lastQtsValue = lastQtsValue;
- FileLog.e("tmessages", "need get diff inner TL_updatesCombined, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq);
- needGetDiff = true;
- } else {
- MessagesStorage.lastDateValue = updates.date;
- MessagesStorage.lastSeqValue = updates.seq;
- if (MessagesStorage.lastQtsValue != lastQtsValue) {
+ } else if (updates instanceof TLRPC.TL_updatesCombined || updates instanceof TLRPC.TL_updates) {
+ MessagesStorage.getInstance().putUsersAndChats(updates.users, updates.chats, true, true);
+ int lastQtsValue = MessagesStorage.lastQtsValue;
+ for (int a = 0; a < updates.updates.size(); a++) {
+ TLRPC.Update update = updates.updates.get(a);
+ if (update instanceof TLRPC.TL_updateNewMessage || update instanceof TLRPC.TL_updateReadMessages || update instanceof TLRPC.TL_updateReadHistoryInbox ||
+ update instanceof TLRPC.TL_updateReadHistoryOutbox || update instanceof TLRPC.TL_updateDeleteMessages) {
+ TLRPC.TL_updates updatesNew = new TLRPC.TL_updates();
+ updatesNew.updates.add(update);
+ updatesNew.pts = update.pts;
+ updatesNew.pts_count = update.pts_count;
+ if (MessagesStorage.lastPtsValue + update.pts_count == update.pts) {
+ if (!processUpdateArray(updatesNew.updates, updates.users, updates.chats)) {
+ FileLog.e("tmessages", "need get diff inner TL_updates, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq);
+ needGetDiff = true;
+ } else {
+ MessagesStorage.lastPtsValue = update.pts;
+ }
+ } else if (MessagesStorage.lastPtsValue != update.pts) {
+ FileLog.e("tmessages", update + " need get diff, pts: " + MessagesStorage.lastPtsValue + " " + update.pts + " count = " + update.pts_count);
+ if (gettingDifference || updatesStartWaitTimePts == 0 || updatesStartWaitTimePts != 0 && updatesStartWaitTimePts + 1500 > System.currentTimeMillis()) {
+ if (updatesStartWaitTimePts == 0) {
+ updatesStartWaitTimePts = System.currentTimeMillis();
+ }
+ FileLog.e("tmessages", "add short message to queue");
+ updatesQueuePts.add(updatesNew);
+ } else {
+ needGetDiff = true;
+ }
+ }
+ } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {
+ TLRPC.TL_updates updatesNew = new TLRPC.TL_updates();
+ updatesNew.updates.add(update);
+ updatesNew.qts = update.qts;
+ if (MessagesStorage.lastQtsValue == 0 || MessagesStorage.lastQtsValue + 1 == update.qts) {
+ processUpdateArray(updatesNew.updates, updates.users, updates.chats);
+ MessagesStorage.lastQtsValue = update.qts;
needReceivedQueue = true;
+ } else if (MessagesStorage.lastPtsValue != update.qts) {
+ FileLog.e("tmessages", update + " need get diff, qts: " + MessagesStorage.lastQtsValue + " " + update.qts);
+ if (gettingDifference || updatesStartWaitTimeQts == 0 || updatesStartWaitTimeQts != 0 && updatesStartWaitTimeQts + 1500 > System.currentTimeMillis()) {
+ if (updatesStartWaitTimeQts == 0) {
+ updatesStartWaitTimeQts = System.currentTimeMillis();
+ }
+ FileLog.e("tmessages", "add short message to queue");
+ updatesQueueQts.add(updatesNew);
+ } else {
+ needGetDiff = true;
+ }
}
- }
- } else {
- FileLog.e("tmessages", "need get diff TL_updatesCombined, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq_start);
- if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) {
- if (updatesStartWaitTime == 0) {
- updatesStartWaitTime = System.currentTimeMillis();
- }
- FileLog.e("tmessages", "add TL_updatesCombined to queue");
- updatesQueue.add(updates);
- addedToQueue = true;
} else {
- needGetDiff = true;
+ continue;
}
+ updates.updates.remove(a);
+ a--;
}
- } else if (updates instanceof TLRPC.TL_updates) {
- if (MessagesStorage.lastSeqValue + 1 == updates.seq || updates.seq == 0 || updates.seq == MessagesStorage.lastSeqValue) {
- MessagesStorage.getInstance().putUsersAndChats(updates.users, updates.chats, true, true);
- int lastPtsValue = MessagesStorage.lastPtsValue;
- int lastQtsValue = MessagesStorage.lastQtsValue;
- if (!processUpdateArray(updates.updates, updates.users, updates.chats)) {
- needGetDiff = true;
- MessagesStorage.lastPtsValue = lastPtsValue;
- MessagesStorage.lastQtsValue = lastQtsValue;
- FileLog.e("tmessages", "need get diff inner TL_updates, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq);
- } else {
+
+ boolean processUpdate = false;
+ if (updates instanceof TLRPC.TL_updatesCombined) {
+ processUpdate = MessagesStorage.lastSeqValue + 1 == updates.seq_start || MessagesStorage.lastSeqValue == updates.seq_start;
+ } else {
+ processUpdate = MessagesStorage.lastSeqValue + 1 == updates.seq || updates.seq == 0 || updates.seq == MessagesStorage.lastSeqValue;
+ }
+ if (processUpdate) {
+ processUpdateArray(updates.updates, updates.users, updates.chats);
+ if (updates.date != 0) {
MessagesStorage.lastDateValue = updates.date;
- if (updates.seq != 0) {
- MessagesStorage.lastSeqValue = updates.seq;
- }
- if (MessagesStorage.lastQtsValue != lastQtsValue) {
- needReceivedQueue = true;
- }
+ }
+ if (updates.seq != 0) {
+ MessagesStorage.lastSeqValue = updates.seq;
}
} else {
- FileLog.e("tmessages", "need get diff TL_updates, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq);
- if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) {
- if (updatesStartWaitTime == 0) {
- updatesStartWaitTime = System.currentTimeMillis();
+ if (updates instanceof TLRPC.TL_updatesCombined) {
+ FileLog.e("tmessages", "need get diff TL_updatesCombined, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq_start);
+ } else {
+ FileLog.e("tmessages", "need get diff TL_updates, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq);
+ }
+
+ if (gettingDifference || updatesStartWaitTimeSeq == 0 || updatesStartWaitTimeSeq != 0 && updatesStartWaitTimeSeq + 1500 > System.currentTimeMillis()) {
+ if (updatesStartWaitTimeSeq == 0) {
+ updatesStartWaitTimeSeq = System.currentTimeMillis();
}
- FileLog.e("tmessages", "add TL_updates to queue");
- updatesQueue.add(updates);
- addedToQueue = true;
+ FileLog.e("tmessages", "add TL_updates/Combined to queue");
+ updatesQueueSeq.add(updates);
} else {
needGetDiff = true;
}
@@ -2816,14 +2938,30 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} else if (updates instanceof TLRPC.TL_updatesTooLong) {
FileLog.e("tmessages", "need get diff TL_updatesTooLong");
needGetDiff = true;
- } else if (updates instanceof UserActionUpdates) {
+ } else if (updates instanceof UserActionUpdatesSeq) {
MessagesStorage.lastSeqValue = updates.seq;
+ } else if (updates instanceof UserActionUpdatesPts) {
+ MessagesStorage.lastPtsValue = updates.pts;
}
SecretChatHelper.getInstance().processPendingEncMessages();
- if (needGetDiff && !fromQueue) {
- getDifference();
- } else if (!fromQueue && !updatesQueue.isEmpty()) {
- processUpdatesQueue(0);
+ if (!fromQueue) {
+ if (needGetDiff) {
+ getDifference();
+ } else {
+ for (int a = 0; a < 3; a++) {
+ ArrayList updatesQueue = null;
+ if (a == 0) {
+ updatesQueue = updatesQueueSeq;
+ } else if (a == 1) {
+ updatesQueue = updatesQueuePts;
+ } else if (a == 2) {
+ updatesQueue = updatesQueueQts;
+ }
+ if (!updatesQueue.isEmpty()) {
+ processUpdatesQueue(a, 0);
+ }
+ }
+ }
}
if (needReceivedQueue) {
TLRPC.TL_messages_receivedQueue req = new TLRPC.TL_messages_receivedQueue();
@@ -2846,29 +2984,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);
}
- private boolean isNotifySettingsMuted(TLRPC.PeerNotifySettings settings) {
- return settings instanceof TLRPC.TL_peerNotifySettings && settings.mute_until > ConnectionsManager.getInstance().getCurrentTime();
- }
-
- public boolean isDialogMuted(long dialog_id) {
- TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
- if (dialog != null) {
- return isNotifySettingsMuted(dialog.notify_settings);
- } else {
- SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
- int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
- if (mute_type == 2) {
- return true;
- } else if (mute_type == 3) {
- int mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0);
- if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
- return true;
- }
- }
- }
- return false;
- }
-
public boolean processUpdateArray(ArrayList updates, final ArrayList usersArr, final ArrayList chatsArr) {
if (updates.isEmpty()) {
return true;
@@ -2876,9 +2991,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter
long currentTime = System.currentTimeMillis();
final HashMap> messages = new HashMap<>();
+ final HashMap webPages = new HashMap<>();
final ArrayList pushMessages = new ArrayList<>();
final ArrayList messagesArr = new ArrayList<>();
- final ArrayList markAsReadMessages = new ArrayList<>();
+ final HashMap markAsReadMessagesInbox = new HashMap<>();
+ final HashMap markAsReadMessagesOutbox = new HashMap<>();
final HashMap markAsReadEncrypted = new HashMap<>();
final ArrayList deletedMessages = new ArrayList<>();
boolean printChanged = false;
@@ -2958,18 +3075,27 @@ public class MessagesController implements NotificationCenter.NotificationCenter
messages.put(uid, arr);
}
arr.add(obj);
- MessagesStorage.lastPtsValue = update.pts;
- if (!obj.isFromMe() && obj.isUnread()) {
+ if (!obj.isOut() && obj.isUnread()) {
pushMessages.add(obj);
}
} else if (update instanceof TLRPC.TL_updateReadMessages) {
- markAsReadMessages.addAll(update.messages);
- MessagesStorage.lastPtsValue = update.pts;
+ //markAsReadMessages.addAll(update.messages); disabled for now
+ } else if (update instanceof TLRPC.TL_updateReadHistoryInbox) {
+ TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryInbox) update).peer;
+ if (peer.chat_id != 0) {
+ markAsReadMessagesInbox.put(-peer.chat_id, update.max_id);
+ } else {
+ markAsReadMessagesInbox.put(peer.user_id, update.max_id);
+ }
+ } else if (update instanceof TLRPC.TL_updateReadHistoryOutbox) {
+ TLRPC.Peer peer = ((TLRPC.TL_updateReadHistoryOutbox) update).peer;
+ if (peer.chat_id != 0) {
+ markAsReadMessagesOutbox.put(-peer.chat_id, update.max_id);
+ } else {
+ markAsReadMessagesOutbox.put(peer.user_id, update.max_id);
+ }
} else if (update instanceof TLRPC.TL_updateDeleteMessages) {
deletedMessages.addAll(update.messages);
- MessagesStorage.lastPtsValue = update.pts;
- } else if (update instanceof TLRPC.TL_updateRestoreMessages) {
- MessagesStorage.lastPtsValue = update.pts;
} else if (update instanceof TLRPC.TL_updateUserTyping || update instanceof TLRPC.TL_updateChatUserTyping) {
if (update.action instanceof TLRPC.TL_sendMessageTypingAction && update.user_id != UserConfig.getClientUserId()) {
long uid = -update.chat_id;
@@ -3038,7 +3164,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
pushMessages.add(obj);
}
} else if (update instanceof TLRPC.TL_updateContactLink) {
- if (update.my_link instanceof TLRPC.TL_contacts_myLinkContact || update.my_link instanceof TLRPC.TL_contacts_myLinkRequested && update.my_link.contact) {
+ if (update.my_link instanceof TLRPC.TL_contactLinkContact) {
int idx = contactsIds.indexOf(-update.user_id);
if (idx != -1) {
contactsIds.remove(idx);
@@ -3058,6 +3184,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} else if (update instanceof TLRPC.TL_updateActivation) {
//DEPRECATED
} else if (update instanceof TLRPC.TL_updateNewAuthorization) {
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.newSessionReceived);
+ }
+ });
TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
newMessage.action = new TLRPC.TL_messageActionLoginUnknownLocation();
newMessage.action.title = update.device;
@@ -3083,8 +3215,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} else if (update instanceof TLRPC.TL_updateNewGeoChatMessage) {
//DEPRECATED
} else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {
- MessagesStorage.lastQtsValue = update.qts;
- ArrayList decryptedMessages = SecretChatHelper.getInstance().decryptMessage(((TLRPC.TL_updateNewEncryptedMessage)update).message);
+ ArrayList decryptedMessages = SecretChatHelper.getInstance().decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) update).message);
if (decryptedMessages != null && !decryptedMessages.isEmpty()) {
int cid = ((TLRPC.TL_updateNewEncryptedMessage)update).message.chat_id;
long uid = ((long) cid) << 32;
@@ -3130,7 +3261,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
} else if (update instanceof TLRPC.TL_updateEncryptedMessagesRead) {
markAsReadEncrypted.put(update.chat_id, Math.max(update.max_date, update.date));
- tasks.add((TLRPC.TL_updateEncryptedMessagesRead)update);
+ tasks.add((TLRPC.TL_updateEncryptedMessagesRead) update);
} else if (update instanceof TLRPC.TL_updateChatParticipantAdd) {
MessagesStorage.getInstance().updateChatInfo(update.chat_id, update.user_id, false, update.inviter_id, update.version);
} else if (update instanceof TLRPC.TL_updateChatParticipantDelete) {
@@ -3192,6 +3323,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
pushMessages.add(obj);
} else if (update instanceof TLRPC.TL_updatePrivacy) {
updatesOnMainThread.add(update);
+ } else if (update instanceof TLRPC.TL_updateWebPage) {
+ webPages.put(update.webpage.id, update.webpage);
}
}
if (!messages.isEmpty()) {
@@ -3270,6 +3403,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
} else if (update instanceof TLRPC.TL_updateUserName) {
if (currentUser != null) {
+ if (currentUser.username != null && currentUser.username.length() > 0) {
+ usersByUsernames.remove(currentUser.username);
+ }
+ if (update.username != null && update.username.length() > 0) {
+ usersByUsernames.put(update.username, currentUser);
+ }
currentUser.first_name = update.first_name;
currentUser.last_name = update.last_name;
currentUser.username = update.username;
@@ -3360,6 +3499,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.getInstance().updateUsers(dbUsers, false, true, true);
}
+ if (!webPages.isEmpty()) {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.didReceivedWebpagesInUpdates, webPages);
+ }
+
if (!messages.isEmpty()) {
for (HashMap.Entry> entry : messages.entrySet()) {
Long key = entry.getKey();
@@ -3394,15 +3537,27 @@ public class MessagesController implements NotificationCenter.NotificationCenter
@Override
public void run() {
int updateMask = 0;
- if (!markAsReadMessages.isEmpty()) {
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesRead, markAsReadMessages);
- NotificationsController.getInstance().processReadMessages(markAsReadMessages, 0, 0, 0, false);
-
- for (Integer id : markAsReadMessages) {
- MessageObject obj = dialogMessage.get(id);
- if (obj != null) {
- obj.setIsRead();
- updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
+ if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesRead, markAsReadMessagesInbox, markAsReadMessagesOutbox);
+ NotificationsController.getInstance().processReadMessages(markAsReadMessagesInbox, 0, 0, 0, false);
+ for (HashMap.Entry entry : markAsReadMessagesInbox.entrySet()) {
+ TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());
+ if (dialog != null && dialog.top_message <= entry.getValue()) {
+ MessageObject obj = dialogMessage.get(dialog.top_message);
+ if (obj != null) {
+ obj.setIsRead();
+ updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
+ }
+ }
+ }
+ for (HashMap.Entry entry : markAsReadMessagesOutbox.entrySet()) {
+ TLRPC.TL_dialog dialog = dialogs_dict.get((long) entry.getKey());
+ if (dialog != null && dialog.top_message <= entry.getValue()) {
+ MessageObject obj = dialogMessage.get(dialog.top_message);
+ if (obj != null) {
+ obj.setIsRead();
+ updateMask |= UPDATE_MASK_READ_DIALOG_MESSAGE;
+ }
}
}
}
@@ -3437,11 +3592,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
});
- if (!markAsReadMessages.isEmpty() || !markAsReadEncrypted.isEmpty()) {
- if (!markAsReadMessages.isEmpty()) {
- MessagesStorage.getInstance().updateDialogsWithReadedMessages(markAsReadMessages, true);
+ if (!webPages.isEmpty()) {
+ MessagesStorage.getInstance().putWebPages(webPages);
+ }
+ if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty() || !markAsReadEncrypted.isEmpty()) {
+ if (!markAsReadMessagesInbox.isEmpty() || !markAsReadMessagesOutbox.isEmpty()) {
+ MessagesStorage.getInstance().updateDialogsWithReadedMessages(markAsReadMessagesInbox, true);
}
- MessagesStorage.getInstance().markMessagesAsRead(markAsReadMessages, markAsReadEncrypted, true);
+ MessagesStorage.getInstance().markMessagesAsRead(markAsReadMessagesInbox, markAsReadMessagesOutbox, markAsReadEncrypted, true);
}
if (!deletedMessages.isEmpty()) {
MessagesStorage.getInstance().markMessagesAsDeleted(deletedMessages, true);
@@ -3458,6 +3616,24 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return true;
}
+ private boolean isNotifySettingsMuted(TLRPC.PeerNotifySettings settings) {
+ return settings instanceof TLRPC.TL_peerNotifySettings && settings.mute_until > ConnectionsManager.getInstance().getCurrentTime();
+ }
+
+ public boolean isDialogMuted(long dialog_id) {
+ SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
+ int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
+ if (mute_type == 2) {
+ return true;
+ } else if (mute_type == 3) {
+ int mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0);
+ if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
private boolean updatePrintingUsersWithNewMessages(long uid, ArrayList messages) {
if (uid > 0) {
ArrayList arr = printingUsers.get(uid);
@@ -3508,7 +3684,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
NotificationCenter.getInstance().postNotificationName(NotificationCenter.didReceivedNewMessages, uid, messages);
for (MessageObject message : messages) {
- if (lastMessage == null || (!isEncryptedChat && message.messageOwner.id > lastMessage.messageOwner.id || isEncryptedChat && message.messageOwner.id < lastMessage.messageOwner.id) || message.messageOwner.date > lastMessage.messageOwner.date) {
+ if (lastMessage == null || (!isEncryptedChat && message.getId() > lastMessage.getId() || isEncryptedChat && message.getId() < lastMessage.getId()) || message.messageOwner.date > lastMessage.messageOwner.date) {
lastMessage = message;
}
}
@@ -3520,17 +3696,17 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialog = new TLRPC.TL_dialog();
dialog.id = uid;
dialog.unread_count = 0;
- dialog.top_message = lastMessage.messageOwner.id;
+ dialog.top_message = lastMessage.getId();
dialog.last_message_date = lastMessage.messageOwner.date;
dialogs_dict.put(uid, dialog);
dialogs.add(dialog);
- dialogMessage.put(lastMessage.messageOwner.id, lastMessage);
+ dialogMessage.put(lastMessage.getId(), lastMessage);
changed = true;
}
} else {
boolean change = false;
- if (dialog.top_message > 0 && lastMessage.messageOwner.id > 0 && lastMessage.messageOwner.id > dialog.top_message ||
- dialog.top_message < 0 && lastMessage.messageOwner.id < 0 && lastMessage.messageOwner.id < dialog.top_message) {
+ if (dialog.top_message > 0 && lastMessage.getId() > 0 && lastMessage.getId() > dialog.top_message ||
+ dialog.top_message < 0 && lastMessage.getId() < 0 && lastMessage.getId() < dialog.top_message) {
change = true;
} else {
MessageObject currentDialogMessage = dialogMessage.get(dialog.top_message);
@@ -3546,12 +3722,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
if (change) {
dialogMessage.remove(dialog.top_message);
- dialog.top_message = lastMessage.messageOwner.id;
+ dialog.top_message = lastMessage.getId();
if (!isBroadcast) {
dialog.last_message_date = lastMessage.messageOwner.date;
changed = true;
}
- dialogMessage.put(lastMessage.messageOwner.id, lastMessage);
+ dialogMessage.put(lastMessage.getId(), lastMessage);
}
}
@@ -3577,4 +3753,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}
}
}
+
+
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java b/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java
index 87f0e1982..d2b7981df 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/MessagesStorage.java
@@ -103,7 +103,7 @@ public class MessagesStorage {
database.executeFast("PRAGMA temp_store = 1").stepThis().dispose();
if (createTable) {
database.executeFast("CREATE TABLE users(uid INTEGER PRIMARY KEY, name TEXT, status INTEGER, data BLOB)").stepThis().dispose();
- database.executeFast("CREATE TABLE messages(mid INTEGER PRIMARY KEY, uid INTEGER, read_state INTEGER, send_state INTEGER, date INTEGER, data BLOB, out INTEGER, ttl INTEGER, media INTEGER)").stepThis().dispose();
+ database.executeFast("CREATE TABLE messages(mid INTEGER PRIMARY KEY, uid INTEGER, read_state INTEGER, send_state INTEGER, date INTEGER, data BLOB, out INTEGER, ttl INTEGER, media INTEGER, replydata BLOB)").stepThis().dispose();
database.executeFast("CREATE TABLE chats(uid INTEGER PRIMARY KEY, name TEXT, data BLOB)").stepThis().dispose();
database.executeFast("CREATE TABLE enc_chats(uid INTEGER PRIMARY KEY, user INTEGER, name TEXT, data BLOB, g BLOB, authkey BLOB, ttl INTEGER, layer INTEGER, seq_in INTEGER, seq_out INTEGER, use_count INTEGER, exchange_id INTEGER, key_date INTEGER, fprint INTEGER, fauthkey BLOB, khash BLOB)").stepThis().dispose();
database.executeFast("CREATE TABLE dialogs(did INTEGER PRIMARY KEY, date INTEGER, unread_count INTEGER, last_mid INTEGER)").stepThis().dispose();
@@ -122,6 +122,8 @@ public class MessagesStorage {
database.executeFast("CREATE TABLE messages_seq(mid INTEGER PRIMARY KEY, seq_in INTEGER, seq_out INTEGER);").stepThis().dispose();
database.executeFast("CREATE TABLE web_recent_v3(id TEXT, type INTEGER, image_url TEXT, thumb_url TEXT, local_url TEXT, width INTEGER, height INTEGER, size INTEGER, date INTEGER, PRIMARY KEY (id, type));").stepThis().dispose();
database.executeFast("CREATE TABLE stickers(id INTEGER PRIMARY KEY, data BLOB, date INTEGER);").stepThis().dispose();
+ database.executeFast("CREATE TABLE hashtag_recent_v2(id TEXT PRIMARY KEY, date INTEGER);").stepThis().dispose();
+ database.executeFast("CREATE TABLE webpage_pending(id INTEGER, mid INTEGER, PRIMARY KEY (id, mid));").stepThis().dispose();
database.executeFast("CREATE TABLE user_contacts_v6(uid INTEGER PRIMARY KEY, fname TEXT, sname TEXT)").stepThis().dispose();
database.executeFast("CREATE TABLE user_phones_v6(uid INTEGER, phone TEXT, sphone TEXT, deleted INTEGER, PRIMARY KEY (uid, phone))").stepThis().dispose();
@@ -162,7 +164,7 @@ public class MessagesStorage {
database.executeFast("CREATE TABLE keyvalue(id TEXT PRIMARY KEY, value TEXT)").stepThis().dispose();
//version
- database.executeFast("PRAGMA user_version = 13").stepThis().dispose();
+ database.executeFast("PRAGMA user_version = 16").stepThis().dispose();
} else {
try {
SQLiteCursor cursor = database.queryFinalized("SELECT seq, pts, date, qts, lsv, sg, pbytes FROM params WHERE id = 1");
@@ -193,7 +195,7 @@ public class MessagesStorage {
}
}
int version = database.executeInt("PRAGMA user_version");
- if (version < 13) {
+ if (version < 16) {
updateDbToLastVersion(version);
}
}
@@ -368,6 +370,21 @@ public class MessagesStorage {
database.executeFast("PRAGMA user_version = 13").stepThis().dispose();
version = 13;
}
+ if (version == 13 && version < 14) {
+ database.executeFast("ALTER TABLE messages ADD COLUMN replydata BLOB default NULL").stepThis().dispose();
+ database.executeFast("PRAGMA user_version = 14").stepThis().dispose();
+ version = 14;
+ }
+ if (version == 14 && version < 15) {
+ database.executeFast("CREATE TABLE IF NOT EXISTS hashtag_recent_v2(id TEXT PRIMARY KEY, date INTEGER);").stepThis().dispose();
+ database.executeFast("PRAGMA user_version = 15").stepThis().dispose();
+ version = 15;
+ }
+ if (version == 15 && version < 16) {
+ database.executeFast("CREATE TABLE IF NOT EXISTS webpage_pending(id INTEGER, mid INTEGER, PRIMARY KEY (id, mid));").stepThis().dispose();
+ database.executeFast("PRAGMA user_version = 16").stepThis().dispose();
+ version = 16;
+ }
} catch (Exception e) {
FileLog.e("tmessages", e);
}
@@ -622,7 +639,7 @@ public class MessagesStorage {
@Override
public void run() {
try {
- SQLiteCursor cursor = database.queryFinalized("SELECT id, image_url, thumb_url, local_url, width, height, size, date FROM web_recent_v3 wallpapers WHERE type = " + type);
+ SQLiteCursor cursor = database.queryFinalized("SELECT id, image_url, thumb_url, local_url, width, height, size, date FROM web_recent_v3 WHERE type = " + type);
final ArrayList arrayList = new ArrayList<>();
while (cursor.next()) {
MediaController.SearchImage searchImage = new MediaController.SearchImage();
@@ -679,6 +696,19 @@ public class MessagesStorage {
});
}
+ public void clearWebRecent(final int type) {
+ storageQueue.postRunnable(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ database.executeFast("DELETE FROM web_recent_v3 WHERE type = " + type).stepThis().dispose();
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
+ });
+ }
+
public void putWebRecent(final ArrayList arrayList) {
storageQueue.postRunnable(new Runnable() {
@Override
@@ -753,7 +783,7 @@ public class MessagesStorage {
try {
ArrayList ids = new ArrayList<>();
ArrayList users = new ArrayList<>();
- SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT * FROM blocked_users WHERE 1"));
+ SQLiteCursor cursor = database.queryFinalized("SELECT * FROM blocked_users WHERE 1");
StringBuilder usersToLoad = new StringBuilder();
while (cursor.next()) {
int user_id = cursor.intValue(0);
@@ -838,6 +868,59 @@ public class MessagesStorage {
//database.executeFast("DELETE FROM secret_holes WHERE uid = " + high_id).stepThis().dispose();
}
}
+
+ if ((int) did == 0) {
+ SQLiteCursor cursor = database.queryFinalized("SELECT data FROM messages WHERE uid = " + did);
+ ArrayList filesToDelete = new ArrayList<>();
+ try {
+ while (cursor.next()) {
+ ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0));
+ if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) {
+ TLRPC.Message message = (TLRPC.Message) TLClassStore.Instance().TLdeserialize(data, data.readInt32());
+ if (message == null || message.media == null) {
+ continue;
+ }
+ if (message.media instanceof TLRPC.TL_messageMediaAudio) {
+ File file = FileLoader.getPathToAttach(message.media.audio);
+ if (file != null && file.toString().length() > 0) {
+ filesToDelete.add(file);
+ }
+ } else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
+ for (TLRPC.PhotoSize photoSize : message.media.photo.sizes) {
+ File file = FileLoader.getPathToAttach(photoSize);
+ if (file != null && file.toString().length() > 0) {
+ filesToDelete.add(file);
+ }
+ }
+ } else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
+ File file = FileLoader.getPathToAttach(message.media.video);
+ if (file != null && file.toString().length() > 0) {
+ filesToDelete.add(file);
+ }
+ file = FileLoader.getPathToAttach(message.media.video.thumb);
+ if (file != null && file.toString().length() > 0) {
+ filesToDelete.add(file);
+ }
+ } else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
+ File file = FileLoader.getPathToAttach(message.media.document);
+ if (file != null && file.toString().length() > 0) {
+ filesToDelete.add(file);
+ }
+ file = FileLoader.getPathToAttach(message.media.document.thumb);
+ if (file != null && file.toString().length() > 0) {
+ filesToDelete.add(file);
+ }
+ }
+ }
+ buffersStorage.reuseFreeBuffer(data);
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ cursor.dispose();
+ FileLoader.getInstance().deleteFiles(filesToDelete);
+ }
+
database.executeFast("UPDATE dialogs SET unread_count = 0 WHERE did = " + did).stepThis().dispose();
database.executeFast("DELETE FROM messages WHERE uid = " + did).stepThis().dispose();
database.executeFast("DELETE FROM media_counts_v2 WHERE uid = " + did).stepThis().dispose();
@@ -1032,20 +1115,16 @@ public class MessagesStorage {
});
}
- private void updateDialogsWithReadedMessagesInternal(final ArrayList messages) {
- if (Thread.currentThread().getId() != storageQueue.getId()) {
- throw new RuntimeException("wrong db thread");
- }
+ private void updateDialogsWithReadedMessagesInternal(final ArrayList messages, final HashMap inbox) {
try {
HashMap dialogsToUpdate = new HashMap<>();
+ StringBuilder dialogsToReload = new StringBuilder();
+
if (messages != null && !messages.isEmpty()) {
- StringBuilder dialogsToReload = new StringBuilder();
String ids = TextUtils.join(",", messages);
- int totalCount = 0;
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, read_state, out FROM messages WHERE mid IN(%s)", ids));
while (cursor.next()) {
int out = cursor.intValue(2);
- totalCount++;
if (out != 0) {
continue;
}
@@ -1066,8 +1145,26 @@ public class MessagesStorage {
}
}
cursor.dispose();
+ } else if (inbox != null && !inbox.isEmpty()) {
+ for (HashMap.Entry entry : inbox.entrySet()) {
+ SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT COUNT(mid) FROM messages WHERE uid = %d AND mid <= %d AND read_state = 0 AND out = 0", entry.getKey(), entry.getValue()));
+ if (cursor.next()) {
+ int count = cursor.intValue(0);
+ if (count == 0) {
+ continue;
+ }
+ dialogsToUpdate.put((long) entry.getKey(), count);
+ if (dialogsToReload.length() != 0) {
+ dialogsToReload.append(",");
+ }
+ dialogsToReload.append(entry.getKey());
+ }
+ cursor.dispose();
+ }
+ }
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT did, unread_count FROM dialogs WHERE did IN(%s)", dialogsToReload.toString()));
+ if (dialogsToReload.length() > 0) {
+ SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT did, unread_count FROM dialogs WHERE did IN(%s)", dialogsToReload.toString()));
while (cursor.next()) {
long did = cursor.longValue(0);
int count = cursor.intValue(1);
@@ -1100,19 +1197,19 @@ public class MessagesStorage {
}
}
- public void updateDialogsWithReadedMessages(final ArrayList messages, boolean useQueue) {
- if (messages.isEmpty()) {
+ public void updateDialogsWithReadedMessages(final HashMap inbox, boolean useQueue) {
+ if (inbox.isEmpty()) {
return;
}
if (useQueue) {
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
- updateDialogsWithReadedMessagesInternal(messages);
+ updateDialogsWithReadedMessagesInternal(null, inbox);
}
});
} else {
- updateDialogsWithReadedMessagesInternal(messages);
+ updateDialogsWithReadedMessagesInternal(null, inbox);
}
}
@@ -1657,6 +1754,8 @@ public class MessagesStorage {
try {
ArrayList loadedUsers = new ArrayList<>();
ArrayList fromUser = new ArrayList<>();
+ ArrayList replyMessages = new ArrayList<>();
+ HashMap> replyMessageOwners = new HashMap<>();
SQLiteCursor cursor = null;
int lower_id = (int)dialog_id;
@@ -1678,18 +1777,18 @@ public class MessagesStorage {
cursor.dispose();
if (containMessage) {
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT * FROM (SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid <= %d ORDER BY m.date DESC, m.mid DESC LIMIT %d) UNION " +
- "SELECT * FROM (SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid > %d ORDER BY m.date ASC, m.mid ASC LIMIT %d)", dialog_id, max_id, count_query / 2, dialog_id, max_id, count_query / 2 - 1));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT * FROM (SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid <= %d ORDER BY m.date DESC, m.mid DESC LIMIT %d) UNION " +
+ "SELECT * FROM (SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid > %d ORDER BY m.date ASC, m.mid ASC LIMIT %d)", dialog_id, max_id, count_query / 2, dialog_id, max_id, count_query / 2 - 1));
} else {
cursor = null;
}
} else if (load_type == 1) {
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.date >= %d AND m.mid > %d ORDER BY m.date ASC, m.mid ASC LIMIT %d", dialog_id, minDate, max_id, count_query));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.date >= %d AND m.mid > %d ORDER BY m.date ASC, m.mid ASC LIMIT %d", dialog_id, minDate, max_id, count_query));
} else if (minDate != 0) {
if (max_id != 0) {
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.date <= %d AND m.mid < %d ORDER BY m.date DESC, m.mid DESC LIMIT %d", dialog_id, minDate, max_id, count_query));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.date <= %d AND m.mid < %d ORDER BY m.date DESC, m.mid DESC LIMIT %d", dialog_id, minDate, max_id, count_query));
} else {
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.date <= %d ORDER BY m.date DESC, m.mid DESC LIMIT %d,%d", dialog_id, minDate, offset_query, count_query));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.date <= %d ORDER BY m.date DESC, m.mid DESC LIMIT %d,%d", dialog_id, minDate, offset_query, count_query));
}
} else {
if (load_type == 2) {
@@ -1725,16 +1824,16 @@ public class MessagesStorage {
offset_query = count_unread - count_query;
count_query += 10;
}
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d ORDER BY m.date DESC, m.mid DESC LIMIT %d,%d", dialog_id, offset_query, count_query));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d ORDER BY m.date DESC, m.mid DESC LIMIT %d,%d", dialog_id, offset_query, count_query));
}
} else {
if (load_type == 1) {
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid < %d ORDER BY m.mid DESC LIMIT %d", dialog_id, max_id, count_query));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid < %d ORDER BY m.mid DESC LIMIT %d", dialog_id, max_id, count_query));
} else if (minDate != 0) {
if (max_id != 0) {
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid > %d ORDER BY m.mid ASC LIMIT %d", dialog_id, max_id, count_query));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.mid > %d ORDER BY m.mid ASC LIMIT %d", dialog_id, max_id, count_query));
} else {
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.date <= %d ORDER BY m.mid ASC LIMIT %d,%d", dialog_id, minDate, offset_query, count_query));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d AND m.date <= %d ORDER BY m.mid ASC LIMIT %d,%d", dialog_id, minDate, offset_query, count_query));
}
} else {
if (load_type == 2) {
@@ -1770,7 +1869,7 @@ public class MessagesStorage {
offset_query = count_unread - count_query;
count_query += 10;
}
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d ORDER BY m.mid ASC LIMIT %d,%d", dialog_id, offset_query, count_query));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.read_state, m.data, m.send_state, m.mid, m.date, r.random_id, m.replydata FROM messages as m LEFT JOIN randoms as r ON r.mid = m.mid WHERE m.uid = %d ORDER BY m.mid ASC LIMIT %d,%d", dialog_id, offset_query, count_query));
}
}
if (cursor != null) {
@@ -1796,6 +1895,43 @@ public class MessagesStorage {
if (message.fwd_from_id != 0) {
fromUser.add(message.fwd_from_id);
}
+ if (message.reply_to_msg_id != 0) {
+ boolean ok = false;
+ if (!cursor.isNull(6)) {
+ ByteBufferDesc data2 = buffersStorage.getFreeBuffer(cursor.byteArrayLength(6));
+ if (data2 != null && cursor.byteBufferValue(6, data2.buffer) != 0) {
+ message.replyMessage = (TLRPC.Message) TLClassStore.Instance().TLdeserialize(data2, data2.readInt32());
+ if (message.replyMessage != null) {
+ fromUser.add(message.replyMessage.from_id);
+ if (message.replyMessage.action != null && message.replyMessage.action.user_id != 0) {
+ fromUser.add(message.replyMessage.action.user_id);
+ }
+ if (message.replyMessage.media != null && message.replyMessage.media.user_id != 0) {
+ fromUser.add(message.replyMessage.media.user_id);
+ }
+ if (message.replyMessage.media != null && message.replyMessage.media.audio != null && message.replyMessage.media.audio.user_id != 0) {
+ fromUser.add(message.replyMessage.media.audio.user_id);
+ }
+ if (message.replyMessage.fwd_from_id != 0) {
+ fromUser.add(message.replyMessage.fwd_from_id);
+ }
+ ok = true;
+ }
+ }
+ buffersStorage.reuseFreeBuffer(data2);
+ }
+ if (!ok) {
+ if (!replyMessages.contains(message.reply_to_msg_id)) {
+ replyMessages.add(message.reply_to_msg_id);
+ }
+ ArrayList messages = replyMessageOwners.get(message.reply_to_msg_id);
+ if (messages == null) {
+ messages = new ArrayList<>();
+ replyMessageOwners.put(message.reply_to_msg_id, messages);
+ }
+ messages.add(message);
+ }
+ }
message.send_state = cursor.intValue(2);
if (!MessageObject.isUnread(message) && lower_id != 0 || message.id > 0) {
message.send_state = 0;
@@ -1846,33 +1982,39 @@ public class MessagesStorage {
}
});
- /*ArrayList> holes = getHoles(dialog_id);
- if (holes != null && !res.messages.isEmpty()) {
- int start = res.messages.get(res.messages.size() - 1).id;
- int end = res.messages.get(0).id;
- for (Range range : holes) {
- if (range.contains(start) && range.contains(end)) {
- res.messages.clear();
- } else if (range.contains(start)) {
- while (!res.messages.isEmpty() && range.contains(res.messages.get(res.messages.size() - 1).id)) {
- res.messages.remove(res.messages.size() - 1);
+ if (!replyMessages.isEmpty()) {
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date FROM messages WHERE mid IN(%s)", TextUtils.join(",", replyMessages)));
+ while (cursor.next()) {
+ ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0));
+ if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) {
+ TLRPC.Message message = (TLRPC.Message) TLClassStore.Instance().TLdeserialize(data, data.readInt32());
+ message.id = cursor.intValue(1);
+ message.date = cursor.intValue(2);
+ message.dialog_id = dialog_id;
+ fromUser.add(message.from_id);
+ if (message.action != null && message.action.user_id != 0) {
+ fromUser.add(message.action.user_id);
}
- if (!res.messages.isEmpty()) {
- start = res.messages.get(res.messages.size() - 1).id;
+ if (message.media != null && message.media.user_id != 0) {
+ fromUser.add(message.media.user_id);
}
- } else if (range.contains(end)) {
- while (!res.messages.isEmpty() && range.contains(res.messages.get(0).id)) {
- res.messages.remove(0);
+ if (message.media != null && message.media.audio != null && message.media.audio.user_id != 0) {
+ fromUser.add(message.media.audio.user_id);
}
- if (!res.messages.isEmpty()) {
- end = res.messages.get(0).id;
+ if (message.fwd_from_id != 0) {
+ fromUser.add(message.fwd_from_id);
+ }
+ ArrayList arrayList = replyMessageOwners.get(message.id);
+ if (arrayList != null) {
+ for (TLRPC.Message m : arrayList) {
+ m.replyMessage = message;
+ }
}
- } else if (start >= )
- if (res.messages.isEmpty()) {
- break;
}
+ buffersStorage.reuseFreeBuffer(data);
}
- }*/
+ cursor.dispose();
+ }
StringBuilder usersToLoad = new StringBuilder();
for (int uid : fromUser) {
@@ -2524,6 +2666,79 @@ public class MessagesStorage {
return -1;
}
+ public void putWebPages(final HashMap webPages) {
+ if (webPages == null || webPages.isEmpty()) {
+ return;
+ }
+ storageQueue.postRunnable(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ String ids = TextUtils.join(",", webPages.keySet());
+ SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM webpage_pending WHERE id IN (%s)", ids));
+ ArrayList mids = new ArrayList<>();
+ while (cursor.next()) {
+ mids.add(cursor.intValue(0));
+ }
+ cursor.dispose();
+
+ if (mids.isEmpty()) {
+ return;
+ }
+ final ArrayList messages = new ArrayList<>();
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid, data FROM messages WHERE mid IN (%s)", TextUtils.join(",", mids)));
+ while (cursor.next()) {
+ int mid = cursor.intValue(0);
+ ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(1));
+ if (data != null && cursor.byteBufferValue(1, data.buffer) != 0) {
+ TLRPC.Message message = (TLRPC.Message)TLClassStore.Instance().TLdeserialize(data, data.readInt32());
+ if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
+ message.id = mid;
+ message.media.webpage = webPages.get(message.media.webpage.id);
+ messages.add(message);
+ }
+ }
+ buffersStorage.reuseFreeBuffer(data);
+ }
+ cursor.dispose();
+
+ database.executeFast(String.format(Locale.US, "DELETE FROM webpage_pending WHERE id IN (%s)", ids)).stepThis().dispose();
+
+ if (messages.isEmpty()) {
+ return;
+ }
+
+ database.beginTransaction();
+
+ SQLitePreparedStatement state = database.executeFast("UPDATE messages SET data = ? WHERE mid = ?");
+ for (TLRPC.Message message : messages) {
+ ByteBufferDesc data = buffersStorage.getFreeBuffer(message.getObjectSize());
+ message.serializeToStream(data);
+
+ state.requery();
+ state.bindByteBuffer(1, data.buffer);
+ state.bindInteger(2, message.id);
+ state.step();
+
+ buffersStorage.reuseFreeBuffer(data);
+ }
+ state.dispose();
+
+ database.commitTransaction();
+
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.didReceivedWebpages, messages);
+ }
+ });
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
+ });
+ }
+
private void putMessagesInternal(final ArrayList messages, final boolean withTransaction, final boolean isBroadcast, final int downloadMask) {
try {
if (withTransaction) {
@@ -2537,10 +2752,11 @@ public class MessagesStorage {
HashMap messagesMediaIdsMap = new HashMap<>();
StringBuilder messageIds = new StringBuilder();
StringBuilder messageMediaIds = new StringBuilder();
- SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");
+ SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)");
SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)");
SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO randoms VALUES(?, ?)");
SQLitePreparedStatement state4 = database.executeFast("REPLACE INTO download_queue VALUES(?, ?, ?, ?)");
+ SQLitePreparedStatement state5 = database.executeFast("REPLACE INTO webpage_pending VALUES(?, ?)");
for (TLRPC.Message message : messages) {
long dialog_id = message.dialog_id;
@@ -2674,15 +2890,23 @@ public class MessagesStorage {
state2.bindByteBuffer(5, data.buffer);
state2.step();
}
+
+ if (message.media instanceof TLRPC.TL_messageMediaWebPage && message.media.webpage instanceof TLRPC.TL_webPagePending) {
+ state5.requery();
+ state5.bindLong(1, message.media.webpage.id);
+ state5.bindInteger(2, message.id);
+ state5.step();
+ }
+
buffersStorage.reuseFreeBuffer(data);
- if (downloadMask != 0) {
+ if (message.date >= ConnectionsManager.getInstance().getCurrentTime() - 60 * 60 * 24 && downloadMask != 0) {
if (message.media instanceof TLRPC.TL_messageMediaAudio || message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaVideo || message.media instanceof TLRPC.TL_messageMediaDocument) {
int type = 0;
long id = 0;
TLObject object = null;
if (message.media instanceof TLRPC.TL_messageMediaAudio) {
- if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0) {
+ if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0 && message.media.audio.size < 1024 * 1024 * 5) {
id = message.media.audio.id;
type = MediaController.AUTODOWNLOAD_MASK_AUDIO;
object = message.media.audio;
@@ -2728,6 +2952,7 @@ public class MessagesStorage {
state2.dispose();
state3.dispose();
state4.dispose();
+ state5.dispose();
state = database.executeFast("REPLACE INTO dialogs(did, date, unread_count, last_mid) VALUES(?, ?, ?, ?)");
for (HashMap.Entry pair : messagesMap.entrySet()) {
@@ -3111,14 +3336,20 @@ public class MessagesStorage {
}
}
- private void markMessagesAsReadInternal(final ArrayList messages, HashMap encryptedMessages) {
+ private void markMessagesAsReadInternal(HashMap inbox, HashMap outbox, HashMap encryptedMessages) {
if (Thread.currentThread().getId() != storageQueue.getId()) {
throw new RuntimeException("wrong db thread");
}
try {
- if (messages != null && !messages.isEmpty()) {
- String ids = TextUtils.join(",", messages);
- database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = 1 WHERE mid IN(%s)", ids)).stepThis().dispose();
+ if (inbox != null) {
+ for (HashMap.Entry entry : inbox.entrySet()) {
+ database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = 1 WHERE uid = %d AND mid <= %d AND read_state = 0 AND out = 0", entry.getKey(), entry.getValue())).stepThis().dispose();
+ }
+ }
+ if (outbox != null) {
+ for (HashMap.Entry entry : outbox.entrySet()) {
+ database.executeFast(String.format(Locale.US, "UPDATE messages SET read_state = 1 WHERE uid = %d AND mid <= %d AND read_state = 0 AND out = 1", entry.getKey(), entry.getValue())).stepThis().dispose();
+ }
}
if (encryptedMessages != null && !encryptedMessages.isEmpty()) {
for (HashMap.Entry entry : encryptedMessages.entrySet()) {
@@ -3137,16 +3368,16 @@ public class MessagesStorage {
}
}
- public void markMessagesAsRead(final ArrayList messages, final HashMap encryptedMessages, boolean useQueue) {
+ public void markMessagesAsRead(final HashMap inbox, final HashMap outbox, final HashMap encryptedMessages, boolean useQueue) {
if (useQueue) {
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
- markMessagesAsReadInternal(messages, encryptedMessages);
+ markMessagesAsReadInternal(inbox, outbox, encryptedMessages);
}
});
} else {
- markMessagesAsReadInternal(messages, encryptedMessages);
+ markMessagesAsReadInternal(inbox, outbox, encryptedMessages);
}
}
@@ -3178,6 +3409,7 @@ public class MessagesStorage {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesDeleted, mids);
}
});
+ MessagesStorage.getInstance().updateDialogsWithReadedMessagesInternal(mids, null);
MessagesStorage.getInstance().markMessagesAsDeletedInternal(mids);
MessagesStorage.getInstance().updateDialogsWithDeletedMessagesInternal(mids);
}
@@ -3189,9 +3421,6 @@ public class MessagesStorage {
}
private void markMessagesAsDeletedInternal(final ArrayList messages) {
- if (Thread.currentThread().getId() != storageQueue.getId()) {
- throw new RuntimeException("wrong db thread");
- }
try {
String ids = TextUtils.join(",", messages);
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT uid, data FROM messages WHERE mid IN(%s)", ids));
@@ -3287,7 +3516,7 @@ public class MessagesStorage {
ArrayList usersToLoad = new ArrayList<>();
ArrayList chatsToLoad = new ArrayList<>();
ArrayList encryptedToLoad = new ArrayList<>();
- cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", ids));
+ cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, m.date FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid WHERE d.did IN(%s)", ids));
while (cursor.next()) {
TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
dialog.id = cursor.longValue(0);
@@ -3302,6 +3531,10 @@ public class MessagesStorage {
MessageObject.setIsUnread(message, cursor.intValue(5) != 1);
message.id = cursor.intValue(6);
message.send_state = cursor.intValue(7);
+ int date = cursor.intValue(8);
+ if (date != 0) {
+ dialog.last_message_date = date;
+ }
dialogs.messages.add(message);
if (!usersToLoad.contains(message.from_id)) {
@@ -3399,11 +3632,19 @@ public class MessagesStorage {
}
private void fixUnsupportedMedia(TLRPC.Message message) {
- if (message != null && message.media instanceof TLRPC.TL_messageMediaUnsupported && message.media.bytes != null) {
+ if (message == null) {
+ return;
+ }
+ boolean ok = false;
+ if (message.media instanceof TLRPC.TL_messageMediaUnsupported_old) {
if (message.media.bytes.length == 0) {
message.media.bytes = new byte[1];
message.media.bytes[0] = TLRPC.LAYER;
}
+ } else if (message.media instanceof TLRPC.TL_messageMediaUnsupported) {
+ message.media = new TLRPC.TL_messageMediaUnsupported_old();
+ message.media.bytes = new byte[1];
+ message.media.bytes[0] = TLRPC.LAYER;
}
}
@@ -3417,7 +3658,7 @@ public class MessagesStorage {
try {
database.beginTransaction();
if (!messages.messages.isEmpty()) {
- SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");
+ SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)");
SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)");
for (TLRPC.Message message : messages.messages) {
fixUnsupportedMedia(message);
@@ -3471,7 +3712,7 @@ public class MessagesStorage {
usersToLoad.add(UserConfig.getClientUserId());
ArrayList chatsToLoad = new ArrayList<>();
ArrayList encryptedToLoad = new ArrayList<>();
- SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid LEFT JOIN dialog_settings as s ON d.did = s.did ORDER BY d.date DESC LIMIT %d,%d", offset, count));
+ SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT d.did, d.last_mid, d.unread_count, d.date, m.data, m.read_state, m.mid, m.send_state, s.flags, m.date FROM dialogs as d LEFT JOIN messages as m ON d.last_mid = m.mid LEFT JOIN dialog_settings as s ON d.did = s.did ORDER BY d.date DESC LIMIT %d,%d", offset, count));
while (cursor.next()) {
TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
dialog.id = cursor.longValue(0);
@@ -3495,6 +3736,10 @@ public class MessagesStorage {
if (message != null) {
MessageObject.setIsUnread(message, cursor.intValue(5) != 1);
message.id = cursor.intValue(6);
+ int date = cursor.intValue(9);
+ if (date != 0) {
+ dialog.last_message_date = date;
+ }
message.send_state = cursor.intValue(7);
dialogs.messages.add(message);
@@ -3585,7 +3830,7 @@ public class MessagesStorage {
}
if (!dialogs.dialogs.isEmpty()) {
- SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");
+ SQLitePreparedStatement state = database.executeFast("REPLACE INTO messages VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)");
SQLitePreparedStatement state2 = database.executeFast("REPLACE INTO dialogs(did, date, unread_count, last_mid) VALUES(?, ?, ?, ?)");
SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO media_v2 VALUES(?, ?, ?, ?, ?)");
SQLitePreparedStatement state4 = database.executeFast("REPLACE INTO dialog_settings VALUES(?, ?)");
@@ -3654,6 +3899,42 @@ public class MessagesStorage {
});
}
+ public TLRPC.User getUserSync(final int user_id) {
+ final Semaphore semaphore = new Semaphore(0);
+ final TLRPC.User[] user = new TLRPC.User[1];
+ MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
+ @Override
+ public void run() {
+ user[0] = getUser(user_id);
+ semaphore.release();
+ }
+ });
+ try {
+ semaphore.acquire();
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ return user[0];
+ }
+
+ public TLRPC.Chat getChatSync(final int user_id) {
+ final Semaphore semaphore = new Semaphore(0);
+ final TLRPC.Chat[] chat = new TLRPC.Chat[1];
+ MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
+ @Override
+ public void run() {
+ chat[0] = getChat(user_id);
+ semaphore.release();
+ }
+ });
+ try {
+ semaphore.acquire();
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ return chat[0];
+ }
+
public TLRPC.User getUser(final int user_id) {
TLRPC.User user = null;
try {
diff --git a/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java b/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java
index eecbbb175..6eab0a11b 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/NativeLoader.java
@@ -23,7 +23,7 @@ import java.util.zip.ZipFile;
public class NativeLoader {
- private final static int LIB_VERSION = 5;
+ private final static int LIB_VERSION = 7;
private final static String LIB_NAME = "tmessages." + LIB_VERSION;
private final static String LIB_SO_NAME = "lib" + LIB_NAME + ".so";
private final static String LOCALE_LIB_SO_NAME = "lib" + LIB_NAME + "loc.so";
diff --git a/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java
index 6e045c321..962de6977 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationCenter.java
@@ -48,6 +48,14 @@ public class NotificationCenter {
public static final int updateMessageMedia = totalEvents++;
public static final int recentImagesDidLoaded = totalEvents++;
public static final int replaceMessagesObjects = totalEvents++;
+ public static final int didSetPasscode = totalEvents++;
+ public static final int didSetTwoStepPassword = totalEvents++;
+ public static final int screenStateChanged = totalEvents++;
+ public static final int appSwitchedToForeground = totalEvents++;
+ public static final int didLoadedReplyMessages = totalEvents++;
+ public static final int newSessionReceived = totalEvents++;
+ public static final int didReceivedWebpages = totalEvents++;
+ public static final int didReceivedWebpagesInUpdates = totalEvents++;
public static final int httpFileDidLoaded = totalEvents++;
public static final int httpFileDidFailedLoad = totalEvents++;
@@ -60,7 +68,6 @@ public class NotificationCenter {
public static final int didReceiveSmsCode = totalEvents++;
public static final int emojiDidLoaded = totalEvents++;
public static final int appDidLogout = totalEvents++;
- public static final int needPasswordEnter = totalEvents++;
public static final int FileDidUpload = totalEvents++;
public static final int FileDidFailUpload = totalEvents++;
@@ -106,7 +113,7 @@ public class NotificationCenter {
}
public interface NotificationCenterDelegate {
- public abstract void didReceivedNotification(int id, Object... args);
+ void didReceivedNotification(int id, Object... args);
}
public void postNotificationName(int id, Object... args) {
diff --git a/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java
index c0cc5d4f9..1f31a687b 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/NotificationsController.java
@@ -11,13 +11,16 @@ package org.telegram.android;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
+import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
+import android.content.res.AssetFileDescriptor;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
+import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
@@ -29,6 +32,7 @@ import android.support.v4.app.RemoteInput;
import org.json.JSONArray;
import org.json.JSONObject;
import org.telegram.messenger.ConnectionsManager;
+import org.telegram.messenger.DispatchQueue;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.R;
import org.telegram.messenger.RPCRequest;
@@ -48,11 +52,13 @@ public class NotificationsController {
public static final String EXTRA_VOICE_REPLY = "extra_voice_reply";
+ private DispatchQueue notificationsQueue = new DispatchQueue("notificationsQueue");
private ArrayList pushMessages = new ArrayList<>();
private HashMap pushMessagesDict = new HashMap<>();
private NotificationManagerCompat notificationManager = null;
private HashMap pushDialogs = new HashMap<>();
private HashMap wearNoticationsIds = new HashMap<>();
+ private HashMap pushDialogsOverrideMention = new HashMap<>();
private int wearNotificationId = 10000;
public ArrayList popupMessages = new ArrayList<>();
private long openned_dialog_id = 0;
@@ -60,6 +66,12 @@ public class NotificationsController {
private int personal_count = 0;
private boolean notifyCheck = false;
private int lastOnlineFromOtherDevice = 0;
+ private boolean inChatSoundEnabled = true;
+
+ private long lastSoundPlay;
+ private MediaPlayer mediaPlayerIn;
+ private MediaPlayer mediaPlayerOut;
+ protected AudioManager audioManager;
private static volatile NotificationsController Instance = null;
public static NotificationsController getInstance() {
@@ -77,6 +89,15 @@ public class NotificationsController {
public NotificationsController() {
notificationManager = NotificationManagerCompat.from(ApplicationLoader.applicationContext);
+ SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
+ inChatSoundEnabled = preferences.getBoolean("EnableInChatSound", true);
+
+ try {
+ audioManager = (AudioManager) ApplicationLoader.applicationContext.getSystemService(Context.AUDIO_SERVICE);
+ //mediaPlayer = new MediaPlayer();
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
}
public void cleanup() {
@@ -95,6 +116,10 @@ public class NotificationsController {
editor.commit();
}
+ public void setInChatSoundEnabled(boolean value) {
+ inChatSoundEnabled = value;
+ }
+
public void setOpennedDialogId(long dialog_id) {
openned_dialog_id = dialog_id;
}
@@ -130,7 +155,9 @@ public class NotificationsController {
}
String msg = null;
- if ((int)dialog_id != 0) {
+ if ((int)dialog_id == 0 || AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
+ msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage);
+ } else {
if (chat_id == 0 && user_id != 0) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
if (preferences.getBoolean("EnablePreviewAll", true)) {
@@ -144,7 +171,7 @@ public class NotificationsController {
msg = LocaleController.formatString("NotificationUnrecognizedDevice", R.string.NotificationUnrecognizedDevice, UserConfig.getCurrentUser().first_name, date, messageObject.messageOwner.action.title, messageObject.messageOwner.action.address);
}
} else {
- if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) {
+ if (messageObject.isMediaEmpty()) {
if (!shortMessage) {
if (messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) {
msg = LocaleController.formatString("NotificationMessageText", R.string.NotificationMessageText, ContactsController.formatName(user.first_name, user.last_name), messageObject.messageOwner.message);
@@ -209,7 +236,7 @@ public class NotificationsController {
msg = messageObject.messageText.toString();
}
} else {
- if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) {
+ if (messageObject.isMediaEmpty()) {
if (!shortMessage && messageObject.messageOwner.message != null && messageObject.messageOwner.message.length() != 0) {
msg = LocaleController.formatString("NotificationMessageGroupText", R.string.NotificationMessageGroupText, ContactsController.formatName(user.first_name, user.last_name), chat.title, messageObject.messageOwner.message);
} else {
@@ -237,8 +264,6 @@ public class NotificationsController {
msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, ContactsController.formatName(user.first_name, user.last_name), chat.title);
}
}
- } else {
- msg = LocaleController.getString("YouHaveNewMessage", R.string.YouHaveNewMessage);
}
return msg;
}
@@ -250,7 +275,7 @@ public class NotificationsController {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int minutes = preferences.getInt("repeat_messages", 60);
if (minutes > 0 && personal_count > 0) {
- alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + minutes * 60 * 1000, pintent);
+ alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + minutes * 60 * 1000, pintent);
} else {
alarm.cancel(pintent);
}
@@ -266,9 +291,9 @@ public class NotificationsController {
PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0, new Intent(ApplicationLoader.applicationContext, NotificationDelay.class), 0);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
if (onlineReason) {
- alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 3 * 1000, pintent);
+ alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3 * 1000, pintent);
} else {
- alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 500, pintent);
+ alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 500, pintent);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
@@ -310,7 +335,11 @@ public class NotificationsController {
MessageObject lastMessageObject = pushMessages.get(0);
long dialog_id = lastMessageObject.getDialogId();
- int mid = lastMessageObject.messageOwner.id;
+ long override_dialog_id = dialog_id;
+ if ((lastMessageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_MENTION) != 0) {
+ override_dialog_id = lastMessageObject.messageOwner.from_id;
+ }
+ int mid = lastMessageObject.getId();
int chat_id = lastMessageObject.messageOwner.to_id.chat_id;
int user_id = lastMessageObject.messageOwner.to_id.user_id;
if (user_id == 0) {
@@ -339,9 +368,9 @@ public class NotificationsController {
int vibrate_override = 0;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
- int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
+ int notify_override = preferences.getInt("notify2_" + override_dialog_id, 0);
if (notify_override == 3) {
- int mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0);
+ int mute_until = preferences.getInt("notifyuntil_" + override_dialog_id, 0);
if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
notify_override = 2;
}
@@ -358,6 +387,7 @@ public class NotificationsController {
inAppPriority = preferences.getBoolean("EnableInAppPriority", false);
vibrate_override = preferences.getInt("vibrate_" + dialog_id, 0);
priority_override = preferences.getInt("priority_" + dialog_id, 3);
+ boolean vibrateOnlyIfSilent = false;
choosenSoundPath = preferences.getString("sound_path_" + dialog_id, null);
if (chat_id != 0) {
@@ -387,6 +417,10 @@ public class NotificationsController {
priority = priority_override;
}
+ if (needVibrate == 4) {
+ vibrateOnlyIfSilent = true;
+ needVibrate = 0;
+ }
if (needVibrate == 2 && (vibrate_override == 1 || vibrate_override == 3 || vibrate_override == 5) || needVibrate != 2 && vibrate_override == 2 || vibrate_override != 0) {
needVibrate = vibrate_override;
}
@@ -403,6 +437,16 @@ public class NotificationsController {
priority = 1;
}
}
+ if (vibrateOnlyIfSilent && needVibrate != 2) {
+ try {
+ int mode = audioManager.getRingerMode();
+ if (mode != AudioManager.RINGER_MODE_SILENT && mode != AudioManager.RINGER_MODE_VIBRATE) {
+ needVibrate = 2;
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
}
Intent intent = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
@@ -416,14 +460,18 @@ public class NotificationsController {
intent.putExtra("userId", user_id);
}
}
- if (pushDialogs.size() == 1) {
- if (chat != null) {
- if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
- photoPath = chat.photo.photo_small;
- }
- } else {
- if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) {
- photoPath = user.photo.photo_small;
+ if (AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
+ photoPath = null;
+ } else {
+ if (pushDialogs.size() == 1) {
+ if (chat != null) {
+ if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
+ photoPath = chat.photo.photo_small;
+ }
+ } else {
+ if (user.photo != null && user.photo.photo_small != null && user.photo.photo_small.volume_id != 0 && user.photo.photo_small.local_id != 0) {
+ photoPath = user.photo.photo_small;
+ }
}
}
}
@@ -436,7 +484,7 @@ public class NotificationsController {
String name = null;
boolean replace = true;
- if ((int)dialog_id == 0 || pushDialogs.size() > 1) {
+ if ((int)dialog_id == 0 || pushDialogs.size() > 1 || AndroidUtilities.needShowPasscode(false) || UserConfig.isWaitingForPasscodeEnter) {
name = LocaleController.getString("AppName", R.string.AppName);
replace = false;
} else {
@@ -451,7 +499,7 @@ public class NotificationsController {
if (pushDialogs.size() == 1) {
detailText = LocaleController.formatPluralString("NewMessages", total_unread_count);
} else {
- detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder", R.string.NotificationMessagesPeopleDisplayOrder, LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromContacts", pushDialogs.size()));
+ detailText = LocaleController.formatString("NotificationMessagesPeopleDisplayOrder", R.string.NotificationMessagesPeopleDisplayOrder, LocaleController.formatPluralString("NewMessages", total_unread_count), LocaleController.formatPluralString("FromChats", pushDialogs.size()));
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ApplicationLoader.applicationContext)
@@ -608,7 +656,7 @@ public class NotificationsController {
for (long dialog_id : sortedDialogs) {
ArrayList messageObjects = messagesByDialogs.get(dialog_id);
- int max_id = messageObjects.get(0).messageOwner.id;
+ int max_id = messageObjects.get(0).getId();
TLRPC.Chat chat = null;
TLRPC.User user = null;
String name = null;
@@ -730,19 +778,21 @@ public class NotificationsController {
}
}
- public void processReadMessages(ArrayList readMessages, long dialog_id, int max_date, int max_id, boolean isPopup) {
+ public void processReadMessages(HashMap inbox, long dialog_id, int max_date, int max_id, boolean isPopup) {
int oldCount = popupMessages.size();
- int oldCount2 = pushMessages.size();
- if (readMessages != null) {
- for (Integer id : readMessages) {
- MessageObject messageObject = pushMessagesDict.get(id);
- if (messageObject != null) {
- if (isPersonalMessage(messageObject)) {
- personal_count--;
+ if (inbox != null) {
+ for (HashMap.Entry entry : inbox.entrySet()) {
+ for (int a = 0; a < pushMessages.size(); a++) {
+ MessageObject messageObject = pushMessages.get(a);
+ if (messageObject.getDialogId() == entry.getKey() && messageObject.getId() <= entry.getValue()) {
+ if (isPersonalMessage(messageObject)) {
+ personal_count--;
+ }
+ popupMessages.remove(messageObject);
+ pushMessagesDict.remove(messageObject.getId());
+ pushMessages.remove(a);
+ a--;
}
- pushMessages.remove(messageObject);
- popupMessages.remove(messageObject);
- pushMessagesDict.remove(id);
}
}
}
@@ -757,11 +807,11 @@ public class NotificationsController {
}
} else {
if (!isPopup) {
- if (messageObject.messageOwner.id <= max_id || max_id < 0) {
+ if (messageObject.getId() <= max_id || max_id < 0) {
remove = true;
}
} else {
- if (messageObject.messageOwner.id == max_id || max_id < 0) {
+ if (messageObject.getId() == max_id || max_id < 0) {
remove = true;
}
}
@@ -772,7 +822,7 @@ public class NotificationsController {
}
pushMessages.remove(a);
popupMessages.remove(messageObject);
- pushMessagesDict.remove(messageObject.messageOwner.id);
+ pushMessagesDict.remove(messageObject.getId());
a--;
}
}
@@ -783,6 +833,126 @@ public class NotificationsController {
}
}
+ private void playInChatSound() {
+ if (!inChatSoundEnabled) {
+ return;
+ }
+ try {
+ if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
+ return;
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+
+ try {
+ SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
+ int notify_override = preferences.getInt("notify2_" + openned_dialog_id, 0);
+ if (notify_override == 3) {
+ int mute_until = preferences.getInt("notifyuntil_" + openned_dialog_id, 0);
+ if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
+ notify_override = 2;
+ }
+ }
+ if (notify_override == 2) {
+ return;
+ }
+ notificationsQueue.postRunnable(new Runnable() {
+ @Override
+ public void run() {
+ if (lastSoundPlay > System.currentTimeMillis() - 500) {
+ return;
+ }
+ try {
+ if (mediaPlayerIn == null) {
+ AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext.getResources().openRawResourceFd(R.raw.sound_in);
+ if (assetFileDescriptor != null) {
+ mediaPlayerIn = new MediaPlayer();
+ mediaPlayerIn.setAudioStreamType(AudioManager.STREAM_SYSTEM);
+ mediaPlayerIn.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
+ mediaPlayerIn.setLooping(false);
+ assetFileDescriptor.close();
+ mediaPlayerIn.prepare();
+ }
+ }
+ mediaPlayerIn.start();
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
+ });
+ /*String choosenSoundPath = null;
+ String defaultPath = Settings.System.DEFAULT_NOTIFICATION_URI.getPath();
+
+ choosenSoundPath = preferences.getString("sound_path_" + openned_dialog_id, null);
+ boolean isChat = (int)(openned_dialog_id) < 0;
+ if (isChat) {
+ if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
+ choosenSoundPath = null;
+ } else if (choosenSoundPath == null) {
+ choosenSoundPath = preferences.getString("GroupSoundPath", defaultPath);
+ }
+ } else {
+ if (choosenSoundPath != null && choosenSoundPath.equals(defaultPath)) {
+ choosenSoundPath = null;
+ } else if (choosenSoundPath == null) {
+ choosenSoundPath = preferences.getString("GlobalSoundPath", defaultPath);
+ }
+ }
+
+ if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
+ if (lastMediaPlayerUri == null || !choosenSoundPath.equals(lastMediaPlayerUri)) {
+ lastMediaPlayerUri = choosenSoundPath;
+ mediaPlayer.reset();
+ mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
+ if (choosenSoundPath.equals(defaultPath)) {
+ mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI);
+ } else {
+ mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Uri.parse(choosenSoundPath));
+ }
+ mediaPlayer.prepare();
+ }
+ mediaPlayer.start();
+ }*/
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
+
+ public void playOutChatSound() {
+ if (!inChatSoundEnabled) {
+ return;
+ }
+ try {
+ if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
+ return;
+ }
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ notificationsQueue.postRunnable(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ if (mediaPlayerOut == null) {
+ AssetFileDescriptor assetFileDescriptor = ApplicationLoader.applicationContext.getResources().openRawResourceFd(R.raw.sound_out);
+ if (assetFileDescriptor != null) {
+ mediaPlayerOut = new MediaPlayer();
+ mediaPlayerOut.setAudioStreamType(AudioManager.STREAM_SYSTEM);
+ mediaPlayerOut.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
+ mediaPlayerOut.setLooping(false);
+ assetFileDescriptor.close();
+ mediaPlayerOut.prepare();
+ }
+ }
+ mediaPlayerOut.start();
+ } catch (Exception e) {
+ FileLog.e("tmessages", e);
+ }
+ }
+ });
+ }
+
public void processNewMessages(ArrayList messageObjects, boolean isLast) {
if (messageObjects.isEmpty()) {
return;
@@ -795,13 +965,18 @@ public class NotificationsController {
int popup = 0;
for (MessageObject messageObject : messageObjects) {
- if (pushMessagesDict.containsKey(messageObject.messageOwner.id)) {
+ if (pushMessagesDict.containsKey(messageObject.getId())) {
continue;
}
long dialog_id = messageObject.getDialogId();
+ long original_dialog_id = dialog_id;
if (dialog_id == openned_dialog_id && ApplicationLoader.isScreenOn) {
+ playInChatSound();
continue;
}
+ if ((messageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_MENTION) != 0) {
+ dialog_id = messageObject.messageOwner.from_id;
+ }
if (isPersonalMessage(messageObject)) {
personal_count++;
}
@@ -826,7 +1001,10 @@ public class NotificationsController {
popupMessages.add(0, messageObject);
}
pushMessages.add(0, messageObject);
- pushMessagesDict.put(messageObject.messageOwner.id, messageObject);
+ pushMessagesDict.put(messageObject.getId(), messageObject);
+ if (original_dialog_id != dialog_id) {
+ pushDialogsOverrideMention.put(original_dialog_id, 1);
+ }
}
}
@@ -834,7 +1012,7 @@ public class NotificationsController {
notifyCheck = isLast;
}
- if (!popupMessages.isEmpty() && oldCount != popupMessages.size()) {
+ if (!popupMessages.isEmpty() && oldCount != popupMessages.size() && !AndroidUtilities.needShowPasscode(false) && !UserConfig.isWaitingForPasscodeEnter) {
if (ApplicationLoader.mainInterfacePaused || !ApplicationLoader.isScreenOn) {
MessageObject messageObject = messageObjects.get(0);
if (popup == 3 || popup == 1 && ApplicationLoader.isScreenOn || popup == 2 && !ApplicationLoader.isScreenOn) {
@@ -859,6 +1037,13 @@ public class NotificationsController {
notify_override = 2;
}
}
+ if (notifyCheck) {
+ Integer override = pushDialogsOverrideMention.get(dialog_id);
+ if (override != null && override == 1) {
+ pushDialogsOverrideMention.put(dialog_id, 0);
+ notify_override = 1;
+ }
+ }
boolean canAddValue = !(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || ((int)dialog_id < 0) && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0);
Integer currentCount = pushDialogs.get(dialog_id);
@@ -876,6 +1061,7 @@ public class NotificationsController {
}
if (newCount == 0) {
pushDialogs.remove(dialog_id);
+ pushDialogsOverrideMention.remove(dialog_id);
for (int a = 0; a < pushMessages.size(); a++) {
MessageObject messageObject = pushMessages.get(a);
if (messageObject.getDialogId() == dialog_id) {
@@ -884,7 +1070,7 @@ public class NotificationsController {
}
pushMessages.remove(a);
a--;
- pushMessagesDict.remove(messageObject.messageOwner.id);
+ pushMessagesDict.remove(messageObject.getId());
popupMessages.remove(messageObject);
}
}
@@ -923,27 +1109,6 @@ public class NotificationsController {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
HashMap settingsCache = new HashMap<>();
- for (HashMap.Entry entry : dialogs.entrySet()) {
- long dialog_id = entry.getKey();
- Boolean value = settingsCache.get(dialog_id);
- if (value == null) {
- int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
- if (notify_override == 3) {
- int mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0);
- if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
- notify_override = 2;
- }
- }
- value = !(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || ((int) dialog_id < 0) && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0);
- settingsCache.put(dialog_id, value);
- }
- if (!value) {
- continue;
- }
- int count = entry.getValue();
- pushDialogs.put(dialog_id, count);
- total_unread_count += count;
- }
if (messages != null) {
for (TLRPC.Message message : messages) {
if (pushMessagesDict.containsKey(message.id)) {
@@ -954,6 +1119,10 @@ public class NotificationsController {
personal_count++;
}
long dialog_id = messageObject.getDialogId();
+ long original_dialog_id = dialog_id;
+ if ((messageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_MENTION) != 0) {
+ dialog_id = messageObject.messageOwner.from_id;
+ }
Boolean value = settingsCache.get(dialog_id);
if (value == null) {
int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
@@ -969,10 +1138,39 @@ public class NotificationsController {
if (!value || dialog_id == openned_dialog_id && ApplicationLoader.isScreenOn) {
continue;
}
- pushMessagesDict.put(messageObject.messageOwner.id, messageObject);
+ pushMessagesDict.put(messageObject.getId(), messageObject);
pushMessages.add(0, messageObject);
+ if (original_dialog_id != dialog_id) {
+ pushDialogsOverrideMention.put(original_dialog_id, 1);
+ }
}
}
+ for (HashMap.Entry entry : dialogs.entrySet()) {
+ long dialog_id = entry.getKey();
+ Boolean value = settingsCache.get(dialog_id);
+ if (value == null) {
+ int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
+ if (notify_override == 3) {
+ int mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0);
+ if (mute_until >= ConnectionsManager.getInstance().getCurrentTime()) {
+ notify_override = 2;
+ }
+ }
+ Integer override = pushDialogsOverrideMention.get(dialog_id);
+ if (override != null && override == 1) {
+ pushDialogsOverrideMention.put(dialog_id, 0);
+ notify_override = 1;
+ }
+ value = !(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || ((int) dialog_id < 0) && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0);
+ settingsCache.put(dialog_id, value);
+ }
+ if (!value) {
+ continue;
+ }
+ int count = entry.getValue();
+ pushDialogs.put(dialog_id, count);
+ total_unread_count += count;
+ }
if (total_unread_count == 0) {
popupMessages.clear();
NotificationCenter.getInstance().postNotificationName(NotificationCenter.pushMessagesUpdated);
@@ -988,20 +1186,33 @@ public class NotificationsController {
setBadge(ApplicationLoader.applicationContext, enabled ? total_unread_count : 0);
}
- private void setBadge(Context context, int count) {
- try {
- String launcherClassName = getLauncherClassName(context);
- if (launcherClassName == null) {
- return;
+ private void setBadge(final Context context, final int count) {
+ notificationsQueue.postRunnable(new Runnable() {
+ @Override
+ public void run() {
+ try {
+ ContentValues cv = new ContentValues();
+ cv.put("tag", "org.telegram.messenger/org.telegram.ui.LaunchActivity");
+ cv.put("count", count);
+ context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);
+ } catch (Throwable e) {
+ //ignore
+ }
+ try {
+ String launcherClassName = getLauncherClassName(context);
+ if (launcherClassName == null) {
+ return;
+ }
+ Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
+ intent.putExtra("badge_count", count);
+ intent.putExtra("badge_count_package_name", context.getPackageName());
+ intent.putExtra("badge_count_class_name", launcherClassName);
+ context.sendBroadcast(intent);
+ } catch (Throwable e) {
+ FileLog.e("tmessages", e);
+ }
}
- Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
- intent.putExtra("badge_count", count);
- intent.putExtra("badge_count_package_name", context.getPackageName());
- intent.putExtra("badge_count_class_name", launcherClassName);
- context.sendBroadcast(intent);
- } catch (Throwable e) {
- FileLog.e("tmessages", e);
- }
+ });
}
public static String getLauncherClassName(Context context) {
diff --git a/TMessagesProj/src/main/java/org/telegram/android/ScreenReceiver.java b/TMessagesProj/src/main/java/org/telegram/android/ScreenReceiver.java
index e6b6c7572..d7824f18b 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/ScreenReceiver.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/ScreenReceiver.java
@@ -28,5 +28,6 @@ public class ScreenReceiver extends BroadcastReceiver {
ConnectionsManager.getInstance().setAppPaused(false, true);
ApplicationLoader.isScreenOn = true;
}
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.screenStateChanged);
}
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java b/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java
index 6a1140245..6a34ea267 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/SecretChatHelper.java
@@ -119,7 +119,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -224,7 +224,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -252,7 +252,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -283,7 +283,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -312,7 +312,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -343,7 +343,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -375,7 +375,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -406,7 +406,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -436,7 +436,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -464,7 +464,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -500,7 +500,7 @@ public class SecretChatHelper {
reqSend = new TLRPC.TL_decryptedMessageService();
} else {
reqSend = new TLRPC.TL_decryptedMessageService_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
@@ -659,7 +659,7 @@ public class SecretChatHelper {
int myLayer = Math.max(17, AndroidUtilities.getMyLayerVersion(chat.layer));
layer.layer = Math.min(myLayer, AndroidUtilities.getPeerLayerVersion(chat.layer));
layer.message = req;
- layer.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ layer.random_bytes = new byte[15];
Utilities.random.nextBytes(layer.random_bytes);
toEncryptObject = layer;
@@ -795,7 +795,7 @@ public class SecretChatHelper {
@Override
public void run() {
newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, newMsgObj.id, newMsgObj.id, newMsgObj, false);
SendMessagesHelper.getInstance().processSentMessage(newMsgObj.id);
if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) {
SendMessagesHelper.getInstance().stopVideoService(attachPath);
@@ -1072,8 +1072,8 @@ public class SecretChatHelper {
}
});
MessagesStorage.getInstance().deleteDialog(did, true);
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.removeAllMessagesFromDialog, did);
}
});
return null;
@@ -1104,10 +1104,7 @@ public class SecretChatHelper {
}
byte[] salt = new byte[256];
- for (int a = 0; a < 256; a++) {
- salt[a] = (byte) (Utilities.random.nextDouble() * 256);
- }
-
+ Utilities.random.nextBytes(salt);
BigInteger p = new BigInteger(1, MessagesStorage.secretPBytes);
BigInteger g_b = BigInteger.valueOf(MessagesStorage.secretG);
g_b = g_b.modPow(new BigInteger(1, salt), p);
@@ -1409,9 +1406,7 @@ public class SecretChatHelper {
return;
}
final byte[] salt = new byte[256];
- for (int a = 0; a < 256; a++) {
- salt[a] = (byte) (Utilities.random.nextDouble() * 256);
- }
+ Utilities.random.nextBytes(salt);
BigInteger i_g_a = BigInteger.valueOf(MessagesStorage.secretG);
i_g_a = i_g_a.modPow(new BigInteger(1, salt), new BigInteger(1, MessagesStorage.secretPBytes));
@@ -1616,7 +1611,7 @@ public class SecretChatHelper {
}
public void startSecretChat(final Context context, final TLRPC.User user) {
- if (user == null) {
+ if (user == null || context == null) {
return;
}
startingSecretChat = true;
@@ -1777,6 +1772,10 @@ public class SecretChatHelper {
}
}
});
- progressDialog.show();
+ try {
+ progressDialog.show();
+ } catch (Exception e) {
+ //don't promt
+ }
}
}
diff --git a/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java b/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java
index b7dc050d7..35e6bedea 100644
--- a/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java
+++ b/TMessagesProj/src/main/java/org/telegram/android/SendMessagesHelper.java
@@ -174,12 +174,12 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
for (int a = 0; a < arr.size(); a++) {
DelayedMessage obj = arr.get(a);
if (enc && obj.sendEncryptedRequest != null || !enc && obj.sendRequest != null) {
- MessagesStorage.getInstance().markMessageAsSendError(obj.obj.messageOwner.id);
+ MessagesStorage.getInstance().markMessageAsSendError(obj.obj.getId());
obj.obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
arr.remove(a);
a--;
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, obj.obj.messageOwner.id);
- processSentMessage(obj.obj.messageOwner.id);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, obj.obj.getId());
+ processSentMessage(obj.obj.getId());
}
}
if (arr.isEmpty()) {
@@ -244,12 +244,12 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
for (int a = 0; a < arr.size(); a++) {
DelayedMessage message = arr.get(a);
if (message.obj == messageObject) {
- MessagesStorage.getInstance().markMessageAsSendError(message.obj.messageOwner.id);
+ MessagesStorage.getInstance().markMessageAsSendError(message.obj.getId());
message.obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
arr.remove(a);
a--;
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, message.obj.messageOwner.id);
- processSentMessage(message.obj.messageOwner.id);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, message.obj.getId());
+ processSentMessage(message.obj.getId());
}
}
if (arr.isEmpty()) {
@@ -284,10 +284,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateMessageMedia, message.obj);
} else {
FileLog.e("tmessages", "can't load image " + message.httpLocation + " to file " + cacheFile.toString());
- MessagesStorage.getInstance().markMessageAsSendError(message.obj.messageOwner.id);
+ MessagesStorage.getInstance().markMessageAsSendError(message.obj.getId());
message.obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, message.obj.messageOwner.id);
- processSentMessage(message.obj.messageOwner.id);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, message.obj.getId());
+ processSentMessage(message.obj.getId());
}
}
});
@@ -339,10 +339,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
ArrayList arr = delayedMessages.get(path);
if (arr != null) {
for (DelayedMessage message : arr) {
- MessagesStorage.getInstance().markMessageAsSendError(message.obj.messageOwner.id);
+ MessagesStorage.getInstance().markMessageAsSendError(message.obj.getId());
message.obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, message.obj.messageOwner.id);
- processSentMessage(message.obj.messageOwner.id);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, message.obj.getId());
+ processSentMessage(message.obj.getId());
}
delayedMessages.remove(path);
}
@@ -356,7 +356,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
ArrayList messages = entry.getValue();
for (int a = 0; a < messages.size(); a++) {
DelayedMessage message = messages.get(a);
- if (message.obj.messageOwner.id == object.messageOwner.id) {
+ if (message.obj.getId() == object.getId()) {
messages.remove(a);
MediaController.getInstance().cancelVideoConvert(message.obj);
if (messages.size() == 0) {
@@ -378,22 +378,22 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
stopVideoService(keyToRemvoe);
}
ArrayList messages = new ArrayList<>();
- messages.add(object.messageOwner.id);
+ messages.add(object.getId());
MessagesController.getInstance().deleteMessages(messages, null, null);
}
public boolean retrySendMessage(MessageObject messageObject, boolean unsent) {
- if (messageObject.messageOwner.id >= 0) {
+ if (messageObject.getId() >= 0) {
return false;
}
if (messageObject.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction) {
int enc_id = (int) (messageObject.getDialogId() >> 32);
TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat(enc_id);
if (encryptedChat == null) {
- MessagesStorage.getInstance().markMessageAsSendError(messageObject.messageOwner.id);
+ MessagesStorage.getInstance().markMessageAsSendError(messageObject.getId());
messageObject.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, messageObject.messageOwner.id);
- processSentMessage(messageObject.messageOwner.id);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, messageObject.getId());
+ processSentMessage(messageObject.getId());
return false;
}
if (messageObject.messageOwner.random_id == 0) {
@@ -429,7 +429,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
return true;
}
if (unsent) {
- unsentMessages.put(messageObject.messageOwner.id, messageObject);
+ unsentMessages.put(messageObject.getId(), messageObject);
}
sendMessage(messageObject);
return true;
@@ -447,73 +447,246 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
if (messageObject == null) {
return;
}
- if (messageObject.messageOwner.media != null && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) {
+ if (messageObject.messageOwner.media != null && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage)) {
if (messageObject.messageOwner.media.photo instanceof TLRPC.TL_photo) {
- sendMessage((TLRPC.TL_photo) messageObject.messageOwner.media.photo, null, null, did);
+ sendMessage((TLRPC.TL_photo) messageObject.messageOwner.media.photo, null, null, did, messageObject.replyMessageObject);
} else if (messageObject.messageOwner.media.audio instanceof TLRPC.TL_audio) {
- sendMessage((TLRPC.TL_audio) messageObject.messageOwner.media.audio, messageObject.messageOwner.attachPath, did);
+ sendMessage((TLRPC.TL_audio) messageObject.messageOwner.media.audio, messageObject.messageOwner.attachPath, did, messageObject.replyMessageObject);
} else if (messageObject.messageOwner.media.video instanceof TLRPC.TL_video) {
TLRPC.TL_video video = (TLRPC.TL_video) messageObject.messageOwner.media.video;
video.videoEditedInfo = messageObject.messageOwner.videoEditedInfo;
- sendMessage(video, null, messageObject.messageOwner.attachPath, did);
+ sendMessage(video, null, messageObject.messageOwner.attachPath, did, messageObject.replyMessageObject);
} else if (messageObject.messageOwner.media.document instanceof TLRPC.TL_document) {
- sendMessage((TLRPC.TL_document) messageObject.messageOwner.media.document, null, messageObject.messageOwner.attachPath, did);
+ sendMessage((TLRPC.TL_document) messageObject.messageOwner.media.document, null, messageObject.messageOwner.attachPath, did, messageObject.replyMessageObject);
} else if (messageObject.messageOwner.media.geo instanceof TLRPC.TL_geoPoint) {
- sendMessage(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long, did);
+ sendMessage(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long, did, messageObject.replyMessageObject);
} else if (messageObject.messageOwner.media.phone_number != null) {
TLRPC.User user = new TLRPC.TL_userContact();
user.phone = messageObject.messageOwner.media.phone_number;
user.first_name = messageObject.messageOwner.media.first_name;
user.last_name = messageObject.messageOwner.media.last_name;
user.id = messageObject.messageOwner.media.user_id;
- sendMessage(user, did);
+ sendMessage(user, did, messageObject.replyMessageObject);
} else {
sendMessage(messageObject, did);
}
} else if (messageObject.messageOwner.message != null) {
- sendMessage(messageObject.messageOwner.message, did);
+ TLRPC.WebPage webPage = null;
+ if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
+ webPage = messageObject.messageOwner.media.webpage;
+ }
+ sendMessage(messageObject.messageOwner.message, did, messageObject.replyMessageObject, webPage, true);
} else {
sendMessage(messageObject, did);
}
}
- public void sendMessage(TLRPC.User user, long peer) {
- sendMessage(null, null, null, null, null, null, user, null, null, null, peer, false, null);
+ public void sendMessage(TLRPC.User user, long peer, MessageObject reply_to_msg) {
+ sendMessage(null, null, null, null, null, null, user, null, null, null, peer, false, null, reply_to_msg, null, true);
+ }
+
+ public void sendMessage(ArrayList messages, long peer) {
+ if ((int) peer == 0 || messages == null || messages.isEmpty()) {
+ return;
+ }
+ int lower_id = (int) peer;
+ TLRPC.Peer to_id;
+ TLRPC.InputPeer sendToPeer;
+ if (lower_id < 0) {
+ to_id = new TLRPC.TL_peerChat();
+ to_id.chat_id = -lower_id;
+ sendToPeer = new TLRPC.TL_inputPeerChat();
+ sendToPeer.chat_id = -lower_id;
+ } else {
+ to_id = new TLRPC.TL_peerUser();
+ to_id.user_id = lower_id;
+ TLRPC.User sendToUser = MessagesController.getInstance().getUser(lower_id);
+ if (sendToUser == null) {
+ return;
+ }
+ if (sendToUser instanceof TLRPC.TL_userForeign || sendToUser instanceof TLRPC.TL_userRequest) {
+ sendToPeer = new TLRPC.TL_inputPeerForeign();
+ sendToPeer.user_id = sendToUser.id;
+ sendToPeer.access_hash = sendToUser.access_hash;
+ } else {
+ sendToPeer = new TLRPC.TL_inputPeerContact();
+ sendToPeer.user_id = sendToUser.id;
+ }
+ }
+
+ ArrayList objArr = new ArrayList<>();
+ ArrayList arr = new ArrayList<>();
+ ArrayList randomIds = new ArrayList<>();
+ ArrayList ids = new ArrayList<>();
+ HashMap messagesByRandomIds = new HashMap<>();
+
+ for (int a = 0; a < messages.size(); a++) {
+ MessageObject msgObj = messages.get(a);
+
+ final TLRPC.Message newMsg = new TLRPC.TL_message();
+ newMsg.flags |= TLRPC.MESSAGE_FLAG_FWD;
+ if (msgObj.isForwarded()) {
+ newMsg.fwd_from_id = msgObj.messageOwner.fwd_from_id;
+ newMsg.fwd_date = msgObj.messageOwner.fwd_date;
+ } else {
+ newMsg.fwd_from_id = msgObj.messageOwner.from_id;
+ newMsg.fwd_date = msgObj.messageOwner.date;
+ }
+ newMsg.media = msgObj.messageOwner.media;
+ newMsg.message = msgObj.messageOwner.message;
+ newMsg.fwd_msg_id = msgObj.getId();
+ newMsg.attachPath = msgObj.messageOwner.attachPath;
+ if (newMsg.attachPath == null) {
+ newMsg.attachPath = "";
+ }
+ newMsg.local_id = newMsg.id = UserConfig.getNewMessageId();
+ newMsg.from_id = UserConfig.getClientUserId();
+ newMsg.flags |= TLRPC.MESSAGE_FLAG_OUT;
+ if (newMsg.random_id == 0) {
+ newMsg.random_id = getNextRandomId();
+ }
+ randomIds.add(newMsg.random_id);
+ messagesByRandomIds.put(newMsg.random_id, newMsg);
+ ids.add(newMsg.fwd_msg_id);
+ newMsg.date = ConnectionsManager.getInstance().getCurrentTime();
+ newMsg.flags |= TLRPC.MESSAGE_FLAG_UNREAD;
+ newMsg.dialog_id = peer;
+ newMsg.to_id = to_id;
+ MessageObject newMsgObj = new MessageObject(newMsg, null, true);
+ newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING;
+ objArr.add(newMsgObj);
+ arr.add(newMsg);
+
+ putToSendingMessages(newMsg);
+
+ if (arr.size() == 100 || a == messages.size() - 1) {
+ MessagesStorage.getInstance().putMessages(arr, false, true, false, 0);
+ MessagesController.getInstance().updateInterfaceWithMessages(peer, objArr);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
+ UserConfig.saveConfig(false);
+
+ TLRPC.TL_messages_forwardMessages req = new TLRPC.TL_messages_forwardMessages();
+ req.peer = sendToPeer;
+ req.random_id = randomIds;
+ req.id = ids;
+
+ final ArrayList newMsgObjArr = arr;
+ final HashMap messagesByRandomIdsFinal = messagesByRandomIds;
+ ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
+ @Override
+ public void run(TLObject response, TLRPC.TL_error error) {
+ if (error == null) {
+ HashMap newMessagesByIds = new HashMap<>();
+ TLRPC.Updates updates = (TLRPC.Updates) response;
+ for (int a = 0; a < updates.updates.size(); a++) {
+ TLRPC.Update update = updates.updates.get(a);
+ if (update instanceof TLRPC.TL_updateMessageID) {
+ newMessagesByIds.put(update.id, update.random_id);
+ updates.updates.remove(a);
+ a--;
+ }
+ }
+ for (TLRPC.Update update : updates.updates) {
+ if (update instanceof TLRPC.TL_updateNewMessage) {
+ MessagesController.getInstance().processNewDifferenceParams(-1, update.pts, -1, update.pts_count);
+ TLRPC.Message message = ((TLRPC.TL_updateNewMessage) update).message;
+ Long random_id = newMessagesByIds.get(message.id);
+ if (random_id != null) {
+ final TLRPC.Message newMsgObj = messagesByRandomIdsFinal.get(random_id);
+ if (newMsgObj == null) {
+ continue;
+ }
+ newMsgObjArr.remove(newMsgObj);
+ final int oldId = newMsgObj.id;
+ final ArrayList sentMessages = new ArrayList<>();
+ sentMessages.add(message);
+ newMsgObj.id = message.id;
+ processSentMessage(newMsgObj, message, null);
+ MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
+ @Override
+ public void run() {
+ MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.random_id, oldId, newMsgObj.id, 0, false);
+ MessagesStorage.getInstance().putMessages(sentMessages, true, false, false, 0);
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, newMsgObj.id, newMsgObj, false);
+ processSentMessage(oldId);
+ removeFromSendingMessages(oldId);
+ }
+ });
+ if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) {
+ stopVideoService(newMsgObj.attachPath);
+ }
+ }
+ });
+ }
+ }
+ }
+ }
+ for (final TLRPC.Message newMsgObj : newMsgObjArr) {
+ MessagesStorage.getInstance().markMessageAsSendError(newMsgObj.id);
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsgObj.id);
+ processSentMessage(newMsgObj.id);
+ if (newMsgObj.media instanceof TLRPC.TL_messageMediaVideo) {
+ stopVideoService(newMsgObj.attachPath);
+ }
+ removeFromSendingMessages(newMsgObj.id);
+ }
+ });
+ }
+ }
+ }, null, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassCanCompress, ConnectionsManager.DEFAULT_DATACENTER_ID);
+
+ if (a != messages.size() - 1) {
+ objArr = new ArrayList<>();
+ arr = new ArrayList<>();
+ randomIds = new ArrayList<>();
+ ids = new ArrayList<>();
+ messagesByRandomIds = new HashMap<>();
+ }
+ }
+ }
}
public void sendMessage(MessageObject message) {
- sendMessage(null, null, null, null, null, message, null, null, null, null, message.getDialogId(), true, message.messageOwner.attachPath);
+ sendMessage(null, null, null, null, null, message, null, null, null, null, message.getDialogId(), true, message.messageOwner.attachPath, null, null, true);
}
public void sendMessage(MessageObject message, long peer) {
- sendMessage(null, null, null, null, null, message, null, null, null, null, peer, false, message.messageOwner.attachPath);
+ sendMessage(null, null, null, null, null, message, null, null, null, null, peer, false, message.messageOwner.attachPath, null, null, true);
}
- public void sendMessage(TLRPC.TL_document document, String originalPath, String path, long peer) {
- sendMessage(null, null, null, null, null, null, null, document, null, originalPath, peer, false, path);
+ public void sendMessage(TLRPC.TL_document document, String originalPath, String path, long peer, MessageObject reply_to_msg) {
+ sendMessage(null, null, null, null, null, null, null, document, null, originalPath, peer, false, path, reply_to_msg, null, true);
}
- public void sendMessage(String message, long peer) {
- sendMessage(message, null, null, null, null, null, null, null, null, null, peer, false, null);
+ public void sendMessage(String message, long peer, MessageObject reply_to_msg, TLRPC.WebPage webPage, boolean searchLinks) {
+ sendMessage(message, null, null, null, null, null, null, null, null, null, peer, false, null, reply_to_msg, webPage, searchLinks);
}
- public void sendMessage(double lat, double lon, long peer) {
- sendMessage(null, lat, lon, null, null, null, null, null, null, null, peer, false, null);
+ public void sendMessage(double lat, double lon, long peer, MessageObject reply_to_msg) {
+ sendMessage(null, lat, lon, null, null, null, null, null, null, null, peer, false, null, reply_to_msg, null, true);
}
- public void sendMessage(TLRPC.TL_photo photo, String originalPath, String path, long peer) {
- sendMessage(null, null, null, photo, null, null, null, null, null, originalPath, peer, false, path);
+ public void sendMessage(TLRPC.TL_photo photo, String originalPath, String path, long peer, MessageObject reply_to_msg) {
+ sendMessage(null, null, null, photo, null, null, null, null, null, originalPath, peer, false, path, reply_to_msg, null, true);
}
- public void sendMessage(TLRPC.TL_video video, String originalPath, String path, long peer) {
- sendMessage(null, null, null, null, video, null, null, null, null, originalPath, peer, false, path);
+ public void sendMessage(TLRPC.TL_video video, String originalPath, String path, long peer, MessageObject reply_to_msg) {
+ sendMessage(null, null, null, null, video, null, null, null, null, originalPath, peer, false, path, reply_to_msg, null, true);
}
- public void sendMessage(TLRPC.TL_audio audio, String path, long peer) {
- sendMessage(null, null, null, null, null, null, null, null, audio, null, peer, false, path);
+ public void sendMessage(TLRPC.TL_audio audio, String path, long peer, MessageObject reply_to_msg) {
+ sendMessage(null, null, null, null, null, null, null, null, audio, null, peer, false, path, reply_to_msg, null, true);
}
- private void sendMessage(String message, Double lat, Double lon, TLRPC.TL_photo photo, TLRPC.TL_video video, MessageObject msgObj, TLRPC.User user, TLRPC.TL_document document, TLRPC.TL_audio audio, String originalPath, long peer, boolean retry, String path) {
+ private void sendMessage(String message, Double lat, Double lon, TLRPC.TL_photo photo, TLRPC.TL_video video, MessageObject msgObj, TLRPC.User user, TLRPC.TL_document document, TLRPC.TL_audio audio, String originalPath, long peer, boolean retry, String path, MessageObject reply_to_msg, TLRPC.WebPage webPage, boolean searchLinks) {
if (peer == 0) {
return;
}
@@ -533,7 +706,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
newMsg = msgObj.messageOwner;
if (msgObj.type == 0) {
- if (msgObj.messageOwner instanceof TLRPC.TL_messageForwarded) {
+ if (msgObj.isForwarded()) {
type = 4;
} else {
message = newMsg.message;
@@ -544,14 +717,14 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
lon = newMsg.media.geo._long;
type = 1;
} else if (msgObj.type == 1) {
- if (msgObj.messageOwner instanceof TLRPC.TL_messageForwarded) {
+ if (msgObj.isForwarded()) {
type = 4;
} else {
photo = (TLRPC.TL_photo) newMsg.media.photo;
type = 2;
}
} else if (msgObj.type == 3) {
- if (msgObj.messageOwner instanceof TLRPC.TL_messageForwarded) {
+ if (msgObj.isForwarded()) {
type = 4;
} else {
type = 3;
@@ -579,7 +752,12 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
} else {
newMsg = new TLRPC.TL_message();
}
- newMsg.media = new TLRPC.TL_messageMediaEmpty();
+ if (encryptedChat != null || webPage == null) {
+ newMsg.media = new TLRPC.TL_messageMediaEmpty();
+ } else {
+ newMsg.media = new TLRPC.TL_messageMediaWebPage();
+ newMsg.media.webpage = webPage;
+ }
type = 0;
newMsg.message = message;
} else if (lat != null && lon != null) {
@@ -627,24 +805,20 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
newMsg.attachPath = path;
} else if (msgObj != null) {
- newMsg = new TLRPC.TL_messageForwarded();
- if (msgObj.messageOwner instanceof TLRPC.TL_messageForwarded) {
+ newMsg = new TLRPC.TL_message();
+ newMsg.flags |= TLRPC.MESSAGE_FLAG_FWD;
+ if (msgObj.isForwarded()) {
newMsg.fwd_from_id = msgObj.messageOwner.fwd_from_id;
newMsg.fwd_date = msgObj.messageOwner.fwd_date;
- newMsg.media = msgObj.messageOwner.media;
- newMsg.message = msgObj.messageOwner.message;
- newMsg.fwd_msg_id = msgObj.messageOwner.id;
- newMsg.attachPath = msgObj.messageOwner.attachPath;
- type = 4;
} else {
newMsg.fwd_from_id = msgObj.messageOwner.from_id;
newMsg.fwd_date = msgObj.messageOwner.date;
- newMsg.media = msgObj.messageOwner.media;
- newMsg.message = msgObj.messageOwner.message;
- newMsg.fwd_msg_id = msgObj.messageOwner.id;
- newMsg.attachPath = msgObj.messageOwner.attachPath;
- type = 4;
}
+ newMsg.media = msgObj.messageOwner.media;
+ newMsg.message = msgObj.messageOwner.message;
+ newMsg.fwd_msg_id = msgObj.getId();
+ newMsg.attachPath = msgObj.messageOwner.attachPath;
+ type = 4;
} else if (user != null) {
if (encryptedChat != null && AndroidUtilities.getPeerLayerVersion(encryptedChat.layer) >= 17) {
newMsg = new TLRPC.TL_message_secret();
@@ -695,9 +869,15 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
newMsg.date = ConnectionsManager.getInstance().getCurrentTime();
newMsg.flags |= TLRPC.MESSAGE_FLAG_UNREAD;
newMsg.dialog_id = peer;
+ if (reply_to_msg != null) {
+ newMsg.flags |= TLRPC.MESSAGE_FLAG_REPLY;
+ newMsg.reply_to_msg_id = reply_to_msg.getId();
+ }
if (lower_id != 0) {
if (high_id == 1) {
if (currentChatInfo == null) {
+ MessagesStorage.getInstance().markMessageAsSendError(newMsg.id);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsg.id);
processSentMessage(newMsg.id);
return;
}
@@ -754,6 +934,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
MessageObject newMsgObj = new MessageObject(newMsg, null, true);
+ newMsgObj.replyMessageObject = reply_to_msg;
newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENDING;
ArrayList objArr = new ArrayList<>();
@@ -769,15 +950,27 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
if (encryptedChat == null) {
if (sendToPeers != null) {
TLRPC.TL_messages_sendBroadcast reqSend = new TLRPC.TL_messages_sendBroadcast();
+ ArrayList random_ids = new ArrayList<>();
+ for (int a = 0; a < sendToPeers.size(); a++) {
+ random_ids.add(Utilities.random.nextLong());
+ }
reqSend.message = message;
reqSend.contacts = sendToPeers;
reqSend.media = new TLRPC.TL_inputMediaEmpty();
+ reqSend.random_id = random_ids;
performSendMessageRequest(reqSend, newMsgObj.messageOwner, null);
} else {
TLRPC.TL_messages_sendMessage reqSend = new TLRPC.TL_messages_sendMessage();
reqSend.message = message;
reqSend.peer = sendToPeer;
reqSend.random_id = newMsg.random_id;
+ if (reply_to_msg != null) {
+ reqSend.flags |= 1;
+ reqSend.reply_to_msg_id = reply_to_msg.getId();
+ }
+ if (!searchLinks) {
+ reqSend.flags |= 2;
+ }
performSendMessageRequest(reqSend, newMsgObj.messageOwner, null);
}
} else {
@@ -787,7 +980,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
reqSend.ttl = newMsg.ttl;
} else {
reqSend = new TLRPC.TL_decryptedMessage_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
reqSend.random_id = newMsg.random_id;
@@ -899,8 +1092,13 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
if (sendToPeers != null) {
TLRPC.TL_messages_sendBroadcast request = new TLRPC.TL_messages_sendBroadcast();
+ ArrayList random_ids = new ArrayList<>();
+ for (int a = 0; a < sendToPeers.size(); a++) {
+ random_ids.add(Utilities.random.nextLong());
+ }
request.contacts = sendToPeers;
request.media = inputMedia;
+ request.random_id = random_ids;
request.message = "";
if (delayedMessage != null) {
delayedMessage.sendRequest = request;
@@ -911,6 +1109,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
request.peer = sendToPeer;
request.random_id = newMsg.random_id;
request.media = inputMedia;
+ if (reply_to_msg != null) {
+ request.flags |= 1;
+ request.reply_to_msg_id = reply_to_msg.getId();
+ }
if (delayedMessage != null) {
delayedMessage.sendRequest = request;
}
@@ -952,7 +1154,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
reqSend.ttl = newMsg.ttl;
} else {
reqSend = new TLRPC.TL_decryptedMessage_old();
- reqSend.random_bytes = new byte[Math.max(1, (int) Math.ceil(Utilities.random.nextDouble() * 16))];
+ reqSend.random_bytes = new byte[15];
Utilities.random.nextBytes(reqSend.random_bytes);
}
reqSend.random_id = newMsg.random_id;
@@ -1107,8 +1309,8 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
TLRPC.TL_messages_forwardMessage reqSend = new TLRPC.TL_messages_forwardMessage();
reqSend.peer = sendToPeer;
reqSend.random_id = newMsg.random_id;
- if (msgObj.messageOwner.id >= 0) {
- reqSend.id = msgObj.messageOwner.id;
+ if (msgObj.getId() >= 0) {
+ reqSend.id = msgObj.getId();
} else {
reqSend.id = msgObj.messageOwner.fwd_msg_id;
}
@@ -1116,10 +1318,10 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
}
} catch (Exception e) {
FileLog.e("tmessages", e);
- MessagesStorage.getInstance().markMessageAsSendError(newMsgObj.messageOwner.id);
+ MessagesStorage.getInstance().markMessageAsSendError(newMsgObj.getId());
newMsgObj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsgObj.messageOwner.id);
- processSentMessage(newMsgObj.messageOwner.id);
+ NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageSendError, newMsgObj.getId());
+ processSentMessage(newMsgObj.getId());
}
}
@@ -1255,70 +1457,82 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
+ boolean isSentError = false;
if (error == null) {
final int oldId = newMsgObj.id;
final boolean isBroadcast = req instanceof TLRPC.TL_messages_sendBroadcast;
final ArrayList sentMessages = new ArrayList<>();
final String attachPath = newMsgObj.attachPath;
-
+ final boolean mediaUpdated = response instanceof TLRPC.messages_SentMessage && !(((TLRPC.messages_SentMessage) response).media instanceof TLRPC.TL_messageMediaEmpty);
if (response instanceof TLRPC.messages_SentMessage) {
TLRPC.messages_SentMessage res = (TLRPC.messages_SentMessage) response;
- newMsgObj.id = res.id;
+ newMsgObj.local_id = newMsgObj.id = res.id;
newMsgObj.date = res.date;
- MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.date);
- } else if (response instanceof TLRPC.messages_StatedMessage) {
- TLRPC.messages_StatedMessage res = (TLRPC.messages_StatedMessage) response;
- sentMessages.add(res.message);
- newMsgObj.id = res.message.id;
- processSentMessage(newMsgObj, res.message, originalPath);
- MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.message.date);
- } else if (response instanceof TLRPC.messages_StatedMessages) {
- TLRPC.messages_StatedMessages res = (TLRPC.messages_StatedMessages) response;
- if (!res.messages.isEmpty()) {
- sentMessages.addAll(res.messages);
- TLRPC.Message message = res.messages.get(0);
- if (!isBroadcast) {
- newMsgObj.id = message.id;
- }
- processSentMessage(newMsgObj, message, originalPath);
+ newMsgObj.media = res.media;
+ if (res instanceof TLRPC.TL_messages_sentMessage) {
+ MessagesController.getInstance().processNewDifferenceParams(-1, res.pts, res.date, res.pts_count);
+ } else if (res instanceof TLRPC.TL_messages_sentMessageLink) {
+ MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, res.date, res.pts_count);
+ }
+ sentMessages.add(newMsgObj);
+ } else if (response instanceof TLRPC.Updates) {
+ TLRPC.TL_updateNewMessage newMessage = null;
+ for (TLRPC.Update update : ((TLRPC.Updates) response).updates) {
+ if (update instanceof TLRPC.TL_updateNewMessage) {
+ newMessage = (TLRPC.TL_updateNewMessage) update;
+ break;
+ }
+ }
+ if (newMessage != null) {
+ sentMessages.add(newMessage.message);
+ newMsgObj.id = newMessage.message.id;
+ processSentMessage(newMsgObj, newMessage.message, originalPath);
+ MessagesController.getInstance().processNewDifferenceParams(-1, newMessage.pts, -1, newMessage.pts_count);
+ } else {
+ isSentError = true;
}
- MessagesController.getInstance().processNewDifferenceParams(res.seq, res.pts, -1);
}
- MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
- @Override
- public void run() {
- MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.random_id, oldId, (isBroadcast ? oldId : newMsgObj.id), 0, false);
- MessagesStorage.getInstance().putMessages(sentMessages, true, false, isBroadcast, 0);
- if (isBroadcast) {
- ArrayList currentMessage = new ArrayList<>();
- currentMessage.add(newMsgObj);
- newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
- MessagesStorage.getInstance().putMessages(currentMessage, true, false, false, 0);
- }
- AndroidUtilities.runOnUIThread(new Runnable() {
- @Override
- public void run() {
+
+ if (!isSentError) {
+ MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
+ @Override
+ public void run() {
+ MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.random_id, oldId, (isBroadcast ? oldId : newMsgObj.id), 0, false);
+ MessagesStorage.getInstance().putMessages(sentMessages, true, false, isBroadcast, 0);
+ if (isBroadcast) {
+ ArrayList currentMessage = new ArrayList<>();
+ currentMessage.add(newMsgObj);
newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
- if (isBroadcast) {
- for (TLRPC.Message message : sentMessages) {
- ArrayList arr = new ArrayList<>();
- MessageObject messageObject = new MessageObject(message, null, false);
- arr.add(messageObject);
- MessagesController.getInstance().updateInterfaceWithMessages(messageObject.getDialogId(), arr, isBroadcast);
- }
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload);
- }
- NotificationCenter.getInstance().postNotificationName(NotificationCenter.messageReceivedByServer, oldId, (isBroadcast ? oldId : newMsgObj.id), newMsgObj);
- processSentMessage(oldId);
- removeFromSendingMessages(oldId);
+ MessagesStorage.getInstance().putMessages(currentMessage, true, false, false, 0);
+ }
+ AndroidUtilities.runOnUIThread(new Runnable() {
+ @Override
+ public void run() {
+ newMsgObj.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
+ if (isBroadcast) {
+ for (TLRPC.Message message : sentMessages) {
+ ArrayList