Beispiel #1
0
        protected internal Result CreateNewResult(string phrase, LanguagePair languagesPair, string subject)
        {
            Result res = new Result(this, phrase, languagesPair, subject);

            return(res);
        }
Beispiel #2
0
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            //http://slovnik.tiscali.cz/index.php?od=0&slovnik=dict_ac&dotaz=test
            string query = "http://slovnik.tiscali.cz/index.php?od=0&slovnik={0}&dotaz={1}";

            query = string.Format(CultureInfo.InvariantCulture, query, ConvertLanguagesPair(languagesPair), HttpUtility.UrlEncode(phrase));

            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri(query),
                                     networkSetting,
                                     WebRequestContentType.UrlEncodedGet);

            string responseFromServer = helper.GetResponse();

            if (responseFromServer.Contains("<strong>Zadané slovo nebylo nalezeno !!!</strong>"))
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }
            else
            {
                if (responseFromServer.Contains("<div class=\"vysledek\">"))
                {
                    result.ArticleUrl        = query;
                    result.ArticleUrlCaption = phrase;

                    string       translation  = StringParser.Parse("<div class=\"vysledek\">", "</div>", responseFromServer);
                    StringParser parser       = new StringParser(translation);
                    string[]     translations = parser.ReadItemsList("<a", "<br />");
                    Result       subres       = null;
                    foreach (string str in translations)
                    {
                        string word           = StringParser.Parse("<strong>", "</strong>", str);
                        string subtranslation = StringParser.Parse(">", "<", StringParser.Parse("<a", "/a>", str));

                        if (subres == null || subres.Phrase != word)
                        {
                            subres = CreateNewResult(word, languagesPair, subject);
                            result.Childs.Add(subres);
                        }
                        subres.Translations.Add(subtranslation);
                    }
                }

                //more
                if (responseFromServer.Contains("<strong>Další >></strong>"))
                {
                    query = "http://slovnik.tiscali.cz/index.php?od=24&slovnik={0}&dotaz={1}";
                    query = string.Format(CultureInfo.InvariantCulture, query, ConvertLanguagesPair(languagesPair), HttpUtility.UrlEncode(phrase));

                    string link = "html!<p><a href=\"{0}\" title=\"{0}\">{1}</a></p>";
                    link = string.Format(link,
                                         query,
                                         "More phrases ...");
                    Result subres = CreateNewResult(link, languagesPair, subject);
                    result.Childs.Add(subres);
                }

                if (result.Childs.Count == 0)
                {
                    result.ResultNotFound = true;
                    throw new TranslationException("Nothing found");
                }
            }
        }
Beispiel #3
0
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            //http://www.dep.pl/dict?word=test&words=&lang=DE
            string query = "http://www.dep.pl/dict?word={0}&words=&lang=DE";

            query                    = string.Format(CultureInfo.InvariantCulture, query, HttpUtility.UrlEncode(phrase));
            result.ArticleUrl        = query;
            result.ArticleUrlCaption = phrase;

            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri(query),
                                     networkSetting,
                                     WebRequestContentType.UrlEncodedGet);

            string responseFromServer = helper.GetResponse();

            if (responseFromServer.IndexOf("has not been found - please post it to the") >= 0)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }
            else
            {
                string translation = StringParser.Parse("<table cellspacing=", "</table>", responseFromServer);

                StringParser parser       = new StringParser(translation);
                string[]     translations = parser.ReadItemsList("<td align=\"left\">", "</td>", "787654323");

                int    cnt = translations.Length;
                string tmp;
                for (int i = 0; i < cnt; i++)
                {
                    tmp             = translations[i];
                    tmp             = StringParser.RemoveAll("<a href=", ">", tmp);
                    tmp             = StringParser.RemoveAll("<font", ">", tmp);
                    tmp             = tmp.Replace("</font>", "");
                    tmp             = tmp.Replace("</a>", "");
                    translations[i] = tmp;
                }

                cnt = translations.Length / 2;
                string polish, german;
                string subphrase, subtranslation;
                Result subres = null;
                for (int i = 0; i < cnt; i++)
                {
                    polish = translations[i * 2];
                    german = translations[i * 2 + 1];

                    if (languagesPair.From == Language.German)
                    {
                        subphrase      = german;
                        subtranslation = polish;
                    }
                    else
                    {
                        subphrase      = polish;
                        subtranslation = german;
                    }

                    if (translations.Length == 2 && string.Compare(subphrase, phrase, true, CultureInfo.InvariantCulture) == 0)
                    {
                        result.Translations.Add(subtranslation);
                        return;
                    }

                    subres = CreateNewResult(subphrase, languagesPair, subject);
                    subres.Translations.Add(subtranslation);
                    result.Childs.Add(subres);
                }
            }
        }
Beispiel #4
0
        public static Result GetCachedResult(ServiceItem serviceItem, string phrase, LanguagePair languagesPair, string subject)
        {
            if (!useCache)
            {
                return(new Result(serviceItem, phrase, languagesPair, subject));
            }

            string key = phrase.Trim().ToLowerInvariant();

            if (key.Length > 500)
            {
                key = key.Substring(0, 500);
            }

            ResultsHashtable collection;
            bool             collection_exists = true;

            lock (cache)
            {
                if (!cache.TryGetValue(key, out collection))
                {
                    collection = new ResultsHashtable();
                    cache.Add(key, collection);
                    collection_exists = false;
                }
            }

            int  hash = Result.GetHashCode(serviceItem.FullName, languagesPair, subject);
            bool needed_new_result = !collection_exists;

            Result res = null;

            lock (collection)
            {
                if (!needed_new_result)
                {
                    if (!collection.TryGetValue(hash, out res))
                    {
                        needed_new_result = true;
                    }
                    else
                    {
                        needed_new_result = (res.Error != null && !res.ResultNotFound) || res.Phrase != phrase;
                    }
                }

                if (needed_new_result)
                {
                    res = new Result(serviceItem, phrase, languagesPair, subject);
                    collection[hash] = res;
                    lock (results_history)
                    {
                        results_history.Add(res);
                    }
                }
                else
                {
                    res.LastUsed = DateTime.Now;
                    lock (results_history)
                    {
                        results_history.Remove(res);
                        results_history.Add(res);
                    }
                }
            }
            return(res);
        }
        void TranslateWord(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            lock (sederetCode)
            {
                if (string.IsNullOrEmpty(sederetCode) || coockieTime < DateTime.Now.AddHours(-1))
                {                  //emulate first access to site
                    WebRequestHelper helpertop =
                        new WebRequestHelper(result, new Uri("http://web.cecs.pdx.edu/~bule/bahasa/search.php"),
                                             networkSetting,
                                             WebRequestContentType.UrlEncodedGet, encoding);
                    helpertop.CookieContainer = cookieContainer;
                    coockieTime = DateTime.Now;
                    string responseFromServertop = helpertop.GetResponse();
                    sederetCode = StringParser.Parse("<input type=\"hidden\" name=\"id\" value=\"", "\"", responseFromServertop);
                }
            }



            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri("http://web.cecs.pdx.edu/~bule/bahasa/search.php"),
                                     networkSetting,
                                     WebRequestContentType.UrlEncoded, encoding);

            helper.CookieContainer = cookieContainer;

            //English to Indonesian, Indonesian to English
            string query = "id={0}&language={1}&method=fuzzy&stoken={2}";

            if (languagesPair.From == Language.Indonesian)
            {
                query = string.Format(CultureInfo.InvariantCulture, query, sederetCode, "Indonesian to English", HttpUtility.UrlEncode(phrase));
            }
            else
            {
                query = string.Format(CultureInfo.InvariantCulture, query, sederetCode, "English to Indonesian", HttpUtility.UrlEncode(phrase));
            }
            helper.AddPostData(query);

            string responseFromServer = helper.GetResponse();

            lock (sederetCode)
            {
                sederetCode = StringParser.Parse("<input type=\"hidden\" name=\"id\" value=\"", "\"", responseFromServer);
            }

            if (!responseFromServer.Contains("<th colspan=\"6\"><hr>"))
            {
                result.ResultNotFound = result.Childs.Count == 0;
                return;
            }

            string translation = StringParser.Parse("<th colspan=\"6\"><hr>", "<tr><td colspan=\"6\"><hr>", responseFromServer);

            Result       child;
            StringParser subparser;


            {
                subparser = new StringParser(translation);
                string[] subtranslation_list = subparser.ReadItemsList("<td", "</td>");
                for (int i = 0; i < subtranslation_list.Length; i += 6)
                {
                    string subphrase = subtranslation_list[i];
                    subphrase = StringParser.ExtractRight(">", subphrase);

                    child = CreateNewResult(subphrase, languagesPair, subject);
                    result.Childs.Add(child);

                    string subtranslation = subtranslation_list[i + 1];
                    subtranslation = StringParser.ExtractRight(">", subtranslation);
                    child.Translations.Add(HttpUtility.HtmlDecode(subtranslation));

                    string abbr = subtranslation_list[i + 2];
                    abbr = StringParser.ExtractRight(">", abbr);
                    child.Abbreviation = abbr;
                }
            }

            result.ResultNotFound = result.Childs.Count == 0;
        }
 protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
 {
     MerriamWebsterUtils.DoTranslate(this, "http://medical.merriam-webster.com/medical", "Medical", phrase, languagesPair, subject, result, networkSetting);
 }
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            string langPair   = GoogleUtils.ConvertLanguagesPair(languagesPair);
            string query_base = "http://ajax.googleapis.com/ajax/services/language/translate?" +
                                "v=1.0&langpair={0}&hl=en&q=";

            query_base = string.Format(query_base, langPair);

            int allowed_length = 2070 - query_base.Length;
            //"key=ABQIAAAA1Xz0dZCPKigOKIhDUJZ6FxQmSA1Htufb6qVqyW_v4yDxIUvb4BRwNjuLUmsgD0bAGP7qnB0dWYfEdg";


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

            SplitToQueries(queries, phrase, SplitMode.Separators, allowed_length);

            StringBuilder sb     = new StringBuilder(phrase.Length);
            string        subres = "";
            int           prefix_idx;
            int           suffix_idx;

            foreach (string subphrase in queries)
            {
                if (subphrase.Length > 500)
                {
                    throw new InvalidOperationException("The length of string is greater of 500 characters." +
                                                        " string : " + subphrase +
                                                        ", full phrase : " + phrase
                                                        );
                }

                //remove not-alphas from start and end of subphrase
                prefix_idx = subphrase.Length;
                for (int i = 0; i < subphrase.Length; i++)
                {
                    if (char.IsLetter(subphrase[i]))
                    {
                        prefix_idx = i;
                        break;
                    }
                }

                if (prefix_idx == subphrase.Length)
                {                 // no alphas - skip without translation
                    sb.Append(subphrase);
                    continue;
                }

                suffix_idx = 0;
                for (int i = subphrase.Length - 1; i >= 0; i--)
                {
                    if (char.IsLetter(subphrase[i]))
                    {
                        suffix_idx = i;
                        break;
                    }
                }

                string real_query = query_base + HttpUtility.UrlEncode(subphrase.Substring(prefix_idx, suffix_idx - prefix_idx + 1));
                if (real_query.Length > 2070)
                {
                    throw new InvalidOperationException("The length of query is greater of 2070 characters." +
                                                        " string : " + subphrase +
                                                        " query : " + real_query +
                                                        " full phrase : " + phrase
                                                        );
                }


                /* debug splitting algo
                 * result.Translations.Add(
                 *              " string length : " + subphrase.Length.ToString());
                 *
                 * result.Translations.Add(
                 *              " \r\nstring : " + subphrase);
                 * result.Translations.Add(
                 *              " \r\nstring for query length : " + (suffix_idx - prefix_idx + 1).ToString());
                 * result.Translations.Add(
                 *              " \r\nstring for query : " + subphrase.Substring(prefix_idx, suffix_idx - prefix_idx + 1));
                 * result.Translations.Add(
                 *              " \r\nquery length : " + real_query.Length.ToString());
                 */

                if (prefix_idx > 0)
                {
                    sb.Append(subphrase.Substring(0, prefix_idx));
                }

                subres = DoInternalTranslate(real_query, result, networkSetting);
                sb.Append(subres);

                if (suffix_idx < subphrase.Length - 1)
                {
                    sb.Append(subphrase.Substring(suffix_idx + 1));
                }
            }
            result.Translations.Add(sb.ToString());
        }
Beispiel #8
0
        public override ReadOnlyServiceSettingCollection GetServiceSettings(string phrase, LanguagePair languagePair)
        {
            PrepareProcessing();
            ServiceSettingCollection result = new ServiceSettingCollection();

            int index;

            foreach (ServiceItemData sid in services)
            {
                if (
                    (sid.LanguagePair.From == languagePair.From || languagePair.From == Language.Any) &&
                    (sid.LanguagePair.To == languagePair.To || languagePair.To == Language.Any)
                    )
                {
                    index = Subjects.BinarySearch(sid.Subject);
                    if (index >= 0)
                    {
                        ServiceItemSetting tsetting = new ServiceItemSetting(sid.LanguagePair, sid.Subject, sid.ServiceItem, TranslateOptions.Instance.GetNetworkSetting(sid.ServiceItem.Service));
                        result.Add(tsetting);
                    }
                }
            }
            return(new ReadOnlyServiceSettingCollection(result));
        }
Beispiel #9
0
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            if (string.IsNullOrEmpty(viewState))
            {              //emulate first access to site
                WebRequestHelper helpertop =
                    new WebRequestHelper(result, new Uri("http://www.prolingoffice.com/page.aspx?l1=43"),
                                         networkSetting,
                                         WebRequestContentType.UrlEncodedGet,
                                         Encoding.GetEncoding(1251));

                string responseFromServertop = helpertop.GetResponse();
                viewState       = StringParser.Parse("id=\"__VIEWSTATE\" value=\"", "\"", responseFromServertop);
                eventValidation = StringParser.Parse("id=\"__EVENTVALIDATION\" value=\"", "\"", responseFromServertop);
            }

            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri("http://www.prolingoffice.com/page.aspx?l1=43"),
                                     networkSetting,
                                     WebRequestContentType.UrlEncoded,
                                     Encoding.GetEncoding(1251));

            //__EVENTTARGET=_ctl1%24Menu1&__EVENTARGUMENT=1&
            //__VIEWSTATE={0}&q={1}&_ctl1%3AtsLang=rbLangU&LanguageH=RUS&
            //__EVENTVALIDATION={2}
            string query = "__EVENTTARGET=_ctl1%24Menu1&__EVENTARGUMENT=1&__VIEWSTATE={0}&q={1}&_ctl1%3AtsLang=rbLangU&LanguageH=RUS&__EVENTVALIDATION={2}";

            query = string.Format(query,
                                  HttpUtility.UrlEncode(viewState, helper.Encoding),
                                  HttpUtility.UrlEncode(phrase, helper.Encoding),
                                  HttpUtility.UrlEncode(eventValidation, helper.Encoding));

            helper.AddPostData(query);

            string responseFromServer = helper.GetResponse();

            viewState       = StringParser.Parse("id=\"__VIEWSTATE\" value=\"", "\"", responseFromServer);
            eventValidation = StringParser.Parse("id=\"__EVENTVALIDATION\" value=\"", "\"", responseFromServer);


            if (responseFromServer.IndexOf("Перекладу цього слова не знайдено. Спробуйте записати слово інакше, або ознайомтеся з інформацією, яка міститься у <a") >= 0)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }
            else if (responseFromServer.IndexOf("В слове содержатся ошибки. Возможно имелось в виду:</b>") >= 0)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }
            else if (responseFromServer.IndexOf("Синонімів для цього слова не знайдено. Спробуйте записати слово інакше, або ознайомтеся з інформацією, яка міститься у <") >= 0)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }
            else if (responseFromServer.IndexOf("В слове содержатся ошибки.</b>") >= 0)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }



            string translation = StringParser.Parse("<span class=\"wrd\" xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\">", "</TABLE></span>", responseFromServer);
            string abbr        = StringParser.Parse("title=\"", "\"", translation);

            abbr += " " + StringParser.Parse("xslt\">", "</span>", translation).Trim();
            //result.Abbreviation = abbr;

            StringParser parser = new StringParser(translation);

            string[] translations = parser.ReadItemsList("<span class=\"tolk\"", "</td><td></td></tr>", "3495783-4572385");

            foreach (string subtranslation in translations)
            {
                translation = StringParser.Parse(">", "</span>", subtranslation);
                Result subres;
                subres = CreateNewResult(translation, languagesPair, subject);
                result.Childs.Add(subres);

                parser = new StringParser(subtranslation);
                string[] subtranslations = parser.ReadItemsList("<a ", "/a>", "3495783-4572385");
                foreach (string s in subtranslations)
                {
                    subres.Translations.Add(StringParser.Parse(">", "<", s));
                }
            }
        }
Beispiel #10
0
        public void SetResult(Result result, LanguagePair languagePair)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (result.ResultNotFound &&
                string.IsNullOrEmpty(result.EditArticleUrl) &&
                TranslateOptions.Instance.ResultWindowOptions.HideWithoutResult)
            {
                return;                 //skip
            }
            string htmlString = "";

            if (TranslateOptions.Instance.ResultWindowOptions.ShowServiceName)
            {
                string name = "";
                if (!string.IsNullOrEmpty(result.ServiceItem.Description))
                {
                    name = LangPack.TranslateString(result.ServiceItem.Description) + " - ";
                }

                name += LangPack.TranslateString(result.ServiceItem.Service.FullName);

                htmlString += string.Format(CultureInfo.InvariantCulture,
                                            HtmlHelper.ServiceNameFormat,
                                            result.ServiceItem.Service.Url,
                                            HttpUtility.HtmlEncode(name));

                htmlString += ", ";
                htmlString += LangPack.TranslateString("Type") + " : " + ServiceSettingsContainer.GetServiceItemType(result.ServiceItem);
            }

            if (result.Subject != SubjectConstants.Common)
            {
                if (htmlString.Length > 0)
                {
                    htmlString += ", ";
                }
                htmlString += LangPack.TranslateString("Subject") + " : " + LangPack.TranslateString(result.Subject);
            }

            if (languagePair.From == Language.Any || languagePair.To == Language.Any || TranslateOptions.Instance.ResultWindowOptions.ShowTranslationDirection)
            {
                if (htmlString.Length > 0)
                {
                    htmlString += ", ";
                }

                if (result.ServiceItem is MonolingualDictionary)
                {
                    htmlString += LangPack.TranslateLanguage(result.LanguagePair.From);
                }
                else
                {
                    htmlString += LangPack.TranslateLanguage(result.LanguagePair.From) +
                                  "->" +
                                  LangPack.TranslateLanguage(result.LanguagePair.To);
                }
            }

            if (htmlString.Length > 0)
            {
                htmlString += "<hr style=\"width: 100%; height: 1px;\">";
            }


            string resultHtml = GetResultHtml(result);

            if (!string.IsNullOrEmpty(result.ArticleUrl) && result.Error == null)
            {
                string icon = "";
                if (result.HasAudio)
                {
                    icon = " " + string.Format(HtmlHelper.IconOfAudioFormat,
                                               LangPack.TranslateString("Pronunciation"));
                }

                htmlString += GetParagraphFormat(0, result);
                if (string.IsNullOrEmpty(result.ArticleUrlCaption))
                {
                    htmlString += string.Format("<a href=\"{0}\" title=\"{0}\">{0}{1}</a>",
                                                result.ArticleUrl, icon
                                                );
                }
                else
                {
                    htmlString += string.Format("<a href=\"{0}\" title=\"{0}\"><b>{1}</b>{2}</a>",
                                                result.ArticleUrl,
                                                result.ArticleUrlCaption, icon
                                                );
                }



                htmlString += "</p>";
                if (!resultHtml.StartsWith("<br>"))
                {
                    htmlString += "<br>";
                }

                htmlString += resultHtml;
            }
            else
            {
                if (!resultHtml.StartsWith("<br>"))
                {
                    htmlString += resultHtml;
                }
                else
                {
                    htmlString += resultHtml.Substring(4);
                }
            }

            if (!string.IsNullOrEmpty(result.ArticleUrl) && result.MoreEntriesCount != 0)
            {
                htmlString += "<br>";
                htmlString += GetParagraphFormat(0, result);
                htmlString += string.Format("<a href=\"{0}\" title=\"{0}\">&gt;&gt;&gt; {1}</a>",
                                            result.ArticleUrl,
                                            string.Format(LangPack.TranslateString("{0} more entries found"),
                                                          result.MoreEntriesCount)
                                            );
                htmlString += "</p>";
            }

            if (result.QueryTicks != 0 && TranslateOptions.Instance.ResultWindowOptions.ShowQueryStatistics)
            {
                htmlString += "<hr style=\"width: 100%; height: 1px;\">";
                htmlString += "<span style=\"" + HtmlHelper.InfoTextStyle + "\">";
                htmlString += string.Format(CultureInfo.InvariantCulture,
                                            LangPack.TranslateString("Query time : {0} s, Queries count : {1}, Bytes sent : {2}, Bytes received : {3}"),
                                            new DateTime(result.QueryTicks).ToString("ss.fffffff", CultureInfo.InvariantCulture),
                                            result.RetryCount,
                                            result.BytesSent,
                                            result.BytesReceived);
                htmlString += "</span>";
            }

            if (!TranslateOptions.Instance.ResultWindowOptions.ShowAccents)
            {
                htmlString = htmlString.Replace("́", "");
            }

            Wait();
            HtmlHelper.AddTranslationCell(wBrowser, isClean, htmlString, result.ServiceItem);
            isClean = false;
            RecalcSizes();
        }
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            string query = "http://dict.tu-chemnitz.de/dings.cgi?lang=en&service={0}&opterrors=0&optpro=0&query={1}&iservice=&dlink=self&comment=";
            query = string.Format(CultureInfo.InvariantCulture, query,
                ConvertLanguagesPair(languagesPair),
                HttpUtility.UrlEncode(phrase, encoding)
                );

            result.ArticleUrl = query;
            result.ArticleUrlCaption = phrase;

            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri(query),
                    networkSetting,
                    WebRequestContentType.UrlEncodedGet);
            helper.Encoding = encoding;

            string responseFromServer = helper.GetResponse();

            if(responseFromServer.Contains(">0 <span class=\"h\">similar</span> results for "))
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }

            string[] translations = StringParser.ParseItemsList("<td align=\"right\"><br", "</tr>", responseFromServer);

            if(translations.Length == 0)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }

            if(responseFromServer.Contains("<td class=\"tip b \" width=\"45%\" align=\"left\" valign=\"top\">"))
            {
                string full_count = StringParser.Parse("<td class=\"tip b \" width=\"45%\" align=\"left\" valign=\"top\">", " ", responseFromServer);
                if(!string.IsNullOrEmpty(full_count))
                {
                    int count;
                    if(int.TryParse(full_count, out count))
                        result.MoreEntriesCount = count - translations.Length;
                }
            }

            string en_string, ge_string, en_url, ge_url;
            bool en_audio, ge_audio;
            Result child = result;
            string subphrase = "";
            foreach(string translation in translations)
            {
                string[] subtranslations = StringParser.ParseItemsList("<td class=\"", "</td>", translation);
                if(subtranslations.Length != 2)
                    throw new TranslationException("Can't found translations in string : " + translation);

                en_string = StringParser.ExtractRight(">", subtranslations[1]);
                if(en_string.Contains("<a href=\""))
                    en_url = StringParser.Parse("<a href=\"", "\"", en_string);
                else
                    en_url = "";
                en_audio = en_string.Contains("href=\"/dings.cgi?speak=");

                en_string = StringParser.RemoveAll("<", ">", en_string);

                ge_string = StringParser.ExtractRight(">", subtranslations[0]);
                if(ge_string.Contains("<a href=\""))
                    ge_url = StringParser.Parse("<a href=\"", "\"", ge_string);
                else
                    ge_url = "";
                ge_audio = ge_string.Contains("href=\"/dings.cgi?speak=");
                ge_string = StringParser.RemoveAll("<", ">", ge_string);

                if(languagesPair.From == Language.German)
                {
                    if(subphrase != ge_string)
                    {
                        child = new Result(result.ServiceItem, ge_string, result.LanguagePair, result.Subject);
                        subphrase = ge_string;
                        if(!string.IsNullOrEmpty(ge_url))
                            child.ArticleUrl = "http://dict.tu-chemnitz.de" + ge_url;
                        child.HasAudio = ge_audio;
                        result.Childs.Add(child);
                    }
                    child.Translations.Add(en_string);
                }
                else
                {
                    if(subphrase != en_string)
                    {
                        child = new Result(result.ServiceItem, en_string, result.LanguagePair, result.Subject);
                        subphrase = en_string;
                        if(!string.IsNullOrEmpty(en_url))
                            child.ArticleUrl = "http://dict.tu-chemnitz.de" + en_url;
                        child.HasAudio = en_audio;
                        result.Childs.Add(child);
                    }

                    child.Translations.Add(ge_string);
                }

            }
        }
Beispiel #12
0
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            string query = "http://www.google.com/dictionary?aq=f&langpair={1}&q={0}&hl=en";

            query = string.Format(query, HttpUtility.UrlEncode(phrase, System.Text.Encoding.UTF8), GoogleUtils.ConvertLanguagesPair(languagesPair));
            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri(query),
                                     networkSetting,
                                     WebRequestContentType.UrlEncodedGet);

            result.ArticleUrl        = query;
            result.ArticleUrlCaption = phrase;

            string responseFromServer = helper.GetResponse();

            if (responseFromServer.Contains("No dictionary translations were found for: <strong>"))
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }
            if (responseFromServer.Contains("No dictionary definitions were found for: <strong>"))
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }

            result.HasAudio    = responseFromServer.Contains("<object data=\"/dictionary/flash");
            responseFromServer = StringParser.Parse("<div class=\"dct-srch-otr\">", "<div class=\"dct-rt-sct\">", responseFromServer);

            //pronuncation
            if (responseFromServer.Contains("<span class=\"dct-tp\">/"))
            {
                string pronuncation = StringParser.Parse("<span class=\"dct-tp\">/", "/</span>", responseFromServer);
                pronuncation        = pronuncation.Trim();
                result.Abbreviation = pronuncation;
            }


            //translations
            //string translations = StringParser.Parse("<div class=\"dct-srch-rslt\">", "</div>", responseFromServer);



            string translations = "";

            //TODO: additional sences like in "water" - "water down" not supported

            if (responseFromServer.Contains("<div class=\"sen\">"))
            {
                translations = StringParser.Parse("<ul class=\"dct-e2\" id=\"pr-root\" >", "</ul>\n<div class=\"sen\">", responseFromServer);
            }
            else if (responseFromServer.Contains("<h3>Related phrases</h3>"))
            {
                translations = StringParser.Parse("<ul class=\"dct-e2\" id=\"pr-root\" >", "</ul>\n<h3>Related phrases</h3>", responseFromServer);
            }
            else if (responseFromServer.Contains("<h3>Web definitions</h3>"))
            {
                translations = StringParser.Parse("<ul class=\"dct-e2\" id=\"pr-root\" >", "</ul>\n<h3>Web definitions</h3>", responseFromServer);
            }
            else
            {
                translations = StringParser.Parse("<ul class=\"dct-e2\" id=\"pr-root\" >", "</ul>", responseFromServer);
            }


            StringParser  parser          = null;
            List <string> subtranslations = new List <string>();

            if (translations.Contains("<li class=\"dct-ec\""))
            {
                //"</li>\n</ul>\n</li>"
                parser = new StringParser(translations);
                string[] subtranslation_list = parser.ReadItemsList("<li class=\"dct-ec\"", "</li>\n</ul>\n</li>", "3485730457203");
                subtranslations.AddRange(subtranslation_list);
            }
            else if (translations.Contains("<div style=\"font-weight:bold\">Synonyms:</div>"))
            {
                Result synonyms_tr = CreateNewResult("Synonyms", languagesPair, subject);
                result.Childs.Add(synonyms_tr);

                string synonyms = StringParser.Parse("<div style=\"font-weight:bold\">Synonyms:</div>", "</div>", translations);
                parser = new StringParser(synonyms);
                string[] syn_group_list = parser.ReadItemsList("<li>", "</li>", "3485730457203");
                foreach (string syngroup in syn_group_list)
                {
                    string syn_group_name = StringParser.Parse("title=\"Part-of-speech\">", "</span>", syngroup);
                    Result syn_tr         = CreateNewResult(syn_group_name, languagesPair, subject);
                    synonyms_tr.Childs.Add(syn_tr);
                    parser = new StringParser(syngroup);
                    string[] syn_list = parser.ReadItemsList("<a", "</a>", "3485730457203");
                    foreach (string syn in syn_list)
                    {
                        string synonym = StringParser.ExtractRight(">", syn);
                        syn_tr.Translations.Add(synonym);
                    }
                }

                subtranslations.Add(translations);
            }
            else
            {
                subtranslations.Add(translations);
            }

            Result subres_tr  = result;
            Result sub2res_tr = null;
            Result sub3res_tr = null;
            string abbr_str;

            foreach (string subtranslation in subtranslations)
            {
                if (subtranslation.Contains("<div  class=\"dct-ec\">"))
                {
                    abbr_str  = StringParser.Parse("title=\"Part-of-speech\">", "</span>", subtranslation);
                    subres_tr = CreateNewResult(abbr_str, languagesPair, subject);
                    result.Childs.Add(subres_tr);
                }

                parser = new StringParser(subtranslation.Replace("<li class=\"dct-em\"", "<end><begin>") + "<end>");
                string[] subsubtranslation_list = parser.ReadItemsList("<begin>", "<end>", "3485730457203");

                foreach (string subsubtanslation in subsubtranslation_list)
                {
                    sub2res_tr = CreateNewResult("", languagesPair, subject);
                    subres_tr.Childs.Add(sub2res_tr);

                    if (subsubtanslation.Contains(">See also</span>"))
                    {
                        sub2res_tr.Translations.Add("See also");
                    }

                    StringParser parser2 = new StringParser(subsubtanslation.Replace("<span class=\"dct-tt\">", "<end><begin>") + "<end>");
                    string[]     sub3translation_list = parser2.ReadItemsList("<begin>", "<end>", "3485730457203");

                    foreach (string sub3tanslation in sub3translation_list)
                    {
                        string text_translation = "";
                        string text_abbr        = "";
                        if (sub3tanslation.Contains("<span"))
                        {
                            text_translation = StringParser.ExtractLeft("<span", sub3tanslation);
                            if (text_translation.Contains("</span"))
                            {
                                text_translation = StringParser.ExtractLeft("</span", text_translation);
                            }
                            text_abbr = StringParser.Parse("<span", "</span", sub3tanslation);
                            text_abbr = StringParser.ExtractRight(">", text_abbr);
                        }
                        else
                        {
                            text_translation = StringParser.ExtractLeft("</span>", sub3tanslation);
                        }

                        text_translation = StringParser.RemoveAll("<", ">", text_translation);

                        if (sub2res_tr.Translations.Count == 0)
                        {
                            sub2res_tr.Translations.Add(text_translation);
                            sub2res_tr.Abbreviation = text_abbr;
                        }
                        else
                        {
                            sub3res_tr = CreateNewResult("", languagesPair, subject);
                            sub3res_tr.Translations.Add(text_translation);
                            //sub3res_tr.Phrase = text_abbr;
                            sub2res_tr.Childs.Add(sub3res_tr);
                        }
                    }
                }
            }


            //related words
            if (responseFromServer.Contains("<h3>Related phrases</h3>"))
            {
                string related = StringParser.Parse("<ul class=\"rlt-snt\">", "</ul>", responseFromServer);
                if (!string.IsNullOrEmpty(related))
                {
                    parser = new StringParser(related);
                    string[] related_list = parser.ReadItemsList("<li>", "</li>");

                    foreach (string related_s in related_list)
                    {
                        string related_str = related_s.Replace("\n", "").Trim();
                        string subphrase   = StringParser.Parse("<div>", "</div>", related_str);
                        subphrase = StringParser.RemoveAll("<", ">", subphrase);
                        subphrase = subphrase.Replace("&nbsp", " ").Replace("\n", "").Trim();


                        string subphrasetrans = StringParser.ExtractRight("</div>", related_str);

                        subphrasetrans = StringParser.RemoveAll("<", ">", subphrasetrans);
                        subphrasetrans = subphrasetrans.Replace("&nbsp", " ").Replace("\n", "").Trim();

                        Result subres = CreateNewResult(subphrase, languagesPair, subject);
                        subres.Translations.Add(subphrasetrans);
                        result.Childs.Add(subres);
                    }
                }
            }

            //Web definitions
            if (responseFromServer.Contains("<h3>Web definitions</h3>"))
            {
                string related = StringParser.ExtractRight("<ul class=\"gls\">", responseFromServer);
                if (!string.IsNullOrEmpty(related))
                {
                    {
                        Result subres_wd = CreateNewResult(phrase, languagesPair, subject);
                        result.Childs.Add(subres_wd);

                        parser = new StringParser(related);
                        string[] related_list = parser.ReadItemsList("<li>", "</li>");

                        foreach (string related_s in related_list)
                        {
                            string related_str = related_s;
                            related_str = related_str.Replace("<br/>", "").Trim();
                            related_str = StringParser.RemoveAll("<", ">", related_str);
                            related_str = related_str.Replace("&nbsp", " ").Replace("\n", "").Trim();
                            subres_wd.Translations.Add(related_str);
                        }
                    }
                }
            }
        }
Beispiel #13
0
 protected abstract void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting);
Beispiel #14
0
 public Result Translate(string phrase, LanguagePair languagesPair, string subject, NetworkSetting networkSetting)
 {
     return(Translate(phrase, languagesPair, subject, networkSetting, null));
 }
Beispiel #15
0
 public ServiceItemData(ServiceItem serviceItem, LanguagePair languagePair, string subject) : base(serviceItem.FullName, subject)
 {
     this.languagePair = languagePair;
     this.ServiceItem  = serviceItem;
 }
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            string query = "http://www.pcdigest.net/cgi-bin/u/book/sis.pl?Qry={0}&found=10&action=search";

            query = string.Format(query, HttpUtility.UrlEncode(phrase, Encoding.GetEncoding(1251)));
            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri(query),
                                     networkSetting,
                                     WebRequestContentType.UrlEncodedGet,
                                     Encoding.GetEncoding(1251));

            string responseFromServer = helper.GetResponse();

            responseFromServer = StringParser.Parse("<!-- START CONTENT -->", "<!-- RIGHT SHORT TABLE -->", responseFromServer);
            responseFromServer = StringParser.Parse("<P align=justify>", "</table>", responseFromServer);
            responseFromServer = responseFromServer.Replace("<font color=darkgreen>", "");
            responseFromServer = responseFromServer.Replace("<font color=red>", "");
            responseFromServer = responseFromServer.Replace("</font>", "");

            responseFromServer = responseFromServer.Replace("<B>", "");
            responseFromServer = responseFromServer.Replace("</B>", "");
            responseFromServer = responseFromServer.Replace("<I>", "");
            responseFromServer = responseFromServer.Replace("</I>", "");

            responseFromServer = responseFromServer.Replace("<i>", "");
            responseFromServer = responseFromServer.Replace("</i>", "");

            responseFromServer = responseFromServer.Replace("<u>", "");
            responseFromServer = responseFromServer.Replace("</u>", "");


            StringParser parser = new StringParser(responseFromServer);

            string[] translations = parser.ReadItemsList("<P align=justify>", "</P>", "3495783-4572385");

            if (translations.Length == 0)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }

            result.ArticleUrl        = query;
            result.ArticleUrlCaption = phrase;

            string translation, abrr, data;
            int    idx;

            foreach (string subtranslation in translations)
            {
                idx = subtranslation.IndexOf("(");
                if (idx < 0)
                {
                    idx = subtranslation.IndexOf("-");
                }

                translation = subtranslation.Substring(0, idx);

                if (subtranslation.IndexOf("(") >= 0)
                {
                    abrr = StringParser.Parse("(", ")", subtranslation);
                }
                else
                {
                    abrr = "";
                }

                idx = subtranslation.IndexOf("-");
                if (idx >= 0)
                {
                    data = subtranslation.Substring(idx + 1);
                }
                else
                {
                    data = "";
                }

                Result subres;
                if (translations.Length > 1)
                {
                    subres = CreateNewResult(translation, languagesPair, subject);
                    result.Childs.Add(subres);
                }
                else
                {
                    subres = result;
                }

                if (!string.IsNullOrEmpty(abrr))
                {
                    subres.Abbreviation = abrr;
                }
                if (!string.IsNullOrEmpty(data))
                {
                    subres.Translations.Add(data);
                }
            }
        }
Beispiel #17
0
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            string query = "http://www.multitran.ru/c/m.exe?EXT=0&a=TM&s={0}&";

            MultitranUtils.DoTranslateSentences(this, query, phrase, languagesPair, subject, result, networkSetting);
        }
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            if (string.IsNullOrEmpty(viewState))
            {              //emulate first access to site
                WebRequestHelper helpertop =
                    new WebRequestHelper(result, new Uri("http://www.priberam.pt/dlpo/dlpo.aspx"),
                                         networkSetting,
                                         WebRequestContentType.UrlEncodedGet,
                                         Encoding.GetEncoding("iso-8859-1"));

                string responseFromServertop = helpertop.GetResponse();
                viewState = StringParser.Parse("name=\"__VIEWSTATE\" value=\"", "\"", responseFromServertop);
            }

            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri("http://www.priberam.pt/dlpo/definir_resultados.aspx"),
                                     networkSetting,
                                     WebRequestContentType.UrlEncoded,
                                     Encoding.GetEncoding("iso-8859-1"));

            string queryStr = "__EVENTTARGET=&__EVENTARGUMENT=&NOTVIEWSTATE={0}" +
                              "&definActionTarget=%2Fdlpo%2Fdefinir_resultados.aspx" +
                              "&pesqActionTarget=%2Fdlpo%2Fpesquisar_resultados.aspx" +
                              "&conjugaActionTarget=%2Fdlpo%2Fconjugar_resultados.aspx" +
                              "&CVdefinActionTarget=%2Fdcvpo%2Fdefinir_resultados.aspx" +
                              "&CVpesqActionTarget=%2Fdcvpo%2Fpesquisar_resultados.aspx" +
                              "&CVconjugaActionTarget=%2Fdcvpo%2Fconjugar_resultados.aspx" +
                              "&h_seccao_index=&h_vista=&h_abrev_cat=1&h_abrev_flex=1&h_abrev_dom=1" +
                              "&h_abrev_exemp=1&h_abrev_etim=1&h_abrev_outras=1&h_filtro=&h_dominio=" +
                              "&h_var_geografica=&h_categoria=&h_reg_linguistico=&h_etimologia=" +
                              "&h_desc_dominio=&h_desc_var_geografica=&h_desc_categoria=" +
                              "&h_desc_reg_linguistico=&h_desc_etimologia=&accao=" +
                              "&h_texto_pesquisa={1}&h_n={2}&accao=" +
                              "&pal={1}&Dicionario%3ApalVisible={3}";



            string query = string.Format(queryStr,
                                         HttpUtility.UrlEncode(viewState, helper.Encoding),
                                         HttpUtility.UrlEncode(phrase, helper.Encoding),
                                         0,
                                         HttpUtility.UrlEncode(phrase, helper.Encoding)
                                         );

            helper.AddPostData(query);

            string responseFromServer = helper.GetResponse();

            viewState = StringParser.Parse("name=\"__VIEWSTATE\" value=\"", "\"", responseFromServer);

            if (responseFromServer.Contains("A palavra não foi encontrada.</span>"))
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }

            if (responseFromServer.Contains("<blockquote>"))
            {
                StringParser parser    = new StringParser(responseFromServer);
                string[]     subblocks = parser.ReadItemsList("<blockquote>", "</blockquote>");
                if (subblocks.Length == 1)
                {
                    SetResult(result, subblocks[0]);
                }
                else
                {
                    foreach (string block in subblocks)
                    {
                        Result child = new Result(result.ServiceItem, phrase, result.LanguagePair, result.Subject);
                        result.Childs.Add(child);
                        SetResult(child, block);
                    }
                }
            }
            else if (responseFromServer.Contains("javascript:SeleccionaEntrada(&quot"))
            {
                StringParser parser   = new StringParser(responseFromServer);
                string[]     sublinks = parser.ReadItemsList("javascript:SeleccionaEntrada(&quot;", "&quot;)\"");
                if (sublinks.Length <= 1)
                {
                    result.ResultNotFound = true;
                    throw new TranslationException("Nothing found");
                }

                string key = "&quot;,&quot;";
                foreach (string sublink in sublinks)
                {
                    int idx = sublink.IndexOf(key);
                    if (idx < 0)
                    {
                        throw new TranslationException("Can't found start tag : \"&quot;,&quot;\" in string : " + sublink);
                    }

                    string val = sublink.Substring(0, idx);
                    string num = sublink.Substring(idx + key.Length);
                    query = string.Format(queryStr,
                                          HttpUtility.UrlEncode(viewState, helper.Encoding),
                                          HttpUtility.UrlEncode(val, helper.Encoding),
                                          num,
                                          HttpUtility.UrlEncode(phrase, helper.Encoding));

                    helper =
                        new WebRequestHelper(result, new Uri("http://www.priberam.pt/dlpo/definir_resultados.aspx"),
                                             networkSetting,
                                             WebRequestContentType.UrlEncoded,
                                             Encoding.GetEncoding("iso-8859-1"));
                    helper.AddPostData(query);

                    responseFromServer = helper.GetResponse();

                    viewState = StringParser.Parse("name=\"__VIEWSTATE\" value=\"", "\"", responseFromServer);

                    if (responseFromServer.Contains("<blockquote>"))
                    {
                        parser = new StringParser(responseFromServer);
                        string[] subblocks = parser.ReadItemsList("<blockquote>", "</blockquote>");
                        foreach (string block in subblocks)
                        {
                            Result child = new Result(result.ServiceItem, val, result.LanguagePair, result.Subject);
                            result.Childs.Add(child);
                            SetResult(child, block);
                        }
                    }
                }

                if (result.Childs.Count == 0)
                {
                    result.ResultNotFound = true;
                    throw new TranslationException("Nothing found");
                }
            }
            else
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }
        }
Beispiel #19
0
        public static void DoTranslate(ServiceItem searchEngine, string searchHost, string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            string link_f = "http://{0}.{1}/wiki/{2}";
            string lang   = WikiUtils.ConvertLanguage(languagesPair.To);

            string link = string.Format(link_f, lang,
                                        searchHost,
                                        phrase);

            result.EditArticleUrl = link;

            Result searchResult = searchEngine.Translate(phrase, languagesPair, subject, networkSetting);

            if (!searchResult.IsHasData() || searchResult.Translations.Count < 1)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }

            string url           = StringParser.Parse("<a href=\"", "\">", searchResult.Translations[0]);
            string searched_name = url.Substring(url.LastIndexOf("/") + 1);

            if (string.Compare(phrase, searched_name, true) != 0)
            {
                //check second line
                if (searchResult.Translations.Count < 2)
                {
                    result.ResultNotFound = true;
                    throw new TranslationException("Nothing found");
                }
                else
                {
                    url           = StringParser.Parse("<a href=\"", "\">", searchResult.Translations[1]);
                    searched_name = url.Substring(url.LastIndexOf("/") + 1);
                    if (string.Compare(phrase, searched_name, true) != 0)
                    {
                        result.ResultNotFound = true;
                        throw new TranslationException("Nothing found");
                    }
                }
            }


            link = string.Format(link_f, lang,
                                 searchHost,
                                 searched_name,
                                 searched_name);
            result.EditArticleUrl = link;

            //http://en.wikipedia.org/w/api.php?action=parse&prop=text&format=xml&page=Ukraine
            string query = "http://{0}.{1}/w/api.php?action=parse&prop=text|revid&format=xml&page={2}";

            query = string.Format(query, lang,
                                  searchHost,
                                  HttpUtility.UrlEncode(searched_name));

            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri(query),
                                     networkSetting,
                                     WebRequestContentType.UrlEncodedGet);

            string responseFromServer = helper.GetResponse();

            if (responseFromServer.IndexOf("<parse revid=\"0\">") >= 0)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }

            string res = StringParser.Parse("<text", "</text>", responseFromServer);

            res = StringParser.ExtractRight(">", res);
            res = res.Replace("width: 100%", "width: 95%");
            res = res.Replace("float:right;", "float: right;margin-right: 0.5em;");

            res = "html!<div style='width:{allowed_width}px;overflow:scroll;overflow-y:hidden;overflow-x:auto;'>" + HttpUtility.HtmlDecode(res) + "&nbsp</div>";

            res = res.Replace("<h1>", "");
            res = res.Replace("</h1>", "");
            res = res.Replace("<h2>", "");
            res = res.Replace("</h2>", "");
            res = res.Replace("<h3>", "");
            res = res.Replace("</h3>", "");
            res = res.Replace("<h4>", "");
            res = res.Replace("</h4>", "");

            res = StringParser.RemoveAll("<span class=\"editsection\">[<a", "</a>]", res);
            res = StringParser.RemoveAll("href=\"#", "\"", res);
            res = StringParser.RemoveAll("<script type=", "</script>", res);
            res = StringParser.RemoveAll("<button onclick=", "</button>", res);



            url = string.Format("a href=\"http://{0}.{1}/", lang, searchHost);
            res = res.Replace("a href=\"/", url);

            url = string.Format("img src=\"http://{0}.{1}/", lang, searchHost);
            res = res.Replace("img src=\"/", url);
            result.Translations.Add(res);
        }
Beispiel #20
0
 protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
 {
     MegaslownikTools.DoTranslate(this, phrase, languagesPair, subject, result, networkSetting);
 }
Beispiel #21
0
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            string from = ConvertLanguage(languagesPair.From);
            string to   = ConvertLanguage(languagesPair.To);

            string query = "http://{0}.{1}.open-tran.eu/json/suggest/{2}";

            query = string.Format(query, from, to, HttpUtility.UrlEncode(phrase));

            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri(query),
                                     networkSetting,
                                     WebRequestContentType.UrlEncodedGet);

            helper.Referer = "http://translate-net.appspot.com/";
            string    responseFromServer = helper.GetResponse();
            JsonArray parsed             = (JsonArray)JsonParser.Parse(responseFromServer);
            string    count;
            string    translation = "";
            string    subphrase, servicename;
            Result    subres;

            foreach (JsonObject item in parsed)
            {
                translation = ((JsonValue)item["text"]).Value;
                count       = ((JsonValue)item["count"]).Value;

                if (translation.StartsWith("&") ||
                    translation.StartsWith("_") ||
                    translation.StartsWith("$") ||
                    translation.StartsWith("~")
                    )
                {
                    translation = translation.Substring(1);
                }

                subres = CreateNewResult(translation, languagesPair, subject);
                if (count != "1")
                {
                    subres.Abbreviation = " {" + count.ToString() + "}";
                }
                result.Childs.Add(subres);

                foreach (JsonObject project in (JsonArray)item["projects"])
                {
                    count       = ((JsonValue)project["count"]).Value;
                    servicename = ((JsonValue)project["path"]).Value.Substring(2);
                    servicename = ((JsonValue)project["name"]).Value + " " + servicename;
                    subphrase   = ((JsonValue)project["orig_phrase"]).Value;
                    if (subphrase.StartsWith("&") ||
                        subphrase.StartsWith("_") ||
                        subphrase.StartsWith("$") ||
                        subphrase.StartsWith("~")
                        )
                    {
                        subphrase = subphrase.Substring(1);
                    }

                    subphrase += " - " + servicename + " - ";
                    subphrase += " {" + count.ToString() + "}";
                    subres.Translations.Add(subphrase);
                }
            }

            if (result.Childs.Count > 0)
            {
                result.ArticleUrl        = "http://" + from + "." + to + ".open-tran.eu/suggest/" + phrase;
                result.ArticleUrlCaption = phrase;
            }
            else
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }
        }
Beispiel #22
0
 public Result(ServiceItem serviceItem, string phrase, LanguagePair languagesPair, string subject) : base(serviceItem, languagesPair, subject)
 {
     this.phrase = phrase;
     childs      = new ResultCollection(this);
 }
Beispiel #23
0
        public override ReadOnlyServiceSettingCollection GetServiceSettings(string phrase, LanguagePair languagePair)
        {
            ServiceSettingCollection result = new ServiceSettingCollection();

            PrepareProcessing();
            foreach (KeyValuePair <LanguagePair, ServiceItemsCollection> kvp in Manager.LanguagePairServiceItems)
            {
                if (disabledSourceLanguages.BinarySearch(kvp.Key.From) >= 0)
                {
                    continue;
                }

                if (disabledTargetLanguages.BinarySearch(kvp.Key.To) >= 0)
                {
                    continue;
                }

                foreach (ServiceItem si in kvp.Value)
                {
                    if (
                        (kvp.Key.From == languagePair.From || languagePair.From == Language.Any) &&
                        (kvp.Key.To == languagePair.To || languagePair.To == Language.Any ||
                         (IncludeMonolingualDictionaryInTranslation && si is MonolingualDictionary)
                        )
                        )
                    {
                        foreach (string subject in si.SupportedSubjects)
                        {
                            if (Subjects.BinarySearch(subject) >= 0)
                            {
                                ServiceItemSetting tsetting = new ServiceItemSetting(kvp.Key, subject, si, TranslateOptions.Instance.GetNetworkSetting(si.Service));
                                result.Add(tsetting);
                            }
                        }
                    }
                }
            }
            return(new ReadOnlyServiceSettingCollection(result));
        }
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            string query = "http://www.cybermova.com/cgi-bin/olenuapro.pl";

            if (languagesPair.From == Language.Ukrainian)
            {
                query = "http://www.cybermova.com/cgi-bin/oluaenpro.pl";
            }
            WebRequestHelper helper =
                new WebRequestHelper(result, new Uri(query),
                                     networkSetting,
                                     WebRequestContentType.UrlEncoded);

            helper.Encoding = Encoding.GetEncoding(1251);

            query = "Word={0}&EnUaBtn=En+--%3E+Ua";
            query = string.Format(query, HttpUtility.UrlEncode(phrase, helper.Encoding));
            helper.AddPostData(query);
            //"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.- "
            //"АБВГҐДЕЄЖЗИIЇЙКЛМНОПРСТУФХЦЧШЩЬЮЯабвгґдеєжзиіїйклмнопрстуфхцчшщьюя'.- !?/,:;()\'\"\""

            string responseFromServer = helper.GetResponse();

            if (responseFromServer.IndexOf("<span id=result><B>") == -1)
            {
                result.ResultNotFound = true;
                throw new TranslationException("Nothing found");
            }
            else
            {
                string translation = StringParser.Parse("<body bgColor=LightSkyBlue>", "<FORM ACTION=", responseFromServer);

                StringParser phrasesParser = new StringParser(translation);
                string[]     phrases       = phrasesParser.ReadItemsList("<span id=result><B>", "</span>", "787654323");

                string subphrase;
                string subtranslation;
                Result subres = null;
                foreach (string data in phrases)
                {
                    int idx = data.IndexOf("</B>");
                    if (idx < 0)
                    {
                        throw new TranslationException("Can't found </B> tag");
                    }
                    subphrase = data.Substring(0, idx);
                    bool   has_root = subphrase.IndexOf("||") > 0;
                    string root     = "";
                    if (has_root)
                    {
                        root      = subphrase.Substring(0, subphrase.IndexOf("||"));
                        subphrase = subphrase.Replace("||", "");
                    }

                    subtranslation = data.Substring(idx + 4);

                    subtranslation = StringParser.RemoveAll("<IMG", ">", subtranslation);

                    if (subphrase.Length > 1)
                    {
                        subtranslation = subtranslation.Replace(subphrase.Substring(0, 1) + ". ", subphrase + " ");
                        subtranslation = subtranslation.Replace(subphrase.Substring(0, 1) + "</B>. ", subphrase + "</B> ");
                    }

                    if (has_root)
                    {
                        subtranslation = subtranslation.Replace("~", root);
                        subtranslation = subtranslation.Replace("||", "");
                    }

                    subtranslation = subtranslation.Replace("<B>", "");
                    subtranslation = subtranslation.Replace("</B>", "");
                    subtranslation = subtranslation.Replace("<I>", "");
                    subtranslation = subtranslation.Replace("</I>", "");


                    if (subtranslation.IndexOf("1.") < 0 && subtranslation.IndexOf("1)") < 0)
                    {
                        if (string.Compare(subphrase, phrase, true, CultureInfo.InvariantCulture) == 0 && phrases.Length == 1)
                        {
                            //single answer
                            result.Translations.Add(subtranslation);
                            return;
                        }

                        subres = CreateNewResult(subphrase, languagesPair, subject);
                        subres.Translations.Add(subtranslation);
                        result.Childs.Add(subres);
                    }
                    else
                    {                     //parsing on parts
                        if (subtranslation.IndexOf("1.") < 0)
                        {
                            int    subsubdefinitionIdx = subtranslation.IndexOf("1)");
                            string abbr = subtranslation.Substring(0, subsubdefinitionIdx).Trim();
                            subtranslation = subtranslation.Substring(subsubdefinitionIdx + 2);
                            List <string> subsubsubtranslations = new List <string>();
                            for (int i = 2; i < 100; i++)
                            {
                                int numIdx = subtranslation.IndexOf(i.ToString(CultureInfo.InvariantCulture) + ")");
                                if (numIdx < 0)
                                {                                  //last def
                                    if (subtranslation.Trim() != ".")
                                    {
                                        subsubsubtranslations.Add(subtranslation.Trim());
                                    }
                                    else
                                    {
                                        subsubsubtranslations.Add(abbr);
                                        abbr = "";
                                    }
                                    break;
                                }
                                else
                                {
                                    string Definition = subtranslation.Substring(0, numIdx);
                                    subtranslation = subtranslation.Substring(numIdx + 2);
                                    subsubsubtranslations.Add(Definition.Trim());
                                }
                            }

                            if (string.Compare(subphrase, phrase, true, CultureInfo.InvariantCulture) == 0 && phrases.Length == 1)
                            {
                                //single answer
                                result.Abbreviation = abbr;
                                foreach (string s in subsubsubtranslations)
                                {
                                    result.Translations.Add(s);
                                }
                                return;
                            }


                            subres = CreateNewResult(subphrase, languagesPair, subject);
                            subres.Abbreviation = abbr;
                            foreach (string s in subsubsubtranslations)
                            {
                                subres.Translations.Add(s);
                            }
                            result.Childs.Add(subres);
                        }
                        else
                        {
                            int    subdefinitionIdx   = subtranslation.IndexOf("1.");
                            string tmp_subtranslation = subtranslation.Substring(subdefinitionIdx + 2).Trim();
                            if (string.IsNullOrEmpty(tmp_subtranslation))
                            {
                                subtranslation = subtranslation.Substring(0, subdefinitionIdx).Trim();
                            }
                            else
                            {
                                subtranslation = tmp_subtranslation;
                            }
                            List <string> subsubtranslations = new List <string>();
                            for (int i = 2; i < 100; i++)
                            {
                                int numIdx = subtranslation.IndexOf(i.ToString(CultureInfo.InvariantCulture) + ".");
                                if (numIdx < 0)
                                {                                  //last def
                                    subsubtranslations.Add(subtranslation.Trim());
                                    break;
                                }
                                else
                                {
                                    string Definition = subtranslation.Substring(0, numIdx);
                                    subtranslation = subtranslation.Substring(numIdx + 2);
                                    subsubtranslations.Add(Definition.Trim());
                                }
                            }

                            subres = CreateNewResult(subphrase, languagesPair, subject);
                            //subres.Translations.Add(" ");
                            result.Childs.Add(subres);
                            Result subsubres;

                            foreach (string subsubtranslation in subsubtranslations)
                            {
                                if (subsubtranslation.IndexOf("1)") < 0)
                                {
                                    subsubres = CreateNewResult("", languagesPair, subject);
                                    subsubres.Translations.Add(subsubtranslation);
                                    subres.Childs.Add(subsubres);
                                }
                                else
                                {
                                    string subdata             = subsubtranslation;
                                    int    subsubdefinitionIdx = subdata.IndexOf("1)");
                                    string abbr = subdata.Substring(0, subsubdefinitionIdx).Trim();
                                    subdata = subdata.Substring(subsubdefinitionIdx + 2);
                                    List <string> subsubsubtranslations = new List <string>();
                                    for (int i = 2; i < 100; i++)
                                    {
                                        int numIdx = subdata.IndexOf(i.ToString(CultureInfo.InvariantCulture) + ")");
                                        if (numIdx < 0)
                                        {                                          //last def
                                            if (subdata.Trim() != ".")
                                            {
                                                subsubsubtranslations.Add(subdata.Trim());
                                            }
                                            else
                                            {
                                                subsubsubtranslations.Add(abbr);
                                                abbr = "";
                                            }
                                            break;
                                        }
                                        else
                                        {
                                            string Definition = subdata.Substring(0, numIdx);
                                            subdata = subdata.Substring(numIdx + 2);
                                            subsubsubtranslations.Add(Definition.Trim());
                                        }
                                    }

                                    subsubres = CreateNewResult(abbr, languagesPair, subject);
                                    foreach (string s in subsubsubtranslations)
                                    {
                                        subsubres.Translations.Add(s);
                                    }
                                    subres.Childs.Add(subsubres);
                                }
                            }
                        }
                    }
                }
            }
        }
        protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            lock (cookieContainer)
            {
                if (coockieTime < DateTime.Now.AddHours(-1))
                {                  //emulate first access to site
                    WebRequestHelper helpertop =
                        new WebRequestHelper(result, new Uri("http://translate.meta.ua/"),
                                             networkSetting,
                                             WebRequestContentType.UrlEncodedGet);
                    helpertop.CookieContainer = cookieContainer;
                    string responseFromServertop = helpertop.GetResponse();
                    coockieTime = DateTime.Now;
                }
            }

            string lang_from = ConvertLanguage(languagesPair.From);
            string lang_to   = ConvertLanguage(languagesPair.To);

            string responseFromServer = null;

            lock (cookieContainer)
            {
                WebRequestHelper helper =
                    new WebRequestHelper(result, new Uri("http://translate.meta.ua/ajax/?sn=save_source"),
                                         networkSetting,
                                         WebRequestContentType.UrlEncoded);
                helper.CookieContainer = cookieContainer;

                //query
                //text_source=проверка&lang_to=ua&lang_from=ru&dict=**
                StringBuilder queryBuilder = new StringBuilder();
                queryBuilder.AppendFormat("text_source={0}&", phrase);
                queryBuilder.AppendFormat("lang_to={0}&lang_from={1}&", lang_to, lang_from);
                queryBuilder.AppendFormat("dict=", GetSubject(subject));
                string query = queryBuilder.ToString();
                helper.AddPostData(query);
                responseFromServer = helper.GetResponse();
                coockieTime        = DateTime.Now;
            }

            if (!String.IsNullOrEmpty(responseFromServer))
            {
                //{"r":true,"pc":1,"ui":"4c1ea0e46198f"}
                string code = StringParser.Parse("ui\":\"", "\"}", responseFromServer);
                //http://translate.meta.ua/ajax/?sn=get_translate&translate_uniqid=4c1ea0e46198f&lang_to=ua&lang_from=ru&translate_part=0
                string query = "http://translate.meta.ua/ajax/?sn=get_translate&translate_uniqid={0}&lang_to={1}&lang_from={2}&translate_part=0";
                string url   = String.Format(query, code, lang_to, lang_from);
                lock (cookieContainer)
                {
                    WebRequestHelper helper =
                        new WebRequestHelper(result, new Uri(url),
                                             networkSetting,
                                             WebRequestContentType.UrlEncodedGet);
                    helper.CookieContainer = cookieContainer;
                    responseFromServer     = helper.GetResponse();
                    coockieTime            = DateTime.Now;
                }
                if (!String.IsNullOrEmpty(responseFromServer))
                {
                    //{"source":"\u043f\u0440\u043e\u0432\u0435\u0440\u043a\u0430","translate":" \u043f\u0435\u0440\u0435\u0432\u0456\u0440\u043a\u0430","translate_part":"0","type":"p","index":0,"r":true}
                    string translation = StringParser.Parse("translate\":\"", "\"", responseFromServer);
                    result.Translations.Add(HttpUtilityEx.HtmlDecode(translation));
                }
                else
                {
                    throw new TranslationException("Nothing returned from call to " + url);
                }
            }
            else
            {
                throw new TranslationException("Nothing returned from call to http://translate.meta.ua/ajax/?sn=save_source");
            }
        }
Beispiel #26
0
 public static int GetHashCode(string serviceItemName, LanguagePair languagePair, string subject)
 {
     return(unchecked (serviceItemName.GetHashCode() * 1000 + languagePair.GetHashCode() + subject.GetHashCode() * 10000));
 }
Beispiel #27
0
        internal static void DoTranslate(IDictDServiceItem dictServiceItem, string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
        {
            ServiceItem      si = dictServiceItem as ServiceItem;
            DictionaryClient dc = null;

            try
            {
                dc = DictDClientsPool.GetPooledClient(dictServiceItem.Urls);
                DefinitionCollection definitions = dc.GetDefinitions(phrase, si.Name);
                string translation;
                if (definitions != null && definitions.Count > 0)
                {
                    foreach (Definition df in definitions)
                    {
                        translation = "html!<div style='width:{allowed_width}px;overflow:scroll;overflow-y:hidden;overflow-x:auto;'><pre>" + df.Description.Replace("\r\n", "<br />") + "&nbsp</pre></div>";
                        result.Translations.Add(translation);
                    }
                }
                else
                {
                    result.ResultNotFound = true;
                    throw new TranslationException("Nothing found");
                }
            }
            catch (DictionaryServerException e)
            {
                if (e.ErrorCode == 552)                //No definitions found
                {
                    result.ResultNotFound = true;
                    throw new TranslationException("Nothing found");
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (dc != null)
                {
                    DictDClientsPool.PushPooledClient(dc);
                }
            }
        }
Beispiel #28
0
 public ServiceItemData(string name, LanguagePair languagePair, string subject) : base(name, subject)
 {
     this.languagePair = languagePair;
 }
Beispiel #29
0
 protected override void DoTranslate(string phrase, LanguagePair languagesPair, string subject, Result result, NetworkSetting networkSetting)
 {
     WikiUtils.DoTranslate(searchEngine, searchHost, phrase, languagesPair, subject, result, networkSetting);
 }
Beispiel #30
0
 protected internal void AddSupportedTranslation(LanguagePair languagePair)
 {
     supportedTranslations.Add(languagePair);
 }