private TLFile GetFile(TLInt dcId, TLInputFileLocationBase 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 async Task <TLFile> GetFile(TLAbsInputFileLocation location, int filePartSize, int offset = 0, CancellationToken token = default(CancellationToken)) { TLFile result = await SendAuthenticatedRequestAsync <TLFile>(new TLRequestGetFile { Location = location, Limit = filePartSize, Offset = offset }, token) .ConfigureAwait(false); return(result); }
public async Task <TLFile> GetFile(TLAbsInputFileLocation location, int filePartSize, int offset = 0) { TLFile result = null; result = await SendRequestAsync <TLFile>(new TLRequestGetFile() { Location = location, Limit = filePartSize, Offset = offset }); return(result); }
public TLFile GetFile(TLFileLocation fileLocation, int iSize) { TLAbsInputFileLocation inputFileLocation = new TLInputFileLocation() { volume_id = fileLocation.volume_id, local_id = fileLocation.local_id, secret = fileLocation.secret, }; TLFile file = (TLFile)AsyncHelpers.RunSync <TLFile>(() => m_client.GetFile(inputFileLocation, iSize)); if (file.bytes.Length != iSize) { throw new TLCoreException("The file need to be downloaded in parts"); } return(file); }
public async Task <TLFile> GetFile(TLAbsInputFileLocation location, int filePartSize, int offset = 0) { TLFile result = null; try { result = await SendRequestAsync <TLFile>(new TLRequestGetFile() { location = location, limit = filePartSize, offset = offset }); } catch (FileMigrationException ex) { var exportedAuth = await SendRequestAsync <TLExportedAuthorization>(new TLRequestExportAuthorization() { dc_id = ex.DC }); var authKey = _session.AuthKey; var timeOffset = _session.TimeOffset; var serverAddress = _session.ServerAddress; var serverPort = _session.Port; await ReconnectToDcAsync(ex.DC); var auth = await SendRequestAsync <TLauthorization>(new TLRequestImportAuthorization { bytes = exportedAuth.bytes, id = exportedAuth.id }); result = await GetFile(location, filePartSize); _session.AuthKey = authKey; _session.TimeOffset = timeOffset; _transport = new TcpTransport(serverAddress, serverPort); _session.ServerAddress = serverAddress; _session.Port = serverPort; await ConnectAsync(); } return(result); }
public async System.Threading.Tasks.Task AuthAsync() { var store = new FileSessionStore(); var apiId = 434408; var apiHash = "0bdea67547ee00f2e164a5522174d7dc"; var client = new TelegramClient(apiId, apiHash); await client.ConnectAsync(); if (client.IsUserAuthorized() == false) { var phone = metroComboBox1.Text + metroTextBox1.Text; var hash = await client.SendCodeRequestAsync(phone); var code = Microsoft.VisualBasic.Interaction.InputBox("Введите код полученый в СМС:"); var user = await client.MakeAuthAsync(phone, hash, code); var photo = ((TLUserProfilePhoto)user.Photo); var photoLocation = (TLFileLocation)photo.PhotoBig; TLFile file = await client.GetFile(new TLInputFileLocation() { LocalId = photoLocation.LocalId, Secret = photoLocation.Secret, VolumeId = photoLocation.VolumeId }, 1024 * 256); using (var m = new MemoryStream(file.Bytes)) { var img = Image.FromStream(m); img.Save("profileimg", System.Drawing.Imaging.ImageFormat.Jpeg); } var rq = new TeleSharp.TL.Users.TLRequestGetFullUser { Id = new TLInputUserSelf() }; TLUserFull rUserSelf = await client.SendRequestAsync <TeleSharp.TL.TLUserFull>(rq); TLUser userSelf = (TLUser)rUserSelf.User; Properties.Settings.Default.Name = userSelf.Username; Properties.Settings.Default.Save(); this.Hide(); Main main = new Main(); main.ShowDialog(); } }
/// <summary> /// 텔레그램 메세지에 있는 사진 파일 저장. /// </summary> /// <param name="photoMsg"></param> /// <returns></returns> string SavePhoto(TeleSharp.TL.TLMessageMediaPhoto photoMsg) { var photo = ((TLPhoto)photoMsg.Photo); var photoSize = photo.Sizes.OfType <TLPhotoSize>().OrderByDescending(m => m.Size).FirstOrDefault(); TLFileLocation tf = (TLFileLocation)photoSize.Location; string fileName = $"{photo.Id}.jpg"; string path = Path.Combine(Directory.GetCurrentDirectory(), fileName); try { var mb = 1048576; var upperLimit = (int)Math.Pow(2, Math.Ceiling(Math.Log(photoSize.Size, 2))) * 4; var limit = Math.Min(mb, upperLimit); var currentOffset = 0; using (var fs = File.OpenWrite(path)) { while (currentOffset < photoSize.Size) { TLFile file = Client.GetFile(new TLInputFileLocation { LocalId = tf.LocalId, Secret = tf.Secret, VolumeId = tf.VolumeId }, limit, currentOffset).ConfigureAwait(false).GetAwaiter().GetResult(); fs.Write(file.Bytes, currentOffset, file.Bytes.Length); currentOffset += file.Bytes.Length; } fs.Close(); } } catch (Exception ex) { Console.WriteLine($" getFile (size:{photoSize.Size}) : {ex.Message} \n {ex.StackTrace}"); return(""); } return(fileName); }
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); } } } } } } }
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 }
protected TLFileBase GetCdnFile(TLFileCdnRedirect redirect, TLInt offset, TLInt limit, out TLCdnFileReuploadNeeded reuploadNeeded, out TLRPCError er, out bool isCanceled, out bool isTokenInvalid) { var manualResetEvent = new ManualResetEvent(false); TLFileBase result = null; TLCdnFileReuploadNeeded outReuploadNeeded = null; TLRPCError outError = null; var outIsCanceled = false; var outIsTokenInvalid = false; _mtProtoService.GetCdnFileAsync(redirect.DCId, redirect.FileToken, offset, limit, cdnFileBase => { var cdnFile = cdnFileBase as TLCdnFile; if (cdnFile != null) { var iv = GetIV(redirect.EncryptionIV.Data, offset); var counter = offset.Value / 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 = redirect.EncryptionKey.Data; var ecount_buf = new byte[0]; var num = 0u; var bytes = Utils.AES_ctr128_encrypt(cdnFile.Bytes.Data, key, ref iv, ref ecount_buf, ref num); result = new TLFile { Bytes = TLString.FromBigEndianData(bytes) }; } var cdnFileReuploadNeeded = cdnFileBase as TLCdnFileReuploadNeeded; if (cdnFileReuploadNeeded != null) { outReuploadNeeded = cdnFileReuploadNeeded; } manualResetEvent.Set(); }, error => { outError = error; if (error.CodeEquals(ErrorCode.INTERNAL) || (error.CodeEquals(ErrorCode.BAD_REQUEST) && (error.TypeEquals(ErrorType.LOCATION_INVALID) || error.TypeEquals(ErrorType.VOLUME_LOC_NOT_FOUND))) || (error.CodeEquals(ErrorCode.NOT_FOUND) && error.Message != null && error.Message.ToString().StartsWith("Incorrect dhGen"))) { outIsCanceled = true; manualResetEvent.Set(); return; } if (error.CodeEquals(ErrorCode.BAD_REQUEST) && error.TypeEquals(ErrorType.FILE_TOKEN_INVALID)) { outIsTokenInvalid = true; manualResetEvent.Set(); return; } int delay; lock (_randomRoot) { delay = _random.Next(1000, 3000); } Execute.BeginOnThreadPool(TimeSpan.FromMilliseconds(delay), () => manualResetEvent.Set()); }); manualResetEvent.WaitOne(); reuploadNeeded = outReuploadNeeded; er = outError; isCanceled = outIsCanceled; isTokenInvalid = outIsTokenInvalid; return(result); }
public async Task <Task> Send(List <TLMessage> messages, Dictionary <int, int> MessageMap, TLChannel channel, Dictionary <int, string> MessageCheckMap) { var config = Config.Configs.Instance; foreach (var message in messages) { var messageId = message.Id; if (messageId > MessageMap[channel.Id]) { string msg = ""; if (message.Media != null) { if (message.Media is TeleSharp.TL.TLMessageMediaPhoto) { var photoMsg = message.Media as TeleSharp.TL.TLMessageMediaPhoto; var photo = ((TLPhoto)photoMsg.Photo); var photoSize = photo.Sizes.OfType <TLPhotoSize>().OrderByDescending(m => m.Size).FirstOrDefault(); TLFileLocation tf = (TLFileLocation)photoSize.Location; string fileName = $"{photo.Id}.jpg"; string path = Path.Combine(Directory.GetCurrentDirectory(), fileName); try { /* * var mb = 1048576; * var upperLimit = (int)Math.Pow(2, Math.Ceiling(Math.Log(fileInfo.Size, 2))) * 4; * var limit = Math.Min(mb, upperLimit); * * var currentOffset = 0; * using (var fs = File.OpenWrite(filename)) * { * while (currentOffset < fileInfo.Size) * { * file = m_telegramClient.GetFile(fileLocation, limit, currentOffset).ConfigureAwait(false).GetAwaiter().GetResult(); * fs.Write(file.Bytes, currentOffset, file.Bytes.Length); * currentOffset += file.Bytes.Length; * } * * fs.Close(); * } */ var mb = 1048576; var upperLimit = (int)Math.Pow(2, Math.Ceiling(Math.Log(photoSize.Size, 2))) * 4; var limit = Math.Min(mb, upperLimit); var currentOffset = 0; using (var fs = File.OpenWrite(path)) { while (currentOffset < photoSize.Size) { TLFile file = Client.GetFile(new TLInputFileLocation { LocalId = tf.LocalId, Secret = tf.Secret, VolumeId = tf.VolumeId }, limit, currentOffset).ConfigureAwait(false).GetAwaiter().GetResult(); fs.Write(file.Bytes, currentOffset, file.Bytes.Length); currentOffset += file.Bytes.Length; } fs.Close(); } /*var resFile2 = await Client.GetFile(tf as TLInputFileLocation, Math.Min(1024 * 256, photoSize.Size)); * var resFile = await Client.GetFile(new TLInputFileLocation { LocalId = tf.LocalId, Secret = tf.Secret, VolumeId = tf.VolumeId }, Math.Min(1024 * 256, photoSize.Size)); * File.WriteAllBytes(path, resFile.Bytes);*/ } catch (Exception ex) { Console.WriteLine($" getFile (size:{photoSize.Size}) : {ex.Message} \n {ex.StackTrace}"); continue; } //var resFile = await Client.GetFile(new TLInputFileLocation { LocalId = fl.LocalId, Secret = fl.Secret, VolumeId = fl.VolumeId }, photoSize.Size); /*ar cachedPhotos = photo.Sizes.OfType<TLPhotoCachedSize>().ToList(); * foreach(var o in cachedPhotos) * { * Console.WriteLine($""); * }*/ // (((TLMessageMediaPhoto)message.Media).Photo as TLPhoto). var caption = ((TLMessageMediaPhoto)message.Media).Caption; DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); DateTime dt = dtDateTime.AddSeconds(message.Date); if (!string.IsNullOrEmpty(caption)) { Console.WriteLine($"photo msg received. [ {caption} ] msg_time [{dt:yyyy-MM-dd HH:mm:ss}]"); msg = caption; } else { Console.WriteLine($"photo msg received but caption empty. msg_time [{dt:yyyy-MM-dd HH:mm:ss}]"); } var fileResult = /*(TLInputFile)*/ await Client.UploadFile(fileName, new StreamReader(path)); Console.WriteLine($"{Receiver.Instance.ForwardChannelId} // {Receiver.Instance.ForwardChannelAccessHash}"); var updates = await Client.SendUploadedPhoto(new TLInputPeerChannel() { ChannelId = Receiver.Instance.ForwardChannelId, AccessHash = Receiver.Instance.ForwardChannelAccessHash }, fileResult, msg); /*var tlUpdate = updates as TLUpdateChannel; * * if(updates is TLUpdateNewMessage _msg) * { * if ( _msg.Message is TLMessage tlmsg) * { * if( tlmsg.Media != null) * { * Console.WriteLine($"{tlmsg.Id}"); * } * } * }*/ } } else { DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); DateTime dt = dtDateTime.AddSeconds(message.Date); Console.WriteLine($" new msg received . [{channel.Title}] from [{channel.Username}]. msg [{ message.Message}] msg_time [{dt:yyyy-MM-dd HH:mm:ss}]"); msg = message.Message; if (!string.IsNullOrEmpty(msg)) { msg += $"\n\n FROM {channel.Title}"; await Client.SendMessageAsync(new TLInputPeerChannel() { ChannelId = Receiver.Instance.ForwardChannelId, AccessHash = Receiver.Instance.ForwardChannelAccessHash }, msg); Console.WriteLine($"Message Send Success From [{channel.Title}]. \n Message >>>> {msg}"); } /*if (channel.Title.ToLower().Contains("rose premium")) * { * msg += $"\n\n FROM Rose"; * await Client.SendMessageAsync(new TLInputPeerChannel() { ChannelId = Receiver.Instance.ForwardChannelId, AccessHash = Receiver.Instance.ForwardChannelAccessHash }, msg); * Console.WriteLine($"Message Send Success From [{channel.Title}]. \n Message >>>> {msg}"); * } * else * { * // 필터링 * foreach (var str in config.channelKeywords["common"]) * { * if (msg != null && msg.Contains(str)) * { * msg += $"\n\n FROM {channel.Title}"; * await Client.SendMessageAsync(new TLInputPeerChannel() { ChannelId = Receiver.Instance.ForwardChannelId, AccessHash = Receiver.Instance.ForwardChannelAccessHash }, msg); * Console.WriteLine($"Message Send Success From [{channel.Title}]. \n Message >>>> {msg}"); * } * } * * }*/ } // 메세지 번호 업데이트 MessageMap[channel.Id] = messageId; if (MessageCheckMap.ContainsKey(channel.Id)) { MessageCheckMap[channel.Id] = msg; } else { MessageCheckMap.Add(channel.Id, msg); } if (string.IsNullOrEmpty(msg)) { continue; } } } return(Task.CompletedTask); }