public async Task <Stream> GetImageStreamAsync() { // Create and initialize the FileOpenPicker FileOpenPicker openPicker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary, }; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); // Get a file and return a Stream StorageFile storageFile = await openPicker.PickSingleFileAsync(); if (storageFile == null) { return(null); } IRandomAccessStreamWithContentType raStream = await storageFile.OpenReadAsync(); //(RTE_Localization.App.Current.BindingContext as ViewModel).Stream1 = raStream.AsStream(); return(raStream.AsStream()); }
private async Task Activate(string mainType, string contentType) { if (IsMainTypeImpelmented(mainType)) { SetLoading(contentType); } else { SetSelect("ContentType is not supported"); return; } IRandomAccessStreamWithContentType stream = await Api.GetFileRandomAccessStream(Source.FullPath); if (stream == null) { SetSelect("Loading stream failed"); bool ping = await Api.IsAuthorized(); if (!ping) { SetSelect("No connection to server"); } return; } try { switch (mainType) { case "text": TextControl textControl = new TextControl(); StreamReader reader = new StreamReader(stream.AsStream()); textControl.SetSource(await reader.ReadToEndAsync()); SetContent(textControl); break; case "audio": case "video": MediaPlayer player = MediaPlayback.Current.SetSource(stream, Source.Name, contentType); SetContent(new MediaControl(player, Controls)); break; case "image": ImageControl imageControl = new ImageControl(); await imageControl.SetSource(stream); SetContent(imageControl); break; default: SetSelect("ContentType is not supported. Logic error!"); break; } } catch (Exception e) { SetSelect(e.Message); } }
private async Task GetTextContent(CancellationToken cancellationToken, StorageFile folderBrowser = null) { StorageFile result = folderBrowser; ReportProgress(Stage2, Stage1ProgressBar, TextProgress1, 0); if (folderBrowser == null) { FileOpenPicker fileOpenPicker = new FileOpenPicker(); fileOpenPicker.FileTypeFilter.Add(".html"); fileOpenPicker.FileTypeFilter.Add(".htm"); result = await fileOpenPicker.PickSingleFileAsync(); } if (result == null) { throw new Exception("stop"); } ResetStages(invertSolidColorBrush, 0, ""); await ClearTempData(); Save.IsEnabled = false; Open.Content = "Cancel"; FileName = result.DisplayName; IRandomAccessStreamWithContentType output = await result.OpenReadAsync(); ReportProgress(Stage2, Stage1ProgressBar, TextProgress1, 50, Stage1); using (Stream stream = output.AsStream()) { buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); Text = Encoding.GetEncoding(-0).GetString(buffer); if (Text.IndexOf("<head") > 0) { Text = Text.Remove(Text.IndexOf("<head"), Text.IndexOf("<body") - Text.IndexOf("<head")); } Text = Windows.Data.Html.HtmlUtilities.ConvertToText(Text); Text = Regex.Replace(Text, "[<](?s)(.*)[>]", "", RegexOptions.Multiline); Text = Regex.Replace(Text, "[&](?!&)", "&", RegexOptions.Multiline); Text = Regex.Replace(Text, "\\[[a-z|0-9|\\ ]{0,}\\]", "", RegexOptions.Multiline | RegexOptions.IgnoreCase); Text = Text.Replace("<", "lesser than "); Text = Text.Replace(">", "greater than "); //Text = Regex.Replace(Text, "[.][[]", ". [", RegexOptions.Multiline); Sources = Text ?? ""; }; ReportProgress(Stage2, Stage1ProgressBar, TextProgress1, 100); CancelTask(cancellationToken); }
public async Task <byte[]> ImagebyteAsync(BitmapImage image) { RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(image.UriSource); IRandomAccessStreamWithContentType streamWithContent = await streamRef.OpenReadAsync(); BinaryReader reader = new BinaryReader(streamWithContent.AsStream()); avatar = reader.ReadBytes((int)streamWithContent.Size); return(avatar); }
public async Task <IZipArchive> OpenReadAsync(string filePath) { var localFolder = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync(booksFolderName); var file = await localFolder.GetFileAsync(filePath); IRandomAccessStreamWithContentType randomStream = await file.OpenReadAsync(); Stream stream = randomStream.AsStream(); ZipArchive archive = new ZipArchive(stream); WinPhoneZipArchive winPhoneZipArchive = new WinPhoneZipArchive(archive); return(winPhoneZipArchive); }
private Image GetImage(IRandomAccessStreamReference imageRef) { var test = imageRef.OpenReadAsync(); test.Cancel(); while (test.Status != Windows.Foundation.AsyncStatus.Started) { Thread.Sleep(100); } IRandomAccessStreamWithContentType sourceStream = test.GetResults(); byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = sourceStream.AsStream().Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return(Image.FromStream(ms)); } }
//Update media thumbnail async Task <BitmapFrame> GetMediaThumbnail(IRandomAccessStreamReference mediaThumbnail) { try { if (mediaThumbnail == null) { return(null); } using (IRandomAccessStreamWithContentType streamReference = await mediaThumbnail.OpenReadAsync()) { using (Stream stream = streamReference.AsStream()) { return(BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad)); } } } catch { //Debug.WriteLine("Failed loading media thumbnail."); return(null); } }
/// <summary> /// Attempts to load image, video and audio assets in the project's 'Assets/SkillAssets' folder, or the overridden storage folder, to the robot's system /// </summary> /// <param name="forceReload">force the system to upload all assets, whether they exist or not</param> /// <param name="assetFolder">pass in to override the default location</param> /// <returns></returns> public async Task LoadAssets(bool forceReload = false, StorageFolder assetFolder = null) { try { await RefreshAssetLists(); //Load the assets in the Assets/SkillAssets folder to the robot if they are missing or if ReloadAssets is passed in StorageFolder skillAssetFolder = assetFolder ?? await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets\SkillAssets"); IList <StorageFile> assetFileList = (await skillAssetFolder.GetFilesAsync()).ToList(); foreach (StorageFile storageFile in assetFileList) { if (forceReload || (!AudioList.Any(x => x.Name == storageFile.Name) && !ImageList.Any(x => x.Name == storageFile.Name) && !VideoList.Any(x => x.Name == storageFile.Name))) { StorageFile file = await skillAssetFolder.GetFileAsync(storageFile.Name); IRandomAccessStreamWithContentType stream = await file.OpenReadAsync(); byte[] contents = new byte[stream.Size]; await stream.AsStream().ReadAsync(contents, 0, contents.Length); if (storageFile.Name.EndsWith(".mp3") || storageFile.Name.EndsWith(".wav") || storageFile.Name.EndsWith(".wma") || storageFile.Name.EndsWith(".aac")) { if ((await _misty.SaveAudioAsync(storageFile.Name, contents, false, true)).Status == ResponseStatus.Success) { AudioList.Add(new AudioDetails { Name = storageFile.Name, SystemAsset = false }); _misty.SkillLogger.LogInfo($"Uploaded audio asset '{storageFile.Name}'"); } else { _misty.SkillLogger.Log($"Failed to upload audio asset '{storageFile.Name}'"); } } else if (storageFile.Name.EndsWith(".mp4") || storageFile.Name.EndsWith(".wmv")) { if ((await _misty.SaveVideoAsync(storageFile.Name, contents, false, true)).Status == ResponseStatus.Success) { VideoList.Add(new VideoDetails { Name = storageFile.Name, SystemAsset = false }); _misty.SkillLogger.LogInfo($"Uploaded video asset '{storageFile.Name}'"); } else { _misty.SkillLogger.Log($"Failed to upload video asset '{storageFile.Name}'"); } } else if (storageFile.Name.EndsWith(".jpg") || storageFile.Name.EndsWith(".jpeg") || storageFile.Name.EndsWith(".png") || storageFile.Name.EndsWith(".gif")) { if ((await _misty.SaveImageAsync(storageFile.Name, contents, false, true, 0, 0)).Status == ResponseStatus.Success) { ImageList.Add(new ImageDetails { Name = storageFile.Name, SystemAsset = false }); _misty.SkillLogger.LogInfo($"Uploaded image asset '{storageFile.Name}'"); } else { _misty.SkillLogger.Log($"Failed to upload image asset '{storageFile.Name}'"); } } else { _misty.SkillLogger.Log($"Unknown extension for asset '{storageFile.Name}', could not load to robot."); } } } } catch (Exception ex) { _misty.SkillLogger.Log("Error loading assets.", ex); } }
private async Task LoadAssets() { //Get the current assets on the robot IGetAudioListResponse audioListResponse = await _misty.GetAudioListAsync(); if (audioListResponse.Status == ResponseStatus.Success && audioListResponse.Data.Count() > 0) { _audioList = audioListResponse.Data; } IGetImageListResponse imageListResponse = await _misty.GetImageListAsync(); if (imageListResponse.Status == ResponseStatus.Success && imageListResponse.Data.Count() > 0) { _imageList = imageListResponse.Data; } IGetVideoListResponse videoListResponse = await _misty.GetVideoListAsync(); if (videoListResponse.Status == ResponseStatus.Success && videoListResponse.Data.Count() > 0) { _videoList = videoListResponse.Data; } //Load the assets in the Assets/SkillAssets folder to the robot if they are missing or if ReloadAssets is passed in StorageFolder skillAssetFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets\SkillAssets"); IList <StorageFile> assetFileList = (await skillAssetFolder.GetFilesAsync()).ToList(); foreach (StorageFile storageFile in assetFileList) { if (_reloadAssets || (!_audioList.Any(x => x.Name == storageFile.Name) && !_imageList.Any(x => x.Name == storageFile.Name) && !_videoList.Any(x => x.Name == storageFile.Name))) { StorageFile file = await skillAssetFolder.GetFileAsync(storageFile.Name); IRandomAccessStreamWithContentType stream = await file.OpenReadAsync(); byte[] contents = new byte[stream.Size]; await stream.AsStream().ReadAsync(contents, 0, contents.Length); if (storageFile.Name.EndsWith(".mp3") || storageFile.Name.EndsWith(".wav") || storageFile.Name.EndsWith(".wma") || storageFile.Name.EndsWith(".aac")) { if ((await _misty.SaveAudioAsync(storageFile.Name, contents, false, true)).Status == ResponseStatus.Success) { _audioList.Add(new AudioDetails { Name = storageFile.Name, SystemAsset = false }); _misty.SkillLogger.LogInfo($"Uploaded audio asset '{storageFile.Name}'"); } else { _misty.SkillLogger.Log($"Failed to upload audio asset '{storageFile.Name}'"); } } else if (storageFile.Name.EndsWith(".mp4") || storageFile.Name.EndsWith(".wmv")) { if ((await _misty.SaveVideoAsync(storageFile.Name, contents, false, true)).Status == ResponseStatus.Success) { _videoList.Add(new VideoDetails { Name = storageFile.Name, SystemAsset = false }); _misty.SkillLogger.LogInfo($"Uploaded video asset '{storageFile.Name}'"); } else { _misty.SkillLogger.Log($"Failed to upload video asset '{storageFile.Name}'"); } } else if (storageFile.Name.EndsWith(".jpg") || storageFile.Name.EndsWith(".jpeg") || storageFile.Name.EndsWith(".png") || storageFile.Name.EndsWith(".gif")) { if ((await _misty.SaveImageAsync(storageFile.Name, contents, false, true, 0, 0)).Status == ResponseStatus.Success) { _imageList.Add(new ImageDetails { Name = storageFile.Name, SystemAsset = false }); _misty.SkillLogger.LogInfo($"Uploaded image asset '{storageFile.Name}'"); } else { _misty.SkillLogger.Log($"Failed to upload image asset '{storageFile.Name}'"); } } else { _misty.SkillLogger.Log($"Unknown extension for asset '{storageFile.Name}', could not load to robot."); } } } }
/// <summary> /// Retrieves a list of artists from BuiltinArtists.xml /// </summary> /// <returns>A list of artists.</returns> private async Task <BuiltinArtistEntry[]> LoadBuiltinArtistEntriesAsync() { XDocument xmlDoc = null; IRandomAccessStreamWithContentType reader = null; //local file only try { using (HttpClient http = new HttpClient()) { var xmlText = await http.GetStringAsync("https://raw.githubusercontent.com/Amrykid/Neptunium-ArtistsDB/master/BuiltinArtists.xml"); xmlDoc = XDocument.Parse(xmlText); } } catch (Exception) { //Opens up an XDocument for reading the xml file. var file = builtInArtistsFile; reader = await file.OpenReadAsync(); xmlDoc = XDocument.Load(reader.AsStream()); } //Creates a list to hold the artists. List <BuiltinArtistEntry> artists = new List <BuiltinArtistEntry>(); //Looks through the <Artist> elements in the file, creating a BuiltinArtistEntry for each one. foreach (var artistElement in xmlDoc.Element("Artists").Elements("Artist")) { var artistEntry = new BuiltinArtistEntry(); artistEntry.Name = artistElement.Attribute("Name").Value; if (artistElement.Attribute("JPopAsiaUrl") != null) { artistEntry.JPopAsiaUrl = new Uri(artistElement.Attribute("JPopAsiaUrl").Value); } if (artistElement.Elements("AltName") != null) { artistEntry.AltNames = artistElement.Elements("AltName").Select(altNameElement => { string name = altNameElement.Value; string lang = "en"; string sayAs = null; if (altNameElement.Attribute("Lang") != null) { lang = altNameElement.Attribute("Lang").Value; } if (altNameElement.Attribute("SayAs") != null) { sayAs = altNameElement.Attribute("SayAs").Value; } return(new BuiltinArtistEntryAltName(name, lang, sayAs)); }).ToArray(); } if (artistElement.Elements("Related") != null) { artistEntry.RelatedArtists = artistElement.Elements("Related").Select(relatedElement => { return(relatedElement.Value); }).ToArray(); } if (artistElement.Attribute("FanArtTVUrl") != null) { artistEntry.FanArtTVUrl = new Uri(artistElement.Attribute("FanArtTVUrl").Value); } if (artistElement.Attribute("MusicBrainzUrl") != null) { artistEntry.MusicBrainzUrl = new Uri(artistElement.Attribute("MusicBrainzUrl").Value); } if (artistElement.Attribute("OriginCountry") != null) { artistEntry.CountryOfOrigin = artistElement.Attribute("OriginCountry").Value; } if (artistElement.Attribute("NameLanguage") != null) { artistEntry.NameLanguage = artistElement.Attribute("NameLanguage").Value; } else { artistEntry.NameLanguage = "en"; } if (artistElement.Attribute("SayAs") != null) { artistEntry.NameSayAs = artistElement.Attribute("SayAs").Value; } artistEntry.IsBuiltIn = true; //Adds the artist entry to the list. artists.Add(artistEntry); } //Clean up. xmlDoc = null; reader?.Dispose(); return(artists.ToArray()); }