public string GetPDFToTxtFilePath(string codeId, FMType fmType) { string txtFilePath = string.Empty; string pdfUrl = GetPDFUrl(codeId); string pdfFilePath = string.Empty; if (pdfUrl == null) { return(null); } if (fmType == FMType.Cbbc) { pdfFilePath = configObj.OutPutDir + "\\" + pdfFileDir + "\\" + "CBBC" + "\\" + codeId + ".pdf"; } else { pdfFilePath = configObj.OutPutDir + "\\" + pdfFileDir + "\\" + "Warrant" + "\\" + codeId + ".pdf"; } if (!Directory.Exists(Path.GetDirectoryName(pdfFilePath))) { Directory.CreateDirectory(Path.GetDirectoryName(pdfFilePath)); } WebClientUtil.DownloadFile(pdfUrl, 24000, pdfFilePath); txtFilePath = PDFToTxt(codeId, pdfFilePath, fmType); return(txtFilePath); }
//Transfer PDF to TXT file public String PDFToTxt(String ricCode, String pdfFilePath, FMType fmType) { string command = "pdftotext.exe"; string txtPath = string.Empty; if (fmType == FMType.Cbbc) { txtPath = configObj.OutPutDir + "\\" + pdfFileDir + "\\" + "CBBC" + "\\" + ricCode + ".txt"; } else { txtPath = configObj.OutPutDir + "\\" + pdfFileDir + "\\" + "Warrant" + "\\" + ricCode + ".txt"; } if (!Directory.Exists(Path.GetDirectoryName(txtPath))) { Directory.CreateDirectory(Path.GetDirectoryName(txtPath)); } string parameters = "-layout -enc UTF-8 -q " + pdfFilePath + " " + txtPath; try { using (ProcessContext p = new ProcessContext(command, parameters, ".")) { p.ProcessInstance.Start(); } } catch (Exception ex) { Logger.LogErrorAndRaiseException("Error accured when transferring PDF to txt. " + ex.Message); } return(txtPath); }
public void PDFAnalysis(RicInfo ric, FMType fmType) { string ricCode = ric.Code; string path = string.Empty; path = GetPDFToTxtFilePath(ricCode, fmType); if (!File.Exists(path)) { return; } ric.Gear = GetGear(path, ricCode); ric.Premium = GetPremium(path, ricCode); }
public HKRicTemplate(RicInfo ricInfo, FMType fmType) { bool isIndex = false; bool isCall = false; bool isHKD = false; bool isStock = false; bool isOil = false; bool isCommodity = false; if (ricInfo.Underlying == "HSI" || ricInfo.Underlying == "HSCEI" || ricInfo.Underlying == "DJI") { isIndex = true; } if (Char.IsDigit(ricInfo.Underlying, 0)) { isStock = true; } if (ricInfo.Name.Contains("OIL")) { isOil = true; } if (ricInfo.BullBear.ToLower().Contains("call")) { isCall = true; } if (ricInfo.Name.Contains("GOLD") || ricInfo.Name.Contains("SILVER")) { isCommodity = true; } if (Char.IsLetter(ricInfo.StrikeLevel, 0)) { isHKD = true; } issuerCodeObj = ConfigUtil.ReadConfig(issuerCodeMapPath, typeof(HK_IssuerCodeMap)) as HK_IssuerCodeMap; DateTime effectiveDate = DateTime.ParseExact(ricInfo.ListingDate, "dd-MM-yyyy", null); EffectiveDate = effectiveDate.ToString("dd-MMM-yy"); UnderLyingRic = ricInfo.Code + ".HK"; CompositeChainRic = "0#" + ricInfo.Code + ".HK"; BrokerPageRic = ricInfo.Code + "bk.HK"; MiscInfoPageRic = ricInfo.Code + "MI.HK"; DisplayName = ricInfo.Name; OfficicalCode = ricInfo.Code; ExchangeSymbol = ricInfo.Code; Currency = "HKD"; RecordType = "097"; SpareUbytes8 = "WRNT"; #region For CBBC only //For CBBC only if (fmType == FMType.Cbbc) { IdnLongName = GetIDNLongName(ricInfo); UnderlyingChainRic1 = "0#CBBC.HK"; UnderlyingChainRic2 = "0#WARRANTS.HK"; GNTX20_10 = "CBBC/" + ricInfo.BullBear; GNTX20_10 = GNTX20_10.ToUpper(); Row80_13 = "Callable " + ricInfo.BullBear + " Contracts"; WarrantType = "Callable " + ricInfo.BullBear + " Contracts"; RdmCur = "344"; if (ricInfo.BullBear.ToLower().Contains("bear")) { GVFlag = "P"; } if (ricInfo.BullBear.ToLower().Contains("bull")) { GVFlag = "C"; } if (Char.IsLetter(ricInfo.StrikeLevel, 0)) { CallLevel = ricInfo.CallLevel.Substring(4); } else { CallLevel = ricInfo.CallLevel; } if (Char.IsLetter(ricInfo.Underlying, 0)) { GNTX20_12 = "IDX~~~~~~<" + ricInfo.Code + "MI.HK>"; IssTpFlg = "I"; if (ricInfo.Underlying == "HSCEI") { GNTX20_6 = "<.HSCE"; LongLink14 = ".HSCE|HKD|1 <-- TQR INSERT DAILY"; } else if (ricInfo.Underlying == "HSI") { LongLink14 = ".HSI|HKD|1 <-- TQR INSERT DAILY"; GNTX20_6 = "<." + ricInfo.Underlying + ">"; } else if (ricInfo.Underlying == "DJI") { LongLink14 = ".DJI|USD|1 <-- TQR INSERT DAILY"; GNTX20_6 = "<." + ricInfo.Underlying + ">"; } else { GNTX20_6 = "<." + ricInfo.Underlying + ">"; LongLink14 = "Index not equal HSI,HSCEI or DJI"; } } else { GNTX20_12 = "HKD~~~~~~<" + ricInfo.Code + "MI.HK>"; IssTpFlg = "S"; GNTX20_6 = "<" + ricInfo.Underlying + ".HK>"; LongLink14 = ricInfo.Underlying.Substring(1) + ".HK"; } } #endregion #region For Warrant only else { GNTX20_10 = "EU/" + ricInfo.BullBear; GNTX20_10 = GNTX20_10.ToUpper(); Row80_13 = "Equity Warrant"; IdnLongName = GetIDNLongNameForWarrant(ricInfo, isIndex, isStock, isCall, isHKD, issuerCodeObj); if (isCall) { GVFlag = "C"; } else { GVFlag = "P"; } if (isStock) { UnderlyingChainRic1 = "0#" + ricInfo.Underlying.Substring(1) + "W.HK"; ChainRic1 = "0#CWRTS.HK"; WarrantType = "Equity Warrant"; GNTX20_6 = "<" + ricInfo.Underlying.Substring(1) + ".HK>"; GNTX20_12 = "HKD~~~~~~<" + ricInfo.Code + "MI.HK>"; IssTpFlg = "S"; RdmCur = "344"; LongLink14 = ricInfo.Underlying.Substring(1) + ".HK"; } else if (isIndex) { ChainRic1 = ""; Row80_13 = "Index Warrant"; GNTX20_12 = "IDX~~~~~~<" + ricInfo.Code + "MI.HK>"; RdmCur = "344"; if (ricInfo.Underlying == "HSCEI") { UnderlyingChainRic1 = "0#.HSCEW.HK"; WarrantType = "Hang Seng China Enterprises Index Warrant"; GNTX20_6 = "<.HSCE>"; LongLink14 = ".HSCE|HKD|1 <-- TQR INSERT DAILY"; } else if (ricInfo.Underlying == "HSI") { WarrantType = "Hang Seng Index Warrant"; UnderlyingChainRic1 = "0#." + ricInfo.Underlying + "W.HK"; GNTX20_6 = "<." + ricInfo.Underlying + ">"; LongLink14 = ".HSI|HKD|1 <-- TQR INSERT DAILY"; } else { if (ricInfo.Underlying == "DJI") { LongLink14 = ".DJI|USD|1 <-- TQR INSERT DAILY"; } else { LongLink14 = "Index not equal HSI,HSCEI or DJI"; } UnderlyingChainRic1 = "0#." + ricInfo.Underlying + "W.HK"; WarrantType = "DJ Industrial Average Index Warrant"; } IssTpFlg = "I"; } else if (isOil) { ChainRic1 = "0#OWRTS.HK"; WarrantType = "Oil Warrant"; Row80_13 = "Future Warrant"; RdmCur = "840"; } else if (isCommodity) { Row80_13 = "Commodity Warrant"; UnderlyingChainRic1 = string.Empty; ChainRic1 = "0#OWRTS.HK"; WarrantType = "Miscellaneous Warrant"; RdmCur = "840"; } else { //isCurrency = true; if (ricInfo.Name.Contains("YEN")) { RdmCur = "392"; } UnderlyingChainRic1 = string.Empty; ChainRic1 = "0#OWRTS.HK"; WarrantType = "Miscellaneous Warrant"; Row80_13 = "Currency Warrant"; IssTpFlg = "F"; RdmCur = string.Empty; LongLink14 = string.Empty; } } #endregion ChainRic2 = "0#WARRANTS.HK"; MiscInfoPageChainRic = "0#MI.HK"; LotSize = ricInfo.BoardLot; //ColDsplyNmll ColDsplyNmll = GetColDsplyNmllInfo(ricInfo); BcastRef = "n/a"; WntRation = (1.0 / Convert.ToDouble(ricInfo.EntitlementRatio)).ToString(); if (Char.IsLetter(ricInfo.StrikeLevel, 0)) { StrikPrc = ricInfo.StrikeLevel.Substring(4); } else { StrikPrc = ricInfo.StrikeLevel; } DateTime maturDate = DateTime.ParseExact(ricInfo.MaturityDate, "dd-MM-yyyy", null); MaturDate = maturDate.ToString("dd-MMM-yy"); LongLink3 = "t" + ricInfo.Code + ".HK"; SpareSnum13 = "1"; GNTX20_3 = "[HK-\"WARRAN*\"]"; GNTX20_7 = "********************"; GNTX20_11 = ricInfo.TotalIssueSize; CouponRate = "n/a"; IssuePrice = ricInfo.IssuerPrice; BondType = "WARRANTS"; Leg1Str = string.Empty; Leg2Str = string.Empty; GNTXT24_1 = string.Empty; GNTXT24_2 = string.Empty; NewOrgList = string.Empty; PrimaryList = string.Empty; OrgnizationName1 = string.Empty; GeographyEntity = string.Empty; OrgnizationType = string.Empty; AliasPre = string.Empty; AliasGen = string.Empty; IssueClassification = string.Empty; MSCICode = string.Empty; BusinessActivity = string.Empty; ExistingOrgList = string.Empty; PrimaryList = string.Empty; OrgnizationName2 = GetIssuerName(ricInfo.Issuer, issuerCodeObj)[1]; IssueClassification = "WNT"; //For WRT_CNR Gearing = ricInfo.Gear; Premium = ricInfo.Premium; DateTime announcementData = DateTime.ParseExact(ricInfo.LauntchDate, "dd-MM-yyyy", null); AnnouncementDate = announcementData.ToString("dd-MMM-yy"); PaymentDate = DateTime.ParseExact(ricInfo.ClearingCommencementDate, "dd-MM-yyyy", null).ToString("dd-MMM-yy"); }
public void PDFAnalysis(RicInfo ric, FMType fmType) { string ricCode = ric.Code; int position = 0; string txtPath = GetPDFToTxtFilePath(ricCode, fmType); System.Threading.Thread.Sleep(3000); try { if (txtPath == null) { throw new Exception(); } String gearStr = ""; String premiumStr = ""; String lineText = ""; StreamReader sr = new StreamReader(txtPath); lineText = sr.ReadToEnd(); sr.Close(); //Get position of stock int stockIndex = lineText.IndexOf("Stock code"); int stockLength = "Stock code".Length; if (stockIndex < 0) { stockIndex = lineText.IndexOf("Stock Code"); } string codeStr = SearchKeyValue(stockIndex, stockLength, lineText); position = codeStr.IndexOf(ricCode) / 5 + 1; //Get gearing value int gearingIndex = lineText.IndexOf("\n Gearing* "); int gearLength = "\n Gearing* ".Length; if (gearingIndex < 0) { gearingIndex = lineText.IndexOf("\nGearing*"); gearLength = "\nGearing*".Length; } if (gearingIndex < 0) { gearingIndex = lineText.IndexOf("\n Gearing *"); gearLength = "\n Gearing *".Length; } if (gearingIndex < 0) { gearingIndex = lineText.IndexOf("\nGearing *"); gearLength = "\n Gearing *".Length; } if (gearingIndex < 0) { gearingIndex = lineText.IndexOf("\nGearing *"); gearLength = "\nGearing *".Length; } if (gearingIndex < 0) { gearingIndex = lineText.IndexOf("Gearing*"); gearLength = "Gearing*".Length; } gearStr = SearchKeyValue(gearingIndex, gearLength, lineText); //Get premium value int premiumIndex = lineText.IndexOf("Premium*"); int premiumLength = "Premium*".Length; if (premiumIndex < 0) { premiumIndex = lineText.IndexOf("Premium *"); premiumLength = "Premium *".Length; } premiumStr = SearchKeyValue(premiumIndex, premiumLength, lineText); String[] gearArr = gearStr.Split('x'); String[] premiumArr = premiumStr.Split('%'); ric.Gear = gearArr[position - 1]; ric.Premium = premiumArr[position - 1]; }//end try catch (Exception) { Logger.Log("PDF analysis failed for " + ricCode + "! Action: Need manually input gearing and premium ", Logger.LogType.Warning); } }
//------------------------------------------------------------------------ public FMRunNfo FMRun(string inpTitle, FMType fmtype, FileRun_Status callStatus, int queue) { callStatus(1,"Initializing..."); SymCommand cmd; string outTitle = "PwrIDE FM - " + new Random().Next(8388608).ToString("D7"); Write("mm0\u001B"); cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); callStatus(2,"Writing Commands..."); Write("1\r"); cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); Write("24\r"); //Misc. Processing cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); Write("5\r"); //Batch FM cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); Write(((int)fmtype).ToString()+"\r"); //FM File Type cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); Write("0\r"); //Undo a Posting? (NO) cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); Write(inpTitle+"\r"); //Title of Batch Report Output to Use as FM Script cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); Write("1\r"); //Number of Search Days? (1) cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); if(fmtype == FMType.Account) { Write("1\r"); //Record FM History (YES) cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); } Write(outTitle+"\r"); //Name of Posting (needed to lookup later) cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); Write("1\r"); //Produce Empty Report If No Exceptions? (YES) cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); Write("0\r"); //Batch Options? (NO) //get queues callStatus(4, "Getting Queue List"); cmd = ReadCommand(); Dictionary<int,int> queAvailable = new Dictionary<int,int>(); while(cmd.command != "Input") { if((cmd.GetParam("Action") == "DisplayLine") && (cmd.GetParam("Text").Contains("Batch Queues Available:"))) { string line = cmd.GetParam("Text"); string[] strQueues = line.Substring(line.IndexOf(':')+1).Split(new char[]{','}); for(int i=0; i<strQueues.Length; i++) { strQueues[i] = strQueues[i].Trim(); if(strQueues[i].Contains("-")) { int pos = strQueues[i].IndexOf('-'); int start = int.Parse(strQueues[i].Substring(0,pos)); int end = int.Parse(strQueues[i].Substring(pos+1)); for(int c=start; c<=end; c++) queAvailable.Add(c,0); } else queAvailable.Add(int.Parse(strQueues[i]),0); } } cmd = ReadCommand(); } //get queue counts callStatus(5, "Getting Queue Counts"); cmd = new SymCommand("Misc"); cmd.SetParam("InfoType", "BatchQueues"); Write(cmd); cmd = ReadCommand(); while(!cmd.HasParam("Done")) { if((cmd.GetParam("Action") == "QueueEntry") && (cmd.GetParam("Stat") == "Running")) queAvailable[int.Parse(cmd.GetParam("Queue"))]++; cmd = ReadCommand(); } if(queue == -1) //auto select lowest pending queue, or last available Zero queue { queue = 0; foreach(KeyValuePair<int, int> Q in queAvailable) if(Q.Value <= queAvailable[queue]) queue = Q.Key; } callStatus(7, "Writing Final Commands"); Write(queue.ToString()+"\r"); //write queue cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); Write("1\r"); //Okay (to Proceed)? (YES) cmd=ReadCommand(); while(cmd.command!="Input") cmd=ReadCommand(); //get queues again callStatus(8, "Finding FM Sequence"); cmd = new SymCommand("Misc"); cmd.SetParam("InfoType", "BatchQueues"); Write(cmd); int newestTime = 0; int sequenceNo = -1; cmd = ReadCommand(); while(!cmd.HasParam("Done")) { if(cmd.GetParam("Action") == "QueueEntry") { int currTime = 0; string timeStr = cmd.GetParam("Time"); currTime = int.Parse(timeStr.Substring(timeStr.LastIndexOf(':')+1)); currTime += 60 * int.Parse(timeStr.Substring(timeStr.IndexOf(':')+1, 2)); currTime += 3600 * int.Parse(timeStr.Substring(0, timeStr.IndexOf(':'))); if(currTime >= newestTime) { newestTime = currTime; sequenceNo = int.Parse(cmd.GetParam("Seq")); } } cmd = ReadCommand(); } callStatus(9, "Running.."); return new FMRunNfo(sequenceNo, outTitle); }
public void EventCollection() { //加载背景图片 string fileName = Properties.Settings.Default.BKImage; BitmapImage source = new BitmapImage(); if (File.Exists(fileName)) { source.BeginInit(); source.UriSource = new Uri(fileName); source.EndInit(); ImageBrush brush = new ImageBrush(source); brush.Stretch = Stretch.UniformToFill; brush.Opacity = 0.8; grid.Background = brush; } DispatcherTimer timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 1); int isLogined = api.HasLogined(); //登陆按钮触发后委托事件 api.loginCompletedEvent += result => { Dispatcher.Invoke(new Action(() => { if (result == null) { ct_LoginErrorMessage.Text = "网络异常或者其他异常!"; isLogined = -1; } else if (result.R != 0) { isLogined = 0; ct_LoginErrorMessage.Text = result.ErrorMessage; AnycUpdateCaptcha(); } else { ct_LoginImage.Source = new BitmapImage(new Uri("Images/LoginUser.png", UriKind.RelativeOrAbsolute)); if (visiblePanel.Equals(LoginPanel)) { ChangeVisibility(UserInfoPanel); } ct_LoginedUserName.Content = result.User.Name; ct_Played.Content = result.User.Record.Played.ToString(); ct_Like.Content = result.User.Record.Liked.ToString(); ct_Ban.Content = result.User.Record.Banned.ToString(); currentUser = result.User; ct_MoreFM.Visibility = Visibility.Visible; isLogined = 1; } })); }; if (isLogined == 1) { api.GetLoginedUserInfo(); } FMType fmType = FMType.NormFM; #region 标题栏事件 //点击最小化按钮--最小化窗口 ct_MinusImage.MouseLeftButtonDown += (sender, e) => { this.WindowState = WindowState.Minimized; }; //点击关闭按钮--关闭窗口 ct_CloseImage.MouseLeftButtonDown += (sender, e) => { this.Close(); }; //拖动标题栏--拖动窗口 TitlePanel.MouseLeftButtonDown += (sender, e) => { if (e.LeftButton == MouseButtonState.Pressed) { this.DragMove(); } }; //点击装扮按钮--更改背景图片 ct_ChangeBGImage.MouseLeftButtonDown += (sender, e) => { Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog(); dialog.Title = "选择背景图片"; dialog.Filter = "图片文件(*.BMP;*.JPG;*.JPEG)|*.BMP;*.JPG;*.JPEG"; dialog.Multiselect = false; if (dialog.ShowDialog() == true) { //grid.Background = new ImageBrush(new BitmapImage(new Uri(dialog.FileName, UriKind.RelativeOrAbsolute))); BitmapImage imageSource = new BitmapImage(); imageSource.BeginInit(); imageSource.UriSource = new Uri(dialog.FileName); imageSource.EndInit(); ImageBrush ib = new ImageBrush(imageSource); ib.Stretch = Stretch.UniformToFill; ib.Opacity = 0.8; grid.Background = ib; Properties.Settings.Default.BKImage = dialog.FileName; Properties.Settings.Default.Save(); } }; //点击置顶按钮--切换总是置顶/不置顶状态 ct_TopImage.MouseLeftButtonDown += (sender, e) => { //this.Topmost = true; if (ct_TopImage.Tag == null || ct_TopImage.Tag.ToString() == "nottop") { this.Topmost = true; ct_TopImage.Source = new BitmapImage(new Uri("images/NotAlwaysTop.png", UriKind.Relative)); ct_TopImage.Tag = "top"; } else { this.Topmost = false; ct_TopImage.Source = new BitmapImage(new Uri("images/AlwaysTop.png", UriKind.Relative)); ct_TopImage.Tag = "nottop"; } }; //点击登陆图像--弹出登陆窗口 ct_LoginImage.MouseLeftButtonDown += (sender, e) => { if (visiblePanel.Equals(LoginPanel) || visiblePanel.Equals(UserInfoPanel)) { ChangeVisibility(PlayerPanel); } else { if (isLogined == 1) { api.GetLoginedUserInfo(); ChangeVisibility(UserInfoPanel); } else if (isLogined == -1) { ct_LoginErrorMessage.Text = "网络故障!"; ChangeVisibility(LoginPanel); } else { ct_LoginErrorMessage.Text = string.Empty; ThreadPool.QueueUserWorkItem(new WaitCallback( captchaUrl => { string _captchaUrl = api.UpdateCaptcha(); Dispatcher.Invoke(new Action(() => { ct_CaptchaImage.Source = new BitmapImage(new Uri(_captchaUrl, UriKind.Absolute)); })); })); ChangeVisibility(LoginPanel); } } }; #endregion #region 登陆窗口事件 //点击验证码图片--更新验证码 ct_CaptchaImage.MouseLeftButtonDown += (sender, e) => { AnycUpdateCaptcha(); }; //点击登陆按钮--登陆豆瓣账户 ct_LoginButton.Click += (sender, e) => { if (api.HasLogined() == 1) { api.GetLoginedUserInfo(); return; } string userName = ct_UserName.Text.Trim(); string password = ct_Password.Password.Trim(); string captcha = ct_Captcha.Text.Trim(); if (string.IsNullOrEmpty(userName)) { ct_LoginErrorMessage.Text = "用户名不能为空!"; ct_UserName.Focus(); return; } else if (string.IsNullOrEmpty(password)) { ct_LoginErrorMessage.Text = "密码不能为空!"; ct_Password.Focus(); return; } else if (string.IsNullOrEmpty(captcha)) { ct_LoginErrorMessage.Text = "验证码不能为空!"; ct_Captcha.Focus(); return; } else { ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.Login(userName, password, captcha); })); ct_LoginErrorMessage.Text = "正在登陆..."; } }; //点击取消按钮--取消登陆界面 ct_CancelLoginButton.Click += (sender, e) => { ChangeVisibility(PlayerPanel); }; //点击退出登陆按钮--退出豆瓣账户 ct_LogoutButton.Click += (sender, e) => { ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.Logout(); })); isLogined = 0; currentUser = null; ChangeVisibility(PlayerPanel); ct_LoginImage.Source = new BitmapImage(new Uri("Images/UnloginUser.png", UriKind.RelativeOrAbsolute)); ct_MoreFM.Visibility = Visibility.Collapsed; currentChannel = api.GetInitChannel(false); api.GetNewPlayList(currentChannel.ChannelID); ct_Channel.Content = currentChannel.Name; }; //点击取消按钮--返回播放界面 ct_CancelLogoutButton.Click += (sender, e) => { ChangeVisibility(PlayerPanel); }; #endregion #region 播放相关 List <TimeSpan> timeSpanList = null; int lyricIndex = 0; currentChannel = api.GetInitChannel(isLogined == 1); SetFavChannel(); ct_Channel.Content = currentChannel.Name; //绑定切换播放列表事件 api.playListChangedEvent += playList => { Dispatcher.Invoke(new Action(() => { //playListBox.ItemsSource = (ObservableCollection<doubanFMAPI.Entities.Song.SongEntity>)playList; //playListBox.UpdateLayout(); List <doubanFMAPI.Entities.Song.SongEntity> n_playList = playList.ToList(); playListBox.ItemsSource = n_playList; })); }; //绑定切换歌曲事件 api.currentSongChangedEvent += song => { timeSpanList = new List <TimeSpan>(); currentSong = song; Dispatcher.Invoke(new Action(() => { Storyboard sb = (Storyboard)Resources["HideSongInfo"]; sb.Begin(); sb = (Storyboard)Resources["ShowSongInfo"]; sb.Begin(); ct_SongName.Content = song.SongName; ct_SingerName.Content = song.SingerName; ct_PublishTime.Content = song.PublishTime; ct_AlbumName.Content = song.AlbumName; SetLike(song.IsLiked == "1" ? true : false); ct_MediaPlayer.Source = new Uri(song.SongUrl, UriKind.Absolute); ct_MediaPlayer.Play(); })); ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { Dispatcher.Invoke(new Action(() => { ct_AlbumPicture.Source = new BitmapImage(new Uri(song.AlbumPicture.Replace("mpic", "lpic"), UriKind.Absolute)); })); api.GetLyric(ref song); timeSpanList = SortTS((Dictionary <TimeSpan, string>)song.Lyrics); })); }; //绑定播放列表为空事件 api.playListEmptyedEvent += () => { api.GetNewPlayList(currentChannel.ChannelID); }; //定时器操作 timer.Tick += (sender, e) => { while (!ct_MediaPlayer.NaturalDuration.HasTimeSpan) { return; } TimeSpan total = ct_MediaPlayer.NaturalDuration.TimeSpan; TimeSpan hasPlayed = ct_MediaPlayer.Position; string totalString = string.Format("{0:D2}:{1:D2}/{2:D2}:{3:D2}", hasPlayed.Minutes, hasPlayed.Seconds, total.Minutes, total.Seconds); ct_SongTimeSpan.Content = totalString; ct_SongLoadProgress.Value = ct_MediaPlayer.DownloadProgress; ct_SongProgress.Value = hasPlayed.TotalSeconds / total.TotalSeconds; ct_Lyric.Text = ShowCurrentLyric((Dictionary <TimeSpan, string>)currentSong.Lyrics, timeSpanList, hasPlayed, ref lyricIndex); }; //一首歌开始播放 ct_MediaPlayer.MediaOpened += (sender, e) => { timer.Start(); lyricIndex = 0; CutString(ct_SongName.Content.ToString(), ref ct_SongName); CutString(ct_SingerName.Content.ToString(), ref ct_SingerName); CutString(ct_AlbumName.Content.ToString(), ref ct_AlbumName, true); }; //一首歌曲自然结束 ct_MediaPlayer.MediaEnded += (sender, e) => { timer.Stop(); if (fmType == FMType.NormFM) { TimeSpan ts = ct_MediaPlayer.Position; api.NaturalEnd(currentChannel.ChannelID, currentSong.SongID, Math.Round(ts.TotalMilliseconds / 1000, 1)); } else { api.NaturalEnd(); } }; //点击音量按钮--改变音量 ct_VolumeSlider.ValueChanged += (sender, e) => { ct_MediaPlayer.Volume = ct_VolumeSlider.Value; }; //点击喜欢按钮--标记红心/取消标记红心 ct_LikeImage.MouseLeftButtonDown += (sender, e) => { TimeSpan ts = ct_MediaPlayer.Position; double songPT = Math.Round(ts.TotalMilliseconds / 1000, 1); if (fmType == FMType.NormFM) { if (ct_LikeImage.Tag != null && ct_LikeImage.Tag.ToString() == "1") { SetLike(false); ct_LikeImage.Tag = "0"; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.UnLike(currentChannel.ChannelID, currentSong.SongID, songPT); })); } else { SetLike(true); ct_LikeImage.Tag = "1"; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.Like(currentChannel.ChannelID, currentSong.SongID, songPT); })); } } else { if (ct_LikeImage.Tag != null && ct_LikeImage.Tag.ToString() == "1") { SetLike(false); ct_LikeImage.Tag = "0"; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.UnLike(currentSong.SongID, songPT); })); } else { SetLike(true); ct_LikeImage.Tag = "1"; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.Like(currentSong.SongID, songPT); })); } } }; //点击不再播放按钮--不再播放 ct_BanImage.MouseLeftButtonDown += (sender, e) => { if (fmType == FMType.NormFM) { TimeSpan ts = ct_MediaPlayer.Position; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.Ban(currentChannel.ChannelID, currentSong.SongID, Math.Round(ts.TotalMilliseconds / 1000, 1)); })); } else { ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.Ban(); })); } }; //点击下一曲按钮--跳过该曲 ct_NextImage.MouseLeftButtonDown += (sender, e) => { if (fmType == FMType.NormFM) { TimeSpan ts = ct_MediaPlayer.Position; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.Next(currentChannel.ChannelID, currentSong.SongID, Math.Round(ts.TotalMilliseconds / 1000, 1)); })); } else { ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.Next(); })); } }; //点击播放歌手歌曲按钮--对登录用户,歌手兆赫 ct_SingerFMImage.MouseLeftButtonDown += (sender, e) => { if (fmType == FMType.SingerFM) { fmType = FMType.NormFM; ct_SingerFMImage.Source = new BitmapImage(new Uri("Images/SingerFM.png", UriKind.RelativeOrAbsolute)); ct_SingerFMImage.ToolTip = "收听该歌手歌曲"; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.GetNewPlayList(currentChannel.ChannelID); })); } else { fmType = FMType.SingerFM; ct_SingerFMImage.Source = new BitmapImage(new Uri("Images/DelSingerFM.png", UriKind.RelativeOrAbsolute)); ct_SingerFMImage.ToolTip = "取消收听该歌手歌曲"; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.GetSingerFMNewPlayList(currentSong.SingerName); })); } }; //点击播放专辑歌曲按钮--对登录用户,专辑兆赫 ct_AlbumFMImage.MouseLeftButtonDown += (sender, e) => { if (fmType == FMType.AlbumFM) { fmType = FMType.NormFM; ct_AlbumFMImage.Source = new BitmapImage(new Uri("Images/AlbumFM.png", UriKind.RelativeOrAbsolute)); ct_AlbumFMImage.ToolTip = "收听该专辑歌曲"; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.GetNewPlayList(currentChannel.ChannelID); })); } else { fmType = FMType.SingerFM; ct_AlbumFMImage.Source = new BitmapImage(new Uri("Images/DelAlbumFM.png", UriKind.RelativeOrAbsolute)); ct_AlbumFMImage.ToolTip = "取消收听该专辑歌曲"; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.GetAlbumFMNewPlayList(currentSong.AlbumName); })); } }; //点击专辑封面--暂停播放 ct_AlbumPicture.MouseLeftButtonDown += (sender, e) => { PlayerPanel.Opacity = 0.5; PauseCanvas.Visibility = Visibility.Visible; visiblePanel = PauseCanvas; ct_LoginImage.IsEnabled = false; ct_MediaPlayer.Pause(); timer.Stop(); }; //点击继续播放--继续播放 PauseCanvas.MouseLeftButtonDown += (sender, e) => { //ChangeVisibility(PlayerPanel); PlayerPanel.Opacity = 1.0; PauseCanvas.Visibility = Visibility.Collapsed; visiblePanel = PlayerPanel; ct_LoginImage.IsEnabled = true; ct_MediaPlayer.Play(); timer.Start(); }; //初始化 api.GetNewPlayList(currentChannel.ChannelID); #endregion #region 播放列表相关 //点击播放列表图标--显示/隐藏播放列表 ct_PlaylistImage.MouseLeftButtonDown += (sender, e) => { if (visiblePanel.Equals(PlayListPanel)) { ChangeVisibility(PlayerPanel); } else { ChangeVisibility(PlayListPanel); } }; #endregion #region 兆赫列表相关 ChannelType channelType = ChannelType.HotChannel; int currentChPage = 1; int totalChPages = 2; int chPerPage = 10; string keyword = string.Empty; //绑定兆赫列表事件 api.channelChangedEvent += channels => { Dispatcher.Invoke(new Action(() => { List <doubanFMAPI.Entities.Channel.ChannelEntity> n_channels = channels.Channels.ToList(); ct_channelListBox.ItemsSource = n_channels; totalChPages = channels.ChannelCount; if (channelType == ChannelType.FavChannel) { totalChPages = 1; } PageChanged(currentChPage, totalChPages); })); }; //点击兆赫图标--显示/隐藏兆赫列表 ct_ChannelStackPanel.MouseLeftButtonDown += (sender, e) => { if (visiblePanel.Equals(ChannelPanel)) { ChangeVisibility(PlayerPanel); } else { ChangeVisibility(ChannelPanel); } }; //点击热门图标按钮--显示热门兆赫 ct_HotChPanel.MouseLeftButtonDown += (sender, e) => { currentChPage = 1; channelType = ChannelType.HotChannel; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.GetHotChannels((currentChPage - 1) * 10, chPerPage); })); ct_chKeywordTextBox.Text = string.Empty; }; //点击上升最快图标按钮--显示上升最快兆赫 ct_UpTrendingChPanel.MouseLeftButtonDown += (sender, e) => { currentChPage = 1; channelType = ChannelType.UpTrendingChannel; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.GetUpTrendingChannels((currentChPage - 1) * 10, chPerPage); })); ct_chKeywordTextBox.Text = string.Empty; }; //点击收藏图标按钮--显示本地收藏兆赫 ct_FavChPanel.MouseLeftButtonDown += (sender, e) => { currentChPage = 1; channelType = ChannelType.FavChannel; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { if (currentUser == null || string.IsNullOrEmpty(currentUser.Name)) { api.GetFavoriateChannels(""); } else { api.GetFavoriateChannels(currentUser.Name); } totalChPages = 1; })); ct_chKeywordTextBox.Text = string.Empty; }; //点击搜素图标按钮--显示搜索兆赫 ct_SearchChPanel.MouseLeftButtonDown += (sender, e) => { keyword = ct_chKeywordTextBox.Text.Trim(); if (string.IsNullOrEmpty(keyword)) { return; } currentChPage = 1; channelType = ChannelType.SearchChannel; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { api.GetSearchChannels(keyword, (currentChPage - 1) * 10, chPerPage); })); }; //点击上一页图标--对当前兆赫进行翻页 ct_PrePageImage.MouseLeftButtonDown += (sender, e) => { currentChPage--; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { if (channelType == ChannelType.HotChannel) { api.GetHotChannels((currentChPage - 1) * 10, chPerPage); } else if (channelType == ChannelType.UpTrendingChannel) { api.GetUpTrendingChannels((currentChPage - 1) * 10, chPerPage); } else if (channelType == ChannelType.FavChannel) { api.GetUpTrendingChannels((currentChPage - 1) * 10, chPerPage); } else { api.GetSearchChannels(keyword, (currentChPage - 1) * 10, chPerPage); } })); }; //点击下一页图标--对当前兆赫进行翻页 ct_NextPageImage.MouseLeftButtonDown += (sender, e) => { currentChPage++; ThreadPool.QueueUserWorkItem(new WaitCallback( obj => { if (channelType == ChannelType.HotChannel) { api.GetHotChannels((currentChPage - 1) * 10, chPerPage); } else if (channelType == ChannelType.UpTrendingChannel) { api.GetUpTrendingChannels((currentChPage - 1) * 10, chPerPage); } else if (channelType == ChannelType.FavChannel) { api.GetUpTrendingChannels((currentChPage - 1) * 10, chPerPage); } else { api.GetSearchChannels(keyword, (currentChPage - 1) * 10, chPerPage); } })); }; //双击兆赫列表--切换当前兆赫 ct_channelListBox.MouseDoubleClick += (sender, e) => { //ct_OpFavChannelImage.Visibility = Visibility.Visible; List <doubanFMAPI.Entities.Channel.ChannelEntity> channels = (List <doubanFMAPI.Entities.Channel.ChannelEntity>)ct_channelListBox.ItemsSource; currentChannel = channels[ct_channelListBox.SelectedIndex]; //currentChannelID = currentChannel.ChannelID; ct_Channel.Content = currentChannel.Name; TimeSpan ts = ct_MediaPlayer.Position; double songPT = Math.Round(ts.TotalMilliseconds / 1000, 1); if (currentSong != null) { api.GetNewPlayList(currentChannel.ChannelID, currentSong.SongID, songPT); } else { api.GetNewPlayList(currentChannel.ChannelID); } SetFavChannel(); }; //点击对当前兆赫进行收藏和取消收藏操作 ct_OpFavChannelImage.MouseLeftButtonDown += (sender, e) => { if (ct_OpFavChannelImage.Tag == null || ct_OpFavChannelImage.Tag.ToString() == "UnFav") { ct_OpFavChannelImage.Tag = "Fav"; api.AddToFavoriateChannels(currentUser == null ? "" : currentUser.Name, currentChannel); ct_OpFavChannelImage.Source = new BitmapImage(new Uri("Images/Favorited.png", UriKind.Relative)); } else { ct_OpFavChannelImage.Tag = "UnFav"; api.RemoveFromFavoriateChannels(currentUser == null ? "" : currentUser.Name, currentChannel.ChannelID); ct_OpFavChannelImage.Source = new BitmapImage(new Uri("Images/Favorite.png", UriKind.Relative)); } }; #endregion }
public string GetPDFToTxtFilePath(string codeId, FMType fmType) { string txtFilePath = string.Empty; string pdfUrl = null; for (int i = 0; i < 10; i++) //as website problem, if get pdf url error retry 10 times { try { pdfUrl = GetPDFUrl(codeId); if (!string.IsNullOrEmpty(pdfUrl)) { break; } } catch (Exception ex) { Thread.Sleep(2000); if (i == 9) { string msg = string.Format("get pdf url :{0} error,retry get 9 times.\r\nmsg:{0}", pdfUrl, ex.Message); Logger.Log(msg, Logger.LogType.Error); } } } string pdfFilePath = string.Empty; if (pdfUrl == null) { return(null); } if (fmType == FMType.Cbbc) { pdfFilePath = configObj.OutPutDir + "\\" + pdfFileDir + "\\" + "CBBC" + "\\" + codeId + ".pdf"; } else { pdfFilePath = configObj.OutPutDir + "\\" + pdfFileDir + "\\" + "Warrant" + "\\" + codeId + ".pdf"; } if (!Directory.Exists(Path.GetDirectoryName(pdfFilePath))) { Directory.CreateDirectory(Path.GetDirectoryName(pdfFilePath)); } for (int i = 0; i < 5; i++) //as website problem, if download pdf error retry 5 times { try { WebClientUtil.DownloadFile(pdfUrl, 24000, pdfFilePath); if (File.Exists(pdfFilePath)) { break; } } catch (Exception ex) { Thread.Sleep(2000); if (i == 4) { string msg = string.Format("Download pdf:{0} error,retry download 5 times.\r\nmsg:{0}", pdfUrl, ex.Message); Logger.Log(msg, Logger.LogType.Error); } } } return(pdfFilePath); }