/
warninggallery.go
91 lines (83 loc) · 2.33 KB
/
warninggallery.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"bytes"
mwclient "cgt.name/pkg/go-mwclient"
"fmt"
"sort"
"strings"
)
type warning struct {
title string
warning string
warningLower string // Lower case version for string-insensitive sort.
}
type warnings []warning
// Sort interface functions.
func (warnings warnings) Len() int {
return len(warnings)
}
func (warnings warnings) Less(i, j int) bool {
return warnings[i].warningLower < warnings[j].warningLower
}
func (warnings warnings) Swap(i, j int) {
warnings[i], warnings[j] = warnings[j], warnings[i]
}
func (warnings *warnings) Append(files []fileData) {
for i := range files {
if files[i].warning != "" {
trimmed := strings.TrimSpace(files[i].warning)
*warnings = append(*warnings, warning{files[i].title, trimmed, strings.ToLower(trimmed)})
}
}
}
// Create a gallery showing all the files with warnings. Page must already
// exist and will be replaced.
func (warnings warnings) createGallery(gallery string, client *mwclient.Client) {
var saveError error
sort.Sort(warnings)
for i := 0; i < 3; i++ {
_, timestamp, err := client.GetPageByName(gallery)
if err != nil {
panic(fmt.Sprintf("%v %v", gallery, err))
}
// Blank the page and create a fresh gallery
var buffer bytes.Buffer
buffer.WriteString("<gallery>\n")
for w := range warnings {
buffer.WriteString(warnings[w].title)
buffer.WriteByte('|')
// Replace problematic text
desc := warnings[w].warning
if strings.Contains(desc, "http:") {
desc = "URL omitted" // Some URLs are blacklisted and gallery won't save
}
desc = strings.Replace(desc, "|", "<nowiki>|</nowiki>", -1)
desc = strings.Replace(desc, "\n", "<br>", -1)
if len(desc) > 200 {
buffer.WriteString(desc[0:200])
buffer.WriteString("...")
} else {
buffer.WriteString(desc)
}
buffer.WriteByte('\n')
}
buffer.WriteString("</gallery>")
editcfg := map[string]string{
"action": "edit",
"title": gallery,
"text": buffer.String(),
"bot": "",
"basetimestamp": timestamp,
}
saveError = client.Edit(editcfg)
if saveError != nil && strings.Contains(saveError.Error(), "edit successful, but did not change page") {
saveError = nil
}
if saveError == nil {
break
}
}
if saveError != nil {
panic(fmt.Sprintf("Failed to save %v %v", gallery, saveError))
}
}