Esempio n. 1
0
        /// <summary>
        /// 静态
        /// </summary>
        static TranslationHelper()
        {
            var runtime = ChakraRuntime.Create();

            _baseUrl         = "http://translate.google.cn/translate_a/single";
            _cookieContainer = new CookieContainer();
            _chakraContext   = runtime.CreateContext(true);

            _googleTransBaseUrl = "https://translate.google.com/";
            _googleTkk          = "";

            var baseResultHtml = HttpHelper.GetRequest(_googleTransBaseUrl, _cookieContainer, null);

            int index      = baseResultHtml.IndexOf("tkk:");
            int startIndex = baseResultHtml.IndexOf("'", index);
            int endIndex   = baseResultHtml.IndexOf("'", startIndex + 1);

            _googleTkk = baseResultHtml.Substring(startIndex + 1, endIndex - startIndex);
            //Regex re = new Regex(@"(?<=tkk=')(.*?)(?=')");
            //Regex re = new Regex("(?<=(tkk:'))[.\\s\\S]*?(?=(';))");
            //_googleTkk = re.Match(baseResultHtml).ToString();

            var jsFileText = File.ReadAllText("../translateLib/gettk.js");

            _chakraContext.RunScript(jsFileText); //运行脚本
        }
Esempio n. 2
0
 public void Load(string script)
 {
     api.Clear(false);
     //manager.ImagePath = WorkPath;
     initJSRuntime();
     injectJSConverter();
     initAPI();
     context.RunScript(script);
 }
Esempio n. 3
0
        static void projectModuleClass(string projectTo, string moduleName, string className)
        {
            string script_setRootObject = $"var {projectTo}={{}}";
            string script_importModule  = $"import {{{className}}} from '{moduleName}'; {projectTo}=new {className}();";

            context.RunScript(script_setRootObject);
            System.IO.File.WriteAllText("__M.js", script_importModule);
            context.ServiceNode.GetService <IContextSwitchService>().With(
                () => { loader.LoadModule("__M.js"); }
                );
        }
Esempio n. 4
0
        private void initJSRuntime()
        {
            runtime = ChakraRuntime.Create();
#if DEBUG
            context = runtime.CreateContext(true);
#else
            context = runtime.CreateContext(false);
#endif
            JSRequireLoader.EnableRequire(context, WorkPath);
            var s = Properties.Resources.boot;
            context.RunScript(Properties.Resources.boot);
        }
Esempio n. 5
0
 public void test1()
 {
     ChakraRuntime runtime = ChakraRuntime.Create();
     ChakraContext context = runtime.CreateContext(true);
     var           s       = context.RunScript("1+1");
     //context.GlobalObject.Binding.SetFunction<int, int>("add", Add);
     //context.RunScript("function test(callback){callback('hello world')})");
     //context.ServiceNode.GetService<IJSValueConverterService>().RegisterMethodConverter<string>();
     //context.GlobalObject.CallMethod<Action<string>>("test", echo);
     DebugEcho instance = new DebugEcho();
     //context.ServiceNode.GetService<IJSValueConverterService>().RegisterProxyConverter<DebugEcho>(
     //    (binding, instance, serviceNode) =>
     //    {
     //        binding.SetMethod<string>("echo",instance.Echo);
     //    });
     //DebugEcho obj = new DebugEcho();
     //context.GlobalObject.WriteProperty<DebugEcho>("debugEcho", obj);
 }
Esempio n. 6
0
        string ParseValues(StateSubmissionField field, JObject source, ChakraRuntime runtime)
        {
            string output = string.Empty;

            foreach (string value in field.Values)
            {
                if (value.StartsWith("literal:"))
                {
                    output += value.Replace("literal:", string.Empty);
                }
                else
                {
                    try
                    {
                        var token       = source.SelectToken(value);
                        var tokenString = (string)token;
                        tokenString = tokenString == null ? string.Empty : tokenString;


                        if (!string.IsNullOrEmpty(field.OnGetValueJavascript) && !string.IsNullOrEmpty(tokenString))
                        {
                            ChakraContext context = runtime.CreateContext(true);
                            context.GlobalObject.WriteProperty <string>("token", tokenString);
                            context.RunScript(field.OnGetValueJavascript);
                            tokenString = context.GlobalObject.CallFunction <string>("onGetValue");
                        }

                        output += tokenString;
                    }
                    catch (Exception e1)
                    {
                        int x = 1;
                    }
                }
            }

            return(Format(field.MaxLength, field.Format, output));
        }
Esempio n. 7
0
 public void RunScript(string jsContent)
 {
     _context.RunScript(jsContent);
 }
Esempio n. 8
0
        public override void Execute(Action onSuccess, Action <Exception> onFailure)
        {
            try
            {
                string filename = string.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}_{7}.txt",
                                                Configuration.State,
                                                StartDate.Month,
                                                StartDate.Day,
                                                StartDate.Year,
                                                EndDate.Month,
                                                EndDate.Day,
                                                EndDate.Year,
                                                DateTime.Now.Ticks);

                MongoClient    client   = new MongoClient(System.Environment.GetEnvironmentVariable("ScreeningCosmosDb", EnvironmentVariableTarget.Process));
                IMongoDatabase database = client.GetDatabase("Screening");
                IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("Screening");

                OutputText = string.Empty;
                ChakraRuntime runtime = ChakraRuntime.Create();

                JObject headerObject = new JObject();
                headerObject.Add("StartMonth", StartDate.Month.ToString());
                headerObject.Add("StartDay", StartDate.Day.ToString());
                headerObject.Add("StartYear", StartDate.Year.ToString());
                headerObject.Add("EndMonth", EndDate.Month.ToString());
                headerObject.Add("EndDay", EndDate.Day.ToString());
                headerObject.Add("EndYear", EndDate.Year.ToString());
                headerObject.Add("Ticks", DateTime.Now.Ticks.ToString());
                headerObject.Add("RecordCount", Screenings.Count);

                List <string> headerValues = new List <string>();
                if (Configuration.HeaderConfiguration != null)
                {
                    foreach (StateSubmissionField field in Configuration.HeaderConfiguration)
                    {
                        headerValues.Add(ParseValues(field, headerObject, runtime));
                    }

                    if (Configuration.HeaderConfiguration.Count > 0)
                    {
                        OutputText += ((Configuration.EncloseFieldsInQuotes ? "\"" : string.Empty) + string.Join(Configuration.DefaultDelimiter, headerValues) + (Configuration.EncloseFieldsInQuotes ? "\"" : string.Empty)) + "\n";
                    }
                }

                if (Screenings != null)
                {
                    List <Screening> screeningsToPrint = new List <Screening>();
                    foreach (var screening in Screenings)
                    {
                        var jsonObject = JObject.FromObject(screening);

                        if (!string.IsNullOrEmpty(Configuration.OnExecuteJavascript))
                        {
                            var           jsonObjectString = jsonObject.ToString();
                            ChakraContext context          = runtime.CreateContext(true);
                            context.GlobalObject.WriteProperty <string>("screeningString", jsonObjectString);
                            context.RunScript(Configuration.OnExecuteJavascript);
                            context.RunScript("var screening=JSON.parse(screeningString);");
                            jsonObjectString = context.GlobalObject.CallFunction <string>("onExecute");
                            jsonObject       = JObject.Parse(jsonObjectString);
                        }

                        JToken forcePrint = null;
                        if (jsonObject.TryGetValue("ForcePrint", out forcePrint))
                        {
                            if (forcePrint.Value <bool>() == true)
                            {
                                screeningsToPrint.Add(screening);
                                continue;
                            }
                        }

                        jsonObject.Add("Type", "StateSubmissionRecord");
                        jsonObject.Add("State", Configuration.State);
                        jsonObject.Add("DatePrepared", DateTime.Now.ToString());
                        jsonObject.Add("FileProduced", string.Empty);
                        jsonObject.Add("DateSent", string.Empty);
                        jsonObject.Add("DateValidated", string.Empty);
                        jsonObject.Add("OutputFile", filename);

                        collection.InsertOne(
                            MongoDB.Bson.Serialization.BsonSerializer.Deserialize <BsonDocument>(jsonObject.ToString()));

                        List <string> screeningValues = new List <string>();

                        if (Configuration.RecordConfiguration != null)
                        {
                            foreach (StateSubmissionField field in Configuration.RecordConfiguration)
                            {
                                screeningValues.Add(ParseValues(field, jsonObject, runtime));
                            }
                        }

                        OutputText += ((Configuration.EncloseFieldsInQuotes ? "\"" : string.Empty) +
                                       string.Join(Configuration.DefaultDelimiter, screeningValues) +
                                       (Configuration.EncloseFieldsInQuotes ? "\"" : string.Empty)) + "\n";
                    }

                    if (screeningsToPrint.Count > 0)
                    {
                        var unitOfWork = new GeneratePhysicalStatePacket();
                        unitOfWork.State      = Configuration.State;
                        unitOfWork.StartDate  = StartDate;
                        unitOfWork.EndDate    = EndDate;
                        unitOfWork.Screenings = screeningsToPrint;
                        unitOfWork.Execute(() => {
                        }, (f) => { });
                    }
                }

                //Microsoft.Azure.KeyVault.KeyVaultKeyResolver cloudResolver = new Microsoft.Azure.KeyVault.KeyVaultKeyResolver(GetToken);
                //var rsa = cloudResolver.ResolveKeyAsync(@"https://neonprod01vault.vault.azure.net/keys/FileStorage",
                //    CancellationToken.None).Result;
                //BlobEncryptionPolicy policy = new BlobEncryptionPolicy(rsa, cloudResolver);
                //BlobRequestOptions options = new BlobRequestOptions() { EncryptionPolicy = policy };

                StorageCredentials  storageCredentials = new StorageCredentials(System.Environment.GetEnvironmentVariable("StorageAccountName", EnvironmentVariableTarget.Process), System.Environment.GetEnvironmentVariable("StorageKeyVault", EnvironmentVariableTarget.Process));
                CloudStorageAccount account            = new CloudStorageAccount(storageCredentials, useHttps: true);
                CloudBlobClient     storageClient      = account.CreateCloudBlobClient();
                CloudBlobContainer  storageContainer   = storageClient.GetContainerReference("statepackages");
                storageContainer.CreateIfNotExists(BlobContainerPublicAccessType.Off);

                CloudBlockBlob blob = storageContainer.GetBlockBlobReference(filename);

                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(OutputText ?? "")))
                {
                    if (stream.Length == 0)
                    {
                        return;
                    }
                    blob.UploadFromStream(stream, stream.Length, null, null, null);
                }

                string filter = string.Format("{{ Type: 'StateSubmissionRecord', OutputFile : '{0}'}}", filename);
                var    update = Builders <BsonDocument> .Update.Set("FileProduced", DateTime.Now.ToString());

                collection.UpdateMany(filter, update);
            }
            catch (Exception e)
            {
                onFailure(e);
            }

            onSuccess();
        }
Esempio n. 9
0
 protected string runScript(string fileName)
 {
     return(context.RunScript(Properties.Resources.ResourceManager.GetString(fileName)));
 }
Esempio n. 10
0
        public static byte[] RunScript(string file, HttpRequestHeader req, HttpRespondHeader res)
        {
            using (ChakraContext context = Runtime.CreateContext(true)) {
                //HttpRequestHeader
                if (!registered)
                {
                    context.ServiceNode.GetService <IJSValueConverterService>().RegisterProxyConverter <HttpRequestHeader>( //register the object converter
                        (binding, instance, serviceNode) => {
                        binding.SetFunction("getServer", new Func <HttpServers.BaseServer>(() => instance.Server));
                        binding.SetFunction("getHeaderKeys", new Func <Dictionary <string, string> >(() => instance.HeaderKeys));
                        binding.SetFunction("getParameters", new Func <System.Collections.Specialized.NameValueCollection>(() => instance.Parameters));
                        binding.SetFunction("getParametersJSON", new Func <string>(() => instance.Parameters.Serialize()));
                        binding.SetFunction("getAbsoluteFilePath", new Func <string>(() => instance.AbsoluteFilePath));
                    });
                    // HttpRespondHeader
                    context.ServiceNode.GetService <IJSValueConverterService>().RegisterProxyConverter <HttpRespondHeader>( //register the object converter
                        (binding, instance, serviceNode) =>
                    {
                        binding.SetMethod <string, string>("setState", (http, state) => instance.SetState(http.Equals("HTTP/1.0") ? HttpVersion.HTTP1_0 : http.Equals("HTTP/1.1") ? HttpVersion.HTTP2_0 : HttpVersion.UNKNOWN, state));
                        binding.SetMethod <string, string>("addHeader", (key, value) => instance.AddHeader(key, value));
                        binding.SetMethod <string>("setBody", (body) => instance.SetBody(body));
                        binding.SetMethod <System.Net.Sockets.TcpClient>("send", c => {
                            byte[] b = instance.Build();
                            c.GetStream().Write(b, 0, b.Length);
                            c.GetStream().Flush();
                        });
                        binding.SetMethod("markAsResponded", instance.Responded);
                    });
                    // TcpClient stuff
                    context.ServiceNode.GetService <IJSValueConverterService>().RegisterProxyConverter <System.Net.Sockets.TcpClient>( //register the object converter
                        (binding, instance, serviceNode) =>
                    {
                        binding.SetMethod <string>("sendText", (s) => {
                            byte[] b = Encoding.UTF8.GetBytes(s);
                            instance.GetStream().Write(b, 0, b.Length);
                            instance.GetStream().Flush();
                        });
                        binding.SetMethod <HttpRespondHeader>("send", (s) => {
                            byte[] b = s.Build();
                            instance.GetStream().Write(b, 0, b.Length);
                            instance.GetStream().Flush();
                        });
                        binding.SetFunction <string>("getIP", () => ((System.Net.IPEndPoint)instance.Client.RemoteEndPoint).Address.ToString());
                        binding.SetFunction <int>("getPort", () => ((System.Net.IPEndPoint)instance.Client.RemoteEndPoint).Port);
                        binding.SetMethod("close", instance.Close);
                        binding.SetFunction <string>("readString", () => {
                            byte[] b = new byte[instance.Available];
                            instance.GetStream().Read(b, 0, b.Length);
                            return(Encoding.UTF8.GetString(b));
                        });
                        binding.SetMethod <string, bool>("sendFile", (file, isBigFile) => { instance.Client.SendFile(file, null, null, isBigFile ? System.Net.Sockets.TransmitFileOptions.UseSystemThread : System.Net.Sockets.TransmitFileOptions.UseDefaultWorkerThread); });
                    });

                    registered = true;
                }


                context.GlobalObject.WriteProperty("RequestResult", "");
                context.GlobalObject.WriteProperty("RequestHandler", req);
                context.GlobalObject.WriteProperty("RespondHandler", res);
                context.GlobalObject.WriteProperty("Client", req.Client);
                context.GlobalObject.WriteProperty("AutoFlush", true);
                context.GlobalObject.Binding.SetMethod <string>("log", (s) => Console.WriteLine(s));
                context.GlobalObject.Binding.SetMethod <string>("send", (s) => {
                    req.Client.GetStream().Write(Encoding.UTF32.GetBytes(s), 0, s.Length);
                    if (context.GlobalObject.ReadProperty <bool>("AutoFlush"))
                    {
                        req.Client.GetStream().Flush();
                    }
                });
                context.GlobalObject.Binding.SetMethod("flush", () => req.Client.GetStream().Flush());
                context.GlobalObject.Binding.SetMethod("closeStream", () => req.Client.GetStream().Dispose());
                context.GlobalObject.Binding.SetMethod("closeConnection", () => req.Client.Close());

                try
                {
                    context.RunScript(System.IO.File.ReadAllText(file));
                }
                catch (Exception exp)
                {
                    ErrorLogger.WithTrace(req.Server.Settings, string.Format("[Warning][Backend error => RunScript()] : exception-message : {0}.\nstacktrace : {1}\n", exp.Message, exp.StackTrace), typeof(ChakraCoreObject));
                }

                if (res.DidRespond())
                {
                    Runtime.CollectGarbage();
                    return(HttpRequestHeader.ContentSplitter);
                }

                else
                {
                    byte[] b = Encoding.UTF8.GetBytes(context.GlobalObject.ReadProperty <string>("RequestResult"));
                    Runtime.CollectGarbage();
                    return(b);
                }
            }


            //context.Dispose();
        }
Esempio n. 11
0
 /// <summary>
 /// 获取TK
 /// </summary>
 /// <param name="originalText"></param>
 /// <returns></returns>
 private static string GetTK(string originalText)
 {
     _chakraContext.GlobalObject.WriteProperty("originalText", originalText);
     return(_chakraContext.RunScript("tk(\"" + originalText + "\",\"" + _googleTkk + "\")"));
 }