コード例 #1
0
 private PendingDownload chooseDownloadMethod(QueuedDownload queuedDownload)
 {
     if (queuedDownload.ForceActiveDownload || queuedDownload.DownloadSize >= 20000000L && queuedDownload.DownloadSize != long.MaxValue)
     {
         HttpWebRequest request = WebRequest.CreateHttp(ApplicationSettings.ServerUrl.DownloadPath(queuedDownload));
         request.SetCredentials(LoggedUser);
         request.Headers["Range"]         = "bytes=" + queuedDownload.DownloadedBytes.ToString() + "-";
         request.AllowReadStreamBuffering = false;
         return(new PendingActiveDownload(request,
                                          Observable.FromAsyncPattern <WebResponse>(request.BeginGetResponse, request.SaneEndGetResponse)()
                                          .Select(response => (RunningDownload) new ActiveDownload(response, queuedDownload))));
     }
     else
     {
         //first check if there is not tranfer request already added to service
         foreach (BackgroundTransferRequest request in BackgroundTransferService.Requests)
         {
             if (request.RequestUri.Equals(ApplicationSettings.ServerUrl.DownloadPath(queuedDownload)))
             {
                 return(new PendingBackgroundDownload(request, Observable.Return(new BackgroundDownload(request, queuedDownload) as RunningDownload)));
             }
             request.Dispose();
         }
         BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(ApplicationSettings.ServerUrl.DownloadPath(queuedDownload));
         return(new PendingBackgroundDownload(transferRequest, Observable.Return(new BackgroundDownload(transferRequest, queuedDownload) as RunningDownload)));
     }
 }
コード例 #2
0
 public void StartDownload(QueuedDownload download, bool resume = false, bool forceNow = false)
 {
     if (queuedDownloads.Contains(download) || startedDownloads.Keys.Contains(download))
     {
         return;
     }
     if (resume)
     {
         queuedDownloads.Insert(0, download);
     }
     else if (!forceNow)
     {
         queuedDownloads.Add(download);
         _downloadEnqueuedEvent.OnNext(download);
     }
     if (forceNow)
     {
         QueuedDownload nextDownload = null;
         if (startedDownloads.Count >= KMaxSimultaneousDownloads)
         {
             nextDownload = startedDownloads.Keys.First();
         }
         IDownloadCancelHandle cancelHandle = StartEnqueuedDownload(download);
         startedDownloads.Add(download, cancelHandle);
         if (nextDownload != null)
         {
             StopDownload(nextDownload, true);
         }
     }
     else
     {
         StartEnqueuedItemsIfPossible();
     }
 }
コード例 #3
0
 private void StartEnqueuedItemsIfPossible()
 {
     while (startedDownloads.Count < KMaxSimultaneousDownloads && queuedDownloads.Count > 0)
     {
         QueuedDownload        download     = queuedDownloads.PopFirst();
         IDownloadCancelHandle cancelHandle = StartEnqueuedDownload(download);
         startedDownloads.Add(download, cancelHandle);
     }
 }
コード例 #4
0
        private MediaItemsListModelItem DownloadToMediaItem(QueuedDownload download)
        {
            if (ActiveLibrary == null)
            {
                return(null);
            }

            return(MediaItems.FirstOrDefault(item => item.Id == download.Id));
        }
コード例 #5
0
        public static string BackgroundFilePath(User user, QueuedDownload queuedDownload)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!isoStore.DirectoryExists("/shared/transfers"))
                {
                    isoStore.CreateDirectory("/shared/transfers");
                }
            }
            string basicPath = MediaFilePath(user, queuedDownload);

            return(Path.Combine("/shared/transfers/", basicPath));
        }
コード例 #6
0
 public void CancelDownload(QueuedDownload download)
 {
     DownloadManager.StopDownload(download).Subscribe(
         dl =>
     {
         using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
         {
             string path = Utils.MediaFilePath(LoggedUser, dl);
             if (isf.FileExists(path))
             {
                 isf.DeleteFile(path);
             }
         }
     });
     LoggedUser.Downloads.Remove(download);
     App.Engine.StatisticsManager.LogDownloadRemove(download);
 }
コード例 #7
0
 private bool IsFileDownloadSuccessfulOrResumed(RunWorkerCompletedEventArgs e, QueuedDownload queuedDownload)
 {
     if (!e.Cancelled && e.Error == null)
     {
         QueuedDownload result = (QueuedDownload)e.Result;
         if (result.DownloadedBytes == result.DownloadSize)
         {
             _downloadCompletedEvent.OnNext(queuedDownload);
             App.Engine.StatisticsManager.LogDownloadCompleted(queuedDownload, "Completed");
         }
         else
         {
             StartDownload(result, true);
         }
         return(true);
     }
     return(false);
 }
コード例 #8
0
        public AddingToQueueResult EnqueueMediaItem(MediaItemsListModelItem mediaItem, bool immediate, bool forceNow = false)
        {
            if (LoggedUser.Downloads.Count(queuedDownload => queuedDownload.Id == mediaItem.Id) == 0)
            {
                QueuedDownload.DownloadState initialState =
                    App.Engine.LoggedUser.Settings.AutomaticDownloads ?
                    QueuedDownload.DownloadState.Queued :
                    (immediate ? QueuedDownload.DownloadState.Queued : QueuedDownload.DownloadState.Paused);

                QueuedDownload queuedDownload = new QueuedDownload(mediaItem)
                {
                    State = initialState
                };

                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (isf.FileExists(Utils.MediaFilePath(LoggedUser, queuedDownload)))
                    {
                        return(AddingToQueueResult.ItemAlreadyDownloaded);
                    }
                }

                StatisticsManager.LogDownloadAdd(queuedDownload);
                LoggedUser.Downloads.Add(queuedDownload);
                _downloadEnqueuedEvent.OnNext(queuedDownload);

                if (initialState != QueuedDownload.DownloadState.Stopped)
                {
                    DownloadManager.StartDownload(queuedDownload, false, forceNow);
                }
                return(AddingToQueueResult.ItemAddedToQueue);
            }
            else if (immediate)
            {
                QueuedDownload queuedDownload = (from download in LoggedUser.Downloads where download.Id == mediaItem.Id select download).First();
                queuedDownload.State = QueuedDownload.DownloadState.Queued;
                DownloadManager.StartDownload(queuedDownload);
                return(AddingToQueueResult.DownloadItemStarted);
            }
            else
            {
                return(AddingToQueueResult.ItemAlreadyDownloaded);
            }
        }
コード例 #9
0
        public IObservable <QueuedDownload> StopDownload(QueuedDownload download, bool queueAgain = false)
        {
            _downloadStopPendingEvent.OnNext(download);

            if (!queuedDownloads.Contains(download) && !startedDownloads.Keys.Contains(download))
            {
                return(Observable.Return <QueuedDownload>(download));
            }

            IObservable <QueuedDownload> result = DownloadDoneEvent.Where(dl => dl == download).Take(1);

            if (queuedDownloads.Remove(download))
            {
                _downloadStoppedEvent.OnNext(download);
            }
            else
            {
                // item was not waiting in queue, so it's already downloading
                startedDownloads[download].Cancel();
                result.Subscribe(dl =>
                {
                    startedDownloads.Remove(dl);
                    if (!queueAgain)
                    {
                        StartEnqueuedItemsIfPossible();
                    }
                    else
                    {
                        queuedDownloads.Insert(0, dl);
                        dl.State = QueuedDownload.DownloadState.Queued;
                        _downloadEnqueuedEvent.OnNext(dl);
                    }
                });
            }

            return(result);
        }
コード例 #10
0
        private IDownloadCancelHandle StartEnqueuedDownload(QueuedDownload download)
        {
            _downloadStartedEvent.OnNext(download);
            App.Engine.StatisticsManager.LogDownloadStart(download);

            Transport.PendingDownload pendingDownload = Transport.StartQueuedDownload(download);

            pendingDownload.Response
            .ObserveOnDispatcher()
            .Subscribe <Transport.RunningDownload>(
                activeDownload =>
            {
                if (activeDownload.Download.DownloadSize == long.MaxValue || activeDownload.Download.DownloadSize == 0)
                {
                    activeDownload.Download.DownloadSize = activeDownload.ContentLength;
                }
                BackgroundWorker worker = new BackgroundWorker()
                {
                    WorkerReportsProgress = true, WorkerSupportsCancellation = true
                };

                // change cancel handle
                startedDownloads[activeDownload.Download] = new ActiveDownloadCancelHandle(worker);

                worker.DoWork += (sender, e) =>
                {
                    Transport.RunningDownload dl = (Transport.RunningDownload)e.Argument;
                    BackgroundWorker bw          = (BackgroundWorker)sender;
                    long bytesRead = dl.Download.DownloadedBytes;

                    // limited number of progress bar updates
                    var uiUpdates       = new Subject <long>();
                    var cancelUiUpdates = uiUpdates
                                          .Take(1)
                                          .Merge(Observable.Empty <long>().Delay(TimeSpan.FromMilliseconds(KProgressUpdateInterval)))
                                          .Repeat()
                                          .Subscribe <long>(progress =>
                    {
                        if (bw.IsBusy)
                        {
                            bw.ReportProgress(0, progress);
                        }
                    });

                    if (dl is Transport.ActiveDownload)
                    {
                        string filePath = Utils.MediaFilePath(App.Engine.LoggedUser, dl.Download);
                        using (Stream writer = new IsolatedStorageFileStream(filePath, FileMode.Append, IsolatedStorageFile.GetUserStoreForApplication()))
                        {
                            using (Stream reader = ((Transport.ActiveDownload)dl).Stream)
                            {
                                byte[] buffer = new byte[16 * 1024];
                                int readCount;
                                while ((readCount = reader.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    bytesRead += readCount;
                                    writer.Write(buffer, 0, readCount);
                                    uiUpdates.OnNext(bytesRead);

                                    if (bw.CancellationPending)
                                    {
                                        pendingDownload.Cancel();
                                        e.Cancel = true;
                                        break;
                                    }
                                }
                                bw.ReportProgress(0, bytesRead);
                                e.Result = activeDownload.Download;
                            }
                        }
                        cancelUiUpdates.Dispose();
                    }
                    if (dl is Transport.BackgroundDownload)
                    {
                        BackgroundTransferRequest downloadRequest = ((Transport.BackgroundDownload)dl).Request;
                        IObservable <IEvent <BackgroundTransferEventArgs> > requestObserver = Observable.FromEvent <BackgroundTransferEventArgs>(downloadRequest, "TransferStatusChanged");
                        if (downloadRequest.TransferStatus != TransferStatus.Completed)
                        {
                            if (downloadRequest.TransferStatus == TransferStatus.None)
                            {
                                downloadRequest.DownloadLocation    = new Uri(Utils.BackgroundFilePath(App.Engine.LoggedUser, dl.Download), UriKind.RelativeOrAbsolute);
                                downloadRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
                                e.Result = activeDownload.Download;
                                BackgroundTransferService.Add(downloadRequest);
                            }
                            downloadRequest.TransferProgressChanged += (senderBackground, eventBackground) =>
                            {
                                if (activeDownload.Download.DownloadSize == long.MaxValue || activeDownload.Download.DownloadSize == 0)
                                {
                                    activeDownload.Download.DownloadSize =
                                        activeDownload.ContentLength == -1 ?
                                        0:
                                        activeDownload.ContentLength;
                                }
                                uiUpdates.OnNext(eventBackground.Request.BytesReceived);
                            };
                            IDisposable cancelOnStop = DownloadStopPendingEvent.Subscribe(stoppedDownload =>
                            {
                                if (dl.Download == stoppedDownload)
                                {
                                    BackgroundTransferService.Remove(downloadRequest);
                                    dl.Download.State           = QueuedDownload.DownloadState.Stopped;
                                    dl.Download.DownloadedBytes = 0;
                                }
                            });
                            bw.ReportProgress(0, requestObserver.First().EventArgs.Request);
                            cancelOnStop.Dispose();
                        }
                        e.Result = activeDownload.Download;
                    }
                };
                worker.ProgressChanged += (sender, e) =>
                {
                    if (e.UserState is BackgroundTransferRequest)
                    {
                        BackgroundTransferRequest request = e.UserState as BackgroundTransferRequest;
                        if (request.TransferStatus != TransferStatus.Completed || request.TransferError is InvalidOperationException)
                        {
                            activeDownload.Download.DownloadedBytes = 0;
                        }
                        else
                        {
                            activeDownload.Download.DownloadedBytes = ((BackgroundTransferRequest)e.UserState).BytesReceived;
                        }
                    }
                    else
                    {
                        activeDownload.Download.DownloadedBytes = (long)e.UserState;
                    }
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    if (activeDownload is Transport.ActiveDownload)
                    {
                        startedDownloads.Remove(activeDownload.Download);

                        if (!IsFileDownloadSuccessfulOrResumed(e, activeDownload.Download))
                        {
                            _downloadStoppedEvent.OnNext(activeDownload.Download);
                        }
                    }
                    else
                    {
                        if (!e.Cancelled && e.Error == null)
                        {
                            startedDownloads.Remove(activeDownload.Download);
                            QueuedDownload result = (QueuedDownload)e.Result;
                            if (IsBackgroundTransferSuccesfull(((Transport.BackgroundDownload)activeDownload).Request, result))
                            {
                                _downloadCompletedEvent.OnNext(activeDownload.Download);
                                App.Engine.StatisticsManager.LogDownloadCompleted(activeDownload.Download, "Completed");
                            }
                            else
                            {
                                _downloadStoppedEvent.OnNext(activeDownload.Download);
                            }
                        }
                        else if (e.Error != null)
                        {
                            startedDownloads.Remove(download);
                            _downloadErrorEvent.OnNext(download);
                        }
                        else
                        {
                            try
                            {
                                BackgroundTransferService.Remove((activeDownload as Transport.BackgroundDownload).Request);
                                _downloadStoppedEvent.OnNext(activeDownload.Download);
                                startedDownloads.Remove(download);
                            }
                            catch (InvalidOperationException)
                            {
                                startedDownloads.Remove(download);
                            }
                        }
                    }
                };
                worker.RunWorkerAsync(activeDownload);
            },
                error =>
            {
                startedDownloads.Remove(download);

                if (IsFileMissingFromServer(error))
                {
                    _downloadErrorEvent.OnNext(download);
                    App.Engine.StatisticsManager.LogDownloadCompleted(download, "Error");
                }
                else
                {
                    _downloadStoppedEvent.OnNext(download);
                }
            }
                );
            return(new PendingDownloadCancelHandle(pendingDownload));
        }
コード例 #11
0
 private PendingDownload chooseDownloadMethod( QueuedDownload queuedDownload )
 {
     if( queuedDownload.ForceActiveDownload || queuedDownload.DownloadSize >= 20000000L && queuedDownload.DownloadSize != long.MaxValue )
     {
         HttpWebRequest request = WebRequest.CreateHttp( ApplicationSettings.ServerUrl.DownloadPath( queuedDownload ) );
         request.SetCredentials( LoggedUser );
         request.Headers["Range"] = "bytes=" + queuedDownload.DownloadedBytes.ToString() + "-";
         request.AllowReadStreamBuffering = false;
         return new PendingActiveDownload( request,
           Observable.FromAsyncPattern<WebResponse>( request.BeginGetResponse, request.SaneEndGetResponse )()
          .Select( response => (RunningDownload)new ActiveDownload( response, queuedDownload ) ) );
     }
     else
     {
         //first check if there is not tranfer request already added to service
         foreach( BackgroundTransferRequest request in BackgroundTransferService.Requests )
         {
             if( request.RequestUri.Equals( ApplicationSettings.ServerUrl.DownloadPath( queuedDownload ) ) )
             {
                 return new PendingBackgroundDownload( request, Observable.Return( new BackgroundDownload( request, queuedDownload ) as RunningDownload ) );
             }
             request.Dispose();
         }
         BackgroundTransferRequest transferRequest = new BackgroundTransferRequest( ApplicationSettings.ServerUrl.DownloadPath( queuedDownload ) );
         return new PendingBackgroundDownload( transferRequest, Observable.Return( new BackgroundDownload( transferRequest, queuedDownload ) as RunningDownload ) );
     }
 }
        private IDownloadCancelHandle StartEnqueuedDownload(QueuedDownload download)
        {
            _downloadStartedEvent.OnNext(download);
            App.Engine.StatisticsManager.LogDownloadStart(download);

            Transport.PendingDownload pendingDownload = Transport.StartQueuedDownload(download);

            pendingDownload.Response
                        .ObserveOnDispatcher()
                        .Subscribe<Transport.RunningDownload>(
                                activeDownload =>
                                {
                                    if (activeDownload.Download.DownloadSize == long.MaxValue || activeDownload.Download.DownloadSize == 0)
                                    {
                                        activeDownload.Download.DownloadSize = activeDownload.ContentLength;
                                    }
                                    BackgroundWorker worker = new BackgroundWorker() { WorkerReportsProgress = true, WorkerSupportsCancellation = true };

                                    // change cancel handle
                                    startedDownloads[activeDownload.Download] = new ActiveDownloadCancelHandle(worker);

                                    worker.DoWork += (sender, e) =>
                                        {
                                            Transport.RunningDownload dl = (Transport.RunningDownload)e.Argument;
                                            BackgroundWorker bw = (BackgroundWorker)sender;
                                            long bytesRead = dl.Download.DownloadedBytes;

                                            // limited number of progress bar updates
                                            var uiUpdates = new Subject<long>();
                                            var cancelUiUpdates = uiUpdates
                                                .Take(1)
                                                .Merge(Observable.Empty<long>().Delay(TimeSpan.FromMilliseconds(KProgressUpdateInterval)))
                                                .Repeat()
                                                .Subscribe<long>(progress =>
                                                {
                                                    if (bw.IsBusy)
                                                    {
                                                        bw.ReportProgress(0, progress);
                                                    }
                                                });

                                            if (dl is Transport.ActiveDownload)
                                            {
                                                string filePath = Utils.MediaFilePath(App.Engine.LoggedUser, dl.Download);
                                                using (Stream writer = new IsolatedStorageFileStream(filePath, FileMode.Append, IsolatedStorageFile.GetUserStoreForApplication()))
                                                {
                                                    using (Stream reader = ((Transport.ActiveDownload)dl).Stream)
                                                    {
                                                        byte[] buffer = new byte[16 * 1024];
                                                        int readCount;
                                                        while ((readCount = reader.Read(buffer, 0, buffer.Length)) > 0)
                                                        {
                                                            bytesRead += readCount;
                                                            writer.Write(buffer, 0, readCount);
                                                            uiUpdates.OnNext(bytesRead);

                                                            if (bw.CancellationPending)
                                                            {
                                                                pendingDownload.Cancel();
                                                                e.Cancel = true;
                                                                break;
                                                            }
                                                        }
                                                        bw.ReportProgress(0, bytesRead);
                                                        e.Result = activeDownload.Download;
                                                    }
                                                }
                                                cancelUiUpdates.Dispose();
                                            }
                                            if (dl is Transport.BackgroundDownload)
                                            {
                                                BackgroundTransferRequest downloadRequest = ((Transport.BackgroundDownload)dl).Request;
                                                IObservable< IEvent <BackgroundTransferEventArgs> > requestObserver = Observable.FromEvent<BackgroundTransferEventArgs>(downloadRequest, "TransferStatusChanged");
                                                if (downloadRequest.TransferStatus != TransferStatus.Completed)
                                                {
                                                    if (downloadRequest.TransferStatus == TransferStatus.None)
                                                    {
                                                             downloadRequest.DownloadLocation = new Uri(Utils.BackgroundFilePath(App.Engine.LoggedUser, dl.Download), UriKind.RelativeOrAbsolute);
                                                             downloadRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
                                                             e.Result = activeDownload.Download;
                                                             BackgroundTransferService.Add(downloadRequest);
                                                    }
                                                    downloadRequest.TransferProgressChanged += (senderBackground, eventBackground) =>
                                                        {
                                                            if (activeDownload.Download.DownloadSize == long.MaxValue || activeDownload.Download.DownloadSize == 0)
                                                            {
                                                                activeDownload.Download.DownloadSize =
                                                                    activeDownload.ContentLength == -1 ?
                                                                    0:
                                                                    activeDownload.ContentLength;
                                                            }
                                                            uiUpdates.OnNext(eventBackground.Request.BytesReceived);
                                                        };
                                                    IDisposable cancelOnStop =  DownloadStopPendingEvent.Subscribe( stoppedDownload =>
                                                                        {
                                                                            if (dl.Download == stoppedDownload)
                                                                            {
                                                                                BackgroundTransferService.Remove(downloadRequest);
                                                                                dl.Download.State = QueuedDownload.DownloadState.Stopped;
                                                                                dl.Download.DownloadedBytes = 0;
                                                                            }
                                                                        });
                                                    bw.ReportProgress(0, requestObserver.First().EventArgs.Request);
                                                    cancelOnStop.Dispose();
                                                }
                                                e.Result = activeDownload.Download;
                                            }
                                        };
                                    worker.ProgressChanged += (sender, e) =>
                                        {
                                            if (e.UserState is BackgroundTransferRequest)
                                            {
                                                BackgroundTransferRequest request = e.UserState as BackgroundTransferRequest;
                                                if (request.TransferStatus != TransferStatus.Completed || request.TransferError is InvalidOperationException)
                                                {
                                                    activeDownload.Download.DownloadedBytes = 0;
                                                }
                                                else
                                                {
                                                    activeDownload.Download.DownloadedBytes = ((BackgroundTransferRequest)e.UserState).BytesReceived;
                                                }
                                            }
                                            else
                                            {
                                            activeDownload.Download.DownloadedBytes = (long)e.UserState;
                                            }
                                        };
                                    worker.RunWorkerCompleted += (sender, e) =>
                                        {
                                            if (activeDownload is Transport.ActiveDownload)
                                            {
                                                startedDownloads.Remove(activeDownload.Download);

                                                if (!IsFileDownloadSuccessfulOrResumed(e,activeDownload.Download))
                                                {
                                                    _downloadStoppedEvent.OnNext(activeDownload.Download);
                                                }
                                            }
                                            else
                                            {
                                                if (!e.Cancelled && e.Error == null)
                                                {
                                                    startedDownloads.Remove(activeDownload.Download);
                                                    QueuedDownload result = (QueuedDownload)e.Result;
                                                    if (IsBackgroundTransferSuccesfull(((Transport.BackgroundDownload)activeDownload).Request, result))
                                                    {
                                                        _downloadCompletedEvent.OnNext(activeDownload.Download);
                                                        App.Engine.StatisticsManager.LogDownloadCompleted(activeDownload.Download, "Completed");

                                                    }
                                                    else
                                                    {
                                                        _downloadStoppedEvent.OnNext(activeDownload.Download);
                                                    }

                                                }
                                                else if (e.Error != null)
                                                {
                                                    startedDownloads.Remove(download);
                                                    _downloadErrorEvent.OnNext(download);
                                                }
                                                else
                                                {
                                                    try
                                                    {
                                                        BackgroundTransferService.Remove((activeDownload as Transport.BackgroundDownload).Request);
                                                        _downloadStoppedEvent.OnNext(activeDownload.Download);
                                                        startedDownloads.Remove(download);
                                                    }
                                                    catch (InvalidOperationException)
                                                    {
                                                        startedDownloads.Remove(download);
                                                    }
                                                }
                                            }
                                        };
                                    worker.RunWorkerAsync(activeDownload);
                                },
                                error =>
                                {
                                    startedDownloads.Remove(download);

                                    if (IsFileMissingFromServer(error))
                                    {
                                        _downloadErrorEvent.OnNext(download);
                                        App.Engine.StatisticsManager.LogDownloadCompleted(download, "Error");
                                    }
                                    else
                                    {
                                        _downloadStoppedEvent.OnNext(download);
                                    }
                                }
                            );
            return new PendingDownloadCancelHandle(pendingDownload);
        }
 private bool IsBackgroundTransferSuccesfull(BackgroundTransferRequest backgroundTransferRequest, QueuedDownload result)
 {
     foreach (BackgroundTransferRequest request in BackgroundTransferService.Requests)
     {
         if (request.RequestUri.ToString().EndsWith(result.Filename))
         {
             if (request.TransferStatus == TransferStatus.Completed)
             {
                 if (request.StatusCode == 200 || request.StatusCode == 206)
                 {
                     if (request.TransferError == null)
                     {
                         using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                         {
                             string filename = Uri.UnescapeDataString(request.DownloadLocation.RemoveTransferPath().ToString());
                             if (isoStore.FileExists(filename))
                             {
                                 isoStore.DeleteFile(filename);
                             }
                             isoStore.MoveFile(request.DownloadLocation.OriginalString, filename);
                         }
                         BackgroundTransferService.Remove(request);
                         request.Dispose();
                         return true;
                     }
                     else
                     {
                         //move request to standard queue
                         BackgroundTransferService.Remove(request);
                         request.Dispose();
                         result.ForceActiveDownload = true;
                         StartDownload(result);
                         return false;
                     }
                 }
                 else
                 {
                     BackgroundTransferService.Remove(request);
                     request.Dispose();
                     _downloadStoppedEvent.OnNext(result);
                     return false;
                 }
             }
             else if (request.TransferStatus == TransferStatus.WaitingForExternalPower
                 || request.TransferStatus == TransferStatus.WaitingForNonVoiceBlockingNetwork
                 || request.TransferStatus == TransferStatus.WaitingForWiFi
                 || request.TransferStatus == TransferStatus.Waiting
                 || request.TransferStatus == TransferStatus.WaitingForExternalPowerDueToBatterySaverMode)
             {
                 //move request to standard queue
                 BackgroundTransferService.Remove(request);
                 request.Dispose();
                 result.ForceActiveDownload = true;
                 StartDownload(result);
                 return false;
             }
         }
         request.Dispose();
     }
     return false;
 }
 public void StartDownload(QueuedDownload download, bool resume = false, bool forceNow = false)
 {
     if (queuedDownloads.Contains(download) || startedDownloads.Keys.Contains(download))
     {
         return;
     }
     if (resume)
     {
         queuedDownloads.Insert(0, download);
     }
     else if(!forceNow)
     {
         queuedDownloads.Add(download);
         _downloadEnqueuedEvent.OnNext(download);
     }
     if (forceNow)
     {
         QueuedDownload nextDownload = null;
         if (startedDownloads.Count >= KMaxSimultaneousDownloads)
         {
             nextDownload = startedDownloads.Keys.First();
         }
         IDownloadCancelHandle cancelHandle = StartEnqueuedDownload(download);
         startedDownloads.Add(download, cancelHandle);
         if (nextDownload != null)
         {
             StopDownload(nextDownload, true);
         }
     }
     else
     {
         StartEnqueuedItemsIfPossible();
     }
 }
 public void LogDownloadCompleted( QueuedDownload download, string status )
 {
     Statistics.Add( DownloadStatisticItem.CreateDownloadCompletedEven( LoggedUser.LoggedUser, ApplicationSettings.ServerUrl.DownloadPath( download ), download, status ) );
 }
コード例 #16
0
 public static DownloadStatisticItem CreateDownloadEndEven(User user, Uri url, QueuedDownload download)
 {
     return(new DownloadStatisticItem(StatisticType.DOWNLOAD_END, user.Username, url.ToString(), GetDownloadPercentProgress(download)));
 }
コード例 #17
0
 public void CancelDownload( QueuedDownload download )
 {
     DownloadManager.StopDownload( download ).Subscribe(
         dl =>
         {
             using( IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication() )
             {
                 string path = Utils.MediaFilePath( LoggedUser, dl );
                 if( isf.FileExists( path ) )
                 {
                     isf.DeleteFile( path );
                 }
             }
         } );
     LoggedUser.Downloads.Remove( download );
     App.Engine.StatisticsManager.LogDownloadRemove( download );
 }
 public void LogDownloadCompleted(QueuedDownload download, string status)
 {
     Statistics.Add(DownloadStatisticItem.CreateDownloadCompletedEven(LoggedUser.LoggedUser, ApplicationSettings.ServerUrl.DownloadPath(download), download, status));
 }
 public void LogDownloadEnd(QueuedDownload download)
 {
     Statistics.Add(DownloadStatisticItem.CreateDownloadEndEven(LoggedUser.LoggedUser, ApplicationSettings.ServerUrl.DownloadPath(download), download));
 }
コード例 #20
0
 public RunningDownload( QueuedDownload download )
 {
     Download = download;
 }
コード例 #21
0
 public void StartDownload(QueuedDownload download)
 {
     DownloadManager.StartDownload(download);
 }
コード例 #22
0
 public static Uri DownloadPath( this Uri serverUrl, QueuedDownload download )
 {
     return serverUrl.CombinePath( download.LibraryId, MediaPathPart2, MediaPathPart3, download.Filename );
 }
コード例 #23
0
        private static string GetDownloadPercentProgress(QueuedDownload download)
        {
            double percent = ((double)download.DownloadedBytes / (double)download.DownloadSize) * 100.0;

            return(percent.ToString());
        }
コード例 #24
0
        public AddingToQueueResult EnqueueMediaItem( MediaItemsListModelItem mediaItem, bool immediate, bool forceNow = false )
        {
            if( LoggedUser.Downloads.Count( queuedDownload => queuedDownload.Id == mediaItem.Id ) == 0 )
            {
                QueuedDownload.DownloadState initialState =
                    App.Engine.LoggedUser.Settings.AutomaticDownloads ?
                    QueuedDownload.DownloadState.Queued :
                    ( immediate ? QueuedDownload.DownloadState.Queued : QueuedDownload.DownloadState.Paused );

                QueuedDownload queuedDownload = new QueuedDownload( mediaItem ) { State = initialState };

                using( IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication() )
                {
                    if( isf.FileExists( Utils.MediaFilePath( LoggedUser, queuedDownload ) ) )
                    {
                        return AddingToQueueResult.ItemAlreadyDownloaded;
                    }
                }

                StatisticsManager.LogDownloadAdd( queuedDownload );
                LoggedUser.Downloads.Add( queuedDownload );
                _downloadEnqueuedEvent.OnNext( queuedDownload );

                if( initialState != QueuedDownload.DownloadState.Stopped )
                {
                    DownloadManager.StartDownload( queuedDownload, false, forceNow );
                }
                return AddingToQueueResult.ItemAddedToQueue;
            }
            else if( immediate )
            {
                QueuedDownload queuedDownload = ( from download in LoggedUser.Downloads where download.Id == mediaItem.Id select download ).First();
                queuedDownload.State = QueuedDownload.DownloadState.Queued;
                DownloadManager.StartDownload( queuedDownload );
                return AddingToQueueResult.DownloadItemStarted;
            }
            else
            {
                return AddingToQueueResult.ItemAlreadyDownloaded;
            }
        }
コード例 #25
0
 public static DownloadStatisticItem CreateDownloadCompletedEven(User user, Uri url, QueuedDownload download, string status)
 {
     return(new DownloadStatisticItem(StatisticType.DOWNLOAD_COMPLETED, user.Username, url.ToString(), GetDownloadPercentProgress(download), status));
 }
コード例 #26
0
 public void StopDownload( QueuedDownload download )
 {
     DownloadManager.StopDownload( download );
 }
 public void LogDownloadStart( QueuedDownload download )
 {
     Statistics.Add( DownloadStatisticItem.CreateDownloadStartEven( LoggedUser.LoggedUser, ApplicationSettings.ServerUrl.DownloadPath( download ), download ) );
 }
コード例 #28
0
 public RunningDownload(QueuedDownload download)
 {
     Download = download;
 }
        public IObservable<QueuedDownload> StopDownload(QueuedDownload download, bool queueAgain = false)
        {
            _downloadStopPendingEvent.OnNext(download);

            if (!queuedDownloads.Contains(download) && !startedDownloads.Keys.Contains(download))
            {
                return Observable.Return<QueuedDownload>(download);
            }

            IObservable<QueuedDownload> result = DownloadDoneEvent.Where(dl => dl == download).Take(1);

            if (queuedDownloads.Remove(download))
            {
                _downloadStoppedEvent.OnNext(download);
            }
            else
            {
                // item was not waiting in queue, so it's already downloading
                startedDownloads[download].Cancel();
                result.Subscribe(dl =>
                    {
                        startedDownloads.Remove(dl);
                        if (!queueAgain)
                        {
                            StartEnqueuedItemsIfPossible();
                        }
                        else
                        {
                            queuedDownloads.Insert(0, dl);
                            dl.State = QueuedDownload.DownloadState.Queued;
                            _downloadEnqueuedEvent.OnNext(dl);
                        }
                    });
            }

            return result;
        }
コード例 #30
0
 public ActiveDownload(WebResponse response, QueuedDownload download)
     : base(download)
 {
     Response = response;
 }
 private bool IsFileDownloadSuccessfulOrResumed(RunWorkerCompletedEventArgs e, QueuedDownload queuedDownload)
 {
     if (!e.Cancelled && e.Error == null)
     {
         QueuedDownload result = (QueuedDownload)e.Result;
         if (result.DownloadedBytes == result.DownloadSize)
         {
             _downloadCompletedEvent.OnNext(queuedDownload);
             App.Engine.StatisticsManager.LogDownloadCompleted(queuedDownload, "Completed");
         }
         else
         {
             StartDownload(result, true);
         }
         return true;
     }
     return false;
 }
コード例 #32
0
 private bool IsBackgroundTransferSuccesfull(BackgroundTransferRequest backgroundTransferRequest, QueuedDownload result)
 {
     foreach (BackgroundTransferRequest request in BackgroundTransferService.Requests)
     {
         if (request.RequestUri.ToString().EndsWith(result.Filename))
         {
             if (request.TransferStatus == TransferStatus.Completed)
             {
                 if (request.StatusCode == 200 || request.StatusCode == 206)
                 {
                     if (request.TransferError == null)
                     {
                         using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                         {
                             string filename = Uri.UnescapeDataString(request.DownloadLocation.RemoveTransferPath().ToString());
                             if (isoStore.FileExists(filename))
                             {
                                 isoStore.DeleteFile(filename);
                             }
                             isoStore.MoveFile(request.DownloadLocation.OriginalString, filename);
                         }
                         BackgroundTransferService.Remove(request);
                         request.Dispose();
                         return(true);
                     }
                     else
                     {
                         //move request to standard queue
                         BackgroundTransferService.Remove(request);
                         request.Dispose();
                         result.ForceActiveDownload = true;
                         StartDownload(result);
                         return(false);
                     }
                 }
                 else
                 {
                     BackgroundTransferService.Remove(request);
                     request.Dispose();
                     _downloadStoppedEvent.OnNext(result);
                     return(false);
                 }
             }
             else if (request.TransferStatus == TransferStatus.WaitingForExternalPower ||
                      request.TransferStatus == TransferStatus.WaitingForNonVoiceBlockingNetwork ||
                      request.TransferStatus == TransferStatus.WaitingForWiFi ||
                      request.TransferStatus == TransferStatus.Waiting ||
                      request.TransferStatus == TransferStatus.WaitingForExternalPowerDueToBatterySaverMode)
             {
                 //move request to standard queue
                 BackgroundTransferService.Remove(request);
                 request.Dispose();
                 result.ForceActiveDownload = true;
                 StartDownload(result);
                 return(false);
             }
         }
         request.Dispose();
     }
     return(false);
 }
コード例 #33
0
 public ActiveDownload( WebResponse response, QueuedDownload download )
     : base(download)
 {
     Response = response;
 }
コード例 #34
0
 public PendingDownload StartQueuedDownload( QueuedDownload queuedDownload )
 {
     return chooseDownloadMethod( queuedDownload );
 }
コード例 #35
0
 public BackgroundDownload( BackgroundTransferRequest request, QueuedDownload download )
     : base(download)
 {
     Request = request;
 }
コード例 #36
0
 public static Uri DownloadPath(this Uri serverUrl, QueuedDownload download)
 {
     return(serverUrl.CombinePath(download.LibraryId, MediaPathPart2, MediaPathPart3, download.Filename));
 }
コード例 #37
0
 public BackgroundDownload(BackgroundTransferRequest request, QueuedDownload download)
     : base(download)
 {
     Request = request;
 }
コード例 #38
0
 public static string MediaFilePath(User user, QueuedDownload file)
 {
     return(MediaFilePath(user, file.LibraryId, file.LocalFilename));
 }
コード例 #39
0
        private MediaItemsListModelItem DownloadToMediaItem( QueuedDownload download )
        {
            if( ActiveLibrary == null )
                return null;

            return MediaItems.FirstOrDefault( item => item.Id == download.Id );
        }
コード例 #40
0
 public PendingDownload StartQueuedDownload(QueuedDownload queuedDownload)
 {
     return(chooseDownloadMethod(queuedDownload));
 }