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 {
minSdkVersion 9
targetSdkVersion 23
versionCode 719
versionName "3.4.2"
versionCode 755
versionName "3.6.1"
}
}

View file

@ -235,7 +235,7 @@ include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
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 += -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

View file

@ -5,6 +5,7 @@
#include <stdlib.h>
#include <time.h>
#include <opusfile.h>
#include <math.h>
#include "utils.h"
typedef struct {
@ -663,6 +664,156 @@ JNIEXPORT int Java_org_telegram_messenger_MediaController_isOpusFile(JNIEnv *env
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) {
(*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, 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.
*/
#include <openssl/rand.h>
#include <stdlib.h>
#include "Connection.h"
#include "ConnectionsManager.h"
#include "BuffersStorage.h"
@ -55,6 +57,8 @@ void Connection::suspendConnection() {
}
void Connection::onReceivedData(NativeByteBuffer *buffer) {
//AES_ctr128_encrypt(buffer->bytes(), buffer->bytes(), buffer->limit(), &decryptKey, decryptIv, decryptCount, &decryptNum);
failedConnectionCount = 0;
NativeByteBuffer *parseLaterBuffer = nullptr;
@ -305,12 +309,47 @@ void Connection::sendData(NativeByteBuffer *buff, bool reportAck) {
bufferLen += 4;
}
if (!firstPacketSent) {
bufferLen++;
bufferLen += 64;
}
NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(bufferLen);
uint8_t *bytes = buffer->bytes();
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;
}
if (packetLength < 0x7f) {
@ -318,17 +357,22 @@ void Connection::sendData(NativeByteBuffer *buff, bool reportAck) {
packetLength |= (1 << 7);
}
buffer->writeByte((uint8_t) packetLength);
bytes += (buffer->limit() - 1);
//AES_ctr128_encrypt(bytes, bytes, 1, &encryptKey, encryptIv, encryptCount, &encryptNum);
} else {
packetLength = (packetLength << 8) + 0x7f;
if (reportAck) {
packetLength |= (1 << 7);
}
buffer->writeInt32(packetLength);
bytes += (buffer->limit() - 4);
//AES_ctr128_encrypt(bytes, bytes, 4, &encryptKey, encryptIv, encryptCount, &encryptNum);
}
buffer->rewind();
writeBuffer(buffer);
buff->rewind();
//AES_ctr128_encrypt(buff->bytes(), buff->bytes(), buff->limit(), &encryptKey, encryptIv, encryptCount, &encryptNum);
writeBuffer(buff);
}

View file

@ -12,6 +12,7 @@
#include <pthread.h>
#include <vector>
#include <string>
#include <openssl/aes.h>
#include "ConnectionSession.h"
#include "ConnectionSocket.h"
#include "Defines.h"
@ -67,6 +68,16 @@ private:
bool wasConnected = false;
uint32_t willRetryConnectCount = 5;
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;
};

View file

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

View file

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

View file

@ -129,18 +129,28 @@
android:windowSoftInputMode="adjustResize|stateHidden">
</activity>
<receiver android:name=".AutoMessageHeardReceiver">
<receiver
android:name=".AutoMessageHeardReceiver"
android:exported="false">
<intent-filter>
<action android:name="org.telegram.messenger.ACTION_MESSAGE_HEARD"/>
</intent-filter>
</receiver>
<receiver android:name=".AutoMessageReplyReceiver">
<receiver
android:name=".AutoMessageReplyReceiver"
android:exported="false">
<intent-filter>
<action android:name="org.telegram.messenger.ACTION_MESSAGE_REPLY"/>
</intent-filter>
</receiver>
<receiver android:name=".CallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<receiver android:name=".SmsListener">
<intent-filter>
<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.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.Browser;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
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() {
if (photoSize == null) {
if (Build.VERSION.SDK_INT >= 16) {
@ -1057,4 +1082,11 @@ public class AndroidUtilities {
}
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.");
Intent intent = new Intent(applicationContext, GcmRegistrationIntentService.class);
startService(intent);
} else {
FileLog.d("tmessages", "GCM regId = " + UserConfig.pushString);
}
} else {
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.
* 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;
public class BuildVars {
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 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";

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++) {
File f = array[b];
if (f.isFile()) {
if (f.getName().equals(".nomedia")) {
continue;
}
if (Build.VERSION.SDK_INT >= 21) {
try {
StructStat stat = Os.stat(f.getPath());

View file

@ -56,7 +56,9 @@ public class ContactsController {
private int loadingDeleteInfo = 0;
private int deleteAccountTTL;
private int loadingLastSeenInfo = 0;
private int loadingGroupInfo = 0;
private ArrayList<TLRPC.PrivacyRule> privacyRules = null;
private ArrayList<TLRPC.PrivacyRule> groupPrivacyRules = null;
public static class Contact {
public int id;
@ -160,6 +162,7 @@ public class ContactsController {
loadingDeleteInfo = 0;
deleteAccountTTL = 0;
loadingLastSeenInfo = 0;
loadingGroupInfo = 0;
privacyRules = null;
}
@ -177,8 +180,8 @@ public class ContactsController {
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
final TLRPC.TL_help_inviteText res = (TLRPC.TL_help_inviteText)response;
if (response != null) {
final TLRPC.TL_help_inviteText res = (TLRPC.TL_help_inviteText) response;
if (res.message.length() != 0) {
AndroidUtilities.runOnUIThread(new Runnable() {
@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);
}
@ -1878,12 +1905,24 @@ public class ContactsController {
return loadingLastSeenInfo != 2;
}
public ArrayList<TLRPC.PrivacyRule> getPrivacyRules() {
return privacyRules;
public boolean getLoadingGroupInfo() {
return loadingGroupInfo != 2;
}
public void setPrivacyRules(ArrayList<TLRPC.PrivacyRule> rules) {
privacyRules = rules;
public ArrayList<TLRPC.PrivacyRule> getPrivacyRules(boolean isGroup) {
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);
reloadContactsStatuses();
}

View file

@ -94,73 +94,59 @@ public class FileLoadOperation {
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) {
if (documentLocation instanceof TLRPC.TL_documentEncrypted) {
location = new TLRPC.TL_inputEncryptedFileLocation();
location.id = documentLocation.id;
location.access_hash = documentLocation.access_hash;
datacenter_id = documentLocation.dc_id;
iv = new byte[32];
System.arraycopy(documentLocation.iv, 0, iv, 0, iv.length);
key = documentLocation.key;
} else if (documentLocation instanceof TLRPC.TL_document) {
location = new TLRPC.TL_inputDocumentFileLocation();
location.id = documentLocation.id;
location.access_hash = documentLocation.access_hash;
datacenter_id = documentLocation.dc_id;
}
if (totalBytesCount <= 0) {
totalBytesCount = documentLocation.size;
}
if (ext == null) {
try {
if (documentLocation instanceof TLRPC.TL_documentEncrypted) {
location = new TLRPC.TL_inputEncryptedFileLocation();
location.id = documentLocation.id;
location.access_hash = documentLocation.access_hash;
datacenter_id = documentLocation.dc_id;
iv = new byte[32];
System.arraycopy(documentLocation.iv, 0, iv, 0, iv.length);
key = documentLocation.key;
} else if (documentLocation instanceof TLRPC.TL_document) {
location = new TLRPC.TL_inputDocumentFileLocation();
location.id = documentLocation.id;
location.access_hash = documentLocation.access_hash;
datacenter_id = documentLocation.dc_id;
}
if (totalBytesCount <= 0) {
totalBytesCount = documentLocation.size;
}
ext = FileLoader.getDocumentFileName(documentLocation);
int idx;
if (ext == null || (idx = ext.lastIndexOf(".")) == -1) {
ext = "";
} else {
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 = "";
}
}
} 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);
state = stateDownloading;
if (location == null) {
cleanup();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
@ -315,7 +302,8 @@ public class FileLoadOperation {
state = stateFailed;
cleanup();
if (requestInfos != null) {
for (RequestInfo requestInfo : requestInfos) {
for (int a = 0; a < requestInfos.size(); a++) {
RequestInfo requestInfo = requestInfos.get(a);
if (requestInfo.requestToken != 0) {
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) {
cancelLoadFile(null, document, null, null, null);
}
public void cancelLoadFile(TLRPC.Audio audio) {
cancelLoadFile(null, null, audio, null, null);
cancelLoadFile(document, null, null);
}
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) {
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) {
if (video == null && location == null && document == null && audio == null) {
private void cancelLoadFile(final TLRPC.Document document, final TLRPC.FileLocation location, final String locationExt) {
if (location == null && document == null) {
return;
}
fileLoaderQueue.postRunnable(new Runnable() {
@Override
public void run() {
String fileName = null;
if (video != null) {
fileName = getAttachFileName(video);
} else if (location != null) {
if (location != null) {
fileName = getAttachFileName(location, locationExt);
} else if (document != null) {
fileName = getAttachFileName(document);
} else if (audio != null) {
fileName = getAttachFileName(audio);
}
if (fileName == null) {
return;
}
FileLoadOperation operation = loadOperationPaths.get(fileName);
FileLoadOperation operation = loadOperationPaths.remove(fileName);
if (operation != null) {
loadOperationPaths.remove(fileName);
if (audio != null) {
if (MessageObject.isVoiceDocument(document)) {
audioLoadOperationQueue.remove(operation);
} else if (location != null) {
photoLoadOperationQueue.remove(operation);
@ -346,39 +333,27 @@ public class FileLoader {
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) {
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) {
loadFile(null, document, null, 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);
loadFile(document, null, null, 0, force, cacheOnly || document != null && document.key != null);
}
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() {
@Override
public void run() {
String fileName = null;
if (video != null) {
fileName = getAttachFileName(video);
} else if (location != null) {
if (location != null) {
fileName = getAttachFileName(location, locationExt);
} else if (document != null) {
fileName = getAttachFileName(document);
} else if (audio != null) {
fileName = getAttachFileName(audio);
}
if (fileName == null || fileName.contains("" + Integer.MIN_VALUE)) {
return;
@ -389,7 +364,7 @@ public class FileLoader {
if (operation != null) {
if (force) {
LinkedList<FileLoadOperation> downloadQueue;
if (audio != null) {
if (MessageObject.isVoiceDocument(document)) {
downloadQueue = audioLoadOperationQueue;
} else if (location != null) {
downloadQueue = photoLoadOperationQueue;
@ -412,18 +387,18 @@ public class FileLoader {
File storeDir = tempDir;
int type = MEDIA_DIR_CACHE;
if (video != null) {
operation = new FileLoadOperation(video);
type = MEDIA_DIR_VIDEO;
} else if (location != null) {
if (location != null) {
operation = new FileLoadOperation(location, locationExt, locationSize);
type = MEDIA_DIR_IMAGE;
} else if (document != null) {
operation = new FileLoadOperation(document);
type = MEDIA_DIR_DOCUMENT;
} else if (audio != null) {
operation = new FileLoadOperation(audio);
type = MEDIA_DIR_AUDIO;
if (MessageObject.isVoiceDocument(document)) {
type = MEDIA_DIR_AUDIO;
} else if (MessageObject.isVideoDocument(document)) {
type = MEDIA_DIR_VIDEO;
} else {
type = MEDIA_DIR_DOCUMENT;
}
}
if (!cacheOnly) {
storeDir = getDirectory(type);
@ -439,12 +414,12 @@ public class FileLoader {
if (delegate != null) {
delegate.fileDidLoaded(finalFileName, finalFile, finalType);
}
checkDownloadQueue(audio, location, finalFileName);
checkDownloadQueue(document, location, finalFileName);
}
@Override
public void didFailedLoadingFile(FileLoadOperation operation, int canceled) {
checkDownloadQueue(audio, location, finalFileName);
checkDownloadQueue(document, location, finalFileName);
if (delegate != null) {
delegate.fileDidFailedLoad(finalFileName, canceled);
}
@ -458,7 +433,7 @@ public class FileLoader {
}
});
int maxCount = force ? 3 : 1;
if (audio != null) {
if (type == MEDIA_DIR_AUDIO) {
if (currentAudioLoadOperationsCount < maxCount) {
currentAudioLoadOperationsCount++;
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() {
@Override
public void run() {
loadOperationPaths.remove(arg1);
FileLoadOperation operation;
if (audio != null) {
if (MessageObject.isVoiceDocument(document)) {
currentAudioLoadOperationsCount--;
if (!audioLoadOperationQueue.isEmpty()) {
operation = audioLoadOperationQueue.get(0);
@ -550,6 +525,44 @@ public class FileLoader {
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) {
if (message == null) {
return new File("");
@ -565,12 +578,8 @@ public class FileLoader {
}
}
} else {
if (message.media instanceof TLRPC.TL_messageMediaVideo) {
return getPathToAttach(message.media.video);
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
if (message.media instanceof TLRPC.TL_messageMediaDocument) {
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) {
ArrayList<TLRPC.PhotoSize> sizes = message.media.photo.sizes;
if (sizes.size() > 0) {
@ -605,19 +614,18 @@ public class FileLoader {
if (forceCache) {
dir = getInstance().getDirectory(MEDIA_DIR_CACHE);
} else {
if (attach instanceof TLRPC.Video) {
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) {
if (attach instanceof TLRPC.Document) {
TLRPC.Document document = (TLRPC.Document) attach;
if (document.key != null) {
dir = getInstance().getDirectory(MEDIA_DIR_CACHE);
} 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) {
TLRPC.PhotoSize photoSize = (TLRPC.PhotoSize) attach;
@ -626,13 +634,6 @@ public class FileLoader {
} else {
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) {
TLRPC.FileLocation fileLocation = (TLRPC.FileLocation) attach;
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) {
if (attach instanceof TLRPC.Video) {
TLRPC.Video video = (TLRPC.Video) attach;
return video.dc_id + "_" + video.id + "." + (ext != null ? ext : "mp4");
} else if (attach instanceof TLRPC.Document) {
if (attach instanceof TLRPC.Document) {
TLRPC.Document document = (TLRPC.Document) attach;
String docExt = null;
if (docExt == null) {
@ -723,6 +721,23 @@ public class FileLoader {
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) {
return document.dc_id + "_" + document.id + docExt;
} else {
@ -734,9 +749,6 @@ public class FileLoader {
return "";
}
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) {
if (attach instanceof TLRPC.TL_fileLocationUnavailable) {
return "";

View file

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

View file

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

View file

@ -700,6 +700,30 @@ public class LocaleController {
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) {
try {
Calendar rightNow = Calendar.getInstance();

View file

@ -64,6 +64,8 @@ public class MessageObject {
public int textHeight;
public int blockHeight = Integer.MAX_VALUE;
private boolean layoutCreated;
public static Pattern urlPattern;
public static class TextLayoutBlock {
@ -96,15 +98,18 @@ public class MessageObject {
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.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 (isOut()) {
messageText = LocaleController.getString("ActionYouCreateGroup", R.string.ActionYouCreateGroup);
@ -357,8 +362,10 @@ public class MessageObject {
} else if (!isMediaEmpty()) {
if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
messageText = LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
} else if (isVideo()) {
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) {
messageText = LocaleController.getString("AttachLocation", R.string.AttachLocation);
} else if (message.media instanceof TLRPC.TL_messageMediaContact) {
@ -385,8 +392,6 @@ public class MessageObject {
messageText = LocaleController.getString("AttachDocument", R.string.AttachDocument);
}
}
} else if (message.media instanceof TLRPC.TL_messageMediaAudio) {
messageText = LocaleController.getString("AttachAudio", R.string.AttachAudio);
}
} else {
messageText = message.message;
@ -394,9 +399,6 @@ public class MessageObject {
if (messageText == null) {
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 (isMediaEmpty()) {
@ -409,9 +411,11 @@ public class MessageObject {
} else if (message.media instanceof TLRPC.TL_messageMediaGeo || message.media instanceof TLRPC.TL_messageMediaVenue) {
contentType = 1;
type = 4;
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
} else if (isVideo()) {
contentType = 1;
type = 3;
} else if (isVoice()) {
contentType = type = 2;
} else if (message.media instanceof TLRPC.TL_messageMediaContact) {
contentType = 3;
type = 12;
@ -433,8 +437,6 @@ public class MessageObject {
} else {
type = 9;
}
} else if (message.media instanceof TLRPC.TL_messageMediaAudio) {
contentType = type = 2;
}
} else if (message instanceof TLRPC.TL_messageService) {
if (message.action instanceof TLRPC.TL_messageActionLoginUnknownLocation) {
@ -468,18 +470,32 @@ public class MessageObject {
//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.parseString(messageOwner.message);
}
generateCaption();
if (generateLayout) {
generateLayout();
messageText = Emoji.replaceEmoji(messageText, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
generateLayout(fromUser);
}
layoutCreated = generateLayout;
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) {
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) {
if (!(messageOwner.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty)) {
if (!update) {
@ -644,12 +652,8 @@ public class MessageObject {
}
public String getFileName() {
if (messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
return FileLoader.getAttachFileName(messageOwner.media.video);
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
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) {
ArrayList<TLRPC.PhotoSize> sizes = messageOwner.media.photo.sizes;
if (sizes.size() > 0) {
@ -663,12 +667,12 @@ public class MessageObject {
}
public int getFileType() {
if (messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
if (isVideo()) {
return FileLoader.MEDIA_DIR_VIDEO;
} else if (isVoice()) {
return FileLoader.MEDIA_DIR_AUDIO;
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
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) {
return FileLoader.MEDIA_DIR_IMAGE;
}
@ -772,7 +776,7 @@ public class MessageObject {
private static void addUsernamesAndHashtags(CharSequence charSequence, boolean botCommands) {
try {
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);
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) {
return;
}
@ -856,6 +860,7 @@ public class MessageObject {
if (messageText instanceof Spannable) {
Spannable spannable = (Spannable) messageText;
int count = messageOwner.entities.size();
URLSpan[] spans = spannable.getSpans(0, messageText.length(), URLSpan.class);
for (int a = 0; a < count; a++) {
TLRPC.MessageEntity entity = messageOwner.entities.get(a);
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()) {
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) {
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) {
@ -904,6 +922,9 @@ public class MessageObject {
maxWidth = Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) - AndroidUtilities.dp(80);
}
}
if (fromUser != null && fromUser.bot) {
maxWidth -= AndroidUtilities.dp(20);
}
StaticLayout textLayout;
@ -1056,7 +1077,11 @@ public class MessageObject {
}
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() {
@ -1100,9 +1125,7 @@ public class MessageObject {
public boolean isSecretMedia() {
return messageOwner instanceof TLRPC.TL_message_secret &&
(messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && messageOwner.ttl > 0 && messageOwner.ttl <= 60 ||
messageOwner.media instanceof TLRPC.TL_messageMediaAudio ||
messageOwner.media instanceof TLRPC.TL_messageMediaVideo);
(messageOwner.media instanceof TLRPC.TL_messageMediaPhoto && messageOwner.ttl > 0 && messageOwner.ttl <= 60 || isVoice() || isVideo());
}
public static void setUnreadFlags(TLRPC.Message message, int flag) {
@ -1128,9 +1151,15 @@ public class MessageObject {
public static boolean isImportant(TLRPC.Message 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) {
@ -1200,9 +1229,10 @@ public class MessageObject {
return "";
}
public static boolean isStickerMessage(TLRPC.Message message) {
if (message.media != null && message.media.document != null) {
for (TLRPC.DocumentAttribute attribute : message.media.document.attributes) {
public static boolean isStickerDocument(TLRPC.Document document) {
if (document != null) {
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeSticker) {
return true;
}
@ -1211,17 +1241,60 @@ public class MessageObject {
return false;
}
public static boolean isMusicMessage(TLRPC.Message message) {
if (message.media != null && message.media.document != null) {
for (TLRPC.DocumentAttribute attribute : message.media.document.attributes) {
public static boolean isVoiceDocument(TLRPC.Document document) {
if (document != null) {
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
if (attribute instanceof TLRPC.TL_documentAttributeAudio) {
return true;
return attribute.voice;
}
}
}
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) {
if (message.media != null && message.media.document != null) {
for (TLRPC.DocumentAttribute attribute : message.media.document.attributes) {
@ -1339,6 +1412,14 @@ public class MessageObject {
return isMusicMessage(messageOwner);
}
public boolean isVoice() {
return isVoiceMessage(messageOwner);
}
public boolean isVideo() {
return isVideoMessage(messageOwner);
}
public boolean isGif() {
return isGifDocument(messageOwner.media.document);
}
@ -1348,8 +1429,12 @@ public class MessageObject {
}
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.voice) {
return LocaleController.formatDateAudio(messageOwner.date);
}
String title = attribute.title;
if (title == null || title.length() == 0) {
title = FileLoader.getDocumentFileName(messageOwner.media.document);
@ -1364,8 +1449,30 @@ public class MessageObject {
}
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.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;
if (performer == null || performer.length() == 0) {
performer = LocaleController.getString("AudioUnknownArtist", R.string.AudioUnknownArtist);
@ -1381,11 +1488,15 @@ public class MessageObject {
}
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() {
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() {
@ -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;
}
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) {
return canDeleteMessage(messageOwner, chat);
}
@ -1414,11 +1551,11 @@ public class MessageObject {
if (chat.creator) {
return true;
} else if (chat.editor) {
if (isOut(message) || message.from_id > 0) {
if (isOut(message) || message.from_id > 0 && !message.post) {
return true;
}
} else if (chat.moderator) {
if (message.from_id > 0) {
if (message.from_id > 0 && !message.post) {
return true;
}
} else if (isOut(message) && message.from_id > 0) {
@ -1429,15 +1566,17 @@ public class MessageObject {
}
public String getForwardedName() {
if (messageOwner.fwd_from_id instanceof TLRPC.TL_peerChannel) {
TLRPC.Chat chat = MessagesController.getInstance().getChat(messageOwner.fwd_from_id.channel_id);
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);
if (user != null) {
return UserObject.getUserName(user);
if (messageOwner.fwd_from != null) {
if (messageOwner.fwd_from.channel_id != 0) {
TLRPC.Chat chat = MessagesController.getInstance().getChat(messageOwner.fwd_from.channel_id);
if (chat != null) {
return chat.title;
}
} else if (messageOwner.fwd_from.from_id != 0) {
TLRPC.User user = MessagesController.getInstance().getUser(messageOwner.fwd_from.from_id);
if (user != null) {
return UserObject.getUserName(user);
}
}
}
return null;

View file

@ -22,7 +22,6 @@ import org.telegram.messenger.query.BotQuery;
import org.telegram.messenger.query.SharedMediaQuery;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.TLClassStore;
import org.telegram.tgnet.TLObject;
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();
//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 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");
if (version < 29) {
if (version < 30) {
updateDbToLastVersion(version);
}
}
@ -464,11 +463,6 @@ public class MessagesStorage {
database.executeFast("PRAGMA user_version = 23").stepThis().dispose();
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) {
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();
@ -487,7 +481,13 @@ public class MessagesStorage {
if (version == 28) {
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();
//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) {
FileLog.e("tmessages", e);
@ -1028,27 +1028,13 @@ public class MessagesStorage {
if (message == null || message.media == null) {
continue;
}
if (message.media instanceof TLRPC.TL_messageMediaAudio) {
File file = FileLoader.getPathToAttach(message.media.audio);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
for (TLRPC.PhotoSize photoSize : message.media.photo.sizes) {
File file = FileLoader.getPathToAttach(photoSize);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
}
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
File file = FileLoader.getPathToAttach(message.media.video);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
file = FileLoader.getPathToAttach(message.media.video.thumb);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
File file = FileLoader.getPathToAttach(message.media.document);
if (file != null && file.toString().length() > 0) {
@ -1287,6 +1273,7 @@ public class MessagesStorage {
try {
int minDate = Integer.MAX_VALUE;
SparseArray<ArrayList<Integer>> messages = new SparseArray<>();
final ArrayList<Long> midsArray = new ArrayList<>();
StringBuilder mids = new StringBuilder();
SQLiteCursor cursor;
if (random_ids == null) {
@ -1297,10 +1284,13 @@ public class MessagesStorage {
}
while (cursor.next()) {
int ttl = cursor.intValue(1);
int mid = cursor.intValue(0);
if (random_ids != null) {
midsArray.add((long) mid);
}
if (ttl <= 0) {
continue;
}
int mid = cursor.intValue(0);
int date = Math.min(readTime, time) + ttl;
minDate = Math.min(minDate, date);
ArrayList<Integer> arr = messages.get(date);
@ -1315,15 +1305,26 @@ public class MessagesStorage {
arr.add(mid);
}
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) {
database.beginTransaction();
SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_tasks_v2 VALUES(?, ?)");
for (int a = 0; a < messages.size(); a++) {
int key = messages.keyAt(a);
ArrayList<Integer> arr = messages.get(key);
for (Integer mid : arr) {
for (int b = 0; b < arr.size(); b++) {
state.requery();
state.bindInteger(1, mid);
state.bindInteger(1, arr.get(b));
state.bindInteger(2, key);
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) {
storageQueue.postRunnable(new Runnable() {
@Override
@ -2143,6 +2174,7 @@ public class MessagesStorage {
ArrayList<Integer> chatsToLoad = new ArrayList<>();
ArrayList<Long> replyMessages = new ArrayList<>();
HashMap<Integer, ArrayList<TLRPC.Message>> replyMessageOwners = new HashMap<>();
HashMap<Long, ArrayList<TLRPC.Message>> replyMessageRandomOwners = new HashMap<>();
SQLiteCursor cursor;
int lower_id = (int) dialog_id;
@ -2389,7 +2421,7 @@ public class MessagesStorage {
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;
if (!cursor.isNull(6)) {
NativeByteBuffer data2 = new NativeByteBuffer(cursor.byteArrayLength(6));
@ -2403,19 +2435,31 @@ public class MessagesStorage {
data2.reuse();
}
if (!ok) {
long messageId = message.reply_to_msg_id;
if (message.to_id.channel_id != 0) {
messageId |= ((long) message.to_id.channel_id) << 32;
if (message.reply_to_msg_id != 0) {
long messageId = message.reply_to_msg_id;
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);
@ -2499,7 +2543,11 @@ public class MessagesStorage {
}
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()) {
NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data) != 0) {
@ -2510,16 +2558,35 @@ public class MessagesStorage {
addUsersAndChatsFromMessage(message, usersToLoad, chatsToLoad);
ArrayList<TLRPC.Message> arrayList = replyMessageOwners.get(message.id);
if (arrayList != null) {
for (TLRPC.Message m : arrayList) {
m.replyMessage = message;
if (!replyMessageOwners.isEmpty()) {
ArrayList<TLRPC.Message> arrayList = replyMessageOwners.get(message.id);
if (arrayList != null) {
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();
}
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()) {
@ -2599,9 +2666,11 @@ public class MessagesStorage {
if (cursor.next()) {
NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data) != 0) {
TLObject file = TLClassStore.Instance().TLdeserialize(data, data.readInt32(false), false);
if (file != null) {
result.add(file);
TLObject file = TLRPC.MessageMedia.TLdeserialize(data, data.readInt32(false), false);
if (file instanceof TLRPC.TL_messageMediaDocument) {
result.add(((TLRPC.TL_messageMediaDocument) file).document);
} else if (file instanceof TLRPC.TL_messageMediaPhoto) {
result.add(((TLRPC.TL_messageMediaDocument) file).photo);
}
}
data.reuse();
@ -2634,10 +2703,23 @@ public class MessagesStorage {
try {
String id = Utilities.MD5(path);
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.requery();
NativeByteBuffer data = new NativeByteBuffer(file.getObjectSize());
file.serializeToStream(data);
NativeByteBuffer data = new NativeByteBuffer(messageMedia.getObjectSize());
messageMedia.serializeToStream(data);
state.bindString(1, id);
state.bindInteger(2, type);
state.bindByteBuffer(3, data);
@ -2738,10 +2820,8 @@ public class MessagesStorage {
public void run() {
SQLitePreparedStatement state = null;
try {
if ((chat.key_hash == null || chat.key_hash.length != 16) && chat.auth_key != null) {
byte[] sha1 = Utilities.computeSHA1(chat.auth_key);
chat.key_hash = new byte[16];
System.arraycopy(sha1, 0, chat.key_hash, 0, chat.key_hash.length);
if ((chat.key_hash == null || chat.key_hash.length < 16) && chat.auth_key != null) {
chat.key_hash = AndroidUtilities.calcAuthKeyHash(chat.auth_key);
}
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
public void run() {
try {
if ((chat.key_hash == null || chat.key_hash.length != 16) && chat.auth_key != null) {
byte[] sha1 = Utilities.computeSHA1(chat.auth_key);
chat.key_hash = new byte[16];
System.arraycopy(sha1, 0, chat.key_hash, 0, chat.key_hash.length);
if ((chat.key_hash == null || chat.key_hash.length < 16) && chat.auth_key != null) {
chat.key_hash = AndroidUtilities.calcAuthKeyHash(chat.auth_key);
}
SQLitePreparedStatement state = database.executeFast("REPLACE INTO enc_chats VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
NativeByteBuffer data = new NativeByteBuffer(chat.getObjectSize());
@ -2950,7 +3028,46 @@ public class MessagesStorage {
return;
}
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();
NativeByteBuffer data = new NativeByteBuffer(user.getObjectSize());
user.serializeToStream(data);
@ -2980,7 +3097,8 @@ public class MessagesStorage {
return;
}
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();
NativeByteBuffer data = new NativeByteBuffer(chat.getObjectSize());
chat.serializeToStream(data);
@ -3171,7 +3289,12 @@ public class MessagesStorage {
downloadObject.id = cursor.longValue(0);
NativeByteBuffer data = new NativeByteBuffer(cursor.byteArrayLength(2));
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();
objects.add(downloadObject);
@ -3194,10 +3317,10 @@ public class MessagesStorage {
private int getMessageMediaType(TLRPC.Message message) {
if (message instanceof TLRPC.TL_message_secret && (
message.media instanceof TLRPC.TL_messageMediaPhoto && message.ttl > 0 && message.ttl <= 60 ||
message.media instanceof TLRPC.TL_messageMediaAudio ||
message.media instanceof TLRPC.TL_messageMediaVideo)) {
MessageObject.isVoiceMessage(message) ||
MessageObject.isVideoMessage(message))) {
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 -1;
@ -3611,15 +3734,17 @@ public class MessagesStorage {
data.reuse();
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;
long id = 0;
TLObject object = null;
if (message.media instanceof TLRPC.TL_messageMediaAudio) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0 && message.media.audio.size < 1024 * 1024 * 5) {
id = message.media.audio.id;
TLRPC.MessageMedia object = null;
if (MessageObject.isVoiceMessage(message)) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0 && message.media.document.size < 1024 * 1024 * 5) {
id = message.media.document.id;
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) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) {
@ -3627,20 +3752,26 @@ public class MessagesStorage {
if (photoSize != null) {
id = message.media.photo.id;
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) {
id = message.media.video.id;
id = message.media.document.id;
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)) {
if ((downloadMask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) {
id = message.media.document.id;
type = MediaController.AUTODOWNLOAD_MASK_DOCUMENT;
object = message.media.document;
object = new TLRPC.TL_messageMediaDocument();
object.caption = "";
object.document = message.media.document;
}
}
if (object != null) {
@ -4260,27 +4391,13 @@ public class MessagesStorage {
if (message == null || message.media == null) {
continue;
}
if (message.media instanceof TLRPC.TL_messageMediaAudio) {
File file = FileLoader.getPathToAttach(message.media.audio);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
} else if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
for (TLRPC.PhotoSize photoSize : message.media.photo.sizes) {
File file = FileLoader.getPathToAttach(photoSize);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
}
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
File file = FileLoader.getPathToAttach(message.media.video);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
file = FileLoader.getPathToAttach(message.media.video.thumb);
if (file != null && file.toString().length() > 0) {
filesToDelete.add(file);
}
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
File file = FileLoader.getPathToAttach(message.media.document);
if (file != null && file.toString().length() > 0) {
@ -4792,6 +4909,15 @@ public class MessagesStorage {
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) {
SQLitePreparedStatement state3 = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
state3.bindLong(1, dialog_id);
@ -4801,7 +4927,7 @@ public class MessagesStorage {
state3.bindInteger(5, message.id);
state3.bindInteger(6, 0);
state3.bindLong(7, messageId);
state3.bindInteger(8, 0);
state3.bindInteger(8, load_type < 0 ? message.ttl : 0);
state3.bindInteger(9, messages.pts);
state3.bindInteger(10, message.date);
state3.step();
@ -4809,7 +4935,7 @@ public class MessagesStorage {
}
boolean isImportant = MessageObject.isImportant(message);
if (load_type != -1 && important == 1) {
if (load_type >= 0 && important == 1) {
if (isImportant) {
minChannelMessageId = Math.min(minChannelMessageId, message.id);
maxChannelMessageId = Math.max(maxChannelMessageId, message.id);
@ -4874,7 +5000,7 @@ public class MessagesStorage {
BotQuery.putBotKeyboard(dialog_id, botKeyboard);
}
if (load_type != -1 && important != 0) {
if (load_type >= 0 && important != 0) {
/*if ((messages.flags & 1) == 0) {
if (countBeforeImportant != 0) {
if (load_type == 0) {
@ -4979,17 +5105,17 @@ public class MessagesStorage {
if (message.media.user_id != 0 && !usersToLoad.contains(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 (!usersToLoad.contains(message.fwd_from_id.user_id)) {
usersToLoad.add(message.fwd_from_id.user_id);
if (message.fwd_from != null) {
if (message.fwd_from.from_id != 0) {
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 (!chatsToLoad.contains(message.fwd_from_id.channel_id)) {
chatsToLoad.add(message.fwd_from_id.channel_id);
if (message.fwd_from.channel_id != 0) {
if (!chatsToLoad.contains(message.fwd_from.channel_id)) {
chatsToLoad.add(message.fwd_from.channel_id);
}
}
}
if (message.ttl < 0) {
@ -5010,7 +5136,7 @@ public class MessagesStorage {
usersToLoad.add(UserConfig.getClientUserId());
ArrayList<Integer> chatsToLoad = 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()) {
TLRPC.Dialog dialog;
int pts = cursor.intValue(12);
@ -5026,6 +5152,7 @@ public class MessagesStorage {
dialog.last_message_date = cursor.intValue(3);
dialog.pts = pts;
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.unread_not_important_count = cursor.intValue(11);
long flags = cursor.longValue(8);

View file

@ -21,15 +21,13 @@ import android.media.RemoteControlClient;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.RemoteViews;
import org.telegram.messenger.audioinfo.AudioInfo;
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_CLOSE = "org.telegram.android.musicplayer.close";
@ -39,8 +37,6 @@ public class MusicPlayerService extends Service implements AudioManager.OnAudioF
private RemoteControlClient remoteControlClient;
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 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);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged);
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();
}
@ -220,7 +193,6 @@ public class MusicPlayerService extends Service implements AudioManager.OnAudioF
metadataEditor.putBitmap(RemoteControlClient.MetadataEditor.BITMAP_KEY_ARTWORK, audioInfo.getCover());
}
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.apply();
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.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
public void didReceivedNotification(int id, Object... args) {
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 {
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_SO_NAME = "lib" + LIB_NAME + ".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 didUpdatedConnectionState = totalEvents++;
public static final int didReceiveSmsCode = totalEvents++;
public static final int didReceiveCall = totalEvents++;
public static final int emojiDidLoaded = totalEvents++;
public static final int appDidLogout = totalEvents++;

View file

@ -78,8 +78,10 @@ public class NotificationsController {
private SoundPool soundPool;
private int soundIn;
private int soundOut;
private int soundRecord;
private boolean soundInLoaded;
private boolean soundOutLoaded;
private boolean soundRecordLoaded;
protected AudioManager audioManager;
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 from_id = messageObject.messageOwner.to_id.user_id;
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()) {
from_id = messageObject.messageOwner.from_id;
}
@ -747,8 +753,10 @@ public class NotificationsController {
}
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
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);
} else if (messageObject.isVoice()) {
msg = LocaleController.formatString("NotificationMessageAudio", R.string.NotificationMessageAudio, name);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
msg = LocaleController.formatString("NotificationMessageContact", R.string.NotificationMessageContact, name);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaGeo || messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVenue) {
@ -761,8 +769,6 @@ public class NotificationsController {
} else {
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 {
@ -857,8 +863,10 @@ public class NotificationsController {
}
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
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);
} else if (messageObject.isVoice()) {
msg = LocaleController.formatString("ChannelMessageAudio", R.string.ChannelMessageAudio, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
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) {
@ -871,8 +879,6 @@ public class NotificationsController {
} else {
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 {
if (messageObject.isMediaEmpty()) {
@ -883,8 +889,10 @@ public class NotificationsController {
}
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
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);
} else if (messageObject.isVoice()) {
msg = LocaleController.formatString("ChannelMessageGroupAudio", R.string.ChannelMessageGroupAudio, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
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) {
@ -897,8 +905,6 @@ public class NotificationsController {
} else {
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 {
@ -910,8 +916,10 @@ public class NotificationsController {
}
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
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);
} else if (messageObject.isVoice()) {
msg = LocaleController.formatString("NotificationMessageGroupAudio", R.string.NotificationMessageGroupAudio, name, chat.title);
} else if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaContact) {
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) {
@ -924,13 +932,15 @@ public class NotificationsController {
} else {
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 {
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() {
if (!inChatSoundEnabled) {
if (!inChatSoundEnabled || MediaController.getInstance().isRecordingAudio()) {
return;
}
try {
@ -1038,7 +1085,7 @@ public class NotificationsController {
}
try {
if (soundPool == null) {
soundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 0);
soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
@ -1298,26 +1345,17 @@ public class NotificationsController {
.setGroupSummary(true)
.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);
if (chat == null && user != null && user.phone != null && user.phone.length() > 0) {
mBuilder.addPerson("tel:+" + user.phone);
}
int silent = 2;
String lastMessage = null;
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) {
return;
}
@ -1336,12 +1374,14 @@ public class NotificationsController {
inboxStyle.setBigContentTitle(name);
int count = Math.min(10, pushMessages.size());
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) {
continue;
}
if (i == 0) {
if (silent == 2) {
lastMessage = message;
silent = messageObject.messageOwner.silent ? 1 : 0;
}
if (pushDialogs.size() == 1) {
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 (lastMessage.length() > 100) {
lastMessage = lastMessage.substring(0, 100).replace("\n", " ").trim() + "...";
}
mBuilder.setTicker(lastMessage);
}
if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
if (choosenSoundPath.equals(defaultPath)) {
/*MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setDataSource(ApplicationLoader.applicationContext, Settings.System.DEFAULT_NOTIFICATION_URI);
mediaPlayer.prepare();
mediaPlayer.start();*/
mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION);
} else {
mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION);
if (!MediaController.getInstance().isRecordingAudio()) {
if (choosenSoundPath != null && !choosenSoundPath.equals("NoSound")) {
if (choosenSoundPath.equals(defaultPath)) {
mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, AudioManager.STREAM_NOTIFICATION);
} else {
mBuilder.setSound(Uri.parse(choosenSoundPath), AudioManager.STREAM_NOTIFICATION);
}
}
}
if (ledColor != 0) {
mBuilder.setLights(ledColor, 1000, 1000);
}
if (needVibrate == 2) {
if (needVibrate == 2 || MediaController.getInstance().isRecordingAudio()) {
mBuilder.setVibrate(new long[]{0, 0});
} else if (needVibrate == 1) {
mBuilder.setVibrate(new long[]{0, 100, 0, 100});
@ -1597,7 +1652,7 @@ public class NotificationsController {
}
public void playOutChatSound() {
if (!inChatSoundEnabled) {
if (!inChatSoundEnabled || MediaController.getInstance().isRecordingAudio()) {
return;
}
try {
@ -1616,7 +1671,7 @@ public class NotificationsController {
}
lastSoundOutPlay = System.currentTimeMillis();
if (soundPool == null) {
soundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 0);
soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
@ -1642,14 +1697,13 @@ public class NotificationsController {
public static void updateServerNotificationsSettings(long dialog_id) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.notificationsSettingsUpdated);
if ((int)dialog_id == 0) {
if ((int) dialog_id == 0) {
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings();
req.settings = new TLRPC.TL_inputPeerNotifySettings();
req.settings.sound = "default";
req.settings.events_mask = 0;
int mute_type = preferences.getInt("notify2_" + dialog_id, 0);
if (mute_type == 3) {
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.show_previews = preferences.getBoolean("preview_" + dialog_id, true);
req.settings.silent = preferences.getBoolean("silent_" + dialog_id, false);
req.peer = new TLRPC.TL_inputNotifyPeer();
((TLRPC.TL_inputNotifyPeer)req.peer).peer = MessagesController.getInputPeer((int) dialog_id);
if (((TLRPC.TL_inputNotifyPeer)req.peer).peer == null) {
return;
}
((TLRPC.TL_inputNotifyPeer) req.peer).peer = MessagesController.getInputPeer((int) dialog_id);
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
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 boolean isWaitingForPasscodeEnter = false;
public static boolean useFingerprint = true;
public static int lastUpdateVersion;
public static String lastUpdateVersion;
public static int lastContactsSyncTime;
public static int migrateOffsetId = -1;
@ -83,7 +83,7 @@ public class UserConfig {
editor.putInt("passcodeType", passcodeType);
editor.putInt("autoLockIn", autoLockIn);
editor.putInt("lastPauseTime", lastPauseTime);
editor.putInt("lastUpdateVersion", lastUpdateVersion);
editor.putString("lastUpdateVersion2", lastUpdateVersion);
editor.putInt("lastContactsSyncTime", lastContactsSyncTime);
editor.putBoolean("useFingerprint", useFingerprint);
@ -224,7 +224,7 @@ public class UserConfig {
autoLockIn = preferences.getInt("autoLockIn", 60 * 60);
lastPauseTime = preferences.getInt("lastPauseTime", 0);
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);
migrateOffsetId = preferences.getInt("migrateOffsetId", 0);
@ -314,7 +314,7 @@ public class UserConfig {
lastPauseTime = 0;
useFingerprint = true;
isWaitingForPasscodeEnter = false;
lastUpdateVersion = BuildVars.BUILD_VERSION;
lastUpdateVersion = BuildVars.BUILD_VERSION_STRING;
lastContactsSyncTime = (int) (System.currentTimeMillis() / 1000) - 23 * 60 * 60;
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 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);
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) {
aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length);

View file

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

View file

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

View file

@ -32,111 +32,188 @@ import java.util.Locale;
public class ReplyMessageQuery {
public static void loadReplyMessagesForMessages(final ArrayList<MessageObject> messages, final long dialog_id) {
final ArrayList<Integer> replyMessages = new ArrayList<>();
final HashMap<Integer, ArrayList<MessageObject>> replyMessageOwners = new HashMap<>();
final StringBuilder stringBuilder = new StringBuilder();
int channelId = 0;
for (MessageObject messageObject : messages) {
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);
if ((int) dialog_id == 0) {
final ArrayList<Long> replyMessages = new ArrayList<>();
final HashMap<Long, ArrayList<MessageObject>> replyMessageRandomOwners = new HashMap<>();
final StringBuilder stringBuilder = new StringBuilder();
for (int a = 0; a < messages.size(); a++) {
MessageObject messageObject = messages.get(a);
if (messageObject.isReply() && messageObject.replyMessageObject == null) {
Long id = messageObject.messageOwner.reply_to_random_id;
if (stringBuilder.length() > 0) {
stringBuilder.append(',');
}
stringBuilder.append(id);
ArrayList<MessageObject> messageObjects = replyMessageRandomOwners.get(id);
if (messageObjects == null) {
messageObjects = new ArrayList<>();
replyMessageRandomOwners.put(id, messageObjects);
}
messageObjects.add(messageObject);
if (!replyMessages.contains(id)) {
replyMessages.add(id);
}
}
}
}
if (replyMessages.isEmpty()) {
return;
}
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<>();
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
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)));
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;
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);
ArrayList<MessageObject> arrayList = replyMessageRandomOwners.remove(cursor.longValue(3));
if (arrayList != null) {
MessageObject messageObject = new MessageObject(message, null, null, false);
for (int b = 0; b < arrayList.size(); b++) {
MessageObject object = arrayList.get(b);
object.replyMessageObject = messageObject;
object.messageOwner.reply_to_msg_id = messageObject.getId();
}
}
});
} 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);
}
}
});
}
data.reuse();
}
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) {

View file

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

View file

@ -43,6 +43,7 @@ public class StickersQuery {
private static int loadDate;
private static ArrayList<TLRPC.TL_messages_stickerSet> stickerSets = new ArrayList<>();
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, TLRPC.Document> stickersById = new HashMap<>();
private static HashMap<String, ArrayList<TLRPC.Document>> allStickers = new HashMap<>();
@ -57,6 +58,7 @@ public class StickersQuery {
stickerSets.clear();
stickersByEmoji.clear();
stickerSetsById.clear();
stickerSetsByName.clear();
loadingStickers = false;
stickersLoaded = false;
}
@ -95,6 +97,10 @@ public class StickersQuery {
return stickerSetsById.containsKey(id);
}
public static boolean isStickerPackInstalled(String name) {
return stickerSetsByName.containsKey(name);
}
public static String getEmojiForSticker(long id) {
String value = stickersByEmoji.get(id);
return value != null ? value : "";
@ -124,32 +130,34 @@ public class StickersQuery {
}
public static void addNewStickerSet(final TLRPC.TL_messages_stickerSet set) {
if (!stickerSetsById.containsKey(set.set.id)) {
stickerSets.add(0, set);
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);
if (stickerSetsById.containsKey(set.set.id) || stickerSetsByName.containsKey(set.set.short_name)) {
return;
}
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);
}
@ -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() {
@Override
public void run() {
try {
if (stickers != null) {
if (stickersFinal != null) {
SQLitePreparedStatement state = MessagesStorage.getInstance().getDatabase().executeFast("REPLACE INTO stickers_v2 VALUES(?, ?, ?, ?)");
state.requery();
int size = 4;
for (int a = 0; a < stickers.size(); a++) {
size += stickers.get(a).getObjectSize();
for (int a = 0; a < stickersFinal.size(); a++) {
size += stickersFinal.get(a).getObjectSize();
}
NativeByteBuffer data = new NativeByteBuffer(size);
data.writeInt32(stickers.size());
for (int a = 0; a < stickers.size(); a++) {
stickers.get(a).serializeToStream(data);
data.writeInt32(stickersFinal.size());
for (int a = 0; a < stickersFinal.size(); a++) {
stickersFinal.get(a).serializeToStream(data);
}
state.bindInteger(1, 1);
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) {
for (int a = 0; a < document.attributes.size(); a++) {
TLRPC.DocumentAttribute attribute = document.attributes.get(a);
@ -350,6 +364,7 @@ public class StickersQuery {
try {
final ArrayList<TLRPC.TL_messages_stickerSet> stickerSetsNew = new ArrayList<>();
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, TLRPC.Document> stickersByIdNew = new HashMap<>();
final HashMap<String, ArrayList<TLRPC.Document>> allStickersNew = new HashMap<>();
@ -361,6 +376,7 @@ public class StickersQuery {
}
stickerSetsNew.add(stickerSet);
stickerSetsByIdNew.put(stickerSet.set.id, stickerSet);
stickerSetsByNameNew.put(stickerSet.set.short_name, stickerSet);
for (int b = 0; b < stickerSet.documents.size(); b++) {
TLRPC.Document document = stickerSet.documents.get(b);
@ -400,6 +416,7 @@ public class StickersQuery {
public void run() {
stickersById = stickersByIdNew;
stickerSetsById = stickerSetsByIdNew;
stickerSetsByName = stickerSetsByNameNew;
stickerSets = stickerSetsNew;
allStickers = allStickersNew;
stickersByEmoji = stickersByEmojiNew;
@ -469,7 +486,11 @@ public class StickersQuery {
if (error == null) {
Toast.makeText(fragment.getParentActivity(), LocaleController.getString("AddStickersInstalled", R.string.AddStickersInstalled), Toast.LENGTH_SHORT).show();
} 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);
@ -539,6 +560,7 @@ public class StickersQuery {
}
}
loadHash = calcStickersHash(stickerSets);
putStickersToCache(stickerSets, loadDate, loadHash);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.stickersDidLoaded);
TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet();
req.stickerset = stickerSetID;

View file

@ -120,42 +120,46 @@ public class ConnectionsManager {
@Override
public void run() {
FileLog.d("tmessages", "send request " + object + " with token = " + requestToken);
NativeByteBuffer buffer = new NativeByteBuffer(object.getObjectSize());
object.serializeToStream(buffer);
object.freeResources();
try {
NativeByteBuffer buffer = new NativeByteBuffer(object.getObjectSize());
object.serializeToStream(buffer);
object.freeResources();
native_sendRequest(buffer.address, new RequestDelegateInternal() {
@Override
public void run(int response, int errorCode, String errorText) {
try {
TLObject resp = null;
TLRPC.TL_error error = null;
if (response != 0) {
NativeByteBuffer buff = NativeByteBuffer.wrap(response);
resp = object.deserializeResponse(buff, buff.readInt32(true), true);
} else if (errorText != null) {
error = new TLRPC.TL_error();
error.code = errorCode;
error.text = errorText;
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();
}
native_sendRequest(buffer.address, new RequestDelegateInternal() {
@Override
public void run(int response, int errorCode, String errorText) {
try {
TLObject resp = null;
TLRPC.TL_error error = null;
if (response != 0) {
NativeByteBuffer buff = NativeByteBuffer.wrap(response);
resp = object.deserializeResponse(buff, buff.readInt32(true), true);
} else if (errorText != null) {
error = new TLRPC.TL_error();
error.code = errorCode;
error.text = errorText;
FileLog.e("tmessages", object + " got error " + error.code + " " + error.text);
}
});
} catch (Exception e) {
FileLog.e("tmessages", e);
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();
}
}
});
} 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;

View file

@ -40,13 +40,17 @@ public class NativeByteBuffer extends AbstractSerializedData {
}
public NativeByteBuffer(int size) {
address = native_getFreeBuffer(size);
if (address != 0) {
buffer = native_getJavaByteBuffer(address);
buffer.position(0);
buffer.limit(size);
buffer.order(ByteOrder.LITTLE_ENDIAN);
public NativeByteBuffer(int size) throws Exception {
if (size >= 0) {
address = native_getFreeBuffer(size);
if (address != 0) {
buffer = native_getJavaByteBuffer(address);
buffer.position(0);
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_config.constructor, TLRPC.TL_config.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_old.constructor, TLRPC.TL_decryptedMessage_old.class);
classStore.put(TLRPC.TL_decryptedMessage_layer17.constructor, TLRPC.TL_decryptedMessage.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_old.constructor, TLRPC.TL_message_secret_old.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_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_updateShortSentMessage.constructor, TLRPC.TL_updateShortSentMessage.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;

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.setTextColor(0xff757575);
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.setGravity(Gravity.CENTER_VERTICAL);
containerView.addView(titleView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));

View file

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

View file

@ -415,7 +415,7 @@ public class AudioPlayerActivity extends BaseFragment implements NotificationCen
private void updateTitle(boolean shutdown) {
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
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();
} else {
removeSelfFromStack();

View file

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

View file

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

View file

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

View file

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

View file

@ -20,25 +20,30 @@ import android.view.SoundEffectConstants;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.FileLoader;
import org.telegram.messenger.MediaController;
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.ResourceLoader;
import org.telegram.ui.Components.SeekBar;
import org.telegram.ui.Components.SeekBarWaveform;
import java.io.File;
public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelegate {
public interface ChatAudioCellDelegate {
boolean needPlayAudio(MessageObject messageObject);
}
private static TextPaint timePaint;
private static Paint circlePaint;
private boolean hasWaveform;
private SeekBar seekBar;
private SeekBarWaveform seekBarWaveform;
private int seekBarX;
private int seekBarY;
@ -50,14 +55,21 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
private StaticLayout timeLayout;
private int timeX;
private int timeWidth;
private int timeWidth2;
private String lastTimeString = null;
private ChatAudioCellDelegate audioDelegate;
public ChatAudioCell(Context context) {
super(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);
drawForwardedName = true;
@ -85,55 +97,83 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
boolean result = seekBar.onTouch(event.getAction(), event.getX() - seekBarX, event.getY() - seekBarY);
if (result) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
getParent().requestDisallowInterceptTouchEvent(true);
boolean result = false;
if (delegate.canPerformActions()) {
if (hasWaveform) {
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();
} else {
int side = AndroidUtilities.dp(36);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
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);
if (result) {
if (!hasWaveform && event.getAction() == MotionEvent.ACTION_DOWN) {
getParent().requestDisallowInterceptTouchEvent(true);
} else if (hasWaveform && !seekBarWaveform.isStartDraging() && event.getAction() == MotionEvent.ACTION_UP) {
didPressedButton();
invalidate();
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
buttonPressed = false;
invalidate();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (!(x >= buttonX && x <= buttonX + side && y >= buttonY && y <= buttonY + side)) {
}
invalidate();
} else {
int side = AndroidUtilities.dp(36);
boolean area;
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;
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;
}
@Override
protected void onLongPress() {
super.onLongPress();
if (buttonPressed) {
buttonPressed = false;
invalidate();
}
}
public void setAudioDelegate(ChatAudioCellDelegate delegate) {
audioDelegate = delegate;
}
private void didPressedButton() {
if (buttonState == 0) {
boolean result = MediaController.getInstance().playAudio(currentMessageObject);
if (!currentMessageObject.isOut() && currentMessageObject.isContentUnread()) {
if (currentMessageObject.messageOwner.to_id.channel_id == 0) {
MessagesController.getInstance().markMessageContentAsRead(currentMessageObject.messageOwner);
}
}
if (result) {
if (audioDelegate.needPlayAudio(currentMessageObject)) {
buttonState = 1;
radialProgress.setBackground(getDrawableForCurrentState(), false, false);
invalidate();
@ -147,12 +187,12 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
}
} else if (buttonState == 2) {
radialProgress.setProgress(0, false);
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true);
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
buttonState = 3;
radialProgress.setBackground(getDrawableForCurrentState(), true, false);
invalidate();
} else if (buttonState == 3) {
FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.audio);
FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.document);
buttonState = 2;
radialProgress.setBackground(getDrawableForCurrentState(), false, false);
invalidate();
@ -170,28 +210,40 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
return;
}
if (!seekBar.isDragging()) {
seekBar.setProgress(currentMessageObject.audioProgress);
if (hasWaveform) {
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)) {
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 {
duration = currentMessageObject.audioProgressSec;
}
String timeString = String.format("%02d:%02d", duration / 60, duration % 60);
if (lastTimeString == null || lastTimeString != null && !lastTimeString.equals(timeString)) {
lastTimeString = timeString;
timeWidth = (int)Math.ceil(timePaint.measureText(timeString));
timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
timeWidth2 = (int)Math.ceil(timePaint.measureText(timeString));
timeLayout = new StaticLayout(timeString, timePaint, timeWidth2, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
invalidate();
}
public void downloadAudioIfNeed() {
if (buttonState == 2) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.audio, true);
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
buttonState = 3;
radialProgress.setBackground(getDrawableForCurrentState(), false, false);
}
@ -221,9 +273,6 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
if (cacheFile == null) {
cacheFile = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
}
if (BuildVars.DEBUG_VERSION) {
FileLog.d("tmessages", "looking for audio in " + cacheFile);
}
if (cacheFile.exists()) {
MediaController.getInstance().removeLoadingFileObserver(this);
boolean playing = MediaController.getInstance().isPlayingAudio(currentMessageObject);
@ -264,6 +313,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
@Override
public void onSuccessDownload(String fileName) {
updateButtonState(true);
updateWaveform();
}
@Override
@ -303,7 +353,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
buttonX = layoutWidth - backgroundWidth + AndroidUtilities.dp(13);
timeX = layoutWidth - backgroundWidth + AndroidUtilities.dp(66);
} else {
if (isChat && currentMessageObject.messageOwner.from_id > 0) {
if (isChat && currentMessageObject.isFromUser()) {
seekBarX = AndroidUtilities.dp(116);
buttonX = AndroidUtilities.dp(74);
timeX = AndroidUtilities.dp(127);
@ -313,9 +363,9 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
timeX = AndroidUtilities.dp(75);
}
}
seekBar.width = backgroundWidth - AndroidUtilities.dp(70);
seekBar.height = AndroidUtilities.dp(30);
seekBarWaveform.width = seekBar.width = backgroundWidth - AndroidUtilities.dp(70);
seekBarWaveform.height = seekBar.height = AndroidUtilities.dp(30);
seekBarWaveform.width -= AndroidUtilities.dp(20);
seekBarY = AndroidUtilities.dp(11) + namesOffset;
buttonY = AndroidUtilities.dp(13) + namesOffset;
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();
if (currentMessageObject != messageObject || dataChanged) {
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 {
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()) {
seekBar.type = 0;
} else {
seekBar.type = 1;
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(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);
}
updateWaveform();
updateButtonState(dataChanged);
}
@Override
protected int getMaxNameWidth() {
return backgroundWidth - AndroidUtilities.dp(24);
}
@Override
public void setCheckPressed(boolean value, boolean pressed) {
super.setCheckPressed(value, pressed);
if (radialProgress.swapBackground(getDrawableForCurrentState())) {
invalidate();
}
seekBarWaveform.setSelected(isDrawSelectedBackground());
}
@Override
@ -358,6 +431,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
if (radialProgress.swapBackground(getDrawableForCurrentState())) {
invalidate();
}
seekBarWaveform.setSelected(isDrawSelectedBackground());
}
@Override
@ -366,12 +440,29 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
if (radialProgress.swapBackground(getDrawableForCurrentState())) {
invalidate();
}
seekBarWaveform.setSelected(isDrawSelectedBackground());
}
private Drawable getDrawableForCurrentState() {
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
protected void onDraw(Canvas canvas) {
if (currentMessageObject == null) {
@ -381,8 +472,13 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
super.onDraw(canvas);
canvas.save();
canvas.translate(seekBarX, seekBarY);
seekBar.draw(canvas);
if (hasWaveform) {
canvas.translate(seekBarX + AndroidUtilities.dp(13), seekBarY);
seekBarWaveform.draw(canvas);
} else {
canvas.translate(seekBarX, seekBarY);
seekBar.draw(canvas);
}
canvas.restore();
radialProgress.setProgressColor(currentMessageObject.isOutOwner() ? 0xff87bf78 : (isDrawSelectedBackground() ? 0xff83b2c2 : 0xffa2b5c7));
@ -396,7 +492,7 @@ public class ChatAudioCell extends ChatBaseCell implements SeekBar.SeekBarDelega
canvas.restore();
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 org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ContactsController;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController;
@ -47,8 +48,8 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
public interface ChatBaseCellDelegate {
void didPressedUserAvatar(ChatBaseCell cell, TLRPC.User user);
void didPressedViaBot(ChatBaseCell cell, TLRPC.User user);
void didPressedChannelAvatar(ChatBaseCell cell, TLRPC.Chat chat);
void didPressedViaBot(ChatBaseCell cell, String username);
void didPressedChannelAvatar(ChatBaseCell cell, TLRPC.Chat chat, int postId);
void didPressedCancelSendButton(ChatBaseCell cell);
void didLongPressed(ChatBaseCell cell);
void didPressReplyMessage(ChatBaseCell cell, int id);
@ -78,6 +79,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
protected MessageObject currentMessageObject;
private int viaWidth;
private int viaNameWidth;
protected int availableTimeWidth;
private static TextPaint timePaint;
private static TextPaint namePaint;
@ -110,7 +112,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
private boolean replyPressed;
private TLRPC.FileLocation currentReplyPhoto;
private boolean drawShareButton;
protected boolean drawShareButton;
private boolean sharePressed;
private int shareStartX;
private int shareStartY;
@ -255,10 +257,12 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
TLRPC.User newUser = null;
TLRPC.Chat newChat = null;
if (currentMessageObject.messageOwner.from_id > 0) {
if (currentMessageObject.isFromUser()) {
newUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id);
} else if (currentMessageObject.messageOwner.from_id < 0) {
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;
@ -312,12 +316,52 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
}
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));
if ((messageObject.messageOwner.flags & TLRPC.MESSAGE_FLAG_HAS_VIEWS) != 0) {
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) {
@ -329,7 +373,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
isCheckPressed = true;
isAvatarVisible = false;
wasLayout = false;
drawShareButton = false;
drawShareButton = checkNeedDrawShareButton(messageObject);
replyNameLayout = null;
replyTextLayout = null;
replyNameWidth = 0;
@ -351,15 +395,15 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
}
}
if (messageObject.messageOwner.from_id > 0) {
currentUser = MessagesController.getInstance().getUser(messageObject.messageOwner.from_id);
} else if (messageObject.messageOwner.from_id < 0) {
currentChat = MessagesController.getInstance().getChat(-messageObject.messageOwner.from_id);
if (messageObject.messageOwner.to_id.channel_id != 0 && (messageObject.messageOwner.reply_to_msg_id == 0 || messageObject.type != 13)) {
drawShareButton = true;
}
if (currentMessageObject.isFromUser()) {
currentUser = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id);
} else if (currentMessageObject.messageOwner.from_id < 0) {
currentChat = MessagesController.getInstance().getChat(-currentMessageObject.messageOwner.from_id);
} else if (currentMessageObject.messageOwner.post) {
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;
if (currentUser != 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);
}
currentTimeString = LocaleController.getInstance().formatterDay.format((long) (messageObject.messageOwner.date) * 1000);
timeTextWidth = timeWidth = (int)Math.ceil(timePaint.measureText(currentTimeString));
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);
}
measureTime(messageObject);
namesOffset = 0;
@ -402,10 +441,14 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
viaWidth = (int) Math.ceil(forwardNamePaint.measureText(viaString));
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 viaBot = messageObject.messageOwner.fwd_from_id == null && currentViaBotUser != null;
boolean viaBot = messageObject.messageOwner.fwd_from == null && viaUsername != null;
if (authorName || viaBot) {
drawName = true;
nameWidth = getMaxNameWidth();
@ -413,7 +456,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
nameWidth = AndroidUtilities.dp(100);
}
if (authorName || !currentMessageObject.isOutOwner()) {
if (authorName) {
if (currentUser != null) {
currentNameString = UserObject.getUserName(currentUser);
} else if (currentChat != null) {
@ -432,12 +475,12 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
viaNameWidth += AndroidUtilities.dp(4);
}
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(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), nameStringFinal.length() + 5, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
nameStringFinal = stringBuilder;
} 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(AndroidUtilities.getTypeface("fonts/rmedium.ttf"), 0, currentMessageObject.isOutOwner() ? 0xff4a923c : 0xff006fc8), 4, stringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
nameStringFinal = stringBuilder;
@ -462,19 +505,24 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
}
if (drawForwardedName && messageObject.isForwarded()) {
if (messageObject.messageOwner.fwd_from_id instanceof TLRPC.TL_peerChannel) {
currentForwardChannel = MessagesController.getInstance().getChat(messageObject.messageOwner.fwd_from_id.channel_id);
currentForwardUser = null;
} else if (messageObject.messageOwner.fwd_from_id instanceof TLRPC.TL_peerUser) {
currentForwardChannel = null;
currentForwardUser = MessagesController.getInstance().getUser(messageObject.messageOwner.fwd_from_id.user_id);
currentForwardUser = null;
currentForwardChannel = null;
if (messageObject.messageOwner.fwd_from.channel_id != 0) {
currentForwardChannel = MessagesController.getInstance().getChat(messageObject.messageOwner.fwd_from.channel_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) {
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);
} else {
currentForwardNameString = currentForwardChannel.title;
}
forwardedNameWidth = getMaxNameWidth();
@ -537,7 +585,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
if (messageObject.isOutOwner()) {
maxWidth = width - backgroundWidth - AndroidUtilities.dp(60);
} 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 {
maxWidth = getMaxNameWidth() - AndroidUtilities.dp(22);
@ -550,7 +598,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
CharSequence stringFinalText = null;
if (messageObject.replyMessageObject != null) {
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);
needReplyImage = false;
} else {
@ -561,16 +609,21 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
}
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);
if (user != null) {
name = UserObject.getUserName(user);
}
} else {
} else if (messageObject.replyMessageObject.messageOwner.from_id < 0) {
TLRPC.Chat chat = MessagesController.getInstance().getChat(-messageObject.replyMessageObject.messageOwner.from_id);
if (chat != null) {
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) {
@ -666,7 +719,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
if (currentUser != null) {
delegate.didPressedUserAvatar(this, currentUser);
} else if (currentChat != null) {
delegate.didPressedChannelAvatar(this, currentChat);
delegate.didPressedChannelAvatar(this, currentChat, 0);
}
}
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
@ -681,10 +734,10 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
forwardNamePressed = false;
playSoundEffect(SoundEffectConstants.CLICK);
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);
} else {
delegate.didPressedChannelAvatar(this, currentForwardChannel);
}
}
} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
@ -699,7 +752,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
forwardBotPressed = false;
playSoundEffect(SoundEffectConstants.CLICK);
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) {
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);
if (!media) {
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 {
timeX = layoutWidth - timeWidth - AndroidUtilities.dp(38.5f);
}
} else {
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 {
timeX = layoutWidth - timeWidth - AndroidUtilities.dp(42.0f);
}
@ -863,7 +916,7 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
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));
} else {
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);
}
} else {
Drawable countDrawable = ResourceLoader.viewsMediaCountDrawable[isDrawSelectedBackground() ? 1 : 0];
Drawable countDrawable = ResourceLoader.viewsMediaCountDrawable;
setDrawableBounds(countDrawable, timeX, layoutHeight - AndroidUtilities.dp(10) - timeLayout.getHeight());
countDrawable.draw(canvas);
@ -1047,8 +1100,8 @@ public class ChatBaseCell extends BaseCell implements MediaController.FileDownlo
}
} else {
if (!currentMessageObject.isOutOwner()) {
setDrawableBounds(ResourceLoader.viewsCountDrawable, timeX, layoutHeight - AndroidUtilities.dp(4.5f) - timeLayout.getHeight());
ResourceLoader.viewsCountDrawable.draw(canvas);
setDrawableBounds(ResourceLoader.viewsCountDrawable[isDrawSelectedBackground() ? 1 : 0], timeX, layoutHeight - AndroidUtilities.dp(4.5f) - timeLayout.getHeight());
ResourceLoader.viewsCountDrawable[isDrawSelectedBackground() ? 1 : 0].draw(canvas);
} else {
setDrawableBounds(ResourceLoader.viewsOutCountDrawable, timeX, layoutHeight - AndroidUtilities.dp(4.5f) - timeLayout.getHeight());
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()) {
avatarPressed = 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;
result = true;
}
@ -196,7 +196,20 @@ public class ChatContactCell extends ChatBaseCell {
}
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);
if (currentNameString.length() == 0) {
currentNameString = phone;
}
int nameWidth = Math.min((int) Math.ceil(namePaint.measureText(currentNameString)), maxWidth);
if (maxWidth < 0) {
maxWidth = AndroidUtilities.dp(100);
@ -210,15 +223,7 @@ public class ChatContactCell extends ChatBaseCell {
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);
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);
@ -230,6 +235,7 @@ public class ChatContactCell extends ChatBaseCell {
namesWidth = Math.max(nameWidth, phoneWidth);
backgroundWidth = AndroidUtilities.dp(77 + (drawAddButton ? 42 : 0)) + namesWidth;
availableTimeWidth = backgroundWidth - AndroidUtilities.dp(29);
super.setMessageObject(messageObject);
}
@ -237,7 +243,7 @@ public class ChatContactCell extends ChatBaseCell {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(71) + namesOffset);
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(75) + namesOffset);
}
@Override
@ -253,7 +259,7 @@ public class ChatContactCell extends ChatBaseCell {
if (currentMessageObject.isOutOwner()) {
x = layoutWidth - backgroundWidth + AndroidUtilities.dp(8);
} else {
if (isChat && currentMessageObject.messageOwner.from_id > 0) {
if (isChat && currentMessageObject.isFromUser()) {
x = AndroidUtilities.dp(69);
} else {
x = AndroidUtilities.dp(16);

View file

@ -21,6 +21,7 @@ import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.MotionEvent;
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.StaticLayoutEx;
import org.telegram.ui.Components.URLSpanBotCommand;
import org.telegram.ui.Components.URLSpanNoUnderline;
import org.telegram.ui.PhotoViewer;
import org.telegram.messenger.ImageReceiver;
@ -417,7 +419,7 @@ public class ChatMediaCell extends ChatBaseCell {
} else if (currentMessageObject.type == 9) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, false, false);
} else if (currentMessageObject.type == 3) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.video, true);
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
}
buttonState = 1;
radialProgress.setBackground(getDrawableForCurrentState(), true, animated);
@ -431,10 +433,8 @@ public class ChatMediaCell extends ChatBaseCell {
cancelLoading = true;
if (currentMessageObject.type == 1 || currentMessageObject.type == 8) {
photoImage.cancelLoadImage();
} else if (currentMessageObject.type == 9) {
} else if (currentMessageObject.type == 9 || currentMessageObject.type == 3) {
FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.document);
} else if (currentMessageObject.type == 3) {
FileLoader.getInstance().cancelLoadFile(currentMessageObject.messageOwner.media.video);
}
buttonState = 0;
radialProgress.setBackground(getDrawableForCurrentState(), false, animated);
@ -475,12 +475,23 @@ public class ChatMediaCell extends ChatBaseCell {
return false;
}
@Override
protected void onLongPress() {
if (pressedLink instanceof URLSpanNoUnderline) {
} else if (pressedLink instanceof URLSpan) {
delegate.didPressUrl(currentMessageObject, pressedLink, true);
return;
}
super.onLongPress();
}
@Override
public void setMessageObject(MessageObject messageObject) {
boolean messageChanged = currentMessageObject != messageObject;
boolean dataChanged = currentMessageObject == messageObject && (isUserDataChanged() || photoNotSet);
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;
cancelLoading = false;
additionHeight = 0;
@ -510,14 +521,24 @@ public class ChatMediaCell extends ChatBaseCell {
} else {
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)) {
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) {
nameWidth = Math.min(maxWidth, (int) Math.ceil(nameLayout.getLineWidth(0)));
nameOffsetX = (int) Math.ceil(-nameLayout.getLineLeft(0));
int maxLineWidth = 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 {
nameWidth = maxWidth;
nameOffsetX = 0;
}
}
@ -528,7 +549,14 @@ public class ChatMediaCell extends ChatBaseCell {
infoOffset = 0;
infoWidth = Math.min(maxWidth, (int) Math.ceil(infoPaint.measureText(currentInfoString)));
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) {
String str = AndroidUtilities.formatFileSize(messageObject.messageOwner.media.document.size);
@ -541,10 +569,17 @@ public class ChatMediaCell extends ChatBaseCell {
nameLayout = null;
currentNameString = null;
} 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 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)) {
currentInfoString = str;
infoOffset = ResourceLoader.videoIconDrawable.getIntrinsicWidth() + AndroidUtilities.dp(4);
@ -560,10 +595,11 @@ public class ChatMediaCell extends ChatBaseCell {
nameLayout = null;
updateSecretTimeText(messageObject);
}
if (messageObject.type == 9) { //doc
if (messageObject.type == 9) {
photoWidth = 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());
photoImage.setNeedsQualityThumb(true);
photoImage.setShouldGenerateQualityThumb(true);
@ -589,6 +625,7 @@ public class ChatMediaCell extends ChatBaseCell {
}
media = false;
availableTimeWidth = maxWidth - AndroidUtilities.dp(7);
measureTime(messageObject);
photoWidth = AndroidUtilities.dp(86);
photoHeight = AndroidUtilities.dp(86);
@ -604,6 +641,7 @@ public class ChatMediaCell extends ChatBaseCell {
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);
} else {
availableTimeWidth = AndroidUtilities.dp(200 - 14);
photoWidth = AndroidUtilities.dp(200);
photoHeight = AndroidUtilities.dp(100);
backgroundWidth = photoWidth + AndroidUtilities.dp(12);
@ -643,6 +681,7 @@ public class ChatMediaCell extends ChatBaseCell {
photoHeight *= maxWidth / photoWidth;
photoWidth = (int) maxWidth;
}
availableTimeWidth = photoWidth - AndroidUtilities.dp(14);
backgroundWidth = photoWidth + AndroidUtilities.dp(12);
currentPhotoObjectThumb = FileLoader.getClosestPhotoSizeWithSize(messageObject.photoThumbs, 80);
photoImage.setNeedsQualityThumb(false);
@ -667,10 +706,11 @@ public class ChatMediaCell extends ChatBaseCell {
messageObject.messageOwner.media.document.size, "webp", true);
}
} else {
int maxPhotoWidth;
if (AndroidUtilities.isTablet()) {
photoWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.7f);
maxPhotoWidth = photoWidth = (int) (AndroidUtilities.getMinTabletSide() * 0.7f);
} 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);
@ -767,6 +807,7 @@ public class ChatMediaCell extends ChatBaseCell {
w = h = AndroidUtilities.dp(100);
}
availableTimeWidth = maxPhotoWidth - AndroidUtilities.dp(14);
measureTime(messageObject);
int timeWidthTotal = timeWidth + AndroidUtilities.dp(14 + (messageObject.isOutOwner() ? 20 : 0));
if (w < timeWidthTotal) {
@ -1022,7 +1063,7 @@ public class ChatMediaCell extends ChatBaseCell {
x = layoutWidth - backgroundWidth + AndroidUtilities.dp(6);
}
} else {
if (isChat && currentMessageObject.messageOwner.from_id > 0) {
if (isChat && currentMessageObject.isFromUser()) {
x = AndroidUtilities.dp(67);
} else {
x = AndroidUtilities.dp(15);
@ -1218,11 +1259,15 @@ public class ChatMediaCell extends ChatBaseCell {
nameLayout.draw(canvas);
canvas.restore();
if (infoLayout != null) {
canvas.save();
canvas.translate(photoImage.getImageX() + photoImage.getImageWidth() + AndroidUtilities.dp(10), photoImage.getImageY() + AndroidUtilities.dp(30));
infoLayout.draw(canvas);
canvas.restore();
try {
if (infoLayout != null) {
canvas.save();
canvas.translate(photoImage.getImageX() + photoImage.getImageWidth() + AndroidUtilities.dp(10), photoImage.getImageY() + nameLayout.getLineBottom(nameLayout.getLineCount() - 1) + AndroidUtilities.dp(10));
infoLayout.draw(canvas);
canvas.restore();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
}

View file

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

View file

@ -68,7 +68,7 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
super(context);
seekBar = new SeekBar(context);
seekBar.delegate = this;
seekBar.setDelegate(this);
radialProgress = new RadialProgress(this);
drawForwardedName = false;
@ -194,7 +194,8 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
int duration = 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) {
duration = attribute.duration;
break;
@ -323,7 +324,7 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
buttonX = layoutWidth - backgroundWidth + AndroidUtilities.dp(13);
timeX = layoutWidth - backgroundWidth + AndroidUtilities.dp(63);
} else {
if (isChat && currentMessageObject.messageOwner.from_id > 0) {
if (isChat && currentMessageObject.isFromUser()) {
seekBarX = AndroidUtilities.dp(113);
buttonX = AndroidUtilities.dp(74);
timeX = AndroidUtilities.dp(124);
@ -348,9 +349,9 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
boolean dataChanged = currentMessageObject == messageObject && isUserDataChanged();
if (currentMessageObject != messageObject || dataChanged) {
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 {
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()) {
@ -375,6 +376,16 @@ public class ChatMusicCell extends ChatBaseCell implements SeekBar.SeekBarDelega
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);
}
updateButtonState(dataChanged);

View file

@ -434,10 +434,10 @@ public class ContextLinkCell extends View implements MediaController.FileDownloa
fileName = FileLoader.getAttachFileName(result.document);
cacheFile = FileLoader.getPathToAttach(result.document);
} 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);
} 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);
}
} else if (gif != null) {

View file

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

View file

@ -16,6 +16,7 @@ import android.widget.LinearLayout;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.R;
import org.telegram.messenger.UserObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Components.AvatarDrawable;
@ -34,6 +35,8 @@ public class MentionCell extends LinearLayout {
setOrientation(HORIZONTAL);
setBackgroundResource(R.drawable.list_selector);
avatarDrawable = new AvatarDrawable();
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.RadioButton;
public class LastSeenRadioCell extends FrameLayout {
public class RadioCell extends FrameLayout {
private TextView textView;
private RadioButton radioButton;
private static Paint paint;
private boolean needDivider;
public LastSeenRadioCell(Context context) {
public RadioCell(Context context) {
super(context);
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) {
int idx;
String name = FileLoader.getDocumentFileName(document.messageOwner.media.document);
if (name.length() == 0) {
if (document.isMusic()) {
name = document.getMusicAuthor() + " - " + document.getMusicTitle();
}
}
placeholderImabeView.setVisibility(VISIBLE);
extTextView.setVisibility(VISIBLE);
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) {
delegate.needOpenWebView(webPage);
} else {
Uri uri = Uri.parse(links.get(pressedLink));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getContext().getPackageName());
getContext().startActivity(intent);
AndroidUtilities.openUrl(getContext(), links.get(pressedLink));
}
} catch (Exception e) {
FileLog.e("tmessages", e);

View file

@ -226,14 +226,21 @@ public class SharedPhotoVideoCell extends FrameLayoutFixed {
PhotoVideoView photoVideoView = photoVideoViews[a];
photoVideoView.imageView.getImageReceiver().setParentMessageObject(messageObject);
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);
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 seconds = duration - minutes * 60;
photoVideoView.videoTextView.setText(String.format("%d:%02d", minutes, seconds));
if (messageObject.messageOwner.media.video.thumb != null) {
TLRPC.FileLocation location = messageObject.messageOwner.media.video.thumb.location;
if (messageObject.messageOwner.media.document.thumb != null) {
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);
} else {
photoVideoView.imageView.setImageResource(R.drawable.photo_placeholder_in);

View file

@ -9,7 +9,11 @@
package org.telegram.ui.Cells;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.R;
@ -21,6 +25,12 @@ import org.telegram.ui.Components.LayoutHelper;
public class StickerCell extends FrameLayoutFixed {
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) {
super(context);
@ -48,6 +58,7 @@ public class StickerCell extends FrameLayoutFixed {
if (document != null && document.thumb != null) {
imageView.setImage(document.thumb.location, null, "webp", null);
}
sticker = document;
if (side == -1) {
setBackgroundResource(R.drawable.stickers_back_left);
setPadding(AndroidUtilities.dp(7), 0, 0, 0);
@ -65,4 +76,46 @@ public class StickerCell extends FrameLayoutFixed {
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 float scale;
private long time = 0;
private AccelerateInterpolator interpolator = new AccelerateInterpolator(0.5f);
private static AccelerateInterpolator interpolator = new AccelerateInterpolator(0.5f);
public StickerEmojiCell(Context context) {
super(context);
@ -63,7 +63,8 @@ public class StickerEmojiCell extends FrameLayout {
if (showEmoji) {
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.alt != null && attribute.alt.length() > 0) {
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();
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.setMessage(LocaleController.getString("Loading", R.string.Loading));
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.BaseFragment;
import org.telegram.ui.Cells.ShadowSectionCell;
import org.telegram.ui.Cells.TextCheckCell;
import org.telegram.ui.Cells.TextInfoPrivacyCell;
import org.telegram.ui.Cells.TextSettingsCell;
import org.telegram.ui.Components.AvatarDrawable;
@ -81,6 +82,7 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
private TLRPC.InputFile uploadedAvatar;
private boolean wasPrivate;
private boolean privateAlertShown;
private boolean signMessages;
private boolean createAfterUpload;
private boolean donePressed;
@ -133,6 +135,7 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
avatarUpdater.parentFragment = this;
avatarUpdater.delegate = this;
allowComments = !currentChat.broadcast;
signMessages = currentChat.signatures;
return super.onFragmentCreate();
}
@ -229,6 +232,10 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
MessagesController.getInstance().updateChannelUserName(chatId, userNameTextView.getText().toString());
}
}
if (signMessages != currentChat.signatures) {
currentChat.signatures = true;
MessagesController.getInstance().toogleChannelSignatures(chatId, signMessages);
}
if (uploadedAvatar != null) {
MessagesController.getInstance().changeChatAvatar(chatId, uploadedAvatar);
} 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);
if (currentChat.megagroup) {
infoCell.setText(LocaleController.getString("DescriptionInfoMega", R.string.DescriptionInfoMega));
infoCell.setBackgroundResource(currentChat.creator ? R.drawable.greydivider : R.drawable.greydivider_bottom);
} else {
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));
if (!currentChat.megagroup) {
if (/*BuildVars.DEBUG_VERSION && currentChat.megagroup && currentChat.creator || */!currentChat.megagroup) {
linearLayout2 = new LinearLayout(context);
linearLayout2.setOrientation(LinearLayout.VERTICAL);
linearLayout2.setBackgroundColor(0xffffffff);
@ -443,7 +451,11 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
if (wasPrivate && hasFocus && !privateAlertShown) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
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);
showDialog(builder.create());
}
@ -476,11 +488,14 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
infoCell = new TextInfoPrivacyCell(context);
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));
}
/*frameLayout = new FrameLayoutFixed(context);
frameLayout.setBackgroundColor(0xffffffff);
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);
linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));*/
frameLayout = new FrameLayoutFixed(context);
frameLayout.setBackgroundColor(0xffffffff);
linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
if (!currentChat.megagroup && 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));
TextCheckCell textCell = new TextCheckCell(context);
textCell.setBackgroundResource(R.drawable.list_selector);
textCell.setTextAndCheck(LocaleController.getString("ChannelSignMessages", R.string.ChannelSignMessages), signMessages, false);
frameLayout.addView(textCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
textCell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signMessages = !signMessages;
((TextCheckCell) v).setChecked(signMessages);
}
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));
infoCell = new TextInfoPrivacyCell(context);
infoCell.setBackgroundResource(R.drawable.greydivider);
infoCell.setText(LocaleController.getString("ChannelSignMessagesInfo", R.string.ChannelSignMessagesInfo));
linearLayout.addView(infoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
}
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.setSelection(nameTextView.length());
@ -655,11 +695,20 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
for (int a = 0; a < name.length(); a++) {
char ch = name.charAt(a);
if (a == 0 && ch >= '0' && ch <= '9') {
if (alert) {
showErrorAlert(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber));
if (currentChat.megagroup) {
if (alert) {
//showErrorAlert(LocaleController.getString("LinkInvalidStartNumberMega", R.string.LinkInvalidStartNumberMega));
} else {
//checkTextView.setText(LocaleController.getString("LinkInvalidStartNumberMega", R.string.LinkInvalidStartNumberMega));
checkTextView.setTextColor(0xffcf3030);
}
} else {
checkTextView.setText(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber));
checkTextView.setTextColor(0xffcf3030);
if (alert) {
showErrorAlert(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber));
} else {
checkTextView.setText(LocaleController.getString("LinkInvalidStartNumber", R.string.LinkInvalidStartNumber));
checkTextView.setTextColor(0xffcf3030);
}
}
return false;
}
@ -675,11 +724,20 @@ public class ChannelEditActivity extends BaseFragment implements AvatarUpdater.A
}
}
if (name == null || name.length() < 5) {
if (alert) {
showErrorAlert(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort));
if (currentChat.megagroup) {
if (alert) {
//showErrorAlert(LocaleController.getString("LinkInvalidShortMega", R.string.LinkInvalidShortMega));
} else {
//checkTextView.setText(LocaleController.getString("LinkInvalidShortMega", R.string.LinkInvalidShortMega));
checkTextView.setTextColor(0xffcf3030);
}
} else {
checkTextView.setText(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort));
checkTextView.setTextColor(0xffcf3030);
if (alert) {
showErrorAlert(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort));
} else {
checkTextView.setText(LocaleController.getString("LinkInvalidShort", R.string.LinkInvalidShort));
checkTextView.setTextColor(0xffcf3030);
}
}
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.BaseFragment;
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.TextCell;
import org.telegram.ui.Cells.TextInfoPrivacyCell;
import org.telegram.ui.Cells.TextSettingsCell;
import org.telegram.ui.Cells.UserCell;
@ -78,7 +81,7 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
if (type == 0) {
participantsStartRow = 0;
} else if (type == 1) {
participantsStartRow = isAdmin ? 2 : 0;
participantsStartRow = isAdmin && isMegagroup ? 4 : 0;
} else if (type == 2) {
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));
ListView listView = new ListView(context);
final ListView listView = new ListView(context);
listView.setEmptyView(emptyView);
listView.setDivider(null);
listView.setDividerHeight(0);
@ -173,7 +176,33 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
} else if (type == 1) {
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();
args.putBoolean("onlyUsers", true);
args.putBoolean("destroyAfterSelect", true);
@ -192,6 +221,7 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
}
});
presentFragment(fragment);
return;
}
}
}
@ -243,16 +273,18 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
final TLRPC.Updates updates = (TLRPC.Updates) response;
MessagesController.getInstance().processUpdates(updates, false);
if (!updates.chats.isEmpty()) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
TLRPC.Chat chat = updates.chats.get(0);
MessagesController.getInstance().loadFullChat(chat.id, 0, true);
}
}, 1000);
if (response != null) {
final TLRPC.Updates updates = (TLRPC.Updates) response;
MessagesController.getInstance().processUpdates(updates, false);
if (!updates.chats.isEmpty()) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
TLRPC.Chat chat = updates.chats.get(0);
MessagesController.getInstance().loadFullChat(chat.id, 0, true);
}
}, 1000);
}
}
}
});
@ -487,12 +519,12 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
}
}
} else if (type == 1) {
if (isAdmin) {
if (i == 0) {
return true;
} else if (i == 1) {
return false;
}
if (i == participantsStartRow + participants.size()) {
return isAdmin;
} else if (i == participantsStartRow + participants.size() + 1) {
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();
@ -502,6 +534,8 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
public int getCount() {
if (participants.isEmpty() && type == 0 || loadingUsers && !firstLoaded) {
return 0;
} else if (type == 1) {
return participants.size() + (isAdmin ? 2 : 1) + (isAdmin && isMegagroup ? 4 : 0);
}
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)));
view.setBackgroundResource(R.drawable.greydivider_bottom);
} else if (type == 1) {
if (i == 1 && isAdmin) {
if (isAdmin) {
if (isMegagroup) {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("MegaAdminsInfo", R.string.MegaAdminsInfo));
view.setBackgroundResource(R.drawable.greydivider_bottom);
} else {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("ChannelAdminsInfo", R.string.ChannelAdminsInfo));
view.setBackgroundResource(R.drawable.greydivider_bottom);
}
view.setBackgroundResource(R.drawable.greydivider);
} else {
((TextInfoPrivacyCell) view).setText("");
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);
}
} 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) {
if (view == null) {
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;
}
@ -608,9 +669,18 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
public int getItemViewType(int i) {
if (type == 1) {
if (isAdmin) {
if (i == 0) {
return 2;
} else if (i == 1) {
if (isMegagroup) {
if (i == 0) {
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;
}
}
@ -639,12 +709,12 @@ public class ChannelUsersActivity extends BaseFragment implements NotificationCe
@Override
public int getViewTypeCount() {
return 4;
return 7;
}
@Override
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.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.MessagesController;
import org.telegram.messenger.MessagesStorage;
@ -97,13 +94,7 @@ public class AlertsCreator {
builder.setNegativeButton(LocaleController.getString("MoreInfo", R.string.MoreInfo), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
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);
}
AndroidUtilities.openUrl(fragment.getParentActivity(), LocaleController.getString("NobodyLikesSpamUrl", R.string.NobodyLikesSpamUrl));
}
});
break;
@ -144,6 +135,16 @@ public class AlertsCreator {
builder.setMessage(LocaleController.getString("GroupUserCantBot", R.string.GroupUserCantBot));
}
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);
fragment.showDialog(builder.create(), true);

View file

@ -21,7 +21,9 @@ import android.media.AudioManager;
import android.os.Build;
import android.os.PowerManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
@ -42,6 +44,7 @@ import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject;
@ -50,6 +53,7 @@ import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaController;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationsController;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.NotificationCenter;
@ -66,6 +70,7 @@ import org.telegram.messenger.AnimationCompat.ViewProxy;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.ui.StickersActivity;
import java.io.File;
import java.util.Locale;
public class ChatActivityEnterView extends FrameLayoutFixed implements NotificationCenter.NotificationCenterDelegate, SizeNotifierFrameLayout.SizeNotifierFrameLayoutDelegate {
@ -78,6 +83,64 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
void onAttachButtonShow();
void onWindowSizeChanged(int size);
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 {
@ -137,16 +200,20 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (captionLayout != null && userNameLength == length()) {
Paint paint = getPaint();
int oldColor = getPaint().getColor();
paint.setColor(0xffb2b2b2);
canvas.save();
canvas.translate(xOffset, yOffset);
captionLayout.draw(canvas);
canvas.restore();
paint.setColor(oldColor);
try {
super.onDraw(canvas);
if (captionLayout != null && userNameLength == length()) {
Paint paint = getPaint();
int oldColor = getPaint().getColor();
paint.setColor(0xffb2b2b2);
canvas.save();
canvas.translate(xOffset, yOffset);
captionLayout.draw(canvas);
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 ImageView audioSendButton;
private FrameLayout recordPanel;
private FrameLayout recordedAudioPanel;
private SeekBarWaveformView recordedAudioSeekBar;
private ImageView recordedAudioPlayButton;
private TextView recordedAudioTimeTextView;
private LinearLayout slideText;
private RecordDot recordDot;
private SizeNotifierFrameLayout sizeNotifierLayout;
private LinearLayout attachButton;
private ImageView botButton;
private LinearLayout textFieldContainer;
private FrameLayout sendButtonContainer;
private View topView;
private PopupWindow botKeyboardPopup;
private BotKeyboardView botKeyboardView;
private ImageView asAdminButton;
private ImageView notifyButton;
private RecordCircle recordCircle;
private ContextProgressView contextProgressView;
private MessageObject editingMessageObject;
private boolean editingCaption;
private int currentPopupContentType = -1;
private boolean silent;
private boolean canWriteToChannel;
private boolean isAsAdmin;
private boolean adminModeAvailable;
@ -228,6 +307,10 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
private boolean messageWebPageSearch = true;
private ChatActivityEnterViewDelegate delegate;
private TLRPC.TL_document audioToSend;
private String audioToSendPath;
private MessageObject audioToSendMessageObject;
private float topViewAnimation;
private boolean topViewShowed;
private boolean needShowTopView;
@ -270,16 +353,16 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
@Override
protected void onDraw(Canvas canvas) {
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);
if (!isIncr) {
alpha -= dt / 200.0f;
alpha -= dt / 400.0f;
if (alpha <= 0) {
alpha = 0;
isIncr = true;
}
} else {
alpha += dt / 200.0f;
alpha += dt / 400.0f;
if (alpha >= 1) {
alpha = 1;
isIncr = false;
@ -379,6 +462,8 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidSent);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioRouteChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioDidReset);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.audioProgressDidChanged);
parentActivity = context;
parentFragment = fragment;
sizeNotifierLayout = parent;
@ -491,7 +576,9 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
if (count > 2 || charSequence == null || charSequence.length() == 0) {
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) {
processChange = true;
@ -584,8 +671,88 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
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.setVisibility(GONE);
recordPanel.setBackgroundColor(0xffffffff);
@ -595,7 +762,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
slideText.setOrientation(LinearLayout.HORIZONTAL);
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);
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);
linearLayout.addView(recordTimeText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 6, 0, 0, 0));
FrameLayout frameLayout1 = new FrameLayout(context);
textFieldContainer.addView(frameLayout1, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM));
sendButtonContainer = new FrameLayout(context);
textFieldContainer.addView(sendButtonContainer, LayoutHelper.createLinear(48, 48, Gravity.BOTTOM));
audioSendButton = new ImageView(context);
audioSendButton.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
@ -629,7 +796,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
audioSendButton.setBackgroundColor(0xffffffff);
audioSendButton.setSoundEffectsEnabled(false);
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() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
@ -664,13 +831,13 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
audioSendButton.getParent().requestDisallowInterceptTouchEvent(true);
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP || motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
startedDraggingX = -1;
MediaController.getInstance().stopRecording(true);
MediaController.getInstance().stopRecording(1);
recordingAudio = false;
updateAudioRecordIntefrace();
} else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE && recordingAudio) {
float x = motionEvent.getX();
if (x < -distCanMove) {
MediaController.getInstance().stopRecording(false);
MediaController.getInstance().stopRecording(0);
recordingAudio = false;
updateAudioRecordIntefrace();
}
@ -727,7 +894,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
ViewProxy.setScaleY(sendButton, 0.1f);
ViewProxy.setAlpha(sendButton, 0.0f);
sendButton.clearAnimation();
frameLayout1.addView(sendButton, LayoutHelper.createFrame(48, 48));
sendButtonContainer.addView(sendButton, LayoutHelper.createFrame(48, 48));
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
@ -787,6 +954,13 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
}
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;
allowGifs = value2;
}
@ -824,7 +998,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
public void onAnimationEnd(Object animation) {
if (currentTopViewAnimation != null && currentTopViewAnimation.equals(animation)) {
setTopViewAnimation(1.0f);
if (!forceShowSendButton || openKeyboard) {
if (recordedAudioPanel.getVisibility() != VISIBLE && (!forceShowSendButton || openKeyboard)) {
openKeyboard();
}
currentTopViewAnimation = null;
@ -835,7 +1009,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
currentTopViewAnimation.start();
} else {
setTopViewAnimation(1.0f);
if (!forceShowSendButton || openKeyboard) {
if (recordedAudioPanel.getVisibility() != VISIBLE && (!forceShowSendButton || openKeyboard)) {
openKeyboard();
}
}
@ -925,6 +1099,11 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.audioDidSent);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.emojiDidLoaded);
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) {
try {
mWakeLock.release();
@ -961,8 +1140,10 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
dialog_id = id;
if ((int) dialog_id < 0) {
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;
adminModeAvailable = isAsAdmin && !currentChat.broadcast;
canWriteToChannel = isAsAdmin;
if (adminModeAvailable) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
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);
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;
}
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 {
messageEditText.setHint(LocaleController.getString("TypeMessage", R.string.TypeMessage));
}
@ -1013,6 +1203,26 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
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() {
if (parentFragment != null) {
String action;
@ -1031,6 +1241,19 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
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();
if (processSendingText(message)) {
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) {
text = getTrimmedString(text);
if (text.length() != 0) {
@ -1073,8 +1303,11 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
}
private void checkSendButton(final boolean animated) {
if (editingMessageObject != null) {
return;
}
String message = getTrimmedString(messageEditText.getText().toString());
if (message.length() > 0 || forceShowSendButton) {
if (message.length() > 0 || forceShowSendButton || audioToSend != null) {
if (audioSendButton.getVisibility() == View.VISIBLE) {
if (animated) {
if (runningAnimationType == 1) {
@ -1109,7 +1342,9 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
updateFieldRight(0);
delegate.onAttachButtonHidden();
if (delegate != null) {
delegate.onAttachButtonHidden();
}
}
sendButton.setVisibility(View.VISIBLE);
@ -1152,7 +1387,9 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
if (attachButton != null) {
attachButton.setVisibility(View.GONE);
attachButton.clearAnimation();
delegate.onAttachButtonHidden();
if (delegate != null) {
delegate.onAttachButtonHidden();
}
updateFieldRight(0);
}
}
@ -1234,19 +1471,19 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
}
private void updateFieldRight(int attachVisible) {
if (messageEditText == null) {
if (messageEditText == null || editingMessageObject != null) {
return;
}
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) messageEditText.getLayoutParams();
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);
} else {
layoutParams.rightMargin = AndroidUtilities.dp(50);
}
} else if (attachVisible == 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);
} else {
layoutParams.rightMargin = AndroidUtilities.dp(50);
@ -1369,6 +1606,9 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
messageEditText.setText(text);
messageEditText.setSelection(messageEditText.getText().length());
ignoreTextChange = false;
if (delegate != null) {
delegate.onTextChanged(messageEditText.getText(), true);
}
if (!keyboardVisible && currentPopupContentType == -1) {
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) {
return;
}
@ -1489,7 +1788,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
botButton.setVisibility(GONE);
}
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();
}
@ -1621,7 +1920,7 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
@Override
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) {
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() {
AndroidUtilities.showKeyboard(messageEditText);
}
@ -1868,8 +2175,10 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
botKeyboardView.invalidateViews();
}
} else if (id == NotificationCenter.recordProgressChanged) {
Long time = (Long) args[0] / 1000;
String str = String.format("%02d:%02d", time / 60, time % 60);
long t = (Long) args[0];
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 (time % 5 == 0) {
MessagesController.getInstance().sendTyping(dialog_id, 1, 0);
@ -1897,14 +2206,77 @@ public class ChatActivityEnterView extends FrameLayoutFixed implements Notificat
updateAudioRecordIntefrace();
}
} else if (id == NotificationCenter.audioDidSent) {
if (delegate != null) {
delegate.onMessageSend(null);
audioToSend = (TLRPC.TL_document) args[0];
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) {
if (parentActivity != null) {
boolean frontSpeaker = (Boolean) args[0];
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("ChatGallery", R.string.ChatGallery),
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("AttachContact", R.string.AttachContact),
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 static HashMap<String, String> emojiColor = new HashMap<>();
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.TL_messages_stickerSet> stickerSets = new ArrayList<>();
private ArrayList<MediaController.SearchImage> recentImages;
@ -518,8 +518,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
private FlowLayoutManager flowLayoutManager;
private GifsAdapter gifsAdapter;
private AdapterView.OnItemClickListener stickersOnItemClickListener;
private Runnable openStickerPreviewRunnable;
private StickerEmojiCell currentStickerPreviewCell;
private EmojiColorPickerView pickerView;
private EmojiPopupWindow pickerViewPopup;
private int popupWidth;
@ -531,8 +531,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
private int gifTabBum = -2;
private boolean switchToGifTab;
private int startX;
private int startY;
private int oldWidth;
private int lastNotifyWidth;
@ -572,45 +571,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
stickersGridView = new GridView(context) {
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
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) || !((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;
boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersGridView, EmojiView.this.getMeasuredHeight());
return super.onInterceptTouchEvent(event) || result;
}
@Override
@ -633,67 +595,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
stickersGridView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (openStickerPreviewRunnable != null || StickerPreviewViewer.getInstance().isVisible()) {
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;
return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView, EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
}
});
stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
@ -702,35 +604,23 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
if (!(view instanceof StickerEmojiCell)) {
return;
}
if (openStickerPreviewRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
openStickerPreviewRunnable = null;
}
if (currentStickerPreviewCell != null) {
currentStickerPreviewCell.setScaled(false);
currentStickerPreviewCell = null;
}
StickerPreviewViewer.getInstance().reset();
StickerEmojiCell cell = (StickerEmojiCell) view;
if (cell.isDisabled()) {
return;
}
cell.disable();
TLRPC.Document document = cell.getSticker();
Integer count = stickersUseHistory.get(document.id);
if (count == null) {
count = 0;
}
if (count == 0 && stickersUseHistory.size() > 19) {
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;
}
int index = newRecentStickers.indexOf(document.id);
if (index == -1) {
newRecentStickers.add(0, document.id);
if (newRecentStickers.size() > 20) {
newRecentStickers.remove(newRecentStickers.size() - 1);
}
} else if (index != 0) {
newRecentStickers.remove(index);
newRecentStickers.add(0, document.id);
}
stickersUseHistory.put(document.id, ++count);
saveRecentStickers();
if (listener != null) {
@ -763,12 +653,6 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
break;
}
}
if (size.width == 0) {
size.width = 100;
}
if (size.height == 0) {
size.height = 100;
}
return size;
}
});
@ -821,7 +705,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
builder.show();
builder.show().setCanceledOnTouchOutside(true);
return true;
}
});
@ -1213,16 +1097,13 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
private void saveRecentStickers() {
SharedPreferences.Editor editor = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE).edit();
StringBuilder stringBuilder = new StringBuilder();
for (HashMap.Entry<Long, Integer> entry : stickersUseHistory.entrySet()) {
for (int a = 0; a < newRecentStickers.size(); a++) {
if (stringBuilder.length() != 0) {
stringBuilder.append(",");
}
stringBuilder.append(entry.getKey());
stringBuilder.append("=");
stringBuilder.append(entry.getValue());
stringBuilder.append(newRecentStickers.get(a));
}
editor.putString("stickers", stringBuilder.toString());
editor.putString("stickers2", stringBuilder.toString());
editor.commit();
}
@ -1270,43 +1151,28 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
return;
}
recentStickers.clear();
HashMap<Long, Integer> hashMap = new HashMap<>();
for (HashMap.Entry<Long, Integer> entry : stickersUseHistory.entrySet()) {
TLRPC.Document sticker = StickersQuery.getStickerById(entry.getKey());
for (int a = 0; a < newRecentStickers.size(); a++) {
TLRPC.Document sticker = StickersQuery.getStickerById(newRecentStickers.get(a));
if (sticker != null) {
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) {
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() {
if (scrollSlidingTabStrip == null) {
return;
}
recentTabBum = -2;
gifTabBum = -2;
@ -1452,7 +1318,8 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
str = preferences.getString("color", "");
if (str != null && str.length() > 0) {
String[] args = str.split(",");
for (String arg : args) {
for (int a = 0; a < args.length; a++) {
String arg = args[a];
String[] args2 = arg.split("=");
emojiColor.put(args2[0], args2[1]);
}
@ -1463,13 +1330,44 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
if (showStickers) {
try {
stickersUseHistory.clear();
newRecentStickers.clear();
str = preferences.getString("stickers", "");
if (str != null && str.length() > 0) {
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("=");
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();
@ -1518,14 +1416,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
if (StickerPreviewViewer.getInstance().isVisible()) {
StickerPreviewViewer.getInstance().close();
}
if (openStickerPreviewRunnable != null) {
AndroidUtilities.cancelRunOnUIThread(openStickerPreviewRunnable);
openStickerPreviewRunnable = null;
}
if (currentStickerPreviewCell != null) {
currentStickerPreviewCell.setScaled(false);
currentStickerPreviewCell = null;
}
StickerPreviewViewer.getInstance().reset();
}
public void setListener(Listener value) {
@ -1546,6 +1437,13 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
if (stickersGridAdapter != null) {
NotificationCenter.getInstance().addObserver(this, NotificationCenter.stickersDidLoaded);
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
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
public void onDestroy() {
if (stickersGridAdapter != null) {
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.stickersDidLoaded);
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.recentImagesDidLoaded);
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (pickerViewPopup != null && pickerViewPopup.isShowing()) {
pickerViewPopup.dismiss();
}
@ -1666,7 +1567,9 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific
int previousCount = recentImages != null ? recentImages.size() : 0;
recentImages = (ArrayList<MediaController.SearchImage>) args[1];
loadingRecent = false;
gifsAdapter.notifyDataSetChanged();
if (gifsAdapter != null) {
gifsAdapter.notifyDataSetChanged();
}
if (previousCount != recentImages.size()) {
updateStickerTabs();
}

View file

@ -13,6 +13,8 @@ import android.view.View;
import android.view.ViewGroup;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.support.widget.RecyclerView;
import java.util.ArrayList;
@ -356,11 +358,14 @@ public class FlowLayoutManager extends RecyclerView.LayoutManager {
}
preferredRowSize = getHeight() / 2.0f;
float viewPortAvailableSize = getWidth();
if (BuildVars.DEBUG_VERSION) {
FileLog.d("tmessages", "preferredRowSize = " + preferredRowSize + " width = " + viewPortAvailableSize);
}
float totalItemSize = 0;
int[] weights = new int[getItemCount()];
for (int a = 0; a < getItemCount(); a++) {
Size size = getSizeForItem(a);
Size size = sizeForItem(a);
totalItemSize += (size.width / size.height) * preferredRowSize;
weights[a] = Math.round(size.width / size.height * 100);
}
@ -377,7 +382,7 @@ public class FlowLayoutManager extends RecyclerView.LayoutManager {
float summedRatios = 0;
for (int j = i, n = i + row.size(); j < n; j++) {
Size preferredSize = getSizeForItem(j);
Size preferredSize = sizeForItem(j);
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++) {
Size preferredSize = getSizeForItem(j);
Size preferredSize = sizeForItem(j);
actualSize.width = Math.round(rowSize / summedRatios * (preferredSize.width / preferredSize.height));
actualSize.height = preferredRowSize;//Math.round(rowSize / summedRatios);
@ -503,7 +508,22 @@ public class FlowLayoutManager extends RecyclerView.LayoutManager {
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) {
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.tgnet.TLRPC;
import org.telegram.messenger.Utilities;
public class IdenticonDrawable extends Drawable {
@ -35,9 +34,7 @@ public class IdenticonDrawable extends Drawable {
public void setEncryptedChat(TLRPC.EncryptedChat encryptedChat) {
data = encryptedChat.key_hash;
if (data == null) {
byte[] sha1 = Utilities.computeSHA1(encryptedChat.auth_key);
encryptedChat.key_hash = data = new byte[16];
System.arraycopy(sha1, 0, data, 0, data.length);
encryptedChat.key_hash = data = AndroidUtilities.calcAuthKeyHash(encryptedChat.auth_key);
}
invalidateSelf();
}
@ -48,17 +45,33 @@ public class IdenticonDrawable extends Drawable {
return;
}
int bitPointer = 0;
float rectSize = (float)Math.floor(Math.min(getBounds().width(), getBounds().height()) / 8.0f);
float xOffset = Math.max(0, (getBounds().width() - rectSize * 8) / 2);
float yOffset = Math.max(0, (getBounds().height() - rectSize * 8) / 2);
for (int iy = 0; iy < 8; iy++) {
for (int ix = 0; ix < 8; ix++) {
int byteValue = getBits(bitPointer);
bitPointer += 2;
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);
if (data.length == 16) {
int bitPointer = 0;
float rectSize = (float) Math.floor(Math.min(getBounds().width(), getBounds().height()) / 8.0f);
float xOffset = Math.max(0, (getBounds().width() - rectSize * 8) / 2);
float yOffset = Math.max(0, (getBounds().height() - rectSize * 8) / 2);
for (int iy = 0; iy < 8; iy++) {
for (int ix = 0; ix < 8; ix++) {
int byteValue = getBits(bitPointer);
bitPointer += 2;
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);
}
}
} 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();
}
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) {
if (motionEvent == null) {
draggingState = 0;
@ -353,7 +479,7 @@ public class PhotoCropView extends FrameLayout {
Matrix matrix = new Matrix();
matrix.setTranslate(-bitmapToEdit.getWidth() / 2, -bitmapToEdit.getHeight() / 2);
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);
} else {
matrix.postTranslate(bitmapToEdit.getWidth() / 2 - x, bitmapToEdit.getHeight() / 2 - y);
@ -381,7 +507,7 @@ public class PhotoCropView extends FrameLayout {
int width;
int height;
if (orientation == 90 || orientation == 270) {
if (orientation % 360 == 90 || orientation % 360 == 270) {
width = bitmapToEdit.getHeight();
height = bitmapToEdit.getWidth();
} else {
@ -467,7 +593,7 @@ public class PhotoCropView extends FrameLayout {
public void run() {
if (animationRunnable == this) {
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 scaleToY = bitmapHeight / rectSizeY;
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 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) {
@ -541,7 +667,7 @@ public class PhotoCropView extends FrameLayout {
float bitmapW;
float bitmapH;
if (orientation == 90 || orientation == 270) {
if (orientation % 360 == 90 || orientation % 360 == 270) {
bitmapW = bitmapToEdit.getHeight();
bitmapH = bitmapToEdit.getWidth();
} else {

View file

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

View file

@ -99,7 +99,8 @@ public class PlayerView extends FrameLayout implements NotificationCenter.Notifi
setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (fragment != null) {
MessageObject messageObject = MediaController.getInstance().getPlayingMessageObject();
if (messageObject != null && messageObject.isMusic() && fragment != null) {
fragment.presentFragment(new AudioPlayerActivity());
}
}
@ -158,7 +159,7 @@ public class PlayerView extends FrameLayout implements NotificationCenter.Notifi
create = true;
}
}
if (messageObject == null || !messageObject.isMusic()) {
if (messageObject == null || messageObject.getId() == 0/* || !messageObject.isMusic()*/) {
lastMessageObject = null;
if (visible) {
visible = false;
@ -224,7 +225,14 @@ public class PlayerView extends FrameLayout implements NotificationCenter.Notifi
}
if (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"));
stringBuilder.setSpan(span, 0, messageObject.getMusicAuthor().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
titleTextView.setText(stringBuilder);

View file

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

View file

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

View file

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

View file

@ -39,9 +39,9 @@ public class ResourceLoader {
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[] viewsMediaCountDrawable = new Drawable[2];
public static Drawable viewsMediaCountDrawable;
public static Drawable geoInDrawable;
public static Drawable geoOutDrawable;
@ -79,10 +79,10 @@ public class ResourceLoader {
backgroundBlack = context.getResources().getDrawable(R.drawable.system_black);
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);
viewsMediaCountDrawable[0] = context.getResources().getDrawable(R.drawable.post_views_w);
viewsMediaCountDrawable[1] = context.getResources().getDrawable(R.drawable.post_views_s);
viewsMediaCountDrawable = context.getResources().getDrawable(R.drawable.post_views_w);
audioStatesDrawable[0][2] = audioStatesDrawable[0][0] = context.getResources().getDrawable(R.drawable.play_w2);
audioStatesDrawable[0][1] = context.getResources().getDrawable(R.drawable.play_w2_pressed);

View file

@ -33,7 +33,7 @@ public class SeekBar {
private boolean pressed = false;
public int width;
public int height;
public SeekBarDelegate delegate;
private SeekBarDelegate delegate;
public SeekBar(Context context) {
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) {
if (action == MotionEvent.ACTION_DOWN) {
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;
import android.content.Context;
import android.os.Build;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
@ -26,9 +27,11 @@ import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.telegram.SQLite.SQLiteCursor;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
@ -37,7 +40,9 @@ import org.telegram.messenger.MessagesController;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.R;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.NativeByteBuffer;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.BottomSheet;
@ -66,12 +71,44 @@ public class ShareFrameLayout extends FrameLayout {
private EmptyTextProgressView searchEmptyView;
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);
parentBottomSheet = bottomSheet;
sendingMessageObject = messageObject;
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.setBackgroundColor(0xffffffff);
@ -85,21 +122,31 @@ public class ShareFrameLayout extends FrameLayout {
doneButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
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;
}
if (selectedDialogs.isEmpty() && isPublicChannel) {
if (loadingLink) {
copyLinkOnEnd = true;
Toast.makeText(ShareFrameLayout.this.getContext(), LocaleController.getString("Loading", R.string.Loading), Toast.LENGTH_SHORT).show();
} else {
copyLink(ShareFrameLayout.this.getContext());
}
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.setGravity(Gravity.CENTER);
doneButtonTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
doneButtonTextView.setText(LocaleController.getString("Send", R.string.Send).toUpperCase());
doneButtonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
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);
cell.setChecked(true, true);
}
updateSelectedCount(selectedDialogs.size(), true);
updateSelectedCount();
}
});
@ -229,20 +275,47 @@ public class ShareFrameLayout extends FrameLayout {
gridView.setEmptyView(searchEmptyView);
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) {
if (count == 0) {
public void copyLink(Context context) {
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);
doneButtonTextView.setTextColor(0xffb3b3b3);
doneButton.setEnabled(false);
if (!isPublicChannel) {
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 {
doneButtonTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
doneButtonBadgeTextView.setVisibility(View.VISIBLE);
doneButtonBadgeTextView.setText(String.format("%d", count));
doneButtonBadgeTextView.setText(String.format("%d", selectedDialogs.size()));
doneButtonTextView.setTextColor(0xff3ec1f9);
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.DialogInterface;
import android.database.DataSetObserver;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
@ -22,6 +23,7 @@ import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.NotificationCenter;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.Cells.StickerEmojiCell;
import org.telegram.ui.StickerPreviewViewer;
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);
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.setAdapter(new GridAdapter(context));
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));
setTitle(set.set.title);
@ -77,6 +91,10 @@ public class StickersAlert extends AlertDialog implements NotificationCenter.Not
if (gridView != null) {
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.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Browser;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
@ -95,10 +92,7 @@ public class WebFrameLayout extends FrameLayout {
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse(openUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getContext().getPackageName());
getContext().startActivity(intent);
AndroidUtilities.openUrl(getContext(), openUrl);
if (dialog != null) {
dialog.dismiss();
}

View file

@ -39,6 +39,7 @@ import android.widget.ProgressBar;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.BuildVars;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.LocaleController;
@ -277,7 +278,11 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
} else {
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);
@ -849,7 +854,7 @@ public class DialogsActivity extends BaseFragment implements NotificationCenter.
ContactsController.getInstance().readContacts();
break;
case Manifest.permission.WRITE_EXTERNAL_STORAGE:
ImageLoader.getInstance().createMediaPaths();
ImageLoader.getInstance().checkMediaPaths();
break;
}
}

View file

@ -9,6 +9,7 @@
package org.telegram.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
@ -77,12 +78,13 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
private int beforeChangeIndex;
private boolean ignoreChange;
private CharSequence changeString;
private int maxCount = 199;
private int maxCount = 1000;
private int chatType = ChatObject.CHAT_TYPE_CHAT;
private boolean isAlwaysShare;
private boolean isNeverShare;
private boolean searchWas;
private boolean searching;
private boolean isGroup;
private HashMap<Integer, ChipSpan> selectedContacts = new HashMap<>();
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);
isAlwaysShare = args.getBoolean("isAlwaysShare", 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
@ -124,9 +127,17 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
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) {
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 {
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));
@ -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));
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) {
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 {
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) {
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;
ChipSpan span = createAndPutChipForUser(user);
span.uid = user.id;

View file

@ -164,7 +164,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
donePressed = true;
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 {
if (avatarUpdater.uploadingAvatar != null) {
createAfterUpload = true;
@ -174,7 +174,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
progressDialog.setCanceledOnTouchOutside(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() {
@Override
@ -335,7 +335,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
avatarImage.setImage(avatar, "50_50", avatarDrawable);
if (createAfterUpload) {
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.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.Surface;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.TLRPC;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.R;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.Components.IdenticonDrawable;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.URLSpanReplacement;
public class IdenticonActivity extends BaseFragment {
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) {
super(args);
}
@ -57,18 +82,11 @@ public class IdenticonActivity extends BaseFragment {
}
});
fragmentView = getParentActivity().getLayoutInflater().inflate(R.layout.identicon_layout, null, false);
ImageView identiconView = (ImageView) fragmentView.findViewById(R.id.identicon_view);
TextView textView = (TextView) fragmentView.findViewById(R.id.identicon_text);
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);
textView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("EncryptionKeyDescription", R.string.EncryptionKeyDescription, user.first_name, user.first_name)));
}
fragmentView = new LinearLayout(context);
LinearLayout linearLayout = (LinearLayout) fragmentView;
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setWeightSum(100);
linearLayout.setBackgroundColor(0xfff0f0f0);
fragmentView.setOnTouchListener(new View.OnTouchListener() {
@Override
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;
}
@ -100,7 +173,7 @@ public class IdenticonActivity extends BaseFragment {
return true;
}
fragmentView.getViewTreeObserver().removeOnPreDrawListener(this);
LinearLayout layout = (LinearLayout)fragmentView;
LinearLayout layout = (LinearLayout) fragmentView;
WindowManager manager = (WindowManager) ApplicationLoader.applicationContext.getSystemService(Context.WINDOW_SERVICE);
int rotation = manager.getDefaultDisplay().getRotation();

View file

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

View file

@ -24,7 +24,6 @@ import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Browser;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.view.ActionMode;
@ -53,6 +52,7 @@ import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.NativeCrashManager;
import org.telegram.messenger.SendMessagesHelper;
import org.telegram.messenger.UserObject;
import org.telegram.messenger.Utilities;
import org.telegram.messenger.query.StickersQuery;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.FileLog;
@ -75,6 +75,7 @@ import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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());
drawerLayoutContainer.closeDrawer(false);
} else if (position == 9) {
try {
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);
}
AndroidUtilities.openUrl(LaunchActivity.this, LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
drawerLayoutContainer.closeDrawer(false);
}
}
@ -610,7 +606,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
error = true;
}
} 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);
if (text == null) {
text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT).toString();
@ -622,8 +618,8 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
text = subject + "\n" + text;
}
sendingText = text;
} else {
error = true;
} else if (subject != null && subject.length() > 0) {
sendingText = subject;
}
}
Parcelable parcelable = intent.getParcelableExtra(Intent.EXTRA_STREAM);
@ -633,38 +629,48 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
parcelable = Uri.parse(parcelable.toString());
}
Uri uri = (Uri) parcelable;
if (uri != null && (type != null && type.startsWith("image/") || uri.toString().toLowerCase().endsWith(".jpg"))) {
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 (uri != null) {
if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
String pathString = Utilities.readlink(uri.getPath());
if (pathString != null && pathString.contains("/data/data/" + getPackageName() + "/files")) {
error = true;
}
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;
if (!error) {
if (uri != null && (type != null && type.startsWith("image/") || uri.toString().toLowerCase().endsWith(".jpg"))) {
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) {
@ -679,9 +685,31 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
try {
ArrayList<Parcelable> uris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
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 (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)) {
parcelable = Uri.parse(parcelable.toString());
}
@ -692,7 +720,8 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
photoPathsArray.add(uri);
}
} else {
for (Parcelable parcelable : uris) {
for (int a = 0; a < uris.size(); a++) {
Parcelable parcelable = uris.get(a);
if (!(parcelable instanceof Uri)) {
parcelable = Uri.parse(parcelable.toString());
}
@ -733,6 +762,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
String botUser = null;
String botChat = null;
String message = null;
Integer messageId = null;
boolean hasUrl = false;
String scheme = data.getScheme();
if (scheme != null) {
@ -758,8 +788,17 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
}
message += data.getQueryParameter("text");
}
} else if (path.length() >= 3) {
username = data.getLastPathSegment();
} else if (path.length() >= 1) {
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");
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) {
runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl, 0);
runLinkRequest(username, group, sticker, botUser, botChat, message, hasUrl, messageId, 0);
} else {
try {
Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
@ -986,7 +1025,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
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);
progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
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) {
args.putString("botUser", botUser);
}
if (messageId != null) {
args.putInt("message_id", messageId);
}
ChatActivity fragment = new ChatActivity(args);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
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() {
@Override
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);
@ -1494,7 +1536,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
if (requestCode == 3 || requestCode == 4 || requestCode == 5) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == 4) {
ImageLoader.getInstance().createMediaPaths();
ImageLoader.getInstance().checkMediaPaths();
} else if (requestCode == 5) {
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() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
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);
}
AndroidUtilities.openUrl(LaunchActivity.this, LocaleController.getString("NobodyLikesSpamUrl", R.string.NobodyLikesSpamUrl));
}
});
}
@ -1882,7 +1918,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa
@Override
public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
if (keyCode == KeyEvent.KEYCODE_MENU && !UserConfig.isWaitingForPasscodeEnter) {
if (AndroidUtilities.isTablet()) {
if (layersActionBarLayout.getVisibility() == View.VISIBLE && !layersActionBarLayout.fragmentsStack.isEmpty()) {
layersActionBarLayout.onKeyUp(keyCode, event);

View file

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

View file

@ -400,7 +400,7 @@ public class LoginActivity extends BaseFragment {
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 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
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (ignoreSelection) {
@ -785,6 +796,7 @@ public class LoginActivity extends BaseFragment {
needShowAlert(LocaleController.getString("AppName", R.string.AppName), LocaleController.getString("InvalidPhoneNumber", R.string.InvalidPhoneNumber));
return;
}
//NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveCall);
ConnectionsManager.getInstance().cleanUp();
TLRPC.TL_auth_sendCode req = new TLRPC.TL_auth_sendCode();
@ -857,6 +869,7 @@ public class LoginActivity extends BaseFragment {
codeField.requestFocus();
}
}
//NotificationCenter.getInstance().addObserver(this, NotificationCenter.didReceiveCall);
}
@Override
@ -1071,9 +1084,14 @@ public class LoginActivity extends BaseFragment {
destroyTimer();
destroyCodeTimer();
timeText.setText(LocaleController.formatString("CallText", R.string.CallText, 1, 0));
lastCurrentTime = System.currentTimeMillis();
problemText.setVisibility(time < 1000 ? VISIBLE : GONE);
if (time >= 3600 * 1000) {
timeText.setVisibility(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();
}
@ -1119,7 +1137,7 @@ public class LoginActivity extends BaseFragment {
}
private void createTimer() {
if (timeTimer != null) {
if (timeTimer != null || time >= 3600 * 1000) {
return;
}
timeTimer = new Timer();

View file

@ -18,7 +18,6 @@ import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Browser;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
@ -446,6 +445,11 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
if ((int) dialog_id != 0) {
dropDownContainer.addSubItem(links_item, LocaleController.getString("LinksTitle", R.string.LinksTitle), 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));
dropDownContainer.setOnClickListener(new View.OnClickListener() {
@ -1115,10 +1119,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
link = ((SharedLinkCell) view).getLink(0);
}
if (link != null) {
Uri uri = Uri.parse(link);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, getParentActivity().getPackageName());
getParentActivity().startActivity(intent);
AndroidUtilities.openUrl(getParentActivity(), link);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
@ -1541,7 +1542,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No
} else if (currentType == 3) {
req.filter = new TLRPC.TL_inputMessagesFilterUrl();
} else if (currentType == 4) {
req.filter = new TLRPC.TL_inputMessagesFilterAudioDocuments();
req.filter = new TLRPC.TL_inputMessagesFilterMusic();
}
req.q = query;
req.peer = MessagesController.getInputPeer(uid);

View file

@ -28,7 +28,7 @@ import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Browser;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.GestureDetector;
@ -48,6 +48,7 @@ import android.widget.Scroller;
import android.widget.TextView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.MessagesStorage;
import org.telegram.messenger.UserObject;
@ -180,19 +181,20 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
private boolean draggingDown = false;
private float dragY;
private float translationX = 0;
private float translationY = 0;
private float translationX;
private float translationY;
private float scale = 1;
private float animateToX;
private float animateToY;
private float animateToScale;
private float animationValue;
private int currentRotation;
private long animationStartTime;
private AnimatorSetProxy imageMoveAnimation;
private AnimatorSetProxy changeModeAnimation;
private GestureDetector gestureDetector;
private DecelerateInterpolator interpolator = new DecelerateInterpolator(1.5f);
private float pinchStartDistance = 0;
private float pinchStartDistance;
private float pinchStartScale = 1;
private float pinchCenterX;
private float pinchCenterY;
@ -960,7 +962,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
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 {
AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
@ -1020,7 +1022,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
return;
}
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));
} else {
builder.setMessage(LocaleController.formatString("AreYouSureDeletePhoto", R.string.AreYouSureDeletePhoto));
@ -1200,13 +1202,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
try {
File f = null;
boolean isVideo = false;
if (currentMessageObject != null) {
isVideo = currentMessageObject.isVideo();
if (currentMessageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
Uri uri = Uri.parse(currentMessageObject.messageOwner.media.webpage.url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, parentActivity.getPackageName());
parentActivity.startActivity(intent);
AndroidUtilities.openUrl(parentActivity, currentMessageObject.messageOwner.media.webpage.url);
return;
}
f = FileLoader.getPathToMessage(currentMessageObject.messageOwner);
@ -1216,7 +1217,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
if (f.exists()) {
Intent intent = new Intent(Intent.ACTION_SEND);
if (f.toString().endsWith("mp4")) {
if (isVideo) {
intent.setType("video/mp4");
} else {
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.setOnDoubleTapListener(this);
@ -2074,23 +2089,17 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
return null;
}
if (!imagesArrLocations.isEmpty() || !imagesArr.isEmpty()) {
TLRPC.InputFileLocation file = getInputFileLocation(index);
if (file == null) {
return null;
}
if (!imagesArrLocations.isEmpty()) {
return file.volume_id + "_" + file.local_id + ".jpg";
} else if (!imagesArr.isEmpty()) {
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";
}
if (index >= imagesArrLocations.size()) {
return null;
}
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()) {
if (index >= imagesArrLocals.size()) {
@ -2109,7 +2118,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
searchImage.localUrl = "";
}
}
return Utilities.MD5(searchImage.imageUrl) + "." + ImageLoader.getHttpUrlExtension(searchImage.imageUrl);
return Utilities.MD5(searchImage.imageUrl) + "." + ImageLoader.getHttpUrlExtension(searchImage.imageUrl, "jpg");
}
}
return null;
@ -2156,72 +2165,12 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
} else {
size[0] = -1;
}
} else if (message.messageOwner.media instanceof TLRPC.TL_messageMediaVideo && message.messageOwner.media.video != null && message.messageOwner.media.video.thumb != null) {
size[0] = message.messageOwner.media.video.thumb.size;
} 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.document.thumb.size;
if (size[0] == 0) {
size[0] = -1;
}
return message.messageOwner.media.video.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 message.messageOwner.media.document.thumb.location;
}
}
return null;
@ -2353,7 +2302,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
canShowBottom = false;
Object obj = imagesArrLocals.get(index);
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.setNeedUsernames(parentChatActivity.currentChat != null);
mentionsAdapter.setNeedBotContext(false);
@ -2401,7 +2350,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
placeProvider.willSwitchFromPhoto(currentMessageObject, currentFileLocation, currentIndex);
int prevIndex = currentIndex;
currentIndex = index;
boolean isVideo = false;
boolean sameImage = false;
if (!imagesArr.isEmpty()) {
@ -2410,12 +2359,13 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
return;
}
currentMessageObject = imagesArr.get(currentIndex);
isVideo = currentMessageObject.isVideo();
if (currentMessageObject.canDeleteMessage(null)) {
menuItem.showSubItem(gallery_menu_delete);
} else {
menuItem.hideSubItem(gallery_menu_delete);
}
if (currentMessageObject.messageOwner.from_id > 0) {
if (currentMessageObject.isFromUser()) {
TLRPC.User user = MessagesController.getInstance().getUser(currentMessageObject.messageOwner.from_id);
if (user != null) {
nameTextView.setText(UserObject.getUserName(user));
@ -2423,7 +2373,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
nameTextView.setText("");
}
} 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) {
nameTextView.setText(chat.title);
} else {
@ -2432,8 +2382,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
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)));
if (currentFileNames[0] != null && currentFileNames[0].endsWith("mp4")) {
dateTextView.setText(String.format("%s (%s)", dateString, AndroidUtilities.formatFileSize(currentMessageObject.messageOwner.media.video.size)));
if (currentFileNames[0] != null && isVideo) {
dateTextView.setText(String.format("%s (%s)", dateString, AndroidUtilities.formatFileSize(currentMessageObject.messageOwner.media.document.size)));
} else {
dateTextView.setText(dateString);
}
@ -2580,7 +2530,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
canDragDown = true;
changingPage = false;
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);
}
@ -2629,8 +2579,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
captionTextViewNew = captionTextView;
captionItem.setIcon(R.drawable.photo_text2);
captionTextView.setTag(caption);
captionTextView.setText(caption);
CharSequence str = Emoji.replaceEmoji(new SpannableStringBuilder(caption.toString()), MessageObject.textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
captionTextView.setTag(str);
captionTextView.setText(str);
ViewProxy.setAlpha(captionTextView, bottomLayout.getVisibility() == View.VISIBLE || pickerView.getVisibility() == View.VISIBLE ? 1.0f : 0.0f);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
@ -2658,9 +2609,11 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
index -= 1;
}
File f = null;
boolean isVideo = false;
if (currentMessageObject != null) {
MessageObject messageObject = imagesArr.get(index);
f = FileLoader.getPathToMessage(messageObject.messageOwner);
isVideo = messageObject.isVideo();
} else if (currentFileLocation != null) {
TLRPC.FileLocation location = imagesArrLocations.get(index);
f = FileLoader.getPathToAttach(location, avatarsUserId != 0);
@ -2671,13 +2624,13 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
}
if (f != null && f.exists()) {
if (currentPathObject == null && currentFileNames[a].endsWith("mp4")) {
if (isVideo) {
radialProgressViews[a].setBackgroundState(3, animated);
} else {
radialProgressViews[a].setBackgroundState(-1, animated);
}
} else {
if (currentPathObject == null && currentFileNames[a].endsWith("mp4")) {
if (isVideo) {
if (!FileLoader.getInstance().isLoadingFile(currentFileNames[a])) {
radialProgressViews[a].setBackgroundState(2, false);
} else {
@ -2693,7 +2646,7 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
radialProgressViews[a].setProgress(progress, false);
}
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 {
radialProgressViews[a].setBackgroundState(-1, animated);
@ -2762,9 +2715,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
imageReceiver.setShouldGenerateQualityThumb(true);
}
if (messageObject != null && messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
if (messageObject != null && messageObject.isVideo()) {
imageReceiver.setNeedsQualityThumb(true);
if (messageObject.messageOwner.media.video.thumb != null) {
if (messageObject.photoThumbs != null && !messageObject.photoThumbs.isEmpty()) {
Bitmap placeHolder = null;
if (currentThumb != null && imageReceiver == centerImage) {
placeHolder = currentThumb;
@ -3963,9 +3916,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
}
if (loadFile) {
if (!FileLoader.getInstance().isLoadingFile(currentFileNames[0])) {
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.video, true);
FileLoader.getInstance().loadFile(currentMessageObject.messageOwner.media.document, true, false);
} 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
public void needSendTyping() {
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.Adapters.BaseFragmentAdapter;
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.TextSettingsCell;
import org.telegram.ui.Components.LayoutHelper;
import java.util.ArrayList;
public class LastSeenActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate {
public class PrivacyControlActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate {
private ListAdapter listAdapter;
private View doneButton;
@ -60,11 +60,15 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
private ArrayList<Integer> currentMinus;
private int lastCheckedType = -1;
private int lastSeenSectionRow;
private boolean isGroup;
private boolean enableAnimation;
private int sectionRow;
private int everybodyRow;
private int myContactsRow;
private int nobodyRow;
private int lastSeenDetailRow;
private int detailRow;
private int shareSectionRow;
private int alwaysShareRow;
private int neverShareRow;
@ -85,6 +89,11 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
}
}
public PrivacyControlActivity(boolean group) {
super();
isGroup = group;
}
@Override
public boolean onFragmentCreate() {
super.onFragmentCreate();
@ -104,7 +113,11 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
public View createView(Context context) {
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
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() {
@Override
public void onItemClick(int id) {
@ -115,12 +128,16 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
return;
}
if (currentType != 0) {
if (currentType != 0 && !isGroup) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean showed = preferences.getBoolean("privacyAlertShowed", false);
if (!showed) {
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.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
@ -176,6 +193,7 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
if (newType == currentType) {
return;
}
enableAnimation = true;
doneButton.setVisibility(View.VISIBLE);
lastCheckedType = currentType;
currentType = newType;
@ -190,19 +208,20 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
if (createFromArray.isEmpty()) {
Bundle args = new Bundle();
args.putBoolean(i == neverShareRow ? "isNeverShare" : "isAlwaysShare", true);
args.putBoolean("isGroup", isGroup);
GroupCreateActivity fragment = new GroupCreateActivity(args);
fragment.setDelegate(new GroupCreateActivity.GroupCreateActivityDelegate() {
@Override
public void didSelectUsers(ArrayList<Integer> ids) {
if (i == neverShareRow) {
currentMinus = ids;
for (Integer id : currentMinus) {
currentPlus.remove(id);
for (int a = 0; a < currentMinus.size(); a++) {
currentPlus.remove(currentMinus.get(a));
}
} else {
currentPlus = ids;
for (Integer id : currentPlus) {
currentMinus.remove(id);
for (int a = 0; a < currentPlus.size(); a++) {
currentMinus.remove(currentPlus.get(a));
}
}
doneButton.setVisibility(View.VISIBLE);
@ -212,22 +231,22 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
});
presentFragment(fragment);
} else {
LastSeenUsersActivity fragment = new LastSeenUsersActivity(createFromArray, i == alwaysShareRow);
fragment.setDelegate(new LastSeenUsersActivity.LastSeenUsersActivityDelegate() {
PrivacyUsersActivity fragment = new PrivacyUsersActivity(createFromArray, isGroup, i == alwaysShareRow);
fragment.setDelegate(new PrivacyUsersActivity.PrivacyActivityDelegate() {
@Override
public void didUpdatedUserList(ArrayList<Integer> ids, boolean added) {
if (i == neverShareRow) {
currentMinus = ids;
if (added) {
for (Integer id : currentMinus) {
currentPlus.remove(id);
for (int a = 0; a < currentMinus.size(); a++) {
currentPlus.remove(currentMinus.get(a));
}
}
} else {
currentPlus = ids;
if (added) {
for (Integer id : currentPlus) {
currentMinus.remove(id);
for (int a = 0; a < currentPlus.size(); a++) {
currentMinus.remove(currentPlus.get(a));
}
}
}
@ -253,11 +272,15 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
private void applyCurrentPrivacySettings() {
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) {
TLRPC.TL_inputPrivacyValueAllowUsers rule = new TLRPC.TL_inputPrivacyValueAllowUsers();
for (Integer uid : currentPlus) {
TLRPC.User user = MessagesController.getInstance().getUser(uid);
for (int a = 0; a < currentPlus.size(); a++) {
TLRPC.User user = MessagesController.getInstance().getUser(currentPlus.get(a));
if (user != null) {
TLRPC.InputUser inputUser = MessagesController.getInputUser(user);
if (inputUser != null) {
@ -269,8 +292,8 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
}
if (currentType != 1 && currentMinus.size() > 0) {
TLRPC.TL_inputPrivacyValueDisallowUsers rule = new TLRPC.TL_inputPrivacyValueDisallowUsers();
for (Integer uid : currentMinus) {
TLRPC.User user = MessagesController.getInstance().getUser(uid);
for (int a = 0; a < currentMinus.size(); a++) {
TLRPC.User user = MessagesController.getInstance().getUser(currentMinus.get(a));
if (user != null) {
TLRPC.InputUser inputUser = MessagesController.getInputUser(user);
if (inputUser != null) {
@ -313,7 +336,7 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
finishFragment();
TLRPC.TL_account_privacyRules rules = (TLRPC.TL_account_privacyRules) response;
MessagesController.getInstance().putUsers(rules.users, false);
ContactsController.getInstance().setPrivacyRules(rules.rules);
ContactsController.getInstance().setPrivacyRules(rules.rules, isGroup);
} else {
showErrorAlert();
}
@ -337,13 +360,14 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
private void checkPrivacy() {
currentPlus = new ArrayList<>();
currentMinus = new ArrayList<>();
ArrayList<TLRPC.PrivacyRule> privacyRules = ContactsController.getInstance().getPrivacyRules();
ArrayList<TLRPC.PrivacyRule> privacyRules = ContactsController.getInstance().getPrivacyRules(isGroup);
if (privacyRules.size() == 0) {
currentType = 1;
return;
}
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) {
currentPlus.addAll(rule.users);
} else if (rule instanceof TLRPC.TL_privacyValueDisallowUsers) {
@ -371,11 +395,15 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
private void updateRows() {
rowCount = 0;
lastSeenSectionRow = rowCount++;
sectionRow = rowCount++;
everybodyRow = rowCount++;
myContactsRow = rowCount++;
nobodyRow = rowCount++;
lastSeenDetailRow = rowCount++;
if (isGroup) {
nobodyRow = -1;
} else {
nobodyRow = rowCount++;
}
detailRow = rowCount++;
shareSectionRow = rowCount++;
if (currentType == 1 || currentType == 2) {
alwaysShareRow = rowCount++;
@ -397,9 +425,7 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
public void onResume() {
super.onResume();
lastCheckedType = -1;
if (listAdapter != null) {
listAdapter.notifyDataSetChanged();
}
enableAnimation = false;
}
private class ListAdapter extends BaseFragmentAdapter {
@ -455,7 +481,11 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
} else {
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) {
String value;
if (currentMinus.size() != 0) {
@ -463,18 +493,30 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
} else {
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) {
if (view == null) {
view = new TextInfoPrivacyCell(mContext);
view.setBackgroundColor(0xffffffff);
}
if (i == lastSeenDetailRow) {
((TextInfoPrivacyCell) view).setText(LocaleController.getString("CustomHelp", R.string.CustomHelp));
if (i == detailRow) {
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);
} 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);
}
} else if (type == 2) {
@ -482,32 +524,36 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
view = new HeaderCell(mContext);
view.setBackgroundColor(0xffffffff);
}
if (i == lastSeenSectionRow) {
((HeaderCell) view).setText(LocaleController.getString("LastSeenTitle", R.string.LastSeenTitle));
if (i == sectionRow) {
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) {
((HeaderCell) view).setText(LocaleController.getString("AddExceptions", R.string.AddExceptions));
}
} else if (type == 3) {
if (view == null) {
view = new LastSeenRadioCell(mContext);
view = new RadioCell(mContext);
view.setBackgroundColor(0xffffffff);
}
LastSeenRadioCell textCell = (LastSeenRadioCell) view;
RadioCell textCell = (RadioCell) view;
int checkedType = 0;
if (i == everybodyRow) {
textCell.setText(LocaleController.getString("LastSeenEverybody", R.string.LastSeenEverybody), lastCheckedType == 0, true);
checkedType = 0;
} 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;
} else if (i == nobodyRow) {
textCell.setText(LocaleController.getString("LastSeenNobody", R.string.LastSeenNobody), lastCheckedType == 1, false);
checkedType = 1;
}
if (lastCheckedType == checkedType) {
textCell.setChecked(false, true);
textCell.setChecked(false, enableAnimation);
} else if (currentType == checkedType) {
textCell.setChecked(true, true);
textCell.setChecked(true, enableAnimation);
}
}
return view;
@ -517,9 +563,9 @@ public class LastSeenActivity extends BaseFragment implements NotificationCenter
public int getItemViewType(int i) {
if (i == alwaysShareRow || i == neverShareRow) {
return 0;
} else if (i == shareDetailRow || i == lastSeenDetailRow) {
} else if (i == shareDetailRow || i == detailRow) {
return 1;
} else if (i == lastSeenSectionRow || i == shareSectionRow) {
} else if (i == sectionRow || i == shareSectionRow) {
return 2;
} else if (i == everybodyRow || i == myContactsRow || i == nobodyRow) {
return 3;

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