Exemple #1
0
        public static PullRequest?Parse(JsonElement je, bool verbose = false)
        {
            if (je.ValueKind != JsonValueKind.Object)
            {
                return(null);
            }

            try
            {
                return(new PullRequest(
                           HTML_URL:        je.Get <string> ("html_url"),
                           HeadRepoOwner:   je.Get <string> ("head/repo/owner/login"),
                           Number:          je.Get <int>    ("number"),
                           HeadRef:         je.Get <string> ("head/ref"),
                           BaseRef:         je.Get <string> ("base/ref")
                           ));
            } catch (KeyNotFoundException knfe) {
                if (verbose)
                {
                    Console.WriteLine($"Error parsing PR : {knfe.Message}");
                }
            }

            return(null);
        }
Exemple #2
0
        public async Task <IActionResult> PostJellyConversationHook([FromBody] JsonElement entity)
        {
            await _loggingService.LogDebug("PostJellyConversationHook - received conversation.", $"Received the following JellyConversation:", entity.GetRawText());

            string      orderType = entity.Get("requestJson")?.Get("intent")?.Get("params")?.Get("Order")?.Get("resolved")?.GetString() ?? _configuration["Services:Jellyfin:DefaultOrder"];
            string      mediaType = entity.Get("requestJson")?.Get("intent")?.Get("params")?.Get("MediaType")?.Get("resolved")?.GetString() ?? _configuration["Services:Jellyfin:DefaultMediaType"];
            JellyPhrase phrase    = new()
            {
                SearchTerm = entity.Get("requestJson")?.Get("intent")?.Get("params")?.Get("Content")?.Get("resolved")?.GetString() ?? string.Empty,
                PathTerm   = entity.Get("requestJson")?.Get("intent")?.Get("params")?.Get("PathTerm")?.Get("resolved")?.GetString() ?? string.Empty,
                User       = entity.Get("requestJson")?.Get("intent")?.Get("params")?.Get("UserName")?.Get("resolved")?.GetString() ?? _configuration["Services:Jellyfin:DefaultUser"],
                Device     = entity.Get("requestJson")?.Get("intent")?.Get("params")?.Get("Device")?.Get("resolved")?.GetString() ?? _configuration["Services:Jellyfin:DefaultDevice"],
                OrderType  = (OrderType)Enum.Parse(typeof(OrderType), orderType),
                MediaType  = (MediaType)Enum.Parse(typeof(MediaType), mediaType)
            };

            return(await ProcessJellyPhrase(phrase, nameof(PostJellyConversationHook)));
        }
        private static ProfileMetaData ParseProfile(this JsonElement e, Context context, FileInfo filepath, DateTime lastChange)
        {
            if (!e.TryGetProperty("speed", out _))
            {
                // not a profile
                return(null);
            }

            var name   = e.Get("name");
            var author = e.TryGet("author");

            if (filepath != null && !(name + ".json").ToLower().Equals(filepath.Name.ToLower()))
            {
                throw new ArgumentException($"Filename does not match the defined name: " +
                                            $"filename is {filepath.Name}, declared name is {name}");
            }

            JsonElement GetTopProperty(string name)
            {
                if (e.TryGetProperty(name, out var p))
                {
                    return(p);
                }

                throw new ArgumentException(
                          filepath + " is not a valid profile; it does not contain the obligated parameter " + name);
            }

            var vehicleTypes = GetTopProperty("vehicletypes").EnumerateArray().Select(
                el => el.GetString()).ToList();
            var metadata = GetTopProperty("metadata").EnumerateArray().Select(
                el => el.GetString()).ToList();


            var access = ParseProfileProperty(e, context, "access").Finalize();
            var oneway = ParseProfileProperty(e, context, "oneway").Finalize();
            var speed  = ParseProfileProperty(e, context, "speed").Finalize();


            IExpression TagsApplied(IExpression x)
            {
                return(new Apply(x, new Constant(new Dictionary <string, string>())));
            }

            context.AddFunction("speed",
                                new AspectMetadata(TagsApplied(speed), "speed", "The speed of this profile", author, "", filepath.Name,
                                                   true));
            context.AddFunction("access",
                                new AspectMetadata(TagsApplied(access), "access", "The access of this profile", author, "",
                                                   filepath.Name,
                                                   true));
            context.AddFunction("oneway",
                                new AspectMetadata(TagsApplied(oneway), "oneway", "The oneway of this profile", author, "",
                                                   filepath.Name,
                                                   true));
            context.AddFunction("distance",
                                new AspectMetadata(new Constant(1), "distance", "The distance travelled of this profile", author, "",
                                                   filepath.Name,
                                                   true));


            var weights = new Dictionary <string, IExpression>();

            var weightProperty = GetTopProperty("priority");

            foreach (var prop in weightProperty.EnumerateObject())
            {
                var parameter = prop.Name.TrimStart('#');
                var factor    = ParseExpression(prop.Value, context).Finalize();
                weights[parameter] = factor;
            }

            var profiles = new Dictionary <string, Dictionary <string, IExpression> >();

            var behaviours = GetTopProperty("behaviours");

            foreach (var profile in behaviours.EnumerateObject())
            {
                profiles[profile.Name] = ParseParameters(profile.Value);
            }

            if (lastChange < filepath.LastWriteTimeUtc)
            {
                lastChange = filepath.LastWriteTimeUtc;
            }

            return(new ProfileMetaData(
                       name,
                       e.Get("description"),
                       author,
                       filepath?.DirectoryName ?? "unknown",
                       vehicleTypes,
                       e.GetProperty("defaults").ParseParameters(),
                       profiles,
                       access,
                       oneway,
                       speed,
                       weights,
                       metadata,
                       lastChange
                       ));
        }
        private static AspectMetadata ParseAspect(this JsonElement e, string filepath, Context context)
        {
            var expr = GetTopLevelExpression(e, context);

            var targetTypes = new List <Type>();

            foreach (var t in expr.Types)
            {
                var a = Var.Fresh(t);
                var b = Var.Fresh(new Curry(a, t));

                if (t.Unify(new Curry(Typs.Tags, a)) != null &&
                    t.Unify(new Curry(Typs.Tags, new Curry(a, b))) == null
                    ) // Second should not  match
                {
                    // The target type is 'Tags -> a', where a is NOT a curry
                    targetTypes.Add(t);
                }
            }

            if (targetTypes.Count == 0)
            {
                throw new ArgumentException("The top level expression has types:\n" +
                                            string.Join("\n    ", expr.Types) +
                                            "\nwhich can not be specialized into a form suiting `tags -> a`\n" + expr);
            }

            var exprSpec = expr.Specialize(targetTypes);

            if (expr == null)
            {
                throw new Exception("Could not specialize the expression " + expr + " to one of the target types " +
                                    string.Join(", ", targetTypes));
            }

            expr = exprSpec.Finalize();

            if (expr.Finalize() == null)
            {
                throw new NullReferenceException("The finalized form of expression `" + exprSpec + "` is null");
            }

            expr = expr.SpecializeToSmallestType();


            var name = e.Get("name");

            if (expr.Types.Count() > 1)
            {
                throw new ArgumentException("The aspect " + name + " is ambigous, it matches multiple types: " +
                                            string.Join(", ", expr.Types));
            }

            if (filepath != null && !(name + ".json").ToLower().Equals(filepath.ToLower()))
            {
                throw new ArgumentException($"Filename does not match the defined name: " +
                                            $"filename is {filepath}, declared name is {name}");
            }

            var keys = (IEnumerable <string>)expr.PossibleTags()?.Keys ?? new List <string>();

            foreach (var key in keys)
            {
                if (!key.Trim().Equals(key))
                {
                    Console.WriteLine($"Warning: a key can be trimmed: '{key}'");
                }
            }

            Console.WriteLine($"Aspect {name} has type {string.Join(",", expr.Types)}");
            return(new AspectMetadata(
                       expr,
                       name,
                       e.Get("description"),
                       e.TryGet("author"),
                       e.TryGet("unit"),
                       filepath ?? "unknown"
                       ));
        }
Exemple #5
0
        public async Task SubscribeForTransactionsWithAddresses()
        {
            KeyPair keys = await _tonClient.Crypto.GenerateRandomSignKeys();

            ITonClient subscriptionClient = _fixture.CreateClient(_outputHelper, true);

            var deployParams = new ParamsOfEncodeMessage
            {
                Abi       = TestsEnv.Packages.Hello.Abi,
                DeploySet = new DeploySet {
                    Tvc = TestsEnv.Packages.Hello.Tvc
                },
                Signer = new Signer.Keys {
                    KeysAccessor = keys
                },
                CallSet = new CallSet {
                    FunctionName = "constructor"
                }
            };

            ResultOfEncodeMessage msg = await _tonClient.Abi.EncodeMessage(deployParams);

            var transactions = new List <string>();
            var errorCodes   = new List <uint>();
            var @lock        = new object();

            var address = msg.Address;

            var callback = new Action <JsonElement, uint>((serdeJson, responseType) =>
            {
                switch ((SubscriptionResponseType)responseType)
                {
                case SubscriptionResponseType.Ok:
                    JsonElement resultOk = serdeJson.GetProperty("result");
                    resultOk.Get <string>("account_addr").Should().Be(address);
                    lock (@lock)
                    {
                        transactions.Add(resultOk.Get <string>("id"));
                    }

                    break;

                case SubscriptionResponseType.Error:
                    var error = serdeJson.ToObject <ClientError>();
                    _outputHelper.WriteLine($">> {error}");
                    lock (@lock)
                    {
                        errorCodes.Add(error.Code);
                    }

                    break;

                default:
                    throw new TonClientException($"Unknown SubscriptionResponseType: {responseType}");
                }
            });

            //act
            ResultOfSubscribeCollection handle1 = await subscriptionClient.Net.SubscribeCollection(new ParamsOfSubscribeCollection
            {
                Collection = "transactions",
                Filter     = new
                {
                    account_addr = new { eq = address },
                    status       = new { eq = (int)TransactionProcessingStatus.Finalized }
                }.ToJsonElement(),
                Result = "id account_addr"
            }, callback);

            // send grams to create first transaction
            await _tonClient.SendGramsFromLocalGiver(address);

            // give some time for subscription to receive all data
            await Task.Delay(TimeSpan.FromSeconds(1));

            var transactionCount1 = transactions.Count;

            // suspend subscription
            await subscriptionClient.Net.Suspend();

            await Task.Delay(TimeSpan.FromSeconds(1));

            // deploy to create second transaction
            await _tonClient.Processing.ProcessMessage(new ParamsOfProcessMessage
            {
                MessageEncodeParams = deployParams,
                SendEvents          = false
            });

            //act
            ResultOfSubscribeCollection handle2 = await subscriptionClient.Net.SubscribeCollection(new ParamsOfSubscribeCollection
            {
                Collection = "transactions",
                Filter     = new
                {
                    account_addr = new { eq = address },
                    status       = new { eq = (int)TransactionProcessingStatus.Finalized }
                }.ToJsonElement(),
                Result = "id account_addr"
            }, callback);

            await Task.Delay(TimeSpan.FromSeconds(1));

            // check that second transaction is not received when subscription suspended
            var transactionCount2 = transactions.Count;

            // resume subscription
            await subscriptionClient.Net.Resume();

            await Task.Delay(TimeSpan.FromSeconds(1));

            // run contract function to create third transaction
            await _tonClient.Processing.ProcessMessage(new ParamsOfProcessMessage
            {
                MessageEncodeParams = new ParamsOfEncodeMessage
                {
                    Abi    = TestsEnv.Packages.Hello.Abi,
                    Signer = new Signer.Keys {
                        KeysAccessor = keys
                    },
                    Address = address,
                    CallSet = new CallSet {
                        FunctionName = "touch"
                    }
                },
                SendEvents = false
            });

            // give some time for subscription to receive all data
            await Task.Delay(TimeSpan.FromSeconds(1));

            await subscriptionClient.Net.Unsubscribe(new ResultOfSubscribeCollection
            {
                Handle = handle1.Handle
            });

            await subscriptionClient.Net.Unsubscribe(new ResultOfSubscribeCollection
            {
                Handle = handle2.Handle
            });

            //check count before suspending
            transactionCount1.Should().Be(1);

            //check count before resume
            transactionCount2.Should().Be(1);

            // check that third transaction is now received after resume
            transactions.Count.Should().Be(3);
            transactions[0].Should().NotBe(transactions[2]);

            // check errors
            errorCodes.Count.Should().Be(4);
            errorCodes.Take(2).Should().AllBeEquivalentTo((uint)NetErrorCode.NetworkModuleSuspended);
            errorCodes.TakeLast(2).Should().AllBeEquivalentTo((uint)NetErrorCode.NetworkModuleResumed);
        }