Beispiel #1
0
 def login(self, username = None, password = None, cookies = None):
     if self.initialized: self.require(1, 10)
     
     if username and password: 
         self.credentials = (username, password)
     if cookies:
         if self.host not in self.conn.cookies:
             self.conn.cookies[self.host] = http.CookieJar()
         self.conn.cookies[self.host].update(cookies)
         
     if self.credentials:
         wait_token = self.wait_token()
         while True:
             login = self.api('login', lgname = self.credentials[0], lgpassword = self.credentials[1])
             if login['login']['result'] == 'Success':
                 break
             elif login['login']['result'] == 'Throttled':
                 self.wait(wait_token, login['login'].get('wait', 5))
             else:
                 raise errors.LoginError(self, login['login'])
             
     if self.initialized:                
         info = self.api('query', meta = 'userinfo', uiprop = 'groups|rights')
         userinfo = compatibility.userinfo(info, self.require(1, 12, raise_error = False))
         self.username = userinfo['name']
         self.groups = userinfo.get('groups', [])
         self.rights = userinfo.get('rights', [])
         self.tokens = {}
     else:
         self.site_init()
Beispiel #2
0
 def site_init(self):
     meta = self.api('query', meta = 'siteinfo|userinfo', 
         siprop = 'general|namespaces', uiprop = 'groups|rights')
     self.site = meta['query']['general']
     self.namespaces = dict(((i['id'], i.get('*', '')) for i in meta['query']['namespaces'].itervalues()))
     self.writeapi = 'writeapi' in self.site
     #self.writeapi = False
         
     if self.site['generator'].startswith('MediaWiki '):
         version = self.site['generator'][10:].split('.')
         if len(version) == 2 and version[1].endswith('alpha'):
             self.version = (int(version[0]), int(version[1][:-5]), 'alpha')
         elif len(version) == 3:
             self.version = (int(version[0]), int(version[1]), int(version[2]))
         else:
             raise errors.MediaWikiVersionError('Unknown MediaWiki %s' % '.'.join(version))
     else:
         raise errors.MediaWikiVersionError('Unknown generator %s' % self.site['generator'])
     # Require 1.11 until some compatibility issues are fixed
     self.require(1, 11)
         
     userinfo = compatibility.userinfo(meta, self.require(1, 12, raise_error = False))
     self.username = userinfo['name']
     self.groups = userinfo.get('groups', [])
     self.rights = userinfo.get('rights', [])
     self.initialized = True
Beispiel #3
0
	def site_init(self):
		meta = self.api('query', meta = 'siteinfo|userinfo', 
			siprop = 'general|namespaces', uiprop = 'groups|rights')
		self.site = meta['query']['general']
		self.namespaces = dict(((i['id'], i.get('*', '')) for i in meta['query']['namespaces'].itervalues()))
		self.writeapi = 'writeapi' in self.site
			
		if self.site['generator'].startswith('MediaWiki '):
			version = self.site['generator'][10:].split('.')
			if len(version) == 2 and version[1].endswith('alpha'):
				self.version = (int(version[0]), int(version[1][:-5]), 'alpha')
			elif len(version) == 3:
				self.version = (int(version[0]), int(version[1]), int(version[2]))
			else:
				raise errors.MediaWikiVersionError('Unknown MediaWiki %s' % '.'.join(version))
		else:
			raise errors.MediaWikiVersionError('Unknown generator %s' % self.site['generator'])
		# Require 1.11 until some compatibility issues are fixed
		self.require(1, 11)
			
		userinfo = compatibility.userinfo(meta, self.require(1, 12, raise_error = False))
		self.username = userinfo['name']
		self.groups = userinfo.get('groups', [])
		self.rights = userinfo.get('rights', [])
		self.initialized = True
Beispiel #4
0
    def handle_api_result(self, info, kwargs=None, token=None):
        if token is None:
            token = self.wait_token()

        try:
            userinfo = compatibility.userinfo(info, self.require(1, 12, raise_error=None))
        except KeyError:
            userinfo = ()

        if 'blockedby' in userinfo:
            self.blocked = (userinfo['blockedby'], userinfo.get('blockreason', u''))
        else:
            self.blocked = False

        self.hasmsg = 'message' in userinfo
        self.logged_in = 'anon' not in userinfo

        if 'error' in info:
            if info['error']['code'] in ('internal_api_error_DBConnectionError', ):
                self.wait(token)
                return False
            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
Beispiel #5
0
    def handle_api_result(self, info, kwargs=None, token=None):
        if token is None:
            token = self.wait_token()

        try:
            userinfo = compatibility.userinfo(info, self.require(1, 12, raise_error=None))
        except KeyError:
            userinfo = ()

        if 'blockedby' in userinfo:
            self.blocked = (userinfo['blockedby'], userinfo.get('blockreason', u''))
        else:
            self.blocked = False

        self.hasmsg = 'message' in userinfo
        self.logged_in = 'anon' not in userinfo

        if 'error' in info:
            if info['error']['code'] in ('internal_api_error_DBConnectionError', ):
                self.wait(token)
                return False
            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
Beispiel #6
0
	def login(self, username = None, password = None, cookies = None):
		if self.initialized: self.require(1, 10)
		
		if username and password: 
			self.credentials = (username, password)
		if cookies:
			if self.host not in self.conn.cookies:
				self.conn.cookies[self.host] = http.CookieJar()
			self.conn.cookies[self.host].update(cookies)
			
		if self.credentials:
			wait_token = self.wait_token()
			while True:
				login = self.api('login', lgname = self.credentials[0], lgpassword = self.credentials[1])
				if login['login']['result'] == 'Success':
					break
				elif login['login']['result'] == 'Throttled':
					self.wait(wait_token, login['login'].get('wait', 5))
				else:
					raise errors.LoginError(self, login['login'])
				
		if self.initialized:				
			info = self.api('query', meta = 'userinfo', uiprop = 'groups|rights')
			userinfo = compatibility.userinfo(info, self.require(1, 12, raise_error = False))
			self.username = userinfo['name']
			self.groups = userinfo.get('groups', [])
			self.rights = userinfo.get('rights', [])
			self.tokens = {}
		else:
			self.site_init()
Beispiel #7
0
    def site_init(self):
        meta = self.api('query',
                        meta='siteinfo|userinfo',
                        siprop='general|namespaces',
                        uiprop='groups|rights')

        # Extract site info
        self.site = meta['query']['general']
        self.namespaces = dict(
            ((i['id'], i.get('*', ''))
             for i in meta['query']['namespaces'].itervalues()))
        self.writeapi = 'writeapi' in self.site

        # Determine version
        if self.site['generator'].startswith('MediaWiki '):
            version = self.site['generator'][10:].split('.')

            def split_num(s):
                i = 0
                while i < len(s):
                    if s[i] < '0' or s[i] > '9':
                        break
                    i += 1
                return int(s[:i]), s[i:]

            # FIXME! Fix those awful two hacks
            if len(version) == 2:
                # An alpha version
                self.version = (int(version[0]), ) + split_num(version[1])
            elif len(version) == 3 and 'rc' in version[2]:
                # Release candidate
                self.version = (int(version[0]), int(version[1]), version[2])
            elif len(version) == 3:
                # Regular y.x.z version
                self.version = (int(version[0]), int(version[1]),
                                int(version[2]))
            else:
                raise errors.MediaWikiVersionError('Unknown MediaWiki %s' %
                                                   '.'.join(version))
        else:
            raise errors.MediaWikiVersionError('Unknown generator %s' %
                                               self.site['generator'])
        # Require 1.11 until some compatibility issues are fixed
        self.require(1, 11)

        # User info
        userinfo = compatibility.userinfo(
            meta, self.require(1, 12, raise_error=False))
        self.username = userinfo['name']
        self.groups = userinfo.get('groups', [])
        self.rights = userinfo.get('rights', [])
        self.initialized = True
Beispiel #8
0
    def site_init(self):
        meta = self.api('query',
                        meta='siteinfo|userinfo',
                        siprop='general|namespaces',
                        uiprop='groups|rights')

        # Extract site info
        self.site = meta['query']['general']
        self.namespaces = dict(
            ((i['id'], i.get('*', ''))
             for i in meta['query']['namespaces'].itervalues()))
        self.writeapi = 'writeapi' in self.site

        # Determine version
        if self.site['generator'].startswith('MediaWiki '):
            version = self.site['generator'][10:].split('.')

            def split_num(s):
                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]), )

            self.version = sum((split_num(s) for s in version), ())

            if len(self.version) < 2:
                raise errors.MediaWikiVersionError('Unknown MediaWiki %s' %
                                                   '.'.join(version))
        else:
            raise errors.MediaWikiVersionError('Unknown generator %s' %
                                               self.site['generator'])
        # Require 1.11 until some compatibility issues are fixed
        self.require(1, 11)

        # User info
        userinfo = compatibility.userinfo(
            meta, self.require(1, 12, raise_error=False))
        self.username = userinfo['name']
        self.groups = userinfo.get('groups', [])
        self.rights = userinfo.get('rights', [])
        self.initialized = True
Beispiel #9
0
	def site_init(self):
		meta = self.api('query', meta = 'siteinfo|userinfo', 
			siprop = 'general|namespaces', uiprop = 'groups|rights')
		
		# Extract site info
		self.site = meta['query']['general']
		self.namespaces = dict(((i['id'], i.get('*', '')) for i in meta['query']['namespaces'].itervalues()))
		self.writeapi = 'writeapi' in self.site
		
		# Determine version
		if self.site['generator'].startswith('MediaWiki '):
			version = self.site['generator'][10:].split('.')
			def split_num(s):
				i = 0
				while i < len(s):
					if s[i] < '0' or s[i] > '9':
						break
					i += 1
				return int(s[:i]), s[i:]
			# FIXME! Fix those awful two hacks
			if len(version) == 2:
				# An alpha version
				self.version = (int(version[0]), ) + split_num(version[1])
			elif len(version) == 3 and 'rc' in version[2]:
				# Release candidate
				self.version = (int(version[0]), int(version[1]), version[2])
			elif len(version) == 3:
				# Regular y.x.z version
				self.version = (int(version[0]), int(version[1]), int(version[2]))
			else:
				raise errors.MediaWikiVersionError('Unknown MediaWiki %s' % '.'.join(version))
		else:
			raise errors.MediaWikiVersionError('Unknown generator %s' % self.site['generator'])
		# Require 1.11 until some compatibility issues are fixed
		self.require(1, 11)
		
		# User info	
		userinfo = compatibility.userinfo(meta, self.require(1, 12, raise_error = False))
		self.username = userinfo['name']
		self.groups = userinfo.get('groups', [])
		self.rights = userinfo.get('rights', [])
		self.initialized = True
Beispiel #10
0
    def site_init(self):
        meta = self.api('query', meta='siteinfo|userinfo', siprop='general|namespaces', uiprop='groups|rights')

        # Extract site info
        self.site = meta['query']['general']
        if pythonver >= 3:
            self.namespaces = dict(((i['id'], i.get('*', '')) for i in list(meta['query']['namespaces'].values())))
        else:
            self.namespaces = dict(((i['id'], i.get('*', '')) for i in meta['query']['namespaces'].itervalues()))
        self.writeapi = 'writeapi' in self.site

        # Determine version
        if self.site['generator'].startswith('MediaWiki '):
            version = self.site['generator'][10:].split('.')

            def split_num(s):
                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]), )
            self.version = sum((split_num(s) for s in version), ())

            if len(self.version) < 2:
                raise errors.MediaWikiVersionError('Unknown MediaWiki %s' % '.'.join(version))
        else:
            raise errors.MediaWikiVersionError('Unknown generator %s' % self.site['generator'])

        # Require 1.11 until some compatibility issues are fixed
        self.require(1, 11)

        # User info
        userinfo = compatibility.userinfo(meta, self.require(1, 12, raise_error=False))
        self.username = userinfo['name']
        self.groups = userinfo.get('groups', [])
        self.rights = userinfo.get('rights', [])
        self.initialized = True
Beispiel #11
0
    def api(self, action, *args, **kwargs):
        kwargs.update(args)
        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'

        token = self.wait_token()
        while True:
            info = self.raw_api(action, **kwargs)
            if not info: info = {}

            try:
                userinfo = compatibility.userinfo(
                    info, self.require(1, 12, raise_error=None))
            except KeyError:
                userinfo = ()
            if 'blockedby' in userinfo:
                self.blocked = (userinfo['blockedby'],
                                userinfo.get('blockreason', u''))
            else:
                self.blocked = False
            self.hasmsg = 'message' in userinfo
            self.logged_in = 'anon' not in userinfo
            if 'error' in info:
                if info['error']['code'] in (
                        u'internal_api_error_DBConnectionError', ):
                    self.wait(token)
                    continue
                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 info
Beispiel #12
0
    def handle_api_result(self, info, kwargs=None, token=None):
        if token is None:
            token = self.wait_token()

        try:
            userinfo = compatibility.userinfo(info, self.require(1, 12, raise_error=None))
        except KeyError:
            userinfo = ()
        if "blockedby" in userinfo:
            self.blocked = (userinfo["blockedby"], userinfo.get("blockreason", u""))
        else:
            self.blocked = False
        self.hasmsg = "message" in userinfo
        self.logged_in = "anon" not in userinfo
        if "error" in info:
            if info["error"]["code"] in (u"internal_api_error_DBConnectionError",):
                self.wait(token)
                return False
            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
Beispiel #13
0
    def site_init(self):
        meta = self.api("query", meta="siteinfo|userinfo", siprop="general|namespaces", uiprop="groups|rights")

        # Extract site info
        self.site = meta["query"]["general"]
        self.namespaces = dict(((i["id"], i.get("*", "")) for i in meta["query"]["namespaces"].itervalues()))
        self.writeapi = "writeapi" in self.site

        # Determine version
        if self.site["generator"].startswith("MediaWiki "):
            version = self.site["generator"][10:].split(".")

            def split_num(s):
                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]),)

            self.version = sum((split_num(s) for s in version), ())

            if len(self.version) < 2:
                raise errors.MediaWikiVersionError("Unknown MediaWiki %s" % ".".join(version))
        else:
            raise errors.MediaWikiVersionError("Unknown generator %s" % self.site["generator"])
            # Require 1.11 until some compatibility issues are fixed
        self.require(1, 11)

        # User info
        userinfo = compatibility.userinfo(meta, self.require(1, 12, raise_error=False))
        self.username = userinfo["name"]
        self.groups = userinfo.get("groups", [])
        self.rights = userinfo.get("rights", [])
        self.initialized = True
Beispiel #14
0
 def api(self, action, *args, **kwargs):
     kwargs.update(args)
     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'
         
     token = self.wait_token()
     while True:
         info = self.raw_api(action, **kwargs)
         if not info: info = {}
             
         try:
             userinfo = compatibility.userinfo(info, self.require(1, 12, raise_error = None))
         except KeyError:
             userinfo = ()
         if 'blockedby' in userinfo:
             self.blocked = (userinfo['blockedby'], userinfo.get('blockreason', u''))
         else:
             self.blocked = False
         self.hasmsg = 'message' in userinfo
         self.logged_in = 'anon' not in userinfo
         if 'error' in info:
             if info['error']['code'] in (u'internal_api_error_DBConnectionError', ):
                 self.wait(token)
                 continue
             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 info
Beispiel #15
0
    def login(self, username=None, password=None, cookies=None, domain=None):
        if self.initialized:
            self.require(1, 10)

        if username and password:
            self.credentials = (username, password, domain)
        if cookies:
            if self.host not in self.conn.cookies:
                self.conn.cookies[self.host] = http.CookieJar()
            self.conn.cookies[self.host].update(cookies)

        if self.credentials:
            wait_token = self.wait_token()
            kwargs = {"lgname": self.credentials[0], "lgpassword": self.credentials[1]}
            if self.credentials[2]:
                kwargs["lgdomain"] = self.credentials[2]
            while True:
                login = self.api("login", **kwargs)
                if login["login"]["result"] == "Success":
                    break
                elif login["login"]["result"] == "NeedToken":
                    kwargs["lgtoken"] = login["login"]["token"]
                elif login["login"]["result"] == "Throttled":
                    self.wait(wait_token, login["login"].get("wait", 5))
                else:
                    raise errors.LoginError(self, login["login"])

        if self.initialized:
            info = self.api("query", meta="userinfo", uiprop="groups|rights")
            userinfo = compatibility.userinfo(info, self.require(1, 12, raise_error=False))
            self.username = userinfo["name"]
            self.groups = userinfo.get("groups", [])
            self.rights = userinfo.get("rights", [])
            self.tokens = {}
        else:
            self.site_init()