protected override void ProcessPage(Page p, EditStatus edit) { if (p.GetNamespace() != 0) return; p.Load(); var changes = new List<string>(); p.InsertPlaceholders(GeneralExtensions.Placeholder.Default); foreach (var replacement in Replacements.Where(replacement => p.text.Contains(replacement.Key))) { p.text = p.text.Replace(replacement.Key, replacement.Value); changes.Add(replacement.Key + " → " + replacement.Value); } foreach (var replacement in RegexReplacements) { var pattern = replacement.Key; var replace = replacement.Value; pattern.Replace(p.text, match => { var replaceWith = RegexParseReplaceWithString(match, replace); changes.Add(match.Value + " → " + replaceWith); return replaceWith; }); } p.RemovePlaceholders(); if (changes.Count > 0) { edit.Save = true; edit.EditComment = "Ersetzt: " + string.Join(", ", changes); } }
protected override void ProcessPage(Page p, EditStatus edit) { if (p.GetNamespace() != 0) return; p.Load(); var before = p.text; var changes = new List<string>(); Match m; while ((m = MuenzenRegex.Match(p.text)).Success) { var kupfer = 0; var silber = 0; var gold = 0; int.TryParse(m.Groups["kupfer"].Value, out kupfer); int.TryParse(m.Groups["silber"].Value, out silber); int.TryParse(m.Groups["gold"].Value, out gold); var muenzen = kupfer + 100*silber + 10000*gold; p.text = p.text.Replace(m.Value.Trim(), "{{Münzen|" + muenzen + "}}"); changes.Add(string.Format("{0}g {1}s {2}k → {3}", gold, silber, kupfer, muenzen)); } if (changes.Count > 0) { edit.EditComment = string.Format("Münzen ({0}x): {1}", changes.Count, string.Join(", ", changes)); edit.Save = true; } }
public static void ConvertPage(string pageName, string newName, bool overwrite = false) { var db = new ZkDataContext(); ForumThread thread = db.ForumThreads.FirstOrDefault(x=> x.WikiKey == pageName); if (thread == null) { Console.WriteLine("No ZK wiki page with name {0} found", pageName); return; } string text = thread.ForumPosts.First().Text; text = BBCodeToMediaWiki(text); Page page = new Page(newWiki, newName); page.Load(); bool update = false; if (!page.IsEmpty()) { if (!overwrite) { Console.WriteLine("Page already exists, exiting"); return; } else update = true; } if (newName.StartsWith("Mission Editor", true, System.Globalization.CultureInfo.CurrentCulture)) page.AddToCategory("Mission Editor"); page.Save(text, update ? "" : "Ported from ZK wiki by DotNetWikiBot", update); }
public static void exec() { string[] line = System.IO.File.ReadAllLines("list"); List<string> ignorelist = new List<string>(); if (System.IO.File.Exists("resultsig")) { ignorelist.AddRange (System.IO.File.ReadAllLines("resultsig")); } if (System.IO.File.Exists("results")) { ignorelist.AddRange (System.IO.File.ReadAllLines("results")); } int processed = 1; foreach (string c in line) { if (ignorelist.Contains(c)) { continue; } try { Page afc = new Page(MainClass.en, "Wikipedia talk:" + c); afc.Load(); if ( afc.text == null || afc.text.Contains("REDIRECT") || afc.text.Contains("{{AFC") || afc.text.Contains("{{WPAFC") || afc.text == "" || afc.text.Contains("[[Category:AfC_submissions_with_missing_AfC_template]]") ) { MainClass.DebugLog("OK:" + c); System.IO.File.AppendAllText("resultsig", c + "\n"); } else { MainClass.DebugLog("Category missing:" + c); afc.text = afc.text + "\n[[Category:AfC_submissions_with_missing_AfC_template]]"; afc.Save(afc.text, "Bot: inserting [[Category:AfC_submissions_with_missing_AfC_template]]", false); processed++; System.IO.File.AppendAllText("results", c + "\n"); if (processed > 100) { MainClass.DebugLog("Finished for today"); return; } } } catch (Exception fail) { Console.WriteLine(fail.ToString()); System.IO.File.AppendAllText("errors", c + Environment.NewLine); } } MainClass.Log("end"); }
protected override void ProcessPage(Page p, EditStatus edit) { if (p.GetNamespace() != 0) return; p.Load(); var templates = p.GetAllTemplates().Where(t => t.Title.ToLower() == "infobox gegenstand"); foreach (var template in templates) { if (template.Parameters.ContainsKey("beschreibung") && _regex.IsMatch(template.Parameters["beschreibung"])) { template.Parameters["beschreibung"] = _regex.Replace(template.Parameters["beschreibung"], "[[$1]]"); template.Save(); edit.Save = true; edit.EditComment = "Attribute in Gegenstandsbeschreibung verlinkt"; } } }
protected override void ProcessPage(Page p, Job.EditStatus edit) { if(p.GetNamespace() != 0) return; p.Load(); foreach (var template in p.GetAllTemplates().Where( template => (template.Title.Equals("Ausrüstungswerte", StringComparison.OrdinalIgnoreCase) || template.Title.Equals("Rezept", StringComparison.OrdinalIgnoreCase)) && (template.Parameters.HasValueIgnoreCase("seltenheit", "Aufgestiegen") && !template.Parameters.ContainsKey("aufwertung")))) { template.InsertParameterAfter("aufwertung", "nein", "infusion2", "infusion"); template.Save(); edit.EditComment = "'aufwertung = nein' hinzugefügt"; edit.Save = true; } }
protected override void ProcessPage(Page p, EditStatus edit) { if (p.GetNamespace() != 0) return; p.Load(); //Nur Seiten mit Vorlage:Infobox NSC if (p.GetAllTemplates().All(t => t.Title.ToLower() != "infobox nsc")) return; //Nur Seiten, die eine Unterseite mit Angeboten haben... var m = Regex.Match(p.text, "\\{\\{:" + p.title + "/([^}]+)}}"); if (!m.Success) return; var subpageTitle = m.Groups[1].Value; var subpage = new Page(p.site, p.title + "/" + subpageTitle); subpage.Load(); if (!subpage.Exists()) { p.text = p.text.Replace(m.Value, ""); edit.EditComment = "Verweis auf nicht vorhandene Angebots-Unterseite „" + subpage.title + "“ entfernt"; edit.Save = true; } else { var pl2 = new PageList(p.site); pl2.FillFromLinksToPage(subpage.title); if (pl2.Count() > 1) return; var subpageContent = Regex.Replace(subpage.text, "<noinclude>.*?</noinclude>", "").Trim(); p.text = p.text.Replace(m.Value, subpageContent); subpage.text = "{{Löschantrag|[Bot] In den Hauptartikel „[[" + p.title + "]]“ verschoben}}\n" + subpage.text; subpage.Save("[Bot] In Hauptartikel „[[" + p.title + "]]“ verschoben", true); edit.EditComment = "Angebot von „" + subpage.title + "“ in den Hauptartikel verschoben"; edit.Save = true; } }
public static void exec() { string[] line = System.IO.File.ReadAllLines("list"); List<string> ignorelist = new List<string>(); if (System.IO.File.Exists("resultsig")) { ignorelist.AddRange (System.IO.File.ReadAllLines("resultsig")); } if (System.IO.File.Exists("results")) { ignorelist.AddRange (System.IO.File.ReadAllLines("results")); } foreach (string c in line) { if (ignorelist.Contains(c)) { continue; } try { Page afc = new Page(MainClass.en, "Wikipedia talk:" + c); afc.Load(); if (afc.text.Contains("REDIRECT") || afc.text.Contains("{{AFC")) { MainClass.DebugLog("OK:" + c); System.IO.File.AppendAllText("resultsig", c + "\n"); } else { MainClass.DebugLog("Template missing:" + c); System.IO.File.AppendAllText("results", c + "\n"); } } catch (Exception fail) { Console.WriteLine(fail.ToString()); System.IO.File.AppendAllText("errors", c + "." + Environment.NewLine); } } MainClass.Log("end"); }
public WikiPage(Page pg) { page = pg; if (page.text == null || page.text == "") { page.Load(); } title = page.text; ns = 0; id = long.Parse(page.pageID); //revid = long.Parse(page.lastRevisionID); //try { parentid = long.Parse(page.lastUserID); } //catch { } timestamp = page.timestamp; text = page.text; tf_IDF_Vec = new TF_IDF_Vector(); }
protected override void ProcessPage(Page p, EditStatus edit) { if (p.GetNamespace() != 0) return; p.Load(); var before = p.text; foreach (var template in p.GetAllTemplates()) { if (template.Title == "#dpl:" && template.Parameters.ContainsKey("category") && template.Parameters.ContainsKey("linksto") && template.Parameters.ContainsKey("format")) { var linksTo = template.Parameters["linksto"]; linksTo = linksTo == p.title ? "{{PAGENAME}}" : linksTo; if (template.Parameters["category"].ToLower() == "trophäe") p.text = p.text.Replace(template.Text, "Beschaffung|gegenstand=" + linksTo + "|kategorie=Trophäe"); else if (template.Parameters["category"].ToLower() == "behälter") p.text = p.text.Replace(template.Text, "Beschaffung|gegenstand=" + linksTo + "|kategorie=Behälter"); } } if (p.text.Contains("#dpl:") && p.text.Contains("Behälter")) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("{0} still contains dpl", p.title); Console.ResetColor(); } if (p.text != before) { edit.Save = true; edit.EditComment = "DPL durch {{Beschaffung}} ersetzt"; } }
protected override void ProcessPage(Page p, EditStatus edit) { if (p.GetNamespace() != 0) return; p.Load(); var allChanges = new List<string>(); var before = p.text; foreach (var template in p.GetAllTemplates()) { var templateChanges = new List<string>(); if (Replacements.ContainsKey(template.Title)) { foreach (var parameter in template.Parameters) { if (Replacements[template.Title].ContainsKey(parameter.Key)) { template.ChangeParametername(parameter.Key, Replacements[template.Title][parameter.Key]); templateChanges.Add(parameter.Key + " → " + Replacements[template.Title][parameter.Key]); } } } if (templateChanges.Count > 0) { template.Save(); allChanges.Add(template.Title + ": " + string.Join(", ", templateChanges)); } } if (allChanges.Count > 0) { edit.Save = true; edit.EditComment = "Parameter umbenannt: " + string.Join("; ", allChanges); } }
void UploadButtonClick( object sender, EventArgs ea ) { if ( string.IsNullOrEmpty( siteTextBox.Text ) || string.IsNullOrEmpty( userNameTextBox.Text ) || string.IsNullOrEmpty( passwordTextBox.Text ) || string.IsNullOrEmpty( folderTextBox.Text ) || string.IsNullOrEmpty( filesDescrTextBox.Text ) ) { MessageBox.Show( "Fill in all required data fileds, please." ); return; } this.Cursor = Cursors.WaitCursor; if ( site == null ) { try { site = new Site( siteTextBox.Text.Trim(), userNameTextBox.Text.Trim(), passwordTextBox.Text.Trim(), userDomainTextBox.Text.Trim() ); } catch ( Exception e ) { this.Cursor = Cursors.Default; MessageBox.Show( e.Message ); return; } } if ( !Directory.Exists( folderTextBox.Text ) ) { this.Cursor = Cursors.Default; MessageBox.Show( "Specified folder doesn't exist." ); return; } Regex allowedFileTypes; if ( !string.IsNullOrEmpty( fileTypesTextBox.Text ) ) { allowedFileTypes = new Regex( String.Format( "(?i)\\.({0})$", fileTypesTextBox.Text.Replace( " ", "" ).Replace( ",", "|" ) ) ); } else { allowedFileTypes = new Regex( "." ); } string[] filenames = Array.FindAll( Directory.GetFiles( folderTextBox.Text ), allowedFileTypes.IsMatch ); if ( filenames.Length == 0 ) { this.Cursor = Cursors.Default; MessageBox.Show( "Specified folder doesn't contain files, that could be uploaded." ); return; } UploadProgressBar.Visible = true; UploadProgressBar.Minimum = 0; UploadProgressBar.Maximum = filenames.Length; UploadProgressBar.Value = 0; UploadProgressBar.Step = 1; Page p = new Page( site ); string filename; for ( int i = 0; i < filenames.Length; UploadProgressBar.PerformStep(), i++ ) { filename = Path.GetFileName( filenames[i] ); p.title = site.namespaces["6"] + ":" + filename; try { p.Load(); } catch ( Exception e ) { MessageBox.Show( e.Message ); continue; } if ( p.Exists() && MessageBox.Show( String.Format( "File \"{0}\" already exists. Overwrite?", filename ), "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question ) != DialogResult.Yes ) { continue; } try { p.UploadImage( filenames[i], filesDescrTextBox.Text, "", "", "" ); } catch ( Exception e ) { MessageBox.Show( e.Message ); continue; } File.AppendAllText("UploadedFiles.txt", filenames[i] + "\r\n"); } MessageBox.Show( "Upload completed." ); UploadProgressBar.Value = 0; this.Cursor = Cursors.Default; }
public static void ReformatPage(string pageName) { Page page = new Page(newWiki, pageName); page.Load(); string text = BBCodeToMediaWiki(page.text); if (pageName.StartsWith("Mission Editor", true, System.Globalization.CultureInfo.CurrentCulture)) page.AddToCategory("Mission Editor"); page.Save(text, "Cleanup by DotNetWikiBot", false); }
public static void AddNavbox(string pageName, string template) { Page page = new Page(newWiki, pageName); page.Load(); AddNavbox(page, template); }
private bool PageIsSchauplatz(string page) { if (_schauplaetze.Contains(page)) return true; //return true if the page doesn't exist var p = new Page(Site, page); p.Load(); if(!p.Exists()) _schauplaetze.Add(page); return !p.Exists(); }
/// <summary>Gets page titles for this PageList from links in some wiki page. All links /// will be retrieved, from all namespaces, except interwiki links to other /// sites. Use FilterNamespaces() or RemoveNamespaces() function to remove pages from /// unwanted namespaces (categories, images, etc.)</summary> /// <param name="pageTitle">Page title as string.</param> /// <example><code>pageList.FillFromAllPageLinks("Art");</code></example> public void FillFromPageLinks(string pageTitle) { if (string.IsNullOrEmpty(pageTitle)) throw new ArgumentNullException("pageTitle"); Regex wikiLinkRegex = new Regex(@"\[\[ *:*(.+?)(]]|\|)"); Page page = new Page(site, pageTitle); page.Load(); MatchCollection matches = wikiLinkRegex.Matches(page.text); Regex outWikiLink = new Regex("^(" + site.generalData["interwiki"] + "):"); foreach (Match match in matches) if (!outWikiLink.IsMatch(match.Groups[1].Value)) pages.Add(new Page(site, match.Groups[1].Value)); Console.WriteLine( Bot.Msg("PageList filled with links, found on \"{0}\" page."), pageTitle); }
protected override void ProcessPage(Page p, EditStatus edit) { if (p.GetNamespace() != 0) return; p.Load(); //ignore pages which already have {{standort}} if (p.GetAllTemplates().Any(t => t.Title == "Standort")) return; var section = p.GetSectionByName("Standort", false); if (section == null) return; var standorte = new List<string>(); Match lastMatch = null; var prependText = ""; var remainingText = ""; var foundNonSchauplatz = false; var compactTemplate = true; var lines = section.Content.GetLines().Skip(1).ToList(); var addAdditionalStar = !lines.First().Contains('*') && lines.First().Length > 2 && PageIsSchauplatz(lines.First().Trim('[', ']', '\'', ';')); foreach (var line in lines) { //just add the line to the remaining text as soon as we found a non schauplatz if (foundNonSchauplatz) remainingText += "\r\n" + line; if (string.IsNullOrWhiteSpace(line)) continue; var match = StandortItemRegex.Match((addAdditionalStar ? "*" : "") + line); //if the line is no listitem and no schauplatz, we are done with the standort list //all remaining text will be added to remainingText if (!match.Success || !PageIsSchauplatz(match.Groups[2].Value)) { if (standorte.Count == 0 && lastMatch == null) { prependText += line + "\r\n"; } else { foundNonSchauplatz = true; remainingText = line; } continue; } var added = false; //has a descripting text if (match.Groups[3].Length > 0) { standorte.Add(match.Groups[2].Value + " = " + match.Groups[4].Value); compactTemplate = false; added = true; } if (lastMatch != null && match.Groups[1].Length <= lastMatch.Groups[1].Length) { //add last standorte.Add(lastMatch.Groups[2].Value + (lastMatch.Groups[4].Length > 0 ? " = " + lastMatch.Groups[4].Value : "")); lastMatch = null; } lastMatch = !added ? match : null; } if (lastMatch != null) { standorte.Add(lastMatch.Groups[2].Value + (lastMatch.Groups[4].Length > 0 ? " = " + lastMatch.Groups[4].Value : "")); } if (standorte.Count == 0) return; if (!foundNonSchauplatz) remainingText += "\r\n"; if (standorte.Count > 3) compactTemplate = false; //build the new section content section.Content = section.Content.GetLines().First() + "\r\n" + prependText + (compactTemplate ? "{{Standort|" + string.Join("|", standorte) + "}}" : "{{Standort\r\n | " + string.Join("\r\n | ", standorte) + "\r\n}}") + "\r\n" + remainingText; section.Save(); edit.Save = true; edit.EditComment = "/* "+section.Title+" */ [[Benutzer: Darthmaim Bot/Projekte#Standort|Standortvorlage eingebaut]] ("+standorte.Count+")"; }
public static void DoStuff() { string username = ""; string password = ""; Console.WriteLine("Enter wiki username: "******"Enter wiki password: "******"G:\zkwiki\output\markup")); files = files.Shuffle(); foreach (string path in files) { string unitname = Path.GetFileNameWithoutExtension(path); unitname = unitname.Replace("/", "/"); var page = new Page(newWiki, unitname); page.Load(); if (page.Exists()) { // do nothing } else { var text = File.ReadAllText(path); Console.WriteLine("-- Making page {0} --", unitname); page.Save(text, "Created page from unitguide builder export", false); count++; //if (count >= 20) break; } } string[,] toPort = { //{"MissionEditorCompatibility", "Mission Editor game compatibility"}, //{"MissionEditorStartPage", "Mission Editor"}, //{"MissionEditorWINE", "Mission Editor in WINE"}, //{"FactoryOrdersTutorial", "Mission Editor Factory Orders Tutorial"}, //{"MissionEditorTutorial", "Mission Editor Tutorial"}, //{"MissionEditorCutsceneTutorial", "Mission Editor Cutscenes Tutorial"} }; for (int i=0; i<toPort.GetLength(0); i++) { ConvertPage(toPort[i, 0], toPort[i, 1], false); } string[] toReformat = { //"Mission Editor Cutscenes Tutorial" }; for (int i = 0; i < toReformat.GetLength(0); i++) { ReformatPage(toReformat[i]); } }
/// <summary>Gets page titles for this PageList from links in some wiki page. All links /// will be retrieved, from all namespaces, except interwiki links to other /// sites. Use <see cref="PageList.FilterNamespaces(int[])"/> or /// <see cref="PageList.RemoveNamespaces(int[])"/> function to remove pages from /// unwanted namespaces (categories, images, etc.)</summary> /// <param name="pageTitle">Page title as string.</param> /// <example><code>pageList.FillFromAllPageLinks("Art");</code></example> public void FillFromPageLinks(string pageTitle) { if (string.IsNullOrEmpty(pageTitle)) throw new ArgumentNullException("pageTitle"); Regex wikiLinkRegex = new Regex(@"\[\[ *:*(.+?)(]]|\|)"); Page page = new Page(site, pageTitle); page.Load(); MatchCollection matches = wikiLinkRegex.Matches(page.text); Regex outWikiLink = new Regex("^(" + site.generalData["interwiki"] + "):"); foreach (Match match in matches) { string link = match.Groups[1].Value; if (outWikiLink.IsMatch(link)) continue; if (link[0] == '/') // relative link link = pageTitle + link; if (link.Contains('_')) link = link.Replace(' ', '_'); if (!this.Contains(link)) pages.Add(new Page(site, link)); } Console.WriteLine( Bot.Msg("PageList has been filled with links found on \"{0}\" page."), pageTitle); }
protected override void ProcessPage(Page p, EditStatus edit) { if (p.GetNamespace() != 0) return; p.Load(); var changes = new List<string>(); var templates = p.GetAllTemplates(); foreach (var template in templates) { if (template.Title == "Rezept") { if (template.Parameters.ContainsKey("seltenheit") && new[] {"meisterwerk", "selten", "exotisch", "legendär"}.Contains( template.Parameters["seltenheit"].ToLower()) && template.Parameters.ContainsKey("gebunden") && template.Parameters["gebunden"].ToLower() == "benutzung") { template.Parameters.Remove("gebunden"); template.Save(); changes.Add("Rezept: 'gebunden = benutzung' entfernt"); } } else if (template.Title == "Eventbelohnung") { string[] parametersToRemove = { "ep-gold", "ep-silber", "ep-bronze", "ep-gold-niederlage", "ep-silber-niederlage", "ep-bronze-niederlage", "ep-niederlage", "karma-gold", "karma-silber", "karma-bronze", "karma-gold-niederlage", "karma-silber-niederlage", "karma-bronze-niederlage", "karma-niederlage", "münzen-gold", "münzen-silber", "münzen-bronze", "münzen-gold-niederlage", "münzen-silber-niederlage", "münzen-bronze-niederlage", "münzen-niederlage" }; var removed = new List<string>(); foreach (var parameter in parametersToRemove) { if (template.Parameters.ContainsKey(parameter)) { template.Parameters.Remove(parameter); removed.Add(parameter); } } if (removed.Any()) { template.Save(); changes.Add("Eventbelohnung: '" + string.Join("', '", removed) + "' entfernt"); } } else if (template.Title == "Infobox Aufgabe") { string[] parametersToRemove = { "erfahrung", "münzen" }; var removed = new List<string>(); foreach (var parameter in parametersToRemove) { if (template.Parameters.ContainsKey(parameter)) { template.Parameters.Remove(parameter); removed.Add(parameter); } } if (removed.Any()) { template.Save(); changes.Add("Infobox Aufgabe: '" + string.Join("', '", removed) + "' entfernt"); } } else if (template.Title == "Infobox Farbstoff") { string[] parametersToRemove = { "seltenheit" }; var removed = new List<string>(); foreach (var parameter in parametersToRemove) { if (template.Parameters.ContainsKey(parameter)) { template.Parameters.Remove(parameter); removed.Add(parameter); } } if (removed.Any()) { template.Save(); changes.Add("Infobox Farbstoff: '" + string.Join("', '", removed) + "' entfernt"); } } } if (changes.Count == 0) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\tUnbekannt..."); Console.ResetColor(); } else { Console.ForegroundColor = ConsoleColor.White; var comment = "Überflüssige Parameter entfernt: " + string.Join("; ", changes); Console.WriteLine("\t" + comment); Console.ResetColor(); edit.EditComment = comment; edit.Save = true; } }
public void LoadPage(Page page) { page.Load(); Invoke(IncrementPagesLoaded); }
protected override void ProcessPage(Page p, EditStatus edit) { var changes = new List<string>(); if (p.GetNamespace() != 0) return; p.Load(); var templates = p.GetAllTemplates(); foreach (var template in templates) { var changeCountBeforeTemplate = changes.Count; #region [G] Infobox Gegenstand if (template.Title.Equals("Infobox Gegenstand", StringComparison.OrdinalIgnoreCase)) { //stapelbar = ja/###/... if (template.Parameters.HasNotValueIgnoreCase("stapelbar", "nein")) { changes.Add(string.Format("'stapelbar = {0}' entfernt", template.Parameters["stapelbar"])); template.Parameters.Remove("stapelbar"); } //wert -> händlerwert if (template.Parameters.ContainsKey("wert")) { //wenn händlerwert schon existiert löschen if (template.Parameters.ContainsKey("händlerwert")) { template.Parameters.Remove("wert"); changes.Add("'wert' entfernt"); } else { template.ChangeParametername("wert", "händlerwert"); changes.Add("'wert' zu 'händlerwert' geändert"); } } //seelengebunden = ja -> gebunden = seele if (template.Parameters.HasValueIgnoreCase("seelengebunden", "ja")) { //wenn gebunden schon existiert löschen if (template.Parameters.ContainsKey("gebunden")) { changes.Add(string.Format("'seelengebunden = {0}' entfernt", template.Parameters["seelengebunden"])); template.Parameters.Remove("seelengebunden"); } else { changes.Add(string.Format("'seelengebunden = {0}' zu 'gebunden = seele' geändert", template.Parameters["seelengebunden"])); template.ChangeParametername("seelengebunden", "gebunden"); template.Parameters["gebunden"] = "seele"; } } //seltenheit = ramsch -> seltenheit = scrhott if (template.Parameters.HasValueIgnoreCase("seltenheit", "ramsch")) { changes.Add(string.Format("'seltenheit = {0}' zu 'seltenheit = Schrott' geändert", template.Parameters["seltenheit"])); template.Parameters["seltenheit"] = "Schrott"; } //benutzungen = 1 if (template.Parameters.HasValue("benutzungen","1")) { changes.Add("'benutzungen = 1' entfernt"); template.Parameters.Remove("benutzungen"); } } #endregion #region [J] Angebot if (template.Title.Equals("angebot", StringComparison.OrdinalIgnoreCase)) { //seltenheit = ja entfernen if (template.Parameters.HasValueIgnoreCase("seltenheit", "ja")) { changes.Add("'seltenheit = ja' entfernt"); template.Parameters.Remove("seltenheit"); } //stufe = ja entfernen if (template.Parameters.HasValueIgnoreCase("stufe", "ja")) { changes.Add("'stufe = ja' entfernt"); template.Parameters.Remove("stufe"); } //typ = ja entfernen if (template.Parameters.HasValueIgnoreCase("typ", "ja")) { changes.Add("'typ = ja' entfernt"); template.Parameters.Remove("typ"); } //werte = ja entfernen if (template.Parameters.HasValueIgnoreCase("werte", "ja")) { changes.Add("'werte = ja' entfernt"); template.Parameters.Remove("werte"); } } #endregion #region [R] Rezept if (template.Title.Equals("Rezept", StringComparison.OrdinalIgnoreCase)) { var changedSomething = false; for (var i = 1; i <= 4; i++) { var key = "attribut" + i + "-wert"; if (template.Parameters.ContainsKey(key) && template.Parameters[key].StartsWith("+")) { template.Parameters[key] = template.Parameters[key].TrimStart('+'); changedSomething = true; } } if (changedSomething) changes.Add("Überflüssiges + aus dem [[Vorlage:Rezept|Rezept]] " + (template.Parameters.ContainsKey("name") ? template.Parameters["name"] : p.title) + " entfernt"); //anzahl = 1 if (template.Parameters.ContainsKey("anzahl") && template.Parameters["anzahl"] == "1") { changes.Add("'anzahl = 1' entfernt"); template.Parameters.Remove("anzahl"); } //gebunden = benutzung bei seltenheit meisterwerk/selten/exotisch/legendär entfernen if (template.Parameters.HasValueIgnoreCase("gebunden", "benutzung") && template.Parameters.HasValueIgnoreCase("seltenheit", "meisterwerk", "selten", "exotisch", "legendär")) { changes.Add(string.Format("'gebunden = {0}' entfernt, da 'seltenheit = {1}'", template.Parameters["gebunden"], template.Parameters["seltenheit"])); template.Parameters.Remove("gebunden"); } } #endregion if (changeCountBeforeTemplate != changes.Count) template.Save(); } if (changes.Count == 0) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\tUnbekannt..."); Console.ResetColor(); } else { Console.ForegroundColor = ConsoleColor.White; var comment = "Parameterfehler behoben: " + string.Join("; ", changes); Console.WriteLine("\t" + comment); Console.ResetColor(); edit.EditComment = comment; edit.Save = true; } }
/// <summary>Gets page titles for this PageList from all links in some wiki page. All links /// will be retrieved, from all standard namespaces, except interwiki links to other /// sites. Use FillFromPageLinks function instead to filter namespaces /// automatically.</summary> /// <param name="pageTitle">Page title as string.</param> /// <example><code>pageList.FillFromAllPageLinks("Art");</code></example> public void FillFromAllPageLinks(string pageTitle) { if (string.IsNullOrEmpty(pageTitle)) throw new ArgumentNullException("pageTitle"); if (string.IsNullOrEmpty(Site.WMLangsStr)) site.GetWikimediaWikisList(); Regex wikiLinkRE = new Regex(@"\[\[:*(.+?)(]]|\|)"); Page page = new Page(site, pageTitle); page.Load(); MatchCollection matches = wikiLinkRE.Matches(page.text); Regex outWikiLink = new Regex("^(" + Site.WMLangsStr + /*"|" + Site.WMSitesStr + */ "):"); foreach (Match match in matches) if (!outWikiLink.IsMatch(match.Groups[1].Value)) pages.Add(new Page(site, match.Groups[1].Value)); Bot.LogEvent( Bot.Msg("PageList filled with links, found on \"{0}\" page."), pageTitle); }
private static bool UploadFile(string fileToUpload) { logger.Info("Logging into Wiki"); string siteurl = "http://commons.wikimedia.org"; //string siteurl = "http://vgsales.wikia.com"; //string siteurl = "http://w3stfa11.limewebs.com/wiki/index.php?title=Main_Page"; Site wikiSite; Page page; try { wikiSite = new Site(siteurl, Configuration.WikiUsername, Configuration.WikiPassword); //wikiSite = new Site(siteurl, "abc", "123"); //limewebs page = new Page(wikiSite,videoInfo.Title); } catch (Exception e) { logger.Error("Unable to login to: " + siteurl + " error:" + e.Message + e.StackTrace + e.Source + e.InnerException + "\n" +e.Data); return false; } string fileNamespace = "6"; string fileName = Path.GetFileName(fileToUpload); page.title = wikiSite.namespaces[fileNamespace] + ":" + fileName; StringBuilder sb = new StringBuilder(); sb.AppendLine("{{Information"); sb.AppendLine("|Description = {{en|1=" + videoInfo.Description + "}}"); sb.AppendFormat("|Source = originally posted to '''[[Flickr]]''' as [{0} {1}]", videoInfo.SourceUrl, videoInfo.Title); sb.AppendLine(); sb.AppendLine("|Date = " + videoInfo.Date); sb.AppendLine("|Author = " + videoInfo.Author); sb.AppendLine("|Permission = " + GetLicenseTemplate(videoInfo.License)); sb.AppendLine("|Other versions = "); sb.AppendLine("}}"); string wikitext = sb.ToString(); logger.Info("--------------\n" + wikitext); try { page.Load(); } catch(Exception ex) { return false; } if (page.Exists()) { int x = 0; //return false; } try { logger.InfoFormat("Uploading {0} to Wiki", fileToUpload); page.UploadImage(fileToUpload, wikitext, "", "", ""); logger.Info("Complete upload to Wiki"); } catch (Exception ex) { logger.Error("Error in UploadFile: " + ex.Message + Environment.NewLine + "fileToUpload: " + fileToUpload + ex.GetBaseException()); } return true; }
private static bool UploadOriginalVersion(out string failureReason, Page page, string mediaUrl, string wikiImageFilename, string picasaImageFilename, bool fetchThumbnailVersion, bool allowWikiBigger) { // if (!wikiImageFilename.ToLower().EndsWith(".jpg") && !wikiImageFilename.ToLower().EndsWith(".jpeg") && // !wikiImageFilename.ToLower().EndsWith(".png")) // { // failureReason = "Cannot compare non-bitmap files to original source - requires manual validation"; // return false; // } failureReason = null; Bitmap wikiBitmap = new Bitmap(wikiImageFilename); // First have the Picasa server resize to the desired size - this will // ensure exactly the same resizing algorithm is used. string thumbnailUrl = new Regex("^(.*)/([^/]*)$").Replace(mediaUrl, "${1}/s" + wikiBitmap.Width + "/${2}"); string filename = "temp_picasa_image"; if (!fetchThumbnailVersion || !WgetToFile(thumbnailUrl, filename)) { filename = picasaImageFilename; } Bitmap picasaBitmap = new Bitmap(filename); if (wikiBitmap.Width < picasaBitmap.Width || wikiBitmap.Height < picasaBitmap.Height) { // Couldn't get version of same size from server - stretch to fit Bitmap newPicasaBitmap = new Bitmap(picasaBitmap, wikiBitmap.Width, wikiBitmap.Height); picasaBitmap.Dispose(); picasaBitmap = newPicasaBitmap; } bool wikiBitmapIsBigger = false; if (wikiBitmap.Width >= picasaBitmap.Width || wikiBitmap.Height >= picasaBitmap.Height) { if (allowWikiBigger) { wikiBitmapIsBigger = true; Bitmap newWikiBitmap = new Bitmap(wikiBitmap, picasaBitmap.Width, picasaBitmap.Height); wikiBitmap.Dispose(); wikiBitmap = newWikiBitmap; } else { // Wiki version is bigger, something odd going on, skip it wikiBitmap.Dispose(); picasaBitmap.Dispose(); failureReason = "license matches and is valid - but Commons version is of a different size than the Picasa version, may have been edited locally"; return false; } } double avgDiff = ImagesMeanSquareDifference(wikiBitmap, picasaBitmap); wikiBitmap.Dispose(); picasaBitmap.Dispose(); if (avgDiff >= 0.032 && avgDiff < 0.10) { failureReason = "license matches and is valid - but Picasa and Commons image were not a close enough match"; return false; } else if (avgDiff < 0.032) { // Got an approximate match, need to upload the full-size version // (unless we've done so before and were reverted) PageList pageHistory = new PageList(page.site); pageHistory.FillFromPageHistory(page.title, int.MaxValue); bool alreadyUploaded = false; foreach (Page revision in pageHistory) { if (revision.lastUser == username && revision.comment.Contains("uploaded a new version")) { alreadyUploaded = true; } } if (!alreadyUploaded && !wikiBitmapIsBigger) { string saveText = page.text; page.UploadImage(picasaImageFilename, "Uploading version from source, revert me if incorrect", "", "", ""); // Set back to current wikitext page.Load(); page.text = saveText; } return true; } else { failureReason = "license matches and is valid - but Picasa and Commons image do not match"; return false; } }
protected override void ProcessPage(Page p, EditStatus edit) { if (p.GetNamespace() != 0) return; p.Load(); var before = p.text; var templates = p.GetAllTemplates().Where(t => t.Title.ToLower() == "fehlende informationen"); foreach (var template in templates) { var fehlendeInformation = template.Parameters["0"].Trim(); if(fehlendeInformation.ToLower() == "interwiki" || fehlendeInformation.ToLower() == "fr" || fehlendeInformation.ToLower() == "en" || fehlendeInformation.ToLower() == "es") { RemoveTemplate(p, template); edit.Save = true; edit.EditComment = "[[Vorlage:Fehlende Informationen]] entfernt (nur interwiki)"; } else if (fehlendeInformation == "") { RemoveTemplate(p, template); edit.Save = true; edit.EditComment = "[[Vorlage:Fehlende Informationen]] entfernt (leer)"; } else { var modifiedFehlendeInformationen = fehlendeInformation; while(true) { var match = _regex.Match(modifiedFehlendeInformationen); if (!match.Success) break; modifiedFehlendeInformationen = _regex.Replace(modifiedFehlendeInformationen, "", 1); } if (modifiedFehlendeInformationen == fehlendeInformation) continue; var removed = fehlendeInformation.FindRemovedPart(modifiedFehlendeInformationen); modifiedFehlendeInformationen = modifiedFehlendeInformationen.RemoveTrailingPunctuation(); if (string.IsNullOrWhiteSpace(modifiedFehlendeInformationen)) { RemoveTemplate(p, template); edit.Save = true; edit.EditComment = string.Format("[[Vorlage:Fehlende Informationen]] entfernt (Inhalt war: „{0}“)", fehlendeInformation); } else { p.text = p.text.Replace(fehlendeInformation, modifiedFehlendeInformationen); edit.Save = true; edit.EditComment = string.Format("Aus fehlenden Informationen entfernt: „{0}“", removed); } } } }