private TLFile GetFile(TLInt dcId, TLInputDocumentFileLocation location, TLInt offset, TLInt limit) { var manualResetEvent = new ManualResetEvent(false); TLFile result = null; _mtProtoService.GetFileAsync(dcId, location, offset, limit, file => { result = file; manualResetEvent.Set(); }, error => { int delay; lock (_randomRoot) { delay = _random.Next(1000, 3000); } Execute.BeginOnThreadPool(TimeSpan.FromMilliseconds(delay), () => manualResetEvent.Set()); }); manualResetEvent.WaitOne(); return(result); }
public void DownloadFile(TLMessagesSlice messages, TelegramClient client) { TLDocument document = GetFileData(messages); string file_name = GetFileName(document); var loc = new TLInputDocumentFileLocation() { AccessHash = document.AccessHash, Id = document.Id, Version = document.Version }; var mb = 1048576; var upperLimit = (int)Math.Pow(2, Math.Ceiling(Math.Log(document.Size, 2))) * 4; var limit = Math.Min(mb, upperLimit); var currentOffset = 0; File.WriteAllText(file_name, ""); using (var fs = File.OpenWrite(file_name)) { while (currentOffset < document.Size) { var file = client.GetFile(loc, limit, currentOffset).ConfigureAwait(false).GetAwaiter().GetResult(); fs.Write(file.Bytes, currentOffset, file.Bytes.Length); currentOffset += file.Bytes.Length; } fs.Close(); } }
public void DownloadFile(string originalFileName, int dcId, TLInputDocumentFileLocation fileLocation, TLObject owner, int fileSize) { Execute.BeginOnThreadPool(() => { var downloadableItem = GetDownloadableItem(originalFileName, dcId, fileLocation, owner, fileSize); var downloadedCount = downloadableItem.Parts.Count(x => x.Status == PartStatus.Processed); var count = downloadableItem.Parts.Count; var isComplete = downloadedCount == count; if (isComplete) { //var id = downloadableItem.InputDocumentLocation.Id; //var accessHash = downloadableItem.InputDocumentLocation.AccessHash; var fileExtension = Path.GetExtension(downloadableItem.FileName.ToString()); var fileName = GetFileName(downloadableItem.InputDocumentLocation, fileExtension); //string.Format("document{0}_{1}{2}", id, accessHash, fileExtension); Func <DownloadablePart, string> getPartName = x => downloadableItem.InputDocumentLocation.GetPartFileName(x.Number); //string.Format("document{0}_{1}_{2}.dat", id, accessHash, x.Number); FileUtils.MergePartsToFile(getPartName, downloadableItem.Parts, fileName); downloadableItem.IsoFileName = fileName; _eventAggregator.Publish(downloadableItem); } else { var progress = downloadedCount / (double)count; Execute.BeginOnThreadPool(() => _eventAggregator.Publish(new DownloadProgressChangedEventArgs(downloadableItem, progress))); lock (_itemsSyncRoot) { bool addFile = true; foreach (var item in _items) { if (item.InputDocumentLocation.AccessHash == fileLocation.AccessHash && item.InputDocumentLocation.Id == fileLocation.Id) { //item.SuppressMerge = true; //item. if (item.Owner == owner) { Execute.ShowDebugMessage("Cancel document=" + fileLocation.Id); addFile = false; break; } } } if (addFile) { _items.Add(downloadableItem); } } StartAwaitingWorkers(); } }); }
public void DownloadFileAsync(TLString originalFileName, TLInt dcId, TLInputDocumentFileLocation fileLocation, TLObject owner, TLInt fileSize, Action <double> callback) { Execute.BeginOnThreadPool(() => { var downloadableItem = GetDownloadableItem(originalFileName, dcId, fileLocation, owner, fileSize); var downloadedCount = downloadableItem.Parts.Count(x => x.Status == PartStatus.Processed); var count = downloadableItem.Parts.Count; var isComplete = downloadedCount == count; if (isComplete) { var id = downloadableItem.InputDocumentLocation.Id; var accessHash = downloadableItem.InputDocumentLocation.AccessHash; var fileExtension = Path.GetExtension(downloadableItem.FileName.ToString()); var fileName = string.Format("document{0}_{1}{2}", id, accessHash, fileExtension); Func <DownloadablePart, string> getPartName = x => string.Format("document{0}_{1}_{2}.dat", id, accessHash, x.Number); FileUtils.MergePartsToFile(getPartName, downloadableItem.Parts, fileName); downloadableItem.IsoFileName = fileName; _eventAggregator.Publish(downloadableItem); } else { var progress = downloadedCount / (double)count; callback.SafeInvoke(progress); lock (_itemsSyncRoot) { bool addFile = true; foreach (var item in _items) { if (item.InputDocumentLocation.AccessHash.Value == fileLocation.AccessHash.Value && item.InputDocumentLocation.Id.Value == fileLocation.Id.Value && item.Owner == owner) { addFile = false; break; } } if (addFile) { _items.Add(downloadableItem); } } StartAwaitingWorkers(); } }); }
private DownloadableItem GetDownloadableItem(string fileName, int dcId, TLInputDocumentFileLocation location, TLObject owner, int fileSize) { var item = new DownloadableItem { DCId = dcId, FileName = fileName, Owner = owner, InputDocumentLocation = location }; item.Parts = GetItemParts(fileSize, item); return(item); }
public static string GetFileName(TLInputDocumentFileLocation fileLocation, string fileExtension) { var fileLocation54 = fileLocation as TLInputDocumentFileLocation; var id = fileLocation.Id; var accessHash = fileLocation.AccessHash; var version = fileLocation54.Version; if (version > 0) { return(string.Format("document{0}_{1}{2}", id, version, fileExtension)); } return(string.Format("document{0}_{1}{2}", id, accessHash, fileExtension)); }
private TLUploadFileBase GetFile(int dcId, TLInputDocumentFileLocation location, int offset, int limit, out TLRPCError er, out bool isCanceled) { var manualResetEvent = new ManualResetEvent(false); TLUploadFileBase result = null; TLRPCError outError = null; var outIsCanceled = false; _mtProtoService.GetFileAsync(dcId, location, offset, limit, callback => { result = callback; manualResetEvent.Set(); if (callback is TLUploadFile file) { _statsService.IncrementReceivedBytesCount(_mtProtoService.NetworkType, _dataType, 4 + 4 + file.Bytes.Length + 4); } }, error => { outError = error; if (error.CodeEquals(TLErrorCode.INTERNAL) || (error.CodeEquals(TLErrorCode.BAD_REQUEST) && (error.TypeEquals(TLErrorType.LOCATION_INVALID) || error.TypeEquals(TLErrorType.VOLUME_LOC_NOT_FOUND))) || (error.CodeEquals(TLErrorCode.NOT_FOUND) && error.ErrorMessage != null && error.ErrorMessage.ToString().StartsWith("Incorrect dhGen"))) { outIsCanceled = true; manualResetEvent.Set(); return; } int delay; lock (_randomRoot) { delay = _random.Next(1000, 3000); } Execute.BeginOnThreadPool(TimeSpan.FromMilliseconds(delay), () => manualResetEvent.Set()); }); manualResetEvent.WaitOne(); er = outError; isCanceled = outIsCanceled; return(result); }
public IEnumerable <TLFile> GetDocument(TLDocument document) { TLAbsInputFileLocation inputDocument = new TLInputDocumentFileLocation() { id = document.id, access_hash = document.access_hash, version = document.version, }; int iRemainingSize = document.size; int iOffset = 0; int iRead; TLFile file; while (iRemainingSize > 0) { file = (TLFile)AsyncHelpers.RunSync <TLFile>(() => m_client.GetFile(inputDocument, iRemainingSize, iOffset)); iRead = file.bytes.Length; iRemainingSize -= iRead; iOffset += iRead; yield return(file); } }
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); } } } } } } }
public IAsyncOperationWithProgress <DownloadableItem, double> DownloadFileAsync(string originalFileName, int dcId, TLInputDocumentFileLocation fileLocation, int fileSize) { return(AsyncInfo.Run <DownloadableItem, double>((token, progress) => { var tsc = new TaskCompletionSource <DownloadableItem>(); var downloadableItem = GetDownloadableItem(originalFileName, dcId, fileLocation, null, fileSize); downloadableItem.Callback = tsc; downloadableItem.Progress = progress; var downloadedCount = downloadableItem.Parts.Count(x => x.Status == PartStatus.Processed); var count = downloadableItem.Parts.Count; var isComplete = downloadedCount == count; if (isComplete) { //var id = downloadableItem.InputDocumentLocation.Id; //var accessHash = downloadableItem.InputDocumentLocation.AccessHash; var fileExtension = Path.GetExtension(downloadableItem.FileName.ToString()); var fileName = GetFileName(downloadableItem.InputDocumentLocation, fileExtension); //string.Format("document{0}_{1}{2}", id, accessHash, fileExtension); Func <DownloadablePart, string> getPartName = x => downloadableItem.InputDocumentLocation.GetPartFileName(x.Number); //string.Format("document{0}_{1}_{2}.dat", id, accessHash, x.Number); FileUtils.MergePartsToFile(getPartName, downloadableItem.Parts, fileName); downloadableItem.IsoFileName = fileName; downloadableItem.Progress.Report(1.0); downloadableItem.Callback.TrySetResult(downloadableItem); } else { downloadableItem.Progress.Report(downloadedCount / (double)count); lock (_itemsSyncRoot) { bool addFile = true; foreach (var item in _items) { if (item.InputDocumentLocation.AccessHash == fileLocation.AccessHash && item.InputDocumentLocation.Id == fileLocation.Id) { downloadableItem.Callback = item.Callback; downloadableItem.Progress = item.Progress; addFile = false; Debug.WriteLine("Already downloading document"); //item.SuppressMerge = true; //item. //if (item.Owner == owner) //{ // Execute.ShowDebugMessage("Cancel document=" + fileLocation.Id); // addFile = false; // break; //} } } if (addFile) { _items.Add(downloadableItem); } } StartAwaitingWorkers(); } return tsc.Task; })); }
private TLUploadFileBase ReuploadFile(TLUploadFileCdnRedirect redirect, byte[] requestToken, int dcId, TLInputDocumentFileLocation location, int offset, int limit, out TLRPCError er, out bool isCanceled) { var manualResetEvent = new ManualResetEvent(false); TLUploadFileBase result = null; TLRPCError outError = null; var outIsCanceled = false; var req = new TLUploadReuploadCdnFile(); req.FileToken = redirect.FileToken; req.RequestToken = requestToken; _mtProtoService.SendRequestAsync <bool>("upload.reuploadCdnFile", req, dcId, false, callback => { if (callback) { result = GetCdnFile(redirect, dcId, location, offset, limit, out outError, out outIsCanceled); while (result == null) { result = GetCdnFile(redirect, dcId, location, offset, limit, out outError, out outIsCanceled); if (outIsCanceled) { break; } } manualResetEvent.Set(); } }, error => { outError = error; if (error.CodeEquals(TLErrorCode.INTERNAL) || (error.CodeEquals(TLErrorCode.BAD_REQUEST) && (error.TypeEquals(TLErrorType.LOCATION_INVALID) || error.TypeEquals(TLErrorType.VOLUME_LOC_NOT_FOUND))) || (error.CodeEquals(TLErrorCode.NOT_FOUND) && error.ErrorMessage != null && error.ErrorMessage.ToString().StartsWith("Incorrect dhGen"))) { outIsCanceled = true; manualResetEvent.Set(); return; } int delay; lock (_randomRoot) { delay = _random.Next(1000, 3000); } Execute.BeginOnThreadPool(TimeSpan.FromMilliseconds(delay), () => manualResetEvent.Set()); }); manualResetEvent.WaitOne(); er = outError; isCanceled = outIsCanceled; return(result); }
private TLUploadFileBase GetCdnFile(TLUploadFileCdnRedirect redirect, int dcId, TLInputDocumentFileLocation location, int offset, int limit, out TLRPCError er, out bool isCanceled) { var manualResetEvent = new ManualResetEvent(false); TLUploadFileBase result = null; TLRPCError outError = null; var outIsCanceled = false; var req = new TLUploadGetCdnFile(); req.FileToken = redirect.FileToken; req.Limit = limit; req.Offset = offset; _mtProtoService.SendRequestAsync <TLUploadCdnFileBase>("upload.getCdnFile", req, redirect.DCId, true, callback => { if (callback is TLUploadCdnFile file) { var iv = redirect.EncryptionIV; var counter = offset / 16; iv[15] = (byte)(counter & 0xFF); iv[14] = (byte)((counter >> 8) & 0xFF); iv[13] = (byte)((counter >> 16) & 0xFF); iv[12] = (byte)((counter >> 24) & 0xFF); var key = CryptographicBuffer.CreateFromByteArray(redirect.EncryptionKey); var ecount_buf = new byte[0]; var num = 0u; var bytes = Utils.AES_ctr128_encrypt(file.Bytes, key, ref iv, ref ecount_buf, ref num); result = new TLUploadFile { Bytes = bytes }; manualResetEvent.Set(); _statsService.IncrementReceivedBytesCount(_mtProtoService.NetworkType, _dataType, file.Bytes.Length + 4); } else if (callback is TLUploadCdnFileReuploadNeeded reupload) { result = ReuploadFile(redirect, reupload.RequestToken, dcId, location, offset, limit, out outError, out outIsCanceled); while (result == null) { result = ReuploadFile(redirect, reupload.RequestToken, dcId, location, offset, limit, out outError, out outIsCanceled); if (outIsCanceled) { break; } } manualResetEvent.Set(); } }, error => { outError = error; if (error.CodeEquals(TLErrorCode.INTERNAL) || (error.CodeEquals(TLErrorCode.BAD_REQUEST) && (error.TypeEquals(TLErrorType.LOCATION_INVALID) || error.TypeEquals(TLErrorType.VOLUME_LOC_NOT_FOUND))) || (error.CodeEquals(TLErrorCode.NOT_FOUND) && error.ErrorMessage != null && error.ErrorMessage.ToString().StartsWith("Incorrect dhGen"))) { outIsCanceled = true; manualResetEvent.Set(); return; } int delay; lock (_randomRoot) { delay = _random.Next(1000, 3000); } Execute.BeginOnThreadPool(TimeSpan.FromMilliseconds(delay), () => manualResetEvent.Set()); }); manualResetEvent.WaitOne(); er = outError; isCanceled = outIsCanceled; return(result); }
private TLUploadFileBase GetCdnFile(TLUploadFileCdnRedirect redirect, int dcId, TLInputDocumentFileLocation location, int offset, int limit, out TLRPCError er, out bool isCanceled) { var manualResetEvent = new ManualResetEvent(false); TLUploadFileBase result = null; TLRPCError outError = null; var outIsCanceled = false; _protoService.GetCdnFileAsync(redirect.DCId, redirect.FileToken, offset, limit, callback => { if (callback is TLUploadCdnFile file) { result = new TLUploadFile { Bytes = file.Bytes }; manualResetEvent.Set(); _statsService.IncrementReceivedBytesCount(_protoService.NetworkType, _dataType, file.Bytes.Length + 4); } else if (callback is TLUploadCdnFileReuploadNeeded reupload) { result = ReuploadFile(redirect, reupload.RequestToken, dcId, location, offset, limit, out outError, out outIsCanceled); while (result == null) { result = ReuploadFile(redirect, reupload.RequestToken, dcId, location, offset, limit, out outError, out outIsCanceled); if (outIsCanceled) { break; } } manualResetEvent.Set(); } }, error => { outError = error; if (error.CodeEquals(TLErrorCode.INTERNAL) || (error.CodeEquals(TLErrorCode.BAD_REQUEST) && (error.TypeEquals(TLErrorType.LOCATION_INVALID) || error.TypeEquals(TLErrorType.VOLUME_LOC_NOT_FOUND))) || (error.CodeEquals(TLErrorCode.NOT_FOUND) && error.ErrorMessage != null && error.ErrorMessage.StartsWith("Incorrect dhGen"))) { outIsCanceled = true; manualResetEvent.Set(); return; } int delay; lock (_randomRoot) { delay = _random.Next(1000, 3000); } Execute.BeginOnThreadPool(TimeSpan.FromMilliseconds(delay), () => manualResetEvent.Set()); }); manualResetEvent.WaitOne(20 * 1000); er = outError; isCanceled = outIsCanceled; return(result); }