Esempio n. 1
0
        private async Task <FilePickerSelectedFilesArray> UploadPickerPickFilesAsync(bool multiple, CancellationToken token)
        {
            var multipleParameter = multiple ? "true" : "false";
            var acceptParameter   = WebAssemblyRuntime.EscapeJs(BuildAcceptString());
            var temporaryFolder   = ApplicationData.Current.LocalCacheFolder;

            if (!Directory.Exists(temporaryFolder.Path))
            {
                temporaryFolder.MakePersistent();
            }
            var targetFolder          = Directory.CreateDirectory(Path.Combine(temporaryFolder.Path, Guid.NewGuid().ToString()));
            var targetFolderParameter = WebAssemblyRuntime.EscapeJs(targetFolder.FullName);
            var jsUploadQuery         = $"{JsType}.uploadPickFilesAsync({multipleParameter},'{targetFolderParameter}','{acceptParameter}')";
            var fileCountString       = await WebAssemblyRuntime.InvokeAsync(jsUploadQuery);

            if (int.TryParse(fileCountString, out var fileCount))
            {
                var files = targetFolder
                            .GetFiles()
                            .Select(f => StorageFile.GetFileFromPath(f.FullName))
                            .ToArray();

                return(new FilePickerSelectedFilesArray(files));
            }
            return(new FilePickerSelectedFilesArray(Array.Empty <StorageFile>()));
        }
            public override async Task <StorageFile> CreateFileAsync(string desiredName, CreationCollisionOption option, CancellationToken cancellationToken)
            {
                var actualName = desiredName;

                var existingItem = await TryGetItemAsync(desiredName, cancellationToken);

                switch (option)
                {
                case CreationCollisionOption.ReplaceExisting:
                    if (existingItem is StorageFolder)
                    {
                        throw new UnauthorizedAccessException("There is already a folder with the same name.");
                    }

                    if (existingItem is StorageFile)
                    {
                        // Delete existing file
                        await existingItem.DeleteAsync();
                    }
                    break;

                case CreationCollisionOption.FailIfExists:
                    if (existingItem != null)
                    {
                        throw new UnauthorizedAccessException("There is already an item with the same name.");
                    }
                    break;

                case CreationCollisionOption.OpenIfExists:
                    if (existingItem is StorageFile existingFile)
                    {
                        return(existingFile);
                    }

                    if (existingItem is StorageFolder)
                    {
                        throw new UnauthorizedAccessException("There is already a file with the same name.");
                    }
                    break;

                case CreationCollisionOption.GenerateUniqueName:
                    actualName = await FindAvailableNumberedFileNameAsync(desiredName);

                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(option));
                }

                var newFolderNativeInfo = await WebAssemblyRuntime.InvokeAsync($"{JsType}.createFileAsync(\"{_id}\", \"{WebAssemblyRuntime.EscapeJs(actualName)}\")");

                if (newFolderNativeInfo == null)
                {
                    throw new UnauthorizedAccessException("Could not create file.");
                }

                var info = JsonHelper.Deserialize <NativeStorageItemInfo>(newFolderNativeInfo);

                return(StorageFile.GetFromNativeInfo(info, Owner));
            }
        public static async Task <Stream> MergeToFileAsync(string video, string audio, string output)
        {
            await WebAssemblyRuntime.InvokeAsync($@"
                ffmpeg.run('-i', '{WebAssemblyRuntime.EscapeJs(video)}', '-i', '{WebAssemblyRuntime.EscapeJs(audio)}', '-c', 'copy', '{WebAssemblyRuntime.EscapeJs(output)}');");

            return(FFmpegFile.OpenRead(output));
        }
Esempio n. 4
0
        public static async Task FetchNoCors(string url, long from, long to)
        {
            Console.WriteLine("LMAO");
            var result = await WebAssemblyRuntime.InvokeAsync($"fetch('{url}', {{mode: 'no-cors', headers: {{'range': 'bytes={from}-{to}'}}}});");

            Console.WriteLine(result);
        }
Esempio n. 5
0
        private static async Task <string> GetClipboardText()
        {
            var command = $"{JsType}.getText();";
            var text    = await WebAssemblyRuntime.InvokeAsync(command);

            return(text);
        }
        private static async Task <bool> ShowShareUIAsync(ShareUIOptions options, DataPackage dataPackage)
        {
            var dataPackageView = dataPackage.GetView();

            var title = dataPackage.Properties.Title != null ? $"\"{WebAssemblyRuntime.EscapeJs(dataPackage.Properties.Title)}\"" : null;

            string?text;

            if (dataPackageView.Contains(StandardDataFormats.Text))
            {
                text = await dataPackageView.GetTextAsync();
            }
            else
            {
                text = dataPackage.Properties.Description;
            }
            text = text != null ? $"\"{WebAssemblyRuntime.EscapeJs(text)}\"" : null;

            var uri = await GetSharedUriAsync(dataPackageView);

            var uriText = uri != null ? $"\"{WebAssemblyRuntime.EscapeJs(uri.OriginalString)}\"" : null;

            var result = await WebAssemblyRuntime.InvokeAsync($"{JsType}.showShareUI({title ?? "null"},{text ?? "null"},{uriText ?? "null"})");

            return(bool.TryParse(result, out var boolResult) && boolResult);
        }
        /// <summary>
        /// Runs the FFmpeg application, as if invoked on the command line.
        /// </summary>
        /// <param name="param">Command line arguments. The last argument MUST be the output file.</param>
        /// <returns>A Stream containing the output file.</returns>
        public static async Task <Stream> RunAsync(params string [] param)
        {
            await WebAssemblyRuntime.InvokeAsync($@"
                ffmpeg.run({string.Join(",", param.Select(x => $@"'{WebAssemblyRuntime.EscapeJs(x)}'"))});
            ");

            return(FFmpegFile.OpenRead(param.Last()));
        }
Esempio n. 8
0
        private static async Task <HashSet <string> > GetAssets(CancellationToken ct)
        {
            var assetsUri = AssetsPathBuilder.BuildAssetUri("uno-assets.txt");

            var assets = await WebAssemblyRuntime.InvokeAsync($"Windows.Storage.AssetManager.DownloadAssetsManifest(\'{assetsUri}\')");

            return(new HashSet <string>(Regex.Split(assets, "\r\n|\r|\n"), StringComparer.OrdinalIgnoreCase));
        }
Esempio n. 9
0
        private static async Task <HashSet <string> > GetAssets(CancellationToken ct)
        {
            var assetsUri = !string.IsNullOrEmpty(UNO_BOOTSTRAP_APP_BASE) ? $"{UNO_BOOTSTRAP_APP_BASE}/uno-assets.txt" : "uno-assets.txt";

            var assets = await WebAssemblyRuntime.InvokeAsync($"Windows.Storage.AssetManager.DownloadAssetsManifest(\'{assetsUri}\')");

            return(new HashSet <string>(Regex.Split(assets, "\r\n|\r|\n"), StringComparer.OrdinalIgnoreCase));
        }
Esempio n. 10
0
            private static async Task <HashSet <string> > GetAssets()
            {
                var assetsUri = !string.IsNullOrEmpty(UNO_BOOTSTRAP_APP_BASE) ? $"{UNO_BOOTSTRAP_APP_BASE}/uno-assets.txt" : "uno-assets.txt";

                var assets = await WebAssemblyRuntime.InvokeAsync($"fetch('{assetsUri}').then(r => r.text())");

                return(new HashSet <string>(Regex.Split(assets, "\r\n|\r|\n")));
            }
Esempio n. 11
0
        public static async Task FetchNoCors(string url)
        {
            Console.WriteLine("LMAO");
            var result = await WebAssemblyRuntime.InvokeAsync($"fetch('{url}', {{mode: 'no-cors'}}).then(res => res.blob()).then(blob => {{return blob.text();}});");

            Console.WriteLine(result);
            Console.WriteLine($"{result.Length} bytes received.");
        }
Esempio n. 12
0
            private static async Task <HashSet <string> > GetAssets()
            {
                var assetsUri = AssetsPathBuilder.BuildAssetUri("uno-assets.txt");

                var assets = await WebAssemblyRuntime.InvokeAsync($"fetch('{assetsUri}').then(r => r.text())");

                return(new HashSet <string>(Regex.Split(assets, "\r\n|\r|\n")));
            }
            internal async Task DeleteItemAsync(string itemName)
            {
                var result = await WebAssemblyRuntime.InvokeAsync($"{JsType}.deleteItemAsync(\"{_id}\", \"{WebAssemblyRuntime.EscapeJs(itemName)}\")");

                if (result == null)
                {
                    throw new UnauthorizedAccessException($"Could not delete item {itemName}");
                }
            }
Esempio n. 14
0
        public async Task WhenPromiseReturnErrorAsynchronously()
        {
            var js = @"
				(function(){
				  return new Promise((ok, err)=> setTimeout(()=>err(""error"")));
				})();"                ;

            Func <Task> Do = () => WebAssemblyRuntime.InvokeAsync(js);

            await Do.Should().ThrowAsync <Exception>().WithMessage("error");
        }
Esempio n. 15
0
        public async Task WhenPromiseThrowsExceptionDuringSetup()
        {
            var js = @"
				(function(){
				  throw ""error"";
				})();"                ;

            Func <Task> Do = () => WebAssemblyRuntime.InvokeAsync(js);

            await Do.Should().ThrowAsync <Exception>().WithMessage("error");
        }
Esempio n. 16
0
        public static DataPackageView GetContent()
        {
            var dataPackageView = new DataPackageView();

            var command     = $"{JsType}.getText()";
            var getTextTask = WebAssemblyRuntime.InvokeAsync(command);

            dataPackageView.SetFormatTask(StandardDataFormats.Text, getTextTask);

            return(dataPackageView);
        }
Esempio n. 17
0
        public async Task <Uri> AcquireAuthorizationCodeAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken)
        {
            var urlNavigate = WebAssemblyRuntime.EscapeJs(authorizationUri.OriginalString);
            var urlRedirect = WebAssemblyRuntime.EscapeJs(redirectUri.OriginalString);

            var js = $@"MSAL.WebUI.authenticate(""{urlNavigate}"", ""{urlRedirect}"", ""Sign in"", 483, 600);";

            var uri = await WebAssemblyRuntime.InvokeAsync(js);

            return(new Uri(uri));
        }
Esempio n. 18
0
        public async Task WhenPromiseReturnAsynchronously()
        {
            var js = @"
				(function(){
				  return new Promise((ok, err)=> setTimeout(()=>ok(""success"")));
				})();"                ;

            var result = await WebAssemblyRuntime.InvokeAsync(js);

            result.Should().Be("success");
        }
        public static async Task <NativeWriteStreamAdapter> CreateAsync(Guid fileId)
        {
            var streamId = Guid.NewGuid();
            var result   = await WebAssemblyRuntime.InvokeAsync($"{JsType}.openAsync('{streamId}', '{fileId}')");

            if (result == null || !long.TryParse(result, out var length))
            {
                throw new InvalidOperationException("Could not create a writable stream.");
            }

            return(new NativeWriteStreamAdapter(streamId, length));
        }
Esempio n. 20
0
        public static async Task <string> DownloadAsset(CancellationToken ct, string assetPath)
        {
            var updatedPath = assetPath.TrimStart("/");
            var assetSet    = await _assets.Value;

            if (assetSet.Contains(updatedPath))
            {
                var localPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, ".assetsCache", UNO_BOOTSTRAP_APP_BASE, updatedPath);

                using var assetLock = await _assetsGate.LockForAsset(ct, updatedPath);

                if (!File.Exists(localPath))
                {
                    var assetUri  = !string.IsNullOrEmpty(UNO_BOOTSTRAP_APP_BASE) ? $"{UNO_BOOTSTRAP_APP_BASE}/{updatedPath}" : updatedPath;
                    var assetInfo = await WebAssemblyRuntime.InvokeAsync($"Windows.Storage.AssetManager.DownloadAsset(\'{assetUri}\')");

                    var parts = assetInfo.Split(';');
                    if (parts.Length == 2)
                    {
                        var ptr    = (IntPtr)int.Parse(parts[0], CultureInfo.InvariantCulture);
                        var length = int.Parse(parts[1], CultureInfo.InvariantCulture);

                        try
                        {
                            var buffer = new byte[length];
                            Marshal.Copy(ptr, buffer, 0, length);

                            if (Path.GetDirectoryName(localPath) is { } path)
                            {
                                Directory.CreateDirectory(path);
                            }

                            File.WriteAllBytes(localPath, buffer);
                        }
                        finally
                        {
                            Marshal.FreeHGlobal(ptr);
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException($"Invalid Windows.Storage.AssetManager.DownloadAsset return value");
                    }
                }

                return(localPath);
            }
            else
            {
                throw new FileNotFoundException($"The file [{assetPath}] cannot be found");
            }
        }
Esempio n. 21
0
        private async Task <Contact[]> PickContactsAsync(bool multiple, CancellationToken token)
        {
            var pickResultJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.pickContacts({(multiple ? "true" : "false")})");

            if (string.IsNullOrEmpty(pickResultJson) || token.IsCancellationRequested)
            {
                return(Array.Empty <Contact>());
            }

            var contacts = JsonHelper.Deserialize <WasmContact[]>(pickResultJson);

            return(contacts.Where(c => c != null).Select(c => ContactFromContactInfo(c)).ToArray());
        }
            public override async Task <IReadOnlyList <StorageFolder> > GetFoldersAsync(CancellationToken ct)
            {
                var itemInfosJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.getFoldersAsync(\"{_id}\")");

                var itemInfos = JsonHelper.Deserialize <NativeStorageItemInfo[]>(itemInfosJson);
                var results   = new List <StorageFolder>();

                foreach (var info in itemInfos)
                {
                    results.Add(GetFromNativeInfo(info, Owner));
                }
                return(results.AsReadOnly());
            }
Esempio n. 23
0
        /// <summary>
        /// Opens FilePicker via javascript and allows user to pick audio file.<br></br>
        /// WASM only.
        /// </summary>
        /// <returns></returns>
        public async Task UploadNewSong_WASM()
        {
            // Setup delegates and resources
            DeleteDelegates();
            WasmSongEvent += OnNewSongUploadedEvent;
            stringBuilder  = new StringBuilder();

            // In WASM UI Thread will be blocked while uploading
            // so we should give user some feedback before hand.
            InformationText = "Processing uploaded file." + Environment.NewLine + " Please wait ...";

            await WebAssemblyRuntime.InvokeAsync($"pickAndUploadAudioFile({AudioProvider.AudioDataProvider.Parameters.MaxUploadSize_MB});");
        }
            public static async Task <StorageFolder?> GetPrivateRootAsync()
            {
                var itemInfoJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.getPrivateRootAsync()");

                if (itemInfoJson == null)
                {
                    return(null);
                }

                var item = JsonHelper.Deserialize <NativeStorageItemInfo>(itemInfoJson);

                return(GetFromNativeInfo(item, null));
            }
Esempio n. 25
0
        private async Task <StorageFolder?> PickSingleFolderTaskAsync(CancellationToken token)
        {
            var pickedFolderJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.pickSingleFolderAsync()");

            if (pickedFolderJson is null)
            {
                // User did not select any folder.
                return(null);
            }

            var info = JsonHelper.Deserialize <NativeStorageItemInfo>(pickedFolderJson);

            return(StorageFolder.GetFromNativeInfo(info, null));
        }
Esempio n. 26
0
            public override async Task <StorageFile> GetFileAsync(string name, CancellationToken token)
            {
                var fileInfoJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.tryGetFileAsync(\"{_id}\", \"{WebAssemblyRuntime.EscapeJs(name)}\")");

                if (fileInfoJson == null)
                {
                    throw new FileNotFoundException($"There is no file with name '{name}'.");
                }

                // File exists
                var fileInfo = JsonHelper.Deserialize <NativeStorageItemInfo>(fileInfoJson);

                return(StorageFile.GetFromNativeInfo(fileInfo, Owner));
            }
Esempio n. 27
0
        /// <summary>
        /// 判断摄像头和麦克设备是否允许使用
        /// </summary>
        /// <returns></returns>
        public static async Task <bool> ExistMediaDevice()
        {
            var js = @"
					(async () => {{
						try {{
                            await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
                            return 'true';
						}}
                        catch (e) {{ }}
                        return 'false';
					}})();"                    ;

            return(await WebAssemblyRuntime.InvokeAsync(js) == "true");
        }
        protected virtual async Task <WebAuthenticationResult> AuthenticateAsyncCore(
            WebAuthenticationOptions options,
            Uri requestUri,
            Uri callbackUri,
            CancellationToken ct)
        {
            // options are ignored for now

            // TODO: support ct

            var    urlNavigate = WebAssemblyRuntime.EscapeJs(requestUri.OriginalString);
            var    urlRedirect = WebAssemblyRuntime.EscapeJs(callbackUri.OriginalString);
            string js;

            var timeout = ((long)Timeout.TotalMilliseconds).ToString();

            var useIframe =
                options.HasFlag(WebAuthenticationOptions.SilentMode) ||
                !string.IsNullOrEmpty(WinRTFeatureConfiguration.WebAuthenticationBroker.IFrameHtmlId);

            if (useIframe)
            {
                var iframeId = WinRTFeatureConfiguration.WebAuthenticationBroker.IFrameHtmlId;
                js =
                    $@"Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateUsingIframe(""{iframeId}"", ""{urlNavigate}"", ""{urlRedirect}"", {timeout});";
            }
            else
            {
                var title = WebAssemblyRuntime.EscapeJs(WinRTFeatureConfiguration.WebAuthenticationBroker.WindowTitle ??
                                                        "Sign In");

                var windowWidth  = WinRTFeatureConfiguration.WebAuthenticationBroker.WindowWidth;
                var windowHeight = WinRTFeatureConfiguration.WebAuthenticationBroker.WindowHeight;
                js =
                    $@"Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateUsingWindow(""{urlNavigate}"", ""{urlRedirect}"", ""{title}"", {windowWidth}, {windowHeight}, {timeout});";
            }

            try
            {
                var results = (await WebAssemblyRuntime.InvokeAsync(js)).Split(new[] { '|' }, 2);

                return(results[0] switch
                {
                    "success" => new WebAuthenticationResult(results[1], 0, WebAuthenticationStatus.Success),
                    "cancel" => new WebAuthenticationResult(null, 0, WebAuthenticationStatus.UserCancel),
                    "timeout" => new WebAuthenticationResult(null, 0, WebAuthenticationStatus.UserCancel),
                    _ => new WebAuthenticationResult(null, 0, WebAuthenticationStatus.ErrorHttp)
                });
            }
Esempio n. 29
0
        public async Task <byte[]> DownloadDataTaskAsync(string url)
        {
            var result = await WebAssemblyRuntime.InvokeAsync($@"FetchToBuffer('{WebAssemblyRuntime.EscapeJs($"{CorsServer}/{url}")}')");

            long[] ints   = result.Split(',').Select(x => long.Parse(x)).ToArray();
            IntPtr ptr    = (IntPtr)ints[0];
            int    length = (int)ints[1];

            byte[] managedArray = new byte[length];
            Marshal.Copy(ptr, managedArray, 0, length);

            WebAssemblyRuntime.InvokeJS($@"Free({ints[0]})");

            return(managedArray);
        }
Esempio n. 30
0
        public static async Task <byte[]> FetchProxy(string url)
        {
            var result = await WebAssemblyRuntime.InvokeAsync($@"
            {{
                    const buf2hex = (buffer) => 
                    {{ // buffer is an ArrayBuffer
                        return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
                    }}
                    return fetch('{CorsServer}/{url}')
                    .then(response => response.blob())
                    .then(blob => blob.arrayBuffer())
                    .then(buffer => buf2hex(buffer));
            }}");

            return(HexStringToByte(result));
        }