Ejemplo n.º 1
0
        protected string GetCookie(Account account)
        {
            if (account.Expires_Cookies != DateTime.MinValue &&
                account.Expires_Cookies.AddMinutes(-10) > DateTime.Now &&
                account.Cookies != null &&
                account.Cookies.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Cookie item in account.Cookies)
                {
                    sb.Append($"{item.Name}={item.Value}; ");
                }
                return(sb.ToString());
            }
            //get sso data
            object[] sso = ByPassword.SSO(account.AccessToken);
            if (sso == null || sso.Length == 0)
            {
                throw new Exception("Get cookie by sso failed.");
            }
            CookieCollection cookies   = null;
            DateTime?        expiresDt = null;

            foreach (var item in sso)
            {
                Type type = item.GetType();
                if (type.Name == "CookieCollection")
                {
                    cookies = (CookieCollection)item;
                }
                if (type.Name == "DateTime")
                {
                    expiresDt = (DateTime)item;
                }
            }
            if (cookies == null || cookies.Count == 0 || expiresDt == null)
            {
                throw new Exception("Get cookie by sso failed.");
            }
            //update account
            account.Cookies         = cookies;
            account.Expires_Cookies = expiresDt.Value;

            //toString
            StringBuilder sbSSO = new StringBuilder();

            foreach (Cookie item in cookies)
            {
                sbSSO.Append($"{item.Name}={item.Value}; ");
            }
            return(sbSSO.ToString());
        }
Ejemplo n.º 2
0
        private static void Main(string[] args)
        {
            Console.WriteLine($"测试版本:{AssemblyName.GetAssemblyName("BiliAccount.dll").Version.ToString()}");
            Console.WriteLine("账号");
            string username = Console.ReadLine();

            Console.WriteLine("密码");
            string  pwd     = Console.ReadLine();
            Account account = ByPassword.LoginByPassword(username, pwd);

            Console.WriteLine(var_dump(account));

            ByQRCode.QrCodeStatus_Changed += ByQRCode_QrCodeStatus_Changed;
            ByQRCode.QrCodeRefresh        += ByQRCode_QrCodeRefresh;
            ByQRCode.LoginByQrCode().Save("tmp.jpg");

            Application.Run();
        }
Ejemplo n.º 3
0
        private static void Main(string[] args)
        {
            Console.WriteLine($"测试版本:");
            Console.WriteLine($"BiliAccount:{AssemblyName.GetAssemblyName("BiliAccount.dll").Version.ToString()}");
            Console.WriteLine($"BiliAccount.Geetest:{AssemblyName.GetAssemblyName("BiliAccount.Geetest.dll").Version.ToString()}");
            Console.WriteLine($"BiliAccount.Geetest.Controls:{AssemblyName.GetAssemblyName("BiliAccount.Geetest.Controls.dll").Version.ToString()}");
            Console.WriteLine("账号");
            string username = Console.ReadLine();

            Console.WriteLine("密码");
            string  pwd     = Console.ReadLine();
            Account account = ByPassword.LoginByPassword(username, pwd);

            Console.WriteLine(var_dump(account));
            if (account.LoginStatus == Account.LoginStatusEnum.NeedSafeVerify)
            {
                Process.Start(account.Url);
            }

            //ByQRCode.QrCodeStatus_Changed += ByQRCode_QrCodeStatus_Changed;
            //ByQRCode.QrCodeRefresh += ByQRCode_QrCodeRefresh;
            //ByQRCode.LoginByQrCode("#ff000000", "#00FFFFFF").Save("tmp.png");

            //string token = Console.ReadLine();
            //Console.WriteLine(BiliAccount.Linq.ByPassword.IsTokenAvailable(token));

            //Console.WriteLine("手机号");
            //string tel = Console.ReadLine();
            //BySMS.SendSMS(tel);
            //Console.WriteLine("验证码");
            //string code = Console.ReadLine();
            //Account account = BySMS.Login(code, tel);
            //Console.WriteLine(var_dump(account));

            //Console.WriteLine(var_dump(ByPassword.SSO(account.AccessToken)));

            //account.Expires_AccessToken = (DateTime)ByPassword.RefreshToken("76b3e1cb9b0d35a80f8c444dcdcb1a21", "bcb656a377362db92487929a7f258d21");
            //Console.WriteLine(var_dump(account));

            //ByPassword.Revoke(ref account);

            Application.Run();
        }
Ejemplo n.º 4
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Console.WriteLine($"测试版本:");
            Console.WriteLine($"BiliAccount:{AssemblyName.GetAssemblyName("BiliAccount.dll").Version.ToString()}");
            Console.WriteLine($"BiliAccount.Geetest:{AssemblyName.GetAssemblyName("BiliAccount.Geetest.dll").Version.ToString()}");
            Console.WriteLine($"BiliAccount.Geetest.Controls:{AssemblyName.GetAssemblyName("BiliAccount.Geetest.Controls.dll").Version.ToString()}");
            Console.WriteLine("账号");
            string username = "";

            Console.WriteLine("密码");
            string pwd = "";

            account = ByPassword.LoginByPassword(username, pwd);
            Console.WriteLine(var_dump(account));

            browser.OnVaildate_Success += Browser_OnVaildate_Success;
            if (account.LoginStatus == Account.LoginStatusEnum.NeedSafeVerify)
            {
                //tmp_token = Device_Verify.Url2TmpToken(account.Url);
                //browser.StartVaildate(account.Url);
                Geetest.Controls.Winforms.GeetestBrowserWindow.ShowValidateWindowDialog(account.Url, ref account);
                Console.WriteLine(var_dump(account));
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        private async Task LoginToBilibili()
        {
            async Task WriteLoginDataToFile(Account account)
            {
                if (account == null)
                {
                    throw new Exception("Write to file data can not null.");
                }
                string dataBeforeEncrypt = JsonUtil.SerializeObject(account);
                string dataAfterEncrypt  = AES128.AESEncrypt(dataBeforeEncrypt, _config.AppSetting.Key, "40863a4f-7cbe-4be2-bb54-765233c83d25");
                await File.WriteAllBytesAsync(_dataFilePath, Encoding.UTF8.GetBytes(dataAfterEncrypt));
            }

            async Task LoginByPassword()
            {
                Account account = ByPassword.LoginByPassword(_config.UserSetting.Account, _config.UserSetting.Password);

                if (account == null)
                {
                    throw new Exception("Get account info failed.");
                }
                if (account.LoginStatus != Account.LoginStatusEnum.ByPassword)
                {
                    throw new Exception($"登录失败,登录失败原因:{account.LoginStatus}");
                }
                await WriteLoginDataToFile(account);

                _account = account;
            }

            try
            {
                if (!File.Exists(_dataFilePath))
                {
                    await LoginByPassword();

                    return;
                }
                //获取历史登录信息
                string fileStr = await File.ReadAllTextAsync(_dataFilePath);

                if (string.IsNullOrEmpty(fileStr))
                {
                    await LoginByPassword();

                    return;
                }
                Account account = null;
                try
                {
                    string decodeStr = AES128.AESDecrypt(fileStr, _config.AppSetting.Key, "40863a4f-7cbe-4be2-bb54-765233c83d25");
                    if (string.IsNullOrEmpty(decodeStr))
                    {
                        await LoginByPassword();

                        return;
                    }
                    account = JsonUtil.DeserializeJsonToObject <Account>(decodeStr);
                }
                catch
                {
                    await LoginByPassword();

                    return;
                }
                //判断AccessToken是否有效
                if (account == null || !ByPassword.IsTokenAvailable(account.AccessToken) || account.UserName != _config.UserSetting.Account)
                {
                    await LoginByPassword();

                    return;
                }
                //判断AccessToken是否需要续期
                if (account.Expires_AccessToken != DateTime.MinValue &&
                    account.Expires_AccessToken.AddDays(-7) < DateTime.Now)
                {
                    DateTime?dt = ByPassword.RefreshToken(account.AccessToken, account.RefreshToken);
                    if (dt == null)
                    {
                        await LoginByPassword();

                        return;
                    }
                    account.Expires_AccessToken = dt.Value;
                    //更新
                    await WriteLoginDataToFile(account);

                    _account = account;
                }
                else
                {
                    _account = account;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Login to bilibili failed, login account is {_config.UserSetting.Account}. {ex.Message}", ex);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 开始推流
        /// </summary>
        /// <param name="setting"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private async Task <bool> UseFFmpegLive(string url)
        {
            try
            {
                if (string.IsNullOrEmpty(_config.LiveSetting.FFmpegCmd))
                {
                    throw new Exception("推流命令不能为空。");
                }
                int markIndex = _config.LiveSetting.FFmpegCmd.IndexOf("[[URL]]");
                if (markIndex < 5)
                {
                    throw new Exception("在填写的命令中未找到 '[[URL]]'标记。");
                }
                if (_config.LiveSetting.FFmpegCmd[markIndex - 1] == '\"')
                {
                    throw new Exception(" '[[URL]]'标记前后无需“\"”。");
                }
                string newCmd        = _config.LiveSetting.FFmpegCmd.Replace("[[URL]]", $"\"{url}\"");
                int    firstNullChar = newCmd.IndexOf((char)32);
                if (firstNullChar < 0)
                {
                    throw new Exception("无法获取命令执行名称,比如在命令ffmpeg -version中,无法获取ffmpeg。");
                }
                string cmdName = newCmd.Substring(0, firstNullChar);
                string cmdArgs = newCmd.Substring(firstNullChar);
                if (string.IsNullOrEmpty(cmdArgs))
                {
                    throw new Exception("命令参数不能为空!");
                }

                var psi = new ProcessStartInfo
                {
                    FileName  = cmdName,
                    Arguments = cmdArgs,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = false,
                    UseShellExecute        = false,
                    CreateNoWindow         = RuntimeInformation.IsOSPlatform(OSPlatform.Linux),
                };
                bool isAutoRestart = true;
                while (isAutoRestart)
                {
                    isAutoRestart = _config.LiveSetting.AutoRestart;
                    //check network
                    while (!await NetworkUtil.NetworkCheck())
                    {
                        _logger.LogWarning($"网络连接已断开,将在10秒后重新检查网络连接...");
                        await Task.Delay(10000);
                    }
                    //check token is available
                    if (!ByPassword.IsTokenAvailable(_account.AccessToken))
                    {
                        await LoginToBilibili();
                    }
                    //start live
                    StartLiveDataInfo liveInfo = await StartLive();

                    if (liveInfo == null)
                    {
                        _logger.LogError($"开启B站直播间失败,无法获取推流地址。");
                        return(false);
                    }
                    _logger.LogInformation("正在初始化推流指令...");
                    //启动
                    using (var proc = Process.Start(psi))
                    {
                        if (proc == null || proc.Id <= 0)
                        {
                            throw new Exception("无法执行指定的推流指令,请检查FFmpegCmd是否填写正确。");
                        }
                        //退出检测
                        if (!Console.IsInputRedirected)
                        {
                            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs eventArgs) =>
                            {
                                isAutoRestart = false;
                            };
                        }
                        await proc.WaitForExitAsync();

                        if (isAutoRestart)
                        {
                            _logger.LogWarning($"FFmpeg异常退出,将在60秒后重试推流。");
                        }
                        else
                        {
                            _logger.LogWarning($"FFmpeg异常退出。");
                        }
                    }
                    if (isAutoRestart)
                    {
                        _logger.LogWarning($"等待重新推流...");
                        //如果开启了自动重试,那么等待60s后再次尝试
                        await Task.Delay(60000);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return(false);
            }
        }