Exemple #1
0
        public static async void ShareVideo(Video video)
        {
            Items = new List <IStorageFile>();
            var files = await WinRtStorageHelper.GetFileAsync(video.VideoUrl, KnownFolders.VideosLibrary);

            Items.Add(files);
            Register();
        }
Exemple #2
0
        public static async void ShareSong(List <Song> songs)
        {
            Items = new List <IStorageFile>();
            foreach (var song in songs)
            {
                _filename = song.Name.CleanForFileName("Invalid Song Name");
                if (song.ArtistName != song.Album.PrimaryArtist.Name)
                {
                    _filename = song.ArtistName.CleanForFileName("Invalid Artist Name") + "-" + _filename;
                }

                _path = string.Format(
                    AppConstant.SongPath,
                    song.Album.PrimaryArtist.Name.CleanForFileName("Invalid Artist Name"),
                    song.Album.Name.CleanForFileName("Invalid Album Name"),
                    _filename);
                var files = await WinRtStorageHelper.GetFileAsync(_path, KnownFolders.MusicLibrary);

                Items.Add(files);
            }
            Register();
        }
Exemple #3
0
        public static async Task MigrateAsync()
        {
            var songs         = App.Locator.CollectionService.Songs.Where(p => p.SongState == SongState.Downloaded).ToList();
            var importedSongs =
                App.Locator.CollectionService.Songs.Where(
                    p => p.SongState == SongState.Local && !p.AudioUrl.Substring(1).StartsWith(":")).ToList();
            var songsFolder = await WinRtStorageHelper.GetFolderAsync("songs");

            if (songs.Count != 0 && songsFolder != null)
            {
                App.Locator.SqlService.BeginTransaction();
                UiBlockerUtility.Block("Preparing...");
                foreach (var song in songs)
                {
                    try
                    {
                        var filename = song.Name.CleanForFileName("Invalid Song Name");
                        if (song.ArtistName != song.Album.PrimaryArtist.Name)
                        {
                            filename = song.ArtistName.CleanForFileName("Invalid Artist Name") + "-" + filename;
                        }

                        var path = string.Format(
                            AppConstant.SongPath,
                            song.Album.PrimaryArtist.Name.CleanForFileName("Invalid Artist Name"),
                            song.Album.Name.CleanForFileName("Invalid Album Name"),
                            filename);

                        var file = await WinRtStorageHelper.GetFileAsync(string.Format("songs/{0}.mp3", song.Id));

                        var folder =
                            await WinRtStorageHelper.EnsureFolderExistsAsync(path, KnownFolders.MusicLibrary);

                        await file.MoveAsync(folder, filename, NameCollisionOption.ReplaceExisting);

                        song.AudioUrl = Path.Combine(folder.Path, filename);
                        await App.Locator.SqlService.UpdateItemAsync(song);
                    }
                    catch (Exception)
                    {
                    }
                }

                App.Locator.SqlService.Commit();
            }

            if (importedSongs.Count > 0)
            {
                UiBlockerUtility.Block("Almost done...");
                App.Locator.SqlService.BeginTransaction();
                foreach (var song in importedSongs)
                {
                    try
                    {
                        await App.Locator.CollectionService.DeleteSongAsync(song);
                    }
                    catch (Exception)
                    {
                    }
                }


                App.Locator.SqlService.Commit();
            }

            UiBlockerUtility.Unblock();

            if (songsFolder != null)
            {
                await songsFolder.DeleteAsync();
            }

            if (importedSongs.Count > 0)
            {
                ToastManager.Show("Few tracks do not have audiourl, make sure they exists.");
            }
        }
        private static async void SourceCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var url        = e.NewValue as string;
            var image      = d as Image;
            var imageBrush = d as ImageBrush;

            if (image != null)
            {
                image.Source = null;
            }
            else if (imageBrush != null)
            {
                imageBrush.ImageSource = null;
            }

            if (string.IsNullOrEmpty(url) || (image == null && imageBrush == null))
            {
                return;
            }

            HttpResponseMessage resp = null;
            Stream stream;

            if (url.StartsWith("http"))
            {
                // Download the image
                using (var client = new HttpClient())
                {
                    resp = await client.GetAsync(url).ConfigureAwait(false);

                    // If it fails, then abort!
                    if (!resp.IsSuccessStatusCode)
                    {
                        return;
                    }
                    stream = await resp.Content.ReadAsStreamAsync().ConfigureAwait(false);
                }
            }
            else
            {
                // Get the file
                StorageFile file;

                if (url.StartsWith("ms-appx:"))
                {
                    url = url.Replace("ms-appx://", "");
                    url = url.Replace("ms-appx:", "");
                }
                if (url.StartsWith("ms-appdata:"))
                {
                    url  = url.Replace("ms-appdata:/local/", "");
                    url  = url.Replace("ms-appdata:///local/", "");
                    file = await WinRtStorageHelper.GetFileAsync(url).ConfigureAwait(false);
                }
                else if (url.StartsWith("/"))
                {
                    file =
                        await
                        StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx://" + url))
                        .AsTask()
                        .ConfigureAwait(false);
                }
                else
                {
                    file = await StorageFile.GetFileFromPathAsync(url).AsTask().ConfigureAwait(false);
                }

                stream = await file.OpenStreamForReadAsync().ConfigureAwait(false);
            }

            using (stream)
            {
                if (stream.Length == 0)
                {
                    return;
                }

                using (var rnd = stream.AsRandomAccessStream())
                {
                    // Then we can create the Random Access Stream Image
                    using (var source = new RandomAccessStreamImageSource(rnd, ImageFormat.Undefined))
                    {
                        // Create effect collection with the source stream
                        using (var filters = new FilterEffect(source))
                        {
                            double blurPercent = 1;

                            await DispatcherHelper.RunAsync(
                                () => blurPercent = GetBlurPercent(d) *256);

                            // Initialize the filter and add the filter to the FilterEffect collection
                            filters.Filters = new IFilter[] { new BlurFilter((int)blurPercent) };

                            // Create a target where the filtered image will be rendered to
                            WriteableBitmap target = null;

                            // Now that you have the raw bytes, create a Image Decoder
                            var decoder = await BitmapDecoder.CreateAsync(rnd).AsTask().ConfigureAwait(false);

                            // Get the first frame from the decoder because we are picking an image
                            var frame = await decoder.GetFrameAsync(0).AsTask().ConfigureAwait(false);

                            // Need to switch to UI thread for this
                            await DispatcherHelper.RunAsync(
                                () =>
                            {
                                var wid = (int)frame.PixelWidth;
                                var hgt = (int)frame.PixelHeight;

                                target = new WriteableBitmap(wid, hgt);
                            }).AsTask().ConfigureAwait(false);

                            // Create a new renderer which outputs WriteableBitmaps
                            using (var renderer = new WriteableBitmapRenderer(filters, target))
                            {
                                rnd.Seek(0);
                                // Render the image with the filter(s)
                                await renderer.RenderAsync().AsTask().ConfigureAwait(false);

                                // Set the output image to Image control as a source
                                // Need to switch to UI thread for this
                                await DispatcherHelper.RunAsync(() =>
                                {
                                    if (image != null)
                                    {
                                        image.Source = target;
                                    }
                                    else if (imageBrush != null)
                                    {
                                        imageBrush.ImageSource = target;
                                    }
                                }).AsTask().ConfigureAwait(false);
                            }
                        }
                    }
                }
            }

            if (resp != null)
            {
                resp.Dispose();
            }
        }
Exemple #5
0
        private async void LoadWallpaperArt()
        {
            if (_loaded ||
                !App.Locator.AppSettingsHelper.Read("WallpaperArt", true, SettingsStrategy.Roaming))
            {
                return;
            }

            var wait    = App.Locator.AppSettingsHelper.Read <int>("WallpaperDayWait");
            var created = App.Locator.AppSettingsHelper.ReadJsonAs <DateTime>("WallpaperCreated");

            // Set the image brush
            var imageBrush = new ImageBrush {
                Opacity = .25, Stretch = Stretch.UniformToFill, AlignmentY = AlignmentY.Top
            };

            LayoutGrid.Background = imageBrush;

            if (created != DateTime.MinValue)
            {
                // Not the first time, so there must already be one created
                imageBrush.ImageSource = new BitmapImage(new Uri("ms-appdata:/local/wallpaper.jpg"));
            }

            // Once a week remake the wallpaper
            if ((DateTime.Now - created).TotalDays > wait)
            {
                var albums =
                    App.Locator.CollectionService.Albums.ToList()
                    .Where(p => p.HasArtwork)
                    .ToList();

                var albumCount = albums.Count;

                if (albumCount < 10)
                {
                    return;
                }


                var       h        = Window.Current.Bounds.Height;
                var       rows     = (int)Math.Ceiling(h / (ActualWidth / 5));
                const int collumns = 5;

                var albumSize = (int)Window.Current.Bounds.Width / collumns;

                var numImages    = rows * 5;
                var imagesNeeded = numImages - albumCount;

                var shuffle = await Task.FromResult(albums
                                                    .Shuffle()
                                                    .Take(numImages > albumCount ? albumCount : numImages)
                                                    .ToList());

                if (imagesNeeded > 0)
                {
                    var repeatList = new List <Album>();

                    while (imagesNeeded > 0)
                    {
                        var takeAmmount = imagesNeeded > albumCount ? albumCount : imagesNeeded;

                        await Task.Run(() => repeatList.AddRange(shuffle.Shuffle().Take(takeAmmount)));

                        imagesNeeded -= shuffle.Count;
                    }

                    shuffle.AddRange(repeatList);
                }

                // Initialize an empty WriteableBitmap.
                var destination = new WriteableBitmap((int)Window.Current.Bounds.Width,
                                                      (int)Window.Current.Bounds.Height);
                var col = 0;                     // Current Column Position
                var row = 0;                     // Current Row Position
                destination.Clear(Colors.Black); // Set the background color of the image to black

                // will be copied
                foreach (var artworkPath in shuffle.Select(album => string.Format(AppConstant.ArtworkPath, album.Id)))
                {
                    var file = await WinRtStorageHelper.GetFileAsync(artworkPath);

                    // Read the image file into a RandomAccessStream
                    using (var fileStream = await file.OpenReadAsync())
                    {
                        try
                        {
                            // Now that you have the raw bytes, create a Image Decoder
                            var decoder = await BitmapDecoder.CreateAsync(fileStream);

                            // Get the first frame from the decoder because we are picking an image
                            var frame = await decoder.GetFrameAsync(0);

                            // Convert the frame into pixels
                            var pixelProvider = await frame.GetPixelDataAsync();

                            // Convert pixels into byte array
                            var srcPixels = pixelProvider.DetachPixelData();
                            var wid       = (int)frame.PixelWidth;
                            var hgt       = (int)frame.PixelHeight;
                            // Create an in memory WriteableBitmap of the same size
                            var bitmap = new WriteableBitmap(wid, hgt); // Temporary bitmap into which the source

                            using (var pixelStream = bitmap.PixelBuffer.AsStream())
                            {
                                pixelStream.Seek(0, SeekOrigin.Begin);
                                // Push the pixels from the original file into the in-memory bitmap
                                await pixelStream.WriteAsync(srcPixels, 0, srcPixels.Length);

                                bitmap.Invalidate();

                                // Resize the in-memory bitmap and Blit (paste) it at the correct tile
                                // position (row, col)
                                destination.Blit(new Rect(col * albumSize, row * albumSize, albumSize, albumSize),
                                                 bitmap.Resize(albumSize, albumSize, WriteableBitmapExtensions.Interpolation.Bilinear),
                                                 new Rect(0, 0, albumSize, albumSize));
                                col++;
                                if (col < collumns)
                                {
                                    continue;
                                }

                                row++;
                                col = 0;
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }

                var wallpaper =
                    await WinRtStorageHelper.CreateFileAsync("wallpaper.jpg", ApplicationData.Current.LocalFolder);

                using (var rndWrite = await wallpaper.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await destination.ToStreamAsJpeg(rndWrite);
                }

                App.Locator.AppSettingsHelper.WriteAsJson("WallpaperCreated", DateTime.Now);
                // If there are 30 or less albums then recreate in one day, else wait a week
                App.Locator.AppSettingsHelper.Write("WallpaperDayWait", albums.Count < 30 ? 1 : 7);

                imageBrush.ImageSource = null;
                imageBrush.ImageSource = new BitmapImage(new Uri("ms-appdata:/local/wallpaper.jpg"));
            }

            _loaded = true;
        }
Exemple #6
0
        private static async void SourceCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var url        = e.NewValue as string;
            var image      = d as Image;
            var imageBrush = d as ImageBrush;

            if (image != null)
            {
                image.Source = null;
            }
            else if (imageBrush != null)
            {
                imageBrush.ImageSource = null;
            }

            if (string.IsNullOrEmpty(url) || (image == null && imageBrush == null))
            {
                return;
            }

            Stream stream;

            if (url.StartsWith("http"))
            {
                // Download the image
                using (var client = new HttpClient())
                {
                    using (var resp = await client.GetAsync(url).ConfigureAwait(false))
                    {
                        // If it fails, then abort!
                        if (!resp.IsSuccessStatusCode)
                        {
                            return;
                        }

                        var bytes = await resp.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                        stream = new MemoryStream(bytes);
                    }
                }
            }
            else
            {
                // Get the file
                StorageFile file;

                if (url.StartsWith("ms-appx:"))
                {
                    url = url.Replace("ms-appx://", "");
                    url = url.Replace("ms-appx:", "");
                }
                if (url.StartsWith("ms-appdata:"))
                {
                    url  = url.Replace("ms-appdata:/local/", "");
                    url  = url.Replace("ms-appdata:///local/", "");
                    file = await WinRtStorageHelper.GetFileAsync(url).ConfigureAwait(false);
                }
                else if (url.StartsWith("/"))
                {
                    file =
                        await
                        StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx://" + url))
                        .AsTask()
                        .ConfigureAwait(false);
                }
                else
                {
                    file = await StorageFile.GetFileFromPathAsync(url).AsTask().ConfigureAwait(false);
                }

                stream = await file.OpenStreamForReadAsync().ConfigureAwait(false);
            }

            using (stream)
            {
                if (stream.Length == 0)
                {
                    return;
                }

                var blurPercent = 13;

                await DispatcherHelper.RunAsync(
                    () => blurPercent = GetBlurPercent(d));

                // Now that you have the raw bytes, create a Image Decoder
                var decoder = await BitmapDecoder.CreateAsync(stream.AsRandomAccessStream()).AsTask().ConfigureAwait(false);

                // Get the first frame from the decoder because we are picking an image
                var frame = await decoder.GetFrameAsync(0).AsTask().ConfigureAwait(false);

                // Need to switch to UI thread for this
                await DispatcherHelper.RunAsync(
                    async() =>
                {
                    var wid = (int)frame.PixelWidth;
                    var hgt = (int)frame.PixelHeight;

                    var target      = new WriteableBitmap(wid, hgt);
                    stream.Position = 0;
                    await target.SetSourceAsync(stream.AsRandomAccessStream());

                    using (var pixelStream = target.PixelBuffer.AsStream())
                    {
                        var data = new byte[pixelStream.Length];
                        await pixelStream.ReadAsync(data, 0, data.Length);
                        pixelStream.Position = 0;

                        await Task.Factory.StartNew(
                            () =>
                        {
                            // Lets get the pixel data, by converty the binary array to int[]
                            var pixels = new int[data.Length * 4];

                            // and copy it
                            Buffer.BlockCopy(data, 0, pixels, 0, data.Length);

                            // apply the box blur
                            BoxBlur(pixels, frame.PixelWidth, frame.PixelHeight, blurPercent);

                            // now copy the int[] back to the byte[]
                            Buffer.BlockCopy(pixels, 0, data, 0, data.Length);
                        });

                        // so we can write it to the pixel buffer stream
                        await pixelStream.WriteAsync(data, 0, data.Length);

                        if (image != null)
                        {
                            image.Source = target;
                        }
                        else if (imageBrush != null)
                        {
                            imageBrush.ImageSource = target;
                        }
                    }
                }).AsTask().ConfigureAwait(false);
            }
        }