-
Notifications
You must be signed in to change notification settings - Fork 6
/
watchlist.py
192 lines (170 loc) · 6.45 KB
/
watchlist.py
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# -*- coding: utf-8 -*-
"""
Allows access to the bot account's watchlist.
The function refresh() downloads the current watchlist and saves it to disk. It
is run automatically when a bot first tries to save a page retrieved. The
watchlist can be updated manually by running this script. The list will also
be reloaded automatically once a month.
Syntax: python watchlist [-all]
Command line options:
-all - Reloads watchlists for all wikis where a watchlist is already
present
-new - Load watchlists for all wikis where accounts is setting in
user-config.py
"""
#
# (C) Daniel Herding, 2005
# (C) Pywikipedia bot team, 2005-2012
#
# Distributed under the terms of the MIT license.
#
__version__='$Id: watchlist.py 10255 2012-05-26 13:23:03Z xqt $'
#
import wikipedia as pywikibot
import re, sys, pickle
import os.path
import time
cache = {}
def get(site = None):
if site is None:
site = pywikibot.getSite()
if site in cache:
# Use cached copy if it exists.
watchlist = cache[site]
else:
fn = pywikibot.config.datafilepath('watchlists',
'watchlist-%s-%s.dat' % (site.family.name, site.lang))
try:
# find out how old our saved dump is (in seconds)
file_age = time.time() - os.path.getmtime(fn)
# if it's older than 1 month, reload it
if file_age > 30 * 24 * 60 * 60:
pywikibot.output(
u'Copy of watchlist is one month old, reloading')
refresh(site)
except OSError:
# no saved watchlist exists yet, retrieve one
refresh(site)
f = open(fn, 'r')
watchlist = pickle.load(f)
f.close()
# create cached copy
cache[site] = watchlist
return watchlist
def isWatched(pageName, site=None):
watchlist = get(site)
return pageName in watchlist
def refresh(site, sysop=False):
if not site.has_api() or site.versionnumber() < 10:
_refreshOld(site)
# get watchlist special page's URL
if not site.loggedInAs(sysop=sysop):
site.forceLogin(sysop=sysop)
params = {
'action': 'query',
'list': 'watchlist',
'wllimit': pywikibot.config.special_page_limit,
'wlprop': 'title',
}
pywikibot.output(u'Retrieving watchlist for %s via API.' % repr(site))
#pywikibot.put_throttle() # It actually is a get, but a heavy one.
watchlist = []
while True:
data = pywikibot.query.GetData(params, site, sysop=sysop)
if 'error' in data:
raise RuntimeError('ERROR: %s' % data)
watchlist.extend([w['title'] for w in data['query']['watchlist']])
if 'query-continue' in data:
params['wlstart'] = data['query-continue']['watchlist']['wlstart']
else:
break
# Save the watchlist to disk
# The file is stored in the watchlists subdir. Create if necessary.
if sysop:
f = open(pywikibot.config.datafilepath('watchlists',
'watchlist-%s-%s-sysop.dat'
% (site.family.name, site.lang)),
'w')
else:
f = open(pywikibot.config.datafilepath('watchlists',
'watchlist-%s-%s.dat'
% (site.family.name, site.lang)),
'w')
pickle.dump(watchlist, f)
f.close()
def _refreshOld(site, sysop=False):
# get watchlist special page's URL
path = site.watchlist_address()
pywikibot.output(u'Retrieving watchlist for %s' % repr(site))
#pywikibot.put_throttle() # It actually is a get, but a heavy one.
watchlistHTML = site.getUrl(path, sysop=sysop)
pywikibot.output(u'Parsing watchlist')
watchlist = []
for itemR in [re.compile(r'<li><input type="checkbox" name="id\[\]" value="(.+?)" />'),
re.compile(r'<li><input name="titles\[\]" type="checkbox" value="(.+?)" />')]:
for m in itemR.finditer(watchlistHTML):
pageName = m.group(1)
watchlist.append(pageName)
# Save the watchlist to disk
# The file is stored in the watchlists subdir. Create if necessary.
if sysop:
f = open(pywikibot.config.datafilepath('watchlists',
'watchlist-%s-%s-sysop.dat'
% (site.family.name, site.lang)),
'w')
else:
f = open(pywikibot.config.datafilepath('watchlists',
'watchlist-%s-%s.dat'
% (site.family.name, site.lang)),
'w')
pickle.dump(watchlist, f)
f.close()
def refresh_all(new = False, sysop=False):
if new:
import config
pywikibot.output(
'Downloading All watchlists for your accounts in user-config.py')
for family in config.usernames:
for lang in config.usernames[ family ]:
refresh(pywikibot.getSite(code=lang, fam=family), sysop=sysop)
for family in config.sysopnames:
for lang in config.sysopnames[family]:
refresh(pywikibot.getSite(code=lang, fam=family), sysop=sysop)
else:
import dircache, time
filenames = dircache.listdir(
pywikibot.config.datafilepath('watchlists'))
watchlist_filenameR = re.compile('watchlist-([a-z\-:]+).dat')
for filename in filenames:
match = watchlist_filenameR.match(filename)
if match:
arr = match.group(1).split('-')
family = arr[0]
lang = '-'.join(arr[1:])
refresh(pywikibot.getSite(code = lang, fam = family))
def main():
all = False
new = False
sysop = False
for arg in pywikibot.handleArgs():
if arg == '-all' or arg == '-update':
all = True
elif arg == '-new':
new = True
elif arg == '-sysop':
sysop = True
if all:
refresh_all(sysop=sysop)
elif new:
refresh_all(new, sysop=sysop)
else:
refresh(pywikibot.getSite(), sysop=sysop)
watchlist = get(pywikibot.getSite())
pywikibot.output(u'%i pages in the watchlist.' % len(watchlist))
for pageName in watchlist:
pywikibot.output( pageName, toStdout = True )
if __name__ == "__main__":
try:
main()
finally:
pywikibot.stopme()