Beispiel #1
0
        private Task GetPatchesShortestPath()
        {
            return(Task.Run(() =>
            {
                var currentVersion = CurrentVersion;
                List <PatchIndexEntry> compatiblePatches = null;
                do
                {
                    var version = currentVersion;
                    compatiblePatches = PatchesIndex.Patches.Where(p => p.From.Equals(version)).ToList();
                    if (compatiblePatches.Count == 0)
                    {
                        continue;
                    }

                    var longestJumpPatch = compatiblePatches.OrderBy(p => p.To).Last();
                    var downloadEntry = new DownloadEntry(
                        Settings.GetRemotePatchDefinitionUrl(longestJumpPatch.From, longestJumpPatch.To),
                        Settings.GetRemotePatchDefinitionUrl(longestJumpPatch.From, longestJumpPatch.To).Replace(Settings.RemoteUrl, string.Empty),
                        null,
                        null,
                        null
                        );
                    PatchesPath.Add(Downloader.DownloadJson <PatchDefinition>(downloadEntry, Serializer));
                    currentVersion = longestJumpPatch.To;
                } while (compatiblePatches.Count > 0);

                Logger.Info("Found {ApplicablePatchesAmount} applicable updates.", PatchesPath.Count);
            }));
        }
        protected override IReadOnlyCollection <DownloadEntry> ReadAllDownloadEntriesFromThread(HtmlNode threadHtmlNode, DownloadContext downloadContext)
        {
            var res = new List <DownloadEntry>();

            var spoilerContainers = threadHtmlNode.Descendants().Where(f => f.Attributes["Class"]?.Value.Contains("bbCodeSpoilerContainer") == true);

            foreach (var spoilerContainer in spoilerContainers)
            {
                var spanElementForUploaded = TryGetSpanElementForUploadedNet(spoilerContainer);
                if (spanElementForUploaded != null)
                {
                    var linkElement = GetExternalLinkElement(spanElementForUploaded);

                    var entryTitle      = linkElement.InnerText;
                    var externalLinkUrl = GetExternalUrl(linkElement);

                    var uploadedDate = GetLastThreadUpdate(threadHtmlNode);

                    var newEntry = new DownloadEntry(downloadContext.Name, externalLinkUrl, entryTitle, uploadedDate, false);
                    res.Add(newEntry);
                }
            }

            return(res.AsReadOnly());
        }
Beispiel #3
0
 private Task GetPatchesIndex()
 {
     return(Task.Run(() =>
     {
         try
         {
             var downloadEntry = new DownloadEntry(
                 Settings.GetRemotePatchesIndexUrl(),
                 Settings.GetRemotePatchesIndexUrl().Replace(Settings.RemoteUrl, string.Empty),
                 null,
                 null,
                 null
                 );
             PatchesIndex = Downloader.DownloadJson <PatchIndex>(downloadEntry, Serializer);
         }
         catch
         {
             PatchesIndex = new PatchIndex()
             {
                 Patches = new List <PatchIndexEntry>()
             };
             Logger.Warning("No patches index found.");
         }
     }));
 }
Beispiel #4
0
 public void SaveDownloadLists(DownloadLists lists)
 {
     try {
         var listsEntry = new DownloadEntry {Title = lists.Title, ThumbnailUrl = lists.ThumbnailUrl, ExecutionStatus = lists.ExecutionStatus };
         foreach (DownloadList list in lists.Entries) {
             if (list.DownloadState == DownloadState.AllFinished || list.Entries.Count <= 0) continue;
             var entry = new DownloadEntry {
                 Title = list.Title,
                 ThumbnailUrl = list.ThumbnailUrl,
                 MediaType = list.MediaType,
                 ExecutionStatus = list.ExecutionStatus,
                 Url = ""
             };
             var firstEntry = list.Entries[0] as YoutubeEntry;
             if (firstEntry == null) continue;
             if (firstEntry.Parent != null) {
                 entry.Url = String.Format("{0}", firstEntry.Parent.Uri);
                 entry.Title = firstEntry.Parent.Title;
             }
             foreach (YoutubeEntry youtubeEntry in list.Entries)
                 entry.List.Add(new DownloadEntry {
                     Title = youtubeEntry.Title,
                     Url = youtubeEntry.Uri.ToString(),
                     MediaType = youtubeEntry.MediaType,
                     ThumbnailUrl = youtubeEntry.ThumbnailUrl,
                     ExecutionStatus = youtubeEntry.ExecutionStatus
                 });
             listsEntry.List.Add(entry);
         }
         using (var file = new StreamWriter(_downloadsFile)) file.Write(JsonConvert.SerializeObject(listsEntry));
     }
     catch {}
 }
Beispiel #5
0
 private Task GetBuildsIndex()
 {
     return(Task.Run(() =>
     {
         try
         {
             var downloadEntry = new DownloadEntry(
                 Settings.GetRemoteBuildsIndexUrl(),
                 Settings.GetRemoteBuildsIndexUrl().Replace(Settings.RemoteUrl, string.Empty),
                 null,
                 null,
                 null
                 );
             BuildsIndex = Downloader.DownloadJson <BuildsIndex>(downloadEntry, Serializer);
         }
         catch (Exception e)
         {
             BuildsIndex = new BuildsIndex()
             {
                 AvailableBuilds = new List <IVersion>()
             };
             Logger.Warning("No builds index found. Problem: {BuildsIndexException}", e);
         }
     }));
 }
        private IEnumerable <DownloadEntry> ReadActualEpisodes(HtmlNode threadHtmlNode, DownloadContext downloadContext)
        {
            var      result = new List <DownloadEntry>();
            HtmlNode actualEpisdesDivElement;

            if (TryReadingActualEpisodesDivElement(threadHtmlNode, out actualEpisdesDivElement))
            {
                var uploadedElements = actualEpisdesDivElement.Descendants("a").Where(f => f.InnerText == "Uploaded");

                foreach (var uploadedEle in uploadedElements)
                {
                    var downloadLink   = uploadedEle.Attributes.First(f => f.Name == "href").Value;
                    var parentSpan     = uploadedEle.NavigateToElementOfType("span", Model.Enumerations.HtmlNavigationType.Parent);
                    var spanWithTitles = parentSpan.NavigateToElementOfType("span", Model.Enumerations.HtmlNavigationType.PreviousSibling);

                    if (spanWithTitles == null)
                    {
                        spanWithTitles = parentSpan.NavigateToElementOfType("span", Model.Enumerations.HtmlNavigationType.Parent);
                    }

                    var entryTitles = GetDownloadEntryTitles(spanWithTitles);

                    var lastUploadDate = GetLastThreadUpdate(threadHtmlNode);
                    var newEntry       = new DownloadEntry(downloadContext.Name, downloadLink, entryTitles, lastUploadDate, false);

                    result.Add(newEntry);
                }
            }
            else
            {
                throw new DownloadException("Could not find an entry-point for the actual episodes");
            }

            return(result);
        }
        private IEnumerable <DownloadEntry> ReadActualEpisodes(HtmlNode threadHtmlNode, DownloadContext downloadContext)
        {
            var result = new List <DownloadEntry>();

            var allLinkElements = threadHtmlNode.Descendants("a").Where(f =>
            {
                var attr = f.Attributes["href"].Value;
                return(attr.ContainsCaseInsensitive("ncrypt.in"));
            });

            foreach (var linkElement in allLinkElements)
            {
                var title = GetTitleFromLink(linkElement);

                // Assuming it is not Season-Pack
                if (!string.IsNullOrEmpty(title))
                {
                    var link          = linkElement.Attributes["href"].Value;
                    var downloadEntry = new DownloadEntry(downloadContext.Name, link, title, GetLastThreadUpdate(threadHtmlNode), false);
                    result.Add(downloadEntry);
                }
            }

            return(result);
        }
Beispiel #8
0
        private DownloadEntry CreateEntry(HtmlNode threadHtmlNode, DownloadContext downloadContext, HtmlNode uploadedSpan)
        {
            var linkElement = uploadedSpan.ParentNode;

            var externalLink = GetExternalUrl(linkElement);

            string entryName;
            bool   isSeasonPack;

            if (CheckIfIsAllEpisodesSpan(uploadedSpan))
            {
                entryName    = Constants.DOWNLOADENTRYTITLE_SEASONPACK;
                isSeasonPack = true;
            }
            else
            {
                entryName    = GetDownloadEntryTitle(linkElement);
                isSeasonPack = false;
            }

            var lastUploadDate = GetLastThreadUpdate(threadHtmlNode);
            var result         = new DownloadEntry(downloadContext.Name, externalLink, entryName, lastUploadDate, isSeasonPack);

            return(result);
        }
        public DownloadProperties(string DownloadID)
        {
            InitializeComponent();

            properties = Downloads.DownloadEntries.Where(download => download.DownloadID == DownloadID).FirstOrDefault();

            FileIcon.Source = IconTools.GetIconForExtension(properties.FileName, ShellIconSize.LargeIcon).IconToImageSource();
            FileName.Text = properties.FileName;

            FileType.Text = SHGetFileInfo_Wrapper.GetFileTypeDescription(properties.FileName);
            Status.Text = properties.Status != null ? properties.Status : "Unknown";
            Size.Text = properties.SizePretty != null ? properties.SizePretty : "Unknown";

            SaveTo_txtBox.Text = properties.SaveTo;

            Address.Text = properties.DownloadLink.ToString();
            Description.Text = properties.Description;

            authUser.Text = properties.AuthUsername;
            authPass.Password = properties.AuthPassword;

            if (properties.Status == "Complete")
            {
                SaveTo_button.Content = "Move";
                btnOpen.IsEnabled = true;
                Address.IsReadOnly = true;
            }

            SaveTo_txtBox.SelectAll(); // select all text in this box on window load (to show that the box is selectable)

            this.PreviewKeyDown += new KeyEventHandler(HandleEsc); // Close window when escape is hit
        }
Beispiel #10
0
        public DownloadProperties(string DownloadID)
        {
            InitializeComponent();

            properties = Downloads.DownloadEntries.Where(download => download.DownloadID == DownloadID).FirstOrDefault();

            FileIcon.Source = IconTools.GetIconForExtension(properties.FileName, ShellIconSize.LargeIcon).IconToImageSource();
            FileName.Text   = properties.FileName;

            FileType.Text = SHGetFileInfo_Wrapper.GetFileTypeDescription(properties.FileName);
            Status.Text   = properties.Status != null ? properties.Status : "Unknown";
            Size.Text     = properties.SizePretty != null ? properties.SizePretty : "Unknown";

            SaveTo_txtBox.Text = properties.SaveTo;

            Address.Text     = properties.DownloadLink.ToString();
            Description.Text = properties.Description;

            authUser.Text     = properties.AuthUsername;
            authPass.Password = properties.AuthPassword;

            if (properties.Status == "Complete")
            {
                SaveTo_button.Content = "Move";
                btnOpen.IsEnabled     = true;
                Address.IsReadOnly    = true;
            }

            SaveTo_txtBox.SelectAll();                             // select all text in this box on window load (to show that the box is selectable)

            this.PreviewKeyDown += new KeyEventHandler(HandleEsc); // Close window when escape is hit
        }
Beispiel #11
0
        public DownloadHandler(BLTEStream blte)
        {
            if (CASContainer.BuildConfig["download-size"][0] != null && blte.Length != long.Parse(CASContainer.BuildConfig["download-size"][0]))
            {
                CASContainer.Settings?.Logger.LogAndThrow(Logging.LogType.Critical, "Download File is corrupt.");
            }

            using (var br = new BinaryReader(blte))
            {
                Header = new DownloadHeader()
                {
                    Header       = br.ReadBytes(2),
                    Version      = br.ReadByte(),
                    ChecksumSize = br.ReadByte(),
                    Unknown      = br.ReadByte(),
                    NumEntries   = br.ReadUInt32BE(),
                    NumTags      = br.ReadUInt16BE(),
                };

                // entries
                for (int i = 0; i < Header.NumEntries; i++)
                {
                    var entry = new DownloadEntry()
                    {
                        Unknown     = Header.Version > 1 ? br.ReadByte() : (byte)0,                     // new V2 field
                        Hash        = new MD5Hash(br),
                        FileSize    = br.ReadUInt40BE(),
                        Stage       = br.ReadByte(),
                        UnknownData = br.ReadBytes(4)
                    };

                    Entries.Add(entry);
                }

                // tags
                int numMaskBytes = ((int)Header.NumEntries + 7) / 8;
                for (int i = 0; i < Header.NumTags; i++)
                {
                    var tag = new DownloadTag()
                    {
                        Name    = br.ReadCString(),
                        Type    = br.ReadUInt16BE(),
                        BitMask = new BoolArray(br.ReadBytes(numMaskBytes))
                    };

                    Tags.Add(tag);
                }

                EncodingMap = blte.EncodingMap.ToArray();

                endofStageIndex = new int[]                 // store last indice of each stage
                {
                    Entries.FindLastIndex(x => x.Stage == 0),
                    Entries.FindLastIndex(x => x.Stage == 1)
                };
            }

            blte?.Dispose();
        }
Beispiel #12
0
        public void TestResolveEntryAvailable()
        {
            updateChecker.DownloadIdentifier = "fileHashMD5";
            DownloadEntry entry = updateChecker.ResolveDownloadEntry(appUpdate);

            Assert.AreEqual("TestFiles\\DownloadTestFile.txt", entry.Link);
            Assert.AreEqual("Download.txt", entry.FileName);
        }
Beispiel #13
0
        public void TestResolveEntryNotAvailable()
        {
            updateChecker.DownloadIdentifier = "notAvailableIdentifier";
            DownloadEntry entry = updateChecker.ResolveDownloadEntry(appUpdate);

            Assert.AreEqual("http://www.example.com", entry.Link);
            Assert.AreEqual("Default.zip", entry.FileName);
            Assert.IsNull(entry.FileHash);
        }
Beispiel #14
0
        public DownloadEntryViewModel(DownloadEntry downloadEntry)
        {
            this._downloadEntry = downloadEntry;

            timer          = new Timer(1000);
            timer.Elapsed += (o, k) => {
                OnPropertyChanged("Status");
                OnPropertyChanged("Progress");
                OnPropertyChanged("DSpeed");
                OnPropertyChanged("USpeed");
            };
            timer.Start();
        }
Beispiel #15
0
 public override string DownloadString(DownloadEntry entry)
 {
     using (var client = new DropboxClient(Credentials.Password))
     {
         var url = entry.PartialRemoteUrl;
         if (!url.StartsWith("/"))
         {
             url = "/" + url;
         }
         using (var response = client.Files.DownloadAsync(url).Result)
         {
             return(response.GetContentAsStringAsync().Result);
         }
     }
 }
Beispiel #16
0
        public void AddEntry(CASResult blte)
        {
            if (CASContainer.EncodingHandler.Layout.ContainsKey(blte.Hash))             // skip existing
            {
                return;
            }

            var entry = new DownloadEntry()
            {
                Hash        = blte.Hash,
                FileSize    = blte.CompressedSize - 30,
                UnknownData = new byte[4],
                Stage       = (byte)(blte.HighPriority ? 0 : 1)
            };

            int index = endofStageIndex[entry.Stage];

            if (index >= 0)
            {
                if (entry.Stage == 0)
                {
                    endofStageIndex[0]++;
                }
                endofStageIndex[1]++;

                Entries.Insert(index, entry);

                foreach (var tag in Tags)
                {
                    if (tag.Name != "Alternate")
                    {
                        tag.BitMask.Insert(index, true);
                    }
                }
            }
            else
            {
                Entries.Add(entry);

                foreach (var tag in Tags)
                {
                    if (tag.Name != "Alternate")
                    {
                        tag.BitMask.Add(true);
                    }
                }
            }
        }
        private IEnumerable <DownloadEntry> ReadActualEpisodes(HtmlNode threadHtmlNode, DownloadContext downloadContext)
        {
            var result             = new List <DownloadEntry>();
            var singleEpisodeSpans = threadHtmlNode.Descendants().Where(f => f.Name == "span" && f.InnerText == "Aktuelle Folge");

            foreach (var singleSpan in singleEpisodeSpans)
            {
                var externalLink     = GetExternalUrl(singleSpan);
                var entryName        = GetDownloadEntryName(singleSpan);
                var lastThreadUpdate = GetLastThreadUpdate(threadHtmlNode);

                var downloadEntry = new DownloadEntry(downloadContext.Name, externalLink, entryName, lastThreadUpdate, false);
                result.Add(downloadEntry);
            }

            return(result);
        }
Beispiel #18
0
        public async Task TestDownloadUpdateNoFileName(string identifier, string expectedName, bool download)
        {
            updateChecker.DownloadIdentifier = identifier;
            // first check FileName
            DownloadEntry entry = updateChecker.ResolveDownloadEntry(appUpdate);

            Assert.AreEqual(expectedName, entry.FileName);
            // now perform download
            if (!download)
            {
                return;
            }
            string downloadPath = await updateChecker.DownloadUpdate(appUpdate);

            Assert.IsNotNull(downloadPath);
            Assert.AreEqual(downloadFileText, File.ReadAllText(downloadPath));
        }
        private bool TryReadingSeasonPack(HtmlNode threadHtmlNode, DownloadContext downloadContext, out DownloadEntry seasonPackEntry)
        {
            var seasonPackSpan = threadHtmlNode.Descendants("span").FirstOrDefault(f => f.InnerText.Contains("Staffelpack"));

            if (seasonPackSpan != null)
            {
                var parentDiv      = seasonPackSpan.NavigateToElementOfType("div", Model.Enumerations.HtmlNavigationType.Parent);
                var downloadLink   = GetExternalLinkUrl(parentDiv);
                var entryTitle     = Constants.DOWNLOADENTRYTITLE_SEASONPACK;
                var lastUploadDate = GetLastThreadUpdate(threadHtmlNode);
                seasonPackEntry = new DownloadEntry(downloadContext.Name, downloadLink, entryTitle, lastUploadDate, true);
                return(true);
            }

            seasonPackEntry = null;
            return(false);
        }
Beispiel #20
0
        private Task GetBuildDefinition()
        {
            return(Task.Run(() =>
            {
                if (CurrentVersion == null)
                {
                    CurrentVersion = BuildsIndex.GetLast();
                }

                if (CurrentVersion == null)
                {
                    Logger.Error(null, "Cannot retrieve any new version...");
                    throw new NoAvailableBuildsException();
                }

                if (!BuildsIndex.Contains(CurrentVersion) && CurrentVersion.IsLower(BuildsIndex.GetFirst()))
                {
                    CurrentVersion = BuildsIndex.GetLast();
                    SetRepairNeeded();
                }

                try
                {
                    var downloadEntry = new DownloadEntry(
                        Settings.GetRemoteBuildDefinitionUrl(CurrentVersion),
                        Settings.GetRemoteBuildDefinitionUrl(CurrentVersion).Replace(Settings.RemoteUrl, string.Empty),
                        null,
                        null,
                        null
                        );
                    CurrentBuildDefinition =
                        Downloader.DownloadJson <BuildDefinition>(downloadEntry, Serializer);
                    Logger.Info("Retrieved definition for {CurrentVersion}", CurrentVersion);
                }
                catch
                {
                    CurrentBuildDefinition = new BuildDefinition()
                    {
                        Entries = new BuildDefinitionEntry[0]
                    };
                    Logger.Warning("Cannot retrieve the build definition for {CurrentVersion}", CurrentVersion);
                }
            }));
        }
        private bool TryReadingSeasonPack(HtmlNode threadHtmlNode, DownloadContext downloadContext, out DownloadEntry seasonPackEntry)
        {
            var staffelpackElement = threadHtmlNode.Descendants("b").FirstOrDefault(f => f.InnerText.Contains("Staffelpack"));

            if (staffelpackElement != null)
            {
                var parentSpan = staffelpackElement.NavigateToElementOfType("span", Model.Enumerations.HtmlNavigationType.Parent);
                var nextBlock  = parentSpan.NavigateToElementOfType("b", Model.Enumerations.HtmlNavigationType.NextSibling);

                var linkElement = nextBlock.Descendants("a").First();

                var link = linkElement.Attributes["href"].Value;
                seasonPackEntry = new DownloadEntry(downloadContext.Name, link, Constants.DOWNLOADENTRYTITLE_SEASONPACK, GetLastThreadUpdate(threadHtmlNode), true);
                return(true);
            }

            seasonPackEntry = null;
            return(false);
        }
Beispiel #22
0
        public void AddEntry(CASResult blte)
        {
            if (CASContainer.EncodingHandler.EKeys.ContainsKey(blte.EKey))             // skip existing
            {
                return;
            }

            var entry = new DownloadEntry()
            {
                EKey     = blte.EKey,
                FileSize = blte.CompressedSize - 30,
                Flags    = new DownloadFlags[Header.NumFlags],
                Priority = (byte)(blte.HighPriority ? 0 : 1)
            };

            if (Header.HasChecksum != 0)
            {
                //entry.Checksum =
            }

            int index = endofStageIndex[entry.Priority];

            if (index >= 0)
            {
                endofStageIndex[entry.Priority]++;

                Entries.Insert(index, entry);

                foreach (var tag in Tags)
                {
                    tag.BitMask.Insert(index, tag.Name != "Alternate");
                }
            }
            else
            {
                Entries.Add(entry);

                foreach (var tag in Tags)
                {
                    tag.BitMask.Add(tag.Name != "Alternate");
                }
            }
        }
        private bool TryReadingSeasonPack(HtmlNode threadHtmlNode, DownloadContext downloadContext, out DownloadEntry seasonPackEntry)
        {
            var seasonPackSpan = threadHtmlNode.Descendants("span").FirstOrDefault(f => f.InnerText == "Staffel");

            if (seasonPackSpan != null)
            {
                var parentSpan = seasonPackSpan.NavigateToElementOfType("span", Model.Enumerations.HtmlNavigationType.Parent);
                if (parentSpan != null)
                {
                    var uploadedLink = parentSpan.NavigateToElement(f => f.Name == "a" && f.InnerText.ContainsCaseInsensitive("Uploaded"), Model.Enumerations.HtmlNavigationType.NextSibling);
                    if (uploadedLink != null)
                    {
                        var link = uploadedLink.Attributes["href"].Value;
                        seasonPackEntry = new DownloadEntry(downloadContext.Name, link, Constants.DOWNLOADENTRYTITLE_SEASONPACK, GetLastThreadUpdate(threadHtmlNode), true);
                        return(true);
                    }
                }
            }

            seasonPackEntry = null;
            return(false);
        }
Beispiel #24
0
        public DownloadProgress(string currentDownloadID)
        {
            InitializeComponent();
            SourceInitialized += OnSourceInitialized;

            downloadData = Downloads.DownloadEntries.Where(download => download.DownloadID == currentDownloadID).FirstOrDefault();

            currentDownload = Mackerel.currentDownloads[downloadData.DownloadID];

            currentDownload.ResumablityChanged += CurrentDownload_ResumablityChanged;
            currentDownload.ProgressChanged    += CurrentDownload_ProgressChanged;
            currentDownload.Completed          += CurrentDownload_Completed;
            currentDownload.Error += CurrentDownload_Error;

            //set temporary values before download starts
            this.Title        = downloadData.FileName;
            FileSize.Text     = Helper.SizeSuffix(downloadData.Size, 3);
            Downloaded.Text   = "Checking...";
            TransferRate.Text = "(Unknown)";
            TimeLeft.Text     = "(Unknown)";


            DownloadLink.Text = downloadData.DownloadLink.ToString();
            Status.Text       = "Connecting...";

            FileSize.Text = Helper.SizeSuffix(downloadData.Size, 3) != null?Helper.SizeSuffix(downloadData.Size, 3) : "Unknown";

            // enables Mackerel class to stop downloads just by setting downloadData.Running value to false
            Downloads.DownloadEntries.ListChanged += delegate
            {
                if (!downloadData.Running && !currentDownload.Stop)
                {
                    currentDownload.StopDownload();
                    downloadData.TransferRate = null;
                    Close();
                }
            };
        }
Beispiel #25
0
 private Task GetUpdaterDefinition()
 {
     return(Task.Run(() =>
     {
         try
         {
             var downloadEntry = new DownloadEntry(
                 Settings.GetRemoteUpdaterIndexUrl(),
                 Settings.GetRemoteUpdaterIndexUrl().Replace(Settings.RemoteUrl, string.Empty),
                 null,
                 null,
                 null
                 );
             CurrentUpdaterDefinition =
                 Downloader.DownloadJson <UpdaterDefinition>(downloadEntry, Serializer);
         }
         catch (Exception e)
         {
             CurrentUpdaterDefinition = null;
             Logger.Warning("No updater definition found. Problem: {UpdaterDefinitionException}", e);
         }
     }));
 }
        public DownloadProgress(string currentDownloadID)
        {
            InitializeComponent();
            SourceInitialized += OnSourceInitialized;

            downloadData = Downloads.DownloadEntries.Where(download => download.DownloadID == currentDownloadID).FirstOrDefault();

            currentDownload = Mackerel.currentDownloads[downloadData.DownloadID];

            currentDownload.ResumablityChanged += CurrentDownload_ResumablityChanged;
            currentDownload.ProgressChanged += CurrentDownload_ProgressChanged;
            currentDownload.Completed += CurrentDownload_Completed;
            currentDownload.Error += CurrentDownload_Error;

            //set temporary values before download starts
            this.Title = downloadData.FileName;
            FileSize.Text = Helper.SizeSuffix(downloadData.Size, 3);
            Downloaded.Text = "Checking...";
            TransferRate.Text = "(Unknown)";
            TimeLeft.Text = "(Unknown)";

            DownloadLink.Text = downloadData.DownloadLink.ToString();
            Status.Text = "Connecting...";

            FileSize.Text = Helper.SizeSuffix(downloadData.Size, 3) != null ? Helper.SizeSuffix(downloadData.Size, 3) : "Unknown";

            // enables Mackerel class to stop downloads just by setting downloadData.Running value to false
            Downloads.DownloadEntries.ListChanged += delegate
            {
                if (!downloadData.Running && !currentDownload.Stop)
                {
                    currentDownload.StopDownload();
                    downloadData.TransferRate = null;
                    Close();
                }
            };
        }
Beispiel #27
0
        public async void DownloadAllTorrents(object state)
        {
            var items = (await _nyaaWrapper.ParseProvidersSubsAsync());

            try
            {
                items.ToList().ForEach(x =>
                {
                    MessageBox.Show(x.Title);
                    // If the item doesn't already exist in the downloader queue.
                    if (!_downloaderViewModel.DownloadList.ToList().Exists(z => z.Title == $"{x.Title} - {x.Episode} - [{x.Quality}]"))
                    {
                        // If the episode exists in our "should download list"
                        if (_settingsViewModel.DownloadList.ToList().Exists(y => y.Title == x.Title && y.Quality == x.Quality))
                        {
                            var item = new DownloadEntry()
                            {
                                Title          = $"{x.Title} - {x.Episode} - [{x.Quality}]",
                                Size           = x.TorrentSize,
                                TorrentManager = _downloadManager.AddTorrentUrl(x.TorrentURL),
                            };
                            _downloaderViewModel.DownloadList.Add(new DownloadEntryViewModel(item));

                            // If the downloader is started, start downloading the episode.
                            if (!_downloaderViewModel.Paused)
                            {
                                item.TorrentManager.Start();
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public async Task <IDisposable> LockForAsset(CancellationToken ct, string updatedPath)
        {
            DownloadEntry GetEntry()
            {
                lock (_assetsGate)
                {
                    if (!_assetsGate.TryGetValue(updatedPath, out var entry))
                    {
                        _assetsGate[updatedPath] = entry = new DownloadEntry();
                    }

                    entry.ReferenceCount++;

                    return(entry);
                }
            }

            var entry = GetEntry();

            var disposable = await entry.Gate.LockAsync(ct);

            void ReleaseEntry()
            {
                lock (_assetsGate)
                {
                    disposable.Dispose();

                    if (--entry.ReferenceCount == 0)
                    {
                        _assetsGate.Remove(updatedPath);
                    }
                }
            }

            return(Disposable.Create(ReleaseEntry));
        }
Beispiel #29
0
        private bool TryGettingPersistedConfigurationEntry(IReadOnlyCollection <DownloadEntryConfiguration> persistedConfigurationEntries, DownloadEntry downloadEntry, out DownloadEntryConfiguration configEntry)
        {
            // We pririorize the LinkIdentifier, but use the ShortTitle for the backword-compatibility
            configEntry = persistedConfigurationEntries.FirstOrDefault(f => f.DownloadLinkIdentifier == downloadEntry.DownloadLinkIdentifier);
            if (configEntry == null)
            {
                configEntry = persistedConfigurationEntries.FirstOrDefault(f => f.Title == downloadEntry.DownloadEntryTitleShort);
            }

            return(configEntry != null);
        }
Beispiel #30
0
        public MainWindowViewModel()
        {
            _configFile = new IniFile();
            // View model data.
            _settingsViewModel   = new SettingsViewModel(new Settings(), _configFile);
            _aboutViewModel      = new AboutViewModel(new Todo());
            _downloaderViewModel = new DownloaderViewModel(new Downloader()
            {
                Paused = false
            });

            CurrentViewModel = _settingsViewModel;

            // Initializing the downloader.

            _downloadManager = new DownloadManager.Manager();
            _downloadManager.SetConfigPath();
            _downloadManager.SetDownloadPath();
            _downloadManager.SetTorrentsPath();
            _downloadManager.InitializeEngine();

            // Instantiating Nyaa wrapper.
            _nyaaWrapper = new DownloadManager.NyaaWrapper();

            // To check for the download state change.
            _downloaderViewModel.PropertyChanged += _downloaderViewModel_PropertyChanged;
            _settingsViewModel.PropertyChanged   += _settingsViewModel_PropertyChanged;

            // Close application command
            closeApplication = new DelegateCommand(o =>
            {
                _settingsViewModel.SaveSettings();
                if (_settingsViewModel.MinimizeOnExit)
                {
                    CurrentWindowState = WindowState.Minimized;
                }
                else
                {
                    try
                    {
                        _downloadManager.ShutdownEngine();
                        Environment.Exit(0);
                    } catch
                    {
                        Environment.Exit(0);
                    }
                }
            });

            // The periodically timer check for new episodes.
            checkForNewEpisodes_timer = new Timer(DownloadAllTorrents, null, timerCheckInterval, timerCheckInterval);

            foreach (var file in System.IO.Directory.GetFiles("Downloads"))
            {
                if (file.EndsWith(".torrent"))
                {
                    var item = new DownloadEntry()
                    {
                        TorrentManager = _downloadManager.AddTorrentFile(file),
                    };
                    _downloaderViewModel.DownloadList.Add(new DownloadEntryViewModel(item));
                    item.Title = item.TorrentManager.Torrent.Files[0].Path;
                    item.Size  = "0";
                }
            }
        }
        private static FrameworkElement ConvertDownloadEntry(DownloadEntry entry)
        {
            var cellPadding = new Thickness(5, 10, 5, 15);

            var title = new TextBlock
            {
                Text   = entry.ToString(),
                Margin = new Thickness(cellPadding.Left, cellPadding.Top, cellPadding.Right, 0)
            };

            Grid.SetRow(title, 0);
            Grid.SetColumn(title, 1);

            var hyperlink = new Hyperlink
            {
                Inlines     = { new Run(entry.FullUrl) },
                NavigateUri = new Uri(entry.FullUrl)
            };

            var link = new TextBlock(hyperlink)
            {
                FontSize = 11,
                Margin   = new Thickness(cellPadding.Left, 0, cellPadding.Right, cellPadding.Bottom)
            };

            Grid.SetRow(link, 1);
            Grid.SetColumn(link, 1);

            var radioButton = new RadioButton
            {
                GroupName = "download",
                Margin    = cellPadding
            };

            var grid = new Grid
            {
                RowDefinitions =
                {
                    new RowDefinition(),
                    new RowDefinition()
                },
                ColumnDefinitions =
                {
                    new ColumnDefinition
                    {
                        Width = GridLength.Auto
                    },
                    new ColumnDefinition()
                },

                Children =
                {
                    radioButton,
                    title,
                    link
                }
            };

            grid.MouseDown += (sender, args) =>
            {
                radioButton.IsChecked = true;

                SelectionChanged?.Invoke(entry);
            };
            grid.MouseEnter += (sender, args) => grid.Background = new SolidColorBrush(Color.FromArgb(36, 0, 0, 0));
            grid.MouseLeave += (sender, args) => grid.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));

            return(grid);
        }
Beispiel #32
0
 private static void SetExecutionStatus(Feed feed, DownloadEntry entry)
 {
     feed.ExecutionStatus = entry.ExecutionStatus;
     if (feed.ExecutionStatus==  ExecutionStatus.Deleted) feed.DownloadState = DownloadState.Deleted;
 }
Beispiel #33
0
        public DownloadHandler(BLTEStream blte)
        {
            if (CASContainer.BuildConfig["download-size"][0] != null && blte.Length != long.Parse(CASContainer.BuildConfig["download-size"][0]))
            {
                CASContainer.Settings?.Logger.LogAndThrow(Logging.LogType.Critical, "Download File is corrupt.");
            }

            using (var br = new BinaryReader(blte))
            {
                Header = new DownloadHeader()
                {
                    Header       = br.ReadBytes(2),
                    Version      = br.ReadByte(),
                    ChecksumSize = br.ReadByte(),
                    HasChecksum  = br.ReadByte(),
                    NumEntries   = br.ReadUInt32BE(),
                    NumTags      = br.ReadUInt16BE(),
                };

                if (Header.Version >= 2)
                {
                    Header.NumFlags = br.ReadByte();
                }

                if (Header.Version >= 3)
                {
                    // TODO do we have a version 3 file to test with?
                    //Header.BasePriority = br.ReadByte();
                    //Header.Unknown_0D = br.ReadBytes(3);
                    throw new NotImplementedException("Download file versions newer than 2 are not supported.");
                }

                // entries
                for (int i = 0; i < Header.NumEntries; i++)
                {
                    var entry = new DownloadEntry()
                    {
                        EKey     = new MD5Hash(br),
                        FileSize = br.ReadUInt40BE(),
                        Priority = br.ReadByte()
                    };

                    if (Header.HasChecksum != 0)
                    {
                        entry.Checksum = br.ReadUInt32BE();
                    }

                    if (Header.Version >= 2)
                    {
                        entry.Flags = (DownloadFlags[])(object)br.ReadBytes(Header.NumFlags);
                    }

                    Entries.Add(entry);
                }

                // tags
                int numMaskBytes = ((int)Header.NumEntries + 7) / 8;
                for (int i = 0; i < Header.NumTags; i++)
                {
                    var tag = new DownloadTag()
                    {
                        Name    = br.ReadCString(),
                        Type    = br.ReadUInt16BE(),
                        BitMask = new BoolArray(br.ReadBytes(numMaskBytes))
                    };

                    // We need to remove trailing bits from the padded byte array.
                    while (tag.BitMask.Count != Entries.Count)
                    {
                        tag.BitMask.RemoveAt(tag.BitMask.Count - 1);
                    }

                    Tags.Add(tag);
                }

                EncodingMap = blte.EncodingMap.ToArray();

                endofStageIndex = new int[]                 // store last indice of each stage
                {
                    Entries.FindLastIndex(x => x.Priority == 0),
                    Entries.FindLastIndex(x => x.Priority == 1)
                };
            }

            blte?.Dispose();
        }
Beispiel #34
0
 public bool FillDownloadLists(DownloadLists lists)
 {
     try {
         lists.Entries.Clear();
         DownloadEntry listsEntry;
         if (!File.Exists(_downloadsFile))
             listsEntry = new DownloadEntry();
         else
             using (var file = new StreamReader(_downloadsFile))
                 listsEntry = JsonConvert.DeserializeObject<DownloadEntry>(file.ReadToEnd());
         if (listsEntry.List != null && listsEntry.List.Count > 0) {
             foreach (var itemList in listsEntry.List) {
                 var youtubeEntries = new List<YoutubeEntry>();
                 var mediaType = itemList.MediaType;
                 Uri uri;
                 var youtubeListEntry =
                     YoutubeEntry.Create(Uri.TryCreate(itemList.Url, UriKind.Absolute, out uri) ? uri : null);
                 youtubeListEntry.Title = itemList.Title;
                 SetExecutionStatus(youtubeListEntry, itemList);
                 youtubeListEntry.ThumbnailUrl = itemList.ThumbnailUrl;
                 foreach (var item in itemList.List) {
                     var youtubeEntry = YoutubeEntry.Create(new Uri(item.Url), youtubeListEntry);
                     youtubeEntry.ThumbnailUrl = item.ThumbnailUrl;
                     youtubeEntry.Title = item.Title;
                     SetExecutionStatus(youtubeEntry, item);
                     youtubeEntries.Add(youtubeEntry);
                 }
                 if (youtubeEntries.Count > 0)
                     lists.SoftAdd(youtubeEntries, mediaType);
             }
         }
         return true;
     }
     catch {
         return false;
     }
 }