Ejemplo n.º 1
0
        public async Task GetListOfPackageVersions(InterceptCallContext context, string id)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] GetListOfPackageVersions: {0}", id), ConsoleColor.Magenta);

            JObject resolverBlob = await FetchJson(context, MakeResolverAddress(id));

            JArray array = new JArray();

            // the package may not exist, in that case return an empty array
            if (resolverBlob != null)
            {
                List <NuGetVersion> versions = new List <NuGetVersion>();
                foreach (JToken package in resolverBlob["packages"])
                {
                    NuGetVersion version = NuGetVersion.Parse(package["version"].ToString());

                    // all versions are returned, filter to only stable if needed
                    if (context.Args.IncludePrerelease || !version.IsPrerelease)
                    {
                        versions.Add(version);
                    }
                }

                versions.Sort();

                foreach (NuGetVersion version in versions)
                {
                    array.Add(version.ToString());
                }
            }

            await context.WriteResponse(array);
        }
Ejemplo n.º 2
0
        public IEnumerable <JToken> GetListAvailableDataStart(InterceptCallContext context, JObject index)
        {
            string skipTo = null;

            if (context.Args.SkipToken != null)
            {
                var skipToken = ParseSkipToken(context.Args.SkipToken);
                skipTo = skipToken.Item1;
            }
            else if (context.Args.FilterStartsWithId != null)
            {
                skipTo = context.Args.FilterStartsWithId;
            }
            if (context.Args.PartialId != null) // intellisense
            {
                skipTo = context.Args.PartialId;
            }

            var segments = GetListAvailableSegmentsIncludingAndAfter(context, index, skipTo);

            foreach (var segUrl in segments)
            {
                var dataTask = FetchJson(context, new Uri(segUrl));
                dataTask.Wait();
                var data = dataTask.Result;

                var orderedData = data["entry"].OrderBy(e => e["id"].ToString(), StringComparer.InvariantCultureIgnoreCase)
                                  .ThenBy(e => new NuGetVersion(e["version"].ToString()), VersionComparer.VersionRelease);

                foreach (var entry in orderedData)
                {
                    yield return(entry);
                }
            }
        }
Ejemplo n.º 3
0
        private async Task SearchImpl(InterceptCallContext context, string feed = null)
        {
            int skip = context.Args.Skip ?? 0;
            int take = context.Args.Top ?? 30;

            await _channel.Search(context, context.Args.SearchTerm, context.Args.IsLatestVersion, context.Args.TargetFramework, context.Args.IncludePrerelease, skip, take, feed);
        }
Ejemplo n.º 4
0
        private async Task Feed_FindPackagesById(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Feed_FindPackagesById", ConsoleColor.Green);
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] feed: {0}", ExtractFeed(context.RequestUri.AbsolutePath)), ConsoleColor.DarkGreen);

            await _channel.GetAllPackageVersions(context, context.Args.Id);
        }
Ejemplo n.º 5
0
        public async Task GetListOfPackages(InterceptCallContext context)
        {
            context.Log("[V3 CALL] GetListOfPackages", ConsoleColor.Magenta);

            var index = await FetchJson(context, context.Args.IncludePrerelease?new Uri(_listAvailableLatestPrereleaseIndex) : new Uri(_listAvailableLatestStableIndex));

            var data = GetListAvailableDataStart(context, index);

            // apply startswith if needed
            if (context.Args.PartialId != null)
            {
                data = data.Where(e => e["id"].ToString().StartsWith(context.Args.PartialId, StringComparison.OrdinalIgnoreCase));

                data = data.TakeWhile(e => e["id"].ToString().StartsWith(context.Args.PartialId, StringComparison.OrdinalIgnoreCase));
            }

            // take only 30
            var ids = data.Take(30).Select(p => p["id"].ToString()).ToList();

            ids.Sort(StringComparer.InvariantCultureIgnoreCase);

            JArray array = new JArray();

            foreach (var id in ids)
            {
                array.Add(id);
            }

            await context.WriteResponse(array);
        }
Ejemplo n.º 6
0
        public async Task DownloadPackage(InterceptCallContext context, string id, string version)
        {
            JToken package = await GetPackageCore(context, id, version);

            if (package == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "unable to find version {0} of package {1}", version, id));
            }

            string address = package["nupkgUrl"].ToString();

            context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 PKG] {0}", address.ToString()), ConsoleColor.Cyan);

            Stopwatch timer = new Stopwatch();

            timer.Start();

            System.Net.Http.HttpClient client   = new System.Net.Http.HttpClient();
            HttpResponseMessage        response = await client.GetAsync(address);

            byte[] data = await response.Content.ReadAsByteArrayAsync();

            timer.Stop();

            context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 PKG] (status:{0}) (time:{1}ms) {2}", response.StatusCode, timer.ElapsedMilliseconds, address.ToString()),
                        response.StatusCode == System.Net.HttpStatusCode.OK ? ConsoleColor.Cyan : ConsoleColor.Red);

            await context.WriteResponse(data, "application/zip");
        }
Ejemplo n.º 7
0
        public async Task Metadata(InterceptCallContext context, string feed = null)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] Metadata: {0}", feed ?? string.Empty), ConsoleColor.Magenta);

            Stream   stream = GetResourceStream(feed == null ? "xml.Metadata.xml" : "xml.FeedMetadata.xml");
            XElement xml    = XElement.Load(stream);
            await context.WriteResponse(xml);
        }
Ejemplo n.º 8
0
        private async Task Feed_Search(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Feed_Search", ConsoleColor.Green);
            string feed = ExtractFeed(context.RequestUri.AbsolutePath);

            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] feed: {0}", feed), ConsoleColor.DarkGreen);
            await SearchImpl(context, feed);
        }
Ejemplo n.º 9
0
        private async Task Packages(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Packages", ConsoleColor.Green);

            string path  = Uri.UnescapeDataString(context.RequestUri.AbsolutePath);
            string query = context.RequestUri.Query;

            await GetPackage(context, path, query);
        }
Ejemplo n.º 10
0
        private async Task PackageVersions(InterceptCallContext context)
        {
            context.Log("[V3 CALL] PackageVersions", ConsoleColor.Green);

            string path = context.RequestUri.AbsolutePath;
            string id   = path.Substring(path.LastIndexOf("/") + 1);

            await _channel.GetListOfPackageVersions(context, id);
        }
Ejemplo n.º 11
0
        public async Task ListAvailable(InterceptCallContext context)
        {
            string indexUrl = _listAvailableLatestStableIndex;

            if (!context.Args.IsLatestVersion)
            {
                indexUrl = _listAvailableAllIndex;
            }
            else if (context.Args.IncludePrerelease)
            {
                indexUrl = _listAvailableLatestPrereleaseIndex;
            }

            var index = await FetchJson(context, new Uri(indexUrl));

            var data = GetListAvailableData(context, index);

            // all versions with no pre
            if (!context.Args.IsLatestVersion && !context.Args.IncludePrerelease)
            {
                data = data.Where(p => (new NuGetVersion(p["version"].ToString())).IsPrerelease == false);
            }

            string nextUrl = null;

            // Convert to a list after calling Take to avoid enumerating the list multiple times.

            if (context.Args.Top.HasValue && context.Args.Top.Value > 0)
            {
                data = data.Take(context.Args.Top.Value).ToList();
            }
            else
            {
                data = data.Take(30).ToList();

                if (data.Count() >= 30)
                {
                    var last = data.LastOrDefault();

                    if (last != null)
                    {
                        string argsWithoutSkipToken = String.Join("&", context.Args.Arguments.Where(a => a.Key.ToLowerInvariant() != "$skiptoken")
                                                                  .Select(a => String.Format(CultureInfo.InvariantCulture, "{0}={1}", a.Key, a.Value)));

                        nextUrl = String.Format(CultureInfo.InvariantCulture, "{0}?{1}&$skiptoken='{2}','{2}','{3}'",
                                                context.RequestUri.AbsoluteUri.Split('?')[0],
                                                argsWithoutSkipToken,
                                                last["id"],
                                                last["version"]);
                    }
                }
            }

            XElement feed = InterceptFormatting.MakeFeed(_passThroughAddress, "Packages", data, data.Select(e => e["id"].ToString()).ToArray(), nextUrl);
            await context.WriteResponse(feed);
        }
Ejemplo n.º 12
0
        public async Task SearchCount(InterceptCallContext context, string searchTerm, bool isLatestVersion, string targetFramework, bool includePrerelease, int skip, int take, string feedName)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] SearchCount: {0}", searchTerm), ConsoleColor.Magenta);

            JObject obj = await FetchJson(context, MakeSearchAddress(searchTerm, isLatestVersion, targetFramework, includePrerelease, skip, take, feedName));

            string count = obj != null ? count = obj["totalHits"].ToString() : "0";

            await context.WriteResponse(count);
        }
Ejemplo n.º 13
0
        public async Task Search(InterceptCallContext context, string searchTerm, bool isLatestVersion, string targetFramework, bool includePrerelease, int skip, int take, string feedName)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] Search: {0} ({1},{2})", searchTerm, skip, take), ConsoleColor.Magenta);

            JObject obj = await FetchJson(context, MakeSearchAddress(searchTerm, isLatestVersion, targetFramework, includePrerelease, skip, take, feedName));

            IEnumerable <JToken> data = (obj != null) ? data = obj["data"] : Enumerable.Empty <JToken>();

            XElement feed = InterceptFormatting.MakeFeedFromSearch(_source, _passThroughAddress, "Packages", data, "");
            await context.WriteResponse(feed);
        }
Ejemplo n.º 14
0
        public IEnumerable <JToken> GetListAvailableData(InterceptCallContext context, JObject index)
        {
            var data = GetListAvailableFastForwardSkipToken(context, index);

            // apply startswith if needed
            if (context.Args.FilterStartsWithId != null)
            {
                data = data.Where(e => e["id"].ToString().StartsWith(context.Args.FilterStartsWithId, StringComparison.OrdinalIgnoreCase));

                data = data.TakeWhile(e => e["id"].ToString().StartsWith(context.Args.FilterStartsWithId, StringComparison.OrdinalIgnoreCase));
            }

            return(data);
        }
Ejemplo n.º 15
0
        public async Task <List <JObject> > GetUpdatesCore(InterceptCallContext context, string[] packageIds, string[] versions, string[] versionConstraints, string[] targetFrameworks, bool includePrerelease, bool includeAllVersions)
        {
            List <JObject> packages = new List <JObject>();

            for (int i = 0; i < packageIds.Length; i++)
            {
                VersionRange range = null;

                if (i < versionConstraints.Length && !String.IsNullOrEmpty(versionConstraints[i]))
                {
                    VersionRange.TryParse(versionConstraints[i], out range);
                }

                JObject resolverBlob = await FetchJson(context, MakeResolverAddress(packageIds[i]));

                // TODO: handle this error
                if (resolverBlob != null)
                {
                    // this can be null if all packages are prerelease
                    JObject latest = ExtractLatestVersion(resolverBlob, includePrerelease, range) as JObject;
                    if (latest != null)
                    {
                        // add the id if it isn't there
                        if (latest["id"] == null)
                        {
                            latest.Add("id", JToken.Parse("'" + packageIds[i] + "'"));
                        }

                        if (i < versions.Length && !String.IsNullOrEmpty(versions[i]))
                        {
                            NuGetVersion latestVersion  = NuGetVersion.Parse(latest["version"].ToString());
                            NuGetVersion currentVersion = NuGetVersion.Parse(versions[i]);

                            // only add the package if it is not the latest version
                            if (VersionComparer.VersionRelease.Compare(latestVersion, currentVersion) > 0)
                            {
                                packages.Add(latest);
                            }
                        }
                        else
                        {
                            packages.Add(latest);
                        }
                    }
                }
            }

            return(packages);
        }
Ejemplo n.º 16
0
        private async Task Feed_Packages(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Feed_Packages", ConsoleColor.Green);
            string feed = ExtractFeed(context.RequestUri.AbsolutePath);

            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] feed: {0}", feed), ConsoleColor.DarkGreen);

            string path = Uri.UnescapeDataString(context.RequestUri.AbsolutePath);

            path = path.Substring(path.IndexOf(feed) + feed.Length + 1);

            string query = context.RequestUri.Query;

            await GetPackage(context, path, query, feed);
        }
Ejemplo n.º 17
0
        public async Task GetPackage(InterceptCallContext context, string id, string version, string feedName)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] GetPackage: {0} {1}", id, version), ConsoleColor.Magenta);

            var desiredPackage = await GetPackageCore(context, id, version);

            if (desiredPackage == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "unable to find version {0} of package {1}", version, id));
            }

            XElement feed = InterceptFormatting.MakeFeed(_passThroughAddress, "Packages", new List <JToken> {
                desiredPackage
            }, id);
            await context.WriteResponse(feed);
        }
Ejemplo n.º 18
0
        private async Task GetUpdates(InterceptCallContext context)
        {
            context.Log("[V3 CALL] GetUpdates", ConsoleColor.Green);

            IDictionary <string, string> arguments = context.Args.Arguments;

            string[] packageIds         = Uri.UnescapeDataString(arguments["packageIds"]).Trim('\'').Split('|');
            string[] versions           = Uri.UnescapeDataString(arguments["versions"]).Trim('\'').Split('|');
            string[] versionConstraints = Uri.UnescapeDataString(arguments["versionConstraints"]).Trim('\'').Split('|');
            string[] targetFrameworks   = Uri.UnescapeDataString(arguments["targetFrameworks"]).Trim('\'').Split('|');
            bool     includeAllVersions = false;

            bool.TryParse(arguments["includeAllVersions"], out includeAllVersions);

            await _channel.GetUpdates(context, packageIds, versions, versionConstraints, targetFrameworks, context.Args.IncludePrerelease, includeAllVersions, context.Args.Count);
        }
Ejemplo n.º 19
0
        public async Task GetUpdates(InterceptCallContext context, string[] packageIds, string[] versions, string[] versionConstraints, string[] targetFrameworks, bool includePrerelease, bool includeAllVersions, bool count = false)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] GetUpdates{1}: {0}", string.Join("|", packageIds), count ? "Count" : string.Empty), ConsoleColor.Magenta);

            var packages = await GetUpdatesCore(context, packageIds, versions, versionConstraints, targetFrameworks, includePrerelease, includeAllVersions);

            if (count)
            {
                await context.WriteResponse(packages.Count);
            }
            else
            {
                XElement feed = InterceptFormatting.MakeFeed(_passThroughAddress, "GetUpdates", packages, packages.Select(p => p["id"].ToString()).ToArray());
                await context.WriteResponse(feed);
            }
        }
Ejemplo n.º 20
0
        public IEnumerable <JToken> GetListAvailableFastForwardSkipToken(InterceptCallContext context, JObject index)
        {
            var data = GetListAvailableDataStart(context, index);

            if (context.Args.SkipToken != null)
            {
                var skipToken    = ParseSkipToken(context.Args.SkipToken);
                var skipTokenId  = skipToken.Item1;
                var skipTokenVer = new NuGetVersion(skipToken.Item2);

                data = data.Where(e => skipTokenId == null || StringComparer.InvariantCultureIgnoreCase.Compare(e["id"].ToString(), skipTokenId) > 0 ||
                                  (StringComparer.InvariantCultureIgnoreCase.Equals(e["id"].ToString(), skipTokenId) &&
                                   (skipTokenVer == null || VersionComparer.VersionRelease.Compare(new NuGetVersion(e["version"].ToString()), skipTokenVer) > 0)));
            }

            return(data);
        }
Ejemplo n.º 21
0
        private async Task DownloadPackage(InterceptCallContext context)
        {
            context.Log("[V3 CALL] DownloadPackage", ConsoleColor.Green);

            var urlParts = new List <string>(context.RequestUri.AbsoluteUri.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries));

            urlParts.Reverse();

            if (urlParts.Count > 3 && StringComparer.OrdinalIgnoreCase.Equals("package", urlParts[2]))
            {
                await _channel.DownloadPackage(context, urlParts[1], urlParts[0]);
            }
            else
            {
                throw new ShimException("Invalid download url: " + context.RequestUri.ToString());
            }
        }
Ejemplo n.º 22
0
        private async Task FindPackagesById(InterceptCallContext context)
        {
            context.Log("[V3 CALL] FindPackagesById", ConsoleColor.Green);

            if (context.Args.Id == null)
            {
                throw new ShimException("unable to find id in query string");
            }

            if (context.Args.IsLatestVersion)
            {
                await _channel.GetLatestVersionPackage(context, context.Args.Id, context.Args.IncludePrerelease);
            }
            else
            {
                await _channel.GetAllPackageVersions(context, context.Args.Id);
            }
        }
Ejemplo n.º 23
0
        public async Task GetAllPackageVersions(InterceptCallContext context, string id)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] GetAllPackageVersions: {0}", id), ConsoleColor.Magenta);

            var ids = id.Split(new string[] { " or " }, StringSplitOptions.RemoveEmptyEntries);

            List <JToken> packages = new List <JToken>();

            foreach (var s in ids)
            {
                string curId = s.Trim('\'');

                if (curId.StartsWith("tolower(id) eq '"))
                {
                    curId = curId.Split('\'')[1];
                }

                // TODO: run in parallel
                JObject resolverBlob = await FetchJson(context, MakeResolverAddress(curId));

                if (resolverBlob == null)
                {
                    throw new InvalidOperationException(string.Format("package {0} not found", curId));
                }

                foreach (var p in resolverBlob["packages"])
                {
                    NuGetVersion version = NuGetVersion.Parse(p["version"].ToString());

                    // all versions are returned, filter to only stable if needed
                    if (context.Args.IncludePrerelease || !version.IsPrerelease)
                    {
                        p["id"] = resolverBlob["id"];

                        packages.Add(p);
                    }
                }
            }

            var data = packages.OrderBy(p => p["id"].ToString()).ThenByDescending(p => NuGetVersion.Parse(p["version"].ToString()), VersionComparer.VersionRelease);

            XElement feed = InterceptFormatting.MakeFeed(_passThroughAddress, "Packages", data, data.Select(p => p["id"].ToString()).ToArray());
            await context.WriteResponse(feed);
        }
Ejemplo n.º 24
0
        public async Task Root(InterceptCallContext context, string feedName = null)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] Root: {0}", feedName ?? string.Empty), ConsoleColor.Magenta);

            if (feedName == null)
            {
                Stream   stream = GetResourceStream("xml.Root.xml");
                XElement xml    = XElement.Load(stream);
                await context.WriteResponse(xml);
            }
            else
            {
                Stream   stream = GetResourceStream("xml.FeedRoot.xml");
                string   s      = (new StreamReader(stream)).ReadToEnd();
                string   t      = string.Format(s, feedName);
                XElement xml    = XElement.Load(new StringReader(t), LoadOptions.SetBaseUri);
                await context.WriteResponse(xml);
            }
        }
Ejemplo n.º 25
0
        public async Task Root(InterceptCallContext context, string feedName = null)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] Root: {0}", feedName ?? string.Empty), ConsoleColor.Magenta);

            if (feedName == null)
            {
                Stream stream = GetResourceStream("xml.Root.xml");
                XElement xml = XElement.Load(stream);
                await context.WriteResponse(xml);
            }
            else
            {
                Stream stream = GetResourceStream("xml.FeedRoot.xml");
                string s = (new StreamReader(stream)).ReadToEnd();
                string t = string.Format(s, feedName);
                XElement xml = XElement.Load(new StringReader(t), LoadOptions.SetBaseUri);
                await context.WriteResponse(xml);
            }
        }
Ejemplo n.º 26
0
        private async Task <JObject> FetchJson(InterceptCallContext context, Uri address)
        {
            string url = address.ToString().ToLowerInvariant();

            JObject fromCache = null;

            if (_cache.TryGet(address, out fromCache))
            {
                context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 CACHE] {0}", address.ToString()), ConsoleColor.DarkCyan);
                return(fromCache);
            }

            context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 REQ] {0}", address.ToString()), ConsoleColor.Cyan);

            Stopwatch timer = new Stopwatch();

            timer.Start();

            System.Net.Http.HttpClient client   = new System.Net.Http.HttpClient();
            HttpResponseMessage        response = await client.GetAsync(address);

            timer.Stop();

            context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 RES] (status:{0}) (time:{1}ms) {2}", response.StatusCode, timer.ElapsedMilliseconds, address.ToString()),
                        response.StatusCode == System.Net.HttpStatusCode.OK ? ConsoleColor.Cyan : ConsoleColor.Red);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string json = await response.Content.ReadAsStringAsync();

                JObject obj = JObject.Parse(json);

                _cache.AddOrUpdate(address, obj);

                return(obj);
            }
            else
            {
                // expected in some cases
                return(null);
            }
        }
Ejemplo n.º 27
0
        public async Task GetLatestVersionPackage(InterceptCallContext context, string id, bool includePrerelease)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] GetLatestVersionPackage: {0} {1}", id, includePrerelease ? "[include prerelease]" : ""), ConsoleColor.Magenta);

            JObject resolverBlob = await FetchJson(context, MakeResolverAddress(id));

            if (resolverBlob == null)
            {
                throw new InvalidOperationException(string.Format("package {0} not found", id));
            }

            JToken latest = ExtractLatestVersion(resolverBlob, includePrerelease);

            if (latest == null)
            {
                throw new InvalidOperationException(string.Format("package {0} not found", id));
            }

            XElement feed = InterceptFormatting.MakeFeed(_passThroughAddress, "Packages", new List <JToken> {
                latest
            }, id);
            await context.WriteResponse(feed);
        }
Ejemplo n.º 28
0
        private async Task <JToken> GetPackageCore(InterceptCallContext context, string id, string version)
        {
            JToken  desiredPackage = null;
            JObject resolverBlob   = await FetchJson(context, MakeResolverAddress(id));


            if (resolverBlob != null)
            {
                NuGetVersion desiredVersion = NuGetVersion.Parse(version);

                foreach (JToken package in resolverBlob["packages"])
                {
                    NuGetVersion currentVersion = NuGetVersion.Parse(package["version"].ToString());
                    if (currentVersion == desiredVersion)
                    {
                        desiredPackage = package;
                        break;
                    }
                }
            }

            return(desiredPackage);
        }
Ejemplo n.º 29
0
        private async Task GetPackage(InterceptCallContext context, string path, string query, string feed = null)
        {
            if (path.EndsWith("Packages()"))
            {
                if (!String.IsNullOrEmpty(context.Args.FilterId))
                {
                    await _channel.GetAllPackageVersions(context, context.Args.FilterId.ToLowerInvariant());
                }
                else
                {
                    await _channel.ListAvailable(context);
                }
            }
            else
            {
                string args = path.Substring(path.LastIndexOf('(')).Trim('(', ')');

                string id      = null;
                string version = null;

                string[] aps = args.Split(',');
                foreach (var ap in aps)
                {
                    string[] a = ap.Split('=');
                    if (a[0].Trim('\'') == "Id")
                    {
                        id = a[1].Trim('\'');
                    }
                    else if (a[0].Trim('\'') == "Version")
                    {
                        version = a[1].Trim('\'');
                    }
                }

                await _channel.GetPackage(context, id, version, feed);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        ///  Skip to the first needed segment, and include all following segments.
        /// </summary>
        public static Queue <string> GetListAvailableSegmentsIncludingAndAfter(InterceptCallContext context, JObject index, string startsWith = null)
        {
            var segs = index["entry"].ToArray();

            Queue <string> needed = new Queue <string>();

            for (int i = 0; i < segs.Length; i++)
            {
                // once we add the first one, take everythign after
                if (needed.Count > 0 || String.IsNullOrEmpty(startsWith))
                {
                    needed.Enqueue(segs[i]["url"].ToString());
                }
                else
                {
                    var seg = segs[i];

                    string lowest = seg["lowest"].ToString();

                    // advance until we go too far
                    if (needed.Count < 1 && StringComparer.InvariantCultureIgnoreCase.Compare(lowest, startsWith) >= 0)
                    {
                        if (i > 0)
                        {
                            // get the previous one
                            needed.Enqueue(segs[i - 1]["url"].ToString());
                        }

                        // add the current one
                        needed.Enqueue(segs[i]["url"].ToString());
                    }
                }
            }

            return(needed);
        }
Ejemplo n.º 31
0
        private async Task<JObject> FetchJson(InterceptCallContext context, Uri address)
        {
            string url = address.ToString().ToLowerInvariant();

            JObject fromCache = null;
            if (_cache.TryGet(address, out fromCache))
            {
                context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 CACHE] {0}", address.ToString()), ConsoleColor.DarkCyan);
                return fromCache;
            }

            context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 REQ] {0}", address.ToString()), ConsoleColor.Cyan);

            Stopwatch timer = new Stopwatch();
            timer.Start();

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            HttpResponseMessage response = await client.GetAsync(address);

            timer.Stop();

            context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 RES] (status:{0}) (time:{1}ms) {2}", response.StatusCode, timer.ElapsedMilliseconds, address.ToString()),
                response.StatusCode == System.Net.HttpStatusCode.OK ? ConsoleColor.Cyan : ConsoleColor.Red);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string json = await response.Content.ReadAsStringAsync();
                JObject obj = JObject.Parse(json);

                _cache.AddOrUpdate(address, obj);

                return obj;
            }
            else
            {
                // expected in some cases
                return null;
            }
        }
Ejemplo n.º 32
0
        private async Task Root(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Root", ConsoleColor.Green);

            await _channel.Root(context);
        }
Ejemplo n.º 33
0
        public async Task GetAllPackageVersions(InterceptCallContext context, string id)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] GetAllPackageVersions: {0}", id), ConsoleColor.Magenta);

            var ids = id.Split(new string[] { " or " }, StringSplitOptions.RemoveEmptyEntries);

            List<JToken> packages = new List<JToken>();

            foreach (var s in ids)
            {
                string curId = s.Trim('\'');

                if (curId.StartsWith("tolower(id) eq '"))
                {
                    curId = curId.Split('\'')[1];
                }

                // TODO: run in parallel
                JObject resolverBlob = await FetchJson(context, MakeResolverAddress(curId));

                if (resolverBlob == null)
                {
                    throw new InvalidOperationException(string.Format("package {0} not found", curId));
                }

                foreach (var p in resolverBlob["packages"])
                {
                    NuGetVersion version = NuGetVersion.Parse(p["version"].ToString());

                    // all versions are returned, filter to only stable if needed
                    if (context.Args.IncludePrerelease || !version.IsPrerelease)
                    {
                        p["id"] = resolverBlob["id"];

                        packages.Add(p);
                    }
                }
            }

            var data = packages.OrderBy(p => p["id"].ToString()).ThenByDescending(p => NuGetVersion.Parse(p["version"].ToString()), VersionComparer.VersionRelease);

            XElement feed = InterceptFormatting.MakeFeed(_passThroughAddress, "Packages", data, data.Select(p => p["id"].ToString()).ToArray());
            await context.WriteResponse(feed);
        }
Ejemplo n.º 34
0
        public IEnumerable<JToken> GetListAvailableFastForwardSkipToken(InterceptCallContext context, JObject index)
        {
            var data = GetListAvailableDataStart(context, index);

            if (context.Args.SkipToken != null)
            {
                var skipToken = ParseSkipToken(context.Args.SkipToken);
                var skipTokenId = skipToken.Item1;
                var skipTokenVer = new NuGetVersion(skipToken.Item2);

                data = data.Where(e => skipTokenId == null || StringComparer.InvariantCultureIgnoreCase.Compare(e["id"].ToString(), skipTokenId) > 0
                    || (StringComparer.InvariantCultureIgnoreCase.Equals(e["id"].ToString(), skipTokenId) &&
                        (skipTokenVer == null || VersionComparer.VersionRelease.Compare(new NuGetVersion(e["version"].ToString()), skipTokenVer) > 0)));
            }

            return data;
        }
Ejemplo n.º 35
0
        public async Task ListAvailable(InterceptCallContext context)
        {
            string indexUrl = _listAvailableLatestStableIndex;

            if (!context.Args.IsLatestVersion)
            {
                indexUrl = _listAvailableAllIndex;
            }
            else if (context.Args.IncludePrerelease)
            {
                indexUrl = _listAvailableLatestPrereleaseIndex;
            }

            var index = await FetchJson(context, new Uri(indexUrl));

            var data = GetListAvailableData(context, index);

            // all versions with no pre
            if (!context.Args.IsLatestVersion && !context.Args.IncludePrerelease)
            {
                data = data.Where(p => (new NuGetVersion(p["version"].ToString())).IsPrerelease == false);
            }

            string nextUrl = null;

            // Convert to a list after calling Take to avoid enumerating the list multiple times.

            if (context.Args.Top.HasValue && context.Args.Top.Value > 0)
            {
                data = data.Take(context.Args.Top.Value).ToList();
            }
            else
            {
                data = data.Take(30).ToList();

                if (data.Count() >= 30)
                {
                    var last = data.LastOrDefault();

                    if (last != null)
                    {
                        string argsWithoutSkipToken = String.Join("&", context.Args.Arguments.Where(a => a.Key.ToLowerInvariant() != "$skiptoken")
                            .Select(a => String.Format(CultureInfo.InvariantCulture, "{0}={1}", a.Key, a.Value)));

                        nextUrl = String.Format(CultureInfo.InvariantCulture, "{0}?{1}&$skiptoken='{2}','{2}','{3}'",
                                                context.RequestUri.AbsoluteUri.Split('?')[0],
                                                argsWithoutSkipToken,
                                                last["id"],
                                                last["version"]);
                    }
                }
            }

            XElement feed = InterceptFormatting.MakeFeed(_passThroughAddress, "Packages", data, data.Select(e => e["id"].ToString()).ToArray(), nextUrl);
            await context.WriteResponse(feed);
        }
Ejemplo n.º 36
0
        private async Task Metadata(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Metadata", ConsoleColor.Green);

            await _channel.Metadata(context);
        }
Ejemplo n.º 37
0
        public async Task GetLatestVersionPackage(InterceptCallContext context, string id, bool includePrerelease)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] GetLatestVersionPackage: {0} {1}", id, includePrerelease ? "[include prerelease]" : ""), ConsoleColor.Magenta);

            JObject resolverBlob = await FetchJson(context, MakeResolverAddress(id));

            if (resolverBlob == null)
            {
                throw new InvalidOperationException(string.Format("package {0} not found", id));
            }

            JToken latest = ExtractLatestVersion(resolverBlob, includePrerelease);

            if (latest == null)
            {
                throw new InvalidOperationException(string.Format("package {0} not found", id));
            }

            XElement feed = InterceptFormatting.MakeFeed(_passThroughAddress, "Packages", new List<JToken> { latest }, id);
            await context.WriteResponse(feed);
        }
Ejemplo n.º 38
0
        private async Task PackageVersions(InterceptCallContext context)
        {
            context.Log("[V3 CALL] PackageVersions", ConsoleColor.Green);

            string path = context.RequestUri.AbsolutePath;
            string id = path.Substring(path.LastIndexOf("/") + 1);

            await _channel.GetListOfPackageVersions(context, id);
        }
Ejemplo n.º 39
0
        private async Task GetUpdates(InterceptCallContext context)
        {
            context.Log("[V3 CALL] GetUpdates", ConsoleColor.Green);

            IDictionary<string, string> arguments = context.Args.Arguments;

            string[] packageIds = Uri.UnescapeDataString(arguments["packageIds"]).Trim('\'').Split('|');
            string[] versions = Uri.UnescapeDataString(arguments["versions"]).Trim('\'').Split('|');
            string[] versionConstraints = Uri.UnescapeDataString(arguments["versionConstraints"]).Trim('\'').Split('|');
            string[] targetFrameworks = Uri.UnescapeDataString(arguments["targetFrameworks"]).Trim('\'').Split('|');
            bool includeAllVersions = false;
            bool.TryParse(arguments["includeAllVersions"], out includeAllVersions);

            await _channel.GetUpdates(context, packageIds, versions, versionConstraints, targetFrameworks, context.Args.IncludePrerelease, includeAllVersions, context.Args.Count);
        }
Ejemplo n.º 40
0
        private async Task PackageIds(InterceptCallContext context)
        {
            context.Log("[V3 CALL] PackageIds", ConsoleColor.Green);

            await _channel.GetListOfPackages(context);
        }
Ejemplo n.º 41
0
        private async Task FindPackagesById(InterceptCallContext context)
        {
            context.Log("[V3 CALL] FindPackagesById", ConsoleColor.Green);

            if (context.Args.Id == null)
            {
                throw new ShimException("unable to find id in query string");
            }

            if (context.Args.IsLatestVersion)
            {
                await _channel.GetLatestVersionPackage(context, context.Args.Id, context.Args.IncludePrerelease);
            }
            else
            {
                await _channel.GetAllPackageVersions(context, context.Args.Id);
            }
        }
Ejemplo n.º 42
0
        private async Task SearchImpl(InterceptCallContext context, string feed = null)
        {
            int skip = context.Args.Skip ?? 0;
            int take = context.Args.Top ?? 30;

            string sortBy = string.Empty;

            await _channel.Search(context, context.Args.SearchTerm, context.Args.IsLatestVersion, context.Args.TargetFramework, context.Args.IncludePrerelease, skip, take, feed, sortBy);
        }
Ejemplo n.º 43
0
        public async Task<List<JObject>> GetUpdatesCore(InterceptCallContext context, string[] packageIds, string[] versions, string[] versionConstraints, string[] targetFrameworks, bool includePrerelease, bool includeAllVersions)
        {
            List<JObject> packages = new List<JObject>();

            for (int i = 0; i < packageIds.Length; i++)
            {
                VersionRange range = null;

                if (i < versionConstraints.Length && !String.IsNullOrEmpty(versionConstraints[i]))
                {
                    VersionRange.TryParse(versionConstraints[i], out range);
                }

                JObject resolverBlob = await FetchJson(context, MakeResolverAddress(packageIds[i]));

                // TODO: handle this error
                if (resolverBlob != null)
                {
                    // this can be null if all packages are prerelease
                    JObject latest = ExtractLatestVersion(resolverBlob, includePrerelease, range) as JObject;
                    if (latest != null)
                    {
                        // add the id if it isn't there
                        if (latest["id"] == null)
                        {
                            latest.Add("id", JToken.Parse("'" + packageIds[i] + "'"));
                        }

                        if (i < versions.Length && !String.IsNullOrEmpty(versions[i]))
                        {
                            NuGetVersion latestVersion = NuGetVersion.Parse(latest["version"].ToString());
                            NuGetVersion currentVersion = NuGetVersion.Parse(versions[i]);

                            // only add the package if it is not the latest version
                            if (VersionComparer.VersionRelease.Compare(latestVersion, currentVersion) > 0)
                            {
                                packages.Add(latest);
                            }
                        }
                        else
                        {
                            packages.Add(latest);
                        }
                    }
                }
            }

            return packages;
        }
Ejemplo n.º 44
0
        /// <summary>
        ///  Skip to the first needed segment, and include all following segments.
        /// </summary>
        public static Queue<string> GetListAvailableSegmentsIncludingAndAfter(InterceptCallContext context, JObject index, string startsWith=null)
        {
            var segs = index["entry"].ToArray();

            Queue<string> needed = new Queue<string>();

            for (int i=0; i < segs.Length; i++)
            {
                // once we add the first one, take everythign after
                if (needed.Count > 0 || String.IsNullOrEmpty(startsWith))
                {
                    needed.Enqueue(segs[i]["url"].ToString());
                }
                else
                {
                    var seg = segs[i];

                    string lowest = seg["lowest"].ToString();

                    // advance until we go too far
                    if (needed.Count < 1 && StringComparer.InvariantCultureIgnoreCase.Compare(lowest, startsWith) >= 0)
                    {
                        if (i > 0)
                        {
                            // get the previous one
                            needed.Enqueue(segs[i - 1]["url"].ToString());
                        }

                        // add the current one
                        needed.Enqueue(segs[i]["url"].ToString());
                    }
                }
            }

            return needed;
        }
Ejemplo n.º 45
0
        private async Task Packages(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Packages", ConsoleColor.Green);

            string path = Uri.UnescapeDataString(context.RequestUri.AbsolutePath);
            string query = context.RequestUri.Query;

            await GetPackage(context, path, query);
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Gathers the response data from the V3 source for the context uri.
        /// </summary>
        public async Task Invoke(InterceptCallContext context)
        {
            try
            {
                if (_initialized != true)
                {
                    throw new InvalidOperationException("Requires Init");
                }

                // report metrics if the headers exist
                Task metricsTask = ReportMetrics(context.Request);

                string unescapedAbsolutePath = Uri.UnescapeDataString(context.RequestUri.AbsolutePath);

                string path = unescapedAbsolutePath;

                // v2 is still in the path for get-package
                if (unescapedAbsolutePath.IndexOf(ShimConstants.V2UrlPath) == 0)
                {
                    path = unescapedAbsolutePath.Remove(0, ShimConstants.V2UrlPath.Length);
                }

                if (unescapedAbsolutePath.IndexOf(ShimConstants.V3UrlPath) == 0)
                {
                    path = unescapedAbsolutePath.Remove(0, ShimConstants.V3UrlPath.Length);
                }

                foreach (var func in _funcs)
                {
                    if (path == string.Empty)
                    {
                        await Root(context);
                        return;
                    }
                    else if (path.StartsWith(func.Item1))
                    {
                        await func.Item2(context);
                        return;
                    }
                }

                //  url was not recognized - perhaps this is a feed

                int index1 = path.IndexOf('/', 0) + 1;
                if (index1 < path.Length)
                {
                    int index2 = path.IndexOf('/', index1);
                    if (index2 < path.Length)
                    {
                        path = path.Remove(0, index2 + 1);
                    }
                }

                foreach (var func in _feedFuncs)
                {
                    if (path == string.Empty)
                    {
                        await _channel.Root(context);

                        //await Feed_Root(context);
                        return;
                    }
                    if (path.StartsWith(func.Item1))
                    {
                        await func.Item2(context);
                        return;
                    }
                }

                // unknown process
                throw new NotImplementedException();
            }
            catch (Exception ex)
            {
                context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 ERR] (exception:{0}) {1}", ex.GetType().ToString(), context.RequestUri.AbsoluteUri), ConsoleColor.Red);
                throw;
            }
        }
Ejemplo n.º 47
0
        public async Task GetUpdates(InterceptCallContext context, string[] packageIds, string[] versions, string[] versionConstraints, string[] targetFrameworks, bool includePrerelease, bool includeAllVersions, bool count = false)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] GetUpdates{1}: {0}", string.Join("|", packageIds), count ? "Count" : string.Empty), ConsoleColor.Magenta);

            var packages = await GetUpdatesCore(context, packageIds, versions, versionConstraints, targetFrameworks, includePrerelease, includeAllVersions);

            if (count)
            {
                await context.WriteResponse(packages.Count);
            }
            else
            {
                XElement feed = InterceptFormatting.MakeFeed(_passThroughAddress, "GetUpdates", packages, packages.Select(p => p["id"].ToString()).ToArray());
                await context.WriteResponse(feed);
            }
        }
Ejemplo n.º 48
0
        private async Task GetPackage(InterceptCallContext context, string path, string query, string feed = null)
        {
            if (path.EndsWith("Packages()"))
            {
                if(!String.IsNullOrEmpty(context.Args.FilterId))
                {
                    await _channel.GetAllPackageVersions(context, context.Args.FilterId.ToLowerInvariant());
                }
                else
                {
                    await _channel.ListAvailable(context);
                }
            }
            else
            {
                string args = path.Substring(path.LastIndexOf('(')).Trim('(', ')');

                string id = null;
                string version = null;

                string[] aps = args.Split(',');
                foreach (var ap in aps)
                {
                    string[] a = ap.Split('=');
                    if (a[0].Trim('\'') == "Id")
                    {
                        id = a[1].Trim('\'');
                    }
                    else if (a[0].Trim('\'') == "Version")
                    {
                        version = a[1].Trim('\'');
                    }
                }

                await _channel.GetPackage(context, id, version, feed);
            }
        }
Ejemplo n.º 49
0
        public IEnumerable<JToken> GetListAvailableDataStart(InterceptCallContext context, JObject index)
        {
            string skipTo = null;

            if (context.Args.SkipToken != null)
            {
                var skipToken = ParseSkipToken(context.Args.SkipToken);
                skipTo = skipToken.Item1;
            }
            else if (context.Args.FilterStartsWithId != null)
            {
                skipTo = context.Args.FilterStartsWithId;
            }
            if (context.Args.PartialId != null) // intellisense
            {
                skipTo = context.Args.PartialId;
            }

            var segments = GetListAvailableSegmentsIncludingAndAfter(context, index, skipTo);

            foreach(var segUrl in segments)
            {
                var dataTask = FetchJson(context, new Uri(segUrl));
                dataTask.Wait();
                var data = dataTask.Result;

                var orderedData = data["entry"].OrderBy(e => e["id"].ToString(), StringComparer.InvariantCultureIgnoreCase)
                    .ThenBy(e => new NuGetVersion(e["version"].ToString()), VersionComparer.VersionRelease);

                foreach (var entry in orderedData)
                {
                    yield return entry;
                }
            }
        }
Ejemplo n.º 50
0
 private async Task Feed_Search(InterceptCallContext context)
 {
     context.Log("[V3 CALL] Feed_Search", ConsoleColor.Green);
     string feed = ExtractFeed(context.RequestUri.AbsolutePath);
     context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] feed: {0}", feed), ConsoleColor.DarkGreen);
     await SearchImpl(context, feed);
 }
Ejemplo n.º 51
0
        public IEnumerable<JToken> GetListAvailableData(InterceptCallContext context, JObject index)
        {
            var data = GetListAvailableFastForwardSkipToken(context, index);

            // apply startswith if needed
            if (context.Args.FilterStartsWithId != null)
            {
                data = data.Where(e => e["id"].ToString().StartsWith(context.Args.FilterStartsWithId, StringComparison.OrdinalIgnoreCase));

                data = data.TakeWhile(e => e["id"].ToString().StartsWith(context.Args.FilterStartsWithId, StringComparison.OrdinalIgnoreCase));
            }

            return data;
        }
Ejemplo n.º 52
0
        private async Task Feed_FindPackagesById(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Feed_FindPackagesById", ConsoleColor.Green);
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] feed: {0}", ExtractFeed(context.RequestUri.AbsolutePath)), ConsoleColor.DarkGreen);

            await _channel.GetAllPackageVersions(context, context.Args.Id);
        }
Ejemplo n.º 53
0
        public async Task GetListOfPackages(InterceptCallContext context)
        {
            context.Log("[V3 CALL] GetListOfPackages", ConsoleColor.Magenta);

            var index = await FetchJson(context, context.Args.IncludePrerelease ? new Uri(_listAvailableLatestPrereleaseIndex) : new Uri(_listAvailableLatestStableIndex));
            var data = GetListAvailableDataStart(context, index);

            // apply startswith if needed
            if (context.Args.PartialId != null)
            {
                data = data.Where(e => e["id"].ToString().StartsWith(context.Args.PartialId, StringComparison.OrdinalIgnoreCase));

                data = data.TakeWhile(e => e["id"].ToString().StartsWith(context.Args.PartialId, StringComparison.OrdinalIgnoreCase));
            }

            // take only 30
            var ids = data.Take(30).Select(p => p["id"].ToString()).ToList();

            ids.Sort(StringComparer.InvariantCultureIgnoreCase);

            JArray array = new JArray();
            foreach (var id in ids)
            {
                array.Add(id);
            }

            await context.WriteResponse(array);
        }
Ejemplo n.º 54
0
        private async Task Feed_Packages(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Feed_Packages", ConsoleColor.Green);
            string feed = ExtractFeed(context.RequestUri.AbsolutePath);
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] feed: {0}", feed), ConsoleColor.DarkGreen);

            string path = Uri.UnescapeDataString(context.RequestUri.AbsolutePath);
            path = path.Substring(path.IndexOf(feed) + feed.Length + 1);

            string query = context.RequestUri.Query;

            await GetPackage(context, path, query, feed);
        }
Ejemplo n.º 55
0
        public async Task GetListOfPackageVersions(InterceptCallContext context, string id)
        {
            context.Log(string.Format(CultureInfo.InvariantCulture, "[V3 CALL] GetListOfPackageVersions: {0}", id), ConsoleColor.Magenta);

            JObject resolverBlob = await FetchJson(context, MakeResolverAddress(id));

            JArray array = new JArray();

            // the package may not exist, in that case return an empty array
            if (resolverBlob != null)
            {
                List<NuGetVersion> versions = new List<NuGetVersion>();
                foreach (JToken package in resolverBlob["packages"])
                {
                    NuGetVersion version = NuGetVersion.Parse(package["version"].ToString());

                    // all versions are returned, filter to only stable if needed
                    if (context.Args.IncludePrerelease || !version.IsPrerelease)
                    {
                        versions.Add(version);
                    }
                }

                versions.Sort();

                foreach (NuGetVersion version in versions)
                {
                    array.Add(version.ToString());
                }
            }

            await context.WriteResponse(array);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Gathers the response data from the V3 source for the context uri.
        /// </summary>
        public async Task Invoke(InterceptCallContext context)
        {
            try
            {
                if (_initialized != true)
                {
                    throw new InvalidOperationException("Requires Init");
                }

                string unescapedAbsolutePath = Uri.UnescapeDataString(context.RequestUri.AbsolutePath);

                string path = unescapedAbsolutePath;

                // v2 is still in the path for get-package
                if (unescapedAbsolutePath.IndexOf(ShimConstants.V2UrlPath) > -1)
                {
                    path = unescapedAbsolutePath.Remove(0, ShimConstants.V2UrlPath.Length);
                }
                else if (unescapedAbsolutePath.IndexOf(ShimConstants.V3UrlPath) > -1)
                {
                    path = unescapedAbsolutePath.Remove(0, ShimConstants.V3UrlPath.Length);
                }

                foreach (var func in _funcs)
                {
                    if (path == string.Empty)
                    {
                        await Root(context);

                        return;
                    }
                    else if (path.StartsWith(func.Item1))
                    {
                        await func.Item2(context);

                        return;
                    }
                }

                //  url was not recognized - perhaps this is a feed

                int index1 = path.IndexOf('/', 0) + 1;
                if (index1 < path.Length)
                {
                    int index2 = path.IndexOf('/', index1);
                    if (index2 < path.Length)
                    {
                        path = path.Remove(0, index2 + 1);
                    }
                }

                foreach (var func in _feedFuncs)
                {
                    if (path == string.Empty)
                    {
                        await _channel.Root(context);

                        //await Feed_Root(context);
                        return;
                    }
                    if (path.StartsWith(func.Item1))
                    {
                        await func.Item2(context);

                        return;
                    }
                }

                // unknown process
                throw new NotImplementedException();
            }
            catch (Exception ex)
            {
                context.Log(String.Format(CultureInfo.InvariantCulture, "[V3 ERR] (exception:{0}) {1}", ex.GetType().ToString(), context.RequestUri.AbsoluteUri), ConsoleColor.Red);
                throw;
            }
        }
Ejemplo n.º 57
0
        private async Task Count(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Count", ConsoleColor.Green);

            await CountImpl(context);
        }
Ejemplo n.º 58
0
        private async Task DownloadPackage(InterceptCallContext context)
        {
            context.Log("[V3 CALL] DownloadPackage", ConsoleColor.Green);

            var urlParts = new List<string>(context.RequestUri.AbsoluteUri.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries));
            urlParts.Reverse();

            if (urlParts.Count > 3 && StringComparer.OrdinalIgnoreCase.Equals("package", urlParts[2]))
            {
                await _channel.DownloadPackage(context, urlParts[1], urlParts[0]);
            }
            else
            {
                throw new ShimException("Invalid download url: " + context.RequestUri.ToString());
            }
        }
Ejemplo n.º 59
0
        private async Task Search(InterceptCallContext context)
        {
            context.Log("[V3 CALL] Search", ConsoleColor.Green);

            await SearchImpl(context);
        }
Ejemplo n.º 60
0
        private async Task<JToken> GetPackageCore(InterceptCallContext context, string id, string version)
        {
            JToken desiredPackage = null;
            JObject resolverBlob = await FetchJson(context, MakeResolverAddress(id));


            if (resolverBlob != null)
            {
                NuGetVersion desiredVersion = NuGetVersion.Parse(version);

                foreach (JToken package in resolverBlob["packages"])
                {
                    NuGetVersion currentVersion = NuGetVersion.Parse(package["version"].ToString());
                    if (currentVersion == desiredVersion)
                    {
                        desiredPackage = package;
                        break;
                    }
                }
            }

            return desiredPackage;
        }