-
Notifications
You must be signed in to change notification settings - Fork 89
/
client.py
1483 lines (1233 loc) · 61.6 KB
/
client.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
import logging
from collections import OrderedDict
import json
import requests
from requests.auth import HTTPBasicAuth, AuthBase
from requests_oauthlib import OAuth1
import mwclient.errors as errors
import mwclient.listing as listing
from mwclient.sleep import Sleepers
from mwclient.util import parse_timestamp, read_in_chunks
__version__ = '0.10.1'
log = logging.getLogger(__name__)
USER_AGENT = 'mwclient/{} ({})'.format(__version__,
'https://github.com/mwclient/mwclient')
class Site:
"""A MediaWiki site identified by its hostname.
Examples:
>>> import mwclient
>>> wikipedia_site = mwclient.Site('en.wikipedia.org')
>>> wikia_site = mwclient.Site('vim.wikia.com', path='/')
Args:
host (str): The hostname of a MediaWiki instance. Must not include a
scheme (e.g. `https://`) - use the `scheme` argument instead.
path (str): The instances script path (where the `index.php` and `api.php` scripts
are located). Must contain a trailing slash (`/`). Defaults to `/w/`.
ext (str): The file extension used by the MediaWiki API scripts. Defaults to
`.php`.
pool (requests.Session): A preexisting :class:`~requests.Session` to be used when
executing API requests.
retry_timeout (int): The number of seconds to sleep for each past retry of a
failing API request. Defaults to `30`.
max_retries (int): The maximum number of retries to perform for failing API
requests. Defaults to `25`.
wait_callback (Callable): A callback function to be executed for each failing
API request.
clients_useragent (str): A prefix to be added to the default mwclient user-agent.
Should follow the pattern `'{tool_name}/{tool_version} ({contact})'`. Check
the `User-Agent policy <https://meta.wikimedia.org/wiki/User-Agent_policy>`_
for more information.
max_lag (int): A `maxlag` parameter to be used in `index.php` calls. Consult the
`documentation <https://www.mediawiki.org/wiki/Manual:Maxlag_parameter>`_ for
more information. Defaults to `3`.
compress (bool): Whether to request and accept gzip compressed API responses.
Defaults to `True`.
force_login (bool): Whether to require authentication when editing pages. Set to
`False` to allow unauthenticated edits. Defaults to `True`.
do_init (bool): Whether to automatically initialize the :py:class:`Site` on
initialization. When set to `False`, the :py:class:`Site` must be initialized
manually using the :py:meth:`.site_init` method. Defaults to `True`.
httpauth (Union[tuple[basestring, basestring], requests.auth.AuthBase]): An
authentication method to be used when making API requests. This can be either
an authentication object as provided by the :py:mod:`requests` library, or a
tuple in the form `{username, password}`. Usernames and passwords provided as
text strings are encoded as UTF-8. If dealing with a server that cannot
handle UTF-8, please provide the username and password already encoded with
the appropriate encoding.
reqs (Dict[str, Any]): Additional arguments to be passed to the
:py:meth:`requests.Session.request` method when performing API calls. If the
`timeout` key is empty, a default timeout of 30 seconds is added.
consumer_token (str): OAuth1 consumer key for owner-only consumers.
consumer_secret (str): OAuth1 consumer secret for owner-only consumers.
access_token (str): OAuth1 access key for owner-only consumers.
access_secret (str): OAuth1 access secret for owner-only consumers.
client_certificate (Union[str, tuple[str, str]]): A client certificate to be added
to the session.
custom_headers (Dict[str, str]): A dictionary of custom headers to be added to all
API requests.
scheme (str): The URI scheme to use. This should be either `http` or `https` in
most cases. Defaults to `https`.
Raises:
RuntimeError: The authentication passed to the `httpauth` parameter is invalid.
You must pass either a tuple or a :class:`requests.auth.AuthBase` object.
errors.OAuthAuthorizationError: The OAuth authorization is invalid.
errors.LoginError: Login failed, the reason can be obtained from e.code and e.info
(where e is the exception object) and will be one of the API:Login errors. The
most common error code is "Failed", indicating a wrong username or password.
"""
api_limit = 500
def __init__(self, host, path='/w/', ext='.php', pool=None, retry_timeout=30,
max_retries=25, wait_callback=lambda *x: None, clients_useragent=None,
max_lag=3, compress=True, force_login=True, do_init=True, httpauth=None,
reqs=None, consumer_token=None, consumer_secret=None, access_token=None,
access_secret=None, client_certificate=None, custom_headers=None,
scheme='https'):
# Setup member variables
self.host = host
self.path = path
self.ext = ext
self.credentials = None
self.compress = compress
self.max_lag = str(max_lag)
self.force_login = force_login
self.requests = reqs or {}
self.scheme = scheme
if 'timeout' not in self.requests:
self.requests['timeout'] = 30 # seconds
if consumer_token is not None:
auth = OAuth1(consumer_token, consumer_secret, access_token, access_secret)
elif isinstance(httpauth, (list, tuple)):
# workaround weird requests default to encode as latin-1
# https://github.com/mwclient/mwclient/issues/315
# https://github.com/psf/requests/issues/4564
httpauth = [
it.encode("utf-8") if isinstance(it, str) else it for it in httpauth
]
auth = HTTPBasicAuth(*httpauth)
elif httpauth is None or isinstance(httpauth, (AuthBase,)):
auth = httpauth
else:
# FIXME: Raise a specific exception instead of a generic RuntimeError.
raise RuntimeError('Authentication is not a tuple or an instance of AuthBase')
self.sleepers = Sleepers(max_retries, retry_timeout, wait_callback)
# Site properties
self.blocked = False # Whether current user is blocked
self.hasmsg = False # Whether current user has new messages
self.groups = [] # Groups current user belongs to
self.rights = [] # Rights current user has
self.tokens = {} # Edit tokens of the current user
self.version = None
self.namespaces = self.default_namespaces
self.writeapi = False
# Setup connection
if pool is None:
self.connection = requests.Session()
self.connection.auth = auth
if client_certificate:
self.connection.cert = client_certificate
# Set User-Agent header field
if clients_useragent:
ua = clients_useragent + ' ' + USER_AGENT
else:
ua = USER_AGENT
self.connection.headers['User-Agent'] = ua
if custom_headers:
self.connection.headers.update(custom_headers)
else:
self.connection = pool
# Page generators
self.pages = listing.PageList(self)
self.categories = listing.PageList(self, namespace=14)
self.images = listing.PageList(self, namespace=6)
# Compat page generators
self.Pages = self.pages
self.Categories = self.categories
self.Images = self.images
# Initialization status
self.initialized = False
# Upload chunk size in bytes
self.chunk_size = 1048576
if do_init:
try:
self.site_init()
except errors.APIError as e:
if e.args[0] == 'mwoauth-invalid-authorization':
raise errors.OAuthAuthorizationError(self, e.code, e.info)
# Private wiki, do init after login
if e.args[0] not in {'unknown_action', 'readapidenied'}:
raise
def site_init(self):
"""Populates the object with information about the current user and site. This is
done automatically when creating the object, unless explicitly disabled using the
`do_init=False` constructor argument."""
if self.initialized:
info = self.get('query', meta='userinfo', uiprop='groups|rights')
userinfo = info['query']['userinfo']
self.username = userinfo['name']
self.groups = userinfo.get('groups', [])
self.rights = userinfo.get('rights', [])
self.tokens = {}
return
meta = self.get('query', meta='siteinfo|userinfo',
siprop='general|namespaces', uiprop='groups|rights',
retry_on_error=False)
# Extract site info
self.site = meta['query']['general']
self.namespaces = {
namespace['id']: namespace.get('*', '')
for namespace in meta['query']['namespaces'].values()
}
self.writeapi = 'writeapi' in self.site
self.version = self.version_tuple_from_generator(self.site['generator'])
# Require MediaWiki version >= 1.16
self.require(1, 16)
# User info
userinfo = meta['query']['userinfo']
self.username = userinfo['name']
self.groups = userinfo.get('groups', [])
self.rights = userinfo.get('rights', [])
self.initialized = True
@staticmethod
def version_tuple_from_generator(string, prefix='MediaWiki '):
"""Return a version tuple from a MediaWiki Generator string.
Example:
>>> Site.version_tuple_from_generator("MediaWiki 1.5.1")
(1, 5, 1)
Args:
string (str): The MediaWiki Generator string.
prefix (str): The expected prefix of the string.
Returns:
A tuple containing the individual elements of the given version number.
"""
if not string.startswith(prefix):
raise errors.MediaWikiVersionError('Unknown generator {}'.format(string))
version = string[len(prefix):].split('.')
def split_num(s):
"""Split the string on the first non-digit character.
Returns:
A tuple of the digit part as int and, if available,
the rest of the string.
"""
i = 0
while i < len(s):
if s[i] < '0' or s[i] > '9':
break
i += 1
if s[i:]:
return (int(s[:i]), s[i:], )
else:
return (int(s[:i]), )
version_tuple = sum((split_num(s) for s in version), ())
if len(version_tuple) < 2:
raise errors.MediaWikiVersionError('Unknown MediaWiki {}'
.format('.'.join(version)))
return version_tuple
default_namespaces = {
0: '', 1: 'Talk', 2: 'User', 3: 'User talk', 4: 'Project',
5: 'Project talk', 6: 'Image', 7: 'Image talk', 8: 'MediaWiki',
9: 'MediaWiki talk', 10: 'Template', 11: 'Template talk', 12: 'Help',
13: 'Help talk', 14: 'Category', 15: 'Category talk',
-1: 'Special', -2: 'Media'
}
def __repr__(self):
return "<%s object '%s%s'>" % (self.__class__.__name__, self.host, self.path)
def get(self, action, *args, **kwargs):
"""Perform a generic API call using GET.
This is just a shorthand for calling api() with http_method='GET'.
All arguments will be passed on.
Args:
action (str): The MediaWiki API action to be performed.
Returns:
The raw response from the API call, as a dictionary.
"""
return self.api(action, 'GET', *args, **kwargs)
def post(self, action, *args, **kwargs):
"""Perform a generic API call using POST.
This is just a shorthand for calling api() with http_method='POST'.
All arguments will be passed on.
Args:
action (str): The MediaWiki API action to be performed.
Returns:
The raw response from the API call, as a dictionary.
"""
return self.api(action, 'POST', *args, **kwargs)
def api(self, action, http_method='POST', *args, **kwargs):
"""Perform a generic API call and handle errors.
All arguments will be passed on.
Args:
action (str): The MediaWiki API action to be performed.
http_method (str): The HTTP method to use.
Example:
To get coordinates from the GeoData MediaWiki extension at English Wikipedia:
>>> site = Site('en.wikipedia.org')
>>> result = site.api('query', prop='coordinates', titles='Oslo|Copenhagen')
>>> for page in result['query']['pages'].values():
... if 'coordinates' in page:
... print('{} {} {}'.format(page['title'],
... page['coordinates'][0]['lat'],
... page['coordinates'][0]['lon']))
Oslo 59.95 10.75
Copenhagen 55.6761 12.5683
Returns:
The raw response from the API call, as a dictionary.
"""
kwargs.update(args)
if action == 'query' and 'continue' not in kwargs:
kwargs['continue'] = ''
if action == 'query':
if 'meta' in kwargs:
kwargs['meta'] += '|userinfo'
else:
kwargs['meta'] = 'userinfo'
if 'uiprop' in kwargs:
kwargs['uiprop'] += '|blockinfo|hasmsg'
else:
kwargs['uiprop'] = 'blockinfo|hasmsg'
sleeper = self.sleepers.make()
while True:
info = self.raw_api(action, http_method, **kwargs)
if not info:
info = {}
if self.handle_api_result(info, sleeper=sleeper):
return info
def handle_api_result(self, info, kwargs=None, sleeper=None):
"""Checks the given API response, raising an appropriate exception or sleeping if
necessary.
Args:
info (dict): The API result.
kwargs (dict): Additional arguments to be passed when raising an
:class:`errors.APIError`.
sleeper (sleep.Sleeper): A :class:`~sleep.Sleeper` instance to use when
sleeping.
Returns:
`False` if the given API response contains an exception, else `True`.
"""
if sleeper is None:
sleeper = self.sleepers.make()
try:
userinfo = info['query']['userinfo']
except KeyError:
userinfo = ()
if 'blockedby' in userinfo:
self.blocked = (userinfo['blockedby'], userinfo.get('blockreason', ''))
else:
self.blocked = False
self.hasmsg = 'messages' in userinfo
self.logged_in = 'anon' not in userinfo
if 'warnings' in info:
for module, warning in info['warnings'].items():
if '*' in warning:
log.warning(warning['*'])
if 'error' in info:
if info['error'].get('code') in {'internal_api_error_DBConnectionError',
'internal_api_error_DBQueryError'}:
sleeper.sleep()
return False
# cope with https://phabricator.wikimedia.org/T106066
if (
info['error'].get('code') == 'mwoauth-invalid-authorization'
and 'Nonce already used' in info['error'].get('info')
):
log.warning('Retrying due to nonce error, see'
'https://phabricator.wikimedia.org/T106066')
sleeper.sleep()
return False
if 'query' in info['error']:
# Semantic Mediawiki does not follow the standard error format
raise errors.APIError(None, info['error']['query'], kwargs)
if '*' in info['error']:
raise errors.APIError(info['error']['code'],
info['error']['info'], info['error']['*'])
raise errors.APIError(info['error']['code'],
info['error']['info'], kwargs)
return True
@staticmethod
def _query_string(*args, **kwargs):
kwargs.update(args)
qs1 = [
(k, v) for k, v in kwargs.items() if k not in {'wpEditToken', 'token'}
]
qs2 = [
(k, v) for k, v in kwargs.items() if k in {'wpEditToken', 'token'}
]
return OrderedDict(qs1 + qs2)
def raw_call(self, script, data, files=None, retry_on_error=True, http_method='POST'):
"""
Perform a generic request and return the raw text.
In the event of a network problem, or an HTTP response with status code 5XX,
we'll wait and retry the configured number of times before giving up
if `retry_on_error` is True.
`requests.exceptions.HTTPError` is still raised directly for
HTTP responses with status codes in the 4XX range, and invalid
HTTP responses.
Args:
script (str): Script name, usually 'api'.
data (dict): Post data
files (dict): Files to upload
retry_on_error (bool): Retry on connection error
http_method (str): The HTTP method, defaults to 'POST'
Returns:
The raw text response.
Raises:
errors.MaximumRetriesExceeded: The API request failed and the maximum number
of retries was exceeded.
requests.exceptions.HTTPError: Received an invalid HTTP response, or a status
code in the 4xx range.
requests.exceptions.ConnectionError: Encountered an unexpected error while
performing the API request.
requests.exceptions.Timeout: The API request timed out.
"""
headers = {}
if self.compress:
headers['Accept-Encoding'] = 'gzip'
sleeper = self.sleepers.make((script, data))
scheme = self.scheme
host = self.host
if isinstance(host, (list, tuple)):
warnings.warn(
'Specifying host as a tuple is deprecated as of mwclient 0.10.1. '
+ 'Please use the new scheme argument instead.',
DeprecationWarning
)
scheme, host = host
url = '{scheme}://{host}{path}{script}{ext}'.format(scheme=scheme, host=host,
path=self.path, script=script,
ext=self.ext)
while True:
toraise = None
wait_time = 0
args = {'files': files, 'headers': headers}
for k, v in self.requests.items():
args[k] = v
if http_method == 'GET':
args['params'] = data
else:
args['data'] = data
try:
stream = self.connection.request(http_method, url, **args)
if stream.headers.get('x-database-lag'):
wait_time = int(stream.headers.get('retry-after'))
log.warning('Database lag exceeds max lag. '
'Waiting for {} seconds'.format(wait_time))
# fall through to the sleep
elif stream.status_code == 200:
return stream.text
elif stream.status_code < 500 or stream.status_code > 599:
stream.raise_for_status()
else:
if not retry_on_error:
stream.raise_for_status()
log.warning('Received {status} response: {text}. '
'Retrying in a moment.'
.format(status=stream.status_code,
text=stream.text))
toraise = "stream"
# fall through to the sleep
except (
requests.exceptions.ConnectionError,
requests.exceptions.Timeout
) as err:
# In the event of a network problem
# (e.g. DNS failure, refused connection, etc),
# Requests will raise a ConnectionError exception.
if not retry_on_error:
raise
log.warning('Connection error. Retrying in a moment.')
toraise = err
# proceed to the sleep
# all retry paths come here
try:
sleeper.sleep(wait_time)
except errors.MaximumRetriesExceeded:
if toraise == "stream":
stream.raise_for_status()
elif toraise:
raise toraise
else:
raise
def raw_api(self, action, http_method='POST', retry_on_error=True, *args, **kwargs):
"""Send a call to the API.
Args:
action (str): The MediaWiki API action to perform.
http_method (str): The HTTP method to use in the request.
retry_on_error (bool): Whether to retry API call on connection errors.
*args (Tuple[str, Any]): Arguments to be passed to the `api.php` script as
data.
**kwargs (Any): Arguments to be passed to the `api.php` script as data.
Returns:
The API response.
Raises:
errors.APIDisabledError: The MediaWiki API is disabled for this instance.
errors.InvalidResponse: The API response could not be decoded from JSON.
errors.MaximumRetriesExceeded: The API request failed and the maximum number
of retries was exceeded.
requests.exceptions.HTTPError: Received an invalid HTTP response, or a status
code in the 4xx range.
requests.exceptions.ConnectionError: Encountered an unexpected error while
performing the API request.
requests.exceptions.Timeout: The API request timed out.
"""
kwargs['action'] = action
kwargs['format'] = 'json'
data = self._query_string(*args, **kwargs)
res = self.raw_call('api', data, retry_on_error=retry_on_error,
http_method=http_method)
try:
return json.loads(res, object_pairs_hook=OrderedDict)
except ValueError:
if res.startswith('MediaWiki API is not enabled for this site.'):
raise errors.APIDisabledError
raise errors.InvalidResponse(res)
def raw_index(self, action, http_method='POST', *args, **kwargs):
"""Sends a call to index.php rather than the API.
Args:
action (str): The MediaWiki API action to perform.
http_method (str): The HTTP method to use in the request.
*args (Tuple[str, Any]): Arguments to be passed to the `index.php` script as
data.
**kwargs (Any): Arguments to be passed to the `index.php` script as data.
Returns:
The API response.
Raises:
errors.MaximumRetriesExceeded: The API request failed and the maximum number
of retries was exceeded.
requests.exceptions.HTTPError: Received an invalid HTTP response, or a status
code in the 4xx range.
requests.exceptions.ConnectionError: Encountered an unexpected error while
performing the API request.
requests.exceptions.Timeout: The API request timed out.
"""
kwargs['action'] = action
kwargs['maxlag'] = self.max_lag
data = self._query_string(*args, **kwargs)
return self.raw_call('index', data, http_method=http_method)
def require(self, major, minor, revision=None, raise_error=True):
"""Check whether the current wiki matches the required version.
Args:
major (int): The required major version.
minor (int): The required minor version.
revision (int): The required revision.
raise_error (bool): Whether to throw an error if the version of the current
wiki is below the required version. Defaults to `True`.
Returns:
`False` if the version of the current wiki is below the required version, else
`True`. If either `raise_error=True` or the site is uninitialized and
`raise_error=None` then nothing is returned.
Raises:
errors.MediaWikiVersionError: The current wiki is below the required version
and `raise_error=True`.
RuntimeError: It `raise_error` is `None` and the `version` attribute is unset
This is usually done automatically on construction of the :class:`Site`,
unless `do_init=False` is passed to the constructor. After instantiation,
the :meth:`~Site.site_init` functon can be used to retrieve and set the
`version`.
NotImplementedError: If the `revision` argument was passed. The logic for this
is currently unimplemented.
"""
if self.version is None:
if raise_error is None:
return
# FIXME: Replace this with a specific error
raise RuntimeError('Site %s has not yet been initialized' % repr(self))
if revision is None:
if self.version[:2] >= (major, minor):
return True
elif raise_error:
raise errors.MediaWikiVersionError(
'Requires version {required[0]}.{required[1]}, '
'current version is {current[0]}.{current[1]}'
.format(required=(major, minor),
current=(self.version[:2]))
)
else:
return False
else:
raise NotImplementedError
# Actions
def email(self, user, text, subject, cc=False):
"""
Send email to a specified user on the wiki.
>>> try:
... site.email('SomeUser', 'Some message', 'Some subject')
... except mwclient.errors.NoSpecifiedEmail:
... print('User does not accept email, or has no email address.')
Args:
user (str): User name of the recipient
text (str): Body of the email
subject (str): Subject of the email
cc (bool): True to send a copy of the email to yourself (default is False)
Returns:
Dictionary of the JSON response
Raises:
NoSpecifiedEmail (mwclient.errors.NoSpecifiedEmail): User doesn't accept email
EmailError (mwclient.errors.EmailError): Other email errors
"""
token = self.get_token('email')
try:
info = self.post('emailuser', target=user, subject=subject,
text=text, ccme=cc, token=token)
except errors.APIError as e:
if e.args[0] == 'noemail':
raise errors.NoSpecifiedEmail(user, e.args[1])
raise errors.EmailError(*e)
return info
def login(self, username=None, password=None, cookies=None, domain=None):
"""
Login to the wiki using a username and bot password. The method returns
nothing if the login was successful, but raises and error if it was not.
If you use mediawiki >= 1.27 and try to login with normal account
(not botpassword account), you should use `clientlogin` instead, because login
action is deprecated since 1.27 with normal account and will stop
working in the near future. See these pages to learn more:
- https://www.mediawiki.org/wiki/API:Login and
- https://www.mediawiki.org/wiki/Manual:Bot_passwords
Note: at least until v1.33.1, botpasswords accounts seem to not have
"userrights" permission. If you need to update user's groups,
this permission is required so you must use `client login`
with a user who has userrights permission (a bureaucrat for eg.).
Args:
username (str): MediaWiki username
password (str): MediaWiki password
cookies (dict): Custom cookies to include with the log-in request.
domain (str): Sends domain name for authentication; used by some
MediaWiki plug-ins like the 'LDAP Authentication' extension.
Raises:
LoginError (mwclient.errors.LoginError): Login failed, the reason can be
obtained from e.code and e.info (where e is the exception object) and
will be one of the API:Login errors. The most common error code is
"Failed", indicating a wrong username or password.
MaximumRetriesExceeded: API call to log in failed and was retried until all
retries were exhausted. This will not occur if the credentials are merely
incorrect. See MaximumRetriesExceeded for possible reasons.
APIError: An API error occurred. Rare, usually indicates an internal server
error.
"""
if username and password:
self.credentials = (username, password, domain)
if cookies:
self.connection.cookies.update(cookies)
if self.credentials:
sleeper = self.sleepers.make()
kwargs = {
'lgname': self.credentials[0],
'lgpassword': self.credentials[1]
}
if self.credentials[2]:
kwargs['lgdomain'] = self.credentials[2]
# Try to login using the scheme for MW 1.27+. If the wiki is read protected,
# it is not possible to get the wiki version upfront using the API, so we just
# have to try. If the attempt fails, we try the old method.
try:
kwargs['lgtoken'] = self.get_token('login')
except (errors.APIError, KeyError):
log.debug('Failed to get login token, MediaWiki is older than 1.27.')
while True:
login = self.post('login', **kwargs)
if login['login']['result'] == 'Success':
break
elif login['login']['result'] == 'NeedToken':
kwargs['lgtoken'] = login['login']['token']
elif login['login']['result'] == 'Throttled':
sleeper.sleep(int(login['login'].get('wait', 5)))
else:
raise errors.LoginError(self, login['login']['result'],
login['login']['reason'])
self.site_init()
def clientlogin(self, cookies=None, **kwargs):
"""
Login to the wiki using a username and password. The method returns
True if it's a success or the returned response if it's a multi-steps
login process you started. In case of failure it raises some Errors.
Example for classic username / password clientlogin request:
>>> try:
... site.clientlogin(username='myusername', password='secret')
... except mwclient.errors.LoginError as e:
... print('Could not login to MediaWiki: %s' % e)
Args:
cookies (dict): Custom cookies to include with the log-in request.
**kwargs (dict): Custom vars used for clientlogin as:
- loginmergerequestfields
- loginpreservestate
- loginreturnurl,
- logincontinue
- logintoken
- *: additional params depending on the available auth requests.
to log with classic username / password, you need to add
`username` and `password`
See https://www.mediawiki.org/wiki/API:Login#Method_2._clientlogin
Raises:
LoginError (mwclient.errors.LoginError): Login failed, the reason can be
obtained from e.code and e.info (where e is the exception object) and
will be one of the API:Login errors. The most common error code is
"Failed", indicating a wrong username or password.
MaximumRetriesExceeded: API call to log in failed and was retried until all
retries were exhausted. This will not occur if the credentials are merely
incorrect. See MaximumRetriesExceeded for possible reasons.
APIError: An API error occurred. Rare, usually indicates an internal server
error.
"""
self.require(1, 27)
if cookies:
self.connection.cookies.update(cookies)
if kwargs:
# Try to login using the scheme for MW 1.27+. If the wiki is read protected,
# it is not possible to get the wiki version upfront using the API, so we just
# have to try. If the attempt fails, we try the old method.
if 'logintoken' not in kwargs:
try:
kwargs['logintoken'] = self.get_token('login')
except (errors.APIError, KeyError):
log.debug('Failed to get login token, MediaWiki is older than 1.27.')
if 'logincontinue' not in kwargs and 'loginreturnurl' not in kwargs:
# should be great if API didn't require this...
kwargs['loginreturnurl'] = '%s://%s' % (self.scheme, self.host)
while True:
login = self.post('clientlogin', **kwargs)
status = login['clientlogin'].get('status')
if status == 'PASS':
return True
elif status in ('UI', 'REDIRECT'):
return login['clientlogin']
else:
raise errors.LoginError(self, status,
login['clientlogin'].get('message'))
def get_token(self, type, force=False, title=None):
"""Request a MediaWiki access token of the given `type`.
Args:
type (str): The type of token to request.
force (bool): Force the request of a new token, even if a token of that type
has already been cached.
title (str): The page title for which to request a token. Only used for
MediaWiki versions below 1.24.
Returns:
A MediaWiki token of the requested `type`.
Raises:
errors.APIError: A token of the given type could not be retrieved.
"""
if self.version is None or self.version[:2] >= (1, 24):
# The 'csrf' (cross-site request forgery) token introduced in 1.24 replaces
# the majority of older tokens, like edittoken and movetoken.
if type not in {'watch', 'patrol', 'rollback', 'userrights', 'login'}:
type = 'csrf'
if type not in self.tokens:
self.tokens[type] = '0'
if self.tokens.get(type, '0') == '0' or force:
if self.version is None or self.version[:2] >= (1, 24):
# We use raw_api() rather than api() because api() is adding "userinfo"
# to the query and this raises a readapideniederror if the wiki is read
# protected, and we're trying to fetch a login token.
info = self.raw_api('query', 'GET', meta='tokens', type=type)
self.handle_api_result(info)
# Note that for read protected wikis, we don't know the version when
# fetching the login token. If it's < 1.27, the request below will
# raise a KeyError that we should catch.
self.tokens[type] = info['query']['tokens']['%stoken' % type]
else:
if title is None:
# Some dummy title was needed to get a token prior to 1.24
title = 'Test'
info = self.post('query', titles=title,
prop='info', intoken=type)
for i in info['query']['pages'].values():
if i['title'] == title:
self.tokens[type] = i['%stoken' % type]
return self.tokens[type]
def upload(self, file=None, filename=None, description='', ignore=False,
file_size=None, url=None, filekey=None, comment=None):
"""Upload a file to the site.
Note that one of `file`, `filekey` and `url` must be specified, but not
more than one. For normal uploads, you specify `file`.
Args:
file (str): File object or stream to upload.
filename (str): Destination filename, don't include namespace
prefix like 'File:'
description (str): Wikitext for the file description page.
ignore (bool): True to upload despite any warnings.
file_size (int): Deprecated in mwclient 0.7
url (str): URL to fetch the file from.
filekey (str): Key that identifies a previous upload that was
stashed temporarily.
comment (str): Upload comment. Also used as the initial page text
for new files if `description` is not specified.
Example:
>>> client.upload(open('somefile', 'rb'), filename='somefile.jpg',
description='Some description')
Returns:
JSON result from the API.
Raises:
errors.InsufficientPermission
requests.exceptions.HTTPError
errors.FileExists: The file already exists and `ignore` is `False`.
"""
if file_size is not None:
# Note that DeprecationWarning is hidden by default since Python 2.7
warnings.warn(
'file_size is deprecated since mwclient 0.7',
DeprecationWarning
)
if filename is None:
raise TypeError('filename must be specified')
if len([x for x in [file, filekey, url] if x is not None]) != 1:
raise TypeError(
"exactly one of 'file', 'filekey' and 'url' must be specified"
)
image = self.Images[filename]
if not image.can('upload'):
raise errors.InsufficientPermission(filename)
if comment is None:
comment = description
text = None
else:
comment = comment
text = description
if file is not None:
if not hasattr(file, 'read'):
file = open(file, 'rb')
content_size = file.seek(0, 2)
file.seek(0)
if self.version[:2] >= (1, 20) and content_size > self.chunk_size:
return self.chunk_upload(file, filename, ignore, comment, text)
predata = {
'action': 'upload',
'format': 'json',
'filename': filename,
'comment': comment,
'text': text,
'token': image.get_token('edit'),
}
if ignore:
predata['ignorewarnings'] = 'true'
if url:
predata['url'] = url
# sessionkey was renamed to filekey in MediaWiki 1.18
# https://phabricator.wikimedia.org/rMW5f13517e36b45342f228f3de4298bb0fe186995d
if self.version[:2] < (1, 18):
predata['sessionkey'] = filekey
else:
predata['filekey'] = filekey
postdata = predata
files = None
if file is not None:
# Workaround for https://github.com/mwclient/mwclient/issues/65
# ----------------------------------------------------------------
# Since the filename in Content-Disposition is not interpreted,
# we can send some ascii-only dummy name rather than the real
# filename, which might contain non-ascii.
files = {'file': ('fake-filename', file)}
sleeper = self.sleepers.make()
while True:
data = self.raw_call('api', postdata, files)
info = json.loads(data)
if not info:
info = {}
if self.handle_api_result(info, kwargs=predata, sleeper=sleeper):
response = info.get('upload', {})
# Workaround for https://github.com/mwclient/mwclient/issues/211
# ----------------------------------------------------------------
# Raise an error if the file already exists. This is necessary because
# MediaWiki returns a warning, not an error, leading to silent failure.
# The user must explicitly set ignore=True (ignorewarnings=True) to
# overwrite an existing file.
if ignore is False and 'exists' in response.get('warnings', {}):
raise errors.FileExists(filename)
break
if file is not None:
file.close()
return response
def chunk_upload(self, file, filename, ignorewarnings, comment, text):