public void IsValidUrl(string url) { SqlLiteDatabaseTest(options => { var uploadService = _server.Host.Services.GetService(typeof(IUploadService)) as IUploadService; using (var context = new PlayCatDbContext(options)) { uploadService.SetDbContext(context); var request = new UrlRequest() { Url = url, }; GetInfoResult result = uploadService.GetInfo(request); CheckIfSuccess(result); Assert.NotNull(result.UrlInfo); Assert.Equal("Flume", result.UrlInfo.Artist); Assert.Equal("Say It (feat. Tove Lo) (Illenium Remix)", result.UrlInfo.Song); Assert.Equal(8023661, result.UrlInfo.ContentLength); } }); }
public void ShouldFailOnAlreadyUpload() { SqlLiteDatabaseTest(options => { var uploadService = _server.Host.Services.GetService(typeof(IUploadService)) as IUploadService; var fileResolver = _server.Host.Services.GetService(typeof(IFileResolver)) as IFileResolver; using (var context = new PlayCatDbContext(options)) { uploadService.SetDbContext(context); string youtubeUrl = "https://www.youtube.com/watch?v=yPYZpwSpKmA"; var request = new UrlRequest() { Url = youtubeUrl, }; GetInfoResult result = uploadService.GetInfo(request); CheckIfSuccess(result); Guid userId = GetUserId(context); context.CreatePlaylist(true, userId, null, 0); context.SaveChanges(); Assert.NotNull(result.UrlInfo); Assert.Equal("Rick Astley", result.UrlInfo.Artist); Assert.Equal("Together Forever", result.UrlInfo.Song); var uploadResult = uploadService.UploadAudioAsync(userId, new UploadAudioRequest() { Artist = "Rick Astley", Song = "Together Forever", Url = youtubeUrl, }).Result; CheckIfSuccess(uploadResult); string audioFilePath = fileResolver.GetAudioFolderPath(StorageType.FileSystem); File.Delete(Path.Combine(audioFilePath, "yPYZpwSpKmA.mp3")); GetInfoResult checkAgainResult = uploadService.GetInfo(request); CheckIfFail(checkAgainResult); Assert.Equal("Video already uploaded", checkAgainResult.Info); } }); }
public void IsWrongUrlId() { var uploadService = _server.Host.Services.GetService(typeof(IUploadService)) as IUploadService; var request = new UrlRequest() { Url = "https://www.youtube.com/watch?v=11111111", }; GetInfoResult result = uploadService.GetInfo(request); CheckIfFail(result); Assert.True(result.Info.Length > 0); Assert.Null(result.Errors); }
public void IsVideoSizeToLarge() { var uploadService = _server.Host.Services.GetService(typeof(IUploadService)) as IUploadService; var request = new UrlRequest() { Url = "https://www.youtube.com/watch?v=2mI0nEgdgsA", }; GetInfoResult result = uploadService.GetInfo(request); CheckIfFail(result); Assert.Equal("Maximim video size is 25 MB", result.Info); Assert.True(result.ShowInfo); Assert.Null(result.Errors); }
public void IsErrorOnInvalidUrl(string url) { var uploadService = _server.Host.Services.GetService(typeof(IUploadService)) as IUploadService; var request = new UrlRequest() { Url = url, }; GetInfoResult result = uploadService.GetInfo(request); CheckIfFail(result); Assert.Equal("Model is not valid", result.Info); Assert.False(result.ShowInfo); Assert.NotNull(result.Errors); Assert.Equal(result.Errors.Count, 1); }
public async Task <IActionResult> LedgerConnection( string command, // getinfo string cryptoCode = null, // getxpub [ModelBinder(typeof(ModelBinders.DerivationSchemeModelBinder))] DerivationStrategyBase derivationScheme = null, int account = 0, // sendtoaddress string destination = null, string amount = null, string feeRate = null, string substractFees = null ) { if (!HttpContext.WebSockets.IsWebSocketRequest) { return(NotFound()); } var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); using (var normalOperationTimeout = new CancellationTokenSource()) using (var signTimeout = new CancellationTokenSource()) { normalOperationTimeout.CancelAfter(TimeSpan.FromMinutes(30)); var hw = new HardwareWalletService(webSocket); object result = null; try { BTCPayNetwork network = null; if (cryptoCode != null) { network = _NetworkProvider.GetNetwork(cryptoCode); if (network == null) { throw new FormatException("Invalid value for crypto code"); } } BitcoinAddress destinationAddress = null; if (destination != null) { try { destinationAddress = BitcoinAddress.Create(destination, network.NBitcoinNetwork); } catch { } if (destinationAddress == null) { throw new FormatException("Invalid value for destination"); } } FeeRate feeRateValue = null; if (feeRate != null) { try { feeRateValue = new FeeRate(Money.Satoshis(int.Parse(feeRate, CultureInfo.InvariantCulture)), 1); } catch { } if (feeRateValue == null || feeRateValue.FeePerK <= Money.Zero) { throw new FormatException("Invalid value for fee rate"); } } Money amountBTC = null; if (amount != null) { try { amountBTC = Money.Parse(amount); } catch { } if (amountBTC == null || amountBTC <= Money.Zero) { throw new FormatException("Invalid value for amount"); } } bool subsctractFeesValue = false; if (substractFees != null) { try { subsctractFeesValue = bool.Parse(substractFees); } catch { throw new FormatException("Invalid value for subtract fees"); } } if (command == "test") { result = await hw.Test(normalOperationTimeout.Token); } if (command == "getxpub") { var getxpubResult = await hw.GetExtPubKey(network, account, normalOperationTimeout.Token); result = getxpubResult; } if (command == "getinfo") { var strategy = GetDirectDerivationStrategy(derivationScheme); if (strategy == null || await hw.GetKeyPath(network, strategy, normalOperationTimeout.Token) == null) { throw new Exception($"This store is not configured to use this ledger"); } var feeProvider = _feeRateProvider.CreateFeeProvider(network); var recommendedFees = feeProvider.GetFeeRateAsync(); var balance = _walletProvider.GetWallet(network).GetBalance(derivationScheme); result = new GetInfoResult() { Balance = (double)(await balance).ToDecimal(MoneyUnit.BTC), RecommendedSatoshiPerByte = (int)(await recommendedFees).GetFee(1).Satoshi }; } if (command == "sendtoaddress") { if (!_dashboard.IsFullySynched(network.CryptoCode, out var summary)) { throw new Exception($"{network.CryptoCode}: not started or fully synched"); } var strategy = GetDirectDerivationStrategy(derivationScheme); var wallet = _walletProvider.GetWallet(network); var change = wallet.GetChangeAddressAsync(derivationScheme); var unspentCoins = await wallet.GetUnspentCoins(derivationScheme); var changeAddress = await change; var send = new[] { (
public async Task <IActionResult> LedgerConnection( string storeId, string command, // getinfo string cryptoCode = null, // sendtoaddress string destination = null, string amount = null, string feeRate = null, string substractFees = null ) { if (!HttpContext.WebSockets.IsWebSocketRequest) { return(NotFound()); } var store = await _Repo.FindStore(storeId, GetUserId()); if (store == null) { return(NotFound()); } var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); var hw = new HardwareWalletService(webSocket); object result = null; try { BTCPayNetwork network = null; if (cryptoCode != null) { network = _NetworkProvider.GetNetwork(cryptoCode); if (network == null) { throw new FormatException("Invalid value for crypto code"); } } BitcoinAddress destinationAddress = null; if (destination != null) { try { destinationAddress = BitcoinAddress.Create(destination); } catch { } if (destinationAddress == null) { throw new FormatException("Invalid value for destination"); } } FeeRate feeRateValue = null; if (feeRate != null) { try { feeRateValue = new FeeRate(Money.Satoshis(int.Parse(feeRate)), 1); } catch { } if (feeRateValue == null || feeRateValue.FeePerK <= Money.Zero) { throw new FormatException("Invalid value for fee rate"); } } Money amountBTC = null; if (amount != null) { try { amountBTC = Money.Parse(amount); } catch { } if (amountBTC == null || amountBTC <= Money.Zero) { throw new FormatException("Invalid value for amount"); } } bool subsctractFeesValue = false; if (substractFees != null) { try { subsctractFeesValue = bool.Parse(substractFees); } catch { throw new FormatException("Invalid value for substract fees"); } } if (command == "test") { result = await hw.Test(); } if (command == "getxpub") { result = await hw.GetExtPubKey(network); } if (command == "getinfo") { var strategy = GetDirectDerivationStrategy(store, network); var strategyBase = GetDerivationStrategy(store, network); if (!await hw.SupportDerivation(network, strategy)) { throw new Exception($"This store is not configured to use this ledger"); } var feeProvider = _FeeRateProvider.CreateFeeProvider(network); var recommendedFees = feeProvider.GetFeeRateAsync(); var balance = _WalletProvider.GetWallet(network).GetBalance(strategyBase); result = new GetInfoResult() { Balance = (double)(await balance).ToDecimal(MoneyUnit.BTC), RecommendedSatoshiPerByte = (int)(await recommendedFees).GetFee(1).Satoshi }; } if (command == "sendtoaddress") { var strategy = GetDirectDerivationStrategy(store, network); var strategyBase = GetDerivationStrategy(store, network); var wallet = _WalletProvider.GetWallet(network); var change = wallet.GetChangeAddressAsync(strategyBase); var unspentCoins = await wallet.GetUnspentCoins(strategyBase); var changeAddress = await change; unspentCoins.Item2.TryAdd(changeAddress.Item1.ScriptPubKey, changeAddress.Item2); var transaction = await hw.SendToAddress(strategy, unspentCoins.Item1, network, new[] { (destinationAddress as IDestination, amountBTC, subsctractFeesValue) },
public async Task <UploadResult> UploadAudioAsync(Guid userId, UploadAudioRequest request) { return(await BaseInvokeCheckModelAsync(request, async() => { User user = _dbContext.Users.FirstOrDefault(x => x.Id == userId); if (user == null) { throw new Exception("User not found, but token does"); } var responseBuilder = ResponseBuilder <UploadResult> .Fail(); if (user.IsUploadingAudio) { return responseBuilder.SetInfoAndBuild("User already uploading audio"); } user.IsUploadingAudio = true; _dbContext.SaveChanges(); using (var transaction = _dbContext.Database.BeginTransaction()) { try { GetInfoResult result = await GetInfoAsync(new UrlRequest { Url = request.Url }); if (!result.Ok) { return responseBuilder .SetErrors(result.Errors) .SetInfoAndBuild(result.Info); } string videoId = UrlFormatter.GetYoutubeVideoIdentifier(request.Url); IFile videoFile = await _saveVideo.SaveAsync(request.Url); IFile audioFile = await _extractAudio.ExtractAsync(videoFile); //TODO: create upload for FileSystem, Blob, etc... string accessUrl = _uploadAudio.Upload(audioFile, StorageType.FileSystem); var generalPlayList = _dbContext.Playlists.FirstOrDefault(x => x.OwnerId == userId && x.IsGeneral); if (generalPlayList == null) { throw new Exception("Playlist not found"); } var audio = new Audio { Id = Guid.NewGuid(), AccessUrl = accessUrl, DateCreated = DateTime.Now, Artist = request.Artist, Song = request.Song, Duration = audioFile.Duration, Extension = audioFile.Extension, FileName = audioFile.Filename, UniqueIdentifier = videoId, UploaderId = userId }; var audioPlaylist = new AudioPlaylist { AudioId = audio.Id, DateCreated = DateTime.Now, PlaylistId = generalPlayList.Id, Order = generalPlayList.OrderValue }; //update max index in playlist generalPlayList.OrderValue++; //add entities _dbContext.AudioPlaylists.Add(audioPlaylist); Audio audioEntity = _dbContext.Audios.Add(audio).Entity; _dbContext.SaveChanges(); transaction.Commit(); return ResponseBuilder <UploadResult> .SuccessBuild(new UploadResult { Audio = AudioMapper.ToApi.FromData(audioEntity) }); } catch (Exception ex) { transaction.Rollback(); throw ex; } finally { //skip upload process user.IsUploadingAudio = false; _dbContext.SaveChanges(); } } })); }
public static void SetVersion(this GetInfoResult result, int version) { version &= 0xFF; result &= (GetInfoResult)0x7FFFFF00; result |= (GetInfoResult)version; }
public static void ClearVersion(this GetInfoResult result) { result &= (GetInfoResult)0x7FFFFF00; }