private void DownloadThread()
{
var random = new Random();
int round = 0;
for (;;)
{
Thread.Sleep(1000 * 1);
if (this.State == ManagerState.Stop) return;
DownloadItem item = null;
try
{
lock (_thisLock)
{
if (_settings.DownloadItems.Count > 0)
{
{
var items = _settings.DownloadItems
.Where(n => n.State == DownloadState.Downloading)
.Where(n => n.Priority != 0)
.Where(x =>
{
if (x.Depth == 1) return 0 == (!_cacheManager.Contains(x.Seed.Metadata.Key) ? 1 : 0);
else return 0 == (x.Index.Groups.Sum(n => n.InformationLength) - x.Index.Groups.Sum(n => Math.Min(n.InformationLength, _existManager.GetCount(n))));
})
.ToList();
item = items.FirstOrDefault();
}
if (item == null)
{
var items = _settings.DownloadItems
.Where(n => n.State == DownloadState.Downloading)
.Where(n => n.Priority != 0)
.OrderBy(n => -n.Priority)
.ToList();
if (items.Count > 0)
{
round = (round >= items.Count) ? 0 : round;
item = items[round++];
}
}
}
}
}
catch (Exception)
{
return;
}
if (item == null) continue;
try
{
if (item.Depth == 1)
{
if (!_cacheManager.Contains(item.Seed.Metadata.Key))
{
item.State = DownloadState.Downloading;
_connectionsManager.Download(item.Seed.Metadata.Key);
}
else
{
item.State = DownloadState.Decoding;
}
}
else
{
if (!item.Index.Groups.All(n => _existManager.GetCount(n) >= n.InformationLength))
{
item.State = DownloadState.Downloading;
var limitCount = (int)(256 * Math.Pow(item.Priority, 3));
foreach (var group in item.Index.Groups.ToArray().Randomize())
{
if (_existManager.GetCount(group) >= group.InformationLength) continue;
foreach (var key in _existManager.GetKeys(group, false))
{
if (_connectionsManager.IsDownloadWaiting(key))
{
limitCount--;
if (limitCount <= 0) goto End;
}
}
}
foreach (var group in item.Index.Groups.ToArray().Randomize())
{
if (_existManager.GetCount(group) >= group.InformationLength) continue;
var tempKeys = new List<Key>();
foreach (var key in _existManager.GetKeys(group, false))
{
if (!_connectionsManager.IsDownloadWaiting(key))
{
tempKeys.Add(key);
}
}
random.Shuffle(tempKeys);
foreach (var key in tempKeys)
{
_connectionsManager.Download(key);
limitCount--;
}
if (limitCount <= 0) goto End;
}
End:;
}
else
{
item.State = DownloadState.ParityDecoding;
}
}
}
catch (Exception e)
{
item.State = DownloadState.Error;
Log.Error(e);
}
}
}