Search in sources :

Example 1 with SerializedData

use of org.telegram.tgnet.SerializedData in project Telegram-FOSS by Telegram-FOSS-Team.

the class SendMessagesHelper method prepareSendingMedia.

@UiThread
public static void prepareSendingMedia(AccountInstance accountInstance, ArrayList<SendingMediaInfo> media, long dialogId, MessageObject replyToMsg, MessageObject replyToTopMsg, InputContentInfoCompat inputContent, boolean forceDocument, boolean groupMedia, MessageObject editingMessageObject, boolean notify, int scheduleDate) {
    if (media.isEmpty()) {
        return;
    }
    for (int a = 0, N = media.size(); a < N; a++) {
        if (media.get(a).ttl > 0) {
            groupMedia = false;
            break;
        }
    }
    final boolean groupMediaFinal = groupMedia;
    mediaSendQueue.postRunnable(() -> {
        long beginTime = System.currentTimeMillis();
        HashMap<SendingMediaInfo, MediaSendPrepareWorker> workers;
        int count = media.size();
        boolean isEncrypted = DialogObject.isEncryptedDialog(dialogId);
        if (!forceDocument && groupMediaFinal) {
            workers = new HashMap<>();
            for (int a = 0; a < count; a++) {
                final SendingMediaInfo info = media.get(a);
                if (info.searchImage == null && !info.isVideo && info.videoEditedInfo == null) {
                    String originalPath = info.path;
                    String tempPath = info.path;
                    if (tempPath == null && info.uri != null) {
                        tempPath = AndroidUtilities.getPath(info.uri);
                        originalPath = info.uri.toString();
                    }
                    boolean isWebP = false;
                    if (tempPath != null && info.ttl <= 0 && (tempPath.endsWith(".gif") || (isWebP = tempPath.endsWith(".webp")))) {
                        if (!isWebP || shouldSendWebPAsSticker(tempPath, null)) {
                            continue;
                        } else {
                            info.forceImage = true;
                        }
                    } else if (ImageLoader.shouldSendImageAsDocument(info.path, info.uri)) {
                        continue;
                    } else if (tempPath == null && info.uri != null) {
                        if (MediaController.isGif(info.uri) || (isWebP = MediaController.isWebp(info.uri))) {
                            if (!isWebP || shouldSendWebPAsSticker(null, info.uri)) {
                                continue;
                            } else {
                                info.forceImage = true;
                            }
                        }
                    }
                    if (tempPath != null) {
                        File temp = new File(tempPath);
                        originalPath += temp.length() + "_" + temp.lastModified();
                    } else {
                        originalPath = null;
                    }
                    TLRPC.TL_photo photo = null;
                    String parentObject = null;
                    if (!isEncrypted && info.ttl == 0) {
                        Object[] sentData = accountInstance.getMessagesStorage().getSentFile(originalPath, !isEncrypted ? 0 : 3);
                        if (sentData != null && sentData[0] instanceof TLRPC.TL_photo) {
                            photo = (TLRPC.TL_photo) sentData[0];
                            parentObject = (String) sentData[1];
                        }
                        if (photo == null && info.uri != null) {
                            sentData = accountInstance.getMessagesStorage().getSentFile(AndroidUtilities.getPath(info.uri), !isEncrypted ? 0 : 3);
                            if (sentData != null && sentData[0] instanceof TLRPC.TL_photo) {
                                photo = (TLRPC.TL_photo) sentData[0];
                                parentObject = (String) sentData[1];
                            }
                        }
                        ensureMediaThumbExists(isEncrypted, photo, info.path, info.uri, 0);
                    }
                    final MediaSendPrepareWorker worker = new MediaSendPrepareWorker();
                    workers.put(info, worker);
                    if (photo != null) {
                        worker.parentObject = parentObject;
                        worker.photo = photo;
                    } else {
                        worker.sync = new CountDownLatch(1);
                        mediaSendThreadPool.execute(() -> {
                            worker.photo = accountInstance.getSendMessagesHelper().generatePhotoSizes(info.path, info.uri);
                            if (isEncrypted && info.canDeleteAfter) {
                                new File(info.path).delete();
                            }
                            worker.sync.countDown();
                        });
                    }
                }
            }
        } else {
            workers = null;
        }
        long groupId = 0;
        long lastGroupId = 0;
        ArrayList<String> sendAsDocuments = null;
        ArrayList<String> sendAsDocumentsOriginal = null;
        ArrayList<Uri> sendAsDocumentsUri = null;
        ArrayList<String> sendAsDocumentsCaptions = null;
        ArrayList<ArrayList<TLRPC.MessageEntity>> sendAsDocumentsEntities = null;
        String extension = null;
        int mediaCount = 0;
        for (int a = 0; a < count; a++) {
            final SendingMediaInfo info = media.get(a);
            if (groupMediaFinal && count > 1 && mediaCount % 10 == 0) {
                lastGroupId = groupId = Utilities.random.nextLong();
                mediaCount = 0;
            }
            if (info.searchImage != null && info.videoEditedInfo == null) {
                if (info.searchImage.type == 1) {
                    final HashMap<String, String> params = new HashMap<>();
                    TLRPC.TL_document document = null;
                    String parentObject = null;
                    File cacheFile;
                    if (info.searchImage.document instanceof TLRPC.TL_document) {
                        document = (TLRPC.TL_document) info.searchImage.document;
                        cacheFile = FileLoader.getPathToAttach(document, true);
                    } else {
                        /*if (!isEncrypted) {
                                Object[] sentData = getMessagesStorage().getSentFile(info.searchImage.imageUrl, !isEncrypted ? 1 : 4);
                                if (sentData != null && sentData[0] instanceof TLRPC.TL_document) {
                                    document = (TLRPC.TL_document) sentData[0];
                                    parentObject = (String) sentData[1];
                                }
                            }*/
                        String md5 = Utilities.MD5(info.searchImage.imageUrl) + "." + ImageLoader.getHttpUrlExtension(info.searchImage.imageUrl, "jpg");
                        cacheFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), md5);
                    }
                    if (document == null) {
                        File thumbFile = null;
                        document = new TLRPC.TL_document();
                        document.id = 0;
                        document.file_reference = new byte[0];
                        document.date = accountInstance.getConnectionsManager().getCurrentTime();
                        TLRPC.TL_documentAttributeFilename fileName = new TLRPC.TL_documentAttributeFilename();
                        fileName.file_name = "animation.gif";
                        document.attributes.add(fileName);
                        document.size = info.searchImage.size;
                        document.dc_id = 0;
                        if (!forceDocument && cacheFile.toString().endsWith("mp4")) {
                            document.mime_type = "video/mp4";
                            document.attributes.add(new TLRPC.TL_documentAttributeAnimated());
                        } else {
                            document.mime_type = "image/gif";
                        }
                        if (cacheFile.exists()) {
                            thumbFile = cacheFile;
                        } else {
                            cacheFile = null;
                        }
                        if (thumbFile == null) {
                            String thumb = Utilities.MD5(info.searchImage.thumbUrl) + "." + ImageLoader.getHttpUrlExtension(info.searchImage.thumbUrl, "jpg");
                            thumbFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), thumb);
                            if (!thumbFile.exists()) {
                                thumbFile = null;
                            }
                        }
                        if (thumbFile != null) {
                            try {
                                int side = isEncrypted || info.ttl != 0 ? 90 : 320;
                                Bitmap bitmap;
                                if (thumbFile.getAbsolutePath().endsWith("mp4")) {
                                    bitmap = SendMessagesHelper.createVideoThumbnail(thumbFile.getAbsolutePath(), MediaStore.Video.Thumbnails.MINI_KIND);
                                } else {
                                    bitmap = ImageLoader.loadBitmap(thumbFile.getAbsolutePath(), null, side, side, true);
                                }
                                if (bitmap != null) {
                                    TLRPC.PhotoSize thumb = ImageLoader.scaleAndSaveImage(bitmap, side, side, side > 90 ? 80 : 55, isEncrypted);
                                    if (thumb != null) {
                                        document.thumbs.add(thumb);
                                        document.flags |= 1;
                                    }
                                    bitmap.recycle();
                                }
                            } catch (Exception e) {
                                FileLog.e(e);
                            }
                        }
                        if (document.thumbs.isEmpty()) {
                            TLRPC.TL_photoSize thumb = new TLRPC.TL_photoSize();
                            thumb.w = info.searchImage.width;
                            thumb.h = info.searchImage.height;
                            thumb.size = 0;
                            thumb.location = new TLRPC.TL_fileLocationUnavailable();
                            thumb.type = "x";
                            document.thumbs.add(thumb);
                            document.flags |= 1;
                        }
                    }
                    final TLRPC.TL_document documentFinal = document;
                    final String parentFinal = parentObject;
                    final String originalPathFinal = info.searchImage.imageUrl;
                    final String pathFinal = cacheFile == null ? info.searchImage.imageUrl : cacheFile.toString();
                    if (params != null && info.searchImage.imageUrl != null) {
                        params.put("originalPath", info.searchImage.imageUrl);
                    }
                    if (parentFinal != null) {
                        params.put("parentObject", parentFinal);
                    }
                    AndroidUtilities.runOnUIThread(() -> {
                        if (editingMessageObject != null) {
                            accountInstance.getSendMessagesHelper().editMessage(editingMessageObject, null, null, documentFinal, pathFinal, params, false, parentFinal);
                        } else {
                            accountInstance.getSendMessagesHelper().sendMessage(documentFinal, null, pathFinal, dialogId, replyToMsg, replyToTopMsg, info.caption, info.entities, null, params, notify, scheduleDate, 0, parentFinal, null);
                        }
                    });
                } else {
                    boolean needDownloadHttp = true;
                    TLRPC.TL_photo photo = null;
                    String parentObject = null;
                    if (info.searchImage.photo instanceof TLRPC.TL_photo) {
                        photo = (TLRPC.TL_photo) info.searchImage.photo;
                    } else {
                        if (!isEncrypted && info.ttl == 0) {
                        /*Object[] sentData = getMessagesStorage().getSentFile(info.searchImage.imageUrl, !isEncrypted ? 0 : 3);
                                if (sentData != null) {
                                    photo = (TLRPC.TL_photo) sentData[0];
                                    parentObject = (String) sentData[1];
                                    ensureMediaThumbExists(currentAccount, photo, );
                                }*/
                        }
                    }
                    if (photo == null) {
                        String md5 = Utilities.MD5(info.searchImage.imageUrl) + "." + ImageLoader.getHttpUrlExtension(info.searchImage.imageUrl, "jpg");
                        File cacheFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), md5);
                        if (cacheFile.exists() && cacheFile.length() != 0) {
                            photo = accountInstance.getSendMessagesHelper().generatePhotoSizes(cacheFile.toString(), null);
                            if (photo != null) {
                                needDownloadHttp = false;
                            }
                        }
                        if (photo == null) {
                            md5 = Utilities.MD5(info.searchImage.thumbUrl) + "." + ImageLoader.getHttpUrlExtension(info.searchImage.thumbUrl, "jpg");
                            cacheFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), md5);
                            if (cacheFile.exists()) {
                                photo = accountInstance.getSendMessagesHelper().generatePhotoSizes(cacheFile.toString(), null);
                            }
                            if (photo == null) {
                                photo = new TLRPC.TL_photo();
                                photo.date = accountInstance.getConnectionsManager().getCurrentTime();
                                photo.file_reference = new byte[0];
                                TLRPC.TL_photoSize photoSize = new TLRPC.TL_photoSize();
                                photoSize.w = info.searchImage.width;
                                photoSize.h = info.searchImage.height;
                                photoSize.size = 0;
                                photoSize.location = new TLRPC.TL_fileLocationUnavailable();
                                photoSize.type = "x";
                                photo.sizes.add(photoSize);
                            }
                        }
                    }
                    if (photo != null) {
                        final TLRPC.TL_photo photoFinal = photo;
                        final String parentFinal = parentObject;
                        final boolean needDownloadHttpFinal = needDownloadHttp;
                        final HashMap<String, String> params = new HashMap<>();
                        if (info.searchImage.imageUrl != null) {
                            params.put("originalPath", info.searchImage.imageUrl);
                        }
                        if (parentFinal != null) {
                            params.put("parentObject", parentFinal);
                        }
                        if (groupMediaFinal) {
                            mediaCount++;
                            params.put("groupId", "" + groupId);
                            if (mediaCount == 10 || a == count - 1) {
                                params.put("final", "1");
                                lastGroupId = 0;
                            }
                        }
                        AndroidUtilities.runOnUIThread(() -> {
                            if (editingMessageObject != null) {
                                accountInstance.getSendMessagesHelper().editMessage(editingMessageObject, photoFinal, null, null, needDownloadHttpFinal ? info.searchImage.imageUrl : null, params, false, parentFinal);
                            } else {
                                accountInstance.getSendMessagesHelper().sendMessage(photoFinal, needDownloadHttpFinal ? info.searchImage.imageUrl : null, dialogId, replyToMsg, replyToTopMsg, info.caption, info.entities, null, params, notify, scheduleDate, info.ttl, parentFinal);
                            }
                        });
                    }
                }
            } else {
                if (info.isVideo || info.videoEditedInfo != null) {
                    Bitmap thumb = null;
                    String thumbKey = null;
                    final VideoEditedInfo videoEditedInfo;
                    if (forceDocument) {
                        videoEditedInfo = null;
                    } else {
                        videoEditedInfo = info.videoEditedInfo != null ? info.videoEditedInfo : createCompressionSettings(info.path);
                    }
                    if (!forceDocument && (videoEditedInfo != null || info.path.endsWith("mp4"))) {
                        if (info.path == null && info.searchImage != null) {
                            if (info.searchImage.photo instanceof TLRPC.TL_photo) {
                                info.path = FileLoader.getPathToAttach(info.searchImage.photo, true).getAbsolutePath();
                            } else {
                                String md5 = Utilities.MD5(info.searchImage.imageUrl) + "." + ImageLoader.getHttpUrlExtension(info.searchImage.imageUrl, "jpg");
                                info.path = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), md5).getAbsolutePath();
                            }
                        }
                        String path = info.path;
                        String originalPath = info.path;
                        File temp = new File(originalPath);
                        long startTime = 0;
                        boolean muted = false;
                        originalPath += temp.length() + "_" + temp.lastModified();
                        if (videoEditedInfo != null) {
                            muted = videoEditedInfo.muted;
                            originalPath += videoEditedInfo.estimatedDuration + "_" + videoEditedInfo.startTime + "_" + videoEditedInfo.endTime + (videoEditedInfo.muted ? "_m" : "");
                            if (videoEditedInfo.resultWidth != videoEditedInfo.originalWidth) {
                                originalPath += "_" + videoEditedInfo.resultWidth;
                            }
                            startTime = videoEditedInfo.startTime >= 0 ? videoEditedInfo.startTime : 0;
                        }
                        TLRPC.TL_document document = null;
                        String parentObject = null;
                        if (!isEncrypted && info.ttl == 0 && (videoEditedInfo == null || videoEditedInfo.filterState == null && videoEditedInfo.paintPath == null && videoEditedInfo.mediaEntities == null && videoEditedInfo.cropState == null)) {
                            Object[] sentData = accountInstance.getMessagesStorage().getSentFile(originalPath, !isEncrypted ? 2 : 5);
                            if (sentData != null && sentData[0] instanceof TLRPC.TL_document) {
                                document = (TLRPC.TL_document) sentData[0];
                                parentObject = (String) sentData[1];
                                ensureMediaThumbExists(isEncrypted, document, info.path, null, startTime);
                            }
                        }
                        if (document == null) {
                            if (info.thumbPath != null) {
                                thumb = BitmapFactory.decodeFile(info.thumbPath);
                            }
                            if (thumb == null) {
                                thumb = createVideoThumbnailAtTime(info.path, startTime);
                                if (thumb == null) {
                                    thumb = createVideoThumbnail(info.path, MediaStore.Video.Thumbnails.MINI_KIND);
                                }
                            }
                            TLRPC.PhotoSize size = null;
                            if (thumb != null) {
                                int side = isEncrypted || info.ttl != 0 ? 90 : Math.max(thumb.getWidth(), thumb.getHeight());
                                size = ImageLoader.scaleAndSaveImage(thumb, side, side, side > 90 ? 80 : 55, isEncrypted);
                                thumbKey = getKeyForPhotoSize(size, null, true, false);
                            }
                            document = new TLRPC.TL_document();
                            document.file_reference = new byte[0];
                            if (size != null) {
                                document.thumbs.add(size);
                                document.flags |= 1;
                            }
                            document.mime_type = "video/mp4";
                            accountInstance.getUserConfig().saveConfig(false);
                            TLRPC.TL_documentAttributeVideo attributeVideo;
                            if (isEncrypted) {
                                attributeVideo = new TLRPC.TL_documentAttributeVideo();
                            } else {
                                attributeVideo = new TLRPC.TL_documentAttributeVideo();
                                attributeVideo.supports_streaming = true;
                            }
                            document.attributes.add(attributeVideo);
                            if (videoEditedInfo != null && (videoEditedInfo.needConvert() || !info.isVideo)) {
                                if (info.isVideo && videoEditedInfo.muted) {
                                    fillVideoAttribute(info.path, attributeVideo, videoEditedInfo);
                                    videoEditedInfo.originalWidth = attributeVideo.w;
                                    videoEditedInfo.originalHeight = attributeVideo.h;
                                } else {
                                    attributeVideo.duration = (int) (videoEditedInfo.estimatedDuration / 1000);
                                }
                                int w, h;
                                int rotation = videoEditedInfo.rotationValue;
                                if (videoEditedInfo.cropState != null) {
                                    w = videoEditedInfo.cropState.transformWidth;
                                    h = videoEditedInfo.cropState.transformHeight;
                                } else {
                                    w = videoEditedInfo.resultWidth;
                                    h = videoEditedInfo.resultHeight;
                                }
                                if (rotation == 90 || rotation == 270) {
                                    attributeVideo.w = h;
                                    attributeVideo.h = w;
                                } else {
                                    attributeVideo.w = w;
                                    attributeVideo.h = h;
                                }
                                document.size = (int) videoEditedInfo.estimatedSize;
                            } else {
                                if (temp.exists()) {
                                    document.size = (int) temp.length();
                                }
                                fillVideoAttribute(info.path, attributeVideo, null);
                            }
                        }
                        if (videoEditedInfo != null && videoEditedInfo.muted) {
                            boolean found = false;
                            for (int b = 0, N = document.attributes.size(); b < N; b++) {
                                if (document.attributes.get(b) instanceof TLRPC.TL_documentAttributeAnimated) {
                                    found = true;
                                    break;
                                }
                            }
                            if (!found) {
                                document.attributes.add(new TLRPC.TL_documentAttributeAnimated());
                            }
                        }
                        if (videoEditedInfo != null && (videoEditedInfo.needConvert() || !info.isVideo)) {
                            String fileName = Integer.MIN_VALUE + "_" + SharedConfig.getLastLocalId() + ".mp4";
                            File cacheFile = new File(FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE), fileName);
                            SharedConfig.saveConfig();
                            path = cacheFile.getAbsolutePath();
                        }
                        final TLRPC.TL_document videoFinal = document;
                        final String parentFinal = parentObject;
                        final String originalPathFinal = originalPath;
                        final String finalPath = path;
                        final HashMap<String, String> params = new HashMap<>();
                        final Bitmap thumbFinal = thumb;
                        final String thumbKeyFinal = thumbKey;
                        if (originalPath != null) {
                            params.put("originalPath", originalPath);
                        }
                        if (parentFinal != null) {
                            params.put("parentObject", parentFinal);
                        }
                        if (!muted && groupMediaFinal) {
                            mediaCount++;
                            params.put("groupId", "" + groupId);
                            if (mediaCount == 10 || a == count - 1) {
                                params.put("final", "1");
                                lastGroupId = 0;
                            }
                        }
                        if (!isEncrypted && info.masks != null && !info.masks.isEmpty()) {
                            document.attributes.add(new TLRPC.TL_documentAttributeHasStickers());
                            SerializedData serializedData = new SerializedData(4 + info.masks.size() * 20);
                            serializedData.writeInt32(info.masks.size());
                            for (int b = 0; b < info.masks.size(); b++) {
                                info.masks.get(b).serializeToStream(serializedData);
                            }
                            params.put("masks", Utilities.bytesToHex(serializedData.toByteArray()));
                            serializedData.cleanup();
                        }
                        AndroidUtilities.runOnUIThread(() -> {
                            if (thumbFinal != null && thumbKeyFinal != null) {
                                ImageLoader.getInstance().putImageToCache(new BitmapDrawable(thumbFinal), thumbKeyFinal, false);
                            }
                            if (editingMessageObject != null) {
                                accountInstance.getSendMessagesHelper().editMessage(editingMessageObject, null, videoEditedInfo, videoFinal, finalPath, params, false, parentFinal);
                            } else {
                                accountInstance.getSendMessagesHelper().sendMessage(videoFinal, videoEditedInfo, finalPath, dialogId, replyToMsg, replyToTopMsg, info.caption, info.entities, null, params, notify, scheduleDate, info.ttl, parentFinal, null);
                            }
                        });
                    } else {
                        if (sendAsDocuments == null) {
                            sendAsDocuments = new ArrayList<>();
                            sendAsDocumentsOriginal = new ArrayList<>();
                            sendAsDocumentsCaptions = new ArrayList<>();
                            sendAsDocumentsEntities = new ArrayList<>();
                            sendAsDocumentsUri = new ArrayList<>();
                        }
                        sendAsDocuments.add(info.path);
                        sendAsDocumentsOriginal.add(info.path);
                        sendAsDocumentsUri.add(info.uri);
                        sendAsDocumentsCaptions.add(info.caption);
                        sendAsDocumentsEntities.add(info.entities);
                    // prepareSendingDocumentInternal(accountInstance, info.path, info.path, null, null, dialogId, replyToMsg, replyToTopMsg, info.caption, info.entities, editingMessageObject, null, false, forceDocument, notify, scheduleDate, null);
                    }
                } else {
                    String originalPath = info.path;
                    String tempPath = info.path;
                    if (tempPath == null && info.uri != null) {
                        if (Build.VERSION.SDK_INT >= 30 && "content".equals(info.uri.getScheme())) {
                            tempPath = null;
                        } else {
                            tempPath = AndroidUtilities.getPath(info.uri);
                        }
                        originalPath = info.uri.toString();
                    }
                    boolean isDocument = false;
                    if (inputContent != null && info.uri != null) {
                        ClipDescription description = inputContent.getDescription();
                        if (description.hasMimeType("image/png")) {
                            InputStream inputStream = null;
                            FileOutputStream stream = null;
                            try {
                                BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                                inputStream = ApplicationLoader.applicationContext.getContentResolver().openInputStream(info.uri);
                                Bitmap b = BitmapFactory.decodeStream(inputStream, null, bmOptions);
                                String fileName = Integer.MIN_VALUE + "_" + SharedConfig.getLastLocalId() + ".webp";
                                File fileDir = FileLoader.getDirectory(FileLoader.MEDIA_DIR_CACHE);
                                final File cacheFile = new File(fileDir, fileName);
                                stream = new FileOutputStream(cacheFile);
                                b.compress(Bitmap.CompressFormat.WEBP, 100, stream);
                                SharedConfig.saveConfig();
                                info.uri = Uri.fromFile(cacheFile);
                            } catch (Throwable e) {
                                FileLog.e(e);
                            } finally {
                                try {
                                    if (inputStream != null) {
                                        inputStream.close();
                                    }
                                } catch (Exception ignore) {
                                }
                                try {
                                    if (stream != null) {
                                        stream.close();
                                    }
                                } catch (Exception ignore) {
                                }
                            }
                        }
                    }
                    if (forceDocument || ImageLoader.shouldSendImageAsDocument(info.path, info.uri)) {
                        isDocument = true;
                        extension = tempPath != null ? FileLoader.getFileExtension(new File(tempPath)) : "";
                    } else if (!info.forceImage && tempPath != null && (tempPath.endsWith(".gif") || tempPath.endsWith(".webp")) && info.ttl <= 0) {
                        if (tempPath.endsWith(".gif")) {
                            extension = "gif";
                        } else {
                            extension = "webp";
                        }
                        isDocument = true;
                    } else if (!info.forceImage && tempPath == null && info.uri != null) {
                        if (MediaController.isGif(info.uri)) {
                            isDocument = true;
                            originalPath = info.uri.toString();
                            tempPath = MediaController.copyFileToCache(info.uri, "gif");
                            extension = "gif";
                        } else if (MediaController.isWebp(info.uri)) {
                            isDocument = true;
                            originalPath = info.uri.toString();
                            tempPath = MediaController.copyFileToCache(info.uri, "webp");
                            extension = "webp";
                        }
                    }
                    if (isDocument) {
                        if (sendAsDocuments == null) {
                            sendAsDocuments = new ArrayList<>();
                            sendAsDocumentsOriginal = new ArrayList<>();
                            sendAsDocumentsCaptions = new ArrayList<>();
                            sendAsDocumentsEntities = new ArrayList<>();
                            sendAsDocumentsUri = new ArrayList<>();
                        }
                        sendAsDocuments.add(tempPath);
                        sendAsDocumentsOriginal.add(originalPath);
                        sendAsDocumentsUri.add(info.uri);
                        sendAsDocumentsCaptions.add(info.caption);
                        sendAsDocumentsEntities.add(info.entities);
                    } else {
                        if (tempPath != null) {
                            File temp = new File(tempPath);
                            originalPath += temp.length() + "_" + temp.lastModified();
                        } else {
                            originalPath = null;
                        }
                        TLRPC.TL_photo photo = null;
                        String parentObject = null;
                        if (workers != null) {
                            MediaSendPrepareWorker worker = workers.get(info);
                            photo = worker.photo;
                            parentObject = worker.parentObject;
                            if (photo == null) {
                                try {
                                    worker.sync.await();
                                } catch (Exception e) {
                                    FileLog.e(e);
                                }
                                photo = worker.photo;
                                parentObject = worker.parentObject;
                            }
                        } else {
                            if (!isEncrypted && info.ttl == 0) {
                                Object[] sentData = accountInstance.getMessagesStorage().getSentFile(originalPath, !isEncrypted ? 0 : 3);
                                if (sentData != null && sentData[0] instanceof TLRPC.TL_photo) {
                                    photo = (TLRPC.TL_photo) sentData[0];
                                    parentObject = (String) sentData[1];
                                }
                                if (photo == null && info.uri != null) {
                                    sentData = accountInstance.getMessagesStorage().getSentFile(AndroidUtilities.getPath(info.uri), !isEncrypted ? 0 : 3);
                                    if (sentData != null && sentData[0] instanceof TLRPC.TL_photo) {
                                        photo = (TLRPC.TL_photo) sentData[0];
                                        parentObject = (String) sentData[1];
                                    }
                                }
                                ensureMediaThumbExists(isEncrypted, photo, info.path, info.uri, 0);
                            }
                            if (photo == null) {
                                photo = accountInstance.getSendMessagesHelper().generatePhotoSizes(info.path, info.uri);
                                if (isEncrypted && info.canDeleteAfter) {
                                    new File(info.path).delete();
                                }
                            }
                        }
                        if (photo != null) {
                            final TLRPC.TL_photo photoFinal = photo;
                            final String parentFinal = parentObject;
                            final HashMap<String, String> params = new HashMap<>();
                            final Bitmap[] bitmapFinal = new Bitmap[1];
                            final String[] keyFinal = new String[1];
                            if (photo.has_stickers = info.masks != null && !info.masks.isEmpty()) {
                                SerializedData serializedData = new SerializedData(4 + info.masks.size() * 20);
                                serializedData.writeInt32(info.masks.size());
                                for (int b = 0; b < info.masks.size(); b++) {
                                    info.masks.get(b).serializeToStream(serializedData);
                                }
                                params.put("masks", Utilities.bytesToHex(serializedData.toByteArray()));
                                serializedData.cleanup();
                            }
                            if (originalPath != null) {
                                params.put("originalPath", originalPath);
                            }
                            if (parentFinal != null) {
                                params.put("parentObject", parentFinal);
                            }
                            try {
                                if (!groupMediaFinal || media.size() == 1) {
                                    TLRPC.PhotoSize currentPhotoObject = FileLoader.getClosestPhotoSizeWithSize(photoFinal.sizes, AndroidUtilities.getPhotoSize());
                                    if (currentPhotoObject != null) {
                                        keyFinal[0] = getKeyForPhotoSize(currentPhotoObject, bitmapFinal, false, false);
                                    }
                                }
                            } catch (Exception e) {
                                FileLog.e(e);
                            }
                            if (groupMediaFinal) {
                                mediaCount++;
                                params.put("groupId", "" + groupId);
                                if (mediaCount == 10 || a == count - 1) {
                                    params.put("final", "1");
                                    lastGroupId = 0;
                                }
                            }
                            AndroidUtilities.runOnUIThread(() -> {
                                if (bitmapFinal[0] != null && keyFinal[0] != null) {
                                    ImageLoader.getInstance().putImageToCache(new BitmapDrawable(bitmapFinal[0]), keyFinal[0], false);
                                }
                                if (editingMessageObject != null) {
                                    accountInstance.getSendMessagesHelper().editMessage(editingMessageObject, photoFinal, null, null, null, params, false, parentFinal);
                                } else {
                                    accountInstance.getSendMessagesHelper().sendMessage(photoFinal, null, dialogId, replyToMsg, replyToTopMsg, info.caption, info.entities, null, params, notify, scheduleDate, info.ttl, parentFinal);
                                }
                            });
                        } else {
                            if (sendAsDocuments == null) {
                                sendAsDocuments = new ArrayList<>();
                                sendAsDocumentsOriginal = new ArrayList<>();
                                sendAsDocumentsCaptions = new ArrayList<>();
                                sendAsDocumentsEntities = new ArrayList<>();
                                sendAsDocumentsUri = new ArrayList<>();
                            }
                            sendAsDocuments.add(tempPath);
                            sendAsDocumentsOriginal.add(originalPath);
                            sendAsDocumentsUri.add(info.uri);
                            sendAsDocumentsCaptions.add(info.caption);
                            sendAsDocumentsEntities.add(info.entities);
                        }
                    }
                }
            }
        }
        if (lastGroupId != 0) {
            finishGroup(accountInstance, lastGroupId, scheduleDate);
        }
        if (inputContent != null) {
            inputContent.releasePermission();
        }
        if (sendAsDocuments != null && !sendAsDocuments.isEmpty()) {
            long[] groupId2 = new long[1];
            int documentsCount = sendAsDocuments.size();
            for (int a = 0; a < documentsCount; a++) {
                if (forceDocument && !isEncrypted && count > 1 && mediaCount % 10 == 0) {
                    groupId2[0] = Utilities.random.nextLong();
                    mediaCount = 0;
                }
                mediaCount++;
                prepareSendingDocumentInternal(accountInstance, sendAsDocuments.get(a), sendAsDocumentsOriginal.get(a), sendAsDocumentsUri.get(a), extension, dialogId, replyToMsg, replyToTopMsg, sendAsDocumentsCaptions.get(a), sendAsDocumentsEntities.get(a), editingMessageObject, groupId2, mediaCount == 10 || a == documentsCount - 1, forceDocument, notify, scheduleDate, null);
            }
        }
        if (BuildVars.LOGS_ENABLED) {
            FileLog.d("total send time = " + (System.currentTimeMillis() - beginTime));
        }
    });
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) BitmapFactory(android.graphics.BitmapFactory) SerializedData(org.telegram.tgnet.SerializedData) BitmapDrawable(android.graphics.drawable.BitmapDrawable) FileOutputStream(java.io.FileOutputStream) JSONObject(org.json.JSONObject) TLObject(org.telegram.tgnet.TLObject) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) Uri(android.net.Uri) Bitmap(android.graphics.Bitmap) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CountDownLatch(java.util.concurrent.CountDownLatch) Point(org.telegram.ui.Components.Point) ClipDescription(android.content.ClipDescription) UiThread(androidx.annotation.UiThread)

Example 2 with SerializedData

use of org.telegram.tgnet.SerializedData in project Telegram-FOSS by Telegram-FOSS-Team.

the class UserConfig method saveConfig.

public void saveConfig(boolean withFile) {
    NotificationCenter.getInstance(currentAccount).doOnIdle(() -> {
        synchronized (sync) {
            try {
                SharedPreferences.Editor editor = getPreferences().edit();
                if (currentAccount == 0) {
                    editor.putInt("selectedAccount", selectedAccount);
                }
                editor.putBoolean("registeredForPush", registeredForPush);
                editor.putInt("lastSendMessageId", lastSendMessageId);
                editor.putInt("contactsSavedCount", contactsSavedCount);
                editor.putInt("lastBroadcastId", lastBroadcastId);
                editor.putInt("lastContactsSyncTime", lastContactsSyncTime);
                editor.putInt("lastHintsSyncTime", lastHintsSyncTime);
                editor.putBoolean("draftsLoaded", draftsLoaded);
                editor.putBoolean("unreadDialogsLoaded", unreadDialogsLoaded);
                editor.putInt("ratingLoadTime", ratingLoadTime);
                editor.putInt("botRatingLoadTime", botRatingLoadTime);
                editor.putBoolean("contactsReimported", contactsReimported);
                editor.putInt("loginTime", loginTime);
                editor.putBoolean("syncContacts", syncContacts);
                editor.putBoolean("suggestContacts", suggestContacts);
                editor.putBoolean("hasSecureData", hasSecureData);
                editor.putBoolean("notificationsSettingsLoaded3", notificationsSettingsLoaded);
                editor.putBoolean("notificationsSignUpSettingsLoaded", notificationsSignUpSettingsLoaded);
                editor.putLong("autoDownloadConfigLoadTime", autoDownloadConfigLoadTime);
                editor.putBoolean("hasValidDialogLoadIds", hasValidDialogLoadIds);
                editor.putInt("sharingMyLocationUntil", sharingMyLocationUntil);
                editor.putInt("lastMyLocationShareTime", lastMyLocationShareTime);
                editor.putBoolean("filtersLoaded", filtersLoaded);
                editor.putInt("6migrateOffsetId", migrateOffsetId);
                if (migrateOffsetId != -1) {
                    editor.putInt("6migrateOffsetDate", migrateOffsetDate);
                    editor.putLong("6migrateOffsetUserId", migrateOffsetUserId);
                    editor.putLong("6migrateOffsetChatId", migrateOffsetChatId);
                    editor.putLong("6migrateOffsetChannelId", migrateOffsetChannelId);
                    editor.putLong("6migrateOffsetAccess", migrateOffsetAccess);
                }
                if (unacceptedTermsOfService != null) {
                    try {
                        SerializedData data = new SerializedData(unacceptedTermsOfService.getObjectSize());
                        unacceptedTermsOfService.serializeToStream(data);
                        editor.putString("terms", Base64.encodeToString(data.toByteArray(), Base64.DEFAULT));
                        data.cleanup();
                    } catch (Exception ignore) {
                    }
                } else {
                    editor.remove("terms");
                }
                SharedConfig.saveConfig();
                if (tmpPassword != null) {
                    SerializedData data = new SerializedData();
                    tmpPassword.serializeToStream(data);
                    String string = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);
                    editor.putString("tmpPassword", string);
                    data.cleanup();
                } else {
                    editor.remove("tmpPassword");
                }
                if (currentUser != null) {
                    if (withFile) {
                        SerializedData data = new SerializedData();
                        currentUser.serializeToStream(data);
                        String string = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT);
                        editor.putString("user", string);
                        data.cleanup();
                    }
                } else {
                    editor.remove("user");
                }
                editor.commit();
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
    });
}
Also used : SharedPreferences(android.content.SharedPreferences) SerializedData(org.telegram.tgnet.SerializedData)

Example 3 with SerializedData

use of org.telegram.tgnet.SerializedData in project Telegram-FOSS by Telegram-FOSS-Team.

the class UserConfig method loadConfig.

public void loadConfig() {
    synchronized (sync) {
        if (configLoaded) {
            return;
        }
        SharedPreferences preferences = getPreferences();
        if (currentAccount == 0) {
            selectedAccount = preferences.getInt("selectedAccount", 0);
        }
        registeredForPush = preferences.getBoolean("registeredForPush", false);
        lastSendMessageId = preferences.getInt("lastSendMessageId", -210000);
        contactsSavedCount = preferences.getInt("contactsSavedCount", 0);
        lastBroadcastId = preferences.getInt("lastBroadcastId", -1);
        lastContactsSyncTime = preferences.getInt("lastContactsSyncTime", (int) (System.currentTimeMillis() / 1000) - 23 * 60 * 60);
        lastHintsSyncTime = preferences.getInt("lastHintsSyncTime", (int) (System.currentTimeMillis() / 1000) - 25 * 60 * 60);
        draftsLoaded = preferences.getBoolean("draftsLoaded", false);
        unreadDialogsLoaded = preferences.getBoolean("unreadDialogsLoaded", false);
        contactsReimported = preferences.getBoolean("contactsReimported", false);
        ratingLoadTime = preferences.getInt("ratingLoadTime", 0);
        botRatingLoadTime = preferences.getInt("botRatingLoadTime", 0);
        loginTime = preferences.getInt("loginTime", currentAccount);
        syncContacts = preferences.getBoolean("syncContacts", true);
        suggestContacts = preferences.getBoolean("suggestContacts", true);
        hasSecureData = preferences.getBoolean("hasSecureData", false);
        notificationsSettingsLoaded = preferences.getBoolean("notificationsSettingsLoaded3", false);
        notificationsSignUpSettingsLoaded = preferences.getBoolean("notificationsSignUpSettingsLoaded", false);
        autoDownloadConfigLoadTime = preferences.getLong("autoDownloadConfigLoadTime", 0);
        hasValidDialogLoadIds = preferences.contains("2dialogsLoadOffsetId") || preferences.getBoolean("hasValidDialogLoadIds", false);
        sharingMyLocationUntil = preferences.getInt("sharingMyLocationUntil", 0);
        lastMyLocationShareTime = preferences.getInt("lastMyLocationShareTime", 0);
        filtersLoaded = preferences.getBoolean("filtersLoaded", false);
        try {
            String terms = preferences.getString("terms", null);
            if (terms != null) {
                byte[] arr = Base64.decode(terms, Base64.DEFAULT);
                if (arr != null) {
                    SerializedData data = new SerializedData(arr);
                    unacceptedTermsOfService = TLRPC.TL_help_termsOfService.TLdeserialize(data, data.readInt32(false), false);
                    data.cleanup();
                }
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
        migrateOffsetId = preferences.getInt("6migrateOffsetId", 0);
        if (migrateOffsetId != -1) {
            migrateOffsetDate = preferences.getInt("6migrateOffsetDate", 0);
            migrateOffsetUserId = AndroidUtilities.getPrefIntOrLong(preferences, "6migrateOffsetUserId", 0);
            migrateOffsetChatId = AndroidUtilities.getPrefIntOrLong(preferences, "6migrateOffsetChatId", 0);
            migrateOffsetChannelId = AndroidUtilities.getPrefIntOrLong(preferences, "6migrateOffsetChannelId", 0);
            migrateOffsetAccess = preferences.getLong("6migrateOffsetAccess", 0);
        }
        String string = preferences.getString("tmpPassword", null);
        if (string != null) {
            byte[] bytes = Base64.decode(string, Base64.DEFAULT);
            if (bytes != null) {
                SerializedData data = new SerializedData(bytes);
                tmpPassword = TLRPC.TL_account_tmpPassword.TLdeserialize(data, data.readInt32(false), false);
                data.cleanup();
            }
        }
        string = preferences.getString("user", null);
        if (string != null) {
            byte[] bytes = Base64.decode(string, Base64.DEFAULT);
            if (bytes != null) {
                SerializedData data = new SerializedData(bytes);
                currentUser = TLRPC.User.TLdeserialize(data, data.readInt32(false), false);
                data.cleanup();
            }
        }
        if (currentUser != null) {
            clientUserId = currentUser.id;
        }
        configLoaded = true;
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) SerializedData(org.telegram.tgnet.SerializedData)

Example 4 with SerializedData

use of org.telegram.tgnet.SerializedData in project Telegram-FOSS by Telegram-FOSS-Team.

the class SharedConfig method loadConfig.

public static void loadConfig() {
    synchronized (sync) {
        if (configLoaded || ApplicationLoader.applicationContext == null) {
            return;
        }
        SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("userconfing", Context.MODE_PRIVATE);
        saveIncomingPhotos = preferences.getBoolean("saveIncomingPhotos", false);
        passcodeHash = preferences.getString("passcodeHash1", "");
        appLocked = preferences.getBoolean("appLocked", false);
        passcodeType = preferences.getInt("passcodeType", 0);
        passcodeRetryInMs = preferences.getLong("passcodeRetryInMs", 0);
        lastUptimeMillis = preferences.getLong("lastUptimeMillis", 0);
        badPasscodeTries = preferences.getInt("badPasscodeTries", 0);
        autoLockIn = preferences.getInt("autoLockIn", 60 * 60);
        lastPauseTime = preferences.getInt("lastPauseTime", 0);
        useFingerprint = preferences.getBoolean("useFingerprint", true);
        lastUpdateVersion = preferences.getString("lastUpdateVersion2", "3.5");
        allowScreenCapture = preferences.getBoolean("allowScreenCapture", false);
        lastLocalId = preferences.getInt("lastLocalId", -210000);
        pushString = preferences.getString("pushString2", "");
        pushStatSent = preferences.getBoolean("pushStatSent", false);
        passportConfigJson = preferences.getString("passportConfigJson", "");
        passportConfigHash = preferences.getInt("passportConfigHash", 0);
        storageCacheDir = preferences.getString("storageCacheDir", null);
        String authKeyString = preferences.getString("pushAuthKey", null);
        if (!TextUtils.isEmpty(authKeyString)) {
            pushAuthKey = Base64.decode(authKeyString, Base64.DEFAULT);
        }
        if (passcodeHash.length() > 0 && lastPauseTime == 0) {
            lastPauseTime = (int) (SystemClock.elapsedRealtime() / 1000 - 60 * 10);
        }
        String passcodeSaltString = preferences.getString("passcodeSalt", "");
        if (passcodeSaltString.length() > 0) {
            passcodeSalt = Base64.decode(passcodeSaltString, Base64.DEFAULT);
        } else {
            passcodeSalt = new byte[0];
        }
        lastUpdateCheckTime = preferences.getLong("appUpdateCheckTime", System.currentTimeMillis());
        try {
            String update = preferences.getString("appUpdate", null);
            if (update != null) {
                pendingAppUpdateBuildVersion = preferences.getInt("appUpdateBuild", BuildVars.BUILD_VERSION);
                byte[] arr = Base64.decode(update, Base64.DEFAULT);
                if (arr != null) {
                    SerializedData data = new SerializedData(arr);
                    pendingAppUpdate = (TLRPC.TL_help_appUpdate) TLRPC.help_AppUpdate.TLdeserialize(data, data.readInt32(false), false);
                    data.cleanup();
                }
            }
            if (pendingAppUpdate != null) {
                long updateTime = 0;
                int updateVersion = 0;
                String updateVersionString = null;
                try {
                    PackageInfo packageInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);
                    updateVersion = packageInfo.versionCode;
                    updateVersionString = packageInfo.versionName;
                } catch (Exception e) {
                    FileLog.e(e);
                }
                if (updateVersion == 0) {
                    updateVersion = BuildVars.BUILD_VERSION;
                }
                if (updateVersionString == null) {
                    updateVersionString = BuildVars.BUILD_VERSION_STRING;
                }
                if (pendingAppUpdateBuildVersion != updateVersion || pendingAppUpdate.version == null || updateVersionString.compareTo(pendingAppUpdate.version) >= 0) {
                    pendingAppUpdate = null;
                    AndroidUtilities.runOnUIThread(SharedConfig::saveConfig);
                }
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
        preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
        saveToGallery = preferences.getBoolean("save_gallery", false);
        autoplayGifs = preferences.getBoolean("autoplay_gif", true);
        autoplayVideo = preferences.getBoolean("autoplay_video", true);
        mapPreviewType = preferences.getInt("mapPreviewType", 2);
        raiseToSpeak = preferences.getBoolean("raise_to_speak", false);
        customTabs = preferences.getBoolean("custom_tabs", true);
        directShare = preferences.getBoolean("direct_share", true);
        shuffleMusic = preferences.getBoolean("shuffleMusic", false);
        playOrderReversed = !shuffleMusic && preferences.getBoolean("playOrderReversed", false);
        inappCamera = preferences.getBoolean("inappCamera", true);
        hasCameraCache = preferences.contains("cameraCache");
        // preferences.getBoolean("roundCamera16to9", false);
        roundCamera16to9 = true;
        repeatMode = preferences.getInt("repeatMode", 0);
        fontSize = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16);
        bubbleRadius = preferences.getInt("bubbleRadius", 10);
        ivFontSize = preferences.getInt("iv_font_size", fontSize);
        allowBigEmoji = preferences.getBoolean("allowBigEmoji", true);
        useSystemEmoji = preferences.getBoolean("useSystemEmoji", false);
        streamMedia = preferences.getBoolean("streamMedia", true);
        saveStreamMedia = preferences.getBoolean("saveStreamMedia", true);
        smoothKeyboard = preferences.getBoolean("smoothKeyboard2", true);
        pauseMusicOnRecord = preferences.getBoolean("pauseMusicOnRecord", false);
        chatBlur = preferences.getBoolean("chatBlur", true);
        streamAllVideo = preferences.getBoolean("streamAllVideo", BuildVars.DEBUG_VERSION);
        streamMkv = preferences.getBoolean("streamMkv", false);
        suggestStickers = preferences.getInt("suggestStickers", 0);
        sortContactsByName = preferences.getBoolean("sortContactsByName", false);
        sortFilesByName = preferences.getBoolean("sortFilesByName", false);
        noSoundHintShowed = preferences.getBoolean("noSoundHintShowed", false);
        directShareHash = preferences.getString("directShareHash2", null);
        useThreeLinesLayout = preferences.getBoolean("useThreeLinesLayout", false);
        archiveHidden = preferences.getBoolean("archiveHidden", false);
        distanceSystemType = preferences.getInt("distanceSystemType", 0);
        devicePerformanceClass = preferences.getInt("devicePerformanceClass", -1);
        loopStickers = preferences.getBoolean("loopStickers", true);
        keepMedia = preferences.getInt("keep_media", 2);
        noStatusBar = preferences.getBoolean("noStatusBar", false);
        lastKeepMediaCheckTime = preferences.getInt("lastKeepMediaCheckTime", 0);
        lastLogsCheckTime = preferences.getInt("lastLogsCheckTime", 0);
        searchMessagesAsListHintShows = preferences.getInt("searchMessagesAsListHintShows", 0);
        searchMessagesAsListUsed = preferences.getBoolean("searchMessagesAsListUsed", false);
        stickersReorderingHintUsed = preferences.getBoolean("stickersReorderingHintUsed", false);
        textSelectionHintShows = preferences.getInt("textSelectionHintShows", 0);
        scheduledOrNoSoundHintShows = preferences.getInt("scheduledOrNoSoundHintShows", 0);
        forwardingOptionsHintShown = preferences.getBoolean("forwardingOptionsHintShown", false);
        lockRecordAudioVideoHint = preferences.getInt("lockRecordAudioVideoHint", 0);
        disableVoiceAudioEffects = preferences.getBoolean("disableVoiceAudioEffects", false);
        noiseSupression = preferences.getBoolean("noiseSupression", false);
        chatSwipeAction = preferences.getInt("ChatSwipeAction", -1);
        messageSeenHintCount = preferences.getInt("messageSeenCount", 3);
        emojiInteractionsHintCount = preferences.getInt("emojiInteractionsHintCount", 3);
        dayNightThemeSwitchHintCount = preferences.getInt("dayNightThemeSwitchHintCount", 3);
        mediaColumnsCount = preferences.getInt("mediaColumnsCount", 3);
        fastScrollHintCount = preferences.getInt("fastScrollHintCount", 3);
        dontAskManageStorage = preferences.getBoolean("dontAskManageStorage", false);
        preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
        showNotificationsForAllAccounts = preferences.getBoolean("AllAccounts", true);
        configLoaded = true;
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) PackageInfo(android.content.pm.PackageInfo) SerializedData(org.telegram.tgnet.SerializedData) TLRPC(org.telegram.tgnet.TLRPC)

Example 5 with SerializedData

use of org.telegram.tgnet.SerializedData in project Telegram-FOSS by Telegram-FOSS-Team.

the class SharedConfig method loadProxyList.

public static void loadProxyList() {
    if (proxyListLoaded) {
        return;
    }
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
    String proxyAddress = preferences.getString("proxy_ip", "");
    String proxyUsername = preferences.getString("proxy_user", "");
    String proxyPassword = preferences.getString("proxy_pass", "");
    String proxySecret = preferences.getString("proxy_secret", "");
    int proxyPort = preferences.getInt("proxy_port", 1080);
    proxyListLoaded = true;
    proxyList.clear();
    currentProxy = null;
    String list = preferences.getString("proxy_list", null);
    if (!TextUtils.isEmpty(list)) {
        byte[] bytes = Base64.decode(list, Base64.DEFAULT);
        SerializedData data = new SerializedData(bytes);
        int count = data.readInt32(false);
        for (int a = 0; a < count; a++) {
            ProxyInfo info = new ProxyInfo(data.readString(false), data.readInt32(false), data.readString(false), data.readString(false), data.readString(false));
            proxyList.add(info);
            if (currentProxy == null && !TextUtils.isEmpty(proxyAddress)) {
                if (proxyAddress.equals(info.address) && proxyPort == info.port && proxyUsername.equals(info.username) && proxyPassword.equals(info.password)) {
                    currentProxy = info;
                }
            }
        }
        data.cleanup();
    }
    if (currentProxy == null && !TextUtils.isEmpty(proxyAddress)) {
        ProxyInfo info = currentProxy = new ProxyInfo(proxyAddress, proxyPort, proxyUsername, proxyPassword, proxySecret);
        proxyList.add(0, info);
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) SerializedData(org.telegram.tgnet.SerializedData)

Aggregations

SerializedData (org.telegram.tgnet.SerializedData)29 SharedPreferences (android.content.SharedPreferences)17 TLRPC (org.telegram.tgnet.TLRPC)17 ArrayList (java.util.ArrayList)11 HashMap (java.util.HashMap)5 Point (org.telegram.ui.Components.Point)5 SuppressLint (android.annotation.SuppressLint)4 Paint (android.graphics.Paint)3 TextPaint (android.text.TextPaint)3 TLObject (org.telegram.tgnet.TLObject)3 Bitmap (android.graphics.Bitmap)2 BitmapFactory (android.graphics.BitmapFactory)2 BitmapDrawable (android.graphics.drawable.BitmapDrawable)2 Uri (android.net.Uri)2 SpannableString (android.text.SpannableString)2 View (android.view.View)2 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 List (java.util.List)2 EmojiThemes (org.telegram.ui.ActionBar.EmojiThemes)2