public void ProcessData(Wiki wiki) { foreach (IPortalModule module in _modules) { module.ProcessData(wiki); } }
public void GetData(Wiki wiki) { foreach (IPortalModule module in _modules) { module.GetData(wiki); } }
public void UpdatePages(Wiki wiki) { foreach (IPortalModule module in _modules) { module.UpdatePage(wiki); } }
public static WikiPage Load(Wiki wiki, string title, string directory) { ParameterCollection parameters = new ParameterCollection(); parameters.Add("prop", "info|revisions"); parameters.Add("intoken", "edit"); parameters.Add("rvprop", "timestamp"); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, new string[] { title }); XmlNode node = xml.SelectSingleNode("//rev"); string baseTimeStamp = null; if (node != null && node.Attributes["timestamp"] != null) { baseTimeStamp = node.Attributes["timestamp"].Value; } node = xml.SelectSingleNode("//page"); string editToken = node.Attributes["edittoken"].Value; string pageFileName = directory + EscapePath(title); string text = LoadPageFromCache(pageFileName, node.Attributes["lastrevid"].Value, title); if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + title + "..."); text = wiki.LoadText(title); CachePage(pageFileName, node.Attributes["lastrevid"].Value, text); } WikiPage page = WikiPage.Parse(title, text); page.BaseTimestamp = baseTimeStamp; page.Token = editToken; return page; }
public static void CacheNamespaces(Wiki wiki, string filename) { using (FileStream fs = new FileStream(filename, FileMode.Create)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) { byte[] data = wiki.NamespacesToArray(); gs.Write(data, 0, data.Length); } }
public void Update(Wiki wiki) { WebClient client = new WebClient(); Cache.LoadPageList(client, Module.Language, Category, Depth); string text = ProcessData(wiki); if (!string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Updating " + Page); wiki.Save(Page, text, Module.UpdateComment); } }
public static bool LoadNamespaces(Wiki wiki, string filename) { if (!File.Exists(filename)) { return false; } using (FileStream fs = new FileStream(filename, FileMode.Open)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Decompress)) using (BinaryReader sr = new BinaryReader(gs)) { List<byte> data = new List<byte>(); int b; while ((b = sr.BaseStream.ReadByte()) != -1) { data.Add((byte)b); } wiki.LoadNamespaces(data); } return true; }
private string ProcessData(Wiki wiki) { StringBuilder result = new StringBuilder(); Console.Out.WriteLine("Processing data of " + Category); string fileName = "Cache\\" + Module.Language + "\\PagesInCategory\\" + Cache.EscapePath(Category) + ".txt"; using (TextReader streamReader = new StreamReader(fileName)) { streamReader.ReadLine(); streamReader.ReadLine(); string line; while ((line = streamReader.ReadLine()) != null) { string[] groups = line.Split(new char[] { '\t' }); if (groups.Length > 2 && groups[2] == Namespace.ToString()) { string title = groups[0].Replace('_', ' '); result.AppendLine(string.Format(Format, title)); } } } return result.ToString(); }
public void UpdatePages(Wiki wiki) { Regex closedRE = new Regex(@"(\{{2}ВПКПМ-Навигация\}{2}\s*\{{2}(Закрыто|Closed|закрыто|closed)\}{2})|(\{{2}(Закрыто|Closed|закрыто|closed)\}{2}\s*\{{2}ВПКПМ-Навигация\}{2})"); Regex wikiLinkRE = new Regex(@"\[{2}(.+?)(\|.+?)?]{2}"); Regex timeRE = new Regex(@"(\d{2}:\d{2}\, \d\d? [а-я]+ \d{4}) \(UTC\)"); ParameterCollection parameters = new ParameterCollection(); parameters.Add("generator", "categorymembers"); parameters.Add("gcmtitle", "Категория:Википедия:Незакрытые обсуждения переименования страниц"); parameters.Add("gcmlimit", "max"); parameters.Add("gcmnamespace", "4"); parameters.Add("prop", "info|revisions"); parameters.Add("intoken", "edit"); XmlDocument doc = wiki.Enumerate(parameters, true); string queryTimestamp = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"); XmlNodeList pages = doc.SelectNodes("//page"); foreach (XmlNode page in pages) { int results = 0; string pageName = page.Attributes["title"].Value; string date = pageName.Substring("Википедия:К переименованию/".Length); string basetimestamp = page.FirstChild.FirstChild.Attributes["timestamp"].Value; string editToken = page.Attributes["edittoken"].Value; Day day = new Day(); if (!DateTime.TryParse(date, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal, out day.Date)) { continue; } string fileName = _cacheDir + date + ".bin"; string text = ""; if (File.Exists(fileName)) { using (FileStream fs = new FileStream(fileName, FileMode.Open)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Decompress)) using (TextReader sr = new StreamReader(gs)) { string revid = sr.ReadLine(); if (revid == page.Attributes["lastrevid"].Value) { Console.Out.WriteLine("Loading " + pageName + "..."); text = sr.ReadToEnd(); } } } if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + pageName + "..."); text = wiki.LoadText(pageName); using (FileStream fs = new FileStream(fileName, FileMode.Create)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) using (StreamWriter sw = new StreamWriter(gs)) { sw.WriteLine(page.Attributes["lastrevid"].Value); sw.Write(text); } } day.Page = WikiPage.Parse(pageName, text); List<string> titlesWithResults = new List<string>(); foreach (WikiPageSection section in day.Page.Sections) { RemoveStrikeOut(section); StrikeOutSection(section); Match m = wikiLinkRE.Match(section.Title); if (m.Success && !m.Groups[1].Value.StartsWith(":Категория:")) { string link = m.Groups[1].Value; string movedTo; string movedBy; DateTime movedAt; DateTime start = day.Date; m = timeRE.Match(section.SectionText); if (m.Success) { start = DateTime.Parse(m.Groups[1].Value, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal); } bool moved = MovedTo(wiki, link, start, out movedTo, out movedBy, out movedAt); WikiPageSection autoVerdictSection = section.Subsections.FirstOrDefault(s => s.Title.Trim() == "Автоматический итог"); if (autoVerdictSection != null && !moved) { autoVerdictSection.Title = " Оспоренный итог "; RemoveStrikeOut(section); StrikeOutSection(section); } if (section.Subsections.Count(s => s.Title.Trim() == "Оспоренный итог") == 0 && section.Subsections.Count(s => s.Title.ToLower().Trim() == "итог") == 0 && section.Subsections.Count(s => s.Title.Trim() == "Автоматический итог") == 0 && moved && !string.IsNullOrEmpty(movedTo)) { string message = string.Format("Страница была переименована {2} в «[[{0}]]» участником [[User:{1}|]]. Данное сообщение было автоматически сгенерировано ботом ~~~~.\n", movedTo, movedBy, movedAt.ToUniversalTime().ToString("d MMMM yyyy в HH:mm (UTC)")); WikiPageSection verdict = new WikiPageSection(" Автоматический итог ", section.Level + 1, message); section.AddSubsection(verdict); StrikeOutSection(section); ++results; } } m = wikiLinkRE.Match(section.Title); if (m.Success && section.Title.Contains("<s>")) { titlesWithResults.Add(m.Groups[1].Value); } List<WikiPageSection> sections = new List<WikiPageSection>(); section.Reduce(sections, SubsectionsList); foreach (WikiPageSection subsection in sections) { m = wikiLinkRE.Match(subsection.Title); if (m.Success && subsection.Title.Contains("<s>")) { titlesWithResults.Add(m.Groups[1].Value.Trim()); } if (m.Success && !subsection.Title.Contains("<s>") && !m.Groups[1].Value.StartsWith(":Категория:")) { string link = m.Groups[1].Value; string movedTo; string movedBy; DateTime movedAt; DateTime start = day.Date; m = timeRE.Match(subsection.SectionText); if (m.Success) { start = DateTime.Parse(m.Groups[1].Value, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal); } bool moved = MovedTo(wiki, link, start, out movedTo, out movedBy, out movedAt); WikiPageSection verdictSection = subsection.Subsections.FirstOrDefault(s => s.Title.Trim() == "Автоматический итог"); if (verdictSection != null && !moved) { verdictSection.Title = " Оспоренный итог "; RemoveStrikeOut(subsection); StrikeOutSection(subsection); } if (subsection.Subsections.Count(s => s.Title.Trim() == "Оспоренный итог") == 0 && subsection.Subsections.Count(s => s.Title.ToLower().Trim() == "итог") == 0 && subsection.Subsections.Count(s => s.Title.Trim() == "Автоматический итог") == 0 && moved && !string.IsNullOrEmpty(movedTo)) { string message = string.Format("Страница была переименована {2} в «[[{0}]]» участником [[User:{1}|]]. Данное сообщение было автоматически сгенерировано ботом ~~~~.\n", movedTo, movedBy, movedAt.ToUniversalTime().ToString("d MMMM yyyy в HH:mm (UTC)")); WikiPageSection verdict = new WikiPageSection(" Автоматический итог ", subsection.Level + 1, message); subsection.AddSubsection(verdict); StrikeOutSection(subsection); ++results; } } } } Match matchClosed = closedRE.Match(text); if (matchClosed.Success) { List<TalkResult> talkResults = new List<TalkResult>(); foreach (string name in titlesWithResults) { if (wiki.PageNamespace(name) > 0) { continue; } string movedTo; string movedBy; DateTime movedAt; bool moved = MovedTo(wiki, name, day.Date, out movedTo, out movedBy, out movedAt); talkResults.Add(new TalkResult(name, movedTo, moved)); } parameters.Clear(); parameters.Add("prop", "info"); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, talkResults.ConvertAll(r => r.Moved ? r.MovedTo : r.Title)); List<string> notificationList = new List<string>(); foreach (XmlNode node in xml.SelectNodes("//page")) { if (node.Attributes["missing"] == null && node.Attributes["ns"].Value == "0") { notificationList.Add(node.Attributes["title"].Value); } } if (notificationList.Count > 0) { parameters.Clear(); parameters.Add("list", "backlinks"); parameters.Add("bltitle", pageName); parameters.Add("blfilterredir", "nonredirects"); parameters.Add("blnamespace", "1"); parameters.Add("bllimit", "max"); XmlDocument backlinks = wiki.Enumerate(parameters, true); foreach (string title in notificationList) { if (backlinks.SelectSingleNode("//bl[@title=\"Обсуждение:" + title + "\"]") == null) { TalkResult tr = talkResults.Find(r => r.Moved ? r.MovedTo == title : r.Title == title); PutNotification(wiki, tr, day.Date); } } } } string newText = day.Page.Text; if (newText.Trim() == text.Trim()) { continue; } try { Console.Out.WriteLine("Updating " + pageName + "..."); string revid = wiki.Save(pageName, "", newText, "зачёркивание заголовков" + (results > 0 ? ", сообщение об итогах" : ""), MinorFlags.Minor, CreateFlags.NoCreate, WatchFlags.None, SaveFlags.Replace, true, basetimestamp, "", editToken); using (FileStream fs = new FileStream(fileName, FileMode.Create)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) using (StreamWriter sw = new StreamWriter(gs)) { sw.WriteLine(revid); sw.Write(newText); } } catch (WikiException) { } } }
public void UpdateMainPage(Wiki wiki) { Console.Out.WriteLine("Updating requested moves..."); using (TextReader sr = new StreamReader(_cacheDir + "MainPage.txt")) { string text = sr.ReadToEnd(); wiki.Save("Википедия:К переименованию", text, "обновление"); } }
public void Analyze(Wiki wiki) { ParameterCollection parameters = new ParameterCollection(); parameters.Add("generator", "categorymembers"); parameters.Add("gcmtitle", "Категория:Википедия:Незакрытые обсуждения переименования страниц"); parameters.Add("gcmlimit", "max"); parameters.Add("gcmnamespace", "4"); parameters.Add("prop", "info|revisions"); parameters.Add("rvprop", "timestamp"); XmlDocument doc = wiki.Enumerate(parameters, true); XmlNodeList pages = doc.SelectNodes("//page"); List<Day> days = new List<Day>(); DateTime start = DateTime.Today; Regex closedRE = new Regex(@"(\{{2}ВПКПМ-Навигация\}{2}\s*\{{2}(Закрыто|Closed|закрыто|closed)\}{2})|(\{{2}(Закрыто|Closed|закрыто|closed)\}{2}\s*\{{2}ВПКПМ-Навигация\}{2})"); wiki.SleepBetweenEdits = 10; wiki.SleepBetweenQueries = 2; DateTime cutOffDate = new DateTime(2009, 3, 21); foreach (XmlNode page in pages) { string pageName = page.Attributes["title"].Value; string date = pageName.Substring("Википедия:К переименованию/".Length); Day day = new Day(); try { day.Date = DateTime.Parse(date, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal); } catch (FormatException) { continue; } string fileName = _cacheDir + date + ".bin"; string text = ""; if (File.Exists(fileName)) { using (FileStream fs = new FileStream(fileName, FileMode.Open)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Decompress)) using (TextReader sr = new StreamReader(gs)) { string revid = sr.ReadLine(); if (revid == page.Attributes["lastrevid"].Value) { Console.Out.WriteLine("Loading " + pageName + "..."); text = sr.ReadToEnd(); } } } if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + pageName + "..."); text = wiki.LoadText(pageName); using (FileStream fs = new FileStream(fileName, FileMode.Create)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) using (StreamWriter sw = new StreamWriter(gs)) { sw.WriteLine(page.Attributes["lastrevid"].Value); sw.Write(text); } } DateTime lastEdit = DateTime.Parse(page.FirstChild.FirstChild.Attributes["timestamp"].Value, null, DateTimeStyles.AssumeUniversal); Match m = closedRE.Match(text); if ((DateTime.Now - lastEdit).TotalDays > 2 && m.Success) { text = text.Replace("{{ВПКПМ-Навигация}}", "{{ВПКПМ-Навигация|nocat=1}}"); try { string revid = wiki.Save(pageName, text, "обсуждение закрыто"); using (FileStream fs = new FileStream(fileName, FileMode.Create)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) using (StreamWriter sw = new StreamWriter(gs)) { sw.WriteLine(revid); sw.Write(text); } } catch (WikiException) { } continue; } day.Page = WikiPage.Parse(pageName, text); days.Add(day); } days.Sort(CompareDays); using (StreamWriter sw = new StreamWriter(_cacheDir + "MainPage.txt")) { sw.WriteLine("{{/Шапка}}\n"); sw.WriteLine("{{Переименование статей/Статьи, вынесенные на переименование}}\n"); Regex wikiLinkRE = new Regex(@"\[{2}(.+?)(\|.+?)?]{2}"); foreach (Day day in days) { Console.Out.WriteLine("Analyzing " + day.Date.ToString("d MMMM yyyy") + "..."); sw.Write("{{Переименование статей/День|" + day.Date.ToString("yyyy-M-d") + "|\n"); List<string> titles = new List<string>(); foreach (WikiPageSection section in day.Page.Sections) { string filler = ""; string result = ""; RemoveStrikeOut(section); StrikeOutSection(section); if (section.SectionText.ToLower().Contains("{{mark out}}")) { section.Title = "{{mark out|" + section.Title.Trim() + "}}"; } bool hasVerdict = section.Subsections.Count(s => s.Title.ToLower().Trim() == "итог") > 0; bool hasAutoVerdict = section.Subsections.Count(s => s.Title.Trim() == "Автоматический итог") > 0; if (hasVerdict || hasAutoVerdict || section.Title.Contains("<s>")) { Match m = wikiLinkRE.Match(section.Title); if (m.Success && !m.Groups[1].Value.StartsWith(":Категория:")) { string link = m.Groups[1].Value; string movedTo; bool moved = MovedTo(wiki, link, day.Date, out movedTo); if (moved && string.IsNullOrEmpty(movedTo)) { result = " ''(переименовано)''"; } else if (moved) { result = string.Format(" ''({1}переименовано в «[[{0}]]»)''", movedTo.StartsWith("Файл:") ? ":" + movedTo : movedTo, hasAutoVerdict ? "де-факто " : ""); } else { result = " ''(не переименовано)''"; } } } for (int i = 0; i < section.Level - 1; ++i) { filler += "*"; } titles.Add(filler + " " + section.Title.Trim() + result); List<WikiPageSection> sections = new List<WikiPageSection>(); section.Reduce(sections, SubsectionsList); foreach (WikiPageSection subsection in sections) { if (subsection.SectionText.ToLower().Contains("{{mark out}}")) { subsection.Title = "{{mark out|" + subsection.Title.Trim() + "}}"; } result = ""; hasVerdict = subsection.Subsections.Count(s => s.Title.ToLower().Trim() == "итог") > 0; hasAutoVerdict = subsection.Subsections.Count(s => s.Title.Trim() == "Автоматический итог") > 0; if (hasVerdict || hasAutoVerdict || subsection.Title.Contains("<s>")) { Match m = wikiLinkRE.Match(subsection.Title); if (m.Success && !m.Groups[1].Value.StartsWith(":Категория:")) { string link = m.Groups[1].Value; string movedTo; bool moved = MovedTo(wiki, link, day.Date, out movedTo); if (moved && string.IsNullOrEmpty(movedTo)) { result = " ''(переименовано)''"; } else if (moved) { result = string.Format(" ''({1}переименовано в «[[{0}]]»)''", movedTo.StartsWith("Файл:") ? ":" + movedTo : movedTo, hasAutoVerdict ? "де-факто " : ""); } else { result = " ''(не переименовано)''"; } } } filler = ""; for (int i = 0; i < subsection.Level - 1; ++i) { filler += "*"; } titles.Add(filler + " " + subsection.Title.Trim() + result); } } if (titles.Count(s => s.Contains("=")) > 0) { titles[0] = "2=<li>" + titles[0].Substring(2) + "</li>"; } sw.Write(string.Join("\n", titles.ConvertAll(c => c).ToArray())); sw.Write("}}\n\n"); } sw.WriteLine("|}\n"); sw.WriteLine("{{/Окончание}}"); } }
public void UpdateArchivePages(Wiki wiki, int year, int monthNumber) { Regex wikiLinkRE = new Regex(@"\[{2}(.+?)(\|.+?)?]{2}"); DateTime month = new DateTime(year, monthNumber, 1); DateTime end = month.AddMonths(1); using (StreamWriter archiveSW = new StreamWriter(_cacheDir + "Archive-" + year.ToString() + "-" + monthNumber.ToString() + ".txt")) while (month < end && month < DateTime.Now) { DateTime start = month; DateTime nextMonth = start.AddMonths(1); List<string> titles = new List<string>(); while (start < nextMonth) { string pageDate = start.ToString("d MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU")); string prefix = "Википедия:К переименованию/"; string pageName = prefix + pageDate; titles.Add(pageName); start = start.AddDays(1); } ParameterCollection parameters = new ParameterCollection(); parameters.Add("prop", "info"); List<Day> days = new List<Day>(); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, titles); XmlNodeList archives = xml.SelectNodes("//page"); foreach (XmlNode page in archives) { string pageName = page.Attributes["title"].Value; string dateString = pageName.Substring("Википедия:К переименованию/".Length); string pageFileName = _cacheDir + dateString + ".bin"; Day day = new Day(); try { day.Date = DateTime.Parse(dateString, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal); } catch (FormatException) { continue; } if (page.Attributes["missing"] != null) { day.Exists = false; days.Add(day); continue; } string text = ""; if (File.Exists(pageFileName)) { using (FileStream fs = new FileStream(pageFileName, FileMode.Open)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Decompress)) using (TextReader sr = new StreamReader(gs)) { string revid = sr.ReadLine(); if (revid == page.Attributes["lastrevid"].Value) { Console.Out.WriteLine("Loading " + pageName + "..."); text = sr.ReadToEnd(); } } } if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + pageName + "..."); text = wiki.LoadText(pageName); using (FileStream fs = new FileStream(pageFileName, FileMode.Create)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) using (StreamWriter sw = new StreamWriter(gs)) { sw.WriteLine(page.Attributes["lastrevid"].Value); sw.Write(text); } } day.Exists = true; day.Page = WikiPage.Parse(pageName, text); days.Add(day); } days.Sort(CompareDays); StringBuilder textBuilder = new StringBuilder(); textBuilder.AppendLine("{{Навигация по архиву КПМ}}\n{{Переименование статей/Начало}}"); StringBuilder sb = new StringBuilder(); foreach (Day day in days) { sb.Append("{{Переименование статей/День|" + day.Date.ToString("yyyy-M-d") + "|\n"); if (!day.Exists) { sb.Append("''нет обсуждений''}}\n\n"); continue; } titles.Clear(); Console.Out.WriteLine("Analyzing " + day.Date.ToString("d MMMM yyyy") + "..."); foreach (WikiPageSection section in day.Page.Sections) { string filler = ""; string result = ""; bool hasVerdict = section.Subsections.Count(s => s.Title.ToLower().Trim() == "итог") > 0; bool hasAutoVerdict = section.Subsections.Count(s => s.Title.Trim() == "Автоматический итог") > 0; if (hasVerdict || hasAutoVerdict || section.Title.Contains("<s>")) { Match m = wikiLinkRE.Match(section.Title); if (m.Success && !m.Groups[1].Value.StartsWith(":Категория:")) { string link = m.Groups[1].Value; string movedTo; bool moved = MovedTo(wiki, link, day.Date, out movedTo); if (moved && string.IsNullOrEmpty(movedTo)) { result = " ''(переименовано)''"; } else if (moved) { result = string.Format(" ''({1}переименовано в «[[{0}]]»)''", movedTo.StartsWith("Файл:") ? ":" + movedTo : movedTo, hasAutoVerdict && !hasVerdict ? "де-факто " : ""); } else { result = " ''(не переименовано)''"; } } } for (int i = 0; i < section.Level - 1; ++i) { filler += "*"; } titles.Add(filler + " " + section.Title.Trim() + result); List<WikiPageSection> sections = new List<WikiPageSection>(); section.Reduce(sections, SubsectionsList); foreach (WikiPageSection subsection in sections) { result = ""; hasVerdict = subsection.Subsections.Count(s => s.Title.ToLower().Trim() == "итог") > 0; hasAutoVerdict = subsection.Subsections.Count(s => s.Title.Trim() == "Автоматический итог") > 0; if (hasVerdict || hasAutoVerdict || subsection.Title.Contains("<s>")) { Match m = wikiLinkRE.Match(subsection.Title); if (m.Success && !m.Groups[1].Value.StartsWith(":Категория:")) { string link = m.Groups[1].Value; string movedTo; bool moved = MovedTo(wiki, link, day.Date, out movedTo); if (moved && string.IsNullOrEmpty(movedTo)) { result = " ''(переименовано)''"; } else if (moved) { result = string.Format(" ''({1}переименовано в «[[{0}]]»)''", movedTo.StartsWith("Файл:") ? ":" + movedTo : movedTo, hasAutoVerdict && !hasVerdict ? "де-факто " : ""); } else { result = " ''(не переименовано)''"; } } } filler = ""; for (int i = 0; i < subsection.Level - 1; ++i) { filler += "*"; } titles.Add(filler + " " + subsection.Title.Trim() + result); } } if (titles.Count(s => s.Contains("=")) > 0) { titles[0] = "2=<li>" + titles[0].Substring(2) + "</li>"; } sb.Append(string.Join("\n", titles.ConvertAll(c => c).ToArray())); sb.Append("}}\n\n"); } sb.Replace("<s>", ""); sb.Replace("</s>", ""); sb.Replace("<strike>", ""); sb.Replace("</strike>", ""); textBuilder.Append(sb.ToString()); textBuilder.AppendLine("{{Переименование статей/Конец}}"); archiveSW.WriteLine(textBuilder.ToString()); month = month.AddMonths(1); } string archiveName = string.Format("Википедия:Архив запросов на переименование/{0}-{1:00}", year, monthNumber); Console.Out.WriteLine("Updating " + archiveName + "..."); using (TextReader sr = new StreamReader(_cacheDir + "Archive-" + year.ToString() + "-" + monthNumber.ToString() + ".txt")) { string text = sr.ReadToEnd(); wiki.Save(archiveName, text, "обновление"); } }
internal void AddNavigationTemplate(Wiki wiki) { ParameterCollection parameters = new ParameterCollection(); parameters.Add("list", "embeddedin"); parameters.Add("eititle", "Template:ВПКОБ-Навигация"); parameters.Add("eilimit", "max"); parameters.Add("einamespace", "4"); parameters.Add("eifilterredir", "nonredirects"); XmlDocument doc = wiki.Enumerate(parameters, true); List<string> titles = new List<string>(); DateTime end = DateTime.Today; DateTime start = end.AddDays(-7); while (start <= end) { string pageDate = start.ToString("d MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU")); string prefix = "Википедия:К объединению/"; string pageName = prefix + pageDate; if (doc.SelectSingleNode("//ei[@title='" + pageName + "']") == null) { titles.Add(pageName); } start = start.AddDays(1); } parameters.Clear(); parameters.Add("prop", "info"); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, titles); foreach (XmlNode node in xml.SelectNodes("//page")) { if (node.Attributes["missing"] == null) { Console.Out.WriteLine("Updating " + node.Attributes["title"].Value + "..."); wiki.Prepend(node.Attributes["title"].Value, "{{ВПКОБ-Навигация}}\n", "добавление навигационного шаблона"); } } }
public void Run(Wiki wiki) { AddNavigationTemplate(wiki); UpdatePages(wiki); Analyze(wiki); UpdateMainPage(wiki); UpdateArchivePages(wiki); }
private void PutNotification(Wiki wiki, TalkResult result, DateTime date) { string talkPageTemplate; string dateString = date.ToString("d MMMM yyyy"); if (!result.Moved) { talkPageTemplate = "{{Не переименовано|" + dateString + "|" + result.Title + "}}\n"; } else { talkPageTemplate = "{{Переименовано|" + dateString + "|" + result.Title + "|" + result.MovedTo + "}}\n"; } string talkPage = "Обсуждение:" + (result.Moved ? result.MovedTo : result.Title); Console.Out.WriteLine("Updating " + talkPage + "..."); try { ParameterCollection parameters = new ParameterCollection(); parameters.Add("rvprop", "content"); parameters.Add("rvsection", "0)"); parameters.Add("prop", "revisions"); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, new string[] { talkPage }); string content; XmlNode node = xml.SelectSingleNode("//rev"); if (node != null) { content = node.FirstChild != null ? node.FirstChild.Value : ""; } else { content = ""; } int index = content.IndexOf("{{talkheader", StringComparison.CurrentCultureIgnoreCase); if (index != -1) { int endIndex = content.IndexOf("}}", index); if (endIndex != -1) { content = content.Insert(endIndex + 2, "\n" + talkPageTemplate); } } else { index = content.IndexOf("{{заголовок обсуждения", StringComparison.CurrentCultureIgnoreCase); if (index != -1) { int endIndex = content.IndexOf("}}", index); if (endIndex != -1) { content = content.Insert(endIndex + 2, "\n" + talkPageTemplate); } } else { content = content.Insert(0, talkPageTemplate); } } wiki.SaveSection(talkPage, "0", content, "итог"); } catch (WikiException e) { Console.Out.WriteLine("Failed to update " + talkPage + ":" + e.Message); } }
static void Main(string[] args) { Wiki wiki = new Wiki("http://ru.wikipedia.org/w/"); if (string.IsNullOrEmpty(Settings.Default.Login) || string.IsNullOrEmpty(Settings.Default.Password)) { Console.Out.WriteLine("Please add login and password to the configuration file."); return; } Console.Out.WriteLine("Logging in as " + Settings.Default.Login + "..."); try { wiki.Login(Settings.Default.Login, Settings.Default.Password); } catch (WikiException e) { Console.Out.WriteLine(e.Message); return; } Console.Out.WriteLine("Logged in as " + Settings.Default.Login + "."); wiki.SleepBetweenQueries = 3; Regex re = new Regex(@"\*\s*\[\[User:(.+?)\]\]\s*→\s*\[\[User:(.+?)\]\]"); Dictionary<string, string> renamedUsers = new Dictionary<string, string>(); string renamedUsersData = wiki.LoadText("Википедия:Проект:Патрулирование/Статистика/1k+/Переименования"); using (TextReader sr = new StringReader(renamedUsersData)) { string line; while ((line = sr.ReadLine()) != null) { Match m = re.Match(line); if (m.Success) { string oldName = m.Groups[1].Value; string newName = m.Groups[2].Value; if (!renamedUsers.ContainsKey(oldName)) { renamedUsers.Add(oldName, newName); } } } } DateTime currentMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1); DateTime now = currentMonth; DateTime firstReviewMonth = new DateTime(2008, 9, 1); while (currentMonth > firstReviewMonth) { DateTime previousMonth = currentMonth.AddMonths(-1); if (File.Exists("output" + previousMonth.ToString("yyyy-MM") + ".txt")) { currentMonth = currentMonth.AddMonths(-1); continue; } string start = previousMonth.ToString("yyyy-MM-ddTHH:mm:ssZ"); string stop = currentMonth.ToString("yyyy-MM-ddTHH:mm:ssZ"); Console.Out.WriteLine("Quering list of editors for " + previousMonth.ToString("MMMM yyyy") + "..."); ParameterCollection parameters = new ParameterCollection(); parameters.Add("list", "logevents"); parameters.Add("letype", "review"); parameters.Add("lestart", start); parameters.Add("leend", stop); parameters.Add("ledir", "newer"); parameters.Add("lelimit", "max"); Dictionary<string, User> users = new Dictionary<string, User>(); XmlNode continueNode = null; while (true) { XmlDocument doc; try { doc = wiki.MakeRequest(Claymore.SharpMediaWiki.Action.Query, parameters); } catch (WikiException e) { Console.Out.WriteLine(e.Message); return; } continueNode = doc.SelectSingleNode("//query-continue"); if (continueNode != null) { string name = continueNode.FirstChild.Attributes[0].Name; string value = continueNode.FirstChild.Attributes[0].Value; parameters.Set(name, value); } XmlNodeList entries = doc.SelectNodes("//item[@action!=\"approve-a\" and @action!=\"approve-ia\"]"); foreach (XmlNode entry in entries) { string username = renamedUsers.ContainsKey(entry.Attributes["user"].Value) ? renamedUsers[entry.Attributes["user"].Value] : entry.Attributes["user"].Value; string ns = entry.Attributes["ns"].Value; if (!users.ContainsKey(username)) { User user = new User(username); if (ns == "0") { user.ArticleActions = 1; } else if (ns == "14") { user.CategoryActions = 1; } else if (ns == "10") { user.TemplateActions = 1; } else if (ns == "6") { user.FileActions = 1; } users.Add(username, user); } else { User user = users[username]; if (ns == "0") { ++user.ArticleActions; } else if (ns == "14") { ++user.CategoryActions; } else if (ns == "10") { ++user.TemplateActions; } else if (ns == "6") { ++user.FileActions; } users[username] = user; } } if (continueNode == null) { break; } } Console.Out.WriteLine("Processing data..."); List<User> userList = new List<User>(users.Select(s => s.Value)); userList.Sort(CompareUsers); using (StreamWriter sw = new StreamWriter("output" + previousMonth.ToString("yyyy-MM") + ".txt", false)) { int totalActions = 0; int totalArticleActions = 0; int totalCategoryActions = 0; int totalTemplateActions = 0; int totalFileActions = 0; bool bots = false; sw.WriteLine("== " + previousMonth.ToString("MMMM") + " =="); sw.WriteLine("{| class=\"standard sortable\""); sw.WriteLine("!№!!Участник!!всего!!статей!!категорий!!шаблонов!!файлов"); for (int i = 0, j = 1; i < userList.Count; ++i) { if (userList[i].Name.Contains("Lockalbot") || userList[i].Name.Contains("Secretary")) { bots = true; continue; } sw.WriteLine("|-"); totalActions += userList[i].Actions; totalArticleActions += userList[i].ArticleActions; totalCategoryActions += userList[i].CategoryActions; totalTemplateActions += userList[i].TemplateActions; totalFileActions += userList[i].FileActions; string line = string.Format("|{0}||[[User:{1}|]]||{2}||{3}||{4}||{5}||{6}", j++, userList[i].Name, userList[i].Actions, userList[i].ArticleActions, userList[i].CategoryActions, userList[i].TemplateActions, userList[i].FileActions); sw.WriteLine(line); } sw.WriteLine("|-"); sw.WriteLine("|||Итого||{0}||{1}||{2}||{3}||{4}", totalActions, totalArticleActions, totalCategoryActions, totalTemplateActions, totalFileActions); sw.WriteLine("|}"); if (bots) { sw.WriteLine("; Боты"); sw.WriteLine("{| class=\"standard sortable\""); sw.WriteLine("!№!!Участник!!всего!!статей!!категорий!!шаблонов!!файлов"); for (int i = 0, j = 1; i < userList.Count; ++i) { if (userList[i].Name.Contains("Lockalbot") || userList[i].Name.Contains("Secretary")) { sw.WriteLine("|-"); string line = string.Format("|{0}||[[User:{1}|]]||{2}||{3}||{4}||{5}||{6}", j++, userList[i].Name, userList[i].Actions, userList[i].ArticleActions, userList[i].CategoryActions, userList[i].TemplateActions, userList[i].FileActions); sw.WriteLine(line); } } sw.WriteLine("|}"); } sw.WriteLine("\n— ~~~~"); } currentMonth = currentMonth.AddMonths(-1); } currentMonth = new DateTime(2008, 9, 1); Dictionary<string, List<MonthStat>> userStatistics = new Dictionary<string, List<MonthStat>>(); while (currentMonth < now) { using (TextReader sr = new StreamReader("output" + currentMonth.ToString("yyyy-MM") + ".txt")) { string line; while ((line = sr.ReadLine()) != null) { if (line == "|-") { line = sr.ReadLine(); string[] fields = line.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries); string user = fields[1]; int actions = int.Parse(fields[2]); if (user.StartsWith("[[User:"******"output" + currentMonth.ToString("yyyy-MM") + ".txt")) { string line; while ((line = sr.ReadLine()) != null) { if (line == "|-") { line = sr.ReadLine(); string[] fields = line.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries); string user = fields[1]; int actions = int.Parse(fields[2]); if (userStatistics.ContainsKey(user)) { List<MonthStat> stats = userStatistics[user]; stats.Add(new MonthStat(currentMonth, actions)); } } } } currentMonth = currentMonth.AddMonths(1); } using (StreamWriter sw = new StreamWriter("output.txt", false)) { sw.WriteLine("== Статистика =="); for (int year = DateTime.Today.Year; year >= 2008; --year) { DateTime currentYear = new DateTime(year, 1, 1); List<UserStat> userStats = new List<UserStat>(); foreach (var user in userStatistics) { var stats = user.Value.Where(s => (s.Month >= currentYear && s.Month < currentYear.AddYears(1))); UserStat userStat = new UserStat(user.Key, stats); userStat.enterDate = user.Value.Where(s => s.Actions >= 1000).Min(s => s.Month); userStat.ActionsBefore = user.Value.Where(s => s.Month < currentYear).Sum(s => s.Actions); userStat.Max = user.Value.Max(s => s.Actions); if (stats.Count() > 0 && userStat.enterDate.Year <= year) { userStats.Add(userStat); } } userStats.Sort(CompareUserStat); sw.WriteLine("\n=== {0} ===", currentYear.Year); sw.WriteLine("{| class=\"wikitable sortable\""); sw.Write("! № !! Участник"); currentMonth = currentYear; while (currentMonth < currentYear.AddYears(1)) { sw.Write(" !! " + currentMonth.ToString("MMM yy")); currentMonth = currentMonth.AddMonths(1); } sw.Write(" !! За {0} !! На конец {0} ", currentYear.Year); sw.WriteLine(); for (int index = 0; index < userStats.Count; ++index) { sw.WriteLine("|-"); sw.WriteLine(userStats[index].IsBot ? "! Бот" : string.Format("! {0}", index + 1)); sw.Write(string.Format("| {0}", userStats[index].Name)); int max = userStats[index].Stat.Max(s => s.Actions); currentMonth = currentYear; int totalActions = 0; while (currentMonth < currentYear.AddYears(1)) { int actions = 0; foreach (var item in userStats[index].Stat) { if (item.Month == currentMonth) { actions = item.Actions; break; } } if (actions != userStats[index].Max) { sw.Write(" || " + actions); } else { sw.Write(string.Format(" || '''{0}'''", actions)); } totalActions += actions; currentMonth = currentMonth.AddMonths(1); } sw.Write(string.Format(" || {0}", totalActions)); sw.Write(string.Format(" || {0}", totalActions + userStats[index].ActionsBefore)); sw.WriteLine(); } sw.WriteLine("|}"); } } currentMonth = new DateTime(now.Year, now.Month, 1).AddMonths(-1); Console.Out.WriteLine("Updating the wiki page..."); using (TextReader sr = new StreamReader("output" + currentMonth.ToString("yyyy-MM") + ".txt")) { DateTime previousMonth = new DateTime(now.Year, now.Month, 1).AddMonths(-1); string text = sr.ReadToEnd(); string period = previousMonth.ToString("MMMM yyyy"); wiki.Save(previousMonth.ToString("Википедия:Проект:Патрулирование\\/Статистика\\/yyyy\\/MM"), text, "статистика патрулирования за " + period[0].ToString().ToLower() + period.Substring(1)); } Console.Out.WriteLine("Updating Википедия:Проект:Патрулирование/Статистика/1k+..."); using (TextReader sr = new StreamReader("output.txt")) { string text = sr.ReadToEnd(); wiki.SaveSection("Википедия:Проект:Патрулирование/Статистика/1k+", "1", text, "обновление"); } wiki.Save(currentMonth.ToString("Википедия:Проект:Патрулирование\\/Статистика\\/yyyy"), string.Format("#REDIRECT [[{0}]]", currentMonth.ToString("Википедия:Проект:Патрулирование\\/Статистика\\/yyyy\\/MM")), "обновление"); Console.Out.WriteLine("Done."); wiki.Logout(); }
public override Dictionary<string, string> Process(Wiki wiki, WikiPage page, ref int diffSize, ref int topicsArchived) { List<WikiPageSection> archivedSections = new List<WikiPageSection>(); foreach (WikiPageSection section in page.Sections) { WikiPageSection result = section.Subsections.FirstOrDefault(ss => ss.Title.Trim().ToLower() == "итог"); bool forceArchivation = LookForLines.Any(s => section.Text.ToLower().Contains(s.ToLower())); if (!OnHold.Any(s => section.Text.ToLower().Contains(s.ToLower())) && ((result != null && !string.IsNullOrEmpty(result.SectionText.Trim())) || forceArchivation || !CheckForResult)) { MatchCollection ms = timeRE.Matches(FilterQuotes(section.Text)); DateTime published = DateTime.Today; DateTime lastReply = DateTime.MinValue; foreach (Match match in ms) { string value = match.Groups[1].Value; DateTime time = DateTime.Parse(value, L10i.Culture, DateTimeStyles.AssumeUniversal); if (time < published) { published = time; } if (time > lastReply) { lastReply = time; } } if (lastReply != DateTime.MinValue && ((forceArchivation && (DateTime.Today - lastReply).TotalHours >= ForcedArchivationDelay) || (DateTime.Today - lastReply).TotalHours >= Delay)) { archivedSections.Add(section); } } if (IsMovedSection(section)) { section.SectionText = section.SectionText.Trim(new char[] { ' ', '\t', '\n' }) + "\n~~~~\n"; archivedSections.Add(section); } } Dictionary<string, string> archiveTexts = new Dictionary<string, string>(); if (archivedSections.Count == 0) { diffSize = 0; return archiveTexts; } var parameters = new ParameterCollection() { { "prop", "info" }, }; XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, MainPage); int ns = int.Parse(xml.SelectSingleNode("//page").Attributes["ns"].Value); string prefix = wiki.GetNamespace(ns) + ":"; parameters = new ParameterCollection() { { "list", "allpages" }, { "apprefix", MainPage.Substring(prefix.Length) }, { "apnamespace", ns.ToString() } }; xml = wiki.Enumerate(parameters, true); int maxNumber = 1; foreach (XmlNode p in xml.SelectNodes("//p")) { string title = p.Attributes["title"].Value; string format = Format.Replace("{0}", ""); if (title.StartsWith(format)) { int number; if (int.TryParse(title.Substring(format.Length), out number)) { if (number > maxNumber) { maxNumber = number; } } } } int index = 0; string pageName = string.Format(Format, maxNumber); parameters.Clear(); parameters.Add("prop", "info"); xml = wiki.Query(QueryBy.Titles, parameters, new string[] { pageName }); XmlNode node = xml.SelectSingleNode("//page"); if (node.Attributes["missing"] == null) { string pageFileName = _cacheDir + Cache.GenerateCachePath(pageName); string text = Cache.LoadPageFromCache(pageFileName, node.Attributes["lastrevid"].Value, pageName); if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + pageName + "..."); text = wiki.LoadText(pageName); Cache.CachePage(pageName, _cacheDir, node.Attributes["lastrevid"].Value, text); } WikiPage archivePage = WikiPage.Parse(pageName, text); if (archivePage.Sections.Count < Topics) { int topics = Topics - archivePage.Sections.Count; for (int i = 0; i < topics && index < archivedSections.Count; ++i, ++index) { WikiPageSection section = archivedSections[index]; section.Title = ProcessSectionTitle(section.Title); archivePage.Sections.Add(section); } if (NewSectionsDown) { archivePage.Sections.Sort(SectionsDown); } else { archivePage.Sections.Sort(SectionsUp); } if (!string.IsNullOrEmpty(RemoveFromText)) { archivePage.Text = archivePage.Text.Replace(RemoveFromText, ""); } archiveTexts.Add(pageName, archivePage.Text); } } if (index < archivedSections.Count) { string text = Header; pageName = string.Format(Format, maxNumber + 1); WikiPage archivePage = WikiPage.Parse(pageName, text); for (; index < archivedSections.Count; ++index) { WikiPageSection section = archivedSections[index]; section.Title = ProcessSectionTitle(section.Title); archivePage.Sections.Add(section); } archivePage.Sections.Sort(SectionsUp); if (!string.IsNullOrEmpty(RemoveFromText)) { archivePage.Text = archivePage.Text.Replace(RemoveFromText, ""); } archiveTexts.Add(pageName, archivePage.Text); } topicsArchived = 0; diffSize = 0; foreach (var section in archivedSections) { diffSize += Encoding.UTF8.GetByteCount(section.Text); ++topicsArchived; page.Sections.Remove(section); } return archiveTexts; }
private void PutNotification(Wiki wiki, string title, string date) { string talkPage = wiki.GetNamespace(1) + ":" + title; Console.Out.WriteLine("Updating " + talkPage + "..."); try { ParameterCollection parameters = new ParameterCollection(); parameters.Add("rvprop", "content"); parameters.Add("rvsection", "0)"); parameters.Add("prop", "revisions"); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, new string[] { talkPage }); string content; XmlNode node = xml.SelectSingleNode("//rev"); if (node != null && node.FirstChild != null) { content = node.FirstChild.Value; } else { content = ""; } int index = content.IndexOf("{{" + _l10i.NotificationTemplate + "|", StringComparison.CurrentCultureIgnoreCase); if (index != -1) { int endIndex = content.IndexOf("}}", index); if (endIndex != -1) { content = content.Insert(endIndex, "|" + date); } } else { index = content.IndexOf("{{talkheader", StringComparison.CurrentCultureIgnoreCase); if (index != -1) { int endIndex = content.IndexOf("}}", index); if (endIndex != -1) { content = content.Insert(endIndex + 2, "\n{{" + _l10i.NotificationTemplate + "|" + date + "}}\n"); } } else { index = content.IndexOf("{{заголовок обсуждения", StringComparison.CurrentCultureIgnoreCase); if (index != -1) { int endIndex = content.IndexOf("}}", index); if (endIndex != -1) { content = content.Insert(endIndex + 2, "\n{{" + _l10i.NotificationTemplate + "|" + date + "}}\n"); } } else { content = content.Insert(0, "\n{{" + _l10i.NotificationTemplate + "|" + date + "}}\n"); } } } wiki.SaveSection(talkPage, "0", content, _l10i.MainPageUpdateComment); } catch (WikiException e) { Console.Out.WriteLine("Failed to update " + talkPage + ":" + e.Message); } }
public void Analyse(Wiki wiki) { Directory.CreateDirectory(_cacheDir); Regex wikiLinkRE = new Regex(@"\[{2}(.+?)(\|.+?)?]{2}"); ParameterCollection parameters = new ParameterCollection(); parameters.Add("generator", "categorymembers"); parameters.Add("gcmtitle", _l10i.Category); parameters.Add("gcmlimit", "max"); parameters.Add("gcmnamespace", "4"); parameters.Add("prop", "info"); XmlDocument doc = wiki.Enumerate(parameters, true); XmlNodeList pages = doc.SelectNodes("//page"); List<Day> days = new List<Day>(); foreach (XmlNode page in pages) { string prefix = _l10i.MainPage + "/"; string pageName = page.Attributes["title"].Value; if (pageName.Length < prefix.Length) { continue; } string date = pageName.Substring(prefix.Length); Day day = new Day(); if (!DateTime.TryParse(date, CultureInfo.CreateSpecificCulture(_l10i.Culture), DateTimeStyles.AssumeUniversal, out day.Date)) { continue; } string fileName = _cacheDir + date + ".bin"; string text = ""; if (File.Exists(fileName)) { using (FileStream fs = new FileStream(fileName, FileMode.Open)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Decompress)) using (TextReader sr = new StreamReader(gs)) { string revid = sr.ReadLine(); if (revid == page.Attributes["lastrevid"].Value) { Console.Out.WriteLine("Loading " + pageName + "..."); text = sr.ReadToEnd(); } } } if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + pageName + "..."); text = wiki.LoadText(pageName); using (FileStream fs = new FileStream(fileName, FileMode.Create)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) using (StreamWriter sw = new StreamWriter(gs)) { sw.WriteLine(page.Attributes["lastrevid"].Value); sw.Write(text); } } day.Page = WikiPage.Parse(pageName, text); days.Add(day); } days.Sort(CompareDays); using (StreamWriter sw = new StreamWriter(_cacheDir + "Main.txt")) { sw.WriteLine("{{" + _l10i.TopTemplate + "}}\n"); foreach (Day day in days) { sw.Write("{{" + _l10i.Template + "|" + day.Date.ToString("yyyy-M-d") + "|"); List<string> titles = new List<string>(); foreach (WikiPageSection section in day.Page.Sections) { ReplaceEmptyResults(section); RemoveStrikeOut(section); StrikeOutSection(section); string result = section.Reduce("", SubsectionsList); if (result.Length > 0) { result = " • <small>" + result.Substring(3) + "</small>"; } string title; if (_l10i.Processor != null) { title = _l10i.Processor(section).Trim(); } else { title = section.Title.Trim(); } titles.Add(title + result); } sw.Write(string.Join(" • ", titles.ConvertAll(c => c).ToArray())); sw.Write("}}\n\n"); } sw.WriteLine("{{" + _l10i.BottomTemplate + "}}"); } List<string> dates = new List<string>(); DateTime today = DateTime.Today; DateTime currentMonth = new DateTime(today.Year, today.Month, 1); for (int i = 0; i < 2; ++i) { DateTime start = currentMonth.AddMonths(-i); DateTime end = start.AddMonths(1); while (start < end) { string date = start.ToString("d MMMM yyyy", CultureInfo.CreateSpecificCulture(_l10i.Culture)); string prefix = _l10i.MainPage + "/"; string pageName = prefix + date; dates.Add(pageName); start = start.AddDays(1); } } parameters.Clear(); parameters.Add("prop", "info"); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, dates); days.Clear(); foreach (string pageName in dates) { string prefix = _l10i.MainPage + "/"; string date = pageName.Substring(prefix.Length); string fileName = _cacheDir + date + ".bin"; bool archived = doc.SelectSingleNode("//page[@title=\"" + pageName + "\"]") == null; XmlNode page = xml.SelectSingleNode("//page[@title=\"" + pageName + "\"]"); Day day = new Day(); day.Archived = archived; if (!DateTime.TryParse(date, CultureInfo.CreateSpecificCulture(_l10i.Culture), DateTimeStyles.AssumeUniversal, out day.Date)) { continue; } if (page.Attributes["missing"] != null) { day.Exists = false; days.Add(day); continue; } string text = ""; if (File.Exists(fileName)) { using (FileStream fs = new FileStream(fileName, FileMode.Open)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Decompress)) using (TextReader sr = new StreamReader(gs)) { string revid = sr.ReadLine(); if (revid == page.Attributes["lastrevid"].Value) { Console.Out.WriteLine("Loading " + pageName + "..."); text = sr.ReadToEnd(); } } } if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + pageName + "..."); text = wiki.LoadText(pageName); using (FileStream fs = new FileStream(fileName, FileMode.Create)) using (GZipStream gs = new GZipStream(fs, CompressionMode.Compress)) using (StreamWriter sw = new StreamWriter(gs)) { sw.WriteLine(page.Attributes["lastrevid"].Value); sw.Write(text); } } day.Exists = true; day.Page = WikiPage.Parse(pageName, text); days.Add(day); } days.Sort(CompareDays); for (int i = 0; i < 2; ++i) { DateTime start = currentMonth.AddMonths(-i); DateTime end = start.AddMonths(1); string archiveDate = start.ToString("yyyy-MM"); IEnumerable<Day> daysInMonth = days.Where(d => d.Date >= start && d.Date < end); using (StreamWriter sw = new StreamWriter(_cacheDir + "Archive-" + archiveDate + ".txt")) { sw.WriteLine(_l10i.ArchiveHeader); StringBuilder sb = new StringBuilder(); foreach (Day day in daysInMonth) { sb.Append("{{" + _l10i.Template + "|" + day.Date.ToString("yyyy-M-d") + "|"); if (!day.Exists) { sb.Append("''" + _l10i.EmptyArchive + "''}}\n\n"); continue; } List<string> titles = new List<string>(); foreach (WikiPageSection section in day.Page.Sections) { string result = section.Reduce("", SubsectionsList); if (result.Length > 0) { result = " • <small>" + result.Substring(3) + "</small>"; } string title; if (_l10i.Processor != null) { title = _l10i.Processor(section).Trim(); } else { title = section.Title.Trim(); } titles.Add(title + result); } sb.Append(string.Join(" • ", titles.ConvertAll(c => c).ToArray())); sb.Append("}}\n\n"); } sb.Replace("<s>", ""); sb.Replace("</s>", ""); sb.Replace("<strike>", ""); sb.Replace("</strike>", ""); sw.Write(sb.ToString()); sw.WriteLine(_l10i.ArchiveFooter); } } }
private static bool MovedTo(Wiki wiki, string title, DateTime start, out string movedTo) { string movedBy; DateTime movedAt; return MovedTo(wiki, title, start, out movedTo, out movedBy, out movedAt); }
private static bool MovedTo(Wiki wiki, string title, DateTime start, out string movedTo, out string movedBy, out DateTime movedAt) { ParameterCollection parameters = new ParameterCollection(); parameters.Add("list", "logevents"); parameters.Add("letitle", title); parameters.Add("letype", "move"); parameters.Add("lestart", start.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")); parameters.Add("ledir", "newer"); parameters.Add("lelimit", "max"); XmlDocument doc = wiki.Enumerate(parameters, true); XmlNodeList moved = doc.SelectNodes("//move"); List<Revision> revs = new List<Revision>(); foreach (XmlNode revision in moved) { revs.Add(new Revision(revision.Attributes["new_title"].Value, revision.ParentNode.Attributes["comment"].Value, revision.ParentNode.Attributes["timestamp"].Value, revision.ParentNode.Attributes["user"].Value)); } revs.Sort(CompareRevisions); if (revs.Count > 0) { bool result = MovedTo(wiki, revs[0].MovedTo, revs[0].Time, out movedTo, out movedBy, out movedAt); if (result) { return movedTo != title; } else { movedTo = revs[0].MovedTo; movedBy = revs[0].User; movedAt = revs[0].Time; return movedTo != title; } } movedTo = ""; movedBy = ""; movedAt = new DateTime(); return false; }
public void UpdateMainPage(Wiki wiki) { Console.Out.WriteLine("Updating proposed merges..."); using (TextReader sr = new StreamReader(_cacheDir + "MainPage.txt")) { string text = sr.ReadToEnd(); wiki.SaveSection("Википедия:К объединению", "1", text, "обновление"); } }
private void UpdateArchives(Wiki wiki) { var parameters = new ParameterCollection() { {"generator", "categorymembers"}, {"gcmtitle", "Категория:Википедия:Незакрытые обсуждения переименования страниц"}, {"gcmlimit", "max"}, {"gcmnamespace", "4"}, {"prop", "info"}, }; XmlDocument doc = wiki.Enumerate(parameters, true); XmlNodeList pages = doc.SelectNodes("//page"); DateTime startDate = DateTime.Today; foreach (XmlNode page in pages) { string pageName = page.Attributes["title"].Value; string dateString = pageName.Substring("Википедия:К переименованию/".Length); DateTime date; if (!DateTime.TryParse(dateString, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal, out date)) { continue; } if (date < startDate) { startDate = new DateTime(date.Year, date.Month, 1); } } DateTime month = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1); do { UpdateArchivePages(wiki, month.Year, month.Month); month = month.AddMonths(-1); } while (month != startDate); }
public static PageInfo LoadPageInformation(Wiki wiki, string language, string title) { if (!File.Exists(string.Format(@"Cache\{0}\pages.txt", language))) { FileStream stream = File.Create(string.Format(@"Cache\{0}\pages.txt", language)); stream.Close(); } using (TextReader streamReader = new StreamReader(string.Format(@"Cache\{0}\pages.txt", language))) { string line; while ((line = streamReader.ReadLine()) != null) { string[] groups = line.Split(new char[] { '\t' }); if (groups[0] == title || (groups.Length > 3 && groups[3] == title)) { DateTime time = DateTime.Parse(groups[2], null, DateTimeStyles.AssumeUniversal); return new PageInfo(groups[0], groups[1], time, 0); } } } ParameterCollection parameters = new ParameterCollection(); parameters.Add("prop", "revisions"); parameters.Add("rvprop", "timestamp|user"); parameters.Add("rvdir", "newer"); parameters.Add("rvlimit", "1"); parameters.Add("redirects"); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, new string[] { title }); XmlNode node = xml.SelectSingleNode("//rev"); if (node != null) { string pageName = xml.SelectSingleNode("//page").Attributes["title"].Value; string user = node.Attributes["user"].Value; string timestamp = node.Attributes["timestamp"].Value; DateTime time = DateTime.Parse(timestamp, null, DateTimeStyles.AssumeUniversal); using (TextWriter streamWriter = new StreamWriter(string.Format(@"Cache\{0}\pages.txt", language), true)) { streamWriter.WriteLine("{0}\t{1}\t{2}\t{3}", pageName, user, timestamp, pageName != title ? title : ""); } return new PageInfo(pageName, user, time, 0); } return null; }
public void UpdateArchivePages(Wiki wiki) { ParameterCollection parameters = new ParameterCollection(); parameters.Add("generator", "categorymembers"); parameters.Add("gcmtitle", "Категория:Википедия:Незакрытые обсуждения объединения страниц"); parameters.Add("gcmlimit", "max"); parameters.Add("gcmnamespace", "4"); parameters.Add("prop", "info"); XmlDocument doc = wiki.Enumerate(parameters, true); XmlNodeList pages = doc.SelectNodes("//page"); DateTime minDate = DateTime.Now; foreach (XmlNode page in pages) { string pageName = page.Attributes["title"].Value; string date = pageName.Substring("Википедия:К объединению/".Length); try { DateTime day = DateTime.Parse(date, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal); if (day < minDate) { minDate = day; } } catch (FormatException) { continue; } } List<string> titles = new List<string>(); minDate = new DateTime(minDate.Year, minDate.Month, 1); DateTime currentMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1); DateTime start = minDate; while (start <= currentMonth) { string date = start.ToString("yyyy-MM"); string pageName = "Википедия:Архив запросов на объединение/" + date; titles.Add(pageName); start = start.AddMonths(1); } parameters.Clear(); parameters.Add("prop", "info"); XmlDocument archivesDoc = wiki.Query(QueryBy.Titles, parameters, titles); pages = archivesDoc.SelectNodes("//page"); foreach (XmlNode archivePage in pages) { string archiveName = archivePage.Attributes["title"].Value; string date = archiveName.Substring("Википедия:Архив запросов на объединение/".Length); DateTime archiveDate; try { archiveDate = DateTime.Parse(date, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal); } catch (FormatException) { continue; } string fileName = _cacheDir + "Archive-" + date + ".txt"; start = archiveDate; DateTime end = start.AddMonths(1); titles.Clear(); while (start < end) { string pageDate = start.ToString("d MMMM yyyy", CultureInfo.CreateSpecificCulture("ru-RU")); string prefix = "Википедия:К объединению/"; string pageName = prefix + pageDate; titles.Add(pageName); start = start.AddDays(1); } parameters.Clear(); parameters.Add("prop", "info"); List<Day> days = new List<Day>(); XmlDocument xml = wiki.Query(QueryBy.Titles, parameters, titles); XmlNodeList archives = xml.SelectNodes("//page"); foreach (XmlNode page in archives) { string pageName = page.Attributes["title"].Value; string dateString = pageName.Substring("Википедия:К объединению/".Length); string pageFileName = _cacheDir + dateString + ".bin"; Day day = new Day(); day.Archived = doc.SelectSingleNode("//page[@title=\"" + pageName + "\"]") == null; try { day.Date = DateTime.Parse(dateString, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal); } catch (FormatException) { continue; } if (page.Attributes["missing"] != null) { day.Exists = false; days.Add(day); continue; } string text = LoadPageFromCache(pageFileName, page.Attributes["lastrevid"].Value, pageName); if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + pageName + "..."); text = wiki.LoadText(pageName); CachePage(pageFileName, page.Attributes["lastrevid"].Value, text); } day.Exists = true; day.Page = WikiPage.Parse(pageName, text); days.Add(day); } days.Sort(CompareDays); StringBuilder textBuilder = new StringBuilder(); textBuilder.AppendLine("{{Навигация по архиву КОБ}}\n{{Объединение статей/Начало}}"); StringBuilder sb = new StringBuilder(); foreach (Day day in days) { sb.Append("{{Объединение статей/День|" + day.Date.ToString("yyyy-M-d") + "|\n"); if (!day.Archived && day.Exists) { sb.Append("''обсуждение не завершено''}}\n\n"); continue; } if (!day.Exists) { sb.Append("''нет обсуждений''}}\n\n"); continue; } List<string> sectionTitles = new List<string>(); foreach (WikiPageSection section in day.Page.Sections) { string filler = ""; for (int i = 0; i < section.Level - 1; ++i) { filler += "*"; } sectionTitles.Add(filler + " " + section.Title.Trim()); List<WikiPageSection> sections = new List<WikiPageSection>(); section.Reduce(sections, SubsectionsList); foreach (WikiPageSection subsection in sections) { filler = ""; for (int i = 0; i < subsection.Level - 1; ++i) { filler += "*"; } sectionTitles.Add(filler + " " + subsection.Title.Trim()); } } if (sectionTitles.Count(s => s.Contains("=")) > 0) { titles[0] = "2=<li>" + titles[0].Substring(2) + "</li>"; } sb.Append(string.Join("\n", sectionTitles.ConvertAll(c => c).ToArray())); sb.Append("}}\n\n"); } sb.Replace("<s>", ""); sb.Replace("</s>", ""); sb.Replace("<strike>", ""); sb.Replace("</strike>", ""); textBuilder.Append(sb.ToString()); textBuilder.AppendLine("{{Объединение статей/Конец}}"); if (File.Exists(fileName)) { using (TextReader sr = new StreamReader(fileName)) { string text = sr.ReadToEnd(); if (text == textBuilder.ToString()) { continue; } } } Console.Out.WriteLine("Updating " + archiveName + "..."); wiki.Save(archiveName, textBuilder.ToString(), "обновление"); using (StreamWriter sw = new StreamWriter(fileName)) { sw.Write(textBuilder.ToString()); } } }
static int Main(string[] args) { if (args.Length < 2) { Console.Out.WriteLine("NewPagesWikiBot <language> <update comment>"); return 0; } string path = @"Cache\" + args[0] + @"\"; Directory.CreateDirectory(@"Cache\" + args[0]); Wiki wiki = new Wiki(string.Format("http://{0}.wikipedia.org/w/", args[0])); wiki.SleepBetweenQueries = 5; if (string.IsNullOrEmpty(Settings.Default.Login) || string.IsNullOrEmpty(Settings.Default.Password)) { Console.Out.WriteLine("Please add login and password to the configuration file."); return 0; } Console.Out.WriteLine("Logging in as " + Settings.Default.Login + " to " + wiki.Uri + "..."); try { string cookieFile = @"Cache\" + args[0] + @"\cookie.jar"; WikiCache.Login(wiki, Settings.Default.Login, Settings.Default.Password, cookieFile); string namespacesFile = @"Cache\" + args[0] + @"\namespaces.dat"; if (!WikiCache.LoadNamespaces(wiki, namespacesFile)) { wiki.GetNamespaces(); WikiCache.CacheNamespaces(wiki, namespacesFile); } } catch (WikiException e) { Console.Out.WriteLine(e.Message); return 0; } Console.Out.WriteLine("Logged in as " + wiki.User + "."); PortalModule portal = new PortalModule(args[0], args[1]); Directory.CreateDirectory("Cache\\" + args[0] + "\\NewPages\\"); Directory.CreateDirectory("Cache\\" + args[0] + "\\PagesInCategory\\"); Directory.CreateDirectory("Cache\\" + args[0] + "\\PagesInCategoryWithTemplates\\"); Cache.PurgeCache(args[0]); if (!File.Exists("Cache\\" + args[0] + "\\processed.txt")) { FileStream stream = File.Create("Cache\\" + args[0] + "\\processed.txt"); stream.Close(); } HashSet<string> processedPages = new HashSet<string>(); using (StreamReader sr = new StreamReader("Cache\\" + args[0] + "\\processed.txt")) { String line; while ((line = sr.ReadLine()) != null) { processedPages.Add(line); } } ParameterCollection parameters = new ParameterCollection() { { "generator", "embeddedin" }, { "geititle", "User:ClaymoreBot/Новые статьи" }, { "geilimit", "max" }, { "prop", "info" }, { "intoken", "edit" }, { "redirects", "1" } }; List<string> pages = new List<string>(); XmlDocument doc = wiki.Enumerate(parameters, true); foreach (XmlNode node in doc.SelectNodes("//page")) { string title = node.Attributes["title"].Value; pages.Add(title); } pages.Sort(); for (int i = 0; i < pages.Count; ++i) { try { if (processedPages.Contains(pages[i])) { continue; } WikiPage page = Cache.Load(wiki, pages[i], path); IPortalModule module; if (TryParse(page, path, portal, out module)) { module.Update(wiki); using (StreamWriter sw = new StreamWriter("Cache\\" + args[0] + "\\processed.txt", true)) { sw.WriteLine(pages[i]); } } } catch (WikiException) { return -1; } catch (System.Net.WebException) { return -1; } } File.Delete("Cache\\" + args[0] + "\\processed.txt"); Console.Out.WriteLine("Done."); return 0; }
public void UpdatePages(Wiki wiki) { ParameterCollection parameters = new ParameterCollection(); parameters.Add("generator", "categorymembers"); parameters.Add("gcmtitle", "Категория:Википедия:Незакрытые обсуждения объединения страниц"); parameters.Add("gcmlimit", "max"); parameters.Add("gcmnamespace", "4"); parameters.Add("prop", "info"); XmlDocument doc = wiki.Enumerate(parameters, true); XmlNodeList pages = doc.SelectNodes("//page"); foreach (XmlNode page in pages) { string pageName = page.Attributes["title"].Value; string date = pageName.Substring("Википедия:К объединению/".Length); Day day = new Day(); try { day.Date = DateTime.Parse(date, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal); } catch (FormatException) { continue; } string fileName = _cacheDir + date + ".bin"; string text = LoadPageFromCache(fileName, page.Attributes["lastrevid"].Value, pageName); if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + pageName + "..."); text = wiki.LoadText(pageName); CachePage(fileName, page.Attributes["lastrevid"].Value, text); } day.Page = WikiPage.Parse(pageName, text); foreach (WikiPageSection section in day.Page.Sections) { RemoveStrikeOut(section); StrikeOutSection(section); } string newText = day.Page.Text; if (newText.Trim() == text.Trim()) { continue; } try { string revid = wiki.Save(pageName, newText, "зачёркивание заголовков"); CachePage(fileName, revid, newText); } catch (WikiException) { } } }
static void Main(string[] args) { Wiki wiki = new Wiki("http://ru.wikipedia.org/w/"); wiki.SleepBetweenQueries = 2; if (string.IsNullOrEmpty(Settings.Default.Login) || string.IsNullOrEmpty(Settings.Default.Password)) { Console.Out.WriteLine("Please add login and password to the configuration file."); return; } Console.Out.WriteLine("Logging in as " + Settings.Default.Login + "..."); try { WikiCache.Login(wiki, Settings.Default.Login, Settings.Default.Password); } catch (WikiException e) { Console.Out.WriteLine(e.Message); return; } Console.Out.WriteLine("Logged in as " + wiki.User + "."); var parameters = new ParameterCollection { {"list", "recentchanges"}, {"rcnamespace", "0"}, {"rcprop", "user"}, {"rcshow", "patrolled|!bot|!anon|!redirect"}, {"rclimit", "2500"}, {"rctype", "edit|new"}, }; if (!File.Exists("DoNotCheck.txt")) { FileStream fs = File.Create("DoNotCheck.txt"); fs.Close(); } HashSet<string> checkedUsers = new HashSet<string>(); using (StreamReader sr = new StreamReader("DoNotCheck.txt")) { string line; while ((line = sr.ReadLine()) != null) { checkedUsers.Add(line); } } HashSet<string> users = new HashSet<string>(); XmlDocument doc = wiki.Enumerate(parameters, false); foreach (XmlNode edit in doc.SelectNodes("//rc")) { string userName = edit.Attributes["user"].Value; if (!checkedUsers.Contains(userName) && !users.Contains(userName)) { users.Add(userName); } } parameters = new ParameterCollection { {"list", "users"}, {"usprop", "groups|editcount|registration"}, }; Dictionary<string, UserInfo> candidates = new Dictionary<string, UserInfo>(); int limit = 500; StringBuilder usersString = new StringBuilder(); int index = 0; foreach (string user in users) { if (index < limit) { usersString.Append("|" + user); ++index; } else { usersString.Remove(0, 1); ParameterCollection localParameters = new ParameterCollection(parameters); localParameters.Add("ususers", usersString.ToString()); doc = wiki.Enumerate(localParameters, true); using (StreamWriter sw = new StreamWriter("DoNotCheck.txt", true)) { FillInCandidates(candidates, doc.SelectNodes("//user"), sw); } index = 1; usersString = new StringBuilder("|" + user); } } if (index > 0) { usersString.Remove(0, 1); ParameterCollection localParameters = new ParameterCollection(parameters); localParameters.Add("ususers", usersString.ToString()); doc = wiki.Enumerate(localParameters, true); using (StreamWriter sw = new StreamWriter("DoNotCheck.txt", true)) { FillInCandidates(candidates, doc.SelectNodes("//user"), sw); } } StringBuilder sb = new StringBuilder("== Список ==\n"); using (StreamWriter sw = new StreamWriter("DoNotCheck.txt", true)) { foreach (var candidate in candidates) { parameters = new ParameterCollection { {"list", "logevents"}, {"leprop", "timestamp"}, {"letype", "block"}, {"letitle", "User:"******"//item") != null; if (wasBlocked) { sw.WriteLine(candidate.Key); continue; } parameters = new ParameterCollection { {"list", "usercontribs"}, {"uclimit", "500"}, {"ucnamespace", "0"}, {"ucprop", "patrolled"}, {"ucuser", candidate.Key}, }; doc = wiki.Enumerate(parameters, false); int totalEdits = doc.SelectNodes("//item").Count; int patrolledEdits = doc.SelectNodes("//item[@patrolled]").Count; Console.Out.WriteLine("{0}: {1} from {2} (was blocked? {3})", candidate.Key, patrolledEdits, totalEdits, wasBlocked ? "Yes" : "No"); if (patrolledEdits > 5 && totalEdits == 500) { sb.AppendFormat("* {{{{userlinks|{0}}}}}, всего правок: {1}, дата регистрации — {2}, отпатрулировано правок: {3}\n", candidate.Key, candidate.Value.Edits, candidate.Value.Registration == DateTime.MinValue ? "— дата неизвестна" : candidate.Value.Registration.ToUniversalTime().ToLongDateString(), patrolledEdits); } } } Console.Out.WriteLine("Википедия:Заявки на статус автопатрулируемого/Кандидаты..."); wiki.SaveSection("Википедия:Заявки на статус автопатрулируемого/Кандидаты", "1", sb.ToString(), "обновление"); }
public void Analyze(Wiki wiki) { ParameterCollection parameters = new ParameterCollection(); parameters.Add("generator", "categorymembers"); parameters.Add("gcmtitle", "Категория:Википедия:Незакрытые обсуждения объединения страниц"); parameters.Add("gcmlimit", "max"); parameters.Add("gcmnamespace", "4"); parameters.Add("prop", "info"); XmlDocument doc = wiki.Enumerate(parameters, true); XmlNodeList pages = doc.SelectNodes("//page"); List<Day> days = new List<Day>(); DateTime start = DateTime.Today; foreach (XmlNode page in pages) { string pageName = page.Attributes["title"].Value; string date = pageName.Substring("Википедия:К объединению/".Length); Day day = new Day(); try { day.Date = DateTime.Parse(date, CultureInfo.CreateSpecificCulture("ru-RU"), DateTimeStyles.AssumeUniversal); } catch (FormatException) { continue; } string fileName = _cacheDir + date + ".bin"; string text = LoadPageFromCache(fileName, page.Attributes["lastrevid"].Value, pageName); if (string.IsNullOrEmpty(text)) { Console.Out.WriteLine("Downloading " + pageName + "..."); text = wiki.LoadText(pageName); CachePage(fileName, page.Attributes["lastrevid"].Value, text); } Match m = _closedRE.Match(text); if (m.Success) { Console.Out.WriteLine("Closing " + pageName + "..."); text = text.Replace("{{ВПКОБ-Навигация}}", "{{ВПКОБ-Навигация|nocat=1}}"); wiki.Save(pageName, text, "обсуждение закрыто"); continue; } day.Page = WikiPage.Parse(pageName, text); days.Add(day); } days.Sort(CompareDays); using (StreamWriter sw = new StreamWriter(_cacheDir + "MainPage.txt")) { sw.WriteLine("== Текущие обсуждения ==\n"); sw.WriteLine("{{Объединение статей/Статьи, вынесенные для объединения}}\n"); foreach (Day day in days) { sw.Write("{{Объединение статей/День|" + day.Date.ToString("yyyy-M-d") + "|\n"); List<string> titles = new List<string>(); foreach (WikiPageSection section in day.Page.Sections) { string filler = ""; RemoveStrikeOut(section); StrikeOutSection(section); for (int i = 0; i < section.Level - 1; ++i) { filler += "*"; } titles.Add(filler + " " + section.Title.Trim()); List<WikiPageSection> sections = new List<WikiPageSection>(); section.Reduce(sections, SubsectionsList); foreach (WikiPageSection subsection in sections) { filler = ""; for (int i = 0; i < subsection.Level - 1; ++i) { filler += "*"; } titles.Add(filler + " " + subsection.Title.Trim()); } } if (titles.Count(s => s.Contains("=")) > 0) { titles[0] = "2=<li>" + titles[0].Substring(2) + "</li>"; } sw.Write(string.Join("\n", titles.ConvertAll(c => c).ToArray())); sw.Write("}}\n\n"); } sw.WriteLine("{{/Подвал}}"); } }
public void Run(Wiki wiki) { UpdatePages(wiki); Analyze(wiki); UpdateMainPage(wiki); UpdateArchives(wiki); }