private static void SavePhotoAsync(TLMessageMediaPhoto mediaPhoto, Action <string> callback = null)
        {
            var photo = mediaPhoto.Photo as TLPhoto;

            if (photo == null)
            {
                return;
            }

            TLPhotoSize  size  = null;
            var          sizes = photo.Sizes.OfType <TLPhotoSize>();
            const double width = 800.0;

            foreach (var photoSize in sizes)
            {
                if (size == null ||
                    Math.Abs(width - size.W.Value) > Math.Abs(width - photoSize.W.Value))
                {
                    size = photoSize;
                }
            }
            if (size == null)
            {
                return;
            }

            var location = size.Location as TLFileLocation;

            if (location == null)
            {
                return;
            }

            var fileName = String.Format("{0}_{1}_{2}.jpg",
                                         location.VolumeId,
                                         location.LocalId,
                                         location.Secret);

            Execute.BeginOnThreadPool(() => SavePhoto(fileName, callback));
        }
Exemplo n.º 2
0
        private static async void OnMyTimedEvent(object source, ElapsedEventArgs e)
        {
            try
            {
                Console.WriteLine("On timer event");
                DateTime nowDateTime = DateTime.Now.ToLocalTime();
                // Check that we are well connected
                if (Client != null && Client.IsConnected && UserId != 0)
                {
                    if (ChannelId != null && ChannelId.Count > 0)
                    {
                        TLAbsDialogs = await Client.GetUserDialogsAsync();

                        foreach (TLAbsMessage tLAbsMessage in ((TLDialogs)TLAbsDialogs).Messages.Where(x => x is TLMessage message && TimeUnixTOWindows(message.Date, true) >= nowDateTime.AddMilliseconds(-(TimerIntervalInMs - 1))))
                        {
                            ((TLMessage)tLAbsMessage).Message = CalculOffset(((TLMessage)tLAbsMessage).Message);
                            if (((TLMessage)tLAbsMessage).ToId is TLPeerUser tLPeerUser)
                            {
                                // Personal Chat Do Not Forward!
                            }
                            else if (((TLMessage)tLAbsMessage).ToId is TLPeerChannel channel0 && ((TLMessage)tLAbsMessage).ReplyToMsgId != null)
                            {
                                int crtChannelId = channel0.ChannelId;
                                if (crtChannelId != MyChanId && ChannelId.ContainsKey(crtChannelId))
                                {
                                    Console.WriteLine("ReplyChannelId " + ((TLMessage)tLAbsMessage).ReplyToMsgId);
                                    await ReplyMessage((TLMessage)tLAbsMessage);
                                }
                            }
                            else if (((TLMessage)tLAbsMessage).ToId is TLPeerChat chat && ((TLMessage)tLAbsMessage).ReplyToMsgId != null)
                            {
                                Console.WriteLine("ReplyChatId " + ((TLMessage)tLAbsMessage).ReplyToMsgId);
                                await ReplyMessage((TLMessage)tLAbsMessage);
                            }
                            else if (((TLMessage)tLAbsMessage).ToId is TLPeerChannel channel && ((TLMessage)tLAbsMessage).ReplyToMsgId == null)
                            {
                                int crtChannelId = channel.ChannelId;
                                if (crtChannelId != MyChanId && ChannelId.ContainsKey(crtChannelId))
                                {
                                    Console.WriteLine("New Message Channel " + ChannelId[crtChannelId][0] + " \n" + ((TLMessage)tLAbsMessage).Message);
                                    if (ChannelId.ContainsKey(crtChannelId))
                                    {
                                        if (((TLMessage)tLAbsMessage).Message != "")
                                        {
                                            if (((TLMessage)tLAbsMessage).Message.ToLower().StartsWith("tp") || ((TLMessage)tLAbsMessage).Message.ToLower().StartsWith("sl"))
                                            {
                                                TLChannelMessages historyFromSourceCanal = (TLChannelMessages)await Client.GetHistoryAsync(new TLInputPeerChannel()
                                                {
                                                    ChannelId = channel.ChannelId, AccessHash = (long)ChannelId[channel.ChannelId][1]
                                                });

                                                List <TLAbsMessage> tLMessageList        = historyFromSourceCanal.Messages.ToList().Where(x => x is TLMessage tL).ToList();
                                                List <TLMessage>    orderedtLMessageList = tLMessageList.Cast <TLMessage>().OrderByDescending(x => x.Id).ToList();
                                                string newMessage = CalculOffset(orderedtLMessageList[1].Message + "\n" + ((TLMessage)tLAbsMessage).Message);
                                                if (orderedtLMessageList[1].Message.ToLower().Contains("sell") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                                else if (orderedtLMessageList[1].Message.ToLower().Contains("vente") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                                else if (orderedtLMessageList[1].Message.ToLower().Contains("buy") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                                else if (orderedtLMessageList[1].Message.ToLower().Contains("achat") && !orderedtLMessageList[1].Message.ToLower().Contains("sl"))
                                                {
                                                    await Client.SendMessageAsync(new TLInputPeerChannel()
                                                    {
                                                        ChannelId = MyChanId, AccessHash = AccessHash
                                                    }, newMessage);
                                                }
                                            }
                                            else
                                            {
                                                await Client.SendMessageAsync(new TLInputPeerChannel()
                                                {
                                                    ChannelId = MyChanId, AccessHash = AccessHash
                                                }, ((TLMessage)tLAbsMessage).Message);
                                            }
                                        }
                                        else if (((TLMessage)tLAbsMessage).Media != null)
                                        {
                                            if (((TLMessage)tLAbsMessage).Media.GetType().ToString() == "TeleSharp.TL.TLMessageMediaPhoto")
                                            {
                                                TLMessageMediaPhoto    tLMessageMediaPhoto    = (TLMessageMediaPhoto)((TLMessage)tLAbsMessage).Media;
                                                TLPhoto                tLPhoto                = (TLPhoto)tLMessageMediaPhoto.Photo;
                                                TLPhotoSize            tLPhotoSize            = tLPhoto.Sizes.ToList().OfType <TLPhotoSize>().Last();
                                                TLFileLocation         tLFileLocation         = (TLFileLocation)tLPhotoSize.Location;
                                                TLAbsInputFileLocation tLAbsInputFileLocation = new TLInputFileLocation()
                                                {
                                                    LocalId  = tLFileLocation.LocalId,
                                                    Secret   = tLFileLocation.Secret,
                                                    VolumeId = tLFileLocation.VolumeId
                                                };
                                                TLInputFileLocation TLInputFileLocation = tLAbsInputFileLocation as TLInputFileLocation;
                                                TLFile buffer = await Client.GetFile(TLInputFileLocation, 1024 * 512);

                                                TLInputFile fileResult = (TLInputFile)await UploadHelper.UploadFile(Client, "", new StreamReader(new MemoryStream(buffer.Bytes)));

                                                await Client.SendUploadedPhoto(new TLInputPeerChannel()
                                                {
                                                    ChannelId = MyChanId, AccessHash = AccessHash
                                                }, fileResult, tLMessageMediaPhoto.Caption);
                                            }
                                            else if (((TLMessage)tLAbsMessage).Media.GetType().ToString() == "TeleSharp.TL.TLMessageMediaDocument")
                                            {
                                                TLMessageMediaDocument            tLMessageMediaDocument      = (TLMessageMediaDocument)((TLMessage)tLAbsMessage).Media;
                                                TLDocument                        tLDocument                  = (TLDocument)tLMessageMediaDocument.Document;
                                                TLVector <TLAbsDocumentAttribute> tLAbsDocumentAttributes     = tLDocument.Attributes;
                                                TLInputDocumentFileLocation       tLInputDocumentFileLocation = new TLInputDocumentFileLocation()
                                                {
                                                    AccessHash = tLDocument.AccessHash,
                                                    Id         = tLDocument.Id,
                                                    Version    = tLDocument.Version,
                                                };
                                                TLFile buffer = await Client.GetFile(tLInputDocumentFileLocation, 1024 * 512);

                                                TLInputFile fileResult = (TLInputFile)await UploadHelper.UploadFile(Client, ((TLDocumentAttributeFilename)tLAbsDocumentAttributes[0]).FileName, new StreamReader(new MemoryStream(buffer.Bytes)));

                                                await Client.SendUploadedDocument(new TLInputPeerChannel()
                                                {
                                                    ChannelId = MyChanId, AccessHash = AccessHash
                                                }, fileResult, tLMessageMediaDocument.Caption, tLDocument.MimeType, tLAbsDocumentAttributes);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
Exemplo n.º 3
0
        public static BitmapImage ReturnOrEnqueueImage(bool checkChatSettings, TLFileLocation location, TLObject owner, int fileSize, TLMessageMediaPhoto mediaPhoto)
        {
            string fileName = string.Format("{0}_{1}_{2}.jpg", location.VolumeId, location.LocalId, location.Secret);

            if (File.Exists(FileUtils.GetTempFileName(fileName)))
            {
                var bitmap = new BitmapImage();
                bitmap.UriSource = FileUtils.GetTempFileUri(fileName);
                return(bitmap);
            }

            if (fileSize >= 0)
            {
                var manager = UnigramContainer.Current.ResolveType <IDownloadFileManager>();
                var bitmap  = new BitmapImage();

                //Execute.BeginOnThreadPool(() => manager.DownloadFile(location, owner, fileSize));
                Execute.BeginOnThreadPool(async() =>
                {
                    await manager.DownloadFileAsync(location, fileSize, mediaPhoto?.Photo.Download());
                    Execute.BeginOnUIThread(() =>
                    {
                        bitmap.UriSource = FileUtils.GetTempFileUri(fileName);
                    });
                });

                return(bitmap);
            }

            return(null);
        }
Exemplo n.º 4
0
        protected string ExportPhoto(TLMessageMediaPhoto media)
        {
            // TLPhoto contains a collection of TLPhotoSize
            TLPhoto photo = media.photo as TLPhoto;

            if (photo == null)
            {
                throw new TLCoreException("The photo is not an instance of TLPhoto");
            }

            if (photo.sizes.lists.Count <= 0)
            {
                throw new TLCoreException("TLPhoto does not have any element");
            }

            // Pick max size photo from TLPhoto
            TLPhotoSize photoMaxSize = null;

            foreach (TLAbsPhotoSize absPhotoSize in photo.sizes.lists)
            {
                TLPhotoSize photoSize = absPhotoSize as TLPhotoSize;
                if (photoSize == null)
                {
                    throw new TLCoreException("The photosize is not an instance of TLPhotoSize");
                }
                if (photoMaxSize != null && photoSize.w < photoMaxSize.w)
                {
                    continue;
                }
                photoMaxSize = photoSize;
            }

            // a TLPhotoSize contains a TLFileLocation
            TLFileLocation fileLocation = photoMaxSize.location as TLFileLocation;

            if (fileLocation == null)
            {
                throw new TLCoreException("The file location is not an instance of TLFileLocation");
            }

            TLFile file = m_archiver.GetFile(fileLocation, photoMaxSize.size);

            string ext = "";

            if (file.type.GetType() == typeof(TLFileJpeg))
            {
                ext = "jpg";
            }
            else if (file.type.GetType() == typeof(TLFileGif))
            {
                ext = "gif";
            }
            else if (file.type.GetType() == typeof(TLFilePng))
            {
                ext = "png";
            }
            else
            {
                throw new TLCoreException("The photo has an unknown file type");
            }

            // Take a caption if exists or set the default one
            string sCaption = String.IsNullOrEmpty(media.caption) ? c_sPhoto : media.caption;

            // Key: YYYY-MM-DD-Caption{0:00}.EXT
            string key = String.Format("{0}-{1}{2}.{3}",
                                       m_sPrefix,
                                       sCaption,
                                       "{0:00}",
                                       ext);

            string sFileName = GetUniqueFileName(key); // YYYY-MM-DD-CaptionXX.EXT

            if (m_config.ExportPhotos)
            {
                // Export the photo to a file
                string sFullFileName = Path.Combine(m_sDialogDirectory, sFileName);
                using (FileStream f = new FileStream(sFullFileName, FileMode.Create, FileAccess.Write))
                    f.Write(file.bytes, 0, photoMaxSize.size);
            }

            return(sFileName); // YYYY-MM-DD-CaptionXX.EXT
        }
Exemplo n.º 5
0
        private async Task SendPhotoAsync(StorageFile file, string caption)
        {
            var originalProps = await file.Properties.GetImagePropertiesAsync();

            var imageWidth = originalProps.Width;
            var imageHeight = originalProps.Height;
            if (imageWidth >= 20 * imageHeight || imageHeight >= 20 * imageWidth)
            {
                await SendFileAsync(file, caption);
                return;
            }

            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId = TLInt.Random(),
                Secret = TLLong.Random(),
                DCId = 0
            };

            var fileName = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            StorageFile fileScale;
            try
            {
                fileScale = await ImageHelper.ScaleJpegAsync(file, fileCache, 1280, 0.77);
            }
            catch (InvalidCastException)
            {
                await fileCache.DeleteAsync();
                await SendGifAsync(file, caption);
                return;
            }

            var basicProps = await fileScale.GetBasicPropertiesAsync();
            var imageProps = await fileScale.Properties.GetImagePropertiesAsync();

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            var photoSize = new TLPhotoSize
            {
                Type = "y",
                W = (int)imageProps.Width,
                H = (int)imageProps.Height,
                Location = fileLocation,
                Size = (int)basicProps.Size
            };

            var photo = new TLPhoto
            {
                Id = 0,
                AccessHash = 0,
                Date = date,
                Sizes = new TLVector<TLPhotoSizeBase> { photoSize }
            };

            var media = new TLMessageMediaPhoto
            {
                Photo = photo,
                Caption = caption
            };

            var message = TLUtils.GetMessage(SettingsHelper.UserId, Peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null);

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId = Reply.Id;
                message.Reply = Reply;
                Reply = null;
            }

            var previousMessage = InsertSendingMessage(message);
            CacheService.SyncSendingMessage(message, previousMessage, async (m) =>
            {
                var fileId = TLLong.Random();
                var upload = await _uploadFileManager.UploadFileAsync(fileId, fileCache.Name, false).AsTask(Upload(photo, progress => new TLSendMessageUploadPhotoAction { Progress = progress }));
                if (upload != null)
                {
                    var inputMedia = new TLInputMediaUploadedPhoto
                    {
                        Caption = media.Caption,
                        File = upload.ToInputFile()
                    };

                    var response = await ProtoService.SendMediaAsync(Peer, inputMedia, message);
                    //if (response.IsSucceeded && response.Result is TLUpdates updates)
                    //{
                    //    TLPhoto newPhoto = null;

                    //    var newMessageUpdate = updates.Updates.FirstOrDefault(x => x is TLUpdateNewMessage) as TLUpdateNewMessage;
                    //    if (newMessageUpdate != null && newMessageUpdate.Message is TLMessage newMessage && newMessage.Media is TLMessageMediaPhoto newPhotoMedia)
                    //    {
                    //        newPhoto = newPhotoMedia.Photo as TLPhoto;
                    //    }

                    //    var newChannelMessageUpdate = updates.Updates.FirstOrDefault(x => x is TLUpdateNewChannelMessage) as TLUpdateNewChannelMessage;
                    //    if (newChannelMessageUpdate != null && newMessageUpdate.Message is TLMessage newChannelMessage && newChannelMessage.Media is TLMessageMediaPhoto newChannelPhotoMedia)
                    //    {
                    //        newPhoto = newChannelPhotoMedia.Photo as TLPhoto;
                    //    }

                    //    if (newPhoto != null && newPhoto.Full is TLPhotoSize newFull && newFull.Location is TLFileLocation newLocation)
                    //    {
                    //        var newFileName = string.Format("{0}_{1}_{2}.jpg", newLocation.VolumeId, newLocation.LocalId, newLocation.Secret);
                    //        var newFile = await FileUtils.CreateTempFileAsync(newFileName);
                    //        await fileCache.CopyAndReplaceAsync(newFile);
                    //    }
                    //}
                }
            });
        }