Update to 3.6.1

This commit is contained in:
DrKLO 2016-03-06 02:49:31 +01:00
parent 2114024ab1
commit 6154c891bd
166 changed files with 10224 additions and 4470 deletions

View File

@ -83,7 +83,7 @@ android {
defaultConfig { defaultConfig {
minSdkVersion 9 minSdkVersion 9
targetSdkVersion 23 targetSdkVersion 23
versionCode 719 versionCode 755
versionName "3.4.2" versionName "3.6.1"
} }
} }

View File

@ -235,7 +235,7 @@ include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS) include $(CLEAR_VARS)
LOCAL_PRELINK_MODULE := false LOCAL_PRELINK_MODULE := false
LOCAL_MODULE := tmessages.17 LOCAL_MODULE := tmessages.19
LOCAL_CFLAGS := -w -std=c11 -Os -DNULL=0 -DSOCKLEN_T=socklen_t -DLOCALE_NOT_USED -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64 LOCAL_CFLAGS := -w -std=c11 -Os -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 += -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 -D__STDC_CONSTANT_MACROS LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT -ffast-math -D__STDC_CONSTANT_MACROS

View File

@ -5,6 +5,7 @@
#include <stdlib.h> #include <stdlib.h>
#include <time.h> #include <time.h>
#include <opusfile.h> #include <opusfile.h>
#include <math.h>
#include "utils.h" #include "utils.h"
typedef struct { typedef struct {
@ -663,6 +664,156 @@ JNIEXPORT int Java_org_telegram_messenger_MediaController_isOpusFile(JNIEnv *env
result = error == OPUS_OK; result = error == OPUS_OK;
} }
if (pathStr != 0) {
(*env)->ReleaseStringUTFChars(env, path, pathStr);
}
return result;
}
static inline void set_bits(uint8_t *bytes, int32_t bitOffset, int32_t numBits, int32_t value) {
numBits = (unsigned int) (2 << (numBits - 1)) - 1;
bytes += bitOffset / 8;
bitOffset %= 8;
*((int32_t *) bytes) |= (value << bitOffset);
}
JNIEXPORT jbyteArray Java_org_telegram_messenger_MediaController_getWaveform2(JNIEnv *env, jclass class, jshortArray array, jint length) {
jshort *sampleBuffer = (*env)->GetShortArrayElements(env, array, 0);
jbyteArray result = 0;
int32_t resultSamples = 100;
uint16_t *samples = malloc(100 * 2);
uint64_t sampleIndex = 0;
uint16_t peakSample = 0;
int32_t sampleRate = (int32_t) max(1, length / resultSamples);
int index = 0;
for (int i = 0; i < length; i++) {
uint16_t sample = (uint16_t) abs(sampleBuffer[i]);
if (sample > peakSample) {
peakSample = sample;
}
if (sampleIndex++ % sampleRate == 0) {
if (index < resultSamples) {
samples[index++] = peakSample;
}
peakSample = 0;
}
}
int64_t sumSamples = 0;
for (int i = 0; i < resultSamples; i++) {
sumSamples += samples[i];
}
uint16_t peak = (uint16_t) (sumSamples * 1.8f / resultSamples);
if (peak < 2500) {
peak = 2500;
}
for (int i = 0; i < resultSamples; i++) {
uint16_t sample = (uint16_t) ((int64_t) samples[i]);
if (sample > peak) {
samples[i] = peak;
}
}
(*env)->ReleaseShortArrayElements(env, array, sampleBuffer, 0);
int bitstreamLength = (resultSamples * 5) / 8 + (((resultSamples * 5) % 8) == 0 ? 0 : 1);
result = (*env)->NewByteArray(env, bitstreamLength);
jbyte *bytes = (*env)->GetByteArrayElements(env, result, NULL);
for (int i = 0; i < resultSamples; i++) {
int32_t value = min(31, abs((int32_t) samples[i]) * 31 / peak);
set_bits(bytes, i * 5, 5, value & 31);
}
(*env)->ReleaseByteArrayElements(env, result, bytes, JNI_COMMIT);
free(samples);
return result;
}
int16_t *sampleBuffer = NULL;
JNIEXPORT jbyteArray Java_org_telegram_messenger_MediaController_getWaveform(JNIEnv *env, jclass class, jstring path) {
const char *pathStr = (*env)->GetStringUTFChars(env, path, 0);
jbyteArray result = 0;
int error = OPUS_OK;
OggOpusFile *opusFile = op_open_file(pathStr, &error);
if (opusFile != NULL && error == OPUS_OK) {
int64_t totalSamples = op_pcm_total(opusFile, -1);
int32_t resultSamples = 100;
int32_t sampleRate = (int32_t) max(1, totalSamples / resultSamples);
uint16_t *samples = malloc(100 * 2);
int bufferSize = 1024 * 128;
if (sampleBuffer == NULL) {
sampleBuffer = malloc(bufferSize);
}
uint64_t sampleIndex = 0;
uint16_t peakSample = 0;
int index = 0;
while (1) {
int readSamples = op_read(opusFile, sampleBuffer, bufferSize / 2, NULL);
for (int i = 0; i < readSamples; i++) {
uint16_t sample = (uint16_t) abs(sampleBuffer[i]);
if (sample > peakSample) {
peakSample = sample;
}
if (sampleIndex++ % sampleRate == 0) {
if (index < resultSamples) {
samples[index++] = peakSample;
}
peakSample = 0;
}
}
if (readSamples == 0) {
break;
}
}
int64_t sumSamples = 0;
for (int i = 0; i < resultSamples; i++) {
sumSamples += samples[i];
}
uint16_t peak = (uint16_t) (sumSamples * 1.8f / resultSamples);
if (peak < 2500) {
peak = 2500;
}
for (int i = 0; i < resultSamples; i++) {
uint16_t sample = (uint16_t) ((int64_t) samples[i]);
if (sample > peak) {
samples[i] = peak;
}
}
//free(sampleBuffer);
op_free(opusFile);
int bitstreamLength = (resultSamples * 5) / 8 + (((resultSamples * 5) % 8) == 0 ? 0 : 1);
result = (*env)->NewByteArray(env, bitstreamLength);
jbyte *bytes = (*env)->GetByteArrayElements(env, result, NULL);
for (int i = 0; i < resultSamples; i++) {
int32_t value = min(31, abs((int32_t) samples[i]) * 31 / peak);
set_bits(bytes, i * 5, 5, value & 31);
}
(*env)->ReleaseByteArrayElements(env, result, bytes, JNI_COMMIT);
free(samples);
}
if (pathStr != 0) { if (pathStr != 0) {
(*env)->ReleaseStringUTFChars(env, path, pathStr); (*env)->ReleaseStringUTFChars(env, path, pathStr);
} }

View File

@ -59,3 +59,16 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *en
(*env)->ReleaseByteArrayElements(env, key, keyBuff, JNI_ABORT); (*env)->ReleaseByteArrayElements(env, key, keyBuff, JNI_ABORT);
(*env)->ReleaseByteArrayElements(env, iv, ivBuff, 0); (*env)->ReleaseByteArrayElements(env, iv, ivBuff, 0);
} }
JNIEXPORT jstring Java_org_telegram_messenger_Utilities_readlink(JNIEnv *env, jclass class, jstring path) {
static char buf[1000];
char *fileName = (*env)->GetStringUTFChars(env, path, NULL);
int result = readlink(fileName, buf, 999);
jstring value = 0;
if (result != -1) {
buf[result] = '\0';
value = (*env)->NewStringUTF(env, buf);
}
(*env)->ReleaseStringUTFChars(env, path, fileName);
return value;
}

View File

@ -6,6 +6,8 @@
* Copyright Nikolai Kudashov, 2015. * Copyright Nikolai Kudashov, 2015.
*/ */
#include <openssl/rand.h>
#include <stdlib.h>
#include "Connection.h" #include "Connection.h"
#include "ConnectionsManager.h" #include "ConnectionsManager.h"
#include "BuffersStorage.h" #include "BuffersStorage.h"
@ -55,6 +57,8 @@ void Connection::suspendConnection() {
} }
void Connection::onReceivedData(NativeByteBuffer *buffer) { void Connection::onReceivedData(NativeByteBuffer *buffer) {
//AES_ctr128_encrypt(buffer->bytes(), buffer->bytes(), buffer->limit(), &decryptKey, decryptIv, decryptCount, &decryptNum);
failedConnectionCount = 0; failedConnectionCount = 0;
NativeByteBuffer *parseLaterBuffer = nullptr; NativeByteBuffer *parseLaterBuffer = nullptr;
@ -305,12 +309,47 @@ void Connection::sendData(NativeByteBuffer *buff, bool reportAck) {
bufferLen += 4; bufferLen += 4;
} }
if (!firstPacketSent) { if (!firstPacketSent) {
bufferLen++; bufferLen += 64;
} }
NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(bufferLen); NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(bufferLen);
uint8_t *bytes = buffer->bytes();
if (!firstPacketSent) { if (!firstPacketSent) {
buffer->writeByte(0xef); buffer->position(64);
static uint8_t temp[64];
while (true) {
RAND_bytes(bytes, 64);
uint32_t val = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0]);
uint32_t val2 = (bytes[7] << 24) | (bytes[6] << 16) | (bytes[5] << 8) | (bytes[4]);
if (bytes[0] != 0xef && val != 0x44414548 && val != 0x54534f50 && val != 0x20544547 && val != 0x4954504f && val != 0xeeeeeeee && val2 != 0x00000000) {
//bytes[56] = bytes[57] = bytes[58] = bytes[59] = 0xef;
break;
}
}
/*for (int a = 0; a < 48; a++) {
temp[a] = bytes[55 - a];
}
encryptNum = decryptNum = 0;
memset(encryptCount, 0, 16);
memset(decryptCount, 0, 16);
if (AES_set_encrypt_key(bytes + 8, 256, &encryptKey) < 0) {
DEBUG_E("unable to set encryptKey");
exit(1);
}
memcpy(encryptIv, bytes + 40, 16);
if (AES_set_encrypt_key(temp, 256, &decryptKey) < 0) {
DEBUG_E("unable to set decryptKey");
exit(1);
}
memcpy(decryptIv, temp + 32, 16);
AES_ctr128_encrypt(bytes, temp, 64, &encryptKey, encryptIv, encryptCount, &encryptNum);
memcpy(bytes + 56, temp + 56, 8);*/
firstPacketSent = true; firstPacketSent = true;
} }
if (packetLength < 0x7f) { if (packetLength < 0x7f) {
@ -318,17 +357,22 @@ void Connection::sendData(NativeByteBuffer *buff, bool reportAck) {
packetLength |= (1 << 7); packetLength |= (1 << 7);
} }
buffer->writeByte((uint8_t) packetLength); buffer->writeByte((uint8_t) packetLength);
bytes += (buffer->limit() - 1);
//AES_ctr128_encrypt(bytes, bytes, 1, &encryptKey, encryptIv, encryptCount, &encryptNum);
} else { } else {
packetLength = (packetLength << 8) + 0x7f; packetLength = (packetLength << 8) + 0x7f;
if (reportAck) { if (reportAck) {
packetLength |= (1 << 7); packetLength |= (1 << 7);
} }
buffer->writeInt32(packetLength); buffer->writeInt32(packetLength);
bytes += (buffer->limit() - 4);
//AES_ctr128_encrypt(bytes, bytes, 4, &encryptKey, encryptIv, encryptCount, &encryptNum);
} }
buffer->rewind(); buffer->rewind();
writeBuffer(buffer); writeBuffer(buffer);
buff->rewind(); buff->rewind();
//AES_ctr128_encrypt(buff->bytes(), buff->bytes(), buff->limit(), &encryptKey, encryptIv, encryptCount, &encryptNum);
writeBuffer(buff); writeBuffer(buff);
} }

View File

@ -12,6 +12,7 @@
#include <pthread.h> #include <pthread.h>
#include <vector> #include <vector>
#include <string> #include <string>
#include <openssl/aes.h>
#include "ConnectionSession.h" #include "ConnectionSession.h"
#include "ConnectionSocket.h" #include "ConnectionSocket.h"
#include "Defines.h" #include "Defines.h"
@ -67,6 +68,16 @@ private:
bool wasConnected = false; bool wasConnected = false;
uint32_t willRetryConnectCount = 5; uint32_t willRetryConnectCount = 5;
Timer *reconnectTimer; Timer *reconnectTimer;
AES_KEY encryptKey;
uint8_t encryptIv[16];
uint32_t encryptNum;
uint8_t encryptCount[16];
AES_KEY decryptKey;
uint8_t decryptIv[16];
uint32_t decryptNum;
uint8_t decryptCount[16];
friend class ConnectionsManager; friend class ConnectionsManager;
}; };

View File

@ -946,6 +946,7 @@ void TL_config::readParams(NativeByteBuffer *stream, bool &error) {
push_chat_period_ms = stream->readInt32(&error); push_chat_period_ms = stream->readInt32(&error);
push_chat_limit = stream->readInt32(&error); push_chat_limit = stream->readInt32(&error);
saved_gifs_limit = stream->readInt32(&error); saved_gifs_limit = stream->readInt32(&error);
edit_time_limit = stream->readInt32(&error);
magic = stream->readUint32(&error); magic = stream->readUint32(&error);
if (magic != 0x1cb5c415) { if (magic != 0x1cb5c415) {
error = true; error = true;
@ -987,6 +988,7 @@ void TL_config::serializeToStream(NativeByteBuffer *stream) {
stream->writeInt32(push_chat_period_ms); stream->writeInt32(push_chat_period_ms);
stream->writeInt32(push_chat_limit); stream->writeInt32(push_chat_limit);
stream->writeInt32(saved_gifs_limit); stream->writeInt32(saved_gifs_limit);
stream->writeInt32(edit_time_limit);
stream->writeInt32(0x1cb5c415); stream->writeInt32(0x1cb5c415);
count = (uint32_t) disabled_features.size(); count = (uint32_t) disabled_features.size();
stream->writeInt32(count); stream->writeInt32(count);

View File

@ -657,7 +657,7 @@ public:
class TL_config : public TLObject { class TL_config : public TLObject {
public: public:
static const uint32_t constructor = 0x6bbc5f8; static const uint32_t constructor = 0x317ceef4;
int32_t date; int32_t date;
int32_t expires; int32_t expires;
@ -677,6 +677,7 @@ public:
int32_t push_chat_period_ms; int32_t push_chat_period_ms;
int32_t push_chat_limit; int32_t push_chat_limit;
int32_t saved_gifs_limit; int32_t saved_gifs_limit;
int32_t edit_time_limit;
std::vector<std::unique_ptr<TL_disabledFeature>> disabled_features; std::vector<std::unique_ptr<TL_disabledFeature>> disabled_features;
static TL_config *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); static TL_config *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error);

View File

@ -129,18 +129,28 @@
android:windowSoftInputMode="adjustResize|stateHidden"> android:windowSoftInputMode="adjustResize|stateHidden">
</activity> </activity>
<receiver android:name=".AutoMessageHeardReceiver"> <receiver
android:name=".AutoMessageHeardReceiver"
android:exported="false">
<intent-filter> <intent-filter>
<action android:name="org.telegram.messenger.ACTION_MESSAGE_HEARD"/> <action android:name="org.telegram.messenger.ACTION_MESSAGE_HEARD"/>
</intent-filter> </intent-filter>
</receiver> </receiver>
<receiver android:name=".AutoMessageReplyReceiver"> <receiver
android:name=".AutoMessageReplyReceiver"
android:exported="false">
<intent-filter> <intent-filter>
<action android:name="org.telegram.messenger.ACTION_MESSAGE_REPLY"/> <action android:name="org.telegram.messenger.ACTION_MESSAGE_REPLY"/>
</intent-filter> </intent-filter>
</receiver> </receiver>
<receiver android:name=".CallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<receiver android:name=".SmsListener"> <receiver android:name=".SmsListener">
<intent-filter> <intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" /> <action android:name="android.provider.Telephony.SMS_RECEIVED" />

View File

@ -27,6 +27,8 @@ import android.graphics.drawable.Drawable;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Environment; import android.os.Environment;
import android.os.Parcelable;
import android.provider.Browser;
import android.provider.DocumentsContract; import android.provider.DocumentsContract;
import android.provider.MediaStore; import android.provider.MediaStore;
import android.text.Spannable; import android.text.Spannable;
@ -409,6 +411,29 @@ public class AndroidUtilities {
} }
} }
public static void openUrl(Context context, String url) {
if (context == null || url == null) {
return;
}
openUrl(context, Uri.parse(url));
}
public static void openUrl(Context context, Uri uri) {
if (context == null || uri == null) {
return;
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra("android.support.customtabs.extra.SESSION", (Parcelable) null);
intent.putExtra("android.support.customtabs.extra.TOOLBAR_COLOR", 0xff54759e);
intent.putExtra("android.support.customtabs.extra.TITLE_VISIBILITY", 1);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
context.startActivity(intent);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static int getPhotoSize() { public static int getPhotoSize() {
if (photoSize == null) { if (photoSize == null) {
if (Build.VERSION.SDK_INT >= 16) { if (Build.VERSION.SDK_INT >= 16) {
@ -1057,4 +1082,11 @@ public class AndroidUtilities {
} }
return true; return true;
} }
public static byte[] calcAuthKeyHash(byte[] auth_key) {
byte[] sha1 = Utilities.computeSHA1(auth_key);
byte[] key_hash = new byte[16];
System.arraycopy(sha1, 0, key_hash, 0, 16);
return key_hash;
}
} }

View File

@ -325,6 +325,8 @@ public class ApplicationLoader extends Application {
FileLog.d("tmessages", "GCM Registration not found."); FileLog.d("tmessages", "GCM Registration not found.");
Intent intent = new Intent(applicationContext, GcmRegistrationIntentService.class); Intent intent = new Intent(applicationContext, GcmRegistrationIntentService.class);
startService(intent); startService(intent);
} else {
FileLog.d("tmessages", "GCM regId = " + UserConfig.pushString);
} }
} else { } else {
FileLog.d("tmessages", "No valid Google Play Services APK found."); FileLog.d("tmessages", "No valid Google Play Services APK found.");

View File

@ -3,14 +3,15 @@
* It is licensed under GNU GPL v. 2 or later. * It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE). * You should have received a copy of the license in this archive (see LICENSE).
* *
* Copyright Nikolai Kudashov, 2013-2015. * Copyright Nikolai Kudashov, 2013-2016.
*/ */
package org.telegram.messenger; package org.telegram.messenger;
public class BuildVars { public class BuildVars {
public static boolean DEBUG_VERSION = false; public static boolean DEBUG_VERSION = false;
public static int BUILD_VERSION = 719; public static int BUILD_VERSION = 753;
public static String BUILD_VERSION_STRING = "3.6";
public static int APP_ID = 0; //obtain your own APP_ID at https://core.telegram.org/api/obtaining_api_id public static int APP_ID = 0; //obtain your own APP_ID at https://core.telegram.org/api/obtaining_api_id
public static String APP_HASH = ""; //obtain your own APP_HASH at https://core.telegram.org/api/obtaining_api_id public static String APP_HASH = ""; //obtain your own APP_HASH at https://core.telegram.org/api/obtaining_api_id
public static String HOCKEY_APP_HASH = "your-hockeyapp-api-key-here"; public static String HOCKEY_APP_HASH = "your-hockeyapp-api-key-here";

View File

@ -0,0 +1,30 @@
/*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.telegram.messenger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class CallReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
/*TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
if (state == 1 && incomingNumber != null && incomingNumber.length() > 0) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.didReceiveCall, incomingNumber);
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);*/
}
}

View File

@ -48,6 +48,9 @@ public class ClearCacheService extends IntentService {
for (int b = 0; b < array.length; b++) { for (int b = 0; b < array.length; b++) {
File f = array[b]; File f = array[b];
if (f.isFile()) { if (f.isFile()) {
if (f.getName().equals(".nomedia")) {
continue;
}
if (Build.VERSION.SDK_INT >= 21) { if (Build.VERSION.SDK_INT >= 21) {
try { try {
StructStat stat = Os.stat(f.getPath()); StructStat stat = Os.stat(f.getPath());

View File

@ -56,7 +56,9 @@ public class ContactsController {
private int loadingDeleteInfo = 0; private int loadingDeleteInfo = 0;
private int deleteAccountTTL; private int deleteAccountTTL;
private int loadingLastSeenInfo = 0; private int loadingLastSeenInfo = 0;
private int loadingGroupInfo = 0;
private ArrayList<TLRPC.PrivacyRule> privacyRules = null; private ArrayList<TLRPC.PrivacyRule> privacyRules = null;
private ArrayList<TLRPC.PrivacyRule> groupPrivacyRules = null;
public static class Contact { public static class Contact {
public int id; public int id;
@ -160,6 +162,7 @@ public class ContactsController {
loadingDeleteInfo = 0; loadingDeleteInfo = 0;
deleteAccountTTL = 0; deleteAccountTTL = 0;
loadingLastSeenInfo = 0; loadingLastSeenInfo = 0;
loadingGroupInfo = 0;
privacyRules = null; privacyRules = null;
} }
@ -177,8 +180,8 @@ public class ContactsController {
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) { if (response != null) {
final TLRPC.TL_help_inviteText res = (TLRPC.TL_help_inviteText)response; final TLRPC.TL_help_inviteText res = (TLRPC.TL_help_inviteText) response;
if (res.message.length() != 0) { if (res.message.length() != 0) {
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(new Runnable() {
@Override @Override
@ -1859,6 +1862,30 @@ public class ContactsController {
} }
}); });
} }
if (loadingGroupInfo == 0) {
loadingGroupInfo = 1;
TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy();
req.key = new TLRPC.TL_inputPrivacyKeyChatInvite();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, final TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (error == null) {
TLRPC.TL_account_privacyRules rules = (TLRPC.TL_account_privacyRules) response;
MessagesController.getInstance().putUsers(rules.users, false);
groupPrivacyRules = rules.rules;
loadingGroupInfo = 2;
} else {
loadingGroupInfo = 0;
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.privacyRulesUpdated);
}
});
}
});
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.privacyRulesUpdated); NotificationCenter.getInstance().postNotificationName(NotificationCenter.privacyRulesUpdated);
} }
@ -1878,12 +1905,24 @@ public class ContactsController {
return loadingLastSeenInfo != 2; return loadingLastSeenInfo != 2;
} }
public ArrayList<TLRPC.PrivacyRule> getPrivacyRules() { public boolean getLoadingGroupInfo() {
return privacyRules; return loadingGroupInfo != 2;
} }
public void setPrivacyRules(ArrayList<TLRPC.PrivacyRule> rules) { public ArrayList<TLRPC.PrivacyRule> getPrivacyRules(boolean isGroup) {
privacyRules = rules; if (isGroup) {
return groupPrivacyRules;
} else {
return privacyRules;
}
}
public void setPrivacyRules(ArrayList<TLRPC.PrivacyRule> rules, boolean isGroup) {
if (isGroup) {
groupPrivacyRules = rules;
} else {
privacyRules = rules;
}
NotificationCenter.getInstance().postNotificationName(NotificationCenter.privacyRulesUpdated); NotificationCenter.getInstance().postNotificationName(NotificationCenter.privacyRulesUpdated);
reloadContactsStatuses(); reloadContactsStatuses();
} }

View File

@ -94,73 +94,59 @@ public class FileLoadOperation {
ext = extension != null ? extension : "jpg"; ext = extension != null ? extension : "jpg";
} }
public FileLoadOperation(TLRPC.Video videoLocation) {
if (videoLocation instanceof TLRPC.TL_videoEncrypted) {
location = new TLRPC.TL_inputEncryptedFileLocation();
location.id = videoLocation.id;
location.access_hash = videoLocation.access_hash;
datacenter_id = videoLocation.dc_id;
iv = new byte[32];
System.arraycopy(videoLocation.iv, 0, iv, 0, iv.length);
key = videoLocation.key;
} else if (videoLocation instanceof TLRPC.TL_video) {
location = new TLRPC.TL_inputVideoFileLocation();
datacenter_id = videoLocation.dc_id;
location.id = videoLocation.id;
location.access_hash = videoLocation.access_hash;
}
totalBytesCount = videoLocation.size;
ext = ".mp4";
}
public FileLoadOperation(TLRPC.Audio audioLocation) {
if (audioLocation instanceof TLRPC.TL_audioEncrypted) {
location = new TLRPC.TL_inputEncryptedFileLocation();
location.id = audioLocation.id;
location.access_hash = audioLocation.access_hash;
datacenter_id = audioLocation.dc_id;
iv = new byte[32];
System.arraycopy(audioLocation.iv, 0, iv, 0, iv.length);
key = audioLocation.key;
} else if (audioLocation instanceof TLRPC.TL_audio) {
location = new TLRPC.TL_inputAudioFileLocation();
datacenter_id = audioLocation.dc_id;
location.id = audioLocation.id;
location.access_hash = audioLocation.access_hash;
}
totalBytesCount = audioLocation.size;
ext = ".ogg";
}
public FileLoadOperation(TLRPC.Document documentLocation) { public FileLoadOperation(TLRPC.Document documentLocation) {
if (documentLocation instanceof TLRPC.TL_documentEncrypted) { try {
location = new TLRPC.TL_inputEncryptedFileLocation(); if (documentLocation instanceof TLRPC.TL_documentEncrypted) {
location.id = documentLocation.id; location = new TLRPC.TL_inputEncryptedFileLocation();
location.access_hash = documentLocation.access_hash; location.id = documentLocation.id;
datacenter_id = documentLocation.dc_id; location.access_hash = documentLocation.access_hash;
iv = new byte[32]; datacenter_id = documentLocation.dc_id;
System.arraycopy(documentLocation.iv, 0, iv, 0, iv.length); iv = new byte[32];
key = documentLocation.key; System.arraycopy(documentLocation.iv, 0, iv, 0, iv.length);
} else if (documentLocation instanceof TLRPC.TL_document) { key = documentLocation.key;
location = new TLRPC.TL_inputDocumentFileLocation(); } else if (documentLocation instanceof TLRPC.TL_document) {
location.id = documentLocation.id; location = new TLRPC.TL_inputDocumentFileLocation();
location.access_hash = documentLocation.access_hash; location.id = documentLocation.id;
datacenter_id = documentLocation.dc_id; location.access_hash = documentLocation.access_hash;
} datacenter_id = documentLocation.dc_id;
if (totalBytesCount <= 0) { }
totalBytesCount = documentLocation.size; if (totalBytesCount <= 0) {
} totalBytesCount = documentLocation.size;
if (ext == null) { }
ext = FileLoader.getDocumentFileName(documentLocation); ext = FileLoader.getDocumentFileName(documentLocation);
int idx; int idx;
if (ext == null || (idx = ext.lastIndexOf(".")) == -1) { if (ext == null || (idx = ext.lastIndexOf(".")) == -1) {
ext = ""; ext = "";
} else { } else {
ext = ext.substring(idx); ext = ext.substring(idx);
if (ext.length() <= 1) { }
if (ext.length() <= 1) {
if (documentLocation.mime_type != null) {
switch (documentLocation.mime_type) {
case "video/mp4":
ext = ".mp4";
break;
case "audio/ogg":
ext = ".ogg";
break;
default:
ext = "";
break;
}
} else {
ext = ""; ext = "";
} }
} }
} catch (Exception e) {
FileLog.e("tmessages", e);
state = stateFailed;
cleanup();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
delegate.didFailedLoadingFile(FileLoadOperation.this, 0);
}
});
} }
} }
@ -187,6 +173,7 @@ public class FileLoadOperation {
delayedRequestInfos = new ArrayList<>(currentMaxDownloadRequests - 1); delayedRequestInfos = new ArrayList<>(currentMaxDownloadRequests - 1);
state = stateDownloading; state = stateDownloading;
if (location == null) { if (location == null) {
cleanup();
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -315,7 +302,8 @@ public class FileLoadOperation {
state = stateFailed; state = stateFailed;
cleanup(); cleanup();
if (requestInfos != null) { if (requestInfos != null) {
for (RequestInfo requestInfo : requestInfos) { for (int a = 0; a < requestInfos.size(); a++) {
RequestInfo requestInfo = requestInfos.get(a);
if (requestInfo.requestToken != 0) { if (requestInfo.requestToken != 0) {
ConnectionsManager.getInstance().cancelRequest(requestInfo.requestToken, true); ConnectionsManager.getInstance().cancelRequest(requestInfo.requestToken, true);
} }

View File

@ -272,50 +272,37 @@ public class FileLoader {
}); });
} }
public void cancelLoadFile(TLRPC.Video video) {
cancelLoadFile(video, null, null, null, null);
}
public void cancelLoadFile(TLRPC.Document document) { public void cancelLoadFile(TLRPC.Document document) {
cancelLoadFile(null, document, null, null, null); cancelLoadFile(document, null, null);
}
public void cancelLoadFile(TLRPC.Audio audio) {
cancelLoadFile(null, null, audio, null, null);
} }
public void cancelLoadFile(TLRPC.PhotoSize photo) { public void cancelLoadFile(TLRPC.PhotoSize photo) {
cancelLoadFile(null, null, null, photo.location, null); cancelLoadFile(null, photo.location, null);
} }
public void cancelLoadFile(TLRPC.FileLocation location, String ext) { public void cancelLoadFile(TLRPC.FileLocation location, String ext) {
cancelLoadFile(null, null, null, location, ext); cancelLoadFile(null, location, ext);
} }
private void cancelLoadFile(final TLRPC.Video video, final TLRPC.Document document, final TLRPC.Audio audio, final TLRPC.FileLocation location, final String locationExt) { private void cancelLoadFile(final TLRPC.Document document, final TLRPC.FileLocation location, final String locationExt) {
if (video == null && location == null && document == null && audio == null) { if (location == null && document == null) {
return; return;
} }
fileLoaderQueue.postRunnable(new Runnable() { fileLoaderQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
String fileName = null; String fileName = null;
if (video != null) { if (location != null) {
fileName = getAttachFileName(video);
} else if (location != null) {
fileName = getAttachFileName(location, locationExt); fileName = getAttachFileName(location, locationExt);
} else if (document != null) { } else if (document != null) {
fileName = getAttachFileName(document); fileName = getAttachFileName(document);
} else if (audio != null) {
fileName = getAttachFileName(audio);
} }
if (fileName == null) { if (fileName == null) {
return; return;
} }
FileLoadOperation operation = loadOperationPaths.get(fileName); FileLoadOperation operation = loadOperationPaths.remove(fileName);
if (operation != null) { if (operation != null) {
loadOperationPaths.remove(fileName); if (MessageObject.isVoiceDocument(document)) {
if (audio != null) {
audioLoadOperationQueue.remove(operation); audioLoadOperationQueue.remove(operation);
} else if (location != null) { } else if (location != null) {
photoLoadOperationQueue.remove(operation); photoLoadOperationQueue.remove(operation);
@ -346,39 +333,27 @@ public class FileLoader {
return result[0]; return result[0];
} }
public void loadFile(TLRPC.Video video, boolean force) {
loadFile(video, null, null, null, null, 0, force, video != null && video.key != null);
}
public void loadFile(TLRPC.PhotoSize photo, String ext, boolean cacheOnly) { public void loadFile(TLRPC.PhotoSize photo, String ext, boolean cacheOnly) {
loadFile(null, null, null, photo.location, ext, photo.size, false, cacheOnly || (photo != null && photo.size == 0 || photo.location.key != null)); loadFile(null, photo.location, ext, photo.size, false, cacheOnly || (photo != null && photo.size == 0 || photo.location.key != null));
} }
public void loadFile(TLRPC.Document document, boolean force, boolean cacheOnly) { public void loadFile(TLRPC.Document document, boolean force, boolean cacheOnly) {
loadFile(null, document, null, null, null, 0, force, cacheOnly || document != null && document.key != null); loadFile(document, null, null, 0, force, cacheOnly || document != null && document.key != null);
}
public void loadFile(TLRPC.Audio audio, boolean force) {
loadFile(null, null, audio, null, null, 0, false, audio != null && audio.key != null);
} }
public void loadFile(TLRPC.FileLocation location, String ext, int size, boolean cacheOnly) { public void loadFile(TLRPC.FileLocation location, String ext, int size, boolean cacheOnly) {
loadFile(null, null, null, location, ext, size, true, cacheOnly || size == 0 || (location != null && location.key != null)); loadFile(null, location, ext, size, true, cacheOnly || size == 0 || (location != null && location.key != null));
} }
private void loadFile(final TLRPC.Video video, final TLRPC.Document document, final TLRPC.Audio audio, final TLRPC.FileLocation location, final String locationExt, final int locationSize, final boolean force, final boolean cacheOnly) { private void loadFile(final TLRPC.Document document, final TLRPC.FileLocation location, final String locationExt, final int locationSize, final boolean force, final boolean cacheOnly) {
fileLoaderQueue.postRunnable(new Runnable() { fileLoaderQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
String fileName = null; String fileName = null;
if (video != null) { if (location != null) {
fileName = getAttachFileName(video);
} else if (location != null) {
fileName = getAttachFileName(location, locationExt); fileName = getAttachFileName(location, locationExt);
} else if (document != null) { } else if (document != null) {
fileName = getAttachFileName(document); fileName = getAttachFileName(document);
} else if (audio != null) {
fileName = getAttachFileName(audio);
} }
if (fileName == null || fileName.contains("" + Integer.MIN_VALUE)) { if (fileName == null || fileName.contains("" + Integer.MIN_VALUE)) {
return; return;
@ -389,7 +364,7 @@ public class FileLoader {
if (operation != null) { if (operation != null) {
if (force) { if (force) {
LinkedList<FileLoadOperation> downloadQueue; LinkedList<FileLoadOperation> downloadQueue;
if (audio != null) { if (MessageObject.isVoiceDocument(document)) {
downloadQueue = audioLoadOperationQueue; downloadQueue = audioLoadOperationQueue;
} else if (location != null) { } else if (location != null) {
downloadQueue = photoLoadOperationQueue; downloadQueue = photoLoadOperationQueue;
@ -412,18 +387,18 @@ public class FileLoader {
File storeDir = tempDir; File storeDir = tempDir;
int type = MEDIA_DIR_CACHE; int type = MEDIA_DIR_CACHE;
if (video != null) { if (location != null) {
operation = new FileLoadOperation(video);
type = MEDIA_DIR_VIDEO;
} else if (location != null) {
operation = new FileLoadOperation(location, locationExt, locationSize); operation = new FileLoadOperation(location, locationExt, locationSize);
type = MEDIA_DIR_IMAGE; type = MEDIA_DIR_IMAGE;
} else if (document != null) { } else if (document != null) {
operation = new FileLoadOperation(document); operation = new FileLoadOperation(document);
type = MEDIA_DIR_DOCUMENT; if (MessageObject.isVoiceDocument(document)) {
} else if (audio != null) { type = MEDIA_DIR_AUDIO;
operation = new FileLoadOperation(audio); } else if (MessageObject.isVideoDocument(document)) {
type = MEDIA_DIR_AUDIO; type = MEDIA_DIR_VIDEO;
} else {
type = MEDIA_DIR_DOCUMENT;
}
} }
if (!cacheOnly) { if (!cacheOnly) {
storeDir = getDirectory(type); storeDir = getDirectory(type);
@ -439,12 +414,12 @@ public class FileLoader {
if (delegate != null) { if (delegate != null) {
delegate.fileDidLoaded(finalFileName, finalFile, finalType); delegate.fileDidLoaded(finalFileName, finalFile, finalType);
} }
checkDownloadQueue(audio, location, finalFileName); checkDownloadQueue(document, location, finalFileName);
} }
@Override @Override
public void didFailedLoadingFile(FileLoadOperation operation, int canceled) { public void didFailedLoadingFile(FileLoadOperation operation, int canceled) {
checkDownloadQueue(audio, location, finalFileName); checkDownloadQueue(document, location, finalFileName);
if (delegate != null) { if (delegate != null) {
delegate.fileDidFailedLoad(finalFileName, canceled); delegate.fileDidFailedLoad(finalFileName, canceled);
} }
@ -458,7 +433,7 @@ public class FileLoader {
} }
}); });
int maxCount = force ? 3 : 1; int maxCount = force ? 3 : 1;
if (audio != null) { if (type == MEDIA_DIR_AUDIO) {
if (currentAudioLoadOperationsCount < maxCount) { if (currentAudioLoadOperationsCount < maxCount) {
currentAudioLoadOperationsCount++; currentAudioLoadOperationsCount++;
operation.start(); operation.start();
@ -496,13 +471,13 @@ public class FileLoader {
}); });
} }
private void checkDownloadQueue(final TLRPC.Audio audio, final TLRPC.FileLocation location, final String arg1) { private void checkDownloadQueue(final TLRPC.Document document, final TLRPC.FileLocation location, final String arg1) {
fileLoaderQueue.postRunnable(new Runnable() { fileLoaderQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
loadOperationPaths.remove(arg1); loadOperationPaths.remove(arg1);
FileLoadOperation operation; FileLoadOperation operation;
if (audio != null) { if (MessageObject.isVoiceDocument(document)) {
currentAudioLoadOperationsCount--; currentAudioLoadOperationsCount--;
if (!audioLoadOperationQueue.isEmpty()) { if (!audioLoadOperationQueue.isEmpty()) {
operation = audioLoadOperationQueue.get(0); operation = audioLoadOperationQueue.get(0);
@ -550,6 +525,44 @@ public class FileLoader {
this.delegate = delegate; this.delegate = delegate;
} }
public static String getMessageFileName(TLRPC.Message message) {
if (message == null) {
return "";
}
if (message instanceof TLRPC.TL_messageService) {
if (message.action.photo != null) {
ArrayList<TLRPC.PhotoSize> sizes = message.action.photo.sizes;
if (sizes.size() > 0) {
TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize());
if (sizeFull != null) {
return getAttachFileName(sizeFull);
}
}
}
} else {
if (message.media instanceof TLRPC.TL_messageMediaDocument) {
return getAttachFileName(message.media.document);
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
ArrayList<TLRPC.PhotoSize> sizes = message.media.photo.sizes;
if (sizes.size() > 0) {
TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize());
if (sizeFull != null) {
return getAttachFileName(sizeFull);
}
}
} else if (message.media instanceof TLRPC.TL_messageMediaWebPage && message.media.webpage.photo != null) {
ArrayList<TLRPC.PhotoSize> sizes = message.media.webpage.photo.sizes;
if (sizes.size() > 0) {
TLRPC.PhotoSize sizeFull = getClosestPhotoSizeWithSize(sizes, AndroidUtilities.getPhotoSize());
if (sizeFull != null) {
return getAttachFileName(sizeFull);
}
}
}
}
return "";
}
public static File getPathToMessage(TLRPC.Message message) { public static File getPathToMessage(TLRPC.Message message) {
if (message == null) { if (message == null) {
return new File(""); return new File("");
@ -565,12 +578,8 @@ public class FileLoader {
} }
} }
} else { } else {
if (message.media instanceof TLRPC.TL_messageMediaVideo) { if (message.media instanceof TLRPC.TL_messageMediaDocument) {
return getPathToAttach(message.media.video);
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
return getPathToAttach(message.media.document); return getPathToAttach(message.media.document);
} else if (message.media instanceof TLRPC.TL_messageMediaAudio) {
return getPathToAttach(message.media.audio);
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
ArrayList<TLRPC.PhotoSize> sizes = message.media.photo.sizes; ArrayList<TLRPC.PhotoSize> sizes = message.media.photo.sizes;
if (sizes.size() > 0) { if (sizes.size() > 0) {
@ -605,19 +614,18 @@ public class FileLoader {
if (forceCache) { if (forceCache) {
dir = getInstance().getDirectory(MEDIA_DIR_CACHE); dir = getInstance().getDirectory(MEDIA_DIR_CACHE);
} else { } else {
if (attach instanceof TLRPC.Video) { if (attach instanceof TLRPC.Document) {
TLRPC.Video video = (TLRPC.Video) attach;
if (video.key != null) {
dir = getInstance().getDirectory(MEDIA_DIR_CACHE);
} else {
dir = getInstance().getDirectory(MEDIA_DIR_VIDEO);
}
} else if (attach instanceof TLRPC.Document) {
TLRPC.Document document = (TLRPC.Document) attach; TLRPC.Document document = (TLRPC.Document) attach;
if (document.key != null) { if (document.key != null) {
dir = getInstance().getDirectory(MEDIA_DIR_CACHE); dir = getInstance().getDirectory(MEDIA_DIR_CACHE);
} else { } else {
dir = getInstance().getDirectory(MEDIA_DIR_DOCUMENT); if (MessageObject.isVoiceDocument(document)) {
dir = getInstance().getDirectory(MEDIA_DIR_AUDIO);
} else if (MessageObject.isVideoDocument(document)) {
dir = getInstance().getDirectory(MEDIA_DIR_VIDEO);
} else {
dir = getInstance().getDirectory(MEDIA_DIR_DOCUMENT);
}
} }
} else if (attach instanceof TLRPC.PhotoSize) { } else if (attach instanceof TLRPC.PhotoSize) {
TLRPC.PhotoSize photoSize = (TLRPC.PhotoSize) attach; TLRPC.PhotoSize photoSize = (TLRPC.PhotoSize) attach;
@ -626,13 +634,6 @@ public class FileLoader {
} else { } else {
dir = getInstance().getDirectory(MEDIA_DIR_IMAGE); dir = getInstance().getDirectory(MEDIA_DIR_IMAGE);
} }
} else if (attach instanceof TLRPC.Audio) {
TLRPC.Audio audio = (TLRPC.Audio) attach;
if (audio.key != null) {
dir = getInstance().getDirectory(MEDIA_DIR_CACHE);
} else {
dir = getInstance().getDirectory(MEDIA_DIR_AUDIO);
}
} else if (attach instanceof TLRPC.FileLocation) { } else if (attach instanceof TLRPC.FileLocation) {
TLRPC.FileLocation fileLocation = (TLRPC.FileLocation) attach; TLRPC.FileLocation fileLocation = (TLRPC.FileLocation) attach;
if (fileLocation.key != null || fileLocation.volume_id == Integer.MIN_VALUE && fileLocation.local_id < 0) { if (fileLocation.key != null || fileLocation.volume_id == Integer.MIN_VALUE && fileLocation.local_id < 0) {
@ -708,10 +709,7 @@ public class FileLoader {
} }
public static String getAttachFileName(TLObject attach, String ext) { public static String getAttachFileName(TLObject attach, String ext) {
if (attach instanceof TLRPC.Video) { if (attach instanceof TLRPC.Document) {
TLRPC.Video video = (TLRPC.Video) attach;
return video.dc_id + "_" + video.id + "." + (ext != null ? ext : "mp4");
} else if (attach instanceof TLRPC.Document) {
TLRPC.Document document = (TLRPC.Document) attach; TLRPC.Document document = (TLRPC.Document) attach;
String docExt = null; String docExt = null;
if (docExt == null) { if (docExt == null) {
@ -723,6 +721,23 @@ public class FileLoader {
docExt = docExt.substring(idx); docExt = docExt.substring(idx);
} }
} }
if (docExt.length() <= 1) {
if (document.mime_type != null) {
switch (document.mime_type) {
case "video/mp4":
docExt = ".mp4";
break;
case "audio/ogg":
docExt = ".ogg";
break;
default:
docExt = "";
break;
}
} else {
docExt = "";
}
}
if (docExt.length() > 1) { if (docExt.length() > 1) {
return document.dc_id + "_" + document.id + docExt; return document.dc_id + "_" + document.id + docExt;
} else { } else {
@ -734,9 +749,6 @@ public class FileLoader {
return ""; return "";
} }
return photo.location.volume_id + "_" + photo.location.local_id + "." + (ext != null ? ext : "jpg"); return photo.location.volume_id + "_" + photo.location.local_id + "." + (ext != null ? ext : "jpg");
} else if (attach instanceof TLRPC.Audio) {
TLRPC.Audio audio = (TLRPC.Audio) attach;
return audio.dc_id + "_" + audio.id + "." + (ext != null ? ext : "ogg");
} else if (attach instanceof TLRPC.FileLocation) { } else if (attach instanceof TLRPC.FileLocation) {
if (attach instanceof TLRPC.TL_fileLocationUnavailable) { if (attach instanceof TLRPC.TL_fileLocationUnavailable) {
return ""; return "";

View File

@ -1001,8 +1001,8 @@ public class ImageLoader {
} }
} }
if (imageReceiverArray.size() == 0) { if (imageReceiverArray.size() == 0) {
for (ImageReceiver receiver : imageReceiverArray) { for (int a = 0; a < imageReceiverArray.size(); a++) {
imageLoadingByTag.remove(receiver.getTag(thumb)); imageLoadingByTag.remove(imageReceiverArray.get(a).getTag(thumb));
} }
imageReceiverArray.clear(); imageReceiverArray.clear();
if (location != null) { if (location != null) {
@ -1233,18 +1233,7 @@ public class ImageLoader {
FileLog.e("tmessages", "file system changed"); FileLog.e("tmessages", "file system changed");
Runnable r = new Runnable() { Runnable r = new Runnable() {
public void run() { public void run() {
cacheOutQueue.postRunnable(new Runnable() { checkMediaPaths();
@Override
public void run() {
final HashMap<Integer, File> paths = createMediaPaths();
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
FileLoader.getInstance().setMediaDirs(paths);
}
});
}
});
} }
}; };
if (Intent.ACTION_MEDIA_UNMOUNTED.equals(intent.getAction())) { if (Intent.ACTION_MEDIA_UNMOUNTED.equals(intent.getAction())) {
@ -1285,6 +1274,10 @@ public class ImageLoader {
mediaDirs.put(FileLoader.MEDIA_DIR_CACHE, cachePath); mediaDirs.put(FileLoader.MEDIA_DIR_CACHE, cachePath);
FileLoader.getInstance().setMediaDirs(mediaDirs); FileLoader.getInstance().setMediaDirs(mediaDirs);
checkMediaPaths();
}
public void checkMediaPaths() {
cacheOutQueue.postRunnable(new Runnable() { cacheOutQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -1702,7 +1695,7 @@ public class ImageLoader {
if (thumb != 2) { if (thumb != 2) {
CacheImage img = new CacheImage(); CacheImage img = new CacheImage();
if (httpLocation != null && (httpLocation.endsWith("mp4") || httpLocation.endsWith("gif")) || imageLocation instanceof TLRPC.Document && MessageObject.isGifDocument((TLRPC.Document) imageLocation)) { if (httpLocation != null && !httpLocation.startsWith("vthumb") && !httpLocation.startsWith("thumb") && (httpLocation.endsWith("mp4") || httpLocation.endsWith("gif")) || imageLocation instanceof TLRPC.Document && MessageObject.isGifDocument((TLRPC.Document) imageLocation)) {
img.animatedFile = true; img.animatedFile = true;
} }
@ -1801,7 +1794,7 @@ public class ImageLoader {
} }
if (httpLocation != null) { if (httpLocation != null) {
key = Utilities.MD5(httpLocation); key = Utilities.MD5(httpLocation);
url = key + "." + getHttpUrlExtension(httpLocation); url = key + "." + getHttpUrlExtension(httpLocation, "jpg");
} else if (imageLocation != null) { } else if (imageLocation != null) {
if (imageLocation instanceof TLRPC.FileLocation) { if (imageLocation instanceof TLRPC.FileLocation) {
TLRPC.FileLocation location = (TLRPC.FileLocation) imageLocation; TLRPC.FileLocation location = (TLRPC.FileLocation) imageLocation;
@ -1822,7 +1815,11 @@ public class ImageLoader {
docExt = ""; docExt = "";
} else { } else {
docExt = docExt.substring(idx); docExt = docExt.substring(idx);
if (docExt.length() <= 1) { }
if (docExt.length() <= 1) {
if (document.mime_type != null && document.mime_type.equals("video/mp4")) {
docExt = ".mp4";
} else {
docExt = ""; docExt = "";
} }
} }
@ -1965,7 +1962,7 @@ public class ImageLoader {
ext = "jpg"; ext = "jpg";
} }
} }
File file = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(url) + "_temp." + ext); File file = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), Utilities.MD5(url) + "_temp." + getHttpUrlExtension(url, extension));
file.delete(); file.delete();
HttpFileTask task = new HttpFileTask(url, file, ext); HttpFileTask task = new HttpFileTask(url, file, ext);
@ -2279,14 +2276,14 @@ public class ImageLoader {
} }
} }
public static String getHttpUrlExtension(String url) { public static String getHttpUrlExtension(String url, String defaultExt) {
String ext = null; String ext = null;
int idx = url.lastIndexOf("."); int idx = url.lastIndexOf(".");
if (idx != -1) { if (idx != -1) {
ext = url.substring(idx + 1); ext = url.substring(idx + 1);
} }
if (ext == null || ext.length() == 0 || ext.length() > 4) { if (ext == null || ext.length() == 0 || ext.length() > 4) {
ext = "jpg"; ext = defaultExt;
} }
return ext; return ext;
} }
@ -2300,10 +2297,6 @@ public class ImageLoader {
break; break;
} }
} }
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
if (message.media.video.thumb instanceof TLRPC.TL_photoCachedSize) {
photoSize = message.media.video.thumb;
}
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) { } else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
if (message.media.document.thumb instanceof TLRPC.TL_photoCachedSize) { if (message.media.document.thumb instanceof TLRPC.TL_photoCachedSize) {
photoSize = message.media.document.thumb; photoSize = message.media.document.thumb;
@ -2350,8 +2343,6 @@ public class ImageLoader {
break; break;
} }
} }
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
message.media.video.thumb = newPhotoSize;
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) { } else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
message.media.document.thumb = newPhotoSize; message.media.document.thumb = newPhotoSize;
} else if (message.media instanceof TLRPC.TL_messageMediaWebPage) { } else if (message.media instanceof TLRPC.TL_messageMediaWebPage) {
@ -2369,7 +2360,8 @@ public class ImageLoader {
if (messages == null || messages.isEmpty()) { if (messages == null || messages.isEmpty()) {
return; return;
} }
for (TLRPC.Message message : messages) { for (int a = 0; a < messages.size(); a++) {
TLRPC.Message message = messages.get(a);
saveMessageThumbs(message); saveMessageThumbs(message);
} }
} }

View File

@ -138,7 +138,8 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
if ((fileLocation == null && httpUrl == null && thumbLocation == null) if ((fileLocation == null && httpUrl == null && thumbLocation == null)
|| (fileLocation != null && !(fileLocation instanceof TLRPC.TL_fileLocation) || (fileLocation != null && !(fileLocation instanceof TLRPC.TL_fileLocation)
&& !(fileLocation instanceof TLRPC.TL_fileEncryptedLocation) && !(fileLocation instanceof TLRPC.TL_fileEncryptedLocation)
&& !(fileLocation instanceof TLRPC.TL_document))) { && !(fileLocation instanceof TLRPC.TL_document)
&& !(fileLocation instanceof TLRPC.TL_documentEncrypted))) {
recycleBitmap(null, false); recycleBitmap(null, false);
recycleBitmap(null, true); recycleBitmap(null, true);
currentKey = null; currentKey = null;
@ -260,6 +261,12 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
} }
public void setOrientation(int angle, boolean center) { public void setOrientation(int angle, boolean center) {
while (angle < 0) {
angle += 360;
}
while (angle > 360) {
angle -= 360;
}
orientation = angle; orientation = angle;
centerRotation = center; centerRotation = center;
} }
@ -376,7 +383,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
} else { } else {
int bitmapW; int bitmapW;
int bitmapH; int bitmapH;
if (orientation == 90 || orientation == 270) { if (orientation % 360 == 90 || orientation % 360 == 270) {
bitmapW = bitmapDrawable.getIntrinsicHeight(); bitmapW = bitmapDrawable.getIntrinsicHeight();
bitmapH = bitmapDrawable.getIntrinsicWidth(); bitmapH = bitmapDrawable.getIntrinsicWidth();
} else { } else {
@ -413,7 +420,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.save(); canvas.save();
canvas.clipRect(imageX, imageY, imageX + imageW, imageY + imageH); canvas.clipRect(imageX, imageY, imageX + imageW, imageY + imageH);
if (orientation != 0) { if (orientation % 360 != 0) {
if (centerRotation) { if (centerRotation) {
canvas.rotate(orientation, imageW / 2, imageH / 2); canvas.rotate(orientation, imageW / 2, imageH / 2);
} else { } else {
@ -428,7 +435,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
bitmapH /= scaleW; bitmapH /= scaleW;
drawRegion.set(imageX, imageY - (bitmapH - imageH) / 2, imageX + imageW, imageY + (bitmapH + imageH) / 2); drawRegion.set(imageX, imageY - (bitmapH - imageH) / 2, imageX + imageW, imageY + (bitmapH + imageH) / 2);
} }
if (orientation == 90 || orientation == 270) { if (orientation % 360 == 90 || orientation % 360 == 270) {
int width = (drawRegion.right - drawRegion.left) / 2; int width = (drawRegion.right - drawRegion.left) / 2;
int height = (drawRegion.bottom - drawRegion.top) / 2; int height = (drawRegion.bottom - drawRegion.top) / 2;
int centerX = (drawRegion.right + drawRegion.left) / 2; int centerX = (drawRegion.right + drawRegion.left) / 2;
@ -457,7 +464,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
canvas.restore(); canvas.restore();
} else { } else {
canvas.save(); canvas.save();
if (orientation != 0) { if (orientation % 360 != 0) {
if (centerRotation) { if (centerRotation) {
canvas.rotate(orientation, imageW / 2, imageH / 2); canvas.rotate(orientation, imageW / 2, imageH / 2);
} else { } else {
@ -465,7 +472,7 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
} }
} }
drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH); drawRegion.set(imageX, imageY, imageX + imageW, imageY + imageH);
if (orientation == 90 || orientation == 270) { if (orientation % 360 == 90 || orientation % 360 == 270) {
int width = (drawRegion.right - drawRegion.left) / 2; int width = (drawRegion.right - drawRegion.left) / 2;
int height = (drawRegion.bottom - drawRegion.top) / 2; int height = (drawRegion.bottom - drawRegion.top) / 2;
int centerX = (drawRegion.right + drawRegion.left) / 2; int centerX = (drawRegion.right + drawRegion.left) / 2;
@ -597,18 +604,18 @@ public class ImageReceiver implements NotificationCenter.NotificationCenterDeleg
public int getBitmapWidth() { public int getBitmapWidth() {
if (currentImage instanceof AnimatedFileDrawable) { if (currentImage instanceof AnimatedFileDrawable) {
return orientation == 0 || orientation == 180 ? currentImage.getIntrinsicWidth() : currentImage.getIntrinsicHeight(); return orientation % 360 == 0 || orientation % 360 == 180 ? currentImage.getIntrinsicWidth() : currentImage.getIntrinsicHeight();
} }
Bitmap bitmap = getBitmap(); Bitmap bitmap = getBitmap();
return orientation == 0 || orientation == 180 ? bitmap.getWidth() : bitmap.getHeight(); return orientation % 360 == 0 || orientation % 360 == 180 ? bitmap.getWidth() : bitmap.getHeight();
} }
public int getBitmapHeight() { public int getBitmapHeight() {
if (currentImage instanceof AnimatedFileDrawable) { if (currentImage instanceof AnimatedFileDrawable) {
return orientation == 0 || orientation == 180 ? currentImage.getIntrinsicHeight() : currentImage.getIntrinsicWidth(); return orientation % 360 == 0 || orientation % 360 == 180 ? currentImage.getIntrinsicHeight() : currentImage.getIntrinsicWidth();
} }
Bitmap bitmap = getBitmap(); Bitmap bitmap = getBitmap();
return orientation == 0 || orientation == 180 ? bitmap.getHeight() : bitmap.getWidth(); return orientation % 360 == 0 || orientation % 360 == 180 ? bitmap.getHeight() : bitmap.getWidth();
} }
public void setVisible(boolean value, boolean invalidate) { public void setVisible(boolean value, boolean invalidate) {

View File

@ -700,6 +700,30 @@ public class LocaleController {
return "LOC_ERR"; return "LOC_ERR";
} }
public static String formatDateAudio(long date) {
try {
Calendar rightNow = Calendar.getInstance();
int day = rightNow.get(Calendar.DAY_OF_YEAR);
int year = rightNow.get(Calendar.YEAR);
rightNow.setTimeInMillis(date * 1000);
int dateDay = rightNow.get(Calendar.DAY_OF_YEAR);
int dateYear = rightNow.get(Calendar.YEAR);
if (dateDay == day && year == dateYear) {
return String.format("%s %s", LocaleController.getString("TodayAt", R.string.TodayAt), getInstance().formatterDay.format(new Date(date * 1000)));
} else if (dateDay + 1 == day && year == dateYear) {
return String.format("%s %s", LocaleController.getString("YesterdayAt", R.string.YesterdayAt), getInstance().formatterDay.format(new Date(date * 1000)));
} else if (year == dateYear) {
return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterMonth.format(new Date(date * 1000)), getInstance().formatterDay.format(new Date(date * 1000)));
} else {
return LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, getInstance().formatterYear.format(new Date(date * 1000)), getInstance().formatterDay.format(new Date(date * 1000)));
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return "LOC_ERR";
}
public static String formatDateOnline(long date) { public static String formatDateOnline(long date) {
try { try {
Calendar rightNow = Calendar.getInstance(); Calendar rightNow = Calendar.getInstance();

View File

@ -64,6 +64,8 @@ public class MessageObject {
public int textHeight; public int textHeight;
public int blockHeight = Integer.MAX_VALUE; public int blockHeight = Integer.MAX_VALUE;
private boolean layoutCreated;
public static Pattern urlPattern; public static Pattern urlPattern;
public static class TextLayoutBlock { public static class TextLayoutBlock {
@ -96,15 +98,18 @@ public class MessageObject {
replyMessageObject = new MessageObject(message.replyMessage, users, chats, false); replyMessageObject = new MessageObject(message.replyMessage, users, chats, false);
} }
TLRPC.User fromUser = null;
if (isFromUser()) {
if (users != null) {
fromUser = users.get(message.from_id);
}
if (fromUser == null) {
fromUser = MessagesController.getInstance().getUser(message.from_id);
}
}
if (message instanceof TLRPC.TL_messageService) { if (message instanceof TLRPC.TL_messageService) {
if (message.action != null) { if (message.action != null) {
TLRPC.User fromUser = null;
if (users != null) {
fromUser = users.get(message.from_id);
}
if (fromUser == null) {
fromUser = MessagesController.getInstance().getUser(message.from_id);
}
if (message.action instanceof TLRPC.TL_messageActionChatCreate) { if (message.action instanceof TLRPC.TL_messageActionChatCreate) {
if (isOut()) { if (isOut()) {
messageText = LocaleController.getString("ActionYouCreateGroup", R.string.ActionYouCreateGroup); messageText = LocaleController.getString("ActionYouCreateGroup", R.string.ActionYouCreateGroup);
@ -357,8 +362,10 @@ public class MessageObject {
} else if (!isMediaEmpty()) { } else if (!isMediaEmpty()) {
if (message.media instanceof TLRPC.TL_messageMediaPhoto) { if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
messageText = LocaleController.getString("AttachPhoto", R.string.AttachPhoto); messageText = LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) { } else if (isVideo()) {
messageText = LocaleController.getString("AttachVideo", R.string.AttachVideo); messageText = LocaleController.getString("AttachVideo", R.string.AttachVideo);
} else if (isVoice()) {
messageText = LocaleController.getString("AttachAudio", R.string.AttachAudio);
} else if (message.media instanceof TLRPC.TL_messageMediaGeo || message.media instanceof TLRPC.TL_messageMediaVenue) { } else if (message.media instanceof TLRPC.TL_messageMediaGeo || message.media instanceof TLRPC.TL_messageMediaVenue) {
messageText = LocaleController.getString("AttachLocation", R.string.AttachLocation); messageText = LocaleController.getString("AttachLocation", R.string.AttachLocation);
} else if (message.media instanceof TLRPC.TL_messageMediaContact) { } else if (message.media instanceof TLRPC.TL_messageMediaContact) {
@ -385,8 +392,6 @@ public class MessageObject {
messageText = LocaleController.getString("AttachDocument", R.string.AttachDocument); messageText = LocaleController.getString("AttachDocument", R.string.AttachDocument);
} }
} }
} else if (message.media instanceof TLRPC.TL_messageMediaAudio) {
messageText = LocaleController.getString("AttachAudio", R.string.AttachAudio);
} }
} else { } else {
messageText = message.message; messageText = message.message;
@ -394,9 +399,6 @@ public class MessageObject {
if (messageText == null) { if (messageText == null) {
messageText = ""; messageText = "";
} }
if (generateLayout) {
messageText = Emoji.replaceEmoji(messageText, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
}
if (message instanceof TLRPC.TL_message || message instanceof TLRPC.TL_messageForwarded_old2) { if (message instanceof TLRPC.TL_message || message instanceof TLRPC.TL_messageForwarded_old2) {
if (isMediaEmpty()) { if (isMediaEmpty()) {
@ -409,9 +411,11 @@ public class MessageObject {
} else if (message.media instanceof TLRPC.TL_messageMediaGeo || message.media instanceof TLRPC.TL_messageMediaVenue) { } else if (message.media instanceof TLRPC.TL_messageMediaGeo || message.media instanceof TLRPC.TL_messageMediaVenue) {
contentType = 1; contentType = 1;
type = 4; type = 4;
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) { } else if (isVideo()) {
contentType = 1; contentType = 1;
type = 3; type = 3;
} else if (isVoice()) {
contentType = type = 2;
} else if (message.media instanceof TLRPC.TL_messageMediaContact) { } else if (message.media instanceof TLRPC.TL_messageMediaContact) {
contentType = 3; contentType = 3;
type = 12; type = 12;
@ -433,8 +437,6 @@ public class MessageObject {
} else { } else {
type = 9; type = 9;
} }
} else if (message.media instanceof TLRPC.TL_messageMediaAudio) {
contentType = type = 2;
} }
} else if (message instanceof TLRPC.TL_messageService) { } else if (message instanceof TLRPC.TL_messageService) {
if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) { if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
@ -468,18 +470,32 @@ public class MessageObject {
//dateKey = "0_0_0"; //dateKey = "0_0_0";
} }
if (messageOwner.message != null && messageOwner.id < 0 && messageOwner.message.length() > 6 && messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { if (messageOwner.message != null && messageOwner.id < 0 && messageOwner.message.length() > 6 && isVideo()) {
videoEditedInfo = new VideoEditedInfo(); videoEditedInfo = new VideoEditedInfo();
videoEditedInfo.parseString(messageOwner.message); videoEditedInfo.parseString(messageOwner.message);
} }
generateCaption(); generateCaption();
if (generateLayout) { if (generateLayout) {
generateLayout(); messageText = Emoji.replaceEmoji(messageText, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
generateLayout(fromUser);
} }
layoutCreated = generateLayout;
generateThumbs(false); generateThumbs(false);
} }
public void checkLayout() {
if (!layoutCreated) {
layoutCreated = true;
TLRPC.User fromUser = null;
if (isFromUser()) {
fromUser = MessagesController.getInstance().getUser(messageOwner.from_id);
}
messageText = Emoji.replaceEmoji(messageText, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
generateLayout(fromUser);
}
}
public static boolean isGifDocument(TLRPC.Document document) { public static boolean isGifDocument(TLRPC.Document document) {
return document != null && document.thumb != null && document.mime_type != null && (document.mime_type.equals("image/gif") || isNewGifDocument(document)); return document != null && document.thumb != null && document.mime_type != null && (document.mime_type.equals("image/gif") || isNewGifDocument(document));
} }
@ -535,14 +551,6 @@ public class MessageObject {
} }
} }
} }
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
if (!update) {
photoThumbs = new ArrayList<>();
photoThumbs.add(messageOwner.media.video.thumb);
} else if (photoThumbs != null && !photoThumbs.isEmpty() && messageOwner.media.video.thumb != null) {
TLRPC.PhotoSize photoObject = photoThumbs.get(0);
photoObject.location = messageOwner.media.video.thumb.location;
}
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { } else if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
if (!(messageOwner.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty)) { if (!(messageOwner.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty)) {
if (!update) { if (!update) {
@ -644,12 +652,8 @@ public class MessageObject {
} }
public String getFileName() { public String getFileName() {
if (messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
return FileLoader.getAttachFileName(messageOwner.media.video);
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
return FileLoader.getAttachFileName(messageOwner.media.document); return FileLoader.getAttachFileName(messageOwner.media.document);
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
return FileLoader.getAttachFileName(messageOwner.media.audio);
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
ArrayList<TLRPC.PhotoSize> sizes = messageOwner.media.photo.sizes; ArrayList<TLRPC.PhotoSize> sizes = messageOwner.media.photo.sizes;
if (sizes.size() > 0) { if (sizes.size() > 0) {
@ -663,12 +667,12 @@ public class MessageObject {
} }
public int getFileType() { public int getFileType() {
if (messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { if (isVideo()) {
return FileLoader.MEDIA_DIR_VIDEO; return FileLoader.MEDIA_DIR_VIDEO;
} else if (isVoice()) {
return FileLoader.MEDIA_DIR_AUDIO;
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) { } else if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
return FileLoader.MEDIA_DIR_DOCUMENT; return FileLoader.MEDIA_DIR_DOCUMENT;
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
return FileLoader.MEDIA_DIR_AUDIO;
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
return FileLoader.MEDIA_DIR_IMAGE; return FileLoader.MEDIA_DIR_IMAGE;
} }
@ -772,7 +776,7 @@ public class MessageObject {
private static void addUsernamesAndHashtags(CharSequence charSequence, boolean botCommands) { private static void addUsernamesAndHashtags(CharSequence charSequence, boolean botCommands) {
try { try {
if (urlPattern == null) { if (urlPattern == null) {
urlPattern = Pattern.compile("(^|\\s)/[a-zA-Z@\\d_]{1,255}|(^|\\s)@[a-zA-Z\\d_]{3,32}|(^|\\s)#[\\w\\.]+"); urlPattern = Pattern.compile("(^|\\s)/[a-zA-Z@\\d_]{1,255}|(^|\\s)@[a-zA-Z\\d_]{1,32}|(^|\\s)#[\\w\\.]+");
} }
Matcher matcher = urlPattern.matcher(charSequence); Matcher matcher = urlPattern.matcher(charSequence);
while (matcher.find()) { while (matcher.find()) {
@ -822,7 +826,7 @@ public class MessageObject {
} }
} }
private void generateLayout() { private void generateLayout(TLRPC.User fromUser) {
if (type != 0 || messageOwner.to_id == null || messageText == null || messageText.length() == 0) { if (type != 0 || messageOwner.to_id == null || messageText == null || messageText.length() == 0) {
return; return;
} }
@ -856,6 +860,7 @@ public class MessageObject {
if (messageText instanceof Spannable) { if (messageText instanceof Spannable) {
Spannable spannable = (Spannable) messageText; Spannable spannable = (Spannable) messageText;
int count = messageOwner.entities.size(); int count = messageOwner.entities.size();
URLSpan[] spans = spannable.getSpans(0, messageText.length(), URLSpan.class);
for (int a = 0; a < count; a++) { for (int a = 0; a < count; a++) {
TLRPC.MessageEntity entity = messageOwner.entities.get(a); TLRPC.MessageEntity entity = messageOwner.entities.get(a);
if (entity.length <= 0 || entity.offset < 0 || entity.offset >= messageOwner.message.length()) { if (entity.length <= 0 || entity.offset < 0 || entity.offset >= messageOwner.message.length()) {
@ -863,6 +868,19 @@ public class MessageObject {
} else if (entity.offset + entity.length > messageOwner.message.length()) { } else if (entity.offset + entity.length > messageOwner.message.length()) {
entity.length = messageOwner.message.length() - entity.offset; entity.length = messageOwner.message.length() - entity.offset;
} }
if (spans != null && spans.length > 0) {
for (int b = 0; b < spans.length; b++) {
if (spans[b] == null) {
continue;
}
int start = spannable.getSpanStart(spans[b]);
int end = spannable.getSpanEnd(spans[b]);
if (entity.offset <= start && entity.offset + entity.length >= start || entity.offset <= end && entity.offset + entity.length >= end) {
spannable.removeSpan(spans[b]);
spans[b] = null;
}
}
}
if (entity instanceof TLRPC.TL_messageEntityBold) { if (entity instanceof TLRPC.TL_messageEntityBold) {
spannable.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), entity.offset, entity.offset + entity.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); spannable.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), entity.offset, entity.offset + entity.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else if (entity instanceof TLRPC.TL_messageEntityItalic) { } else if (entity instanceof TLRPC.TL_messageEntityItalic) {
@ -904,6 +922,9 @@ public class MessageObject {
maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(80); maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(80);
} }
} }
if (fromUser != null && fromUser.bot) {
maxWidth -= AndroidUtilities.dp(20);
}
StaticLayout textLayout; StaticLayout textLayout;
@ -1056,7 +1077,11 @@ public class MessageObject {
} }
public boolean isOutOwner() { public boolean isOutOwner() {
return messageOwner.out && messageOwner.from_id > 0; return messageOwner.out && messageOwner.from_id > 0 && !messageOwner.post;
}
public boolean isFromUser() {
return messageOwner.from_id > 0 && !messageOwner.post;
} }
public boolean isUnread() { public boolean isUnread() {
@ -1100,9 +1125,7 @@ public class MessageObject {
public boolean isSecretMedia() { public boolean isSecretMedia() {
return messageOwner instanceof TLRPC.TL_message_secret && return messageOwner instanceof TLRPC.TL_message_secret &&
(messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && messageOwner.ttl > 0 && messageOwner.ttl <= 60 || (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && messageOwner.ttl > 0 && messageOwner.ttl <= 60 || isVoice() || isVideo());
messageOwner.media instanceof TLRPC.TL_messageMediaAudio ||
messageOwner.media instanceof TLRPC.TL_messageMediaVideo);
} }
public static void setUnreadFlags(TLRPC.Message message, int flag) { public static void setUnreadFlags(TLRPC.Message message, int flag) {
@ -1128,9 +1151,15 @@ public class MessageObject {
public static boolean isImportant(TLRPC.Message message) { public static boolean isImportant(TLRPC.Message message) {
if (isMegagroup(message)) { if (isMegagroup(message)) {
return message.from_id <= 0; return message.post;
} }
return message.to_id.channel_id != 0 && (message.from_id <= 0 || message.mentioned || message.out || (message.flags & TLRPC.MESSAGE_FLAG_HAS_FROM_ID) == 0); if (message.to_id.channel_id != 0) {
if (message instanceof TLRPC.TL_message_layer47 || message instanceof TLRPC.TL_message_old7) {
return message.to_id.channel_id != 0 && (message.from_id <= 0 || message.mentioned || message.out || (message.flags & TLRPC.MESSAGE_FLAG_HAS_FROM_ID) == 0);
}
return message.post;
}
return false;
} }
public static boolean isMegagroup(TLRPC.Message message) { public static boolean isMegagroup(TLRPC.Message message) {
@ -1200,9 +1229,10 @@ public class MessageObject {
return ""; return "";
} }
public static boolean isStickerMessage(TLRPC.Message message) { public static boolean isStickerDocument(TLRPC.Document document) {
if (message.media != null && message.media.document != null) { if (document != null) {
for (TLRPC.DocumentAttribute attribute : message.media.document.attributes) { for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeSticker) { if (attribute instanceof TLRPC.TL_documentAttributeSticker) {
return true; return true;
} }
@ -1211,17 +1241,60 @@ public class MessageObject {
return false; return false;
} }
public static boolean isMusicMessage(TLRPC.Message message) { public static boolean isVoiceDocument(TLRPC.Document document) {
if (message.media != null && message.media.document != null) { if (document != null) {
for (TLRPC.DocumentAttribute attribute : message.media.document.attributes) { for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) { if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
return true; return attribute.voice;
} }
} }
} }
return false; return false;
} }
public static boolean isVideoDocument(TLRPC.Document document) {
if (document != null) {
boolean isAnimated = false;
boolean isVideo = false;
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
isVideo = true;
} else if (attribute instanceof TLRPC.TL_documentAttributeAnimated) {
isAnimated = true;
}
}
return isVideo && !isAnimated;
}
return false;
}
public static boolean isStickerMessage(TLRPC.Message message) {
return message.media != null && message.media.document != null && isStickerDocument(message.media.document);
}
public static boolean isMusicMessage(TLRPC.Message message) {
if (message.media != null && message.media.document != null) {
for (int a = 0; a < message.media.document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = message.media.document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
return !attribute.voice;
}
}
}
return false;
}
public static boolean isVoiceMessage(TLRPC.Message message) {
return message.media != null && message.media.document != null && isVoiceDocument(message.media.document);
}
public static boolean isVideoMessage(TLRPC.Message message) {
return message.media != null && message.media.document != null && isVideoDocument(message.media.document);
/* && message.media.document.mime_type.equals("video/mp4")*/
}
public static TLRPC.InputStickerSet getInputStickerSet(TLRPC.Message message) { public static TLRPC.InputStickerSet getInputStickerSet(TLRPC.Message message) {
if (message.media != null && message.media.document != null) { if (message.media != null && message.media.document != null) {
for (TLRPC.DocumentAttribute attribute : message.media.document.attributes) { for (TLRPC.DocumentAttribute attribute : message.media.document.attributes) {
@ -1339,6 +1412,14 @@ public class MessageObject {
return isMusicMessage(messageOwner); return isMusicMessage(messageOwner);
} }
public boolean isVoice() {
return isVoiceMessage(messageOwner);
}
public boolean isVideo() {
return isVideoMessage(messageOwner);
}
public boolean isGif() { public boolean isGif() {
return isGifDocument(messageOwner.media.document); return isGifDocument(messageOwner.media.document);
} }
@ -1348,8 +1429,12 @@ public class MessageObject {
} }
public String getMusicTitle() { public String getMusicTitle() {
for (TLRPC.DocumentAttribute attribute : messageOwner.media.document.attributes) { for (int a = 0; a < messageOwner.media.document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = messageOwner.media.document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) { if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
if (attribute.voice) {
return LocaleController.formatDateAudio(messageOwner.date);
}
String title = attribute.title; String title = attribute.title;
if (title == null || title.length() == 0) { if (title == null || title.length() == 0) {
title = FileLoader.getDocumentFileName(messageOwner.media.document); title = FileLoader.getDocumentFileName(messageOwner.media.document);
@ -1364,8 +1449,30 @@ public class MessageObject {
} }
public String getMusicAuthor() { public String getMusicAuthor() {
for (TLRPC.DocumentAttribute attribute : messageOwner.media.document.attributes) { for (int a = 0; a < messageOwner.media.document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = messageOwner.media.document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) { if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
if (attribute.voice) {
if (isOutOwner() || messageOwner.fwd_from != null && messageOwner.fwd_from.from_id == UserConfig.getClientUserId()) {
return LocaleController.getString("FromYou", R.string.FromYou);
}
TLRPC.User user = null;
TLRPC.Chat chat = null;
if (messageOwner.fwd_from != null && messageOwner.fwd_from.channel_id != 0) {
chat = MessagesController.getInstance().getChat(messageOwner.fwd_from.channel_id);
} else if (messageOwner.fwd_from != null && messageOwner.fwd_from.from_id != 0) {
user = MessagesController.getInstance().getUser(messageOwner.fwd_from.from_id);
} else if (messageOwner.from_id < 0) {
chat = MessagesController.getInstance().getChat(-messageOwner.from_id);
} else {
user = MessagesController.getInstance().getUser(messageOwner.from_id);
}
if (user != null) {
return UserObject.getUserName(user);
} else if (chat != null) {
return chat.title;
}
}
String performer = attribute.performer; String performer = attribute.performer;
if (performer == null || performer.length() == 0) { if (performer == null || performer.length() == 0) {
performer = LocaleController.getString("AudioUnknownArtist", R.string.AudioUnknownArtist); performer = LocaleController.getString("AudioUnknownArtist", R.string.AudioUnknownArtist);
@ -1381,11 +1488,15 @@ public class MessageObject {
} }
public boolean isForwarded() { public boolean isForwarded() {
return (messageOwner.flags & TLRPC.MESSAGE_FLAG_FWD) != 0; return isForwardedMessage(messageOwner);
}
public static boolean isForwardedMessage(TLRPC.Message message) {
return (message.flags & TLRPC.MESSAGE_FLAG_FWD) != 0;
} }
public boolean isReply() { 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; return !(replyMessageObject != null && replyMessageObject.messageOwner instanceof TLRPC.TL_messageEmpty) && (messageOwner.reply_to_msg_id != 0 || messageOwner.reply_to_random_id != 0) && (messageOwner.flags & TLRPC.MESSAGE_FLAG_REPLY) != 0;
} }
public boolean isMediaEmpty() { public boolean isMediaEmpty() {
@ -1396,6 +1507,32 @@ public class MessageObject {
return message == null || message.media == null || message.media instanceof TLRPC.TL_messageMediaEmpty || message.media instanceof TLRPC.TL_messageMediaWebPage; return message == null || message.media == null || message.media instanceof TLRPC.TL_messageMediaEmpty || message.media instanceof TLRPC.TL_messageMediaWebPage;
} }
public boolean canEditMessage(TLRPC.Chat chat) {
return canEditMessage(messageOwner, chat);
}
public static boolean canEditMessage(TLRPC.Message message, TLRPC.Chat chat) {
if (message.action != null && !(message.action instanceof TLRPC.TL_messageActionEmpty) || isForwardedMessage(message) || message.via_bot_id != 0 || message.id < 0 || Math.abs(message.date - ConnectionsManager.getInstance().getCurrentTime()) > MessagesController.getInstance().maxEditTime) {
return false;
}
if (chat == null && message.to_id.channel_id != 0) {
chat = MessagesController.getInstance().getChat(message.to_id.channel_id);
}
if (ChatObject.isChannel(chat) && chat.megagroup) {
return message.out;
}
if (ChatObject.isChannel(chat) && !chat.megagroup && (chat.creator || chat.editor && isOut(message)) && isImportant(message)) {
if (message.media instanceof TLRPC.TL_messageMediaPhoto ||
message.media instanceof TLRPC.TL_messageMediaDocument && (isVideoMessage(message) || isGifDocument(message.media.document)) ||
message.media instanceof TLRPC.TL_messageMediaEmpty ||
message.media instanceof TLRPC.TL_messageMediaWebPage ||
message.media == null) {
return true;
}
}
return false;
}
public boolean canDeleteMessage(TLRPC.Chat chat) { public boolean canDeleteMessage(TLRPC.Chat chat) {
return canDeleteMessage(messageOwner, chat); return canDeleteMessage(messageOwner, chat);
} }
@ -1414,11 +1551,11 @@ public class MessageObject {
if (chat.creator) { if (chat.creator) {
return true; return true;
} else if (chat.editor) { } else if (chat.editor) {
if (isOut(message) || message.from_id > 0) { if (isOut(message) || message.from_id > 0 && !message.post) {
return true; return true;
} }
} else if (chat.moderator) { } else if (chat.moderator) {
if (message.from_id > 0) { if (message.from_id > 0 && !message.post) {
return true; return true;
} }
} else if (isOut(message) && message.from_id > 0) { } else if (isOut(message) && message.from_id > 0) {
@ -1429,15 +1566,17 @@ public class MessageObject {
} }
public String getForwardedName() { public String getForwardedName() {
if (messageOwner.fwd_from_id instanceof TLRPC.TL_peerChannel) { if (messageOwner.fwd_from != null) {
TLRPC.Chat chat = MessagesController.getInstance().getChat(messageOwner.fwd_from_id.channel_id); if (messageOwner.fwd_from.channel_id != 0) {
if (chat != null) { TLRPC.Chat chat = MessagesController.getInstance().getChat(messageOwner.fwd_from.channel_id);
return chat.title; if (chat != null) {
} return chat.title;
} else if (messageOwner.fwd_from_id instanceof TLRPC.TL_peerUser) { }
TLRPC.User user = MessagesController.getInstance().getUser(messageOwner.fwd_from_id.user_id); } else if (messageOwner.fwd_from.from_id != 0) {
if (user != null) { TLRPC.User user = MessagesController.getInstance().getUser(messageOwner.fwd_from.from_id);
return UserObject.getUserName(user); if (user != null) {
return UserObject.getUserName(user);
}
} }
} }
return null; return null;

View File

@ -22,7 +22,6 @@ import org.telegram.messenger.query.BotQuery;
import org.telegram.messenger.query.SharedMediaQuery; import org.telegram.messenger.query.SharedMediaQuery;
import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.TLClassStore;
import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
@ -166,7 +165,7 @@ public class MessagesStorage {
database.executeFast("CREATE TABLE bot_info(uid INTEGER PRIMARY KEY, info BLOB)").stepThis().dispose(); database.executeFast("CREATE TABLE bot_info(uid INTEGER PRIMARY KEY, info BLOB)").stepThis().dispose();
//version //version
database.executeFast("PRAGMA user_version = 29").stepThis().dispose(); database.executeFast("PRAGMA user_version = 30").stepThis().dispose();
//database.executeFast("CREATE TABLE secret_holes(uid INTEGER, seq_in INTEGER, seq_out INTEGER, data BLOB, PRIMARY KEY (uid, seq_in, seq_out));").stepThis().dispose(); //database.executeFast("CREATE TABLE secret_holes(uid INTEGER, seq_in INTEGER, seq_out INTEGER, data BLOB, PRIMARY KEY (uid, seq_in, seq_out));").stepThis().dispose();
//database.executeFast("CREATE TABLE attach_data(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose(); //database.executeFast("CREATE TABLE attach_data(uid INTEGER, id INTEGER, data BLOB, PRIMARY KEY (uid, id))").stepThis().dispose();
@ -200,7 +199,7 @@ public class MessagesStorage {
} }
} }
int version = database.executeInt("PRAGMA user_version"); int version = database.executeInt("PRAGMA user_version");
if (version < 29) { if (version < 30) {
updateDbToLastVersion(version); updateDbToLastVersion(version);
} }
} }
@ -464,11 +463,6 @@ public class MessagesStorage {
database.executeFast("PRAGMA user_version = 23").stepThis().dispose(); database.executeFast("PRAGMA user_version = 23").stepThis().dispose();
version = 23; version = 23;
} }
if (version == 23) {
database.executeFast("DELETE FROM sent_files_v2 WHERE 1").stepThis().dispose();
database.executeFast("PRAGMA user_version = 24").stepThis().dispose();
version = 24;
}
if (version == 24) { if (version == 24) {
database.executeFast("DELETE FROM media_holes_v2 WHERE uid != 0 AND type >= 0 AND start IN (0, 1)").stepThis().dispose(); database.executeFast("DELETE FROM media_holes_v2 WHERE uid != 0 AND type >= 0 AND start IN (0, 1)").stepThis().dispose();
database.executeFast("PRAGMA user_version = 25").stepThis().dispose(); database.executeFast("PRAGMA user_version = 25").stepThis().dispose();
@ -487,7 +481,13 @@ public class MessagesStorage {
if (version == 28) { if (version == 28) {
database.executeFast("CREATE TABLE IF NOT EXISTS bot_recent(id INTEGER PRIMARY KEY, date INTEGER);").stepThis().dispose(); database.executeFast("CREATE TABLE IF NOT EXISTS bot_recent(id INTEGER PRIMARY KEY, date INTEGER);").stepThis().dispose();
database.executeFast("PRAGMA user_version = 29").stepThis().dispose(); database.executeFast("PRAGMA user_version = 29").stepThis().dispose();
//version = 29; version = 29;
}
if (version == 29) {
database.executeFast("DELETE FROM sent_files_v2 WHERE 1").stepThis().dispose();
database.executeFast("DELETE FROM download_queue WHERE 1").stepThis().dispose();
database.executeFast("PRAGMA user_version = 30").stepThis().dispose();
//version = 30;
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
@ -1028,27 +1028,13 @@ public class MessagesStorage {
if (message == null || message.media == null) { if (message == null || message.media == null) {
continue; continue;
} }
if (message.media instanceof TLRPC.TL_messageMediaAudio) { if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
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) { for (TLRPC.PhotoSize photoSize : message.media.photo.sizes) {
File file = FileLoader.getPathToAttach(photoSize); File file = FileLoader.getPathToAttach(photoSize);
if (file != null && file.toString().length() > 0) { if (file != null && file.toString().length() > 0) {
filesToDelete.add(file); 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) { } else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
File file = FileLoader.getPathToAttach(message.media.document); File file = FileLoader.getPathToAttach(message.media.document);
if (file != null && file.toString().length() > 0) { if (file != null && file.toString().length() > 0) {
@ -1287,6 +1273,7 @@ public class MessagesStorage {
try { try {
int minDate = Integer.MAX_VALUE; int minDate = Integer.MAX_VALUE;
SparseArray<ArrayList<Integer>> messages = new SparseArray<>(); SparseArray<ArrayList<Integer>> messages = new SparseArray<>();
final ArrayList<Long> midsArray = new ArrayList<>();
StringBuilder mids = new StringBuilder(); StringBuilder mids = new StringBuilder();
SQLiteCursor cursor; SQLiteCursor cursor;
if (random_ids == null) { if (random_ids == null) {
@ -1297,10 +1284,13 @@ public class MessagesStorage {
} }
while (cursor.next()) { while (cursor.next()) {
int ttl = cursor.intValue(1); int ttl = cursor.intValue(1);
int mid = cursor.intValue(0);
if (random_ids != null) {
midsArray.add((long) mid);
}
if (ttl <= 0) { if (ttl <= 0) {
continue; continue;
} }
int mid = cursor.intValue(0);
int date = Math.min(readTime, time) + ttl; int date = Math.min(readTime, time) + ttl;
minDate = Math.min(minDate, date); minDate = Math.min(minDate, date);
ArrayList<Integer> arr = messages.get(date); ArrayList<Integer> arr = messages.get(date);
@ -1315,15 +1305,26 @@ public class MessagesStorage {
arr.add(mid); arr.add(mid);
} }
cursor.dispose(); cursor.dispose();
if (random_ids != null) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
MessagesStorage.getInstance().markMessagesContentAsRead(midsArray);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.messagesReadContent, midsArray);
}
});
}
if (messages.size() != 0) { if (messages.size() != 0) {
database.beginTransaction(); database.beginTransaction();
SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v2 VALUES(?, ?)"); SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v2 VALUES(?, ?)");
for (int a = 0; a < messages.size(); a++) { for (int a = 0; a < messages.size(); a++) {
int key = messages.keyAt(a); int key = messages.keyAt(a);
ArrayList<Integer> arr = messages.get(key); ArrayList<Integer> arr = messages.get(key);
for (Integer mid : arr) { for (int b = 0; b < arr.size(); b++) {
state.requery(); state.requery();
state.bindInteger(1, mid); state.bindInteger(1, arr.get(b));
state.bindInteger(2, key); state.bindInteger(2, key);
state.step(); state.step();
} }
@ -2116,6 +2117,36 @@ public class MessagesStorage {
}); });
} }
public boolean checkMessageId(final long dialog_id, final int mid) {
final boolean[] result = new boolean[1];
final Semaphore semaphore = new Semaphore(0);
storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
SQLiteCursor cursor = null;
try {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages WHERE uid = %d AND mid = %d", dialog_id, mid));
if (cursor.next()) {
result[0] = true;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
if (cursor != null) {
cursor.dispose();
}
}
semaphore.release();
}
});
try {
semaphore.acquire();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return result[0];
}
public void getMessages(final long dialog_id, final int count, final int max_id, final int minDate, final int classGuid, final int load_type, final int important, final int loadIndex) { public void getMessages(final long dialog_id, final int count, final int max_id, final int minDate, final int classGuid, final int load_type, final int important, final int loadIndex) {
storageQueue.postRunnable(new Runnable() { storageQueue.postRunnable(new Runnable() {
@Override @Override
@ -2143,6 +2174,7 @@ public class MessagesStorage {
ArrayList<Integer> chatsToLoad = new ArrayList<>(); ArrayList<Integer> chatsToLoad = new ArrayList<>();
ArrayList<Long> replyMessages = new ArrayList<>(); ArrayList<Long> replyMessages = new ArrayList<>();
HashMap<Integer, ArrayList<TLRPC.Message>> replyMessageOwners = new HashMap<>(); HashMap<Integer, ArrayList<TLRPC.Message>> replyMessageOwners = new HashMap<>();
HashMap<Long, ArrayList<TLRPC.Message>> replyMessageRandomOwners = new HashMap<>();
SQLiteCursor cursor; SQLiteCursor cursor;
int lower_id = (int) dialog_id; int lower_id = (int) dialog_id;
@ -2389,7 +2421,7 @@ public class MessagesStorage {
addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad);
if (message.reply_to_msg_id != 0) { if (message.reply_to_msg_id != 0 || message.reply_to_random_id != 0) {
boolean ok = false; boolean ok = false;
if (!cursor.isNull(6)) { if (!cursor.isNull(6)) {
NativeByteBuffer data2 = new NativeByteBuffer(cursor.byteArrayLength(6)); NativeByteBuffer data2 = new NativeByteBuffer(cursor.byteArrayLength(6));
@ -2403,19 +2435,31 @@ public class MessagesStorage {
data2.reuse(); data2.reuse();
} }
if (!ok) { if (!ok) {
long messageId = message.reply_to_msg_id; if (message.reply_to_msg_id != 0) {
if (message.to_id.channel_id != 0) { long messageId = message.reply_to_msg_id;
messageId |= ((long) message.to_id.channel_id) << 32; if (message.to_id.channel_id != 0) {
messageId |= ((long) message.to_id.channel_id) << 32;
}
if (!replyMessages.contains(messageId)) {
replyMessages.add(messageId);
}
ArrayList<TLRPC.Message> 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);
} else {
if (!replyMessages.contains(message.reply_to_random_id)) {
replyMessages.add(message.reply_to_random_id);
}
ArrayList<TLRPC.Message> messages = replyMessageRandomOwners.get(message.reply_to_random_id);
if (messages == null) {
messages = new ArrayList<>();
replyMessageRandomOwners.put(message.reply_to_random_id, messages);
}
messages.add(message);
} }
if (!replyMessages.contains(messageId)) {
replyMessages.add(messageId);
}
ArrayList<TLRPC.Message> 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); message.send_state = cursor.intValue(2);
@ -2499,7 +2543,11 @@ public class MessagesStorage {
} }
if (!replyMessages.isEmpty()) { if (!replyMessages.isEmpty()) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date FROM messages WHERE mid IN(%s)", TextUtils.join(",", replyMessages))); if (!replyMessageOwners.isEmpty()) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, mid, date FROM messages WHERE mid IN(%s)", TextUtils.join(",", replyMessages)));
} else {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, m.date, r.random_id FROM randoms as r INNER JOIN messages as m ON r.mid = m.mid WHERE r.random_id IN(%s)", TextUtils.join(",", replyMessages)));
}
while (cursor.next()) { while (cursor.next()) {
NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0)); NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data) != 0) { if (data != null && cursor.byteBufferValue(0, data) != 0) {
@ -2510,16 +2558,35 @@ public class MessagesStorage {
addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad); addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad);
ArrayList<TLRPC.Message> arrayList = replyMessageOwners.get(message.id); if (!replyMessageOwners.isEmpty()) {
if (arrayList != null) { ArrayList<TLRPC.Message> arrayList = replyMessageOwners.get(message.id);
for (TLRPC.Message m : arrayList) { if (arrayList != null) {
m.replyMessage = message; for (int a = 0; a < arrayList.size(); a++) {
arrayList.get(a).replyMessage = message;
}
}
} else {
ArrayList<TLRPC.Message> arrayList = replyMessageRandomOwners.remove(cursor.longValue(3));
if (arrayList != null) {
for (int a = 0; a < arrayList.size(); a++) {
TLRPC.Message object = arrayList.get(a);
object.replyMessage = message;
object.reply_to_msg_id = message.id;
}
} }
} }
} }
data.reuse(); data.reuse();
} }
cursor.dispose(); cursor.dispose();
if (!replyMessageRandomOwners.isEmpty()) {
for (HashMap.Entry<Long, ArrayList<TLRPC.Message>> entry : replyMessageRandomOwners.entrySet()) {
ArrayList<TLRPC.Message> arrayList = entry.getValue();
for (int a = 0; a < arrayList.size(); a++) {
arrayList.get(a).reply_to_random_id = 0;
}
}
}
} }
if (!usersToLoad.isEmpty()) { if (!usersToLoad.isEmpty()) {
@ -2599,9 +2666,11 @@ public class MessagesStorage {
if (cursor.next()) { if (cursor.next()) {
NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0)); NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data) != 0) { if (data != null && cursor.byteBufferValue(0, data) != 0) {
TLObject file = TLClassStore.Instance().TLdeserialize(data, data.readInt32(false), false); TLObject file = TLRPC.MessageMedia.TLdeserialize(data, data.readInt32(false), false);
if (file != null) { if (file instanceof TLRPC.TL_messageMediaDocument) {
result.add(file); result.add(((TLRPC.TL_messageMediaDocument) file).document);
} else if (file instanceof TLRPC.TL_messageMediaPhoto) {
result.add(((TLRPC.TL_messageMediaDocument) file).photo);
} }
} }
data.reuse(); data.reuse();
@ -2634,10 +2703,23 @@ public class MessagesStorage {
try { try {
String id = Utilities.MD5(path); String id = Utilities.MD5(path);
if (id != null) { if (id != null) {
TLRPC.MessageMedia messageMedia = null;
if (file instanceof TLRPC.Photo) {
messageMedia = new TLRPC.TL_messageMediaPhoto();
messageMedia.caption = "";
messageMedia.photo = (TLRPC.Photo) file;
} else if (file instanceof TLRPC.Document) {
messageMedia = new TLRPC.TL_messageMediaDocument();
messageMedia.caption = "";
messageMedia.document = (TLRPC.Document) file;
}
if (messageMedia == null) {
return;
}
state = database.executeFast("REPLACE INTO sent_files_v2 VALUES(?, ?, ?)"); state = database.executeFast("REPLACE INTO sent_files_v2 VALUES(?, ?, ?)");
state.requery(); state.requery();
NativeByteBuffer data = new NativeByteBuffer(file.getObjectSize()); NativeByteBuffer data = new NativeByteBuffer(messageMedia.getObjectSize());
file.serializeToStream(data); messageMedia.serializeToStream(data);
state.bindString(1, id); state.bindString(1, id);
state.bindInteger(2, type); state.bindInteger(2, type);
state.bindByteBuffer(3, data); state.bindByteBuffer(3, data);
@ -2738,10 +2820,8 @@ public class MessagesStorage {
public void run() { public void run() {
SQLitePreparedStatement state = null; SQLitePreparedStatement state = null;
try { try {
if ((chat.key_hash == null || chat.key_hash.length != 16) && chat.auth_key != null) { if ((chat.key_hash == null || chat.key_hash.length < 16) && chat.auth_key != null) {
byte[] sha1 = Utilities.computeSHA1(chat.auth_key); chat.key_hash = AndroidUtilities.calcAuthKeyHash(chat.auth_key);
chat.key_hash = new byte[16];
System.arraycopy(sha1, 0, chat.key_hash, 0, chat.key_hash.length);
} }
state = database.executeFast("UPDATE enc_chats SET data = ?, g = ?, authkey = ?, ttl = ?, layer = ?, seq_in = ?, seq_out = ?, use_count = ?, exchange_id = ?, key_date = ?, fprint = ?, fauthkey = ?, khash = ? WHERE uid = ?"); state = database.executeFast("UPDATE enc_chats SET data = ?, g = ?, authkey = ?, ttl = ?, layer = ?, seq_in = ?, seq_out = ?, use_count = ?, exchange_id = ?, key_date = ?, fprint = ?, fauthkey = ?, khash = ? WHERE uid = ?");
@ -2856,10 +2936,8 @@ public class MessagesStorage {
@Override @Override
public void run() { public void run() {
try { try {
if ((chat.key_hash == null || chat.key_hash.length != 16) && chat.auth_key != null) { if ((chat.key_hash == null || chat.key_hash.length < 16) && chat.auth_key != null) {
byte[] sha1 = Utilities.computeSHA1(chat.auth_key); chat.key_hash = AndroidUtilities.calcAuthKeyHash(chat.auth_key);
chat.key_hash = new byte[16];
System.arraycopy(sha1, 0, chat.key_hash, 0, chat.key_hash.length);
} }
SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_chats VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_chats VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
NativeByteBuffer data = new NativeByteBuffer(chat.getObjectSize()); NativeByteBuffer data = new NativeByteBuffer(chat.getObjectSize());
@ -2950,7 +3028,46 @@ public class MessagesStorage {
return; return;
} }
SQLitePreparedStatement state = database.executeFast("REPLACE INTO users VALUES(?, ?, ?, ?)"); SQLitePreparedStatement state = database.executeFast("REPLACE INTO users VALUES(?, ?, ?, ?)");
for (TLRPC.User user : users) { for (int a = 0; a < users.size(); a++) {
TLRPC.User user = users.get(a);
if (user.min) {
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT data FROM users WHERE uid = %d", user.id));
if (cursor.next()) {
try {
NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data) != 0) {
TLRPC.User oldUser = TLRPC.User.TLdeserialize(data, data.readInt32(false), false);
if (user != null) {
if (user.first_name != null) {
oldUser.first_name = user.first_name;
oldUser.flags |= 2;
} else {
oldUser.first_name = null;
oldUser.flags = oldUser.flags &~ 2;
}
if (user.last_name != null) {
oldUser.last_name = user.last_name;
oldUser.flags |= 4;
} else {
oldUser.last_name = null;
oldUser.flags = oldUser.flags &~ 4;
}
if (user.photo != null) {
oldUser.photo = user.photo;
oldUser.flags |= 32;
} else {
oldUser.photo = null;
oldUser.flags = oldUser.flags &~ 32;
}
}
user = oldUser;
}
data.reuse();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}
state.requery(); state.requery();
NativeByteBuffer data = new NativeByteBuffer(user.getObjectSize()); NativeByteBuffer data = new NativeByteBuffer(user.getObjectSize());
user.serializeToStream(data); user.serializeToStream(data);
@ -2980,7 +3097,8 @@ public class MessagesStorage {
return; return;
} }
SQLitePreparedStatement state = database.executeFast("REPLACE INTO chats VALUES(?, ?, ?)"); SQLitePreparedStatement state = database.executeFast("REPLACE INTO chats VALUES(?, ?, ?)");
for (TLRPC.Chat chat : chats) { for (int a = 0; a < chats.size(); a++) {
TLRPC.Chat chat = chats.get(a);
state.requery(); state.requery();
NativeByteBuffer data = new NativeByteBuffer(chat.getObjectSize()); NativeByteBuffer data = new NativeByteBuffer(chat.getObjectSize());
chat.serializeToStream(data); chat.serializeToStream(data);
@ -3171,7 +3289,12 @@ public class MessagesStorage {
downloadObject.id = cursor.longValue(0); downloadObject.id = cursor.longValue(0);
NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(2)); NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(2));
if (data != null && cursor.byteBufferValue(2, data) != 0) { if (data != null && cursor.byteBufferValue(2, data) != 0) {
downloadObject.object = TLClassStore.Instance().TLdeserialize(data, data.readInt32(false), false); TLRPC.MessageMedia messageMedia = TLRPC.MessageMedia.TLdeserialize(data, data.readInt32(false), false);
if (messageMedia.document != null) {
downloadObject.object = messageMedia.document;
} else if (messageMedia.photo != null) {
downloadObject.object = FileLoader.getClosestPhotoSizeWithSize(messageMedia.photo.sizes, AndroidUtilities.getPhotoSize());
}
} }
data.reuse(); data.reuse();
objects.add(downloadObject); objects.add(downloadObject);
@ -3194,10 +3317,10 @@ public class MessagesStorage {
private int getMessageMediaType(TLRPC.Message message) { private int getMessageMediaType(TLRPC.Message message) {
if (message instanceof TLRPC.TL_message_secret && ( if (message instanceof TLRPC.TL_message_secret && (
message.media instanceof TLRPC.TL_messageMediaPhoto && message.ttl > 0 && message.ttl <= 60 || message.media instanceof TLRPC.TL_messageMediaPhoto && message.ttl > 0 && message.ttl <= 60 ||
message.media instanceof TLRPC.TL_messageMediaAudio || MessageObject.isVoiceMessage(message) ||
message.media instanceof TLRPC.TL_messageMediaVideo)) { MessageObject.isVideoMessage(message))) {
return 1; return 1;
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaVideo) { } else if (message.media instanceof TLRPC.TL_messageMediaPhoto || MessageObject.isVideoMessage(message)) {
return 0; return 0;
} }
return -1; return -1;
@ -3611,15 +3734,17 @@ public class MessagesStorage {
data.reuse(); data.reuse();
if ((message.to_id.channel_id == 0 || MessageObject.isImportant(message)) && message.date >= ConnectionsManager.getInstance().getCurrentTime() - 60 * 60 && downloadMask != 0) { if ((message.to_id.channel_id == 0 || MessageObject.isImportant(message)) && message.date >= ConnectionsManager.getInstance().getCurrentTime() - 60 * 60 && 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) { if (message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaDocument) {
int type = 0; int type = 0;
long id = 0; long id = 0;
TLObject object = null; TLRPC.MessageMedia object = null;
if (message.media instanceof TLRPC.TL_messageMediaAudio) { if (MessageObject.isVoiceMessage(message)) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0 && message.media.audio.size < 1024 * 1024 * 5) { if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0 && message.media.document.size < 1024 * 1024 * 5) {
id = message.media.audio.id; id = message.media.document.id;
type = MediaController.AUTODOWNLOAD_MASK_AUDIO; type = MediaController.AUTODOWNLOAD_MASK_AUDIO;
object = message.media.audio; object = new TLRPC.TL_messageMediaDocument();
object.caption = "";
object.document = message.media.document;
} }
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) { if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) {
@ -3627,20 +3752,26 @@ public class MessagesStorage {
if (photoSize != null) { if (photoSize != null) {
id = message.media.photo.id; id = message.media.photo.id;
type = MediaController.AUTODOWNLOAD_MASK_PHOTO; type = MediaController.AUTODOWNLOAD_MASK_PHOTO;
object = photoSize; object = new TLRPC.TL_messageMediaPhoto();
object.caption = "";
object.photo = message.media.photo;
} }
} }
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) { } else if (MessageObject.isVideoMessage(message)) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0) { if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0) {
id = message.media.video.id; id = message.media.document.id;
type = MediaController.AUTODOWNLOAD_MASK_VIDEO; type = MediaController.AUTODOWNLOAD_MASK_VIDEO;
object = message.media.video; object = new TLRPC.TL_messageMediaDocument();
object.caption = "";
object.document = message.media.document;
} }
} else if (message.media instanceof TLRPC.TL_messageMediaDocument && !MessageObject.isMusicMessage(message) && !MessageObject.isGifDocument(message.media.document)) { } else if (message.media instanceof TLRPC.TL_messageMediaDocument && !MessageObject.isMusicMessage(message) && !MessageObject.isGifDocument(message.media.document)) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) { if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) {
id = message.media.document.id; id = message.media.document.id;
type = MediaController.AUTODOWNLOAD_MASK_DOCUMENT; type = MediaController.AUTODOWNLOAD_MASK_DOCUMENT;
object = message.media.document; object = new TLRPC.TL_messageMediaDocument();
object.caption = "";
object.document = message.media.document;
} }
} }
if (object != null) { if (object != null) {
@ -4260,27 +4391,13 @@ public class MessagesStorage {
if (message == null || message.media == null) { if (message == null || message.media == null) {
continue; continue;
} }
if (message.media instanceof TLRPC.TL_messageMediaAudio) { if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
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) { for (TLRPC.PhotoSize photoSize : message.media.photo.sizes) {
File file = FileLoader.getPathToAttach(photoSize); File file = FileLoader.getPathToAttach(photoSize);
if (file != null && file.toString().length() > 0) { if (file != null && file.toString().length() > 0) {
filesToDelete.add(file); 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) { } else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
File file = FileLoader.getPathToAttach(message.media.document); File file = FileLoader.getPathToAttach(message.media.document);
if (file != null && file.toString().length() > 0) { if (file != null && file.toString().length() > 0) {
@ -4792,6 +4909,15 @@ public class MessagesStorage {
messageId |= ((long) channelId) << 32; messageId |= ((long) channelId) << 32;
} }
if (load_type == -2) {
SQLiteCursor cursor = database.queryFinalized(String.format(Locale.US, "SELECT mid FROM messages WHERE mid = %d", messageId));
boolean exist = cursor.next();
cursor.dispose();
if (!exist) {
continue;
}
}
if (a == 0 && createDialog) { if (a == 0 && createDialog) {
SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
state3.bindLong(1, dialog_id); state3.bindLong(1, dialog_id);
@ -4801,7 +4927,7 @@ public class MessagesStorage {
state3.bindInteger(5, message.id); state3.bindInteger(5, message.id);
state3.bindInteger(6, 0); state3.bindInteger(6, 0);
state3.bindLong(7, messageId); state3.bindLong(7, messageId);
state3.bindInteger(8, 0); state3.bindInteger(8, load_type < 0 ? message.ttl : 0);
state3.bindInteger(9, messages.pts); state3.bindInteger(9, messages.pts);
state3.bindInteger(10, message.date); state3.bindInteger(10, message.date);
state3.step(); state3.step();
@ -4809,7 +4935,7 @@ public class MessagesStorage {
} }
boolean isImportant = MessageObject.isImportant(message); boolean isImportant = MessageObject.isImportant(message);
if (load_type != -1 && important == 1) { if (load_type >= 0 && important == 1) {
if (isImportant) { if (isImportant) {
minChannelMessageId = Math.min(minChannelMessageId, message.id); minChannelMessageId = Math.min(minChannelMessageId, message.id);
maxChannelMessageId = Math.max(maxChannelMessageId, message.id); maxChannelMessageId = Math.max(maxChannelMessageId, message.id);
@ -4874,7 +5000,7 @@ public class MessagesStorage {
BotQuery.putBotKeyboard(dialog_id, botKeyboard); BotQuery.putBotKeyboard(dialog_id, botKeyboard);
} }
if (load_type != -1 && important != 0) { if (load_type >= 0 && important != 0) {
/*if ((messages.flags & 1) == 0) { /*if ((messages.flags & 1) == 0) {
if (countBeforeImportant != 0) { if (countBeforeImportant != 0) {
if (load_type == 0) { if (load_type == 0) {
@ -4979,17 +5105,17 @@ public class MessagesStorage {
if (message.media.user_id != 0 && !usersToLoad.contains(message.media.user_id)) { if (message.media.user_id != 0 && !usersToLoad.contains(message.media.user_id)) {
usersToLoad.add(message.media.user_id); usersToLoad.add(message.media.user_id);
} }
if (message.media.audio != null && message.media.audio.user_id != 0 && !usersToLoad.contains(message.media.audio.user_id)) {
usersToLoad.add(message.media.audio.user_id);
}
} }
if (message.fwd_from_id instanceof TLRPC.TL_peerUser) { if (message.fwd_from != null) {
if (!usersToLoad.contains(message.fwd_from_id.user_id)) { if (message.fwd_from.from_id != 0) {
usersToLoad.add(message.fwd_from_id.user_id); if (!usersToLoad.contains(message.fwd_from.from_id)) {
usersToLoad.add(message.fwd_from.from_id);
}
} }
} else if (message.fwd_from_id instanceof TLRPC.TL_peerChannel) { if (message.fwd_from.channel_id != 0) {
if (!chatsToLoad.contains(message.fwd_from_id.channel_id)) { if (!chatsToLoad.contains(message.fwd_from.channel_id)) {
chatsToLoad.add(message.fwd_from_id.channel_id); chatsToLoad.add(message.fwd_from.channel_id);
}
} }
} }
if (message.ttl < 0) { if (message.ttl < 0) {
@ -5010,7 +5136,7 @@ public class MessagesStorage {
usersToLoad.add(UserConfig.getClientUserId()); usersToLoad.add(UserConfig.getClientUserId());
ArrayList<Integer> chatsToLoad = new ArrayList<>(); ArrayList<Integer> chatsToLoad = new ArrayList<>();
ArrayList<Integer> encryptedToLoad = new ArrayList<>(); ArrayList<Integer> 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, m.date, d.last_mid_i, d.unread_count_i, d.pts, d.inbox_max 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, d.last_mid_i, d.unread_count_i, d.pts, d.inbox_max, d.date_i 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()) { while (cursor.next()) {
TLRPC.Dialog dialog; TLRPC.Dialog dialog;
int pts = cursor.intValue(12); int pts = cursor.intValue(12);
@ -5026,6 +5152,7 @@ public class MessagesStorage {
dialog.last_message_date = cursor.intValue(3); dialog.last_message_date = cursor.intValue(3);
dialog.pts = pts; dialog.pts = pts;
dialog.read_inbox_max_id = cursor.intValue(13); dialog.read_inbox_max_id = cursor.intValue(13);
dialog.last_message_date_i = cursor.intValue(14);
dialog.top_not_important_message = cursor.intValue(10); dialog.top_not_important_message = cursor.intValue(10);
dialog.unread_not_important_count = cursor.intValue(11); dialog.unread_not_important_count = cursor.intValue(11);
long flags = cursor.longValue(8); long flags = cursor.longValue(8);

View File

@ -21,15 +21,13 @@ import android.media.RemoteControlClient;
import android.os.Build; import android.os.Build;
import android.os.IBinder; import android.os.IBinder;
import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View; import android.view.View;
import android.widget.RemoteViews; import android.widget.RemoteViews;
import org.telegram.messenger.audioinfo.AudioInfo; import org.telegram.messenger.audioinfo.AudioInfo;
import org.telegram.ui.LaunchActivity; import org.telegram.ui.LaunchActivity;
public class MusicPlayerService extends Service implements AudioManager.OnAudioFocusChangeListener, NotificationCenter.NotificationCenterDelegate { public class MusicPlayerService extends Service implements NotificationCenter.NotificationCenterDelegate {
public static final String NOTIFY_PREVIOUS = "org.telegram.android.musicplayer.previous"; public static final String NOTIFY_PREVIOUS = "org.telegram.android.musicplayer.previous";
public static final String NOTIFY_CLOSE = "org.telegram.android.musicplayer.close"; public static final String NOTIFY_CLOSE = "org.telegram.android.musicplayer.close";
@ -39,8 +37,6 @@ public class MusicPlayerService extends Service implements AudioManager.OnAudioF
private RemoteControlClient remoteControlClient; private RemoteControlClient remoteControlClient;
private AudioManager audioManager; private AudioManager audioManager;
private static boolean ignoreAudioFocus = false;
private PhoneStateListener phoneStateListener;
private static boolean supportBigNotifications = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN; private static boolean supportBigNotifications = Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
private static boolean supportLockScreenControls = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH; private static boolean supportLockScreenControls = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
@ -55,29 +51,6 @@ public class MusicPlayerService extends Service implements AudioManager.OnAudioF
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged); NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioPlayStateChanged); NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioPlayStateChanged);
try {
phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
if (MediaController.getInstance().isPlayingAudio(MediaController.getInstance().getPlayingMessageObject()) && !MediaController.getInstance().isAudioPaused()) {
MediaController.getInstance().pauseAudio(MediaController.getInstance().getPlayingMessageObject());
}
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
super.onCreate(); super.onCreate();
} }
@ -220,7 +193,6 @@ public class MusicPlayerService extends Service implements AudioManager.OnAudioF
metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, audioInfo.getCover()); metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, audioInfo.getCover());
} }
metadataEditor.apply(); metadataEditor.apply();
audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
} }
} }
@ -246,35 +218,11 @@ public class MusicPlayerService extends Service implements AudioManager.OnAudioF
metadataEditor.clear(); metadataEditor.clear();
metadataEditor.apply(); metadataEditor.apply();
audioManager.unregisterRemoteControlClient(remoteControlClient); audioManager.unregisterRemoteControlClient(remoteControlClient);
audioManager.abandonAudioFocus(this);
}
try {
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioProgressDidChanged); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioProgressDidChanged);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioPlayStateChanged); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioPlayStateChanged);
} }
@Override
public void onAudioFocusChange(int focusChange) {
if (ignoreAudioFocus) {
ignoreAudioFocus = false;
return;
}
if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
if (MediaController.getInstance().isPlayingAudio(MediaController.getInstance().getPlayingMessageObject()) && !MediaController.getInstance().isAudioPaused()) {
MediaController.getInstance().pauseAudio(MediaController.getInstance().getPlayingMessageObject());
}
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
//MediaController.getInstance().playAudio(MediaController.getInstance().getPlayingMessageObject());
}
}
@Override @Override
public void didReceivedNotification(int id, Object... args) { public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.audioPlayStateChanged) { if (id == NotificationCenter.audioPlayStateChanged) {
@ -286,8 +234,4 @@ public class MusicPlayerService extends Service implements AudioManager.OnAudioF
} }
} }
} }
public static void setIgnoreAudioFocus() {
ignoreAudioFocus = true;
}
} }

View File

@ -23,7 +23,7 @@ import java.util.zip.ZipFile;
public class NativeLoader { public class NativeLoader {
private final static int LIB_VERSION = 17; private final static int LIB_VERSION = 19;
private final static String LIB_NAME = "tmessages." + LIB_VERSION; private final static String LIB_NAME = "tmessages." + LIB_VERSION;
private final static String LIB_SO_NAME = "lib" + LIB_NAME + ".so"; private final static String LIB_SO_NAME = "lib" + LIB_NAME + ".so";
private final static String LOCALE_LIB_SO_NAME = "lib" + LIB_NAME + "loc.so"; private final static String LOCALE_LIB_SO_NAME = "lib" + LIB_NAME + "loc.so";

View File

@ -77,6 +77,7 @@ public class NotificationCenter {
public static final int closeOtherAppActivities = totalEvents++; public static final int closeOtherAppActivities = totalEvents++;
public static final int didUpdatedConnectionState = totalEvents++; public static final int didUpdatedConnectionState = totalEvents++;
public static final int didReceiveSmsCode = totalEvents++; public static final int didReceiveSmsCode = totalEvents++;
public static final int didReceiveCall = totalEvents++;
public static final int emojiDidLoaded = totalEvents++; public static final int emojiDidLoaded = totalEvents++;
public static final int appDidLogout = totalEvents++; public static final int appDidLogout = totalEvents++;

View File

@ -78,8 +78,10 @@ public class NotificationsController {
private SoundPool soundPool; private SoundPool soundPool;
private int soundIn; private int soundIn;
private int soundOut; private int soundOut;
private int soundRecord;
private boolean soundInLoaded; private boolean soundInLoaded;
private boolean soundOutLoaded; private boolean soundOutLoaded;
private boolean soundRecordLoaded;
protected AudioManager audioManager; protected AudioManager audioManager;
private AlarmManager alarmManager; private AlarmManager alarmManager;
@ -681,7 +683,11 @@ public class NotificationsController {
int chat_id = messageObject.messageOwner.to_id.chat_id != 0 ? messageObject.messageOwner.to_id.chat_id : messageObject.messageOwner.to_id.channel_id; int chat_id = messageObject.messageOwner.to_id.chat_id != 0 ? messageObject.messageOwner.to_id.chat_id : messageObject.messageOwner.to_id.channel_id;
int from_id = messageObject.messageOwner.to_id.user_id; int from_id = messageObject.messageOwner.to_id.user_id;
if (from_id == 0) { if (from_id == 0) {
from_id = messageObject.messageOwner.from_id; if (messageObject.isFromUser()) {
from_id = messageObject.messageOwner.from_id;
} else {
from_id = -chat_id;
}
} else if (from_id == UserConfig.getClientUserId()) { } else if (from_id == UserConfig.getClientUserId()) {
from_id = messageObject.messageOwner.from_id; from_id = messageObject.messageOwner.from_id;
} }
@ -747,8 +753,10 @@ public class NotificationsController {
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
msg = LocaleController.formatString("NotificationMessagePhoto", R.string.NotificationMessagePhoto, name); msg = LocaleController.formatString("NotificationMessagePhoto", R.string.NotificationMessagePhoto, name);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { } else if (messageObject.isVideo()) {
msg = LocaleController.formatString("NotificationMessageVideo", R.string.NotificationMessageVideo, name); msg = LocaleController.formatString("NotificationMessageVideo", R.string.NotificationMessageVideo, name);
} else if (messageObject.isVoice()) {
msg = LocaleController.formatString("NotificationMessageAudio", R.string.NotificationMessageAudio, name);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
msg = LocaleController.formatString("NotificationMessageContact", R.string.NotificationMessageContact, name); msg = LocaleController.formatString("NotificationMessageContact", R.string.NotificationMessageContact, name);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
@ -761,8 +769,6 @@ public class NotificationsController {
} else { } else {
msg = LocaleController.formatString("NotificationMessageDocument", R.string.NotificationMessageDocument, name); msg = LocaleController.formatString("NotificationMessageDocument", R.string.NotificationMessageDocument, name);
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
msg = LocaleController.formatString("NotificationMessageAudio", R.string.NotificationMessageAudio, name);
} }
} }
} else { } else {
@ -857,8 +863,10 @@ public class NotificationsController {
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
msg = LocaleController.formatString("ChannelMessagePhoto", R.string.ChannelMessagePhoto, name, chat.title); msg = LocaleController.formatString("ChannelMessagePhoto", R.string.ChannelMessagePhoto, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { } else if (messageObject.isVideo()) {
msg = LocaleController.formatString("ChannelMessageVideo", R.string.ChannelMessageVideo, name, chat.title); msg = LocaleController.formatString("ChannelMessageVideo", R.string.ChannelMessageVideo, name, chat.title);
} else if (messageObject.isVoice()) {
msg = LocaleController.formatString("ChannelMessageAudio", R.string.ChannelMessageAudio, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
msg = LocaleController.formatString("ChannelMessageContact", R.string.ChannelMessageContact, name, chat.title); msg = LocaleController.formatString("ChannelMessageContact", R.string.ChannelMessageContact, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
@ -871,8 +879,6 @@ public class NotificationsController {
} else { } else {
msg = LocaleController.formatString("ChannelMessageDocument", R.string.ChannelMessageDocument, name, chat.title); msg = LocaleController.formatString("ChannelMessageDocument", R.string.ChannelMessageDocument, name, chat.title);
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
msg = LocaleController.formatString("ChannelMessageAudio", R.string.ChannelMessageAudio, name, chat.title);
} }
} else { } else {
if (messageObject.isMediaEmpty()) { if (messageObject.isMediaEmpty()) {
@ -883,8 +889,10 @@ public class NotificationsController {
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
msg = LocaleController.formatString("ChannelMessageGroupPhoto", R.string.ChannelMessageGroupPhoto, name, chat.title); msg = LocaleController.formatString("ChannelMessageGroupPhoto", R.string.ChannelMessageGroupPhoto, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { } else if (messageObject.isVideo()) {
msg = LocaleController.formatString("ChannelMessageGroupVideo", R.string.ChannelMessageGroupVideo, name, chat.title); msg = LocaleController.formatString("ChannelMessageGroupVideo", R.string.ChannelMessageGroupVideo, name, chat.title);
} else if (messageObject.isVoice()) {
msg = LocaleController.formatString("ChannelMessageGroupAudio", R.string.ChannelMessageGroupAudio, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
msg = LocaleController.formatString("ChannelMessageGroupContact", R.string.ChannelMessageGroupContact, name, chat.title); msg = LocaleController.formatString("ChannelMessageGroupContact", R.string.ChannelMessageGroupContact, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
@ -897,8 +905,6 @@ public class NotificationsController {
} else { } else {
msg = LocaleController.formatString("ChannelMessageGroupDocument", R.string.ChannelMessageGroupDocument, name, chat.title); msg = LocaleController.formatString("ChannelMessageGroupDocument", R.string.ChannelMessageGroupDocument, name, chat.title);
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
msg = LocaleController.formatString("ChannelMessageGroupAudio", R.string.ChannelMessageGroupAudio, name, chat.title);
} }
} }
} else { } else {
@ -910,8 +916,10 @@ public class NotificationsController {
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
msg = LocaleController.formatString("NotificationMessageGroupPhoto", R.string.NotificationMessageGroupPhoto, name, chat.title); msg = LocaleController.formatString("NotificationMessageGroupPhoto", R.string.NotificationMessageGroupPhoto, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { } else if (messageObject.isVideo()) {
msg = LocaleController.formatString("NotificationMessageGroupVideo", R.string.NotificationMessageGroupVideo, name, chat.title); msg = LocaleController.formatString("NotificationMessageGroupVideo", R.string.NotificationMessageGroupVideo, name, chat.title);
} else if (messageObject.isVoice()) {
msg = LocaleController.formatString("NotificationMessageGroupAudio", R.string.NotificationMessageGroupAudio, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
msg = LocaleController.formatString("NotificationMessageGroupContact", R.string.NotificationMessageGroupContact, name, chat.title); msg = LocaleController.formatString("NotificationMessageGroupContact", R.string.NotificationMessageGroupContact, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) { } else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
@ -924,13 +932,15 @@ public class NotificationsController {
} else { } else {
msg = LocaleController.formatString("NotificationMessageGroupDocument", R.string.NotificationMessageGroupDocument, name, chat.title); msg = LocaleController.formatString("NotificationMessageGroupDocument", R.string.NotificationMessageGroupDocument, name, chat.title);
} }
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaAudio) {
msg = LocaleController.formatString("NotificationMessageGroupAudio", R.string.NotificationMessageGroupAudio, name, chat.title);
} }
} }
} }
} else { } else {
msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, name, chat.title); if (ChatObject.isChannel(chat) && !chat.megagroup) {
msg = LocaleController.formatString("ChannelMessageNoText", R.string.ChannelMessageNoText, name, chat.title);
} else {
msg = LocaleController.formatString("NotificationMessageGroupNoText", R.string.NotificationMessageGroupNoText, name, chat.title);
}
} }
} }
} }
@ -1012,8 +1022,45 @@ public class NotificationsController {
} }
} }
/*public void playRecordSound() {
try {
if (audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT) {
return;
}
notificationsQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
if (soundPool == null) {
soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
if (status == 0) {
soundPool.play(sampleId, 1.0f, 1.0f, 1, 0, 1.0f);
}
}
});
}
if (soundRecord == 0 && !soundRecordLoaded) {
soundRecordLoaded = true;
soundRecord = soundPool.load(ApplicationLoader.applicationContext, R.raw.sound_record, 1);
}
if (soundRecord != 0) {
soundPool.play(soundRecord, 1.0f, 1.0f, 1, 0, 1.0f);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}*/
private void playInChatSound() { private void playInChatSound() {
if (!inChatSoundEnabled) { if (!inChatSoundEnabled || MediaController.getInstance().isRecordingAudio()) {
return; return;
} }
try { try {
@ -1038,7 +1085,7 @@ public class NotificationsController {
} }
try { try {
if (soundPool == null) { if (soundPool == null) {
soundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 0); soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override @Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
@ -1298,26 +1345,17 @@ public class NotificationsController {
.setGroupSummary(true) .setGroupSummary(true)
.setColor(0xff2ca5e0); .setColor(0xff2ca5e0);
if (!notifyAboutLast) {
mBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
} else {
if (priority == 0) {
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
} else if (priority == 1) {
mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
} else if (priority == 2) {
mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
}
}
mBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE); mBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE);
if (chat == null && user != null && user.phone != null && user.phone.length() > 0) { if (chat == null && user != null && user.phone != null && user.phone.length() > 0) {
mBuilder.addPerson("tel:+" + user.phone); mBuilder.addPerson("tel:+" + user.phone);
} }
int silent = 2;
String lastMessage = null; String lastMessage = null;
if (pushMessages.size() == 1) { if (pushMessages.size() == 1) {
String message = lastMessage = getStringForMessage(pushMessages.get(0), false); MessageObject messageObject = pushMessages.get(0);
String message = lastMessage = getStringForMessage(messageObject, false);
silent = messageObject.messageOwner.silent ? 1 : 0;
if (message == null) { if (message == null) {
return; return;
} }
@ -1336,12 +1374,14 @@ public class NotificationsController {
inboxStyle.setBigContentTitle(name); inboxStyle.setBigContentTitle(name);
int count = Math.min(10, pushMessages.size()); int count = Math.min(10, pushMessages.size());
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
String message = getStringForMessage(pushMessages.get(i), false); MessageObject messageObject = pushMessages.get(i);
String message = getStringForMessage(messageObject, false);
if (message == null) { if (message == null) {
continue; continue;
} }
if (i == 0) { if (silent == 2) {
lastMessage = message; lastMessage = message;
silent = messageObject.messageOwner.silent ? 1 : 0;
} }
if (pushDialogs.size() == 1) { if (pushDialogs.size() == 1) {
if (replace) { if (replace) {
@ -1365,29 +1405,44 @@ public class NotificationsController {
} }
} }
if (!notifyDisabled) { if (silent == 1) {
FileLog.e("tmessages", "don't notify " + lastMessage);
} else {
FileLog.e("tmessages", "notify" + lastMessage);
}
if (!notifyAboutLast || silent == 1) {
mBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
} else {
if (priority == 0) {
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
} else if (priority == 1) {
mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
} else if (priority == 2) {
mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
}
}
if (silent != 1 && !notifyDisabled) {
if (ApplicationLoader.mainInterfacePaused || inAppPreview) { if (ApplicationLoader.mainInterfacePaused || inAppPreview) {
if (lastMessage.length() > 100) { if (lastMessage.length() > 100) {
lastMessage = lastMessage.substring(0, 100).replace("\n", " ").trim() + "..."; lastMessage = lastMessage.substring(0, 100).replace("\n", " ").trim() + "...";
} }
mBuilder.setTicker(lastMessage); mBuilder.setTicker(lastMessage);
} }
if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) { if (!MediaController.getInstance().isRecordingAudio()) {
if (choosenSoundPath.equals(defaultPath)) { if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
/*MediaPlayer mediaPlayer = new MediaPlayer(); if (choosenSoundPath.equals(defaultPath)) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION);
mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI); } else {
mediaPlayer.prepare(); mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION);
mediaPlayer.start();*/ }
mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION);
} else {
mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION);
} }
} }
if (ledColor != 0) { if (ledColor != 0) {
mBuilder.setLights(ledColor, 1000, 1000); mBuilder.setLights(ledColor, 1000, 1000);
} }
if (needVibrate == 2) { if (needVibrate == 2 || MediaController.getInstance().isRecordingAudio()) {
mBuilder.setVibrate(new long[]{0, 0}); mBuilder.setVibrate(new long[]{0, 0});
} else if (needVibrate == 1) { } else if (needVibrate == 1) {
mBuilder.setVibrate(new long[]{0, 100, 0, 100}); mBuilder.setVibrate(new long[]{0, 100, 0, 100});
@ -1597,7 +1652,7 @@ public class NotificationsController {
} }
public void playOutChatSound() { public void playOutChatSound() {
if (!inChatSoundEnabled) { if (!inChatSoundEnabled || MediaController.getInstance().isRecordingAudio()) {
return; return;
} }
try { try {
@ -1616,7 +1671,7 @@ public class NotificationsController {
} }
lastSoundOutPlay = System.currentTimeMillis(); lastSoundOutPlay = System.currentTimeMillis();
if (soundPool == null) { if (soundPool == null) {
soundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 0); soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override @Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
@ -1642,14 +1697,13 @@ public class NotificationsController {
public static void updateServerNotificationsSettings(long dialog_id) { public static void updateServerNotificationsSettings(long dialog_id) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.notificationsSettingsUpdated); NotificationCenter.getInstance().postNotificationName(NotificationCenter.notificationsSettingsUpdated);
if ((int)dialog_id == 0) { if ((int) dialog_id == 0) {
return; return;
} }
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings(); TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings();
req.settings = new TLRPC.TL_inputPeerNotifySettings(); req.settings = new TLRPC.TL_inputPeerNotifySettings();
req.settings.sound = "default"; req.settings.sound = "default";
req.settings.events_mask = 0;
int mute_type = preferences.getInt("notify2_" + dialog_id, 0); int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
if (mute_type == 3) { if (mute_type == 3) {
req.settings.mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0); req.settings.mute_until = preferences.getInt("notifyuntil_" + dialog_id, 0);
@ -1657,14 +1711,9 @@ public class NotificationsController {
req.settings.mute_until = mute_type != 2 ? 0 : Integer.MAX_VALUE; req.settings.mute_until = mute_type != 2 ? 0 : Integer.MAX_VALUE;
} }
req.settings.show_previews = preferences.getBoolean("preview_" + dialog_id, true); req.settings.show_previews = preferences.getBoolean("preview_" + dialog_id, true);
req.settings.silent = preferences.getBoolean("silent_" + dialog_id, false);
req.peer = new TLRPC.TL_inputNotifyPeer(); req.peer = new TLRPC.TL_inputNotifyPeer();
((TLRPC.TL_inputNotifyPeer) req.peer).peer = MessagesController.getInputPeer((int) dialog_id);
((TLRPC.TL_inputNotifyPeer)req.peer).peer = MessagesController.getInputPeer((int) dialog_id);
if (((TLRPC.TL_inputNotifyPeer)req.peer).peer == null) {
return;
}
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {

View File

@ -39,7 +39,7 @@ public class UserConfig {
public static int lastPauseTime = 0; public static int lastPauseTime = 0;
public static boolean isWaitingForPasscodeEnter = false; public static boolean isWaitingForPasscodeEnter = false;
public static boolean useFingerprint = true; public static boolean useFingerprint = true;
public static int lastUpdateVersion; public static String lastUpdateVersion;
public static int lastContactsSyncTime; public static int lastContactsSyncTime;
public static int migrateOffsetId = -1; public static int migrateOffsetId = -1;
@ -83,7 +83,7 @@ public class UserConfig {
editor.putInt("passcodeType", passcodeType); editor.putInt("passcodeType", passcodeType);
editor.putInt("autoLockIn", autoLockIn); editor.putInt("autoLockIn", autoLockIn);
editor.putInt("lastPauseTime", lastPauseTime); editor.putInt("lastPauseTime", lastPauseTime);
editor.putInt("lastUpdateVersion", lastUpdateVersion); editor.putString("lastUpdateVersion2", lastUpdateVersion);
editor.putInt("lastContactsSyncTime", lastContactsSyncTime); editor.putInt("lastContactsSyncTime", lastContactsSyncTime);
editor.putBoolean("useFingerprint", useFingerprint); editor.putBoolean("useFingerprint", useFingerprint);
@ -224,7 +224,7 @@ public class UserConfig {
autoLockIn = preferences.getInt("autoLockIn", 60 * 60); autoLockIn = preferences.getInt("autoLockIn", 60 * 60);
lastPauseTime = preferences.getInt("lastPauseTime", 0); lastPauseTime = preferences.getInt("lastPauseTime", 0);
useFingerprint = preferences.getBoolean("useFingerprint", true); useFingerprint = preferences.getBoolean("useFingerprint", true);
lastUpdateVersion = preferences.getInt("lastUpdateVersion", 511); lastUpdateVersion = preferences.getString("lastUpdateVersion2", "3.5");
lastContactsSyncTime = preferences.getInt("lastContactsSyncTime", (int) (System.currentTimeMillis() / 1000) - 23 * 60 * 60); lastContactsSyncTime = preferences.getInt("lastContactsSyncTime", (int) (System.currentTimeMillis() / 1000) - 23 * 60 * 60);
migrateOffsetId = preferences.getInt("migrateOffsetId", 0); migrateOffsetId = preferences.getInt("migrateOffsetId", 0);
@ -314,7 +314,7 @@ public class UserConfig {
lastPauseTime = 0; lastPauseTime = 0;
useFingerprint = true; useFingerprint = true;
isWaitingForPasscodeEnter = false; isWaitingForPasscodeEnter = false;
lastUpdateVersion = BuildVars.BUILD_VERSION; lastUpdateVersion = BuildVars.BUILD_VERSION_STRING;
lastContactsSyncTime = (int) (System.currentTimeMillis() / 1000) - 23 * 60 * 60; lastContactsSyncTime = (int) (System.currentTimeMillis() / 1000) - 23 * 60 * 60;
saveConfig(true); saveConfig(true);
} }

View File

@ -53,6 +53,7 @@ public class Utilities {
public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin); public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin);
public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap); public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap);
private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
public native static String readlink(String path);
public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);

View File

@ -156,7 +156,7 @@ public class ID3v2Info extends AudioInfo {
smallCover = cover; smallCover = cover;
} }
} }
} catch (Exception e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
} }
coverPictureType = picture.type; coverPictureType = picture.type;

View File

@ -60,6 +60,9 @@ public class MessagesSearchQuery {
lastReturnedNum--; lastReturnedNum--;
return; return;
} }
if (searchResultMessages.isEmpty()) {
return;
}
query = lastSearchQuery; query = lastSearchQuery;
MessageObject messageObject = searchResultMessages.get(searchResultMessages.size() - 1); MessageObject messageObject = searchResultMessages.get(searchResultMessages.size() - 1);
if (messageObject.getDialogId() == dialog_id && !messagesSearchEndReached[0]) { if (messageObject.getDialogId() == dialog_id && !messagesSearchEndReached[0]) {

View File

@ -32,111 +32,188 @@ import java.util.Locale;
public class ReplyMessageQuery { public class ReplyMessageQuery {
public static void loadReplyMessagesForMessages(final ArrayList<MessageObject> messages, final long dialog_id) { public static void loadReplyMessagesForMessages(final ArrayList<MessageObject> messages, final long dialog_id) {
final ArrayList<Integer> replyMessages = new ArrayList<>(); if ((int) dialog_id == 0) {
final HashMap<Integer, ArrayList<MessageObject>> replyMessageOwners = new HashMap<>(); final ArrayList<Long> replyMessages = new ArrayList<>();
final StringBuilder stringBuilder = new StringBuilder(); final HashMap<Long, ArrayList<MessageObject>> replyMessageRandomOwners = new HashMap<>();
int channelId = 0; final StringBuilder stringBuilder = new StringBuilder();
for (MessageObject messageObject : messages) { for (int a = 0; a < messages.size(); a++) {
if (messageObject.getId() > 0 && messageObject.isReply() && messageObject.replyMessageObject == null) { MessageObject messageObject = messages.get(a);
Integer id = messageObject.messageOwner.reply_to_msg_id; if (messageObject.isReply() && messageObject.replyMessageObject == null) {
long messageId = id; Long id = messageObject.messageOwner.reply_to_random_id;
if (messageObject.messageOwner.to_id.channel_id != 0) { if (stringBuilder.length() > 0) {
messageId |= ((long) messageObject.messageOwner.to_id.channel_id) << 32; stringBuilder.append(',');
channelId = messageObject.messageOwner.to_id.channel_id; }
} stringBuilder.append(id);
if (stringBuilder.length() > 0) { ArrayList<MessageObject> messageObjects = replyMessageRandomOwners.get(id);
stringBuilder.append(','); if (messageObjects == null) {
} messageObjects = new ArrayList<>();
stringBuilder.append(messageId); replyMessageRandomOwners.put(id, messageObjects);
ArrayList<MessageObject> messageObjects = replyMessageOwners.get(id); }
if (messageObjects == null) { messageObjects.add(messageObject);
messageObjects = new ArrayList<>(); if (!replyMessages.contains(id)) {
replyMessageOwners.put(id, messageObjects); replyMessages.add(id);
} }
messageObjects.add(messageObject);
if (!replyMessages.contains(id)) {
replyMessages.add(id);
} }
} }
} if (replyMessages.isEmpty()) {
if (replyMessages.isEmpty()) { return;
return; }
}
final int channelIdFinal = channelId; MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override
@Override public void run() {
public void run() { try {
try { SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT m.data, m.mid, m.date, r.random_id FROM randoms as r INNER JOIN messages as m ON r.mid = m.mid WHERE r.random_id IN(%s)", TextUtils.join(",", replyMessages)));
final ArrayList<TLRPC.Message> result = new ArrayList<>(); while (cursor.next()) {
final ArrayList<TLRPC.User> users = new ArrayList<>(); NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0));
final ArrayList<TLRPC.Chat> chats = new ArrayList<>(); if (data != null && cursor.byteBufferValue(0, data) != 0) {
ArrayList<Integer> usersToLoad = new ArrayList<>(); TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
ArrayList<Integer> chatsToLoad = new ArrayList<>(); message.id = cursor.intValue(1);
message.date = cursor.intValue(2);
message.dialog_id = dialog_id;
SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid, date FROM messages WHERE mid IN(%s)", stringBuilder.toString()));
while (cursor.next()) {
NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data) != 0) {
TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
message.id = cursor.intValue(1);
message.date = cursor.intValue(2);
message.dialog_id = dialog_id;
MessagesStorage.addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad);
result.add(message);
replyMessages.remove((Integer) message.id);
}
data.reuse();
}
cursor.dispose();
if (!usersToLoad.isEmpty()) { ArrayList<MessageObject> arrayList = replyMessageRandomOwners.remove(cursor.longValue(3));
MessagesStorage.getInstance().getUsersInternal(TextUtils.join(",", usersToLoad), users); if (arrayList != null) {
} MessageObject messageObject = new MessageObject(message, null, null, false);
if (!chatsToLoad.isEmpty()) { for (int b = 0; b < arrayList.size(); b++) {
MessagesStorage.getInstance().getChatsInternal(TextUtils.join(",", chatsToLoad), chats); MessageObject object = arrayList.get(b);
} object.replyMessageObject = messageObject;
broadcastReplyMessages(result, replyMessageOwners, users, chats, dialog_id, true); object.messageOwner.reply_to_msg_id = messageObject.getId();
if (!replyMessages.isEmpty()) {
if (channelIdFinal != 0) {
final TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages();
req.channel = MessagesController.getInputChannel(channelIdFinal);
req.id = replyMessages;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response;
ImageLoader.saveMessagesThumbs(messagesRes.messages);
broadcastReplyMessages(messagesRes.messages, replyMessageOwners, messagesRes.users, messagesRes.chats, dialog_id, false);
MessagesStorage.getInstance().putUsersAndChats(messagesRes.users, messagesRes.chats, true, true);
saveReplyMessages(replyMessageOwners, messagesRes.messages);
} }
} }
}); }
} else { data.reuse();
TLRPC.TL_messages_getMessages req = new TLRPC.TL_messages_getMessages();
req.id = replyMessages;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response;
ImageLoader.saveMessagesThumbs(messagesRes.messages);
broadcastReplyMessages(messagesRes.messages, replyMessageOwners, messagesRes.users, messagesRes.chats, dialog_id, false);
MessagesStorage.getInstance().putUsersAndChats(messagesRes.users, messagesRes.chats, true, true);
saveReplyMessages(replyMessageOwners, messagesRes.messages);
}
}
});
} }
cursor.dispose();
if (!replyMessageRandomOwners.isEmpty()) {
for (HashMap.Entry<Long, ArrayList<MessageObject>> entry : replyMessageRandomOwners.entrySet()) {
ArrayList<MessageObject> arrayList = entry.getValue();
for (int a = 0; a < arrayList.size(); a++) {
arrayList.get(a).messageOwner.reply_to_random_id = 0;
}
}
}
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.didLoadedReplyMessages, dialog_id);
}
});
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
} else {
final ArrayList<Integer> replyMessages = new ArrayList<>();
final HashMap<Integer, ArrayList<MessageObject>> replyMessageOwners = new HashMap<>();
final StringBuilder stringBuilder = new StringBuilder();
int channelId = 0;
for (int a = 0; a < messages.size(); a++) {
MessageObject messageObject = messages.get(a);
if (messageObject.getId() > 0 && messageObject.isReply() && messageObject.replyMessageObject == null) {
Integer id = messageObject.messageOwner.reply_to_msg_id;
long messageId = id;
if (messageObject.messageOwner.to_id.channel_id != 0) {
messageId |= ((long) messageObject.messageOwner.to_id.channel_id) << 32;
channelId = messageObject.messageOwner.to_id.channel_id;
}
if (stringBuilder.length() > 0) {
stringBuilder.append(',');
}
stringBuilder.append(messageId);
ArrayList<MessageObject> messageObjects = replyMessageOwners.get(id);
if (messageObjects == null) {
messageObjects = new ArrayList<>();
replyMessageOwners.put(id, messageObjects);
}
messageObjects.add(messageObject);
if (!replyMessages.contains(id)) {
replyMessages.add(id);
} }
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
} }
}); if (replyMessages.isEmpty()) {
return;
}
final int channelIdFinal = channelId;
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
try {
final ArrayList<TLRPC.Message> result = new ArrayList<>();
final ArrayList<TLRPC.User> users = new ArrayList<>();
final ArrayList<TLRPC.Chat> chats = new ArrayList<>();
ArrayList<Integer> usersToLoad = new ArrayList<>();
ArrayList<Integer> chatsToLoad = new ArrayList<>();
SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT data, mid, date FROM messages WHERE mid IN(%s)", stringBuilder.toString()));
while (cursor.next()) {
NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data) != 0) {
TLRPC.Message message = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
message.id = cursor.intValue(1);
message.date = cursor.intValue(2);
message.dialog_id = dialog_id;
MessagesStorage.addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad);
result.add(message);
replyMessages.remove((Integer) message.id);
}
data.reuse();
}
cursor.dispose();
if (!usersToLoad.isEmpty()) {
MessagesStorage.getInstance().getUsersInternal(TextUtils.join(",", usersToLoad), users);
}
if (!chatsToLoad.isEmpty()) {
MessagesStorage.getInstance().getChatsInternal(TextUtils.join(",", chatsToLoad), chats);
}
broadcastReplyMessages(result, replyMessageOwners, users, chats, dialog_id, true);
if (!replyMessages.isEmpty()) {
if (channelIdFinal != 0) {
final TLRPC.TL_channels_getMessages req = new TLRPC.TL_channels_getMessages();
req.channel = MessagesController.getInputChannel(channelIdFinal);
req.id = replyMessages;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response;
ImageLoader.saveMessagesThumbs(messagesRes.messages);
broadcastReplyMessages(messagesRes.messages, replyMessageOwners, messagesRes.users, messagesRes.chats, dialog_id, false);
MessagesStorage.getInstance().putUsersAndChats(messagesRes.users, messagesRes.chats, true, true);
saveReplyMessages(replyMessageOwners, messagesRes.messages);
}
}
});
} else {
TLRPC.TL_messages_getMessages req = new TLRPC.TL_messages_getMessages();
req.id = replyMessages;
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.messages_Messages messagesRes = (TLRPC.messages_Messages) response;
ImageLoader.saveMessagesThumbs(messagesRes.messages);
broadcastReplyMessages(messagesRes.messages, replyMessageOwners, messagesRes.users, messagesRes.chats, dialog_id, false);
MessagesStorage.getInstance().putUsersAndChats(messagesRes.users, messagesRes.chats, true, true);
saveReplyMessages(replyMessageOwners, messagesRes.messages);
}
}
});
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
} }
private static void saveReplyMessages(final HashMap<Integer, ArrayList<MessageObject>> replyMessageOwners, final ArrayList<TLRPC.Message> result) { private static void saveReplyMessages(final HashMap<Integer, ArrayList<MessageObject>> replyMessageOwners, final ArrayList<TLRPC.Message> result) {

View File

@ -56,11 +56,11 @@ public class SharedMediaQuery {
} else if (type == MEDIA_FILE) { } else if (type == MEDIA_FILE) {
req.filter = new TLRPC.TL_inputMessagesFilterDocument(); req.filter = new TLRPC.TL_inputMessagesFilterDocument();
} else if (type == MEDIA_AUDIO) { } else if (type == MEDIA_AUDIO) {
req.filter = new TLRPC.TL_inputMessagesFilterAudio(); req.filter = new TLRPC.TL_inputMessagesFilterVoice();
} else if (type == MEDIA_URL) { } else if (type == MEDIA_URL) {
req.filter = new TLRPC.TL_inputMessagesFilterUrl(); req.filter = new TLRPC.TL_inputMessagesFilterUrl();
} else if (type == MEDIA_MUSIC) { } else if (type == MEDIA_MUSIC) {
req.filter = new TLRPC.TL_inputMessagesFilterAudioDocuments(); req.filter = new TLRPC.TL_inputMessagesFilterMusic();
} }
req.q = ""; req.q = "";
req.peer = MessagesController.getInputPeer(lower_part); req.peer = MessagesController.getInputPeer(lower_part);
@ -101,11 +101,11 @@ public class SharedMediaQuery {
} else if (type == MEDIA_FILE) { } else if (type == MEDIA_FILE) {
req.filter = new TLRPC.TL_inputMessagesFilterDocument(); req.filter = new TLRPC.TL_inputMessagesFilterDocument();
} else if (type == MEDIA_AUDIO) { } else if (type == MEDIA_AUDIO) {
req.filter = new TLRPC.TL_inputMessagesFilterAudio(); req.filter = new TLRPC.TL_inputMessagesFilterVoice();
} else if (type == MEDIA_URL) { } else if (type == MEDIA_URL) {
req.filter = new TLRPC.TL_inputMessagesFilterUrl(); req.filter = new TLRPC.TL_inputMessagesFilterUrl();
} else if (type == MEDIA_MUSIC) { } else if (type == MEDIA_MUSIC) {
req.filter = new TLRPC.TL_inputMessagesFilterAudioDocuments(); req.filter = new TLRPC.TL_inputMessagesFilterMusic();
} }
req.q = ""; req.q = "";
req.peer = MessagesController.getInputPeer(lower_part); req.peer = MessagesController.getInputPeer(lower_part);
@ -144,8 +144,10 @@ public class SharedMediaQuery {
if (message == null) { if (message == null) {
return -1; return -1;
} }
if (message.media instanceof TLRPC.TL_messageMediaPhoto || message.media instanceof TLRPC.TL_messageMediaVideo) { if (message.media instanceof TLRPC.TL_messageMediaPhoto || MessageObject.isVideoMessage(message)) {
return MEDIA_PHOTOVIDEO; return MEDIA_PHOTOVIDEO;
} else if (MessageObject.isVoiceMessage(message)) {
return MEDIA_AUDIO;
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) { } else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
if (MessageObject.isStickerMessage(message)) { if (MessageObject.isStickerMessage(message)) {
return -1; return -1;
@ -154,8 +156,6 @@ public class SharedMediaQuery {
} else { } else {
return MEDIA_FILE; return MEDIA_FILE;
} }
} else if (message.media instanceof TLRPC.TL_messageMediaAudio) {
return MEDIA_AUDIO;
} else if (!message.entities.isEmpty()) { } else if (!message.entities.isEmpty()) {
for (int a = 0; a < message.entities.size(); a++) { for (int a = 0; a < message.entities.size(); a++) {
TLRPC.MessageEntity entity = message.entities.get(a); TLRPC.MessageEntity entity = message.entities.get(a);
@ -171,9 +171,7 @@ public class SharedMediaQuery {
if (message instanceof TLRPC.TL_message_secret && message.media instanceof TLRPC.TL_messageMediaPhoto && message.ttl != 0 && message.ttl <= 60) { if (message instanceof TLRPC.TL_message_secret && message.media instanceof TLRPC.TL_messageMediaPhoto && message.ttl != 0 && message.ttl <= 60) {
return false; return false;
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto || } else if (message.media instanceof TLRPC.TL_messageMediaPhoto ||
message.media instanceof TLRPC.TL_messageMediaVideo || message.media instanceof TLRPC.TL_messageMediaDocument && !MessageObject.isGifDocument(message.media.document)) {
message.media instanceof TLRPC.TL_messageMediaDocument && !MessageObject.isGifDocument(message.media.document) ||
message.media instanceof TLRPC.TL_messageMediaAudio) {
return true; return true;
} else if (!message.entities.isEmpty()) { } else if (!message.entities.isEmpty()) {
for (int a = 0; a < message.entities.size(); a++) { for (int a = 0; a < message.entities.size(); a++) {

View File

@ -43,6 +43,7 @@ public class StickersQuery {
private static int loadDate; private static int loadDate;
private static ArrayList<TLRPC.TL_messages_stickerSet> stickerSets = new ArrayList<>(); private static ArrayList<TLRPC.TL_messages_stickerSet> stickerSets = new ArrayList<>();
private static HashMap<Long, TLRPC.TL_messages_stickerSet> stickerSetsById = new HashMap<>(); private static HashMap<Long, TLRPC.TL_messages_stickerSet> stickerSetsById = new HashMap<>();
private static HashMap<String, TLRPC.TL_messages_stickerSet> stickerSetsByName = new HashMap<>();
private static HashMap<Long, String> stickersByEmoji = new HashMap<>(); private static HashMap<Long, String> stickersByEmoji = new HashMap<>();
private static HashMap<Long, TLRPC.Document> stickersById = new HashMap<>(); private static HashMap<Long, TLRPC.Document> stickersById = new HashMap<>();
private static HashMap<String, ArrayList<TLRPC.Document>> allStickers = new HashMap<>(); private static HashMap<String, ArrayList<TLRPC.Document>> allStickers = new HashMap<>();
@ -57,6 +58,7 @@ public class StickersQuery {
stickerSets.clear(); stickerSets.clear();
stickersByEmoji.clear(); stickersByEmoji.clear();
stickerSetsById.clear(); stickerSetsById.clear();
stickerSetsByName.clear();
loadingStickers = false; loadingStickers = false;
stickersLoaded = false; stickersLoaded = false;
} }
@ -95,6 +97,10 @@ public class StickersQuery {
return stickerSetsById.containsKey(id); return stickerSetsById.containsKey(id);
} }
public static boolean isStickerPackInstalled(String name) {
return stickerSetsByName.containsKey(name);
}
public static String getEmojiForSticker(long id) { public static String getEmojiForSticker(long id) {
String value = stickersByEmoji.get(id); String value = stickersByEmoji.get(id);
return value != null ? value : ""; return value != null ? value : "";
@ -124,32 +130,34 @@ public class StickersQuery {
} }
public static void addNewStickerSet(final TLRPC.TL_messages_stickerSet set) { public static void addNewStickerSet(final TLRPC.TL_messages_stickerSet set) {
if (!stickerSetsById.containsKey(set.set.id)) { if (stickerSetsById.containsKey(set.set.id) || stickerSetsByName.containsKey(set.set.short_name)) {
stickerSets.add(0, set); return;
stickerSetsById.put(set.set.id, set);
for (int a = 0; a < set.documents.size(); a++) {
TLRPC.Document document = set.documents.get(a);
stickersById.put(document.id, document);
}
for (int a = 0; a < set.packs.size(); a++) {
TLRPC.TL_stickerPack stickerPack = set.packs.get(a);
stickerPack.emoticon = stickerPack.emoticon.replace("\uFE0F", "");
ArrayList<TLRPC.Document> arrayList = allStickers.get(stickerPack.emoticon);
if (arrayList == null) {
arrayList = new ArrayList<>();
allStickers.put(stickerPack.emoticon, arrayList);
}
for (int c = 0; c < stickerPack.documents.size(); c++) {
Long id = stickerPack.documents.get(c);
if (!stickersByEmoji.containsKey(id)) {
stickersByEmoji.put(id, stickerPack.emoticon);
}
arrayList.add(stickersById.get(id));
}
}
loadHash = calcStickersHash(stickerSets);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.stickersDidLoaded);
} }
stickerSets.add(0, set);
stickerSetsById.put(set.set.id, set);
stickerSetsByName.put(set.set.short_name, set);
for (int a = 0; a < set.documents.size(); a++) {
TLRPC.Document document = set.documents.get(a);
stickersById.put(document.id, document);
}
for (int a = 0; a < set.packs.size(); a++) {
TLRPC.TL_stickerPack stickerPack = set.packs.get(a);
stickerPack.emoticon = stickerPack.emoticon.replace("\uFE0F", "");
ArrayList<TLRPC.Document> arrayList = allStickers.get(stickerPack.emoticon);
if (arrayList == null) {
arrayList = new ArrayList<>();
allStickers.put(stickerPack.emoticon, arrayList);
}
for (int c = 0; c < stickerPack.documents.size(); c++) {
Long id = stickerPack.documents.get(c);
if (!stickersByEmoji.containsKey(id)) {
stickersByEmoji.put(id, stickerPack.emoticon);
}
arrayList.add(stickersById.get(id));
}
}
loadHash = calcStickersHash(stickerSets);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.stickersDidLoaded);
StickersQuery.loadStickers(false, true); StickersQuery.loadStickers(false, true);
} }
@ -258,22 +266,23 @@ public class StickersQuery {
} }
} }
private static void putStickersToCache(final ArrayList<TLRPC.TL_messages_stickerSet> stickers, final int date, final int hash) { private static void putStickersToCache(ArrayList<TLRPC.TL_messages_stickerSet> stickers, final int date, final int hash) {
final ArrayList<TLRPC.TL_messages_stickerSet> stickersFinal = stickers != null ? new ArrayList<>(stickers) : null;
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
if (stickers != null) { if (stickersFinal != null) {
SQLitePreparedStatement state = MessagesStorage.getInstance().getDatabase().executeFast("REPLACE INTO stickers_v2 VALUES(?, ?, ?, ?)"); SQLitePreparedStatement state = MessagesStorage.getInstance().getDatabase().executeFast("REPLACE INTO stickers_v2 VALUES(?, ?, ?, ?)");
state.requery(); state.requery();
int size = 4; int size = 4;
for (int a = 0; a < stickers.size(); a++) { for (int a = 0; a < stickersFinal.size(); a++) {
size += stickers.get(a).getObjectSize(); size += stickersFinal.get(a).getObjectSize();
} }
NativeByteBuffer data = new NativeByteBuffer(size); NativeByteBuffer data = new NativeByteBuffer(size);
data.writeInt32(stickers.size()); data.writeInt32(stickersFinal.size());
for (int a = 0; a < stickers.size(); a++) { for (int a = 0; a < stickersFinal.size(); a++) {
stickers.get(a).serializeToStream(data); stickersFinal.get(a).serializeToStream(data);
} }
state.bindInteger(1, 1); state.bindInteger(1, 1);
state.bindByteBuffer(2, data); state.bindByteBuffer(2, data);
@ -296,6 +305,11 @@ public class StickersQuery {
}); });
} }
public static String getStickerSetName(long setId) {
TLRPC.TL_messages_stickerSet stickerSet = stickerSetsById.get(setId);
return stickerSet != null ? stickerSet.set.short_name : null;
}
public static long getStickerSetId(TLRPC.Document document) { public static long getStickerSetId(TLRPC.Document document) {
for (int a = 0; a < document.attributes.size(); a++) { for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a); TLRPC.DocumentAttribute attribute = document.attributes.get(a);
@ -350,6 +364,7 @@ public class StickersQuery {
try { try {
final ArrayList<TLRPC.TL_messages_stickerSet> stickerSetsNew = new ArrayList<>(); final ArrayList<TLRPC.TL_messages_stickerSet> stickerSetsNew = new ArrayList<>();
final HashMap<Long, TLRPC.TL_messages_stickerSet> stickerSetsByIdNew = new HashMap<>(); final HashMap<Long, TLRPC.TL_messages_stickerSet> stickerSetsByIdNew = new HashMap<>();
final HashMap<String, TLRPC.TL_messages_stickerSet> stickerSetsByNameNew = new HashMap<>();
final HashMap<Long, String> stickersByEmojiNew = new HashMap<>(); final HashMap<Long, String> stickersByEmojiNew = new HashMap<>();
final HashMap<Long, TLRPC.Document> stickersByIdNew = new HashMap<>(); final HashMap<Long, TLRPC.Document> stickersByIdNew = new HashMap<>();
final HashMap<String, ArrayList<TLRPC.Document>> allStickersNew = new HashMap<>(); final HashMap<String, ArrayList<TLRPC.Document>> allStickersNew = new HashMap<>();
@ -361,6 +376,7 @@ public class StickersQuery {
} }
stickerSetsNew.add(stickerSet); stickerSetsNew.add(stickerSet);
stickerSetsByIdNew.put(stickerSet.set.id, stickerSet); stickerSetsByIdNew.put(stickerSet.set.id, stickerSet);
stickerSetsByNameNew.put(stickerSet.set.short_name, stickerSet);
for (int b = 0; b < stickerSet.documents.size(); b++) { for (int b = 0; b < stickerSet.documents.size(); b++) {
TLRPC.Document document = stickerSet.documents.get(b); TLRPC.Document document = stickerSet.documents.get(b);
@ -400,6 +416,7 @@ public class StickersQuery {
public void run() { public void run() {
stickersById = stickersByIdNew; stickersById = stickersByIdNew;
stickerSetsById = stickerSetsByIdNew; stickerSetsById = stickerSetsByIdNew;
stickerSetsByName = stickerSetsByNameNew;
stickerSets = stickerSetsNew; stickerSets = stickerSetsNew;
allStickers = allStickersNew; allStickers = allStickersNew;
stickersByEmoji = stickersByEmojiNew; stickersByEmoji = stickersByEmojiNew;
@ -469,7 +486,11 @@ public class StickersQuery {
if (error == null) { if (error == null) {
Toast.makeText(fragment.getParentActivity(), LocaleController.getString("AddStickersInstalled", R.string.AddStickersInstalled), Toast.LENGTH_SHORT).show(); Toast.makeText(fragment.getParentActivity(), LocaleController.getString("AddStickersInstalled", R.string.AddStickersInstalled), Toast.LENGTH_SHORT).show();
} else { } else {
Toast.makeText(fragment.getParentActivity(), LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred), Toast.LENGTH_SHORT).show(); if (error.text.equals("STICKERSETS_TOO_MUCH")) {
Toast.makeText(fragment.getParentActivity(), LocaleController.getString("TooMuchStickersets", R.string.TooMuchStickersets), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(fragment.getParentActivity(), LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred), Toast.LENGTH_SHORT).show();
}
} }
} }
loadStickers(false, true); loadStickers(false, true);
@ -539,6 +560,7 @@ public class StickersQuery {
} }
} }
loadHash = calcStickersHash(stickerSets); loadHash = calcStickersHash(stickerSets);
putStickersToCache(stickerSets, loadDate, loadHash);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.stickersDidLoaded); NotificationCenter.getInstance().postNotificationName(NotificationCenter.stickersDidLoaded);
TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet(); TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet();
req.stickerset = stickerSetID; req.stickerset = stickerSetID;

View File

@ -120,42 +120,46 @@ public class ConnectionsManager {
@Override @Override
public void run() { public void run() {
FileLog.d("tmessages", "send request " + object + " with token = " + requestToken); FileLog.d("tmessages", "send request " + object + " with token = " + requestToken);
NativeByteBuffer buffer = new NativeByteBuffer(object.getObjectSize()); try {
object.serializeToStream(buffer); NativeByteBuffer buffer = new NativeByteBuffer(object.getObjectSize());
object.freeResources(); object.serializeToStream(buffer);
object.freeResources();
native_sendRequest(buffer.address, new RequestDelegateInternal() { native_sendRequest(buffer.address, new RequestDelegateInternal() {
@Override @Override
public void run(int response, int errorCode, String errorText) { public void run(int response, int errorCode, String errorText) {
try { try {
TLObject resp = null; TLObject resp = null;
TLRPC.TL_error error = null; TLRPC.TL_error error = null;
if (response != 0) { if (response != 0) {
NativeByteBuffer buff = NativeByteBuffer.wrap(response); NativeByteBuffer buff = NativeByteBuffer.wrap(response);
resp = object.deserializeResponse(buff, buff.readInt32(true), true); resp = object.deserializeResponse(buff, buff.readInt32(true), true);
} else if (errorText != null) { } else if (errorText != null) {
error = new TLRPC.TL_error(); error = new TLRPC.TL_error();
error.code = errorCode; error.code = errorCode;
error.text = errorText; error.text = errorText;
FileLog.e("tmessages", object + " got error " + error.code + " " + error.text); FileLog.e("tmessages", object + " got error " + error.code + " " + error.text);
}
FileLog.d("tmessages", "java received " + resp + " error = " + error);
final TLObject finalResponse = resp;
final TLRPC.TL_error finalError = error;
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
onComplete.run(finalResponse, finalError);
if (finalResponse != null) {
finalResponse.freeResources();
}
} }
}); FileLog.d("tmessages", "java received " + resp + " error = " + error);
} catch (Exception e) { final TLObject finalResponse = resp;
FileLog.e("tmessages", e); final TLRPC.TL_error finalError = error;
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
onComplete.run(finalResponse, finalError);
if (finalResponse != null) {
finalResponse.freeResources();
}
}
});
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
} }, onQuickAck, flags, datacenterId, connetionType, immediate, requestToken);
}, onQuickAck, flags, datacenterId, connetionType, immediate, requestToken); } catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
}); });
return requestToken; return requestToken;

View File

@ -40,13 +40,17 @@ public class NativeByteBuffer extends AbstractSerializedData {
} }
public NativeByteBuffer(int size) { public NativeByteBuffer(int size) throws Exception {
address = native_getFreeBuffer(size); if (size >= 0) {
if (address != 0) { address = native_getFreeBuffer(size);
buffer = native_getJavaByteBuffer(address); if (address != 0) {
buffer.position(0); buffer = native_getJavaByteBuffer(address);
buffer.limit(size); buffer.position(0);
buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.limit(size);
buffer.order(ByteOrder.LITTLE_ENDIAN);
}
} else {
throw new Exception("invalid NativeByteBuffer size");
} }
} }

View File

@ -23,11 +23,12 @@ public class TLClassStore {
classStore.put(TLRPC.TL_decryptedMessage.constructor, TLRPC.TL_decryptedMessage.class); classStore.put(TLRPC.TL_decryptedMessage.constructor, TLRPC.TL_decryptedMessage.class);
classStore.put(TLRPC.TL_config.constructor, TLRPC.TL_config.class); classStore.put(TLRPC.TL_config.constructor, TLRPC.TL_config.class);
classStore.put(TLRPC.TL_decryptedMessageLayer.constructor, TLRPC.TL_decryptedMessageLayer.class); classStore.put(TLRPC.TL_decryptedMessageLayer.constructor, TLRPC.TL_decryptedMessageLayer.class);
classStore.put(TLRPC.TL_decryptedMessageService_old.constructor, TLRPC.TL_decryptedMessageService_old.class); classStore.put(TLRPC.TL_decryptedMessage_layer17.constructor, TLRPC.TL_decryptedMessage.class);
classStore.put(TLRPC.TL_decryptedMessage_old.constructor, TLRPC.TL_decryptedMessage_old.class); classStore.put(TLRPC.TL_decryptedMessageService_layer8.constructor, TLRPC.TL_decryptedMessageService_layer8.class);
classStore.put(TLRPC.TL_decryptedMessage_layer8.constructor, TLRPC.TL_decryptedMessage_layer8.class);
classStore.put(TLRPC.TL_message_secret.constructor, TLRPC.TL_message_secret.class); classStore.put(TLRPC.TL_message_secret.constructor, TLRPC.TL_message_secret.class);
classStore.put(TLRPC.TL_message_secret_old.constructor, TLRPC.TL_message_secret_old.class);
classStore.put(TLRPC.TL_messageEncryptedAction.constructor, TLRPC.TL_messageEncryptedAction.class); classStore.put(TLRPC.TL_messageEncryptedAction.constructor, TLRPC.TL_messageEncryptedAction.class);
classStore.put(TLRPC.TL_decryptedMessageHolder.constructor, TLRPC.TL_decryptedMessageHolder.class);
classStore.put(TLRPC.TL_null.constructor, TLRPC.TL_null.class); classStore.put(TLRPC.TL_null.constructor, TLRPC.TL_null.class);
classStore.put(TLRPC.TL_updateShortChatMessage.constructor, TLRPC.TL_updateShortChatMessage.class); classStore.put(TLRPC.TL_updateShortChatMessage.constructor, TLRPC.TL_updateShortChatMessage.class);
@ -37,33 +38,6 @@ public class TLClassStore {
classStore.put(TLRPC.TL_updatesCombined.constructor, TLRPC.TL_updatesCombined.class); classStore.put(TLRPC.TL_updatesCombined.constructor, TLRPC.TL_updatesCombined.class);
classStore.put(TLRPC.TL_updateShortSentMessage.constructor, TLRPC.TL_updateShortSentMessage.class); classStore.put(TLRPC.TL_updateShortSentMessage.constructor, TLRPC.TL_updateShortSentMessage.class);
classStore.put(TLRPC.TL_updatesTooLong.constructor, TLRPC.TL_updatesTooLong.class); classStore.put(TLRPC.TL_updatesTooLong.constructor, TLRPC.TL_updatesTooLong.class);
classStore.put(TLRPC.TL_video.constructor, TLRPC.TL_video.class);
classStore.put(TLRPC.TL_videoEmpty.constructor, TLRPC.TL_videoEmpty.class);
classStore.put(TLRPC.TL_video_old2.constructor, TLRPC.TL_video_old2.class);
classStore.put(TLRPC.TL_video_old.constructor, TLRPC.TL_video_old.class);
classStore.put(TLRPC.TL_videoEncrypted.constructor, TLRPC.TL_videoEncrypted.class);
classStore.put(TLRPC.TL_video_old3.constructor, TLRPC.TL_video_old3.class);
classStore.put(TLRPC.TL_audio.constructor, TLRPC.TL_audio.class);
classStore.put(TLRPC.TL_audioEncrypted.constructor, TLRPC.TL_audioEncrypted.class);
classStore.put(TLRPC.TL_audioEmpty.constructor, TLRPC.TL_audioEmpty.class);
classStore.put(TLRPC.TL_audio_old.constructor, TLRPC.TL_audio_old.class);
classStore.put(TLRPC.TL_audio_old2.constructor, TLRPC.TL_audio_old2.class);
classStore.put(TLRPC.TL_document.constructor, TLRPC.TL_document.class);
classStore.put(TLRPC.TL_documentEmpty.constructor, TLRPC.TL_documentEmpty.class);
classStore.put(TLRPC.TL_documentEncrypted_old.constructor, TLRPC.TL_documentEncrypted_old.class);
classStore.put(TLRPC.TL_documentEncrypted.constructor, TLRPC.TL_documentEncrypted.class);
classStore.put(TLRPC.TL_document_old.constructor, TLRPC.TL_document_old.class);
classStore.put(TLRPC.TL_photo.constructor, TLRPC.TL_photo.class);
classStore.put(TLRPC.TL_photoEmpty.constructor, TLRPC.TL_photoEmpty.class);
classStore.put(TLRPC.TL_photoSize.constructor, TLRPC.TL_photoSize.class);
classStore.put(TLRPC.TL_photoSizeEmpty.constructor, TLRPC.TL_photoSizeEmpty.class);
classStore.put(TLRPC.TL_photoCachedSize.constructor, TLRPC.TL_photoCachedSize.class);
classStore.put(TLRPC.TL_photo_old.constructor, TLRPC.TL_photo_old.class);
classStore.put(TLRPC.TL_photo_old2.constructor, TLRPC.TL_photo_old2.class);
} }
static TLClassStore store = null; static TLClassStore store = null;

File diff suppressed because it is too large Load Diff

View File

@ -384,6 +384,7 @@ public class BottomSheet extends Dialog {
titleView.setText(title); titleView.setText(title);
titleView.setTextColor(0xff757575); titleView.setTextColor(0xff757575);
titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
titleView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), AndroidUtilities.dp(8)); titleView.setPadding(AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), AndroidUtilities.dp(8));
titleView.setGravity(Gravity.CENTER_VERTICAL); titleView.setGravity(Gravity.CENTER_VERTICAL);
containerView.addView(titleView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48)); containerView.addView(titleView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));

View File

@ -71,6 +71,7 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
private boolean isDarkTheme; private boolean isDarkTheme;
private int botsCount; private int botsCount;
private boolean loadingBotRecent; private boolean loadingBotRecent;
private boolean botRecentLoaded;
private String searchingContextUsername; private String searchingContextUsername;
private String searchingContextQuery; private String searchingContextQuery;
@ -96,7 +97,7 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
} }
private void loadBotRecent() { private void loadBotRecent() {
if (loadingBotRecent) { if (loadingBotRecent || botRecentLoaded) {
return; return;
} }
loadingBotRecent = true; loadingBotRecent = true;
@ -120,6 +121,7 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
public void run() { public void run() {
botRecent = users; botRecent = users;
loadingBotRecent = false; loadingBotRecent = false;
botRecentLoaded = true;
if (lastText != null) { if (lastText != null) {
searchUsernameOrHashtag(lastText, lastPosition, messages); searchUsernameOrHashtag(lastText, lastPosition, messages);
} }
@ -130,6 +132,7 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
@Override @Override
public void run() { public void run() {
loadingBotRecent = false; loadingBotRecent = false;
botRecentLoaded = true;
} }
}); });
} }
@ -241,6 +244,10 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
return foundContextBot != null ? foundContextBot.id : 0; return foundContextBot != null ? foundContextBot.id : 0;
} }
public String getContextBotName() {
return foundContextBot != null ? foundContextBot.username : "";
}
private void searchForContextBot(final String username, final String query) { private void searchForContextBot(final String username, final String query) {
searchResultBotContext = null; searchResultBotContext = null;
searchResultBotContextById = null; searchResultBotContextById = null;
@ -457,7 +464,7 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
int index = text.indexOf(' '); int index = text.indexOf(' ');
if (index > 0) { if (index > 0) {
String username = text.substring(1, index); String username = text.substring(1, index);
if (username.length() >= 3) { if (username.length() >= 1) {
for (int a = 1; a < username.length(); a++) { for (int a = 1; a < username.length(); a++) {
char ch = username.charAt(a); char ch = username.charAt(a);
if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) { if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_')) {
@ -488,7 +495,7 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
char ch = text.charAt(a); char ch = text.charAt(a);
if (a == 0 || text.charAt(a - 1) == ' ' || text.charAt(a - 1) == '\n') { if (a == 0 || text.charAt(a - 1) == ' ' || text.charAt(a - 1) == '\n') {
if (ch == '@') { if (ch == '@') {
if (needUsernames || botRecent != null && a == 0) { if (needUsernames || needBotContext && botRecent != null && a == 0) {
if (hasIllegalUsernameCharacters) { if (hasIllegalUsernameCharacters) {
delegate.needChangePanelVisibility(false); delegate.needChangePanelVisibility(false);
return; return;
@ -556,7 +563,7 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
String usernameString = result.toString().toLowerCase(); String usernameString = result.toString().toLowerCase();
ArrayList<TLRPC.User> newResult = new ArrayList<>(); ArrayList<TLRPC.User> newResult = new ArrayList<>();
final HashMap<Integer, TLRPC.User> newResultsHashMap = new HashMap<>(); final HashMap<Integer, TLRPC.User> newResultsHashMap = new HashMap<>();
if (dogPostion == 0 && botRecent != null) { if (needBotContext && dogPostion == 0 && botRecent != null) {
for (int a = 0; a < botRecent.size(); a++) { for (int a = 0; a < botRecent.size(); a++) {
TLRPC.User user = botRecent.get(a); TLRPC.User user = botRecent.get(a);
if (user.username != null && user.username.length() > 0 && (usernameString.length() > 0 && user.username.toLowerCase().startsWith(usernameString) || usernameString.length() == 0)) { if (user.username != null && user.username.length() > 0 && (usernameString.length() > 0 && user.username.toLowerCase().startsWith(usernameString) || usernameString.length() == 0)) {
@ -609,7 +616,8 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
} else if (foundType == 1) { } else if (foundType == 1) {
ArrayList<String> newResult = new ArrayList<>(); ArrayList<String> newResult = new ArrayList<>();
String hashtagString = result.toString().toLowerCase(); String hashtagString = result.toString().toLowerCase();
for (HashtagObject hashtagObject : hashtags) { for (int a = 0; a < hashtags.size(); a++) {
HashtagObject hashtagObject = hashtags.get(a);
if (hashtagObject != null && hashtagObject.hashtag != null && hashtagObject.hashtag.startsWith(hashtagString)) { if (hashtagObject != null && hashtagObject.hashtag != null && hashtagObject.hashtag.startsWith(hashtagString)) {
newResult.add(hashtagObject.hashtag); newResult.add(hashtagObject.hashtag);
} }
@ -711,7 +719,7 @@ public class MentionsAdapter extends BaseSearchAdapterRecycler {
} }
public boolean isLongClickEnabled() { public boolean isLongClickEnabled() {
return searchResultHashtags != null; return searchResultHashtags != null || searchResultCommands != null;
} }
public boolean isBotCommands() { public boolean isBotCommands() {

View File

@ -415,7 +415,7 @@ public class AudioPlayerActivity extends BaseFragment implements NotificationCen
private void updateTitle(boolean shutdown) { private void updateTitle(boolean shutdown) {
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject(); MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
if (messageObject == null && shutdown || messageObject != null && !messageObject.isMusic()) { if (messageObject == null && shutdown || messageObject != null && !messageObject.isMusic()) {
if (!parentLayout.fragmentsStack.isEmpty() && parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 1) == this) { if (parentLayout != null && !parentLayout.fragmentsStack.isEmpty() && parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 1) == this) {
finishFragment(); finishFragment();
} else { } else {
removeSelfFromStack(); removeSelfFromStack();

View File

@ -85,7 +85,7 @@ public class AudioSelectActivity extends BaseFragment implements NotificationCen
public View createView(Context context) { public View createView(Context context) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true); actionBar.setAllowOverlayTitle(true);
actionBar.setTitle(LocaleController.getString("AttachAudio", R.string.AttachAudio)); actionBar.setTitle(LocaleController.getString("AttachMusic", R.string.AttachMusic));
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override @Override
public void onItemClick(int id) { public void onItemClick(int id) {
@ -243,6 +243,7 @@ public class AudioSelectActivity extends BaseFragment implements NotificationCen
attributeAudio.duration = audioEntry.duration; attributeAudio.duration = audioEntry.duration;
attributeAudio.title = audioEntry.title; attributeAudio.title = audioEntry.title;
attributeAudio.performer = audioEntry.author; attributeAudio.performer = audioEntry.author;
attributeAudio.flags |= 3;
message.media.document.attributes.add(attributeAudio); message.media.document.attributes.add(attributeAudio);
TLRPC.TL_documentAttributeFilename fileName = new TLRPC.TL_documentAttributeFilename(); TLRPC.TL_documentAttributeFilename fileName = new TLRPC.TL_documentAttributeFilename();

View File

@ -241,8 +241,8 @@ public class CacheControlActivity extends BaseFragment {
File[] array = file.listFiles(); File[] array = file.listFiles();
if (array != null) { if (array != null) {
for (int b = 0; b < array.length; b++) { for (int b = 0; b < array.length; b++) {
String name = array[b].getName().toLowerCase();
if (documentsMusicType == 1 || documentsMusicType == 2) { if (documentsMusicType == 1 || documentsMusicType == 2) {
String name = array[b].getName().toLowerCase();
if (name.endsWith(".mp3") || name.endsWith(".m4a")) { if (name.endsWith(".mp3") || name.endsWith(".m4a")) {
if (documentsMusicType == 1) { if (documentsMusicType == 1) {
continue; continue;
@ -251,6 +251,9 @@ public class CacheControlActivity extends BaseFragment {
continue; continue;
} }
} }
if (name.equals(".nomedia")) {
continue;
}
if (array[b].isFile()) { if (array[b].isFile()) {
array[b].delete(); array[b].delete();
} }

View File

@ -18,6 +18,7 @@ import android.text.SpannableStringBuilder;
import android.text.StaticLayout; import android.text.StaticLayout;
import android.text.TextPaint; import android.text.TextPaint;
import android.text.style.ClickableSpan; import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.Gravity; import android.view.Gravity;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.widget.FrameLayout; import android.widget.FrameLayout;
@ -152,7 +153,11 @@ public class AboutLinkCell extends FrameLayout {
} }
} }
} else { } else {
pressedLink.onClick(this); if (pressedLink instanceof URLSpan) {
AndroidUtilities.openUrl(getContext(), ((URLSpan) pressedLink).getURL());
} else {
pressedLink.onClick(this);
}
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);

View File

@ -18,6 +18,7 @@ import android.text.Spanned;
import android.text.StaticLayout; import android.text.StaticLayout;
import android.text.TextPaint; import android.text.TextPaint;
import android.text.style.ClickableSpan; import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View; import android.view.View;
@ -160,7 +161,11 @@ public class BotHelpCell extends View {
} }
} }
} else { } else {
pressedLink.onClick(this); if (pressedLink instanceof URLSpan) {
AndroidUtilities.openUrl(getContext(), ((URLSpan) pressedLink).getURL());
} else {
pressedLink.onClick(this);
}
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);

View File

@ -20,25 +20,30 @@ import android.view.SoundEffectConstants;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLoader;
import org.telegram.messenger.MediaController; import org.telegram.messenger.MediaController;
import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessageObject;
import org.telegram.messenger.FileLog; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Components.RadialProgress; import org.telegram.ui.Components.RadialProgress;
import org.telegram.ui.Components.ResourceLoader; import org.telegram.ui.Components.ResourceLoader;
import org.telegram.ui.Components.SeekBar; import org.telegram.ui.Components.SeekBar;
import org.telegram.ui.Components.SeekBarWaveform;
import java.io.File; import java.io.File;
public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelegate { public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelegate {
public interface ChatAudioCellDelegate {
boolean needPlayAudio(MessageObject messageObject);
}
private static TextPaint timePaint; private static TextPaint timePaint;
private static Paint circlePaint; private static Paint circlePaint;
private boolean hasWaveform;
private SeekBar seekBar; private SeekBar seekBar;
private SeekBarWaveform seekBarWaveform;
private int seekBarX; private int seekBarX;
private int seekBarY; private int seekBarY;
@ -50,14 +55,21 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
private StaticLayout timeLayout; private StaticLayout timeLayout;
private int timeX; private int timeX;
private int timeWidth; private int timeWidth2;
private String lastTimeString = null; private String lastTimeString = null;
private ChatAudioCellDelegate audioDelegate;
public ChatAudioCell(Context context) { public ChatAudioCell(Context context) {
super(context); super(context);
seekBar = new SeekBar(context); seekBar = new SeekBar(context);
seekBar.delegate = this; seekBar.setDelegate(this);
seekBarWaveform = new SeekBarWaveform(context);
seekBarWaveform.setDelegate(this);
seekBarWaveform.setParentView(this);
radialProgress = new RadialProgress(this); radialProgress = new RadialProgress(this);
drawForwardedName = true; drawForwardedName = true;
@ -85,55 +97,83 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
public boolean onTouchEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) {
float x = event.getX(); float x = event.getX();
float y = event.getY(); float y = event.getY();
boolean result = seekBar.onTouch(event.getAction(), event.getX() - seekBarX, event.getY() - seekBarY); boolean result = false;
if (result) { if (delegate.canPerformActions()) {
if (event.getAction() == MotionEvent.ACTION_DOWN) { if (hasWaveform) {
getParent().requestDisallowInterceptTouchEvent(true); result = seekBarWaveform.onTouch(event.getAction(), event.getX() - seekBarX - AndroidUtilities.dp(13), event.getY() - seekBarY);
} else {
result = seekBar.onTouch(event.getAction(), event.getX() - seekBarX, event.getY() - seekBarY);
} }
invalidate(); if (result) {
} else { if (!hasWaveform && event.getAction() == MotionEvent.ACTION_DOWN) {
int side = AndroidUtilities.dp(36); getParent().requestDisallowInterceptTouchEvent(true);
if (event.getAction() == MotionEvent.ACTION_DOWN) { } else if (hasWaveform && !seekBarWaveform.isStartDraging() && event.getAction() == MotionEvent.ACTION_UP) {
if (x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side) {
buttonPressed = true;
invalidate();
result = true;
radialProgress.swapBackground(getDrawableForCurrentState());
}
} else if (buttonPressed) {
if (event.getAction() == MotionEvent.ACTION_UP) {
buttonPressed = false;
playSoundEffect(SoundEffectConstants.CLICK);
didPressedButton(); didPressedButton();
invalidate(); }
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) { invalidate();
buttonPressed = false; } else {
invalidate(); int side = AndroidUtilities.dp(36);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) { boolean area;
if (!(x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side)) { if (buttonState == 0 || buttonState == 1) {
area = x >= buttonX - AndroidUtilities.dp(12) && x <= buttonX - AndroidUtilities.dp(12) + backgroundWidth && y >= namesOffset && y <= getMeasuredHeight();
} else {
area = x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side;
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (area) {
buttonPressed = true;
invalidate();
result = true;
radialProgress.swapBackground(getDrawableForCurrentState());
}
} else if (buttonPressed) {
if (event.getAction() == MotionEvent.ACTION_UP) {
buttonPressed = false;
playSoundEffect(SoundEffectConstants.CLICK);
didPressedButton();
invalidate();
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
buttonPressed = false; buttonPressed = false;
invalidate(); invalidate();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (!area) {
buttonPressed = false;
invalidate();
}
} }
radialProgress.swapBackground(getDrawableForCurrentState());
}
if (result && event.getAction() == MotionEvent.ACTION_DOWN) {
startCheckLongPress();
}
if (event.getAction() != MotionEvent.ACTION_DOWN && event.getAction() != MotionEvent.ACTION_MOVE) {
cancelCheckLongPress();
}
if (!result) {
result = super.onTouchEvent(event);
} }
radialProgress.swapBackground(getDrawableForCurrentState());
}
if (!result) {
result = super.onTouchEvent(event);
} }
} }
return result; return result;
} }
@Override
protected void onLongPress() {
super.onLongPress();
if (buttonPressed) {
buttonPressed = false;
invalidate();
}
}
public void setAudioDelegate(ChatAudioCellDelegate delegate) {
audioDelegate = delegate;
}
private void didPressedButton() { private void didPressedButton() {
if (buttonState == 0) { if (buttonState == 0) {
boolean result = MediaController.getInstance().playAudio(currentMessageObject); if (audioDelegate.needPlayAudio(currentMessageObject)) {
if (!currentMessageObject.isOut() && currentMessageObject.isContentUnread()) {
if (currentMessageObject.messageOwner.to_id.channel_id == 0) {
MessagesController.getInstance().markMessageContentAsRead(currentMessageObject.messageOwner);
}
}
if (result) {
buttonState = 1; buttonState = 1;
radialProgress.setBackground(getDrawableForCurrentState(), false, false); radialProgress.setBackground(getDrawableForCurrentState(), false, false);
invalidate(); invalidate();
@ -147,12 +187,12 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
} }
} else if (buttonState == 2) { } else if (buttonState == 2) {
radialProgress.setProgress(0, false); radialProgress.setProgress(0, false);
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true); FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
buttonState = 3; buttonState = 3;
radialProgress.setBackground(getDrawableForCurrentState(), true, false); radialProgress.setBackground(getDrawableForCurrentState(), true, false);
invalidate(); invalidate();
} else if (buttonState == 3) { } else if (buttonState == 3) {
FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.audio); FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.document);
buttonState = 2; buttonState = 2;
radialProgress.setBackground(getDrawableForCurrentState(), false, false); radialProgress.setBackground(getDrawableForCurrentState(), false, false);
invalidate(); invalidate();
@ -170,28 +210,40 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
return; return;
} }
if (!seekBar.isDragging()) { if (hasWaveform) {
seekBar.setProgress(currentMessageObject.audioProgress); if (!seekBarWaveform.isDragging()) {
seekBarWaveform.setProgress(currentMessageObject.audioProgress);
}
} else {
if (!seekBar.isDragging()) {
seekBar.setProgress(currentMessageObject.audioProgress);
}
} }
int duration; int duration = 0;
if (!MediaController.getInstance().isPlayingAudio(currentMessageObject)) { if (!MediaController.getInstance().isPlayingAudio(currentMessageObject)) {
duration = currentMessageObject.messageOwner.media.audio.duration; for (int a = 0; a < currentMessageObject.messageOwner.media.document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = currentMessageObject.messageOwner.media.document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
duration = attribute.duration;
break;
}
}
} else { } else {
duration = currentMessageObject.audioProgressSec; duration = currentMessageObject.audioProgressSec;
} }
String timeString = String.format("%02d:%02d", duration / 60, duration % 60); String timeString = String.format("%02d:%02d", duration / 60, duration % 60);
if (lastTimeString == null || lastTimeString != null && !lastTimeString.equals(timeString)) { if (lastTimeString == null || lastTimeString != null && !lastTimeString.equals(timeString)) {
lastTimeString = timeString; lastTimeString = timeString;
timeWidth = (int)Math.ceil(timePaint.measureText(timeString)); timeWidth2 = (int)Math.ceil(timePaint.measureText(timeString));
timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); timeLayout = new StaticLayout(timeString, timePaint, timeWidth2, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
} }
invalidate(); invalidate();
} }
public void downloadAudioIfNeed() { public void downloadAudioIfNeed() {
if (buttonState == 2) { if (buttonState == 2) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true); FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
buttonState = 3; buttonState = 3;
radialProgress.setBackground(getDrawableForCurrentState(), false, false); radialProgress.setBackground(getDrawableForCurrentState(), false, false);
} }
@ -221,9 +273,6 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
if (cacheFile == null) { if (cacheFile == null) {
cacheFile = FileLoader.getPathToMessage(currentMessageObject.messageOwner); cacheFile = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
} }
if (BuildVars.DEBUG_VERSION) {
FileLog.d("tmessages", "looking for audio in " + cacheFile);
}
if (cacheFile.exists()) { if (cacheFile.exists()) {
MediaController.getInstance().removeLoadingFileObserver(this); MediaController.getInstance().removeLoadingFileObserver(this);
boolean playing = MediaController.getInstance().isPlayingAudio(currentMessageObject); boolean playing = MediaController.getInstance().isPlayingAudio(currentMessageObject);
@ -264,6 +313,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
@Override @Override
public void onSuccessDownload(String fileName) { public void onSuccessDownload(String fileName) {
updateButtonState(true); updateButtonState(true);
updateWaveform();
} }
@Override @Override
@ -303,7 +353,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
buttonX = layoutWidth - backgroundWidth + AndroidUtilities.dp(13); buttonX = layoutWidth - backgroundWidth + AndroidUtilities.dp(13);
timeX = layoutWidth - backgroundWidth + AndroidUtilities.dp(66); timeX = layoutWidth - backgroundWidth + AndroidUtilities.dp(66);
} else { } else {
if (isChat && currentMessageObject.messageOwner.from_id > 0) { if (isChat && currentMessageObject.isFromUser()) {
seekBarX = AndroidUtilities.dp(116); seekBarX = AndroidUtilities.dp(116);
buttonX = AndroidUtilities.dp(74); buttonX = AndroidUtilities.dp(74);
timeX = AndroidUtilities.dp(127); timeX = AndroidUtilities.dp(127);
@ -313,9 +363,9 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
timeX = AndroidUtilities.dp(75); timeX = AndroidUtilities.dp(75);
} }
} }
seekBarWaveform.width = seekBar.width = backgroundWidth - AndroidUtilities.dp(70);
seekBar.width = backgroundWidth - AndroidUtilities.dp(70); seekBarWaveform.height = seekBar.height = AndroidUtilities.dp(30);
seekBar.height = AndroidUtilities.dp(30); seekBarWaveform.width -= AndroidUtilities.dp(20);
seekBarY = AndroidUtilities.dp(11) + namesOffset; seekBarY = AndroidUtilities.dp(11) + namesOffset;
buttonY = AndroidUtilities.dp(13) + namesOffset; buttonY = AndroidUtilities.dp(13) + namesOffset;
radialProgress.setProgressRect(buttonX, buttonY, buttonX + AndroidUtilities.dp(40), buttonY + AndroidUtilities.dp(40)); radialProgress.setProgressRect(buttonX, buttonY, buttonX + AndroidUtilities.dp(40), buttonY + AndroidUtilities.dp(40));
@ -328,28 +378,51 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
boolean dataChanged = currentMessageObject == messageObject && isUserDataChanged(); boolean dataChanged = currentMessageObject == messageObject && isUserDataChanged();
if (currentMessageObject != messageObject || dataChanged) { if (currentMessageObject != messageObject || dataChanged) {
if (AndroidUtilities.isTablet()) { if (AndroidUtilities.isTablet()) {
backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(isChat && messageObject.messageOwner.from_id > 0 ? 102 : 50), AndroidUtilities.dp(300)); backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(isChat && messageObject.isFromUser() && !messageObject.isOutOwner() ? 102 : 50), AndroidUtilities.dp(300));
} else { } else {
backgroundWidth = Math.min(AndroidUtilities.displaySize.x - AndroidUtilities.dp(isChat && messageObject.messageOwner.from_id > 0 ? 102 : 50), AndroidUtilities.dp(300)); backgroundWidth = Math.min(AndroidUtilities.displaySize.x - AndroidUtilities.dp(isChat && messageObject.isFromUser() && !messageObject.isOutOwner() ? 102 : 50), AndroidUtilities.dp(300));
} }
if (messageObject.isOutOwner()) { int duration = 0;
seekBar.type = 0; for (int a = 0; a < messageObject.messageOwner.media.document.attributes.size(); a++) {
} else { TLRPC.DocumentAttribute attribute = messageObject.messageOwner.media.document.attributes.get(a);
seekBar.type = 1; if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
duration = attribute.duration;
break;
}
} }
availableTimeWidth = backgroundWidth - AndroidUtilities.dp(75 + 14) - (int) Math.ceil(timePaint.measureText("00:00"));
measureTime(messageObject);
int minSize = AndroidUtilities.dp(40 + 14 + 20 + 90 + 10) + timeWidth;
backgroundWidth = Math.min(backgroundWidth, minSize + duration * AndroidUtilities.dp(10));
hasWaveform = false;
if (messageObject.isOutOwner()) {
seekBarWaveform.setColors(0xffc3e3ab, 0xff87bf78, 0xffa9d389);
} else {
seekBarWaveform.setColors(0xffdee5eb, 0xff4195e5, 0xffaed5e2);
}
seekBar.type = messageObject.isOutOwner() ? 0 : 1;
super.setMessageObject(messageObject); super.setMessageObject(messageObject);
} }
updateWaveform();
updateButtonState(dataChanged); updateButtonState(dataChanged);
} }
@Override
protected int getMaxNameWidth() {
return backgroundWidth - AndroidUtilities.dp(24);
}
@Override @Override
public void setCheckPressed(boolean value, boolean pressed) { public void setCheckPressed(boolean value, boolean pressed) {
super.setCheckPressed(value, pressed); super.setCheckPressed(value, pressed);
if (radialProgress.swapBackground(getDrawableForCurrentState())) { if (radialProgress.swapBackground(getDrawableForCurrentState())) {
invalidate(); invalidate();
} }
seekBarWaveform.setSelected(isDrawSelectedBackground());
} }
@Override @Override
@ -358,6 +431,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
if (radialProgress.swapBackground(getDrawableForCurrentState())) { if (radialProgress.swapBackground(getDrawableForCurrentState())) {
invalidate(); invalidate();
} }
seekBarWaveform.setSelected(isDrawSelectedBackground());
} }
@Override @Override
@ -366,12 +440,29 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
if (radialProgress.swapBackground(getDrawableForCurrentState())) { if (radialProgress.swapBackground(getDrawableForCurrentState())) {
invalidate(); invalidate();
} }
seekBarWaveform.setSelected(isDrawSelectedBackground());
} }
private Drawable getDrawableForCurrentState() { private Drawable getDrawableForCurrentState() {
return ResourceLoader.audioStatesDrawable[currentMessageObject.isOutOwner() ? buttonState : buttonState + 5][isDrawSelectedBackground() ? 2 : (buttonPressed ? 1 : 0)]; return ResourceLoader.audioStatesDrawable[currentMessageObject.isOutOwner() ? buttonState : buttonState + 5][isDrawSelectedBackground() ? 2 : (buttonPressed ? 1 : 0)];
} }
private void updateWaveform() {
File path = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
for (int a = 0; a < currentMessageObject.messageOwner.media.document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = currentMessageObject.messageOwner.media.document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
if (attribute.waveform == null || attribute.waveform.length == 0) {
MediaController.getInstance().generateWaveform(currentMessageObject);
}
hasWaveform = attribute.waveform != null;
seekBarWaveform.setWaveform(attribute.waveform);
seekBarWaveform.setMessageObject(currentMessageObject);
break;
}
}
}
@Override @Override
protected void onDraw(Canvas canvas) { protected void onDraw(Canvas canvas) {
if (currentMessageObject == null) { if (currentMessageObject == null) {
@ -381,8 +472,13 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
super.onDraw(canvas); super.onDraw(canvas);
canvas.save(); canvas.save();
canvas.translate(seekBarX, seekBarY); if (hasWaveform) {
seekBar.draw(canvas); canvas.translate(seekBarX + AndroidUtilities.dp(13), seekBarY);
seekBarWaveform.draw(canvas);
} else {
canvas.translate(seekBarX, seekBarY);
seekBar.draw(canvas);
}
canvas.restore(); canvas.restore();
radialProgress.setProgressColor(currentMessageObject.isOutOwner() ? 0xff87bf78 : (isDrawSelectedBackground() ? 0xff83b2c2 : 0xffa2b5c7)); radialProgress.setProgressColor(currentMessageObject.isOutOwner() ? 0xff87bf78 : (isDrawSelectedBackground() ? 0xff83b2c2 : 0xffa2b5c7));
@ -396,7 +492,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
canvas.restore(); canvas.restore();
if (currentMessageObject.messageOwner.to_id.channel_id == 0 && currentMessageObject.isContentUnread()) { if (currentMessageObject.messageOwner.to_id.channel_id == 0 && currentMessageObject.isContentUnread()) {
canvas.drawCircle(timeX + timeWidth + AndroidUtilities.dp(8), AndroidUtilities.dp(49.5f) + namesOffset, AndroidUtilities.dp(3), circlePaint); canvas.drawCircle(timeX + timeWidth2 + AndroidUtilities.dp(8), AndroidUtilities.dp(49.5f) + namesOffset, AndroidUtilities.dp(3), circlePaint);
} }
} }
} }

View File

@ -25,6 +25,7 @@ import android.view.MotionEvent;
import android.view.SoundEffectConstants; import android.view.SoundEffectConstants;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.Emoji; import org.telegram.messenger.Emoji;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController; import org.telegram.messenger.MediaController;
@ -47,8 +48,8 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
public interface ChatBaseCellDelegate { public interface ChatBaseCellDelegate {
void didPressedUserAvatar(ChatBaseCell cell, TLRPC.User user); void didPressedUserAvatar(ChatBaseCell cell, TLRPC.User user);
void didPressedViaBot(ChatBaseCell cell, TLRPC.User user); void didPressedViaBot(ChatBaseCell cell, String username);
void didPressedChannelAvatar(ChatBaseCell cell, TLRPC.Chat chat); void didPressedChannelAvatar(ChatBaseCell cell, TLRPC.Chat chat, int postId);
void didPressedCancelSendButton(ChatBaseCell cell); void didPressedCancelSendButton(ChatBaseCell cell);
void didLongPressed(ChatBaseCell cell); void didLongPressed(ChatBaseCell cell);
void didPressReplyMessage(ChatBaseCell cell, int id); void didPressReplyMessage(ChatBaseCell cell, int id);
@ -78,6 +79,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
protected MessageObject currentMessageObject; protected MessageObject currentMessageObject;
private int viaWidth; private int viaWidth;
private int viaNameWidth; private int viaNameWidth;
protected int availableTimeWidth;
private static TextPaint timePaint; private static TextPaint timePaint;
private static TextPaint namePaint; private static TextPaint namePaint;
@ -110,7 +112,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
private boolean replyPressed; private boolean replyPressed;
private TLRPC.FileLocation currentReplyPhoto; private TLRPC.FileLocation currentReplyPhoto;
private boolean drawShareButton; protected boolean drawShareButton;
private boolean sharePressed; private boolean sharePressed;
private int shareStartX; private int shareStartX;
private int shareStartY; private int shareStartY;
@ -255,10 +257,12 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
TLRPC.User newUser = null; TLRPC.User newUser = null;
TLRPC.Chat newChat = null; TLRPC.Chat newChat = null;
if (currentMessageObject.messageOwner.from_id > 0) { if (currentMessageObject.isFromUser()) {
newUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id); newUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id);
} else if (currentMessageObject.messageOwner.from_id < 0) { } else if (currentMessageObject.messageOwner.from_id < 0) {
newChat = MessagesController.getInstance().getChat(-currentMessageObject.messageOwner.from_id); newChat = MessagesController.getInstance().getChat(-currentMessageObject.messageOwner.from_id);
} else if (currentMessageObject.messageOwner.post) {
newChat = MessagesController.getInstance().getChat(currentMessageObject.messageOwner.to_id.channel_id);
} }
TLRPC.FileLocation newPhoto = null; TLRPC.FileLocation newPhoto = null;
@ -312,12 +316,52 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
} }
protected void measureTime(MessageObject messageObject) { protected void measureTime(MessageObject messageObject) {
currentTimeString = LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000); boolean hasSign = !messageObject.isOutOwner() && messageObject.messageOwner.from_id > 0 && messageObject.messageOwner.post;
TLRPC.User signUser = MessagesController.getInstance().getUser(messageObject.messageOwner.from_id);
if (hasSign && signUser == null) {
hasSign = false;
}
if (hasSign) {
currentTimeString = ", " + LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000);
} else {
currentTimeString = LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000);
}
timeTextWidth = timeWidth = (int) Math.ceil(timePaint.measureText(currentTimeString)); timeTextWidth = timeWidth = (int) Math.ceil(timePaint.measureText(currentTimeString));
if ((messageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) { if ((messageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
currentViewsString = String.format("%s", LocaleController.formatShortNumber(Math.max(1, messageObject.messageOwner.views), null)); currentViewsString = String.format("%s", LocaleController.formatShortNumber(Math.max(1, messageObject.messageOwner.views), null));
timeWidth += (int) Math.ceil(timePaint.measureText(currentViewsString)) + ResourceLoader.viewsCountDrawable.getIntrinsicWidth() + AndroidUtilities.dp(10); viewsTextWidth = (int) Math.ceil(timePaint.measureText(currentViewsString));
timeWidth += viewsTextWidth + ResourceLoader.viewsCountDrawable[0].getIntrinsicWidth() + AndroidUtilities.dp(10);
} }
if (hasSign) {
if (availableTimeWidth == 0) {
availableTimeWidth = AndroidUtilities.dp(100);
}
CharSequence name = ContactsController.formatName(signUser.first_name, signUser.last_name).replace('\n', ' ');
int widthForSign = availableTimeWidth - timeWidth;
int width = (int) Math.ceil(timePaint.measureText(name, 0, name.length()));
if (width > widthForSign) {
name = TextUtils.ellipsize(name, timePaint, widthForSign, TextUtils.TruncateAt.END);
width = widthForSign;
}
currentTimeString = name + currentTimeString;
timeTextWidth += width;
timeWidth += width;
}
}
protected boolean checkNeedDrawShareButton(MessageObject messageObject) {
if (messageObject.isFromUser()) {
TLRPC.User user = MessagesController.getInstance().getUser(messageObject.messageOwner.from_id);
if (user != null && user.bot && messageObject.type != 13 && !(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty || messageObject.messageOwner.media == null
|| messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && !(messageObject.messageOwner.media.webpage instanceof TLRPC.TL_webPage))) {
return true;
}
} else if (messageObject.messageOwner.from_id < 0 || messageObject.messageOwner.post) {
if (messageObject.messageOwner.to_id.channel_id != 0 && (messageObject.messageOwner.reply_to_msg_id == 0 || messageObject.type != 13)) {
return true;
}
}
return false;
} }
public void setMessageObject(MessageObject messageObject) { public void setMessageObject(MessageObject messageObject) {
@ -329,7 +373,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
isCheckPressed = true; isCheckPressed = true;
isAvatarVisible = false; isAvatarVisible = false;
wasLayout = false; wasLayout = false;
drawShareButton = false; drawShareButton = checkNeedDrawShareButton(messageObject);
replyNameLayout = null; replyNameLayout = null;
replyTextLayout = null; replyTextLayout = null;
replyNameWidth = 0; replyNameWidth = 0;
@ -351,15 +395,15 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
} }
} }
if (messageObject.messageOwner.from_id > 0) { if (currentMessageObject.isFromUser()) {
currentUser = MessagesController.getInstance().getUser(messageObject.messageOwner.from_id); currentUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id);
} else if (messageObject.messageOwner.from_id < 0) { } else if (currentMessageObject.messageOwner.from_id < 0) {
currentChat = MessagesController.getInstance().getChat(-messageObject.messageOwner.from_id); currentChat = MessagesController.getInstance().getChat(-currentMessageObject.messageOwner.from_id);
if (messageObject.messageOwner.to_id.channel_id != 0 && (messageObject.messageOwner.reply_to_msg_id == 0 || messageObject.type != 13)) { } else if (currentMessageObject.messageOwner.post) {
drawShareButton = true; currentChat = MessagesController.getInstance().getChat(currentMessageObject.messageOwner.to_id.channel_id);
}
} }
if (isChat && !messageObject.isOutOwner() && messageObject.messageOwner.from_id > 0) {
if (isChat && !messageObject.isOutOwner() && messageObject.isFromUser()) {
isAvatarVisible = true; isAvatarVisible = true;
if (currentUser != null) { if (currentUser != null) {
if (currentUser.photo != null) { if (currentUser.photo != null) {
@ -382,13 +426,8 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
avatarImage.setImage(currentPhoto, "50_50", avatarDrawable, null, false); avatarImage.setImage(currentPhoto, "50_50", avatarDrawable, null, false);
} }
currentTimeString = LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000);
timeTextWidth = timeWidth = (int)Math.ceil(timePaint.measureText(currentTimeString)); measureTime(messageObject);
if ((messageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
currentViewsString = String.format("%s", LocaleController.formatShortNumber(Math.max(1, messageObject.messageOwner.views), null));
viewsTextWidth = (int) Math.ceil(timePaint.measureText(currentViewsString));
timeWidth += viewsTextWidth + ResourceLoader.viewsCountDrawable.getIntrinsicWidth() + AndroidUtilities.dp(10);
}
namesOffset = 0; namesOffset = 0;
@ -402,10 +441,14 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
viaWidth = (int) Math.ceil(forwardNamePaint.measureText(viaString)); viaWidth = (int) Math.ceil(forwardNamePaint.measureText(viaString));
currentViaBotUser = botUser; currentViaBotUser = botUser;
} }
} else if (messageObject.messageOwner.via_bot_name != null && messageObject.messageOwner.via_bot_name.length() > 0) {
viaUsername = "@" + messageObject.messageOwner.via_bot_name;
viaString = " via " + messageObject.messageOwner.via_bot_name;
viaWidth = (int) Math.ceil(forwardNamePaint.measureText(viaString));
} }
boolean authorName = drawName && isChat && !currentMessageObject.isOutOwner(); boolean authorName = drawName && isChat && !currentMessageObject.isOutOwner();
boolean viaBot = messageObject.messageOwner.fwd_from_id == null && currentViaBotUser != null; boolean viaBot = messageObject.messageOwner.fwd_from == null && viaUsername != null;
if (authorName || viaBot) { if (authorName || viaBot) {
drawName = true; drawName = true;
nameWidth = getMaxNameWidth(); nameWidth = getMaxNameWidth();
@ -413,7 +456,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
nameWidth = AndroidUtilities.dp(100); nameWidth = AndroidUtilities.dp(100);
} }
if (authorName || !currentMessageObject.isOutOwner()) { if (authorName) {
if (currentUser != null) { if (currentUser != null) {
currentNameString = UserObject.getUserName(currentUser); currentNameString = UserObject.getUserName(currentUser);
} else if (currentChat != null) { } else if (currentChat != null) {
@ -432,12 +475,12 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
viaNameWidth += AndroidUtilities.dp(4); viaNameWidth += AndroidUtilities.dp(4);
} }
if (currentNameString.length() > 0) { if (currentNameString.length() > 0) {
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(String.format("%s via @%s", nameStringFinal, currentViaBotUser.username)); SpannableStringBuilder stringBuilder = new SpannableStringBuilder(String.format("%s via %s", nameStringFinal, viaUsername));
stringBuilder.setSpan(new TypefaceSpan(null, 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), nameStringFinal.length() + 1, nameStringFinal.length() + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); stringBuilder.setSpan(new TypefaceSpan(null, 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), nameStringFinal.length() + 1, nameStringFinal.length() + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), nameStringFinal.length() + 5, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), nameStringFinal.length() + 5, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
nameStringFinal = stringBuilder; nameStringFinal = stringBuilder;
} else { } else {
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(String.format("via @%s", currentViaBotUser.username)); SpannableStringBuilder stringBuilder = new SpannableStringBuilder(String.format("via %s", viaUsername));
stringBuilder.setSpan(new TypefaceSpan(null, 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); stringBuilder.setSpan(new TypefaceSpan(null, 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), 0, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), 4, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), 4, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
nameStringFinal = stringBuilder; nameStringFinal = stringBuilder;
@ -462,19 +505,24 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
} }
if (drawForwardedName && messageObject.isForwarded()) { if (drawForwardedName && messageObject.isForwarded()) {
if (messageObject.messageOwner.fwd_from_id instanceof TLRPC.TL_peerChannel) { currentForwardUser = null;
currentForwardChannel = MessagesController.getInstance().getChat(messageObject.messageOwner.fwd_from_id.channel_id); currentForwardChannel = null;
currentForwardUser = null; if (messageObject.messageOwner.fwd_from.channel_id != 0) {
} else if (messageObject.messageOwner.fwd_from_id instanceof TLRPC.TL_peerUser) { currentForwardChannel = MessagesController.getInstance().getChat(messageObject.messageOwner.fwd_from.channel_id);
currentForwardChannel = null; }
currentForwardUser = MessagesController.getInstance().getUser(messageObject.messageOwner.fwd_from_id.user_id); if (messageObject.messageOwner.fwd_from.from_id != 0) {
currentForwardUser = MessagesController.getInstance().getUser(messageObject.messageOwner.fwd_from.from_id);
} }
if (currentForwardUser != null || currentForwardChannel != null) { if (currentForwardUser != null || currentForwardChannel != null) {
if (currentForwardUser != null) { if (currentForwardChannel != null) {
if (currentForwardUser != null) {
currentForwardNameString = String.format("%s (%s)", currentForwardChannel.title, UserObject.getUserName(currentForwardUser));
} else {
currentForwardNameString = currentForwardChannel.title;
}
} else if (currentForwardUser != null) {
currentForwardNameString = UserObject.getUserName(currentForwardUser); currentForwardNameString = UserObject.getUserName(currentForwardUser);
} else {
currentForwardNameString = currentForwardChannel.title;
} }
forwardedNameWidth = getMaxNameWidth(); forwardedNameWidth = getMaxNameWidth();
@ -537,7 +585,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
if (messageObject.isOutOwner()) { if (messageObject.isOutOwner()) {
maxWidth = width - backgroundWidth - AndroidUtilities.dp(60); maxWidth = width - backgroundWidth - AndroidUtilities.dp(60);
} else { } else {
maxWidth = width - backgroundWidth - AndroidUtilities.dp(56 + (isChat && messageObject.messageOwner.from_id > 0 ? 61 : 0)); maxWidth = width - backgroundWidth - AndroidUtilities.dp(56 + (isChat && messageObject.isFromUser() ? 61 : 0));
} }
} else { } else {
maxWidth = getMaxNameWidth() - AndroidUtilities.dp(22); maxWidth = getMaxNameWidth() - AndroidUtilities.dp(22);
@ -550,7 +598,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
CharSequence stringFinalText = null; CharSequence stringFinalText = null;
if (messageObject.replyMessageObject != null) { if (messageObject.replyMessageObject != null) {
TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(messageObject.replyMessageObject.photoThumbs, 80); TLRPC.PhotoSize photoSize = FileLoader.getClosestPhotoSizeWithSize(messageObject.replyMessageObject.photoThumbs, 80);
if (photoSize == null || messageObject.replyMessageObject.type == 13 || messageObject.type == 13 && !AndroidUtilities.isTablet()) { if (photoSize == null || messageObject.replyMessageObject.type == 13 || messageObject.type == 13 && !AndroidUtilities.isTablet() || messageObject.replyMessageObject.isSecretMedia()) {
replyImageReceiver.setImageBitmap((Drawable) null); replyImageReceiver.setImageBitmap((Drawable) null);
needReplyImage = false; needReplyImage = false;
} else { } else {
@ -561,16 +609,21 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
} }
String name = null; String name = null;
if (messageObject.replyMessageObject.messageOwner.from_id > 0) { if (messageObject.replyMessageObject.isFromUser()) {
TLRPC.User user = MessagesController.getInstance().getUser(messageObject.replyMessageObject.messageOwner.from_id); TLRPC.User user = MessagesController.getInstance().getUser(messageObject.replyMessageObject.messageOwner.from_id);
if (user != null) { if (user != null) {
name = UserObject.getUserName(user); name = UserObject.getUserName(user);
} }
} else { } else if (messageObject.replyMessageObject.messageOwner.from_id < 0) {
TLRPC.Chat chat = MessagesController.getInstance().getChat(-messageObject.replyMessageObject.messageOwner.from_id); TLRPC.Chat chat = MessagesController.getInstance().getChat(-messageObject.replyMessageObject.messageOwner.from_id);
if (chat != null) { if (chat != null) {
name = chat.title; name = chat.title;
} }
} else {
TLRPC.Chat chat = MessagesController.getInstance().getChat(messageObject.replyMessageObject.messageOwner.to_id.channel_id);
if (chat != null) {
name = chat.title;
}
} }
if (name != null) { if (name != null) {
@ -666,7 +719,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
if (currentUser != null) { if (currentUser != null) {
delegate.didPressedUserAvatar(this, currentUser); delegate.didPressedUserAvatar(this, currentUser);
} else if (currentChat != null) { } else if (currentChat != null) {
delegate.didPressedChannelAvatar(this, currentChat); delegate.didPressedChannelAvatar(this, currentChat, 0);
} }
} }
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) { } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
@ -681,10 +734,10 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
forwardNamePressed = false; forwardNamePressed = false;
playSoundEffect(SoundEffectConstants.CLICK); playSoundEffect(SoundEffectConstants.CLICK);
if (delegate != null) { if (delegate != null) {
if (currentForwardUser != null) { if (currentForwardChannel != null) {
delegate.didPressedChannelAvatar(this, currentForwardChannel, currentMessageObject.messageOwner.fwd_from.channel_post);
} else if (currentForwardUser != null) {
delegate.didPressedUserAvatar(this, currentForwardUser); delegate.didPressedUserAvatar(this, currentForwardUser);
} else {
delegate.didPressedChannelAvatar(this, currentForwardChannel);
} }
} }
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) { } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
@ -699,7 +752,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
forwardBotPressed = false; forwardBotPressed = false;
playSoundEffect(SoundEffectConstants.CLICK); playSoundEffect(SoundEffectConstants.CLICK);
if (delegate != null) { if (delegate != null) {
delegate.didPressedViaBot(this, currentViaBotUser); delegate.didPressedViaBot(this, currentViaBotUser != null ? currentViaBotUser.username : currentMessageObject.messageOwner.via_bot_name);
} }
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) { } else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
forwardBotPressed = false; forwardBotPressed = false;
@ -763,13 +816,13 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
timeLayout = new StaticLayout(currentTimeString, timePaint, timeTextWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); timeLayout = new StaticLayout(currentTimeString, timePaint, timeTextWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (!media) { if (!media) {
if (!currentMessageObject.isOutOwner()) { if (!currentMessageObject.isOutOwner()) {
timeX = backgroundWidth - AndroidUtilities.dp(9) - timeWidth + (isChat && currentMessageObject.messageOwner.from_id > 0 ? AndroidUtilities.dp(52) : 0); timeX = backgroundWidth - AndroidUtilities.dp(9) - timeWidth + (isChat && currentMessageObject.isFromUser() ? AndroidUtilities.dp(52) : 0);
} else { } else {
timeX = layoutWidth - timeWidth - AndroidUtilities.dp(38.5f); timeX = layoutWidth - timeWidth - AndroidUtilities.dp(38.5f);
} }
} else { } else {
if (!currentMessageObject.isOutOwner()) { if (!currentMessageObject.isOutOwner()) {
timeX = backgroundWidth - AndroidUtilities.dp(4) - timeWidth + (isChat && currentMessageObject.messageOwner.from_id > 0 ? AndroidUtilities.dp(52) : 0); timeX = backgroundWidth - AndroidUtilities.dp(4) - timeWidth + (isChat && currentMessageObject.isFromUser() ? AndroidUtilities.dp(52) : 0);
} else { } else {
timeX = layoutWidth - timeWidth - AndroidUtilities.dp(42.0f); timeX = layoutWidth - timeWidth - AndroidUtilities.dp(42.0f);
} }
@ -863,7 +916,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
currentBackgroundDrawable = ResourceLoader.backgroundMediaDrawableIn; currentBackgroundDrawable = ResourceLoader.backgroundMediaDrawableIn;
} }
} }
if (isChat && currentMessageObject.messageOwner.from_id > 0) { if (isChat && currentMessageObject.isFromUser()) {
setDrawableBounds(currentBackgroundDrawable, AndroidUtilities.dp(52 + (!media ? 0 : 9)), AndroidUtilities.dp(1), backgroundWidth, layoutHeight - AndroidUtilities.dp(2)); setDrawableBounds(currentBackgroundDrawable, AndroidUtilities.dp(52 + (!media ? 0 : 9)), AndroidUtilities.dp(1), backgroundWidth, layoutHeight - AndroidUtilities.dp(2));
} else { } else {
setDrawableBounds(currentBackgroundDrawable, (!media ? 0 : AndroidUtilities.dp(9)), AndroidUtilities.dp(1), backgroundWidth, layoutHeight - AndroidUtilities.dp(2)); setDrawableBounds(currentBackgroundDrawable, (!media ? 0 : AndroidUtilities.dp(9)), AndroidUtilities.dp(1), backgroundWidth, layoutHeight - AndroidUtilities.dp(2));
@ -1012,7 +1065,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
ResourceLoader.errorDrawable.draw(canvas); ResourceLoader.errorDrawable.draw(canvas);
} }
} else { } else {
Drawable countDrawable = ResourceLoader.viewsMediaCountDrawable[isDrawSelectedBackground() ? 1 : 0]; Drawable countDrawable = ResourceLoader.viewsMediaCountDrawable;
setDrawableBounds(countDrawable, timeX, layoutHeight - AndroidUtilities.dp(10) - timeLayout.getHeight()); setDrawableBounds(countDrawable, timeX, layoutHeight - AndroidUtilities.dp(10) - timeLayout.getHeight());
countDrawable.draw(canvas); countDrawable.draw(canvas);
@ -1047,8 +1100,8 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
} }
} else { } else {
if (!currentMessageObject.isOutOwner()) { if (!currentMessageObject.isOutOwner()) {
setDrawableBounds(ResourceLoader.viewsCountDrawable, timeX, layoutHeight - AndroidUtilities.dp(4.5f) - timeLayout.getHeight()); setDrawableBounds(ResourceLoader.viewsCountDrawable[isDrawSelectedBackground() ? 1 : 0], timeX, layoutHeight - AndroidUtilities.dp(4.5f) - timeLayout.getHeight());
ResourceLoader.viewsCountDrawable.draw(canvas); ResourceLoader.viewsCountDrawable[isDrawSelectedBackground() ? 1 : 0].draw(canvas);
} else { } else {
setDrawableBounds(ResourceLoader.viewsOutCountDrawable, timeX, layoutHeight - AndroidUtilities.dp(4.5f) - timeLayout.getHeight()); setDrawableBounds(ResourceLoader.viewsOutCountDrawable, timeX, layoutHeight - AndroidUtilities.dp(4.5f) - timeLayout.getHeight());
ResourceLoader.viewsOutCountDrawable.draw(canvas); ResourceLoader.viewsOutCountDrawable.draw(canvas);

View File

@ -112,7 +112,7 @@ public class ChatContactCell extends ChatBaseCell {
if (x >= avatarImage.getImageX() && x <= avatarImage.getImageX() + namesWidth + AndroidUtilities.dp(42) && y >= avatarImage.getImageY() && y <= avatarImage.getImageY() + avatarImage.getImageHeight()) { if (x >= avatarImage.getImageX() && x <= avatarImage.getImageX() + namesWidth + AndroidUtilities.dp(42) && y >= avatarImage.getImageY() && y <= avatarImage.getImageY() + avatarImage.getImageHeight()) {
avatarPressed = true; avatarPressed = true;
result = true; result = true;
} else if (x >= avatarImage.getImageX() + namesWidth + AndroidUtilities.dp(52) && y >= AndroidUtilities.dp(13) + namesOffset && x <= avatarImage.getImageX() + namesWidth + AndroidUtilities.dp(92) && y <= AndroidUtilities.dp(52) + namesOffset) { } else if (drawAddButton && x >= avatarImage.getImageX() + namesWidth + AndroidUtilities.dp(52) && y >= AndroidUtilities.dp(13) + namesOffset && x <= avatarImage.getImageX() + namesWidth + AndroidUtilities.dp(92) && y <= AndroidUtilities.dp(52) + namesOffset) {
buttonPressed = true; buttonPressed = true;
result = true; result = true;
} }
@ -196,7 +196,20 @@ public class ChatContactCell extends ChatBaseCell {
} }
avatarImage.setImage(currentPhoto, "50_50", avatarDrawable, null, false); avatarImage.setImage(currentPhoto, "50_50", avatarDrawable, null, false);
String phone = messageObject.messageOwner.media.phone_number;
if (phone != null && phone.length() != 0) {
if (!phone.startsWith("+")) {
phone = "+" + phone;
}
phone = PhoneFormat.getInstance().format(phone);
} else {
phone = LocaleController.getString("NumberUnknown", R.string.NumberUnknown);
}
String currentNameString = ContactsController.formatName(messageObject.messageOwner.media.first_name, messageObject.messageOwner.media.last_name); String currentNameString = ContactsController.formatName(messageObject.messageOwner.media.first_name, messageObject.messageOwner.media.last_name);
if (currentNameString.length() == 0) {
currentNameString = phone;
}
int nameWidth = Math.min((int) Math.ceil(namePaint.measureText(currentNameString)), maxWidth); int nameWidth = Math.min((int) Math.ceil(namePaint.measureText(currentNameString)), maxWidth);
if (maxWidth < 0) { if (maxWidth < 0) {
maxWidth = AndroidUtilities.dp(100); maxWidth = AndroidUtilities.dp(100);
@ -210,15 +223,7 @@ public class ChatContactCell extends ChatBaseCell {
nameWidth = 0; nameWidth = 0;
} }
String phone = messageObject.messageOwner.media.phone_number;
if (phone != null && phone.length() != 0) {
if (!phone.startsWith("+")) {
phone = "+" + phone;
}
phone = PhoneFormat.getInstance().format(phone);
} else {
phone = LocaleController.getString("NumberUnknown", R.string.NumberUnknown);
}
int phoneWidth = Math.min((int) Math.ceil(phonePaint.measureText(phone)), maxWidth); int phoneWidth = Math.min((int) Math.ceil(phonePaint.measureText(phone)), maxWidth);
stringFinal = TextUtils.ellipsize(phone.replace("\n", " "), phonePaint, phoneWidth, TextUtils.TruncateAt.END); stringFinal = TextUtils.ellipsize(phone.replace("\n", " "), phonePaint, phoneWidth, TextUtils.TruncateAt.END);
phoneLayout = new StaticLayout(stringFinal, phonePaint, phoneWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); phoneLayout = new StaticLayout(stringFinal, phonePaint, phoneWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
@ -230,6 +235,7 @@ public class ChatContactCell extends ChatBaseCell {
namesWidth = Math.max(nameWidth, phoneWidth); namesWidth = Math.max(nameWidth, phoneWidth);
backgroundWidth = AndroidUtilities.dp(77 + (drawAddButton ? 42 : 0)) + namesWidth; backgroundWidth = AndroidUtilities.dp(77 + (drawAddButton ? 42 : 0)) + namesWidth;
availableTimeWidth = backgroundWidth - AndroidUtilities.dp(29);
super.setMessageObject(messageObject); super.setMessageObject(messageObject);
} }
@ -237,7 +243,7 @@ public class ChatContactCell extends ChatBaseCell {
@Override @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(71) + namesOffset); setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(75) + namesOffset);
} }
@Override @Override
@ -253,7 +259,7 @@ public class ChatContactCell extends ChatBaseCell {
if (currentMessageObject.isOutOwner()) { if (currentMessageObject.isOutOwner()) {
x = layoutWidth - backgroundWidth + AndroidUtilities.dp(8); x = layoutWidth - backgroundWidth + AndroidUtilities.dp(8);
} else { } else {
if (isChat && currentMessageObject.messageOwner.from_id > 0) { if (isChat && currentMessageObject.isFromUser()) {
x = AndroidUtilities.dp(69); x = AndroidUtilities.dp(69);
} else { } else {
x = AndroidUtilities.dp(16); x = AndroidUtilities.dp(16);

View File

@ -21,6 +21,7 @@ import android.text.StaticLayout;
import android.text.TextPaint; import android.text.TextPaint;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.style.ClickableSpan; import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.SoundEffectConstants; import android.view.SoundEffectConstants;
@ -39,6 +40,7 @@ import org.telegram.ui.Components.RadialProgress;
import org.telegram.ui.Components.ResourceLoader; import org.telegram.ui.Components.ResourceLoader;
import org.telegram.ui.Components.StaticLayoutEx; import org.telegram.ui.Components.StaticLayoutEx;
import org.telegram.ui.Components.URLSpanBotCommand; import org.telegram.ui.Components.URLSpanBotCommand;
import org.telegram.ui.Components.URLSpanNoUnderline;
import org.telegram.ui.PhotoViewer; import org.telegram.ui.PhotoViewer;
import org.telegram.messenger.ImageReceiver; import org.telegram.messenger.ImageReceiver;
@ -417,7 +419,7 @@ public class ChatMediaCell extends ChatBaseCell {
} else if (currentMessageObject.type == 9) { } else if (currentMessageObject.type == 9) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, false, false); FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, false, false);
} else if (currentMessageObject.type == 3) { } else if (currentMessageObject.type == 3) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.video, true); FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
} }
buttonState = 1; buttonState = 1;
radialProgress.setBackground(getDrawableForCurrentState(), true, animated); radialProgress.setBackground(getDrawableForCurrentState(), true, animated);
@ -431,10 +433,8 @@ public class ChatMediaCell extends ChatBaseCell {
cancelLoading = true; cancelLoading = true;
if (currentMessageObject.type == 1 || currentMessageObject.type == 8) { if (currentMessageObject.type == 1 || currentMessageObject.type == 8) {
photoImage.cancelLoadImage(); photoImage.cancelLoadImage();
} else if (currentMessageObject.type == 9) { } else if (currentMessageObject.type == 9 || currentMessageObject.type == 3) {
FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.document); FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.document);
} else if (currentMessageObject.type == 3) {
FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.video);
} }
buttonState = 0; buttonState = 0;
radialProgress.setBackground(getDrawableForCurrentState(), false, animated); radialProgress.setBackground(getDrawableForCurrentState(), false, animated);
@ -475,12 +475,23 @@ public class ChatMediaCell extends ChatBaseCell {
return false; return false;
} }
@Override
protected void onLongPress() {
if (pressedLink instanceof URLSpanNoUnderline) {
} else if (pressedLink instanceof URLSpan) {
delegate.didPressUrl(currentMessageObject, pressedLink, true);
return;
}
super.onLongPress();
}
@Override @Override
public void setMessageObject(MessageObject messageObject) { public void setMessageObject(MessageObject messageObject) {
boolean messageChanged = currentMessageObject != messageObject; boolean messageChanged = currentMessageObject != messageObject;
boolean dataChanged = currentMessageObject == messageObject && (isUserDataChanged() || photoNotSet); boolean dataChanged = currentMessageObject == messageObject && (isUserDataChanged() || photoNotSet);
if (currentMessageObject != messageObject || isPhotoDataChanged(messageObject) || dataChanged) { if (currentMessageObject != messageObject || isPhotoDataChanged(messageObject) || dataChanged) {
drawForwardedName = messageObject.messageOwner.fwd_from_id != null && messageObject.type != 13; drawForwardedName = messageObject.messageOwner.fwd_from != null && messageObject.type != 13;
media = messageObject.type != 9; media = messageObject.type != 9;
cancelLoading = false; cancelLoading = false;
additionHeight = 0; additionHeight = 0;
@ -510,14 +521,24 @@ public class ChatMediaCell extends ChatBaseCell {
} else { } else {
maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122 + 86 + 24); maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122 + 86 + 24);
} }
if (checkNeedDrawShareButton(messageObject)) {
maxWidth -= AndroidUtilities.dp(20);
}
if (currentNameString == null || !currentNameString.equals(name)) { if (currentNameString == null || !currentNameString.equals(name)) {
currentNameString = name; currentNameString = name;
nameLayout = StaticLayoutEx.createStaticLayout(currentNameString, namePaint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false, TextUtils.TruncateAt.END, maxWidth, 1); nameLayout = StaticLayoutEx.createStaticLayout(currentNameString, namePaint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false, TextUtils.TruncateAt.MIDDLE, maxWidth, 3);
nameOffsetX = Integer.MIN_VALUE;
if (nameLayout != null && nameLayout.getLineCount() > 0) { if (nameLayout != null && nameLayout.getLineCount() > 0) {
nameWidth = Math.min(maxWidth, (int) Math.ceil(nameLayout.getLineWidth(0))); int maxLineWidth = 0;
nameOffsetX = (int) Math.ceil(-nameLayout.getLineLeft(0)); int maxLeft = 0;
for (int a = 0; a < nameLayout.getLineCount(); a++) {
maxLineWidth = Math.max(maxLineWidth, (int) Math.ceil(nameLayout.getLineWidth(a)));
nameOffsetX = Math.max(maxLeft, (int) Math.ceil(-nameLayout.getLineLeft(a)));
}
nameWidth = Math.min(maxWidth, maxLineWidth);
} else { } else {
nameWidth = maxWidth; nameWidth = maxWidth;
nameOffsetX = 0;
} }
} }
@ -528,7 +549,14 @@ public class ChatMediaCell extends ChatBaseCell {
infoOffset = 0; infoOffset = 0;
infoWidth = Math.min(maxWidth, (int) Math.ceil(infoPaint.measureText(currentInfoString))); infoWidth = Math.min(maxWidth, (int) Math.ceil(infoPaint.measureText(currentInfoString)));
CharSequence str2 = TextUtils.ellipsize(currentInfoString, infoPaint, infoWidth, TextUtils.TruncateAt.END); CharSequence str2 = TextUtils.ellipsize(currentInfoString, infoPaint, infoWidth, TextUtils.TruncateAt.END);
infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); try {
if (infoWidth < 0) {
infoWidth = AndroidUtilities.dp(10);
}
infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
} else if (messageObject.type == 8) { } else if (messageObject.type == 8) {
String str = AndroidUtilities.formatFileSize(messageObject.messageOwner.media.document.size); String str = AndroidUtilities.formatFileSize(messageObject.messageOwner.media.document.size);
@ -541,10 +569,17 @@ public class ChatMediaCell extends ChatBaseCell {
nameLayout = null; nameLayout = null;
currentNameString = null; currentNameString = null;
} else if (messageObject.type == 3) { } else if (messageObject.type == 3) {
int duration = messageObject.messageOwner.media.video.duration; int duration = 0;
for (int a = 0; a < messageObject.messageOwner.media.document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = messageObject.messageOwner.media.document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
duration = attribute.duration;
break;
}
}
int minutes = duration / 60; int minutes = duration / 60;
int seconds = duration - minutes * 60; int seconds = duration - minutes * 60;
String str = String.format("%d:%02d, %s", minutes, seconds, AndroidUtilities.formatFileSize(messageObject.messageOwner.media.video.size)); String str = String.format("%d:%02d, %s", minutes, seconds, AndroidUtilities.formatFileSize(messageObject.messageOwner.media.document.size));
if (currentInfoString == null || !currentInfoString.equals(str)) { if (currentInfoString == null || !currentInfoString.equals(str)) {
currentInfoString = str; currentInfoString = str;
infoOffset = ResourceLoader.videoIconDrawable.getIntrinsicWidth() + AndroidUtilities.dp(4); infoOffset = ResourceLoader.videoIconDrawable.getIntrinsicWidth() + AndroidUtilities.dp(4);
@ -560,10 +595,11 @@ public class ChatMediaCell extends ChatBaseCell {
nameLayout = null; nameLayout = null;
updateSecretTimeText(messageObject); updateSecretTimeText(messageObject);
} }
if (messageObject.type == 9) { //doc if (messageObject.type == 9) {
photoWidth = AndroidUtilities.dp(86); photoWidth = AndroidUtilities.dp(86);
photoHeight = AndroidUtilities.dp(86); photoHeight = AndroidUtilities.dp(86);
backgroundWidth = photoWidth + Math.max(nameWidth, infoWidth) + AndroidUtilities.dp(68); availableTimeWidth = Math.max(nameWidth, infoWidth) + AndroidUtilities.dp(37);
backgroundWidth = photoWidth + availableTimeWidth + AndroidUtilities.dp(31);
currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, AndroidUtilities.getPhotoSize()); currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, AndroidUtilities.getPhotoSize());
photoImage.setNeedsQualityThumb(true); photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true); photoImage.setShouldGenerateQualityThumb(true);
@ -589,6 +625,7 @@ public class ChatMediaCell extends ChatBaseCell {
} }
media = false; media = false;
availableTimeWidth = maxWidth - AndroidUtilities.dp(7);
measureTime(messageObject); measureTime(messageObject);
photoWidth = AndroidUtilities.dp(86); photoWidth = AndroidUtilities.dp(86);
photoHeight = AndroidUtilities.dp(86); photoHeight = AndroidUtilities.dp(86);
@ -604,6 +641,7 @@ public class ChatMediaCell extends ChatBaseCell {
backgroundWidth = photoWidth + AndroidUtilities.dp(21) + maxWidth; backgroundWidth = photoWidth + AndroidUtilities.dp(21) + maxWidth;
currentUrl = String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=15&size=72x72&maptype=roadmap&scale=%d&markers=color:red|size:big|%f,%f&sensor=false", lat, lon, Math.min(2, (int) Math.ceil(AndroidUtilities.density)), lat, lon); currentUrl = String.format(Locale.US, "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=15&size=72x72&maptype=roadmap&scale=%d&markers=color:red|size:big|%f,%f&sensor=false", lat, lon, Math.min(2, (int) Math.ceil(AndroidUtilities.density)), lat, lon);
} else { } else {
availableTimeWidth = AndroidUtilities.dp(200 - 14);
photoWidth = AndroidUtilities.dp(200); photoWidth = AndroidUtilities.dp(200);
photoHeight = AndroidUtilities.dp(100); photoHeight = AndroidUtilities.dp(100);
backgroundWidth = photoWidth + AndroidUtilities.dp(12); backgroundWidth = photoWidth + AndroidUtilities.dp(12);
@ -643,6 +681,7 @@ public class ChatMediaCell extends ChatBaseCell {
photoHeight *= maxWidth / photoWidth; photoHeight *= maxWidth / photoWidth;
photoWidth = (int) maxWidth; photoWidth = (int) maxWidth;
} }
availableTimeWidth = photoWidth - AndroidUtilities.dp(14);
backgroundWidth = photoWidth + AndroidUtilities.dp(12); backgroundWidth = photoWidth + AndroidUtilities.dp(12);
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 80); currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 80);
photoImage.setNeedsQualityThumb(false); photoImage.setNeedsQualityThumb(false);
@ -667,10 +706,11 @@ public class ChatMediaCell extends ChatBaseCell {
messageObject.messageOwner.media.document.size, "webp", true); messageObject.messageOwner.media.document.size, "webp", true);
} }
} else { } else {
int maxPhotoWidth;
if (AndroidUtilities.isTablet()) { if (AndroidUtilities.isTablet()) {
photoWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.7f); maxPhotoWidth = photoWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.7f);
} else { } else {
photoWidth = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f); maxPhotoWidth = photoWidth = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f);
} }
photoHeight = photoWidth + AndroidUtilities.dp(100); photoHeight = photoWidth + AndroidUtilities.dp(100);
@ -767,6 +807,7 @@ public class ChatMediaCell extends ChatBaseCell {
w = h = AndroidUtilities.dp(100); w = h = AndroidUtilities.dp(100);
} }
availableTimeWidth = maxPhotoWidth - AndroidUtilities.dp(14);
measureTime(messageObject); measureTime(messageObject);
int timeWidthTotal = timeWidth + AndroidUtilities.dp(14 + (messageObject.isOutOwner() ? 20 : 0)); int timeWidthTotal = timeWidth + AndroidUtilities.dp(14 + (messageObject.isOutOwner() ? 20 : 0));
if (w < timeWidthTotal) { if (w < timeWidthTotal) {
@ -1022,7 +1063,7 @@ public class ChatMediaCell extends ChatBaseCell {
x = layoutWidth - backgroundWidth + AndroidUtilities.dp(6); x = layoutWidth - backgroundWidth + AndroidUtilities.dp(6);
} }
} else { } else {
if (isChat && currentMessageObject.messageOwner.from_id > 0) { if (isChat && currentMessageObject.isFromUser()) {
x = AndroidUtilities.dp(67); x = AndroidUtilities.dp(67);
} else { } else {
x = AndroidUtilities.dp(15); x = AndroidUtilities.dp(15);
@ -1218,11 +1259,15 @@ public class ChatMediaCell extends ChatBaseCell {
nameLayout.draw(canvas); nameLayout.draw(canvas);
canvas.restore(); canvas.restore();
if (infoLayout != null) { try {
canvas.save(); if (infoLayout != null) {
canvas.translate(photoImage.getImageX() + photoImage.getImageWidth() + AndroidUtilities.dp(10), photoImage.getImageY() + AndroidUtilities.dp(30)); canvas.save();
infoLayout.draw(canvas); canvas.translate(photoImage.getImageX() + photoImage.getImageWidth() + AndroidUtilities.dp(10), photoImage.getImageY() + nameLayout.getLineBottom(nameLayout.getLineCount() - 1) + AndroidUtilities.dp(10));
canvas.restore(); infoLayout.draw(canvas);
canvas.restore();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
} }
} }

View File

@ -9,13 +9,10 @@
package org.telegram.ui.Cells; package org.telegram.ui.Cells;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.provider.Browser;
import android.text.Layout; import android.text.Layout;
import android.text.Spannable; import android.text.Spannable;
import android.text.SpannableStringBuilder; import android.text.SpannableStringBuilder;
@ -23,6 +20,7 @@ import android.text.StaticLayout;
import android.text.TextPaint; import android.text.TextPaint;
import android.text.TextUtils; import android.text.TextUtils;
import android.text.style.ClickableSpan; import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.SoundEffectConstants; import android.view.SoundEffectConstants;
import android.view.ViewStructure; import android.view.ViewStructure;
@ -218,7 +216,11 @@ public class ChatMessageCell extends ChatBaseCell {
} else if (linkPreviewPressed) { } else if (linkPreviewPressed) {
try { try {
if (pressedLink != null) { if (pressedLink != null) {
pressedLink.onClick(this); if (pressedLink instanceof URLSpan) {
AndroidUtilities.openUrl(getContext(), ((URLSpan) pressedLink).getURL());
} else {
pressedLink.onClick(this);
}
} else { } else {
if (drawImageButton && delegate != null) { if (drawImageButton && delegate != null) {
if (isGifDocument) { if (isGifDocument) {
@ -243,10 +245,7 @@ public class ChatMessageCell extends ChatBaseCell {
if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null && webPage.embed_url.length() != 0) { if (Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null && webPage.embed_url.length() != 0) {
delegate.needOpenWebView(webPage.embed_url, webPage.site_name, webPage.url, webPage.embed_width, webPage.embed_height); delegate.needOpenWebView(webPage.embed_url, webPage.site_name, webPage.url, webPage.embed_width, webPage.embed_height);
} else { } else {
Uri uri = Uri.parse(webPage.url); AndroidUtilities.openUrl(getContext(), webPage.url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getContext().getPackageName());
getContext().startActivity(intent);
} }
} }
} }
@ -388,6 +387,9 @@ public class ChatMessageCell extends ChatBaseCell {
delegate.didPressUrl(currentMessageObject, pressedLink, true); delegate.didPressUrl(currentMessageObject, pressedLink, true);
return; return;
} }
} else if (pressedLink instanceof URLSpan) {
delegate.didPressUrl(currentMessageObject, pressedLink, true);
return;
} }
super.onLongPress(); super.onLongPress();
} }
@ -420,7 +422,7 @@ public class ChatMessageCell extends ChatBaseCell {
int maxWidth; int maxWidth;
if (AndroidUtilities.isTablet()) { if (AndroidUtilities.isTablet()) {
if (isChat && !messageObject.isOutOwner() && messageObject.messageOwner.from_id > 0) { if (isChat && !messageObject.isOutOwner() && messageObject.isFromUser()) {
maxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(122); maxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(122);
drawName = true; drawName = true;
} else { } else {
@ -428,7 +430,7 @@ public class ChatMessageCell extends ChatBaseCell {
maxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(80); maxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(80);
} }
} else { } else {
if (isChat && !messageObject.isOutOwner() && messageObject.messageOwner.from_id > 0) { if (isChat && !messageObject.isOutOwner() && messageObject.isFromUser()) {
maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122); maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122);
drawName = true; drawName = true;
} else { } else {
@ -438,6 +440,7 @@ public class ChatMessageCell extends ChatBaseCell {
} }
backgroundWidth = maxWidth; backgroundWidth = maxWidth;
availableTimeWidth = backgroundWidth - AndroidUtilities.dp(29);
super.setMessageObject(messageObject); super.setMessageObject(messageObject);
@ -458,18 +461,21 @@ public class ChatMessageCell extends ChatBaseCell {
if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageObject.messageOwner.media.webpage instanceof TLRPC.TL_webPage) { if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage && messageObject.messageOwner.media.webpage instanceof TLRPC.TL_webPage) {
int linkPreviewMaxWidth; int linkPreviewMaxWidth;
if (AndroidUtilities.isTablet()) { if (AndroidUtilities.isTablet()) {
if (messageObject.messageOwner.from_id > 0 && (currentMessageObject.messageOwner.to_id.channel_id != 0 || currentMessageObject.messageOwner.to_id.chat_id != 0) && !currentMessageObject.isOut()) { if (messageObject.isFromUser() && (currentMessageObject.messageOwner.to_id.channel_id != 0 || currentMessageObject.messageOwner.to_id.chat_id != 0) && !currentMessageObject.isOut()) {
linkPreviewMaxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(122); linkPreviewMaxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(122);
} else { } else {
linkPreviewMaxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(80); linkPreviewMaxWidth = AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(80);
} }
} else { } else {
if (messageObject.messageOwner.from_id > 0 && (currentMessageObject.messageOwner.to_id.channel_id != 0 || currentMessageObject.messageOwner.to_id.chat_id != 0) && !currentMessageObject.isOutOwner()) { if (messageObject.isFromUser() && (currentMessageObject.messageOwner.to_id.channel_id != 0 || currentMessageObject.messageOwner.to_id.chat_id != 0) && !currentMessageObject.isOutOwner()) {
linkPreviewMaxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122); linkPreviewMaxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(122);
} else { } else {
linkPreviewMaxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(80); linkPreviewMaxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(80);
} }
} }
if (drawShareButton) {
linkPreviewMaxWidth -= AndroidUtilities.dp(20);
}
TLRPC.TL_webPage webPage = (TLRPC.TL_webPage) messageObject.messageOwner.media.webpage; TLRPC.TL_webPage webPage = (TLRPC.TL_webPage) messageObject.messageOwner.media.webpage;
@ -791,6 +797,7 @@ public class ChatMessageCell extends ChatBaseCell {
if (hasLinkPreview || maxWidth - messageObject.lastLineWidth < timeMore) { if (hasLinkPreview || maxWidth - messageObject.lastLineWidth < timeMore) {
totalHeight += AndroidUtilities.dp(14); totalHeight += AndroidUtilities.dp(14);
backgroundWidth = Math.max(maxChildWidth, messageObject.lastLineWidth) + AndroidUtilities.dp(29); backgroundWidth = Math.max(maxChildWidth, messageObject.lastLineWidth) + AndroidUtilities.dp(29);
backgroundWidth = Math.max(backgroundWidth, timeWidth + AndroidUtilities.dp(29));
} else { } else {
int diff = maxChildWidth - messageObject.lastLineWidth; int diff = maxChildWidth - messageObject.lastLineWidth;
if (diff >= 0 && diff <= timeMore) { if (diff >= 0 && diff <= timeMore) {
@ -816,7 +823,7 @@ public class ChatMessageCell extends ChatBaseCell {
textX = layoutWidth - backgroundWidth + AndroidUtilities.dp(10); textX = layoutWidth - backgroundWidth + AndroidUtilities.dp(10);
textY = AndroidUtilities.dp(10) + namesOffset; textY = AndroidUtilities.dp(10) + namesOffset;
} else { } else {
textX = AndroidUtilities.dp(19) + (isChat && currentMessageObject.messageOwner.from_id > 0 ? AndroidUtilities.dp(52) : 0); textX = AndroidUtilities.dp(19) + (isChat && currentMessageObject.isFromUser() ? AndroidUtilities.dp(52) : 0);
textY = AndroidUtilities.dp(10) + namesOffset; textY = AndroidUtilities.dp(10) + namesOffset;
} }
} }
@ -832,7 +839,7 @@ public class ChatMessageCell extends ChatBaseCell {
textX = layoutWidth - backgroundWidth + AndroidUtilities.dp(10); textX = layoutWidth - backgroundWidth + AndroidUtilities.dp(10);
textY = AndroidUtilities.dp(10) + namesOffset; textY = AndroidUtilities.dp(10) + namesOffset;
} else { } else {
textX = AndroidUtilities.dp(19) + (isChat && currentMessageObject.messageOwner.from_id > 0 ? AndroidUtilities.dp(52) : 0); textX = AndroidUtilities.dp(19) + (isChat && currentMessageObject.isFromUser() ? AndroidUtilities.dp(52) : 0);
textY = AndroidUtilities.dp(10) + namesOffset; textY = AndroidUtilities.dp(10) + namesOffset;
} }

View File

@ -68,7 +68,7 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
super(context); super(context);
seekBar = new SeekBar(context); seekBar = new SeekBar(context);
seekBar.delegate = this; seekBar.setDelegate(this);
radialProgress = new RadialProgress(this); radialProgress = new RadialProgress(this);
drawForwardedName = false; drawForwardedName = false;
@ -194,7 +194,8 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
int duration = 0; int duration = 0;
int currentProgress = 0; int currentProgress = 0;
for (TLRPC.DocumentAttribute attribute : currentMessageObject.messageOwner.media.document.attributes) { for (int a = 0; a < currentMessageObject.messageOwner.media.document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = currentMessageObject.messageOwner.media.document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) { if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
duration = attribute.duration; duration = attribute.duration;
break; break;
@ -323,7 +324,7 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
buttonX = layoutWidth - backgroundWidth + AndroidUtilities.dp(13); buttonX = layoutWidth - backgroundWidth + AndroidUtilities.dp(13);
timeX = layoutWidth - backgroundWidth + AndroidUtilities.dp(63); timeX = layoutWidth - backgroundWidth + AndroidUtilities.dp(63);
} else { } else {
if (isChat && currentMessageObject.messageOwner.from_id > 0) { if (isChat && currentMessageObject.isFromUser()) {
seekBarX = AndroidUtilities.dp(113); seekBarX = AndroidUtilities.dp(113);
buttonX = AndroidUtilities.dp(74); buttonX = AndroidUtilities.dp(74);
timeX = AndroidUtilities.dp(124); timeX = AndroidUtilities.dp(124);
@ -348,9 +349,9 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
boolean dataChanged = currentMessageObject == messageObject && isUserDataChanged(); boolean dataChanged = currentMessageObject == messageObject && isUserDataChanged();
if (currentMessageObject != messageObject || dataChanged) { if (currentMessageObject != messageObject || dataChanged) {
if (AndroidUtilities.isTablet()) { if (AndroidUtilities.isTablet()) {
backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(isChat && messageObject.messageOwner.from_id > 0 ? 102 : 50), AndroidUtilities.dp(300)); backgroundWidth = Math.min(AndroidUtilities.getMinTabletSide() - AndroidUtilities.dp(isChat && messageObject.isFromUser() && !messageObject.isOutOwner() ? 102 : 50), AndroidUtilities.dp(300));
} else { } else {
backgroundWidth = Math.min(AndroidUtilities.displaySize.x - AndroidUtilities.dp(isChat && messageObject.messageOwner.from_id > 0 ? 102 : 50), AndroidUtilities.dp(300)); backgroundWidth = Math.min(AndroidUtilities.displaySize.x - AndroidUtilities.dp(isChat && messageObject.isFromUser() && !messageObject.isOutOwner() ? 102 : 50), AndroidUtilities.dp(300));
} }
if (messageObject.isOutOwner()) { if (messageObject.isOutOwner()) {
@ -375,6 +376,16 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
authorX = -(int) Math.ceil(authorLayout.getLineLeft(0)); authorX = -(int) Math.ceil(authorLayout.getLineLeft(0));
} }
int duration = 0;
for (int a = 0; a < messageObject.messageOwner.media.document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = messageObject.messageOwner.media.document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
duration = attribute.duration;
break;
}
}
availableTimeWidth = backgroundWidth - AndroidUtilities.dp(72 + 14) - (int) Math.ceil(timePaint.measureText(String.format("%d:%02d / %d:%02d", duration / 60, duration % 60, duration / 60, duration % 60)));
super.setMessageObject(messageObject); super.setMessageObject(messageObject);
} }
updateButtonState(dataChanged); updateButtonState(dataChanged);

View File

@ -434,10 +434,10 @@ public class ContextLinkCell extends View implements MediaController.FileDownloa
fileName = FileLoader.getAttachFileName(result.document); fileName = FileLoader.getAttachFileName(result.document);
cacheFile = FileLoader.getPathToAttach(result.document); cacheFile = FileLoader.getPathToAttach(result.document);
} else if (result.content_url != null) { } else if (result.content_url != null) {
fileName = Utilities.MD5(result.content_url) + "." + ImageLoader.getHttpUrlExtension(result.content_url); fileName = Utilities.MD5(result.content_url) + "." + ImageLoader.getHttpUrlExtension(result.content_url, "jpg");
cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName);
} else if (result.thumb_url != null) { } else if (result.thumb_url != null) {
fileName = Utilities.MD5(result.thumb_url) + "." + ImageLoader.getHttpUrlExtension(result.thumb_url); fileName = Utilities.MD5(result.thumb_url) + "." + ImageLoader.getHttpUrlExtension(result.thumb_url, "jpg");
cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName); cacheFile = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName);
} }
} else if (gif != null) { } else if (gif != null) {

View File

@ -358,10 +358,10 @@ public class DialogCell extends BaseCell {
} else { } else {
TLRPC.User fromUser = null; TLRPC.User fromUser = null;
TLRPC.Chat fromChat = null; TLRPC.Chat fromChat = null;
if (message.messageOwner.from_id > 0) { if (message.isFromUser()) {
fromUser = MessagesController.getInstance().getUser(message.messageOwner.from_id); fromUser = MessagesController.getInstance().getUser(message.messageOwner.from_id);
} else if (message.messageOwner.from_id < 0) { } else {
fromChat = MessagesController.getInstance().getChat(-message.messageOwner.from_id); fromChat = MessagesController.getInstance().getChat(message.messageOwner.to_id.channel_id);
} }
if (lastMessageDate != 0) { if (lastMessageDate != 0) {
@ -859,7 +859,11 @@ public class DialogCell extends BaseCell {
if (messageLayout != null) { if (messageLayout != null) {
canvas.save(); canvas.save();
canvas.translate(messageLeft, messageTop); canvas.translate(messageLeft, messageTop);
messageLayout.draw(canvas); try {
messageLayout.draw(canvas);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
canvas.restore(); canvas.restore();
} }

View File

@ -16,6 +16,7 @@ import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.R;
import org.telegram.messenger.UserObject; import org.telegram.messenger.UserObject;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.AvatarDrawable;
@ -34,6 +35,8 @@ public class MentionCell extends LinearLayout {
setOrientation(HORIZONTAL); setOrientation(HORIZONTAL);
setBackgroundResource(R.drawable.list_selector);
avatarDrawable = new AvatarDrawable(); avatarDrawable = new AvatarDrawable();
avatarDrawable.setSmallStyle(true); avatarDrawable.setSmallStyle(true);

View File

@ -22,14 +22,14 @@ import org.telegram.messenger.LocaleController;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.RadioButton; import org.telegram.ui.Components.RadioButton;
public class LastSeenRadioCell extends FrameLayout { public class RadioCell extends FrameLayout {
private TextView textView; private TextView textView;
private RadioButton radioButton; private RadioButton radioButton;
private static Paint paint; private static Paint paint;
private boolean needDivider; private boolean needDivider;
public LastSeenRadioCell(Context context) { public RadioCell(Context context) {
super(context); super(context);
if (paint == null) { if (paint == null) {

View File

@ -207,6 +207,11 @@ public class SharedDocumentCell extends FrameLayout implements MediaController.F
if (document != null && document.messageOwner.media != null && document.messageOwner.media.document != null) { if (document != null && document.messageOwner.media != null && document.messageOwner.media.document != null) {
int idx; int idx;
String name = FileLoader.getDocumentFileName(document.messageOwner.media.document); String name = FileLoader.getDocumentFileName(document.messageOwner.media.document);
if (name.length() == 0) {
if (document.isMusic()) {
name = document.getMusicAuthor() + " - " + document.getMusicTitle();
}
}
placeholderImabeView.setVisibility(VISIBLE); placeholderImabeView.setVisibility(VISIBLE);
extTextView.setVisibility(VISIBLE); extTextView.setVisibility(VISIBLE);
placeholderImabeView.setImageResource(getThumbForNameOrMime(name, document.messageOwner.media.document.mime_type)); placeholderImabeView.setImageResource(getThumbForNameOrMime(name, document.messageOwner.media.document.mime_type));

View File

@ -390,10 +390,7 @@ public class SharedLinkCell extends FrameLayout {
if (webPage != null && Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null && webPage.embed_url.length() != 0) { if (webPage != null && Build.VERSION.SDK_INT >= 16 && webPage.embed_url != null && webPage.embed_url.length() != 0) {
delegate.needOpenWebView(webPage); delegate.needOpenWebView(webPage);
} else { } else {
Uri uri = Uri.parse(links.get(pressedLink)); AndroidUtilities.openUrl(getContext(), links.get(pressedLink));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getContext().getPackageName());
getContext().startActivity(intent);
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);

View File

@ -226,14 +226,21 @@ public class SharedPhotoVideoCell extends FrameLayoutFixed {
PhotoVideoView photoVideoView = photoVideoViews[a]; PhotoVideoView photoVideoView = photoVideoViews[a];
photoVideoView.imageView.getImageReceiver().setParentMessageObject(messageObject); photoVideoView.imageView.getImageReceiver().setParentMessageObject(messageObject);
photoVideoView.imageView.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(messageObject), false); photoVideoView.imageView.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(messageObject), false);
if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo && messageObject.messageOwner.media.video != null) { if (messageObject.isVideo()) {
photoVideoView.videoInfoContainer.setVisibility(VISIBLE); photoVideoView.videoInfoContainer.setVisibility(VISIBLE);
int duration = messageObject.messageOwner.media.video.duration; int duration = 0;
for (int b = 0; b < messageObject.messageOwner.media.document.attributes.size(); b++) {
TLRPC.DocumentAttribute attribute = messageObject.messageOwner.media.document.attributes.get(b);
if (attribute instanceof TLRPC.TL_documentAttributeVideo) {
duration = attribute.duration;
break;
}
}
int minutes = duration / 60; int minutes = duration / 60;
int seconds = duration - minutes * 60; int seconds = duration - minutes * 60;
photoVideoView.videoTextView.setText(String.format("%d:%02d", minutes, seconds)); photoVideoView.videoTextView.setText(String.format("%d:%02d", minutes, seconds));
if (messageObject.messageOwner.media.video.thumb != null) { if (messageObject.messageOwner.media.document.thumb != null) {
TLRPC.FileLocation location = messageObject.messageOwner.media.video.thumb.location; TLRPC.FileLocation location = messageObject.messageOwner.media.document.thumb.location;
photoVideoView.imageView.setImage(null, null, null, ApplicationLoader.applicationContext.getResources().getDrawable(R.drawable.photo_placeholder_in), null, location, "b", null, 0); photoVideoView.imageView.setImage(null, null, null, ApplicationLoader.applicationContext.getResources().getDrawable(R.drawable.photo_placeholder_in), null, location, "b", null, 0);
} else { } else {
photoVideoView.imageView.setImageResource(R.drawable.photo_placeholder_in); photoVideoView.imageView.setImageResource(R.drawable.photo_placeholder_in);

View File

@ -9,7 +9,11 @@
package org.telegram.ui.Cells; package org.telegram.ui.Cells;
import android.content.Context; import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.view.Gravity; import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.R; import org.telegram.messenger.R;
@ -21,6 +25,12 @@ import org.telegram.ui.Components.LayoutHelper;
public class StickerCell extends FrameLayoutFixed { public class StickerCell extends FrameLayoutFixed {
private BackupImageView imageView; private BackupImageView imageView;
private TLRPC.Document sticker;
private long lastUpdateTime;
private boolean scaled;
private float scale;
private long time = 0;
private static AccelerateInterpolator interpolator = new AccelerateInterpolator(0.5f);
public StickerCell(Context context) { public StickerCell(Context context) {
super(context); super(context);
@ -48,6 +58,7 @@ public class StickerCell extends FrameLayoutFixed {
if (document != null && document.thumb != null) { if (document != null && document.thumb != null) {
imageView.setImage(document.thumb.location, null, "webp", null); imageView.setImage(document.thumb.location, null, "webp", null);
} }
sticker = document;
if (side == -1) { if (side == -1) {
setBackgroundResource(R.drawable.stickers_back_left); setBackgroundResource(R.drawable.stickers_back_left);
setPadding(AndroidUtilities.dp(7), 0, 0, 0); setPadding(AndroidUtilities.dp(7), 0, 0, 0);
@ -65,4 +76,46 @@ public class StickerCell extends FrameLayoutFixed {
getBackground().setAlpha(230); getBackground().setAlpha(230);
} }
} }
public TLRPC.Document getSticker() {
return sticker;
}
public void setScaled(boolean value) {
scaled = value;
lastUpdateTime = System.currentTimeMillis();
invalidate();
}
public boolean showingBitmap() {
return imageView.getImageReceiver().getBitmap() != null;
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child == imageView && (scaled && scale != 0.8f || !scaled && scale != 1.0f)) {
long newTime = System.currentTimeMillis();
long dt = (newTime - lastUpdateTime);
lastUpdateTime = newTime;
if (scaled && scale != 0.8f) {
scale -= dt / 400.0f;
if (scale < 0.8f) {
scale = 0.8f;
}
} else {
scale += dt / 400.0f;
if (scale > 1.0f) {
scale = 1.0f;
}
}
if (Build.VERSION.SDK_INT >= 11) {
imageView.setScaleX(scale);
imageView.setScaleY(scale);
}
imageView.invalidate();
invalidate();
}
return result;
}
} }

View File

@ -36,7 +36,7 @@ public class StickerEmojiCell extends FrameLayout {
private boolean scaled; private boolean scaled;
private float scale; private float scale;
private long time = 0; private long time = 0;
private AccelerateInterpolator interpolator = new AccelerateInterpolator(0.5f); private static AccelerateInterpolator interpolator = new AccelerateInterpolator(0.5f);
public StickerEmojiCell(Context context) { public StickerEmojiCell(Context context) {
super(context); super(context);
@ -63,7 +63,8 @@ public class StickerEmojiCell extends FrameLayout {
if (showEmoji) { if (showEmoji) {
boolean set = false; boolean set = false;
for (TLRPC.DocumentAttribute attribute : document.attributes) { for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeSticker) { if (attribute instanceof TLRPC.TL_documentAttributeSticker) {
if (attribute.alt != null && attribute.alt.length() > 0) { if (attribute.alt != null && attribute.alt.length() > 0) {
emojiTextView.setText(Emoji.replaceEmoji(attribute.alt, emojiTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(16), false)); emojiTextView.setText(Emoji.replaceEmoji(attribute.alt, emojiTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(16), false));

View File

@ -252,7 +252,7 @@ public class ChannelCreateActivity extends BaseFragment implements NotificationC
progressDialog.show(); progressDialog.show();
return; return;
} }
final int reqId = MessagesController.getInstance().createChat(nameTextView.getText().toString(), new ArrayList<Integer>(), descriptionTextView.getText().toString(), ChatObject.CHAT_TYPE_CHANNEL); final int reqId = MessagesController.getInstance().createChat(nameTextView.getText().toString(), new ArrayList<Integer>(), descriptionTextView.getText().toString(), ChatObject.CHAT_TYPE_CHANNEL, ChannelCreateActivity.this);
progressDialog = new ProgressDialog(getParentActivity()); progressDialog = new ProgressDialog(getParentActivity());
progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCanceledOnTouchOutside(false);

View File

@ -47,6 +47,7 @@ import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Cells.ShadowSectionCell; import org.telegram.ui.Cells.ShadowSectionCell;
import org.telegram.ui.Cells.TextCheckCell;
import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Cells.TextInfoPrivacyCell;
import org.telegram.ui.Cells.TextSettingsCell; import org.telegram.ui.Cells.TextSettingsCell;
import org.telegram.ui.Components.AvatarDrawable; import org.telegram.ui.Components.AvatarDrawable;
@ -81,6 +82,7 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
private TLRPC.InputFile uploadedAvatar; private TLRPC.InputFile uploadedAvatar;
private boolean wasPrivate; private boolean wasPrivate;
private boolean privateAlertShown; private boolean privateAlertShown;
private boolean signMessages;
private boolean createAfterUpload; private boolean createAfterUpload;
private boolean donePressed; private boolean donePressed;
@ -133,6 +135,7 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
avatarUpdater.parentFragment = this; avatarUpdater.parentFragment = this;
avatarUpdater.delegate = this; avatarUpdater.delegate = this;
allowComments = !currentChat.broadcast; allowComments = !currentChat.broadcast;
signMessages = currentChat.signatures;
return super.onFragmentCreate(); return super.onFragmentCreate();
} }
@ -229,6 +232,10 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
MessagesController.getInstance().updateChannelUserName(chatId, userNameTextView.getText().toString()); MessagesController.getInstance().updateChannelUserName(chatId, userNameTextView.getText().toString());
} }
} }
if (signMessages != currentChat.signatures) {
currentChat.signatures = true;
MessagesController.getInstance().toogleChannelSignatures(chatId, signMessages);
}
if (uploadedAvatar != null) { if (uploadedAvatar != null) {
MessagesController.getInstance().changeChatAvatar(chatId, uploadedAvatar); MessagesController.getInstance().changeChatAvatar(chatId, uploadedAvatar);
} else if (avatar == null && currentChat.photo instanceof TLRPC.TL_chatPhoto) { } else if (avatar == null && currentChat.photo instanceof TLRPC.TL_chatPhoto) {
@ -392,13 +399,14 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
TextInfoPrivacyCell infoCell = new TextInfoPrivacyCell(context); TextInfoPrivacyCell infoCell = new TextInfoPrivacyCell(context);
if (currentChat.megagroup) { if (currentChat.megagroup) {
infoCell.setText(LocaleController.getString("DescriptionInfoMega", R.string.DescriptionInfoMega)); infoCell.setText(LocaleController.getString("DescriptionInfoMega", R.string.DescriptionInfoMega));
infoCell.setBackgroundResource(currentChat.creator ? R.drawable.greydivider : R.drawable.greydivider_bottom);
} else { } else {
infoCell.setText(LocaleController.getString("DescriptionInfo", R.string.DescriptionInfo)); infoCell.setText(LocaleController.getString("DescriptionInfo", R.string.DescriptionInfo));
infoCell.setBackgroundResource(R.drawable.greydivider);
} }
infoCell.setBackgroundResource(R.drawable.greydivider);
linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
if (!currentChat.megagroup) { if (/*BuildVars.DEBUG_VERSION && currentChat.megagroup && currentChat.creator || */!currentChat.megagroup) {
linearLayout2 = new LinearLayout(context); linearLayout2 = new LinearLayout(context);
linearLayout2.setOrientation(LinearLayout.VERTICAL); linearLayout2.setOrientation(LinearLayout.VERTICAL);
linearLayout2.setBackgroundColor(0xffffffff); linearLayout2.setBackgroundColor(0xffffffff);
@ -443,7 +451,11 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
if (wasPrivate && hasFocus && !privateAlertShown) { if (wasPrivate && hasFocus && !privateAlertShown) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("ChannelWasPrivateAlert", R.string.ChannelWasPrivateAlert)); if (currentChat.megagroup) {
//builder.setMessage(LocaleController.getString("MegaWasPrivateAlert", R.string.MegaWasPrivateAlert));
} else {
builder.setMessage(LocaleController.getString("ChannelWasPrivateAlert", R.string.ChannelWasPrivateAlert));
}
builder.setPositiveButton(LocaleController.getString("Close", R.string.Close), null); builder.setPositiveButton(LocaleController.getString("Close", R.string.Close), null);
showDialog(builder.create()); showDialog(builder.create());
} }
@ -476,11 +488,14 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
infoCell = new TextInfoPrivacyCell(context); infoCell = new TextInfoPrivacyCell(context);
infoCell.setBackgroundResource(R.drawable.greydivider); infoCell.setBackgroundResource(R.drawable.greydivider);
infoCell.setText(LocaleController.getString("ChannelUsernameHelp", R.string.ChannelUsernameHelp)); if (currentChat.megagroup) {
//infoCell.setText(LocaleController.getString("MegaUsernameHelp", R.string.MegaUsernameHelp));
} else {
infoCell.setText(LocaleController.getString("ChannelUsernameHelp", R.string.ChannelUsernameHelp));
}
linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
} }
/*frameLayout = new FrameLayoutFixed(context); /*frameLayout = new FrameLayoutFixed(context);
frameLayout.setBackgroundColor(0xffffffff); frameLayout.setBackgroundColor(0xffffffff);
linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
@ -502,55 +517,80 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
infoCell.setBackgroundResource(R.drawable.greydivider); infoCell.setBackgroundResource(R.drawable.greydivider);
linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));*/ linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));*/
frameLayout = new FrameLayoutFixed(context); if (!currentChat.megagroup && currentChat.creator) {
frameLayout.setBackgroundColor(0xffffffff); frameLayout = new FrameLayoutFixed(context);
linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); frameLayout.setBackgroundColor(0xffffffff);
linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
TextSettingsCell textCell = new TextSettingsCell(context); TextCheckCell textCell = new TextCheckCell(context);
textCell.setTextColor(0xffed3d39); textCell.setBackgroundResource(R.drawable.list_selector);
textCell.setBackgroundResource(R.drawable.list_selector); textCell.setTextAndCheck(LocaleController.getString("ChannelSignMessages", R.string.ChannelSignMessages), signMessages, false);
if (currentChat.megagroup) { frameLayout.addView(textCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
textCell.setText(LocaleController.getString("DeleteMega", R.string.DeleteMega), false); textCell.setOnClickListener(new View.OnClickListener() {
} else { @Override
textCell.setText(LocaleController.getString("ChannelDelete", R.string.ChannelDelete), false); public void onClick(View v) {
} signMessages = !signMessages;
frameLayout.addView(textCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT)); ((TextCheckCell) v).setChecked(signMessages);
textCell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
if (currentChat.megagroup) {
builder.setMessage(LocaleController.getString("MegaDeleteAlert", R.string.MegaDeleteAlert));
} else {
builder.setMessage(LocaleController.getString("ChannelDeleteAlert", R.string.ChannelDeleteAlert));
} }
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); });
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats);
if (AndroidUtilities.isTablet()) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats, -(long) chatId);
} else {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
}
MessagesController.getInstance().deleteUserFromChat(chatId, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), info);
finishFragment();
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
}
});
infoCell = new TextInfoPrivacyCell(context); infoCell = new TextInfoPrivacyCell(context);
infoCell.setBackgroundResource(R.drawable.greydivider_bottom); infoCell.setBackgroundResource(R.drawable.greydivider);
if (currentChat.megagroup) { infoCell.setText(LocaleController.getString("ChannelSignMessagesInfo", R.string.ChannelSignMessagesInfo));
infoCell.setText(LocaleController.getString("MegaDeleteInfo", R.string.MegaDeleteInfo)); linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
} else { }
infoCell.setText(LocaleController.getString("ChannelDeleteInfo", R.string.ChannelDeleteInfo));
if (currentChat.creator) {
frameLayout = new FrameLayoutFixed(context);
frameLayout.setBackgroundColor(0xffffffff);
linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
TextSettingsCell textCell = new TextSettingsCell(context);
textCell.setTextColor(0xffed3d39);
textCell.setBackgroundResource(R.drawable.list_selector);
if (currentChat.megagroup) {
textCell.setText(LocaleController.getString("DeleteMega", R.string.DeleteMega), false);
} else {
textCell.setText(LocaleController.getString("ChannelDelete", R.string.ChannelDelete), false);
}
frameLayout.addView(textCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
textCell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
if (currentChat.megagroup) {
builder.setMessage(LocaleController.getString("MegaDeleteAlert", R.string.MegaDeleteAlert));
} else {
builder.setMessage(LocaleController.getString("ChannelDeleteAlert", R.string.ChannelDeleteAlert));
}
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.closeChats);
if (AndroidUtilities.isTablet()) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats, -(long) chatId);
} else {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
}
MessagesController.getInstance().deleteUserFromChat(chatId, MessagesController.getInstance().getUser(UserConfig.getClientUserId()), info);
finishFragment();
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
}
});
infoCell = new TextInfoPrivacyCell(context);
infoCell.setBackgroundResource(R.drawable.greydivider_bottom);
if (currentChat.megagroup) {
infoCell.setText(LocaleController.getString("MegaDeleteInfo", R.string.MegaDeleteInfo));
} else {
infoCell.setText(LocaleController.getString("ChannelDeleteInfo", R.string.ChannelDeleteInfo));
}
linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
} }
linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
nameTextView.setText(currentChat.title); nameTextView.setText(currentChat.title);
nameTextView.setSelection(nameTextView.length()); nameTextView.setSelection(nameTextView.length());
@ -655,11 +695,20 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
for (int a = 0; a < name.length(); a++) { for (int a = 0; a < name.length(); a++) {
char ch = name.charAt(a); char ch = name.charAt(a);
if (a == 0 && ch >= '0' && ch <= '9') { if (a == 0 && ch >= '0' && ch <= '9') {
if (alert) { if (currentChat.megagroup) {
showErrorAlert(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber)); if (alert) {
//showErrorAlert(LocaleController.getString("LinkInvalidStartNumberMega", R.string.LinkInvalidStartNumberMega));
} else {
//checkTextView.setText(LocaleController.getString("LinkInvalidStartNumberMega", R.string.LinkInvalidStartNumberMega));
checkTextView.setTextColor(0xffcf3030);
}
} else { } else {
checkTextView.setText(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber)); if (alert) {
checkTextView.setTextColor(0xffcf3030); showErrorAlert(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber));
} else {
checkTextView.setText(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber));
checkTextView.setTextColor(0xffcf3030);
}
} }
return false; return false;
} }
@ -675,11 +724,20 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
} }
} }
if (name == null || name.length() < 5) { if (name == null || name.length() < 5) {
if (alert) { if (currentChat.megagroup) {
showErrorAlert(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort)); if (alert) {
//showErrorAlert(LocaleController.getString("LinkInvalidShortMega", R.string.LinkInvalidShortMega));
} else {
//checkTextView.setText(LocaleController.getString("LinkInvalidShortMega", R.string.LinkInvalidShortMega));
checkTextView.setTextColor(0xffcf3030);
}
} else { } else {
checkTextView.setText(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort)); if (alert) {
checkTextView.setTextColor(0xffcf3030); showErrorAlert(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort));
} else {
checkTextView.setText(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort));
checkTextView.setTextColor(0xffcf3030);
}
} }
return false; return false;
} }

View File

@ -36,7 +36,10 @@ import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu; import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Cells.HeaderCell;
import org.telegram.ui.Cells.RadioCell;
import org.telegram.ui.Cells.ShadowSectionCell; import org.telegram.ui.Cells.ShadowSectionCell;
import org.telegram.ui.Cells.TextCell;
import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Cells.TextInfoPrivacyCell;
import org.telegram.ui.Cells.TextSettingsCell; import org.telegram.ui.Cells.TextSettingsCell;
import org.telegram.ui.Cells.UserCell; import org.telegram.ui.Cells.UserCell;
@ -78,7 +81,7 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
if (type == 0) { if (type == 0) {
participantsStartRow = 0; participantsStartRow = 0;
} else if (type == 1) { } else if (type == 1) {
participantsStartRow = isAdmin ? 2 : 0; participantsStartRow = isAdmin && isMegagroup ? 4 : 0;
} else if (type == 2) { } else if (type == 2) {
participantsStartRow = isAdmin ? (isPublic ? 2 : 3) : 0; participantsStartRow = isAdmin ? (isPublic ? 2 : 3) : 0;
} }
@ -134,7 +137,7 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
} }
frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
ListView listView = new ListView(context); final ListView listView = new ListView(context);
listView.setEmptyView(emptyView); listView.setEmptyView(emptyView);
listView.setDivider(null); listView.setDivider(null);
listView.setDividerHeight(0); listView.setDividerHeight(0);
@ -173,7 +176,33 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
} else if (type == 1) { } else if (type == 1) {
if (isAdmin) { if (isAdmin) {
if (i == 0) { if (isMegagroup && (i == 1 || i == 2)) {
TLRPC.Chat chat = MessagesController.getInstance().getChat(chatId);
if (chat == null) {
return;
}
boolean changed = false;
if (i == 1 && !chat.democracy) {
chat.democracy = true;
changed = true;
} else if (i == 2 && chat.democracy) {
chat.democracy = false;
changed = true;
}
if (changed) {
MessagesController.getInstance().toogleChannelInvites(chatId, chat.democracy);
int count = listView.getChildCount();
for (int a = 0; a < count; a++) {
View child = listView.getChildAt(a);
if (child instanceof RadioCell) {
int num = (Integer) child.getTag();
((RadioCell) child).setChecked(num == 0 && chat.democracy || num == 1 && !chat.democracy, true);
}
}
}
return;
}
if (i == participantsStartRow + participants.size()) {
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putBoolean("onlyUsers", true); args.putBoolean("onlyUsers", true);
args.putBoolean("destroyAfterSelect", true); args.putBoolean("destroyAfterSelect", true);
@ -192,6 +221,7 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
} }
}); });
presentFragment(fragment); presentFragment(fragment);
return;
} }
} }
} }
@ -243,16 +273,18 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
final TLRPC.Updates updates = (TLRPC.Updates) response; if (response != null) {
MessagesController.getInstance().processUpdates(updates, false); final TLRPC.Updates updates = (TLRPC.Updates) response;
if (!updates.chats.isEmpty()) { MessagesController.getInstance().processUpdates(updates, false);
AndroidUtilities.runOnUIThread(new Runnable() { if (!updates.chats.isEmpty()) {
@Override AndroidUtilities.runOnUIThread(new Runnable() {
public void run() { @Override
TLRPC.Chat chat = updates.chats.get(0); public void run() {
MessagesController.getInstance().loadFullChat(chat.id, 0, true); TLRPC.Chat chat = updates.chats.get(0);
} MessagesController.getInstance().loadFullChat(chat.id, 0, true);
}, 1000); }
}, 1000);
}
} }
} }
}); });
@ -487,12 +519,12 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
} }
} }
} else if (type == 1) { } else if (type == 1) {
if (isAdmin) { if (i == participantsStartRow + participants.size()) {
if (i == 0) { return isAdmin;
return true; } else if (i == participantsStartRow + participants.size() + 1) {
} else if (i == 1) { return false;
return false; } else if (isMegagroup && isAdmin && i < 4) {
} return i == 1 || i == 2;
} }
} }
return i != participants.size() + participantsStartRow && participants.get(i - participantsStartRow).user_id != UserConfig.getClientUserId(); return i != participants.size() + participantsStartRow && participants.get(i - participantsStartRow).user_id != UserConfig.getClientUserId();
@ -502,6 +534,8 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
public int getCount() { public int getCount() {
if (participants.isEmpty() && type == 0 || loadingUsers && !firstLoaded) { if (participants.isEmpty() && type == 0 || loadingUsers && !firstLoaded) {
return 0; return 0;
} else if (type == 1) {
return participants.size() + (isAdmin ? 2 : 1) + (isAdmin && isMegagroup ? 4 : 0);
} }
return participants.size() + participantsStartRow + 1; return participants.size() + participantsStartRow + 1;
} }
@ -557,13 +591,14 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
((TextInfoPrivacyCell) view).setText(String.format("%1$s\n\n%2$s", LocaleController.getString("NoBlockedGroup", R.string.NoBlockedGroup), LocaleController.getString("UnblockText", R.string.UnblockText))); ((TextInfoPrivacyCell) view).setText(String.format("%1$s\n\n%2$s", LocaleController.getString("NoBlockedGroup", R.string.NoBlockedGroup), LocaleController.getString("UnblockText", R.string.UnblockText)));
view.setBackgroundResource(R.drawable.greydivider_bottom); view.setBackgroundResource(R.drawable.greydivider_bottom);
} else if (type == 1) { } else if (type == 1) {
if (i == 1 && isAdmin) { if (isAdmin) {
if (isMegagroup) { if (isMegagroup) {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("MegaAdminsInfo", R.string.MegaAdminsInfo)); ((TextInfoPrivacyCell) view).setText(LocaleController.getString("MegaAdminsInfo", R.string.MegaAdminsInfo));
view.setBackgroundResource(R.drawable.greydivider_bottom);
} else { } else {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("ChannelAdminsInfo", R.string.ChannelAdminsInfo)); ((TextInfoPrivacyCell) view).setText(LocaleController.getString("ChannelAdminsInfo", R.string.ChannelAdminsInfo));
view.setBackgroundResource(R.drawable.greydivider_bottom);
} }
view.setBackgroundResource(R.drawable.greydivider);
} else { } else {
((TextInfoPrivacyCell) view).setText(""); ((TextInfoPrivacyCell) view).setText("");
view.setBackgroundResource(R.drawable.greydivider_bottom); view.setBackgroundResource(R.drawable.greydivider_bottom);
@ -594,12 +629,38 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
actionCell.setText(LocaleController.getString("ChannelInviteViaLink", R.string.ChannelInviteViaLink), false); actionCell.setText(LocaleController.getString("ChannelInviteViaLink", R.string.ChannelInviteViaLink), false);
} }
} else if (type == 1) { } else if (type == 1) {
actionCell.setText(LocaleController.getString("ChannelAddAdmin", R.string.ChannelAddAdmin), true); actionCell.setTextAndIcon(LocaleController.getString("ChannelAddAdmin", R.string.ChannelAddAdmin), R.drawable.managers, false);
} }
} else if (viewType == 3) { } else if (viewType == 3) {
if (view == null) { if (view == null) {
view = new ShadowSectionCell(mContext); view = new ShadowSectionCell(mContext);
} }
} else if (viewType == 4) {
if (view == null) {
view = new TextCell(mContext);
view.setBackgroundColor(0xffffffff);
}
((TextCell) view).setTextAndIcon(LocaleController.getString("ChannelAddAdmin", R.string.ChannelAddAdmin), R.drawable.managers);
} else if (viewType == 5) {
if (view == null) {
view = new HeaderCell(mContext);
view.setBackgroundColor(0xffffffff);
}
((HeaderCell) view).setText(LocaleController.getString("WhoCanAddMembers", R.string.WhoCanAddMembers));
} else if (viewType == 6) {
if (view == null) {
view = new RadioCell(mContext);
view.setBackgroundColor(0xffffffff);
}
RadioCell radioCell = (RadioCell) view;
TLRPC.Chat chat = MessagesController.getInstance().getChat(chatId);
if (i == 1) {
radioCell.setTag(0);
radioCell.setText(LocaleController.getString("WhoCanAddMembersAllMembers", R.string.WhoCanAddMembersAllMembers), chat != null && chat.democracy, true);
} else if (i == 2) {
radioCell.setTag(1);
radioCell.setText(LocaleController.getString("WhoCanAddMembersAdmins", R.string.WhoCanAddMembersAdmins), chat != null && !chat.democracy, false);
}
} }
return view; return view;
} }
@ -608,9 +669,18 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
public int getItemViewType(int i) { public int getItemViewType(int i) {
if (type == 1) { if (type == 1) {
if (isAdmin) { if (isAdmin) {
if (i == 0) { if (isMegagroup) {
return 2; if (i == 0) {
} else if (i == 1) { return 5;
} else if (i == 1 || i == 2) {
return 6;
} else if (i == 3) {
return 3;
}
}
if (i == participantsStartRow + participants.size()) {
return 4;
} else if (i == participantsStartRow + participants.size() + 1) {
return 1; return 1;
} }
} }
@ -639,12 +709,12 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
@Override @Override
public int getViewTypeCount() { public int getViewTypeCount() {
return 4; return 7;
} }
@Override @Override
public boolean isEmpty() { public boolean isEmpty() {
return participants.isEmpty(); return getCount() == 0 || participants.isEmpty() && loadingUsers;
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -13,12 +13,9 @@ import android.app.AlertDialog;
import android.app.Dialog; import android.app.Dialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.net.Uri;
import android.provider.Browser;
import org.telegram.messenger.FileLog; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
@ -97,13 +94,7 @@ public class AlertsCreator {
builder.setNegativeButton(LocaleController.getString("MoreInfo", R.string.MoreInfo), new DialogInterface.OnClickListener() { builder.setNegativeButton(LocaleController.getString("MoreInfo", R.string.MoreInfo), new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialogInterface, int i) { public void onClick(DialogInterface dialogInterface, int i) {
try { AndroidUtilities.openUrl(fragment.getParentActivity(), LocaleController.getString("NobodyLikesSpamUrl", R.string.NobodyLikesSpamUrl));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(LocaleController.getString("NobodyLikesSpamUrl", R.string.NobodyLikesSpamUrl)));
intent.putExtra(Browser.EXTRA_APPLICATION_ID, fragment.getParentActivity().getPackageName());
fragment.getParentActivity().startActivity(intent);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
}); });
break; break;
@ -144,6 +135,16 @@ public class AlertsCreator {
builder.setMessage(LocaleController.getString("GroupUserCantBot", R.string.GroupUserCantBot)); builder.setMessage(LocaleController.getString("GroupUserCantBot", R.string.GroupUserCantBot));
} }
break; break;
case "USER_PRIVACY_RESTRICTED":
if (isChannel) {
builder.setMessage(LocaleController.getString("InviteToChannelError", R.string.InviteToChannelError));
} else {
builder.setMessage(LocaleController.getString("InviteToGroupError", R.string.InviteToGroupError));
}
break;
case "USERS_TOO_FEW":
builder.setMessage(LocaleController.getString("CreateGroupError", R.string.CreateGroupError));
break;
} }
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null); builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
fragment.showDialog(builder.create(), true); fragment.showDialog(builder.create(), true);

View File

@ -21,7 +21,9 @@ import android.media.AudioManager;
import android.os.Build; import android.os.Build;
import android.os.PowerManager; import android.os.PowerManager;
import android.text.Editable; import android.text.Editable;
import android.text.InputFilter;
import android.text.Layout; import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout; import android.text.StaticLayout;
import android.text.TextPaint; import android.text.TextPaint;
import android.text.TextUtils; import android.text.TextUtils;
@ -42,6 +44,7 @@ import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.PopupWindow; import android.widget.PopupWindow;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatObject;
@ -50,6 +53,7 @@ import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController; import org.telegram.messenger.MediaController;
import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationsController;
import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
@ -66,6 +70,7 @@ import org.telegram.messenger.AnimationCompat.ViewProxy;
import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ApplicationLoader;
import org.telegram.ui.StickersActivity; import org.telegram.ui.StickersActivity;
import java.io.File;
import java.util.Locale; import java.util.Locale;
public class ChatActivityEnterView extends FrameLayoutFixed implements NotificationCenter.NotificationCenterDelegate, SizeNotifierFrameLayout.SizeNotifierFrameLayoutDelegate { public class ChatActivityEnterView extends FrameLayoutFixed implements NotificationCenter.NotificationCenterDelegate, SizeNotifierFrameLayout.SizeNotifierFrameLayoutDelegate {
@ -78,6 +83,64 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
void onAttachButtonShow(); void onAttachButtonShow();
void onWindowSizeChanged(int size); void onWindowSizeChanged(int size);
void onStickersTab(boolean opened); void onStickersTab(boolean opened);
void onMessageEditEnd();
}
private class SeekBarWaveformView extends View {
private SeekBarWaveform seekBarWaveform;
public SeekBarWaveformView(Context context) {
super(context);
seekBarWaveform = new SeekBarWaveform(context);
seekBarWaveform.setColors(0xffa2cef8, 0xffffffff, 0xffa2cef8);
seekBarWaveform.setDelegate(new SeekBar.SeekBarDelegate() {
@Override
public void onSeekBarDrag(float progress) {
audioToSendMessageObject.audioProgress = progress;
MediaController.getInstance().seekToProgress(audioToSendMessageObject, progress);
}
});
}
public void setWaveform(byte[] waveform) {
seekBarWaveform.setWaveform(waveform);
invalidate();
}
public void setProgress(float progress) {
seekBarWaveform.setProgress(progress);
invalidate();
}
public boolean isDragging() {
return seekBarWaveform.isDragging();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean result = seekBarWaveform.onTouch(event.getAction(), event.getX(), event.getY());
if (result) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
requestDisallowInterceptTouchEvent(true);
}
invalidate();
}
return result || super.onTouchEvent(event);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
seekBarWaveform.width = right - left;
seekBarWaveform.height = bottom - top;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
seekBarWaveform.draw(canvas);
}
} }
private class EditTextCaption extends EditText { private class EditTextCaption extends EditText {
@ -137,16 +200,20 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
@Override @Override
protected void onDraw(Canvas canvas) { protected void onDraw(Canvas canvas) {
super.onDraw(canvas); try {
if (captionLayout != null && userNameLength == length()) { super.onDraw(canvas);
Paint paint = getPaint(); if (captionLayout != null && userNameLength == length()) {
int oldColor = getPaint().getColor(); Paint paint = getPaint();
paint.setColor(0xffb2b2b2); int oldColor = getPaint().getColor();
canvas.save(); paint.setColor(0xffb2b2b2);
canvas.translate(xOffset, yOffset); canvas.save();
captionLayout.draw(canvas); canvas.translate(xOffset, yOffset);
canvas.restore(); captionLayout.draw(canvas);
paint.setColor(oldColor); canvas.restore();
paint.setColor(oldColor);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
} }
@ -167,21 +234,33 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
private TextView recordTimeText; private TextView recordTimeText;
private ImageView audioSendButton; private ImageView audioSendButton;
private FrameLayout recordPanel; private FrameLayout recordPanel;
private FrameLayout recordedAudioPanel;
private SeekBarWaveformView recordedAudioSeekBar;
private ImageView recordedAudioPlayButton;
private TextView recordedAudioTimeTextView;
private LinearLayout slideText; private LinearLayout slideText;
private RecordDot recordDot; private RecordDot recordDot;
private SizeNotifierFrameLayout sizeNotifierLayout; private SizeNotifierFrameLayout sizeNotifierLayout;
private LinearLayout attachButton; private LinearLayout attachButton;
private ImageView botButton; private ImageView botButton;
private LinearLayout textFieldContainer; private LinearLayout textFieldContainer;
private FrameLayout sendButtonContainer;
private View topView; private View topView;
private PopupWindow botKeyboardPopup; private PopupWindow botKeyboardPopup;
private BotKeyboardView botKeyboardView; private BotKeyboardView botKeyboardView;
private ImageView asAdminButton; private ImageView asAdminButton;
private ImageView notifyButton;
private RecordCircle recordCircle; private RecordCircle recordCircle;
private ContextProgressView contextProgressView; private ContextProgressView contextProgressView;
private MessageObject editingMessageObject;
private boolean editingCaption;
private int currentPopupContentType = -1; private int currentPopupContentType = -1;
private boolean silent;
private boolean canWriteToChannel;
private boolean isAsAdmin; private boolean isAsAdmin;
private boolean adminModeAvailable; private boolean adminModeAvailable;
@ -228,6 +307,10 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
private boolean messageWebPageSearch = true; private boolean messageWebPageSearch = true;
private ChatActivityEnterViewDelegate delegate; private ChatActivityEnterViewDelegate delegate;
private TLRPC.TL_document audioToSend;
private String audioToSendPath;
private MessageObject audioToSendMessageObject;
private float topViewAnimation; private float topViewAnimation;
private boolean topViewShowed; private boolean topViewShowed;
private boolean needShowTopView; private boolean needShowTopView;
@ -270,16 +353,16 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
@Override @Override
protected void onDraw(Canvas canvas) { protected void onDraw(Canvas canvas) {
dotDrawable.setBounds(0, 0, AndroidUtilities.dp(11), AndroidUtilities.dp(11)); dotDrawable.setBounds(0, 0, AndroidUtilities.dp(11), AndroidUtilities.dp(11));
dotDrawable.setAlpha(185 + (int) (70 * alpha)); dotDrawable.setAlpha((int) (255 * alpha));
long dt = (System.currentTimeMillis() - lastUpdateTime); long dt = (System.currentTimeMillis() - lastUpdateTime);
if (!isIncr) { if (!isIncr) {
alpha -= dt / 200.0f; alpha -= dt / 400.0f;
if (alpha <= 0) { if (alpha <= 0) {
alpha = 0; alpha = 0;
isIncr = true; isIncr = true;
} }
} else { } else {
alpha += dt / 200.0f; alpha += dt / 400.0f;
if (alpha >= 1) { if (alpha >= 1) {
alpha = 1; alpha = 1;
isIncr = false; isIncr = false;
@ -379,6 +462,8 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidSent); NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidSent);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded); NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioRouteChanged); NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioRouteChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidReset);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged);
parentActivity = context; parentActivity = context;
parentFragment = fragment; parentFragment = fragment;
sizeNotifierLayout = parent; sizeNotifierLayout = parent;
@ -491,7 +576,9 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
if (count > 2 || charSequence == null || charSequence.length() == 0) { if (count > 2 || charSequence == null || charSequence.length() == 0) {
messageWebPageSearch = true; messageWebPageSearch = true;
} }
delegate.onTextChanged(charSequence, before > count + 1 || (count - before) > 2); if (!ignoreTextChange) {
delegate.onTextChanged(charSequence, before > count + 1 || (count - before) > 2);
}
} }
if (innerTextChange != 2 && before != count && (count - before) > 1) { if (innerTextChange != 2 && before != count && (count - before) > 1) {
processChange = true; processChange = true;
@ -584,8 +671,88 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
preferences.edit().putBoolean("asadmin_" + dialog_id, isAsAdmin).commit(); preferences.edit().putBoolean("asadmin_" + dialog_id, isAsAdmin).commit();
} }
}); });
notifyButton = new ImageView(context);
notifyButton.setImageResource(silent ? R.drawable.notify_members_off : R.drawable.notify_members_on);
notifyButton.setScaleType(ImageView.ScaleType.CENTER);
notifyButton.setVisibility(canWriteToChannel ? VISIBLE : GONE);
attachButton.addView(notifyButton, LayoutHelper.createLinear(48, 48));
notifyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
silent = !silent;
notifyButton.setImageResource(silent ? R.drawable.notify_members_off : R.drawable.notify_members_on);
ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE).edit().putBoolean("silent_" + dialog_id, silent).commit();
NotificationsController.updateServerNotificationsSettings(dialog_id);
if (silent) {
Toast.makeText(parentActivity, LocaleController.getString("ChannelNotifyMembersInfoOff", R.string.ChannelNotifyMembersInfoOff), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(parentActivity, LocaleController.getString("ChannelNotifyMembersInfoOn", R.string.ChannelNotifyMembersInfoOn), Toast.LENGTH_SHORT).show();
}
}
});
} }
recordedAudioPanel = new FrameLayoutFixed(context);
recordedAudioPanel.setVisibility(audioToSend == null ? GONE : VISIBLE);
recordedAudioPanel.setBackgroundColor(0xffffffff);
recordedAudioPanel.setFocusable(true);
recordedAudioPanel.setFocusableInTouchMode(true);
recordedAudioPanel.setClickable(true);
frameLayout.addView(recordedAudioPanel, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM));
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.drawable.ic_ab_fwd_delete);
recordedAudioPanel.addView(imageView, LayoutHelper.createFrame(48, 48));
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
MessageObject playing = MediaController.getInstance().getPlayingMessageObject();
if (playing != null && playing == audioToSendMessageObject) {
MediaController.getInstance().cleanupPlayer(true, true);
}
if (audioToSendPath != null) {
new File(audioToSendPath).delete();
}
hideRecordedAudioPanel();
checkSendButton(true);
}
});
View view = new View(context);
view.setBackgroundResource(R.drawable.recorded);
recordedAudioPanel.addView(view, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32, Gravity.CENTER_VERTICAL | Gravity.LEFT, 48, 0, 0, 0));
recordedAudioSeekBar = new SeekBarWaveformView(context);
recordedAudioPanel.addView(recordedAudioSeekBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 32, Gravity.CENTER_VERTICAL | Gravity.LEFT, 48 + 44, 0, 52, 0));
recordedAudioPlayButton = new ImageView(context);
recordedAudioPlayButton.setImageResource(R.drawable.s_player_play_states);
recordedAudioPlayButton.setScaleType(ImageView.ScaleType.CENTER);
recordedAudioPanel.addView(recordedAudioPlayButton, LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.BOTTOM, 48, 0, 0, 0));
recordedAudioPlayButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (audioToSend == null) {
return;
}
if (MediaController.getInstance().isPlayingAudio(audioToSendMessageObject) && !MediaController.getInstance().isAudioPaused()) {
MediaController.getInstance().pauseAudio(audioToSendMessageObject);
recordedAudioPlayButton.setImageResource(R.drawable.s_player_play_states);
} else {
recordedAudioPlayButton.setImageResource(R.drawable.s_player_pause_states);
MediaController.getInstance().playAudio(audioToSendMessageObject);
}
}
});
recordedAudioTimeTextView = new TextView(context);
recordedAudioTimeTextView.setTextColor(0xffffffff);
recordedAudioTimeTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
recordedAudioTimeTextView.setText("0:13");
recordedAudioPanel.addView(recordedAudioTimeTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL, 0, 0, 13, 0));
recordPanel = new FrameLayoutFixed(context); recordPanel = new FrameLayoutFixed(context);
recordPanel.setVisibility(GONE); recordPanel.setVisibility(GONE);
recordPanel.setBackgroundColor(0xffffffff); recordPanel.setBackgroundColor(0xffffffff);
@ -595,7 +762,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
slideText.setOrientation(LinearLayout.HORIZONTAL); slideText.setOrientation(LinearLayout.HORIZONTAL);
recordPanel.addView(slideText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 30, 0, 0, 0)); recordPanel.addView(slideText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 30, 0, 0, 0));
ImageView imageView = new ImageView(context); imageView = new ImageView(context);
imageView.setImageResource(R.drawable.slidearrow); imageView.setImageResource(R.drawable.slidearrow);
slideText.addView(imageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 1, 0, 0)); slideText.addView(imageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 0, 1, 0, 0));
@ -620,8 +787,8 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
recordTimeText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); recordTimeText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
linearLayout.addView(recordTimeText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 6, 0, 0, 0)); linearLayout.addView(recordTimeText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 6, 0, 0, 0));
FrameLayout frameLayout1 = new FrameLayout(context); sendButtonContainer = new FrameLayout(context);
textFieldContainer.addView(frameLayout1, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM)); textFieldContainer.addView(sendButtonContainer, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM));
audioSendButton = new ImageView(context); audioSendButton = new ImageView(context);
audioSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE); audioSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
@ -629,7 +796,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
audioSendButton.setBackgroundColor(0xffffffff); audioSendButton.setBackgroundColor(0xffffffff);
audioSendButton.setSoundEffectsEnabled(false); audioSendButton.setSoundEffectsEnabled(false);
audioSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0); audioSendButton.setPadding(0, 0, AndroidUtilities.dp(4), 0);
frameLayout1.addView(audioSendButton, LayoutHelper.createFrame(48, 48)); sendButtonContainer.addView(audioSendButton, LayoutHelper.createFrame(48, 48));
audioSendButton.setOnTouchListener(new View.OnTouchListener() { audioSendButton.setOnTouchListener(new View.OnTouchListener() {
@Override @Override
public boolean onTouch(View view, MotionEvent motionEvent) { public boolean onTouch(View view, MotionEvent motionEvent) {
@ -664,13 +831,13 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
audioSendButton.getParent().requestDisallowInterceptTouchEvent(true); audioSendButton.getParent().requestDisallowInterceptTouchEvent(true);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) { } else if (motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
startedDraggingX = -1; startedDraggingX = -1;
MediaController.getInstance().stopRecording(true); MediaController.getInstance().stopRecording(1);
recordingAudio = false; recordingAudio = false;
updateAudioRecordIntefrace(); updateAudioRecordIntefrace();
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && recordingAudio) { } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && recordingAudio) {
float x = motionEvent.getX(); float x = motionEvent.getX();
if (x < -distCanMove) { if (x < -distCanMove) {
MediaController.getInstance().stopRecording(false); MediaController.getInstance().stopRecording(0);
recordingAudio = false; recordingAudio = false;
updateAudioRecordIntefrace(); updateAudioRecordIntefrace();
} }
@ -727,7 +894,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
ViewProxy.setScaleY(sendButton, 0.1f); ViewProxy.setScaleY(sendButton, 0.1f);
ViewProxy.setAlpha(sendButton, 0.0f); ViewProxy.setAlpha(sendButton, 0.0f);
sendButton.clearAnimation(); sendButton.clearAnimation();
frameLayout1.addView(sendButton, LayoutHelper.createFrame(48, 48)); sendButtonContainer.addView(sendButton, LayoutHelper.createFrame(48, 48));
sendButton.setOnClickListener(new View.OnClickListener() { sendButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
@ -787,6 +954,13 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
} }
public void setAllowStickersAndGifs(boolean value, boolean value2) { public void setAllowStickersAndGifs(boolean value, boolean value2) {
if ((allowStickers != value || allowGifs != value2) && emojiView != null) {
if (emojiView.getVisibility() == VISIBLE) {
hidePopup(false);
}
sizeNotifierLayout.removeView(emojiView);
emojiView = null;
}
allowStickers = value; allowStickers = value;
allowGifs = value2; allowGifs = value2;
} }
@ -824,7 +998,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
public void onAnimationEnd(Object animation) { public void onAnimationEnd(Object animation) {
if (currentTopViewAnimation != null && currentTopViewAnimation.equals(animation)) { if (currentTopViewAnimation != null && currentTopViewAnimation.equals(animation)) {
setTopViewAnimation(1.0f); setTopViewAnimation(1.0f);
if (!forceShowSendButton || openKeyboard) { if (recordedAudioPanel.getVisibility() != VISIBLE && (!forceShowSendButton || openKeyboard)) {
openKeyboard(); openKeyboard();
} }
currentTopViewAnimation = null; currentTopViewAnimation = null;
@ -835,7 +1009,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
currentTopViewAnimation.start(); currentTopViewAnimation.start();
} else { } else {
setTopViewAnimation(1.0f); setTopViewAnimation(1.0f);
if (!forceShowSendButton || openKeyboard) { if (recordedAudioPanel.getVisibility() != VISIBLE && (!forceShowSendButton || openKeyboard)) {
openKeyboard(); openKeyboard();
} }
} }
@ -925,6 +1099,11 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidSent); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidSent);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioRouteChanged); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioRouteChanged);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidReset);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioProgressDidChanged);
if (emojiView != null) {
emojiView.onDestroy();
}
if (mWakeLock != null) { if (mWakeLock != null) {
try { try {
mWakeLock.release(); mWakeLock.release();
@ -961,8 +1140,10 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
dialog_id = id; dialog_id = id;
if ((int) dialog_id < 0) { if ((int) dialog_id < 0) {
TLRPC.Chat currentChat = MessagesController.getInstance().getChat(-(int) dialog_id); TLRPC.Chat currentChat = MessagesController.getInstance().getChat(-(int) dialog_id);
silent = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE).getBoolean("silent_" + dialog_id, false);
isAsAdmin = ChatObject.isChannel(currentChat) && (currentChat.creator || currentChat.editor) && !currentChat.megagroup; isAsAdmin = ChatObject.isChannel(currentChat) && (currentChat.creator || currentChat.editor) && !currentChat.megagroup;
adminModeAvailable = isAsAdmin && !currentChat.broadcast; adminModeAvailable = isAsAdmin && !currentChat.broadcast;
canWriteToChannel = isAsAdmin;
if (adminModeAvailable) { if (adminModeAvailable) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
isAsAdmin = preferences.getBoolean("asadmin_" + dialog_id, true); isAsAdmin = preferences.getBoolean("asadmin_" + dialog_id, true);
@ -972,6 +1153,11 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
asAdminButton.setImageResource(isAsAdmin ? R.drawable.publish_active : R.drawable.publish); asAdminButton.setImageResource(isAsAdmin ? R.drawable.publish_active : R.drawable.publish);
updateFieldHint(); updateFieldHint();
} }
if (notifyButton != null) {
notifyButton.setVisibility(canWriteToChannel ? VISIBLE : GONE);
notifyButton.setImageResource(silent ? R.drawable.notify_members_off : R.drawable.notify_members_on);
ViewProxy.setPivotX(attachButton, AndroidUtilities.dp((botButton == null || botButton.getVisibility() == GONE) && (notifyButton == null || notifyButton.getVisibility() == GONE) ? 48 : 96));
}
} }
} }
@ -982,7 +1168,11 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
isChannel = ChatObject.isChannel(chat) && !chat.megagroup; isChannel = ChatObject.isChannel(chat) && !chat.megagroup;
} }
if (isChannel) { if (isChannel) {
messageEditText.setHint(isAsAdmin ? LocaleController.getString("ChannelBroadcast", R.string.ChannelBroadcast) : LocaleController.getString("ChannelComment", R.string.ChannelComment)); if (editingMessageObject != null) {
messageEditText.setHint(editingCaption ? LocaleController.getString("Caption", R.string.Caption) : LocaleController.getString("TypeMessage", R.string.TypeMessage));
} else {
messageEditText.setHint(isAsAdmin ? LocaleController.getString("ChannelBroadcast", R.string.ChannelBroadcast) : LocaleController.getString("ChannelComment", R.string.ChannelComment));
}
} else { } else {
messageEditText.setHint(LocaleController.getString("TypeMessage", R.string.TypeMessage)); messageEditText.setHint(LocaleController.getString("TypeMessage", R.string.TypeMessage));
} }
@ -1013,6 +1203,26 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
return messageWebPageSearch; return messageWebPageSearch;
} }
private void hideRecordedAudioPanel() {
audioToSendPath = null;
audioToSend = null;
audioToSendMessageObject = null;
AnimatorSetProxy animatorSetProxy = new AnimatorSetProxy();
animatorSetProxy.playTogether(
ObjectAnimatorProxy.ofFloat(recordedAudioPanel, "alpha", 0.0f)
);
animatorSetProxy.setDuration(200);
animatorSetProxy.addListener(new AnimatorListenerAdapterProxy() {
@Override
public void onAnimationEnd(Object animation) {
recordedAudioPanel.clearAnimation();
recordedAudioPanel.setVisibility(View.GONE);
}
});
animatorSetProxy.start();
}
private void sendMessage() { private void sendMessage() {
if (parentFragment != null) { if (parentFragment != null) {
String action; String action;
@ -1031,6 +1241,19 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
return; return;
} }
} }
if (audioToSend != null) {
MessageObject playing = MediaController.getInstance().getPlayingMessageObject();
if (playing != null && playing == audioToSendMessageObject) {
MediaController.getInstance().cleanupPlayer(true, true);
}
SendMessagesHelper.getInstance().sendMessage(audioToSend, null, audioToSendPath, dialog_id, replyingMessageObject, isAsAdmin, null);
if (delegate != null) {
delegate.onMessageSend(null);
}
hideRecordedAudioPanel();
checkSendButton(true);
return;
}
String message = messageEditText.getText().toString(); String message = messageEditText.getText().toString();
if (processSendingText(message)) { if (processSendingText(message)) {
messageEditText.setText(""); messageEditText.setText("");
@ -1045,6 +1268,13 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
} }
} }
public void doneEditingMessage() {
if (editingMessageObject != null) {
SendMessagesHelper.getInstance().editMessage(editingMessageObject, messageEditText.getText().toString(), messageWebPageSearch, parentFragment);
setEditinigMessageObject(null, false);
}
}
public boolean processSendingText(String text) { public boolean processSendingText(String text) {
text = getTrimmedString(text); text = getTrimmedString(text);
if (text.length() != 0) { if (text.length() != 0) {
@ -1073,8 +1303,11 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
} }
private void checkSendButton(final boolean animated) { private void checkSendButton(final boolean animated) {
if (editingMessageObject != null) {
return;
}
String message = getTrimmedString(messageEditText.getText().toString()); String message = getTrimmedString(messageEditText.getText().toString());
if (message.length() > 0 || forceShowSendButton) { if (message.length() > 0 || forceShowSendButton || audioToSend != null) {
if (audioSendButton.getVisibility() == View.VISIBLE) { if (audioSendButton.getVisibility() == View.VISIBLE) {
if (animated) { if (animated) {
if (runningAnimationType == 1) { if (runningAnimationType == 1) {
@ -1109,7 +1342,9 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
updateFieldRight(0); updateFieldRight(0);
delegate.onAttachButtonHidden(); if (delegate != null) {
delegate.onAttachButtonHidden();
}
} }
sendButton.setVisibility(View.VISIBLE); sendButton.setVisibility(View.VISIBLE);
@ -1152,7 +1387,9 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
if (attachButton != null) { if (attachButton != null) {
attachButton.setVisibility(View.GONE); attachButton.setVisibility(View.GONE);
attachButton.clearAnimation(); attachButton.clearAnimation();
delegate.onAttachButtonHidden(); if (delegate != null) {
delegate.onAttachButtonHidden();
}
updateFieldRight(0); updateFieldRight(0);
} }
} }
@ -1234,19 +1471,19 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
} }
private void updateFieldRight(int attachVisible) { private void updateFieldRight(int attachVisible) {
if (messageEditText == null) { if (messageEditText == null || editingMessageObject != null) {
return; return;
} }
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) messageEditText.getLayoutParams(); FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) messageEditText.getLayoutParams();
if (attachVisible == 1) { if (attachVisible == 1) {
if (botButton != null && botButton.getVisibility() == VISIBLE) { if (botButton != null && botButton.getVisibility() == VISIBLE || notifyButton != null && notifyButton.getVisibility() == VISIBLE) {
layoutParams.rightMargin = AndroidUtilities.dp(98); layoutParams.rightMargin = AndroidUtilities.dp(98);
} else { } else {
layoutParams.rightMargin = AndroidUtilities.dp(50); layoutParams.rightMargin = AndroidUtilities.dp(50);
} }
} else if (attachVisible == 2) { } else if (attachVisible == 2) {
if (layoutParams.rightMargin != AndroidUtilities.dp(2)) { if (layoutParams.rightMargin != AndroidUtilities.dp(2)) {
if (botButton != null && botButton.getVisibility() == VISIBLE) { if (botButton != null && botButton.getVisibility() == VISIBLE || notifyButton != null && notifyButton.getVisibility() == VISIBLE) {
layoutParams.rightMargin = AndroidUtilities.dp(98); layoutParams.rightMargin = AndroidUtilities.dp(98);
} else { } else {
layoutParams.rightMargin = AndroidUtilities.dp(50); layoutParams.rightMargin = AndroidUtilities.dp(50);
@ -1369,6 +1606,9 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
messageEditText.setText(text); messageEditText.setText(text);
messageEditText.setSelection(messageEditText.getText().length()); messageEditText.setSelection(messageEditText.getText().length());
ignoreTextChange = false; ignoreTextChange = false;
if (delegate != null) {
delegate.onTextChanged(messageEditText.getText(), true);
}
if (!keyboardVisible && currentPopupContentType == -1) { if (!keyboardVisible && currentPopupContentType == -1) {
openKeyboard(); openKeyboard();
} }
@ -1382,7 +1622,66 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
} }
} }
public void setFieldText(String text) { public void setEditinigMessageObject(MessageObject messageObject, boolean caption) {
if (audioToSend != null || editingMessageObject == messageObject) {
return;
}
editingMessageObject = messageObject;
editingCaption = caption;
if (editingMessageObject != null) {
InputFilter[] inputFilters = new InputFilter[1];
if (caption) {
inputFilters[0] = new InputFilter.LengthFilter(200);
if (editingMessageObject.caption != null) {
setFieldText(Emoji.replaceEmoji(new SpannableStringBuilder(editingMessageObject.caption.toString()), messageEditText.getPaint().getFontMetricsInt(), AndroidUtilities.dp(20), false));
} else {
setFieldText("");
}
} else {
inputFilters[0] = new InputFilter.LengthFilter(4096);
if (editingMessageObject.messageText != null) {
setFieldText(Emoji.replaceEmoji(new SpannableStringBuilder(editingMessageObject.messageText.toString()), messageEditText.getPaint().getFontMetricsInt(), AndroidUtilities.dp(20), false));
} else {
setFieldText("");
}
}
messageEditText.setFilters(inputFilters);
openKeyboard();
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) messageEditText.getLayoutParams();
layoutParams.rightMargin = AndroidUtilities.dp(4);
messageEditText.setLayoutParams(layoutParams);
sendButton.clearAnimation();
audioSendButton.clearAnimation();
attachButton.clearAnimation();
sendButtonContainer.clearAnimation();
sendButton.setVisibility(GONE);
audioSendButton.setVisibility(GONE);
attachButton.setVisibility(GONE);
sendButtonContainer.setVisibility(GONE);
} else {
messageEditText.setFilters(new InputFilter[0]);
delegate.onMessageEditEnd();
audioSendButton.setVisibility(VISIBLE);
attachButton.setVisibility(VISIBLE);
sendButtonContainer.setVisibility(VISIBLE);
ViewProxy.setScaleX(attachButton, 1.0f);
ViewProxy.setAlpha(attachButton, 1.0f);
ViewProxy.setScaleX(sendButton, 0.1f);
ViewProxy.setScaleY(sendButton, 0.1f);
ViewProxy.setAlpha(sendButton, 0.0f);
ViewProxy.setScaleX(audioSendButton, 1.0f);
ViewProxy.setScaleY(audioSendButton, 1.0f);
ViewProxy.setAlpha(audioSendButton, 1.0f);
sendButton.setVisibility(View.GONE);
sendButton.clearAnimation();
messageEditText.setText("");
delegate.onAttachButtonShow();
updateFieldRight(1);
}
updateFieldHint();
}
public void setFieldText(CharSequence text) {
if (messageEditText == null) { if (messageEditText == null) {
return; return;
} }
@ -1489,7 +1788,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
botButton.setVisibility(GONE); botButton.setVisibility(GONE);
} }
updateFieldRight(2); updateFieldRight(2);
ViewProxy.setPivotX(attachButton, AndroidUtilities.dp(botButton.getVisibility() == GONE ? 48 : 96)); ViewProxy.setPivotX(attachButton, AndroidUtilities.dp((botButton == null || botButton.getVisibility() == GONE) && (notifyButton == null || notifyButton.getVisibility() == GONE) ? 48 : 96));
attachButton.clearAnimation(); attachButton.clearAnimation();
} }
@ -1621,7 +1920,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
@Override @Override
public void onGifSelected(TLRPC.Document gif) { public void onGifSelected(TLRPC.Document gif) {
SendMessagesHelper.getInstance().sendMessage((TLRPC.TL_document) gif, null, dialog_id, replyingMessageObject, asAdmin(), null); SendMessagesHelper.getInstance().sendMessage((TLRPC.TL_document) gif, null, null, dialog_id, replyingMessageObject, asAdmin(), null);
if (delegate != null) { if (delegate != null) {
delegate.onMessageSend(null); delegate.onMessageSend(null);
} }
@ -1759,6 +2058,14 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
} }
} }
public boolean isEditingMessage() {
return editingMessageObject != null;
}
public boolean isEditingCaption() {
return editingCaption;
}
public void openKeyboard() { public void openKeyboard() {
AndroidUtilities.showKeyboard(messageEditText); AndroidUtilities.showKeyboard(messageEditText);
} }
@ -1868,8 +2175,10 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
botKeyboardView.invalidateViews(); botKeyboardView.invalidateViews();
} }
} else if (id == NotificationCenter.recordProgressChanged) { } else if (id == NotificationCenter.recordProgressChanged) {
Long time = (Long) args[0] / 1000; long t = (Long) args[0];
String str = String.format("%02d:%02d", time / 60, time % 60); Long time = t / 1000;
int ms = (int) (t % 1000L) / 10;
String str = String.format("%02d:%02d.%02d", time / 60, time % 60, ms);
if (lastTimeString == null || !lastTimeString.equals(str)) { if (lastTimeString == null || !lastTimeString.equals(str)) {
if (time % 5 == 0) { if (time % 5 == 0) {
MessagesController.getInstance().sendTyping(dialog_id, 1, 0); MessagesController.getInstance().sendTyping(dialog_id, 1, 0);
@ -1897,14 +2206,77 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
updateAudioRecordIntefrace(); updateAudioRecordIntefrace();
} }
} else if (id == NotificationCenter.audioDidSent) { } else if (id == NotificationCenter.audioDidSent) {
if (delegate != null) { audioToSend = (TLRPC.TL_document) args[0];
delegate.onMessageSend(null); audioToSendPath = (String) args[1];
if (audioToSend != null) {
if (recordedAudioPanel == null) {
return;
}
TLRPC.TL_message message = new TLRPC.TL_message();
message.out = true;
message.id = 0;
message.to_id = new TLRPC.TL_peerUser();
message.to_id.user_id = message.from_id = UserConfig.getClientUserId();
message.date = (int) (System.currentTimeMillis() / 1000);
message.message = "-1";
message.attachPath = audioToSendPath;
message.media = new TLRPC.TL_messageMediaDocument();
message.media.document = audioToSend;
message.flags |= TLRPC.MESSAGE_FLAG_HAS_MEDIA | TLRPC.MESSAGE_FLAG_HAS_FROM_ID;
audioToSendMessageObject = new MessageObject(message, null, false);
ViewProxy.setAlpha(recordedAudioPanel, 1.0f);
recordedAudioPanel.clearAnimation();
recordedAudioPanel.setVisibility(VISIBLE);
int duration = 0;
for (int a = 0; a < audioToSend.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = audioToSend.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
duration = attribute.duration;
break;
}
}
for (int a = 0; a < audioToSend.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = audioToSend.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
if (attribute.waveform == null || attribute.waveform.length == 0) {
attribute.waveform = MediaController.getInstance().getWaveform(audioToSendPath);
}
recordedAudioSeekBar.setWaveform(attribute.waveform);
break;
}
}
recordedAudioTimeTextView.setText(String.format("%d:%02d", duration / 60, duration % 60));
closeKeyboard();
hidePopup(false);
checkSendButton(false);
} else {
if (delegate != null) {
delegate.onMessageSend(null);
}
} }
} else if (id == NotificationCenter.audioRouteChanged) { } else if (id == NotificationCenter.audioRouteChanged) {
if (parentActivity != null) { if (parentActivity != null) {
boolean frontSpeaker = (Boolean) args[0]; boolean frontSpeaker = (Boolean) args[0];
parentActivity.setVolumeControlStream(frontSpeaker ? AudioManager.STREAM_VOICE_CALL : AudioManager.USE_DEFAULT_STREAM_TYPE); parentActivity.setVolumeControlStream(frontSpeaker ? AudioManager.STREAM_VOICE_CALL : AudioManager.USE_DEFAULT_STREAM_TYPE);
} }
} else if (id == NotificationCenter.audioDidReset) {
if (audioToSendMessageObject != null && !MediaController.getInstance().isPlayingAudio(audioToSendMessageObject)) {
recordedAudioPlayButton.setImageResource(R.drawable.s_player_play_states);
recordedAudioSeekBar.setProgress(0);
}
} else if (id == NotificationCenter.audioProgressDidChanged) {
Integer mid = (Integer) args[0];
if (audioToSendMessageObject != null && MediaController.getInstance().isPlayingAudio(audioToSendMessageObject)) {
MessageObject player = MediaController.getInstance().getPlayingMessageObject();
audioToSendMessageObject.audioProgress = player.audioProgress;
audioToSendMessageObject.audioProgressSec = player.audioProgressSec;
if (!recordedAudioSeekBar.isDragging()) {
recordedAudioSeekBar.setProgress(audioToSendMessageObject.audioProgress);
}
}
} }
} }
} }

View File

@ -173,7 +173,7 @@ public class ChatAttachView extends FrameLayout implements NotificationCenter.No
LocaleController.getString("ChatCamera", R.string.ChatCamera), LocaleController.getString("ChatCamera", R.string.ChatCamera),
LocaleController.getString("ChatGallery", R.string.ChatGallery), LocaleController.getString("ChatGallery", R.string.ChatGallery),
LocaleController.getString("ChatVideo", R.string.ChatVideo), LocaleController.getString("ChatVideo", R.string.ChatVideo),
LocaleController.getString("AttachAudio", R.string.AttachAudio), LocaleController.getString("AttachMusic", R.string.AttachMusic),
LocaleController.getString("ChatDocument", R.string.ChatDocument), LocaleController.getString("ChatDocument", R.string.ChatDocument),
LocaleController.getString("AttachContact", R.string.AttachContact), LocaleController.getString("AttachContact", R.string.AttachContact),
LocaleController.getString("ChatLocation", R.string.ChatLocation), LocaleController.getString("ChatLocation", R.string.ChatLocation),

View File

@ -488,7 +488,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
private HashMap<String, Integer> emojiUseHistory = new HashMap<>(); private HashMap<String, Integer> emojiUseHistory = new HashMap<>();
private static HashMap<String, String> emojiColor = new HashMap<>(); private static HashMap<String, String> emojiColor = new HashMap<>();
private ArrayList<String> recentEmoji = new ArrayList<>(); private ArrayList<String> recentEmoji = new ArrayList<>();
private HashMap<Long, Integer> stickersUseHistory = new HashMap<>(); private ArrayList<Long> newRecentStickers = new ArrayList<>();
private ArrayList<TLRPC.Document> recentStickers = new ArrayList<>(); private ArrayList<TLRPC.Document> recentStickers = new ArrayList<>();
private ArrayList<TLRPC.TL_messages_stickerSet> stickerSets = new ArrayList<>(); private ArrayList<TLRPC.TL_messages_stickerSet> stickerSets = new ArrayList<>();
private ArrayList<MediaController.SearchImage> recentImages; private ArrayList<MediaController.SearchImage> recentImages;
@ -518,8 +518,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
private FlowLayoutManager flowLayoutManager; private FlowLayoutManager flowLayoutManager;
private GifsAdapter gifsAdapter; private GifsAdapter gifsAdapter;
private AdapterView.OnItemClickListener stickersOnItemClickListener; private AdapterView.OnItemClickListener stickersOnItemClickListener;
private Runnable openStickerPreviewRunnable;
private StickerEmojiCell currentStickerPreviewCell;
private EmojiColorPickerView pickerView; private EmojiColorPickerView pickerView;
private EmojiPopupWindow pickerViewPopup; private EmojiPopupWindow pickerViewPopup;
private int popupWidth; private int popupWidth;
@ -531,8 +531,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
private int gifTabBum = -2; private int gifTabBum = -2;
private boolean switchToGifTab; private boolean switchToGifTab;
private int startX;
private int startY;
private int oldWidth; private int oldWidth;
private int lastNotifyWidth; private int lastNotifyWidth;
@ -572,45 +571,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
stickersGridView = new GridView(context) { stickersGridView = new GridView(context) {
@Override @Override
public boolean onInterceptTouchEvent(MotionEvent event) { public boolean onInterceptTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) { boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersGridView, EmojiView.this.getMeasuredHeight());
int x = (int) event.getX(); return super.onInterceptTouchEvent(event) || result;
int y = (int) event.getY();
int count = stickersGridView.getChildCount();
for (int a = 0; a < count; a++) {
View view = stickersGridView.getChildAt(a);
int top = view.getTop();
int bottom = view.getBottom();
int left = view.getLeft();
int right = view.getRight();
if (top > y || bottom < y || left > x || right < x) {
continue;
}
if (!(view instanceof StickerEmojiCell) || !((StickerEmojiCell) view).showingBitmap()) {
return super.onInterceptTouchEvent(event);
}
startX = x;
startY = y;
currentStickerPreviewCell = (StickerEmojiCell) view;
openStickerPreviewRunnable = new Runnable() {
@Override
public void run() {
if (openStickerPreviewRunnable == null) {
return;
}
stickersGridView.setOnItemClickListener(null);
stickersGridView.requestDisallowInterceptTouchEvent(true);
openStickerPreviewRunnable = null;
StickerPreviewViewer.getInstance().setParentActivity((Activity) getContext());
StickerPreviewViewer.getInstance().setKeyboardHeight(EmojiView.this.getMeasuredHeight());
StickerPreviewViewer.getInstance().open(currentStickerPreviewCell.getSticker());
currentStickerPreviewCell.setScaled(true);
}
};
AndroidUtilities.runOnUIThread(openStickerPreviewRunnable, 200);
return true;
}
}
return false;
} }
@Override @Override
@ -633,67 +595,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
stickersGridView.setOnTouchListener(new OnTouchListener() { stickersGridView.setOnTouchListener(new OnTouchListener() {
@Override @Override
public boolean onTouch(View v, MotionEvent event) { public boolean onTouch(View v, MotionEvent event) {
if (openStickerPreviewRunnable != null || StickerPreviewViewer.getInstance().isVisible()) { return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView, EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
}
}, 150);
if (openStickerPreviewRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
openStickerPreviewRunnable = null;
} else if (StickerPreviewViewer.getInstance().isVisible()) {
StickerPreviewViewer.getInstance().close();
if (currentStickerPreviewCell != null) {
currentStickerPreviewCell.setScaled(false);
currentStickerPreviewCell = null;
}
}
} else if (event.getAction() != MotionEvent.ACTION_DOWN) {
if (StickerPreviewViewer.getInstance().isVisible()) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int x = (int) event.getX();
int y = (int) event.getY();
int count = stickersGridView.getChildCount();
for (int a = 0; a < count; a++) {
View view = stickersGridView.getChildAt(a);
int top = view.getTop();
int bottom = view.getBottom();
int left = view.getLeft();
int right = view.getRight();
if (top > y || bottom < y || left > x || right < x) {
continue;
}
if (!(view instanceof StickerEmojiCell) || view == currentStickerPreviewCell) {
break;
}
if (currentStickerPreviewCell != null) {
currentStickerPreviewCell.setScaled(false);
}
currentStickerPreviewCell = (StickerEmojiCell) view;
StickerPreviewViewer.getInstance().setKeyboardHeight(EmojiView.this.getMeasuredHeight());
StickerPreviewViewer.getInstance().open(currentStickerPreviewCell.getSticker());
currentStickerPreviewCell.setScaled(true);
return true;
}
}
return true;
} else if (openStickerPreviewRunnable != null) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities.dp(10)) {
AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
openStickerPreviewRunnable = null;
}
} else {
AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
openStickerPreviewRunnable = null;
}
}
}
}
return false;
} }
}); });
stickersOnItemClickListener = new AdapterView.OnItemClickListener() { stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
@ -702,35 +604,23 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
if (!(view instanceof StickerEmojiCell)) { if (!(view instanceof StickerEmojiCell)) {
return; return;
} }
if (openStickerPreviewRunnable != null) { StickerPreviewViewer.getInstance().reset();
AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
openStickerPreviewRunnable = null;
}
if (currentStickerPreviewCell != null) {
currentStickerPreviewCell.setScaled(false);
currentStickerPreviewCell = null;
}
StickerEmojiCell cell = (StickerEmojiCell) view; StickerEmojiCell cell = (StickerEmojiCell) view;
if (cell.isDisabled()) { if (cell.isDisabled()) {
return; return;
} }
cell.disable(); cell.disable();
TLRPC.Document document = cell.getSticker(); TLRPC.Document document = cell.getSticker();
Integer count = stickersUseHistory.get(document.id); int index = newRecentStickers.indexOf(document.id);
if (count == null) { if (index == -1) {
count = 0; newRecentStickers.add(0, document.id);
} if (newRecentStickers.size() > 20) {
if (count == 0 && stickersUseHistory.size() > 19) { newRecentStickers.remove(newRecentStickers.size() - 1);
for (int a = recentStickers.size() - 1; a >= 0; a--) {
TLRPC.Document sticker = recentStickers.get(a);
stickersUseHistory.remove(sticker.id);
recentStickers.remove(a);
if (stickersUseHistory.size() <= 19) {
break;
}
} }
} else if (index != 0) {
newRecentStickers.remove(index);
newRecentStickers.add(0, document.id);
} }
stickersUseHistory.put(document.id, ++count);
saveRecentStickers(); saveRecentStickers();
if (listener != null) { if (listener != null) {
@ -763,12 +653,6 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
break; break;
} }
} }
if (size.width == 0) {
size.width = 100;
}
if (size.height == 0) {
size.height = 100;
}
return size; return size;
} }
}); });
@ -821,7 +705,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
} }
}); });
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
builder.show(); builder.show().setCanceledOnTouchOutside(true);
return true; return true;
} }
}); });
@ -1213,16 +1097,13 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
private void saveRecentStickers() { private void saveRecentStickers() {
SharedPreferences.Editor editor = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE).edit(); SharedPreferences.Editor editor = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE).edit();
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
for (HashMap.Entry<Long, Integer> entry : stickersUseHistory.entrySet()) { for (int a = 0; a < newRecentStickers.size(); a++) {
if (stringBuilder.length() != 0) { if (stringBuilder.length() != 0) {
stringBuilder.append(","); stringBuilder.append(",");
} }
stringBuilder.append(entry.getKey()); stringBuilder.append(newRecentStickers.get(a));
stringBuilder.append("=");
stringBuilder.append(entry.getValue());
} }
editor.putString("stickers", stringBuilder.toString()); editor.putString("stickers2", stringBuilder.toString());
editor.commit(); editor.commit();
} }
@ -1270,43 +1151,28 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
return; return;
} }
recentStickers.clear(); recentStickers.clear();
HashMap<Long, Integer> hashMap = new HashMap<>(); for (int a = 0; a < newRecentStickers.size(); a++) {
for (HashMap.Entry<Long, Integer> entry : stickersUseHistory.entrySet()) { TLRPC.Document sticker = StickersQuery.getStickerById(newRecentStickers.get(a));
TLRPC.Document sticker = StickersQuery.getStickerById(entry.getKey());
if (sticker != null) { if (sticker != null) {
recentStickers.add(sticker); recentStickers.add(sticker);
hashMap.put(sticker.id, entry.getValue());
} }
} }
if (stickersUseHistory.size() != hashMap.size()) {
stickersUseHistory = hashMap;
saveRecentStickers();
}
Collections.sort(recentStickers, new Comparator<TLRPC.Document>() {
@Override
public int compare(TLRPC.Document lhs, TLRPC.Document rhs) {
Integer count1 = stickersUseHistory.get(lhs.id);
Integer count2 = stickersUseHistory.get(rhs.id);
if (count1 == null) {
count1 = 0;
}
if (count2 == null) {
count2 = 0;
}
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
}
return 0;
}
});
while (recentStickers.size() > 20) { while (recentStickers.size() > 20) {
recentStickers.remove(recentStickers.size() - 1); recentStickers.remove(recentStickers.size() - 1);
} }
if (newRecentStickers.size() != recentStickers.size()) {
newRecentStickers.clear();
for (int a = 0; a < recentStickers.size(); a++) {
newRecentStickers.add(recentStickers.get(a).id);
}
saveRecentStickers();
}
} }
private void updateStickerTabs() { private void updateStickerTabs() {
if (scrollSlidingTabStrip == null) {
return;
}
recentTabBum = -2; recentTabBum = -2;
gifTabBum = -2; gifTabBum = -2;
@ -1452,7 +1318,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
str = preferences.getString("color", ""); str = preferences.getString("color", "");
if (str != null && str.length() > 0) { if (str != null && str.length() > 0) {
String[] args = str.split(","); String[] args = str.split(",");
for (String arg : args) { for (int a = 0; a < args.length; a++) {
String arg = args[a];
String[] args2 = arg.split("="); String[] args2 = arg.split("=");
emojiColor.put(args2[0], args2[1]); emojiColor.put(args2[0], args2[1]);
} }
@ -1463,13 +1330,44 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
if (showStickers) { if (showStickers) {
try { try {
stickersUseHistory.clear(); newRecentStickers.clear();
str = preferences.getString("stickers", ""); str = preferences.getString("stickers", "");
if (str != null && str.length() > 0) { if (str != null && str.length() > 0) {
String[] args = str.split(","); String[] args = str.split(",");
for (String arg : args) { final HashMap<Long, Integer> stickersUseHistory = new HashMap<>();
for (int a = 0; a < args.length; a++) {
String arg = args[a];
String[] args2 = arg.split("="); String[] args2 = arg.split("=");
stickersUseHistory.put(Long.parseLong(args2[0]), Integer.parseInt(args2[1])); Long key = Long.parseLong(args2[0]);
stickersUseHistory.put(key, Integer.parseInt(args2[1]));
newRecentStickers.add(key);
}
Collections.sort(newRecentStickers, new Comparator<Long>() {
@Override
public int compare(Long lhs, Long rhs) {
Integer count1 = stickersUseHistory.get(lhs);
Integer count2 = stickersUseHistory.get(rhs);
if (count1 == null) {
count1 = 0;
}
if (count2 == null) {
count2 = 0;
}
if (count1 > count2) {
return -1;
} else if (count1 < count2) {
return 1;
}
return 0;
}
});
preferences.edit().remove("stickers").commit();
saveRecentStickers();
} else {
str = preferences.getString("stickers2", "");
String[] args = str.split(",");
for (int a = 0; a < args.length; a++) {
newRecentStickers.add(Long.parseLong(args[a]));
} }
} }
sortStickers(); sortStickers();
@ -1518,14 +1416,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
if (StickerPreviewViewer.getInstance().isVisible()) { if (StickerPreviewViewer.getInstance().isVisible()) {
StickerPreviewViewer.getInstance().close(); StickerPreviewViewer.getInstance().close();
} }
if (openStickerPreviewRunnable != null) { StickerPreviewViewer.getInstance().reset();
AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
openStickerPreviewRunnable = null;
}
if (currentStickerPreviewCell != null) {
currentStickerPreviewCell.setScaled(false);
currentStickerPreviewCell = null;
}
} }
public void setListener(Listener value) { public void setListener(Listener value) {
@ -1546,6 +1437,13 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
if (stickersGridAdapter != null) { if (stickersGridAdapter != null) {
NotificationCenter.getInstance().addObserver(this, NotificationCenter.stickersDidLoaded); NotificationCenter.getInstance().addObserver(this, NotificationCenter.stickersDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.recentImagesDidLoaded); NotificationCenter.getInstance().addObserver(this, NotificationCenter.recentImagesDidLoaded);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
updateStickerTabs();
reloadStickersAdapter();
}
});
} }
} }
@ -1576,13 +1474,16 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
} }
} }
@Override public void onDestroy() {
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (stickersGridAdapter != null) { if (stickersGridAdapter != null) {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.stickersDidLoaded); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.stickersDidLoaded);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recentImagesDidLoaded); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recentImagesDidLoaded);
} }
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (pickerViewPopup != null && pickerViewPopup.isShowing()) { if (pickerViewPopup != null && pickerViewPopup.isShowing()) {
pickerViewPopup.dismiss(); pickerViewPopup.dismiss();
} }
@ -1666,7 +1567,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
int previousCount = recentImages != null ? recentImages.size() : 0; int previousCount = recentImages != null ? recentImages.size() : 0;
recentImages = (ArrayList<MediaController.SearchImage>) args[1]; recentImages = (ArrayList<MediaController.SearchImage>) args[1];
loadingRecent = false; loadingRecent = false;
gifsAdapter.notifyDataSetChanged(); if (gifsAdapter != null) {
gifsAdapter.notifyDataSetChanged();
}
if (previousCount != recentImages.size()) { if (previousCount != recentImages.size()) {
updateStickerTabs(); updateStickerTabs();
} }

View File

@ -13,6 +13,8 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.support.widget.RecyclerView; import org.telegram.messenger.support.widget.RecyclerView;
import java.util.ArrayList; import java.util.ArrayList;
@ -356,11 +358,14 @@ public class FlowLayoutManager extends RecyclerView.LayoutManager {
} }
preferredRowSize = getHeight() / 2.0f; preferredRowSize = getHeight() / 2.0f;
float viewPortAvailableSize = getWidth(); float viewPortAvailableSize = getWidth();
if (BuildVars.DEBUG_VERSION) {
FileLog.d("tmessages", "preferredRowSize = " + preferredRowSize + " width = " + viewPortAvailableSize);
}
float totalItemSize = 0; float totalItemSize = 0;
int[] weights = new int[getItemCount()]; int[] weights = new int[getItemCount()];
for (int a = 0; a < getItemCount(); a++) { for (int a = 0; a < getItemCount(); a++) {
Size size = getSizeForItem(a); Size size = sizeForItem(a);
totalItemSize += (size.width / size.height) * preferredRowSize; totalItemSize += (size.width / size.height) * preferredRowSize;
weights[a] = Math.round(size.width / size.height * 100); weights[a] = Math.round(size.width / size.height * 100);
} }
@ -377,7 +382,7 @@ public class FlowLayoutManager extends RecyclerView.LayoutManager {
float summedRatios = 0; float summedRatios = 0;
for (int j = i, n = i + row.size(); j < n; j++) { for (int j = i, n = i + row.size(); j < n; j++) {
Size preferredSize = getSizeForItem(j); Size preferredSize = sizeForItem(j);
summedRatios += preferredSize.width / preferredSize.height; summedRatios += preferredSize.width / preferredSize.height;
} }
@ -392,7 +397,7 @@ public class FlowLayoutManager extends RecyclerView.LayoutManager {
} }
for (int j = i, n = i + row.size(); j < n; j++) { for (int j = i, n = i + row.size(); j < n; j++) {
Size preferredSize = getSizeForItem(j); Size preferredSize = sizeForItem(j);
actualSize.width = Math.round(rowSize / summedRatios * (preferredSize.width / preferredSize.height)); actualSize.width = Math.round(rowSize / summedRatios * (preferredSize.width / preferredSize.height));
actualSize.height = preferredRowSize;//Math.round(rowSize / summedRatios); actualSize.height = preferredRowSize;//Math.round(rowSize / summedRatios);
@ -503,7 +508,22 @@ public class FlowLayoutManager extends RecyclerView.LayoutManager {
return answer; return answer;
} }
private Size sizeForItem(int i) {
Size size = getSizeForItem(i);
if (size.width == 0) {
size.width = 100;
}
if (size.height == 0) {
size.height = 100;
}
float aspect = size.width / size.height;
if (aspect > 4.0f || aspect < 0.2f) {
size.height = size.width = Math.max(size.width, size.height);
}
return size;
}
protected Size getSizeForItem(int i) { protected Size getSizeForItem(int i) {
return new Size(1, 1); return new Size(100, 100);
} }
} }

View File

@ -15,7 +15,6 @@ import android.graphics.drawable.Drawable;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.messenger.Utilities;
public class IdenticonDrawable extends Drawable { public class IdenticonDrawable extends Drawable {
@ -35,9 +34,7 @@ public class IdenticonDrawable extends Drawable {
public void setEncryptedChat(TLRPC.EncryptedChat encryptedChat) { public void setEncryptedChat(TLRPC.EncryptedChat encryptedChat) {
data = encryptedChat.key_hash; data = encryptedChat.key_hash;
if (data == null) { if (data == null) {
byte[] sha1 = Utilities.computeSHA1(encryptedChat.auth_key); encryptedChat.key_hash = data = AndroidUtilities.calcAuthKeyHash(encryptedChat.auth_key);
encryptedChat.key_hash = data = new byte[16];
System.arraycopy(sha1, 0, data, 0, data.length);
} }
invalidateSelf(); invalidateSelf();
} }
@ -48,17 +45,33 @@ public class IdenticonDrawable extends Drawable {
return; return;
} }
int bitPointer = 0; if (data.length == 16) {
float rectSize = (float)Math.floor(Math.min(getBounds().width(), getBounds().height()) / 8.0f); int bitPointer = 0;
float xOffset = Math.max(0, (getBounds().width() - rectSize * 8) / 2); float rectSize = (float) Math.floor(Math.min(getBounds().width(), getBounds().height()) / 8.0f);
float yOffset = Math.max(0, (getBounds().height() - rectSize * 8) / 2); float xOffset = Math.max(0, (getBounds().width() - rectSize * 8) / 2);
for (int iy = 0; iy < 8; iy++) { float yOffset = Math.max(0, (getBounds().height() - rectSize * 8) / 2);
for (int ix = 0; ix < 8; ix++) { for (int iy = 0; iy < 8; iy++) {
int byteValue = getBits(bitPointer); for (int ix = 0; ix < 8; ix++) {
bitPointer += 2; int byteValue = getBits(bitPointer);
int colorIndex = Math.abs(byteValue) % 4; bitPointer += 2;
paint.setColor(colors[colorIndex]); int colorIndex = Math.abs(byteValue) % 4;
canvas.drawRect(xOffset + ix * rectSize, iy * rectSize + yOffset, xOffset + ix * rectSize + rectSize, iy * rectSize + rectSize + yOffset, paint); paint.setColor(colors[colorIndex]);
canvas.drawRect(xOffset + ix * rectSize, iy * rectSize + yOffset, xOffset + ix * rectSize + rectSize, iy * rectSize + rectSize + yOffset, paint);
}
}
} else {
int bitPointer = 0;
float rectSize = (float) Math.floor(Math.min(getBounds().width(), getBounds().height()) / 12.0f);
float xOffset = Math.max(0, (getBounds().width() - rectSize * 12) / 2);
float yOffset = Math.max(0, (getBounds().height() - rectSize * 12) / 2);
for (int iy = 0; iy < 12; iy++) {
for (int ix = 0; ix < 12; ix++) {
int byteValue = getBits(bitPointer);
int colorIndex = Math.abs(byteValue) % 4;
paint.setColor(colors[colorIndex]);
canvas.drawRect(xOffset + ix * rectSize, iy * rectSize + yOffset, xOffset + ix * rectSize + rectSize, iy * rectSize + rectSize + yOffset, paint);
bitPointer += 2;
}
} }
} }
} }

View File

@ -80,6 +80,132 @@ public class PhotoCropView extends FrameLayout {
requestLayout(); requestLayout();
} }
public void setOrientation(int rotation) {
orientation = rotation;
rectX = -1;
rectY = -1;
rectSizeX = 600;
rectSizeY = 600;
delegate.needMoveImageTo(0, 0, 1, false);
requestLayout();
/*float bitmapScaledWidth = bitmapWidth * bitmapGlobalScale;
float bitmapScaledHeight = bitmapHeight * bitmapGlobalScale;
float bitmapStartX = (getWidth() - AndroidUtilities.dp(28) - bitmapScaledWidth) / 2 + bitmapGlobalX + AndroidUtilities.dp(14);
float bitmapStartY = (getHeight() - AndroidUtilities.dp(28) - bitmapScaledHeight) / 2 + bitmapGlobalY + AndroidUtilities.dp(14);
float percSizeX = rectSizeX / bitmapScaledWidth;
float percSizeY = rectSizeY / bitmapScaledHeight;
float percX = (rectX - bitmapStartX) / bitmapScaledWidth + percSizeX;
float percY = (rectY - bitmapStartY) / bitmapScaledHeight;
int width;
int height;
if (orientation % 360 == 90 || orientation % 360 == 270) {
width = bitmapToEdit.getHeight();
height = bitmapToEdit.getWidth();
} else {
width = bitmapToEdit.getWidth();
height = bitmapToEdit.getHeight();
}
int x = (int) (percX * width);
int y = (int) (percY * height);
int sizeX = (int) (percSizeX * width);
int sizeY = (int) (percSizeY * height);
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x + sizeX > width) {
sizeX = width - x;
}
if (y + sizeY > height) {
sizeY = height - y;
}
double cx = (x + sizeX) - width / 2.0f;
double cy = y - height / 2.0f;
double newX = cx * Math.cos(-Math.PI / 2) - cy * Math.sin(-Math.PI / 2) + height / 2.0f;
double newY = cx * Math.sin(-Math.PI / 2) + cy * Math.cos(-Math.PI / 2) + width / 2.0f;
int temp = sizeX;
sizeY = sizeY;
sizeY = temp;*/
/*int temp = bitmapWidth;
orientation = rotation;
bitmapWidth = bitmapHeight;
bitmapHeight = temp;
bitmapScaledWidth = bitmapWidth * bitmapGlobalScale;
bitmapScaledHeight = bitmapHeight * bitmapGlobalScale;
rectX = (float) (newX * bitmapScaledWidth);
rectY = (float) (newX * bitmapScaledHeight);
float temp2 = rectSizeX;
rectSizeX = rectSizeY;
rectSizeY = temp2;
moveToFill(false);
invalidate();*/
/*float temp = rectX;
rectX = rectY;
rectY = temp;
temp = rectSizeX;
rectSizeX = rectSizeY;
rectSizeY = temp;
int temp2 = bitmapWidth;*/
//requestLayout();
/*
bitmapWidth = bitmapHeight;
bitmapHeight = temp2;*/
/*float bitmapScaledWidth = bitmapWidth * bitmapGlobalScale;
float bitmapScaledHeight = bitmapHeight * bitmapGlobalScale;
float bitmapStartX = (getWidth() - AndroidUtilities.dp(28) - bitmapScaledWidth) / 2 + bitmapGlobalX + AndroidUtilities.dp(14);
float bitmapStartY = (getHeight() - AndroidUtilities.dp(28) - bitmapScaledHeight) / 2 + bitmapGlobalY + AndroidUtilities.dp(14);
float percX = (rectX - bitmapStartX) / bitmapScaledWidth;
float percY = (rectY - bitmapStartY) / bitmapScaledHeight;
float percSizeX = rectSizeX / bitmapScaledWidth;
float percSizeY = rectSizeY / bitmapScaledHeight;
rectX = percY
int width;
int height;
if (orientation % 360 == 90 || orientation % 360 == 270) {
width = bitmapToEdit.getHeight();
height = bitmapToEdit.getWidth();
} else {
width = bitmapToEdit.getWidth();
height = bitmapToEdit.getHeight();
}
int x = (int) (percX * width);
int y = (int) (percY * height);
int sizeX = (int) (percSizeX * width);
int sizeY = (int) (percSizeY * height);
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x + sizeX > width) {
sizeX = width - x;
}
if (y + sizeY > height) {
sizeY = height - y;
}*/
//moveToFill(false);
}
public boolean onTouch(MotionEvent motionEvent) { public boolean onTouch(MotionEvent motionEvent) {
if (motionEvent == null) { if (motionEvent == null) {
draggingState = 0; draggingState = 0;
@ -353,7 +479,7 @@ public class PhotoCropView extends FrameLayout {
Matrix matrix = new Matrix(); Matrix matrix = new Matrix();
matrix.setTranslate(-bitmapToEdit.getWidth() / 2, -bitmapToEdit.getHeight() / 2); matrix.setTranslate(-bitmapToEdit.getWidth() / 2, -bitmapToEdit.getHeight() / 2);
matrix.postRotate(orientation); matrix.postRotate(orientation);
if (orientation == 90 || orientation == 270) { if (orientation % 360 == 90 || orientation % 360 == 270) {
matrix.postTranslate(bitmapToEdit.getHeight() / 2 - x, bitmapToEdit.getWidth() / 2 - y); matrix.postTranslate(bitmapToEdit.getHeight() / 2 - x, bitmapToEdit.getWidth() / 2 - y);
} else { } else {
matrix.postTranslate(bitmapToEdit.getWidth() / 2 - x, bitmapToEdit.getHeight() / 2 - y); matrix.postTranslate(bitmapToEdit.getWidth() / 2 - x, bitmapToEdit.getHeight() / 2 - y);
@ -381,7 +507,7 @@ public class PhotoCropView extends FrameLayout {
int width; int width;
int height; int height;
if (orientation == 90 || orientation == 270) { if (orientation % 360 == 90 || orientation % 360 == 270) {
width = bitmapToEdit.getHeight(); width = bitmapToEdit.getHeight();
height = bitmapToEdit.getWidth(); height = bitmapToEdit.getWidth();
} else { } else {
@ -467,7 +593,7 @@ public class PhotoCropView extends FrameLayout {
public void run() { public void run() {
if (animationRunnable == this) { if (animationRunnable == this) {
animationRunnable = null; animationRunnable = null;
animateToFill(); moveToFill(true);
} }
} }
}; };
@ -502,7 +628,7 @@ public class PhotoCropView extends FrameLayout {
} }
} }
public void animateToFill() { public void moveToFill(boolean animated) {
float scaleToX = bitmapWidth / rectSizeX; float scaleToX = bitmapWidth / rectSizeX;
float scaleToY = bitmapHeight / rectSizeY; float scaleToY = bitmapHeight / rectSizeY;
float scaleTo = scaleToX > scaleToY ? scaleToY : scaleToX; float scaleTo = scaleToX > scaleToY ? scaleToY : scaleToX;
@ -521,7 +647,7 @@ public class PhotoCropView extends FrameLayout {
float newBitmapGlobalX = newX + getWidth() / 2 * (scaleTo - 1) + (bitmapGlobalX - rectX) * scaleTo; float newBitmapGlobalX = newX + getWidth() / 2 * (scaleTo - 1) + (bitmapGlobalX - rectX) * scaleTo;
float newBitmapGlobalY = newY + getHeight() / 2 * (scaleTo - 1) + (bitmapGlobalY - rectY) * scaleTo; float newBitmapGlobalY = newY + getHeight() / 2 * (scaleTo - 1) + (bitmapGlobalY - rectY) * scaleTo;
delegate.needMoveImageTo(newBitmapGlobalX, newBitmapGlobalY, bitmapGlobalScale * scaleTo, true); delegate.needMoveImageTo(newBitmapGlobalX, newBitmapGlobalY, bitmapGlobalScale * scaleTo, animated);
} }
public void setDelegate(PhotoCropViewDelegate delegate) { public void setDelegate(PhotoCropViewDelegate delegate) {
@ -541,7 +667,7 @@ public class PhotoCropView extends FrameLayout {
float bitmapW; float bitmapW;
float bitmapH; float bitmapH;
if (orientation == 90 || orientation == 270) { if (orientation % 360 == 90 || orientation % 360 == 270) {
bitmapW = bitmapToEdit.getHeight(); bitmapW = bitmapToEdit.getHeight();
bitmapH = bitmapToEdit.getWidth(); bitmapH = bitmapToEdit.getWidth();
} else { } else {

View File

@ -61,7 +61,7 @@ public class PhotoFilterBlurControl extends FrameLayout {
private float pointerScale = 1; private float pointerScale = 1;
private boolean isMoving; private boolean isMoving;
private boolean isZooming; private boolean isZooming;
private boolean checkForMoving; private boolean checkForMoving = true;
private boolean checkForZooming; private boolean checkForZooming;
private int type; private int type;

View File

@ -0,0 +1,322 @@
/*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.telegram.ui.Components;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.text.TextPaint;
import android.view.MotionEvent;
import android.view.View;
import org.telegram.messenger.AndroidUtilities;
import java.util.Locale;
public class PhotoFilterCurvesControl extends View {
public interface PhotoFilterCurvesControlDelegate {
void valueChanged();
}
private final static int CurvesSegmentNone = 0;
private final static int CurvesSegmentBlacks = 1;
private final static int CurvesSegmentShadows = 2;
private final static int CurvesSegmentMidtones = 3;
private final static int CurvesSegmentHighlights = 4;
private final static int CurvesSegmentWhites = 5;
private final static int GestureStateBegan = 1;
private final static int GestureStateChanged = 2;
private final static int GestureStateEnded = 3;
private final static int GestureStateCancelled = 4;
private final static int GestureStateFailed = 5;
private int activeSegment = CurvesSegmentNone;
private boolean isMoving;
private boolean checkForMoving = true;
private float lastX;
private float lastY;
private Rect actualArea = new Rect();
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint paintDash = new Paint(Paint.ANTI_ALIAS_FLAG);
private Paint paintCurve = new Paint(Paint.ANTI_ALIAS_FLAG);
private TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
private Path path = new Path();
private PhotoFilterCurvesControlDelegate delegate;
private PhotoFilterView.CurvesToolValue curveValue;
public PhotoFilterCurvesControl(Context context, PhotoFilterView.CurvesToolValue value) {
super(context);
setWillNotDraw(false);
curveValue = value;
paint.setColor(0x99ffffff);
paint.setStrokeWidth(AndroidUtilities.dp(1));
paint.setStyle(Paint.Style.STROKE);
paintDash.setColor(0x99ffffff);
paintDash.setStrokeWidth(AndroidUtilities.dp(2));
paintDash.setStyle(Paint.Style.STROKE);
paintCurve.setColor(0xffffffff);
paintCurve.setStrokeWidth(AndroidUtilities.dp(2));
paintCurve.setStyle(Paint.Style.STROKE);
textPaint.setColor(0xffbfbfbf);
textPaint.setTextSize(AndroidUtilities.dp(13));
}
public void setDelegate(PhotoFilterCurvesControlDelegate photoFilterCurvesControlDelegate) {
delegate = photoFilterCurvesControlDelegate;
}
public void setActualArea(float x, float y, float width, float height) {
actualArea.x = x;
actualArea.y = y;
actualArea.width = width;
actualArea.height = height;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_DOWN: {
if (event.getPointerCount() == 1) {
if (checkForMoving && !isMoving) {
float locationX = event.getX();
float locationY = event.getY();
lastX = locationX;
lastY = locationY;
if (locationX >= actualArea.x && locationX <= actualArea.x + actualArea.width && locationY >= actualArea.y && locationY <= actualArea.y + actualArea.height) {
isMoving = true;
}
checkForMoving = false;
if (isMoving) {
handlePan(GestureStateBegan, event);
}
}
} else {
if (isMoving) {
handlePan(GestureStateEnded, event);
checkForMoving = true;
isMoving = false;
}
}
break;
}
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
if (isMoving) {
handlePan(GestureStateEnded, event);
isMoving = false;
}
checkForMoving = true;
break;
}
case MotionEvent.ACTION_MOVE: {
if (isMoving) {
handlePan(GestureStateChanged, event);
}
}
}
return true;
}
private void handlePan(int state, MotionEvent event) {
float locationX = event.getX();
float locationY = event.getY();
switch (state) {
case GestureStateBegan: {
selectSegmentWithPoint(locationX);
break;
}
case GestureStateChanged: {
float delta = Math.min(2, (lastY - locationY) / 8.0f);
PhotoFilterView.CurvesValue curveValue = null;
switch (this.curveValue.activeType) {
case PhotoFilterView.CurvesToolValue.CurvesTypeLuminance:
curveValue = this.curveValue.luminanceCurve;
break;
case PhotoFilterView.CurvesToolValue.CurvesTypeRed:
curveValue = this.curveValue.redCurve;
break;
case PhotoFilterView.CurvesToolValue.CurvesTypeGreen:
curveValue = this.curveValue.greenCurve;
break;
case PhotoFilterView.CurvesToolValue.CurvesTypeBlue:
curveValue = this.curveValue.blueCurve;
break;
default:
break;
}
switch (activeSegment) {
case CurvesSegmentBlacks:
curveValue.blacksLevel = Math.max(0, Math.min(100, curveValue.blacksLevel + delta));
break;
case CurvesSegmentShadows:
curveValue.shadowsLevel = Math.max(0, Math.min(100, curveValue.shadowsLevel + delta));
break;
case CurvesSegmentMidtones:
curveValue.midtonesLevel = Math.max(0, Math.min(100, curveValue.midtonesLevel + delta));
break;
case CurvesSegmentHighlights:
curveValue.highlightsLevel = Math.max(0, Math.min(100, curveValue.highlightsLevel + delta));
break;
case CurvesSegmentWhites:
curveValue.whitesLevel = Math.max(0, Math.min(100, curveValue.whitesLevel + delta));
break;
default:
break;
}
invalidate();
if (delegate != null) {
delegate.valueChanged();
}
lastX = locationX;
lastY = locationY;
}
break;
case GestureStateEnded:
case GestureStateCancelled:
case GestureStateFailed: {
unselectSegments();
}
break;
default:
break;
}
}
private void selectSegmentWithPoint(float pointx) {
if (activeSegment != CurvesSegmentNone) {
return;
}
float segmentWidth = actualArea.width / 5.0f;
pointx -= actualArea.x;
activeSegment = (int) Math.floor((pointx / segmentWidth) + 1);
}
private void unselectSegments() {
if (activeSegment == CurvesSegmentNone) {
return;
}
activeSegment = CurvesSegmentNone;
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
float segmentWidth = actualArea.width / 5.0f;
for (int i = 0; i < 4; i++) {
canvas.drawLine(actualArea.x + segmentWidth + i * segmentWidth, actualArea.y, actualArea.x + segmentWidth + i * segmentWidth, actualArea.y + actualArea.height, paint);
}
canvas.drawLine(actualArea.x, actualArea.y + actualArea.height, actualArea.x + actualArea.width, actualArea.y, paintDash);
PhotoFilterView.CurvesValue curvesValue = null;
switch (curveValue.activeType) {
case PhotoFilterView.CurvesToolValue.CurvesTypeLuminance:
paintCurve.setColor(0xffffffff);
curvesValue = curveValue.luminanceCurve;
break;
case PhotoFilterView.CurvesToolValue.CurvesTypeRed:
paintCurve.setColor(0xffed3d4c);
curvesValue = curveValue.redCurve;
break;
case PhotoFilterView.CurvesToolValue.CurvesTypeGreen:
paintCurve.setColor(0xff10ee9d);
curvesValue = curveValue.greenCurve;
break;
case PhotoFilterView.CurvesToolValue.CurvesTypeBlue:
paintCurve.setColor(0xff3377fb);
curvesValue = curveValue.blueCurve;
break;
default:
break;
}
for (int a = 0; a < 5; a++) {
String str;
switch (a) {
case 0:
str = String.format(Locale.US, "%.2f", curvesValue.blacksLevel / 100.0f);
break;
case 1:
str = String.format(Locale.US, "%.2f", curvesValue.shadowsLevel / 100.0f);
break;
case 2:
str = String.format(Locale.US, "%.2f", curvesValue.midtonesLevel / 100.0f);
break;
case 3:
str = String.format(Locale.US, "%.2f", curvesValue.highlightsLevel / 100.0f);
break;
case 4:
str = String.format(Locale.US, "%.2f", curvesValue.whitesLevel / 100.0f);
break;
default:
str = "";
break;
}
float width = textPaint.measureText(str);
canvas.drawText(str, actualArea.x + (segmentWidth - width) / 2 + segmentWidth * a, actualArea.y + actualArea.height - AndroidUtilities.dp(4), textPaint);
}
float[] points = curvesValue.interpolateCurve();
invalidate();
path.reset();
for (int a = 0; a < points.length / 2; a++) {
if (a == 0) {
path.moveTo(actualArea.x + points[a * 2] * actualArea.width, actualArea.y + (1.0f - points[a * 2 + 1]) * actualArea.height);
} else {
path.lineTo(actualArea.x + points[a * 2] * actualArea.width, actualArea.y + (1.0f - points[a * 2 + 1]) * actualArea.height);
}
}
canvas.drawPath(path, paintCurve);
}
}

View File

@ -22,7 +22,6 @@ import android.widget.EditText;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.Emoji; import org.telegram.messenger.Emoji;
@ -99,8 +98,8 @@ public class PhotoViewerCaptionEnterView extends FrameLayoutFixed implements Not
messageEditText = new EditText(context); messageEditText = new EditText(context);
messageEditText.setHint(LocaleController.getString("AddCaption", R.string.AddCaption)); messageEditText.setHint(LocaleController.getString("AddCaption", R.string.AddCaption));
messageEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_ACTION_DONE); messageEditText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
messageEditText.setInputType(EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES | EditorInfo.TYPE_CLASS_TEXT); messageEditText.setInputType(messageEditText.getInputType() | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES);
messageEditText.setMaxLines(4); messageEditText.setMaxLines(4);
messageEditText.setHorizontallyScrolling(false); messageEditText.setHorizontallyScrolling(false);
messageEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); messageEditText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
@ -111,7 +110,7 @@ public class PhotoViewerCaptionEnterView extends FrameLayoutFixed implements Not
messageEditText.setTextColor(0xffffffff); messageEditText.setTextColor(0xffffffff);
messageEditText.setHintTextColor(0xb2ffffff); messageEditText.setHintTextColor(0xb2ffffff);
InputFilter[] inputFilters = new InputFilter[1]; InputFilter[] inputFilters = new InputFilter[1];
inputFilters[0] = new InputFilter.LengthFilter(140); inputFilters[0] = new InputFilter.LengthFilter(200);
messageEditText.setFilters(inputFilters); messageEditText.setFilters(inputFilters);
frameLayout.addView(messageEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 52, 0, 6, 0)); frameLayout.addView(messageEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM, 52, 0, 6, 0));
messageEditText.setOnKeyListener(new OnKeyListener() { messageEditText.setOnKeyListener(new OnKeyListener() {
@ -122,9 +121,6 @@ public class PhotoViewerCaptionEnterView extends FrameLayoutFixed implements Not
showPopup(0); showPopup(0);
} }
return true; return true;
} else if (i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
delegate.onCaptionEnter();
return true;
} }
return false; return false;
} }
@ -137,19 +133,20 @@ public class PhotoViewerCaptionEnterView extends FrameLayoutFixed implements Not
} }
} }
}); });
messageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { /*messageEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override @Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_DONE || i == EditorInfo.IME_ACTION_NEXT) { if (i == EditorInfo.IME_ACTION_DONE || i == EditorInfo.IME_ACTION_NEXT) {
delegate.onCaptionEnter(); delegate.onCaptionEnter();
return true; return true;
} else if (keyEvent != null && i == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) { } else
if (keyEvent != null && i == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
delegate.onCaptionEnter(); delegate.onCaptionEnter();
return true; return true;
} }
return false; return false;
} }
}); });*/
messageEditText.addTextChangedListener(new TextWatcher() { messageEditText.addTextChangedListener(new TextWatcher() {
boolean processChange = false; boolean processChange = false;

View File

@ -99,7 +99,8 @@ public class PlayerView extends FrameLayout implements NotificationCenter.Notifi
setOnClickListener(new View.OnClickListener() { setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (fragment != null) { MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
if (messageObject != null && messageObject.isMusic() && fragment != null) {
fragment.presentFragment(new AudioPlayerActivity()); fragment.presentFragment(new AudioPlayerActivity());
} }
} }
@ -158,7 +159,7 @@ public class PlayerView extends FrameLayout implements NotificationCenter.Notifi
create = true; create = true;
} }
} }
if (messageObject == null || !messageObject.isMusic()) { if (messageObject == null || messageObject.getId() == 0/* || !messageObject.isMusic()*/) {
lastMessageObject = null; lastMessageObject = null;
if (visible) { if (visible) {
visible = false; visible = false;
@ -224,7 +225,14 @@ public class PlayerView extends FrameLayout implements NotificationCenter.Notifi
} }
if (lastMessageObject != messageObject) { if (lastMessageObject != messageObject) {
lastMessageObject = messageObject; lastMessageObject = messageObject;
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(String.format("%s - %s", messageObject.getMusicAuthor(), messageObject.getMusicTitle())); SpannableStringBuilder stringBuilder;
if (lastMessageObject.isVoice()) {
stringBuilder = new SpannableStringBuilder(String.format("%s %s", messageObject.getMusicAuthor(), messageObject.getMusicTitle()));
titleTextView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
} else {
stringBuilder = new SpannableStringBuilder(String.format("%s - %s", messageObject.getMusicAuthor(), messageObject.getMusicTitle()));
titleTextView.setEllipsize(TextUtils.TruncateAt.END);
}
TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); TypefaceSpan span = new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
stringBuilder.setSpan(span, 0, messageObject.getMusicAuthor().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); stringBuilder.setSpan(span, 0, messageObject.getMusicAuthor().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
titleTextView.setText(stringBuilder); titleTextView.setText(stringBuilder);

View File

@ -24,6 +24,7 @@ import org.telegram.messenger.MessagesController;
import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLoader;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessageObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Cells.BaseCell; import org.telegram.ui.Cells.BaseCell;
import java.io.File; import java.io.File;
@ -84,7 +85,7 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate,
TAG = MediaController.getInstance().generateObserverTag(); TAG = MediaController.getInstance().generateObserverTag();
seekBar = new SeekBar(getContext()); seekBar = new SeekBar(getContext());
seekBar.delegate = this; seekBar.setDelegate(this);
progressView = new ProgressView(); progressView = new ProgressView();
} }
@ -232,7 +233,7 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate,
boolean result = MediaController.getInstance().playAudio(currentMessageObject); boolean result = MediaController.getInstance().playAudio(currentMessageObject);
if (!currentMessageObject.isOut() && currentMessageObject.isContentUnread()) { if (!currentMessageObject.isOut() && currentMessageObject.isContentUnread()) {
if (currentMessageObject.messageOwner.to_id.channel_id == 0) { if (currentMessageObject.messageOwner.to_id.channel_id == 0) {
MessagesController.getInstance().markMessageContentAsRead(currentMessageObject.messageOwner); MessagesController.getInstance().markMessageContentAsRead(currentMessageObject);
currentMessageObject.setContentIsRead(); currentMessageObject.setContentIsRead();
} }
} }
@ -247,11 +248,11 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate,
invalidate(); invalidate();
} }
} else if (buttonState == 2) { } else if (buttonState == 2) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true); FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
buttonState = 3; buttonState = 3;
invalidate(); invalidate();
} else if (buttonState == 3) { } else if (buttonState == 3) {
FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.audio); FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.document);
buttonState = 2; buttonState = 2;
invalidate(); invalidate();
} }
@ -266,9 +267,15 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate,
seekBar.setProgress(currentMessageObject.audioProgress); seekBar.setProgress(currentMessageObject.audioProgress);
} }
int duration; int duration = 0;
if (!MediaController.getInstance().isPlayingAudio(currentMessageObject)) { if (!MediaController.getInstance().isPlayingAudio(currentMessageObject)) {
duration = currentMessageObject.messageOwner.media.audio.duration; for (int a = 0; a < currentMessageObject.messageOwner.media.document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = currentMessageObject.messageOwner.media.document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
duration = attribute.duration;
break;
}
}
} else { } else {
duration = currentMessageObject.audioProgressSec; duration = currentMessageObject.audioProgressSec;
} }
@ -282,7 +289,7 @@ public class PopupAudioView extends BaseCell implements SeekBar.SeekBarDelegate,
public void downloadAudioIfNeed() { public void downloadAudioIfNeed() {
if (buttonState == 2) { if (buttonState == 2) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true); FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
buttonState = 3; buttonState = 3;
invalidate(); invalidate();
} }

View File

@ -85,6 +85,7 @@ public class RadioButton extends View {
public void setColor(int color1, int color2) { public void setColor(int color1, int color2) {
color = color1; color = color1;
checkedColor = color2; checkedColor = color2;
invalidate();
} }
private void cancelCheckAnimator() { private void cancelCheckAnimator() {

View File

@ -9,11 +9,16 @@
package org.telegram.ui.Components; package org.telegram.ui.Components;
public class Rect { public class Rect {
public float x; public float x;
public float y; public float y;
public float width; public float width;
public float height; public float height;
public Rect() {
}
public Rect(float x, float y, float width, float height) { public Rect(float x, float y, float width, float height) {
this.x = x; this.x = x;
this.y = y; this.y = y;

View File

@ -39,9 +39,9 @@ public class ResourceLoader {
public static Drawable[][] shareDrawable = new Drawable[2][2]; public static Drawable[][] shareDrawable = new Drawable[2][2];
public static Drawable viewsCountDrawable; public static Drawable[] viewsCountDrawable = new Drawable[2];
public static Drawable viewsOutCountDrawable; public static Drawable viewsOutCountDrawable;
public static Drawable[] viewsMediaCountDrawable = new Drawable[2]; public static Drawable viewsMediaCountDrawable;
public static Drawable geoInDrawable; public static Drawable geoInDrawable;
public static Drawable geoOutDrawable; public static Drawable geoOutDrawable;
@ -79,10 +79,10 @@ public class ResourceLoader {
backgroundBlack = context.getResources().getDrawable(R.drawable.system_black); backgroundBlack = context.getResources().getDrawable(R.drawable.system_black);
backgroundBlue = context.getResources().getDrawable(R.drawable.system_blue); backgroundBlue = context.getResources().getDrawable(R.drawable.system_blue);
viewsCountDrawable = context.getResources().getDrawable(R.drawable.post_views); viewsCountDrawable[0] = context.getResources().getDrawable(R.drawable.post_views);
viewsCountDrawable[1] = context.getResources().getDrawable(R.drawable.post_views_s);
viewsOutCountDrawable = context.getResources().getDrawable(R.drawable.post_viewsg); viewsOutCountDrawable = context.getResources().getDrawable(R.drawable.post_viewsg);
viewsMediaCountDrawable[0] = context.getResources().getDrawable(R.drawable.post_views_w); viewsMediaCountDrawable = context.getResources().getDrawable(R.drawable.post_views_w);
viewsMediaCountDrawable[1] = context.getResources().getDrawable(R.drawable.post_views_s);
audioStatesDrawable[0][2] = audioStatesDrawable[0][0] = context.getResources().getDrawable(R.drawable.play_w2); audioStatesDrawable[0][2] = audioStatesDrawable[0][0] = context.getResources().getDrawable(R.drawable.play_w2);
audioStatesDrawable[0][1] = context.getResources().getDrawable(R.drawable.play_w2_pressed); audioStatesDrawable[0][1] = context.getResources().getDrawable(R.drawable.play_w2_pressed);

View File

@ -33,7 +33,7 @@ public class SeekBar {
private boolean pressed = false; private boolean pressed = false;
public int width; public int width;
public int height; public int height;
public SeekBarDelegate delegate; private SeekBarDelegate delegate;
public SeekBar(Context context) { public SeekBar(Context context) {
if (innerPaint1 == null) { if (innerPaint1 == null) {
@ -54,6 +54,10 @@ public class SeekBar {
} }
} }
public void setDelegate(SeekBarDelegate seekBarDelegate) {
delegate = seekBarDelegate;
}
public boolean onTouch(int action, float x, float y) { public boolean onTouch(int action, float x, float y) {
if (action == MotionEvent.ACTION_DOWN) { if (action == MotionEvent.ACTION_DOWN) {
int additionWidth = (height - thumbWidth) / 2; int additionWidth = (height - thumbWidth) / 2;

View File

@ -0,0 +1,190 @@
/*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.telegram.ui.Components;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.MessageObject;
public class SeekBarWaveform {
private static Paint paintInner;
private static Paint paintOuter;
public int thumbX = 0;
public int thumbDX = 0;
private float startX;
private boolean startDraging = false;
private boolean pressed = false;
public int width;
public int height;
private SeekBar.SeekBarDelegate delegate;
private byte[] waveformBytes;
private MessageObject messageObject;
private View parentView;
private boolean selected;
private int innerColor;
private int outerColor;
private int selectedColor;
public SeekBarWaveform(Context context) {
if (paintInner == null) {
paintInner = new Paint();
paintOuter = new Paint();
}
}
public void setDelegate(SeekBar.SeekBarDelegate seekBarDelegate) {
delegate = seekBarDelegate;
}
public void setColors(int inner, int outer, int selected) {
innerColor = inner;
outerColor = outer;
selectedColor = selected;
}
public void setWaveform(byte[] waveform) {
waveformBytes = waveform;
}
public void setSelected(boolean value) {
selected = value;
}
public void setMessageObject(MessageObject object) {
messageObject = object;
}
public void setParentView(View view) {
parentView = view;
}
public boolean isStartDraging() {
return startDraging;
}
public boolean onTouch(int action, float x, float y) {
if (action == MotionEvent.ACTION_DOWN) {
if (0 <= x && x <= width && y >= 0 && y <= height) {
startX = x;
pressed = true;
thumbDX = (int) (x - thumbX);
startDraging = false;
return true;
}
} else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
if (pressed) {
if (action == MotionEvent.ACTION_UP && delegate != null) {
delegate.onSeekBarDrag((float) thumbX / (float) width);
}
pressed = false;
return true;
}
} else if (action == MotionEvent.ACTION_MOVE) {
if (pressed) {
if (startDraging) {
thumbX = (int) (x - thumbDX);
if (thumbX < 0) {
thumbX = 0;
} else if (thumbX > width) {
thumbX = width;
}
}
if (startX != -1 && Math.abs(x - startX) > AndroidUtilities.getPixelsInCM(0.2f, true)) {
if (parentView != null) {
parentView.getParent().requestDisallowInterceptTouchEvent(true);
}
startDraging = true;
startX = -1;
}
return true;
}
}
return false;
}
public void setProgress(float progress) {
thumbX = (int)Math.ceil(width * progress);
if (thumbX < 0) {
thumbX = 0;
} else if (thumbX > width) {
thumbX = width;
}
}
public boolean isDragging() {
return pressed;
}
public void draw(Canvas canvas) {
if (waveformBytes == null || width == 0) {
return;
}
float totalBarsCount = width / AndroidUtilities.dp(3);
if (totalBarsCount <= 0.1f) {
return;
}
byte value;
int samplesCount = (waveformBytes.length * 8 / 5);
float samplesPerBar = samplesCount / totalBarsCount;
float barCounter = 0;
int nextBarNum = 0;
paintInner.setColor(messageObject != null && !messageObject.isOutOwner() && messageObject.isContentUnread() && messageObject.messageOwner.to_id.channel_id == 0 ? outerColor : (selected ? selectedColor : innerColor));
paintOuter.setColor(outerColor);
int y = (height - AndroidUtilities.dp(14)) / 2;
int barNum = 0;
int lastBarNum;
int drawBarCount;
for (int a = 0; a < samplesCount; a++) {
if (a != nextBarNum) {
continue;
}
drawBarCount = 0;
lastBarNum = nextBarNum;
while (lastBarNum == nextBarNum) {
barCounter += samplesPerBar;
nextBarNum = (int) barCounter;
drawBarCount++;
}
int bitPointer = a * 5;
int byteNum = bitPointer / 8;
int byteBitOffset = bitPointer - byteNum * 8;
int currentByteCount = 8 - byteBitOffset;
int nextByteRest = 5 - currentByteCount;
value = (byte) ((waveformBytes[byteNum] >> byteBitOffset) & ((2 << (Math.min(5, currentByteCount) - 1)) - 1));
if (nextByteRest > 0) {
value <<= nextByteRest;
value |= waveformBytes[byteNum + 1] & ((2 << (nextByteRest - 1)) - 1);
}
for (int b = 0; b < drawBarCount; b++) {
int x = barNum * AndroidUtilities.dp(3);
if (x < thumbX && x + AndroidUtilities.dp(2) < thumbX) {
canvas.drawRect(x, y + AndroidUtilities.dp(14 - Math.max(1, 14.0f * value / 31.0f)), x + AndroidUtilities.dp(2), y + AndroidUtilities.dp(14), paintOuter);
} else {
canvas.drawRect(x, y + AndroidUtilities.dp(14 - Math.max(1, 14.0f * value / 31.0f)), x + AndroidUtilities.dp(2), y + AndroidUtilities.dp(14), paintInner);
if (x < thumbX) {
canvas.drawRect(x, y + AndroidUtilities.dp(14 - Math.max(1, 14.0f * value / 31.0f)), thumbX, y + AndroidUtilities.dp(14), paintOuter);
}
}
barNum++;
}
}
}
}

View File

@ -9,6 +9,7 @@
package org.telegram.ui.Components; package org.telegram.ui.Components;
import android.content.Context; import android.content.Context;
import android.os.Build;
import android.text.Editable; import android.text.Editable;
import android.text.InputType; import android.text.InputType;
import android.text.TextUtils; import android.text.TextUtils;
@ -26,9 +27,11 @@ import android.widget.GridView;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast;
import org.telegram.SQLite.SQLiteCursor; import org.telegram.SQLite.SQLiteCursor;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatObject;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
@ -37,7 +40,9 @@ import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.SendMessagesHelper;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.BottomSheet; import org.telegram.ui.ActionBar.BottomSheet;
@ -66,12 +71,44 @@ public class ShareFrameLayout extends FrameLayout {
private EmptyTextProgressView searchEmptyView; private EmptyTextProgressView searchEmptyView;
private HashMap<Long, TLRPC.Dialog> selectedDialogs = new HashMap<>(); private HashMap<Long, TLRPC.Dialog> selectedDialogs = new HashMap<>();
public ShareFrameLayout(Context context, BottomSheet bottomSheet, MessageObject messageObject) { private TLRPC.TL_exportedMessageLink exportedMessageLink;
private boolean loadingLink;
private boolean copyLinkOnEnd;
private boolean isPublicChannel;
public ShareFrameLayout(final Context context, BottomSheet bottomSheet, final MessageObject messageObject, boolean publicChannel) {
super(context); super(context);
parentBottomSheet = bottomSheet; parentBottomSheet = bottomSheet;
sendingMessageObject = messageObject; sendingMessageObject = messageObject;
searchAdapter = new ShareSearchAdapter(context); searchAdapter = new ShareSearchAdapter(context);
isPublicChannel = publicChannel;
if (publicChannel) {
loadingLink = true;
TLRPC.TL_channels_exportMessageLink req = new TLRPC.TL_channels_exportMessageLink();
req.id = messageObject.getId();
req.channel = MessagesController.getInputChannel(messageObject.messageOwner.to_id.channel_id);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(final TLObject response, TLRPC.TL_error error) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (response != null) {
exportedMessageLink = (TLRPC.TL_exportedMessageLink) response;
if (copyLinkOnEnd) {
copyLink(context);
}
}
loadingLink = false;
}
});
}
});
}
FrameLayout frameLayout = new FrameLayout(context); FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setBackgroundColor(0xffffffff); frameLayout.setBackgroundColor(0xffffffff);
@ -85,21 +122,31 @@ public class ShareFrameLayout extends FrameLayout {
doneButton.setOnClickListener(new OnClickListener() { doneButton.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
ArrayList<MessageObject> arrayList = new ArrayList<>(); if (selectedDialogs.isEmpty() && isPublicChannel) {
arrayList.add(sendingMessageObject); if (loadingLink) {
for (HashMap.Entry<Long, TLRPC.Dialog> entry : selectedDialogs.entrySet()) { copyLinkOnEnd = true;
TLRPC.Dialog dialog = entry.getValue(); Toast.makeText(ShareFrameLayout.this.getContext(), LocaleController.getString("Loading", R.string.Loading), Toast.LENGTH_SHORT).show();
boolean asAdmin = true; } else {
int lower_id = (int) dialog.id; copyLink(ShareFrameLayout.this.getContext());
if (lower_id < 0) {
TLRPC.Chat chat = MessagesController.getInstance().getChat(-lower_id);
if (chat.megagroup) {
asAdmin = false;
}
} }
SendMessagesHelper.getInstance().sendMessage(arrayList, entry.getKey(), asAdmin); parentBottomSheet.dismiss();
} else {
ArrayList<MessageObject> arrayList = new ArrayList<>();
arrayList.add(sendingMessageObject);
for (HashMap.Entry<Long, TLRPC.Dialog> entry : selectedDialogs.entrySet()) {
TLRPC.Dialog dialog = entry.getValue();
boolean asAdmin = true;
int lower_id = (int) dialog.id;
if (lower_id < 0) {
TLRPC.Chat chat = MessagesController.getInstance().getChat(-lower_id);
if (chat.megagroup) {
asAdmin = false;
}
}
SendMessagesHelper.getInstance().sendMessage(arrayList, entry.getKey(), asAdmin);
}
parentBottomSheet.dismiss();
} }
parentBottomSheet.dismiss();
} }
}); });
@ -118,7 +165,6 @@ public class ShareFrameLayout extends FrameLayout {
doneButtonTextView.setTextColor(0xff19a7e8); doneButtonTextView.setTextColor(0xff19a7e8);
doneButtonTextView.setGravity(Gravity.CENTER); doneButtonTextView.setGravity(Gravity.CENTER);
doneButtonTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8)); doneButtonTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
doneButtonTextView.setText(LocaleController.getString("Send", R.string.Send).toUpperCase());
doneButtonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); doneButtonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
doneButton.addView(doneButtonTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL)); doneButton.addView(doneButtonTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL));
@ -218,7 +264,7 @@ public class ShareFrameLayout extends FrameLayout {
selectedDialogs.put(dialog.id, dialog); selectedDialogs.put(dialog.id, dialog);
cell.setChecked(true, true); cell.setChecked(true, true);
} }
updateSelectedCount(selectedDialogs.size(), true); updateSelectedCount();
} }
}); });
@ -229,20 +275,47 @@ public class ShareFrameLayout extends FrameLayout {
gridView.setEmptyView(searchEmptyView); gridView.setEmptyView(searchEmptyView);
addView(searchEmptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 0)); addView(searchEmptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 48, 0, 0));
updateSelectedCount(selectedDialogs.size(), true); updateSelectedCount();
} }
public void updateSelectedCount(int count, boolean disable) { public void copyLink(Context context) {
if (count == 0) { if (exportedMessageLink == null) {
return;
}
try {
if (Build.VERSION.SDK_INT < 11) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(exportedMessageLink.link);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("label", exportedMessageLink.link);
clipboard.setPrimaryClip(clip);
}
Toast.makeText(context, LocaleController.getString("LinkCopied", R.string.LinkCopied), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public void updateSelectedCount() {
if (selectedDialogs.isEmpty()) {
doneButtonBadgeTextView.setVisibility(View.GONE); doneButtonBadgeTextView.setVisibility(View.GONE);
doneButtonTextView.setTextColor(0xffb3b3b3); if (!isPublicChannel) {
doneButton.setEnabled(false); doneButtonTextView.setTextColor(0xffb3b3b3);
doneButton.setEnabled(false);
doneButtonTextView.setText(LocaleController.getString("Send", R.string.Send).toUpperCase());
} else {
doneButtonTextView.setTextColor(0xff517fad);
doneButton.setEnabled(true);
doneButtonTextView.setText(LocaleController.getString("CopyLink", R.string.CopyLink).toUpperCase());
}
} else { } else {
doneButtonTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); doneButtonTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
doneButtonBadgeTextView.setVisibility(View.VISIBLE); doneButtonBadgeTextView.setVisibility(View.VISIBLE);
doneButtonBadgeTextView.setText(String.format("%d", count)); doneButtonBadgeTextView.setText(String.format("%d", selectedDialogs.size()));
doneButtonTextView.setTextColor(0xff3ec1f9); doneButtonTextView.setTextColor(0xff3ec1f9);
doneButton.setEnabled(true); doneButton.setEnabled(true);
doneButtonTextView.setText(LocaleController.getString("Send", R.string.Send).toUpperCase());
} }
} }

View File

@ -12,6 +12,7 @@ import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.database.DataSetObserver; import android.database.DataSetObserver;
import android.view.MotionEvent;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.BaseAdapter; import android.widget.BaseAdapter;
@ -22,6 +23,7 @@ import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.NotificationCenter;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Cells.StickerEmojiCell; import org.telegram.ui.Cells.StickerEmojiCell;
import org.telegram.ui.StickerPreviewViewer;
import java.util.ArrayList; import java.util.ArrayList;
@ -42,10 +44,22 @@ public class StickersAlert extends AlertDialog implements NotificationCenter.Not
}; };
setView(container, AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), 0); setView(container, AndroidUtilities.dp(16), 0, AndroidUtilities.dp(16), 0);
gridView = new GridView(context); gridView = new GridView(context) {
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, gridView, 0);
return super.onInterceptTouchEvent(event) || result;
}
};
gridView.setNumColumns(4); gridView.setNumColumns(4);
gridView.setAdapter(new GridAdapter(context)); gridView.setAdapter(new GridAdapter(context));
gridView.setVerticalScrollBarEnabled(false); gridView.setVerticalScrollBarEnabled(false);
gridView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return StickerPreviewViewer.getInstance().onTouch(event, gridView, 0, null);
}
});
container.addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); container.addView(gridView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
setTitle(set.set.title); setTitle(set.set.title);
@ -77,6 +91,10 @@ public class StickersAlert extends AlertDialog implements NotificationCenter.Not
if (gridView != null) { if (gridView != null) {
gridView.invalidateViews(); gridView.invalidateViews();
} }
if (StickerPreviewViewer.getInstance().isVisible()) {
StickerPreviewViewer.getInstance().close();
}
StickerPreviewViewer.getInstance().reset();
} }
} }

View File

@ -10,10 +10,7 @@ package org.telegram.ui.Components;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.provider.Browser;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.Gravity; import android.view.Gravity;
@ -95,10 +92,7 @@ public class WebFrameLayout extends FrameLayout {
textView.setOnClickListener(new OnClickListener() { textView.setOnClickListener(new OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
Uri uri = Uri.parse(openUrl); AndroidUtilities.openUrl(getContext(), openUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getContext().getPackageName());
getContext().startActivity(intent);
if (dialog != null) { if (dialog != null) {
dialog.dismiss(); dialog.dismiss();
} }

View File

@ -39,6 +39,7 @@ import android.widget.ProgressBar;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.ChatObject; import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
@ -277,7 +278,11 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
} else { } else {
actionBar.setBackButtonDrawable(new MenuDrawable()); actionBar.setBackButtonDrawable(new MenuDrawable());
} }
actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName)); if (BuildVars.DEBUG_VERSION) {
actionBar.setTitle(LocaleController.getString("AppNameBeta", R.string.AppNameBeta));
} else {
actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName));
}
} }
actionBar.setAllowOverlayTitle(true); actionBar.setAllowOverlayTitle(true);
@ -849,7 +854,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
ContactsController.getInstance().readContacts(); ContactsController.getInstance().readContacts();
break; break;
case Manifest.permission.WRITE_EXTERNAL_STORAGE: case Manifest.permission.WRITE_EXTERNAL_STORAGE:
ImageLoader.getInstance().createMediaPaths(); ImageLoader.getInstance().checkMediaPaths();
break; break;
} }
} }

View File

@ -9,6 +9,7 @@
package org.telegram.ui; package org.telegram.ui;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Canvas; import android.graphics.Canvas;
@ -77,12 +78,13 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
private int beforeChangeIndex; private int beforeChangeIndex;
private boolean ignoreChange; private boolean ignoreChange;
private CharSequence changeString; private CharSequence changeString;
private int maxCount = 199; private int maxCount = 1000;
private int chatType = ChatObject.CHAT_TYPE_CHAT; private int chatType = ChatObject.CHAT_TYPE_CHAT;
private boolean isAlwaysShare; private boolean isAlwaysShare;
private boolean isNeverShare; private boolean isNeverShare;
private boolean searchWas; private boolean searchWas;
private boolean searching; private boolean searching;
private boolean isGroup;
private HashMap<Integer, ChipSpan> selectedContacts = new HashMap<>(); private HashMap<Integer, ChipSpan> selectedContacts = new HashMap<>();
private ArrayList<ChipSpan> allSpans = new ArrayList<>(); private ArrayList<ChipSpan> allSpans = new ArrayList<>();
@ -97,7 +99,8 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
chatType = args.getInt("chatType", ChatObject.CHAT_TYPE_CHAT); chatType = args.getInt("chatType", ChatObject.CHAT_TYPE_CHAT);
isAlwaysShare = args.getBoolean("isAlwaysShare", false); isAlwaysShare = args.getBoolean("isAlwaysShare", false);
isNeverShare = args.getBoolean("isNeverShare", false); isNeverShare = args.getBoolean("isNeverShare", false);
maxCount = chatType == ChatObject.CHAT_TYPE_CHAT ? (MessagesController.getInstance().maxGroupCount - 1) : MessagesController.getInstance().maxBroadcastCount; isGroup = args.getBoolean("isGroup", false);
maxCount = chatType == ChatObject.CHAT_TYPE_CHAT ? MessagesController.getInstance().maxMegagroupCount : MessagesController.getInstance().maxBroadcastCount;
} }
@Override @Override
@ -124,9 +127,17 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true); actionBar.setAllowOverlayTitle(true);
if (isAlwaysShare) { if (isAlwaysShare) {
actionBar.setTitle(LocaleController.getString("AlwaysShareWithTitle", R.string.AlwaysShareWithTitle)); if (isGroup) {
actionBar.setTitle(LocaleController.getString("AlwaysAllow", R.string.AlwaysAllow));
} else {
actionBar.setTitle(LocaleController.getString("AlwaysShareWithTitle", R.string.AlwaysShareWithTitle));
}
} else if (isNeverShare) { } else if (isNeverShare) {
actionBar.setTitle(LocaleController.getString("NeverShareWithTitle", R.string.NeverShareWithTitle)); if (isGroup) {
actionBar.setTitle(LocaleController.getString("NeverAllow", R.string.NeverAllow));
} else {
actionBar.setTitle(LocaleController.getString("NeverShareWithTitle", R.string.NeverShareWithTitle));
}
} else { } else {
actionBar.setTitle(chatType == ChatObject.CHAT_TYPE_CHAT ? LocaleController.getString("NewGroup", R.string.NewGroup) : LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList)); actionBar.setTitle(chatType == ChatObject.CHAT_TYPE_CHAT ? LocaleController.getString("NewGroup", R.string.NewGroup) : LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList));
actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount)); actionBar.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount));
@ -191,9 +202,17 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
frameLayout.addView(userSelectEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 10, 0, 10, 0)); frameLayout.addView(userSelectEditText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 10, 0, 10, 0));
if (isAlwaysShare) { if (isAlwaysShare) {
userSelectEditText.setHint(LocaleController.getString("AlwaysShareWithPlaceholder", R.string.AlwaysShareWithPlaceholder)); if (isGroup) {
userSelectEditText.setHint(LocaleController.getString("AlwaysAllowPlaceholder", R.string.AlwaysAllowPlaceholder));
} else {
userSelectEditText.setHint(LocaleController.getString("AlwaysShareWithPlaceholder", R.string.AlwaysShareWithPlaceholder));
}
} else if (isNeverShare) { } else if (isNeverShare) {
userSelectEditText.setHint(LocaleController.getString("NeverShareWithPlaceholder", R.string.NeverShareWithPlaceholder)); if (isGroup) {
userSelectEditText.setHint(LocaleController.getString("NeverAllowPlaceholder", R.string.NeverAllowPlaceholder));
} else {
userSelectEditText.setHint(LocaleController.getString("NeverShareWithPlaceholder", R.string.NeverShareWithPlaceholder));
}
} else { } else {
userSelectEditText.setHint(LocaleController.getString("SendMessageTo", R.string.SendMessageTo)); userSelectEditText.setHint(LocaleController.getString("SendMessageTo", R.string.SendMessageTo));
} }
@ -356,6 +375,14 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
if (maxCount != 0 && selectedContacts.size() == maxCount) { if (maxCount != 0 && selectedContacts.size() == maxCount) {
return; return;
} }
if (chatType == ChatObject.CHAT_TYPE_CHAT && selectedContacts.size() == MessagesController.getInstance().maxGroupCount - 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setMessage(LocaleController.getString("SoftUserLimitAlert", R.string.SoftUserLimitAlert));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
showDialog(builder.create());
return;
}
ignoreChange = true; ignoreChange = true;
ChipSpan span = createAndPutChipForUser(user); ChipSpan span = createAndPutChipForUser(user);
span.uid = user.id; span.uid = user.id;

View File

@ -164,7 +164,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
donePressed = true; donePressed = true;
if (chatType == ChatObject.CHAT_TYPE_BROADCAST) { if (chatType == ChatObject.CHAT_TYPE_BROADCAST) {
MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, null, chatType); MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, null, chatType, GroupCreateFinalActivity.this);
} else { } else {
if (avatarUpdater.uploadingAvatar != null) { if (avatarUpdater.uploadingAvatar != null) {
createAfterUpload = true; createAfterUpload = true;
@ -174,7 +174,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false); progressDialog.setCancelable(false);
final int reqId = MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, null, chatType); final int reqId = MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, null, chatType, GroupCreateFinalActivity.this);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() {
@Override @Override
@ -335,7 +335,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
avatarImage.setImage(avatar, "50_50", avatarDrawable); avatarImage.setImage(avatar, "50_50", avatarDrawable);
if (createAfterUpload) { if (createAfterUpload) {
FileLog.e("tmessages", "avatar did uploaded"); FileLog.e("tmessages", "avatar did uploaded");
MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, null, chatType); MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, null, chatType, GroupCreateFinalActivity.this);
} }
} }
}); });

View File

@ -10,28 +10,53 @@ package org.telegram.ui;
import android.content.Context; import android.content.Context;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.Surface; import android.view.Surface;
import android.view.View; import android.view.View;
import android.view.ViewTreeObserver; import android.view.ViewTreeObserver;
import android.view.WindowManager; import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.TLRPC; import org.telegram.tgnet.TLRPC;
import org.telegram.messenger.MessagesController; import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.ui.ActionBar.ActionBar; import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Components.IdenticonDrawable; import org.telegram.ui.Components.IdenticonDrawable;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.URLSpanReplacement;
public class IdenticonActivity extends BaseFragment { public class IdenticonActivity extends BaseFragment {
private int chat_id; private int chat_id;
private static class LinkMovementMethodMy extends LinkMovementMethod {
@Override
public boolean onTouchEvent(@NonNull TextView widget, @NonNull Spannable buffer, @NonNull MotionEvent event) {
try {
return super.onTouchEvent(widget, buffer, event);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return false;
}
}
public IdenticonActivity(Bundle args) { public IdenticonActivity(Bundle args) {
super(args); super(args);
} }
@ -57,18 +82,11 @@ public class IdenticonActivity extends BaseFragment {
} }
}); });
fragmentView = getParentActivity().getLayoutInflater().inflate(R.layout.identicon_layout, null, false); fragmentView = new LinearLayout(context);
ImageView identiconView = (ImageView) fragmentView.findViewById(R.id.identicon_view); LinearLayout linearLayout = (LinearLayout) fragmentView;
TextView textView = (TextView) fragmentView.findViewById(R.id.identicon_text); linearLayout.setOrientation(LinearLayout.VERTICAL);
TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat(chat_id); linearLayout.setWeightSum(100);
if (encryptedChat != null) { linearLayout.setBackgroundColor(0xfff0f0f0);
IdenticonDrawable drawable = new IdenticonDrawable();
identiconView.setImageDrawable(drawable);
drawable.setEncryptedChat(encryptedChat);
TLRPC.User user = MessagesController.getInstance().getUser(encryptedChat.user_id);
textView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("EncryptionKeyDescription", R.string.EncryptionKeyDescription, user.first_name, user.first_name)));
}
fragmentView.setOnTouchListener(new View.OnTouchListener() { fragmentView.setOnTouchListener(new View.OnTouchListener() {
@Override @Override
public boolean onTouch(View v, MotionEvent event) { public boolean onTouch(View v, MotionEvent event) {
@ -76,6 +94,61 @@ public class IdenticonActivity extends BaseFragment {
} }
}); });
FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(20), AndroidUtilities.dp(20), AndroidUtilities.dp(20));
linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 50.0f));
ImageView identiconView = new ImageView(context);
identiconView.setScaleType(ImageView.ScaleType.FIT_XY);
frameLayout.addView(identiconView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
frameLayout = new FrameLayout(context);
frameLayout.setBackgroundColor(0xffffffff);
frameLayout.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), AndroidUtilities.dp(10));
linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 50.0f));
TextView textView = new TextView(context);
textView.setTextColor(0xff7f7f7f);
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textView.setLinksClickable(true);
textView.setClickable(true);
textView.setMovementMethod(new LinkMovementMethodMy());
//textView.setAutoLinkMask(Linkify.WEB_URLS);
textView.setLinkTextColor(0xff316f9f);
textView.setGravity(Gravity.CENTER);
frameLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat(chat_id);
if (encryptedChat != null) {
IdenticonDrawable drawable = new IdenticonDrawable();
identiconView.setImageDrawable(drawable);
drawable.setEncryptedChat(encryptedChat);
TLRPC.User user = MessagesController.getInstance().getUser(encryptedChat.user_id);
SpannableStringBuilder hash = new SpannableStringBuilder();
if (encryptedChat.key_hash.length > 16) {
String hex = Utilities.bytesToHex(encryptedChat.key_hash);
for (int a = 0; a < 32; a++) {
if (a != 0) {
if (a % 8 == 0) {
hash.append('\n');
} else if (a % 4 == 0) {
hash.append(' ');
}
}
hash.append(hex.substring(a * 2, a * 2 + 2));
hash.append(' ');
}
hash.append("\n\n");
}
hash.append(AndroidUtilities.replaceTags(LocaleController.formatString("EncryptionKeyDescription", R.string.EncryptionKeyDescription, user.first_name, user.first_name)));
final String url = "telegram.org";
int index = hash.toString().indexOf(url);
if (index != -1) {
hash.setSpan(new URLSpanReplacement(LocaleController.getString("EncryptionKeyLink", R.string.EncryptionKeyLink)), index, index + url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
textView.setText(hash);
}
return fragmentView; return fragmentView;
} }
@ -100,7 +173,7 @@ public class IdenticonActivity extends BaseFragment {
return true; return true;
} }
fragmentView.getViewTreeObserver().removeOnPreDrawListener(this); fragmentView.getViewTreeObserver().removeOnPreDrawListener(this);
LinearLayout layout = (LinearLayout)fragmentView; LinearLayout layout = (LinearLayout) fragmentView;
WindowManager manager = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Context.WINDOW_SERVICE); WindowManager manager = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Context.WINDOW_SERVICE);
int rotation = manager.getDefaultDisplay().getRotation(); int rotation = manager.getDefaultDisplay().getRotation();

View File

@ -28,7 +28,7 @@ import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildConfig; import org.telegram.messenger.BuildVars;
import org.telegram.messenger.LocaleController; import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R; import org.telegram.messenger.R;
import org.telegram.tgnet.ConnectionsManager; import org.telegram.tgnet.ConnectionsManager;
@ -221,7 +221,7 @@ public class IntroActivity extends Activity {
finish(); finish();
} }
}); });
if (BuildConfig.DEBUG) { if (BuildVars.DEBUG_VERSION) {
startMessagingButton.setOnLongClickListener(new View.OnLongClickListener() { startMessagingButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override @Override
public boolean onLongClick(View v) { public boolean onLongClick(View v) {

View File

@ -24,7 +24,6 @@ import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Parcelable; import android.os.Parcelable;
import android.provider.Browser;
import android.provider.ContactsContract; import android.provider.ContactsContract;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.view.ActionMode; import android.view.ActionMode;
@ -53,6 +52,7 @@ import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NativeCrashManager; import org.telegram.messenger.NativeCrashManager;
import org.telegram.messenger.SendMessagesHelper; import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.UserObject; import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.query.StickersQuery; import org.telegram.messenger.query.StickersQuery;
import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLog; import org.telegram.messenger.FileLog;
@ -75,6 +75,7 @@ import java.io.BufferedReader;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
public class LaunchActivity extends Activity implements ActionBarLayout.ActionBarLayoutDelegate, NotificationCenter.NotificationCenterDelegate, DialogsActivity.MessagesActivityDelegate { public class LaunchActivity extends Activity implements ActionBarLayout.ActionBarLayoutDelegate, NotificationCenter.NotificationCenterDelegate, DialogsActivity.MessagesActivityDelegate {
@ -327,12 +328,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
presentFragment(new SettingsActivity()); presentFragment(new SettingsActivity());
drawerLayoutContainer.closeDrawer(false); drawerLayoutContainer.closeDrawer(false);
} else if (position == 9) { } else if (position == 9) {
try { AndroidUtilities.openUrl(LaunchActivity.this, LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
Intent pickIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl)));
startActivityForResult(pickIntent, 500);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
drawerLayoutContainer.closeDrawer(false); drawerLayoutContainer.closeDrawer(false);
} }
} }
@ -610,7 +606,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
error = true; error = true;
} }
} else { } else {
if (type != null && (type.equals("text/plain") || type.equals("message/rfc822")) && (intent.getStringExtra(Intent.EXTRA_TEXT) != null || intent.getCharSequenceExtra(Intent.EXTRA_TEXT) != null)) { if ((type == null || type != null && (type.equals("text/plain") || type.equals("message/rfc822"))) && (intent.getStringExtra(Intent.EXTRA_TEXT) != null || intent.getCharSequenceExtra(Intent.EXTRA_TEXT) != null)) {
String text = intent.getStringExtra(Intent.EXTRA_TEXT); String text = intent.getStringExtra(Intent.EXTRA_TEXT);
if (text == null) { if (text == null) {
text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT).toString(); text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT).toString();
@ -622,8 +618,8 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
text = subject + "\n" + text; text = subject + "\n" + text;
} }
sendingText = text; sendingText = text;
} else { } else if (subject != null && subject.length() > 0) {
error = true; sendingText = subject;
} }
} }
Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM); Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM);
@ -633,38 +629,48 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
parcelable = Uri.parse(parcelable.toString()); parcelable = Uri.parse(parcelable.toString());
} }
Uri uri = (Uri) parcelable; Uri uri = (Uri) parcelable;
if (uri != null && (type != null && type.startsWith("image/") || uri.toString().toLowerCase().endsWith(".jpg"))) { if (uri != null) {
if (photoPathsArray == null) { if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
photoPathsArray = new ArrayList<>(); String pathString = Utilities.readlink(uri.getPath());
} if (pathString != null && pathString.contains("/data/data/" + getPackageName() + "/files")) {
photoPathsArray.add(uri); error = true;
} else {
path = AndroidUtilities.getPath(uri);
if (path != null) {
if (path.startsWith("file:")) {
path = path.replace("file://", "");
} }
if (type != null && type.startsWith("video/")) {
videoPath = path;
} else {
if (documentsPathsArray == null) {
documentsPathsArray = new ArrayList<>();
documentsOriginalPathsArray = new ArrayList<>();
}
documentsPathsArray.add(path);
documentsOriginalPathsArray.add(uri.toString());
}
} else {
if (documentsUrisArray == null) {
documentsUrisArray = new ArrayList<>();
}
documentsUrisArray.add(uri);
documentsMimeType = type;
} }
} }
if (sendingText != null) { if (!error) {
if (sendingText.contains("WhatsApp")) { //remove unnecessary caption 'sent from WhatsApp' from photos forwarded from WhatsApp if (uri != null && (type != null && type.startsWith("image/") || uri.toString().toLowerCase().endsWith(".jpg"))) {
sendingText = null; if (photoPathsArray == null) {
photoPathsArray = new ArrayList<>();
}
photoPathsArray.add(uri);
} else {
path = AndroidUtilities.getPath(uri);
if (path != null) {
if (path.startsWith("file:")) {
path = path.replace("file://", "");
}
if (type != null && type.startsWith("video/")) {
videoPath = path;
} else {
if (documentsPathsArray == null) {
documentsPathsArray = new ArrayList<>();
documentsOriginalPathsArray = new ArrayList<>();
}
documentsPathsArray.add(path);
documentsOriginalPathsArray.add(uri.toString());
}
} else {
if (documentsUrisArray == null) {
documentsUrisArray = new ArrayList<>();
}
documentsUrisArray.add(uri);
documentsMimeType = type;
}
}
if (sendingText != null) {
if (sendingText.contains("WhatsApp")) { //remove unnecessary caption 'sent from WhatsApp' from photos forwarded from WhatsApp
sendingText = null;
}
} }
} }
} else if (sendingText == null) { } else if (sendingText == null) {
@ -679,9 +685,31 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
try { try {
ArrayList<Parcelable> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); ArrayList<Parcelable> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
String type = intent.getType(); String type = intent.getType();
if (uris != null) {
for (int a = 0; a < uris.size(); a++) {
Parcelable parcelable = uris.get(a);
if (!(parcelable instanceof Uri)) {
parcelable = Uri.parse(parcelable.toString());
}
Uri uri = (Uri) parcelable;
if (uri != null) {
if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
String pathString = Utilities.readlink(uri.getPath());
if (pathString != null && pathString.contains("/data/data/" + getPackageName() + "/files")) {
uris.remove(a);
a--;
}
}
}
}
if (uris.isEmpty()) {
uris = null;
}
}
if (uris != null) { if (uris != null) {
if (type != null && type.startsWith("image/")) { if (type != null && type.startsWith("image/")) {
for (Parcelable parcelable : uris) { for (int a = 0; a < uris.size(); a++) {
Parcelable parcelable = uris.get(a);
if (!(parcelable instanceof Uri)) { if (!(parcelable instanceof Uri)) {
parcelable = Uri.parse(parcelable.toString()); parcelable = Uri.parse(parcelable.toString());
} }
@ -692,7 +720,8 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
photoPathsArray.add(uri); photoPathsArray.add(uri);
} }
} else { } else {
for (Parcelable parcelable : uris) { for (int a = 0; a < uris.size(); a++) {
Parcelable parcelable = uris.get(a);
if (!(parcelable instanceof Uri)) { if (!(parcelable instanceof Uri)) {
parcelable = Uri.parse(parcelable.toString()); parcelable = Uri.parse(parcelable.toString());
} }
@ -733,6 +762,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
String botUser = null; String botUser = null;
String botChat = null; String botChat = null;
String message = null; String message = null;
Integer messageId = null;
boolean hasUrl = false; boolean hasUrl = false;
String scheme = data.getScheme(); String scheme = data.getScheme();
if (scheme != null) { if (scheme != null) {
@ -758,8 +788,17 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
} }
message += data.getQueryParameter("text"); message += data.getQueryParameter("text");
} }
} else if (path.length() >= 3) { } else if (path.length() >= 1) {
username = data.getLastPathSegment(); List<String> segments = data.getPathSegments();
if (segments.size() > 0) {
username = segments.get(0);
if (segments.size() > 1) {
messageId = Utilities.parseInt(segments.get(1));
if (messageId == 0) {
messageId = null;
}
}
}
botUser = data.getQueryParameter("start"); botUser = data.getQueryParameter("start");
botChat = data.getQueryParameter("startgroup"); botChat = data.getQueryParameter("startgroup");
} }
@ -799,7 +838,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
} }
} }
if (username != null || group != null || sticker != null || message != null) { if (username != null || group != null || sticker != null || message != null) {
runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl, 0); runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl, messageId, 0);
} else { } else {
try { try {
Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null); Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
@ -986,7 +1025,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
return false; return false;
} }
private void runLinkRequest(final String username, final String group, final String sticker, final String botUser, final String botChat, final String message, final boolean hasUrl, final int state) { private void runLinkRequest(final String username, final String group, final String sticker, final String botUser, final String botChat, final String message, final boolean hasUrl, final Integer messageId, final int state) {
final ProgressDialog progressDialog = new ProgressDialog(this); final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading)); progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCanceledOnTouchOutside(false);
@ -1051,6 +1090,9 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
if (botUser != null && res.users.size() > 0 && res.users.get(0).bot) { if (botUser != null && res.users.size() > 0 && res.users.get(0).bot) {
args.putString("botUser", botUser); args.putString("botUser", botUser);
} }
if (messageId != null) {
args.putInt("message_id", messageId);
}
ChatActivity fragment = new ChatActivity(args); ChatActivity fragment = new ChatActivity(args);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats); NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
actionBarLayout.presentFragment(fragment, false, true, true); actionBarLayout.presentFragment(fragment, false, true, true);
@ -1106,7 +1148,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialogInterface, int i) { public void onClick(DialogInterface dialogInterface, int i) {
runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl, 1); runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl, messageId, 1);
} }
}); });
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
@ -1494,7 +1536,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
if (requestCode == 3 || requestCode == 4 || requestCode == 5) { if (requestCode == 3 || requestCode == 4 || requestCode == 5) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == 4) { if (requestCode == 4) {
ImageLoader.getInstance().createMediaPaths(); ImageLoader.getInstance().checkMediaPaths();
} else if (requestCode == 5) { } else if (requestCode == 5) {
ContactsController.getInstance().readContacts(); ContactsController.getInstance().readContacts();
} }
@ -1678,13 +1720,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
builder.setNegativeButton(LocaleController.getString("MoreInfo", R.string.MoreInfo), new DialogInterface.OnClickListener() { builder.setNegativeButton(LocaleController.getString("MoreInfo", R.string.MoreInfo), new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialogInterface, int i) { public void onClick(DialogInterface dialogInterface, int i) {
try { AndroidUtilities.openUrl(LaunchActivity.this, LocaleController.getString("NobodyLikesSpamUrl", R.string.NobodyLikesSpamUrl));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(LocaleController.getString("NobodyLikesSpamUrl", R.string.NobodyLikesSpamUrl)));
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
startActivity(intent);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} }
}); });
} }
@ -1882,7 +1918,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
@Override @Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) { public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) { if (keyCode == KeyEvent.KEYCODE_MENU && !UserConfig.isWaitingForPasscodeEnter) {
if (AndroidUtilities.isTablet()) { if (AndroidUtilities.isTablet()) {
if (layersActionBarLayout.getVisibility() == View.VISIBLE && !layersActionBarLayout.fragmentsStack.isEmpty()) { if (layersActionBarLayout.getVisibility() == View.VISIBLE && !layersActionBarLayout.fragmentsStack.isEmpty()) {
layersActionBarLayout.onKeyUp(keyCode, event); layersActionBarLayout.onKeyUp(keyCode, event);

View File

@ -817,10 +817,10 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
if (messageObject != null && avatarImageView != null) { if (messageObject != null && avatarImageView != null) {
int fromId = messageObject.messageOwner.from_id; int fromId = messageObject.messageOwner.from_id;
if (messageObject.isForwarded()) { if (messageObject.isForwarded()) {
if (messageObject.messageOwner.fwd_from_id.user_id != 0) { if (messageObject.messageOwner.fwd_from.channel_id != 0) {
fromId = messageObject.messageOwner.fwd_from_id.user_id; fromId = -messageObject.messageOwner.fwd_from.channel_id;
} else { } else {
fromId = -messageObject.messageOwner.fwd_from_id.channel_id; fromId = messageObject.messageOwner.fwd_from.from_id;
} }
} }
String name = ""; String name = "";

View File

@ -400,7 +400,7 @@ public class LoginActivity extends BaseFragment {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged); NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
} }
public class PhoneView extends SlideView implements AdapterView.OnItemSelectedListener { public class PhoneView extends SlideView implements AdapterView.OnItemSelectedListener, NotificationCenter.NotificationCenterDelegate {
private EditText codeField; private EditText codeField;
private HintEditText phoneField; private HintEditText phoneField;
@ -752,6 +752,17 @@ public class LoginActivity extends BaseFragment {
} }
} }
@Override
public void didReceivedNotification(int id, final Object... args) {
/*if (id == NotificationCenter.didReceiveCall) {
if (codeField != null) {
String phone = (String) args[0];
phone = PhoneFormat.stripExceptNumbers(phone);
codeField.setText(phone);
}
}*/
}
@Override @Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (ignoreSelection) { if (ignoreSelection) {
@ -785,6 +796,7 @@ public class LoginActivity extends BaseFragment {
needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber)); needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber));
return; return;
} }
//NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveCall);
ConnectionsManager.getInstance().cleanUp(); ConnectionsManager.getInstance().cleanUp();
TLRPC.TL_auth_sendCode req = new TLRPC.TL_auth_sendCode(); TLRPC.TL_auth_sendCode req = new TLRPC.TL_auth_sendCode();
@ -857,6 +869,7 @@ public class LoginActivity extends BaseFragment {
codeField.requestFocus(); codeField.requestFocus();
} }
} }
//NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReceiveCall);
} }
@Override @Override
@ -1071,9 +1084,14 @@ public class LoginActivity extends BaseFragment {
destroyTimer(); destroyTimer();
destroyCodeTimer(); destroyCodeTimer();
timeText.setText(LocaleController.formatString("CallText", R.string.CallText, 1, 0)); if (time >= 3600 * 1000) {
lastCurrentTime = System.currentTimeMillis(); timeText.setVisibility(GONE);
problemText.setVisibility(time < 1000 ? VISIBLE : GONE); problemText.setVisibility(GONE);
} else {
timeText.setText(LocaleController.formatString("CallText", R.string.CallText, 1, 0));
lastCurrentTime = System.currentTimeMillis();
problemText.setVisibility(time < 1000 ? VISIBLE : GONE);
}
createTimer(); createTimer();
} }
@ -1119,7 +1137,7 @@ public class LoginActivity extends BaseFragment {
} }
private void createTimer() { private void createTimer() {
if (timeTimer != null) { if (timeTimer != null || time >= 3600 * 1000) {
return; return;
} }
timeTimer = new Timer(); timeTimer = new Timer();

View File

@ -18,7 +18,6 @@ import android.graphics.Bitmap;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.provider.Browser;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.Gravity; import android.view.Gravity;
@ -446,6 +445,11 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
if ((int) dialog_id != 0) { if ((int) dialog_id != 0) {
dropDownContainer.addSubItem(links_item, LocaleController.getString("LinksTitle", R.string.LinksTitle), 0); dropDownContainer.addSubItem(links_item, LocaleController.getString("LinksTitle", R.string.LinksTitle), 0);
dropDownContainer.addSubItem(music_item, LocaleController.getString("AudioTitle", R.string.AudioTitle), 0); dropDownContainer.addSubItem(music_item, LocaleController.getString("AudioTitle", R.string.AudioTitle), 0);
} else {
TLRPC.EncryptedChat currentEncryptedChat = MessagesController.getInstance().getEncryptedChat((int) (dialog_id >> 32));
if (currentEncryptedChat != null && AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46) {
dropDownContainer.addSubItem(music_item, LocaleController.getString("AudioTitle", R.string.AudioTitle), 0);
}
} }
actionBar.addView(dropDownContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 64 : 56, 0, 40, 0)); actionBar.addView(dropDownContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 64 : 56, 0, 40, 0));
dropDownContainer.setOnClickListener(new View.OnClickListener() { dropDownContainer.setOnClickListener(new View.OnClickListener() {
@ -1115,10 +1119,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
link = ((SharedLinkCell) view).getLink(0); link = ((SharedLinkCell) view).getLink(0);
} }
if (link != null) { if (link != null) {
Uri uri = Uri.parse(link); AndroidUtilities.openUrl(getParentActivity(), link);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getParentActivity().getPackageName());
getParentActivity().startActivity(intent);
} }
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
@ -1541,7 +1542,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
} else if (currentType == 3) { } else if (currentType == 3) {
req.filter = new TLRPC.TL_inputMessagesFilterUrl(); req.filter = new TLRPC.TL_inputMessagesFilterUrl();
} else if (currentType == 4) { } else if (currentType == 4) {
req.filter = new TLRPC.TL_inputMessagesFilterAudioDocuments(); req.filter = new TLRPC.TL_inputMessagesFilterMusic();
} }
req.q = query; req.q = query;
req.peer = MessagesController.getInputPeer(uid); req.peer = MessagesController.getInputPeer(uid);

View File

@ -28,7 +28,7 @@ import android.graphics.drawable.Drawable;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.provider.Browser; import android.text.SpannableStringBuilder;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.GestureDetector; import android.view.GestureDetector;
@ -48,6 +48,7 @@ import android.widget.Scroller;
import android.widget.TextView; import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.ImageLoader; import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.MessagesStorage; import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.UserObject; import org.telegram.messenger.UserObject;
@ -180,19 +181,20 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
private boolean draggingDown = false; private boolean draggingDown = false;
private float dragY; private float dragY;
private float translationX = 0; private float translationX;
private float translationY = 0; private float translationY;
private float scale = 1; private float scale = 1;
private float animateToX; private float animateToX;
private float animateToY; private float animateToY;
private float animateToScale; private float animateToScale;
private float animationValue; private float animationValue;
private int currentRotation;
private long animationStartTime; private long animationStartTime;
private AnimatorSetProxy imageMoveAnimation; private AnimatorSetProxy imageMoveAnimation;
private AnimatorSetProxy changeModeAnimation; private AnimatorSetProxy changeModeAnimation;
private GestureDetector gestureDetector; private GestureDetector gestureDetector;
private DecelerateInterpolator interpolator = new DecelerateInterpolator(1.5f); private DecelerateInterpolator interpolator = new DecelerateInterpolator(1.5f);
private float pinchStartDistance = 0; private float pinchStartDistance;
private float pinchStartScale = 1; private float pinchStartScale = 1;
private float pinchCenterX; private float pinchCenterX;
private float pinchCenterY; private float pinchCenterY;
@ -960,7 +962,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
if (f != null && f.exists()) { if (f != null && f.exists()) {
MediaController.saveFile(f.toString(), parentActivity, currentFileNames[0].endsWith("mp4") ? 1 : 0, null); MediaController.saveFile(f.toString(), parentActivity, currentMessageObject != null && currentMessageObject.isVideo() ? 1 : 0, null);
} else { } else {
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -1020,7 +1022,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
return; return;
} }
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity); AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
if (currentFileNames[0] != null && currentFileNames[0].endsWith("mp4")) { if (currentMessageObject != null && currentMessageObject.isVideo()) {
builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideo", R.string.AreYouSureDeleteVideo)); builder.setMessage(LocaleController.formatString("AreYouSureDeleteVideo", R.string.AreYouSureDeleteVideo));
} else { } else {
builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto", R.string.AreYouSureDeletePhoto)); builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto", R.string.AreYouSureDeletePhoto));
@ -1200,13 +1202,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
try { try {
File f = null; File f = null;
boolean isVideo = false;
if (currentMessageObject != null) { if (currentMessageObject != null) {
isVideo = currentMessageObject.isVideo();
if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) { if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
Uri uri = Uri.parse(currentMessageObject.messageOwner.media.webpage.url); AndroidUtilities.openUrl(parentActivity, currentMessageObject.messageOwner.media.webpage.url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, parentActivity.getPackageName());
parentActivity.startActivity(intent);
return; return;
} }
f = FileLoader.getPathToMessage(currentMessageObject.messageOwner); f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
@ -1216,7 +1217,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (f.exists()) { if (f.exists()) {
Intent intent = new Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
if (f.toString().endsWith("mp4")) { if (isVideo) {
intent.setType("video/mp4"); intent.setType("video/mp4");
} else { } else {
intent.setType("image/jpeg"); intent.setType("image/jpeg");
@ -1306,6 +1307,20 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
}); });
ImageView rotateButton = new ImageView(parentActivity);
rotateButton.setScaleType(ImageView.ScaleType.CENTER);
rotateButton.setImageResource(R.drawable.tool_rotate);
rotateButton.setBackgroundResource(R.drawable.bar_selector_white);
editorDoneLayout.addView(rotateButton, LayoutHelper.createFrame(48, 48, Gravity.CENTER));
rotateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
centerImage.setOrientation(centerImage.getOrientation() - 90, false);
photoCropView.setOrientation(centerImage.getOrientation());
containerView.invalidate();
}
});
gestureDetector = new GestureDetector(containerView.getContext(), this); gestureDetector = new GestureDetector(containerView.getContext(), this);
gestureDetector.setOnDoubleTapListener(this); gestureDetector.setOnDoubleTapListener(this);
@ -2074,23 +2089,17 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
return null; return null;
} }
if (!imagesArrLocations.isEmpty() || !imagesArr.isEmpty()) { if (!imagesArrLocations.isEmpty() || !imagesArr.isEmpty()) {
TLRPC.InputFileLocation file = getInputFileLocation(index);
if (file == null) {
return null;
}
if (!imagesArrLocations.isEmpty()) { if (!imagesArrLocations.isEmpty()) {
return file.volume_id + "_" + file.local_id + ".jpg"; if (index >= imagesArrLocations.size()) {
} else if (!imagesArr.isEmpty()) { return null;
MessageObject message = imagesArr.get(index);
if (message.messageOwner instanceof TLRPC.TL_messageService) {
return file.volume_id + "_" + file.local_id + ".jpg";
} else if (message.messageOwner.media != null) {
if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
return file.volume_id + "_" + file.id + ".mp4";
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || message.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
return file.volume_id + "_" + file.local_id + ".jpg";
}
} }
TLRPC.FileLocation location = imagesArrLocations.get(index);
return location.volume_id + "_" + location.local_id + ".jpg";
} else if (!imagesArr.isEmpty()) {
if (index >= imagesArr.size()) {
return null;
}
return FileLoader.getMessageFileName(imagesArr.get(index).messageOwner);
} }
} else if (!imagesArrLocals.isEmpty()) { } else if (!imagesArrLocals.isEmpty()) {
if (index >= imagesArrLocals.size()) { if (index >= imagesArrLocals.size()) {
@ -2109,7 +2118,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
searchImage.localUrl = ""; searchImage.localUrl = "";
} }
} }
return Utilities.MD5(searchImage.imageUrl) + "." + ImageLoader.getHttpUrlExtension(searchImage.imageUrl); return Utilities.MD5(searchImage.imageUrl) + "." + ImageLoader.getHttpUrlExtension(searchImage.imageUrl, "jpg");
} }
} }
return null; return null;
@ -2156,72 +2165,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} else { } else {
size[0] = -1; size[0] = -1;
} }
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo && message.messageOwner.media.video != null && message.messageOwner.media.video.thumb != null) { } else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaDocument && message.messageOwner.media.document != null && message.messageOwner.media.document.thumb != null) {
size[0] = message.messageOwner.media.video.thumb.size; size[0] = message.messageOwner.media.document.thumb.size;
if (size[0] == 0) { if (size[0] == 0) {
size[0] = -1; size[0] = -1;
} }
return message.messageOwner.media.video.thumb.location; return message.messageOwner.media.document.thumb.location;
}
}
return null;
}
private TLRPC.InputFileLocation getInputFileLocation(int index) {
if (index < 0) {
return null;
}
if (!imagesArrLocations.isEmpty()) {
if (index >= imagesArrLocations.size()) {
return null;
}
TLRPC.FileLocation sizeFull = imagesArrLocations.get(index);
TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation();
location.local_id = sizeFull.local_id;
location.volume_id = sizeFull.volume_id;
location.id = sizeFull.dc_id;
location.secret = sizeFull.secret;
return location;
} else if (!imagesArr.isEmpty()) {
if (index >= imagesArr.size()) {
return null;
}
MessageObject message = imagesArr.get(index);
if (message.messageOwner instanceof TLRPC.TL_messageService) {
if (message.messageOwner.action instanceof TLRPC.TL_messageActionUserUpdatedPhoto) {
TLRPC.FileLocation sizeFull = message.messageOwner.action.newUserPhoto.photo_big;
TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation();
location.local_id = sizeFull.local_id;
location.volume_id = sizeFull.volume_id;
location.id = sizeFull.dc_id;
location.secret = sizeFull.secret;
return location;
} else {
TLRPC.PhotoSize sizeFull = FileLoader.getClosestPhotoSizeWithSize(message.photoThumbs, AndroidUtilities.getPhotoSize());
if (sizeFull != null) {
TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation();
location.local_id = sizeFull.location.local_id;
location.volume_id = sizeFull.location.volume_id;
location.id = sizeFull.location.dc_id;
location.secret = sizeFull.location.secret;
return location;
}
}
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto || message.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
TLRPC.PhotoSize sizeFull = FileLoader.getClosestPhotoSizeWithSize(message.photoThumbs, AndroidUtilities.getPhotoSize());
if (sizeFull != null) {
TLRPC.TL_inputFileLocation location = new TLRPC.TL_inputFileLocation();
location.local_id = sizeFull.location.local_id;
location.volume_id = sizeFull.location.volume_id;
location.id = sizeFull.location.dc_id;
location.secret = sizeFull.location.secret;
return location;
}
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
TLRPC.TL_inputVideoFileLocation location = new TLRPC.TL_inputVideoFileLocation();
location.volume_id = message.messageOwner.media.video.dc_id;
location.id = message.messageOwner.media.video.id;
return location;
} }
} }
return null; return null;
@ -2353,7 +2302,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
canShowBottom = false; canShowBottom = false;
Object obj = imagesArrLocals.get(index); Object obj = imagesArrLocals.get(index);
cropItem.setVisibility(obj instanceof MediaController.PhotoEntry || obj instanceof MediaController.SearchImage && ((MediaController.SearchImage) obj).type == 0 ? View.VISIBLE : View.GONE); cropItem.setVisibility(obj instanceof MediaController.PhotoEntry || obj instanceof MediaController.SearchImage && ((MediaController.SearchImage) obj).type == 0 ? View.VISIBLE : View.GONE);
if (parentChatActivity != null && parentChatActivity.currentEncryptedChat == null) { if (parentChatActivity != null && (parentChatActivity.currentEncryptedChat == null || AndroidUtilities.getPeerLayerVersion(parentChatActivity.currentEncryptedChat.layer) >= 46)) {
mentionsAdapter.setChatInfo(parentChatActivity.info); mentionsAdapter.setChatInfo(parentChatActivity.info);
mentionsAdapter.setNeedUsernames(parentChatActivity.currentChat != null); mentionsAdapter.setNeedUsernames(parentChatActivity.currentChat != null);
mentionsAdapter.setNeedBotContext(false); mentionsAdapter.setNeedBotContext(false);
@ -2401,7 +2350,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
placeProvider.willSwitchFromPhoto(currentMessageObject, currentFileLocation, currentIndex); placeProvider.willSwitchFromPhoto(currentMessageObject, currentFileLocation, currentIndex);
int prevIndex = currentIndex; int prevIndex = currentIndex;
currentIndex = index; currentIndex = index;
boolean isVideo = false;
boolean sameImage = false; boolean sameImage = false;
if (!imagesArr.isEmpty()) { if (!imagesArr.isEmpty()) {
@ -2410,12 +2359,13 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
return; return;
} }
currentMessageObject = imagesArr.get(currentIndex); currentMessageObject = imagesArr.get(currentIndex);
isVideo = currentMessageObject.isVideo();
if (currentMessageObject.canDeleteMessage(null)) { if (currentMessageObject.canDeleteMessage(null)) {
menuItem.showSubItem(gallery_menu_delete); menuItem.showSubItem(gallery_menu_delete);
} else { } else {
menuItem.hideSubItem(gallery_menu_delete); menuItem.hideSubItem(gallery_menu_delete);
} }
if (currentMessageObject.messageOwner.from_id > 0) { if (currentMessageObject.isFromUser()) {
TLRPC.User user = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id); TLRPC.User user = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id);
if (user != null) { if (user != null) {
nameTextView.setText(UserObject.getUserName(user)); nameTextView.setText(UserObject.getUserName(user));
@ -2423,7 +2373,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
nameTextView.setText(""); nameTextView.setText("");
} }
} else { } else {
TLRPC.Chat chat = MessagesController.getInstance().getChat(-currentMessageObject.messageOwner.from_id); TLRPC.Chat chat = MessagesController.getInstance().getChat(currentMessageObject.messageOwner.to_id.channel_id);
if (chat != null) { if (chat != null) {
nameTextView.setText(chat.title); nameTextView.setText(chat.title);
} else { } else {
@ -2432,8 +2382,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
long date = (long) currentMessageObject.messageOwner.date * 1000; long date = (long) currentMessageObject.messageOwner.date * 1000;
String dateString = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(new Date(date)), LocaleController.getInstance().formatterDay.format(new Date(date))); String dateString = LocaleController.formatString("formatDateAtTime", R.string.formatDateAtTime, LocaleController.getInstance().formatterYear.format(new Date(date)), LocaleController.getInstance().formatterDay.format(new Date(date)));
if (currentFileNames[0] != null && currentFileNames[0].endsWith("mp4")) { if (currentFileNames[0] != null && isVideo) {
dateTextView.setText(String.format("%s (%s)", dateString, AndroidUtilities.formatFileSize(currentMessageObject.messageOwner.media.video.size))); dateTextView.setText(String.format("%s (%s)", dateString, AndroidUtilities.formatFileSize(currentMessageObject.messageOwner.media.document.size)));
} else { } else {
dateTextView.setText(dateString); dateTextView.setText(dateString);
} }
@ -2580,7 +2530,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
canDragDown = true; canDragDown = true;
changingPage = false; changingPage = false;
switchImageAfterAnimation = 0; switchImageAfterAnimation = 0;
canZoom = !imagesArrLocals.isEmpty() || (currentFileNames[0] != null && !currentFileNames[0].endsWith("mp4") && radialProgressViews[0].backgroundState != 0); canZoom = !imagesArrLocals.isEmpty() || (currentFileNames[0] != null && !isVideo && radialProgressViews[0].backgroundState != 0);
updateMinMax(scale); updateMinMax(scale);
} }
@ -2629,8 +2579,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
captionTextViewNew = captionTextView; captionTextViewNew = captionTextView;
captionItem.setIcon(R.drawable.photo_text2); captionItem.setIcon(R.drawable.photo_text2);
captionTextView.setTag(caption); CharSequence str = Emoji.replaceEmoji(new SpannableStringBuilder(caption.toString()), MessageObject.textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
captionTextView.setText(caption); captionTextView.setTag(str);
captionTextView.setText(str);
ViewProxy.setAlpha(captionTextView, bottomLayout.getVisibility() == View.VISIBLE || pickerView.getVisibility() == View.VISIBLE ? 1.0f : 0.0f); ViewProxy.setAlpha(captionTextView, bottomLayout.getVisibility() == View.VISIBLE || pickerView.getVisibility() == View.VISIBLE ? 1.0f : 0.0f);
AndroidUtilities.runOnUIThread(new Runnable() { AndroidUtilities.runOnUIThread(new Runnable() {
@Override @Override
@ -2658,9 +2609,11 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
index -= 1; index -= 1;
} }
File f = null; File f = null;
boolean isVideo = false;
if (currentMessageObject != null) { if (currentMessageObject != null) {
MessageObject messageObject = imagesArr.get(index); MessageObject messageObject = imagesArr.get(index);
f = FileLoader.getPathToMessage(messageObject.messageOwner); f = FileLoader.getPathToMessage(messageObject.messageOwner);
isVideo = messageObject.isVideo();
} else if (currentFileLocation != null) { } else if (currentFileLocation != null) {
TLRPC.FileLocation location = imagesArrLocations.get(index); TLRPC.FileLocation location = imagesArrLocations.get(index);
f = FileLoader.getPathToAttach(location, avatarsUserId != 0); f = FileLoader.getPathToAttach(location, avatarsUserId != 0);
@ -2671,13 +2624,13 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
} }
if (f != null && f.exists()) { if (f != null && f.exists()) {
if (currentPathObject == null && currentFileNames[a].endsWith("mp4")) { if (isVideo) {
radialProgressViews[a].setBackgroundState(3, animated); radialProgressViews[a].setBackgroundState(3, animated);
} else { } else {
radialProgressViews[a].setBackgroundState(-1, animated); radialProgressViews[a].setBackgroundState(-1, animated);
} }
} else { } else {
if (currentPathObject == null && currentFileNames[a].endsWith("mp4")) { if (isVideo) {
if (!FileLoader.getInstance().isLoadingFile(currentFileNames[a])) { if (!FileLoader.getInstance().isLoadingFile(currentFileNames[a])) {
radialProgressViews[a].setBackgroundState(2, false); radialProgressViews[a].setBackgroundState(2, false);
} else { } else {
@ -2693,7 +2646,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
radialProgressViews[a].setProgress(progress, false); radialProgressViews[a].setProgress(progress, false);
} }
if (a == 0) { if (a == 0) {
canZoom = !imagesArrLocals.isEmpty() || (currentFileNames[0] != null && !currentFileNames[0].endsWith("mp4") && radialProgressViews[0].backgroundState != 0); canZoom = !imagesArrLocals.isEmpty() || (currentFileNames[0] != null && !isVideo && radialProgressViews[0].backgroundState != 0);
} }
} else { } else {
radialProgressViews[a].setBackgroundState(-1, animated); radialProgressViews[a].setBackgroundState(-1, animated);
@ -2762,9 +2715,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
imageReceiver.setShouldGenerateQualityThumb(true); imageReceiver.setShouldGenerateQualityThumb(true);
} }
if (messageObject != null && messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) { if (messageObject != null && messageObject.isVideo()) {
imageReceiver.setNeedsQualityThumb(true); imageReceiver.setNeedsQualityThumb(true);
if (messageObject.messageOwner.media.video.thumb != null) { if (messageObject.photoThumbs != null && !messageObject.photoThumbs.isEmpty()) {
Bitmap placeHolder = null; Bitmap placeHolder = null;
if (currentThumb != null && imageReceiver == centerImage) { if (currentThumb != null && imageReceiver == centerImage) {
placeHolder = currentThumb; placeHolder = currentThumb;
@ -3963,9 +3916,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} }
if (loadFile) { if (loadFile) {
if (!FileLoader.getInstance().isLoadingFile(currentFileNames[0])) { if (!FileLoader.getInstance().isLoadingFile(currentFileNames[0])) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.video, true); FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
} else { } else {
FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.video); FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.document);
} }
} }
} }

View File

@ -308,6 +308,11 @@ public class PopupNotificationActivity extends Activity implements NotificationC
} }
@Override
public void onMessageEditEnd() {
}
@Override @Override
public void needSendTyping() { public void needSendTyping() {
if (currentMessageObject != null) { if (currentMessageObject != null) {

View File

@ -43,14 +43,14 @@ import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.BaseFragment; import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Adapters.BaseFragmentAdapter; import org.telegram.ui.Adapters.BaseFragmentAdapter;
import org.telegram.ui.Cells.HeaderCell; import org.telegram.ui.Cells.HeaderCell;
import org.telegram.ui.Cells.LastSeenRadioCell; import org.telegram.ui.Cells.RadioCell;
import org.telegram.ui.Cells.TextInfoPrivacyCell; import org.telegram.ui.Cells.TextInfoPrivacyCell;
import org.telegram.ui.Cells.TextSettingsCell; import org.telegram.ui.Cells.TextSettingsCell;
import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.LayoutHelper;
import java.util.ArrayList; import java.util.ArrayList;
public class LastSeenActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { public class PrivacyControlActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate {
private ListAdapter listAdapter; private ListAdapter listAdapter;
private View doneButton; private View doneButton;
@ -60,11 +60,15 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
private ArrayList<Integer> currentMinus; private ArrayList<Integer> currentMinus;
private int lastCheckedType = -1; private int lastCheckedType = -1;
private int lastSeenSectionRow; private boolean isGroup;
private boolean enableAnimation;
private int sectionRow;
private int everybodyRow; private int everybodyRow;
private int myContactsRow; private int myContactsRow;
private int nobodyRow; private int nobodyRow;
private int lastSeenDetailRow; private int detailRow;
private int shareSectionRow; private int shareSectionRow;
private int alwaysShareRow; private int alwaysShareRow;
private int neverShareRow; private int neverShareRow;
@ -85,6 +89,11 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
} }
} }
public PrivacyControlActivity(boolean group) {
super();
isGroup = group;
}
@Override @Override
public boolean onFragmentCreate() { public boolean onFragmentCreate() {
super.onFragmentCreate(); super.onFragmentCreate();
@ -104,7 +113,11 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
public View createView(Context context) { public View createView(Context context) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true); actionBar.setAllowOverlayTitle(true);
actionBar.setTitle(LocaleController.getString("PrivacyLastSeen", R.string.PrivacyLastSeen)); if (isGroup) {
actionBar.setTitle(LocaleController.getString("GroupsAndChannels", R.string.GroupsAndChannels));
} else {
actionBar.setTitle(LocaleController.getString("PrivacyLastSeen", R.string.PrivacyLastSeen));
}
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override @Override
public void onItemClick(int id) { public void onItemClick(int id) {
@ -115,12 +128,16 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
return; return;
} }
if (currentType != 0) { if (currentType != 0 && !isGroup) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean showed = preferences.getBoolean("privacyAlertShowed", false); boolean showed = preferences.getBoolean("privacyAlertShowed", false);
if (!showed) { if (!showed) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("CustomHelp", R.string.CustomHelp)); if (isGroup) {
builder.setMessage(LocaleController.getString("WhoCanAddMeInfo", R.string.WhoCanAddMeInfo));
} else {
builder.setMessage(LocaleController.getString("CustomHelp", R.string.CustomHelp));
}
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() { builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override @Override
@ -176,6 +193,7 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
if (newType == currentType) { if (newType == currentType) {
return; return;
} }
enableAnimation = true;
doneButton.setVisibility(View.VISIBLE); doneButton.setVisibility(View.VISIBLE);
lastCheckedType = currentType; lastCheckedType = currentType;
currentType = newType; currentType = newType;
@ -190,19 +208,20 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
if (createFromArray.isEmpty()) { if (createFromArray.isEmpty()) {
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putBoolean(i == neverShareRow ? "isNeverShare" : "isAlwaysShare", true); args.putBoolean(i == neverShareRow ? "isNeverShare" : "isAlwaysShare", true);
args.putBoolean("isGroup", isGroup);
GroupCreateActivity fragment = new GroupCreateActivity(args); GroupCreateActivity fragment = new GroupCreateActivity(args);
fragment.setDelegate(new GroupCreateActivity.GroupCreateActivityDelegate() { fragment.setDelegate(new GroupCreateActivity.GroupCreateActivityDelegate() {
@Override @Override
public void didSelectUsers(ArrayList<Integer> ids) { public void didSelectUsers(ArrayList<Integer> ids) {
if (i == neverShareRow) { if (i == neverShareRow) {
currentMinus = ids; currentMinus = ids;
for (Integer id : currentMinus) { for (int a = 0; a < currentMinus.size(); a++) {
currentPlus.remove(id); currentPlus.remove(currentMinus.get(a));
} }
} else { } else {
currentPlus = ids; currentPlus = ids;
for (Integer id : currentPlus) { for (int a = 0; a < currentPlus.size(); a++) {
currentMinus.remove(id); currentMinus.remove(currentPlus.get(a));
} }
} }
doneButton.setVisibility(View.VISIBLE); doneButton.setVisibility(View.VISIBLE);
@ -212,22 +231,22 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
}); });
presentFragment(fragment); presentFragment(fragment);
} else { } else {
LastSeenUsersActivity fragment = new LastSeenUsersActivity(createFromArray, i == alwaysShareRow); PrivacyUsersActivity fragment = new PrivacyUsersActivity(createFromArray, isGroup, i == alwaysShareRow);
fragment.setDelegate(new LastSeenUsersActivity.LastSeenUsersActivityDelegate() { fragment.setDelegate(new PrivacyUsersActivity.PrivacyActivityDelegate() {
@Override @Override
public void didUpdatedUserList(ArrayList<Integer> ids, boolean added) { public void didUpdatedUserList(ArrayList<Integer> ids, boolean added) {
if (i == neverShareRow) { if (i == neverShareRow) {
currentMinus = ids; currentMinus = ids;
if (added) { if (added) {
for (Integer id : currentMinus) { for (int a = 0; a < currentMinus.size(); a++) {
currentPlus.remove(id); currentPlus.remove(currentMinus.get(a));
} }
} }
} else { } else {
currentPlus = ids; currentPlus = ids;
if (added) { if (added) {
for (Integer id : currentPlus) { for (int a = 0; a < currentPlus.size(); a++) {
currentMinus.remove(id); currentMinus.remove(currentPlus.get(a));
} }
} }
} }
@ -253,11 +272,15 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
private void applyCurrentPrivacySettings() { private void applyCurrentPrivacySettings() {
TLRPC.TL_account_setPrivacy req = new TLRPC.TL_account_setPrivacy(); TLRPC.TL_account_setPrivacy req = new TLRPC.TL_account_setPrivacy();
req.key = new TLRPC.TL_inputPrivacyKeyStatusTimestamp(); if (isGroup) {
req.key = new TLRPC.TL_inputPrivacyKeyChatInvite();
} else {
req.key = new TLRPC.TL_inputPrivacyKeyStatusTimestamp();
}
if (currentType != 0 && currentPlus.size() > 0) { if (currentType != 0 && currentPlus.size() > 0) {
TLRPC.TL_inputPrivacyValueAllowUsers rule = new TLRPC.TL_inputPrivacyValueAllowUsers(); TLRPC.TL_inputPrivacyValueAllowUsers rule = new TLRPC.TL_inputPrivacyValueAllowUsers();
for (Integer uid : currentPlus) { for (int a = 0; a < currentPlus.size(); a++) {
TLRPC.User user = MessagesController.getInstance().getUser(uid); TLRPC.User user = MessagesController.getInstance().getUser(currentPlus.get(a));
if (user != null) { if (user != null) {
TLRPC.InputUser inputUser = MessagesController.getInputUser(user); TLRPC.InputUser inputUser = MessagesController.getInputUser(user);
if (inputUser != null) { if (inputUser != null) {
@ -269,8 +292,8 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
} }
if (currentType != 1 && currentMinus.size() > 0) { if (currentType != 1 && currentMinus.size() > 0) {
TLRPC.TL_inputPrivacyValueDisallowUsers rule = new TLRPC.TL_inputPrivacyValueDisallowUsers(); TLRPC.TL_inputPrivacyValueDisallowUsers rule = new TLRPC.TL_inputPrivacyValueDisallowUsers();
for (Integer uid : currentMinus) { for (int a = 0; a < currentMinus.size(); a++) {
TLRPC.User user = MessagesController.getInstance().getUser(uid); TLRPC.User user = MessagesController.getInstance().getUser(currentMinus.get(a));
if (user != null) { if (user != null) {
TLRPC.InputUser inputUser = MessagesController.getInputUser(user); TLRPC.InputUser inputUser = MessagesController.getInputUser(user);
if (inputUser != null) { if (inputUser != null) {
@ -313,7 +336,7 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
finishFragment(); finishFragment();
TLRPC.TL_account_privacyRules rules = (TLRPC.TL_account_privacyRules) response; TLRPC.TL_account_privacyRules rules = (TLRPC.TL_account_privacyRules) response;
MessagesController.getInstance().putUsers(rules.users, false); MessagesController.getInstance().putUsers(rules.users, false);
ContactsController.getInstance().setPrivacyRules(rules.rules); ContactsController.getInstance().setPrivacyRules(rules.rules, isGroup);
} else { } else {
showErrorAlert(); showErrorAlert();
} }
@ -337,13 +360,14 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
private void checkPrivacy() { private void checkPrivacy() {
currentPlus = new ArrayList<>(); currentPlus = new ArrayList<>();
currentMinus = new ArrayList<>(); currentMinus = new ArrayList<>();
ArrayList<TLRPC.PrivacyRule> privacyRules = ContactsController.getInstance().getPrivacyRules(); ArrayList<TLRPC.PrivacyRule> privacyRules = ContactsController.getInstance().getPrivacyRules(isGroup);
if (privacyRules.size() == 0) { if (privacyRules.size() == 0) {
currentType = 1; currentType = 1;
return; return;
} }
int type = -1; int type = -1;
for (TLRPC.PrivacyRule rule : privacyRules) { for (int a = 0; a < privacyRules.size(); a++) {
TLRPC.PrivacyRule rule = privacyRules.get(a);
if (rule instanceof TLRPC.TL_privacyValueAllowUsers) { if (rule instanceof TLRPC.TL_privacyValueAllowUsers) {
currentPlus.addAll(rule.users); currentPlus.addAll(rule.users);
} else if (rule instanceof TLRPC.TL_privacyValueDisallowUsers) { } else if (rule instanceof TLRPC.TL_privacyValueDisallowUsers) {
@ -371,11 +395,15 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
private void updateRows() { private void updateRows() {
rowCount = 0; rowCount = 0;
lastSeenSectionRow = rowCount++; sectionRow = rowCount++;
everybodyRow = rowCount++; everybodyRow = rowCount++;
myContactsRow = rowCount++; myContactsRow = rowCount++;
nobodyRow = rowCount++; if (isGroup) {
lastSeenDetailRow = rowCount++; nobodyRow = -1;
} else {
nobodyRow = rowCount++;
}
detailRow = rowCount++;
shareSectionRow = rowCount++; shareSectionRow = rowCount++;
if (currentType == 1 || currentType == 2) { if (currentType == 1 || currentType == 2) {
alwaysShareRow = rowCount++; alwaysShareRow = rowCount++;
@ -397,9 +425,7 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
lastCheckedType = -1; lastCheckedType = -1;
if (listAdapter != null) { enableAnimation = false;
listAdapter.notifyDataSetChanged();
}
} }
private class ListAdapter extends BaseFragmentAdapter { private class ListAdapter extends BaseFragmentAdapter {
@ -455,7 +481,11 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
} else { } else {
value = LocaleController.getString("EmpryUsersPlaceholder", R.string.EmpryUsersPlaceholder); value = LocaleController.getString("EmpryUsersPlaceholder", R.string.EmpryUsersPlaceholder);
} }
textCell.setTextAndValue(LocaleController.getString("AlwaysShareWith", R.string.AlwaysShareWith), value, neverShareRow != -1); if (isGroup) {
textCell.setTextAndValue(LocaleController.getString("AlwaysAllow", R.string.AlwaysAllow), value, neverShareRow != -1);
} else {
textCell.setTextAndValue(LocaleController.getString("AlwaysShareWith", R.string.AlwaysShareWith), value, neverShareRow != -1);
}
} else if (i == neverShareRow) { } else if (i == neverShareRow) {
String value; String value;
if (currentMinus.size() != 0) { if (currentMinus.size() != 0) {
@ -463,18 +493,30 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
} else { } else {
value = LocaleController.getString("EmpryUsersPlaceholder", R.string.EmpryUsersPlaceholder); value = LocaleController.getString("EmpryUsersPlaceholder", R.string.EmpryUsersPlaceholder);
} }
textCell.setTextAndValue(LocaleController.getString("NeverShareWith", R.string.NeverShareWith), value, false); if (isGroup) {
textCell.setTextAndValue(LocaleController.getString("NeverAllow", R.string.NeverAllow), value, false);
} else {
textCell.setTextAndValue(LocaleController.getString("NeverShareWith", R.string.NeverShareWith), value, false);
}
} }
} else if (type == 1) { } else if (type == 1) {
if (view == null) { if (view == null) {
view = new TextInfoPrivacyCell(mContext); view = new TextInfoPrivacyCell(mContext);
view.setBackgroundColor(0xffffffff); view.setBackgroundColor(0xffffffff);
} }
if (i == lastSeenDetailRow) { if (i == detailRow) {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("CustomHelp", R.string.CustomHelp)); if (isGroup) {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("WhoCanAddMeInfo", R.string.WhoCanAddMeInfo));
} else {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("CustomHelp", R.string.CustomHelp));
}
view.setBackgroundResource(R.drawable.greydivider); view.setBackgroundResource(R.drawable.greydivider);
} else if (i == shareDetailRow) { } else if (i == shareDetailRow) {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("CustomShareSettingsHelp", R.string.CustomShareSettingsHelp)); if (isGroup) {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("CustomShareInfo", R.string.CustomShareInfo));
} else {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("CustomShareSettingsHelp", R.string.CustomShareSettingsHelp));
}
view.setBackgroundResource(R.drawable.greydivider_bottom); view.setBackgroundResource(R.drawable.greydivider_bottom);
} }
} else if (type == 2) { } else if (type == 2) {
@ -482,32 +524,36 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
view = new HeaderCell(mContext); view = new HeaderCell(mContext);
view.setBackgroundColor(0xffffffff); view.setBackgroundColor(0xffffffff);
} }
if (i == lastSeenSectionRow) { if (i == sectionRow) {
((HeaderCell) view).setText(LocaleController.getString("LastSeenTitle", R.string.LastSeenTitle)); if (isGroup) {
((HeaderCell) view).setText(LocaleController.getString("WhoCanAddMe", R.string.WhoCanAddMe));
} else {
((HeaderCell) view).setText(LocaleController.getString("LastSeenTitle", R.string.LastSeenTitle));
}
} else if (i == shareSectionRow) { } else if (i == shareSectionRow) {
((HeaderCell) view).setText(LocaleController.getString("AddExceptions", R.string.AddExceptions)); ((HeaderCell) view).setText(LocaleController.getString("AddExceptions", R.string.AddExceptions));
} }
} else if (type == 3) { } else if (type == 3) {
if (view == null) { if (view == null) {
view = new LastSeenRadioCell(mContext); view = new RadioCell(mContext);
view.setBackgroundColor(0xffffffff); view.setBackgroundColor(0xffffffff);
} }
LastSeenRadioCell textCell = (LastSeenRadioCell) view; RadioCell textCell = (RadioCell) view;
int checkedType = 0; int checkedType = 0;
if (i == everybodyRow) { if (i == everybodyRow) {
textCell.setText(LocaleController.getString("LastSeenEverybody", R.string.LastSeenEverybody), lastCheckedType == 0, true); textCell.setText(LocaleController.getString("LastSeenEverybody", R.string.LastSeenEverybody), lastCheckedType == 0, true);
checkedType = 0; checkedType = 0;
} else if (i == myContactsRow) { } else if (i == myContactsRow) {
textCell.setText(LocaleController.getString("LastSeenContacts", R.string.LastSeenContacts), lastCheckedType == 2, true); textCell.setText(LocaleController.getString("LastSeenContacts", R.string.LastSeenContacts), lastCheckedType == 2, nobodyRow != -1);
checkedType = 2; checkedType = 2;
} else if (i == nobodyRow) { } else if (i == nobodyRow) {
textCell.setText(LocaleController.getString("LastSeenNobody", R.string.LastSeenNobody), lastCheckedType == 1, false); textCell.setText(LocaleController.getString("LastSeenNobody", R.string.LastSeenNobody), lastCheckedType == 1, false);
checkedType = 1; checkedType = 1;
} }
if (lastCheckedType == checkedType) { if (lastCheckedType == checkedType) {
textCell.setChecked(false, true); textCell.setChecked(false, enableAnimation);
} else if (currentType == checkedType) { } else if (currentType == checkedType) {
textCell.setChecked(true, true); textCell.setChecked(true, enableAnimation);
} }
} }
return view; return view;
@ -517,9 +563,9 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
public int getItemViewType(int i) { public int getItemViewType(int i) {
if (i == alwaysShareRow || i == neverShareRow) { if (i == alwaysShareRow || i == neverShareRow) {
return 0; return 0;
} else if (i == shareDetailRow || i == lastSeenDetailRow) { } else if (i == shareDetailRow || i == detailRow) {
return 1; return 1;
} else if (i == lastSeenSectionRow || i == shareSectionRow) { } else if (i == sectionRow || i == shareSectionRow) {
return 2; return 2;
} else if (i == everybodyRow || i == myContactsRow || i == nobodyRow) { } else if (i == everybodyRow || i == myContactsRow || i == nobodyRow) {
return 3; return 3;

Some files were not shown because too many files have changed in this diff Show More