Esempio n. 1
0
        private static void SetClipboardText(string text)
        {
            var escapedText = WebAssemblyRuntime.EscapeJs(text);
            var command     = $"{JsType}.setText(\"{escapedText}\");";

            WebAssemblyRuntime.InvokeJS(command);
        }
Esempio n. 2
0
        public static void SetContent(DataPackage content)
        {
            var text    = WebAssemblyRuntime.EscapeJs(content.Text);
            var command = $"Uno.Utils.Clipboard.setText(\"{text}\");";

            WebAssemblyRuntime.InvokeJS(command);
        }
        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
        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>()));
        }
        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>
        /// Tries to get the relevant permissions and show toast notifications.
        /// </summary>
        /// <param name="toast"></param>
        /// <returns></returns>
        public static async Task Show(this ToastNotification toast)
        {
            // Mono seems to optimize away unsued functions..
            if (await DummyFalseStuff().ConfigureAwait(false))
            {
                Report(null);
            }

            _permission = _permission ?? await QueryPermissionAsync().ConfigureAwait(false);

            if ((bool)_permission)
            {
                WebAssemblyRuntime.InvokeJS($@"
                    var n = new Notification(
                        '{WebAssemblyRuntime.EscapeJs(toast.Title)}',
                        {{
                            body: '{WebAssemblyRuntime.EscapeJs(toast.Message)}',
                            {await SetIconIfOveriddenAsync(toast.AppLogoOverride).ConfigureAwait(false)}
                        }}
                    );
                ");
            }
            else
            {
                // Fall back to simple alert pop-up.
                WebAssemblyRuntime.InvokeJS($@"alert('{WebAssemblyRuntime.EscapeJs(toast.Message)}');");
            }
        }
Esempio n. 7
0
        private void SendMessage(object sender, RoutedEventArgs e)
        {
            var message = WebAssemblyRuntime.EscapeJs(msgToSend.Text);
            var js      = $"element.UnoPeerConnection.SendMessage(\"{message}\");";

            this.ExecuteJavascript(js);
        }
        /// <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()));
        }
        static partial void InnerReportPageView(string pageName, string arguments)
        {
            var command = string.Concat(
                "Uno.UI.Demo.Analytics.reportPageView(\"",
                WebAssemblyRuntime.EscapeJs(pageName),
                "\");");

            WebAssemblyRuntime.InvokeJS(command);
        }
Esempio n. 10
0
        protected internal void SetStyle(string name, string value)
        {
            var escapedvalue = WebAssemblyRuntime.EscapeJs(value);

            var command = "Uno.UI.WindowManager.current.setStyle(\"" +
                          HtmlId + "\", " +
                          "{\"" + name + "\": \"" + escapedvalue + "\"}" +
                          ");";

            WebAssemblyRuntime.InvokeJS(command);
        }
Esempio n. 11
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));
        }
        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. 13
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. 14
0
        private async Task <string> InitPeerInitiatorConnection(string roomName = "")
        {
            var escapedRoomName = WebAssemblyRuntime.EscapeJs(roomName);
            var js = $@"
					(async () => {{
						if(element.UnoPeerConnection) {{
							element.UnoPeerConnection.Close();
						}}
						element.UnoPeerConnection = await Uno.WebRTC.PeerConnection.CreateInitiator(""{escapedRoomName}"", element);
					}})();"                    ;

            await this.ExecuteJavascriptAsync(js);

            _iceTcs = new TaskCompletionSource <string>();

            var offer = await _iceTcs.Task;

            return(offer);
        }
Esempio n. 15
0
        private async Task <StorageFile?> NativePickerPickSaveFileAsync(CancellationToken token)
        {
            var showAllEntryParameter = "true";
            var fileTypeMapParameter  = JsonHelper.Serialize(BuildFileTypesMap());

            var suggestedFileName = SuggestedFileName != "" ? WebAssemblyRuntime.EscapeJs(SuggestedFileName) : "";

            var id = WebAssemblyRuntime.EscapeJs(SettingsIdentifier);

            var startIn = SuggestedStartLocation.ToStartInDirectory();
            var promise = $"{JsType}.nativePickSaveFileAsync({showAllEntryParameter},'{WebAssemblyRuntime.EscapeJs(fileTypeMapParameter)}','{suggestedFileName}','{id}','{startIn}')";
            var nativeStorageItemInfo = await WebAssemblyRuntime.InvokeAsync(promise);

            if (nativeStorageItemInfo is null)
            {
                return(null);
            }

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

            return(StorageFile.GetFromNativeInfo(info));
        }
Esempio n. 16
0
        private async Task <FilePickerSelectedFilesArray> NativePickerPickFilesAsync(bool multiple, CancellationToken token)
        {
            var showAllEntryParameter   = FileTypeFilter.Contains("*") ? "true" : "false";
            var multipleParameter       = multiple ? "true" : "false";
            var fileTypeAcceptTypes     = BuildFileTypesMap();
            var fileTypeAcceptTypesJson = JsonHelper.Serialize(fileTypeAcceptTypes);
            var fileTypeMapParameter    = WebAssemblyRuntime.EscapeJs(fileTypeAcceptTypesJson);

            var nativeStorageItemInfosJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.nativePickFilesAsync({multipleParameter},{showAllEntryParameter},'{fileTypeMapParameter}')");

            var infos = JsonHelper.Deserialize <NativeStorageItemInfo[]>(nativeStorageItemInfosJson);

            var results = new List <StorageFile>();

            foreach (var info in infos)
            {
                var storageFile = StorageFile.GetFromNativeInfo(info);
                results.Add(storageFile);
            }

            return(new FilePickerSelectedFilesArray(results.ToArray()));
        }
Esempio n. 17
0
        private async Task <StorageFolder?> PickSingleFolderTaskAsync(CancellationToken token)
        {
            if (!IsNativePickerSupported())
            {
                throw new NotSupportedException("Could not handle the request using any picker implementation.");
            }

            var id      = WebAssemblyRuntime.EscapeJs(SettingsIdentifier);
            var startIn = SuggestedStartLocation.ToStartInDirectory();

            var pickedFolderJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.pickSingleFolderAsync('{id}','{startIn}')");

            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. 18
0
        /// <summary>
        /// Starts recording audio or opens filepicker, validates uploaded song format, queries server for song recognition and shows result on the screen. <br></br>
        /// Also handles necessary UI updates. <br></br>
        /// WASM only.
        /// </summary>
        public void RecognizeSong_WASM()
        {
            // Setup Delegates
            DeleteDelegates();
            WasmSongEvent += OnSongToRecognizeEvent;

            // Update UI
            UpdateRecognitionUI();

            if (Settings.UseMicrophone)
            {
                IsRecording   = true;
                stringBuilder = new StringBuilder();
                var escapedRecLength = WebAssemblyRuntime.EscapeJs((Settings.RecordingLength).ToString());
                WebAssemblyRuntime.InvokeJS($"recordAndUploadAudio({escapedRecLength}, {AudioProvider.AudioDataProvider.Parameters.SamplingRate}, {AudioProvider.AudioDataProvider.Parameters.Channels});");
            }
            else
            {
                stringBuilder = new StringBuilder();
                WebAssemblyRuntime.InvokeJS($"pickAndUploadAudioFile({AudioProvider.AudioDataProvider.Parameters.MaxRecordingUploadSize_MB}, 0);");                 //(size_limit, js metadata offset)
            }
        }
Esempio n. 19
0
        public void SetCookie(SetCookieRequest request)
        {
            var httpCookie = new HttpCookie(request.Cookie.Name, request.Domain ?? string.Empty, request.Path ?? string.Empty)
            {
                Secure  = request.Secure,
                Expires = request.Expires,
                Value   = request.Cookie.Value,
            };
            var serializedCookie = httpCookie.ToString();

            if (request.MaxAge != null)
            {
                serializedCookie += $"; max-age={request.MaxAge.Value.ToString(CultureInfo.InvariantCulture)}";
            }
            if (request.SameSite != null)
            {
                serializedCookie += $"; samesite={request.SameSite.Value.ToString("g").ToLowerInvariant()}";
            }

            var escapedCookie = WebAssemblyRuntime.EscapeJs(serializedCookie);
            var jsInvoke      = $"document.cookie = '{escapedCookie}'";

            WebAssemblyRuntime.InvokeJS(jsInvoke);
        }
            public override async Task <StorageFile> GetFileAsync(string name, CancellationToken token)
            {
                var fileInfoJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.tryGetFileAsync(\"{_id}\", \"{WebAssemblyRuntime.EscapeJs(name)}\")");

                if (fileInfoJson == null)
                {
                    var folderInfoJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.tryGetFolderAsync(\"{_id}\", \"{WebAssemblyRuntime.EscapeJs(name)}\")");

                    if (folderInfoJson != null)
                    {
                        // Folder exists
                        throw new ArgumentException("The item with given name is a folder.", nameof(name));
                    }
                    else
                    {
                        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. 21
0
        private async Task <StorageFile?> NativePickerPickSaveFileAsync(CancellationToken token)
        {
            var showAllEntryParameter = "true";
            var fileTypeMapParameter  = JsonHelper.Serialize(BuildFileTypesMap());

            var promise = $"{JsType}.nativePickSaveFileAsync({showAllEntryParameter},'{WebAssemblyRuntime.EscapeJs(fileTypeMapParameter)}')";
            var nativeStorageItemInfo = await WebAssemblyRuntime.InvokeAsync(promise);

            if (nativeStorageItemInfo is null)
            {
                return(null);
            }

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

            return(StorageFile.GetFromNativeInfo(info));
        }
Esempio n. 22
0
 public static void Delete(string fileName)
 {
     WebAssemblyRuntime.InvokeJS($@"ffmpeg.FS('unlink', '{WebAssemblyRuntime.EscapeJs(fileName)}');");
 }
 internal FFmpegFileStream(string fileName, string mode)
 {
     if (!FFmpeg.Loaded)
     {
         throw new InvalidOperationException("Cannot use FFmpegFileStream before initializing FFmpeg.");
     }
     uuid          = System.Guid.NewGuid().ToString();
     this.fileName = fileName;
     WebAssemblyRuntime.InvokeJS($@"fileStreams['{uuid}'] = ffmpeg.FS('open', '{WebAssemblyRuntime.EscapeJs(fileName)}', '{mode}')");
     canWrite = mode.Contains("r");
     canRead  = mode.Contains("w");
 }
            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}");
                }
            }
            public override async Task <IStorageItem?> TryGetItemAsync(string name, CancellationToken token)
            {
                var fileInfoJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.tryGetFileAsync(\"{_id}\", \"{WebAssemblyRuntime.EscapeJs(name)}\")");

                if (fileInfoJson != null)
                {
                    // File exists
                    var fileInfo = JsonHelper.Deserialize <NativeStorageItemInfo>(fileInfoJson);
                    return(StorageFile.GetFromNativeInfo(fileInfo, Owner));
                }

                var folderInfoJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.tryGetFolderAsync(\"{_id}\", \"{WebAssemblyRuntime.EscapeJs(name)}\")");

                if (folderInfoJson != null)
                {
                    // Folder exists
                    var folderInfo = JsonHelper.Deserialize <NativeStorageItemInfo>(folderInfoJson);
                    return(GetFromNativeInfo(folderInfo, Owner));
                }

                return(null);
            }
Esempio n. 26
0
            public override async Task <StorageFolder> GetFolderAsync(string name, CancellationToken ct)
            {
                // Handling validation
                // Source: https://docs.microsoft.com/en-us/uwp/api/windows.storage.storagefolder.getfolderasync?view=winrt-19041#exceptions

                if (Uri.IsWellFormedUriString(name, UriKind.RelativeOrAbsolute))
                {
                    throw new ArgumentException("The path cannot be in Uri format (for example, /Assets). Check the value of name.", nameof(name));
                }

                var folderInfoJson = await WebAssemblyRuntime.InvokeAsync($"{JsType}.tryGetFolderAsync(\"{_id}\", \"{WebAssemblyRuntime.EscapeJs(name)}\")");

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

                var info          = JsonHelper.Deserialize <NativeStorageItemInfo>(folderInfoJson);
                var storageFolder = GetFromNativeInfo(info, Owner);

                return(storageFolder);
            }
            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));
            }