public override bool Call(object value, IContinuation succ, IFailure fail)
        {
            if (breakpointCall)
                Console.WriteLine("Breakpoint in MatchProduceAgent");
            Context context = (Context) value;
            bool production = context.LookupDefaulted<bool>("$production", false);
            if (!production)
            {
                object check = context.LookupDefaulted<object>("$check", null);

                if (check == null)
                {
                    // Matcher did not call us
                    List<IContent> contents = new List<IContent>();
                    Context child = new Context(context, contents);
                    // Put us into content stream, for matcher to find
                    contents.Add(new Value(this));
                    // Save this context-- we'll use it later!
                    child.Map["$argctx"] = context;

                    succ.Continue(child, fail);
                    return true;
                }

                Context argctx = context.LookupDefaulted<Context>("$argctx", context);
                // Add our context, shadowing variables in argctx
                Context argctxchild = argctx.ChildRange(0);
                argctxchild.AddMappings(context);

                return Match(check, argctxchild, succ, fail);
            }
            else
                return Produce(context, succ, fail);
        }
示例#2
0
 public CallableAsEvaluable(ICallable callable, object value, IContinuation succ, IFailure fail)
 {
     this.callable = callable;
     this.value = value;
     this.succ = succ;
     this.fail = fail;
 }
        public int Call(object value, IContinuation succ, IFailure fail)
        {
            if (aborter.IsAborted)
                return 1;   // abort!

            List<IAction> namedacts = plugenv.GetNamedActions(resultType.Name);
            // Remove all actions that have already been used
            int ii = 0;
            while (ii < namedacts.Count)
            {
                if (searched.ContainsKey(namedacts[ii]))
                    namedacts.RemoveAt(ii);
                else
                {
                    searched.Add(namedacts[ii], 1);
                    ii++;
                }
            }

            if (namedacts.Count == 0)
                return arena.Fail(fail, salience, "no matching acts", succ);

            IContinuation next = new ContinueletWrapper(CheckAction, value, succ);
            IFailure more = new FailletWrapper(RecurseConversionAttempt, value, namedacts, succ);

            if (namedacts.Count == 1)
                return arena.Continue(next, salience, namedacts[0], more) + 2;

            TryValues<IAction> tryeach = new TryValues<IAction>();
            return arena.Call(tryeach, salience * .9, namedacts, next, more) + 3;
        }
        public PatternMatch Match(AmbiguousPhrase phrase, IContinuation succ, IFailure fail)
        {
            //IArena arena = new QueueArena();
            //arena.Call();

            return null;
        }
        public static ContinueToCallAgent Instantiate(CallAgent agent, Context context, IContinuation succ, IFailure fail)
        {
            ContinueToCallAgent continuer = new ContinueToCallAgent(agent, succ);
            continuer.SetResult(new TwoTuple<Context, IFailure>(context, fail), context.Weight, "ContinueToCallAgent: Instantiate");

            return continuer;
        }
 public ContinueCodelet(double salience, Context context, IContinuation succ, IFailure fail)
     : base(context.Coderack, salience, 4 * 4, 5)
 {
     this.context = context;
     this.succ = succ;
     this.fail = fail;
 }
示例#7
0
 public Evaluator(double salience, ArgumentMode argumentMode, IContinuation valuesucc, IContinuation aftersucc, bool isUserInput)
     : base(salience, 2 * 4, 100, valuesucc)
 {
     this.argumentMode = argumentMode;
     this.aftersucc = aftersucc;
     this.isUserInput = isUserInput;
 }
        public override bool Call(object value, IContinuation succ, IFailure fail)
        {
            Context context = (Context) value;
            if (principleSource == null || assertionSource == null) {
                fail.Fail("ConceptNet sources missing", succ);
                return true;
            }

            Notion concept;
            if (!principleSource.TryGetValue(StarUtilities.ContentsCode(context, tagger, parser), out concept))
            {
                fail.Fail("Could not find produced in ConceptNet", succ);
                return true;
            }

            List<Assertion> assertions;
            if (!assertionSource.TryGetValue(new KeyValuePair<Notion, string>(concept, relation), out assertions))
                assertions = new List<Assertion>();

            List<IContent> contents = new List<IContent>();

            foreach (Assertion assertion in assertions)
            {
                contents.Add(new Word(assertion.Sentence));
                contents.Add(new Word(" ."));
            }

            succ.Continue(new Context(context, contents), fail);
            return true;
        }
 public int Call(ICallable callable, double salience, object value, IContinuation succ, IFailure fail)
 {
     if (callable is IAgent)
         ((IAgent)callable).Initialize(this, salience);
     if (salience > 0)
         return callable.Call(value, succ, fail);
     return 1;
 }
示例#10
0
 // Don't call this.  Call MatchAgainst
 protected Matcher(double salience, IParsedPhrase input, List<IParsedPhrase> unmatched, IContinuation succ)
     : base(salience, 2 * 4, 10, succ)
 {
     if (input == null)
         throw new NullReferenceException("Input cannot be null.");
     this.input = input;
     this.unmatched = new List<IParsedPhrase>(unmatched);   // make copy, or %opt-fail has effects
 }
 /// <summary>
 /// Initializes a new instance of the PromiseAsyncExecutionEventArgs
 /// class.
 /// </summary>
 /// <param name="continuation">
 /// The continuation to be invoked when the async operation completes.
 /// </param>
 public PromiseAsyncExecutionEventArgs(IContinuation continuation)
 {
     if (continuation == null)
     {
         throw new ArgumentNullException("continuation");
     }
     this.continuation = continuation;
 }
        public override bool Match(object check, Context context, IContinuation succ, IFailure fail)
        {
            List<Relations.Relation> kinds = new List<Relations.Relation>();
            kinds.Add(Relations.Relation.AtTime);

            Thinker.SearchForMatch(salience, memory, kinds, (Datum) check, context, succ, fail);

            return true;
        }
        public ContinuationAppender(Context master, IContinuation succ)
        {
            this.master = master;
            this.succ = succ;
            indexes = 0;

            // filled upon continuation
            callers = new List<uint>();
            completes = new List<Context>();
        }
        public static bool PrintContents(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            PluginEnvironment plugenv = (PluginEnvironment) args[0];
            POSTagger tagger = new POSTagger(plugenv);
            GrammarParser parser = new GrammarParser(plugenv);

            Console.WriteLine(StarUtilities.ProducedCode(context, tagger, parser));
            succ.Continue(new Context(context, new List<IContent>()), fail);
            return true;
        }
 public int Fail(IFailure fail, double salience, string reason, IContinuation skip)
 {
     // Clone it!
     fail = (IFailure)fail.Clone();
     if (fail is IAgent)
         ((IAgent)fail).Initialize(this, salience);
     if (salience > 0)
         return fail.Fail(reason, skip);
     return 1;
 }
 bool FailToTryToRescue(IArena arena, double salience, string reason, IContinuation skip, params object[] args)
 {
     TryToRescueMatch tryToRescueMatch = (TryToRescueMatch) args[0];
     IParsedPhrase input = (IParsedPhrase) args[1];
     PatternTemplateSource patternTemplateSource = (PatternTemplateSource) args[2];
     IContinuation succ = (IContinuation) args[3];
     IFailure fail = (IFailure) args[4];
     Coderack coderack = (Coderack) args[5];
     return tryToRescueMatch.CallRescue(coderack, input, patternTemplateSource, reason, skip, succ, fail);
 }
 public int Continue(IContinuation cont, double salience, object value, IFailure fail)
 {
     // Clone it!
     cont = (IContinuation)cont.Clone();
     if (cont is IAgent)
         ((IAgent)cont).Initialize(this, salience);
     if (salience > 0)
         return cont.Continue(value, fail);
     return 1;
 }
        public PatternTemplateSource(PatternTemplateSource parent, Coderack coderack, double salience, IContinuation succ)
        {
            pattern = parent.pattern;
            template = parent.template;
            score = parent.score;
            source = parent.source;

            this.coderack = coderack;
            this.salience = salience;
            this.succ = succ;
        }
        public override bool Produce(Context context, IContinuation succ, IFailure fail)
        {
            object var = context.LookupDefaulted<object>("$p$" + name, null);

            if (var is IParsedPhrase)
                succ.Continue((IParsedPhrase)var, fail);

            succ.Continue(null, fail);

            return true;
        }
示例#20
0
 public Thinker(double salience, Memory memory, List<Relations.Relation> kinds, Datum check, IContinuation succ)
     : base(salience, 4 * 7, timeEach, succ)
 {
     this.memory = memory;
     this.kinds = kinds;
     directchecks = new List<Datum>();
     directchecks.Add(check);
     parentchecks = new Queue<Concept>();
     parentchecks.Enqueue(check.Left);
     parentchecks.Enqueue(check.Right);
 }
 public override int Call(object value, IContinuation succ, IFailure fail)
 {
     try
     {
         object results = Handle(value);
         return time + arena.Continue(succ, salience, results, fail);
     }
     catch (Exception ex)
     {
         return time + 2 + arena.Fail(fail, salience, ex.Message, succ);
     }
 }
        public override bool Produce(Context context, IContinuation succ, IFailure fail)
        {
            IParsedPhrase phrase = StarUtilities.ProducedPhrase(context, tagger, parser);
            if (phrase == null)
            {
                succ.Continue(new Context(context, new List<IContent>()), fail);
                return true; // cannot do!
            }

            KnowPhrase(phrase, context, memory);

            succ.Continue(new Context(context, new List<IContent>()), fail);
            return true;
        }
        public static bool DefineInNoArgRule(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            double salience = (double) args[0];

            List<IContent> contents = context.Contents;
            string name = contents[0].Name;

            Context definition = context.ChildRange(1);
            context.Map.Add(name, new CallAgentWrapper(EvaluateDefinition, ArgumentMode.NoArugments, salience, definition.Size, 10, salience, definition));

            Context empty = new Context(context, new List<IContent>());
            succ.Continue(empty, fail);

            return true;
        }
 public void Start(IContinuation continuation)
 {
     try
     {
         Method.Invoke(Instance, new object[0]);
         continuation.Success();
     }
     catch (TargetInvocationException ex)
     {
         continuation.Error(ex.InnerException.ToString());
     }
     catch (Exception ex)
     {
         continuation.Error(ex.ToString());
     }
 }
        public override bool Call(object value, IContinuation succ, IFailure fail)
        {
            Context context = (Context) value;
            IContent content = context.Contents[0];
            double term = 0;
            if (content is Word && double.TryParse(content.Name, out term))
            {
                term = -term;
                Context result = new Context(context, context.Contents);
                result.Contents[0] = new Word(term.ToString());
                succ.Continue(result, fail);
            }
            else
                fail.Fail("Argument isn't number", succ);

            return true;
        }
 /// <summary>
 /// Start the async WinJS operation.
 /// </summary>
 /// <param name="continuation">
 /// Continuation that should be invoked when the async operation has
 /// completed.
 /// </param>
 public void Start(IContinuation continuation)
 {
     EventHandler<PromiseAsyncExecutionEventArgs> handler = this.Execute;
     if (handler != null)
     {
         try
         {
             // Invoke the WinJS operation by raising the Execute event
             handler(this, new PromiseAsyncExecutionEventArgs(continuation));
         }
         catch (Exception ex)
         {
             // In the event the operation is actually sync, we'll catch
             // any errors now and pass them to the error continuation.
             continuation.Error(ex.ToString());
         }
     }
 }
 private async void Execute(IContinuation continuation)
 {
     try
     {
         Task result = Method.Invoke(Instance, new object[0]) as Task;
         if (result != null)
         {
             await result;
             continuation.Success();
         }                
     }
     catch (TargetInvocationException ex)
     {
         continuation.Error(ex.InnerException.ToString());
     }
     catch (Exception ex)
     {
         continuation.Error(ex.ToString());
     }
 }
        public override bool CallRescue(Coderack coderack, IParsedPhrase input, PatternTemplateSource patternTemplateSource, string reason, IContinuation skip, IContinuation succ, IFailure fail)
        {
            List<string> words = GroupPhrase.PhraseToTexts(input);

            bool changed = false;
            List<string> corrected = new List<string>();
            foreach (string word in words) {
                string correct = comparer.GetCorrects(word)[0];
                if (correct.ToLower() != word.ToLower())
                    changed = true;
                corrected.Add(correct);
            }

            if (changed) {
                IParsedPhrase correct = parser.Parse(StringUtilities.JoinWords(corrected));
                IFailure fallfail = fallback.MakeFailure(input, patternTemplateSource, succ, fail, coderack);
                patternTemplateSource.Generate(coderack, correct, succ, fallfail, weight);
                return true;
            } else
                return fallback.CallRescue(coderack, input, patternTemplateSource, reason, skip, succ, fail);
        }
        public override bool Call(object value, IContinuation succ, IFailure fail)
        {
            Context context = (Context) value;

            double result = 0;

            foreach (IContent content in context.Contents)
            {
                double term = 0;
                if (content is Word && double.TryParse(content.Name, out term))
                    result += term;
                else
                {
                    fail.Fail("Argument isn't number", succ);
                    return true;
                }
            }

            List<IContent> cntres = new List<IContent>();
            cntres.Add(new Word(result.ToString()));
            succ.Continue(new Context(context, cntres), fail);

            return true;
        }
        public static bool DefinePhraseChoiceVariable(Context context, IContinuation succ, IFailure fail, params object[] args)
        {
            List<IContent> contents = context.Contents;
            string name = contents[0].Name;
            PluginEnvironment plugenv = (PluginEnvironment) args[0];

            List<List<string>> options = new List<List<string>>();
            List<string> curropt = new List<string>();
            for (int ii = 1; ii < contents.Count; ii++) {
                if (contents[ii] == Special.ArgDelimSpecial) {
                    options.Add(curropt);
                    curropt = new List<string>();
                } else
                    curropt.Add(contents[ii].Name.ToLower());
            }
            options.Add(curropt);

            context.Map.Add(name, new PhraseChoiceVariable(name, options, plugenv, (WordComparer) context.LookupSimple("$Compare")));

            Context empty = new Context(context, new List<IContent>());
            succ.Continue(empty, fail);

            return true;
        }
 // Don't call this.  Call MatchAgainst
 protected Matcher(double salience, IParsedPhrase input, List <IParsedPhrase> unmatched, IContinuation succ)
     : base(salience, 2 * 4, 10, succ)
 {
     if (input == null)
     {
         throw new NullReferenceException("Input cannot be null.");
     }
     this.input     = input;
     this.unmatched = new List <IParsedPhrase>(unmatched);   // make copy, or %opt-fail has effects
 }
 public CallableAsContinuation(ICallable callable, IContinuation succ)
 {
     this.callable = callable;
     this.succ     = succ;
 }
 ProcedureCallContinuation(ProcedureSignature invokedProcedure, IContinuation currentContinuation)
 {
     procedure    = invokedProcedure;
     continuation = currentContinuation;
 }
        public static Evaluator MakeMatcherContinue(double salience, Context context, IParsedPhrase input, List <IParsedPhrase> unmatched, IContinuation succ)
        {
            context.Map["$check"] = null;

            // Match this to first constituent, the continue for others
            Matcher matcheval = new Matcher(salience, input, unmatched, succ);

            ContinuationAppender appender = new ContinuationAppender(context, matcheval);

            Evaluator eval = new Evaluator(salience, ArgumentMode.SingleArgument, appender.AsIndex(0), appender.AsIndex(1), true);

            return(eval);
        }
示例#35
0
 public Continuation(IContinuation <R> content)
 {
     Content = content;
 }
示例#36
0
 public ContinuationSource(IContinuation continuation)
 {
     Continuation = continuation;
 }
 public void Start(IContinuation continuation)
 {
     Execute(continuation);
 }
示例#38
0
            public ThenContinueExpression ContinueWith(IContinuation continuation)
            {
                _handler.Value.AddContinuation(continuation);

                return(this);
            }
 internal abstract void AddContinuation(IContinuation continuation);
        public override bool Evaluate()
        {
            List <IContent> contents = context.Contents;

            if (contents.Count == 0)
            {
                Unilog.Notice(this, "Ran out of template before input");
                fail.Fail("Ran out of tokens before matched all input", succ);
                return(true);
            }

            // Does our first element match the whole thing?
            IContent first = contents[0];

            //Console.WriteLine("Match " + first.Name + " against " + input.Text + " + " + unmatched.Count);

            // always consider dropping interjections
            IFailure myfail = fail;

            if (input.Part == "UH")
            {
                IFailure skipfail;
                if (unmatched.Count == 0)
                {
                    // then fail becomes success!
                    skipfail = new ContinueCodelet(salience, context, succ, fail);
                }
                else
                {
                    Matcher matchskip = new Matcher(salience, unmatched[0], unmatched.GetRange(1, unmatched.Count - 1), succ);
                    skipfail = new ContinueCodelet(salience, context, matchskip, fail);
                }

                myfail = skipfail;
            }

            if (first.Name == "*")
            {
                // Failure state has the first POS eaten by the star
                StarEater eater = new StarEater(coderack, salience, this, StarUtilities.NextStarName(context, "*"), true);

                if (context.Contents.Count == 1)
                {
                    // We ran out elements, but we still have some unmatched
                    coderack.AddCodelet(eater, "Evaluate *");
                    return(true);
                }
                else
                {
                    MatchAgainst(salience, context.ChildRange(1), input, unmatched, succ, eater);
                    return(true);
                }
            }
            else if (first.Name == "_")
            {
                StarEater eater = new StarEater(coderack, salience, this, StarUtilities.NextStarName(context, "_"), true);

                coderack.AddCodelet(eater, "Evaluate _");
                return(true);
            }
            else if (first.Name == "%opt")
            {
                // Try with, and if that fails, do without
                int end = context.Contents.IndexOf(Special.EndDelimSpecial);
                if (end == -1)
                {
                    // It's all optional-- but on fail return to match to ensure blank
                    Context   without     = new Context(context, new List <IContent>());
                    Evaluator evalfail    = MakeMatcherContinue(salience, without, input, unmatched, succ);
                    IFailure  withoutfail = new ContinueCodelet(salience, without, evalfail, myfail);

                    Context with = new Context(context, context.Contents.GetRange(1, context.Contents.Count - 1));
                    Matcher.MatchAgainst(salience, with, input, unmatched, succ, withoutfail);
                }
                else
                {
                    Context   without     = new Context(context, context.Contents.GetRange(end + 1, context.Contents.Count - (end + 1)));
                    Evaluator evalfail    = MakeMatcherContinue(salience, without, input, unmatched, succ);
                    IFailure  withoutfail = new ContinueCodelet(salience, without, evalfail, myfail);

                    Context with = new Context(context, context.Contents.GetRange(1, end - 1));
                    with.Contents.AddRange(without.Contents);
                    Matcher.MatchAgainst(salience, with, input, unmatched, succ, withoutfail);
                }
                return(true);
            }
            else if (first is Variable)
            {
                if (((Variable)first).Match(context, input))
                {
                    ContinueNextUnmatched(context.ChildRange(1));
                    return(true);
                }
                else if (input.IsLeaf)
                {
                    // we didn't match-- fail!
                    Unilog.Notice(this, first.Name + " does not match " + input.Text);
                    fail.Fail("Initial variable didn't match", succ);
                    return(true);
                }
                else
                {
                    GroupPhrase groupPhrase = new GroupPhrase(input);
                    unmatched.InsertRange(0, groupPhrase.GetRange(1));
                    // Call again with the same evaluated first argument
                    Matcher matchrest = new Matcher(salience, groupPhrase.GetBranch(0), unmatched, succ);
                    matchrest.Continue(context, myfail);
                    return(true);
                }
            }
            else if (first is Value && ((Value)first).Data is MatchProduceAgent)
            {
                IContinuation mysucc = succ;
                // Check if we have values to match later
                if (unmatched.Count != 0)
                {
                    mysucc = MakeNextUnmatchedContinue(mysucc);
                }
                ContextAppender appender = new ContextAppender(salience, context, -1, mysucc);

                MatchProduceAgent agent = (MatchProduceAgent)((Value)first).Data;
                context.Map["$check"] = input;
                ContinueToCallAgent codelet = new ContinueToCallAgent(agent, appender);

                IFailure deepenfail = myfail;
                if (!input.IsLeaf)
                {
                    // Continue to deeper
                    GroupPhrase groupPhrase = new GroupPhrase(input);
                    unmatched.InsertRange(0, groupPhrase.GetRange(1));
                    // Call again with the same evaluated first argument
                    Matcher matchrest = new Matcher(salience, groupPhrase.GetBranch(0), unmatched, succ);
                    deepenfail = new FailToContinue(context, matchrest, myfail);
                }

                codelet.Continue(context, deepenfail);
                return(true);
            }

            if (first is Word && input.IsLeaf)
            {
                WordComparer comparer = (WordComparer)context.LookupSimple("$Compare");
                if (comparer.Match(input.Text, first.Name))
                {
                    ContinueNextUnmatched(context.ChildRange(1));
                    return(true);
                }
                else
                {
                    // failure!
                    fail.Fail(string.Format("Pattern [{0}] does not match [{1}]", first.Name, input.Text), succ);
                    return(true);
                }
            }
            else if (first is Word)
            {
                GroupPhrase groupPhrase = new GroupPhrase(input);
                unmatched.InsertRange(0, groupPhrase.GetRange(1));
                Matcher matchcont = new Matcher(salience, groupPhrase.GetBranch(0), unmatched, succ);
                matchcont.Continue(context, myfail);
                return(true);
            }

            // We can't handle this!  fail
            fail.Fail("Unknown first element", succ);

            return(true);
        }
 public bool Fail(string reason, IContinuation skip)
 {
     return(succ.Continue(context, fail));
 }
 public FailToContinue(Context context, IContinuation succ, IFailure fail)
 {
     this.context = context;
     this.succ    = succ;
     this.fail    = fail;
 }
示例#43
0
 /// <summary>
 /// Create a yield exception, with a continuation
 /// representing the work to do later.
 /// </summary>
 public YieldException(IContinuation continuation)
 {
     Continuation = continuation;
 }
示例#44
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="s"></param>
        /// <exception cref="ChatUnavailableException"></exception>
        ///
        /// <returns></returns>
        public static (IContinuation continuation, ChatContinuation, List <CommentData> actions) ParseYtInitialData(string s)
        {
            var json = DynamicJson.Parse(s);

            if (!json.IsDefined("contents"))
            {
                //"{\"responseContext\":{\"errors\":{\"error\":[{\"domain\":\"gdata.CoreErrorDomain\",\"code\":\"INVALID_VALUE\",\"debugInfo\":\"Error decrypting and parsing the live chat ID.\",\"externalErrorMessage\":\"不明なエラーです。\"}]},\"serviceTrackingParams\":[{\"service\":\"CSI\",\"params\":[{\"key\":\"GetLiveChat_rid\",\"value\":\"0x3365759ba77f978f\"},{\"key\":\"c\",\"value\":\"WEB\"},{\"key\":\"cver\",\"value\":\"2.20190529\"},{\"key\":\"yt_li\",\"value\":\"1\"}]},{\"service\":\"GFEEDBACK\",\"params\":[{\"key\":\"e\",\"value\":\"23720702,23736685,23744176,23750984,23751767,23752869,23755886,23755898,23759224,23766102,23767634,23771992,23785333,23788845,23793834,23794471,23799777,23804281,23804294,23805410,23806435,23808949,23809331,23810273,23811378,23811593,23812530,23812566,23813310,23813548,23813622,23813949,23814199,23814507,23815144,23815164,23815172,23815485,23815949,23817343,23817794,23817825,23818213,9407610,9441381,9449243,9471235\"},{\"key\":\"logged_in\",\"value\":\"1\"}]},{\"service\":\"GUIDED_HELP\",\"params\":[{\"key\":\"creator_channel_id\",\"value\":\"UCK6F1ecql0T_9hHGTw7heBA\"},{\"key\":\"logged_in\",\"value\":\"1\"}]},{\"service\":\"ECATCHER\",\"params\":[{\"key\":\"client.name\",\"value\":\"WEB\"},{\"key\":\"client.version\",\"value\":\"2.20190529\"},{\"key\":\"innertube.build.changelist\",\"value\":\"250485423\"},{\"key\":\"innertube.build.experiments.source_version\",\"value\":\"250547910\"},{\"key\":\"innertube.build.label\",\"value\":\"youtube.ytfe.innertube_20190528_7_RC1\"},{\"key\":\"innertube.build.timestamp\",\"value\":\"1559140061\"},{\"key\":\"innertube.build.variants.checksum\",\"value\":\"7e46d96e46a45788f840d135c2cf4890\"},{\"key\":\"innertube.run.job\",\"value\":\"ytfe-innertube-replica-only.ytfe\"}]}],\"webResponseContextExtensionData\":{\"ytConfigData\":{\"csn\":\"4wLwXOyiG5OPgAOH4LYI\",\"visitorData\":\"CgtpTXJTMXZJR3ZLayjjhcDnBQ%3D%3D\",\"sessionIndex\":1}}},\"trackingParams\":\"CAAQ0b4BIhMIrKDMwNTD4gIVkwdgCh0HsA0B\"}";
                throw new YouTubeLiveServerErrorException();
            }
            if (!json.contents.IsDefined("liveChatRenderer"))
            {
                throw new ChatUnavailableException();
            }
            if (!json.contents.liveChatRenderer.IsDefined("continuations"))
            {
                throw new ContinuationNotExistsException();
            }
            var chatContinuation = new ChatContinuation
            {
                AllChatContinuation  = (string)json.contents.liveChatRenderer.header.liveChatHeaderRenderer.viewSelector.sortFilterSubMenuRenderer.subMenuItems[1].continuation.reloadContinuationData.continuation,
                JouiChatContinuation = (string)json.contents.liveChatRenderer.header.liveChatHeaderRenderer.viewSelector.sortFilterSubMenuRenderer.subMenuItems[0].continuation.reloadContinuationData.continuation,
            };

            IContinuation continuation;
            var           lowContinuations = json.contents.liveChatRenderer.continuations;

            if (lowContinuations[0].IsDefined("invalidationContinuationData"))
            {
                var data = lowContinuations[0].invalidationContinuationData;
                var inv  = new InvalidationContinuation
                {
                    Continuation = data.continuation,
                    TimeoutMs    = (int)data.timeoutMs,
                    ObjectId     = data.invalidationId.objectId
                };
                continuation = inv;
            }
            else
            {
                var data  = lowContinuations[0].timedContinuationData;
                var timed = new TimedContinuation()
                {
                    Continuation = data.continuation,
                    TimeoutMs    = (int)data.timeoutMs,
                };
                continuation = timed;
            }

            var dataList = new List <CommentData>();

            if (json.contents.liveChatRenderer.IsDefined("actions"))
            {
                foreach (var action in json.contents.liveChatRenderer.actions)
                {
                    try
                    {
                        if (action.IsDefined("addChatItemAction"))
                        {
                            var item = action.addChatItemAction.item;
                            if (item.IsDefined("liveChatTextMessageRenderer"))
                            {
                                var commentData = (CommentData)Parser.ParseLiveChatTextMessageRenderer(item.liveChatTextMessageRenderer);
                                commentData.Raw = action.ToString();
                                dataList.Add(commentData);
                            }
                            else if (item.IsDefined("liveChatPaidMessageRenderer"))
                            {
                                var ren         = item.liveChatPaidMessageRenderer;
                                var commentData = Parser.ParseLiveChatPaidMessageRenderer(ren);
                                commentData.Raw = action.ToString();
                                dataList.Add(commentData);
                            }
                        }
                    }
                    catch (ParseException ex)
                    {
                        throw new ParseException(s, ex);
                    }
                }
            }



            //var actions = lowLiveChat.contents.liveChatRenderer.actions;
            //var actionList = new List<IAction>();
            //foreach(var action in actions)
            //{
            //    if(action.addChatItemAction != null)
            //    {
            //        if(action.addChatItemAction.item.liveChatTextMessageRenderer != null)
            //        {
            //            actionList.Add(new TextMessage(action.addChatItemAction.item.liveChatTextMessageRenderer));
            //        }
            //        else if(action.addChatItemAction.item.liveChatPaidMessageRenderer != null)
            //        {
            //            actionList.Add(new PaidMessage(action.addChatItemAction.item.liveChatPaidMessageRenderer));
            //        }
            //    }
            //}
            return(continuation, chatContinuation, dataList);
        }
示例#45
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="getLiveChatJson"></param>
        /// <returns></returns>
        /// <exception cref="ContinuationContentsNullException"></exception>
        /// <exception cref="NoContinuationException">放送終了</exception>
        public static (IContinuation, List <CommentData>, string sessionToken) ParseGetLiveChat(string getLiveChatJson)
        {
            try
            {
                var json = DynamicJson.Parse(getLiveChatJson);
                if (!json.response.IsDefined("continuationContents"))
                {
                    throw new ContinuationContentsNullException();
                }

                if (!json.response.continuationContents.liveChatContinuation.IsDefined("continuations"))
                {
                    throw new ContinuationNotExistsException();
                }

                IContinuation continuation;
                var           continuations = json.response.continuationContents.liveChatContinuation.continuations;
                if (continuations[0].IsDefined("invalidationContinuationData"))
                {
                    var invalidation = continuations[0].invalidationContinuationData;
                    var inv          = new InvalidationContinuation
                    {
                        Continuation             = invalidation.continuation,
                        TimeoutMs                = (int)invalidation.timeoutMs,
                        ObjectId                 = invalidation.invalidationId.objectId,
                        ObjectSource             = (int)invalidation.invalidationId.objectSource,
                        ProtoCreationTimestampMs = invalidation.invalidationId.protoCreationTimestampMs
                    };
                    continuation = inv;
                }
                else
                {
                    var timed = continuations[0].timedContinuationData;
                    var inv   = new TimedContinuation
                    {
                        Continuation = timed.continuation,
                        TimeoutMs    = (int)timed.timeoutMs,
                    };
                    continuation = inv;
                }

                var dataList = new List <CommentData>();
                if (json.response.continuationContents.liveChatContinuation.IsDefined("actions"))
                {
                    var actions = json.response.continuationContents.liveChatContinuation.actions;
                    foreach (var action in actions)
                    {
                        if (action.IsDefined("addChatItemAction"))
                        {
                            var item = action.addChatItemAction.item;
                            if (item.IsDefined("liveChatTextMessageRenderer"))
                            {
                                dataList.Add(Parser.ParseLiveChatTextMessageRenderer(item.liveChatTextMessageRenderer));
                            }
                            else if (item.IsDefined("liveChatPaidMessageRenderer"))
                            {
                                var ren         = item.liveChatPaidMessageRenderer;
                                var commentData = Parser.ParseLiveChatPaidMessageRenderer(ren);
                                dataList.Add(commentData);
                            }
                        }
                    }
                }
                var sessionToken = json.xsrf_token;
                //var actions = lowLiveChat.response.continuationContents.liveChatContinuation.actions;
                //var actionList = new List<IAction>();
                //if (actions != null)
                //{
                //    foreach (var action in actions)
                //    {
                //        if (action.addChatItemAction != null)
                //        {
                //            if (action.addChatItemAction.item.liveChatTextMessageRenderer != null)
                //            {
                //                actionList.Add(new TextMessage(action.addChatItemAction.item.liveChatTextMessageRenderer));
                //            }
                //            else if (action.addChatItemAction.item.liveChatPaidMessageRenderer != null)
                //            {
                //                actionList.Add(new PaidMessage(action.addChatItemAction.item.liveChatPaidMessageRenderer));
                //            }
                //        }
                //    }
                //}
                //return (continuation, actionList);
                return(continuation, dataList, sessionToken);
            }
            catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
            {
                throw new ParseException(getLiveChatJson, ex);
            }
        }
 public bool Fail(string reason, IContinuation succ)
 {
     coderack.AddCodelet((Codelet)this.Clone(), "Fail: " + reason);
     return(true);
 }
示例#47
0
 public void AddContinuation(IContinuation continuation)
 {
     Sources.Add(new ContinuationSource(continuation));
 }
示例#48
0
 public static void True(this IContinuation <bool?> expectation, string message)
 {
     expectation.Equal(true, message);
 }
示例#49
0
 public bool Call(object value, IContinuation succ, IFailure fail)
 {
     return(calllet(arena, salience, value, succ, fail, args));
 }
示例#50
0
 // default is failure to rescue
 public virtual bool CallRescue(Coderack coderack, IParsedPhrase input, PatternTemplateSource patternTemplateSource, string reason, IContinuation skip, IContinuation succ, IFailure fail)
 {
     return(fail.Fail(reason, skip));
 }
示例#51
0
 public static void False(this IContinuation <bool?> expectation)
 {
     expectation.False(null);
 }
        public static void MatchAgainst(double salience, Context context, IParsedPhrase input, List <IParsedPhrase> unmatched, IContinuation succ, IFailure fail)
        {
            Evaluator eval = MakeMatcherContinue(salience, context, input, unmatched, succ);

            eval.Continue(context, fail);
        }
示例#53
0
 public IFailure MakeFailure(IParsedPhrase input, PatternTemplateSource patternTemplateSource, IContinuation succ, IFailure fail, Coderack coderack)
 {
     return(new FailletWrapper(FailToTryToRescue, this, input, patternTemplateSource, succ, fail, coderack));
 }
示例#54
0
 public static void False(this IContinuation <bool?> expectation, string message)
 {
     expectation.Equal(false, message);
 }
 public void AddContinuation(IContinuation continuation)
 {
     _continuations.Add(continuation);
 }
示例#56
0
 public static void True(this IContinuation <bool> expectation)
 {
     expectation.True(null);
 }
示例#57
0
 public abstract bool Call(object value, IContinuation succ, IFailure fail);
示例#58
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="vid"></param>
        /// <param name="initialContinuation"></param>
        /// <param name="cc"></param>
        /// <returns></returns>
        /// <exception cref="ReloadException"></exception>
        public async Task ReceiveAsync(string vid, IContinuation initialContinuation, CookieContainer cc)
        {
            _cts = new CancellationTokenSource();

            var continuation = initialContinuation;

            while (!_cts.IsCancellationRequested)
            {
                var getLiveChatUrl = $"https://www.youtube.com/live_chat/get_live_chat?continuation={System.Web.HttpUtility.UrlEncode( continuation.Continuation)}&pbj=1";
                //var wc = new MyWebClient(cc);
                var    ua = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.2924.87 Safari/537.36";
                string getLiveChatJson = null;
                try
                {
                    var getLiveChatBytes = await _server.GetBytesAsync(getLiveChatUrl);

                    getLiveChatJson         = Encoding.UTF8.GetString(getLiveChatBytes);
                    var(c, a, sessionToken) = Tools.ParseGetLiveChat(getLiveChatJson);
                    continuation            = c;
                    if (a.Count > 0)
                    {
                        if (c is ITimedContinuation timed)
                        {
                            var interval = c.TimeoutMs / a.Count;
                            foreach (var action in a)
                            {
                                ActionsReceived?.Invoke(this, new List <CommentData> {
                                    action
                                });
                                await Task.Delay(interval, _cts.Token);
                            }
                        }
                        else if (c is IInvalidationContinuation invalid)
                        {
                            ActionsReceived?.Invoke(this, a);
                            await Task.Delay(1000, _cts.Token);
                        }
                        else if (c is IReloadContinuation)
                        {
                            throw new ReloadException();
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                        await Task.Delay(1000, _cts.Token);
                    }
                }
                catch (WebException ex)
                {
                    throw new ReloadException(ex);
                }
                catch (HttpRequestException ex)
                {
                    throw new ReloadException(ex);
                }
                catch (ParseException ex)
                {
                    _logger.LogException(ex, "get_live_chatのパースに失敗", getLiveChatJson);
                }
                catch (TaskCanceledException)
                {
                    break;
                }
                catch (ContinuationContentsNullException)
                {
                    //放送終了
                    break;
                }
                catch (ContinuationNotExistsException)
                {
                    break;
                }
            }
        }
 public Evaluator MakeNextUnmatchedContinue(IContinuation succ)
 {
     return(MakeMatcherContinue(salience, context.ChildRange(1), unmatched[0], unmatched.GetRange(1, unmatched.Count - 1), succ));
 }
示例#60
0
		internal void RemoveContinuation (IContinuation continuation)
		{
			continuations.Remove (continuation);
		}