Esempio n. 1
0
        /// <summary>
        /// Event Handler for the Save Button
        /// </summary>
        private async void Save_Click(object sender, RoutedEventArgs e)
        {
            var image = ImagesList.SelectedItem as ImageResult;

            if (image == null)
            {
                return;
            }

            var uri       = new Uri(image.MediaUrl);
            var filename  = uri.Segments[uri.Segments.Length - 1];
            var extension = System.IO.Path.GetExtension(filename);

            var picker = new FileSavePicker();

            picker.SuggestedFileName      = filename;
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeChoices.Add(extension.Trim('.').ToUpper(), new string[] { extension });

            var saveFile = await picker.PickSaveFileAsync();

            if (saveFile != null)
            {
                Status.Text = "Download Started";
                var download = new BackgroundDownloader().CreateDownload(uri, saveFile);
                await download.StartAsync();

                Status.Text = "Download Complete";
            }
        }
Esempio n. 2
0
        internal static async Task DownloadFile(string url, string name, StorageFolder folder)
        {
            try
            {
                if (folder == null)
                {
                    var picker = new FolderPicker
                    {
                        ViewMode = PickerViewMode.Thumbnail,
                        SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                        FileTypeFilter         = { "*" }
                    };
                    folder = await picker.PickSingleFolderAsync();
                }
                CancellationToken token;
                if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out Uri source))
                {
                    throw new Exception("Invalid URI");
                }
                var destinationFile = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);

                var download = new BackgroundDownloader().CreateDownload(source, destinationFile);
                download.Priority = BackgroundTransferPriority.High;
                await download.StartAsync().AsTask(token);
            }
            catch (Exception e) { throw e; }
        }
Esempio n. 3
0
        public static async Task preloadMp3SingleAsync(string mp3RemoteUrl)
        {
            var    url      = new Uri(mp3RemoteUrl);
            string filename = System.IO.Path.GetFileName(url.LocalPath);

            if (await isFilePresent(filename))
            {
                // do nothing
            }
            else
            {
                var destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                var download = new BackgroundDownloader().CreateDownload(url, destinationFile);
                await download.StartAsync().AsTask();
            }
        }
Esempio n. 4
0
        public async Task DownloadFile(string url, string name)
        {
            try
            {
                CancellationToken token;
                Uri           source;
                StorageFolder folder = KnownFolders.VideosLibrary;
                if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out source))
                {
                    throw new Exception("Invalid URI");
                }
                StorageFile destinationFile;
                destinationFile = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);

                var download = new BackgroundDownloader().CreateDownload(source, destinationFile);
                download.Priority = BackgroundTransferPriority.High;
                await download.StartAsync().AsTask(token);
            }
            catch (Exception e) { throw e; }
        }
Esempio n. 5
0
        private static async Task <bool> Download(string url, string fileName,
                                                  StorageFolder destinationFolder, CancellationToken token)
        {
            if (string.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out Uri source))
            {
                throw new Exception("Invalid URI");
            }
            try
            {
                StorageFile destinationFile = await(destinationFolder ?? KnownFolders.VideosLibrary)
                                              .CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
                var downloader = new BackgroundDownloader().CreateDownload(source, destinationFile);
                downloader.Priority = BackgroundTransferPriority.Default;
                await downloader.StartAsync().AsTask(token);

                return(true);
            }
            catch (TaskCanceledException e) { throw e; }
            catch { return(false); }
        }
Esempio n. 6
0
        private async Task <bool> GetMediaDataAsync(string path)
        {
            //if (this._groups.Count != 0)
            //    return false;
            string jsonText = string.Empty;

            if (string.IsNullOrEmpty(path))
            {
                // load the default data
                //If retrieving json from web failed then use embedded json data file.
                if (string.IsNullOrEmpty(jsonText))
                {
                    Uri dataUri = new Uri("ms-appx:///DataModel/MediaData.json");

                    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);

                    jsonText = await FileIO.ReadTextAsync(file);

                    MediaDataPath = "ms-appx:///DataModel/MediaData.json";
                }
            }
            else
            {
                if (path.StartsWith("ms-appx://"))
                {
                    Uri dataUri = new Uri(path);

                    StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);

                    jsonText = await FileIO.ReadTextAsync(file);

                    MediaDataPath = path;
                }
                else if (path.StartsWith("https://"))
                {
                    try
                    {
                        using (var client = new HttpClient())
                        {
                            var response = await client.GetAsync(path);

                            response.EnsureSuccessStatusCode();
                            jsonText = await response.Content.ReadAsStringAsync();

                            MediaDataPath = path;
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
                    }
                }
                else if (path.StartsWith("http://"))
                {
                    try
                    {
                        //Download the json file from the server to configure what content will be dislayed.
                        //You can also modify the local MediaData.json file and delete this code block to test
                        //the local json file

                        Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                        filter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
                        Windows.Web.Http.HttpClient http = new Windows.Web.Http.HttpClient(filter);
                        Uri httpUri = new Uri(path);
                        jsonText = await http.GetStringAsync(httpUri);

                        MediaDataPath = path;
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
                    }
                }
                else
                {
                    try
                    {
                        //Download the json file from the server to configure what content will be dislayed.
                        //You can also modify the local MediaData.json file and delete this code block to test
                        //the local json file
                        string      MediaDataFile = path;
                        StorageFile file;
                        file = await Windows.Storage.StorageFile.GetFileFromPathAsync(path);

                        if (file != null)
                        {
                            jsonText = await FileIO.ReadTextAsync(file);

                            MediaDataPath = MediaDataFile;
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
                    }
                }
            }

            if (string.IsNullOrEmpty(jsonText))
            {
                return(false);
            }

            try
            {
                JsonObject jsonObject = JsonObject.Parse(jsonText);
                JsonArray  jsonArray  = jsonObject["Groups"].GetArray();

                foreach (JsonValue groupValue in jsonArray)
                {
                    JsonObject     groupObject = groupValue.GetObject();
                    MediaDataGroup group       = new MediaDataGroup(groupObject["UniqueId"].GetString(),
                                                                    groupObject["Title"].GetString(),
                                                                    groupObject["Category"].GetString(),
                                                                    groupObject["ImagePath"].GetString(),
                                                                    groupObject["Description"].GetString());

                    foreach (JsonValue itemValue in groupObject["Items"].GetArray())
                    {
                        JsonObject itemObject = itemValue.GetObject();
                        long       timeValue  = 0;
                        if (!itemObject.ContainsKey("Title"))
                        {
                            var id        = itemObject["UniqueId"].GetString().GetHashCode().ToString();
                            var videoPath = _localVideoReady.ContainsKey(id) ? ApplicationData.Current.LocalFolder.Path + "/" + _localVideoReady[id] : itemObject["Content"].GetString();
                            group.Items.Add(new MediaItem(id, "", "", "ms-appx:///Assets/SMOOTH.png",
                                                          "", videoPath, "", 0, 0, "", "", "", false));
                        }
                        else
                        {
                            var id        = itemObject["UniqueId"].GetString().GetHashCode().ToString();
                            var videoPath = _localVideoReady.ContainsKey(id) ? ApplicationData.Current.LocalFolder.Path + "/" + _localVideoReady[id] : itemObject["Content"].GetString();
                            group.Items.Add(new MediaItem(id,
                                                          itemObject["Comment"].GetString(),
                                                          itemObject["Title"].GetString(),
                                                          itemObject["ImagePath"].GetString(),
                                                          itemObject["Description"].GetString(),
                                                          videoPath,
                                                          itemObject["PosterContent"].GetString(),
                                                          (long.TryParse(itemObject["Start"].GetString(), out timeValue) ? timeValue : 0),
                                                          (long.TryParse(itemObject["Duration"].GetString(), out timeValue) ? timeValue : 0),
                                                          (itemObject.ContainsKey("HttpHeaders") ? itemObject["HttpHeaders"].GetString() : ""),
                                                          itemObject["PlayReadyUrl"].GetString(),
                                                          itemObject["PlayReadyCustomData"].GetString(),
                                                          itemObject["BackgroundAudio"].GetBoolean()));
                        }
                    }
                    if (Groups.Any(g => g.UniqueId == group.UniqueId))
                    {
                        var currentGroup = Groups.First(g => g.UniqueId == group.UniqueId);
                        currentGroup.Items.Where(item => group.Items.All(i => i.UniqueId != item.UniqueId) || item.Content.Contains("http")).ToList()
                        .ForEach(item => currentGroup.Items.Remove(item));
                        foreach (var item in group.Items)
                        {
                            if (currentGroup.Items.All(i => i.UniqueId != item.UniqueId))
                            {
                                currentGroup.Items.Add(item);
                            }
                        }
                    }
                    else
                    {
                        Groups.Add(group);
                    }

                    foreach (var item in group.Items)
                    {
                        if (!_localVideoReady.ContainsKey(item.UniqueId) &&
                            !_toDownload.Exists(x => x.Id == item.UniqueId))
                        {
                            _toDownload.Add(new Video {
                                Id = item.UniqueId, Url = item.Content
                            });
                        }
                    }
                    var itemReady = new List <Video>();
                    foreach (var item in _toDownload)
                    {
                        try
                        {
                            var fileName = string.Format(@"{0}.mp4", Guid.NewGuid());
                            // create the blank file in specified folder
                            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                            // create the downloader instance and prepare for downloading the file
                            var downloadOperation = new BackgroundDownloader().CreateDownload(new Uri(item.Url), file);
                            // start the download operation asynchronously
                            await downloadOperation.StartAsync();

                            _localVideoReady[item.Id] = fileName;
                            itemReady.Add(item);
                            await SaveVideos();
                        }
                        catch (Exception e)
                        {
                            System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while Downloading: " + item.Url + " Exception: " + e.Message);
                        }
                    }
                    itemReady.ForEach(x => _toDownload.Remove(x));
                    return(true);
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Exception while opening the playlist: " + path + " Exception: " + e.Message);
            }
            return(false);
        }