Beispiel #1
0
        // http://stackoverflow.com/questions/21169573/how-to-implement-progress-reporting-for-portable-httpclient
        // var progress = new Microsoft.Progress<double>();
        // progress.ProgressChanged += (sender, value) => System.Console.Write("\r%{0:N0}", value);
        // var cancellationToken = new CancellationTokenSource();
        // await DownloadFileAsync("http://www.dotpdn.com/files/Paint.NET.3.5.11.Install.zip", progress, cancellationToken.Token);
        public async Task DownloadFileAsync(string url, ProgressBar_Model progressBar, IFile file,CancellationToken token)
        {
            HttpClient client = new HttpClient();
            var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(string.Format("The request returned with HTTP status code {0}", response.StatusCode));
            }

            long total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L;
            bool canReportProgress = progressBar != null && total != -1;
            if (total == -1 && progressBar != null) progressBar.IsIndeterminate = true;

            using (Stream 
                stream = await response.Content.ReadAsStreamAsync(),
                writestream = await file.OpenAsync(FileAccess.ReadAndWrite))
            {
                int totalRead = 0;
                byte[] buffer = new byte[4096];
                bool isMoreToRead = true;

                do
                {
                    token.ThrowIfCancellationRequested();

                    var read = await stream.ReadAsync(buffer, 0, buffer.Length, token);

                    if (read == 0)
                    {
                        isMoreToRead = false;
                    }
                    else
                    {
                        //var data = new byte[read];
                        //buffer.ToList().CopyTo(0, data, 0, read);

                        // TODO: put here the code to write the file to disk
                        await writestream.WriteAsync(buffer, totalRead, read);

                        totalRead += read;

                        if (canReportProgress)
                        {
                            progressBar.Value = Convert.ToInt32((totalRead * 1d) / (total * 1d) * 100);
                        }

                    }
                } while (isMoreToRead);
            }
        }
Beispiel #2
0
        public void InstallLearningItem(UUID id,string path,ProgressBar_Model pb = null)
        {
            string DataFolder = FileService.GetPathToApplicationDataFolder();
            string LearningItemFolder = Path.Combine(DataFolder, id.ToString());
            FileService.CreateDirectory(LearningItemFolder);

            if (pb != null) pb.Text = Tx.T("IStore.InstallLearningItem.Extract");

            using (ZipFile zip = new ZipFile(path))
            {
                pb.Minimum = 0;pb.Maximum = 100;
                zip.ExtractProgress += (sender,e) => pb.Value = Convert.ToInt32(e.BytesTransferred == 0 ? 0 : e.BytesTransferred * 100 / e.TotalBytesToTransfer);

                foreach (ZipEntry zipelm in zip.Entries)
                {
                    string localpath = Path.Combine(DataFolder,zipelm.FileName);
                    if (zipelm.IsDirectory)
                    {
                        Directory.CreateDirectory(localpath);
                        continue;
                    }
                    if (FileService.FileExists(localpath))
                    {
                        FileInfo fi = new FileInfo(localpath);
                        if (fi.Length == zipelm.UncompressedSize && fi.CreationTimeUtc == zipelm.CreationTime)
                        {
                            continue;
                        }
                    }
                    zipelm.Extract(DataFolder, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            if (pb != null) pb.Text = Tx.T("IStore.InstallLearningItem.Install");
            string tmpDataFile = Path.Combine(LearningItemFolder, Constants.Store.LearningItemFileName);
            DBBulkOperations.ImportLearningItem(tmpDataFile,false);
            FileService.DeleteFile(tmpDataFile);

        }
Beispiel #3
0
        public void PublishLearningItem(LearningItem LearningItem,bool UploadVideo)
        {
            APIResult res;

            pb = new ProgressBar_Model {};
            pb.Title = string.Format(Tx.T("Publish.Messages.Publishing"), LearningItem.Name);
            App.AddLongTaskProgressBar(pb);

            try
            {
                // Testing rights
                InteractiveAuthenticationAsUser();

                if (!HasRight(UserRights.Collection.Publish))
                {
                    string msg = Tx.T("Publish.Messages.NoRightForPublish");
                    throw new Exception(msg);
                }

                // Create a dat file
                string DatFile = CreateDatFile(LearningItem);

                // Create an archive
                string ArchiveFile;
                try
                {
                    ArchiveFile = CreateArchive(LearningItem);
                }
                finally
                {
                    File.Delete(DatFile);
                }

                // Create a Store item
                StoreItem si = new StoreItem
                {
                    id = LearningItem.id.guid,
                    Name = LearningItem.Name,
                    Description = LearningItem.Description,
                    YoutubeURL = LearningItem.YoutubeURL,
                    CoverFile = LearningItem.CoverFile,
                    VideoFileName = FileService.GetFileNameWithoutPath(LearningItem.VideoFileName),
                    VideoFileSize = FileService.GetFileSize(LearningItem.VideoFileName),
                    Version = LearningItem.Version
                };
                StoreItem r = WebAPI_LearningItems.GetById(si.id).Result;
                if (r != null)
                {
                    // update
                    res = WebAPI_LearningItems.Update(si).Result;
                }
                else
                {
                    // create
                    res = WebAPI_LearningItems.Create(si).Result;
                }

                if (!res.Result)
                {
                    FileService.DeleteFile(ArchiveFile);
                    throw new Exception(res.Message).Init(Tx.T("Publish.Messages.CantCreateStoreItem"), res.FullMessage);
                }

                // Upload an archive
                try
                {
                    AttachFile(LearningItem, ArchiveFile);
                }
                finally
                {
                    FileService.DeleteFile(ArchiveFile);
                }

                // Upload a cover
                string pathtocover = Path.Combine(FileService.GetPathToLearningItem(LearningItem),LearningItem.CoverFile);
                if (FileService.FileExists(pathtocover))
                {
                    AttachFile(LearningItem, pathtocover);
                }



                // Upload a video
                if (UploadVideo)
                {
                    if (!string.IsNullOrEmpty(LearningItem.VideoFileName))
                    {
                        AttachFile(LearningItem, LearningItem.VideoFileName);
                    }
                }

                LearningItem.Version++;
                EFDbContext.SaveChgs();
            }
            finally
            {
                App.RemoveLongTaskProgressBar(pb);
            }

        }
        public static void Download(ObservableCollection<VideoInfo> VideoInfos,VideoInfo videoinfo,string path,ProgressBar_Model pb)
        {
            if(pb != null)
            {
                pb.IsIndeterminate = false;
                pb.Text = Tx.T("IStore.YoutubeDownloader.DownloadVideo")+" "+videoinfo.Title;
                pb.Minimum = 0;
                pb.Maximum = 100;
            }

            Info inf = GetInfo(videoinfo);
          
            if (videoinfo.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(videoinfo);
            }
            string pathtovideo = Path.Combine(path,inf.VideoFileName);
            if (!File.Exists(pathtovideo))
            {
                var videoDownloader = new VideoDownloader(videoinfo, Path.Combine(path, inf.VideoFileName));
                videoDownloader.DownloadProgressChanged += (sender, args) =>
                    {
                        if(pb != null) pb.Value = Convert.ToInt32(args.ProgressPercentage);
                        //if(args.ProgressPercentage == 100) ViewModelLocator.RemoveLongTaskProgressBar(pb);
                    };
                videoDownloader.Execute();
            }


            /*
             * Execute the video downloader.
             * For GUI applications note, that this method runs synchronously.
             */

            // Audio
            if(videoinfo.AudioBitrate == 0)
            {
                VideoInfo vi = VideoInfos.OrderBy(x => x.Resolution).ThenByDescending(x=>x.AudioBitrate).FirstOrDefault();

                if(vi != null)
                {
                    if(pb != null)
                    {
                        pb.Text = Tx.T("IStore.YoutubeDownloader.DownloadSoundTrack")+" "+videoinfo.Title;
                        pb.Minimum = 0;
                        pb.Maximum = 100;
                    }

                    if (vi.RequiresDecryption)
                    {
                        DownloadUrlResolver.DecryptDownloadUrl(vi);
                    }
                    
                    string pathtoaudio = Path.Combine(path, inf.AudioFileName);
                    if (!File.Exists(pathtoaudio))
                    {
                        var audioDownloader = new VideoDownloader(vi,pathtoaudio);

                        if(pb != null)
                        {
                            audioDownloader.DownloadProgressChanged += (sender, args) => {
                                pb.Value = Convert.ToInt32(args.ProgressPercentage);
                                };
                        }
                        audioDownloader.Execute();
                    }

                }

            }

        }
Beispiel #5
0
        public void DownloadStoreItem(StoreItemExt StoreItem)
        {

            pb = new ProgressBar_Model {};
            pb.Title = string.Format(Tx.T("IStore.DownloadStoreItem.Messages.Download"), StoreItem.Name);
            App.AddLongTaskProgressBar(pb);

            try
            {
                // download dat file
                string tempDatFile = Path.Combine(FileService.GetPathToTempFolder(), "LearningItem."+ StoreItem.id.ToString()+".dat");
                string DatFileUrl = WebAPI_LearningItems.GetPathToDatFile(StoreItem.id);
                DownloadFile(DatFileUrl, tempDatFile);

                UUID li_id = new UUID(StoreItem.id);
                // install dat file
                try
                {
                    InstallLearningItem(li_id,tempDatFile,pb);
                }
                finally
                {
                    FileService.DeleteFile(tempDatFile);
                }

                LearningItem li = EFDbContext.Context.Find<LearningItem>(li_id);
                if (AppSetting.LearningItems.Any(x=>x.id == li_id))
                {
                    li.RefreshFromDB();
                }
                else
                {
                    AppSetting.LearningItems.Add(li);
                }
                li.AppSetting = AppSetting;

                // download video file
                YoutubeDownloader.Info vinf =  DownloadVideo(StoreItem);

                li.VideoFileName = vinf.VideoFileName;
                foreach(AudioTrack at in li.AudioTracks)
                {
                    if (vinf.isExternalAudio)
                    {
                        at.ExternalFile = vinf.AudioFileName;
                        at.isExternal = vinf.isExternalAudio;
                    }
                }

                if (!AppSetting.LearningItems.Contains(li)) AppSetting.LearningItems.Add(li);
                EFDbContext.SaveChgs();

                StoreItem.LearningItem = li;
                StoreItem.UpdateDownloadButtonStatus();
            }
            finally
            {
                App.RemoveLongTaskProgressBar(pb);
            }
         
        }