private bool CheckLanguageSupport(AbstractHumanTranslationService humanService, TranslationSettings settings)
    {
        var sourceLanguage = settings.SourceLanguage;

        if (!humanService.CheckSourceLanguageAvailability(sourceLanguage))
        {
            AddError(String.Format(ResHelper.GetString("translationservice.sourcelanguagenotsupported"), sourceLanguage));
            return(false);
        }

        var unavailableLanguages = humanService.CheckTargetLanguagesAvailability(settings.TargetLanguages);

        if (unavailableLanguages.Count > 0)
        {
            AddError(String.Format(ResHelper.GetString("translationservice.targetlanguagenotsupported"), String.Join(", ", unavailableLanguages)));
            return(false);
        }

        return(true);
    }
Esempio n. 2
0
    /// <summary>
    /// Translates document(s).
    /// </summary>
    private void Translate(object parameter)
    {
        if ((parameter == null) || nodeIds.Count < 1)
        {
            return;
        }

        AbstractMachineTranslationService machineService = null;
        AbstractHumanTranslationService   humanService   = null;
        TranslationSubmissionInfo         submission     = null;
        string submissionFileName        = "";
        int    charCount                 = 0;
        int    wordCount                 = 0;
        int    refreshId                 = 0;
        int    itemCount                 = 0;
        int    pageCount                 = 0;
        bool   oneSubmission             = translationElem.CreateSeparateSubmission;
        bool   success                   = false;
        bool   separateSubmissionCreated = false;

        TreeProvider tree = new TreeProvider();

        tree.AllowAsyncActions = false;

        try
        {
            // Begin log
            AddLog(ResHelper.GetString("contentrequest.starttranslate", currentUICulture));

            // Prepare translation settings
            var settings = PrepareTranslationSettings();

            // Check selected service
            var service = TranslationServiceInfoProvider.GetTranslationServiceInfo(translationElem.SelectedService);
            if (service == null)
            {
                return;
            }

            // Set if we need target tag (Translations.com workaround)
            settings.GenerateTargetTag = service.TranslationServiceGenerateTargetTag;

            if (service.TranslationServiceIsMachine)
            {
                machineService = AbstractMachineTranslationService.GetTranslationService(service, CurrentSiteName);
            }
            else
            {
                humanService = AbstractHumanTranslationService.GetTranslationService(service, CurrentSiteName);
            }

            bool langSupported = true;
            if (humanService != null)
            {
                var unavailableLanguages = humanService.CheckTargetLanguagesAvailability(settings.TargetLanguages);
                if (unavailableLanguages.Count > 0)
                {
                    AddError(String.Format(ResHelper.GetString("translationservice.targetlanguagenotsupported"), String.Join(", ", unavailableLanguages)));
                    langSupported = false;
                }
            }

            if (!langSupported)
            {
                return;
            }

            if ((machineService != null) || (humanService != null))
            {
                var data = tree.SelectNodes()
                           .CombineWithDefaultCulture(false)
                           .Published(false)
                           .Culture(settings.SourceLanguage)
                           .WhereIn("NodeID", nodeIds)
                           .OnSite(SiteContext.CurrentSiteName)
                           .OrderBy("NodeLevel, NodeAliasPath")
                           .Column("NodeID");

                if (!DataHelper.DataSourceIsEmpty(data))
                {
                    var processedNodes = new List <int>();

                    // Translate the documents
                    foreach (DataRow dr in data.Tables[0].Rows)
                    {
                        int nodeId = ValidationHelper.GetInteger(dr["NodeID"], 0);

                        // Get document in source language
                        var node = DocumentHelper.GetDocument(nodeId, settings.SourceLanguage, false, tree);
                        if (node == null)
                        {
                            // Document doesn't exist in source culture, skip it
                            continue;
                        }

                        if ((submission == null) && (humanService != null))
                        {
                            // Create new submission if not exists for human translation service
                            submission = TranslationServiceHelper.CreateSubmissionInfo(settings, service, MembershipContext.AuthenticatedUser.UserID, SiteContext.CurrentSiteID, node.GetDocumentName());
                        }

                        // Handle duplicities
                        if (processedNodes.Contains(nodeId))
                        {
                            continue;
                        }

                        processedNodes.Add(nodeId);
                        bool   targetLanguageVersionCreated = false;
                        bool   logged      = false;
                        string encodedPath = HTMLHelper.HTMLEncode(node.NodeAliasPath);

                        // Get target languages
                        IEnumerable <string> targetLanguages = settings.TargetLanguages;
                        if (chkSkipTranslated.Checked)
                        {
                            // Skip already translated
                            targetLanguages = targetLanguages.Except(node.GetTranslatedCultures());
                        }

                        foreach (var targetLanguage in targetLanguages)
                        {
                            // Log only once per document
                            if (!logged)
                            {
                                AddLog(String.Format(ResHelper.GetString("content.translating"), encodedPath, settings.SourceLanguage));
                                logged = true;
                            }

                            itemCount++;
                            targetLanguageVersionCreated = true;

                            if (humanService != null)
                            {
                                if (String.IsNullOrEmpty(submissionFileName))
                                {
                                    submissionFileName = node.NodeAlias;
                                }

                                var targetNode = TranslationServiceHelper.CreateTargetCultureNode(node, targetLanguage, true, false, !settings.TranslateAttachments);

                                TranslationSubmissionItemInfo submissionItem;
                                using (new CMSActionContext {
                                    TouchParent = false
                                })
                                {
                                    // Do not touch parent because all updated information are saved after last item
                                    submissionItem = TranslationServiceHelper.CreateSubmissionItemInfo(settings, submission, node, targetNode.DocumentID, targetLanguage);
                                }

                                charCount += submissionItem.SubmissionItemCharCount;
                                wordCount += submissionItem.SubmissionItemWordCount;
                            }
                            else
                            {
                                // Prepare local settings to translate per one target language
                                var localSettings = settings.Clone();
                                localSettings.TargetLanguages.Clear();
                                localSettings.TargetLanguages.Add(targetLanguage);

                                // Translate page via machine translator
                                TranslationServiceHelper.Translate(machineService, localSettings, node);
                            }
                        }

                        // Each page has own submission if human service is used
                        if (!oneSubmission && (humanService != null))
                        {
                            if (itemCount > 0)
                            {
                                SubmitSubmissionToService(itemCount, submission, charCount, wordCount, submissionFileName, humanService, true);

                                // Reset counters
                                itemCount = 0;
                                charCount = 0;
                                wordCount = 0;

                                // Reset submission file name
                                submissionFileName = null;

                                // At least one submission was created
                                separateSubmissionCreated = true;
                            }
                            else
                            {
                                // No documents were submitted to translation delete empty submission
                                TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);
                            }

                            // Reset submission to create new for next page
                            submission = null;
                        }

                        if (targetLanguageVersionCreated)
                        {
                            // Check if at least one target language version was created
                            pageCount++;
                        }

                        // Store parent ID to refresh UI
                        refreshId = node.NodeParentID;
                    }

                    success = true;
                }
                else
                {
                    AddError(ResHelper.GetString("TranslateDocument.NoSourceDocuments", currentUICulture));
                }
            }
            else
            {
                AddError(ResHelper.GetString("TranslateDocument.TranslationServiceNotFound", currentUICulture));
            }
        }
        catch (ThreadAbortException ex)
        {
            if (CMSThread.Stopped(ex))
            {
                // When canceled
                AddError(ResHelper.GetString("TranslateDocument.TranslationCanceled", currentUICulture));
            }
            else
            {
                // Log error
                LogExceptionToEventLog(ex);
            }
        }
        catch (Exception ex)
        {
            // Log error
            LogExceptionToEventLog(ex);
        }
        finally
        {
            var showAllAlreadyTranslatedError = false;
            if (itemCount > 0)
            {
                // All pages are submitted via only one submission or using machine service
                if ((humanService != null) && (submission != null))
                {
                    // Set submission name if more pages are translated
                    if (pageCount > 1)
                    {
                        submission.SubmissionName += " " + string.Format(GetString("translationservices.submissionnamesuffix"), pageCount - 1);
                        // Do not localize the file name
                        submissionFileName += string.Format(" (and {0} more)", pageCount - 1);
                    }

                    SubmitSubmissionToService(itemCount, submission, charCount, wordCount, submissionFileName, humanService, success);
                }
            }
            else if (oneSubmission)
            {
                TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission);

                // Log error only if the translation was successfully processed
                if (success)
                {
                    showAllAlreadyTranslatedError = true;
                }
            }
            else if (!separateSubmissionCreated)
            {
                // Separate submissions were used and no one was created
                showAllAlreadyTranslatedError = true;
            }

            if (showAllAlreadyTranslatedError)
            {
                AddError(ResHelper.GetString("TranslateDocument.DocumentsAlreadyTranslated", currentUICulture));
            }

            if (IsDialog)
            {
                ctlAsyncLog.Parameter = "wopener.location.replace(wopener.location); CloseDialog(); if (wopener.RefreshTree) { wopener.RefreshTree(null, null);}";
            }
            else
            {
                if (string.IsNullOrEmpty(CurrentError))
                {
                    // Overwrite refreshId variable if sub-levels are visible
                    if (ValidationHelper.GetBoolean(parameter, false) && Parameters.ContainsKey("refreshnodeid"))
                    {
                        refreshId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0);
                    }

                    // Refresh tree
                    ctlAsyncLog.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");";
                }
                else
                {
                    ctlAsyncLog.Parameter = "RefreshTree(null, null);";
                }
            }
        }
    }