Example #1
0
        private static FileSample GetSampleBase(IStorageFile file)
        {
            // TODO: We could move this to the environment service to actually attempt to load the file
            string ext = Path.GetExtension(file.Name);

            if (String.IsNullOrWhiteSpace(ext))
            {
                return(null);
            }

            FileSample baseSample = null;

            if (AudioExtensions.Contains(ext))
            {
                baseSample = new AudioSample();
            }

            if (baseSample != null)
            {
                baseSample = baseSample with
                {
                    SourceUrl = file.Path,
                    Name      = Path.GetFileNameWithoutExtension(file.Name)
                };
            }

            return(baseSample);
        }
    }
Example #2
0
        public async Task <FileSample> ScanSampleAsync(FileSample sample, IProgress <double> progress = null)
        {
            if (sample is null)
            {
                throw new ArgumentNullException(nameof(sample));
            }
            if (!(sample is AudioSample audio))
            {
                throw new ArgumentException("Must be an audio sample");
            }

            try {
                StorageFile file;
                try {
                    file = await StorageFile.GetFileFromPathAsync(sample.SourceUrl).ConfigureAwait(false);
                } catch (AccessViolationException) {
                    if (sample.Token != null)
                    {
                        file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(sample.Token).ConfigureAwait(false);
                    }
                    else
                    {
                        throw;
                    }
                }

                CreateAudioFileInputNodeResult result = await this.graph.CreateFileInputNodeAsync(file);

                if (result.Status != AudioFileNodeCreationStatus.Success)
                {
                    Trace.TraceWarning($"Failed to scan file sample: {result.Status}");
                    return(null);
                }

                using (var node = result.FileInputNode) {
                    progress?.Report(.5);

                    var hashTask = GetContentHashAsync(await file.OpenStreamForReadAsync());

                    audio = audio with {
                        Duration    = node.Duration,
                        Channels    = (AudioChannels)node.EncodingProperties.ChannelCount,
                        Frequency   = node.EncodingProperties.SampleRate,
                        ContentHash = await hashTask
                    };
                }

                return(audio);
            } catch (Exception ex) {
                Trace.TraceWarning("Failed to scan file sample: " + ex);
                return(null);
            } finally {
                progress?.Report(1);
            }
        }
Example #3
0
        private async Task <string> SampleToHashTask(Task <FileSample> importTask)
        {
            FileSample sample = null;

            try {
                sample = await importTask;
            } catch {
            }

            return(sample?.ContentHash);
        }
Example #4
0
        public static async Task ImportAsync(IReadOnlyList <IStorageItem> items, IProgress <double> progress = null)
        {
            items = GetImportableItems(items);

            AggregateProgress total = (progress != null) ? new AggregateProgress(progress) : null;

            ISyncService sync = await App.Services.GetServiceAsync <ISyncService> ().ConfigureAwait(false);

            DownloadManager downloads = await App.Services.GetServiceAsync <DownloadManager> ().ConfigureAwait(false);

            List <Task> importTasks = new List <Task> ();

            foreach (IStorageItem item in items)
            {
                var node = total?.CreateProgressNode();
                if (item is IStorageFolder folder)
                {
                    var children = await folder.GetItemsAsync();

                    importTasks.Add(ImportAsync(children, node));
                }
                else if (item is IStorageFile file)
                {
                    Task <FileSample> import   = null;
                    ManagedDownload   download = null;

                    Func <CancellationToken, IProgress <double>, Task <FileSample> > importGetter = async(cancel, progress) => {
                        import = ImportAsync(file, sync, progress, cancel);
                        FileSample sample = null;
                        try {
                            sample = await import;
                            if (download != null)
                            {
                                download.State = DownloadState.Completed;
                            }
                        } catch {
                            if (download != null)
                            {
                                download.State = DownloadState.LocalError;
                            }
                        }

                        return(sample);
                    };
                    download = downloads.QueueImport(file.Name, importGetter);
                    importTasks.Add(import);
                }
            }

            total?.FinishDiscovery();
            await Task.WhenAll(importTasks);
        }
Example #5
0
        public bool CanAcquire(FileSample sample)
        {
            if (sample == null)
            {
                return(false);
            }
            if (!Uri.TryCreate(sample.SourceUrl, UriKind.Absolute, out Uri uri))
            {
                return(false);
            }

            return(uri.Host == "freesound.org");
        }
Example #6
0
        public async Task <IReadOnlyList <FileSample> > EnsureElementPresentAsync(EnvironmentElement element, IProgress <double> progress = null, CancellationToken cancellationToken = default)
        {
            if (element is null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            await this.loadedServices.ConfigureAwait(false);

            List <Task>       tasks   = new List <Task> ();
            List <FileSample> samples = new List <FileSample> ();

            AggregateProgress totalProgress = (progress != null) ? new AggregateProgress(progress) : null;

            if (element.Audio != null)
            {
                foreach (string sampleId in element.Audio.Playlist.Descriptors)
                {
                    FileSample sample = (await this.sync.GetElementByIdAsync(sampleId).ConfigureAwait(false) as FileSample);
                    if (sample == null)
                    {
                        continue;
                    }

                    IProgress <double> nodeProgress = totalProgress?.CreateProgressNode();

                    samples.Add(sample);
                    tasks.Add(this.downloadManager.EnsurePresentAsync(sample, nodeProgress, cancellationToken));
                }
            }

            totalProgress?.FinishDiscovery();

            int offset = 0;

            for (int i = 0; i < tasks.Count; i++)
            {
                try {
                    await tasks[i].ConfigureAwait(false);
                } catch {
                    samples.RemoveAt(i - offset++);
                }
            }

            return(samples);
        }
Example #7
0
        static void Main(string[] args)
        {
            //Console.WriteLine("本日!");
            //SchoolGetter c1 = new SchoolGetter();
            //c1.GetHTML();


            //CollectionSample cs = new CollectionSample();

            //DateSample ds = new DateSample();

            /*String dbHost = ConfigurationManager.AppSettings["dbHost"];
             * DataBase db = new DataBase(
             *  ConfigurationManager.AppSettings["dbHost"],
             *  ConfigurationManager.AppSettings["dbName"],
             *  ConfigurationManager.AppSettings["dbUser"],
             *  ConfigurationManager.AppSettings["dbPass"]
             * );*/

            FileSample fs = new FileSample();
        }
Example #8
0
        public async Task EnsurePresentAsync(FileSample sample, IProgress <double> progress = null, CancellationToken cancellationToken = default)
        {
            if (sample is null)
            {
                throw new ArgumentNullException(nameof(sample));
            }

            if (await this.storage.GetIsPresentAsync(sample.Id, sample.ContentHash))
            {
                progress?.Report(1);
                return;
            }

            if (!this.settings.DownloadInBackground)
            {
                Task <bool> downloadQuestionTask;
                if (this.downloadInBackground != null)
                {
                    downloadQuestionTask = this.downloadInBackground;
                }
                else
                {
                    lock (this.settings) {
                        if (this.downloadInBackground == null)
                        {
                            // TODO: Localize
                            var prompt = new PromptMessage("Download missing files", "Some of the files for these elements are missing. Would you like to download them now?", "Download");
                            Messenger.Default.Send(prompt);
                            this.downloadInBackground = prompt.Result;
                            downloadQuestionTask      = this.downloadInBackground;
                        }
                        else
                        {
                            downloadQuestionTask = this.downloadInBackground;
                        }
                    }
                }

                if (!await downloadQuestionTask)
                {
                    progress?.Report(1);
                    return;
                }
            }

            IContentProviderService[] providers = await this.services.GetServicesAsync <IContentProviderService> ().ConfigureAwait(false);

            IContentProviderService handler = providers.FirstOrDefault(c => c.CanAcquire(sample));

            ManagedDownload download = null;

            if (handler != null)
            {
                string id = handler.GetEntryIdFromUrl(sample.SourceUrl);
                if (id != null)
                {
                    ContentEntry entry = await handler.GetEntryAsync(id, cancellationToken);

                    download = QueueDownload(sample.Id, sample.Name, handler.DownloadEntryAsync(id), entry.Size, sample.ContentHash, progress, cancellationToken);
                }
            }

            if (download == null)
            {
                if (!Uri.TryCreate(sample.SourceUrl, UriKind.Absolute, out Uri uri))
                {
                    progress?.Report(1);
                    throw new ArgumentException();
                }

                if (uri.IsFile)
                {
                    if (await this.storage.GetIsPresentAsync(uri))
                    {
                        progress?.Report(1);
                        return;
                    }
                    else
                    {
                        progress?.Report(1);
                        throw new FileNotFoundException();
                    }
                }

                download = QueueDownload(sample.Id, sample.Name, new Uri(sample.SourceUrl), sample.ContentHash, progress, cancellationToken);
            }

            await download.Task;
        }
Example #9
0
        public static async Task <ISampledService> GetServiceAsync(this IAsyncServiceProvider self, FileSample sample)
        {
            if (self is null)
            {
                throw new ArgumentNullException(nameof(self));
            }
            if (sample is null)
            {
                throw new ArgumentNullException(nameof(sample));
            }

            if (!ServiceMapping.TryGetValue(sample.GetType(), out Type serviceType))
            {
                return(null);
            }

            PlaySpaceManager playSpace = await self.GetServiceAsync <PlaySpaceManager> ().ConfigureAwait(false);

            await playSpace.Loading.ConfigureAwait(false);

            IEnumerable <IEnvironmentService> services = await self.GetServicesAsync <IEnvironmentService> ().ConfigureAwait(false);

            services = services.Where(s => serviceType.IsAssignableFrom(s.GetType()));

            PlaySpaceElement space = playSpace.SelectedElement;

            if (space != null)
            {
                services = services.Where(s => space.Services.Contains(s.GetType().GetSimpleTypeName()));
            }

            return((ISampledService)services.FirstOrDefault());
        }
 public PingService()
 {
     rnd = new Random();
     ClientHostDetails     = new ObservableCollection <HostInfo>();
     AvailableFileMetaData = new FileSample().GetFileMetaData().Take(rnd.Next(1, _count)).ToList();
 }
Example #11
0
        public static async Task <FileSample> ImportAsync(IStorageFile file, ISyncService sync, IProgress <double> progress = null, CancellationToken cancelToken = default)
        {
            FileSample sample = GetSampleBase(file);

            if (sample == null)
            {
                Trace.TraceWarning("Could not import file " + file.Path);
                progress?.Report(1);
                return(null);
            }

            var total         = (progress != null) ? new AggregateProgress(progress) : null;
            var localProgress = total?.CreateProgressNode();
            var scanProgress  = total?.CreateProgressNode();

            total?.FinishDiscovery();

            try {
                ISampledService service = await App.Services.GetServiceAsync(sample).ConfigureAwait(false);

                string token = StorageApplicationPermissions.FutureAccessList.Add(file);
                sample = sample with {
                    Token = token
                };
                sample = await service.ScanSampleAsync(sample, scanProgress).ConfigureAwait(false);

                localProgress?.Report(.5);

                var existing = (await sync.FindElementsAsync <FileSample> (fs => fs.ContentHash == sample.ContentHash || fs.SourceUrl == sample.SourceUrl).ConfigureAwait(false)).FirstOrDefault();
                if (existing != null)
                {
                    if (existing.ContentHash != sample.ContentHash)
                    {
                        // We'll use the newly scanned sample and update the record, the file changed since the hash does not match
                        StorageApplicationPermissions.FutureAccessList.Remove(existing.Token);
                        sample = sample with
                        {
                            Id      = existing.Id,
                            Tags    = existing.Tags,
                            Events  = existing.Events,
                            Version = existing.Version
                        };
                    }
                    else
                    {
                        return(existing);
                    }
                }

                localProgress?.Report(.75);

                cancelToken.ThrowIfCancellationRequested();
                if (sample != null)
                {
                    sample = await sync.SaveElementAsync(sample).ConfigureAwait(false);
                }

                return(sample);
            } finally {
                localProgress?.Report(1);
                scanProgress?.Report(1);
            }
        }