Пример #1
0
        public static List<string> GettingAllUrls2(string PageSource, string MustMatchString)
        {
            List<string> suburllist1 = new List<string>();

            HtmlUtil htmlUtil = new HtmlUtil();
            PageSource = htmlUtil.EntityDecode(PageSource);

            try
            {
                string[] Dataconnection = System.Text.RegularExpressions.Regex.Split(PageSource, "2nd degree contact\",");
                string DataImage = string.Empty;

                foreach (string item in Dataconnection)
                {
                    if (!item.Contains("!DOCTYPE "))
                    {
                        if (item.Contains("&pid="))
                        {
                            int startindex = item.IndexOf("&pid=");
                            string start = item.Substring(startindex).Replace("&pid=","");
                            int endIndex = start.IndexOf(",");
                            string finalurl = "http://www.linkedin.com/profile/view?id=" + start.Substring(0, endIndex).Replace("\"", string.Empty);
                            suburllist1.Add(finalurl);
                        }
                    }
                }
            }

            catch { }
            return suburllist1.Distinct().ToList();
        }
        public static List<string> GettingAllprname(string PageSource, string MustMatchString)
        {
            List<string> suburllist1 = new List<string>();
            Dictionary<string, string> categoryDictonsry = new Dictionary<string, string>();

            HtmlUtil htmlUtil = new HtmlUtil();
            PageSource = htmlUtil.EntityDecode(PageSource);

            try
            {
                string[] Dataconnection = System.Text.RegularExpressions.Regex.Split(PageSource, "<select id=\"cid");
                string DataImage = string.Empty;
                string[] datacon = System.Text.RegularExpressions.Regex.Split(PageSource, "<select id=\"cid");
                string[] Arr = Regex.Split(datacon[1], "</option>");


                foreach (string item in Arr)
                {
                    if (!item.Contains("Show All Companies"))
                    {
                        if (item.Contains("option value"))//(item.Contains("search/profile/person?"))
                        {
                            string[] category = Regex.Split(item, ">");
                            string catId = category[0].Replace("<option value=", "").Replace("\n", "").Replace("\"", "").Replace("/", "").Trim();
                            string catname = category[1];
                            //string value = item.Substring(item.IndexOf("<option value="), item.IndexOf("\"") - item.IndexOf("<option value=")).Trim().Replace("<option value=", "").Replace("\"", "");
                            string finalurl = catId + "," + catname;
                            //categoryDict
                            // string finalurl = item.Substring(item.IndexOf("\""), item.IndexOf(">") - item.IndexOf("\"")).Trim().Replace("class=", "").Replace("\"","");
                            //string finalurl1 = "http://subscriber.zoominfo.com/zoominfo/" + finalurl;
                            suburllist1.Add(catname);
                            if (item.Contains("<select id=\"status"))
                            {
                                break;
                            }

                        }
                    }
                }
            }

            catch { }
            return suburllist1.Distinct().ToList();

        }
        public static List<string> GettingAllUrls1_writtenBysharan(string PageSource, string MustMatchString)
        {
            List<string> suburllist1 = new List<string>();

            HtmlUtil htmlUtil = new HtmlUtil();
            PageSource = htmlUtil.EntityDecode(PageSource);

            try
            {
                string[] Dataconnection = System.Text.RegularExpressions.Regex.Split(PageSource, "/profile/view?");
                string DataImage = string.Empty;

                foreach (string item in Dataconnection)
                {
                    if (!item.Contains("!DOCTYPE "))
                    {
                        if (item.Contains("vsrp_people_res_name"))
                        {

                            //string finalurl = item.Substring(item.IndexOf("/profile/view?id="), item.IndexOf("url_unfollow_infl") - item.IndexOf(",\"link_nprofile_view")).Trim();
                            //string finalurls1 = finalurl.Substring(finalurl.IndexOf("/profile/view?id="), finalurl.IndexOf("%3Aprimary")+10 - finalurl.IndexOf("")).Trim();
                            //int startindex = item.IndexOf("?");
                            //string start = item.Substring(startindex);
                            //int endIndex = start.IndexOf(",");

                            string id = Utils.getBetween(item, "pid=", "&");

                          //  string finalurl = "http://www.linkedin.com/profile/view" + start.Substring(0, endIndex).Replace("\"", string.Empty);

                            string finalurl = "https://www.linkedin.com/profile/view?id=" + id;
                            suburllist1.Add(finalurl);
                            //http://www.linkedin.com?id=230385129&authType=OUT_OF_NETWORK&authToken=OWRO&locale=en_US&srchid=2732756961375079939471&srchindex=1&srchtotal=10&trk=vsrp_people_res_name&trkInfo=VSRPsearchId%3A2732756961375079939471%2CVSRPtargetId%3A230385129%2CVSRPcmpt%3Aprimary"
                            //http://www.linkedin.com/profile/view?id=6741047&authType=OUT_OF_NETWORK&authToken=MWyZ&locale=en_US&srchid=2732758471375077875757&srchindex=1&srchtotal=55&trk=vsrp_people_res_name&trkInfo=VSRPsearchId%3A2732758471375077875757%2CVSRPtargetId%3A6741047%2CVSRPcmpt%3Aprimary

                        }
                    }
                }
            }

            catch { }
            return suburllist1.Distinct().ToList();

        }
Пример #4
0
        public static List<string> GettingAllUrls(string PageSource, string MustMatchString)
        {
            List<string> suburllist = new List<string>();

            HtmlUtil htmlUtil = new HtmlUtil();
            PageSource = htmlUtil.EntityDecode(PageSource);
            StringArray datagoogle = htmlUtil.GetHyperlinkedUrls(PageSource);

            for (int i = 0; i < datagoogle.Length; i++)
            {
                string hreflink = datagoogle.GetString(i);

                if (hreflink.Contains(MustMatchString) && hreflink.Contains("goback"))
                {
                    suburllist.Add(hreflink);
                }
            }
            return suburllist.Distinct().ToList();
        }
 /// <summary>
 /// 返回网页实体
 /// </summary>
 public static void WriteHtml(string msg)
 {
     msg = HtmlUtil.CompletePage(msg);
     Write(msg);
 }
Пример #6
0
        public void Fix(Subtitle subtitle, IFixCallbacks callbacks)
        {
            var    language  = Configuration.Settings.Language.FixCommonErrors;
            string fixAction = language.FixMissingPeriodAtEndOfLine;
            int    missigPeriodsAtEndOfLine = 0;

            for (int i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                Paragraph p        = subtitle.Paragraphs[i];
                Paragraph next     = subtitle.GetParagraphOrDefault(i + 1);
                string    nextText = string.Empty;
                if (next != null)
                {
                    nextText = HtmlUtil.RemoveHtmlTags(next.Text, true).TrimStart('-', '"', '„').TrimStart();
                }
                bool   isNextClose = next != null && next.StartTime.TotalMilliseconds - p.EndTime.TotalMilliseconds < 400;
                string tempNoHtml  = HtmlUtil.RemoveHtmlTags(p.Text).TrimEnd();

                if (IsOneLineUrl(p.Text) || p.Text.Contains(ExpectedChars) || p.Text.EndsWith('\''))
                {
                    // ignore urls
                }
                else if (!string.IsNullOrEmpty(nextText) && next != null &&
                         next.Text.Length > 0 &&
                         char.IsUpper(nextText[0]) &&
                         tempNoHtml.Length > 0 &&
                         !ExpectedString1.Contains(tempNoHtml[tempNoHtml.Length - 1]))
                {
                    string tempTrimmed = tempNoHtml.TrimEnd().TrimEnd('\'', '"', '“', '”').TrimEnd();
                    if (tempTrimmed.Length > 0 && !ExpectedString2.Contains(tempTrimmed[tempTrimmed.Length - 1]) && p.Text != p.Text.ToUpper())
                    {
                        //don't end the sentence if the next word is an I word as they're always capped.
                        bool isNextCloseAndStartsWithI = isNextClose && (nextText.StartsWith("I ", StringComparison.Ordinal) ||
                                                                         nextText.StartsWith("I'", StringComparison.Ordinal));

                        if (!isNextCloseAndStartsWithI)
                        {
                            //test to see if the first word of the next line is a name
                            if (!callbacks.IsName(next.Text.Split(WordSplitChars)[0]) && callbacks.AllowFix(p, fixAction))
                            {
                                string oldText = p.Text;
                                if (p.Text.EndsWith('>'))
                                {
                                    int lastLessThan = p.Text.LastIndexOf('<');
                                    if (lastLessThan > 0)
                                    {
                                        p.Text = p.Text.Insert(lastLessThan, ".");
                                    }
                                }
                                else
                                {
                                    if (p.Text.EndsWith('“') && tempNoHtml.StartsWith('„'))
                                    {
                                        p.Text = p.Text.TrimEnd('“') + ".“";
                                    }
                                    else if (p.Text.EndsWith('"') && tempNoHtml.StartsWith('"'))
                                    {
                                        p.Text = p.Text.TrimEnd('"') + ".\"";
                                    }
                                    else
                                    {
                                        p.Text += ".";
                                    }
                                }
                                if (p.Text != oldText)
                                {
                                    missigPeriodsAtEndOfLine++;
                                    callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                                }
                            }
                        }
                    }
                }
                else if (next != null && !string.IsNullOrEmpty(p.Text) && Utilities.AllLettersAndNumbers.Contains(p.Text[p.Text.Length - 1]))
                {
                    if (p.Text != p.Text.ToUpper())
                    {
                        var st = new StrippableText(next.Text);
                        if (st.StrippedText.Length > 0 && st.StrippedText != st.StrippedText.ToUpper() &&
                            char.IsUpper(st.StrippedText[0]))
                        {
                            if (callbacks.AllowFix(p, fixAction))
                            {
                                int j = p.Text.Length - 1;
                                while (j >= 0 && !@".!?¿¡".Contains(p.Text[j]))
                                {
                                    j--;
                                }

                                string endSign = ".";
                                if (j >= 0 && p.Text[j] == '¿')
                                {
                                    endSign = "?";
                                }

                                if (j >= 0 && p.Text[j] == '¡')
                                {
                                    endSign = "!";
                                }

                                string oldText = p.Text;
                                missigPeriodsAtEndOfLine++;
                                p.Text += endSign;
                                callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                            }
                        }
                    }
                }

                if (p.Text.Length > 4)
                {
                    int indexOfNewLine = p.Text.IndexOf(Environment.NewLine + " -", 3, StringComparison.Ordinal);
                    if (indexOfNewLine < 0)
                    {
                        indexOfNewLine = p.Text.IndexOf(Environment.NewLine + "-", 3, StringComparison.Ordinal);
                    }

                    if (indexOfNewLine < 0)
                    {
                        indexOfNewLine = p.Text.IndexOf(Environment.NewLine + "<i>-", 3, StringComparison.Ordinal);
                    }

                    if (indexOfNewLine < 0)
                    {
                        indexOfNewLine = p.Text.IndexOf(Environment.NewLine + "<i> -", 3, StringComparison.Ordinal);
                    }

                    if (indexOfNewLine > 0 && char.IsUpper(char.ToUpper(p.Text[indexOfNewLine - 1])) && callbacks.AllowFix(p, fixAction))
                    {
                        string oldText = p.Text;

                        string text = p.Text.Substring(0, indexOfNewLine);
                        var    st   = new StrippableText(text);
                        if (st.Pre.TrimEnd().EndsWith('¿')) // Spanish ¿
                        {
                            p.Text = p.Text.Insert(indexOfNewLine, "?");
                        }
                        else if (st.Pre.TrimEnd().EndsWith('¡')) // Spanish ¡
                        {
                            p.Text = p.Text.Insert(indexOfNewLine, "!");
                        }
                        else
                        {
                            p.Text = p.Text.Insert(indexOfNewLine, ".");
                        }

                        missigPeriodsAtEndOfLine++;
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                }
            }
            callbacks.UpdateFixStatus(missigPeriodsAtEndOfLine, language.AddPeriods, language.XPeriodsAdded);
        }
Пример #7
0
        public override string ToText(Subtitle subtitle, string title)
        {
            var sb = new StringBuilder();

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                sb.AppendLine($"{EncodeTimeCode(p.StartTime)} – {EncodeTimeCode(p.EndTime)}{Environment.NewLine}{HtmlUtil.RemoveHtmlTags(p.Text)}");
            }
            return(sb.ToString());
        }
Пример #8
0
        private Bitmap GenerateImageFromTextWithStyle(string text)
        {
            const bool subtitleFontBold  = false;
            bool       subtitleAlignLeft = comboBoxHAlign.SelectedIndex == 0;

            // remove styles for display text (except italic)
            text = Utilities.RemoveSsaTags(text);
            text = text.Replace("<b>", string.Empty);
            text = text.Replace("</b>", string.Empty);
            text = text.Replace("<B>", string.Empty);
            text = text.Replace("</B>", string.Empty);
            text = text.Replace("<u>", string.Empty);
            text = text.Replace("</u>", string.Empty);
            text = text.Replace("<U>", string.Empty);
            text = text.Replace("</U>", string.Empty);

            Font font;

            try
            {
                font = new Font(_subtitleFontName, _subtitleFontSize, FontStyle.Regular);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                font = new Font(FontFamily.Families[0].Name, _subtitleFontSize);
            }
            var bmp = new Bitmap(400, 200);
            var g   = Graphics.FromImage(bmp);

            SizeF textSize   = g.MeasureString("Hj!", font);
            var   lineHeight = (textSize.Height * 0.64f);

            textSize = g.MeasureString(HtmlUtil.RemoveHtmlTags(text), font);
            g.Dispose();
            bmp.Dispose();
            int sizeX = (int)(textSize.Width * 0.8) + 40;
            int sizeY = (int)(textSize.Height * 0.8) + 30;

            if (sizeX < 1)
            {
                sizeX = 1;
            }
            if (sizeY < 1)
            {
                sizeY = 1;
            }
            bmp = new Bitmap(sizeX, sizeY);
            g   = Graphics.FromImage(bmp);

            var lefts = new List <float>();

            foreach (var line in HtmlUtil.RemoveOpenCloseTags(text, HtmlUtil.TagItalic, HtmlUtil.TagFont).SplitToLines())
            {
                if (subtitleAlignLeft)
                {
                    lefts.Add(5);
                }
                else
                {
                    lefts.Add((float)(bmp.Width - g.MeasureString(line, font).Width * 0.8 + 15) / 2);
                }
            }

            g.TextRenderingHint  = TextRenderingHint.AntiAliasGridFit;
            g.SmoothingMode      = SmoothingMode.AntiAlias;
            g.CompositingQuality = CompositingQuality.HighQuality;

            var sf = new StringFormat
            {
                Alignment     = StringAlignment.Near,
                LineAlignment = StringAlignment.Near
            };
            // draw the text to a path
            var path = new GraphicsPath();

            // display italic
            var   sb       = new StringBuilder();
            int   i        = 0;
            bool  isItalic = false;
            float left     = 5;

            if (lefts.Count > 0)
            {
                left = lefts[0];
            }
            float top              = 5;
            bool  newLine          = false;
            int   lineNumber       = 0;
            float leftMargin       = left;
            int   newLinePathPoint = -1;
            Color c          = _subtitleColor;
            var   colorStack = new Stack <Color>();
            var   lastText   = new StringBuilder();

            while (i < text.Length)
            {
                if (text.Substring(i).StartsWith("<font ", StringComparison.OrdinalIgnoreCase))
                {
                    float addLeft           = 0;
                    int   oldPathPointIndex = path.PointCount;
                    if (oldPathPointIndex < 0)
                    {
                        oldPathPointIndex = 0;
                    }

                    if (sb.Length > 0)
                    {
                        TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    }
                    if (path.PointCount > 0)
                    {
                        PointF[] list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                        for (int k = oldPathPointIndex; k < list.Length; k++)
                        {
                            if (list[k].X > addLeft)
                            {
                                addLeft = list[k].X;
                            }
                        }
                    }
                    if (Math.Abs(addLeft) < 0.001)
                    {
                        addLeft = left + 2;
                    }
                    left = addLeft;

                    if (_borderWidth > 0)
                    {
                        g.DrawPath(new Pen(_borderColor, _borderWidth), path);
                    }

                    g.FillPath(new SolidBrush(c), path);
                    path.Reset();
                    path = new GraphicsPath();
                    sb.Clear();

                    int endIndex = text.Substring(i).IndexOf('>');
                    if (endIndex < 0)
                    {
                        i += 9999;
                    }
                    else
                    {
                        string fontContent = text.Substring(i, endIndex);
                        if (fontContent.Contains(" color=", StringComparison.OrdinalIgnoreCase))
                        {
                            var arr = fontContent.Substring(fontContent.IndexOf(" color=", StringComparison.OrdinalIgnoreCase) + 7).Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                            if (arr.Length > 0)
                            {
                                string fontColor = arr[0].Trim('\'').Trim('"').Trim('\'');
                                try
                                {
                                    colorStack.Push(c); // save old color
                                    if (fontColor.StartsWith("rgb(", StringComparison.OrdinalIgnoreCase))
                                    {
                                        arr = fontColor.Remove(0, 4).TrimEnd(')').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                        c   = Color.FromArgb(int.Parse(arr[0]), int.Parse(arr[1]), int.Parse(arr[2]));
                                    }
                                    else
                                    {
                                        c = ColorTranslator.FromHtml(fontColor);
                                    }
                                }
                                catch
                                {
                                    c = _subtitleColor;
                                }
                            }
                        }
                        i += endIndex;
                    }
                }
                else if (text.Substring(i).StartsWith("</font>", StringComparison.OrdinalIgnoreCase))
                {
                    if (text.Substring(i).ToLowerInvariant().Replace("</font>", string.Empty).Replace("</FONT>", string.Empty).Length > 0)
                    {
                        if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                        {
                            string t = sb.ToString();
                            sb.Clear();
                            sb.Append(' ');
                            sb.Append(t);
                        }

                        float addLeft           = 0;
                        int   oldPathPointIndex = path.PointCount - 1;
                        if (oldPathPointIndex < 0)
                        {
                            oldPathPointIndex = 0;
                        }
                        if (sb.Length > 0)
                        {
                            TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                        }
                        if (path.PointCount > 0)
                        {
                            PointF[] list = (PointF[])path.PathPoints.Clone(); // avoid using very slow path.PathPoints indexer!!!
                            for (int k = oldPathPointIndex; k < list.Length; k++)
                            {
                                if (list[k].X > addLeft)
                                {
                                    addLeft = list[k].X;
                                }
                            }
                        }
                        if (Math.Abs(addLeft) < 0.001)
                        {
                            addLeft = left + 2;
                        }
                        left = addLeft;

                        if (_borderWidth > 0)
                        {
                            g.DrawPath(new Pen(_borderColor, _borderWidth), path);
                        }
                        g.FillPath(new SolidBrush(c), path);
                        path.Reset();
                        sb.Clear();
                        if (colorStack.Count > 0)
                        {
                            c = colorStack.Pop();
                        }
                    }
                    i += 6;
                }
                else if (text.Substring(i).StartsWith("<i>", StringComparison.OrdinalIgnoreCase))
                {
                    if (sb.Length > 0)
                    {
                        TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    }
                    isItalic = true;
                    i       += 2;
                }
                else if (text.Substring(i).StartsWith("</i>", StringComparison.OrdinalIgnoreCase) && isItalic)
                {
                    if (lastText.EndsWith(' ') && !sb.StartsWith(' '))
                    {
                        string t = sb.ToString();
                        sb.Clear();
                        sb.Append(' ');
                        sb.Append(t);
                    }
                    TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    isItalic = false;
                    i       += 3;
                }
                else if (text.Substring(i).StartsWith(Environment.NewLine, StringComparison.Ordinal))
                {
                    TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
                    top    += lineHeight;
                    newLine = true;
                    i      += Environment.NewLine.Length - 1;
                    lineNumber++;
                    if (lineNumber < lefts.Count)
                    {
                        leftMargin = lefts[lineNumber];
                        left       = leftMargin;
                    }
                }
                else
                {
                    sb.Append(text[i]);
                }
                i++;
            }
            if (sb.Length > 0)
            {
                TextDraw.DrawText(font, sf, path, sb, isItalic, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint);
            }
            sf.Dispose();

            if (_borderWidth > 0)
            {
                g.DrawPath(new Pen(_borderColor, _borderWidth), path);
            }
            g.FillPath(new SolidBrush(c), path);
            g.Dispose();
            var nbmp = new NikseBitmap(bmp);

            nbmp.CropTransparentSidesAndBottom(2, true);
            return(nbmp.GetBitmap());
        }
        public override string ToText(Subtitle subtitle, string title)
        {
            var sb = new StringBuilder();

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                //00:03:15:22 00:03:23:10 This is line one.
                //This is line two.
                sb.AppendLine($"{EncodeTimeCode(p.StartTime)} {EncodeTimeCode(p.EndTime)} {HtmlUtil.RemoveHtmlTags(p.Text.Replace(Environment.NewLine, "//"), true)}");
            }
            return(sb.ToString());
        }
Пример #10
0
        public void SendMsgWhatsNew(DateTime scheduleDate)
        {
            var log            = ServiceProvider.GetService <IOptionsMonitor <ILog> >().Get("ASC.Notify");
            var WebItemManager = ServiceProvider.GetService <WebItemManager>();

            if (WebItemManager.GetItemsAll <IProduct>().Count == 0)
            {
                log.Info("No products. Return from function");
                return;
            }

            log.Info("Start send whats new.");

            var products = WebItemManager.GetItemsAll().ToDictionary(p => p.GetSysName());

            foreach (var tenantid in GetChangedTenants(ServiceProvider.GetService <FeedAggregateDataProvider>(), scheduleDate))
            {
                try
                {
                    using var scope = ServiceProvider.CreateScope();
                    var scopeClass = scope.ServiceProvider.GetService <StudioWhatsNewNotifyScope>();
                    var(tenantManager, paymentManager, tenantUtil, studioNotifyHelper, userManager, securityContext, authContext, authManager, commonLinkUtility, displayUserSettingsHelper, feedAggregateDataProvider, coreSettings) = scopeClass;
                    var tenant = tenantManager.GetTenant(tenantid);
                    if (tenant == null ||
                        tenant.Status != TenantStatus.Active ||
                        !TimeToSendWhatsNew(tenantUtil.DateTimeFromUtc(tenant.TimeZone, scheduleDate)) ||
                        TariffState.NotPaid <= paymentManager.GetTariff(tenantid).State)
                    {
                        continue;
                    }

                    tenantManager.SetCurrentTenant(tenant);
                    var client = WorkContext.NotifyContext.NotifyService.RegisterClient(studioNotifyHelper.NotifySource, scope);

                    log.InfoFormat("Start send whats new in {0} ({1}).", tenant.GetTenantDomain(coreSettings), tenantid);
                    foreach (var user in userManager.GetUsers())
                    {
                        if (!studioNotifyHelper.IsSubscribedToNotify(user, Actions.SendWhatsNew))
                        {
                            continue;
                        }

                        securityContext.AuthenticateMe(authManager.GetAccountByID(tenant.TenantId, user.ID));

                        var culture = string.IsNullOrEmpty(user.CultureName) ? tenant.GetCulture() : user.GetCulture();

                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        var feeds = feedAggregateDataProvider.GetFeeds(new FeedApiFilter
                        {
                            From = scheduleDate.Date.AddDays(-1),
                            To   = scheduleDate.Date.AddSeconds(-1),
                            Max  = 100,
                        });

                        var feedMinWrappers = feeds.ConvertAll(f => f.ToFeedMin(userManager));

                        var feedMinGroupedWrappers = feedMinWrappers
                                                     .Where(f =>
                                                            (f.CreatedDate == DateTime.MaxValue || f.CreatedDate >= scheduleDate.Date.AddDays(-1)) && //'cause here may be old posts with new comments
                                                            products.ContainsKey(f.Product) &&
                                                            !f.Id.StartsWith("participant")
                                                            )
                                                     .GroupBy(f => products[f.Product]);

                        var ProjectsProductName = products["projects"]?.Name; //from ASC.Feed.Aggregator.Modules.ModulesHelper.ProjectsProductName

                        var activities = feedMinGroupedWrappers
                                         .Where(f => f.Key.Name != ProjectsProductName) //not for project product
                                         .ToDictionary(
                            g => g.Key.Name,
                            g => g.Select(f => new WhatsNewUserActivity
                        {
                            Date            = f.CreatedDate,
                            UserName        = f.Author != null && f.Author.UserInfo != null ? f.Author.UserInfo.DisplayUserName(displayUserSettingsHelper) : string.Empty,
                            UserAbsoluteURL = f.Author != null && f.Author.UserInfo != null ? commonLinkUtility.GetFullAbsolutePath(f.Author.UserInfo.GetUserProfilePageURL(commonLinkUtility)) : string.Empty,
                            Title           = HtmlUtil.GetText(f.Title, 512),
                            URL             = commonLinkUtility.GetFullAbsolutePath(f.ItemUrl),
                            BreadCrumbs     = new string[0],
                            Action          = GetWhatsNewActionText(f)
                        }).ToList());


                        var projectActivities = feedMinGroupedWrappers
                                                .Where(f => f.Key.Name == ProjectsProductName) // for project product
                                                .SelectMany(f => f);

                        var projectActivitiesWithoutBreadCrumbs = projectActivities.Where(p => string.IsNullOrEmpty(p.ExtraLocation));

                        var whatsNewUserActivityGroupByPrjs = new List <WhatsNewUserActivity>();

                        foreach (var prawbc in projectActivitiesWithoutBreadCrumbs)
                        {
                            whatsNewUserActivityGroupByPrjs.Add(
                                new WhatsNewUserActivity
                            {
                                Date            = prawbc.CreatedDate,
                                UserName        = prawbc.Author != null && prawbc.Author.UserInfo != null ? prawbc.Author.UserInfo.DisplayUserName(displayUserSettingsHelper) : string.Empty,
                                UserAbsoluteURL = prawbc.Author != null && prawbc.Author.UserInfo != null ? commonLinkUtility.GetFullAbsolutePath(prawbc.Author.UserInfo.GetUserProfilePageURL(commonLinkUtility)) : string.Empty,
                                Title           = HtmlUtil.GetText(prawbc.Title, 512),
                                URL             = commonLinkUtility.GetFullAbsolutePath(prawbc.ItemUrl),
                                BreadCrumbs     = new string[0],
                                Action          = GetWhatsNewActionText(prawbc)
                            });
                        }

                        var groupByPrjs = projectActivities.Where(p => !string.IsNullOrEmpty(p.ExtraLocation)).GroupBy(f => f.ExtraLocation);
                        foreach (var gr in groupByPrjs)
                        {
                            var grlist = gr.ToList();
                            for (var i = 0; i < grlist.Count(); i++)
                            {
                                var ls = grlist[i];
                                whatsNewUserActivityGroupByPrjs.Add(
                                    new WhatsNewUserActivity
                                {
                                    Date            = ls.CreatedDate,
                                    UserName        = ls.Author != null && ls.Author.UserInfo != null ? ls.Author.UserInfo.DisplayUserName(displayUserSettingsHelper) : string.Empty,
                                    UserAbsoluteURL = ls.Author != null && ls.Author.UserInfo != null ? commonLinkUtility.GetFullAbsolutePath(ls.Author.UserInfo.GetUserProfilePageURL(commonLinkUtility)) : string.Empty,
                                    Title           = HtmlUtil.GetText(ls.Title, 512),
                                    URL             = commonLinkUtility.GetFullAbsolutePath(ls.ItemUrl),
                                    BreadCrumbs     = i == 0 ? new string[1] {
                                        gr.Key
                                    } : new string[0],
                                    Action = GetWhatsNewActionText(ls)
                                });
                            }
                        }

                        if (whatsNewUserActivityGroupByPrjs.Count > 0)
                        {
                            activities.Add(ProjectsProductName, whatsNewUserActivityGroupByPrjs);
                        }

                        if (activities.Count > 0)
                        {
                            log.InfoFormat("Send whats new to {0}", user.Email);
                            client.SendNoticeAsync(
                                Actions.SendWhatsNew, null, user,
                                new TagValue(Tags.Activities, activities),
                                new TagValue(Tags.Date, DateToString(scheduleDate.AddDays(-1), culture)),
                                new TagValue(CommonTags.Priority, 1)
                                );
                        }
                    }
                }
                catch (Exception error)
                {
                    log.Error(error);
                }
            }
        }
Пример #11
0
        public string Invoke(InterjectionRemoveContext context)
        {
            if (string.IsNullOrWhiteSpace(context.Text))
            {
                return(context.Text);
            }

            string text     = context.Text;
            string oldText  = text;
            bool   doRepeat = true;

            while (doRepeat)
            {
                doRepeat = false;
                foreach (string s in context.Interjections)
                {
                    if (text.Contains(s))
                    {
                        var regex = new Regex("\\b" + Regex.Escape(s) + "\\b");
                        var match = regex.Match(text);
                        if (match.Success)
                        {
                            int    index = match.Index;
                            string temp  = text.Remove(index, s.Length);
                            if (index == 0 && temp.StartsWith("... ", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(0, 4);
                            }

                            if (index == 3 && temp.StartsWith("<i>... ", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(3, 4);
                            }

                            if (index > 2 && " \r\n".Contains(text.Substring(index - 1, 1)) && temp.Substring(index).StartsWith("... ", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(index, 4);
                            }

                            if (index > 4 && temp.Substring(index - 4).StartsWith("\n<i>... ", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(index, 4);
                            }

                            if (temp.Remove(0, index) == " —" && temp.EndsWith("—  —", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(temp.Length - 3);
                                if (temp.EndsWith(Environment.NewLine + "—", StringComparison.Ordinal))
                                {
                                    temp = temp.Remove(temp.Length - 1).TrimEnd();
                                }
                            }
                            else if (temp.Remove(0, index) == " —" && temp.EndsWith("-  —", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(temp.Length - 3);
                                if (temp.EndsWith(Environment.NewLine + "-", StringComparison.Ordinal))
                                {
                                    temp = temp.Remove(temp.Length - 1).TrimEnd();
                                }
                            }
                            else if (index == 2 && temp.StartsWith("-  —", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(2, 2);
                            }
                            else if (index == 2 && temp.StartsWith("- —", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(2, 1);
                            }
                            else if (index == 0 && temp.StartsWith(" —", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(0, 2);
                            }
                            else if (index == 0 && temp.StartsWith('—'))
                            {
                                temp = temp.Remove(0, 1);
                            }
                            else if (index > 3 && (temp.Substring(index - 2) == ".  —" || temp.Substring(index - 2) == "!  —" || temp.Substring(index - 2) == "?  —"))
                            {
                                temp = temp.Remove(index - 2, 1).Replace("  ", " ");
                            }

                            string pre = string.Empty;
                            if (index > 0)
                            {
                                doRepeat = true;
                            }

                            bool removeAfter = true;

                            if (index > s.Length)
                            {
                                if (temp.Length > index - s.Length + 3)
                                {
                                    int    subIndex = index - s.Length + 1;
                                    string subTemp  = temp.Substring(subIndex, 3);
                                    if (subTemp == ", !" || subTemp == ", ?" || subTemp == ", .")
                                    {
                                        temp        = temp.Remove(subIndex, 2);
                                        removeAfter = false;
                                    }
                                    else if (subIndex > 3 && ".!?".Contains(temp.Substring(subIndex - 1, 1)))
                                    {
                                        subTemp = temp.Substring(subIndex);
                                        if (subTemp == " ..." || subTemp.StartsWith(" ..." + Environment.NewLine, StringComparison.InvariantCulture))
                                        {
                                            temp        = temp.Remove(subIndex, 4).Trim();
                                            removeAfter = false;
                                        }
                                    }
                                }

                                if (removeAfter && temp.Length > index - s.Length + 2)
                                {
                                    int    subIndex = index - s.Length;
                                    string subTemp  = temp.Substring(subIndex, 3);
                                    if (subTemp == ", !" || subTemp == ", ?" || subTemp == ", .")
                                    {
                                        temp        = temp.Remove(subIndex, 2);
                                        removeAfter = false;
                                    }
                                    else
                                    {
                                        subTemp = temp.Substring(subIndex);
                                        if (subTemp.StartsWith(", -—", StringComparison.Ordinal))
                                        {
                                            temp        = temp.Remove(subIndex, 3);
                                            removeAfter = false;
                                        }
                                        else if (subTemp.StartsWith(", --", StringComparison.Ordinal))
                                        {
                                            temp        = temp.Remove(subIndex, 2);
                                            removeAfter = false;
                                        }
                                        else if (index > 2 && subTemp.StartsWith("-  —", StringComparison.Ordinal))
                                        {
                                            temp        = temp.Remove(subIndex + 2, 2).Replace("  ", " ");
                                            removeAfter = false;
                                        }
                                    }
                                }

                                if (removeAfter && temp.Length > index - s.Length + 2)
                                {
                                    int    subIndex = index - s.Length + 1;
                                    string subTemp  = temp.Substring(subIndex, 2);
                                    if (subTemp == "-!" || subTemp == "-?" || subTemp == "-.")
                                    {
                                        temp        = temp.Remove(subIndex, 1);
                                        removeAfter = false;
                                    }

                                    subTemp = temp.Substring(subIndex);
                                    if (subTemp == " !" || subTemp == " ?" || subTemp == " .")
                                    {
                                        temp        = temp.Remove(subIndex, 1);
                                        removeAfter = false;
                                    }
                                }
                            }

                            if (index > 3 && index - 2 < temp.Length)
                            {
                                string subTemp = temp.Substring(index - 2);
                                if (subTemp.StartsWith(",  —", StringComparison.Ordinal) || subTemp.StartsWith(", —", StringComparison.Ordinal))
                                {
                                    temp = temp.Remove(index - 2, 1);
                                    index--;
                                }

                                if (subTemp.StartsWith("- ...", StringComparison.Ordinal))
                                {
                                    removeAfter = false;
                                }
                            }

                            if (removeAfter)
                            {
                                if (index == 0)
                                {
                                    if (temp.StartsWith('-'))
                                    {
                                        temp = temp.Remove(0, 1).Trim();
                                    }
                                }
                                else if (index == 3 && temp.StartsWith("<i>-", StringComparison.Ordinal))
                                {
                                    temp = temp.Remove(3, 1);
                                }
                                else if (index > 0 && temp.Length > index)
                                {
                                    pre  = text.Substring(0, index);
                                    temp = temp.Remove(0, index);
                                    if (temp.StartsWith('-') && pre.EndsWith('-'))
                                    {
                                        temp = temp.Remove(0, 1);
                                    }

                                    if (temp.StartsWith('-') && pre.EndsWith("- ", StringComparison.Ordinal))
                                    {
                                        temp = temp.Remove(0, 1);
                                    }
                                }

                                if (temp.StartsWith("...", StringComparison.Ordinal))
                                {
                                    pre = pre.Trim();
                                }
                                else
                                {
                                    while (temp.Length > 0 && " ,.?!".Contains(temp[0]))
                                    {
                                        temp     = temp.Remove(0, 1);
                                        doRepeat = true;
                                    }
                                }

                                if (temp.Length > 0 && s[0].ToString(CultureInfo.InvariantCulture) != s[0].ToString(CultureInfo.InvariantCulture).ToLowerInvariant())
                                {
                                    temp     = char.ToUpper(temp[0]) + temp.Substring(1);
                                    doRepeat = true;
                                }

                                if (temp.StartsWith('-') && pre.EndsWith(' '))
                                {
                                    temp = temp.Remove(0, 1);
                                }

                                if (temp.StartsWith('—') && pre.EndsWith(','))
                                {
                                    pre = pre.TrimEnd(',') + " ";
                                }

                                temp = pre + temp;
                            }

                            if (temp.EndsWith(Environment.NewLine + "- ", StringComparison.Ordinal))
                            {
                                temp = temp.Remove(temp.Length - 2).TrimEnd();
                            }

                            var st = new StrippableText(temp);
                            if (st.StrippedText.Length == 0)
                            {
                                return(string.Empty);
                            }

                            if (temp.StartsWith('-') && !temp.Contains(Environment.NewLine) && text.Contains(Environment.NewLine))
                            {
                                temp = temp.Remove(0, 1).Trim();
                            }

                            text = temp;
                        }
                    }
                }
            }

            var lines = text.SplitToLines();

            if (lines.Count == 2 && text != oldText)
            {
                if (lines[0] == "-" && lines[1] == "-")
                {
                    return(string.Empty);
                }

                if (lines[0].Length > 1 && lines[0][0] == '-' && lines[1].Trim() == "-")
                {
                    return(lines[0].Remove(0, 1).Trim());
                }

                if (lines[1].Length > 1 && lines[1][0] == '-' && lines[0].Trim() == "-")
                {
                    return(lines[1].Remove(0, 1).Trim());
                }

                if (lines[1].Length > 4 && lines[1].StartsWith("<i>-", StringComparison.Ordinal) && lines[0].Trim() == "-")
                {
                    return("<i>" + lines[1].Remove(0, 4).Trim());
                }

                if (lines[0].Length > 1 && lines[1] == "-" || lines[1] == "." || lines[1] == "!" || lines[1] == "?")
                {
                    if (lines[0].StartsWith('-') && oldText.Contains(Environment.NewLine + "-"))
                    {
                        lines[0] = lines[0].Remove(0, 1);
                    }

                    return(lines[0].Trim());
                }

                var noTags0 = HtmlUtil.RemoveHtmlTags(lines[0]).Trim();
                var noTags1 = HtmlUtil.RemoveHtmlTags(lines[1]).Trim();
                if (noTags0 == "-")
                {
                    if (noTags1 == noTags0)
                    {
                        return(string.Empty);
                    }

                    if (lines[1].Length > 1 && lines[1][0] == '-')
                    {
                        return(lines[1].Remove(0, 1).Trim());
                    }

                    if (lines[1].Length > 4 && lines[1].StartsWith("<i>-", StringComparison.Ordinal))
                    {
                        return("<i>" + lines[1].Remove(0, 4).Trim());
                    }

                    return(lines[1]);
                }

                if (noTags1 == "-")
                {
                    if (lines[0].Length > 1 && lines[0][0] == '-')
                    {
                        return(lines[0].Remove(0, 1).Trim());
                    }

                    if (lines[0].Length > 4 && lines[0].StartsWith("<i>-", StringComparison.Ordinal))
                    {
                        if (!lines[0].Contains("</i>") && lines[1].Contains("</i>"))
                        {
                            return("<i>" + lines[0].Remove(0, 4).Trim() + "</i>");
                        }

                        return("<i>" + lines[0].Remove(0, 4).Trim());
                    }

                    return(lines[0]);
                }
            }

            if (lines.Count == 2)
            {
                if (string.IsNullOrWhiteSpace(lines[1].RemoveChar('.').RemoveChar('?').RemoveChar('!').RemoveChar('-').RemoveChar('—')))
                {
                    text  = lines[0];
                    lines = text.SplitToLines();
                }
                else if (string.IsNullOrWhiteSpace(lines[0].RemoveChar('.').RemoveChar('?').RemoveChar('!').RemoveChar('-').RemoveChar('—')))
                {
                    text  = lines[1];
                    lines = text.SplitToLines();
                }
            }

            if (lines.Count == 1 && text != oldText && Utilities.GetNumberOfLines(oldText) == 2)
            {
                if ((oldText.StartsWith('-') || oldText.StartsWith("<i>-", StringComparison.Ordinal)) &&
                    (oldText.Contains("." + Environment.NewLine) || oldText.Contains(".</i>" + Environment.NewLine) ||
                     oldText.Contains("!" + Environment.NewLine) || oldText.Contains("!</i>" + Environment.NewLine) ||
                     oldText.Contains("?" + Environment.NewLine) || oldText.Contains("?</i>" + Environment.NewLine)))
                {
                    if (text.StartsWith("<i>-", StringComparison.Ordinal))
                    {
                        text = "<i>" + text.Remove(0, 4).TrimStart();
                    }
                    else
                    {
                        text = text.TrimStart('-').TrimStart();
                    }
                }
                else if ((oldText.Contains(Environment.NewLine + "-") || oldText.Contains(Environment.NewLine + "<i>-")) &&
                         (oldText.Contains("." + Environment.NewLine) || oldText.Contains(".</i>" + Environment.NewLine) ||
                          oldText.Contains("!" + Environment.NewLine) || oldText.Contains("!</i>" + Environment.NewLine) ||
                          oldText.Contains("?" + Environment.NewLine) || oldText.Contains("?</i>" + Environment.NewLine)))
                {
                    if (text.StartsWith("<i>-", StringComparison.Ordinal))
                    {
                        text = "<i>" + text.Remove(0, 4).TrimStart();
                    }
                    else
                    {
                        text = text.TrimStart('-').TrimStart();
                    }
                }
            }

            if (oldText != text)
            {
                text = text.Replace(Environment.NewLine + "<i>" + Environment.NewLine, Environment.NewLine + "<i>");
                text = text.Replace(Environment.NewLine + "</i>" + Environment.NewLine, "</i>" + Environment.NewLine);
                if (text.StartsWith("<i>" + Environment.NewLine, StringComparison.Ordinal))
                {
                    text = text.Remove(3, Environment.NewLine.Length);
                }

                if (text.EndsWith(Environment.NewLine + "</i>", StringComparison.Ordinal))
                {
                    text = text.Remove(text.Length - (Environment.NewLine.Length + 4), Environment.NewLine.Length);
                }

                text = text.Replace(Environment.NewLine + "</i>" + Environment.NewLine, "</i>" + Environment.NewLine);

                if (context.OnlySeparetedLines)
                {
                    if (string.IsNullOrEmpty(text))
                    {
                        return(text);
                    }

                    var oldLines = oldText.SplitToLines();
                    var newLines = text.SplitToLines();
                    if (oldLines.Count == 2 && newLines.Count == 1 &&
                        (oldLines[0] == newLines[0] || oldLines[1] == newLines[0]))
                    {
                        return(text);
                    }

                    return(oldText);
                }
            }

            return(text);
        }
Пример #12
0
        public override string ToText(Subtitle subtitle, string title)
        {
            const string paragraphWriteFormat = "{0} {1} {2}";
            const string timeFormat           = "{0:00}:{1:00}:{2:00}.{3:000}";
            var          sb = new StringBuilder();

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                string startTime = string.Format(timeFormat, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, p.StartTime.Milliseconds);
                string endTime   = string.Format(timeFormat, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, p.EndTime.Milliseconds);
                sb.AppendLine(string.Format(paragraphWriteFormat, startTime, endTime, HtmlUtil.RemoveHtmlTags(p.Text.Replace(Environment.NewLine, " "))));
            }
            return(sb.ToString().Trim());
        }
        private void FixSpanishInvertedLetter(char mark, string inverseMark, Paragraph p, Paragraph last, ref bool wasLastLineClosed, string fixAction, ref int fixCount, IFixCallbacks callbacks)
        {
            if (p.Text.Contains(mark))
            {
                bool skip = last != null && !p.Text.Contains(inverseMark) && last.Text.Contains(inverseMark) && !last.Text.Contains(mark);

                if (!skip && Utilities.CountTagInText(p.Text, mark) == Utilities.CountTagInText(p.Text, inverseMark) &&
                    HtmlUtil.RemoveHtmlTags(p.Text).TrimStart(inverseMark[0]).Contains(inverseMark) == false &&
                    HtmlUtil.RemoveHtmlTags(p.Text).TrimEnd(mark).Contains(mark) == false)
                {
                    skip = true;
                }

                if (!skip)
                {
                    int startIndex = 0;
                    int markIndex  = p.Text.IndexOf(mark);
                    if (!wasLastLineClosed && ((p.Text.IndexOf('!') > 0 && p.Text.IndexOf('!') < markIndex) ||
                                               (p.Text.IndexOf('?') > 0 && p.Text.IndexOf('?') < markIndex) ||
                                               (p.Text.IndexOf('.') > 0 && p.Text.IndexOf('.') < markIndex)))
                    {
                        wasLastLineClosed = true;
                    }
                    while (markIndex > 0 && startIndex < p.Text.Length)
                    {
                        int inverseMarkIndex = p.Text.IndexOf(inverseMark, startIndex, StringComparison.Ordinal);
                        if (wasLastLineClosed && (inverseMarkIndex < 0 || inverseMarkIndex > markIndex))
                        {
                            if (callbacks.AllowFix(p, fixAction))
                            {
                                int j = markIndex - 1;

                                while (j > startIndex && (p.Text[j] == '.' || p.Text[j] == '!' || p.Text[j] == '?'))
                                {
                                    j--;
                                }

                                while (j > startIndex &&
                                       (p.Text[j] != '.' || IsSpanishAbbreviation(p.Text, j, callbacks)) &&
                                       p.Text[j] != '!' &&
                                       p.Text[j] != '?' &&
                                       !(j > 3 && p.Text.Substring(j - 3, 3) == Environment.NewLine + "-") &&
                                       !(j > 4 && p.Text.Substring(j - 4, 4) == Environment.NewLine + " -") &&
                                       !(j > 6 && p.Text.Substring(j - 6, 6) == Environment.NewLine + "<i>-"))
                                {
                                    j--;
                                }

                                if (@".!?".Contains(p.Text[j]))
                                {
                                    j++;
                                }
                                if (j + 3 < p.Text.Length && p.Text.Substring(j + 1, 2) == Environment.NewLine)
                                {
                                    j += 3;
                                }
                                else if (j + 2 < p.Text.Length && p.Text.Substring(j, 2) == Environment.NewLine)
                                {
                                    j += 2;
                                }
                                if (j >= startIndex)
                                {
                                    string part = p.Text.Substring(j, markIndex - j + 1);

                                    string speaker    = string.Empty;
                                    int    speakerEnd = part.IndexOf(')');
                                    if (part.StartsWith('(') && speakerEnd > 0 && speakerEnd < part.IndexOf(mark))
                                    {
                                        while (Environment.NewLine.Contains(part[speakerEnd + 1]))
                                        {
                                            speakerEnd++;
                                        }
                                        speaker = part.Substring(0, speakerEnd + 1);
                                        part    = part.Substring(speakerEnd + 1);
                                    }
                                    speakerEnd = part.IndexOf(']');
                                    if (part.StartsWith('[') && speakerEnd > 0 && speakerEnd < part.IndexOf(mark))
                                    {
                                        while (Environment.NewLine.Contains(part[speakerEnd + 1]))
                                        {
                                            speakerEnd++;
                                        }
                                        speaker = part.Substring(0, speakerEnd + 1);
                                        part    = part.Substring(speakerEnd + 1);
                                    }

                                    var st = new StrippableText(part);
                                    if (j == 0 && mark == '!' && st.Pre == "¿" && Utilities.CountTagInText(p.Text, mark) == 1 && HtmlUtil.RemoveHtmlTags(p.Text).EndsWith(mark))
                                    {
                                        p.Text = inverseMark + p.Text;
                                    }
                                    else if (j == 0 && mark == '?' && st.Pre == "¡" && Utilities.CountTagInText(p.Text, mark) == 1 && HtmlUtil.RemoveHtmlTags(p.Text).EndsWith(mark))
                                    {
                                        p.Text = inverseMark + p.Text;
                                    }
                                    else
                                    {
                                        string temp       = inverseMark;
                                        int    addToIndex = 0;
                                        while (p.Text.Length > markIndex + 1 && p.Text[markIndex + 1] == mark &&
                                               Utilities.CountTagInText(p.Text, mark) > Utilities.CountTagInText(p.Text + temp, inverseMark))
                                        {
                                            temp    += inverseMark;
                                            st.Post += mark;
                                            markIndex++;
                                            addToIndex++;
                                        }

                                        p.Text     = p.Text.Remove(j, markIndex - j + 1).Insert(j, speaker + st.Pre + temp + st.StrippedText + st.Post);
                                        markIndex += addToIndex;
                                    }
                                }
                            }
                        }
                        else if (last != null && !wasLastLineClosed && inverseMarkIndex == p.Text.IndexOf(mark) && !last.Text.Contains(inverseMark))
                        {
                            string lastOldtext = last.Text;
                            int    idx         = last.Text.Length - 2;
                            while (idx > 0 && (last.Text.Substring(idx, 2) != ". ") && (last.Text.Substring(idx, 2) != "! ") && (last.Text.Substring(idx, 2) != "? "))
                            {
                                idx--;
                            }

                            last.Text = last.Text.Insert(idx, inverseMark);
                            fixCount++;
                            callbacks.AddFixToListView(last, fixAction, lastOldtext, last.Text);
                        }

                        startIndex = markIndex + 2;
                        if (startIndex < p.Text.Length)
                        {
                            markIndex = p.Text.IndexOf(mark, startIndex);
                        }
                        else
                        {
                            markIndex = -1;
                        }
                        wasLastLineClosed = true;
                    }
                }
                if (p.Text.EndsWith(mark + "...", StringComparison.Ordinal) && p.Text.Length > 4)
                {
                    p.Text = p.Text.Remove(p.Text.Length - 4, 4) + "..." + mark;
                }
            }
            else if (Utilities.CountTagInText(p.Text, inverseMark) == 1)
            {
                int idx = p.Text.IndexOf(inverseMark, StringComparison.Ordinal);
                while (idx < p.Text.Length && !@".!?".Contains(p.Text[idx]))
                {
                    idx++;
                }
                if (idx < p.Text.Length)
                {
                    p.Text = p.Text.Insert(idx, mark.ToString(CultureInfo.InvariantCulture));
                    if (p.Text.Contains("¡¿") && p.Text.Contains("!?"))
                    {
                        p.Text = p.Text.Replace("!?", "?!");
                    }
                    if (p.Text.Contains("¿¡") && p.Text.Contains("?!"))
                    {
                        p.Text = p.Text.Replace("?!", "!?");
                    }
                }
            }
        }
Пример #14
0
        public override string ToText(Subtitle subtitle, string title)
        {
            const string writeFormat = "{3}{2}<{0}><{1}>{2}";
            var          sb          = new StringBuilder();

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                sb.AppendLine(string.Format(writeFormat, EncodeTimeCode(p.StartTime), EncodeTimeCode(p.EndTime), Environment.NewLine, HtmlUtil.RemoveHtmlTags(p.Text, true)));
                //Var vi bedre end japanerne
                //eller bare mere heldige?
                //<12:03:29:03> <12:03:35:06>
            }
            return(sb.ToString());
        }
Пример #15
0
        public void Fix(Subtitle subtitle, IFixCallbacks callbacks)
        {
            string languageCode  = callbacks.Language;
            string fixAction     = Language.FixMissingSpace;
            int    missingSpaces = 0;
            var    dialogHelper  = new DialogSplitMerge
            {
                DialogStyle           = Configuration.Settings.General.DialogStyle,
                TwoLetterLanguageCode = callbacks.Language,
                ContinuationStyle     = Configuration.Settings.General.ContinuationStyle
            };
            const string expectedChars = @"""”<.";

            for (int i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                var p = subtitle.Paragraphs[i];

                // Arabic
                if (callbacks.Language == "ar") // special rules for Arabic
                {
                    if (!p.Text.Contains("www.", StringComparison.OrdinalIgnoreCase) &&
                        !p.Text.Contains("http://", StringComparison.OrdinalIgnoreCase) &&
                        !Url.IsMatch(p.Text)) // Skip urls.
                    {
                        string newText = FixSpaceAfter(p.Text, '؟');
                        newText = FixSpaceAfter(newText, '\u060C'); // Arabic comma
                        newText = FixSpaceAfter(newText, '.');
                        newText = FixSpaceAfter(newText, '!');
                        if (newText != p.Text && callbacks.AllowFix(p, fixAction))
                        {
                            missingSpaces++;
                            string oldText = p.Text;
                            p.Text = newText;
                            callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                        }
                    }

                    continue;
                }


                // missing space after comma ","
                var match = FixMissingSpacesReComma.Match(p.Text);
                while (match.Success)
                {
                    bool doFix = !expectedChars.Contains(p.Text[match.Index + 2]);

                    if (doFix && languageCode == "el" &&
                        (p.Text.Substring(match.Index).StartsWith("ό,τι", StringComparison.Ordinal) ||
                         p.Text.Substring(match.Index).StartsWith("O,τι", StringComparison.Ordinal) ||
                         p.Text.Substring(match.Index).StartsWith("Ό,τι", StringComparison.Ordinal) ||
                         p.Text.Substring(match.Index).StartsWith("Ο,ΤΙ", StringComparison.Ordinal) ||
                         p.Text.Substring(match.Index).StartsWith("ο,τι", StringComparison.Ordinal)))
                    {
                        doFix = false;
                    }

                    if (doFix && callbacks.AllowFix(p, fixAction))
                    {
                        missingSpaces++;
                        string oldText = p.Text;
                        p.Text = p.Text.Replace(match.Value, match.Value[0] + ", " + match.Value[match.Value.Length - 1]);
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                    match = match.NextMatch();
                }

                bool allowFix = callbacks.AllowFix(p, fixAction);

                // missing space after "?"
                match = FixMissingSpacesReQuestionMark.Match(p.Text);
                while (match.Success)
                {
                    if (allowFix && !@"""<".Contains(p.Text[match.Index + 2]))
                    {
                        missingSpaces++;
                        string oldText = p.Text;
                        p.Text = p.Text.Replace(match.Value, match.Value[0] + "? " + match.Value[match.Value.Length - 1]);
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                    match = FixMissingSpacesReQuestionMark.Match(p.Text, match.Index + 1);
                }

                // missing space after "!"
                match = FixMissingSpacesReExclamation.Match(p.Text);
                while (match.Success)
                {
                    if (allowFix && !@"""<".Contains(p.Text[match.Index + 2]))
                    {
                        missingSpaces++;
                        string oldText = p.Text;
                        p.Text = p.Text.Replace(match.Value, match.Value[0] + "! " + match.Value[match.Value.Length - 1]);
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                    match = FixMissingSpacesReExclamation.Match(p.Text, match.Index + 1);
                }

                // missing space after ":"
                match = FixMissingSpacesReColon.Match(p.Text);
                while (match.Success)
                {
                    int start = match.Index;
                    start -= 4;
                    if (start < 0)
                    {
                        start = 0;
                    }

                    int indexOfStartCodeTag = p.Text.IndexOf('{', start);
                    int indexOfEndCodeTag   = p.Text.IndexOf('}', start);
                    if (indexOfStartCodeTag >= 0 && indexOfEndCodeTag >= 0 && indexOfStartCodeTag < match.Index)
                    {
                        // we are inside a tag: like indexOfEndCodeTag "{y:i}Is this italic?"
                    }
                    else if (allowFix && !@"""<".Contains(p.Text[match.Index + 2]))
                    {
                        bool skipSwedishOrFinish = false;
                        if (languageCode == "sv" || languageCode == "fi")
                        {
                            var m = FixMissingSpacesReColonWithAfter.Match(p.Text, match.Index);
                            skipSwedishOrFinish = IsSwedishSkipValue(languageCode, m) || IsFinnishSkipValue(languageCode, m);
                        }
                        if (!skipSwedishOrFinish)
                        {
                            missingSpaces++;
                            string oldText = p.Text;
                            p.Text = p.Text.Replace(match.Value, match.Value[0] + ": " + match.Value[match.Value.Length - 1]);
                            callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                        }
                    }
                    match = FixMissingSpacesReColon.Match(p.Text, match.Index + 1);
                }

                // missing space after period "."
                match = FixMissingSpacesRePeriod.Match(p.Text);
                while (match.Success)
                {
                    if (!p.Text.Contains("www.", StringComparison.OrdinalIgnoreCase) &&
                        !p.Text.Contains("http://", StringComparison.OrdinalIgnoreCase) &&
                        !Url.IsMatch(p.Text)) // Skip urls.
                    {
                        bool isMatchAbbreviation = false;

                        string word = GetWordFromIndex(p.Text, match.Index);
                        if (Utilities.CountTagInText(word, '.') > 1)
                        {
                            isMatchAbbreviation = true;
                        }

                        if (!isMatchAbbreviation && word.Contains('@')) // skip emails
                        {
                            isMatchAbbreviation = true;
                        }

                        if (match.Value.Equals("h.d", StringComparison.OrdinalIgnoreCase) && match.Index > 0 && p.Text.Substring(match.Index - 1, 4).Equals("ph.d", StringComparison.OrdinalIgnoreCase))
                        {
                            isMatchAbbreviation = true;
                        }

                        if (!isMatchAbbreviation && callbacks.AllowFix(p, fixAction))
                        {
                            missingSpaces++;
                            string oldText = p.Text;
                            p.Text = p.Text.Replace(match.Value, match.Value.Replace(".", ". "));
                            callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                        }
                    }
                    match = match.NextMatch();
                }

                if (!p.Text.StartsWith("--", StringComparison.Ordinal))
                {
                    var newText = dialogHelper.AddSpaces(p.Text);
                    if (newText != p.Text && callbacks.AllowFix(p, fixAction))
                    {
                        missingSpaces++;
                        string oldText = p.Text;
                        p.Text = newText;
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                }

                //fix missing spaces before/after quotes - Get a"get out of jail free"card. -> Get a "get out of jail free" card.
                if (Utilities.CountTagInText(p.Text, '"') == 2)
                {
                    int    start = p.Text.IndexOf('"');
                    int    end   = p.Text.LastIndexOf('"');
                    string quote = p.Text.Substring(start, end - start + 1);
                    if (!quote.Contains(Environment.NewLine))
                    {
                        string newText         = p.Text;
                        int    indexOfFontTag  = newText.IndexOf("<font ", StringComparison.OrdinalIgnoreCase);
                        bool   isAfterAssTag   = newText.Contains("{\\") && start > 0 && newText[start - 1] == '}';
                        bool   isAfterEllipsis = start >= 3 && newText.Substring(start - 3, 3) == "...";
                        if (!isAfterAssTag && !isAfterEllipsis && start > 0 && !(Environment.NewLine + @" >[(♪♫¿").Contains(p.Text[start - 1]))
                        {
                            if (indexOfFontTag < 0 || start > newText.IndexOf('>', indexOfFontTag)) // font tags can contain "
                            {
                                newText = newText.Insert(start, " ");
                                end++;
                            }
                        }
                        if (end < newText.Length - 2 && !(Environment.NewLine + @" <,.!?:;])♪♫¿").Contains(p.Text[end + 1]))
                        {
                            if (indexOfFontTag < 0 || end > newText.IndexOf('>', indexOfFontTag)) // font tags can contain "
                            {
                                newText = newText.Insert(end + 1, " ");
                            }
                        }
                        if (newText != p.Text && callbacks.AllowFix(p, fixAction))
                        {
                            missingSpaces++;
                            string oldText = p.Text;
                            p.Text = newText;
                            callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                        }
                    }
                }

                //fix missing spaces before/after music quotes - #He's so happy# -> #He's so happy#
                var musicSymbols = new[] { '#', '♪', '♫' };
                if (p.Text.Length > 5 && p.Text.Contains(musicSymbols))
                {
                    var lines = p.Text.SplitToLines();
                    for (var lineIndex = 0; lineIndex < lines.Count; lineIndex++)
                    {
                        var lineNoHtmlAndMusicTags = HtmlUtil.RemoveHtmlTags(lines[lineIndex], true)
                                                     .RemoveChar('#')
                                                     .RemoveChar('♪')
                                                     .RemoveChar('♫');
                        if (lineNoHtmlAndMusicTags.Length > 1)
                        {
                            foreach (var musicSymbol in musicSymbols)
                            {
                                var fix = !(musicSymbol == '#' && Utilities.CountTagInText(lines[lineIndex], musicSymbol) == 1 && !lines[lineIndex].EndsWith(musicSymbol));
                                if (fix)
                                {
                                    lines[lineIndex] = FixMissingSpaceBeforeAfterMusicQuotes(lines[lineIndex], musicSymbol);
                                }
                            }
                        }
                    }
                    string newText = string.Join(Environment.NewLine, lines);
                    if (newText != p.Text && callbacks.AllowFix(p, fixAction))
                    {
                        missingSpaces++;
                        string oldText = p.Text;
                        p.Text = newText;
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                }

                //fix missing spaces in "Hey...move it!" to "Hey... move it!"
                int index = p.Text.IndexOf("...", StringComparison.Ordinal);
                if (index > 0 && p.Text.Length > 5)
                {
                    string newText = p.Text;
                    while (index != -1)
                    {
                        if (newText.Length > index + 4 && index >= 1)
                        {
                            if ((Utilities.AllLettersAndNumbers + "$").Contains(newText[index + 3]) &&
                                Utilities.AllLettersAndNumbers.Contains(newText[index - 1]))
                            {
                                newText = newText.Insert(index + 3, " ");
                            }
                        }
                        index = newText.IndexOf("...", index + 2, StringComparison.Ordinal);
                    }
                    if (newText != p.Text && callbacks.AllowFix(p, fixAction))
                    {
                        missingSpaces++;
                        string oldText = p.Text;
                        p.Text = newText;
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                }

                //fix missing spaces in "The<i>Bombshell</i> will gone." to "The <i>Bombshell</i> will gone."
                index = p.Text.IndexOf("<i>", StringComparison.OrdinalIgnoreCase);
                if (index >= 0 && p.Text.Length > 5)
                {
                    string newText = p.Text;
                    while (index != -1)
                    {
                        if (newText.Length > index + 6 && index > 1)
                        {
                            if (Utilities.AllLettersAndNumbers.Contains(newText[index + 3]) &&
                                Utilities.AllLettersAndNumbers.Contains(newText[index - 1]))
                            {
                                newText = newText.Insert(index, " ");
                            }
                        }
                        index = newText.IndexOf("<i>", index + 3, StringComparison.OrdinalIgnoreCase);
                    }
                    if (newText != p.Text && callbacks.AllowFix(p, fixAction))
                    {
                        missingSpaces++;
                        string oldText = p.Text;
                        p.Text = newText;
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                }

                //fix missing spaces in "The <i>Bombshell</i>will gone." to "The <i>Bombshell</i> will gone."
                index = p.Text.IndexOf("</i>", StringComparison.OrdinalIgnoreCase);
                if (index > 3 && p.Text.Length > 5)
                {
                    string newText = p.Text;
                    while (index != -1)
                    {
                        if (newText.Length > index + 6 && index > 1)
                        {
                            if (Utilities.AllLettersAndNumbers.Contains(newText[index + 4]) &&
                                Utilities.AllLettersAndNumbers.Contains(newText[index - 1]))
                            {
                                newText = newText.Insert(index + 4, " ");
                            }
                        }
                        index = newText.IndexOf("</i>", index + 4, StringComparison.OrdinalIgnoreCase);
                    }
                    if (newText != p.Text && callbacks.AllowFix(p, fixAction))
                    {
                        missingSpaces++;
                        string oldText = p.Text;
                        p.Text = newText;
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                }

                if (callbacks.Language == "fr") // special rules for French
                {
                    string newText = p.Text;
                    int    j       = 1;
                    while (j < newText.Length)
                    {
                        if (@"!?:;".Contains(newText[j]) && char.IsLetter(newText[j - 1]))
                        {
                            newText = newText.Insert(j++, " ");
                        }
                        j++;
                    }
                    if (newText != p.Text && callbacks.AllowFix(p, fixAction))
                    {
                        missingSpaces++;
                        string oldText = p.Text;
                        p.Text = newText;
                        callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                    }
                }
            }
            callbacks.UpdateFixStatus(missingSpaces, Language.FixMissingSpaces);
        }
Пример #16
0
        public override string ToText(Subtitle subtitle, string title)
        {
            Errors = null;
            var ss = Configuration.Settings.SubtitleSettings;

            if (!string.IsNullOrEmpty(ss.CurrentDCinemaEditRate))
            {
                var temp = ss.CurrentDCinemaEditRate.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (temp.Length == 2 && double.TryParse(temp[0], out var d1) && double.TryParse(temp[1], out var d2))
                {
                    _frameRate = d1 / d2;
                }
            }

            string xmlStructure =
                "<dcst:SubtitleReel xmlns:dcst=\"http://www.smpte-ra.org/schemas/428-7/2010/DCST\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + Environment.NewLine +
                "  <dcst:Id>" + DCinemaSmpte2007.GenerateId() + "</dcst:Id>" + Environment.NewLine +
                "  <dcst:ContentTitleText></dcst:ContentTitleText> " + Environment.NewLine +
                "  <dcst:AnnotationText>This is a subtitle file</dcst:AnnotationText>" + Environment.NewLine +
                "  <dcst:IssueDate>2012-06-26T12:33:59.000-00:00</dcst:IssueDate>" + Environment.NewLine +
                "  <dcst:ReelNumber>1</dcst:ReelNumber>" + Environment.NewLine +
                "  <dcst:Language>en</dcst:Language>" + Environment.NewLine +
                "  <dcst:EditRate>25 1</dcst:EditRate>" + Environment.NewLine +
                "  <dcst:TimeCodeRate>25</dcst:TimeCodeRate>" + Environment.NewLine +
                "  <dcst:StartTime>00:00:00:00</dcst:StartTime> " + Environment.NewLine +
                "  <dcst:LoadFont ID=\"theFontId\">urn:uuid:3dec6dc0-39d0-498d-97d0-928d2eb78391</dcst:LoadFont>" + Environment.NewLine +
                "  <dcst:SubtitleList>" + Environment.NewLine +
                "    <dcst:Font ID=\"theFontId\" Size=\"39\" Weight=\"normal\" Color=\"FFFFFFFF\" Effect=\"border\" EffectColor=\"FF000000\">" + Environment.NewLine +
                "    </dcst:Font>" + Environment.NewLine +
                "  </dcst:SubtitleList>" + Environment.NewLine +
                "</dcst:SubtitleReel>";

            var xml = new XmlDocument();

            xml.LoadXml(xmlStructure);
            xml.PreserveWhitespace = true;
            var nsmgr = new XmlNamespaceManager(xml.NameTable);

            nsmgr.AddNamespace("dcst", xml.DocumentElement.NamespaceURI);

            if (string.IsNullOrEmpty(ss.CurrentDCinemaMovieTitle))
            {
                ss.CurrentDCinemaMovieTitle = title;
            }

            if (ss.CurrentDCinemaFontSize == 0 || string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect))
            {
                Configuration.Settings.SubtitleSettings.InitializeDCinameSettings(true);
            }

            xml.DocumentElement.SelectSingleNode("dcst:ContentTitleText", nsmgr).InnerText = ss.CurrentDCinemaMovieTitle;
            if (string.IsNullOrEmpty(ss.CurrentDCinemaSubtitleId) || !ss.CurrentDCinemaSubtitleId.StartsWith("urn:uuid:"))
            {
                ss.CurrentDCinemaSubtitleId = "urn:uuid:" + Guid.NewGuid();
            }

            if (!ss.DCinemaAutoGenerateSubtitleId)
            {
                xml.DocumentElement.SelectSingleNode("dcst:Id", nsmgr).InnerText = ss.CurrentDCinemaSubtitleId;
            }

            xml.DocumentElement.SelectSingleNode("dcst:ReelNumber", nsmgr).InnerText = ss.CurrentDCinemaReelNumber;
            xml.DocumentElement.SelectSingleNode("dcst:IssueDate", nsmgr).InnerText  = ss.CurrentDCinemaIssueDate;
            if (string.IsNullOrEmpty(ss.CurrentDCinemaLanguage))
            {
                ss.CurrentDCinemaLanguage = "en";
            }

            xml.DocumentElement.SelectSingleNode("dcst:Language", nsmgr).InnerText = ss.CurrentDCinemaLanguage;
            if (ss.CurrentDCinemaEditRate == null && ss.CurrentDCinemaTimeCodeRate == null)
            {
                if (Math.Abs(Configuration.Settings.General.CurrentFrameRate - 24) < 0.01)
                {
                    ss.CurrentDCinemaEditRate     = "24 1";
                    ss.CurrentDCinemaTimeCodeRate = "24";
                }
                else
                {
                    ss.CurrentDCinemaEditRate     = "25 1";
                    ss.CurrentDCinemaTimeCodeRate = "25";
                }
            }
            xml.DocumentElement.SelectSingleNode("dcst:EditRate", nsmgr).InnerText     = ss.CurrentDCinemaEditRate;
            xml.DocumentElement.SelectSingleNode("dcst:TimeCodeRate", nsmgr).InnerText = ss.CurrentDCinemaTimeCodeRate;
            if (string.IsNullOrEmpty(ss.CurrentDCinemaStartTime))
            {
                ss.CurrentDCinemaStartTime = "00:00:00:00";
            }

            xml.DocumentElement.SelectSingleNode("dcst:StartTime", nsmgr).InnerText = ss.CurrentDCinemaStartTime;
            xml.DocumentElement.SelectSingleNode("dcst:LoadFont", nsmgr).InnerText  = ss.CurrentDCinemaFontUri;
            int    fontSize     = ss.CurrentDCinemaFontSize;
            string loadedFontId = "Font1";

            if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontId))
            {
                loadedFontId = ss.CurrentDCinemaFontId;
            }

            xml.DocumentElement.SelectSingleNode("dcst:LoadFont", nsmgr).Attributes["ID"].Value = loadedFontId;
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Size"].Value        = fontSize.ToString();
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Color"].Value       = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontColor).TrimStart('#').ToUpperInvariant();
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["ID"].Value          = loadedFontId;
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Effect"].Value      = ss.CurrentDCinemaFontEffect;
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["EffectColor"].Value = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontEffectColor).TrimStart('#').ToUpperInvariant();

            XmlNode mainListFont = xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr);
            var     no           = 0;

            foreach (var p in subtitle.Paragraphs)
            {
                if (p.Text != null)
                {
                    XmlNode subNode = xml.CreateElement("dcst:Subtitle", "dcst");

                    var id = xml.CreateAttribute("SpotNumber");
                    id.InnerText = (no + 1).ToString();
                    subNode.Attributes.Append(id);

                    var fadeUpTime = xml.CreateAttribute("FadeUpTime");
                    fadeUpTime.InnerText = new TimeCode(FramesToMilliseconds(Configuration.Settings.SubtitleSettings.DCinemaFadeUpTime)).ToHHMMSSFF();
                    subNode.Attributes.Append(fadeUpTime);

                    var fadeDownTime = xml.CreateAttribute("FadeDownTime");
                    fadeDownTime.InnerText = new TimeCode(FramesToMilliseconds(Configuration.Settings.SubtitleSettings.DCinemaFadeDownTime)).ToHHMMSSFF();
                    subNode.Attributes.Append(fadeDownTime);

                    var start = xml.CreateAttribute("TimeIn");
                    start.InnerText = ConvertToTimeString(p.StartTime);
                    subNode.Attributes.Append(start);

                    var end = xml.CreateAttribute("TimeOut");
                    end.InnerText = ConvertToTimeString(p.EndTime);
                    subNode.Attributes.Append(end);

                    var alignLeft = p.Text.StartsWith("{\\a1}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a5}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a9}", StringComparison.Ordinal) ||      // sub station alpha
                                    p.Text.StartsWith("{\\an1}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an4}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an7}", StringComparison.Ordinal);     // advanced sub station alpha

                    var alignRight = p.Text.StartsWith("{\\a3}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a7}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a11}", StringComparison.Ordinal) ||    // sub station alpha
                                     p.Text.StartsWith("{\\an3}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an6}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an9}", StringComparison.Ordinal);    // advanced sub station alpha

                    var alignVTop = p.Text.StartsWith("{\\a5}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a6}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a7}", StringComparison.Ordinal) ||      // sub station alpha
                                    p.Text.StartsWith("{\\an7}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an8}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an9}", StringComparison.Ordinal);     // advanced sub station alpha

                    var alignVCenter = p.Text.StartsWith("{\\a9}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a10}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a11}", StringComparison.Ordinal) || // sub station alpha
                                       p.Text.StartsWith("{\\an4}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an5}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an6}", StringComparison.Ordinal);  // advanced sub station alpha

                    var text = Utilities.RemoveSsaTags(p.Text);

                    var lines      = text.SplitToLines();
                    var vPos       = 1 + lines.Count * 7;
                    var vPosFactor = (int)Math.Round(fontSize / 7.4);
                    if (alignVTop)
                    {
                        vPos = Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8
                    }
                    else if (alignVCenter)
                    {
                        vPos = (int)Math.Round((lines.Count * vPosFactor * -1) / 2.0);
                    }
                    else
                    {
                        vPos = (lines.Count * vPosFactor) - vPosFactor + Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8
                    }

                    var isItalic   = false;
                    var fontNo     = 0;
                    var fontColors = new Stack <string>();
                    foreach (var line in lines)
                    {
                        XmlNode textNode = xml.CreateElement("dcst:Text", "dcst");

                        var vPosition = xml.CreateAttribute("Vposition");
                        vPosition.InnerText = vPos.ToString();
                        textNode.Attributes.Append(vPosition);

                        var vAlign = xml.CreateAttribute("Valign");
                        if (alignVTop)
                        {
                            vAlign.InnerText = "top";
                        }
                        else if (alignVCenter)
                        {
                            vAlign.InnerText = "center";
                        }
                        else
                        {
                            vAlign.InnerText = "bottom";
                        }

                        textNode.Attributes.Append(vAlign); textNode.Attributes.Append(vAlign);

                        var hAlign = xml.CreateAttribute("Halign");
                        if (alignLeft)
                        {
                            hAlign.InnerText = "left";
                        }
                        else if (alignRight)
                        {
                            hAlign.InnerText = "right";
                        }
                        else
                        {
                            hAlign.InnerText = "center";
                        }

                        textNode.Attributes.Append(hAlign);

                        var direction = xml.CreateAttribute("Direction");
                        direction.InnerText = "ltr";
                        textNode.Attributes.Append(direction);

                        var     i        = 0;
                        var     txt      = new StringBuilder();
                        var     html     = new StringBuilder();
                        XmlNode nodeTemp = xml.CreateElement("temp");
                        while (i < line.Length)
                        {
                            if (!isItalic && line.Substring(i).StartsWith("<i>", StringComparison.Ordinal))
                            {
                                if (txt.Length > 0)
                                {
                                    nodeTemp.InnerText = txt.ToString();
                                    html.Append(nodeTemp.InnerXml);
                                    txt.Clear();
                                }
                                isItalic = true;
                                i       += 2;
                            }
                            else if (isItalic && line.Substring(i).StartsWith("</i>", StringComparison.Ordinal))
                            {
                                if (txt.Length > 0)
                                {
                                    XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                    var italic = xml.CreateAttribute("Italic");
                                    italic.InnerText = "yes";
                                    fontNode.Attributes.Append(italic);

                                    if (line.Length > i + 5 && line.Substring(i + 4).StartsWith("</font>", StringComparison.Ordinal))
                                    {
                                        var fontColor = xml.CreateAttribute("Color");
                                        fontColor.InnerText = fontColors.Pop();
                                        fontNode.Attributes.Append(fontColor);
                                        fontNo--;
                                        i += 7;
                                    }

                                    fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString());
                                    html.Append(fontNode.OuterXml);
                                    txt.Clear();
                                }
                                isItalic = false;
                                i       += 3;
                            }
                            else if (line.Substring(i).StartsWith("<font color=", StringComparison.Ordinal) && line.Substring(i + 3).Contains('>'))
                            {
                                var endOfFont = line.IndexOf('>', i);
                                if (txt.Length > 0)
                                {
                                    nodeTemp.InnerText = txt.ToString();
                                    html.Append(nodeTemp.InnerXml);
                                    txt.Clear();
                                }
                                var c = DCinemaInterop.GetDCinemaColorString(line.Substring(i + 12, endOfFont - (i + 12)));
                                fontColors.Push(c);
                                fontNo++;
                                i = endOfFont;
                            }
                            else if (fontNo > 0 && line.Substring(i).StartsWith("</font>", StringComparison.Ordinal))
                            {
                                if (txt.Length > 0)
                                {
                                    XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                    var fontColor = xml.CreateAttribute("Color");
                                    fontColor.InnerText = fontColors.Pop();
                                    fontNode.Attributes.Append(fontColor);

                                    if (line.Length > i + 9 && line.Substring(i + 7).StartsWith("</i>", StringComparison.Ordinal))
                                    {
                                        XmlAttribute italic = xml.CreateAttribute("Italic");
                                        italic.InnerText = "yes";
                                        fontNode.Attributes.Append(italic);
                                        isItalic = false;
                                        i       += 4;
                                    }

                                    fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString());
                                    html.Append(fontNode.OuterXml);
                                    txt.Clear();
                                }
                                fontNo--;
                                i += 6;
                            }
                            else
                            {
                                txt.Append(line[i]);
                            }
                            i++;
                        }

                        if (fontNo > 0)
                        {
                            if (txt.Length > 0)
                            {
                                XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                var fontColor = xml.CreateAttribute("Color");
                                fontColor.InnerText = fontColors.Peek();
                                fontNode.Attributes.Append(fontColor);

                                if (isItalic)
                                {
                                    var italic = xml.CreateAttribute("Italic");
                                    italic.InnerText = "yes";
                                    fontNode.Attributes.Append(italic);
                                }

                                fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString());
                                html.Append(fontNode.OuterXml);
                            }
                            else if (html.Length > 0 && html.ToString().StartsWith("<dcst:Font ", StringComparison.Ordinal))
                            {
                                XmlDocument temp = new XmlDocument();
                                temp.LoadXml("<root>" + html.ToString().Replace("dcst:Font", "Font") + "</root>");
                                XmlNode fontNode = xml.CreateElement("dcst:Font");
                                fontNode.InnerXml = temp.DocumentElement.SelectSingleNode("Font").InnerXml;
                                foreach (XmlAttribute a in temp.DocumentElement.SelectSingleNode("Font").Attributes)
                                {
                                    var newA = xml.CreateAttribute(a.Name);
                                    newA.InnerText = a.InnerText;
                                    fontNode.Attributes.Append(newA);
                                }

                                var fontColor = xml.CreateAttribute("Color");
                                fontColor.InnerText = fontColors.Peek();
                                fontNode.Attributes.Append(fontColor);

                                html.Clear();
                                html.Append(fontNode.OuterXml);
                            }
                        }
                        else if (isItalic)
                        {
                            if (txt.Length > 0)
                            {
                                XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                var italic = xml.CreateAttribute("Italic");
                                italic.InnerText = "yes";
                                fontNode.Attributes.Append(italic);

                                fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString());
                                html.Append(fontNode.OuterXml);
                            }
                        }
                        else
                        {
                            if (txt.Length > 0)
                            {
                                nodeTemp.InnerText = txt.ToString();
                                html.Append(nodeTemp.InnerXml);
                            }
                        }
                        textNode.InnerXml = html.ToString();
                        if (html.Length == 0)
                        {
                            textNode.InnerText = " "; // We need to have at least a single space character on exporting empty subtitles, because otherwise I will get errors on import.ou need to have at least a single space character on exporting empty subtitles, otherwise we will get errors on import.
                        }

                        subNode.AppendChild(textNode);
                        if (alignVTop)
                        {
                            vPos += vPosFactor;
                        }
                        else
                        {
                            vPos -= vPosFactor;
                        }
                    }
                    if (subNode.InnerXml.Length == 0)
                    { // Empty text is just one space
                        XmlNode textNode = xml.CreateElement("dcst:Text", "dcst");
                        textNode.InnerXml = " ";
                        subNode.AppendChild(textNode);

                        var vPosition = xml.CreateAttribute("Vposition");
                        vPosition.InnerText = vPos.ToString();
                        textNode.Attributes.Append(vPosition);

                        var vAlign = xml.CreateAttribute("Valign");
                        vAlign.InnerText = "bottom";
                        textNode.Attributes.Append(vAlign);
                    }
                    mainListFont.AppendChild(subNode);
                    no++;
                }
            }

            var result = ToUtf8XmlString(xml)
                         .Replace("encoding=\"utf-8\"", "encoding=\"UTF-8\"")
                         .Replace(" xmlns:dcst=\"dcst\"", string.Empty)
                         .Replace("<dcst:", "<")
                         .Replace("</dcst:", "</")
                         .Replace("xmlns:dcst=\"http://www.smpte-ra.org/schemas/", "xmlns=\"http://www.smpte-ra.org/schemas/");

            const string res    = "Nikse.SubtitleEdit.Resources.SMPTE-428-7-2010-DCST.xsd.gz";
            var          asm    = System.Reflection.Assembly.GetExecutingAssembly();
            var          stream = asm.GetManifestResourceStream(res);

            if (stream != null)
            {
                try
                {
                    var xmld = new XmlDocument();
                    var rdr  = new StreamReader(stream);
                    var zip  = new GZipStream(rdr.BaseStream, CompressionMode.Decompress);
                    xmld.LoadXml(result);
                    using (var xr = XmlReader.Create(zip))
                    {
                        xmld.Schemas.Add(null, xr);
                        xmld.Validate(ValidationCallBack);
                    }
                }
                catch (Exception exception)
                {
                    Errors = "Error validating xml via SMPTE-428-7-2010-DCST.xsd: " + exception.Message;
                }
            }

            return(FixDcsTextSameLine(result));
        }
Пример #17
0
        public override string ToText(Subtitle subtitle, string title)
        {
            var sb = new StringBuilder();

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                //00:00:54:08   00:00:58:06 - Saucers... - ... a dry lake bed.  (newline is \r)
                sb.AppendLine($"{EncodeTimeCode(p.StartTime)}\t{EncodeTimeCode(p.EndTime)}\t{HtmlUtil.RemoveHtmlTags(p.Text, true).Replace(Environment.NewLine, "\r")}");
            }
            return(sb.ToString());
        }
Пример #18
0
        public override void Execute()
        {
            ErrorInfo            info   = ((ExceptionData)Model).Error;
            List <ExceptionInfo> errors = ((ExceptionData)Model).Infos;

            errors.Reverse();
            int i = 0;

            WriteLiteral("\r\n<!DOCTYPE html>\r\n<html>\r\n<head>\r\n    <title>程序出错了!</title>\r\n    <meta");

            WriteLiteral(" http-equiv=\"X-UA-Compatible\"");

            WriteLiteral(" content=\"IE=edge\"");

            WriteLiteral(" />\r\n    <meta");

            WriteLiteral(" http-equiv=\"Content-Type\"");

            WriteLiteral(" content=\"text/html; charset=utf-8\"");

            WriteLiteral(" />\r\n    <meta");

            WriteLiteral(" name=\"viewport\"");

            WriteLiteral(" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable" +
                         "=0;\"");

            WriteLiteral(" />\r\n    <link");

            WriteLiteral(" rel=\"stylesheet\"");

            WriteLiteral(" type=\"text/css\"");

            WriteAttribute("href", Tuple.Create(" href=\"", 705), Tuple.Create("\"", 778)
                           , Tuple.Create(Tuple.Create("", 712), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/bootstrap/css/bootstrap.min.css".AppVirutalPath()
                                                                                                            , 712), false)
                           );

            WriteLiteral(" />\r\n    <link");

            WriteLiteral(" rel=\"stylesheet\"");

            WriteLiteral(" type=\"text/css\"");

            WriteAttribute("href", Tuple.Create(" href=\"", 826), Tuple.Create("\"", 905)
                           , Tuple.Create(Tuple.Create("", 833), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/bootstrap/css/bootstrap-theme.min.css".AppVirutalPath()
                                                                                                            , 833), false)
                           );

            WriteLiteral(" />\r\n</head>\r\n<body>\r\n    <div");

            WriteLiteral(" class=\"container\"");

            WriteLiteral(">\r\n        <h2");

            WriteLiteral(" class=\"text-danger\"");

            WriteLiteral(">“");

            Write(info.Page);

            WriteLiteral("”出现错误。 </h2>\r\n        <h2><small>");

            Write(info.Url);

            WriteLiteral("</small></h2>\r\n        <div");

            WriteLiteral(" class=\"panel-group\"");

            WriteLiteral(" id=\"exceptionDetail\"");

            WriteLiteral(">\r\n");


            foreach (ExceptionInfo error in errors)
            {
                string inClass = string.Empty;
                if (i == 0)
                {
                    inClass = "in";
                }
                string name = "error" + (++i);



                WriteLiteral("                <div");

                WriteLiteral(" class=\"panel panel-default\"");

                WriteLiteral(">\r\n                    <div");

                WriteLiteral(" class=\"panel-heading\"");

                WriteLiteral(">\r\n                        <h4");

                WriteLiteral(" class=\"panel-title\"");

                WriteLiteral(">\r\n                            <a");

                WriteLiteral(" data-toggle=\"collapse\"");

                WriteLiteral(" data-parent=\"#exceptionDetail\"");

                WriteAttribute("href", Tuple.Create(" href=\"", 1685), Tuple.Create("\"", 1705)
                               , Tuple.Create(Tuple.Create("", 1692), Tuple.Create <System.Object, System.Int32>("#" + name
                                                                                                                 , 1692), false)
                               );

                WriteLiteral(">");

                Write(StringUtil.EscapeHtml(error.Message));

                WriteLiteral("</a>\r\n                        </h4>\r\n                    </div>\r\n                " +
                             "    <div");

                WriteAttribute("id", Tuple.Create(" id=\"", 1833), Tuple.Create("\"", 1843)
                               , Tuple.Create(Tuple.Create("", 1838), Tuple.Create <System.Object, System.Int32>(name
                                                                                                                 , 1838), false)
                               );

                WriteAttribute("class", Tuple.Create(" class=\"", 1844), Tuple.Create("\"", 1908)
                               , Tuple.Create(Tuple.Create("", 1852), Tuple.Create <System.Object, System.Int32>(HtmlUtil.MergeClass("panel-collapse collapse", inClass)
                                                                                                                 , 1852), false)
                               );

                WriteLiteral(">\r\n                        <div");

                WriteLiteral(" class=\"panel-body\"");

                WriteLiteral(">\r\n                            <dl");

                WriteLiteral(" class=\"dl-horizontal\"");

                WriteLiteral(">\r\n                                <dt>例外类型</dt>\r\n                               " +
                             " <dd>");

                Write(error.Type);

                WriteLiteral("</dd>\r\n                            </dl>\r\n");


                if (!string.IsNullOrEmpty(error.TargetSite))
                {
                    WriteLiteral("                                <dl");

                    WriteLiteral(" class=\"dl-horizontal\"");

                    WriteLiteral(">\r\n                                    <dt>TargetSite</dt>\r\n                     " +
                                 "               <dd>");

                    Write(StringUtil.EscapeHtml(error.TargetSite));

                    WriteLiteral("</dd>\r\n                                </dl>\r\n");
                }

                WriteLiteral("                            <dl");

                WriteLiteral(" class=\"dl-horizontal\"");

                WriteLiteral(">\r\n                                <dt>错误源</dt>\r\n                                " +
                             "<dd>");

                Write(error.ErrorSource + ".dll");

                WriteLiteral("</dd>\r\n                            </dl>\r\n");


                if (!string.IsNullOrEmpty(error.ErrorObj))
                {
                    WriteLiteral("                                <dl");

                    WriteLiteral(" class=\"dl-horizontal\"");

                    WriteLiteral(">\r\n                                    <dt>错误对象</dt>\r\n                           " +
                                 "         <dd>");

                    Write(StringUtil.EscapeHtml(error.ErrorObj));

                    WriteLiteral("</dd>\r\n                                </dl>\r\n");

                    WriteLiteral("                                <dl");

                    WriteLiteral(" class=\"dl-horizontal\"");

                    WriteLiteral(">\r\n                                    <dt>错误对象类型</dt>\r\n                         " +
                                 "           <dd>");

                    Write(StringUtil.EscapeHtml(error.ErrorObjType));

                    WriteLiteral("</dd>\r\n                                </dl>\r\n");
                }

                WriteLiteral("                            ");

                if (!string.IsNullOrEmpty(error.Argument))
                {
                    WriteLiteral("                                <dl");

                    WriteLiteral(" class=\"dl-horizontal\"");

                    WriteLiteral(">\r\n                                    <dt>函数参数</dt>\r\n                           " +
                                 "         <dd>");

                    Write(StringUtil.EscapeHtml(error.Argument));

                    WriteLiteral("</dd>\r\n                                </dl>\r\n");
                }

                WriteLiteral("                            ");

                if (error.OtherInfos.Count > 0)
                {
                    foreach (KeyValuePair <string, string> pair in error.OtherInfos)
                    {
                        WriteLiteral("                                    <dl");

                        WriteLiteral(" class=\"dl-horizontal\"");

                        WriteLiteral(">\r\n                                        <dt>");

                        Write(pair.Key);

                        WriteLiteral("</dt>\r\n                                        <dd><pre>");

                        Write(StringUtil.EscapeHtml(pair.Value));

                        WriteLiteral("</pre></dd>\r\n                                    </dl>\r\n");
                    }
                }

                WriteLiteral("                            <pre>");

                Write(StringUtil.EscapeHtml(error.StackTrace));

                WriteLiteral("</pre>\r\n                        </div>\r\n                    </div>\r\n             " +
                             "   </div>\r\n");
            }

            WriteLiteral("        </div>\r\n        <script");

            WriteLiteral(" type=\"text/javascript\"");

            WriteAttribute("src", Tuple.Create(" src=\"", 4514), Tuple.Create("\"", 4579)
                           , Tuple.Create(Tuple.Create("", 4520), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/lib/jquery-1.11.1.min.js".AppVirutalPath()
                                                                                                             , 4520), false)
                           );

            WriteLiteral("></script>\r\n        <script");

            WriteLiteral(" type=\"text/javascript\"");

            WriteAttribute("src", Tuple.Create(" src=\"", 4630), Tuple.Create("\"", 4700)
                           , Tuple.Create(Tuple.Create("", 4636), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/bootstrap/js/bootstrap.min.js".AppVirutalPath()
                                                                                                             , 4636), false)
                           );

            WriteLiteral("></script>\r\n</body>\r\n</html>\r\n");
        }
Пример #19
0
        private void buttonTranslate_Click(object sender, EventArgs e)
        {
            if (buttonTranslate.Text == Configuration.Settings.Language.General.Cancel)
            {
                buttonTranslate.Enabled = false;
                _breakTranslation       = true;
                buttonOK.Enabled        = true;
                buttonCancel.Enabled    = true;
                return;
            }

            // empty all texts
            foreach (Paragraph p in _translatedSubtitle.Paragraphs)
            {
                p.Text = string.Empty;
            }

            if (!_googleTranslate)
            {
                string from = (comboBoxFrom.SelectedItem as ComboBoxItem).Value;
                string to   = (comboBoxTo.SelectedItem as ComboBoxItem).Value;
                DoMicrosoftTranslate(from, to);
                return;
            }

            _formattingTypes = new FormattingType[_subtitle.Paragraphs.Count];

            buttonOK.Enabled     = false;
            buttonCancel.Enabled = false;
            _breakTranslation    = false;
            buttonTranslate.Text = Configuration.Settings.Language.General.Cancel;
            const int textMaxSize = 1000;

            Cursor.Current          = Cursors.WaitCursor;
            progressBar1.Maximum    = _subtitle.Paragraphs.Count;
            progressBar1.Value      = 0;
            progressBar1.Visible    = true;
            labelPleaseWait.Visible = true;
            int start = 0;

            try
            {
                var sb    = new StringBuilder();
                int index = 0;
                for (int i = 0; i < _subtitle.Paragraphs.Count; i++)
                {
                    Paragraph p    = _subtitle.Paragraphs[i];
                    string    text = p.Text.Trim();
                    if (text.StartsWith("<i>", StringComparison.Ordinal) && text.EndsWith("</i>", StringComparison.Ordinal) && text.Contains("</i>" + Environment.NewLine + "<i>") && Utilities.GetNumberOfLines(text) == 2 && Utilities.CountTagInText(text, "<i>") == 1)
                    {
                        _formattingTypes[i] = FormattingType.ItalicTwoLines;
                        text = HtmlUtil.RemoveOpenCloseTags(text, HtmlUtil.TagItalic);
                    }
                    else if (text.StartsWith("<i>", StringComparison.Ordinal) && text.EndsWith("</i>", StringComparison.Ordinal) && Utilities.CountTagInText(text, "<i>") == 1)
                    {
                        _formattingTypes[i] = FormattingType.Italic;
                        text = text.Substring(3, text.Length - 7);
                    }
                    else
                    {
                        _formattingTypes[i] = FormattingType.None;
                    }

                    text = string.Format("{1} {0} |", text, SplitterString);
                    if (Utilities.UrlEncode(sb + text).Length >= textMaxSize)
                    {
                        FillTranslatedText(DoTranslate(sb.ToString()), start, index - 1);
                        sb = new StringBuilder();
                        progressBar1.Refresh();
                        Application.DoEvents();
                        start = index;
                    }
                    sb.Append(text);
                    index++;
                    progressBar1.Value = index;
                    if (_breakTranslation)
                    {
                        break;
                    }
                }
                if (sb.Length > 0)
                {
                    FillTranslatedText(DoTranslate(sb.ToString()), start, index - 1);
                }
            }
            catch (WebException webException)
            {
                MessageBox.Show(webException.Source + ": " + webException.Message);
            }
            finally
            {
                labelPleaseWait.Visible = false;
                progressBar1.Visible    = false;
                Cursor.Current          = Cursors.Default;
                buttonTranslate.Text    = Configuration.Settings.Language.GoogleTranslate.Translate;
                buttonTranslate.Enabled = true;
                buttonOK.Enabled        = true;
                buttonCancel.Enabled    = true;

                Configuration.Settings.Tools.GoogleTranslateLastTargetLanguage = (comboBoxTo.SelectedItem as ComboBoxItem).Value;
            }
        }
Пример #20
0
        public override string ToText(Subtitle subtitle, string title)
        {
            var sb     = new StringBuilder();
            var lineSb = new StringBuilder();

            sb.AppendLine("*PART 1*");
            sb.AppendLine("00:00:00:00\\00:00:00:00");
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                string text        = p.Text;
                bool   positionTop = false;

                // If text starts with {\an8}, subtitle appears at the top
                if (text.StartsWith("{\\an8}", StringComparison.Ordinal))
                {
                    positionTop = true;
                    // Remove the tag {\an8}.
                    text = text.Remove(0, 6);
                }

                // Split lines (split a subtitle into its lines)
                var lines = text.SplitToLines();
                int count = 0;
                lineSb.Clear();
                string tempLine          = string.Empty;
                bool   nextLineInItalics = false;
                foreach (string line in lines)
                {
                    // Append line break in every line except the first one
                    if (count > 0)
                    {
                        lineSb.Append(Environment.NewLine);
                    }

                    tempLine = line;

                    // This line should be in italics (it was detected in previous line)
                    if (nextLineInItalics)
                    {
                        tempLine          = "<i>" + tempLine;
                        nextLineInItalics = false;
                    }

                    if (tempLine.StartsWith("<i>") && tempLine.EndsWith("</i>"))
                    {
                        // Whole line is in italics
                        // Remove <i> from the beginning
                        tempLine = tempLine.Remove(0, 3);
                        // Remove </i> from the end
                        tempLine = tempLine.Remove(tempLine.Length - 4, 4);
                        // Add new italics tag at the beginning
                        tempLine = "[" + tempLine;
                    }
                    else if (tempLine.StartsWith("<i>") && Utilities.CountTagInText(tempLine, "<i>") > Utilities.CountTagInText(tempLine, "</i>"))
                    {
                        // Line starts with <i> but italics are not closed. So the next line should be in italics
                        nextLineInItalics = true;
                    }
                    lineSb.Append(tempLine);
                    count++;

                    text = lineSb.ToString();
                    // Replace remaining italics tags
                    text = text.Replace("<i>", @"[");
                    text = text.Replace("</i>", @"]");
                    text = HtmlUtil.RemoveHtmlTags(text);
                }

                // Add top-position SoftNI marker "}" at the beginning of first line.
                if (positionTop)
                {
                    text = "}" + text;
                }

                sb.AppendLine(string.Format("{0}{1}{2}\\{3}", text, Environment.NewLine, p.StartTime.ToHHMMSSPeriodFF().Replace(".", ":"), p.EndTime.ToHHMMSSPeriodFF().Replace(".", ":")));
            }
            sb.AppendLine(@"*END*");
            sb.AppendLine(@"...........\...........");
            sb.AppendLine(@"*CODE*");
            sb.AppendLine(@"0000000000000000");
            sb.AppendLine(@"*CAST*");
            sb.AppendLine(@"*GENERATOR*");
            sb.AppendLine(@"*FONTS*");
            sb.AppendLine(@"*READ*");
            sb.AppendLine(@"0,300 15,000 130,000 100,000 25,000");
            sb.AppendLine(@"*TIMING*");
            sb.AppendLine(@"1 25 0");
            sb.AppendLine(@"*TIMED BACKUP NAME*");
            sb.AppendLine(@"C:\");
            sb.AppendLine(@"*FORMAT SAMPLE ÅåÉéÌìÕõÛûÿ*");
            sb.AppendLine(@"*READ ADVANCED*");
            sb.AppendLine(@"< > 1 1 0,300");
            sb.AppendLine(@"*MARKERS*");
            return(sb.ToString());
        }
Пример #21
0
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            //0002       00:01:48:22       00:01:52:17      - I need those samples, fast!
            //                                              - Yes, professor.
            Paragraph p = null;

            subtitle.Paragraphs.Clear();
            _errorCount = 0;
            foreach (string line in lines)
            {
                string s = line;
                if (RegexTimeCodes.IsMatch(s))
                {
                    var temp = s.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    if (temp.Length > 1)
                    {
                        string start = temp[1];
                        string end   = temp[2];

                        string[] startParts = start.Split(SplitCharColon, StringSplitOptions.RemoveEmptyEntries);
                        string[] endParts   = end.Split(SplitCharColon, StringSplitOptions.RemoveEmptyEntries);
                        if (startParts.Length == 4 && endParts.Length == 4)
                        {
                            try
                            {
                                string text = s.Remove(0, RegexTimeCodes.Match(s).Length - 1).Trim();
                                if (!text.Contains(Environment.NewLine))
                                {
                                    text = text.Replace("//", Environment.NewLine);
                                }

                                if (text.Contains("@Italic@"))
                                {
                                    bool italicOn = false;
                                    while (text.Contains("@Italic@"))
                                    {
                                        var    index     = text.IndexOf("@Italic@", StringComparison.Ordinal);
                                        string italicTag = "<i>";
                                        if (italicOn)
                                        {
                                            italicTag = "</i>";
                                        }

                                        text     = text.Remove(index, "@Italic@".Length).Insert(index, italicTag);
                                        italicOn = !italicOn;
                                    }
                                    text = HtmlUtil.FixInvalidItalicTags(text);
                                }
                                p = new Paragraph(DecodeTimeCodeFramesFourParts(startParts), DecodeTimeCodeFramesFourParts(endParts), text);
                                subtitle.Paragraphs.Add(p);
                            }
                            catch (Exception exception)
                            {
                                _errorCount++;
                                System.Diagnostics.Debug.WriteLine(exception.Message);
                            }
                        }
                    }
                }
                else if (line == "\t\t\t" || line == "\t\t\t\t" || line == "\t\t\t\t\t")
                {
                    // skip empty lines
                }
                else if (line.StartsWith("\t\t\t\t", StringComparison.Ordinal) && p != null)
                {
                    if (p.Text.Length < 200)
                    {
                        p.Text = (p.Text + Environment.NewLine + line.Trim()).Trim();
                    }
                }
                else if (!string.IsNullOrWhiteSpace(line) && p != null)
                {
                    _errorCount++;
                }
            }

            subtitle.Renumber();
        }
Пример #22
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
                "<tt xmlns=\"http://www.w3.org/2006/04/ttaf1\" xmlns:tts=\"http://www.w3.org/2006/04/ttaf1#styling\">" + Environment.NewLine +
                "   <head>" + Environment.NewLine +
                "       <styling>" + Environment.NewLine +
                "         <style id=\"defaultSpeaker\" tts:fontSize=\"12px\" tts:fontFamily=\"SansSerif\" tts:fontWeight=\"normal\" tts:fontStyle=\"normal\" tts:textDecoration=\"none\" tts:color=\"white\" tts:backgroundColor=\"black\" tts:textAlign=\"center\" />" + Environment.NewLine +
                "      </styling>" + Environment.NewLine +
                "   </head>" + Environment.NewLine +
                "   <body id=\"thebody\" style=\"defaultCaption\">" + Environment.NewLine +
                "       <div />" + Environment.NewLine +
                "   </body>" + Environment.NewLine +
                "</tt>";

            var xml = new XmlDocument();

            xml.LoadXml(xmlStructure);
            var nsmgr = new XmlNamespaceManager(xml.NameTable);

            nsmgr.AddNamespace("ttaf1", "http://www.w3.org/2006/04/ttaf1");
            nsmgr.AddNamespace("tts", "http://www.w3.org/2006/04/ttaf1#styling");

            XmlNode titleNode = xml.DocumentElement.SelectSingleNode("//ttaf1:head", nsmgr).FirstChild.FirstChild;

            titleNode.InnerText = title;

            XmlNode div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).SelectSingleNode("ttaf1:div", nsmgr);

            if (div == null)
            {
                div = xml.DocumentElement.SelectSingleNode("//ttaf1:body", nsmgr).FirstChild;
            }

            int no = 0;

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("p", "http://www.w3.org/2006/04/ttaf1");

                if (UseCDataForParagraphText)
                {
                    XmlCDataSection cData = xml.CreateCDataSection(p.Text);
                    paragraph.AppendChild(cData);
                }
                else
                {
                    string text  = HtmlUtil.RemoveHtmlTags(p.Text);
                    bool   first = true;
                    foreach (string line in text.SplitToLines())
                    {
                        if (!first)
                        {
                            XmlNode br = xml.CreateElement("br", "http://www.w3.org/2006/04/ttaf1");
                            paragraph.AppendChild(br);
                        }
                        XmlNode textNode = xml.CreateTextNode(line);
                        paragraph.AppendChild(textNode);
                        first = false;
                    }
                }

                XmlAttribute start = xml.CreateAttribute("begin");
                start.InnerText = ConvertToTimeString(p.StartTime);
                paragraph.Attributes.Append(start);

                XmlAttribute id = xml.CreateAttribute("id");
                id.InnerText = "p" + no;
                paragraph.Attributes.Append(id);

                XmlAttribute end = xml.CreateAttribute("end");
                end.InnerText = ConvertToTimeString(p.EndTime);
                paragraph.Attributes.Append(end);

                div.AppendChild(paragraph);
                no++;
            }

            return(ToUtf8XmlString(xml));
        }
Пример #23
0
        private NoticeSendResult SendMessage(NotifyMessage m)
        {
            //Check if we need to query stats
            RefreshQuotaIfNeeded();
            if (quota != null)
            {
                lock (locker)
                {
                    if (quota.Max24HourSend <= quota.SentLast24Hours)
                    {
                        //Quota exceeded, queue next refresh to +24 hours
                        lastRefresh = DateTime.UtcNow.AddHours(24);
                        log.WarnFormat("Quota limit reached. setting next check to: {0}", lastRefresh);
                        return(NoticeSendResult.SendingImpossible);
                    }
                }
            }

            var dest = new Destination
            {
                ToAddresses = m.To.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => MailAddressUtils.Create(a).Address).ToList(),
            };

            var subject = new Content(MimeHeaderUtils.EncodeMime(m.Subject))
            {
                Charset = Encoding.UTF8.WebName,
            };

            Body body;

            if (m.ContentType == Pattern.HTMLContentType)
            {
                body = new Body(new Content(HtmlUtil.GetText(m.Content))
                {
                    Charset = Encoding.UTF8.WebName
                });
                body.Html = new Content(GetHtmlView(m.Content))
                {
                    Charset = Encoding.UTF8.WebName
                };
            }
            else
            {
                body = new Body(new Content(m.Content)
                {
                    Charset = Encoding.UTF8.WebName
                });
            }

            var from    = MailAddressUtils.Create(m.From).ToEncodedString();
            var request = new SendEmailRequest {
                Source = from, Destination = dest, Message = new Message(subject, body)
            };

            if (!string.IsNullOrEmpty(m.ReplyTo))
            {
                request.ReplyToAddresses.Add(MailAddressUtils.Create(m.ReplyTo).Address);
            }

            ThrottleIfNeeded();

            var response = ses.SendEmail(request);

            lastSend = DateTime.UtcNow;

            return(response != null ? NoticeSendResult.OK : NoticeSendResult.TryOnceAgain);
        }
Пример #24
0
        public override string ToText(Subtitle subtitle, string title)
        {
            StringBuilder sb    = new StringBuilder();
            int           index = 0;

            sb.AppendLine("@ This file written with the Avid Caption plugin, version 1");
            sb.AppendLine();
            sb.AppendLine("<begin subtitles>");
            foreach (Paragraph p in subtitle.Paragraphs)
            {
                sb.AppendLine(string.Format("{0} {1}{2}{3}{2}", EncodeTimeCode(p.StartTime), EncodeTimeCode(p.EndTime), Environment.NewLine, HtmlUtil.RemoveHtmlTags(p.Text, true)));
                //00:50:34:22 00:50:39:13
                //Ich muss dafür sorgen,
                //dass die Epsteins weiterleben
                index++;
            }
            sb.AppendLine("<end subtitles>");
            return(sb.ToString());
        }
Пример #25
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
                "<USFSubtitles version=\"1.0\">" + Environment.NewLine +
                @"<metadata>
    <title>Universal Subtitle Format</title>
    <author>
      <name>SubtitleEdit</name>
      <email>[email protected]</email>
      <url>http://www.nikse.dk/</url>
    </author>" + Environment.NewLine +
                "   <language code=\"eng\">English</language>" + Environment.NewLine +
                @"  <date>[DATE]</date>
    <comment>This is a USF file</comment>
  </metadata>
  <styles>
    <!-- Here we redefine the default style -->" + Environment.NewLine +
                "    <style name=\"Default\">" + Environment.NewLine +
                "      <fontstyle face=\"Arial\" size=\"24\" color=\"#FFFFFF\" back-color=\"#AAAAAA\" />" +
                Environment.NewLine +
                "      <position alignment=\"BottomCenter\" vertical-margin=\"20%\" relative-to=\"Window\" />" +
                @"    </style>
  </styles>

  <subtitles>
  </subtitles>
</USFSubtitles>";

            xmlStructure = xmlStructure.Replace("[DATE]", DateTime.Now.ToString("yyyy-MM-dd"));

            var xml = new XmlDocument();

            xml.LoadXml(xmlStructure);
            xml.DocumentElement.SelectSingleNode("metadata/title").InnerText = title;
            var subtitlesNode = xml.DocumentElement.SelectSingleNode("subtitles");

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("subtitle");

                XmlAttribute start = xml.CreateAttribute("start");
                start.InnerText = p.StartTime.ToString().Replace(",", ".");
                paragraph.Attributes.Prepend(start);

                XmlAttribute stop = xml.CreateAttribute("stop");
                stop.InnerText = p.EndTime.ToString().Replace(",", ".");
                paragraph.Attributes.Append(stop);

                XmlNode text = xml.CreateElement("text");
                text.InnerText = HtmlUtil.RemoveHtmlTags(p.Text);
                paragraph.AppendChild(text);

                XmlAttribute style = xml.CreateAttribute("style");
                style.InnerText = "Default";
                text.Attributes.Append(style);

                subtitlesNode.AppendChild(paragraph);
            }

            return(ToUtf8XmlString(xml));
        }
Пример #26
0
        public static void Save(string fileName, Subtitle subtitle)
        {
            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                byte[] buffer = Encoding.ASCII.GetBytes(UltechId);
                fs.Write(buffer, 0, buffer.Length);

                buffer = new byte[] { 0, 0, 2, 0x1D, 0 }; // ?
                fs.Write(buffer, 0, buffer.Length);

                int numberOfLines = subtitle.Paragraphs.Count;
                fs.WriteByte((byte)(numberOfLines % 256));                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              // paragraphs - low byte
                fs.WriteByte((byte)(numberOfLines / 256));                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              // paragraphs - high byte

                buffer = new byte[] { 0, 0, 0, 0, 0x1, 0, 0xF, 0x15, 0, 0, 0, 0, 0, 0, 0, 0x1, 0, 0xE, 0x15, 0, 0, 0, 0, 0, 0, 0, 0x1, 0, 0xD, 0x15, 0, 0, 0, 0, 0, 0, 0, 0x1, 0, 0xC, 0x15, 0, 0, 0, 0, 0, 0, 0, 0x1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // ?
                fs.Write(buffer, 0, buffer.Length);

                buffer = Encoding.ASCII.GetBytes("Subtitle Edit");
                fs.Write(buffer, 0, buffer.Length);

                while (fs.Length < 512)
                {
                    fs.WriteByte(0);
                }

                var footer = new byte[] { 0xF1, 0x0B, 0x00, 0x00, 0x00, 0x1B, 0x18, 0x14, 0x20, 0x14, 0x2E, 0x14, 0x2F, 0x00 }; // footer

                // paragraphs
                foreach (Paragraph p in subtitle.Paragraphs)
                {
                    // convert line breaks
                    var    sb               = new StringBuilder();
                    var    line             = new StringBuilder();
                    int    skipCount        = 0;
                    int    numberOfNewLines = Utilities.GetNumberOfLines(p.Text);
                    bool   italic           = p.Text.StartsWith("<i>") && p.Text.EndsWith("</i>");
                    string text             = HtmlUtil.RemoveHtmlTags(p.Text, true);
                    if (italic)
                    {
                        sb.Append('\u0011');
                        sb.Append('\u002E');
                    }
                    int y = 0x74 - (numberOfNewLines * 0x20);
                    for (int j = 0; j < text.Length; j++)
                    {
                        if (text.Substring(j).StartsWith(Environment.NewLine, StringComparison.Ordinal))
                        {
                            y += 0x20;
                            if (line.Length > 0)
                            {
                                sb.Append(line);
                            }
                            line.Clear();
                            skipCount = Environment.NewLine.Length - 1;
                            sb.Append('\u0014');
                            sb.Append(Convert.ToChar((byte)(y)));

                            //center
                            sb.Append('\u0017');
                            sb.Append('\u0021');

                            if (italic)
                            {
                                sb.Append('\u0011');
                                sb.Append('\u002E');
                            }
                        }
                        else if (skipCount == 0)
                        {
                            line.Append(text[j]);
                        }
                        else
                        {
                            skipCount--;
                        }
                    }
                    if (line.Length > 0)
                    {
                        sb.Append(line);
                    }
                    text = sb.ToString();

                    // codes?
                    buffer = new byte[] {
                        0x14,
                        0x20,
                        0x14,
                        0x2E,
                        0x14,
                        (byte)(0x74 - (numberOfNewLines * 0x20)),

                        0x17, 0x21, // 0x1721=center, 0x1722=right ?
                    };

                    //if (text.StartsWith("{\\a6}"))
                    //{
                    //    text = p.Text.Remove(0, 5);
                    //    buffer[7] = 1; // align top
                    //}
                    //else if (text.StartsWith("{\\a1}"))
                    //{
                    //    text = p.Text.Remove(0, 5);
                    //    buffer[8] = 0x0A; // align left
                    //}
                    //else if (text.StartsWith("{\\a3}"))
                    //{
                    //    text = p.Text.Remove(0, 5);
                    //    buffer[8] = 0x1E; // align right
                    //}
                    //else if (text.StartsWith("{\\a5}"))
                    //{
                    //    text = p.Text.Remove(0, 5);
                    //    buffer[7] = 1; // align top
                    //    buffer[8] = 05; // align left
                    //}
                    //else if (text.StartsWith("{\\a7}"))
                    //{
                    //    text = p.Text.Remove(0, 5);
                    //    buffer[7] = 1; // align top
                    //    buffer[8] = 0xc; // align right
                    //}

                    fs.WriteByte(0xF1); //ID of start record

                    // length
                    int length = text.Length + 15;
                    fs.WriteByte((byte)(length));
                    fs.WriteByte(0);

                    // start time
                    WriteTime(fs, p.StartTime);
                    fs.Write(buffer, 0, buffer.Length);

                    // text
                    buffer = Encoding.ASCII.GetBytes(text);
                    fs.Write(buffer, 0, buffer.Length); // Text starter på index 19 (0 baseret)
                    fs.WriteByte(0x14);
                    fs.WriteByte(0x2F);
                    fs.WriteByte(0);

                    // end time
                    fs.WriteByte(0xF1); // id of start record
                    fs.WriteByte(7);    // length of end time
                    fs.WriteByte(0);
                    WriteTime(fs, p.EndTime);
                    fs.WriteByte(0x14);
                    fs.WriteByte(0x2c);
                    fs.WriteByte(0);
                }

                buffer = footer;
                fs.Write(buffer, 0, buffer.Length);
            }
        }
Пример #27
0
        private SearchResultItem[] ToSearchResultItem(IEnumerable <object[]> rows)
        {
            var result = new List <SearchResultItem>();

            foreach (var row in rows)
            {
                var    containerType = ((EntityType)Convert.ToInt32(row[0]));
                var    id            = row[1];
                string imageRef;
                String url;

                switch (containerType)
                {
                case EntityType.Contact:
                {
                    var contact = Global.DaoFactory.GetContactDao().GetByID(Convert.ToInt32(id));

                    if (!CRMSecurity.CanAccessTo(contact))
                    {
                        continue;
                    }

                    url = String.Format("default.aspx?id={0}", id);

                    if (contact is Company)
                    {
                        imageRef = WebImageSupplier.GetAbsoluteWebPath("companies_widget.png",
                                                                       ProductEntryPoint.ID);
                    }
                    else
                    {
                        imageRef = WebImageSupplier.GetAbsoluteWebPath("people_widget.png",
                                                                       ProductEntryPoint.ID);
                    }

                    break;
                }

                case EntityType.Opportunity:
                {
                    var deal = Global.DaoFactory.GetDealDao().GetByID(Convert.ToInt32(id));

                    if (!CRMSecurity.CanAccessTo(deal))
                    {
                        continue;
                    }

                    url = String.Format("deals.aspx?id={0}", id);

                    imageRef = WebImageSupplier.GetAbsoluteWebPath("deal_widget.png",
                                                                   ProductEntryPoint.ID);
                    break;
                }

                case EntityType.Case:
                {
                    var cases = Global.DaoFactory.GetCasesDao().GetByID(Convert.ToInt32(id));

                    if (!CRMSecurity.CanAccessTo(cases))
                    {
                        continue;
                    }

                    url = String.Format("cases.aspx?id={0}", id);

                    imageRef = WebImageSupplier.GetAbsoluteWebPath("cases_widget.png",
                                                                   ProductEntryPoint.ID);

                    break;
                }

                case EntityType.Task:
                {
                    var task = Global.DaoFactory.GetTaskDao().GetByID(Convert.ToInt32(id));

                    if (!CRMSecurity.CanAccessTo(task))
                    {
                        continue;
                    }

                    url = String.Format("tasks.aspx?id={0}", id);

                    imageRef = WebImageSupplier.GetAbsoluteWebPath("tasks_widget.png",
                                                                   ProductEntryPoint.ID);
                    break;
                }

                case EntityType.Invoice:
                {
                    var invoice = Global.DaoFactory.GetInvoiceDao().GetByID(Convert.ToInt32(id));

                    if (!CRMSecurity.CanAccessTo(invoice))
                    {
                        continue;
                    }

                    url = String.Format("invoices.aspx?id={0}", id);

                    imageRef = WebImageSupplier.GetAbsoluteWebPath("invoices_widget.png",
                                                                   ProductEntryPoint.ID);

                    break;
                }

                default:
                    throw new ArgumentException();
                }

                result.Add(new SearchResultItem
                {
                    Name        = Convert.ToString(row[2]),
                    Description = HtmlUtil.GetText(Convert.ToString(row[3]), 120),
                    URL         = String.Concat(PathProvider.BaseAbsolutePath, url),
                    Date        = TenantUtil.DateTimeFromUtc(DateTime.Parse(Convert.ToString(row[7]))),
                    Additional  = new Dictionary <String, Object>
                    {
                        { "imageRef", imageRef },
                        { "relativeInfo", GetPath(
                              Convert.ToInt32(row[4]),
                              Convert.ToInt32(row[5]),
                              (EntityType)Convert.ToInt32(row[6])) },
                        { "typeInfo", containerType.ToLocalizedString() }
                    }
                });
            }

            return(result.ToArray());
        }
Пример #28
0
        public void Fix(Subtitle subtitle, IFixCallbacks callbacks)
        {
            var    language  = Configuration.Settings.Language.FixCommonErrors;
            string fixAction = language.StartWithUppercaseLetterAfterColon;
            int    noOfFixes = 0;

            for (int i = 0; i < subtitle.Paragraphs.Count; i++)
            {
                var       p         = new Paragraph(subtitle.Paragraphs[i]);
                Paragraph last      = subtitle.GetParagraphOrDefault(i - 1);
                string    oldText   = p.Text;
                int       skipCount = 0;

                if (last != null)
                {
                    string lastText = HtmlUtil.RemoveHtmlTags(last.Text);
                    if (lastText.EndsWith(':') || lastText.EndsWith(';'))
                    {
                        var st = new StrippableText(p.Text);
                        if (st.StrippedText.Length > 0 && st.StrippedText[0] != char.ToUpper(st.StrippedText[0]))
                        {
                            p.Text = st.Pre + char.ToUpper(st.StrippedText[0]) + st.StrippedText.Substring(1) + st.Post;
                        }
                    }
                }

                if (oldText.Contains(ExpectedChars))
                {
                    bool lastWasColon = false;
                    for (int j = 0; j < p.Text.Length; j++)
                    {
                        var s = p.Text[j];
                        if (s == ':' || s == ';')
                        {
                            lastWasColon = true;
                        }
                        else if (lastWasColon)
                        {
                            // skip whitespace index
                            if (j + 2 < p.Text.Length && p.Text[j] == ' ')
                            {
                                s = p.Text[++j];
                            }

                            var startFromJ = p.Text.Substring(j);
                            if (startFromJ.Length > 3 && startFromJ[0] == '<' && startFromJ[2] == '>' && (startFromJ[1] == 'i' || startFromJ[1] == 'b' || startFromJ[1] == 'u'))
                            {
                                skipCount = 2;
                            }
                            else if (startFromJ.StartsWith("<font ", StringComparison.OrdinalIgnoreCase) && p.Text.Substring(j).Contains('>'))
                            {
                                skipCount = (j + startFromJ.IndexOf('>', 6)) - j;
                            }
                            else if (Helper.IsTurkishLittleI(s, callbacks.Encoding, callbacks.Language))
                            {
                                p.Text       = p.Text.Remove(j, 1).Insert(j, Helper.GetTurkishUppercaseLetter(s, callbacks.Encoding).ToString(CultureInfo.InvariantCulture));
                                lastWasColon = false;
                            }
                            else if (char.IsLower(s))
                            {
                                // iPhone
                                bool change = true;
                                if (s == 'i' && p.Text.Length > j + 1)
                                {
                                    if (p.Text[j + 1] == char.ToUpper(p.Text[j + 1]))
                                    {
                                        change = false;
                                    }
                                }
                                if (change)
                                {
                                    p.Text = p.Text.Remove(j, 1).Insert(j, char.ToUpper(s).ToString(CultureInfo.InvariantCulture));
                                }

                                lastWasColon = false;
                            }
                            else if (!(" " + Environment.NewLine).Contains(s))
                            {
                                lastWasColon = false;
                            }

                            // move the: 'j' pointer and reset skipCount to 0
                            if (skipCount > 0)
                            {
                                j        += skipCount;
                                skipCount = 0;
                            }
                        }
                    }
                }

                if (oldText != p.Text && callbacks.AllowFix(p, fixAction))
                {
                    noOfFixes++;
                    subtitle.Paragraphs[i].Text = p.Text;
                    callbacks.AddFixToListView(p, fixAction, oldText, p.Text);
                }
            }
            callbacks.UpdateFixStatus(noOfFixes, language.StartWithUppercaseLetterAfterColon, noOfFixes.ToString(CultureInfo.InvariantCulture));
        }
Пример #29
0
        public override void Execute()
        {
            DataSet   dataSet     = (DataSet)Model;
            DataRow   row         = dataSet.GetRow("CS_DOCUMENT");
            string    title       = row.GetString("Title");
            DataTable attachTable = dataSet.Tables["CS_DOC_ATTACHMENT"];
            string    context     = string.Empty;

            if (!string.IsNullOrEmpty(row.GetString("SourceId")))
            {
                context = "Tools";
            }

            WriteLiteral("\r\n<!DOCTYPE html>\r\n<html>\r\n<head>\r\n    <title>");

            Write(title);

            WriteLiteral("</title>\r\n    <meta");

            WriteLiteral(" http-equiv=\"X-UA-Compatible\"");

            WriteLiteral(" content=\"IE=edge\"");

            WriteLiteral(" />\r\n    <meta");

            WriteLiteral(" http-equiv=\"Content-Type\"");

            WriteLiteral(" content=\"text/html; charset=utf-8\"");

            WriteLiteral(" />\r\n    <meta");

            WriteLiteral(" name=\"viewport\"");

            WriteLiteral(" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable" +
                         "=0;\"");

            WriteLiteral(" />\r\n    <link");

            WriteLiteral(" rel=\"stylesheet\"");

            WriteLiteral(" type=\"text/css\"");

            WriteAttribute("href", Tuple.Create(" href=\"", 812), Tuple.Create("\"", 885)
                           , Tuple.Create(Tuple.Create("", 819), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/bootstrap/css/bootstrap.min.css".AppVirutalPath()
                                                                                                            , 819), false)
                           );

            WriteLiteral(" />\r\n    <link");

            WriteLiteral(" rel=\"stylesheet\"");

            WriteLiteral(" type=\"text/css\"");

            WriteAttribute("href", Tuple.Create(" href=\"", 933), Tuple.Create("\"", 986)
                           , Tuple.Create(Tuple.Create("", 940), Tuple.Create <System.Object, System.Int32>("usercss/document.css?v=2".AppVirutalPath()
                                                                                                            , 940), false)
                           );

            WriteLiteral(" />\r\n</head>\r\n<body");

            WriteLiteral(" data-webPath=\"");

            Write(HtmlUtil.AppVirtualPath);

            WriteLiteral("\"");

            WriteLiteral(">\r\n    <div");

            WriteLiteral(" class=\"container\"");

            WriteLiteral(" name=\"_top\"");

            WriteLiteral(" id=\"_top\"");

            WriteLiteral(">\r\n        <div");

            WriteLiteral(" id=\"metaData\"");

            WriteLiteral(" class=\"Hide\"");

            WriteLiteral(" data-toolbar=\"true\"");

            WriteLiteral(" data-option=\"true\"");

            WriteLiteral(" data-title=\"");

            Write(StringUtil.EscapeHtmlAttribute(title));

            WriteLiteral("\"");

            WriteLiteral(" data-desc=\"");

            Write(StringUtil.EscapeHtmlAttribute(row.GetString("PrevContent")));

            WriteLiteral("\"");

            WriteLiteral(" data-link=\"");

            Write("~/doc.vp?" + row.GetString("DocId"));

            WriteLiteral("\"");

            WriteLiteral(" data-img=\"~/pic/sys/shui.jpg\"");

            WriteLiteral("></div>\r\n");


            if (!string.IsNullOrEmpty(row.GetString("OrginOrg")))
            {
                WriteLiteral("            <h1>");

                Write(row.GetString("OrginOrg"));

                WriteLiteral("<br />");

                Write(title);

                WriteLiteral("</h1>\r\n");
            }
            else
            {
                WriteLiteral("            <h1>");

                Write(title);

                WriteLiteral("</h1>\r\n");
            }

            WriteLiteral("        </h1>\r\n");


            if (!string.IsNullOrEmpty(row.GetString("Number")))
            {
                WriteLiteral("            <p");

                WriteLiteral(" class=\"text-center\"");

                WriteLiteral(">");

                Write(row.GetString("Number"));

                WriteLiteral("</p>\r\n");
            }

            WriteLiteral("        <div>\r\n");

            WriteLiteral("            ");

            Write(row.GetString("Content"));

            WriteLiteral("\r\n        </div>\r\n");


            if (attachTable != null && attachTable.Rows.Count > 0)
            {
                WriteLiteral("            <ul");

                WriteLiteral(" class=\"list-group\"");

                WriteLiteral(">\r\n");


                foreach (DataRow attachRow in attachTable.Rows)
                {
                    WriteLiteral("                    <li");

                    WriteLiteral(" class=\"list-group-item\"");

                    WriteLiteral(">\r\n                        <a");

                    WriteLiteral(" target=\"_blank\"");

                    WriteAttribute("href", Tuple.Create(" href=\"", 2131), Tuple.Create("\"", 2215)
                                   , Tuple.Create(Tuple.Create("", 2138), Tuple.Create <System.Object, System.Int32>(HtmlUtil.GetDownloadUrl(attachRow.GetString("FileId"), true, false, context)
                                                                                                                     , 2138), false)
                                   );

                    WriteLiteral(">");

                    Write(attachRow.GetString("FileName"));

                    WriteLiteral("</a>\r\n                    </li>\r\n");
                }

                WriteLiteral("            </ul>\r\n");
            }

            WriteLiteral("        <div");

            WriteLiteral(" class=\"text-right mt10 mb10 f16\"");

            WriteLiteral(">\r\n            <a");

            WriteLiteral(" href=\"#_top\"");

            WriteLiteral(">返回顶部</a>\r\n        </div>\r\n    </div>\r\n    <script");

            WriteLiteral(" type=\"text/javascript\"");

            WriteAttribute("src", Tuple.Create(" src=\"", 2479), Tuple.Create("\"", 2543)
                           , Tuple.Create(Tuple.Create("", 2485), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/lib/jquery-1.7.2.min.js".AppVirutalPath()
                                                                                                             , 2485), false)
                           );

            WriteLiteral("></script>\r\n    <script");

            WriteLiteral(" type=\"text/javascript\"");

            WriteAttribute("src", Tuple.Create(" src=\"", 2590), Tuple.Create("\"", 2660)
                           , Tuple.Create(Tuple.Create("", 2596), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/bootstrap/js/bootstrap.min.js".AppVirutalPath()
                                                                                                             , 2596), false)
                           );

            WriteLiteral("></script>\r\n    <script");

            WriteLiteral(" type=\"text/javascript\"");

            WriteAttribute("src", Tuple.Create(" src=\"", 2707), Tuple.Create("\"", 2766)
                           , Tuple.Create(Tuple.Create("", 2713), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/toolkit/toolkit.js".AppVirutalPath()
                                                                                                             , 2713), false)
                           );

            WriteLiteral("></script>\r\n    <script");

            WriteLiteral(" type=\"text/javascript\"");

            WriteAttribute("src", Tuple.Create(" src=\"", 2813), Tuple.Create("\"", 2883)
                           , Tuple.Create(Tuple.Create("", 2819), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/toolkit/coreT/toolkit.page.js".AppVirutalPath()
                                                                                                             , 2819), false)
                           );

            WriteLiteral("></script>\r\n    <script");

            WriteLiteral(" type=\"text/javascript\"");

            WriteAttribute("src", Tuple.Create(" src=\"", 2930), Tuple.Create("\"", 3006)
                           , Tuple.Create(Tuple.Create("", 2936), Tuple.Create <System.Object, System.Int32>("toolkitjs/v5/toolkit/coreT/toolkit.weixin.js?v=4".AppVirutalPath()
                                                                                                             , 2936), false)
                           );

            WriteLiteral("></script>\r\n</body>\r\n</html>\r\n");
        }
Пример #30
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string       paragraphWriteFormat = "#{0:00000}\t{1}\t{2}\t{3}\t#F\tCC00000D0\t#C " + Environment.NewLine + "{4}";
            const string timeFormat           = "{0:00}:{1:00}:{2:00}.{3:00}";
            var          sb     = new StringBuilder();
            string       header = @"FILE_INFO_BEGIN
VIDEOFILE:
ORIG_TITLE: [TITLE]
PGM_TITLE:
EP_TITLE: 03
PROD:
TRANSL: SDI Media
CLIENT: FIC-HD
COMMENT:
TAPE#: TN10179565
CRE_DATE:
REP_DATE:
TR_DATE:
PROG_LEN:
SOM: 09:59:35:00
TRA_FONT:
LANG_CO: English
LIST_FONT: Arial Unicode MS 450
TV_SYS: 625/50
TV_FPS: EBU 625/50
LINE_LEN: 43.2
SW_VER: 2.25
FILE_INFO_END";

            if (subtitle.Header != null && subtitle.Header.Contains("FILE_INFO_BEGIN"))
            {
                header = subtitle.Header;
            }
            sb.AppendLine(header);
            int number = 1;

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                var    startFrame = MillisecondsToFramesMaxFrameRate(p.StartTime.Milliseconds);
                string startTime  = string.Format(timeFormat, p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, startFrame);

                var    endFrame = MillisecondsToFramesMaxFrameRate(p.EndTime.Milliseconds);
                string endTime  = string.Format(timeFormat, p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, endFrame);

                // to avoid rounding errors in duration
                var durationCalc = new Paragraph(
                    new TimeCode(p.StartTime.Hours, p.StartTime.Minutes, p.StartTime.Seconds, FramesToMillisecondsMax999(startFrame)),
                    new TimeCode(p.EndTime.Hours, p.EndTime.Minutes, p.EndTime.Seconds, FramesToMillisecondsMax999(endFrame)),
                    string.Empty);
                string duration = string.Format(timeFormat, durationCalc.Duration.Hours, durationCalc.Duration.Minutes, durationCalc.Duration.Seconds, MillisecondsToFramesMaxFrameRate(durationCalc.Duration.Milliseconds));

                sb.AppendLine(string.Format(paragraphWriteFormat, number, startTime, endTime, duration, HtmlUtil.RemoveHtmlTags(p.Text)));
                number++;
            }
            return(sb.ToString().Trim());
        }
Пример #31
0
        private void GeneratePreview()
        {
            Cursor        = Cursors.WaitCursor;
            FixedSubtitle = new Subtitle(_subtitle);
            DeleteIndices = new List <int>();
            FixCount      = 0;
            listViewFixes.BeginUpdate();
            listViewFixes.Items.Clear();
            var replaceExpressions = new HashSet <ReplaceExpression>();

            foreach (var group in Configuration.Settings.MultipleSearchAndReplaceGroups)
            {
                if (group.Enabled)
                {
                    foreach (var rule in group.Rules)
                    {
                        if (rule.Enabled)
                        {
                            string findWhat = rule.FindWhat;
                            if (!string.IsNullOrEmpty(findWhat)) // allow space or spaces
                            {
                                string replaceWith = RegexUtils.FixNewLine(rule.ReplaceWith);
                                findWhat = RegexUtils.FixNewLine(findWhat);
                                string searchType = rule.SearchType;
                                var    mpi        = new ReplaceExpression(findWhat, replaceWith, searchType);
                                replaceExpressions.Add(mpi);
                                if (mpi.SearchType == ReplaceExpression.SearchRegEx && !_compiledRegExList.ContainsKey(findWhat))
                                {
                                    _compiledRegExList.Add(findWhat, new Regex(findWhat, RegexOptions.Compiled | RegexOptions.Multiline));
                                }
                            }
                        }
                    }
                }
            }

            var fixes = new List <ListViewItem>();

            foreach (Paragraph p in _subtitle.Paragraphs)
            {
                bool   hit     = false;
                string newText = p.Text;
                foreach (ReplaceExpression item in replaceExpressions)
                {
                    if (item.SearchType == ReplaceExpression.SearchCaseSensitive)
                    {
                        if (newText.Contains(item.FindWhat))
                        {
                            hit     = true;
                            newText = newText.Replace(item.FindWhat, item.ReplaceWith);
                        }
                    }
                    else if (item.SearchType == ReplaceExpression.SearchRegEx)
                    {
                        Regex r = _compiledRegExList[item.FindWhat];
                        if (r.IsMatch(newText))
                        {
                            hit     = true;
                            newText = RegexUtils.ReplaceNewLineSafe(r, newText, item.ReplaceWith);
                        }
                    }
                    else
                    {
                        int index = newText.IndexOf(item.FindWhat, StringComparison.OrdinalIgnoreCase);
                        if (index >= 0)
                        {
                            hit = true;
                            do
                            {
                                newText = newText.Remove(index, item.FindWhat.Length).Insert(index, item.ReplaceWith);
                                index   = newText.IndexOf(item.FindWhat, index + item.ReplaceWith.Length, StringComparison.OrdinalIgnoreCase);
                            }while (index >= 0);
                        }
                    }
                }
                if (hit && newText != p.Text)
                {
                    FixCount++;
                    fixes.Add(MakePreviewListItem(p, newText));
                    int index = _subtitle.GetIndex(p);
                    FixedSubtitle.Paragraphs[index].Text = newText;
                    if (!string.IsNullOrWhiteSpace(p.Text) && (string.IsNullOrWhiteSpace(newText) || string.IsNullOrWhiteSpace(HtmlUtil.RemoveHtmlTags(newText, true))))
                    {
                        DeleteIndices.Add(index);
                    }
                }
            }
            listViewFixes.Items.AddRange(fixes.ToArray());
            listViewFixes.EndUpdate();
            groupBoxLinesFound.Text = string.Format(Configuration.Settings.Language.MultipleReplace.LinesFoundX, FixCount);
            Cursor = Cursors.Default;
            DeleteIndices.Reverse();
        }
Пример #32
0
        public List<string> GettingAllUrls(string PageSource, string MustMatchString)
        {
            List<string> suburllist = new List<string>();

            try
            {
                HtmlUtil htmlUtil = new HtmlUtil();
                PageSource = htmlUtil.EntityDecode(PageSource);
                StringArray datagoogle = htmlUtil.GetHyperlinkedUrls(PageSource);

                for (int i = 0; i < datagoogle.Length; i++)
                {
                    try
                    {
                        string hreflink = datagoogle.GetString(i);

                        if (hreflink.Contains(MustMatchString) && hreflink.Contains("&authType="))
                        {
                            if (hreflink.Contains("http://www.linkedin.com"))
                            {
                                suburllist.Add(hreflink);
                                Log("[ " + DateTime.Now + " ] => [ URL >>> " + hreflink + " ]");
                            }
                            else
                            {
                                suburllist.Add("http://www.linkedin.com" + hreflink);
                                Log("[ " + DateTime.Now + " ] => [ URL >>> http://www.linkedin.com" + hreflink + " ]");
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch
            {
            }
            suburllist = suburllist.Distinct().ToList();
            return suburllist.Distinct().ToList();
        }
Пример #33
0
 private static void TestXss(string xss)
 {
     Assert.IsTrue(HtmlUtil.ContainsScript(xss));
     Assert.IsTrue(HtmlUtil.ContainsHtml(xss));
 }
Пример #34
0
        public void TestStripHtmlTags()
        {
            // Nothing to strip.

            Assert.IsNull(HtmlUtil.StripHtmlTags(null));
            Assert.AreEqual("", HtmlUtil.StripHtmlTags(""));
            Assert.AreEqual("no HTML", HtmlUtil.StripHtmlTags("no HTML"));

            // Strip to nothing.

            Assert.AreEqual("", HtmlUtil.StripHtmlTags("<html>"));
            Assert.AreEqual("", HtmlUtil.StripHtmlTags("</html>"));
            Assert.AreEqual("", HtmlUtil.StripHtmlTags("<html></html>"));
            Assert.AreEqual("", HtmlUtil.StripHtmlTags("<br />"));

            // Strip HTML tags and leave some text.

            Assert.AreEqual("plain text", HtmlUtil.StripHtmlTags("plain<br />text"));
            Assert.AreEqual("plain text", HtmlUtil.StripHtmlTags("<html>plain text</html>"));
            Assert.AreEqual("plain text", HtmlUtil.StripHtmlTags("plain<html> text</html>"));
            Assert.AreEqual("plain text", HtmlUtil.StripHtmlTags("plain <html>text</html>"));
            Assert.AreEqual("plain text", HtmlUtil.StripHtmlTags("plain<html>text</html>"));
            Assert.AreEqual("plain text and more", HtmlUtil.StripHtmlTags("plain<html>text</html> and<ul>more"));
            Assert.AreEqual("office tags with ns", HtmlUtil.StripHtmlTags("office<o:p>tags</o:p> with<st1:state w:st=\"on\">ns"));

            // Strip some HTML tags, ignore others.

            Assert.AreEqual("plain text and<ul>more", HtmlUtil.StripHtmlTags(
                                "plain<html>text</html> and<ul>more", "ul"));
            Assert.AreEqual("plain<br />text", HtmlUtil.StripHtmlTags("plain<br />text", "BR"));
            Assert.AreEqual("plain</BR>", HtmlUtil.StripHtmlTags("plain</BR>", "BR"));
            Assert.AreEqual("plain<br />text<br>and</br> more", HtmlUtil.StripHtmlTags(
                                "<html>plain<br />text<br>and</br></html>more", "BR"));

            // Unclosed tags

            Assert.AreEqual("Test one", HtmlUtil.StripHtmlTags("Test one<<ul>"));
            Assert.AreEqual("Test one <ul>", HtmlUtil.StripHtmlTags("Test one<<ul>", "ul"));
            Assert.AreEqual("Test one", HtmlUtil.StripHtmlTags("Test one<</ul>"));
            Assert.AreEqual("Test one", HtmlUtil.StripHtmlTags("Test one<li</ul>"));
            Assert.AreEqual("One > Two", HtmlUtil.StripHtmlTags("<li>One<li>> Two</ul>"));
            Assert.AreEqual("One /> Two", HtmlUtil.StripHtmlTags("<li>One<li>/> Two</ul>"));

            // Various ways to close the tag.

            Assert.AreEqual("something", HtmlUtil.StripHtmlTags("<tag> something"));
            Assert.AreEqual("something", HtmlUtil.StripHtmlTags("something <tag>"));
            Assert.AreEqual("", HtmlUtil.StripHtmlTags("<br/>"));
            Assert.AreEqual("", HtmlUtil.StripHtmlTags("<font size=5/>"));
            Assert.AreEqual("", HtmlUtil.StripHtmlTags("<font /"));
            Assert.AreEqual("", HtmlUtil.StripHtmlTags("<font /something"));
            Assert.AreEqual("", HtmlUtil.StripHtmlTags("<font / something"));
            Assert.AreEqual("finally closed", HtmlUtil.StripHtmlTags("<font / something> finally closed"));
            Assert.AreEqual("<", HtmlUtil.StripHtmlTags("<test <"));

            // Invalid characters in the tag name - don't treat them as tags.

            Assert.AreEqual("<not/atag>", HtmlUtil.StripHtmlTags("<not/atag>"));
            Assert.AreEqual("<this! is> not a tag but  is", HtmlUtil.StripHtmlTags("<this! is> not a tag but <this> is"));
            Assert.AreEqual("<http://some.url/which/should/stay.html> then a real  and <br><br /><br/>",
                            HtmlUtil.StripHtmlTags("<http://some.url/which/should/stay.html> then a real <tag>"
                                                   + " and <br><br /><br/>", "br"));
            Assert.AreEqual("< not", HtmlUtil.StripHtmlTags("< not <tag"));
        }
Пример #35
0
        public void Fix(Subtitle subtitle, IFixCallbacks callbacks)
        {
            var language = Configuration.Settings.Language.FixCommonErrors;

            string fixAction0 = language.RemovedEmptyLine;
            string fixAction1 = language.RemovedEmptyLineAtTop;
            string fixAction2 = language.RemovedEmptyLineAtBottom;
            string fixAction3 = language.RemovedEmptyLineInMiddle;

            if (subtitle.Paragraphs.Count == 0)
            {
                return;
            }

            int emptyLinesRemoved = 0;

            for (int i = subtitle.Paragraphs.Count - 1; i >= 0; i--)
            {
                Paragraph p = subtitle.Paragraphs[i];
                if (!string.IsNullOrEmpty(p.Text))
                {
                    string text    = p.Text.Trim(' ');
                    var    oldText = text;
                    var    pre     = string.Empty;
                    var    post    = string.Empty;

                    // Ssa Tags
                    if (text.StartsWith("{\\", StringComparison.Ordinal))
                    {
                        var endIdx = text.IndexOf('}', 2);
                        if (endIdx > 2)
                        {
                            pre  = text.Substring(0, endIdx + 1);
                            text = text.Remove(0, endIdx + 1);
                        }
                    }

                    while (text.LineStartsWithHtmlTag(true, true))
                    {
                        // Three length tag
                        if (text[2] == '>')
                        {
                            pre += text.Substring(0, 3);
                            text = text.Remove(0, 3);
                        }
                        else // <font ...>
                        {
                            var closeIdx = text.IndexOf('>');
                            if (closeIdx <= 2)
                            {
                                break;
                            }

                            pre += text.Substring(0, closeIdx + 1);
                            text = text.Remove(0, closeIdx + 1);
                        }
                    }
                    while (text.LineEndsWithHtmlTag(true, true))
                    {
                        var len = text.Length;

                        // Three length tag
                        if (text[len - 4] == '<')
                        {
                            post = text.Substring(text.Length - 4) + post;
                            text = text.Remove(text.Length - 4);
                        }
                        else // </font>
                        {
                            post = text.Substring(text.Length - 7) + post;
                            text = text.Remove(text.Length - 7);
                        }
                    }

                    if (callbacks.AllowFix(p, fixAction1) && text.StartsWith(Environment.NewLine, StringComparison.Ordinal))
                    {
                        if (pre.Length > 0)
                        {
                            text = pre + text.TrimStart(Utilities.NewLineChars);
                        }
                        else
                        {
                            text = text.TrimStart(Utilities.NewLineChars);
                        }
                        p.Text = text;
                        emptyLinesRemoved++;
                        callbacks.AddFixToListView(p, fixAction1, oldText, p.Text);
                    }
                    else
                    {
                        text = pre + text;
                    }

                    if (callbacks.AllowFix(p, fixAction2) && text.EndsWith(Environment.NewLine, StringComparison.Ordinal))
                    {
                        if (post.Length > 0)
                        {
                            text = text.TrimEnd(Utilities.NewLineChars) + post;
                        }
                        else
                        {
                            text = text.TrimEnd(Utilities.NewLineChars);
                        }
                        p.Text = text;
                        emptyLinesRemoved++;
                        callbacks.AddFixToListView(p, fixAction2, oldText, p.Text);
                    }

                    if (Configuration.Settings.Tools.RemoveEmptyLinesBetweenText &&
                        callbacks.AllowFix(p, fixAction3) && text.Contains(Environment.NewLine + Environment.NewLine))
                    {
                        int beforeLength = text.Length;
                        while (text.Contains(Environment.NewLine + Environment.NewLine))
                        {
                            text = text.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine);
                        }
                        p.Text             = text;
                        emptyLinesRemoved += (beforeLength - text.Length) / Environment.NewLine.Length;
                        callbacks.AddFixToListView(p, fixAction3, oldText, p.Text);
                    }
                }
            }

            // this must be the very last action done, or line numbers will be messed up!!!
            for (int i = subtitle.Paragraphs.Count - 1; i >= 0; i--)
            {
                Paragraph p    = subtitle.Paragraphs[i];
                var       text = HtmlUtil.RemoveHtmlTags(p.Text, true).Trim();
                if (callbacks.AllowFix(p, fixAction0) && string.IsNullOrEmpty(text.RemoveControlCharacters()))
                {
                    subtitle.Paragraphs.RemoveAt(i);
                    emptyLinesRemoved++;
                    callbacks.AddFixToListView(p, fixAction0, p.Text, $"[{language.RemovedEmptyLine}]");
                    callbacks.AddToDeleteIndices(i);
                }
            }

            if (emptyLinesRemoved > 0)
            {
                callbacks.UpdateFixStatus(emptyLinesRemoved, language.RemovedEmptyLinesUnsedLineBreaks, string.Format(language.EmptyLinesRemovedX, emptyLinesRemoved));
                subtitle.Renumber();
            }
        }