Commit 7545dfe2 authored by DrKLO's avatar DrKLO

Merge branch 'dev'

parents 331a0bb7 8f7652bb
...@@ -18,7 +18,7 @@ tasks.withType(JavaCompile) { ...@@ -18,7 +18,7 @@ tasks.withType(JavaCompile) {
dependencies { dependencies {
compile 'com.android.support:support-v4:19.0.+' compile 'com.android.support:support-v4:19.0.+'
compile 'com.google.android.gms:play-services:4.1.+' compile 'com.google.android.gms:play-services:3.2.+'
compile 'net.hockeyapp.android:HockeySDK:3.0.1' compile 'net.hockeyapp.android:HockeySDK:3.0.1'
compile 'com.googlecode.mp4parser:isoparser:1.0.+' compile 'com.googlecode.mp4parser:isoparser:1.0.+'
} }
...@@ -83,7 +83,7 @@ android { ...@@ -83,7 +83,7 @@ android {
defaultConfig { defaultConfig {
minSdkVersion 8 minSdkVersion 8
targetSdkVersion 19 targetSdkVersion 19
versionCode 288 versionCode 307
versionName "1.6.1" versionName "1.7.0"
} }
} }
...@@ -28,7 +28,6 @@ ...@@ -28,7 +28,6 @@
android:largeHeap="true"> android:largeHeap="true">
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCTNmNqbWovP9ETcAob98YlrfOQEAC0CJ4" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyCTNmNqbWovP9ETcAob98YlrfOQEAC0CJ4" />
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<activity android:name="net.hockeyapp.android.UpdateActivity" /> <activity android:name="net.hockeyapp.android.UpdateActivity" />
......
...@@ -28,7 +28,6 @@ ...@@ -28,7 +28,6 @@
android:largeHeap="true"> android:largeHeap="true">
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyA-t0jLPjUt2FxrA8VPK2EiYHcYcboIR6k" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyA-t0jLPjUt2FxrA8VPK2EiYHcYcboIR6k" />
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
<activity android:name="net.hockeyapp.android.UpdateActivity" /> <activity android:name="net.hockeyapp.android.UpdateActivity" />
......
...@@ -8,6 +8,7 @@ LOCAL_CFLAGS += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT -DUSE_ALLOCA ...@@ -8,6 +8,7 @@ LOCAL_CFLAGS += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT -DUSE_ALLOCA
LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT
LOCAL_CPPFLAGS := -DBSD=1 -ffast-math -O2 -funroll-loops LOCAL_CPPFLAGS := -DBSD=1 -ffast-math -O2 -funroll-loops
#LOCAL_LDLIBS := -llog #LOCAL_LDLIBS := -llog
LOCAL_LDLIBS := -ljnigraphics
LOCAL_SRC_FILES := \ LOCAL_SRC_FILES := \
./opus/src/opus.c \ ./opus/src/opus.c \
......
...@@ -2,5 +2,5 @@ ...@@ -2,5 +2,5 @@
void fakeFunction() { void fakeFunction() {
printf("some androids has buggy native loader, so i should check size of libs in java to know that native library is correct. So each changed native library should has diffrent size in different app versions. This function will increase lib size for few bytes :)"); printf("some androids has buggy native loader, so i should check size of libs in java to know that native library is correct. So each changed native library should has diffrent size in different app versions. This function will increase lib size for few bytes :)");
printf("bla blablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablabla"); printf("bla blablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablabla");
} }
//tanks to https://github.com/koral--/android-gif-drawable //thanks to https://github.com/koral--/android-gif-drawable
/* /*
MIT License MIT License
Copyright (c) Copyright (c)
...@@ -73,7 +73,7 @@ typedef struct { ...@@ -73,7 +73,7 @@ typedef struct {
typedef struct { typedef struct {
unsigned int duration; unsigned int duration;
short transpIndex; int transpIndex;
unsigned char disposalMethod; unsigned char disposalMethod;
} FrameInfo; } FrameInfo;
...@@ -132,8 +132,9 @@ static int fileRewindFun(GifInfo *info) { ...@@ -132,8 +132,9 @@ static int fileRewindFun(GifInfo *info) {
static unsigned long getRealTime() { static unsigned long getRealTime() {
struct timespec ts; struct timespec ts;
const clockid_t id = CLOCK_MONOTONIC; const clockid_t id = CLOCK_MONOTONIC;
if (id != (clockid_t) - 1 && clock_gettime(id, &ts) != -1) if (id != (clockid_t) - 1 && clock_gettime(id, &ts) != -1) {
return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
return -1; return -1;
} }
...@@ -195,7 +196,7 @@ static void packARGB32(argb *pixel, GifByteType alpha, GifByteType red, GifByteT ...@@ -195,7 +196,7 @@ static void packARGB32(argb *pixel, GifByteType alpha, GifByteType red, GifByteT
} }
static void getColorFromTable(int idx, argb *dst, const ColorMapObject *cmap) { static void getColorFromTable(int idx, argb *dst, const ColorMapObject *cmap) {
char colIdx = idx >= cmap->ColorCount ? 0 : idx; int colIdx = (idx >= cmap->ColorCount) ? 0 : idx;
GifColorType *col = &cmap->Colors[colIdx]; GifColorType *col = &cmap->Colors[colIdx];
packARGB32(dst, 0xFF, col->Red, col->Green, col->Blue); packARGB32(dst, 0xFF, col->Red, col->Green, col->Blue);
} }
...@@ -218,7 +219,7 @@ static inline bool setupBackupBmp(GifInfo *info, short transpIndex) { ...@@ -218,7 +219,7 @@ static inline bool setupBackupBmp(GifInfo *info, short transpIndex) {
if (transpIndex == -1) { if (transpIndex == -1) {
getColorFromTable(fGIF->SBackGroundColor, &paintingColor, fGIF->SColorMap); getColorFromTable(fGIF->SBackGroundColor, &paintingColor, fGIF->SColorMap);
} else { } else {
packARGB32(&paintingColor,0,0,0,0); packARGB32(&paintingColor, 0, 0, 0, 0);
} }
eraseColor(info->backupPtr, fGIF->SWidth, fGIF->SHeight, paintingColor); eraseColor(info->backupPtr, fGIF->SWidth, fGIF->SHeight, paintingColor);
return true; return true;
...@@ -231,14 +232,15 @@ static int readExtensions(int ExtFunction, GifByteType *ExtData, GifInfo *info) ...@@ -231,14 +232,15 @@ static int readExtensions(int ExtFunction, GifByteType *ExtData, GifInfo *info)
if (ExtFunction == GRAPHICS_EXT_FUNC_CODE && ExtData[0] == 4) { if (ExtFunction == GRAPHICS_EXT_FUNC_CODE && ExtData[0] == 4) {
FrameInfo *fi = &info->infos[info->gifFilePtr->ImageCount]; FrameInfo *fi = &info->infos[info->gifFilePtr->ImageCount];
fi->transpIndex = -1; fi->transpIndex = -1;
char *b = (char *)ExtData + 1; char *b = (char*) ExtData + 1;
short delay = ((b[2] << 8) | b[1]); short delay = ((b[2] << 8) | b[1]);
fi->duration = delay > 1 ? delay * 10 : 100; fi->duration = delay > 1 ? delay * 10 : 100;
fi->disposalMethod = ((b[0] >> 2) & 7); fi->disposalMethod = ((b[0] >> 2) & 7);
if (ExtData[1] & 1) if (ExtData[1] & 1) {
fi->transpIndex = (short) b[3]; fi->transpIndex = 0xff & b[3];
}
if (fi->disposalMethod == 3 && info->backupPtr == NULL) { if (fi->disposalMethod == 3 && info->backupPtr == NULL) {
if (!setupBackupBmp(info,fi->transpIndex)) { if (!setupBackupBmp(info, fi->transpIndex)) {
return GIF_ERROR; return GIF_ERROR;
} }
} }
...@@ -260,7 +262,7 @@ static int readExtensions(int ExtFunction, GifByteType *ExtData, GifInfo *info) ...@@ -260,7 +262,7 @@ static int readExtensions(int ExtFunction, GifByteType *ExtData, GifInfo *info)
return GIF_OK; return GIF_OK;
} }
static int DDGifSlurp(GifFileType *GifFile, GifInfo *info, bool shouldDecode) { static int DDGifSlurp(GifFileType *GifFile, GifInfo* info, bool shouldDecode) {
GifRecordType RecordType; GifRecordType RecordType;
GifByteType *ExtData; GifByteType *ExtData;
int codeSize; int codeSize;
...@@ -268,12 +270,13 @@ static int DDGifSlurp(GifFileType *GifFile, GifInfo *info, bool shouldDecode) { ...@@ -268,12 +270,13 @@ static int DDGifSlurp(GifFileType *GifFile, GifInfo *info, bool shouldDecode) {
size_t ImageSize; size_t ImageSize;
do { do {
if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR) { if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR) {
return GIF_ERROR; return (GIF_ERROR);
} }
switch (RecordType) { switch (RecordType) {
case IMAGE_DESC_RECORD_TYPE: { case IMAGE_DESC_RECORD_TYPE:
if (DGifGetImageDesc(GifFile, !shouldDecode) == GIF_ERROR) { if (DGifGetImageDesc(GifFile, !shouldDecode) == GIF_ERROR) {
return GIF_ERROR; return (GIF_ERROR);
} }
int i = shouldDecode ? info->currentIndex : GifFile->ImageCount - 1; int i = shouldDecode ? info->currentIndex : GifFile->ImageCount - 1;
SavedImage *sp = &GifFile->SavedImages[i]; SavedImage *sp = &GifFile->SavedImages[i];
...@@ -302,12 +305,13 @@ static int DDGifSlurp(GifFileType *GifFile, GifInfo *info, bool shouldDecode) { ...@@ -302,12 +305,13 @@ static int DDGifSlurp(GifFileType *GifFile, GifInfo *info, bool shouldDecode) {
} }
} else { } else {
if (DGifGetLine(GifFile, sp->RasterBits, ImageSize) == GIF_ERROR) { if (DGifGetLine(GifFile, sp->RasterBits, ImageSize) == GIF_ERROR) {
return GIF_ERROR; return (GIF_ERROR);
} }
} }
if (info->currentIndex >= GifFile->ImageCount - 1) { if (info->currentIndex >= GifFile->ImageCount - 1) {
if (info->loopCount > 0) if (info->loopCount > 0) {
info->currentLoop++; info->currentLoop++;
}
if (fileRewindFun(info) != 0) { if (fileRewindFun(info) != 0) {
info->gifFilePtr->Error = D_GIF_ERR_READ_FAILED; info->gifFilePtr->Error = D_GIF_ERR_READ_FAILED;
return GIF_ERROR; return GIF_ERROR;
...@@ -316,31 +320,34 @@ static int DDGifSlurp(GifFileType *GifFile, GifInfo *info, bool shouldDecode) { ...@@ -316,31 +320,34 @@ static int DDGifSlurp(GifFileType *GifFile, GifInfo *info, bool shouldDecode) {
return GIF_OK; return GIF_OK;
} else { } else {
if (DGifGetCode(GifFile, &codeSize, &ExtData) == GIF_ERROR) { if (DGifGetCode(GifFile, &codeSize, &ExtData) == GIF_ERROR) {
return GIF_ERROR; return (GIF_ERROR);
} }
while (ExtData) { while (ExtData != NULL) {
if (DGifGetCodeNext(GifFile, &ExtData) == GIF_ERROR) { if (DGifGetCodeNext(GifFile, &ExtData) == GIF_ERROR) {
return GIF_ERROR; return (GIF_ERROR);
} }
} }
} }
break; break;
}
case EXTENSION_RECORD_TYPE: { case EXTENSION_RECORD_TYPE:
if (DGifGetExtension(GifFile, &ExtFunction, &ExtData) == GIF_ERROR) { if (DGifGetExtension(GifFile, &ExtFunction, &ExtData) == GIF_ERROR) {
return GIF_ERROR; return (GIF_ERROR);
} }
if (!shouldDecode) { if (!shouldDecode) {
info->infos = realloc(info->infos, (GifFile->ImageCount + 1) * sizeof(FrameInfo)); FrameInfo *tmpInfos = realloc(info->infos, (GifFile->ImageCount + 1) * sizeof(FrameInfo));
if (tmpInfos == NULL) {
return GIF_ERROR;
}
info->infos = tmpInfos;
if (readExtensions(ExtFunction, ExtData, info) == GIF_ERROR) { if (readExtensions(ExtFunction, ExtData, info) == GIF_ERROR) {
return GIF_ERROR; return GIF_ERROR;
} }
} }
while (ExtData) { while (ExtData != NULL) {
if (DGifGetExtensionNext(GifFile, &ExtData, &ExtFunction) == GIF_ERROR) { if (DGifGetExtensionNext(GifFile, &ExtData, &ExtFunction) == GIF_ERROR) {
return GIF_ERROR; return (GIF_ERROR);
} }
if (!shouldDecode) { if (!shouldDecode) {
if (readExtensions(ExtFunction, ExtData, info) == GIF_ERROR) { if (readExtensions(ExtFunction, ExtData, info) == GIF_ERROR) {
...@@ -349,22 +356,23 @@ static int DDGifSlurp(GifFileType *GifFile, GifInfo *info, bool shouldDecode) { ...@@ -349,22 +356,23 @@ static int DDGifSlurp(GifFileType *GifFile, GifInfo *info, bool shouldDecode) {
} }
} }
break; break;
}
case TERMINATE_RECORD_TYPE: case TERMINATE_RECORD_TYPE:
break;
default: default:
break; break;
} }
} while (RecordType != TERMINATE_RECORD_TYPE); } while (RecordType != TERMINATE_RECORD_TYPE);
bool ok = true; bool ok = true;
if (shouldDecode) { if (shouldDecode) {
ok = (fileRewindFun(info) == 0); ok = (fileRewindFun(info) == 0);
} }
if (ok) { if (ok) {
return GIF_OK; return (GIF_OK);
} else { } else {
info->gifFilePtr->Error = D_GIF_ERR_READ_FAILED; info->gifFilePtr->Error = D_GIF_ERR_READ_FAILED;
return GIF_ERROR; return (GIF_ERROR);
} }
} }
...@@ -381,7 +389,7 @@ static argb *getAddr(argb *bm, int width, int left, int top) { ...@@ -381,7 +389,7 @@ static argb *getAddr(argb *bm, int width, int left, int top) {
} }
static void blitNormal(argb *bm, int width, int height, const SavedImage *frame, const ColorMapObject *cmap, int transparent) { static void blitNormal(argb *bm, int width, int height, const SavedImage *frame, const ColorMapObject *cmap, int transparent) {
const unsigned char *src = (unsigned char *)frame->RasterBits; const unsigned char* src = (unsigned char*) frame->RasterBits;
argb *dst = getAddr(bm, width, frame->ImageDesc.Left, frame->ImageDesc.Top); argb *dst = getAddr(bm, width, frame->ImageDesc.Left, frame->ImageDesc.Top);
GifWord copyWidth = frame->ImageDesc.Width; GifWord copyWidth = frame->ImageDesc.Width;
if (frame->ImageDesc.Left + copyWidth > width) { if (frame->ImageDesc.Left + copyWidth > width) {
...@@ -393,9 +401,6 @@ static void blitNormal(argb *bm, int width, int height, const SavedImage *frame, ...@@ -393,9 +401,6 @@ static void blitNormal(argb *bm, int width, int height, const SavedImage *frame,
copyHeight = height - frame->ImageDesc.Top; copyHeight = height - frame->ImageDesc.Top;
} }
int srcPad, dstPad;
dstPad = width - copyWidth;
srcPad = frame->ImageDesc.Width - copyWidth;
for (; copyHeight > 0; copyHeight--) { for (; copyHeight > 0; copyHeight--) {
copyLine(dst, src, cmap, transparent, copyWidth); copyLine(dst, src, cmap, transparent, copyWidth);
src += frame->ImageDesc.Width; src += frame->ImageDesc.Width;
...@@ -404,7 +409,7 @@ static void blitNormal(argb *bm, int width, int height, const SavedImage *frame, ...@@ -404,7 +409,7 @@ static void blitNormal(argb *bm, int width, int height, const SavedImage *frame,
} }
static void fillRect(argb *bm, int bmWidth, int bmHeight, GifWord left, GifWord top, GifWord width, GifWord height, argb col) { static void fillRect(argb *bm, int bmWidth, int bmHeight, GifWord left, GifWord top, GifWord width, GifWord height, argb col) {
uint32_t *dst = (uint32_t *)getAddr(bm, bmWidth, left, top); uint32_t* dst = (uint32_t*) getAddr(bm, bmWidth, left, top);
GifWord copyWidth = width; GifWord copyWidth = width;
if (left + copyWidth > bmWidth) { if (left + copyWidth > bmWidth) {
copyWidth = bmWidth - left; copyWidth = bmWidth - left;
...@@ -414,7 +419,7 @@ static void fillRect(argb *bm, int bmWidth, int bmHeight, GifWord left, GifWord ...@@ -414,7 +419,7 @@ static void fillRect(argb *bm, int bmWidth, int bmHeight, GifWord left, GifWord
if (top + copyHeight > bmHeight) { if (top + copyHeight > bmHeight) {
copyHeight = bmHeight - top; copyHeight = bmHeight - top;
} }
uint32_t *pColor = (uint32_t *)(&col); uint32_t* pColor = (uint32_t *) (&col);
for (; copyHeight > 0; copyHeight--) { for (; copyHeight > 0; copyHeight--) {
memset(dst, *pColor, copyWidth * sizeof(argb)); memset(dst, *pColor, copyWidth * sizeof(argb));
dst += bmWidth; dst += bmWidth;
...@@ -424,12 +429,11 @@ static void fillRect(argb *bm, int bmWidth, int bmHeight, GifWord left, GifWord ...@@ -424,12 +429,11 @@ static void fillRect(argb *bm, int bmWidth, int bmHeight, GifWord left, GifWord
static void drawFrame(argb *bm, int bmWidth, int bmHeight, const SavedImage *frame, const ColorMapObject *cmap, short transpIndex) { static void drawFrame(argb *bm, int bmWidth, int bmHeight, const SavedImage *frame, const ColorMapObject *cmap, short transpIndex) {
if (frame->ImageDesc.ColorMap != NULL) { if (frame->ImageDesc.ColorMap != NULL) {
cmap = frame->ImageDesc.ColorMap; cmap = frame->ImageDesc.ColorMap;
if (cmap == NULL || cmap->ColorCount != (1 << cmap->BitsPerPixel)) { if (cmap->ColorCount != (1 << cmap->BitsPerPixel)) {
cmap = defaultCmap; cmap = defaultCmap;
} }
} }
blitNormal(bm, bmWidth, bmHeight, frame, cmap, transpIndex);
blitNormal(bm, bmWidth, bmHeight, frame, cmap, (int) transpIndex);
} }
static bool checkIfCover(const SavedImage *target, const SavedImage *covered) { static bool checkIfCover(const SavedImage *target, const SavedImage *covered) {
...@@ -445,30 +449,28 @@ static bool checkIfCover(const SavedImage *target, const SavedImage *covered) { ...@@ -445,30 +449,28 @@ static bool checkIfCover(const SavedImage *target, const SavedImage *covered) {
} }
static inline void disposeFrameIfNeeded(argb *bm, GifInfo *info, unsigned int idx) { static inline void disposeFrameIfNeeded(argb *bm, GifInfo *info, unsigned int idx) {
argb *backup = info->backupPtr; argb* backup = info->backupPtr;
argb color; argb color;
packARGB32(&color, 0, 0, 0, 0); packARGB32(&color, 0, 0, 0, 0);
GifFileType *fGif = info->gifFilePtr; GifFileType *fGif = info->gifFilePtr;
SavedImage *cur = &fGif->SavedImages[idx - 1]; SavedImage* cur = &fGif->SavedImages[idx - 1];
SavedImage *next = &fGif->SavedImages[idx]; SavedImage* next = &fGif->SavedImages[idx];
bool curTrans = info->infos[idx - 1].transpIndex != -1; bool curTrans = info->infos[idx - 1].transpIndex != -1;
int curDisposal = info->infos[idx - 1].disposalMethod; int curDisposal = info->infos[idx - 1].disposalMethod;
bool nextTrans = info->infos[idx].transpIndex != -1; bool nextTrans = info->infos[idx].transpIndex != -1;
int nextDisposal = info->infos[idx].disposalMethod; int nextDisposal = info->infos[idx].disposalMethod;
argb *tmp; argb *tmp;
if ((curDisposal == 2 || curDisposal == 3) && (nextTrans || !checkIfCover(next, cur))) { if ((curDisposal == 2 || curDisposal == 3) && (nextTrans || !checkIfCover(next, cur))) {
switch (curDisposal) { switch (curDisposal) {
case 2: { case 2:
fillRect(bm, fGif->SWidth, fGif->SHeight, cur->ImageDesc.Left, cur->ImageDesc.Top, cur->ImageDesc.Width, cur->ImageDesc.Height, color); fillRect(bm, fGif->SWidth, fGif->SHeight, cur->ImageDesc.Left, cur->ImageDesc.Top, cur->ImageDesc.Width, cur->ImageDesc.Height, color);
}
break; break;
case 3: { case 3:
tmp = bm; tmp = bm;
bm = backup; bm = backup;
backup = tmp; backup = tmp;
}
break; break;
} }
} }
...@@ -478,27 +480,25 @@ static inline void disposeFrameIfNeeded(argb *bm, GifInfo *info, unsigned int id ...@@ -478,27 +480,25 @@ static inline void disposeFrameIfNeeded(argb *bm, GifInfo *info, unsigned int id
} }
} }
static jboolean reset(GifInfo *info) { static void reset(GifInfo *info) {
if (fileRewindFun(info) != 0) { if (fileRewindFun(info) != 0) {
return JNI_FALSE; return;
} }
info->nextStartTime = 0; info->nextStartTime = 0;
info->currentLoop = -1; info->currentLoop = -1;
info->currentIndex = -1; info->currentIndex = -1;
return JNI_TRUE;
} }
static void getBitmap(argb *bm, GifInfo *info) { static void getBitmap(argb *bm, GifInfo *info) {
GifFileType *fGIF = info->gifFilePtr; GifFileType* fGIF = info->gifFilePtr;
argb paintingColor; argb paintingColor;
int i = info->currentIndex; int i = info->currentIndex;
if (DDGifSlurp(fGIF, info, true) == GIF_ERROR) { if (DDGifSlurp(fGIF, info, true) == GIF_ERROR) {
return; //TODO add leniency support return;
} }
SavedImage *cur = &fGIF->SavedImages[i]; SavedImage* cur = &fGIF->SavedImages[i];
int transpIndex = info->infos[i].transpIndex;
short transpIndex = info->infos[i].transpIndex;
if (i == 0) { if (i == 0) {
if (transpIndex == -1) { if (transpIndex == -1) {
getColorFromTable(fGIF->SBackGroundColor, &paintingColor, fGIF->SColorMap); getColorFromTable(fGIF->SBackGroundColor, &paintingColor, fGIF->SColorMap);
...@@ -513,11 +513,14 @@ static void getBitmap(argb *bm, GifInfo *info) { ...@@ -513,11 +513,14 @@ static void getBitmap(argb *bm, GifInfo *info) {
} }
static void setMetaData(int width, int height, int ImageCount, int errorCode, JNIEnv *env, jintArray metaData) { static void setMetaData(int width, int height, int ImageCount, int errorCode, JNIEnv *env, jintArray metaData) {
jint *ints = (*env)->GetIntArrayElements(env, metaData, 0); jint *const ints = (*env)->GetIntArrayElements(env, metaData, 0);
*ints++ = width; if (ints == NULL) {
*ints++ = height; return;
*ints++ = ImageCount; }
*ints = errorCode; ints[0] = width;
ints[1] = height;
ints[2] = ImageCount;
ints[3] = errorCode;
(*env)->ReleaseIntArrayElements(env, metaData, ints, 0); (*env)->ReleaseIntArrayElements(env, metaData, ints, 0);
} }
...@@ -554,9 +557,6 @@ static jint open(GifFileType *GifFileIn, int Error, int startPos, JNIEnv *env, j ...@@ -554,9 +557,6 @@ static jint open(GifFileType *GifFileIn, int Error, int startPos, JNIEnv *env, j
info->speedFactor = 1.0; info->speedFactor = 1.0;
info->rasterBits = calloc(GifFileIn->SHeight * GifFileIn->SWidth, sizeof(GifPixelType)); info->rasterBits = calloc(GifFileIn->SHeight * GifFileIn->SWidth, sizeof(GifPixelType));
info->infos = malloc(sizeof(FrameInfo)); info->infos = malloc(sizeof(FrameInfo));
info->infos->duration = 0;
info->infos->disposalMethod = 0;
info->infos->transpIndex = -1;
info->backupPtr = NULL; info->backupPtr = NULL;
if (info->rasterBits == NULL || info->infos == NULL) { if (info->rasterBits == NULL || info->infos == NULL) {
...@@ -564,15 +564,18 @@ static jint open(GifFileType *GifFileIn, int Error, int startPos, JNIEnv *env, j ...@@ -564,15 +564,18 @@ static jint open(GifFileType *GifFileIn, int Error, int startPos, JNIEnv *env, j
setMetaData(width, height, 0, D_GIF_ERR_NOT_ENOUGH_MEM, env, metaData); setMetaData(width, height, 0, D_GIF_ERR_NOT_ENOUGH_MEM, env, metaData);
return (jint) NULL; return (jint) NULL;
} }
info->infos->duration = 0;
if (DDGifSlurp(GifFileIn, info, false) == GIF_ERROR) { info->infos->disposalMethod = 0;
Error = GifFileIn->Error; info->infos->transpIndex = -1;
}
if (GifFileIn->SColorMap == NULL || GifFileIn->SColorMap->ColorCount != (1 << GifFileIn->SColorMap->BitsPerPixel)) { if (GifFileIn->SColorMap == NULL || GifFileIn->SColorMap->ColorCount != (1 << GifFileIn->SColorMap->BitsPerPixel)) {
GifFreeMapObject(GifFileIn->SColorMap); GifFreeMapObject(GifFileIn->SColorMap);
GifFileIn->SColorMap = defaultCmap; GifFileIn->SColorMap = defaultCmap;
} }
DDGifSlurp(GifFileIn, info, false);
int imgCount = GifFileIn->ImageCount; int imgCount = GifFileIn->ImageCount;
if (imgCount < 1) { if (imgCount < 1) {
Error = D_GIF_ERR_NO_FRAMES; Error = D_GIF_ERR_NO_FRAMES;
} }
...@@ -583,7 +586,6 @@ static jint open(GifFileType *GifFileIn, int Error, int startPos, JNIEnv *env, j ...@@ -583,7 +586,6 @@ static jint open(GifFileType *GifFileIn, int Error, int startPos, JNIEnv *env, j
cleanUp(info); cleanUp(info);
} }
setMetaData(width, height, imgCount, Error, env, metaData); setMetaData(width, height, imgCount, Error, env, metaData);
return (jint)(Error == 0 ? info : NULL); return (jint)(Error == 0 ? info : NULL);
} }
...@@ -600,12 +602,12 @@ JNIEXPORT jlong JNICALL Java_org_telegram_ui_Views_GifDrawable_getAllocationByte ...@@ -600,12 +602,12 @@ JNIEXPORT jlong JNICALL Java_org_telegram_ui_Views_GifDrawable_getAllocationByte
return sum; return sum;
} }
JNIEXPORT jboolean JNICALL Java_org_telegram_ui_Views_GifDrawable_reset(JNIEnv *env, jclass class, jobject gifInfo) { JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_reset(JNIEnv *env, jclass class, jobject gifInfo) {
GifInfo *info = (GifInfo *)gifInfo; GifInfo *info = (GifInfo *)gifInfo;
if (info == NULL) { if (info == NULL) {
return JNI_FALSE; return;
} }
return reset(info); reset(info);
} }
JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_setSpeedFactor(JNIEnv *env, jclass class, jobject gifInfo, jfloat factor) { JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_setSpeedFactor(JNIEnv *env, jclass class, jobject gifInfo, jfloat factor) {
...@@ -618,7 +620,7 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_setSpeedFactor(JNI ...@@ -618,7 +620,7 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_setSpeedFactor(JNI
JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToTime(JNIEnv *env, jclass class, jobject gifInfo, jint desiredPos, jintArray jPixels) { JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToTime(JNIEnv *env, jclass class, jobject gifInfo, jint desiredPos, jintArray jPixels) {
GifInfo *info = (GifInfo *)gifInfo; GifInfo *info = (GifInfo *)gifInfo;
if (info == NULL) { if (info == NULL || jPixels == NULL) {
return; return;
} }
int imgCount = info->gifFilePtr->ImageCount; int imgCount = info->gifFilePtr->ImageCount;
...@@ -643,15 +645,19 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToTime(JNIEnv ...@@ -643,15 +645,19 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToTime(JNIEnv
if (i == imgCount - 1 && lastFrameRemainder > info->infos[i].duration) { if (i == imgCount - 1 && lastFrameRemainder > info->infos[i].duration) {
lastFrameRemainder = info->infos[i].duration; lastFrameRemainder = info->infos[i].duration;
} }
info->lastFrameReaminder = lastFrameRemainder;
if (i > info->currentIndex) { if (i > info->currentIndex) {
jint *pixels = (*env)->GetIntArrayElements(env, jPixels, 0); jint *const pixels = (*env)->GetIntArrayElements(env, jPixels, 0);
if (pixels == NULL) {
return;
}
while (info->currentIndex <= i) { while (info->currentIndex <= i) {
info->currentIndex++; info->currentIndex++;
getBitmap((argb *)pixels, info); getBitmap((argb*) pixels, info);
} }
(*env)->ReleaseIntArrayElements(env, jPixels, pixels, 0); (*env)->ReleaseIntArrayElements(env, jPixels, pixels, 0);
} }
info->lastFrameReaminder = lastFrameRemainder;
if (info->speedFactor == 1.0) { if (info->speedFactor == 1.0) {
info->nextStartTime = getRealTime() + lastFrameRemainder; info->nextStartTime = getRealTime() + lastFrameRemainder;
} else { } else {
...@@ -661,7 +667,7 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToTime(JNIEnv ...@@ -661,7 +667,7 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToTime(JNIEnv
JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToFrame(JNIEnv *env, jclass class, jobject gifInfo, jint desiredIdx, jintArray jPixels) { JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToFrame(JNIEnv *env, jclass class, jobject gifInfo, jint desiredIdx, jintArray jPixels) {
GifInfo *info = (GifInfo *)gifInfo; GifInfo *info = (GifInfo *)gifInfo;
if (info == NULL) { if (info == NULL|| jPixels==NULL) {
return; return;
} }
if (desiredIdx <= info->currentIndex) { if (desiredIdx <= info->currentIndex) {
...@@ -673,15 +679,19 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToFrame(JNIEnv ...@@ -673,15 +679,19 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToFrame(JNIEnv
return; return;
} }
jint *const pixels = (*env)->GetIntArrayElements(env, jPixels, 0);
if (pixels == NULL) {
return;
}
info->lastFrameReaminder = 0;
if (desiredIdx >= imgCount) { if (desiredIdx >= imgCount) {
desiredIdx = imgCount - 1; desiredIdx = imgCount - 1;
} }
info->lastFrameReaminder = 0;
jint *pixels = (*env)->GetIntArrayElements(env, jPixels, 0);
while (info->currentIndex < desiredIdx) { while (info->currentIndex < desiredIdx) {
info->currentIndex++; info->currentIndex++;
getBitmap((argb *)pixels, info); getBitmap((argb *) pixels, info);
} }
(*env)->ReleaseIntArrayElements(env, jPixels, pixels, 0); (*env)->ReleaseIntArrayElements(env, jPixels, pixels, 0);
if (info->speedFactor == 1.0) { if (info->speedFactor == 1.0) {
...@@ -689,16 +699,13 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToFrame(JNIEnv ...@@ -689,16 +699,13 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_seekToFrame(JNIEnv
} else { } else {
info->nextStartTime = getRealTime() + info->infos[info->currentIndex].duration * info->speedFactor; info->nextStartTime = getRealTime() + info->infos[info->currentIndex].duration * info->speedFactor;
} }
} }
JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_renderFrame(JNIEnv *env, jclass class, jintArray jPixels, jobject gifInfo, jintArray metaData) { JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_renderFrame(JNIEnv *env, jclass class, jintArray jPixels, jobject gifInfo, jintArray metaData) {
GifInfo *info = (GifInfo *)gifInfo; GifInfo *info = (GifInfo *)gifInfo;
if (info == NULL) { if (info == NULL || jPixels == NULL) {
return; return;
} }
bool needRedraw = false; bool needRedraw = false;
unsigned long rt = getRealTime(); unsigned long rt = getRealTime();
...@@ -708,23 +715,39 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_renderFrame(JNIEnv ...@@ -708,23 +715,39 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_renderFrame(JNIEnv
} }
needRedraw = true; needRedraw = true;
} }
jint *rawMetaData = (*env)->GetIntArrayElements(env, metaData, 0); jint *const rawMetaData = (*env)->GetIntArrayElements(env, metaData, 0);
if (rawMetaData == NULL) {
return;
}
if (needRedraw) { if (needRedraw) {
jint *pixels = (*env)->GetIntArrayElements(env, jPixels, 0); jint *const pixels = (*env)->GetIntArrayElements(env, jPixels, 0);
if (pixels == NULL) {
(*env)->ReleaseIntArrayElements(env, metaData, rawMetaData, 0);
return;
}
getBitmap((argb *)pixels, info); getBitmap((argb *)pixels, info);
rawMetaData[3] = info->gifFilePtr->Error; rawMetaData[3] = info->gifFilePtr->Error;
(*env)->ReleaseIntArrayElements(env, jPixels, pixels, 0); (*env)->ReleaseIntArrayElements(env, jPixels, pixels, 0);
unsigned int scaledDuration = info->infos[info->currentIndex].duration;
int scaledDuration = info->infos[info->currentIndex].duration;
if (info->speedFactor != 1.0) { if (info->speedFactor != 1.0) {
scaledDuration /= info->speedFactor; scaledDuration /= info->speedFactor;
if (scaledDuration<=0) {
scaledDuration=1;
} else if (scaledDuration > INT_MAX) {
scaledDuration = INT_MAX;
}
} }
info->nextStartTime = rt + scaledDuration; info->nextStartTime = rt + scaledDuration;
rawMetaData[4] = scaledDuration; rawMetaData[4] = scaledDuration;
} else { } else {
rawMetaData[4] = (int) (rt - info->nextStartTime); long delay = info->nextStartTime-rt;
if (delay < 0) {
rawMetaData[4] = -1;
} else {
rawMetaData[4] = (int) delay;
}
} }
(*env)->ReleaseIntArrayElements(env, metaData, rawMetaData, 0); (*env)->ReleaseIntArrayElements(env, metaData, rawMetaData, 0);
} }
...@@ -794,9 +817,6 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_saveRemainder(JNIE ...@@ -794,9 +817,6 @@ JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_saveRemainder(JNIE
return; return;
} }
info->lastFrameReaminder = getRealTime() - info->nextStartTime; info->lastFrameReaminder = getRealTime() - info->nextStartTime;
if (info->lastFrameReaminder > 0) {
info->lastFrameReaminder = 0;
}
} }
JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_restoreRemainder(JNIEnv *env, jclass class, jobject gifInfo) { JNIEXPORT void JNICALL Java_org_telegram_ui_Views_GifDrawable_restoreRemainder(JNIEnv *env, jclass class, jobject gifInfo) {
...@@ -814,7 +834,7 @@ JNIEXPORT jint JNICALL Java_org_telegram_ui_Views_GifDrawable_openFile(JNIEnv *e ...@@ -814,7 +834,7 @@ JNIEXPORT jint JNICALL Java_org_telegram_ui_Views_GifDrawable_openFile(JNIEnv *e
return (jint) NULL; return (jint) NULL;
} }
const char *fname = (*env)->GetStringUTFChars(env, jfname, 0); const char *const fname = (*env)->GetStringUTFChars(env, jfname, 0);
FILE *file = fopen(fname, "rb"); FILE *file = fopen(fname, "rb");
(*env)->ReleaseStringUTFChars(env, jfname, fname); (*env)->ReleaseStringUTFChars(env, jfname, fname);
if (file == NULL) { if (file == NULL) {
......
...@@ -2,8 +2,101 @@ ...@@ -2,8 +2,101 @@
#include <stdio.h> #include <stdio.h>
#include <setjmp.h> #include <setjmp.h>
#include <libjpeg/jpeglib.h> #include <libjpeg/jpeglib.h>
#include <android/bitmap.h>
#include "utils.h" #include "utils.h"
static inline uint64_t get_colors (const uint8_t *p) {
return p[0] + (p[1] << 16) + ((uint64_t)p[2] << 32);
}
static void fastBlur(int imageWidth, int imageHeight, int imageStride, void *pixels) {
uint8_t *pix = (uint8_t *)pixels;
const int w = imageWidth;
const int h = imageHeight;
const int stride = imageStride;
const int radius = 3;
const int r1 = radius + 1;
const int div = radius * 2 + 1;
if (radius > 15 || div >= w || div >= h) {
return;
}
uint64_t rgb[imageStride * imageHeight];
int x, y, i;
int yw = 0;
const int we = w - r1;
for (y = 0; y < h; y++) {
uint64_t cur = get_colors (&pix[yw]);
uint64_t rgballsum = -radius * cur;
uint64_t rgbsum = cur * ((r1 * (r1 + 1)) >> 1);
for (i = 1; i <= radius; i++) {
uint64_t cur = get_colors (&pix[yw + i * 4]);
rgbsum += cur * (r1 - i);
rgballsum += cur;
}
x = 0;
#define update(start, middle, end) \
rgb[y * w + x] = (rgbsum >> 4) & 0x00FF00FF00FF00FFLL; \
rgballsum += get_colors (&pix[yw + (start) * 4]) - 2 * get_colors (&pix[yw + (middle) * 4]) + get_colors (&pix[yw + (end) * 4]); \
rgbsum += rgballsum; \
x++; \
while (x < r1) {
update (0, x, x + r1);
}
while (x < we) {
update (x - r1, x, x + r1);
}
while (x < w) {
update (x - r1, x, w - 1);
}
#undef update
yw += stride;
}
const int he = h - r1;
for (x = 0; x < w; x++) {
uint64_t rgballsum = -radius * rgb[x];
uint64_t rgbsum = rgb[x] * ((r1 * (r1 + 1)) >> 1);
for (i = 1; i <= radius; i++) {
rgbsum += rgb[i * w + x] * (r1 - i);
rgballsum += rgb[i * w + x];
}
y = 0;
int yi = x * 4;
#define update(start, middle, end) \
int64_t res = rgbsum >> 4; \
pix[yi] = res; \
pix[yi + 1] = res >> 16; \
pix[yi + 2] = res >> 32; \
rgballsum += rgb[x + (start) * w] - 2 * rgb[x + (middle) * w] + rgb[x + (end) * w]; \
rgbsum += rgballsum; \
y++; \
yi += stride;
while (y < r1) {
update (0, y, y + r1);
}
while (y < he) {
update (y - r1, y, y + r1);
}
while (y < h) {
update (y - r1, y, h - 1);
}
#undef update
}
}
typedef struct my_error_mgr { typedef struct my_error_mgr {
struct jpeg_error_mgr pub; struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer; jmp_buf setjmp_buffer;
...@@ -16,6 +109,15 @@ METHODDEF(void) my_error_exit(j_common_ptr cinfo) { ...@@ -16,6 +109,15 @@ METHODDEF(void) my_error_exit(j_common_ptr cinfo) {
longjmp(myerr->setjmp_buffer, 1); longjmp(myerr->setjmp_buffer, 1);
} }
JNIEXPORT void Java_org_telegram_messenger_Utilities_blurBitmap(JNIEnv *env, jclass class, jobject bitmap, int width, int height, int stride) {
void *pixels = 0;
if (AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
return;
}
fastBlur(width, height, stride, pixels);
AndroidBitmap_unlockPixels(env, bitmap);
}
JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jclass class, jstring path, jintArray bitmap, int scale, int format, int width, int height) { JNIEXPORT void Java_org_telegram_messenger_Utilities_loadBitmap(JNIEnv *env, jclass class, jstring path, jintArray bitmap, int scale, int format, int width, int height) {
int i; int i;
......
...@@ -221,4 +221,8 @@ public class AndroidUtilities { ...@@ -221,4 +221,8 @@ public class AndroidUtilities {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
} }
public static long makeBroadcastId(int id) {
return 0x0000000100000000L | ((long)id & 0x00000000FFFFFFFFL);
}
} }
...@@ -47,10 +47,7 @@ public class ContactsController { ...@@ -47,10 +47,7 @@ public class ContactsController {
private final Integer observerLock = 1; private final Integer observerLock = 1;
public boolean contactsLoaded = false; public boolean contactsLoaded = false;
private boolean contactsBookLoaded = false; private boolean contactsBookLoaded = false;
private int lastContactsPhonesCount = -1; private String lastContactsVersions = "";
private int lastContactsPhonesMaxId = -1;
private int lastContactsNamesCount = -1;
private int lastContactsNamesMaxId = -1;
private ArrayList<Integer> delayedContactsUpdate = new ArrayList<Integer>(); private ArrayList<Integer> delayedContactsUpdate = new ArrayList<Integer>();
public static class Contact { public static class Contact {
...@@ -119,10 +116,7 @@ public class ContactsController { ...@@ -119,10 +116,7 @@ public class ContactsController {
contactsSyncInProgress = false; contactsSyncInProgress = false;
contactsLoaded = false; contactsLoaded = false;
contactsBookLoaded = false; contactsBookLoaded = false;
lastContactsPhonesCount = -1; lastContactsVersions = "";
lastContactsPhonesMaxId = -1;
lastContactsNamesCount = -1;
lastContactsNamesMaxId = -1;
} }
public void checkAppAccount() { public void checkAppAccount() {
...@@ -191,70 +185,17 @@ public class ContactsController { ...@@ -191,70 +185,17 @@ public class ContactsController {
ContentResolver cr = ApplicationLoader.applicationContext.getContentResolver(); ContentResolver cr = ApplicationLoader.applicationContext.getContentResolver();
Cursor pCur = null; Cursor pCur = null;
try { try {
pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone._ID}, null, null, ContactsContract.CommonDataKinds.Phone._ID + " desc LIMIT 1"); pCur = cr.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts.VERSION}, null, null, null);
if (pCur != null) { StringBuilder currentVersion = new StringBuilder();
if (pCur.getCount() > 0 && pCur.moveToFirst()) { while (pCur.moveToNext()) {
int value = pCur.getInt(0); int col = pCur.getColumnIndex(ContactsContract.RawContacts.VERSION);
if (lastContactsPhonesMaxId != -1 && value != lastContactsPhonesMaxId) { currentVersion.append(pCur.getString(col));
reload = true;
}
lastContactsPhonesMaxId = value;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
if (pCur != null) {
pCur.close();
}
}
try {
pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone._COUNT}, null, null, null);
if (pCur != null) {
if (pCur.getCount() > 0 && pCur.moveToFirst()) {
int value = pCur.getInt(0);
if (lastContactsPhonesCount != -1 && value != lastContactsPhonesCount) {
reload = true;
}
lastContactsPhonesCount = value;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
if (pCur != null) {
pCur.close();
}
}
try {
pCur = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data._COUNT}, ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'", null, null);
if (pCur != null) {
if (pCur.getCount() > 0 && pCur.moveToFirst()) {
int value = pCur.getInt(0);
if (lastContactsNamesCount != -1 && value != lastContactsNamesCount) {
reload = true;
}
lastContactsNamesCount = value;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
} finally {
if (pCur != null) {
pCur.close();
}
} }
try { String newContactsVersion = currentVersion.toString();
pCur = cr.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data._ID}, ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'", null, ContactsContract.Data._ID + " desc LIMIT 1"); if (lastContactsVersions.length() != 0 && !lastContactsVersions.equals(newContactsVersion)) {
if (pCur != null) {
if (pCur.getCount() > 0 && pCur.moveToFirst()) {
int value = pCur.getInt(0);
if (lastContactsNamesMaxId != -1 && value != lastContactsNamesMaxId) {
reload = true; reload = true;
} }
lastContactsNamesMaxId = value; lastContactsVersions = newContactsVersion;
}
}
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} finally { } finally {
...@@ -368,7 +309,7 @@ public class ContactsController { ...@@ -368,7 +309,7 @@ public class ContactsController {
String sname2 = pCur.getString(3); String sname2 = pCur.getString(3);
String mname = pCur.getString(4); String mname = pCur.getString(4);
Contact contact = contactsMap.get(id); Contact contact = contactsMap.get(id);
if (contact != null) { if (contact != null && contact.first_name.length() == 0 && contact.last_name.length() == 0) {
contact.first_name = fname; contact.first_name = fname;
contact.last_name = sname; contact.last_name = sname;
if (contact.first_name == null) { if (contact.first_name == null) {
...@@ -535,7 +476,8 @@ public class ContactsController { ...@@ -535,7 +476,8 @@ public class ContactsController {
} }
} }
if (existing == null || existing != null && (!existing.first_name.equals(value.first_name) || !existing.last_name.equals(value.last_name))) { boolean nameChanged = existing != null && (!existing.first_name.equals(value.first_name) || !existing.last_name.equals(value.last_name));
if (existing == null || nameChanged) {
for (int a = 0; a < value.phones.size(); a++) { for (int a = 0; a < value.phones.size(); a++) {
String sphone = value.shortPhones.get(a); String sphone = value.shortPhones.get(a);
contactsBookShort.put(sphone, value); contactsBookShort.put(sphone, value);
...@@ -550,7 +492,7 @@ public class ContactsController { ...@@ -550,7 +492,7 @@ public class ContactsController {
} }
} }
if (request) { if (request) {
if (contactsByPhone.containsKey(sphone)) { if (!nameChanged && contactsByPhone.containsKey(sphone)) {
continue; continue;
} }
......
...@@ -92,6 +92,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -92,6 +92,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public boolean enableJoined = true; public boolean enableJoined = true;
public int fontSize = AndroidUtilities.dp(16); public int fontSize = AndroidUtilities.dp(16);
public int maxGroupCount = 200;
public int maxBroadcastCount = 100;
private TLRPC.ChatParticipants currentChatInfo = null;
private int chatParticipantsId = 0;
private class UserActionUpdates extends TLRPC.Updates { private class UserActionUpdates extends TLRPC.Updates {
...@@ -118,7 +123,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -118,7 +123,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
private class DelayedMessage { private class DelayedMessage {
public TLRPC.TL_messages_sendMedia sendRequest; public TLObject sendRequest;
public TLRPC.TL_decryptedMessage sendEncryptedRequest; public TLRPC.TL_decryptedMessage sendEncryptedRequest;
public int type; public int type;
public String originalPath; public String originalPath;
...@@ -182,14 +187,32 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -182,14 +187,32 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage storage = MessagesStorage.getInstance(); MessagesStorage storage = MessagesStorage.getInstance();
NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidUpload); NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidUpload);
NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidFailUpload); NotificationCenter.getInstance().addObserver(this, FileLoader.FileDidFailUpload);
NotificationCenter.getInstance().addObserver(this, 10); NotificationCenter.getInstance().addObserver(this, chatInfoDidLoaded);
NotificationCenter.getInstance().addObserver(this, messageReceivedByServer);
addSupportUser(); addSupportUser();
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
enableJoined = preferences.getBoolean("EnableContactJoined", true); enableJoined = preferences.getBoolean("EnableContactJoined", true);
preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
maxGroupCount = preferences.getInt("maxGroupCount", 200);
maxBroadcastCount = preferences.getInt("maxBroadcastCount", 100);
fontSize = preferences.getInt("fons_size", 16); fontSize = preferences.getInt("fons_size", 16);
} }
public void updateConfig(final TLRPC.TL_config config) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
maxBroadcastCount = config.broadcast_size_max;
maxGroupCount = config.chat_size_max;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("maxGroupCount", maxGroupCount);
editor.putInt("maxBroadcastCount", maxBroadcastCount);
editor.commit();
}
});
}
public void addSupportUser() { public void addSupportUser() {
TLRPC.TL_userForeign user = new TLRPC.TL_userForeign(); TLRPC.TL_userForeign user = new TLRPC.TL_userForeign();
user.phone = "333"; user.phone = "333";
...@@ -282,28 +305,35 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -282,28 +305,35 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (arr != null) { if (arr != null) {
for (int a = 0; a < arr.size(); a++) { for (int a = 0; a < arr.size(); a++) {
DelayedMessage message = arr.get(a); DelayedMessage message = arr.get(a);
if (file != null && message.sendRequest != null) { TLRPC.InputMedia media = null;
if (message.sendRequest instanceof TLRPC.TL_messages_sendMedia) {
media = ((TLRPC.TL_messages_sendMedia)message.sendRequest).media;
} else if (message.sendRequest instanceof TLRPC.TL_messages_sendBroadcast) {
media = ((TLRPC.TL_messages_sendBroadcast)message.sendRequest).media;
}
if (file != null && media != null) {
if (message.type == 0) { if (message.type == 0) {
message.sendRequest.media.file = file; media.file = file;
performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); performSendMessageRequest(message.sendRequest, message.obj, message.originalPath);
} else if (message.type == 1) { } else if (message.type == 1) {
if (message.sendRequest.media.thumb == null) { if (media.thumb == null) {
message.sendRequest.media.thumb = file; media.thumb = file;
performSendDelayedMessage(message); performSendDelayedMessage(message);
} else { } else {
message.sendRequest.media.file = file; media.file = file;
performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); performSendMessageRequest(message.sendRequest, message.obj, message.originalPath);
} }
} else if (message.type == 2) { } else if (message.type == 2) {
if (message.sendRequest.media.thumb == null && message.location != null) { if (media.thumb == null && message.location != null) {
message.sendRequest.media.thumb = file; media.thumb = file;
performSendDelayedMessage(message); performSendDelayedMessage(message);
} else { } else {
message.sendRequest.media.file = file; media.file = file;
performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); performSendMessageRequest(message.sendRequest, message.obj, message.originalPath);
} }
} else if (message.type == 3) { } else if (message.type == 3) {
message.sendRequest.media.file = file; media.file = file;
performSendMessageRequest(message.sendRequest, message.obj, message.originalPath); performSendMessageRequest(message.sendRequest, message.obj, message.originalPath);
} }
arr.remove(a); arr.remove(a);
...@@ -380,6 +410,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -380,6 +410,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
} }
} else if (id == chatInfoDidLoaded) {
int chatId = (Integer)args[0];
if (chatParticipantsId == chatId) {
currentChatInfo = (TLRPC.ChatParticipants)args[1];
}
} }
} }
...@@ -388,6 +423,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -388,6 +423,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
super.finalize(); super.finalize();
NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidUpload); NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidUpload);
NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidFailUpload); NotificationCenter.getInstance().removeObserver(this, FileLoader.FileDidFailUpload);
NotificationCenter.getInstance().removeObserver(this, chatInfoDidLoaded);
NotificationCenter.getInstance().removeObserver(this, messageReceivedByServer); NotificationCenter.getInstance().removeObserver(this, messageReceivedByServer);
} }
...@@ -432,6 +468,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -432,6 +468,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
startingSecretChat = false; startingSecretChat = false;
statusRequest = 0; statusRequest = 0;
statusSettingState = 0; statusSettingState = 0;
currentChatInfo = null;
chatParticipantsId = 0;
addSupportUser(); addSupportUser();
} }
...@@ -689,6 +727,23 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -689,6 +727,23 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) { if (error == null) {
final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, true, true);
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
for (TLRPC.User user : res.users) {
users.put(user.id, user);
if (user.id == UserConfig.getClientUserId()) {
UserConfig.setCurrentUser(user);
}
}
for (TLRPC.Chat chat : res.chats) {
chats.put(chat.id, chat);
}
}
});
if (res instanceof TLRPC.TL_messages_messagesSlice) { if (res instanceof TLRPC.TL_messages_messagesSlice) {
processLoadedMediaCount(res.count, uid, classGuid, false); processLoadedMediaCount(res.count, uid, classGuid, false);
} else { } else {
...@@ -746,6 +801,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -746,6 +801,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
TLRPC.TL_dialog dialog = dialogs_dict.get(did); TLRPC.TL_dialog dialog = dialogs_dict.get(did);
if (dialog != null) { if (dialog != null) {
int lower_part = (int)did; int lower_part = (int)did;
int high_id = (int)(did >> 32);
if (offset == 0) { if (offset == 0) {
if (!onlyHistory) { if (!onlyHistory) {
...@@ -753,13 +809,33 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -753,13 +809,33 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialogsServerOnly.remove(dialog); dialogsServerOnly.remove(dialog);
dialogs_dict.remove(did); dialogs_dict.remove(did);
totalDialogsCount--; totalDialogsCount--;
} else {
dialog.unread_count = 0;
} }
dialogMessage.remove(dialog.top_message); dialogMessage.remove(dialog.top_message);
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
NotificationsController.getInstance().processReadMessages(null, did, 0, Integer.MAX_VALUE);
HashMap<Long, Integer> dialogsToUpdate = new HashMap<Long, Integer>();
dialogsToUpdate.put(did, 0);
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, true);
}
});
}
});
MessagesStorage.getInstance().deleteDialog(did, onlyHistory); MessagesStorage.getInstance().deleteDialog(did, onlyHistory);
NotificationCenter.getInstance().postNotificationName(removeAllMessagesFromDialog, did); NotificationCenter.getInstance().postNotificationName(removeAllMessagesFromDialog, did);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
} }
if (high_id == 1) {
return;
}
if (lower_part != 0) { if (lower_part != 0) {
TLRPC.TL_messages_deleteHistory req = new TLRPC.TL_messages_deleteHistory(); TLRPC.TL_messages_deleteHistory req = new TLRPC.TL_messages_deleteHistory();
req.offset = offset; req.offset = offset;
...@@ -806,19 +882,20 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -806,19 +882,20 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
}); });
} else { } else {
int encId = (int)(did >> 32);
if (onlyHistory) { if (onlyHistory) {
TLRPC.EncryptedChat encryptedChat = encryptedChats.get(encId); TLRPC.EncryptedChat encryptedChat = encryptedChats.get(high_id);
sendClearHistoryMessage(encryptedChat); sendClearHistoryMessage(encryptedChat);
} else { } else {
declineSecretChat(encId); declineSecretChat(high_id);
} }
} }
} }
} }
public void loadChatInfo(final int chat_id) { public void loadChatInfo(final int chat_id, Semaphore semaphore) {
MessagesStorage.getInstance().loadChatInfo(chat_id); currentChatInfo = null;
chatParticipantsId = chat_id;
MessagesStorage.getInstance().loadChatInfo(chat_id, semaphore);
} }
public void processChatInfo(final int chat_id, final TLRPC.ChatParticipants info, final ArrayList<TLRPC.User> usersArr, final boolean fromCache) { public void processChatInfo(final int chat_id, final TLRPC.ChatParticipants info, final ArrayList<TLRPC.User> usersArr, final boolean fromCache) {
...@@ -877,7 +954,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -877,7 +954,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
checkDeletingTask(); checkDeletingTask();
if (UserConfig.isClientActivated()) { if (UserConfig.isClientActivated()) {
if (ConnectionsManager.getInstance().getPauseTime() == 0 && ApplicationLoader.isScreenOn) { if (ConnectionsManager.getInstance().getPauseTime() == 0 && ApplicationLoader.isScreenOn && !ApplicationLoader.mainInterfacePaused) {
if (statusSettingState != 1 && (lastStatusUpdateTime == 0 || lastStatusUpdateTime <= System.currentTimeMillis() - 55000 || offlineSent)) { if (statusSettingState != 1 && (lastStatusUpdateTime == 0 || lastStatusUpdateTime <= System.currentTimeMillis() - 55000 || offlineSent)) {
statusSettingState = 1; statusSettingState = 1;
...@@ -927,7 +1004,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -927,7 +1004,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 < currentTime) { if (updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 < currentTime) {
FileLog.e("tmessages", "UPDATES WAIT TIMEOUT - CHECK QUEUE"); FileLog.e("tmessages", "UPDATES WAIT TIMEOUT - CHECK QUEUE");
processUpdatesQueue(false); processUpdatesQueue(0);
} }
} }
if (!printingUsers.isEmpty() || lastPrintingStringCount != printingUsers.size()) { if (!printingUsers.isEmpty() || lastPrintingStringCount != printingUsers.size()) {
...@@ -1017,7 +1094,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1017,7 +1094,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
return; return;
} }
int lower_part = (int)dialog_id; int lower_part = (int)dialog_id;
int high_id = (int)(dialog_id >> 32);
if (lower_part != 0) { if (lower_part != 0) {
if (high_id == 1) {
return;
}
TLRPC.TL_messages_setTyping req = new TLRPC.TL_messages_setTyping(); TLRPC.TL_messages_setTyping req = new TLRPC.TL_messages_setTyping();
if (lower_part < 0) { if (lower_part < 0) {
req.peer = new TLRPC.TL_inputPeerChat(); req.peer = new TLRPC.TL_inputPeerChat();
...@@ -1046,8 +1128,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1046,8 +1128,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors); }, true, RPCRequest.RPCRequestClassGeneric | RPCRequest.RPCRequestClassFailOnServerErrors);
ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid); ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid);
} else { } else {
int encId = (int)(dialog_id >> 32); TLRPC.EncryptedChat chat = encryptedChats.get(high_id);
TLRPC.EncryptedChat chat = encryptedChats.get(encId);
if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) { if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) {
TLRPC.TL_messages_setEncryptedTyping req = new TLRPC.TL_messages_setEncryptedTyping(); TLRPC.TL_messages_setEncryptedTyping req = new TLRPC.TL_messages_setEncryptedTyping();
req.peer = new TLRPC.TL_inputEncryptedChat(); req.peer = new TLRPC.TL_inputEncryptedChat();
...@@ -1065,10 +1146,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1065,10 +1146,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
public void loadMessages(final long dialog_id, final int offset, final int count, final int max_id, boolean fromCache, int midDate, final int classGuid, boolean from_unread, boolean forward) { public void loadMessages(final long dialog_id, final int count, final int max_id, boolean fromCache, int midDate, final int classGuid, boolean from_unread, boolean forward) {
int lower_part = (int)dialog_id; int lower_part = (int)dialog_id;
if (fromCache || lower_part == 0) { if (fromCache || lower_part == 0) {
MessagesStorage.getInstance().getMessages(dialog_id, offset, count, max_id, midDate, classGuid, from_unread, forward); MessagesStorage.getInstance().getMessages(dialog_id, count, max_id, midDate, classGuid, from_unread, forward);
} else { } else {
TLRPC.TL_messages_getHistory req = new TLRPC.TL_messages_getHistory(); TLRPC.TL_messages_getHistory req = new TLRPC.TL_messages_getHistory();
if (lower_part < 0) { if (lower_part < 0) {
...@@ -1085,7 +1166,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1085,7 +1166,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
req.peer.user_id = user.id; req.peer.user_id = user.id;
} }
} }
req.offset = offset; req.offset = 0;
req.limit = count; req.limit = count;
req.max_id = max_id; req.max_id = max_id;
long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { long reqId = ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
...@@ -1093,7 +1174,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1093,7 +1174,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) { if (error == null) {
final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; final TLRPC.messages_Messages res = (TLRPC.messages_Messages) response;
processLoadedMessages(res, dialog_id, offset, count, max_id, false, classGuid, 0, 0, 0, 0, false); processLoadedMessages(res, dialog_id, count, max_id, false, classGuid, 0, 0, 0, 0, false);
} }
} }
}); });
...@@ -1101,7 +1182,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1101,7 +1182,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
public void processLoadedMessages(final TLRPC.messages_Messages messagesRes, final long dialog_id, final int offset, final int count, final int max_id, final boolean isCache, final int classGuid, final int first_unread, final int last_unread, final int unread_count, final int last_date, final boolean isForward) { public void processLoadedMessages(final TLRPC.messages_Messages messagesRes, final long dialog_id, final int count, final int max_id, final boolean isCache, final int classGuid, final int first_unread, final int last_unread, final int unread_count, final int last_date, final boolean isForward) {
Utilities.stageQueue.postRunnable(new Runnable() { Utilities.stageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
...@@ -1113,7 +1194,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1113,7 +1194,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
loadMessages(dialog_id, offset, count, max_id, false, 0, classGuid, false, false); loadMessages(dialog_id, count, max_id, false, 0, classGuid, false, false);
} }
}); });
return; return;
...@@ -1125,7 +1206,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1125,7 +1206,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
final ArrayList<MessageObject> objects = new ArrayList<MessageObject>(); final ArrayList<MessageObject> objects = new ArrayList<MessageObject>();
for (TLRPC.Message message : messagesRes.messages) { for (TLRPC.Message message : messagesRes.messages) {
message.dialog_id = dialog_id; message.dialog_id = dialog_id;
objects.add(new MessageObject(message, usersLocal)); objects.add(new MessageObject(message, usersLocal, 2));
} }
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
...@@ -1151,7 +1232,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1151,7 +1232,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
chats.put(c.id, c); chats.put(c.id, c);
} }
} }
NotificationCenter.getInstance().postNotificationName(messagesDidLoaded, dialog_id, offset, count, objects, isCache, first_unread, last_unread, unread_count, last_date, isForward); NotificationCenter.getInstance().postNotificationName(messagesDidLoaded, dialog_id, count, objects, isCache, first_unread, last_unread, unread_count, last_date, isForward);
} }
}); });
} }
...@@ -1234,7 +1315,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1234,7 +1315,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
for (TLRPC.Message m : dialogsRes.messages) { for (TLRPC.Message m : dialogsRes.messages) {
new_dialogMessage.put(m.id, new MessageObject(m, usersLocal)); new_dialogMessage.put(m.id, new MessageObject(m, usersLocal, 0));
} }
for (TLRPC.TL_dialog d : dialogsRes.dialogs) { for (TLRPC.TL_dialog d : dialogsRes.dialogs) {
if (d.last_message_date == 0) { if (d.last_message_date == 0) {
...@@ -1309,7 +1390,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1309,7 +1390,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
}); });
for (TLRPC.TL_dialog d : dialogs) { for (TLRPC.TL_dialog d : dialogs) {
if ((int)d.id != 0) { int high_id = (int)(d.id >> 32);
if ((int)d.id != 0 && high_id != 1) {
dialogsServerOnly.add(d); dialogsServerOnly.add(d);
} }
} }
...@@ -1374,7 +1456,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1374,7 +1456,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
for (TLRPC.Message m : dialogsRes.messages) { for (TLRPC.Message m : dialogsRes.messages) {
new_dialogMessage.put(m.id, new MessageObject(m, usersLocal)); new_dialogMessage.put(m.id, new MessageObject(m, usersLocal, 0));
} }
for (TLRPC.TL_dialog d : dialogsRes.dialogs) { for (TLRPC.TL_dialog d : dialogsRes.dialogs) {
if (d.last_message_date == 0) { if (d.last_message_date == 0) {
...@@ -1473,7 +1555,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1473,7 +1555,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
}); });
for (TLRPC.TL_dialog d : dialogs) { for (TLRPC.TL_dialog d : dialogs) {
if ((int)d.id != 0) { int high_id = (int)(d.id >> 32);
if ((int)d.id != 0 && high_id != 1) {
dialogsServerOnly.add(d); dialogsServerOnly.add(d);
} }
} }
...@@ -1522,10 +1605,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1522,10 +1605,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
public void markDialogAsRead(final long dialog_id, final int max_id, final int max_positive_id, final int offset, final int max_date, final boolean was) { public void markDialogAsRead(final long dialog_id, final int max_id, final int max_positive_id, final int offset, final int max_date, final boolean was, final boolean popup) {
int lower_part = (int)dialog_id; int lower_part = (int)dialog_id;
int high_id = (int)(dialog_id >> 32);
if (lower_part != 0) { if (lower_part != 0) {
if (max_id == 0 && offset == 0) { if (max_id == 0 && offset == 0 || high_id == 1) {
return; return;
} }
TLRPC.TL_messages_readHistory req = new TLRPC.TL_messages_readHistory(); TLRPC.TL_messages_readHistory req = new TLRPC.TL_messages_readHistory();
...@@ -1546,7 +1631,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1546,7 +1631,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
req.max_id = max_positive_id; req.max_id = max_positive_id;
req.offset = offset; req.offset = offset;
if (offset == 0) { if (offset == 0) {
NotificationsController.getInstance().processReadMessages(null, dialog_id, 0, max_positive_id);
MessagesStorage.getInstance().processPendingRead(dialog_id, max_positive_id, max_date, false); MessagesStorage.getInstance().processPendingRead(dialog_id, max_positive_id, max_date, false);
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override @Override
...@@ -1559,10 +1643,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1559,10 +1643,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialog.unread_count = 0; dialog.unread_count = 0;
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
} }
if (!popup) {
NotificationsController.getInstance().processReadMessages(null, dialog_id, 0, max_positive_id);
HashMap<Long, Integer> dialogsToUpdate = new HashMap<Long, Integer>(); HashMap<Long, Integer> dialogsToUpdate = new HashMap<Long, Integer>();
dialogsToUpdate.put(dialog_id, 0); dialogsToUpdate.put(dialog_id, 0);
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, true); NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, true);
} }
}
}); });
} }
}); });
...@@ -1575,7 +1662,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1575,7 +1662,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.getInstance().processPendingRead(dialog_id, max_positive_id, max_date, true); MessagesStorage.getInstance().processPendingRead(dialog_id, max_positive_id, max_date, true);
TLRPC.TL_messages_affectedHistory res = (TLRPC.TL_messages_affectedHistory) response; TLRPC.TL_messages_affectedHistory res = (TLRPC.TL_messages_affectedHistory) response;
if (res.offset > 0) { if (res.offset > 0) {
markDialogAsRead(dialog_id, 0, max_positive_id, res.offset, max_date, was); markDialogAsRead(dialog_id, 0, max_positive_id, res.offset, max_date, was, popup);
} }
if (MessagesStorage.lastSeqValue + 1 == res.seq) { if (MessagesStorage.lastSeqValue + 1 == res.seq) {
...@@ -1615,9 +1702,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1615,9 +1702,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (max_date == 0) { if (max_date == 0) {
return; return;
} }
NotificationsController.getInstance().processReadMessages(null, dialog_id, max_date, 0); TLRPC.EncryptedChat chat = encryptedChats.get(high_id);
int encId = (int)(dialog_id >> 32);
TLRPC.EncryptedChat chat = encryptedChats.get(encId);
if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) { if (chat.auth_key != null && chat.auth_key.length > 1 && chat instanceof TLRPC.TL_encryptedChat) {
TLRPC.TL_messages_readEncryptedHistory req = new TLRPC.TL_messages_readEncryptedHistory(); TLRPC.TL_messages_readEncryptedHistory req = new TLRPC.TL_messages_readEncryptedHistory();
req.peer = new TLRPC.TL_inputEncryptedChat(); req.peer = new TLRPC.TL_inputEncryptedChat();
...@@ -1640,6 +1725,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1640,6 +1725,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
NotificationsController.getInstance().processReadMessages(null, dialog_id, max_date, 0);
TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id); TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
if (dialog != null) { if (dialog != null) {
dialog.unread_count = 0; dialog.unread_count = 0;
...@@ -1795,7 +1881,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1795,7 +1881,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
objArr.add(newMsgObj); objArr.add(newMsgObj);
ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>(); ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>();
arr.add(newMsg); arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true); MessagesStorage.getInstance().putMessages(arr, false, true, false);
updateInterfaceWithMessages(newMsg.dialog_id, objArr); updateInterfaceWithMessages(newMsg.dialog_id, objArr);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
...@@ -1844,7 +1930,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1844,7 +1930,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
objArr.add(newMsgObj); objArr.add(newMsgObj);
ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>(); ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>();
arr.add(newMsg); arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true); MessagesStorage.getInstance().putMessages(arr, false, true, false);
updateInterfaceWithMessages(newMsg.dialog_id, objArr); updateInterfaceWithMessages(newMsg.dialog_id, objArr);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
...@@ -1942,9 +2028,26 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1942,9 +2028,26 @@ public class MessagesController implements NotificationCenter.NotificationCenter
newMsg.unread = true; newMsg.unread = true;
newMsg.dialog_id = peer; newMsg.dialog_id = peer;
int lower_id = (int)peer; int lower_id = (int)peer;
int high_id = (int)(peer >> 32);
TLRPC.EncryptedChat encryptedChat = null; TLRPC.EncryptedChat encryptedChat = null;
TLRPC.InputPeer sendToPeer = null; TLRPC.InputPeer sendToPeer = null;
ArrayList<TLRPC.InputUser> sendToPeers = null;
if (lower_id != 0) { if (lower_id != 0) {
if (high_id == 1) {
if (currentChatInfo == null) {
return;
}
sendToPeers = new ArrayList<TLRPC.InputUser>();
for (TLRPC.TL_chatParticipant participant : currentChatInfo.participants) {
TLRPC.User sendToUser = users.get(participant.user_id);
TLRPC.InputUser peerUser = getInputUser(sendToUser);
if (peerUser != null) {
sendToPeers.add(peerUser);
}
}
newMsg.to_id = new TLRPC.TL_peerChat();
newMsg.to_id.chat_id = high_id;
} else {
if (lower_id < 0) { if (lower_id < 0) {
newMsg.to_id = new TLRPC.TL_peerChat(); newMsg.to_id = new TLRPC.TL_peerChat();
newMsg.to_id.chat_id = -lower_id; newMsg.to_id.chat_id = -lower_id;
...@@ -1967,8 +2070,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1967,8 +2070,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
sendToPeer.user_id = sendToUser.id; sendToPeer.user_id = sendToUser.id;
} }
} }
}
} else { } else {
encryptedChat = encryptedChats.get((int)(peer >> 32)); encryptedChat = encryptedChats.get(high_id);
newMsg.to_id = new TLRPC.TL_peerUser(); newMsg.to_id = new TLRPC.TL_peerUser();
if (encryptedChat.participant_id == UserConfig.getClientUserId()) { if (encryptedChat.participant_id == UserConfig.getClientUserId()) {
newMsg.to_id.user_id = encryptedChat.admin_id; newMsg.to_id.user_id = encryptedChat.admin_id;
...@@ -1981,14 +2085,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1981,14 +2085,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter
newMsg.date = ConnectionsManager.getInstance().getCurrentTime(); newMsg.date = ConnectionsManager.getInstance().getCurrentTime();
newMsg.random_id = getNextRandomId(); newMsg.random_id = getNextRandomId();
UserConfig.saveConfig(false); UserConfig.saveConfig(false);
final MessageObject newMsgObj = new MessageObject(newMsg, null); final MessageObject newMsgObj = new MessageObject(newMsg, null, 2);
newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENDING; newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENDING;
final ArrayList<MessageObject> objArr = new ArrayList<MessageObject>(); final ArrayList<MessageObject> objArr = new ArrayList<MessageObject>();
objArr.add(newMsgObj); objArr.add(newMsgObj);
ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>(); ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>();
arr.add(newMsg); arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true); MessagesStorage.getInstance().putMessages(arr, false, true, false);
updateInterfaceWithMessages(peer, objArr); updateInterfaceWithMessages(peer, objArr);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
...@@ -1996,11 +2100,19 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -1996,11 +2100,19 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (type == 0) { if (type == 0) {
if (encryptedChat == null) { if (encryptedChat == null) {
if (sendToPeers != null) {
TLRPC.TL_messages_sendBroadcast reqSend = new TLRPC.TL_messages_sendBroadcast();
reqSend.message = message;
reqSend.contacts = sendToPeers;
reqSend.media = new TLRPC.TL_inputMediaEmpty();
performSendMessageRequest(reqSend, newMsgObj, null);
} else {
TLRPC.TL_messages_sendMessage reqSend = new TLRPC.TL_messages_sendMessage(); TLRPC.TL_messages_sendMessage reqSend = new TLRPC.TL_messages_sendMessage();
reqSend.message = message; reqSend.message = message;
reqSend.peer = sendToPeer; reqSend.peer = sendToPeer;
reqSend.random_id = newMsg.random_id; reqSend.random_id = newMsg.random_id;
performSendMessageRequest(reqSend, newMsgObj, null); performSendMessageRequest(reqSend, newMsgObj, null);
}
} else { } else {
TLRPC.TL_decryptedMessage reqSend = new TLRPC.TL_decryptedMessage(); TLRPC.TL_decryptedMessage reqSend = new TLRPC.TL_decryptedMessage();
reqSend.random_id = newMsg.random_id; reqSend.random_id = newMsg.random_id;
...@@ -2012,74 +2124,64 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2012,74 +2124,64 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} else if (type >= 1 && type <= 3 || type >= 5 && type <= 8) { } else if (type >= 1 && type <= 3 || type >= 5 && type <= 8) {
if (encryptedChat == null) { if (encryptedChat == null) {
TLRPC.TL_messages_sendMedia reqSend = new TLRPC.TL_messages_sendMedia(); TLRPC.InputMedia inputMedia = null;
reqSend.peer = sendToPeer; DelayedMessage delayedMessage = null;
reqSend.random_id = newMsg.random_id;
if (type == 1) { if (type == 1) {
reqSend.media = new TLRPC.TL_inputMediaGeoPoint(); inputMedia = new TLRPC.TL_inputMediaGeoPoint();
reqSend.media.geo_point = new TLRPC.TL_inputGeoPoint(); inputMedia.geo_point = new TLRPC.TL_inputGeoPoint();
reqSend.media.geo_point.lat = lat; inputMedia.geo_point.lat = lat;
reqSend.media.geo_point._long = lon; inputMedia.geo_point._long = lon;
performSendMessageRequest(reqSend, newMsgObj, null);
} else if (type == 2) { } else if (type == 2) {
if (photo.access_hash == 0) { if (photo.access_hash == 0) {
reqSend.media = new TLRPC.TL_inputMediaUploadedPhoto(); inputMedia = new TLRPC.TL_inputMediaUploadedPhoto();
DelayedMessage delayedMessage = new DelayedMessage(); delayedMessage = new DelayedMessage();
delayedMessage.originalPath = originalPath; delayedMessage.originalPath = originalPath;
delayedMessage.sendRequest = reqSend;
delayedMessage.type = 0; delayedMessage.type = 0;
delayedMessage.obj = newMsgObj; delayedMessage.obj = newMsgObj;
delayedMessage.location = photo.sizes.get(photo.sizes.size() - 1).location; delayedMessage.location = photo.sizes.get(photo.sizes.size() - 1).location;
performSendDelayedMessage(delayedMessage);
} else { } else {
TLRPC.TL_inputMediaPhoto media = new TLRPC.TL_inputMediaPhoto(); TLRPC.TL_inputMediaPhoto media = new TLRPC.TL_inputMediaPhoto();
media.id = new TLRPC.TL_inputPhoto(); media.id = new TLRPC.TL_inputPhoto();
media.id.id = photo.id; media.id.id = photo.id;
media.id.access_hash = photo.access_hash; media.id.access_hash = photo.access_hash;
reqSend.media = media; inputMedia = media;
performSendMessageRequest(reqSend, newMsgObj, null);
} }
} else if (type == 3) { } else if (type == 3) {
if (video.access_hash == 0) { if (video.access_hash == 0) {
reqSend.media = new TLRPC.TL_inputMediaUploadedThumbVideo(); inputMedia = new TLRPC.TL_inputMediaUploadedThumbVideo();
reqSend.media.duration = video.duration; inputMedia.duration = video.duration;
reqSend.media.w = video.w; inputMedia.w = video.w;
reqSend.media.h = video.h; inputMedia.h = video.h;
reqSend.media.mime_type = video.mime_type; inputMedia.mime_type = video.mime_type;
DelayedMessage delayedMessage = new DelayedMessage(); delayedMessage = new DelayedMessage();
delayedMessage.originalPath = originalPath; delayedMessage.originalPath = originalPath;
delayedMessage.sendRequest = reqSend;
delayedMessage.type = 1; delayedMessage.type = 1;
delayedMessage.obj = newMsgObj; delayedMessage.obj = newMsgObj;
delayedMessage.location = video.thumb.location; delayedMessage.location = video.thumb.location;
delayedMessage.videoLocation = video; delayedMessage.videoLocation = video;
performSendDelayedMessage(delayedMessage);
} else { } else {
TLRPC.TL_inputMediaVideo media = new TLRPC.TL_inputMediaVideo(); TLRPC.TL_inputMediaVideo media = new TLRPC.TL_inputMediaVideo();
media.id = new TLRPC.TL_inputVideo(); media.id = new TLRPC.TL_inputVideo();
media.id.id = video.id; media.id.id = video.id;
media.id.access_hash = video.access_hash; media.id.access_hash = video.access_hash;
reqSend.media = media; inputMedia = media;
performSendMessageRequest(reqSend, newMsgObj, null);
} }
} else if (type == 6) { } else if (type == 6) {
reqSend.media = new TLRPC.TL_inputMediaContact(); inputMedia = new TLRPC.TL_inputMediaContact();
reqSend.media.phone_number = user.phone; inputMedia.phone_number = user.phone;
reqSend.media.first_name = user.first_name; inputMedia.first_name = user.first_name;
reqSend.media.last_name = user.last_name; inputMedia.last_name = user.last_name;
performSendMessageRequest(reqSend, newMsgObj, null);
} else if (type == 7) { } else if (type == 7) {
if (document.access_hash == 0) { if (document.access_hash == 0) {
if (document.thumb.location != null && document.thumb.location instanceof TLRPC.TL_fileLocation) { if (document.thumb.location != null && document.thumb.location instanceof TLRPC.TL_fileLocation) {
reqSend.media = new TLRPC.TL_inputMediaUploadedThumbDocument(); inputMedia = new TLRPC.TL_inputMediaUploadedThumbDocument();
} else { } else {
reqSend.media = new TLRPC.TL_inputMediaUploadedDocument(); inputMedia = new TLRPC.TL_inputMediaUploadedDocument();
} }
reqSend.media.mime_type = document.mime_type; inputMedia.mime_type = document.mime_type;
reqSend.media.file_name = document.file_name; inputMedia.file_name = document.file_name;
DelayedMessage delayedMessage = new DelayedMessage(); delayedMessage = new DelayedMessage();
delayedMessage.originalPath = originalPath; delayedMessage.originalPath = originalPath;
delayedMessage.sendRequest = reqSend;
delayedMessage.type = 2; delayedMessage.type = 2;
delayedMessage.obj = newMsgObj; delayedMessage.obj = newMsgObj;
delayedMessage.documentLocation = document; delayedMessage.documentLocation = document;
...@@ -2090,26 +2192,73 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2090,26 +2192,73 @@ public class MessagesController implements NotificationCenter.NotificationCenter
media.id = new TLRPC.TL_inputDocument(); media.id = new TLRPC.TL_inputDocument();
media.id.id = document.id; media.id.id = document.id;
media.id.access_hash = document.access_hash; media.id.access_hash = document.access_hash;
reqSend.media = media; inputMedia = media;
performSendMessageRequest(reqSend, newMsgObj, null);
} }
} else if (type == 8) { } else if (type == 8) {
if (audio.access_hash == 0) { if (audio.access_hash == 0) {
reqSend.media = new TLRPC.TL_inputMediaUploadedAudio(); inputMedia = new TLRPC.TL_inputMediaUploadedAudio();
reqSend.media.duration = audio.duration; inputMedia.duration = audio.duration;
reqSend.media.mime_type = audio.mime_type; inputMedia.mime_type = audio.mime_type;
DelayedMessage delayedMessage = new DelayedMessage(); delayedMessage = new DelayedMessage();
delayedMessage.sendRequest = reqSend;
delayedMessage.type = 3; delayedMessage.type = 3;
delayedMessage.obj = newMsgObj; delayedMessage.obj = newMsgObj;
delayedMessage.audioLocation = audio; delayedMessage.audioLocation = audio;
performSendDelayedMessage(delayedMessage);
} else { } else {
TLRPC.TL_inputMediaAudio media = new TLRPC.TL_inputMediaAudio(); TLRPC.TL_inputMediaAudio media = new TLRPC.TL_inputMediaAudio();
media.id = new TLRPC.TL_inputAudio(); media.id = new TLRPC.TL_inputAudio();
media.id.id = audio.id; media.id.id = audio.id;
media.id.access_hash = audio.access_hash; media.id.access_hash = audio.access_hash;
reqSend.media = media; inputMedia = media;
}
}
TLObject reqSend = null;
if (sendToPeers != null) {
TLRPC.TL_messages_sendBroadcast request = new TLRPC.TL_messages_sendBroadcast();
request.contacts = sendToPeers;
request.media = inputMedia;
request.message = "";
if (delayedMessage != null) {
delayedMessage.sendRequest = request;
}
reqSend = request;
} else {
TLRPC.TL_messages_sendMedia request = new TLRPC.TL_messages_sendMedia();
request.peer = sendToPeer;
request.random_id = newMsg.random_id;
request.media = inputMedia;
if (delayedMessage != null) {
delayedMessage.sendRequest = request;
}
reqSend = request;
}
if (type == 1) {
performSendMessageRequest(reqSend, newMsgObj, null);
} else if (type == 2) {
if (photo.access_hash == 0) {
performSendDelayedMessage(delayedMessage);
} else {
performSendMessageRequest(reqSend, newMsgObj, null);
}
} else if (type == 3) {
if (video.access_hash == 0) {
performSendDelayedMessage(delayedMessage);
} else {
performSendMessageRequest(reqSend, newMsgObj, null);
}
} else if (type == 6) {
performSendMessageRequest(reqSend, newMsgObj, null);
} else if (type == 7) {
if (document.access_hash == 0) {
performSendDelayedMessage(delayedMessage);
} else {
performSendMessageRequest(reqSend, newMsgObj, null);
}
} else if (type == 8) {
if (audio.access_hash == 0) {
performSendDelayedMessage(delayedMessage);
} else {
performSendMessageRequest(reqSend, newMsgObj, null); performSendMessageRequest(reqSend, newMsgObj, null);
} }
} }
...@@ -2360,7 +2509,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2360,7 +2509,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
FileLoader.getInstance().replaceImageInCache(fileName, fileName2); FileLoader.getInstance().replaceImageInCache(fileName, fileName2);
ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>(); ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>();
arr.add(newMsg); arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true); MessagesStorage.getInstance().putMessages(arr, false, true, false);
MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.photo, 3); MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.photo, 3);
} else if (newMsg.media instanceof TLRPC.TL_messageMediaVideo && newMsg.media.video != null) { } else if (newMsg.media instanceof TLRPC.TL_messageMediaVideo && newMsg.media.video != null) {
...@@ -2383,7 +2532,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2383,7 +2532,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
newMsg.media.video.mime_type = video.mime_type; newMsg.media.video.mime_type = video.mime_type;
ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>(); ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>();
arr.add(newMsg); arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true); MessagesStorage.getInstance().putMessages(arr, false, true, false);
MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.video, 5); MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.video, 5);
} else if (newMsg.media instanceof TLRPC.TL_messageMediaDocument && newMsg.media.document != null) { } else if (newMsg.media instanceof TLRPC.TL_messageMediaDocument && newMsg.media.document != null) {
...@@ -2410,7 +2559,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2410,7 +2559,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>(); ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>();
arr.add(newMsg); arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true); MessagesStorage.getInstance().putMessages(arr, false, true, false);
MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.document, 4); MessagesStorage.getInstance().putSentFile(originalPath, newMsg.media.document, 4);
} else if (newMsg.media instanceof TLRPC.TL_messageMediaAudio && newMsg.media.audio != null) { } else if (newMsg.media instanceof TLRPC.TL_messageMediaAudio && newMsg.media.audio != null) {
...@@ -2438,7 +2587,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2438,7 +2587,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>(); ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>();
arr.add(newMsg); arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true); MessagesStorage.getInstance().putMessages(arr, false, true, false);
} }
} }
} }
...@@ -2539,12 +2688,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2539,12 +2688,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}); });
} }
private void performSendMessageRequest(TLObject req, final MessageObject newMsgObj, final String originalPath) { private void performSendMessageRequest(final TLObject req, final MessageObject newMsgObj, final String originalPath) {
ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() { ConnectionsManager.getInstance().performRpc(req, new RPCRequest.RPCRequestDelegate() {
@Override @Override
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) { if (error == null) {
final int oldId = newMsgObj.messageOwner.id; final int oldId = newMsgObj.messageOwner.id;
final boolean isBroadcast = req instanceof TLRPC.TL_messages_sendBroadcast;
final ArrayList<TLRPC.Message> sentMessages = new ArrayList<TLRPC.Message>(); final ArrayList<TLRPC.Message> sentMessages = new ArrayList<TLRPC.Message>();
if (response instanceof TLRPC.TL_messages_sentMessage) { if (response instanceof TLRPC.TL_messages_sentMessage) {
...@@ -2596,9 +2746,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2596,9 +2746,11 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} else if (response instanceof TLRPC.messages_StatedMessages) { } else if (response instanceof TLRPC.messages_StatedMessages) {
TLRPC.messages_StatedMessages res = (TLRPC.messages_StatedMessages) response; TLRPC.messages_StatedMessages res = (TLRPC.messages_StatedMessages) response;
if (!res.messages.isEmpty()) { if (!res.messages.isEmpty()) {
sentMessages.addAll(res.messages);
TLRPC.Message message = res.messages.get(0); TLRPC.Message message = res.messages.get(0);
if (!isBroadcast) {
newMsgObj.messageOwner.id = message.id; newMsgObj.messageOwner.id = message.id;
sentMessages.add(message); }
processSentMessage(newMsgObj.messageOwner, message, null, null, originalPath); processSentMessage(newMsgObj.messageOwner, message, null, null, originalPath);
} }
if (MessagesStorage.lastSeqValue + 1 == res.seq) { if (MessagesStorage.lastSeqValue + 1 == res.seq) {
...@@ -2623,13 +2775,28 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2623,13 +2775,28 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.messageOwner.random_id, oldId, newMsgObj.messageOwner.id, 0, false); MessagesStorage.getInstance().updateMessageStateAndId(newMsgObj.messageOwner.random_id, oldId, (isBroadcast ? oldId : newMsgObj.messageOwner.id), 0, false);
MessagesStorage.getInstance().putMessages(sentMessages, true, false); MessagesStorage.getInstance().putMessages(sentMessages, true, false, isBroadcast);
if (isBroadcast) {
ArrayList<TLRPC.Message> currentMessage = new ArrayList<TLRPC.Message>();
currentMessage.add(newMsgObj.messageOwner);
newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENT;
MessagesStorage.getInstance().putMessages(currentMessage, true, false, false);
}
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
public void run() { public void run() {
newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENT; newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENT;
NotificationCenter.getInstance().postNotificationName(messageReceivedByServer, oldId, newMsgObj.messageOwner.id, newMsgObj); if (isBroadcast) {
for (TLRPC.Message message : sentMessages) {
ArrayList<MessageObject> arr = new ArrayList<MessageObject>();
MessageObject messageObject = new MessageObject(message, users, 0);
arr.add(messageObject);
updateInterfaceWithMessages(messageObject.getDialogId(), arr, isBroadcast);
}
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
}
NotificationCenter.getInstance().postNotificationName(messageReceivedByServer, oldId, (isBroadcast ? oldId : newMsgObj.messageOwner.id), newMsgObj);
sendingMessages.remove(oldId); sendingMessages.remove(oldId);
} }
}); });
...@@ -2681,7 +2848,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2681,7 +2848,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} else if (message.type == 1) { } else if (message.type == 1) {
if (message.sendRequest != null) { if (message.sendRequest != null) {
if (message.sendRequest.media.thumb == null) { TLRPC.InputMedia media = null;
if (message.sendRequest instanceof TLRPC.TL_messages_sendMedia) {
media = ((TLRPC.TL_messages_sendMedia)message.sendRequest).media;
} else if (message.sendRequest instanceof TLRPC.TL_messages_sendBroadcast) {
media = ((TLRPC.TL_messages_sendBroadcast)message.sendRequest).media;
}
if (media.thumb == null) {
String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg"; String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg";
putToDelayedMessages(location, message); putToDelayedMessages(location, message);
FileLoader.getInstance().uploadFile(location, false); FileLoader.getInstance().uploadFile(location, false);
...@@ -2702,7 +2875,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2702,7 +2875,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter
FileLoader.getInstance().uploadFile(location, true); FileLoader.getInstance().uploadFile(location, true);
} }
} else if (message.type == 2) { } else if (message.type == 2) {
if (message.sendRequest != null && message.sendRequest.media.thumb == null && message.location != null) { TLRPC.InputMedia media = null;
if (message.sendRequest instanceof TLRPC.TL_messages_sendMedia) {
media = ((TLRPC.TL_messages_sendMedia)message.sendRequest).media;
} else if (message.sendRequest instanceof TLRPC.TL_messages_sendBroadcast) {
media = ((TLRPC.TL_messages_sendBroadcast)message.sendRequest).media;
}
if (message.sendRequest != null && media.thumb == null && message.location != null) {
String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg"; String location = AndroidUtilities.getCacheDir() + "/" + message.location.volume_id + "_" + message.location.local_id + ".jpg";
putToDelayedMessages(location, message); putToDelayedMessages(location, message);
FileLoader.getInstance().uploadFile(location, false); FileLoader.getInstance().uploadFile(location, false);
...@@ -2726,7 +2905,61 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2726,7 +2905,61 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
public long createChat(String title, ArrayList<Integer> selectedContacts, final TLRPC.InputFile uploadedAvatar) { public long createChat(String title, ArrayList<Integer> selectedContacts, final TLRPC.InputFile uploadedAvatar, boolean isBroadcast) {
if (isBroadcast) {
TLRPC.TL_chat chat = new TLRPC.TL_chat();
chat.id = UserConfig.lastBroadcastId;
chat.title = title;
chat.photo = new TLRPC.TL_chatPhotoEmpty();
chat.participants_count = selectedContacts.size();
chat.date = (int)(System.currentTimeMillis() / 1000);
chat.left = false;
chat.version = 1;
UserConfig.lastBroadcastId--;
chats.put(chat.id, chat);
ArrayList<TLRPC.Chat> chatsArrays = new ArrayList<TLRPC.Chat>();
chatsArrays.add(chat);
MessagesStorage.getInstance().putUsersAndChats(null, chatsArrays, true, true);
TLRPC.TL_chatParticipants participants = new TLRPC.TL_chatParticipants();
participants.chat_id = chat.id;
participants.admin_id = UserConfig.getClientUserId();
participants.version = 1;
for (Integer id : selectedContacts) {
TLRPC.TL_chatParticipant participant = new TLRPC.TL_chatParticipant();
participant.user_id = id;
participant.inviter_id = UserConfig.getClientUserId();
participant.date = (int)(System.currentTimeMillis() / 1000);
participants.participants.add(participant);
}
MessagesStorage.getInstance().updateChatInfo(chat.id, participants, false);
TLRPC.TL_messageService newMsg = new TLRPC.TL_messageService();
newMsg.action = new TLRPC.TL_messageActionCreatedBroadcastList();
newMsg.local_id = newMsg.id = UserConfig.getNewMessageId();
newMsg.from_id = UserConfig.getClientUserId();
newMsg.unread = false;
newMsg.dialog_id = AndroidUtilities.makeBroadcastId(chat.id);
newMsg.to_id = new TLRPC.TL_peerChat();
newMsg.to_id.chat_id = chat.id;
newMsg.out = false;
newMsg.date = ConnectionsManager.getInstance().getCurrentTime();
newMsg.random_id = 0;
UserConfig.saveConfig(false);
MessageObject newMsgObj = new MessageObject(newMsg, users);
newMsgObj.messageOwner.send_state = MESSAGE_SEND_STATE_SENT;
ArrayList<MessageObject> objArr = new ArrayList<MessageObject>();
objArr.add(newMsgObj);
ArrayList<TLRPC.Message> arr = new ArrayList<TLRPC.Message>();
arr.add(newMsg);
MessagesStorage.getInstance().putMessages(arr, false, true, false);
updateInterfaceWithMessages(newMsg.dialog_id, objArr);
NotificationCenter.getInstance().postNotificationName(chatDidCreated, chat.id);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
return 0;
} else {
TLRPC.TL_messages_createChat req = new TLRPC.TL_messages_createChat(); TLRPC.TL_messages_createChat req = new TLRPC.TL_messages_createChat();
req.title = title; req.title = title;
for (Integer uid : selectedContacts) { for (Integer uid : selectedContacts) {
...@@ -2777,7 +3010,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2777,7 +3010,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>(); final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>();
messages.add(res.message); messages.add(res.message);
MessagesStorage.getInstance().putMessages(messages, true, true); MessagesStorage.getInstance().putMessages(messages, true, true, false);
if (MessagesStorage.lastSeqValue + 1 == res.seq) { if (MessagesStorage.lastSeqValue + 1 == res.seq) {
MessagesStorage.lastSeqValue = res.seq; MessagesStorage.lastSeqValue = res.seq;
MessagesStorage.lastPtsValue = res.pts; MessagesStorage.lastPtsValue = res.pts;
...@@ -2799,12 +3032,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2799,12 +3032,14 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
}); });
} }
}
public void addUserToChat(int chat_id, final TLRPC.User user, final TLRPC.ChatParticipants info, int count_fwd) { public void addUserToChat(int chat_id, final TLRPC.User user, final TLRPC.ChatParticipants info, int count_fwd) {
if (user == null) { if (user == null) {
return; return;
} }
if (chat_id > 0) {
TLRPC.TL_messages_addChatUser req = new TLRPC.TL_messages_addChatUser(); TLRPC.TL_messages_addChatUser req = new TLRPC.TL_messages_addChatUser();
req.chat_id = chat_id; req.chat_id = chat_id;
req.fwd_limit = count_fwd; req.fwd_limit = count_fwd;
...@@ -2859,7 +3094,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2859,7 +3094,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>(); final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>();
messages.add(res.message); messages.add(res.message);
MessagesStorage.getInstance().putMessages(messages, true, true); MessagesStorage.getInstance().putMessages(messages, true, true, false);
if (MessagesStorage.lastSeqValue + 1 == res.seq) { if (MessagesStorage.lastSeqValue + 1 == res.seq) {
MessagesStorage.lastSeqValue = res.seq; MessagesStorage.lastSeqValue = res.seq;
MessagesStorage.lastPtsValue = res.pts; MessagesStorage.lastPtsValue = res.pts;
...@@ -2880,12 +3115,37 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2880,12 +3115,37 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
}); });
} else {
if (info != null) {
for (TLRPC.TL_chatParticipant p : info.participants) {
if (p.user_id == user.id) {
return;
}
}
TLRPC.Chat chat = chats.get(chat_id);
chat.participants_count++;
ArrayList<TLRPC.Chat> chatArrayList = new ArrayList<TLRPC.Chat>();
chatArrayList.add(chat);
MessagesStorage.getInstance().putUsersAndChats(null, chatArrayList, true, true);
TLRPC.TL_chatParticipant newPart = new TLRPC.TL_chatParticipant();
newPart.user_id = user.id;
newPart.inviter_id = UserConfig.getClientUserId();
newPart.date = ConnectionsManager.getInstance().getCurrentTime();
info.participants.add(0, newPart);
MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);
NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info);
NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
}
}
} }
public void deleteUserFromChat(int chat_id, final TLRPC.User user, final TLRPC.ChatParticipants info) { public void deleteUserFromChat(int chat_id, final TLRPC.User user, final TLRPC.ChatParticipants info) {
if (user == null) { if (user == null) {
return; return;
} }
if (chat_id > 0) {
TLRPC.TL_messages_deleteChatUser req = new TLRPC.TL_messages_deleteChatUser(); TLRPC.TL_messages_deleteChatUser req = new TLRPC.TL_messages_deleteChatUser();
req.chat_id = chat_id; req.chat_id = chat_id;
req.user_id = getInputUser(user); req.user_id = getInputUser(user);
...@@ -2940,7 +3200,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2940,7 +3200,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (user.id != UserConfig.getClientUserId()) { if (user.id != UserConfig.getClientUserId()) {
final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>(); final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>();
messages.add(res.message); messages.add(res.message);
MessagesStorage.getInstance().putMessages(messages, true, true); MessagesStorage.getInstance().putMessages(messages, true, true, false);
} }
if (MessagesStorage.lastSeqValue + 1 == res.seq) { if (MessagesStorage.lastSeqValue + 1 == res.seq) {
MessagesStorage.lastSeqValue = res.seq; MessagesStorage.lastSeqValue = res.seq;
...@@ -2962,9 +3222,36 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -2962,9 +3222,36 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
}); });
} else {
if (info != null) {
TLRPC.Chat chat = chats.get(chat_id);
chat.participants_count--;
ArrayList<TLRPC.Chat> chatArrayList = new ArrayList<TLRPC.Chat>();
chatArrayList.add(chat);
MessagesStorage.getInstance().putUsersAndChats(null, chatArrayList, true, true);
boolean changed = false;
if (info != null) {
for (int a = 0; a < info.participants.size(); a++) {
TLRPC.TL_chatParticipant p = info.participants.get(a);
if (p.user_id == user.id) {
info.participants.remove(a);
changed = true;
break;
}
}
if (changed) {
MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);
NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info);
}
}
NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_MEMBERS);
}
}
} }
public void changeChatTitle(int chat_id, String title) { public void changeChatTitle(int chat_id, String title) {
if (chat_id > 0) {
TLRPC.TL_messages_editChatTitle req = new TLRPC.TL_messages_editChatTitle(); TLRPC.TL_messages_editChatTitle req = new TLRPC.TL_messages_editChatTitle();
req.chat_id = chat_id; req.chat_id = chat_id;
req.title = title; req.title = title;
...@@ -3001,7 +3288,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3001,7 +3288,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>(); final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>();
messages.add(res.message); messages.add(res.message);
MessagesStorage.getInstance().putMessages(messages, true, true); MessagesStorage.getInstance().putMessages(messages, true, true, false);
if (MessagesStorage.lastSeqValue + 1 == res.seq) { if (MessagesStorage.lastSeqValue + 1 == res.seq) {
MessagesStorage.lastSeqValue = res.seq; MessagesStorage.lastSeqValue = res.seq;
MessagesStorage.lastPtsValue = res.pts; MessagesStorage.lastPtsValue = res.pts;
...@@ -3022,6 +3309,15 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3022,6 +3309,15 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
}); });
} else {
TLRPC.Chat chat = chats.get(chat_id);
chat.title = title;
ArrayList<TLRPC.Chat> chatArrayList = new ArrayList<TLRPC.Chat>();
chatArrayList.add(chat);
MessagesStorage.getInstance().putUsersAndChats(null, chatArrayList, true, true);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_CHAT_NAME);
}
} }
public void changeChatAvatar(int chat_id, TLRPC.InputFile uploadedAvatar) { public void changeChatAvatar(int chat_id, TLRPC.InputFile uploadedAvatar) {
...@@ -3067,7 +3363,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3067,7 +3363,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>(); final ArrayList<TLRPC.Message> messages = new ArrayList<TLRPC.Message>();
messages.add(res.message); messages.add(res.message);
MessagesStorage.getInstance().putMessages(messages, true, true); MessagesStorage.getInstance().putMessages(messages, true, true, false);
if (MessagesStorage.lastSeqValue + 1 == res.seq) { if (MessagesStorage.lastSeqValue + 1 == res.seq) {
MessagesStorage.lastSeqValue = res.seq; MessagesStorage.lastSeqValue = res.seq;
MessagesStorage.lastPtsValue = res.pts; MessagesStorage.lastPtsValue = res.pts;
...@@ -3197,6 +3493,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3197,6 +3493,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.lastPtsValue = res.pts; MessagesStorage.lastPtsValue = res.pts;
MessagesStorage.lastSeqValue = res.seq; MessagesStorage.lastSeqValue = res.seq;
MessagesStorage.lastQtsValue = res.qts; MessagesStorage.lastQtsValue = res.qts;
processUpdatesQueue(2);
MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);
} else { } else {
if (error.code != 401) { if (error.code != 401) {
...@@ -3215,7 +3512,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3215,7 +3512,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
private void processUpdatesQueue(boolean getDifference) { private void processUpdatesQueue(int state) {
if (!updatesQueue.isEmpty()) { if (!updatesQueue.isEmpty()) {
Collections.sort(updatesQueue, new Comparator<TLRPC.Updates>() { Collections.sort(updatesQueue, new Comparator<TLRPC.Updates>() {
@Override @Override
...@@ -3231,6 +3528,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3231,6 +3528,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
}); });
boolean anyProceed = false; boolean anyProceed = false;
if (state == 2) {
TLRPC.Updates updates = updatesQueue.get(0);
MessagesStorage.lastSeqValue = getUpdateSeq(updates);
}
for (int a = 0; a < updatesQueue.size(); a++) { for (int a = 0; a < updatesQueue.size(); a++) {
TLRPC.Updates updates = updatesQueue.get(a); TLRPC.Updates updates = updatesQueue.get(a);
int seq = getUpdateSeq(updates); int seq = getUpdateSeq(updates);
...@@ -3261,7 +3562,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3261,7 +3562,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
updatesQueue.clear(); updatesQueue.clear();
FileLog.e("tmessages", "UPDATES QUEUE PROCEED - OK"); FileLog.e("tmessages", "UPDATES QUEUE PROCEED - OK");
updatesStartWaitTime = 0; updatesStartWaitTime = 0;
if (getDifference) { if (state == 1) {
final int stateCopy = ConnectionsManager.getInstance().getConnectionState(); final int stateCopy = ConnectionsManager.getInstance().getConnectionState();
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
...@@ -3271,7 +3572,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3271,7 +3572,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
}); });
} }
} else { } else {
if (getDifference) { if (state == 1) {
final int stateCopy = ConnectionsManager.getInstance().getConnectionState(); final int stateCopy = ConnectionsManager.getInstance().getConnectionState();
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
@Override @Override
...@@ -3395,7 +3696,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3395,7 +3696,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
final ArrayList<MessageObject> pushMessages = new ArrayList<MessageObject>(); final ArrayList<MessageObject> pushMessages = new ArrayList<MessageObject>();
for (TLRPC.Message message : res.new_messages) { for (TLRPC.Message message : res.new_messages) {
MessageObject obj = new MessageObject(message, usersDict); MessageObject obj = new MessageObject(message, usersDict, 2);
long dialog_id = obj.messageOwner.dialog_id; long dialog_id = obj.messageOwner.dialog_id;
if (dialog_id == 0) { if (dialog_id == 0) {
...@@ -3442,16 +3743,21 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3442,16 +3743,21 @@ public class MessagesController implements NotificationCenter.NotificationCenter
updateInterfaceWithMessages(key, value); updateInterfaceWithMessages(key, value);
} }
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
if (!pushMessages.isEmpty()) {
NotificationsController.getInstance().processNewMessages(pushMessages, !(res instanceof TLRPC.TL_updates_differenceSlice));
}
} }
}); });
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() { MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
if (!pushMessages.isEmpty()) {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
NotificationsController.getInstance().processNewMessages(pushMessages, !(res instanceof TLRPC.TL_updates_differenceSlice));
}
});
}
MessagesStorage.getInstance().startTransaction(false); MessagesStorage.getInstance().startTransaction(false);
MessagesStorage.getInstance().putMessages(res.new_messages, false, false); MessagesStorage.getInstance().putMessages(res.new_messages, false, false, false);
MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, false, false); MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, false, false);
MessagesStorage.getInstance().commitTransaction(false); MessagesStorage.getInstance().commitTransaction(false);
} }
...@@ -3469,7 +3775,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3469,7 +3775,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.lastPtsValue = res.state.pts; MessagesStorage.lastPtsValue = res.state.pts;
MessagesStorage.lastQtsValue = res.state.qts; MessagesStorage.lastQtsValue = res.state.qts;
ConnectionsManager.getInstance().setConnectionState(0); ConnectionsManager.getInstance().setConnectionState(0);
processUpdatesQueue(true); processUpdatesQueue(1);
} else if (res instanceof TLRPC.TL_updates_differenceSlice) { } else if (res instanceof TLRPC.TL_updates_differenceSlice) {
MessagesStorage.lastDateValue = res.intermediate_state.date; MessagesStorage.lastDateValue = res.intermediate_state.date;
MessagesStorage.lastPtsValue = res.intermediate_state.pts; MessagesStorage.lastPtsValue = res.intermediate_state.pts;
...@@ -3480,7 +3786,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3480,7 +3786,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
MessagesStorage.lastSeqValue = res.seq; MessagesStorage.lastSeqValue = res.seq;
MessagesStorage.lastDateValue = res.date; MessagesStorage.lastDateValue = res.date;
ConnectionsManager.getInstance().setConnectionState(0); ConnectionsManager.getInstance().setConnectionState(0);
processUpdatesQueue(true); processUpdatesQueue(1);
} }
MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue); MessagesStorage.getInstance().saveDiffParams(MessagesStorage.lastSeqValue, MessagesStorage.lastPtsValue, MessagesStorage.lastDateValue, MessagesStorage.lastQtsValue);
FileLog.e("tmessages", "received difference with date = " + MessagesStorage.lastDateValue + " pts = " + MessagesStorage.lastPtsValue + " seq = " + MessagesStorage.lastSeqValue); FileLog.e("tmessages", "received difference with date = " + MessagesStorage.lastDateValue + " pts = " + MessagesStorage.lastPtsValue + " seq = " + MessagesStorage.lastSeqValue);
...@@ -3544,14 +3850,25 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3544,14 +3850,25 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (printUpdate) { if (printUpdate) {
NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_USER_PRINT); NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_USER_PRINT);
} }
updateInterfaceWithMessages(-updates.chat_id, objArr);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
}
});
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
if (!obj.isFromMe() && obj.isUnread()) { if (!obj.isFromMe() && obj.isUnread()) {
NotificationsController.getInstance().processNewMessages(objArr, true); NotificationsController.getInstance().processNewMessages(objArr, true);
} }
updateInterfaceWithMessages(-updates.chat_id, objArr);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
} }
}); });
MessagesStorage.getInstance().putMessages(arr, false, true); }
});
MessagesStorage.getInstance().putMessages(arr, false, true, false);
} else if (MessagesStorage.lastSeqValue != updates.seq) { } else if (MessagesStorage.lastSeqValue != updates.seq) {
FileLog.e("tmessages", "need get diff TL_updateShortChatMessage, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq); FileLog.e("tmessages", "need get diff TL_updateShortChatMessage, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq);
if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) {
...@@ -3599,14 +3916,24 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3599,14 +3916,24 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (printUpdate) { if (printUpdate) {
NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_USER_PRINT); NotificationCenter.getInstance().postNotificationName(updateInterfaces, UPDATE_MASK_USER_PRINT);
} }
updateInterfaceWithMessages(updates.from_id, objArr);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
}
});
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
if (!obj.isFromMe() && obj.isUnread()) { if (!obj.isFromMe() && obj.isUnread()) {
NotificationsController.getInstance().processNewMessages(objArr, true); NotificationsController.getInstance().processNewMessages(objArr, true);
} }
updateInterfaceWithMessages(updates.from_id, objArr);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
} }
}); });
MessagesStorage.getInstance().putMessages(arr, false, true); }
});
MessagesStorage.getInstance().putMessages(arr, false, true, false);
} else if (MessagesStorage.lastSeqValue != updates.seq) { } else if (MessagesStorage.lastSeqValue != updates.seq) {
FileLog.e("tmessages", "need get diff TL_updateShortMessage, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq); FileLog.e("tmessages", "need get diff TL_updateShortMessage, seq: " + MessagesStorage.lastSeqValue + " " + updates.seq);
if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) { if (gettingDifference || updatesStartWaitTime == 0 || updatesStartWaitTime != 0 && updatesStartWaitTime + 1500 > System.currentTimeMillis()) {
...@@ -3692,7 +4019,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3692,7 +4019,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (needGetDiff && !fromQueue) { if (needGetDiff && !fromQueue) {
getDifference(); getDifference();
} else if (!fromQueue && !updatesQueue.isEmpty()) { } else if (!fromQueue && !updatesQueue.isEmpty()) {
processUpdatesQueue(false); processUpdatesQueue(0);
} }
if (needReceivedQueue) { if (needReceivedQueue) {
TLRPC.TL_messages_receivedQueue req = new TLRPC.TL_messages_receivedQueue(); TLRPC.TL_messages_receivedQueue req = new TLRPC.TL_messages_receivedQueue();
...@@ -3779,7 +4106,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3779,7 +4106,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
messagesArr.add(upd.message); messagesArr.add(upd.message);
MessageObject obj = new MessageObject(upd.message, usersDict); MessageObject obj = new MessageObject(upd.message, usersDict, 2);
if (obj.type == 11) { if (obj.type == 11) {
interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR; interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR;
} else if (obj.type == 10) { } else if (obj.type == 10) {
...@@ -3928,7 +4255,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -3928,7 +4255,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
if (message != null) { if (message != null) {
int cid = ((TLRPC.TL_updateNewEncryptedMessage)update).message.chat_id; int cid = ((TLRPC.TL_updateNewEncryptedMessage)update).message.chat_id;
messagesArr.add(message); messagesArr.add(message);
MessageObject obj = new MessageObject(message, usersDict); MessageObject obj = new MessageObject(message, usersDict, 2);
long uid = ((long)cid) << 32; long uid = ((long)cid) << 32;
ArrayList<MessageObject> arr = messages.get(uid); ArrayList<MessageObject> arr = messages.get(uid);
if (arr == null) { if (arr == null) {
...@@ -4014,7 +4341,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4014,7 +4341,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
}); });
for (TLRPC.TL_dialog d : dialogs) { for (TLRPC.TL_dialog d : dialogs) {
if ((int)d.id != 0) { int high_id = (int)(d.id >> 32);
if ((int)d.id != 0 && high_id != 1) {
dialogsServerOnly.add(d); dialogsServerOnly.add(d);
} }
} }
...@@ -4076,8 +4404,22 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4076,8 +4404,22 @@ public class MessagesController implements NotificationCenter.NotificationCenter
ContactsController.getInstance().processContactsUpdates(contactsIds, usersDict); ContactsController.getInstance().processContactsUpdates(contactsIds, usersDict);
} }
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
if (!pushMessages.isEmpty()) {
NotificationsController.getInstance().processNewMessages(pushMessages, true);
}
}
});
}
});
if (!messagesArr.isEmpty()) { if (!messagesArr.isEmpty()) {
MessagesStorage.getInstance().putMessages(messagesArr, true, true); MessagesStorage.getInstance().putMessages(messagesArr, true, true, false);
} }
Utilities.RunOnUIThread(new Runnable() { Utilities.RunOnUIThread(new Runnable() {
...@@ -4131,7 +4473,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4131,7 +4473,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} else { } else {
editor.remove("notify2_" + dialog_id); editor.remove("notify2_" + dialog_id);
} }
} else if (update.peer instanceof TLRPC.TL_notifyChats) { }/* else if (update.peer instanceof TLRPC.TL_notifyChats) { disable global settings sync
if (editor == null) { if (editor == null) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
editor = preferences.edit(); editor = preferences.edit();
...@@ -4145,7 +4487,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4145,7 +4487,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
editor.putBoolean("EnableAll", update.notify_settings.mute_until == 0); editor.putBoolean("EnableAll", update.notify_settings.mute_until == 0);
editor.putBoolean("EnablePreviewAll", update.notify_settings.show_previews); editor.putBoolean("EnablePreviewAll", update.notify_settings.show_previews);
} }*/
} }
} }
if (editor != null) { if (editor != null) {
...@@ -4164,10 +4506,36 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4164,10 +4506,36 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
} }
if (!pushMessages.isEmpty()) { if (printChangedArg) {
NotificationsController.getInstance().processNewMessages(pushMessages, true); updateMask |= UPDATE_MASK_USER_PRINT;
} }
if (!contactsIds.isEmpty()) {
updateMask |= UPDATE_MASK_NAME;
updateMask |= UPDATE_MASK_USER_PHONE;
}
if (!chatInfoToUpdate.isEmpty()) {
for (TLRPC.ChatParticipants info : chatInfoToUpdate) {
MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);
NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info);
}
}
if (updateMask != 0) {
NotificationCenter.getInstance().postNotificationName(updateInterfaces, updateMask);
}
}
});
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
int updateMask = 0;
if (!markAsReadMessages.isEmpty()) { if (!markAsReadMessages.isEmpty()) {
NotificationCenter.getInstance().postNotificationName(messagesReaded, markAsReadMessages);
NotificationsController.getInstance().processReadMessages(markAsReadMessages, 0, 0, 0);
for (Integer id : markAsReadMessages) { for (Integer id : markAsReadMessages) {
MessageObject obj = dialogMessage.get(id); MessageObject obj = dialogMessage.get(id);
if (obj != null) { if (obj != null) {
...@@ -4190,9 +4558,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4190,9 +4558,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
} }
if (!markAsReadMessages.isEmpty()) {
NotificationsController.getInstance().processReadMessages(markAsReadMessages, 0, 0, 0);
}
if (!deletedMessages.isEmpty()) { if (!deletedMessages.isEmpty()) {
NotificationCenter.getInstance().postNotificationName(messagesDeleted, deletedMessages); NotificationCenter.getInstance().postNotificationName(messagesDeleted, deletedMessages);
for (Integer id : deletedMessages) { for (Integer id : deletedMessages) {
...@@ -4202,40 +4567,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4202,40 +4567,13 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
} }
} }
if (printChangedArg) {
updateMask |= UPDATE_MASK_USER_PRINT;
}
if (!contactsIds.isEmpty()) {
updateMask |= UPDATE_MASK_NAME;
updateMask |= UPDATE_MASK_USER_PHONE;
}
if (!chatInfoToUpdate.isEmpty()) {
for (TLRPC.ChatParticipants info : chatInfoToUpdate) {
MessagesStorage.getInstance().updateChatInfo(info.chat_id, info, true);
NotificationCenter.getInstance().postNotificationName(chatInfoDidLoaded, info.chat_id, info);
}
}
if (updateMask != 0) { if (updateMask != 0) {
NotificationCenter.getInstance().postNotificationName(updateInterfaces, updateMask); NotificationCenter.getInstance().postNotificationName(updateInterfaces, updateMask);
} }
} }
}); });
if (!markAsReadMessages.isEmpty() || !markAsReadEncrypted.isEmpty()) {
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
if (!markAsReadMessages.isEmpty()) {
NotificationCenter.getInstance().postNotificationName(messagesReaded, markAsReadMessages);
}
}
});
} }
}); });
}
if (!markAsReadMessages.isEmpty() || !markAsReadEncrypted.isEmpty()) { if (!markAsReadMessages.isEmpty() || !markAsReadEncrypted.isEmpty()) {
if (!markAsReadMessages.isEmpty()) { if (!markAsReadMessages.isEmpty()) {
...@@ -4312,6 +4650,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4312,6 +4650,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
private void updateInterfaceWithMessages(long uid, ArrayList<MessageObject> messages) { private void updateInterfaceWithMessages(long uid, ArrayList<MessageObject> messages) {
updateInterfaceWithMessages(uid, messages, false);
}
private void updateInterfaceWithMessages(final long uid, final ArrayList<MessageObject> messages, boolean isBroadcast) {
MessageObject lastMessage = null; MessageObject lastMessage = null;
TLRPC.TL_dialog dialog = dialogs_dict.get(uid); TLRPC.TL_dialog dialog = dialogs_dict.get(uid);
...@@ -4328,6 +4670,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4328,6 +4670,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter
boolean changed = false; boolean changed = false;
if (dialog == null) { if (dialog == null) {
if (!isBroadcast) {
dialog = new TLRPC.TL_dialog(); dialog = new TLRPC.TL_dialog();
dialog.id = uid; dialog.id = uid;
dialog.unread_count = 0; dialog.unread_count = 0;
...@@ -4337,16 +4680,19 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4337,16 +4680,19 @@ public class MessagesController implements NotificationCenter.NotificationCenter
dialogs.add(dialog); dialogs.add(dialog);
dialogMessage.put(lastMessage.messageOwner.id, lastMessage); dialogMessage.put(lastMessage.messageOwner.id, lastMessage);
changed = true; changed = true;
}
} else { } else {
if (dialog.top_message > 0 && lastMessage.messageOwner.id > 0 && lastMessage.messageOwner.id > dialog.top_message || if (dialog.top_message > 0 && lastMessage.messageOwner.id > 0 && lastMessage.messageOwner.id > dialog.top_message ||
dialog.top_message < 0 && lastMessage.messageOwner.id < 0 && lastMessage.messageOwner.id < dialog.top_message || dialog.top_message < 0 && lastMessage.messageOwner.id < 0 && lastMessage.messageOwner.id < dialog.top_message ||
dialog.last_message_date < lastMessage.messageOwner.date) { dialog.last_message_date < lastMessage.messageOwner.date) {
dialogMessage.remove(dialog.top_message); dialogMessage.remove(dialog.top_message);
dialog.top_message = lastMessage.messageOwner.id; dialog.top_message = lastMessage.messageOwner.id;
if (!isBroadcast) {
dialog.last_message_date = lastMessage.messageOwner.date; dialog.last_message_date = lastMessage.messageOwner.date;
dialogMessage.put(lastMessage.messageOwner.id, lastMessage);
changed = true; changed = true;
} }
dialogMessage.put(lastMessage.messageOwner.id, lastMessage);
}
} }
if (changed) { if (changed) {
...@@ -4364,7 +4710,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4364,7 +4710,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
}); });
for (TLRPC.TL_dialog d : dialogs) { for (TLRPC.TL_dialog d : dialogs) {
if ((int)d.id != 0) { int high_id = (int)(d.id >> 32);
if ((int)d.id != 0 && high_id != 1) {
dialogsServerOnly.add(d); dialogsServerOnly.add(d);
} }
} }
...@@ -4411,7 +4758,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4411,7 +4758,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter
TLObject object = TLClassStore.Instance().TLdeserialize(is, is.readInt32()); TLObject object = TLClassStore.Instance().TLdeserialize(is, is.readInt32());
BuffersStorage.getInstance().reuseFreeBuffer(is); BuffersStorage.getInstance().reuseFreeBuffer(is);
if (object != null) { if (object != null) {
int from_id = chat.admin_id; int from_id = chat.admin_id;
if (from_id == UserConfig.getClientUserId()) { if (from_id == UserConfig.getClientUserId()) {
from_id = chat.participant_id; from_id = chat.participant_id;
...@@ -4592,8 +4938,23 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4592,8 +4938,23 @@ public class MessagesController implements NotificationCenter.NotificationCenter
public void run() { public void run() {
TLRPC.TL_dialog dialog = dialogs_dict.get(did); TLRPC.TL_dialog dialog = dialogs_dict.get(did);
if (dialog != null) { if (dialog != null) {
dialog.unread_count = 0;
dialogMessage.remove(dialog.top_message); dialogMessage.remove(dialog.top_message);
} }
MessagesStorage.getInstance().storageQueue.postRunnable(new Runnable() {
@Override
public void run() {
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
NotificationsController.getInstance().processReadMessages(null, did, 0, Integer.MAX_VALUE);
HashMap<Long, Integer> dialogsToUpdate = new HashMap<Long, Integer>();
dialogsToUpdate.put(did, 0);
NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate, true);
}
});
}
});
MessagesStorage.getInstance().deleteDialog(did, true); MessagesStorage.getInstance().deleteDialog(did, true);
NotificationCenter.getInstance().postNotificationName(removeAllMessagesFromDialog, did); NotificationCenter.getInstance().postNotificationName(removeAllMessagesFromDialog, did);
NotificationCenter.getInstance().postNotificationName(dialogsNeedReload); NotificationCenter.getInstance().postNotificationName(dialogsNeedReload);
...@@ -4605,6 +4966,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4605,6 +4966,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
pendingEncMessagesToDelete.addAll(serviceMessage.action.random_ids); pendingEncMessagesToDelete.addAll(serviceMessage.action.random_ids);
} }
return null; return null;
} else {
return null;
} }
} else { } else {
FileLog.e("tmessages", "unkown message " + object); FileLog.e("tmessages", "unkown message " + object);
...@@ -4613,9 +4976,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4613,9 +4976,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter
FileLog.e("tmessages", "unkown TLObject"); FileLog.e("tmessages", "unkown TLObject");
} }
} else { } else {
BuffersStorage.getInstance().reuseFreeBuffer(is);
FileLog.e("tmessages", "fingerprint mismatch"); FileLog.e("tmessages", "fingerprint mismatch");
} }
BuffersStorage.getInstance().reuseFreeBuffer(is);
return null; return null;
} }
...@@ -4881,7 +5244,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter ...@@ -4881,7 +5244,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter
} }
}); });
for (TLRPC.TL_dialog d : dialogs) { for (TLRPC.TL_dialog d : dialogs) {
if ((int) d.id != 0) { int high_id = (int)(d.id >> 32);
if ((int)d.id != 0 && high_id != 1) {
dialogsServerOnly.add(d); dialogsServerOnly.add(d);
} }
} }
......
...@@ -191,7 +191,7 @@ public class MessagesStorage { ...@@ -191,7 +191,7 @@ public class MessagesStorage {
} }
} }
public void cleanUp() { public void cleanUp(final boolean isLogin) {
storageQueue.cleanupQueue(); storageQueue.cleanupQueue();
storageQueue.postRunnable(new Runnable() { storageQueue.postRunnable(new Runnable() {
@Override @Override
...@@ -217,8 +217,15 @@ public class MessagesStorage { ...@@ -217,8 +217,15 @@ public class MessagesStorage {
cacheFile.delete(); cacheFile.delete();
cacheFile = null; cacheFile = null;
} }
storageQueue.cleanupQueue();
openDatabase(); openDatabase();
if (isLogin) {
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
MessagesController.getInstance().getDifference();
}
});
}
} }
}); });
} }
...@@ -358,7 +365,19 @@ public class MessagesStorage { ...@@ -358,7 +365,19 @@ public class MessagesStorage {
if (!messagesOnly) { if (!messagesOnly) {
database.executeFast("DELETE FROM dialogs WHERE did = " + did).stepThis().dispose(); database.executeFast("DELETE FROM dialogs WHERE did = " + did).stepThis().dispose();
database.executeFast("DELETE FROM chat_settings WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM chat_settings WHERE uid = " + did).stepThis().dispose();
int lower_id = (int)did;
int high_id = (int)(did >> 32);
if (lower_id != 0) {
if (high_id == 1) {
database.executeFast("DELETE FROM chats WHERE uid = " + lower_id).stepThis().dispose();
} else if (lower_id < 0) {
database.executeFast("DELETE FROM chats WHERE uid = " + (-lower_id)).stepThis().dispose();
}
} else {
database.executeFast("DELETE FROM enc_chats WHERE uid = " + high_id).stepThis().dispose();
}
} }
database.executeFast("UPDATE dialogs SET unread_count = 0 WHERE did = " + did).stepThis().dispose();
database.executeFast("DELETE FROM media_counts WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM media_counts WHERE uid = " + did).stepThis().dispose();
database.executeFast("DELETE FROM messages WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM messages WHERE uid = " + did).stepThis().dispose();
database.executeFast("DELETE FROM media WHERE uid = " + did).stepThis().dispose(); database.executeFast("DELETE FROM media WHERE uid = " + did).stepThis().dispose();
...@@ -699,6 +718,11 @@ public class MessagesStorage { ...@@ -699,6 +718,11 @@ public class MessagesStorage {
} }
} }
} else { } else {
for (TLRPC.TL_chatParticipant part : info.participants) {
if (part.user_id == user_id) {
return;
}
}
TLRPC.TL_chatParticipant participant = new TLRPC.TL_chatParticipant(); TLRPC.TL_chatParticipant participant = new TLRPC.TL_chatParticipant();
participant.user_id = user_id; participant.user_id = user_id;
participant.inviter_id = invited_id; participant.inviter_id = invited_id;
...@@ -731,7 +755,7 @@ public class MessagesStorage { ...@@ -731,7 +755,7 @@ public class MessagesStorage {
}); });
} }
public void loadChatInfo(final int chat_id) { public void loadChatInfo(final int chat_id, final Semaphore semaphore) {
storageQueue.postRunnable(new Runnable() { storageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
...@@ -749,13 +773,23 @@ public class MessagesStorage { ...@@ -749,13 +773,23 @@ public class MessagesStorage {
cursor.dispose(); cursor.dispose();
if (info != null) { if (info != null) {
boolean modified = false;
ArrayList<Integer> usersArr = new ArrayList<Integer>();
String usersToLoad = ""; String usersToLoad = "";
for (TLRPC.TL_chatParticipant c : info.participants) { for (int a = 0; a < info.participants.size(); a++) {
TLRPC.TL_chatParticipant c = info.participants.get(a);
if (usersArr.contains(c.user_id)) {
info.participants.remove(a);
modified = true;
a--;
} else {
if (usersToLoad.length() != 0) { if (usersToLoad.length() != 0) {
usersToLoad += ","; usersToLoad += ",";
} }
usersArr.add(c.user_id);
usersToLoad += c.user_id; usersToLoad += c.user_id;
} }
}
if (usersToLoad.length() != 0) { if (usersToLoad.length() != 0) {
cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, status FROM users WHERE uid IN(%s)", usersToLoad)); cursor = database.queryFinalized(String.format(Locale.US, "SELECT data, status FROM users WHERE uid IN(%s)", usersToLoad));
while (cursor.next()) { while (cursor.next()) {
...@@ -771,10 +805,20 @@ public class MessagesStorage { ...@@ -771,10 +805,20 @@ public class MessagesStorage {
} }
cursor.dispose(); cursor.dispose();
} }
if (modified) {
updateChatInfo(chat_id, info, false);
}
}
if (semaphore != null) {
semaphore.release();
} }
MessagesController.getInstance().processChatInfo(chat_id, info, loadedUsers, true); MessagesController.getInstance().processChatInfo(chat_id, info, loadedUsers, true);
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} finally {
if (semaphore != null) {
semaphore.release();
}
} }
} }
}); });
...@@ -900,7 +944,7 @@ public class MessagesStorage { ...@@ -900,7 +944,7 @@ public class MessagesStorage {
cursor.dispose(); cursor.dispose();
} }
cursor = database.queryFinalized("SELECT c.data, c.name FROM chats as c INNER JOIN dialogs as d ON c.uid = -d.did"); cursor = database.queryFinalized("SELECT data, name FROM chats");
while (cursor.next()) { while (cursor.next()) {
String name = cursor.stringValue(1); String name = cursor.stringValue(1);
String[] args = name.split(" "); String[] args = name.split(" ");
...@@ -909,6 +953,9 @@ public class MessagesStorage { ...@@ -909,6 +953,9 @@ public class MessagesStorage {
ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0)); ByteBufferDesc data = buffersStorage.getFreeBuffer(cursor.byteArrayLength(0));
if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) { if (data != null && cursor.byteBufferValue(0, data.buffer) != 0) {
TLRPC.Chat chat = (TLRPC.Chat) TLClassStore.Instance().TLdeserialize(data, data.readInt32()); TLRPC.Chat chat = (TLRPC.Chat) TLClassStore.Instance().TLdeserialize(data, data.readInt32());
if (!needEncrypted && chat.id < 0) {
continue;
}
resultArrayNames.add(Utilities.generateSearchName(chat.title, null, q)); resultArrayNames.add(Utilities.generateSearchName(chat.title, null, q));
resultArray.add(chat); resultArray.add(chat);
} }
...@@ -918,6 +965,7 @@ public class MessagesStorage { ...@@ -918,6 +965,7 @@ public class MessagesStorage {
} }
} }
cursor.dispose(); cursor.dispose();
NotificationCenter.getInstance().postNotificationName(MessagesController.reloadSearchResults, token, resultArray, resultArrayNames, encUsers); NotificationCenter.getInstance().postNotificationName(MessagesController.reloadSearchResults, token, resultArray, resultArrayNames, encUsers);
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
...@@ -1281,14 +1329,14 @@ public class MessagesStorage { ...@@ -1281,14 +1329,14 @@ public class MessagesStorage {
}); });
} }
public void getMessages(final long dialog_id, final int offset, final int count, final int max_id, final int minDate, final int classGuid, final boolean from_unread, final boolean forward) { public void getMessages(final long dialog_id, final int count, final int max_id, final int minDate, final int classGuid, final boolean from_unread, final boolean forward) {
storageQueue.postRunnable(new Runnable() { storageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
TLRPC.TL_messages_messages res = new TLRPC.TL_messages_messages(); TLRPC.TL_messages_messages res = new TLRPC.TL_messages_messages();
int count_unread = 0; int count_unread = 0;
int count_query = count; int count_query = count;
int offset_query = offset; int offset_query = 0;
int min_unread_id = 0; int min_unread_id = 0;
int max_unread_id = 0; int max_unread_id = 0;
int max_unread_date = 0; int max_unread_date = 0;
...@@ -1447,7 +1495,7 @@ public class MessagesStorage { ...@@ -1447,7 +1495,7 @@ public class MessagesStorage {
res.users.clear(); res.users.clear();
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} finally { } finally {
MessagesController.getInstance().processLoadedMessages(res, dialog_id, offset, count_query, max_id, true, classGuid, min_unread_id, max_unread_id, count_unread, max_unread_date, forward); MessagesController.getInstance().processLoadedMessages(res, dialog_id, count_query, max_id, true, classGuid, min_unread_id, max_unread_id, count_unread, max_unread_date, forward);
} }
} }
}); });
...@@ -1800,7 +1848,7 @@ public class MessagesStorage { ...@@ -1800,7 +1848,7 @@ public class MessagesStorage {
} }
} }
private void putMessagesInternal(final ArrayList<TLRPC.Message> messages, final boolean withTransaction) { private void putMessagesInternal(final ArrayList<TLRPC.Message> messages, final boolean withTransaction, final boolean isBroadcast) {
try { try {
if (withTransaction) { if (withTransaction) {
database.beginTransaction(); database.beginTransaction();
...@@ -1941,10 +1989,21 @@ public class MessagesStorage { ...@@ -1941,10 +1989,21 @@ public class MessagesStorage {
state.dispose(); state.dispose();
state2.dispose(); state2.dispose();
state3.dispose(); state3.dispose();
state = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ifnull((SELECT unread_count FROM dialogs WHERE did = ?), 0) + ?, ?)");
state = database.executeFast("REPLACE INTO dialogs VALUES(?, ?, ?, ?)");
for (HashMap.Entry<Long, TLRPC.Message> pair : messagesMap.entrySet()) { for (HashMap.Entry<Long, TLRPC.Message> pair : messagesMap.entrySet()) {
state.requery();
Long key = pair.getKey(); Long key = pair.getKey();
int dialog_date = 0;
int old_unread_count = 0;
SQLiteCursor cursor = database.queryFinalized("SELECT date, unread_count FROM dialogs WHERE did = " + key);
if (cursor.next()) {
dialog_date = cursor.intValue(0);
old_unread_count = cursor.intValue(1);
}
cursor.dispose();
state.requery();
TLRPC.Message value = pair.getValue(); TLRPC.Message value = pair.getValue();
Integer unread_count = messagesCounts.get(key); Integer unread_count = messagesCounts.get(key);
if (unread_count == null) { if (unread_count == null) {
...@@ -1955,10 +2014,13 @@ public class MessagesStorage { ...@@ -1955,10 +2014,13 @@ public class MessagesStorage {
messageId = value.local_id; messageId = value.local_id;
} }
state.bindLong(1, key); state.bindLong(1, key);
if (!isBroadcast) {
state.bindInteger(2, value.date); state.bindInteger(2, value.date);
state.bindLong(3, key); } else {
state.bindInteger(4, unread_count); state.bindInteger(2, dialog_date != 0 ? dialog_date : value.date);
state.bindInteger(5, messageId); }
state.bindInteger(3, old_unread_count + unread_count);
state.bindInteger(4, messageId);
state.step(); state.step();
} }
state.dispose(); state.dispose();
...@@ -1994,7 +2056,7 @@ public class MessagesStorage { ...@@ -1994,7 +2056,7 @@ public class MessagesStorage {
} }
} }
public void putMessages(final ArrayList<TLRPC.Message> messages, final boolean withTransaction, boolean useQueue) { public void putMessages(final ArrayList<TLRPC.Message> messages, final boolean withTransaction, boolean useQueue, final boolean isBroadcast) {
if (messages.size() == 0) { if (messages.size() == 0) {
return; return;
} }
...@@ -2002,11 +2064,11 @@ public class MessagesStorage { ...@@ -2002,11 +2064,11 @@ public class MessagesStorage {
storageQueue.postRunnable(new Runnable() { storageQueue.postRunnable(new Runnable() {
@Override @Override
public void run() { public void run() {
putMessagesInternal(messages, withTransaction); putMessagesInternal(messages, withTransaction, isBroadcast);
} }
}); });
} else { } else {
putMessagesInternal(messages, withTransaction); putMessagesInternal(messages, withTransaction, isBroadcast);
} }
} }
...@@ -2406,7 +2468,13 @@ public class MessagesStorage { ...@@ -2406,7 +2468,13 @@ public class MessagesStorage {
buffersStorage.reuseFreeBuffer(data); buffersStorage.reuseFreeBuffer(data);
int lower_id = (int)dialog.id; int lower_id = (int)dialog.id;
int high_id = (int)(dialog.id >> 32);
if (lower_id != 0) { if (lower_id != 0) {
if (high_id == 1) {
if (!chatsToLoad.contains(lower_id)) {
chatsToLoad.add(lower_id);
}
} else {
if (lower_id > 0) { if (lower_id > 0) {
if (!usersToLoad.contains(lower_id)) { if (!usersToLoad.contains(lower_id)) {
usersToLoad.add(lower_id); usersToLoad.add(lower_id);
...@@ -2416,10 +2484,10 @@ public class MessagesStorage { ...@@ -2416,10 +2484,10 @@ public class MessagesStorage {
chatsToLoad.add(-lower_id); chatsToLoad.add(-lower_id);
} }
} }
}
} else { } else {
int encryptedId = (int)(dialog.id >> 32); if (!encryptedToLoad.contains(high_id)) {
if (!encryptedToLoad.contains(encryptedId)) { encryptedToLoad.add(high_id);
encryptedToLoad.add(encryptedId);
} }
} }
} }
...@@ -2673,7 +2741,13 @@ public class MessagesStorage { ...@@ -2673,7 +2741,13 @@ public class MessagesStorage {
buffersStorage.reuseFreeBuffer(data); buffersStorage.reuseFreeBuffer(data);
int lower_id = (int)dialog.id; int lower_id = (int)dialog.id;
int high_id = (int)(dialog.id >> 32);
if (lower_id != 0) { if (lower_id != 0) {
if (high_id == 1) {
if (!chatsToLoad.contains(lower_id)) {
chatsToLoad.add(lower_id);
}
} else {
if (lower_id > 0) { if (lower_id > 0) {
if (!usersToLoad.contains(lower_id)) { if (!usersToLoad.contains(lower_id)) {
usersToLoad.add(lower_id); usersToLoad.add(lower_id);
...@@ -2683,10 +2757,10 @@ public class MessagesStorage { ...@@ -2683,10 +2757,10 @@ public class MessagesStorage {
chatsToLoad.add(-lower_id); chatsToLoad.add(-lower_id);
} }
} }
}
} else { } else {
int encryptedId = (int)(dialog.id >> 32); if (!encryptedToLoad.contains(high_id)) {
if (!encryptedToLoad.contains(encryptedId)) { encryptedToLoad.add(high_id);
encryptedToLoad.add(encryptedId);
} }
} }
} }
......
...@@ -24,9 +24,9 @@ import java.util.zip.ZipFile; ...@@ -24,9 +24,9 @@ import java.util.zip.ZipFile;
public class NativeLoader { public class NativeLoader {
private static final long sizes[] = new long[] { private static final long sizes[] = new long[] {
799376, //armeabi 803472, //armeabi
848548, //armeabi-v7a 856740, //armeabi-v7a
1246260, //x86 1250356, //x86
0, //mips 0, //mips
}; };
......
...@@ -183,6 +183,8 @@ public class NotificationsController { ...@@ -183,6 +183,8 @@ public class NotificationsController {
} }
msg = LocaleController.formatString("NotificationGroupKickMember", R.string.NotificationGroupKickMember, Utilities.formatName(user.first_name, user.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name)); msg = LocaleController.formatString("NotificationGroupKickMember", R.string.NotificationGroupKickMember, Utilities.formatName(user.first_name, user.last_name), chat.title, Utilities.formatName(u2.first_name, u2.last_name));
} }
} else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatCreate) {
msg = messageObject.messageText.toString();
} }
} else { } else {
if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) { if (messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty) {
...@@ -305,11 +307,13 @@ public class NotificationsController { ...@@ -305,11 +307,13 @@ public class NotificationsController {
intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE); intent.setAction("com.tmessages.openchat" + Math.random() + Integer.MAX_VALUE);
intent.setFlags(32768); intent.setFlags(32768);
if ((int)dialog_id != 0) { if ((int)dialog_id != 0) {
if (pushDialogs.size() == 1) {
if (chat_id != 0) { if (chat_id != 0) {
intent.putExtra("chatId", chat_id); intent.putExtra("chatId", chat_id);
} else if (user_id != 0) { } else if (user_id != 0) {
intent.putExtra("userId", user_id); intent.putExtra("userId", user_id);
} }
}
if (pushDialogs.size() == 1) { if (pushDialogs.size() == 1) {
if (chat != null) { if (chat != null) {
if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) { if (chat.photo != null && chat.photo.photo_small != null && chat.photo.photo_small.volume_id != 0 && chat.photo.photo_small.local_id != 0) {
...@@ -322,7 +326,9 @@ public class NotificationsController { ...@@ -322,7 +326,9 @@ public class NotificationsController {
} }
} }
} else { } else {
intent.putExtra("encId", (int)(dialog_id >> 32)); if (pushDialogs.size() == 1) {
intent.putExtra("encId", (int) (dialog_id >> 32));
}
} }
PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
...@@ -350,7 +356,6 @@ public class NotificationsController { ...@@ -350,7 +356,6 @@ public class NotificationsController {
.setContentTitle(name) .setContentTitle(name)
.setSmallIcon(R.drawable.notification) .setSmallIcon(R.drawable.notification)
.setAutoCancel(true) .setAutoCancel(true)
.setContentText(detailText)
.setContentIntent(contentIntent); .setContentIntent(contentIntent);
String lastMessage = null; String lastMessage = null;
...@@ -366,8 +371,10 @@ public class NotificationsController { ...@@ -366,8 +371,10 @@ public class NotificationsController {
message = message.replace(name + ": ", "").replace(name + " ", ""); message = message.replace(name + ": ", "").replace(name + " ", "");
} }
} }
mBuilder.setContentText(message);
mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message)); mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(message));
} else { } else {
mBuilder.setContentText(detailText);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(name); inboxStyle.setBigContentTitle(name);
int count = Math.min(10, pushMessages.size()); int count = Math.min(10, pushMessages.size());
...@@ -395,7 +402,7 @@ public class NotificationsController { ...@@ -395,7 +402,7 @@ public class NotificationsController {
} }
if (photoPath != null) { if (photoPath != null) {
Bitmap img = FileLoader.getInstance().getImageFromMemory(photoPath, null, null, "50_50", false); Bitmap img = FileLoader.getInstance().getImageFromMemory(photoPath, null, null, "50_50");
if (img != null) { if (img != null) {
mBuilder.setLargeIcon(img); mBuilder.setLargeIcon(img);
} }
...@@ -417,6 +424,8 @@ public class NotificationsController { ...@@ -417,6 +424,8 @@ public class NotificationsController {
} }
if (needVibrate) { if (needVibrate) {
mBuilder.setVibrate(new long[]{0, 100, 0, 100}); mBuilder.setVibrate(new long[]{0, 100, 0, 100});
} else {
mBuilder.setVibrate(new long[]{0, 0});
} }
} else { } else {
mBuilder.setVibrate(new long[]{0, 0}); mBuilder.setVibrate(new long[]{0, 0});
...@@ -485,7 +494,7 @@ public class NotificationsController { ...@@ -485,7 +494,7 @@ public class NotificationsController {
remove = true; remove = true;
} }
} else { } else {
if (messageObject.messageOwner.id <= max_id) { if (messageObject.messageOwner.id <= max_id || max_id < 0) {
remove = true; remove = true;
} }
} }
...@@ -501,9 +510,6 @@ public class NotificationsController { ...@@ -501,9 +510,6 @@ public class NotificationsController {
if (oldCount != popupMessages.size()) { if (oldCount != popupMessages.size()) {
NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated); NotificationCenter.getInstance().postNotificationName(pushMessagesUpdated);
} }
// if (readMessages != null || oldCount2 != pushMessages.size() || readMessages == null && dialog_id == 0) {
// showOrUpdateNotification(notifyCheck);
// }
} }
public void processNewMessages(ArrayList<MessageObject> messageObjects, boolean isLast) { public void processNewMessages(ArrayList<MessageObject> messageObjects, boolean isLast) {
...@@ -529,7 +535,7 @@ public class NotificationsController { ...@@ -529,7 +535,7 @@ public class NotificationsController {
Boolean value = settingsCache.get(dialog_id); Boolean value = settingsCache.get(dialog_id);
boolean isChat = (int)dialog_id < 0; boolean isChat = (int)dialog_id < 0;
popup = preferences.getInt(isChat ? "popupGroup" : "popupAll", 0); popup = (int)dialog_id == 0 ? 0 : preferences.getInt(isChat ? "popupGroup" : "popupAll", 0);
if (value == null) { if (value == null) {
int notify_override = preferences.getInt("notify2_" + dialog_id, 0); int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
value = !(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0); value = !(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0);
...@@ -569,7 +575,8 @@ public class NotificationsController { ...@@ -569,7 +575,8 @@ public class NotificationsController {
int notify_override = preferences.getInt("notify2_" + dialog_id, 0); int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
boolean isChat = (int)dialog_id < 0; boolean isChat = (int)dialog_id < 0;
Integer currentCount = pushDialogs.get(dialog_id); Integer currentCount = pushDialogs.get(dialog_id);
if (!(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0)) { boolean canAddValue = !(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0);
Integer newCount = entry.getValue(); Integer newCount = entry.getValue();
if (replace) { if (replace) {
if (currentCount != null) { if (currentCount != null) {
...@@ -577,11 +584,20 @@ public class NotificationsController { ...@@ -577,11 +584,20 @@ public class NotificationsController {
} }
if (newCount == 0) { if (newCount == 0) {
pushDialogs.remove(dialog_id); pushDialogs.remove(dialog_id);
} else { for (int a = 0; a < pushMessages.size(); a++) {
MessageObject messageObject = pushMessages.get(a);
if (messageObject.getDialogId() == dialog_id) {
pushMessages.remove(a);
a--;
pushMessagesDict.remove(messageObject.messageOwner.id);
popupMessages.remove(messageObject);
}
}
} else if (canAddValue) {
total_unread_count += newCount; total_unread_count += newCount;
pushDialogs.put(dialog_id, newCount); pushDialogs.put(dialog_id, newCount);
} }
} else { } else if (canAddValue) {
if (currentCount == null) { if (currentCount == null) {
currentCount = 0; currentCount = 0;
} }
...@@ -590,11 +606,10 @@ public class NotificationsController { ...@@ -590,11 +606,10 @@ public class NotificationsController {
pushDialogs.put(dialog_id, currentCount); pushDialogs.put(dialog_id, currentCount);
} }
} }
}
if (old_unread_count != total_unread_count) { if (old_unread_count != total_unread_count) {
showOrUpdateNotification(notifyCheck); showOrUpdateNotification(notifyCheck);
notifyCheck = false;
} }
notifyCheck = false;
if (preferences.getBoolean("badgeNumber", true)) { if (preferences.getBoolean("badgeNumber", true)) {
setBadge(ApplicationLoader.applicationContext, total_unread_count); setBadge(ApplicationLoader.applicationContext, total_unread_count);
} }
...@@ -604,7 +619,6 @@ public class NotificationsController { ...@@ -604,7 +619,6 @@ public class NotificationsController {
pushDialogs.clear(); pushDialogs.clear();
total_unread_count = 0; total_unread_count = 0;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
String dialogsToLoad = "";
for (HashMap.Entry<Long, Integer> entry : dialogs.entrySet()) { for (HashMap.Entry<Long, Integer> entry : dialogs.entrySet()) {
long dialog_id = entry.getKey(); long dialog_id = entry.getKey();
int notify_override = preferences.getInt("notify2_" + dialog_id, 0); int notify_override = preferences.getInt("notify2_" + dialog_id, 0);
...@@ -612,10 +626,6 @@ public class NotificationsController { ...@@ -612,10 +626,6 @@ public class NotificationsController {
if (!(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0)) { if (!(notify_override == 2 || (!preferences.getBoolean("EnableAll", true) || isChat && !preferences.getBoolean("EnableGroup", true)) && notify_override == 0)) {
pushDialogs.put(dialog_id, entry.getValue()); pushDialogs.put(dialog_id, entry.getValue());
total_unread_count += entry.getValue(); total_unread_count += entry.getValue();
if (dialogsToLoad.length() != 0) {
dialogsToLoad += ",";
}
dialogsToLoad += "" + dialog_id;
} }
} }
if (total_unread_count == 0) { if (total_unread_count == 0) {
......
...@@ -781,6 +781,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. ...@@ -781,6 +781,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
processRequestQueue(RPCRequest.RPCRequestClassTransportMask, 0); processRequestQueue(RPCRequest.RPCRequestClassTransportMask, 0);
} }
MessagesController.getInstance().updateConfig(config);
} }
updatingDcSettings = false; updatingDcSettings = false;
} }
...@@ -850,7 +851,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. ...@@ -850,7 +851,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
public long performRpc(final TLObject rpc, final RPCRequest.RPCRequestDelegate completionBlock, final RPCRequest.RPCQuickAckDelegate quickAckBlock, final boolean requiresCompletion, final int requestClass, final int datacenterId, final boolean runQueue) { public long performRpc(final TLObject rpc, final RPCRequest.RPCRequestDelegate completionBlock, final RPCRequest.RPCQuickAckDelegate quickAckBlock, final boolean requiresCompletion, final int requestClass, final int datacenterId, final boolean runQueue) {
if (!UserConfig.isClientActivated() && (requestClass & RPCRequest.RPCRequestClassWithoutLogin) == 0) { if (rpc == null || !UserConfig.isClientActivated() && (requestClass & RPCRequest.RPCRequestClassWithoutLogin) == 0) {
FileLog.e("tmessages", "can't do request without login " + rpc); FileLog.e("tmessages", "can't do request without login " + rpc);
return 0; return 0;
} }
...@@ -1752,7 +1753,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. ...@@ -1752,7 +1753,7 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
} }
private void registerForPush() { private void registerForPush() {
if (registeringForPush) { if (registeringForPush || !UserConfig.isClientActivated()) {
return; return;
} }
UserConfig.registeredForInternalPush = false; UserConfig.registeredForInternalPush = false;
...@@ -1805,6 +1806,8 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection. ...@@ -1805,6 +1806,8 @@ public class ConnectionsManager implements Action.ActionDelegate, TcpConnection.
UserConfig.saveConfig(false); UserConfig.saveConfig(false);
saveSession(); saveSession();
FileLog.e("tmessages", "registered for internal push"); FileLog.e("tmessages", "registered for internal push");
} else {
UserConfig.registeredForInternalPush = false;
} }
registeringForPush = false; registeringForPush = false;
} }
......
...@@ -10,16 +10,17 @@ package org.telegram.messenger; ...@@ -10,16 +10,17 @@ package org.telegram.messenger;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.provider.MediaStore; import android.provider.MediaStore;
import org.telegram.android.AndroidUtilities; import org.telegram.android.AndroidUtilities;
import org.telegram.ui.ApplicationLoader; import org.telegram.ui.ApplicationLoader;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.net.URL;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -57,9 +58,8 @@ public class FileLoadOperation { ...@@ -57,9 +58,8 @@ public class FileLoadOperation {
private String ext; private String ext;
private String httpUrl; private String httpUrl;
private URLConnection httpConnection; private DownloadImageTask httpTask = null;
public boolean needBitmapCreate = true; public boolean needBitmapCreate = true;
private InputStream httpConnectionStream;
private RandomAccessFile fileOutputStream; private RandomAccessFile fileOutputStream;
private RandomAccessFile fiv; private RandomAccessFile fiv;
...@@ -69,6 +69,109 @@ public class FileLoadOperation { ...@@ -69,6 +69,109 @@ public class FileLoadOperation {
public abstract void didChangedLoadProgress(FileLoadOperation operation, float progress); public abstract void didChangedLoadProgress(FileLoadOperation operation, float progress);
} }
private class DownloadImageTask extends AsyncTask<String, Void, Boolean> {
protected Boolean doInBackground(String... urls) {
String url = urls[0];
InputStream httpConnectionStream = null;
try {
URL downloadUrl = new URL(url);
URLConnection httpConnection = downloadUrl.openConnection();
httpConnection.setConnectTimeout(5000);
httpConnection.setReadTimeout(5000);
httpConnection.connect();
httpConnectionStream = httpConnection.getInputStream();
/*String ALLOWED_URI_CHARS = "@#&=*+-_.,:!?()/~'%";
String str = Uri.encode(url, ALLOWED_URI_CHARS);
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(str);
httpConnectionStream = httpclient.execute(request).getEntity().getContent();*/
} catch (Exception e) {
FileLog.e("tmessages", e);
cleanup();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
});
return false;
}
byte[] data = new byte[1024 * 2];
while (true) {
if (isCancelled()) {
break;
}
try {
int readed = httpConnectionStream.read(data);
if (readed > 0) {
fileOutputStream.write(data, 0, readed);
} else if (readed == -1) {
FileLoader.fileLoaderQueue.postRunnable(new Runnable() {
@Override
public void run() {
cleanup();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
onFinishLoadingFile();
} catch (Exception e) {
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
}
});
}
});
break;
} else {
FileLoader.fileLoaderQueue.postRunnable(new Runnable() {
@Override
public void run() {
cleanup();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
});
}
});
break;
}
} catch (Exception e) {
FileLog.e("tmessages", e);
FileLoader.fileLoaderQueue.postRunnable(new Runnable() {
@Override
public void run() {
cleanup();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
});
}
});
}
}
try {
if (httpConnectionStream != null) {
httpConnectionStream.close();
}
httpConnectionStream = null;
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return true;
}
}
public FileLoadOperation(TLRPC.FileLocation fileLocation) { public FileLoadOperation(TLRPC.FileLocation fileLocation) {
if (fileLocation instanceof TLRPC.TL_fileEncryptedLocation) { if (fileLocation instanceof TLRPC.TL_fileEncryptedLocation) {
location = new TLRPC.TL_inputEncryptedFileLocation(); location = new TLRPC.TL_inputEncryptedFileLocation();
...@@ -248,10 +351,14 @@ public class FileLoadOperation { ...@@ -248,10 +351,14 @@ public class FileLoadOperation {
float w_filter = 0; float w_filter = 0;
float h_filter = 0; float h_filter = 0;
boolean blur = false;
if (filter != null) { if (filter != null) {
String args[] = filter.split("_"); String args[] = filter.split("_");
w_filter = Float.parseFloat(args[0]) * AndroidUtilities.density; w_filter = Float.parseFloat(args[0]) * AndroidUtilities.density;
h_filter = Float.parseFloat(args[1]) * AndroidUtilities.density; h_filter = Float.parseFloat(args[1]) * AndroidUtilities.density;
if (args.length > 2) {
blur = true;
}
opts.inJustDecodeBounds = true; opts.inJustDecodeBounds = true;
if (mediaIdFinal != null) { if (mediaIdFinal != null) {
...@@ -270,7 +377,7 @@ public class FileLoadOperation { ...@@ -270,7 +377,7 @@ public class FileLoadOperation {
opts.inSampleSize = (int)scaleFactor; opts.inSampleSize = (int)scaleFactor;
} }
if (filter == null) { if (filter == null || blur) {
opts.inPreferredConfig = Bitmap.Config.ARGB_8888; opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
} else { } else {
opts.inPreferredConfig = Bitmap.Config.RGB_565; opts.inPreferredConfig = Bitmap.Config.RGB_565;
...@@ -300,7 +407,9 @@ public class FileLoadOperation { ...@@ -300,7 +407,9 @@ public class FileLoadOperation {
image = scaledBitmap; image = scaledBitmap;
} }
} }
if (image != null && blur && bitmapH < 100 && bitmapW < 100) {
Utilities.blurBitmap(image, (int)bitmapW, (int)bitmapH, image.getRowBytes());
}
} }
if (FileLoader.getInstance().runtimeHack != null) { if (FileLoader.getInstance().runtimeHack != null) {
FileLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); FileLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight());
...@@ -400,7 +509,6 @@ public class FileLoadOperation { ...@@ -400,7 +509,6 @@ public class FileLoadOperation {
} }
} }
}); });
} }
} }
} }
...@@ -428,14 +536,8 @@ public class FileLoadOperation { ...@@ -428,14 +536,8 @@ public class FileLoadOperation {
private void cleanup() { private void cleanup() {
if (httpUrl != null) { if (httpUrl != null) {
try { if (httpTask != null) {
if (httpConnectionStream != null) { httpTask.cancel(true);
httpConnectionStream.close();
}
httpConnection = null;
httpConnectionStream = null;
} catch (Exception e) {
FileLog.e("tmessages", e);
} }
} else { } else {
try { try {
...@@ -494,10 +596,14 @@ public class FileLoadOperation { ...@@ -494,10 +596,14 @@ public class FileLoadOperation {
float w_filter = 0; float w_filter = 0;
float h_filter; float h_filter;
boolean blur = false;
if (filter != null) { if (filter != null) {
String args[] = filter.split("_"); String args[] = filter.split("_");
w_filter = Float.parseFloat(args[0]) * AndroidUtilities.density; w_filter = Float.parseFloat(args[0]) * AndroidUtilities.density;
h_filter = Float.parseFloat(args[1]) * AndroidUtilities.density; h_filter = Float.parseFloat(args[1]) * AndroidUtilities.density;
if (args.length > 2) {
blur = true;
}
opts.inJustDecodeBounds = true; opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(cacheFileFinal.getAbsolutePath(), opts); BitmapFactory.decodeFile(cacheFileFinal.getAbsolutePath(), opts);
...@@ -511,7 +617,7 @@ public class FileLoadOperation { ...@@ -511,7 +617,7 @@ public class FileLoadOperation {
opts.inSampleSize = (int) scaleFactor; opts.inSampleSize = (int) scaleFactor;
} }
if (filter == null) { if (filter == null || blur) {
opts.inPreferredConfig = Bitmap.Config.ARGB_8888; opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
} else { } else {
opts.inPreferredConfig = Bitmap.Config.RGB_565; opts.inPreferredConfig = Bitmap.Config.RGB_565;
...@@ -540,7 +646,9 @@ public class FileLoadOperation { ...@@ -540,7 +646,9 @@ public class FileLoadOperation {
image = scaledBitmap; image = scaledBitmap;
} }
} }
if (image != null && blur && bitmapH < 100 && bitmapW < 100) {
Utilities.blurBitmap(image, (int)bitmapW, (int)bitmapH, image.getRowBytes());
}
} }
if (image != null && FileLoader.getInstance().runtimeHack != null) { if (image != null && FileLoader.getInstance().runtimeHack != null) {
FileLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); FileLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight());
...@@ -565,68 +673,11 @@ public class FileLoadOperation { ...@@ -565,68 +673,11 @@ public class FileLoadOperation {
if (state != 1) { if (state != 1) {
return; return;
} }
if (httpConnection == null) { httpTask = new DownloadImageTask();
try { if (android.os.Build.VERSION.SDK_INT >= 11) {
URL downloadUrl = new URL(httpUrl); httpTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
httpConnection = downloadUrl.openConnection();
httpConnection.setConnectTimeout(5000);
httpConnection.setReadTimeout(5000);
httpConnection.connect();
httpConnectionStream = httpConnection.getInputStream();
} catch (Exception e) {
FileLog.e("tmessages", e);
cleanup();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
});
return;
}
}
try {
byte[] data = new byte[1024 * 2];
int readed = httpConnectionStream.read(data);
if (readed > 0) {
fileOutputStream.write(data, 0, readed);
FileLoader.fileLoaderQueue.postRunnable(new Runnable() {
@Override
public void run() {
startDownloadHTTPRequest();
}
});
} else if (readed == -1) {
cleanup();
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
try {
onFinishLoadingFile();
} catch (Exception e) {
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
}
});
} else { } else {
cleanup(); httpTask.execute(null, null, null);
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
});
}
} catch (Exception e) {
cleanup();
FileLog.e("tmessages", e);
Utilities.stageQueue.postRunnable(new Runnable() {
@Override
public void run() {
delegate.didFailedLoadingFile(FileLoadOperation.this);
}
});
} }
} }
......
...@@ -64,7 +64,7 @@ public class FileLoader { ...@@ -64,7 +64,7 @@ public class FileLoader {
private long lastProgressUpdateTime = 0; private long lastProgressUpdateTime = 0;
private HashMap<String, Integer> BitmapUseCounts = new HashMap<String, Integer>(); private HashMap<String, Integer> BitmapUseCounts = new HashMap<String, Integer>();
int lastImageNum; private int lastImageNum = 0;
public static final int FileDidUpload = 10000; public static final int FileDidUpload = 10000;
public static final int FileDidFailUpload = 10001; public static final int FileDidFailUpload = 10001;
...@@ -717,15 +717,15 @@ public class FileLoader { ...@@ -717,15 +717,15 @@ public class FileLoader {
}); });
} }
public Bitmap getImageFromMemory(TLRPC.FileLocation url, ImageReceiver imageView, String filter, boolean cancel) { public Bitmap getImageFromMemory(TLRPC.FileLocation url, ImageReceiver imageView, String filter) {
return getImageFromMemory(url, null, imageView, filter, cancel); return getImageFromMemory(url, null, imageView, filter);
} }
public Bitmap getImageFromMemory(String url, ImageReceiver imageView, String filter, boolean cancel) { public Bitmap getImageFromMemory(String url, ImageReceiver imageView, String filter) {
return getImageFromMemory(null, url, imageView, filter, cancel); return getImageFromMemory(null, url, imageView, filter);
} }
public Bitmap getImageFromMemory(TLRPC.FileLocation url, String httpUrl, ImageReceiver imageView, String filter, boolean cancel) { public Bitmap getImageFromMemory(TLRPC.FileLocation url, String httpUrl, ImageReceiver imageView, String filter) {
if (url == null && httpUrl == null) { if (url == null && httpUrl == null) {
return null; return null;
} }
...@@ -739,11 +739,7 @@ public class FileLoader { ...@@ -739,11 +739,7 @@ public class FileLoader {
key += "@" + filter; key += "@" + filter;
} }
Bitmap img = imageFromKey(key); return imageFromKey(key);
if (imageView != null && img != null && cancel) {
cancelLoadingForImageView(imageView);
}
return img;
} }
private void performReplace(String oldKey, String newKey) { private void performReplace(String oldKey, String newKey) {
...@@ -1105,8 +1101,13 @@ public class FileLoader { ...@@ -1105,8 +1101,13 @@ public class FileLoader {
return null; return null;
} }
float scaleFactor = Math.max(photoW / maxWidth, photoH / maxHeight); float scaleFactor = Math.max(photoW / maxWidth, photoH / maxHeight);
int w = (int)(photoW / scaleFactor);
int h = (int)(photoH / scaleFactor);
if (h == 0 || w == 0) {
return null;
}
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int)(photoW / scaleFactor), (int)(photoH / scaleFactor), true); Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
TLRPC.TL_fileLocation location = new TLRPC.TL_fileLocation(); TLRPC.TL_fileLocation location = new TLRPC.TL_fileLocation();
location.volume_id = Integer.MIN_VALUE; location.volume_id = Integer.MIN_VALUE;
......
...@@ -63,12 +63,12 @@ public class FileLog { ...@@ -63,12 +63,12 @@ public class FileLog {
e.printStackTrace(); e.printStackTrace();
} }
try { try {
logQueue = new DispatchQueue("logQueue");
currentFile.createNewFile(); currentFile.createNewFile();
FileOutputStream stream = new FileOutputStream(currentFile); FileOutputStream stream = new FileOutputStream(currentFile);
streamWriter = new OutputStreamWriter(stream); streamWriter = new OutputStreamWriter(stream);
streamWriter.write("-----start log " + dateFormat.format(System.currentTimeMillis()) + "-----\n"); streamWriter.write("-----start log " + dateFormat.format(System.currentTimeMillis()) + "-----\n");
streamWriter.flush(); streamWriter.flush();
logQueue = new DispatchQueue("logQueue");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -439,6 +439,7 @@ public class TLClassStore { ...@@ -439,6 +439,7 @@ public class TLClassStore {
classStore.put(TLRPC.TL_decryptedMessageMediaAudio_old.constructor, TLRPC.TL_decryptedMessageMediaAudio_old.class); classStore.put(TLRPC.TL_decryptedMessageMediaAudio_old.constructor, TLRPC.TL_decryptedMessageMediaAudio_old.class);
classStore.put(TLRPC.TL_audio_old.constructor, TLRPC.TL_audio_old.class); classStore.put(TLRPC.TL_audio_old.constructor, TLRPC.TL_audio_old.class);
classStore.put(TLRPC.TL_video_old.constructor, TLRPC.TL_video_old.class); classStore.put(TLRPC.TL_video_old.constructor, TLRPC.TL_video_old.class);
classStore.put(TLRPC.TL_messageActionCreatedBroadcastList.constructor, TLRPC.TL_messageActionCreatedBroadcastList.class);
} }
static TLClassStore store = null; static TLClassStore store = null;
......
...@@ -8996,6 +8996,17 @@ public class TLRPC { ...@@ -8996,6 +8996,17 @@ public class TLRPC {
} }
} }
public static class TL_messageActionCreatedBroadcastList extends MessageAction {
public static int constructor = 0x55555557;
public void readParams(AbsSerializedData stream) {
}
public void serializeToStream(AbsSerializedData stream) {
stream.writeInt32(constructor);
}
}
public static class TL_documentEncrypted extends TL_document { public static class TL_documentEncrypted extends TL_document {
public static int constructor = 0x55555556; public static int constructor = 0x55555556;
......
...@@ -24,6 +24,7 @@ public class UserConfig { ...@@ -24,6 +24,7 @@ public class UserConfig {
public static String pushString = ""; public static String pushString = "";
public static int lastSendMessageId = -210000; public static int lastSendMessageId = -210000;
public static int lastLocalId = -210000; public static int lastLocalId = -210000;
public static int lastBroadcastId = -1;
public static String contactsHash = ""; public static String contactsHash = "";
public static String importHash = ""; public static String importHash = "";
private final static Integer sync = 1; private final static Integer sync = 1;
...@@ -56,6 +57,7 @@ public class UserConfig { ...@@ -56,6 +57,7 @@ public class UserConfig {
editor.putString("importHash", importHash); editor.putString("importHash", importHash);
editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos); editor.putBoolean("saveIncomingPhotos", saveIncomingPhotos);
editor.putInt("contactsVersion", contactsVersion); editor.putInt("contactsVersion", contactsVersion);
editor.putInt("lastBroadcastId", lastBroadcastId);
editor.putBoolean("registeredForInternalPush", registeredForInternalPush); editor.putBoolean("registeredForInternalPush", registeredForInternalPush);
if (currentUser != null) { if (currentUser != null) {
if (withFile) { if (withFile) {
...@@ -174,6 +176,7 @@ public class UserConfig { ...@@ -174,6 +176,7 @@ public class UserConfig {
importHash = preferences.getString("importHash", ""); importHash = preferences.getString("importHash", "");
saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false); saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false);
contactsVersion = preferences.getInt("contactsVersion", 0); contactsVersion = preferences.getInt("contactsVersion", 0);
lastBroadcastId = preferences.getInt("lastBroadcastId", -1);
registeredForInternalPush = preferences.getBoolean("registeredForInternalPush", false); registeredForInternalPush = preferences.getBoolean("registeredForInternalPush", false);
String user = preferences.getString("user", null); String user = preferences.getString("user", null);
if (user != null) { if (user != null) {
...@@ -196,6 +199,7 @@ public class UserConfig { ...@@ -196,6 +199,7 @@ public class UserConfig {
lastLocalId = -210000; lastLocalId = -210000;
lastSendMessageId = -210000; lastSendMessageId = -210000;
contactsVersion = 1; contactsVersion = 1;
lastBroadcastId = -1;
saveIncomingPhotos = false; saveIncomingPhotos = false;
saveConfig(true); saveConfig(true);
} }
......
...@@ -132,6 +132,7 @@ public class Utilities { ...@@ -132,6 +132,7 @@ public class Utilities {
public native static long doPQNative(long _what); public native static long doPQNative(long _what);
public native static void loadBitmap(String path, int[] bitmap, int scale, int format, int width, int height); public native static void loadBitmap(String path, int[] bitmap, int scale, int format, int width, int height);
public native static void blurBitmap(Object bitmap, int width, int height, int stride);
private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length);
public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) {
...@@ -139,6 +140,9 @@ public class Utilities { ...@@ -139,6 +140,9 @@ public class Utilities {
} }
public static Integer parseInt(String value) { public static Integer parseInt(String value) {
if (value == null) {
return 0;
}
Integer val = 0; Integer val = 0;
try { try {
Matcher matcher = pattern.matcher(value); Matcher matcher = pattern.matcher(value);
...@@ -548,7 +552,7 @@ public class Utilities { ...@@ -548,7 +552,7 @@ public class Utilities {
} }
public static int getGroupAvatarForId(int id) { public static int getGroupAvatarForId(int id) {
return arrGroupsAvatars[getColorIndex(-id)]; return arrGroupsAvatars[getColorIndex(-Math.abs(id))];
} }
public static String MD5(String md5) { public static String MD5(String md5) {
......
...@@ -39,7 +39,6 @@ public class MessageObject { ...@@ -39,7 +39,6 @@ public class MessageObject {
public int contentType; public int contentType;
public ArrayList<PhotoObject> photoThumbs; public ArrayList<PhotoObject> photoThumbs;
public Bitmap imagePreview; public Bitmap imagePreview;
public PhotoObject previewPhoto;
public String dateKey; public String dateKey;
public boolean deleted = false; public boolean deleted = false;
public float audioProgress; public float audioProgress;
...@@ -63,6 +62,10 @@ public class MessageObject { ...@@ -63,6 +62,10 @@ public class MessageObject {
public ArrayList<TextLayoutBlock> textLayoutBlocks; public ArrayList<TextLayoutBlock> textLayoutBlocks;
public MessageObject(TLRPC.Message message, AbstractMap<Integer, TLRPC.User> users) { public MessageObject(TLRPC.Message message, AbstractMap<Integer, TLRPC.User> users) {
this(message, users, 1);
}
public MessageObject(TLRPC.Message message, AbstractMap<Integer, TLRPC.User> users, int preview) {
if (textPaint == null) { if (textPaint == null) {
textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(0xff000000); textPaint.setColor(0xff000000);
...@@ -134,10 +137,6 @@ public class MessageObject { ...@@ -134,10 +137,6 @@ public class MessageObject {
messageText = LocaleController.getString("ActionAddUser", R.string.ActionAddUser).replace("un2", "").replace("un1", ""); messageText = LocaleController.getString("ActionAddUser", R.string.ActionAddUser).replace("un2", "").replace("un1", "");
} }
} else if (message.action instanceof TLRPC.TL_messageActionChatEditPhoto) { } else if (message.action instanceof TLRPC.TL_messageActionChatEditPhoto) {
photoThumbs = new ArrayList<PhotoObject>();
for (TLRPC.PhotoSize size : message.action.photo.sizes) {
photoThumbs.add(new PhotoObject(size));
}
if (isFromMe()) { if (isFromMe()) {
messageText = LocaleController.getString("ActionYouChangedPhoto", R.string.ActionYouChangedPhoto); messageText = LocaleController.getString("ActionYouChangedPhoto", R.string.ActionYouChangedPhoto);
} else { } else {
...@@ -232,26 +231,14 @@ public class MessageObject { ...@@ -232,26 +231,14 @@ public class MessageObject {
} }
} }
} }
} else if (message.action instanceof TLRPC.TL_messageActionCreatedBroadcastList) {
messageText = LocaleController.formatString("YouCreatedBroadcastList", R.string.YouCreatedBroadcastList);
} }
} }
} else if (message.media != null && !(message.media instanceof TLRPC.TL_messageMediaEmpty)) { } else if (message.media != null && !(message.media instanceof TLRPC.TL_messageMediaEmpty)) {
if (message.media instanceof TLRPC.TL_messageMediaPhoto) { if (message.media instanceof TLRPC.TL_messageMediaPhoto) {
photoThumbs = new ArrayList<PhotoObject>();
for (TLRPC.PhotoSize size : message.media.photo.sizes) {
PhotoObject obj = new PhotoObject(size);
photoThumbs.add(obj);
if (imagePreview == null && obj.image != null) {
imagePreview = obj.image;
}
}
messageText = LocaleController.getString("AttachPhoto", R.string.AttachPhoto); messageText = LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
} else if (message.media instanceof TLRPC.TL_messageMediaVideo) { } else if (message.media instanceof TLRPC.TL_messageMediaVideo) {
photoThumbs = new ArrayList<PhotoObject>();
PhotoObject obj = new PhotoObject(message.media.video.thumb);
photoThumbs.add(obj);
if (imagePreview == null && obj.image != null) {
imagePreview = obj.image;
}
messageText = LocaleController.getString("AttachVideo", R.string.AttachVideo); messageText = LocaleController.getString("AttachVideo", R.string.AttachVideo);
} else if (message.media instanceof TLRPC.TL_messageMediaGeo) { } else if (message.media instanceof TLRPC.TL_messageMediaGeo) {
messageText = LocaleController.getString("AttachLocation", R.string.AttachLocation); messageText = LocaleController.getString("AttachLocation", R.string.AttachLocation);
...@@ -260,11 +247,6 @@ public class MessageObject { ...@@ -260,11 +247,6 @@ public class MessageObject {
} else if (message.media instanceof TLRPC.TL_messageMediaUnsupported) { } else if (message.media instanceof TLRPC.TL_messageMediaUnsupported) {
messageText = LocaleController.getString("UnsuppotedMedia", R.string.UnsuppotedMedia); messageText = LocaleController.getString("UnsuppotedMedia", R.string.UnsuppotedMedia);
} else if (message.media instanceof TLRPC.TL_messageMediaDocument) { } else if (message.media instanceof TLRPC.TL_messageMediaDocument) {
if (!(message.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty)) {
photoThumbs = new ArrayList<PhotoObject>();
PhotoObject obj = new PhotoObject(message.media.document.thumb);
photoThumbs.add(obj);
}
messageText = LocaleController.getString("AttachDocument", R.string.AttachDocument); messageText = LocaleController.getString("AttachDocument", R.string.AttachDocument);
} else if (message.media instanceof TLRPC.TL_messageMediaAudio) { } else if (message.media instanceof TLRPC.TL_messageMediaAudio) {
messageText = LocaleController.getString("AttachAudio", R.string.AttachAudio); messageText = LocaleController.getString("AttachAudio", R.string.AttachAudio);
...@@ -329,6 +311,80 @@ public class MessageObject { ...@@ -329,6 +311,80 @@ public class MessageObject {
dateKey = String.format("%d_%02d_%02d", dateYear, dateMonth, dateDay); dateKey = String.format("%d_%02d_%02d", dateYear, dateMonth, dateDay);
generateLayout(); generateLayout();
generateThumbs(false, preview);
}
public void generateThumbs(boolean update, int preview) {
if (messageOwner instanceof TLRPC.TL_messageService) {
if (messageOwner.action instanceof TLRPC.TL_messageActionChatEditPhoto) {
if (!update) {
photoThumbs = new ArrayList<PhotoObject>();
for (TLRPC.PhotoSize size : messageOwner.action.photo.sizes) {
photoThumbs.add(new PhotoObject(size, preview));
}
} else if (photoThumbs != null && !photoThumbs.isEmpty()) {
for (PhotoObject photoObject : photoThumbs) {
for (TLRPC.PhotoSize size : messageOwner.action.photo.sizes) {
if (size instanceof TLRPC.TL_photoSizeEmpty) {
continue;
}
if (size.type.equals(photoObject.photoOwner.type)) {
photoObject.photoOwner.location = size.location;
break;
}
}
}
}
}
} else if (messageOwner.media != null && !(messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) {
if (messageOwner.media instanceof TLRPC.TL_messageMediaPhoto) {
if (!update) {
photoThumbs = new ArrayList<PhotoObject>();
for (TLRPC.PhotoSize size : messageOwner.media.photo.sizes) {
PhotoObject obj = new PhotoObject(size, preview);
photoThumbs.add(obj);
if (imagePreview == null && obj.image != null) {
imagePreview = obj.image;
}
}
} else if (photoThumbs != null && !photoThumbs.isEmpty()) {
for (PhotoObject photoObject : photoThumbs) {
for (TLRPC.PhotoSize size : messageOwner.media.photo.sizes) {
if (size instanceof TLRPC.TL_photoSizeEmpty) {
continue;
}
if (size.type.equals(photoObject.photoOwner.type)) {
photoObject.photoOwner.location = size.location;
break;
}
}
}
}
} else if (messageOwner.media instanceof TLRPC.TL_messageMediaVideo) {
if (!update) {
photoThumbs = new ArrayList<PhotoObject>();
PhotoObject obj = new PhotoObject(messageOwner.media.video.thumb, preview);
photoThumbs.add(obj);
if (imagePreview == null && obj.image != null) {
imagePreview = obj.image;
}
} else if (photoThumbs != null && !photoThumbs.isEmpty() && messageOwner.media.video.thumb != null) {
PhotoObject photoObject = photoThumbs.get(0);
photoObject.photoOwner.location = messageOwner.media.video.thumb.location;
}
} if (messageOwner.media instanceof TLRPC.TL_messageMediaDocument) {
if (!(messageOwner.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty)) {
if (!update) {
photoThumbs = new ArrayList<PhotoObject>();
PhotoObject obj = new PhotoObject(messageOwner.media.document.thumb, preview);
photoThumbs.add(obj);
} else if (photoThumbs != null && !photoThumbs.isEmpty() && messageOwner.media.document.thumb != null) {
PhotoObject photoObject = photoThumbs.get(0);
photoObject.photoOwner.location = messageOwner.media.document.thumb.location;
}
}
}
}
} }
public String getFileName() { public String getFileName() {
......
...@@ -13,6 +13,7 @@ import android.graphics.BitmapFactory; ...@@ -13,6 +13,7 @@ import android.graphics.BitmapFactory;
import org.telegram.messenger.TLRPC; import org.telegram.messenger.TLRPC;
import org.telegram.messenger.FileLoader; import org.telegram.messenger.FileLoader;
import org.telegram.messenger.Utilities;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -20,21 +21,26 @@ public class PhotoObject { ...@@ -20,21 +21,26 @@ public class PhotoObject {
public TLRPC.PhotoSize photoOwner; public TLRPC.PhotoSize photoOwner;
public Bitmap image; public Bitmap image;
public PhotoObject(TLRPC.PhotoSize photo) { public PhotoObject(TLRPC.PhotoSize photo, int preview) {
photoOwner = photo; photoOwner = photo;
if (photo instanceof TLRPC.TL_photoCachedSize) { if (preview != 0 && photo instanceof TLRPC.TL_photoCachedSize) {
BitmapFactory.Options opts = new BitmapFactory.Options(); BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.RGB_565; opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
opts.inDither = false; opts.inDither = false;
opts.outWidth = photo.w; opts.outWidth = photo.w;
opts.outHeight = photo.h; opts.outHeight = photo.h;
image = BitmapFactory.decodeByteArray(photoOwner.bytes, 0, photoOwner.bytes.length, opts); image = BitmapFactory.decodeByteArray(photoOwner.bytes, 0, photoOwner.bytes.length, opts);
if (image != null && FileLoader.getInstance().runtimeHack != null) { if (image != null) {
if (preview == 2) {
Utilities.blurBitmap(image, image.getWidth(), image.getHeight(), image.getRowBytes());
}
if (FileLoader.getInstance().runtimeHack != null) {
FileLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight()); FileLoader.getInstance().runtimeHack.trackFree(image.getRowBytes() * image.getHeight());
} }
} }
} }
}
public static PhotoObject getClosestImageWithSize(ArrayList<PhotoObject> arr, int width, int height) { public static PhotoObject getClosestImageWithSize(ArrayList<PhotoObject> arr, int width, int height) {
if (arr == null) { if (arr == null) {
......
...@@ -8,7 +8,6 @@ ...@@ -8,7 +8,6 @@
package org.telegram.ui; package org.telegram.ui;
import android.app.Activity;
import android.app.AlarmManager; import android.app.AlarmManager;
import android.app.Application; import android.app.Application;
import android.app.PendingIntent; import android.app.PendingIntent;
...@@ -93,34 +92,6 @@ public class ApplicationLoader extends Application { ...@@ -93,34 +92,6 @@ public class ApplicationLoader extends Application {
UserConfig.loadConfig(); UserConfig.loadConfig();
if (UserConfig.getCurrentUser() != null) { if (UserConfig.getCurrentUser() != null) {
boolean changed = false;
SharedPreferences preferences = applicationContext.getSharedPreferences("Notifications", MODE_PRIVATE);
int v = preferences.getInt("v", 0);
if (v != 1) {
SharedPreferences preferences2 = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences2.edit();
if (preferences.contains("view_animations")) {
editor.putBoolean("view_animations", preferences.getBoolean("view_animations", false));
}
if (preferences.contains("selectedBackground")) {
editor.putInt("selectedBackground", preferences.getInt("selectedBackground", 1000001));
}
if (preferences.contains("selectedColor")) {
editor.putInt("selectedColor", preferences.getInt("selectedColor", 0));
}
if (preferences.contains("fons_size")) {
editor.putInt("fons_size", preferences.getInt("fons_size", 16));
}
editor.commit();
editor = preferences.edit();
editor.putInt("v", 1);
editor.remove("view_animations");
editor.remove("selectedBackground");
editor.remove("selectedColor");
editor.remove("fons_size");
editor.commit();
}
MessagesController.getInstance().users.put(UserConfig.getClientUserId(), UserConfig.getCurrentUser()); MessagesController.getInstance().users.put(UserConfig.getClientUserId(), UserConfig.getCurrentUser());
ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone); ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone);
ConnectionsManager.getInstance().initPushConnection(); ConnectionsManager.getInstance().initPushConnection();
......
...@@ -60,9 +60,11 @@ public class ChatBaseCell extends BaseCell { ...@@ -60,9 +60,11 @@ public class ChatBaseCell extends BaseCell {
private static Drawable checkDrawable; private static Drawable checkDrawable;
private static Drawable halfCheckDrawable; private static Drawable halfCheckDrawable;
private static Drawable clockDrawable; private static Drawable clockDrawable;
private static Drawable broadcastDrawable;
private static Drawable checkMediaDrawable; private static Drawable checkMediaDrawable;
private static Drawable halfCheckMediaDrawable; private static Drawable halfCheckMediaDrawable;
private static Drawable clockMediaDrawable; private static Drawable clockMediaDrawable;
private static Drawable broadcastMediaDrawable;
private static Drawable errorDrawable; private static Drawable errorDrawable;
protected static Drawable mediaBackgroundDrawable; protected static Drawable mediaBackgroundDrawable;
private static TextPaint timePaintIn; private static TextPaint timePaintIn;
...@@ -177,6 +179,8 @@ public class ChatBaseCell extends BaseCell { ...@@ -177,6 +179,8 @@ public class ChatBaseCell extends BaseCell {
clockMediaDrawable = getResources().getDrawable(R.drawable.msg_clock_photo); clockMediaDrawable = getResources().getDrawable(R.drawable.msg_clock_photo);
errorDrawable = getResources().getDrawable(R.drawable.msg_warning); errorDrawable = getResources().getDrawable(R.drawable.msg_warning);
mediaBackgroundDrawable = getResources().getDrawable(R.drawable.phototime); mediaBackgroundDrawable = getResources().getDrawable(R.drawable.phototime);
broadcastDrawable = getResources().getDrawable(R.drawable.broadcast3);
broadcastMediaDrawable = getResources().getDrawable(R.drawable.broadcast4);
timePaintIn = new TextPaint(TextPaint.ANTI_ALIAS_FLAG); timePaintIn = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
timePaintIn.setTextSize(AndroidUtilities.dp(12)); timePaintIn.setTextSize(AndroidUtilities.dp(12));
...@@ -569,6 +573,7 @@ public class ChatBaseCell extends BaseCell { ...@@ -569,6 +573,7 @@ public class ChatBaseCell extends BaseCell {
boolean drawCheck2 = false; boolean drawCheck2 = false;
boolean drawClock = false; boolean drawClock = false;
boolean drawError = false; boolean drawError = false;
boolean isBroadcast = (int)(currentMessageObject.getDialogId() >> 32) == 1;
if (currentMessageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { if (currentMessageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) {
drawCheck1 = false; drawCheck1 = false;
...@@ -601,6 +606,17 @@ public class ChatBaseCell extends BaseCell { ...@@ -601,6 +606,17 @@ public class ChatBaseCell extends BaseCell {
clockMediaDrawable.draw(canvas); clockMediaDrawable.draw(canvas);
} }
} }
if (isBroadcast) {
if (drawCheck1 || drawCheck2) {
if (!media) {
setDrawableBounds(broadcastDrawable, layoutWidth - AndroidUtilities.dpf(20.5f) - broadcastDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(8.0f) - broadcastDrawable.getIntrinsicHeight());
broadcastDrawable.draw(canvas);
} else {
setDrawableBounds(broadcastMediaDrawable, layoutWidth - AndroidUtilities.dpf(24.0f) - broadcastMediaDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(13.0f) - broadcastMediaDrawable.getIntrinsicHeight());
broadcastMediaDrawable.draw(canvas);
}
}
} else {
if (drawCheck2) { if (drawCheck2) {
if (!media) { if (!media) {
if (drawCheck1) { if (drawCheck1) {
...@@ -627,6 +643,7 @@ public class ChatBaseCell extends BaseCell { ...@@ -627,6 +643,7 @@ public class ChatBaseCell extends BaseCell {
halfCheckMediaDrawable.draw(canvas); halfCheckMediaDrawable.draw(canvas);
} }
} }
}
if (drawError) { if (drawError) {
if (!media) { if (!media) {
setDrawableBounds(errorDrawable, layoutWidth - AndroidUtilities.dp(18) - errorDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(6.5f) - errorDrawable.getIntrinsicHeight()); setDrawableBounds(errorDrawable, layoutWidth - AndroidUtilities.dp(18) - errorDrawable.getIntrinsicWidth(), layoutHeight - AndroidUtilities.dpf(6.5f) - errorDrawable.getIntrinsicHeight());
......
...@@ -31,7 +31,7 @@ import org.telegram.objects.PhotoObject; ...@@ -31,7 +31,7 @@ import org.telegram.objects.PhotoObject;
import org.telegram.ui.PhotoViewer; import org.telegram.ui.PhotoViewer;
import org.telegram.ui.Views.GifDrawable; import org.telegram.ui.Views.GifDrawable;
import org.telegram.ui.Views.ImageReceiver; import org.telegram.ui.Views.ImageReceiver;
import org.telegram.ui.Views.ProgressView; import org.telegram.ui.Views.RoundProgressView;
import java.io.File; import java.io.File;
import java.util.Locale; import java.util.Locale;
...@@ -45,7 +45,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -45,7 +45,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
private static Drawable placeholderInDrawable; private static Drawable placeholderInDrawable;
private static Drawable placeholderOutDrawable; private static Drawable placeholderOutDrawable;
private static Drawable videoIconDrawable; private static Drawable videoIconDrawable;
private static Drawable[][] buttonStatesDrawables = new Drawable[4][2]; private static Drawable[] buttonStatesDrawables = new Drawable[4];
private static TextPaint infoPaint; private static TextPaint infoPaint;
private static MessageObject lastDownloadedGifMessage = null; private static MessageObject lastDownloadedGifMessage = null;
...@@ -57,10 +57,11 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -57,10 +57,11 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
private String currentUrl; private String currentUrl;
private String currentPhotoFilter; private String currentPhotoFilter;
private ImageReceiver photoImage; private ImageReceiver photoImage;
private ProgressView progressView; private RoundProgressView progressView;
public int downloadPhotos = 0; public int downloadPhotos = 0;
private boolean progressVisible = false; private boolean progressVisible = false;
private boolean photoNotSet = false; private boolean photoNotSet = false;
private boolean cancelLoading = false;
private int TAG; private int TAG;
...@@ -83,14 +84,10 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -83,14 +84,10 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
if (placeholderInDrawable == null) { if (placeholderInDrawable == null) {
placeholderInDrawable = getResources().getDrawable(R.drawable.photo_placeholder_in); placeholderInDrawable = getResources().getDrawable(R.drawable.photo_placeholder_in);
placeholderOutDrawable = getResources().getDrawable(R.drawable.photo_placeholder_out); placeholderOutDrawable = getResources().getDrawable(R.drawable.photo_placeholder_out);
buttonStatesDrawables[0][0] = getResources().getDrawable(R.drawable.photoload); buttonStatesDrawables[0] = getResources().getDrawable(R.drawable.photoload);
buttonStatesDrawables[0][1] = getResources().getDrawable(R.drawable.photoload_pressed); buttonStatesDrawables[1] = getResources().getDrawable(R.drawable.photocancel);
buttonStatesDrawables[1][0] = getResources().getDrawable(R.drawable.photocancel); buttonStatesDrawables[2] = getResources().getDrawable(R.drawable.photogif);
buttonStatesDrawables[1][1] = getResources().getDrawable(R.drawable.photocancel_pressed); buttonStatesDrawables[3] = getResources().getDrawable(R.drawable.playvideo);
buttonStatesDrawables[2][0] = getResources().getDrawable(R.drawable.photogif);
buttonStatesDrawables[2][1] = getResources().getDrawable(R.drawable.photogif_pressed);
buttonStatesDrawables[3][0] = getResources().getDrawable(R.drawable.playvideo);
buttonStatesDrawables[3][1] = getResources().getDrawable(R.drawable.playvideo_pressed);
videoIconDrawable = getResources().getDrawable(R.drawable.ic_video); videoIconDrawable = getResources().getDrawable(R.drawable.ic_video);
infoPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); infoPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
...@@ -102,8 +99,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -102,8 +99,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
photoImage = new ImageReceiver(); photoImage = new ImageReceiver();
photoImage.parentView = this; photoImage.parentView = this;
progressView = new ProgressView(); progressView = new RoundProgressView();
progressView.setProgressColors(0x802a2a2a, 0xffffffff);
} }
public void clearGifImage() { public void clearGifImage() {
...@@ -225,6 +221,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -225,6 +221,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
private void didPressedButton() { private void didPressedButton() {
if (buttonState == 0) { if (buttonState == 0) {
cancelLoading = false;
if (currentMessageObject.type == 1) { if (currentMessageObject.type == 1) {
if (currentMessageObject.imagePreview != null) { if (currentMessageObject.imagePreview != null) {
photoImage.setImage(currentPhotoObject.photoOwner.location, currentPhotoFilter, new BitmapDrawable(currentMessageObject.imagePreview), currentPhotoObject.photoOwner.size); photoImage.setImage(currentPhotoObject.photoOwner.location, currentPhotoFilter, new BitmapDrawable(currentMessageObject.imagePreview), currentPhotoObject.photoOwner.size);
...@@ -246,6 +243,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -246,6 +243,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
delegate.didPressedCancelSendButton(this); delegate.didPressedCancelSendButton(this);
} }
} else { } else {
cancelLoading = true;
if (currentMessageObject.type == 1) { if (currentMessageObject.type == 1) {
FileLoader.getInstance().cancelLoadingForImageView(photoImage); FileLoader.getInstance().cancelLoadingForImageView(photoImage);
} else if (currentMessageObject.type == 8) { } else if (currentMessageObject.type == 8) {
...@@ -304,6 +302,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -304,6 +302,7 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
public void setMessageObject(MessageObject messageObject) { public void setMessageObject(MessageObject messageObject) {
if (currentMessageObject != messageObject || isPhotoDataChanged(messageObject) || isUserDataChanged()) { if (currentMessageObject != messageObject || isPhotoDataChanged(messageObject) || isUserDataChanged()) {
super.setMessageObject(messageObject); super.setMessageObject(messageObject);
cancelLoading = false;
progressVisible = false; progressVisible = false;
buttonState = -1; buttonState = -1;
...@@ -395,6 +394,9 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -395,6 +394,9 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
photoHeight = h; photoHeight = h;
backgroundWidth = w + AndroidUtilities.dp(12); backgroundWidth = w + AndroidUtilities.dp(12);
currentPhotoFilter = String.format(Locale.US, "%d_%d", (int) (w / AndroidUtilities.density), (int) (h / AndroidUtilities.density)); currentPhotoFilter = String.format(Locale.US, "%d_%d", (int) (w / AndroidUtilities.density), (int) (h / AndroidUtilities.density));
if (messageObject.photoThumbs.size() > 1 || messageObject.type == 3 || messageObject.type == 8) {
currentPhotoFilter += "_b";
}
if (currentPhotoObject.image != null) { if (currentPhotoObject.image != null) {
photoImage.setImageBitmap(currentPhotoObject.image); photoImage.setImageBitmap(currentPhotoObject.image);
...@@ -485,20 +487,16 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -485,20 +487,16 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
if (!cacheFile.exists()) { if (!cacheFile.exists()) {
MediaController.getInstance().addLoadingFileObserver(fileName, this); MediaController.getInstance().addLoadingFileObserver(fileName, this);
if (!FileLoader.getInstance().isLoadingFile(fileName)) { if (!FileLoader.getInstance().isLoadingFile(fileName)) {
if (currentMessageObject.type != 1 || downloadPhotos == 1 || downloadPhotos == 2 && !ConnectionsManager.isConnectedToWiFi()) { if (cancelLoading || currentMessageObject.type != 1 || downloadPhotos == 1 || downloadPhotos == 2 && !ConnectionsManager.isConnectedToWiFi()) {
buttonState = 0; buttonState = 0;
progressVisible = false; progressVisible = false;
} else { } else {
buttonState = -1; buttonState = 1;
progressVisible = true; progressVisible = true;
} }
progressView.setProgress(0); progressView.setProgress(0);
} else { } else {
if (currentMessageObject.type != 1 || downloadPhotos == 1 || downloadPhotos == 2 && !ConnectionsManager.isConnectedToWiFi()) {
buttonState = 1; buttonState = 1;
} else {
buttonState = -1;
}
progressVisible = true; progressVisible = true;
Float progress = FileLoader.getInstance().fileProgresses.get(fileName); Float progress = FileLoader.getInstance().fileProgresses.get(fileName);
if (progress != null) { if (progress != null) {
...@@ -544,13 +542,10 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -544,13 +542,10 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
photoImage.imageW = photoWidth; photoImage.imageW = photoWidth;
photoImage.imageH = photoHeight; photoImage.imageH = photoHeight;
progressView.width = timeX - photoImage.imageX - AndroidUtilities.dpf(23.0f);
progressView.height = AndroidUtilities.dp(3);
progressView.progressHeight = AndroidUtilities.dp(3);
int size = AndroidUtilities.dp(44); int size = AndroidUtilities.dp(44);
buttonX = (int)(photoImage.imageX + (photoWidth - size) / 2.0f); buttonX = (int)(photoImage.imageX + (photoWidth - size) / 2.0f);
buttonY = (int)(photoImage.imageY + (photoHeight - size) / 2.0f); buttonY = (int)(photoImage.imageY + (photoHeight - size) / 2.0f);
progressView.rect.set(buttonX + AndroidUtilities.dp(2), buttonY + AndroidUtilities.dp(2), buttonX + AndroidUtilities.dp(42), buttonY + AndroidUtilities.dp(42));
} }
@Override @Override
...@@ -566,22 +561,16 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD ...@@ -566,22 +561,16 @@ public class ChatMediaCell extends ChatBaseCell implements MediaController.FileD
drawTime = photoImage.getVisible(); drawTime = photoImage.getVisible();
} }
if (progressVisible) {
setDrawableBounds(mediaBackgroundDrawable, photoImage.imageX + AndroidUtilities.dp(4), layoutHeight - AndroidUtilities.dpf(27.5f), progressView.width + AndroidUtilities.dp(12), AndroidUtilities.dpf(16.5f));
mediaBackgroundDrawable.draw(canvas);
canvas.save();
canvas.translate(photoImage.imageX + AndroidUtilities.dp(10), layoutHeight - AndroidUtilities.dpf(21.0f));
progressView.draw(canvas);
canvas.restore();
}
if (buttonState >= 0 && buttonState < 4) { if (buttonState >= 0 && buttonState < 4) {
Drawable currentButtonDrawable = buttonStatesDrawables[buttonState][buttonPressed]; Drawable currentButtonDrawable = buttonStatesDrawables[buttonState];
setDrawableBounds(currentButtonDrawable, buttonX, buttonY); setDrawableBounds(currentButtonDrawable, buttonX, buttonY);
currentButtonDrawable.draw(canvas); currentButtonDrawable.draw(canvas);
} }
if (progressVisible) {
progressView.draw(canvas);
}
if (infoLayout != null && (buttonState == 1 || buttonState == 0 || buttonState == 3)) { if (infoLayout != null && (buttonState == 1 || buttonState == 0 || buttonState == 3)) {
setDrawableBounds(mediaBackgroundDrawable, photoImage.imageX + AndroidUtilities.dp(4), photoImage.imageY + AndroidUtilities.dp(4), infoWidth + AndroidUtilities.dp(8) + infoOffset, AndroidUtilities.dpf(16.5f)); setDrawableBounds(mediaBackgroundDrawable, photoImage.imageX + AndroidUtilities.dp(4), photoImage.imageY + AndroidUtilities.dp(4), infoWidth + AndroidUtilities.dp(8) + infoOffset, AndroidUtilities.dpf(16.5f));
mediaBackgroundDrawable.draw(canvas); mediaBackgroundDrawable.draw(canvas);
......
...@@ -35,6 +35,8 @@ public class ChatOrUserCell extends BaseCell { ...@@ -35,6 +35,8 @@ public class ChatOrUserCell extends BaseCell {
private static TextPaint offlinePaint; private static TextPaint offlinePaint;
private static Drawable lockDrawable; private static Drawable lockDrawable;
private static Drawable broadcastDrawable;
private static Drawable groupDrawable;
private static Paint linePaint; private static Paint linePaint;
private CharSequence currentName; private CharSequence currentName;
...@@ -93,6 +95,14 @@ public class ChatOrUserCell extends BaseCell { ...@@ -93,6 +95,14 @@ public class ChatOrUserCell extends BaseCell {
linePaint.setColor(0xffdcdcdc); linePaint.setColor(0xffdcdcdc);
} }
if (broadcastDrawable == null) {
broadcastDrawable = getResources().getDrawable(R.drawable.broadcast);
}
if (groupDrawable == null) {
groupDrawable = getResources().getDrawable(R.drawable.grouplist);
}
if (avatarImage == null) { if (avatarImage == null) {
avatarImage = new ImageReceiver(); avatarImage = new ImageReceiver();
avatarImage.parentView = this; avatarImage.parentView = this;
...@@ -230,6 +240,12 @@ public class ChatOrUserCell extends BaseCell { ...@@ -230,6 +240,12 @@ public class ChatOrUserCell extends BaseCell {
if (cellLayout.drawNameLock) { if (cellLayout.drawNameLock) {
setDrawableBounds(lockDrawable, cellLayout.nameLockLeft, cellLayout.nameLockTop); setDrawableBounds(lockDrawable, cellLayout.nameLockLeft, cellLayout.nameLockTop);
lockDrawable.draw(canvas); lockDrawable.draw(canvas);
} else if (cellLayout.drawNameGroup) {
setDrawableBounds(groupDrawable, cellLayout.nameLockLeft, cellLayout.nameLockTop);
groupDrawable.draw(canvas);
} else if (cellLayout.drawNameBroadcast) {
setDrawableBounds(broadcastDrawable, cellLayout.nameLockLeft, cellLayout.nameLockTop);
broadcastDrawable.draw(canvas);
} }
canvas.save(); canvas.save();
...@@ -262,8 +278,10 @@ public class ChatOrUserCell extends BaseCell { ...@@ -262,8 +278,10 @@ public class ChatOrUserCell extends BaseCell {
private int nameWidth; private int nameWidth;
private StaticLayout nameLayout; private StaticLayout nameLayout;
private boolean drawNameLock; private boolean drawNameLock;
private boolean drawNameBroadcast;
private boolean drawNameGroup;
private int nameLockLeft; private int nameLockLeft;
private int nameLockTop = AndroidUtilities.dp(15); private int nameLockTop;
private int onlineLeft; private int onlineLeft;
private int onlineTop = AndroidUtilities.dp(36); private int onlineTop = AndroidUtilities.dp(36);
...@@ -277,6 +295,10 @@ public class ChatOrUserCell extends BaseCell { ...@@ -277,6 +295,10 @@ public class ChatOrUserCell extends BaseCell {
CharSequence nameString = ""; CharSequence nameString = "";
TextPaint currentNamePaint; TextPaint currentNamePaint;
drawNameBroadcast = false;
drawNameLock = false;
drawNameGroup = false;
if (encryptedChat != null) { if (encryptedChat != null) {
drawNameLock = true; drawNameLock = true;
if (!LocaleController.isRTL) { if (!LocaleController.isRTL) {
...@@ -286,14 +308,30 @@ public class ChatOrUserCell extends BaseCell { ...@@ -286,14 +308,30 @@ public class ChatOrUserCell extends BaseCell {
nameLockLeft = width - AndroidUtilities.dp(63 + (usePadding ? 11 : 0)) - lockDrawable.getIntrinsicWidth(); nameLockLeft = width - AndroidUtilities.dp(63 + (usePadding ? 11 : 0)) - lockDrawable.getIntrinsicWidth();
nameLeft = usePadding ? AndroidUtilities.dp(11) : 0; nameLeft = usePadding ? AndroidUtilities.dp(11) : 0;
} }
nameLockTop = AndroidUtilities.dp(15);
} else {
if (chat != null) {
nameLockTop = AndroidUtilities.dp(26);
if (chat.id < 0) {
drawNameBroadcast = true;
} else {
drawNameGroup = true;
}
if (!LocaleController.isRTL) {
nameLockLeft = AndroidUtilities.dp(61 + (usePadding ? 11 : 0));
nameLeft = AndroidUtilities.dp(65 + (usePadding ? 11 : 0)) + (drawNameGroup ? groupDrawable.getIntrinsicWidth() : broadcastDrawable.getIntrinsicWidth());
} else {
nameLockLeft = width - AndroidUtilities.dp(63 + (usePadding ? 11 : 0)) - (drawNameGroup ? groupDrawable.getIntrinsicWidth() : broadcastDrawable.getIntrinsicWidth());
nameLeft = usePadding ? AndroidUtilities.dp(11) : 0;
}
} else { } else {
drawNameLock = false;
if (!LocaleController.isRTL) { if (!LocaleController.isRTL) {
nameLeft = AndroidUtilities.dp(61 + (usePadding ? 11 : 0)); nameLeft = AndroidUtilities.dp(61 + (usePadding ? 11 : 0));
} else { } else {
nameLeft = usePadding ? AndroidUtilities.dp(11) : 0; nameLeft = usePadding ? AndroidUtilities.dp(11) : 0;
} }
} }
}
if (currentName != null) { if (currentName != null) {
nameString = currentName; nameString = currentName;
...@@ -326,6 +364,8 @@ public class ChatOrUserCell extends BaseCell { ...@@ -326,6 +364,8 @@ public class ChatOrUserCell extends BaseCell {
} }
if (drawNameLock) { if (drawNameLock) {
nameWidth -= AndroidUtilities.dp(6) + lockDrawable.getIntrinsicWidth(); nameWidth -= AndroidUtilities.dp(6) + lockDrawable.getIntrinsicWidth();
} else if (drawNameBroadcast) {
nameWidth -= AndroidUtilities.dp(6) + broadcastDrawable.getIntrinsicWidth();
} }
CharSequence nameStringFinal = TextUtils.ellipsize(nameString, currentNamePaint, nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END); CharSequence nameStringFinal = TextUtils.ellipsize(nameString, currentNamePaint, nameWidth - AndroidUtilities.dp(12), TextUtils.TruncateAt.END);
......
...@@ -46,6 +46,7 @@ public class DialogCell extends BaseCell { ...@@ -46,6 +46,7 @@ public class DialogCell extends BaseCell {
private static Drawable lockDrawable; private static Drawable lockDrawable;
private static Drawable countDrawable; private static Drawable countDrawable;
private static Drawable groupDrawable; private static Drawable groupDrawable;
private static Drawable broadcastDrawable;
private TLRPC.TL_dialog currentDialog; private TLRPC.TL_dialog currentDialog;
private ImageReceiver avatarImage; private ImageReceiver avatarImage;
...@@ -130,6 +131,10 @@ public class DialogCell extends BaseCell { ...@@ -130,6 +131,10 @@ public class DialogCell extends BaseCell {
groupDrawable = getResources().getDrawable(R.drawable.grouplist); groupDrawable = getResources().getDrawable(R.drawable.grouplist);
} }
if (broadcastDrawable == null) {
broadcastDrawable = getResources().getDrawable(R.drawable.broadcast);
}
if (avatarImage == null) { if (avatarImage == null) {
avatarImage = new ImageReceiver(); avatarImage = new ImageReceiver();
avatarImage.parentView = this; avatarImage.parentView = this;
...@@ -220,14 +225,19 @@ public class DialogCell extends BaseCell { ...@@ -220,14 +225,19 @@ public class DialogCell extends BaseCell {
encryptedChat = null; encryptedChat = null;
int lower_id = (int)currentDialog.id; int lower_id = (int)currentDialog.id;
int high_id = (int)(currentDialog.id >> 32);
if (lower_id != 0) { if (lower_id != 0) {
if (high_id == 1) {
chat = MessagesController.getInstance().chats.get(lower_id);
} else {
if (lower_id < 0) { if (lower_id < 0) {
chat = MessagesController.getInstance().chats.get(-lower_id); chat = MessagesController.getInstance().chats.get(-lower_id);
} else { } else {
user = MessagesController.getInstance().users.get(lower_id); user = MessagesController.getInstance().users.get(lower_id);
} }
}
} else { } else {
encryptedChat = MessagesController.getInstance().encryptedChats.get((int)(currentDialog.id >> 32)); encryptedChat = MessagesController.getInstance().encryptedChats.get(high_id);
if (encryptedChat != null) { if (encryptedChat != null) {
user = MessagesController.getInstance().users.get(encryptedChat.user_id); user = MessagesController.getInstance().users.get(encryptedChat.user_id);
} }
...@@ -274,6 +284,9 @@ public class DialogCell extends BaseCell { ...@@ -274,6 +284,9 @@ public class DialogCell extends BaseCell {
} else if (cellLayout.drawNameGroup) { } else if (cellLayout.drawNameGroup) {
setDrawableBounds(groupDrawable, cellLayout.nameLockLeft, cellLayout.nameLockTop); setDrawableBounds(groupDrawable, cellLayout.nameLockLeft, cellLayout.nameLockTop);
groupDrawable.draw(canvas); groupDrawable.draw(canvas);
} else if (cellLayout.drawNameBroadcast) {
setDrawableBounds(broadcastDrawable, cellLayout.nameLockLeft, cellLayout.nameLockTop);
broadcastDrawable.draw(canvas);
} }
canvas.save(); canvas.save();
...@@ -328,6 +341,7 @@ public class DialogCell extends BaseCell { ...@@ -328,6 +341,7 @@ public class DialogCell extends BaseCell {
private StaticLayout nameLayout; private StaticLayout nameLayout;
private boolean drawNameLock; private boolean drawNameLock;
private boolean drawNameGroup; private boolean drawNameGroup;
private boolean drawNameBroadcast;
private int nameLockLeft; private int nameLockLeft;
private int nameLockTop; private int nameLockTop;
...@@ -372,9 +386,12 @@ public class DialogCell extends BaseCell { ...@@ -372,9 +386,12 @@ public class DialogCell extends BaseCell {
TextPaint currentMessagePaint = messagePaint; TextPaint currentMessagePaint = messagePaint;
boolean checkMessage = true; boolean checkMessage = true;
drawNameGroup = false;
drawNameBroadcast = false;
drawNameLock = false;
if (encryptedChat != null) { if (encryptedChat != null) {
drawNameLock = true; drawNameLock = true;
drawNameGroup = false;
nameLockTop = AndroidUtilities.dp(13); nameLockTop = AndroidUtilities.dp(13);
if (!LocaleController.isRTL) { if (!LocaleController.isRTL) {
nameLockLeft = AndroidUtilities.dp(77); nameLockLeft = AndroidUtilities.dp(77);
...@@ -384,19 +401,21 @@ public class DialogCell extends BaseCell { ...@@ -384,19 +401,21 @@ public class DialogCell extends BaseCell {
nameLeft = AndroidUtilities.dp(14); nameLeft = AndroidUtilities.dp(14);
} }
} else { } else {
drawNameLock = false;
if (chat != null) { if (chat != null) {
if (chat.id < 0) {
drawNameBroadcast = true;
} else {
drawNameGroup = true; drawNameGroup = true;
}
nameLockTop = AndroidUtilities.dp(14); nameLockTop = AndroidUtilities.dp(14);
if (!LocaleController.isRTL) { if (!LocaleController.isRTL) {
nameLockLeft = AndroidUtilities.dp(77); nameLockLeft = AndroidUtilities.dp(77);
nameLeft = AndroidUtilities.dp(81) + groupDrawable.getIntrinsicWidth(); nameLeft = AndroidUtilities.dp(81) + (drawNameGroup ? groupDrawable.getIntrinsicWidth() : broadcastDrawable.getIntrinsicWidth());
} else { } else {
nameLockLeft = width - AndroidUtilities.dp(77) - groupDrawable.getIntrinsicWidth(); nameLockLeft = width - AndroidUtilities.dp(77) - (drawNameGroup ? groupDrawable.getIntrinsicWidth() : broadcastDrawable.getIntrinsicWidth());
nameLeft = AndroidUtilities.dp(14); nameLeft = AndroidUtilities.dp(14);
} }
} else { } else {
drawNameGroup = false;
if (!LocaleController.isRTL) { if (!LocaleController.isRTL) {
nameLeft = AndroidUtilities.dp(77); nameLeft = AndroidUtilities.dp(77);
} else { } else {
...@@ -461,7 +480,7 @@ public class DialogCell extends BaseCell { ...@@ -461,7 +480,7 @@ public class DialogCell extends BaseCell {
messageString = message.messageText; messageString = message.messageText;
currentMessagePaint = messagePrintingPaint; currentMessagePaint = messagePrintingPaint;
} else { } else {
if (chat != null) { if (chat != null && chat.id > 0) {
String name = ""; String name = "";
if (message.isFromMe()) { if (message.isFromMe()) {
name = LocaleController.getString("FromYou", R.string.FromYou); name = LocaleController.getString("FromYou", R.string.FromYou);
...@@ -505,7 +524,7 @@ public class DialogCell extends BaseCell { ...@@ -505,7 +524,7 @@ public class DialogCell extends BaseCell {
} }
} }
if (message.isFromMe()) { if (message.isFromMe() && message.isOut()) {
if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) { if (message.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SENDING) {
drawCheck1 = false; drawCheck1 = false;
drawCheck2 = false; drawCheck2 = false;
...@@ -579,6 +598,8 @@ public class DialogCell extends BaseCell { ...@@ -579,6 +598,8 @@ public class DialogCell extends BaseCell {
nameWidth -= AndroidUtilities.dp(4) + lockDrawable.getIntrinsicWidth(); nameWidth -= AndroidUtilities.dp(4) + lockDrawable.getIntrinsicWidth();
} else if (drawNameGroup) { } else if (drawNameGroup) {
nameWidth -= AndroidUtilities.dp(4) + groupDrawable.getIntrinsicWidth(); nameWidth -= AndroidUtilities.dp(4) + groupDrawable.getIntrinsicWidth();
} else if (drawNameBroadcast) {
nameWidth -= AndroidUtilities.dp(4) + broadcastDrawable.getIntrinsicWidth();
} }
if (drawClock) { if (drawClock) {
int w = clockDrawable.getIntrinsicWidth() + AndroidUtilities.dp(2); int w = clockDrawable.getIntrinsicWidth() + AndroidUtilities.dp(2);
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
package org.telegram.ui; package org.telegram.ui;
import android.animation.Animator;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
...@@ -129,6 +130,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -129,6 +130,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private View pagedownButton; private View pagedownButton;
private TextView topPanelText; private TextView topPanelText;
private long dialog_id; private long dialog_id;
private boolean isBraodcast = false;
private HashMap<Integer, MessageObject> selectedMessagesIds = new HashMap<Integer, MessageObject>(); private HashMap<Integer, MessageObject> selectedMessagesIds = new HashMap<Integer, MessageObject>();
private HashMap<Integer, MessageObject> selectedMessagesCanCopyIds = new HashMap<Integer, MessageObject>(); private HashMap<Integer, MessageObject> selectedMessagesCanCopyIds = new HashMap<Integer, MessageObject>();
...@@ -141,10 +143,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -141,10 +143,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private boolean endReached = false; private boolean endReached = false;
private boolean loading = false; private boolean loading = false;
private boolean cacheEndReaced = false; private boolean cacheEndReaced = false;
private boolean firstLoading = true;
private int minDate = 0; private int minDate = 0;
private int progressTag = 0; private int progressTag = 0;
boolean first = true; private boolean first = true;
private int unread_to_load = 0; private int unread_to_load = 0;
private int first_unread_id = 0; private int first_unread_id = 0;
private int last_unread_id = 0; private int last_unread_id = 0;
...@@ -211,8 +214,24 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -211,8 +214,24 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
return false; return false;
} }
} }
MessagesController.getInstance().loadChatInfo(currentChat.id); if (chatId > 0) {
dialog_id = -chatId; dialog_id = -chatId;
} else {
isBraodcast = true;
dialog_id = AndroidUtilities.makeBroadcastId(chatId);
}
Semaphore semaphore = null;
if (isBraodcast) {
semaphore = new Semaphore(0);
}
MessagesController.getInstance().loadChatInfo(currentChat.id, semaphore);
if (isBraodcast) {
try {
semaphore.acquire();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
} else if (userId != 0) { } else if (userId != 0) {
currentUser = MessagesController.getInstance().users.get(userId); currentUser = MessagesController.getInstance().users.get(userId);
if (currentUser == null) { if (currentUser == null) {
...@@ -331,7 +350,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -331,7 +350,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
super.onFragmentCreate(); super.onFragmentCreate();
loading = true; loading = true;
MessagesController.getInstance().loadMessages(dialog_id, 0, 30, 0, true, 0, classGuid, true, false); MessagesController.getInstance().loadMessages(dialog_id, 30, 0, true, 0, classGuid, true, false);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (currentChat != null) { if (currentChat != null) {
...@@ -456,7 +475,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -456,7 +475,11 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (info != null && info instanceof TLRPC.TL_chatParticipantsForbidden) { if (info != null && info instanceof TLRPC.TL_chatParticipantsForbidden) {
return; return;
} }
if (currentChat.participants_count == 0 || currentChat.left || currentChat instanceof TLRPC.TL_chatForbidden) { int count = currentChat.participants_count;
if (info != null) {
count = info.participants.size();
}
if (count == 0 || currentChat.left || currentChat instanceof TLRPC.TL_chatForbidden) {
return; return;
} }
Bundle args = new Bundle(); Bundle args = new Bundle();
...@@ -528,6 +551,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -528,6 +551,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (currentEncryptedChat != null) { if (currentEncryptedChat != null) {
actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, AndroidUtilities.dp(4)); actionBarLayer.setTitleIcon(R.drawable.ic_lock_white, AndroidUtilities.dp(4));
} else if (currentChat != null && currentChat.id < 0) {
actionBarLayer.setTitleIcon(R.drawable.broadcast2, AndroidUtilities.dp(4));
} }
ActionBarMenu menu = actionBarLayer.createMenu(); ActionBarMenu menu = actionBarLayer.createMenu();
...@@ -609,6 +634,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -609,6 +634,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
View bottomOverlayChat = fragmentView.findViewById(R.id.bottom_overlay_chat); View bottomOverlayChat = fragmentView.findViewById(R.id.bottom_overlay_chat);
progressView = fragmentView.findViewById(R.id.progressLayout); progressView = fragmentView.findViewById(R.id.progressLayout);
pagedownButton = fragmentView.findViewById(R.id.pagedown_button); pagedownButton = fragmentView.findViewById(R.id.pagedown_button);
pagedownButton.setVisibility(View.GONE);
View progressViewInner = progressView.findViewById(R.id.progressLayoutInner); View progressViewInner = progressView.findViewById(R.id.progressLayoutInner);
...@@ -719,24 +745,22 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -719,24 +745,22 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (firstVisibleItem <= 4) { if (firstVisibleItem <= 4) {
if (!endReached && !loading) { if (!endReached && !loading) {
if (messagesByDays.size() != 0) { if (messagesByDays.size() != 0) {
MessagesController.getInstance().loadMessages(dialog_id, 0, 20, maxMessageId, !cacheEndReaced, minDate, classGuid, false, false); MessagesController.getInstance().loadMessages(dialog_id, 20, maxMessageId, !cacheEndReaced, minDate, classGuid, false, false);
} else { } else {
MessagesController.getInstance().loadMessages(dialog_id, 0, 20, 0, !cacheEndReaced, minDate, classGuid, false, false); MessagesController.getInstance().loadMessages(dialog_id, 20, 0, !cacheEndReaced, minDate, classGuid, false, false);
} }
loading = true; loading = true;
} }
} }
if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) { if (firstVisibleItem + visibleItemCount >= totalItemCount - 6) {
if (!unread_end_reached && !loadingForward) { if (!unread_end_reached && !loadingForward) {
MessagesController.getInstance().loadMessages(dialog_id, 0, 20, minMessageId, true, maxDate, classGuid, false, true); MessagesController.getInstance().loadMessages(dialog_id, 20, minMessageId, true, maxDate, classGuid, false, true);
loadingForward = true; loadingForward = true;
} }
} }
if (firstVisibleItem + visibleItemCount == totalItemCount && unread_end_reached) { if (firstVisibleItem + visibleItemCount == totalItemCount && unread_end_reached) {
showPagedownButton(false, true); showPagedownButton(false, true);
} }
} else {
showPagedownButton(false, false);
} }
for (int a = 0; a < visibleItemCount; a++) { for (int a = 0; a < visibleItemCount; a++) {
View view = absListView.getChildAt(a); View view = absListView.getChildAt(a);
...@@ -853,9 +877,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -853,9 +877,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
maxDate = Integer.MIN_VALUE; maxDate = Integer.MIN_VALUE;
minDate = 0; minDate = 0;
unread_end_reached = true; unread_end_reached = true;
MessagesController.getInstance().loadMessages(dialog_id, 0, 30, 0, true, 0, classGuid, true, false);
loading = true; loading = true;
chatAdapter.notifyDataSetChanged(); chatAdapter.notifyDataSetChanged();
MessagesController.getInstance().loadMessages(dialog_id, 30, 0, true, 0, classGuid, true, false);
} }
} }
...@@ -865,7 +889,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -865,7 +889,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
if (show) { if (show) {
if (pagedownButton.getVisibility() == View.GONE) { if (pagedownButton.getVisibility() == View.GONE) {
if (android.os.Build.VERSION.SDK_INT >= 16 && animated) { if (android.os.Build.VERSION.SDK_INT > 13 && animated) {
pagedownButton.setVisibility(View.VISIBLE); pagedownButton.setVisibility(View.VISIBLE);
pagedownButton.setAlpha(0); pagedownButton.setAlpha(0);
pagedownButton.animate().alpha(1).setDuration(200).start(); pagedownButton.animate().alpha(1).setDuration(200).start();
...@@ -875,13 +899,28 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -875,13 +899,28 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
} else { } else {
if (pagedownButton.getVisibility() == View.VISIBLE) { if (pagedownButton.getVisibility() == View.VISIBLE) {
if (android.os.Build.VERSION.SDK_INT >= 16 && animated) { if (android.os.Build.VERSION.SDK_INT > 13 && animated) {
pagedownButton.animate().alpha(0).withEndAction(new Runnable() { pagedownButton.animate().alpha(0).setDuration(200).setListener(new Animator.AnimatorListener() {
@Override @Override
public void run() { public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
pagedownButton.setVisibility(View.GONE); pagedownButton.setVisibility(View.GONE);
} }
}).setDuration(200).start();
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}).start();
} else { } else {
pagedownButton.setVisibility(View.GONE); pagedownButton.setVisibility(View.GONE);
} }
...@@ -1045,7 +1084,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -1045,7 +1084,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private int getMessageType(MessageObject messageObject) { private int getMessageType(MessageObject messageObject) {
if (currentEncryptedChat == null) { if (currentEncryptedChat == null) {
if (messageObject.messageOwner.id <= 0 && messageObject.isOut()) { boolean isBroadcastError = isBraodcast && messageObject.messageOwner.id <= 0 && messageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR;
if (!isBraodcast && messageObject.messageOwner.id <= 0 && messageObject.isOut() || isBroadcastError) {
if (messageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) { if (messageObject.messageOwner.send_state == MessagesController.MESSAGE_SEND_STATE_SEND_ERROR) {
if (!(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) { if (!(messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaEmpty)) {
return 0; return 0;
...@@ -1224,10 +1264,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -1224,10 +1264,14 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} else if (currentChat.left) { } else if (currentChat.left) {
actionBarLayer.setSubtitle(LocaleController.getString("YouLeft", R.string.YouLeft)); actionBarLayer.setSubtitle(LocaleController.getString("YouLeft", R.string.YouLeft));
} else { } else {
if (onlineCount > 0 && currentChat.participants_count != 0) { int count = currentChat.participants_count;
actionBarLayer.setSubtitle(String.format("%s, %d %s", LocaleController.formatPluralString("Members", currentChat.participants_count), onlineCount, LocaleController.getString("Online", R.string.Online))); if (info != null) {
count = info.participants.size();
}
if (onlineCount > 0 && count != 0) {
actionBarLayer.setSubtitle(String.format("%s, %d %s", LocaleController.formatPluralString("Members", count), onlineCount, LocaleController.getString("Online", R.string.Online)));
} else { } else {
actionBarLayer.setSubtitle(LocaleController.formatPluralString("Members", currentChat.participants_count)); actionBarLayer.setSubtitle(LocaleController.formatPluralString("Members", count));
} }
} }
} else if (currentUser != null) { } else if (currentUser != null) {
...@@ -1447,6 +1491,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -1447,6 +1491,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (tempPath != null) { if (tempPath != null) {
File temp = new File(tempPath); File temp = new File(tempPath);
originalPath += temp.length() + "_" + temp.lastModified(); originalPath += temp.length() + "_" + temp.lastModified();
} else {
originalPath = null;
} }
TLRPC.TL_photo photo = (TLRPC.TL_photo)MessagesStorage.getInstance().getSentFile(originalPath, currentEncryptedChat == null ? 0 : 3); TLRPC.TL_photo photo = (TLRPC.TL_photo)MessagesStorage.getInstance().getSentFile(originalPath, currentEncryptedChat == null ? 0 : 3);
if (photo == null && uri != null) { if (photo == null && uri != null) {
...@@ -1664,24 +1710,42 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -1664,24 +1710,42 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (id == MessagesController.messagesDidLoaded) { if (id == MessagesController.messagesDidLoaded) {
long did = (Long)args[0]; long did = (Long)args[0];
if (did == dialog_id) { if (did == dialog_id) {
int offset = (Integer)args[1]; int count = (Integer)args[1];
int count = (Integer)args[2]; boolean isCache = (Boolean)args[3];
boolean isCache = (Boolean)args[4]; int fnid = (Integer)args[4];
int fnid = (Integer)args[5]; int last_unread_date = (Integer)args[7];
int last_unread_date = (Integer)args[8]; boolean forwardLoad = (Boolean)args[8];
boolean forwardLoad = (Boolean)args[9];
boolean wasUnread = false; boolean wasUnread = false;
boolean positionToUnread = false; boolean positionToUnread = false;
if (fnid != 0) { if (fnid != 0) {
first_unread_id = (Integer)args[5]; first_unread_id = fnid;
last_unread_id = (Integer)args[6]; last_unread_id = (Integer)args[5];
unread_to_load = (Integer)args[7]; unread_to_load = (Integer)args[6];
positionToUnread = true; positionToUnread = true;
} }
ArrayList<MessageObject> messArr = (ArrayList<MessageObject>)args[3]; ArrayList<MessageObject> messArr = (ArrayList<MessageObject>)args[2];
int newRowsCount = 0; int newRowsCount = 0;
unread_end_reached = last_unread_id == 0; unread_end_reached = last_unread_id == 0;
if (firstLoading) {
if (!unread_end_reached) {
messages.clear();
messagesByDays.clear();
messagesDict.clear();
if (currentEncryptedChat == null) {
maxMessageId = Integer.MAX_VALUE;
minMessageId = Integer.MIN_VALUE;
} else {
maxMessageId = Integer.MIN_VALUE;
minMessageId = Integer.MAX_VALUE;
}
maxDate = Integer.MIN_VALUE;
minDate = 0;
}
firstLoading = false;
}
for (int a = 0; a < messArr.size(); a++) { for (int a = 0; a < messArr.size(); a++) {
MessageObject obj = messArr.get(a); MessageObject obj = messArr.get(a);
if (messagesDict.containsKey(obj.messageOwner.id)) { if (messagesDict.containsKey(obj.messageOwner.id)) {
...@@ -1771,7 +1835,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -1771,7 +1835,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (messArr.size() != count) { if (messArr.size() != count) {
if (isCache) { if (isCache) {
cacheEndReaced = true; cacheEndReaced = true;
if (currentEncryptedChat != null) { if (currentEncryptedChat != null || isBraodcast) {
endReached = true; endReached = true;
} }
} else { } else {
...@@ -1849,9 +1913,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -1849,9 +1913,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
if (first && messages.size() > 0) { if (first && messages.size() > 0) {
if (last_unread_id != 0) { if (last_unread_id != 0) {
MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, last_unread_id, 0, last_unread_date, wasUnread); MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, last_unread_id, 0, last_unread_date, wasUnread, false);
} else { } else {
MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, minMessageId, 0, maxDate, wasUnread); MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, minMessageId, 0, maxDate, wasUnread, false);
} }
first = false; first = false;
} }
...@@ -1932,7 +1996,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -1932,7 +1996,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
readWithMid = currentMinMsgId; readWithMid = currentMinMsgId;
} else { } else {
if (messages.size() > 0) { if (messages.size() > 0) {
MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, currentMinMsgId, 0, currentMaxDate, true); MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, currentMinMsgId, 0, currentMaxDate, true, false);
} }
} }
} }
...@@ -2010,6 +2074,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -2010,6 +2074,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
lastVisible++; lastVisible++;
} }
if (lastVisible == oldCount) { if (lastVisible == oldCount) {
if (!firstLoading) {
if (paused) { if (paused) {
scrollToTopOnResume = true; scrollToTopOnResume = true;
} else { } else {
...@@ -2020,6 +2085,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -2020,6 +2085,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
}); });
} }
}
} else { } else {
showPagedownButton(true, true); showPagedownButton(true, true);
} }
...@@ -2033,7 +2099,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -2033,7 +2099,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
readWithDate = maxDate; readWithDate = maxDate;
readWithMid = minMessageId; readWithMid = minMessageId;
} else { } else {
MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, minMessageId, 0, maxDate, true); MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, minMessageId, 0, maxDate, true, false);
} }
} }
} }
...@@ -2090,7 +2156,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -2090,7 +2156,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
} }
maxDate = Integer.MIN_VALUE; maxDate = Integer.MIN_VALUE;
minDate = 0; minDate = 0;
MessagesController.getInstance().loadMessages(dialog_id, 0, 30, 0, !cacheEndReaced, minDate, classGuid, false, false); MessagesController.getInstance().loadMessages(dialog_id, 30, 0, !cacheEndReaced, minDate, classGuid, false, false);
loading = true; loading = true;
} }
} }
...@@ -2106,6 +2172,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -2106,6 +2172,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
MessageObject newMsgObj = (MessageObject)args[2]; MessageObject newMsgObj = (MessageObject)args[2];
if (newMsgObj != null) { if (newMsgObj != null) {
obj.messageOwner.media = newMsgObj.messageOwner.media; obj.messageOwner.media = newMsgObj.messageOwner.media;
obj.generateThumbs(true, 1);
} }
messagesDict.remove(msgId); messagesDict.remove(msgId);
messagesDict.put(newMsgId, obj); messagesDict.put(newMsgId, obj);
...@@ -2388,7 +2455,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -2388,7 +2455,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
messageObject.messageOwner.unread = false; messageObject.messageOwner.unread = false;
} }
readWhenResume = false; readWhenResume = false;
MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, readWithMid, 0, readWithDate, true); MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).messageOwner.id, readWithMid, 0, readWithDate, true, false);
} }
fixLayout(true); fixLayout(true);
...@@ -2897,26 +2964,26 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -2897,26 +2964,26 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
private void forwardSelectedMessages(long did, boolean fromMyName) { private void forwardSelectedMessages(long did, boolean fromMyName) {
if (forwaringMessage != null) { if (forwaringMessage != null) {
if (forwaringMessage.messageOwner.id > 0) {
if (!fromMyName) { if (!fromMyName) {
if (forwaringMessage.messageOwner.id > 0) {
MessagesController.getInstance().sendMessage(forwaringMessage, did); MessagesController.getInstance().sendMessage(forwaringMessage, did);
}
} else { } else {
processForwardFromMe(forwaringMessage, did); processForwardFromMe(forwaringMessage, did);
} }
}
forwaringMessage = null; forwaringMessage = null;
} else { } else {
ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesIds.keySet()); ArrayList<Integer> ids = new ArrayList<Integer>(selectedMessagesIds.keySet());
Collections.sort(ids); Collections.sort(ids);
for (Integer id : ids) { for (Integer id : ids) {
if (id > 0) {
if (!fromMyName) { if (!fromMyName) {
if (id > 0) {
MessagesController.getInstance().sendMessage(selectedMessagesIds.get(id), did); MessagesController.getInstance().sendMessage(selectedMessagesIds.get(id), did);
}
} else { } else {
processForwardFromMe(selectedMessagesIds.get(id), did); processForwardFromMe(selectedMessagesIds.get(id), did);
} }
} }
}
selectedMessagesCanCopyIds.clear(); selectedMessagesCanCopyIds.clear();
selectedMessagesIds.clear(); selectedMessagesIds.clear();
} }
...@@ -2925,7 +2992,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -2925,7 +2992,9 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
@Override @Override
public void didSelectDialog(MessagesActivity activity, long did, boolean param) { public void didSelectDialog(MessagesActivity activity, long did, boolean param) {
if (dialog_id != 0 && (forwaringMessage != null || !selectedMessagesIds.isEmpty())) { if (dialog_id != 0 && (forwaringMessage != null || !selectedMessagesIds.isEmpty())) {
if (isBraodcast) {
param = true;
}
if (did != dialog_id) { if (did != dialog_id) {
int lower_part = (int)did; int lower_part = (int)did;
if (lower_part != 0) { if (lower_part != 0) {
...@@ -2937,8 +3006,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not ...@@ -2937,8 +3006,8 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not
args.putInt("chat_id", -lower_part); args.putInt("chat_id", -lower_part);
} }
presentFragment(new ChatActivity(args), true); presentFragment(new ChatActivity(args), true);
removeSelfFromStack();
forwardSelectedMessages(did, param); forwardSelectedMessages(did, param);
removeSelfFromStack();
} else { } else {
activity.finishFragment(); activity.finishFragment();
} }
......
...@@ -112,7 +112,9 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -112,7 +112,9 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats); NotificationCenter.getInstance().addObserver(this, MessagesController.closeChats);
updateOnlineCount(); updateOnlineCount();
if (chat_id > 0) {
MessagesController.getInstance().getMediaCount(-chat_id, classGuid, true); MessagesController.getInstance().getMediaCount(-chat_id, classGuid, true);
}
avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() { avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() {
@Override @Override
public void didUploadedPhoto(TLRPC.InputFile file, TLRPC.PhotoSize small, TLRPC.PhotoSize big) { public void didUploadedPhoto(TLRPC.InputFile file, TLRPC.PhotoSize small, TLRPC.PhotoSize big) {
...@@ -131,15 +133,18 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -131,15 +133,18 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
private void updateRowsIds() { private void updateRowsIds() {
rowCount = 0; rowCount = 0;
avatarRow = rowCount++; avatarRow = rowCount++;
if (chat_id > 0) {
settingsSectionRow = rowCount++; settingsSectionRow = rowCount++;
settingsNotificationsRow = rowCount++; settingsNotificationsRow = rowCount++;
sharedMediaSectionRow = rowCount++; sharedMediaSectionRow = rowCount++;
sharedMediaRow = rowCount++; sharedMediaRow = rowCount++;
}
if (info != null && !(info instanceof TLRPC.TL_chatParticipantsForbidden)) { if (info != null && !(info instanceof TLRPC.TL_chatParticipantsForbidden)) {
membersSectionRow = rowCount++; membersSectionRow = rowCount++;
rowCount += info.participants.size(); rowCount += info.participants.size();
membersEndRow = rowCount; membersEndRow = rowCount;
if (info.participants.size() < 200) { int maxCount = chat_id > 0 ? MessagesController.getInstance().maxGroupCount : MessagesController.getInstance().maxBroadcastCount;
if (info.participants.size() < maxCount) {
addMemberRow = rowCount++; addMemberRow = rowCount++;
} else { } else {
addMemberRow = -1; addMemberRow = -1;
...@@ -149,8 +154,10 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -149,8 +154,10 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
addMemberRow = -1; addMemberRow = -1;
membersSectionRow = -1; membersSectionRow = -1;
} }
if (chat_id > 0) {
leaveGroupRow = rowCount++; leaveGroupRow = rowCount++;
} }
}
@Override @Override
public void onFragmentDestroy() { public void onFragmentDestroy() {
...@@ -166,7 +173,11 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -166,7 +173,11 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
if (fragmentView == null) { if (fragmentView == null) {
actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back); actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back);
actionBarLayer.setBackOverlay(R.layout.updating_state_layout); actionBarLayer.setBackOverlay(R.layout.updating_state_layout);
if (chat_id > 0) {
actionBarLayer.setTitle(LocaleController.getString("GroupInfo", R.string.GroupInfo)); actionBarLayer.setTitle(LocaleController.getString("GroupInfo", R.string.GroupInfo));
} else {
actionBarLayer.setTitle(LocaleController.getString("BroadcastList", R.string.BroadcastList));
}
actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() { actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
@Override @Override
public void onItemClick(int id) { public void onItemClick(int id) {
...@@ -181,7 +192,11 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -181,7 +192,11 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
View item = menu.addItemResource(done_button, R.layout.group_profile_add_member_layout); View item = menu.addItemResource(done_button, R.layout.group_profile_add_member_layout);
TextView textView = (TextView)item.findViewById(R.id.done_button); TextView textView = (TextView)item.findViewById(R.id.done_button);
if (textView != null) { if (textView != null) {
if (chat_id > 0) {
textView.setText(LocaleController.getString("AddMember", R.string.AddMember)); textView.setText(LocaleController.getString("AddMember", R.string.AddMember));
} else {
textView.setText(LocaleController.getString("AddRecipient", R.string.AddRecipient));
}
} }
fragmentView = inflater.inflate(R.layout.chat_profile_layout, container, false); fragmentView = inflater.inflate(R.layout.chat_profile_layout, container, false);
...@@ -206,7 +221,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -206,7 +221,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
selectedUser = user; selectedUser = user;
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
CharSequence[] items = new CharSequence[] {LocaleController.getString("KickFromGroup", R.string.KickFromGroup)}; CharSequence[] items = new CharSequence[] {chat_id > 0 ? LocaleController.getString("KickFromGroup", R.string.KickFromGroup) : LocaleController.getString("KickFromBroadcast", R.string.KickFromBroadcast)};
builder.setItems(items, new DialogInterface.OnClickListener() { builder.setItems(items, new DialogInterface.OnClickListener() {
@Override @Override
...@@ -259,7 +274,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -259,7 +274,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
@Override @Override
public void didSelectContact(TLRPC.User user, String param) { public void didSelectContact(TLRPC.User user, String param) {
MessagesController.getInstance().addUserToChat(chat_id, user, info, Utilities.parseInt(param)); MessagesController.getInstance().addUserToChat(chat_id, user, info, param != null ? Utilities.parseInt(param) : 0);
} }
@Override @Override
...@@ -276,7 +291,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -276,7 +291,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
@Override @Override
public void restoreSelfArgs(Bundle args) { public void restoreSelfArgs(Bundle args) {
MessagesController.getInstance().loadChatInfo(chat_id); MessagesController.getInstance().loadChatInfo(chat_id, null);
if (avatarUpdater != null) { if (avatarUpdater != null) {
avatarUpdater.currentPicturePath = args.getString("path"); avatarUpdater.currentPicturePath = args.getString("path");
} }
...@@ -461,7 +476,9 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -461,7 +476,9 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
args.putBoolean("destroyAfterSelect", true); args.putBoolean("destroyAfterSelect", true);
args.putBoolean("usersAsSections", true); args.putBoolean("usersAsSections", true);
args.putBoolean("returnAsResult", true); args.putBoolean("returnAsResult", true);
if (chat_id > 0) {
args.putString("selectAlertString", LocaleController.getString("AddToTheGroup", R.string.AddToTheGroup)); args.putString("selectAlertString", LocaleController.getString("AddToTheGroup", R.string.AddToTheGroup));
}
ContactsActivity fragment = new ContactsActivity(args); ContactsActivity fragment = new ContactsActivity(args);
fragment.setDelegate(this); fragment.setDelegate(this);
if (info != null) { if (info != null) {
...@@ -546,6 +563,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -546,6 +563,7 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
}); });
final ImageButton button2 = (ImageButton)view.findViewById(R.id.settings_change_avatar_button); final ImageButton button2 = (ImageButton)view.findViewById(R.id.settings_change_avatar_button);
if (chat_id > 0) {
button2.setOnClickListener(new View.OnClickListener() { button2.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
...@@ -557,10 +575,10 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -557,10 +575,10 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
int type; int type;
TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id); TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id);
if (chat.photo == null || chat.photo.photo_big == null || chat.photo instanceof TLRPC.TL_chatPhotoEmpty) { if (chat.photo == null || chat.photo.photo_big == null || chat.photo instanceof TLRPC.TL_chatPhotoEmpty) {
items = new CharSequence[] {LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)};
type = 0; type = 0;
} else { } else {
items = new CharSequence[] {LocaleController.getString("OpenPhoto", R.string.OpenPhoto), LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; items = new CharSequence[]{LocaleController.getString("OpenPhoto", R.string.OpenPhoto), LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)};
type = 1; type = 1;
} }
...@@ -592,6 +610,9 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -592,6 +610,9 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
showAlertDialog(builder); showAlertDialog(builder);
} }
}); });
} else {
button2.setVisibility(View.GONE);
}
} else { } else {
onlineText = (TextView)view.findViewById(R.id.settings_online); onlineText = (TextView)view.findViewById(R.id.settings_online);
} }
...@@ -603,10 +624,15 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -603,10 +624,15 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
textView.setText(chat.title); textView.setText(chat.title);
if (chat.participants_count != 0 && onlineCount > 0) { int count = chat.participants_count;
onlineText.setText(Html.fromHtml(String.format("%s, <font color='#357aa8'>%d %s</font>", LocaleController.formatPluralString("Members", chat.participants_count), onlineCount, LocaleController.getString("Online", R.string.Online)))); if (info != null) {
count = info.participants.size();
}
if (count != 0 && onlineCount > 0) {
onlineText.setText(Html.fromHtml(String.format("%s, <font color='#357aa8'>%d %s</font>", LocaleController.formatPluralString("Members", count), onlineCount, LocaleController.getString("Online", R.string.Online))));
} else { } else {
onlineText.setText(LocaleController.formatPluralString("Members", chat.participants_count)); onlineText.setText(LocaleController.formatPluralString("Members", count));
} }
TLRPC.FileLocation photo = null; TLRPC.FileLocation photo = null;
...@@ -630,7 +656,11 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -630,7 +656,11 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
textView.setText(LocaleController.getString("SHAREDMEDIA", R.string.SHAREDMEDIA)); textView.setText(LocaleController.getString("SHAREDMEDIA", R.string.SHAREDMEDIA));
} else if (i == membersSectionRow) { } else if (i == membersSectionRow) {
TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id); TLRPC.Chat chat = MessagesController.getInstance().chats.get(chat_id);
textView.setText(LocaleController.formatPluralString("Members", chat.participants_count).toUpperCase()); int count = chat.participants_count;
if (info != null) {
count = info.participants.size();
}
textView.setText(LocaleController.formatPluralString("Members", count).toUpperCase());
} }
} else if (type == 2) { } else if (type == 2) {
if (view == null) { if (view == null) {
...@@ -665,7 +695,13 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen ...@@ -665,7 +695,13 @@ public class ChatProfileActivity extends BaseFragment implements NotificationCen
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.chat_profile_add_row, viewGroup, false); view = li.inflate(R.layout.chat_profile_add_row, viewGroup, false);
TextView textView = (TextView)view.findViewById(R.id.messages_list_row_name); TextView textView = (TextView)view.findViewById(R.id.messages_list_row_name);
if (chat_id > 0) {
textView.setText(LocaleController.getString("AddMember", R.string.AddMember)); textView.setText(LocaleController.getString("AddMember", R.string.AddMember));
} else {
textView.setText(LocaleController.getString("AddRecipient", R.string.AddRecipient));
View divider = view.findViewById(R.id.settings_row_divider);
divider.setVisibility(View.INVISIBLE);
}
} }
} else if (type == 5) { } else if (type == 5) {
if (view == null) { if (view == null) {
......
...@@ -76,7 +76,11 @@ public class ChatProfileChangeNameActivity extends BaseFragment { ...@@ -76,7 +76,11 @@ public class ChatProfileChangeNameActivity extends BaseFragment {
TLRPC.Chat currentChat = MessagesController.getInstance().chats.get(chat_id); TLRPC.Chat currentChat = MessagesController.getInstance().chats.get(chat_id);
firstNameField = (EditText)fragmentView.findViewById(R.id.first_name_field); firstNameField = (EditText)fragmentView.findViewById(R.id.first_name_field);
if (chat_id > 0) {
firstNameField.setHint(LocaleController.getString("GroupName", R.string.GroupName)); firstNameField.setHint(LocaleController.getString("GroupName", R.string.GroupName));
} else {
firstNameField.setHint(LocaleController.getString("EnterListName", R.string.EnterListName));
}
firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() { firstNameField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override @Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
...@@ -91,7 +95,11 @@ public class ChatProfileChangeNameActivity extends BaseFragment { ...@@ -91,7 +95,11 @@ public class ChatProfileChangeNameActivity extends BaseFragment {
firstNameField.setSelection(firstNameField.length()); firstNameField.setSelection(firstNameField.length());
TextView headerLabel = (TextView)fragmentView.findViewById(R.id.settings_section_text); TextView headerLabel = (TextView)fragmentView.findViewById(R.id.settings_section_text);
if (chat_id > 0) {
headerLabel.setText(LocaleController.getString("EnterGroupNameTitle", R.string.EnterGroupNameTitle)); headerLabel.setText(LocaleController.getString("EnterGroupNameTitle", R.string.EnterGroupNameTitle));
} else {
headerLabel.setText(LocaleController.getString("EnterListName", R.string.EnterListName).toUpperCase());
}
} else { } else {
ViewGroup parent = (ViewGroup)fragmentView.getParent(); ViewGroup parent = (ViewGroup)fragmentView.getParent();
if (parent != null) { if (parent != null) {
......
...@@ -90,6 +90,8 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ...@@ -90,6 +90,8 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
private TextView emptyTextView; private TextView emptyTextView;
private EditText userSelectEditText; private EditText userSelectEditText;
private boolean ignoreChange = false; private boolean ignoreChange = false;
private boolean isBroadcast = false;
private int maxCount = 200;
private HashMap<Integer, XImageSpan> selectedContacts = new HashMap<Integer, XImageSpan>(); private HashMap<Integer, XImageSpan> selectedContacts = new HashMap<Integer, XImageSpan>();
private ArrayList<XImageSpan> allSpans = new ArrayList<XImageSpan>(); private ArrayList<XImageSpan> allSpans = new ArrayList<XImageSpan>();
...@@ -105,6 +107,16 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ...@@ -105,6 +107,16 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
private final static int done_button = 1; private final static int done_button = 1;
public GroupCreateActivity() {
super();
}
public GroupCreateActivity(Bundle args) {
super(args);
isBroadcast = args.getBoolean("broadcast", false);
maxCount = !isBroadcast ? MessagesController.getInstance().maxGroupCount : MessagesController.getInstance().maxBroadcastCount;
}
@Override @Override
public boolean onFragmentCreate() { public boolean onFragmentCreate() {
NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded); NotificationCenter.getInstance().addObserver(this, MessagesController.contactsDidLoaded);
...@@ -126,8 +138,12 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ...@@ -126,8 +138,12 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
if (fragmentView == null) { if (fragmentView == null) {
actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back); actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back);
actionBarLayer.setBackOverlay(R.layout.updating_state_layout); actionBarLayer.setBackOverlay(R.layout.updating_state_layout);
if (isBroadcast) {
actionBarLayer.setTitle(LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList));
} else {
actionBarLayer.setTitle(LocaleController.getString("NewGroup", R.string.NewGroup)); actionBarLayer.setTitle(LocaleController.getString("NewGroup", R.string.NewGroup));
actionBarLayer.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), 200)); }
actionBarLayer.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount));
actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() { actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
@Override @Override
...@@ -140,6 +156,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ...@@ -140,6 +156,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
result.addAll(selectedContacts.keySet()); result.addAll(selectedContacts.keySet());
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putIntegerArrayList("result", result); args.putIntegerArrayList("result", result);
args.putBoolean("broadcast", isBroadcast);
presentFragment(new GroupCreateFinalActivity(args)); presentFragment(new GroupCreateFinalActivity(args));
} }
} }
...@@ -201,7 +218,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ...@@ -201,7 +218,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
selectedContacts.remove(sp.uid); selectedContacts.remove(sp.uid);
} }
} }
actionBarLayer.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), 200)); actionBarLayer.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount));
listView.invalidateViews(); listView.invalidateViews();
} else { } else {
search = true; search = true;
...@@ -259,7 +276,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ...@@ -259,7 +276,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
userSelectEditText.setSelection(text.length()); userSelectEditText.setSelection(text.length());
ignoreChange = false; ignoreChange = false;
} else { } else {
if (selectedContacts.size() == 200) { if (selectedContacts.size() == maxCount) {
return; return;
} }
ignoreChange = true; ignoreChange = true;
...@@ -267,7 +284,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen ...@@ -267,7 +284,7 @@ public class GroupCreateActivity extends BaseFragment implements NotificationCen
span.uid = user.id; span.uid = user.id;
ignoreChange = false; ignoreChange = false;
} }
actionBarLayer.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), 200)); actionBarLayer.setSubtitle(LocaleController.formatString("MembersCount", R.string.MembersCount, selectedContacts.size(), maxCount));
if (searching || searchWas) { if (searching || searchWas) {
searching = false; searching = false;
searchWas = false; searchWas = false;
......
...@@ -54,11 +54,13 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -54,11 +54,13 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
private AvatarUpdater avatarUpdater = new AvatarUpdater(); private AvatarUpdater avatarUpdater = new AvatarUpdater();
private ProgressDialog progressDialog = null; private ProgressDialog progressDialog = null;
private String nameToSet = null; private String nameToSet = null;
private boolean isBroadcast = false;
private final static int done_button = 1; private final static int done_button = 1;
public GroupCreateFinalActivity(Bundle args) { public GroupCreateFinalActivity(Bundle args) {
super(args); super(args);
isBroadcast = args.getBoolean("broadcast", false);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
...@@ -120,7 +122,11 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -120,7 +122,11 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
if (fragmentView == null) { if (fragmentView == null) {
actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back); actionBarLayer.setDisplayHomeAsUpEnabled(true, R.drawable.ic_ab_back);
actionBarLayer.setBackOverlay(R.layout.updating_state_layout); actionBarLayer.setBackOverlay(R.layout.updating_state_layout);
if (isBroadcast) {
actionBarLayer.setTitle(LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList));
} else {
actionBarLayer.setTitle(LocaleController.getString("NewGroup", R.string.NewGroup)); actionBarLayer.setTitle(LocaleController.getString("NewGroup", R.string.NewGroup));
}
actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() { actionBarLayer.setActionBarMenuOnItemClick(new ActionBarLayer.ActionBarMenuOnItemClick() {
@Override @Override
...@@ -136,6 +142,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -136,6 +142,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
} }
donePressed = true; donePressed = true;
if (isBroadcast) {
MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, uploadedAvatar, isBroadcast);
} else {
if (avatarUpdater.uploadingAvatar != null) { if (avatarUpdater.uploadingAvatar != null) {
createAfterUpload = true; createAfterUpload = true;
} else { } else {
...@@ -144,7 +153,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -144,7 +153,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
progressDialog.setCanceledOnTouchOutside(false); progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false); progressDialog.setCancelable(false);
final long reqId = MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, uploadedAvatar); final long reqId = MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, uploadedAvatar, isBroadcast);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() {
@Override @Override
...@@ -162,6 +171,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -162,6 +171,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
} }
} }
} }
}
}); });
ActionBarMenu menu = actionBarLayer.createMenu(); ActionBarMenu menu = actionBarLayer.createMenu();
...@@ -173,6 +183,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -173,6 +183,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
fragmentView = inflater.inflate(R.layout.group_create_final_layout, container, false); fragmentView = inflater.inflate(R.layout.group_create_final_layout, container, false);
final ImageButton button2 = (ImageButton)fragmentView.findViewById(R.id.settings_change_avatar_button); final ImageButton button2 = (ImageButton)fragmentView.findViewById(R.id.settings_change_avatar_button);
if (isBroadcast) {
button2.setVisibility(View.GONE);
} else {
button2.setOnClickListener(new View.OnClickListener() { button2.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
...@@ -184,9 +197,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -184,9 +197,9 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
CharSequence[] items; CharSequence[] items;
if (avatar != null) { if (avatar != null) {
items = new CharSequence[] {LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)}; items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)};
} else { } else {
items = new CharSequence[] {LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)}; items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)};
} }
builder.setItems(items, new DialogInterface.OnClickListener() { builder.setItems(items, new DialogInterface.OnClickListener() {
...@@ -206,12 +219,17 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -206,12 +219,17 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
showAlertDialog(builder); showAlertDialog(builder);
} }
}); });
}
avatarImage = (BackupImageView)fragmentView.findViewById(R.id.settings_avatar_image); avatarImage = (BackupImageView)fragmentView.findViewById(R.id.settings_avatar_image);
avatarImage.setImageResource(R.drawable.group_blue); avatarImage.setImageResource(R.drawable.group_blue);
nameTextView = (EditText)fragmentView.findViewById(R.id.bubble_input_text); nameTextView = (EditText)fragmentView.findViewById(R.id.bubble_input_text);
if (isBroadcast) {
nameTextView.setHint(LocaleController.getString("EnterListName", R.string.EnterListName));
} else {
nameTextView.setHint(LocaleController.getString("EnterGroupNamePlaceholder", R.string.EnterGroupNamePlaceholder)); nameTextView.setHint(LocaleController.getString("EnterGroupNamePlaceholder", R.string.EnterGroupNamePlaceholder));
}
if (nameToSet != null) { if (nameToSet != null) {
nameTextView.setText(nameToSet); nameTextView.setText(nameToSet);
nameToSet = null; nameToSet = null;
...@@ -237,7 +255,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati ...@@ -237,7 +255,7 @@ public class GroupCreateFinalActivity extends BaseFragment implements Notificati
avatarImage.setImage(avatar, "50_50", R.drawable.group_blue); avatarImage.setImage(avatar, "50_50", R.drawable.group_blue);
if (createAfterUpload) { if (createAfterUpload) {
FileLog.e("tmessages", "avatar did uploaded"); FileLog.e("tmessages", "avatar did uploaded");
MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, uploadedAvatar); MessagesController.getInstance().createChat(nameTextView.getText().toString(), selectedContacts, uploadedAvatar, false);
} }
} }
}); });
......
...@@ -85,7 +85,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen ...@@ -85,7 +85,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
currentConnectionState = ConnectionsManager.getInstance().getConnectionState(); currentConnectionState = ConnectionsManager.getInstance().getConnectionState();
NotificationCenter.getInstance().addObserver(this, 1234); NotificationCenter.getInstance().addObserver(this, 1234);
NotificationCenter.getInstance().addObserver(this, 658);
NotificationCenter.getInstance().addObserver(this, 701); NotificationCenter.getInstance().addObserver(this, 701);
NotificationCenter.getInstance().addObserver(this, 702); NotificationCenter.getInstance().addObserver(this, 702);
NotificationCenter.getInstance().addObserver(this, 703); NotificationCenter.getInstance().addObserver(this, 703);
...@@ -149,6 +148,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen ...@@ -149,6 +148,7 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
Integer push_chat_id = 0; Integer push_chat_id = 0;
Integer push_enc_id = 0; Integer push_enc_id = 0;
Integer open_settings = 0; Integer open_settings = 0;
boolean showDialogsList = false;
photoPathsArray = null; photoPathsArray = null;
videoPath = null; videoPath = null;
...@@ -379,6 +379,8 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen ...@@ -379,6 +379,8 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
push_enc_id = encId; push_enc_id = encId;
} }
} else {
showDialogsList = true;
} }
} }
} }
...@@ -408,6 +410,11 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen ...@@ -408,6 +410,11 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
if (presentFragment(fragment, false, true)) { if (presentFragment(fragment, false, true)) {
pushOpened = true; pushOpened = true;
} }
} else if (showDialogsList) {
for (int a = 1; a < fragmentsStack.size(); a++) {
removeFragmentFromStack(fragmentsStack.get(a));
a--;
}
} }
if (videoPath != null || photoPathsArray != null || sendingText != null || documentsPathsArray != null || contactsToSend != null) { if (videoPath != null || photoPathsArray != null || sendingText != null || documentsPathsArray != null || contactsToSend != null) {
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
...@@ -440,18 +447,23 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen ...@@ -440,18 +447,23 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
public void didSelectDialog(MessagesActivity messageFragment, long dialog_id, boolean param) { public void didSelectDialog(MessagesActivity messageFragment, long dialog_id, boolean param) {
if (dialog_id != 0) { if (dialog_id != 0) {
int lower_part = (int)dialog_id; int lower_part = (int)dialog_id;
int high_id = (int)(dialog_id >> 32);
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putBoolean("scrollToTopOnResume", true); args.putBoolean("scrollToTopOnResume", true);
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats); NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
if (lower_part != 0) { if (lower_part != 0) {
if (high_id == 1) {
args.putInt("chat_id", lower_part);
} else {
if (lower_part > 0) { if (lower_part > 0) {
args.putInt("user_id", lower_part); args.putInt("user_id", lower_part);
} else if (lower_part < 0) { } else if (lower_part < 0) {
args.putInt("chat_id", -lower_part); args.putInt("chat_id", -lower_part);
} }
}
} else { } else {
args.putInt("enc_id", (int)(dialog_id >> 32)); args.putInt("enc_id", high_id);
} }
ChatActivity fragment = new ChatActivity(args); ChatActivity fragment = new ChatActivity(args);
presentFragment(fragment, true); presentFragment(fragment, true);
...@@ -522,7 +534,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen ...@@ -522,7 +534,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
} }
finished = true; finished = true;
NotificationCenter.getInstance().removeObserver(this, 1234); NotificationCenter.getInstance().removeObserver(this, 1234);
NotificationCenter.getInstance().removeObserver(this, 658);
NotificationCenter.getInstance().removeObserver(this, 701); NotificationCenter.getInstance().removeObserver(this, 701);
NotificationCenter.getInstance().removeObserver(this, 702); NotificationCenter.getInstance().removeObserver(this, 702);
NotificationCenter.getInstance().removeObserver(this, 703); NotificationCenter.getInstance().removeObserver(this, 703);
...@@ -546,30 +557,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen ...@@ -546,30 +557,6 @@ public class LaunchActivity extends ActionBarActivity implements NotificationCen
startActivity(intent2); startActivity(intent2);
onFinish(); onFinish();
finish(); finish();
} else if (id == 658) {
if (PhotoViewer.getInstance().isVisible()) {
PhotoViewer.getInstance().closePhoto(false);
}
Integer push_chat_id = (Integer)args[0];
Integer push_user_id = (Integer)args[1];
Integer push_enc_id = (Integer)args[2];
if (push_user_id != 0) {
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
Bundle args2 = new Bundle();
args2.putInt("user_id", push_user_id);
presentFragment(new ChatActivity(args2), false, true);
} else if (push_chat_id != 0) {
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
Bundle args2 = new Bundle();
args2.putInt("chat_id", push_chat_id);
presentFragment(new ChatActivity(args2), false, true);
} else if (push_enc_id != 0) {
NotificationCenter.getInstance().postNotificationName(MessagesController.closeChats);
Bundle args2 = new Bundle();
args2.putInt("enc_id", push_enc_id);
presentFragment(new ChatActivity(args2), false, true);
}
} else if (id == 702) { } else if (id == 702) {
if (args[0] != this) { if (args[0] != this) {
onFinish(); onFinish();
......
...@@ -8,7 +8,9 @@ ...@@ -8,7 +8,9 @@
package org.telegram.ui; package org.telegram.ui;
import android.content.Context;
import android.location.Location; import android.location.Location;
import android.location.LocationManager;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
...@@ -39,6 +41,8 @@ import org.telegram.ui.Views.ActionBar.ActionBarMenuItem; ...@@ -39,6 +41,8 @@ import org.telegram.ui.Views.ActionBar.ActionBarMenuItem;
import org.telegram.ui.Views.BackupImageView; import org.telegram.ui.Views.BackupImageView;
import org.telegram.ui.Views.ActionBar.BaseFragment; import org.telegram.ui.Views.ActionBar.BaseFragment;
import java.util.List;
public class LocationActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate { public class LocationActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate {
private GoogleMap googleMap; private GoogleMap googleMap;
private TextView distanceTextView; private TextView distanceTextView;
...@@ -164,8 +168,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter ...@@ -164,8 +168,7 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
positionMarker(location); positionMarker(location);
} }
}); });
myLocation = googleMap.getMyLocation(); myLocation = getLastLocation();
if (sendButton != null) { if (sendButton != null) {
userLocation = new Location("network"); userLocation = new Location("network");
...@@ -249,6 +252,19 @@ public class LocationActivity extends BaseFragment implements NotificationCenter ...@@ -249,6 +252,19 @@ public class LocationActivity extends BaseFragment implements NotificationCenter
return fragmentView; return fragmentView;
} }
private Location getLastLocation() {
LocationManager lm = (LocationManager) ApplicationLoader.applicationContext.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location l = null;
for (int i = providers.size() - 1; i >= 0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) {
break;
}
}
return l;
}
private void updateUserData() { private void updateUserData() {
if (messageObject != null && avatarImageView != null) { if (messageObject != null && avatarImageView != null) {
int fromId = messageObject.messageOwner.from_id; int fromId = messageObject.messageOwner.from_id;
......
...@@ -150,10 +150,10 @@ public class LoginActivityRegisterView extends SlideView { ...@@ -150,10 +150,10 @@ public class LoginActivityRegisterView extends SlideView {
final TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response; final TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response;
TLRPC.TL_userSelf user = (TLRPC.TL_userSelf)res.user; TLRPC.TL_userSelf user = (TLRPC.TL_userSelf)res.user;
UserConfig.clearConfig(); UserConfig.clearConfig();
MessagesStorage.getInstance().cleanUp();
MessagesController.getInstance().cleanUp(); MessagesController.getInstance().cleanUp();
UserConfig.setCurrentUser(user); UserConfig.setCurrentUser(user);
UserConfig.saveConfig(true); UserConfig.saveConfig(true);
MessagesStorage.getInstance().cleanUp(true);
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>(); ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
users.add(user); users.add(user);
MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); MessagesStorage.getInstance().putUsersAndChats(users, null, true, true);
......
...@@ -54,9 +54,12 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ...@@ -54,9 +54,12 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
private Bundle currentParams; private Bundle currentParams;
private Timer timeTimer; private Timer timeTimer;
private Timer codeTimer;
private static final Integer timerSync = 1; private static final Integer timerSync = 1;
private volatile int time = 60000; private volatile int time = 60000;
private volatile int codeTime = 15000;
private double lastCurrentTime; private double lastCurrentTime;
private double lastCodeTime;
private boolean waitingForSms = false; private boolean waitingForSms = false;
private boolean nextPressed = false; private boolean nextPressed = false;
private String lastError = ""; private String lastError = "";
...@@ -162,6 +165,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ...@@ -162,6 +165,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
codeField.requestFocus(); codeField.requestFocus();
destroyTimer(); destroyTimer();
destroyCodeTimer();
timeText.setText(String.format("%s 1:00", LocaleController.getString("CallText", R.string.CallText))); timeText.setText(String.format("%s 1:00", LocaleController.getString("CallText", R.string.CallText)));
lastCurrentTime = System.currentTimeMillis(); lastCurrentTime = System.currentTimeMillis();
problemText.setVisibility(time < 1000 ? VISIBLE : GONE); problemText.setVisibility(time < 1000 ? VISIBLE : GONE);
...@@ -169,6 +173,46 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ...@@ -169,6 +173,46 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
createTimer(); createTimer();
} }
private void createCodeTimer() {
if (codeTimer != null) {
return;
}
codeTime = 15000;
codeTimer = new Timer();
lastCodeTime = System.currentTimeMillis();
codeTimer.schedule(new TimerTask() {
@Override
public void run() {
double currentTime = System.currentTimeMillis();
double diff = currentTime - lastCodeTime;
codeTime -= diff;
lastCodeTime = currentTime;
Utilities.RunOnUIThread(new Runnable() {
@Override
public void run() {
if (codeTime <= 1000) {
problemText.setVisibility(VISIBLE);
destroyCodeTimer();
}
}
});
}
}, 0, 1000);
}
private void destroyCodeTimer() {
try {
synchronized(timerSync) {
if (codeTimer != null) {
codeTimer.cancel();
codeTimer = null;
}
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
private void createTimer() { private void createTimer() {
if (timeTimer != null) { if (timeTimer != null) {
return; return;
...@@ -189,9 +233,9 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ...@@ -189,9 +233,9 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
int seconds = time / 1000 - minutes * 60; int seconds = time / 1000 - minutes * 60;
timeText.setText(String.format("%s %d:%02d", LocaleController.getString("CallText", R.string.CallText), minutes, seconds)); timeText.setText(String.format("%s %d:%02d", LocaleController.getString("CallText", R.string.CallText), minutes, seconds));
} else { } else {
problemText.setVisibility(VISIBLE);
timeText.setText(LocaleController.getString("Calling", R.string.Calling)); timeText.setText(LocaleController.getString("Calling", R.string.Calling));
destroyTimer(); destroyTimer();
createCodeTimer();
TLRPC.TL_auth_sendCall req = new TLRPC.TL_auth_sendCall(); TLRPC.TL_auth_sendCall req = new TLRPC.TL_auth_sendCall();
req.phone_number = requestPhone; req.phone_number = requestPhone;
req.phone_code_hash = phoneHash; req.phone_code_hash = phoneHash;
...@@ -259,11 +303,12 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ...@@ -259,11 +303,12 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
if (error == null) { if (error == null) {
TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response; TLRPC.TL_auth_authorization res = (TLRPC.TL_auth_authorization)response;
destroyTimer(); destroyTimer();
destroyCodeTimer();
UserConfig.clearConfig(); UserConfig.clearConfig();
MessagesStorage.getInstance().cleanUp();
MessagesController.getInstance().cleanUp(); MessagesController.getInstance().cleanUp();
UserConfig.setCurrentUser(res.user); UserConfig.setCurrentUser(res.user);
UserConfig.saveConfig(true); UserConfig.saveConfig(true);
MessagesStorage.getInstance().cleanUp(true);
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>(); ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
users.add(res.user); users.add(res.user);
MessagesStorage.getInstance().putUsersAndChats(users, null, true, true); MessagesStorage.getInstance().putUsersAndChats(users, null, true, true);
...@@ -280,6 +325,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ...@@ -280,6 +325,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
params.putString("code", req.phone_code); params.putString("code", req.phone_code);
delegate.setPage(2, true, params, false); delegate.setPage(2, true, params, false);
destroyTimer(); destroyTimer();
destroyCodeTimer();
} else { } else {
createTimer(); createTimer();
if (error.text.contains("PHONE_NUMBER_INVALID")) { if (error.text.contains("PHONE_NUMBER_INVALID")) {
...@@ -304,6 +350,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ...@@ -304,6 +350,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
@Override @Override
public void onBackPressed() { public void onBackPressed() {
destroyTimer(); destroyTimer();
destroyCodeTimer();
currentParams = null; currentParams = null;
AndroidUtilities.setWaitingForSms(false); AndroidUtilities.setWaitingForSms(false);
NotificationCenter.getInstance().removeObserver(this, 998); NotificationCenter.getInstance().removeObserver(this, 998);
...@@ -316,6 +363,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente ...@@ -316,6 +363,7 @@ public class LoginActivitySmsView extends SlideView implements NotificationCente
AndroidUtilities.setWaitingForSms(false); AndroidUtilities.setWaitingForSms(false);
NotificationCenter.getInstance().removeObserver(this, 998); NotificationCenter.getInstance().removeObserver(this, 998);
destroyTimer(); destroyTimer();
destroyCodeTimer();
waitingForSms = false; waitingForSms = false;
} }
......
...@@ -74,6 +74,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter ...@@ -74,6 +74,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
private final static int messages_list_menu_new_secret_chat = 3; private final static int messages_list_menu_new_secret_chat = 3;
private final static int messages_list_menu_contacts = 4; private final static int messages_list_menu_contacts = 4;
private final static int messages_list_menu_settings = 5; private final static int messages_list_menu_settings = 5;
private final static int messages_list_menu_new_broadcast = 6;
public static interface MessagesActivityDelegate { public static interface MessagesActivityDelegate {
public abstract void didSelectDialog(MessagesActivity fragment, long dialog_id, boolean param); public abstract void didSelectDialog(MessagesActivity fragment, long dialog_id, boolean param);
...@@ -175,6 +176,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter ...@@ -175,6 +176,7 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other); ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
item.addSubItem(messages_list_menu_new_chat, LocaleController.getString("NewGroup", R.string.NewGroup), 0); item.addSubItem(messages_list_menu_new_chat, LocaleController.getString("NewGroup", R.string.NewGroup), 0);
item.addSubItem(messages_list_menu_new_secret_chat, LocaleController.getString("NewSecretChat", R.string.NewSecretChat), 0); item.addSubItem(messages_list_menu_new_secret_chat, LocaleController.getString("NewSecretChat", R.string.NewSecretChat), 0);
item.addSubItem(messages_list_menu_new_broadcast, LocaleController.getString("NewBroadcastList", R.string.NewBroadcastList), 0);
item.addSubItem(messages_list_menu_contacts, LocaleController.getString("Contacts", R.string.Contacts), 0); item.addSubItem(messages_list_menu_contacts, LocaleController.getString("Contacts", R.string.Contacts), 0);
item.addSubItem(messages_list_menu_settings, LocaleController.getString("Settings", R.string.Settings), 0); item.addSubItem(messages_list_menu_settings, LocaleController.getString("Settings", R.string.Settings), 0);
} }
...@@ -206,6 +208,10 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter ...@@ -206,6 +208,10 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
if (onlySelect) { if (onlySelect) {
finishFragment(); finishFragment();
} }
} else if (id == messages_list_menu_new_broadcast) {
Bundle args = new Bundle();
args.putBoolean("broadcast", true);
presentFragment(new GroupCreateActivity(args));
} }
} }
}); });
...@@ -258,7 +264,11 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter ...@@ -258,7 +264,11 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
if (obj instanceof TLRPC.User) { if (obj instanceof TLRPC.User) {
dialog_id = ((TLRPC.User) obj).id; dialog_id = ((TLRPC.User) obj).id;
} else if (obj instanceof TLRPC.Chat) { } else if (obj instanceof TLRPC.Chat) {
if (((TLRPC.Chat) obj).id > 0) {
dialog_id = -((TLRPC.Chat) obj).id; dialog_id = -((TLRPC.Chat) obj).id;
} else {
dialog_id = AndroidUtilities.makeBroadcastId(((TLRPC.Chat) obj).id);
}
} else if (obj instanceof TLRPC.EncryptedChat) { } else if (obj instanceof TLRPC.EncryptedChat) {
dialog_id = ((long)((TLRPC.EncryptedChat) obj).id) << 32; dialog_id = ((long)((TLRPC.EncryptedChat) obj).id) << 32;
} }
...@@ -282,14 +292,19 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter ...@@ -282,14 +292,19 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
} else { } else {
Bundle args = new Bundle(); Bundle args = new Bundle();
int lower_part = (int)dialog_id; int lower_part = (int)dialog_id;
int high_id = (int)(dialog_id >> 32);
if (lower_part != 0) { if (lower_part != 0) {
if (high_id == 1) {
args.putInt("chat_id", lower_part);
} else {
if (lower_part > 0) { if (lower_part > 0) {
args.putInt("user_id", lower_part); args.putInt("user_id", lower_part);
} else if (lower_part < 0) { } else if (lower_part < 0) {
args.putInt("chat_id", -lower_part); args.putInt("chat_id", -lower_part);
} }
}
} else { } else {
args.putInt("enc_id", (int)(dialog_id >> 32)); args.putInt("enc_id", high_id);
} }
presentFragment(new ChatActivity(args)); presentFragment(new ChatActivity(args));
} }
...@@ -319,7 +334,10 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter ...@@ -319,7 +334,10 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
if ((int)selectedDialog < 0) { int lower_id = (int)selectedDialog;
int high_id = (int)(selectedDialog >> 32);
if (lower_id < 0 && high_id != 1) {
builder.setItems(new CharSequence[]{LocaleController.getString("ClearHistory", R.string.ClearHistory), LocaleController.getString("DeleteChat", R.string.DeleteChat)}, new DialogInterface.OnClickListener() { builder.setItems(new CharSequence[]{LocaleController.getString("ClearHistory", R.string.ClearHistory), LocaleController.getString("DeleteChat", R.string.DeleteChat)}, new DialogInterface.OnClickListener() {
@Override @Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
...@@ -482,7 +500,15 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter ...@@ -482,7 +500,15 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity()); AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName)); builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
int lower_part = (int)dialog_id; int lower_part = (int)dialog_id;
int high_id = (int)(dialog_id >> 32);
if (lower_part != 0) { if (lower_part != 0) {
if (high_id == 1) {
TLRPC.Chat chat = MessagesController.getInstance().chats.get(lower_part);
if (chat == null) {
return;
}
builder.setMessage(LocaleController.formatStringSimple(selectAlertString, chat.title));
} else {
if (lower_part > 0) { if (lower_part > 0) {
TLRPC.User user = MessagesController.getInstance().users.get(lower_part); TLRPC.User user = MessagesController.getInstance().users.get(lower_part);
if (user == null) { if (user == null) {
...@@ -496,9 +522,9 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter ...@@ -496,9 +522,9 @@ public class MessagesActivity extends BaseFragment implements NotificationCenter
} }
builder.setMessage(LocaleController.formatStringSimple(selectAlertString, chat.title)); builder.setMessage(LocaleController.formatStringSimple(selectAlertString, chat.title));
} }
}
} else { } else {
int chat_id = (int)(dialog_id >> 32); TLRPC.EncryptedChat chat = MessagesController.getInstance().encryptedChats.get(high_id);
TLRPC.EncryptedChat chat = MessagesController.getInstance().encryptedChats.get(chat_id);
TLRPC.User user = MessagesController.getInstance().users.get(chat.user_id); TLRPC.User user = MessagesController.getInstance().users.get(chat.user_id);
if (user == null) { if (user == null) {
return; return;
......
...@@ -413,6 +413,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat ...@@ -413,6 +413,9 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
imagesByIdsTemp.clear(); imagesByIdsTemp.clear();
needSearchImageInArr = false; needSearchImageInArr = false;
currentIndex = -1; currentIndex = -1;
if (foundIndex >= imagesArr.size()) {
foundIndex = imagesArr.size() - 1;
}
setImageIndex(foundIndex, true); setImageIndex(foundIndex, true);
} else { } else {
if (!cacheEndReached || !arr.isEmpty() && added != 0) { if (!cacheEndReached || !arr.isEmpty() && added != 0) {
...@@ -1384,6 +1387,15 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat ...@@ -1384,6 +1387,15 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
NotificationCenter.getInstance().addObserver(this, MessagesController.mediaDidLoaded); NotificationCenter.getInstance().addObserver(this, MessagesController.mediaDidLoaded);
NotificationCenter.getInstance().addObserver(this, MessagesController.userPhotosLoaded); NotificationCenter.getInstance().addObserver(this, MessagesController.userPhotosLoaded);
try {
if (windowView.getParent() != null) {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(windowView);
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
placeProvider = provider; placeProvider = provider;
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE); WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.addView(windowView, windowLayoutParams); wm.addView(windowView, windowLayoutParams);
...@@ -1702,8 +1714,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat ...@@ -1702,8 +1714,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
return; return;
} }
try { try {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
if (windowView.getParent() != null) { if (windowView.getParent() != null) {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.removeViewImmediate(windowView); wm.removeViewImmediate(windowView);
} }
windowView = null; windowView = null;
...@@ -1730,8 +1742,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat ...@@ -1730,8 +1742,8 @@ public class PhotoViewer implements NotificationCenter.NotificationCenterDelegat
public void run() { public void run() {
animatingImageView.setImageBitmap(null); animatingImageView.setImageBitmap(null);
try { try {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
if (windowView.getParent() != null) { if (windowView.getParent() != null) {
WindowManager wm = (WindowManager) parentActivity.getSystemService(Context.WINDOW_SERVICE);
wm.removeView(windowView); wm.removeView(windowView);
} }
} catch (Exception e) { } catch (Exception e) {
......
...@@ -161,7 +161,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC ...@@ -161,7 +161,7 @@ public class PopupNotificationActivity extends Activity implements NotificationC
return; return;
} }
NotificationsController.getInstance().popupMessages.remove(currentMessageNum); NotificationsController.getInstance().popupMessages.remove(currentMessageNum);
MessagesController.getInstance().markDialogAsRead(currentMessageObject.getDialogId(), currentMessageObject.messageOwner.id, Math.max(0, currentMessageObject.messageOwner.id), 0, currentMessageObject.messageOwner.date, true); MessagesController.getInstance().markDialogAsRead(currentMessageObject.getDialogId(), currentMessageObject.messageOwner.id, Math.max(0, currentMessageObject.messageOwner.id), 0, currentMessageObject.messageOwner.date, true, true);
currentMessageObject = null; currentMessageObject = null;
getNewMessage(); getNewMessage();
} }
...@@ -874,9 +874,6 @@ public class PopupNotificationActivity extends Activity implements NotificationC ...@@ -874,9 +874,6 @@ public class PopupNotificationActivity extends Activity implements NotificationC
chatActivityEnterView.setFieldFocused(false); chatActivityEnterView.setFieldFocused(false);
} }
ConnectionsManager.getInstance().setAppPaused(true, false); ConnectionsManager.getInstance().setAppPaused(true, false);
if (wakeLock.isHeld()) {
wakeLock.release();
}
} }
@Override @Override
......
...@@ -568,6 +568,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter ...@@ -568,6 +568,9 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
} catch (Exception e) { } catch (Exception e) {
FileLog.e("tmessages", e); FileLog.e("tmessages", e);
} }
ArrayList<TLRPC.User> users = new ArrayList<TLRPC.User>();
users.add(res.user);
MessagesStorage.getInstance().putUsersAndChats(users, null, true, true);
MessagesController.getInstance().users.put(res.user.id, res.user); MessagesController.getInstance().users.put(res.user.id, res.user);
Bundle args = new Bundle(); Bundle args = new Bundle();
args.putInt("user_id", res.user.id); args.putInt("user_id", res.user.id);
...@@ -962,7 +965,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter ...@@ -962,7 +965,7 @@ public class SettingsActivity extends BaseFragment implements NotificationCenter
MessagesController.getInstance().unregistedPush(); MessagesController.getInstance().unregistedPush();
MessagesController.getInstance().logOut(); MessagesController.getInstance().logOut();
UserConfig.clearConfig(); UserConfig.clearConfig();
MessagesStorage.getInstance().cleanUp(); MessagesStorage.getInstance().cleanUp(false);
MessagesController.getInstance().cleanUp(); MessagesController.getInstance().cleanUp();
ContactsController.getInstance().deleteAllAppAccounts(); ContactsController.getInstance().deleteAllAppAccounts();
} }
......
...@@ -406,7 +406,8 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif ...@@ -406,7 +406,8 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif
} }
public void updateServerNotificationsSettings(boolean group) { public void updateServerNotificationsSettings(boolean group) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); //disable global settings sync
/*SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings(); TLRPC.TL_account_updateNotifySettings req = new TLRPC.TL_account_updateNotifySettings();
req.settings = new TLRPC.TL_inputPeerNotifySettings(); req.settings = new TLRPC.TL_inputPeerNotifySettings();
req.settings.sound = "default"; req.settings.sound = "default";
...@@ -425,7 +426,7 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif ...@@ -425,7 +426,7 @@ public class SettingsNotificationsActivity extends BaseFragment implements Notif
public void run(TLObject response, TLRPC.TL_error error) { public void run(TLObject response, TLRPC.TL_error error) {
} }
}); });*/
} }
@Override @Override
......
...@@ -467,18 +467,15 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C ...@@ -467,18 +467,15 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C
List<Track> tracks = movie.getTracks(); List<Track> tracks = movie.getTracks();
movie.setTracks(new LinkedList<Track>()); movie.setTracks(new LinkedList<Track>());
double startTime = videoTimelineView.getLeftProgress() * videoPlayer.getDuration() / 1000.0; double startTime = 0;
double endTime = videoTimelineView.getRightProgress() * videoPlayer.getDuration() / 1000.0; double endTime = 0;
boolean timeCorrected = false;
for (Track track : tracks) { for (Track track : tracks) {
if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) { if (track.getSyncSamples() != null && track.getSyncSamples().length > 0) {
if (timeCorrected) { double duration = (double)track.getDuration() / (double)track.getTrackMetaData().getTimescale();
throw new RuntimeException("The startTime has already been corrected by another track with SyncSample. Not Supported."); startTime = correctTimeToSyncSample(track, videoTimelineView.getLeftProgress() * duration, false);
} endTime = videoTimelineView.getRightProgress() * duration;
startTime = correctTimeToSyncSample(track, startTime, false); break;
endTime = correctTimeToSyncSample(track, endTime, true);
timeCorrected = true;
} }
} }
...@@ -486,7 +483,7 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C ...@@ -486,7 +483,7 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C
long currentSample = 0; long currentSample = 0;
double currentTime = 0; double currentTime = 0;
double lastTime = 0; double lastTime = 0;
long startSample = -1; long startSample = 0;
long endSample = -1; long endSample = -1;
for (int i = 0; i < track.getSampleDurations().length; i++) { for (int i = 0; i < track.getSampleDurations().length; i++) {
...@@ -503,9 +500,7 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C ...@@ -503,9 +500,7 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C
} }
movie.addTrack(new CroppedTrack(track, startSample, endSample)); movie.addTrack(new CroppedTrack(track, startSample, endSample));
} }
long start1 = System.currentTimeMillis();
Container out = new DefaultMp4Builder().build(movie); Container out = new DefaultMp4Builder().build(movie);
long start2 = System.currentTimeMillis();
String fileName = Integer.MIN_VALUE + "_" + UserConfig.lastLocalId + ".mp4"; String fileName = Integer.MIN_VALUE + "_" + UserConfig.lastLocalId + ".mp4";
UserConfig.lastLocalId--; UserConfig.lastLocalId--;
...@@ -524,6 +519,11 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C ...@@ -524,6 +519,11 @@ public class VideoEditorActivity extends BaseFragment implements SurfaceHolder.C
} }
} }
// private void startEncodeVideo() {
// MediaExtractor mediaExtractor = new MediaExtractor();
// mediaExtractor.s
// }
private static double correctTimeToSyncSample(Track track, double cutHere, boolean next) { private static double correctTimeToSyncSample(Track track, double cutHere, boolean next) {
double[] timeOfSyncSamples = new double[track.getSyncSamples().length]; double[] timeOfSyncSamples = new double[track.getSyncSamples().length];
long currentSample = 0; long currentSample = 0;
......
...@@ -46,7 +46,7 @@ public class GifDrawable extends Drawable implements Animatable, MediaController ...@@ -46,7 +46,7 @@ public class GifDrawable extends Drawable implements Animatable, MediaController
private static native void renderFrame(int[] pixels, int gifFileInPtr, int[] metaData); private static native void renderFrame(int[] pixels, int gifFileInPtr, int[] metaData);
private static native int openFile(int[] metaData, String filePath); private static native int openFile(int[] metaData, String filePath);
private static native void free(int gifFileInPtr); private static native void free(int gifFileInPtr);
private static native boolean reset(int gifFileInPtr); private static native void reset(int gifFileInPtr);
private static native void setSpeedFactor(int gifFileInPtr, float factor); private static native void setSpeedFactor(int gifFileInPtr, float factor);
private static native String getComment(int gifFileInPtr); private static native String getComment(int gifFileInPtr);
private static native int getLoopCount(int gifFileInPtr); private static native int getLoopCount(int gifFileInPtr);
......
...@@ -75,17 +75,20 @@ public class ImageReceiver { ...@@ -75,17 +75,20 @@ public class ImageReceiver {
if (filter != null) { if (filter != null) {
key += "@" + filter; key += "@" + filter;
} }
Bitmap img; Bitmap img = null;
if (currentPath != null) { if (currentPath != null) {
if (currentPath.equals(key)) { if (currentPath.equals(key)) {
if (currentImage != null) {
return; return;
} else { } else {
img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter, true); img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter);
recycleBitmap(img);
} }
} else { } else {
img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter, true); img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter);
recycleBitmap(img);
}
} }
img = FileLoader.getInstance().getImageFromMemory(path, httpUrl, this, filter);
currentPath = key; currentPath = key;
last_path = path; last_path = path;
last_httpUrl = httpUrl; last_httpUrl = httpUrl;
...@@ -132,6 +135,9 @@ public class ImageReceiver { ...@@ -132,6 +135,9 @@ public class ImageReceiver {
last_filter = null; last_filter = null;
currentImage = null; currentImage = null;
last_size = 0; last_size = 0;
if (parentView != null) {
parentView.invalidate();
}
} }
public void setImageBitmap(Drawable bitmap) { public void setImageBitmap(Drawable bitmap) {
...@@ -145,6 +151,9 @@ public class ImageReceiver { ...@@ -145,6 +151,9 @@ public class ImageReceiver {
last_httpUrl = null; last_httpUrl = null;
last_filter = null; last_filter = null;
last_size = 0; last_size = 0;
if (parentView != null) {
parentView.invalidate();
}
} }
public void clearImage() { public void clearImage() {
......
/*
* This is the source code of Telegram for Android v. 1.7.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-2014.
*/
package org.telegram.ui.Views;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import org.telegram.android.AndroidUtilities;
public class RoundProgressView {
private Paint paint;
public float currentProgress = 0;
public RectF rect = new RectF();
public RoundProgressView() {
paint = new Paint();
paint.setColor(0xffffffff);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(AndroidUtilities.dp(1));
paint.setAntiAlias(true);
}
public void setProgress(float progress) {
currentProgress = progress;
if (currentProgress < 0) {
currentProgress = 0;
} else if (currentProgress > 1) {
currentProgress = 1;
}
}
public void draw(Canvas canvas) {
canvas.drawArc(rect, -90, 360 * currentProgress, false, paint);
}
}
TMessagesProj/src/main/res/drawable-hdpi/playvideo.png

2.59 KB | W: | H:

TMessagesProj/src/main/res/drawable-hdpi/playvideo.png

2.3 KB | W: | H:

TMessagesProj/src/main/res/drawable-hdpi/playvideo.png
TMessagesProj/src/main/res/drawable-hdpi/playvideo.png
TMessagesProj/src/main/res/drawable-hdpi/playvideo.png
TMessagesProj/src/main/res/drawable-hdpi/playvideo.png
  • 2-up
  • Swipe
  • Onion skin
TMessagesProj/src/main/res/drawable-ldpi/playvideo.png

785 Bytes | W: | H:

TMessagesProj/src/main/res/drawable-ldpi/playvideo.png

1.59 KB | W: | H:

TMessagesProj/src/main/res/drawable-ldpi/playvideo.png
TMessagesProj/src/main/res/drawable-ldpi/playvideo.png
TMessagesProj/src/main/res/drawable-ldpi/playvideo.png
TMessagesProj/src/main/res/drawable-ldpi/playvideo.png
  • 2-up
  • Swipe
  • Onion skin
TMessagesProj/src/main/res/drawable-mdpi/playvideo.png

1.78 KB | W: | H:

TMessagesProj/src/main/res/drawable-mdpi/playvideo.png

1.84 KB | W: | H:

TMessagesProj/src/main/res/drawable-mdpi/playvideo.png
TMessagesProj/src/main/res/drawable-mdpi/playvideo.png
TMessagesProj/src/main/res/drawable-mdpi/playvideo.png
TMessagesProj/src/main/res/drawable-mdpi/playvideo.png
  • 2-up
  • Swipe
  • Onion skin
TMessagesProj/src/main/res/drawable-xhdpi/playvideo.png

3.45 KB | W: | H:

TMessagesProj/src/main/res/drawable-xhdpi/playvideo.png

2.74 KB | W: | H:

TMessagesProj/src/main/res/drawable-xhdpi/playvideo.png
TMessagesProj/src/main/res/drawable-xhdpi/playvideo.png
TMessagesProj/src/main/res/drawable-xhdpi/playvideo.png
TMessagesProj/src/main/res/drawable-xhdpi/playvideo.png
  • 2-up
  • Swipe
  • Onion skin
TMessagesProj/src/main/res/drawable-xxhdpi/playvideo.png

5.23 KB | W: | H:

TMessagesProj/src/main/res/drawable-xxhdpi/playvideo.png

3.63 KB | W: | H:

TMessagesProj/src/main/res/drawable-xxhdpi/playvideo.png
TMessagesProj/src/main/res/drawable-xxhdpi/playvideo.png
TMessagesProj/src/main/res/drawable-xxhdpi/playvideo.png
TMessagesProj/src/main/res/drawable-xxhdpi/playvideo.png
  • 2-up
  • Swipe
  • Onion skin
...@@ -45,6 +45,7 @@ ...@@ -45,6 +45,7 @@
android:layout_marginTop="0dp" android:layout_marginTop="0dp"
android:gravity="right|center_vertical" android:gravity="right|center_vertical"
android:imeOptions="flagNoExtractUi" android:imeOptions="flagNoExtractUi"
android:inputType="textCapSentences"
android:layout_gravity="center_vertical|right" android:layout_gravity="center_vertical|right"
android:textCursorDrawable="@null" android:textCursorDrawable="@null"
android:textColor="#000000"/> android:textColor="#000000"/>
......
...@@ -45,6 +45,7 @@ ...@@ -45,6 +45,7 @@
android:layout_marginTop="0dp" android:layout_marginTop="0dp"
android:gravity="left|center_vertical" android:gravity="left|center_vertical"
android:imeOptions="flagNoExtractUi" android:imeOptions="flagNoExtractUi"
android:inputType="textCapSentences"
android:layout_gravity="center_vertical" android:layout_gravity="center_vertical"
android:textCursorDrawable="@null" android:textCursorDrawable="@null"
android:textColor="#000000"/> android:textColor="#000000"/>
......
...@@ -57,6 +57,14 @@ ...@@ -57,6 +57,14 @@
<string name="HiddenName">الاسم مخفي</string> <string name="HiddenName">الاسم مخفي</string>
<string name="SelectChat">اختر محادثة</string> <string name="SelectChat">اختر محادثة</string>
<!--broadcasts-->
<string name="BroadcastList">Broadcast List</string>
<string name="NewBroadcastList">New Broadcast List</string>
<string name="EnterListName">Enter list name</string>
<string name="YouCreatedBroadcastList">You created a broadcast list</string>
<string name="AddRecipient">Add Recipient</string>
<string name="KickFromBroadcast">Remove from broadcast list</string>
<!--documents view--> <!--documents view-->
<string name="SelectFile">اختر ملف</string> <string name="SelectFile">اختر ملف</string>
<string name="FreeOfTotal">متاح %1$s من %2$s</string> <string name="FreeOfTotal">متاح %1$s من %2$s</string>
...@@ -300,7 +308,7 @@ ...@@ -300,7 +308,7 @@
<string name="NoPhotos">لا توجد صور حتى الآن</string> <string name="NoPhotos">لا توجد صور حتى الآن</string>
<!--edit video view--> <!--edit video view-->
<string name="EditVideo">Edit Video</string> <string name="EditVideo">تحرير الفيديو</string>
<string name="OriginalVideo">Original Video</string> <string name="OriginalVideo">Original Video</string>
<string name="EditedVideo">Edited Video</string> <string name="EditedVideo">Edited Video</string>
......
...@@ -57,6 +57,14 @@ ...@@ -57,6 +57,14 @@
<string name="HiddenName">Versteckter Name</string> <string name="HiddenName">Versteckter Name</string>
<string name="SelectChat">Chat auswählen</string> <string name="SelectChat">Chat auswählen</string>
<!--broadcasts-->
<string name="BroadcastList">Broadcast Liste</string>
<string name="NewBroadcastList">Neue Broadcast Liste</string>
<string name="EnterListName">Name der Liste eingeben</string>
<string name="YouCreatedBroadcastList">Du hast eine Broadcast Liste erstellt</string>
<string name="AddRecipient">Empfänger hinzufügen</string>
<string name="KickFromBroadcast">Aus Broadcast Liste entfernen</string>
<!--documents view--> <!--documents view-->
<string name="SelectFile">Datei auswählen</string> <string name="SelectFile">Datei auswählen</string>
<string name="FreeOfTotal">Freier Speicher: %1$s von %2$s</string> <string name="FreeOfTotal">Freier Speicher: %1$s von %2$s</string>
...@@ -150,7 +158,7 @@ ...@@ -150,7 +158,7 @@
<string name="NotificationGroupKickYou">%1$s hat dich aus der Gruppe %2$s entfernt</string> <string name="NotificationGroupKickYou">%1$s hat dich aus der Gruppe %2$s entfernt</string>
<string name="NotificationGroupLeftMember">%1$s hat die Gruppe %2$s verlassen</string> <string name="NotificationGroupLeftMember">%1$s hat die Gruppe %2$s verlassen</string>
<string name="NotificationContactJoined">%1$s benutzt jetzt Telegram!</string> <string name="NotificationContactJoined">%1$s benutzt jetzt Telegram!</string>
<string name="NotificationUnrecognizedDevice">%1$s,\n\nwir haben einen Zugriff auf dein Konto von einem neuen Gerät am %2$s erkannt.\n\nGerät: %3$s\nStandort: %4$s\n\nWenn du das nicht warst, kannst du in den Einstellungen alle Sitzungen beenden.\n\nDanke,\ndas Telegram Team</string> <string name="NotificationUnrecognizedDevice">%1$s,\nWir haben eine Anmeldung von einem neuen Gerät mit der IP-Adresse %2$s festgestellt.\n\nGerät: %3$s\nStandort: %4$s\n\nWenn du es nicht selbst gewesen bist, melde alle anderen Sitzungen in den Telegram Einstellungen unverzüglich ab. \n\n\nMit freundlichen Grüßen,\nDas Telegram Team</string>
<string name="NotificationContactNewPhoto">%1$s hat das Profilbild geändert</string> <string name="NotificationContactNewPhoto">%1$s hat das Profilbild geändert</string>
<!--contacts view--> <!--contacts view-->
...@@ -193,7 +201,7 @@ ...@@ -193,7 +201,7 @@
<string name="PhoneHome">FESTNETZ</string> <string name="PhoneHome">FESTNETZ</string>
<string name="PhoneMobile">MOBIL</string> <string name="PhoneMobile">MOBIL</string>
<string name="PhoneWork">ARBEIT</string> <string name="PhoneWork">ARBEIT</string>
<string name="PhoneOther">ANDERE</string> <string name="PhoneOther">SONSTIGES</string>
<string name="PhoneMain">HAUPTNUMMER</string> <string name="PhoneMain">HAUPTNUMMER</string>
<string name="ContactInfo">Kontaktdaten</string> <string name="ContactInfo">Kontaktdaten</string>
<string name="PHONE">TELEFON</string> <string name="PHONE">TELEFON</string>
...@@ -270,12 +278,12 @@ ...@@ -270,12 +278,12 @@
<string name="SortFirstName">Vorname</string> <string name="SortFirstName">Vorname</string>
<string name="SortLastName">Nachname</string> <string name="SortLastName">Nachname</string>
<string name="LedColor">LED-Farbe</string> <string name="LedColor">LED-Farbe</string>
<string name="PopupNotification">Popup-Benachrichtigung</string> <string name="PopupNotification">Popup Benachrichtigungen</string>
<string name="NoPopup">Kein Popup</string> <string name="NoPopup">Kein Popup</string>
<string name="OnlyWhenScreenOn">Nur wenn Bildschirm „an“</string> <string name="OnlyWhenScreenOn">Nur wenn Bildschirm „an“</string>
<string name="OnlyWhenScreenOff">Nur wenn Bildschirm „aus“</string> <string name="OnlyWhenScreenOff">Nur wenn Bildschirm „aus“</string>
<string name="AlwaysShowPopup">Popups immer anzeigen</string> <string name="AlwaysShowPopup">Popups immer anzeigen</string>
<string name="BadgeNumber">Nummer auf Symbol</string> <string name="BadgeNumber">BADGE (Anzahl)</string>
<!--media view--> <!--media view-->
<string name="NoMedia">Noch keine geteilten Medien vorhanden</string> <string name="NoMedia">Noch keine geteilten Medien vorhanden</string>
...@@ -300,9 +308,9 @@ ...@@ -300,9 +308,9 @@
<string name="NoPhotos">Noch keine Fotos</string> <string name="NoPhotos">Noch keine Fotos</string>
<!--edit video view--> <!--edit video view-->
<string name="EditVideo">Edit Video</string> <string name="EditVideo">Video bearbeiten</string>
<string name="OriginalVideo">Original Video</string> <string name="OriginalVideo">Originalvideo</string>
<string name="EditedVideo">Edited Video</string> <string name="EditedVideo">Bearbeitetes Video</string>
<!--button titles--> <!--button titles-->
<string name="Next">Weiter</string> <string name="Next">Weiter</string>
...@@ -363,7 +371,7 @@ ...@@ -363,7 +371,7 @@
<string name="Loading">Lädt…</string> <string name="Loading">Lädt…</string>
<string name="NoPlayerInstalled">Du hast keinen Videoplayer. Bitte installiere einen um fortzufahren.</string> <string name="NoPlayerInstalled">Du hast keinen Videoplayer. Bitte installiere einen um fortzufahren.</string>
<string name="NoMailInstalled">Bitte sende uns eine Email an sms@telegram.org mit einer Beschreibung des Problems.</string> <string name="NoMailInstalled">Bitte sende uns eine Email an sms@telegram.org mit einer Beschreibung des Problems.</string>
<string name="NoHandleAppInstalled">Du hast keine App, die den Dokumententyp \'%1$s\' öffnen kann.</string> <string name="NoHandleAppInstalled">Du hast keine Applikationen, die den Dateityp \'%1$s\' öffnen könnten. Bitte installiere eine entsprechende Anwendung um fortzufahren.</string>
<string name="InviteUser">Dieser Benutzer hat noch kein Telegram. Möchtest du ihn einladen?</string> <string name="InviteUser">Dieser Benutzer hat noch kein Telegram. Möchtest du ihn einladen?</string>
<string name="AreYouSure">Bist du sicher?</string> <string name="AreYouSure">Bist du sicher?</string>
<string name="AddContactQ">Kontakt hinzufügen?</string> <string name="AddContactQ">Kontakt hinzufügen?</string>
...@@ -375,7 +383,7 @@ ...@@ -375,7 +383,7 @@
<string name="AreYouSureSessions">Sicher, dass du alle anderen Geräte abmelden möchtest?</string> <string name="AreYouSureSessions">Sicher, dass du alle anderen Geräte abmelden möchtest?</string>
<string name="AreYouSureDeleteAndExit">Diese Gruppe wirklich löschen und verlassen?</string> <string name="AreYouSureDeleteAndExit">Diese Gruppe wirklich löschen und verlassen?</string>
<string name="AreYouSureDeleteThisChat">Möchtest du wirklich diesen Chat löschen?</string> <string name="AreYouSureDeleteThisChat">Möchtest du wirklich diesen Chat löschen?</string>
<string name="AreYouSureShareMyContactInfo">Möchtest du wirklich die eigenen Kontaktdaten teilen?</string> <string name="AreYouSureShareMyContactInfo">Wirklich die eigenen Kontaktinformationen teilen?</string>
<string name="AreYouSureBlockContact">Diesen Kontakt wirklich blockieren?</string> <string name="AreYouSureBlockContact">Diesen Kontakt wirklich blockieren?</string>
<string name="AreYouSureUnblockContact">Blockierung für diesen Kontakt wirklich aufheben?</string> <string name="AreYouSureUnblockContact">Blockierung für diesen Kontakt wirklich aufheben?</string>
<string name="AreYouSureDeleteContact">Diesen Kontakt wirklich löschen?</string> <string name="AreYouSureDeleteContact">Diesen Kontakt wirklich löschen?</string>
......
...@@ -57,6 +57,14 @@ ...@@ -57,6 +57,14 @@
<string name="HiddenName">Nombre oculto</string> <string name="HiddenName">Nombre oculto</string>
<string name="SelectChat">Selecciona el chat</string> <string name="SelectChat">Selecciona el chat</string>
<!--broadcasts-->
<string name="BroadcastList">Lista de difusión</string>
<string name="NewBroadcastList">Nueva lista de difusión</string>
<string name="EnterListName">Ingresa el nombre de la lista</string>
<string name="YouCreatedBroadcastList">Creaste una lista de difusión</string>
<string name="AddRecipient">Añadir destinatario</string>
<string name="KickFromBroadcast">Quitar de la lista de difusión</string>
<!--documents view--> <!--documents view-->
<string name="SelectFile">Seleccionar archivo</string> <string name="SelectFile">Seleccionar archivo</string>
<string name="FreeOfTotal">%1$s de %2$s libres</string> <string name="FreeOfTotal">%1$s de %2$s libres</string>
...@@ -150,7 +158,7 @@ ...@@ -150,7 +158,7 @@
<string name="NotificationGroupKickYou">%1$s te ha expulsado del grupo %2$s</string> <string name="NotificationGroupKickYou">%1$s te ha expulsado del grupo %2$s</string>
<string name="NotificationGroupLeftMember">%1$s abandonó el grupo %2$s</string> <string name="NotificationGroupLeftMember">%1$s abandonó el grupo %2$s</string>
<string name="NotificationContactJoined">¡%1$s se unió a Telegram!</string> <string name="NotificationContactJoined">¡%1$s se unió a Telegram!</string>
<string name="NotificationUnrecognizedDevice">%1$s,\nHemos detectado una conexión a tu cuenta desde un nuevo dispositivo el %2$s\n\nDispositivo: %3$s\nUbicación: %4$s\n\nSi no eras tú, puedes ir a Ajustes - Cerrar todas las otras sesiones.\n\nGracias,\nEl equipo de Telegram</string> <string name="NotificationUnrecognizedDevice">%1$s,\nHemos detectado un inicio de sesión en tu cuenta desde un nuevo dispositivo, el %2$s\n\nDispositivo: %3$s\nUbicación: %4$s\n\nSi no eras tú, puedes ir a Ajustes - Cerrar todas las otras sesiones. \n\nAtentamente,\nEl Equipo de Telegram</string>
<string name="NotificationContactNewPhoto">%1$s actualizó su foto de perfil</string> <string name="NotificationContactNewPhoto">%1$s actualizó su foto de perfil</string>
<!--contacts view--> <!--contacts view-->
...@@ -263,19 +271,19 @@ ...@@ -263,19 +271,19 @@
<string name="Enabled">Activado</string> <string name="Enabled">Activado</string>
<string name="Disabled">Desactivado</string> <string name="Disabled">Desactivado</string>
<string name="NotificationsService">Servicio de notificaciones</string> <string name="NotificationsService">Servicio de notificaciones</string>
<string name="NotificationsServiceDisableInfo">Si los servicios de google play son suficientes para recibir notificaciones, puedes desactivar el \'Servicio de notificaciones\'. Sin embargo, te recomendamos activarlos para mantener la aplicación funcionando en segundo plano y recibir notificaciones de forma instantánea.</string> <string name="NotificationsServiceDisableInfo">Si los Servicios de Google Play son suficientes para que recibas las notificaciones, puedes desactivar el Servicio de notificaciones. Sin embargo, te recomendamos que lo dejes activo para mantener funcionando la aplicación en segundo plano y recibir las notificaciones al instante.</string>
<string name="SortBy">Ordenar por</string> <string name="SortBy">Ordenar por</string>
<string name="ImportContacts">Importar contactos</string> <string name="ImportContacts">Importar contactos</string>
<string name="WiFiOnly">Solo vía Wifi</string> <string name="WiFiOnly">Solo vía Wifi</string>
<string name="SortFirstName">Nombre</string> <string name="SortFirstName">Nombre</string>
<string name="SortLastName">Apellido</string> <string name="SortLastName">Apellido</string>
<string name="LedColor">Color del LED</string> <string name="LedColor">Color del LED</string>
<string name="PopupNotification">Notificación emergente</string> <string name="PopupNotification">Notificaciones emergentes</string>
<string name="NoPopup">Sin notificación emergente</string> <string name="NoPopup">Sin notificación emergente</string>
<string name="OnlyWhenScreenOn">Sólo con pantalla encendida</string> <string name="OnlyWhenScreenOn">Sólo con pantalla encendida</string>
<string name="OnlyWhenScreenOff">Sólo con pantalla apagada</string> <string name="OnlyWhenScreenOff">Sólo con pantalla apagada</string>
<string name="AlwaysShowPopup">Siempre mostrar notificación emergente</string> <string name="AlwaysShowPopup">Siempre mostrar notificación emergente</string>
<string name="BadgeNumber">Globo de notificación</string> <string name="BadgeNumber">Globo en el ícono</string>
<!--media view--> <!--media view-->
<string name="NoMedia">No hay fotos ni vídeos compartidos aún</string> <string name="NoMedia">No hay fotos ni vídeos compartidos aún</string>
...@@ -300,9 +308,9 @@ ...@@ -300,9 +308,9 @@
<string name="NoPhotos">No hay fotos aún</string> <string name="NoPhotos">No hay fotos aún</string>
<!--edit video view--> <!--edit video view-->
<string name="EditVideo">Edit Video</string> <string name="EditVideo">Editar vídeo</string>
<string name="OriginalVideo">Original Video</string> <string name="OriginalVideo">Vídeo original</string>
<string name="EditedVideo">Edited Video</string> <string name="EditedVideo">Vídeo editado</string>
<!--button titles--> <!--button titles-->
<string name="Next">Siguiente</string> <string name="Next">Siguiente</string>
...@@ -362,8 +370,8 @@ ...@@ -362,8 +370,8 @@
<string name="InvalidLastName">Apellido/s inválido/s</string> <string name="InvalidLastName">Apellido/s inválido/s</string>
<string name="Loading">Cargando...</string> <string name="Loading">Cargando...</string>
<string name="NoPlayerInstalled">No tienes reproductor de vídeo. Por favor, instala uno para continuar.</string> <string name="NoPlayerInstalled">No tienes reproductor de vídeo. Por favor, instala uno para continuar.</string>
<string name="NoMailInstalled">Por favor, envía un correo a sms@telegram.org y explica tu problema.</string> <string name="NoMailInstalled">Por favor, envíanos un correo electrónico a sms@telegram.org y cuéntanos tu problema.</string>
<string name="NoHandleAppInstalled">No tienes una aplicación que pueda manejar el tipo mime \'%1$s\'. Por favor, instala una para continuar</string> <string name="NoHandleAppInstalled">No tienes aplicaciones que puedan manejar el tipo de archivo \'%1$s\'. Por favor, instala una para continuar.</string>
<string name="InviteUser">Este usuario no tiene Telegram aún. ¿Enviarle una invitación?</string> <string name="InviteUser">Este usuario no tiene Telegram aún. ¿Enviarle una invitación?</string>
<string name="AreYouSure">¿Estás seguro?</string> <string name="AreYouSure">¿Estás seguro?</string>
<string name="AddContactQ">¿Añadir contacto?</string> <string name="AddContactQ">¿Añadir contacto?</string>
......
...@@ -57,6 +57,14 @@ ...@@ -57,6 +57,14 @@
<string name="HiddenName">Nome nascosto</string> <string name="HiddenName">Nome nascosto</string>
<string name="SelectChat">Seleziona chat</string> <string name="SelectChat">Seleziona chat</string>
<!--broadcasts-->
<string name="BroadcastList">Lista Broadcast</string>
<string name="NewBroadcastList">Nuova Lista Broadcast</string>
<string name="EnterListName">Immetti il nome della lista</string>
<string name="YouCreatedBroadcastList">Hai creato una lista broadcast</string>
<string name="AddRecipient">Aggiungi Destinatario</string>
<string name="KickFromBroadcast">Rimuovi dalla lista broadcast</string>
<!--documents view--> <!--documents view-->
<string name="SelectFile">Seleziona file</string> <string name="SelectFile">Seleziona file</string>
<string name="FreeOfTotal">Liberi %1$s di %2$s</string> <string name="FreeOfTotal">Liberi %1$s di %2$s</string>
...@@ -150,7 +158,7 @@ ...@@ -150,7 +158,7 @@
<string name="NotificationGroupKickYou">%1$s ti ha rimosso dal gruppo %2$s</string> <string name="NotificationGroupKickYou">%1$s ti ha rimosso dal gruppo %2$s</string>
<string name="NotificationGroupLeftMember">%1$s ha lasciato il gruppo %2$s</string> <string name="NotificationGroupLeftMember">%1$s ha lasciato il gruppo %2$s</string>
<string name="NotificationContactJoined">%1$s ha iniziato a usare Telegram!</string> <string name="NotificationContactJoined">%1$s ha iniziato a usare Telegram!</string>
<string name="NotificationUnrecognizedDevice">%1$s,\nAbbiamo rilevato un accesso al tuo account da un nuovo dispositivo %2$s\n\nDispositivo: %3$s\nPosizione: %4$s\n\nSe non sei stato tu, puoi andare su Impostazioni - Termina tutte le sessioni.\n\nGrazie,\nla squadra di Telegram</string> <string name="NotificationUnrecognizedDevice">%1$s,\nAbbiamo rilevato un accesso al tuo account da un nuovo dispositivo %2$s\n\nDispositivo: %3$s\nPosizione: %4$s\n\nSe non sei stato tu, puoi andare su Impostazioni - Termina tutte le sessioni.\n\nGrazie,\nIl Team di Telegram</string>
<string name="NotificationContactNewPhoto">%1$s ha aggiornato la foto del profilo</string> <string name="NotificationContactNewPhoto">%1$s ha aggiornato la foto del profilo</string>
<!--contacts view--> <!--contacts view-->
...@@ -263,19 +271,19 @@ ...@@ -263,19 +271,19 @@
<string name="Enabled">Abilitato</string> <string name="Enabled">Abilitato</string>
<string name="Disabled">Disabilitato</string> <string name="Disabled">Disabilitato</string>
<string name="NotificationsService">Servizio notifiche</string> <string name="NotificationsService">Servizio notifiche</string>
<string name="NotificationsServiceDisableInfo">Se i servizi di Google Play ti bastano per ricevere le notifiche, puoi disabilitare il Servizio notifiche. Tuttavia sarebbe meglio lasciarlo abilitato al fine di mantenere l\'applicazione attiva in background e ricevere notifiche istantanee.</string> <string name="NotificationsServiceDisableInfo">Se i servizi di Google Play sono sufficienti per ricevere le notifiche, è possibile disabilitare il Servizio Notifiche. Ti raccomandiamo comunque di lasciarlo abilitato per lasciare l\'app attiva in background e ricevere le notifiche istantanee.</string>
<string name="SortBy">Ordina per</string> <string name="SortBy">Ordina per</string>
<string name="ImportContacts">Importa contatti</string> <string name="ImportContacts">Importa contatti</string>
<string name="WiFiOnly">Solo tramite WiFi</string> <string name="WiFiOnly">Solo tramite WiFi</string>
<string name="SortFirstName">Nome</string> <string name="SortFirstName">Nome</string>
<string name="SortLastName">Cognome</string> <string name="SortLastName">Cognome</string>
<string name="LedColor">Colore LED</string> <string name="LedColor">Colore LED</string>
<string name="PopupNotification">Notifica popup</string> <string name="PopupNotification">Notifiche Popup</string>
<string name="NoPopup">Nessun popup</string> <string name="NoPopup">Nessun popup</string>
<string name="OnlyWhenScreenOn">Solo con schermo acceso</string> <string name="OnlyWhenScreenOn">Solo con schermo acceso</string>
<string name="OnlyWhenScreenOff">Solo con schermo spento</string> <string name="OnlyWhenScreenOff">Solo con schermo spento</string>
<string name="AlwaysShowPopup">Mostra sempre i popup</string> <string name="AlwaysShowPopup">Mostra sempre i popup</string>
<string name="BadgeNumber">Badge Number</string> <string name="BadgeNumber">Contatore Badge</string>
<!--media view--> <!--media view-->
<string name="NoMedia">Nessun media condiviso</string> <string name="NoMedia">Nessun media condiviso</string>
...@@ -300,9 +308,9 @@ ...@@ -300,9 +308,9 @@
<string name="NoPhotos">Ancora nessuna foto</string> <string name="NoPhotos">Ancora nessuna foto</string>
<!--edit video view--> <!--edit video view-->
<string name="EditVideo">Edit Video</string> <string name="EditVideo">Modifica Video</string>
<string name="OriginalVideo">Original Video</string> <string name="OriginalVideo">Video Originale</string>
<string name="EditedVideo">Edited Video</string> <string name="EditedVideo">Video Modificato</string>
<!--button titles--> <!--button titles-->
<string name="Next">Avanti</string> <string name="Next">Avanti</string>
...@@ -362,8 +370,8 @@ ...@@ -362,8 +370,8 @@
<string name="InvalidLastName">Cognome non valido</string> <string name="InvalidLastName">Cognome non valido</string>
<string name="Loading">Caricamento…</string> <string name="Loading">Caricamento…</string>
<string name="NoPlayerInstalled">Non hai un lettore video, per favore installane uno per continuare</string> <string name="NoPlayerInstalled">Non hai un lettore video, per favore installane uno per continuare</string>
<string name="NoMailInstalled">Invia un’email a sms@telegram.org spiegandoci il problema.</string> <string name="NoMailInstalled">Invia un’email a sms@telegram.org e parlaci del tuo problema.</string>
<string name="NoHandleAppInstalled">Non hai nessuna applicazione che può gestire il tipo mime \'%1$s\', installane una per continuare</string> <string name="NoHandleAppInstalled">Nessuna applicazione può gestire il tipo di file \'%1$s\', per favore installane una per proseguire</string>
<string name="InviteUser">Questo utente non ha ancora Telegram, vuoi invitarlo?</string> <string name="InviteUser">Questo utente non ha ancora Telegram, vuoi invitarlo?</string>
<string name="AreYouSure">Sei sicuro?</string> <string name="AreYouSure">Sei sicuro?</string>
<string name="AddContactQ">Vuoi aggiungere il contatto?</string> <string name="AddContactQ">Vuoi aggiungere il contatto?</string>
...@@ -375,7 +383,7 @@ ...@@ -375,7 +383,7 @@
<string name="AreYouSureSessions">Chiudere tutte le altre sessioni?</string> <string name="AreYouSureSessions">Chiudere tutte le altre sessioni?</string>
<string name="AreYouSureDeleteAndExit">Eliminare il gruppo e uscire da esso?</string> <string name="AreYouSureDeleteAndExit">Eliminare il gruppo e uscire da esso?</string>
<string name="AreYouSureDeleteThisChat">Eliminare questa chat?</string> <string name="AreYouSureDeleteThisChat">Eliminare questa chat?</string>
<string name="AreYouSureShareMyContactInfo">Condividere le proprie informazioni di contatto?</string> <string name="AreYouSureShareMyContactInfo">Condividere le informazioni del proprio contatto?</string>
<string name="AreYouSureBlockContact">Bloccare questo contatto?</string> <string name="AreYouSureBlockContact">Bloccare questo contatto?</string>
<string name="AreYouSureUnblockContact">Sbloccare questo contatto?</string> <string name="AreYouSureUnblockContact">Sbloccare questo contatto?</string>
<string name="AreYouSureDeleteContact">Eliminare questo contatto?</string> <string name="AreYouSureDeleteContact">Eliminare questo contatto?</string>
......
...@@ -57,6 +57,14 @@ ...@@ -57,6 +57,14 @@
<string name="HiddenName">Verborgen naam</string> <string name="HiddenName">Verborgen naam</string>
<string name="SelectChat">Kies een gesprek</string> <string name="SelectChat">Kies een gesprek</string>
<!--broadcasts-->
<string name="BroadcastList">Verzendlijst</string>
<string name="NewBroadcastList">Nieuwe verzendlijst</string>
<string name="EnterListName">Naam van lijst</string>
<string name="YouCreatedBroadcastList">Je hebt een verzendlijst gemaakt</string>
<string name="AddRecipient">Ontvanger toevoegen</string>
<string name="KickFromBroadcast">Verwijder van verzendlijst</string>
<!--documents view--> <!--documents view-->
<string name="SelectFile">Kies een bestand</string> <string name="SelectFile">Kies een bestand</string>
<string name="FreeOfTotal">Vrij: %1$s van %2$s</string> <string name="FreeOfTotal">Vrij: %1$s van %2$s</string>
...@@ -110,7 +118,7 @@ ...@@ -110,7 +118,7 @@
<string name="SlideToCancel">SLEEP OM TE ANNULEREN</string> <string name="SlideToCancel">SLEEP OM TE ANNULEREN</string>
<string name="SaveToDownloads">Opslaan in Downloads</string> <string name="SaveToDownloads">Opslaan in Downloads</string>
<string name="ApplyLocalizationFile">Vertaling toepassen</string> <string name="ApplyLocalizationFile">Vertaling toepassen</string>
<string name="UnsupportedAttachment">Bijlageformaat niet ondersteund</string> <string name="UnsupportedAttachment">Bestandstype niet ondersteund</string>
<!--notification--> <!--notification-->
<string name="EncryptedChatRequested">Privégesprek aangevraagd</string> <string name="EncryptedChatRequested">Privégesprek aangevraagd</string>
...@@ -150,7 +158,7 @@ ...@@ -150,7 +158,7 @@
<string name="NotificationGroupKickYou">%1$s heeft je verwijderd uit de groep %2$s</string> <string name="NotificationGroupKickYou">%1$s heeft je verwijderd uit de groep %2$s</string>
<string name="NotificationGroupLeftMember">%1$s heeft de groep %2$s verlaten</string> <string name="NotificationGroupLeftMember">%1$s heeft de groep %2$s verlaten</string>
<string name="NotificationContactJoined">%1$s heeft nu Telegram!</string> <string name="NotificationContactJoined">%1$s heeft nu Telegram!</string>
<string name="NotificationUnrecognizedDevice">%1$s,\nEr is op je account ingelogd vanaf een nieuw apparaat op %2$s\n\nApparaat: %3$s\nLocatie: %4$s\n\nAls jij dit niet was, kun je alle sessies beëindigen via Instellingen – Alle andere sessies beëindigen.\n\nHet Telegram-team</string> <string name="NotificationUnrecognizedDevice">%1$s,\nEr is op je account ingelogd vanaf een nieuw apparaat op %2$s\n\nApparaat: %3$s\nLocatie: %4$s\n\nAls jij dit niet was, kun je alle sessies beëindigen via Instellingen – Beëindig alle andere sessies.\n\nBedankt,\nHet Telegram-team</string>
<string name="NotificationContactNewPhoto">%1$s heeft zijn/haar profielfoto gewijzigd</string> <string name="NotificationContactNewPhoto">%1$s heeft zijn/haar profielfoto gewijzigd</string>
<!--contacts view--> <!--contacts view-->
...@@ -245,7 +253,7 @@ ...@@ -245,7 +253,7 @@
<string name="ChatBackground">Achtergrond gesprekken</string> <string name="ChatBackground">Achtergrond gesprekken</string>
<string name="MessagesSettings">BERICHTEN</string> <string name="MessagesSettings">BERICHTEN</string>
<string name="SendByEnter">Verzenden met Enter</string> <string name="SendByEnter">Verzenden met Enter</string>
<string name="TerminateAllSessions">Alle andere sessies beëindigen</string> <string name="TerminateAllSessions">Beëindig alle andere sessies</string>
<string name="AutomaticPhotoDownload">FOTO\'S AUTOMATISCH DOWNLOADEN</string> <string name="AutomaticPhotoDownload">FOTO\'S AUTOMATISCH DOWNLOADEN</string>
<string name="AutomaticAudioDownload">GELUIDSBESTANDEN AUTOMATISCH DOWNLOADEN</string> <string name="AutomaticAudioDownload">GELUIDSBESTANDEN AUTOMATISCH DOWNLOADEN</string>
<string name="AutomaticPhotoDownloadGroups">Groepen</string> <string name="AutomaticPhotoDownloadGroups">Groepen</string>
...@@ -263,19 +271,19 @@ ...@@ -263,19 +271,19 @@
<string name="Enabled">Inschakelen</string> <string name="Enabled">Inschakelen</string>
<string name="Disabled">Uitschakelen</string> <string name="Disabled">Uitschakelen</string>
<string name="NotificationsService">Meldingenservice</string> <string name="NotificationsService">Meldingenservice</string>
<string name="NotificationsServiceDisableInfo">Als google play services genoeg is om notificaties te ontvangen, kan de meldingenservice worden uitgeschakeld. Echter, we adviseren de service ingeschakeld te laten zodat de app in de achtergrond blijft draaien en meldingen direct worden ontvangen.</string> <string name="NotificationsServiceDisableInfo">Als Google Play Services genoeg voor je is om meldingen te ontvangen kun je de Meldingenservice uitschakelen. We raden echter aan dit ingeschakeld te laten om de app in de achtergrond te laten draaien en directe meldingen te ontvangen.</string>
<string name="SortBy">Sorteren op</string> <string name="SortBy">Sorteren op</string>
<string name="ImportContacts">Importeer contacten</string> <string name="ImportContacts">Importeer contacten</string>
<string name="WiFiOnly">Alleen via WiFi</string> <string name="WiFiOnly">Alleen via WiFi</string>
<string name="SortFirstName">Voornaam</string> <string name="SortFirstName">Voornaam</string>
<string name="SortLastName">Achternaam</string> <string name="SortLastName">Achternaam</string>
<string name="LedColor">LED kleur</string> <string name="LedColor">LED kleur</string>
<string name="PopupNotification">Popup melding</string> <string name="PopupNotification">Popup meldingen</string>
<string name="NoPopup">Geen popup</string> <string name="NoPopup">Geen popup</string>
<string name="OnlyWhenScreenOn">Alleen wanneer scherm \"aan\" staat</string> <string name="OnlyWhenScreenOn">Alleen wanneer scherm \"aan\" staat</string>
<string name="OnlyWhenScreenOff">Alleen wanneer scherm \"uit\" staat</string> <string name="OnlyWhenScreenOff">Alleen wanneer scherm \"uit\" staat</string>
<string name="AlwaysShowPopup">Altijd popup tonen</string> <string name="AlwaysShowPopup">Altijd popup tonen</string>
<string name="BadgeNumber">Badge Number</string> <string name="BadgeNumber">Badgenummer</string>
<!--media view--> <!--media view-->
<string name="NoMedia">Nog geen media gedeeld</string> <string name="NoMedia">Nog geen media gedeeld</string>
...@@ -300,9 +308,9 @@ ...@@ -300,9 +308,9 @@
<string name="NoPhotos">Nog geen foto\'s</string> <string name="NoPhotos">Nog geen foto\'s</string>
<!--edit video view--> <!--edit video view-->
<string name="EditVideo">Edit Video</string> <string name="EditVideo">Video bewerken</string>
<string name="OriginalVideo">Original Video</string> <string name="OriginalVideo">Originele video</string>
<string name="EditedVideo">Edited Video</string> <string name="EditedVideo">Bewerkte video</string>
<!--button titles--> <!--button titles-->
<string name="Next">Volgende</string> <string name="Next">Volgende</string>
...@@ -362,8 +370,8 @@ ...@@ -362,8 +370,8 @@
<string name="InvalidLastName">Ongeldige achternaam</string> <string name="InvalidLastName">Ongeldige achternaam</string>
<string name="Loading">Bezig met laden…</string> <string name="Loading">Bezig met laden…</string>
<string name="NoPlayerInstalled">Je hebt geen mediaspeler. Installeer een mediaspeler om door te gaan.</string> <string name="NoPlayerInstalled">Je hebt geen mediaspeler. Installeer een mediaspeler om door te gaan.</string>
<string name="NoMailInstalled">Stuur aub een emailbericht naar sms@telegram.org en beschrijf uw probleem</string> <string name="NoMailInstalled">Mail ons op sms@telegram.org en vertel ons over je probleem.</string>
<string name="NoHandleAppInstalled">Je hebt geen applicaties die het MIME-type \'%1$s\' ondersteunen. Installeer een geschikte applicatie om door te gaan.</string> <string name="NoHandleAppInstalled">Je hebt geen apps die bestandstype \'%1$s\' kunnen verwerken, gelieve een compitabele app te installeren</string>
<string name="InviteUser">Deze gebruiker heeft nog geen Telegram. Wil je een uitnodiging sturen?</string> <string name="InviteUser">Deze gebruiker heeft nog geen Telegram. Wil je een uitnodiging sturen?</string>
<string name="AreYouSure">Weet je het zeker?</string> <string name="AreYouSure">Weet je het zeker?</string>
<string name="AddContactQ">Contact toevoegen?</string> <string name="AddContactQ">Contact toevoegen?</string>
...@@ -371,15 +379,15 @@ ...@@ -371,15 +379,15 @@
<string name="ForwardMessagesTo">Berichten doorsturen naar %1$s?</string> <string name="ForwardMessagesTo">Berichten doorsturen naar %1$s?</string>
<string name="DeleteChatQuestion">Dit gesprek verwijderen?</string> <string name="DeleteChatQuestion">Dit gesprek verwijderen?</string>
<string name="SendMessagesTo">Berichten naar %1$s verzenden?</string> <string name="SendMessagesTo">Berichten naar %1$s verzenden?</string>
<string name="AreYouSureLogout">Weet u zeker dat u wil uitloggen?</string> <string name="AreYouSureLogout">Weet je zeker dat je wilt uitloggen?</string>
<string name="AreYouSureSessions">Alle andere apparaten afmelden?</string> <string name="AreYouSureSessions">Weet je zeker dat je alle andere sessies wilt beëindigen?</string>
<string name="AreYouSureDeleteAndExit">Deze groep verlaten en groep verwijderen?</string> <string name="AreYouSureDeleteAndExit">Weet je zeker dat je alles wilt verwijderen en de groep wilt verlaten?</string>
<string name="AreYouSureDeleteThisChat">Dit gesprek verwijderen?</string> <string name="AreYouSureDeleteThisChat">Weet je zeker dat je dit gesprek wilt verwijderen?</string>
<string name="AreYouSureShareMyContactInfo">Deze contact-informatie delen?</string> <string name="AreYouSureShareMyContactInfo">Weet je zeker dat je je contactinformatie wilt delen?</string>
<string name="AreYouSureBlockContact">Deze persoon blokkeren?</string> <string name="AreYouSureBlockContact">Weet je zeker dat je deze persoon wilt blokkeren?</string>
<string name="AreYouSureUnblockContact">Deze persoon deblokkeren?</string> <string name="AreYouSureUnblockContact">Weet je zeker dat je deze persoon wilt deblokkeren?</string>
<string name="AreYouSureDeleteContact">Deze contactpersoon verwijderen?</string> <string name="AreYouSureDeleteContact">Weet je zeker dat je deze contactpersoon wilt verwijderen?</string>
<string name="AreYouSureSecretChat">Een privégesprek starten?</string> <string name="AreYouSureSecretChat">Weet je zeker dat je een privégesprek wilt starten?</string>
<string name="ForwardFromMyName">doorsturen via mijn eigen naam</string> <string name="ForwardFromMyName">doorsturen via mijn eigen naam</string>
<!--Intro view--> <!--Intro view-->
...@@ -396,7 +404,7 @@ ...@@ -396,7 +404,7 @@
<string name="Page4Message"><![CDATA[<b>Telegram</b>]]> beveiligt je berichten tegen hackers</string> <string name="Page4Message"><![CDATA[<b>Telegram</b>]]> beveiligt je berichten tegen hackers</string>
<string name="Page5Message"><![CDATA[<b>Telegram</b>]]> heeft geen beperkingen op de grootte van je media en gesprekken</string> <string name="Page5Message"><![CDATA[<b>Telegram</b>]]> heeft geen beperkingen op de grootte van je media en gesprekken</string>
<string name="Page6Message"><![CDATA[<b>Telegram</b>]]> biedt toegang tot je berichten vanaf meerdere apparaten</string> <string name="Page6Message"><![CDATA[<b>Telegram</b>]]> biedt toegang tot je berichten vanaf meerdere apparaten</string>
<string name="Page7Message"><![CDATA[<b>Telegram</b>]]> berichten zijn sterk versleuteld en kunnen zichzelf vernietigen</string> <string name="Page7Message"><![CDATA[<b>Telegram</b>]]> berichten zijn sterk versleuteld<![CDATA[<br/>]]>en kunnen zichzelf vernietigen</string>
<string name="StartMessaging">Begin nu met chatten</string> <string name="StartMessaging">Begin nu met chatten</string>
<!--plurals--> <!--plurals-->
......
...@@ -57,6 +57,14 @@ ...@@ -57,6 +57,14 @@
<string name="HiddenName">Nome oculto</string> <string name="HiddenName">Nome oculto</string>
<string name="SelectChat">Selecione uma Conversa</string> <string name="SelectChat">Selecione uma Conversa</string>
<!--broadcasts-->
<string name="BroadcastList">Lista de Broadcast</string>
<string name="NewBroadcastList">Nova lista de Broadcast</string>
<string name="EnterListName">Digite o nome da lista</string>
<string name="YouCreatedBroadcastList">Você criou uma lista de broadcast</string>
<string name="AddRecipient">Adicionar Recipiente</string>
<string name="KickFromBroadcast">Remover da lista de broadcast</string>
<!--documents view--> <!--documents view-->
<string name="SelectFile">Selecione um Arquivo</string> <string name="SelectFile">Selecione um Arquivo</string>
<string name="FreeOfTotal">Disponível %1$s de %2$s</string> <string name="FreeOfTotal">Disponível %1$s de %2$s</string>
...@@ -150,7 +158,7 @@ ...@@ -150,7 +158,7 @@
<string name="NotificationGroupKickYou">%1$s removeu você do grupo %2$s</string> <string name="NotificationGroupKickYou">%1$s removeu você do grupo %2$s</string>
<string name="NotificationGroupLeftMember">%1$s saiu do grupo %2$s</string> <string name="NotificationGroupLeftMember">%1$s saiu do grupo %2$s</string>
<string name="NotificationContactJoined">%1$s entrou para o Telegram!</string> <string name="NotificationContactJoined">%1$s entrou para o Telegram!</string>
<string name="NotificationUnrecognizedDevice">%1$s,\nNós detectamos um acesso à sua conta de um novo dispositivo em %2$s\n\nDispositivo: %3$s\nLocalização: %4$s\n\nCaso não tenha sido você, vá para Configurações – Encerrar todas as sessões.\n\nObrigado,\nA equipe do Telegram</string> <string name="NotificationUnrecognizedDevice">%1$s,\nNós detectamos um login na sua conta de um novo dispositivo %2$s\n\nDispositivo: %3$s\nLocalização: %4$s\n\nSe não foi você, você pode ir para Configurações - Terminar todas as sessões.\n\nAtenciosamente,\nTime do Telegram</string>
<string name="NotificationContactNewPhoto">%1$s atualizou a foto do perfil</string> <string name="NotificationContactNewPhoto">%1$s atualizou a foto do perfil</string>
<!--contacts view--> <!--contacts view-->
...@@ -263,19 +271,19 @@ ...@@ -263,19 +271,19 @@
<string name="Enabled">Ativado</string> <string name="Enabled">Ativado</string>
<string name="Disabled">Desativado</string> <string name="Disabled">Desativado</string>
<string name="NotificationsService">Serviço de Notificações</string> <string name="NotificationsService">Serviço de Notificações</string>
<string name="NotificationsServiceDisableInfo">Se os serviços do Google Play forem suficientes para você receber as notificações, você pode desabilitar o \"Serviço de Notificações\". Porém, nós recomendamos deixá-lo ativo para que o aplicativo continue rodando em segundo plano e recebendo notificações instantâneas.</string> <string name="NotificationsServiceDisableInfo">Se o serviço de notificação do Google Play é o suficiente para você, você pode desativar as Notificações de Serviço. No entanto, recomendamos que você deixá-lo habilitado para manter o aplicativo em execução em segundo plano e receber notificações instantâneas.</string>
<string name="SortBy">Ordenar Por</string> <string name="SortBy">Ordenar Por</string>
<string name="ImportContacts">Importar Contatos</string> <string name="ImportContacts">Importar Contatos</string>
<string name="WiFiOnly">Apenas por WiFi</string> <string name="WiFiOnly">Apenas por WiFi</string>
<string name="SortFirstName">Primeiro nome</string> <string name="SortFirstName">Primeiro nome</string>
<string name="SortLastName">Sobrenome</string> <string name="SortLastName">Sobrenome</string>
<string name="LedColor">Cor do LED</string> <string name="LedColor">Cor do LED</string>
<string name="PopupNotification">Notificação Popup</string> <string name="PopupNotification">Notificações Popup</string>
<string name="NoPopup">Sem popup</string> <string name="NoPopup">Sem popup</string>
<string name="OnlyWhenScreenOn">Somente com a tela ligada</string> <string name="OnlyWhenScreenOn">Somente com a tela ligada</string>
<string name="OnlyWhenScreenOff">Somente com a tela desligada</string> <string name="OnlyWhenScreenOff">Somente com a tela desligada</string>
<string name="AlwaysShowPopup">Sempre mostrar popup</string> <string name="AlwaysShowPopup">Sempre mostrar popup</string>
<string name="BadgeNumber">Badge Number</string> <string name="BadgeNumber">Contador de medalhas</string>
<!--media view--> <!--media view-->
<string name="NoMedia">Ainda não há mídia compartilhada</string> <string name="NoMedia">Ainda não há mídia compartilhada</string>
...@@ -300,9 +308,9 @@ ...@@ -300,9 +308,9 @@
<string name="NoPhotos">Ainda não há fotos</string> <string name="NoPhotos">Ainda não há fotos</string>
<!--edit video view--> <!--edit video view-->
<string name="EditVideo">Edit Video</string> <string name="EditVideo">Editar Vídeo</string>
<string name="OriginalVideo">Original Video</string> <string name="OriginalVideo">Vídeo Original</string>
<string name="EditedVideo">Edited Video</string> <string name="EditedVideo">Vídeo Editado</string>
<!--button titles--> <!--button titles-->
<string name="Next">Próximo</string> <string name="Next">Próximo</string>
...@@ -362,8 +370,8 @@ ...@@ -362,8 +370,8 @@
<string name="InvalidLastName">Sobrenome inválido</string> <string name="InvalidLastName">Sobrenome inválido</string>
<string name="Loading">Carregando...</string> <string name="Loading">Carregando...</string>
<string name="NoPlayerInstalled">Você não possui um reprodutor de vídeo, instale um para continuar</string> <string name="NoPlayerInstalled">Você não possui um reprodutor de vídeo, instale um para continuar</string>
<string name="NoMailInstalled">Por favor, envie um email para sms@telegram.org e explique seu problema.</string> <string name="NoMailInstalled">Por favor, envie um email para sms@telegram.org e conte-nos sobre seu problema.</string>
<string name="NoHandleAppInstalled">Você não possui algum aplicativo que pode lidar com o tipo MIME \'%1$s\'. Por favor, instale um para continuar</string> <string name="NoHandleAppInstalled">Você não possui uma aplicação que suporte o tipo de arquivo \'%1$s\', por favor instale uma e continue</string>
<string name="InviteUser">Este usuário ainda não possui Telegram, deseja enviar um convite?</string> <string name="InviteUser">Este usuário ainda não possui Telegram, deseja enviar um convite?</string>
<string name="AreYouSure">Você tem certeza?</string> <string name="AreYouSure">Você tem certeza?</string>
<string name="AddContactQ">Adicionar contato?</string> <string name="AddContactQ">Adicionar contato?</string>
...@@ -371,15 +379,15 @@ ...@@ -371,15 +379,15 @@
<string name="ForwardMessagesTo">Encaminhar mensagem para %1$s?</string> <string name="ForwardMessagesTo">Encaminhar mensagem para %1$s?</string>
<string name="DeleteChatQuestion">Apagar esta conversa?</string> <string name="DeleteChatQuestion">Apagar esta conversa?</string>
<string name="SendMessagesTo">Enviar mensagens para %1$s?</string> <string name="SendMessagesTo">Enviar mensagens para %1$s?</string>
<string name="AreYouSureLogout">Você tem certeza que deseja sair dessa sessão?</string> <string name="AreYouSureLogout">Você tem certeza que deseja sair?</string>
<string name="AreYouSureSessions">Você tem certeza que deseja terminar todas as outras sessões?</string> <string name="AreYouSureSessions">Você tem certeza que deseja terminar todas as outras sessões?</string>
<string name="AreYouSureDeleteAndExit">Você tem certeza que deseja deletar e sair do grupo?</string> <string name="AreYouSureDeleteAndExit">Você tem certeza que deseja deletar e sair do grupo?</string>
<string name="AreYouSureDeleteThisChat">Você tem certeza que deseja deletar esta conversa?</string> <string name="AreYouSureDeleteThisChat">Você tem certeza que deseja deletar esta conversa?</string>
<string name="AreYouSureShareMyContactInfo">Você tem certeza que deseja compartilhar as informações do seu contato?</string> <string name="AreYouSureShareMyContactInfo">Você tem certesa que deseja compartilhar suas informações de contato?</string>
<string name="AreYouSureBlockContact">Você tem certeza que deseja bloquear este contato?</string> <string name="AreYouSureBlockContact">Você tem certeza que deseja bloquear este contato?</string>
<string name="AreYouSureUnblockContact">Você tem certeza que deseja desbloquear este contato?</string> <string name="AreYouSureUnblockContact">Você tem certeza que deseja desbloquear este contato?</string>
<string name="AreYouSureDeleteContact">Você tem certeza que deseja deletar este contato?</string> <string name="AreYouSureDeleteContact">Você tem certeza que deseja deletar este contato?</string>
<string name="AreYouSureSecretChat">Você tem certeza que deseja iniciar uma conversa secreta?</string> <string name="AreYouSureSecretChat">Você tem certeza que deseja começar uma conversa secreta?</string>
<string name="ForwardFromMyName">encaminhar pelo meu nome</string> <string name="ForwardFromMyName">encaminhar pelo meu nome</string>
<!--Intro view--> <!--Intro view-->
...@@ -396,7 +404,7 @@ ...@@ -396,7 +404,7 @@
<string name="Page4Message"><![CDATA[<b>Telegram</b>]]> mantém suas mensagens seguras contra ataques de hackers</string> <string name="Page4Message"><![CDATA[<b>Telegram</b>]]> mantém suas mensagens seguras contra ataques de hackers</string>
<string name="Page5Message"><![CDATA[<b>Telegram</b>]]> não tem limites para o tamanho de suas mídias e conversas</string> <string name="Page5Message"><![CDATA[<b>Telegram</b>]]> não tem limites para o tamanho de suas mídias e conversas</string>
<string name="Page6Message"><![CDATA[<b>Telegram</b>]]> permite que você acesse suas mensagens a partir de vários dispositivos</string> <string name="Page6Message"><![CDATA[<b>Telegram</b>]]> permite que você acesse suas mensagens a partir de vários dispositivos</string>
<string name="Page7Message">As mensagens do <![CDATA[<b>Telegram</b>]]> são fortemente criptografadas e podem se autodestruir</string> <string name="Page7Message">As mensagens do <![CDATA[<b>Telegram</b>]]> são fortemente criptografadas<![CDATA[<br/>]]>e podem se autodestruir</string>
<string name="StartMessaging">Comece a conversar</string> <string name="StartMessaging">Comece a conversar</string>
<!--plurals--> <!--plurals-->
......
...@@ -57,6 +57,14 @@ ...@@ -57,6 +57,14 @@
<string name="HiddenName">Nome oculto</string> <string name="HiddenName">Nome oculto</string>
<string name="SelectChat">Selecionar chat</string> <string name="SelectChat">Selecionar chat</string>
<!--broadcasts-->
<string name="BroadcastList">Broadcast List</string>
<string name="NewBroadcastList">New Broadcast List</string>
<string name="EnterListName">Enter list name</string>
<string name="YouCreatedBroadcastList">You created a broadcast list</string>
<string name="AddRecipient">Add Recipient</string>
<string name="KickFromBroadcast">Remove from broadcast list</string>
<!--documents view--> <!--documents view-->
<string name="SelectFile">Selecionar ficheiro</string> <string name="SelectFile">Selecionar ficheiro</string>
<string name="FreeOfTotal">%1$s de %2$s livres</string> <string name="FreeOfTotal">%1$s de %2$s livres</string>
......
...@@ -57,6 +57,14 @@ ...@@ -57,6 +57,14 @@
<string name="HiddenName">Hidden Name</string> <string name="HiddenName">Hidden Name</string>
<string name="SelectChat">Select Chat</string> <string name="SelectChat">Select Chat</string>
<!--broadcasts-->
<string name="BroadcastList">Broadcast List</string>
<string name="NewBroadcastList">New Broadcast List</string>
<string name="EnterListName">Enter list name</string>
<string name="YouCreatedBroadcastList">You created a broadcast list</string>
<string name="AddRecipient">Add Recipient</string>
<string name="KickFromBroadcast">Remove from broadcast list</string>
<!--documents view--> <!--documents view-->
<string name="SelectFile">Select File</string> <string name="SelectFile">Select File</string>
<string name="FreeOfTotal">Free %1$s of %2$s</string> <string name="FreeOfTotal">Free %1$s of %2$s</string>
...@@ -150,7 +158,7 @@ ...@@ -150,7 +158,7 @@
<string name="NotificationGroupKickYou">%1$s removed you from the group %2$s</string> <string name="NotificationGroupKickYou">%1$s removed you from the group %2$s</string>
<string name="NotificationGroupLeftMember">%1$s has left the group %2$s</string> <string name="NotificationGroupLeftMember">%1$s has left the group %2$s</string>
<string name="NotificationContactJoined">%1$s joined Telegram!</string> <string name="NotificationContactJoined">%1$s joined Telegram!</string>
<string name="NotificationUnrecognizedDevice">%1$s,\nWe detected a login into your account from a new device on %2$s\n\nDevice: %3$s\nLocation: %4$s\n\nIf this wasn’t you, you can go to Settings – Terminate all sessions.\n\nThanks,\nThe Telegram Team</string> <string name="NotificationUnrecognizedDevice">%1$s,\nWe detected a login into your account from a new device on %2$s\n\nDevice: %3$s\nLocation: %4$s\n\nIf this wasn\'t you, you can go to Settings - Terminate all sessions.\n\nSincerely,\nThe Telegram Team</string>
<string name="NotificationContactNewPhoto">%1$s updated profile photo</string> <string name="NotificationContactNewPhoto">%1$s updated profile photo</string>
<!--contacts view--> <!--contacts view-->
...@@ -263,19 +271,19 @@ ...@@ -263,19 +271,19 @@
<string name="Enabled">Enabled</string> <string name="Enabled">Enabled</string>
<string name="Disabled">Disabled</string> <string name="Disabled">Disabled</string>
<string name="NotificationsService">Notifications Service</string> <string name="NotificationsService">Notifications Service</string>
<string name="NotificationsServiceDisableInfo">If google play services are enough for you to receive notifications, you can disable Notifications Service. However we recommend you to leave it enabled to keep app running in background and receive instant notifications.</string> <string name="NotificationsServiceDisableInfo">If Google Play Services are enough for you to receive notifications, you can disable Notifications Service. However we recommend you to leave it enabled to keep app running in background and receive instant notifications.</string>
<string name="SortBy">Sort By</string> <string name="SortBy">Sort By</string>
<string name="ImportContacts">Import Contacts</string> <string name="ImportContacts">Import Contacts</string>
<string name="WiFiOnly">Via WiFi only</string> <string name="WiFiOnly">Via WiFi only</string>
<string name="SortFirstName">First name</string> <string name="SortFirstName">First name</string>
<string name="SortLastName">Last name</string> <string name="SortLastName">Last name</string>
<string name="LedColor">LED Color</string> <string name="LedColor">LED Color</string>
<string name="PopupNotification">Popup Notification</string> <string name="PopupNotification">Popup Notifications</string>
<string name="NoPopup">No popup</string> <string name="NoPopup">No popup</string>
<string name="OnlyWhenScreenOn">Only when screen "on"</string> <string name="OnlyWhenScreenOn">Only when screen "on"</string>
<string name="OnlyWhenScreenOff">Only when screen "off"</string> <string name="OnlyWhenScreenOff">Only when screen "off"</string>
<string name="AlwaysShowPopup">Always show popup</string> <string name="AlwaysShowPopup">Always show popup</string>
<string name="BadgeNumber">Badge Number</string> <string name="BadgeNumber">Badge Counter</string>
<!--media view--> <!--media view-->
<string name="NoMedia">No shared media yet</string> <string name="NoMedia">No shared media yet</string>
...@@ -362,8 +370,8 @@ ...@@ -362,8 +370,8 @@
<string name="InvalidLastName">Invalid last name</string> <string name="InvalidLastName">Invalid last name</string>
<string name="Loading">Loading...</string> <string name="Loading">Loading...</string>
<string name="NoPlayerInstalled">You don\'t have a video player, please install one to continue</string> <string name="NoPlayerInstalled">You don\'t have a video player, please install one to continue</string>
<string name="NoMailInstalled">Please send an email to sms@telegram.org and explain your problem.</string> <string name="NoMailInstalled">Please send an email to sms@telegram.org and tell us about your problem.</string>
<string name="NoHandleAppInstalled">You don\'t have any application that can handle with mime type \'%1$s\', please install one to continue</string> <string name="NoHandleAppInstalled">You don\'t have applications that can handle the file type \'%1$s\', please install one to continue</string>
<string name="InviteUser">This user does not have Telegram yet, send an invitation?</string> <string name="InviteUser">This user does not have Telegram yet, send an invitation?</string>
<string name="AreYouSure">Are you sure?</string> <string name="AreYouSure">Are you sure?</string>
<string name="AddContactQ">Add contact?</string> <string name="AddContactQ">Add contact?</string>
...@@ -371,15 +379,15 @@ ...@@ -371,15 +379,15 @@
<string name="ForwardMessagesTo">Forward messages to %1$s?</string> <string name="ForwardMessagesTo">Forward messages to %1$s?</string>
<string name="DeleteChatQuestion">Delete this chat?</string> <string name="DeleteChatQuestion">Delete this chat?</string>
<string name="SendMessagesTo">Send messages to %1$s?</string> <string name="SendMessagesTo">Send messages to %1$s?</string>
<string name="AreYouSureLogout">Are you sure you want to logout?</string> <string name="AreYouSureLogout">Are you sure you want to log out?</string>
<string name="AreYouSureSessions">Are you sure you want to terminate all other sessions?</string> <string name="AreYouSureSessions">Are you sure you want to terminate all other sessions?</string>
<string name="AreYouSureDeleteAndExit">Are you sure you want to delete and leave group?</string> <string name="AreYouSureDeleteAndExit">Are you sure you want to delete and leave the group?</string>
<string name="AreYouSureDeleteThisChat">Are you sure you want to delete this chat?</string> <string name="AreYouSureDeleteThisChat">Are you sure you want to delete this chat?</string>
<string name="AreYouSureShareMyContactInfo">Are you sure that you want to share your contact info?</string> <string name="AreYouSureShareMyContactInfo">Are you sure you want to share your contact info?</string>
<string name="AreYouSureBlockContact">Are you sure you want to block this contact?</string> <string name="AreYouSureBlockContact">Are you sure you want to block this contact?</string>
<string name="AreYouSureUnblockContact">Are you sure you want to unblock this contact?</string> <string name="AreYouSureUnblockContact">Are you sure you want to unblock this contact?</string>
<string name="AreYouSureDeleteContact">Are you sure you want to delete this contact?</string> <string name="AreYouSureDeleteContact">Are you sure you want to delete this contact?</string>
<string name="AreYouSureSecretChat">Are you sure you want to start secret chat?</string> <string name="AreYouSureSecretChat">Are you sure you want to start a secret chat?</string>
<string name="ForwardFromMyName">forward from my name</string> <string name="ForwardFromMyName">forward from my name</string>
<!--Intro view--> <!--Intro view-->
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment