Browse Source

Merge branch 'release-0.1'

Jonathan Golder 1 year ago
parent
commit
d69d873624
6 changed files with 902 additions and 75 deletions
  1. 22
    0
      README.md
  2. 30
    0
      __init__.py
  3. 279
    0
      bot.py
  4. 96
    0
      config.py
  5. 287
    75
      jogobot.py
  6. 188
    0
      license.txt

+ 22
- 0
README.md View File

@@ -0,0 +1,22 @@
1
+# wiki-jogobot-core
2
+This python module contains code shared between several [Pywikibot](https://www.mediawiki.org/wiki/Manual:Pywikibot)
3
+based projects of [User:JogoBot](https://de.wikipedia.org/wiki/Benutzer:JogoBot) on the
4
+[German Wikipedia](https://de.wikipedia.org/wiki/Wikipedia:Hauptseite).
5
+
6
+## Requirements
7
+* Python 3.4+ (at least it is only tested with those)
8
+* pywikibot-core 2.0
9
+
10
+## Bugs
11
+[wiki-jogobot-core on fs.golderweb.de (de)](https://fs.golderweb.de/proj22)
12
+
13
+## Version
14
+
15
+* 0.1
16
+  - first stable release
17
+
18
+## License
19
+GPLv3+
20
+
21
+## Author Information
22
+Copyright 2017 Jonathan Golder <jonathan@golderweb.de>

+ 30
- 0
__init__.py View File

@@ -0,0 +1,30 @@
1
+#!/usr/bin/env python3
2
+# -*- coding: utf-8  -*-
3
+#
4
+#  __init__.py
5
+#
6
+#  Copyright 2017 Jonathan Golder <jonathan@golderweb.de>
7
+#
8
+#  This program is free software; you can redistribute it and/or modify
9
+#  it under the terms of the GNU General Public License as published by
10
+#  the Free Software Foundation; either version 2 of the License, or
11
+#  (at your option) any later version.
12
+#
13
+#  This program is distributed in the hope that it will be useful,
14
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+#  GNU General Public License for more details.
17
+#
18
+#  You should have received a copy of the GNU General Public License
19
+#  along with this program; if not, write to the Free Software
20
+#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
+#  MA 02110-1301, USA.
22
+#
23
+#
24
+"""
25
+Scripts for our bot framework
26
+"""
27
+# noqa needed to prevent pyflakes from warning about unused imports
28
+from jogobot.jogobot import ( output, sendmail, is_active )  # noqa
29
+from jogobot.config import config  # noqa
30
+import jogobot.bot as bot  # noqa

+ 279
- 0
bot.py View File

@@ -0,0 +1,279 @@
1
+#!/usr/bin/env python3
2
+# -*- coding: utf-8  -*-
3
+#
4
+#  bot.py
5
+#
6
+#  Copyright 2017 Jonathan Golder <jonathan@golderweb.de>
7
+#
8
+#  This program is free software; you can redistribute it and/or modify
9
+#  it under the terms of the GNU General Public License as published by
10
+#  the Free Software Foundation; either version 2 of the License, or
11
+#  (at your option) any later version.
12
+#
13
+#  This program is distributed in the hope that it will be useful,
14
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+#  GNU General Public License for more details.
17
+#
18
+#  You should have received a copy of the GNU General Public License
19
+#  along with this program; if not, write to the Free Software
20
+#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
+#  MA 02110-1301, USA.
22
+#
23
+#
24
+"""
25
+Wrapper functions to invoke bot tasks
26
+"""
27
+
28
+import sys
29
+
30
+from pywikibot import pagegenerators
31
+
32
+import jogobot
33
+
34
+
35
+def active(task_slug):
36
+    """
37
+    Checks up if bot with given task_slug is active via jogobot.framework
38
+
39
+    @param  task_slug  Task slug to check
40
+    @type task_slug  str
41
+
42
+    @return  True if active, otherwise False
43
+    @rtype  bool
44
+    """
45
+
46
+    try:
47
+        # Will throw Exception if disabled/blocked
48
+        jogobot.is_active( task_slug )
49
+
50
+    except jogobot.jogobot.Blocked:
51
+        (type, value, traceback) = sys.exc_info()
52
+        jogobot.output( "\03{lightpurple} %s (%s)" % (value, type ),
53
+                        "CRITICAL" )
54
+        return False
55
+
56
+    except jogobot.jogobot.Disabled:
57
+        (type, value, traceback) = sys.exc_info()
58
+        jogobot.output( "\03{red} %s (%s)" % (value, type ),
59
+                        "ERROR" )
60
+        return False
61
+
62
+    # Bot/Task is active
63
+    else:
64
+        return True
65
+
66
+
67
+def parse_local_args( local_args, callback=None ):
68
+    """
69
+    Parses local cmd args which are not parsed by pywikibot
70
+
71
+    @param  local_args  Local args returned by pywikibot.handle_args(args)
72
+    @type  iterable
73
+    @param  callback  A callback method could be provided. It will get a single
74
+                      arg and the related value as params:
75
+                            callback( arg, value )
76
+                      The method should return a tuple of key, value which can
77
+                      be directly appended to the kwargs dict.
78
+                      Or if arg is not relevant, return None or False. Then the
79
+                      arg will be passed to genFactory.handleArg()
80
+    @type  callable
81
+
82
+    @returns  The following tuple
83
+        @return 1  Slug of given subtask (Arg "-task")
84
+        @rtype  str
85
+        @return 2  GenFactory with parsed pagegenerator args
86
+        @rtype  pagegenerators.GeneratorFactory
87
+        @return 3  Additional args for subtasks
88
+        @rtype  dict
89
+    @rtype  tuple
90
+    """
91
+
92
+    # This factory is responsible for processing command line arguments
93
+    # that are also used by other scripts and that determine on which pages
94
+    # to work on.
95
+    genFactory = pagegenerators.GeneratorFactory()
96
+
97
+    # If always is True, bot won't ask for confirmation of edit (automode)
98
+    # always = False
99
+
100
+    # If force_reload is True, bot will always parse Countrylist regardless
101
+    # if parsing is needed or not
102
+    # force_reload = False
103
+
104
+    # Subtask selects the specific bot to run
105
+    # Default is reddiscparser
106
+    subtask = None
107
+
108
+    # kwargs are passed to selected bot as **kwargs
109
+    kwargs = dict()
110
+
111
+    # Parse command line arguments
112
+    for arg in local_args:
113
+
114
+        # Split args
115
+        argkey, sep, value = arg.partition(':')
116
+
117
+        if argkey.startswith("-always"):
118
+            kwargs['always'] = True
119
+        elif argkey.startswith("-task"):
120
+            subtask = value
121
+
122
+        # Must be the last but one entry
123
+        elif callable(callback):
124
+            ret_val = callback( argkey, value )
125
+
126
+            # Was relevant for callback
127
+            if ret_val:
128
+                kwargs[ret_val[0]] = ret_val[1]
129
+            # Otherwise pass to genFactory.handleArg(arg)
130
+            else:
131
+                genFactory.handleArg(arg)
132
+        else:
133
+            genFactory.handleArg(arg)
134
+
135
+    # Return Tuple
136
+    return ( subtask, genFactory, kwargs )
137
+
138
+
139
+# In current version it does not realy make sense to use this method,
140
+# as it just proxies the callback
141
+def prepare_bot( task_slug, subtask, genFactory, subtask_args, callback ):
142
+    """
143
+    Handles importing subtask Bot class and prepares specific args
144
+
145
+    Throws exception if bot not exists
146
+
147
+    @param  task_slug  Task slug, needed for logging
148
+    @type task_slug  str
149
+    @param  subtask  Slug of given subtask
150
+    @type  subtask  str
151
+    @param  genFactory  GenFactory with parsed pagegenerator args
152
+    @type  genFactory  pagegenerators.GeneratorFactory
153
+    @param  subtask_args  Additional args for subtasks
154
+    @type  subtask_args  dict
155
+    @param  callback  A reference to a callback method which gets the arg
156
+                      of this method (except the callback) and should
157
+                      return the same as this function
158
+
159
+
160
+    @returns  The following tuple
161
+        @return 1  Subtask slug (replaced None for default)
162
+        @rtype  str
163
+        @return 2  Botclass of given subtask (Arg "-task")
164
+        @rtype  Class
165
+        @return 3  GenFactory with parsed pagegenerator args
166
+        @rtype  pagegenerators.GeneratorFactory
167
+        @return 4  Additional args for subtasks
168
+        @rtype  dict
169
+    @rtype  tuple
170
+    """
171
+    # kwargs are passed to selected bot as **kwargs
172
+    kwargs = dict()
173
+
174
+    if callable( callback ):
175
+        ( subtask, Bot, genFactory, subtask_args ) = callback(
176
+            task_slug, subtask, genFactory, subtask_args )
177
+    # Subtask error
178
+    else:
179
+        jogobot.output( (
180
+            "\03{{red}} Given prepare_bot_callback from \"{task_slug}\" " +
181
+            "is not callable!" ).format(task_slug=task_slug), "ERROR" )
182
+        raise Exception
183
+
184
+    return ( subtask, Bot, genFactory, kwargs )
185
+
186
+
187
+def init_bot( task_slug, subtask, Bot, genFactory, **kwargs ):
188
+    """
189
+    Initiates Bot-Object with Class given in Bot and passes params genFactory
190
+    and kwargs to it
191
+
192
+    Passes through exception generated by Bot.__init__() after logging.
193
+
194
+    @param  task_slug  Task slug, needed for logging
195
+    @type task_slug  str
196
+    @param  subtask  Slug of given subtask
197
+    @type  subtask  str
198
+    @param  Bot  Bot class to build bot-object from
199
+    @type  Class
200
+    @param  genFactory  GenFactory with parsed pagegenerator args
201
+    @type  genFactory  pagegenerators.GeneratorFactory
202
+    @param  **kwargs  Additional args for Bot()
203
+    @type  **kwargs  dict
204
+
205
+    @returns bot-object
206
+    @type  type(Bot())
207
+    """
208
+    # Bot gets prepared genFactory as first param and possible kwargs dict
209
+    # It has to threw an exception if something does not work properly
210
+    try:
211
+        # Init bot with genFactory and **kwargs
212
+        bot = Bot( genFactory, **kwargs )
213
+
214
+    except:
215
+        # Catch Errors while initiation
216
+        jogobot.output( (
217
+            "\03{{red}} Error while trying to init " +
218
+            "subtask \"{task_slug}-{subtask}\"!" ).
219
+            format( task_slug=task_slug, subtask=subtask ), "ERROR" )
220
+        raise
221
+    else:
222
+        # Init successfull
223
+        jogobot.output( (
224
+            "Subtask \"{task_slug}-{subtask}\" was " +
225
+            "initiated successfully" ).
226
+            format(task_slug=task_slug, subtask=subtask) )
227
+        return bot
228
+
229
+
230
+def run_bot( task_slug, subtask, bot ):
231
+    """
232
+    Calls the run()-method of bot-object
233
+
234
+    Passes through exceptions generated by Bot.__init__() after logging.
235
+    Catches Errors caused by missing run(0-method.
236
+
237
+    @param  task_slug  Task slug, needed for logging
238
+    @type task_slug  str
239
+    @param  subtask  Slug of given subtask
240
+    @type  subtask  str
241
+    @param  bot  Bot object to call run()-method on
242
+    @type  object with method run
243
+    """
244
+
245
+    # Fire up Bot
246
+    # Bot must have implemented a run()-method
247
+    # It has to threw an exception if something does not work properly
248
+    try:
249
+        # Call run method on Bot
250
+        bot.run()
251
+
252
+    # Special event on AttributeError to catch missing run()-method
253
+    except AttributeError:
254
+        (type, value, traceback) = sys.exc_info()
255
+
256
+        # Catch missing run()-method
257
+        if "has no attribute 'run'" in value:
258
+            jogobot.output( (
259
+                "\03{{red}} Error while trying to run " +
260
+                "subtask \"{task_slug}-{subtask} \": +"
261
+                "Run-method is missing! ").
262
+                format( task_slug=task_slug, subtask=subtask ), "ERROR" )
263
+
264
+        # Pass through other AttributeError
265
+        else:
266
+            raise
267
+
268
+    except:
269
+        jogobot.output( (
270
+            "\03{{red}} Error while trying to run " +
271
+            "subtask \"{task_slug}-{subtask} \"!" ).
272
+            format( task_slug=task_slug, subtask=subtask ), "ERROR" )
273
+        raise
274
+
275
+    else:
276
+        # Run successfull
277
+        jogobot.output( (
278
+            "Subtask \"{task_slug}-{subtask}\" was finished successfully").
279
+            format(task_slug=task_slug, subtask=subtask) )

+ 96
- 0
config.py View File

@@ -0,0 +1,96 @@
1
+#!/usr/bin/env python3
2
+# -*- coding: utf-8  -*-
3
+#
4
+#  config.py
5
+#
6
+#  Copyright 2017 Jonathan Golder <jonathan@golderweb.de>
7
+#
8
+#  This program is free software; you can redistribute it and/or modify
9
+#  it under the terms of the GNU General Public License as published by
10
+#  the Free Software Foundation; either version 2 of the License, or
11
+#  (at your option) any later version.
12
+#
13
+#  This program is distributed in the hope that it will be useful,
14
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
+#  GNU General Public License for more details.
17
+#
18
+#  You should have received a copy of the GNU General Public License
19
+#  along with this program; if not, write to the Free Software
20
+#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
+#  MA 02110-1301, USA.
22
+#
23
+#
24
+"""
25
+This module will read config for jogobot from config file (ini-style) using
26
+python standard library module configparser
27
+"""
28
+
29
+import configparser
30
+import ast
31
+
32
+import pywikibot
33
+
34
+
35
+def load_config():
36
+    """
37
+    Reads raw configuration from file and provides it as attribute
38
+
39
+    @param  Config-Object
40
+    @r-type  configparser.ConfigParser
41
+    """
42
+    # Load configparser
43
+    config = configparser.ConfigParser(interpolation=None)
44
+    # Load config file
45
+    config.read(pywikibot.config.get_base_dir() + "/jogobot.conf")
46
+
47
+    return config
48
+
49
+
50
+def parse_config( raw_config ):
51
+    """
52
+    Converts config to normal dictionary
53
+    Parses each entry with ast.literal_eval
54
+
55
+    @param config  Config-Object to parse
56
+    @type config  configparser.ConfigParser
57
+
58
+    @return  Parsed configuration
59
+    @rtype  dict
60
+    """
61
+    # Convert to dict as configparser could contain only strings
62
+    config = dict( raw_config )
63
+
64
+    # Parse all sections
65
+    for section in raw_config.sections():
66
+        # Convert to dict as configparser could contain only strings
67
+        config[section] = dict( raw_config[section] )
68
+
69
+        # Parse config with ast.literal_eval to get python datatypes
70
+        for key, value in config[section].items():
71
+            config[section][key] = ast.literal_eval( value )
72
+
73
+    return config
74
+
75
+
76
+def root_section( config, section="jogobot" ):
77
+    """
78
+    Make 'section' entrys available in root level (without sections)
79
+
80
+    @param config  Config-Object to parse
81
+    @type config  dict
82
+
83
+    @return  Parsed configuration
84
+    @rtype  dict
85
+    """
86
+    for key, value in config[section].items():
87
+        config[key] = value
88
+
89
+    return config
90
+
91
+# Load config
92
+config = load_config()
93
+# Parse config to get python datatypes
94
+config = parse_config( config )
95
+# Make jogobot section available as root
96
+config = root_section( config )

+ 287
- 75
jogobot.py View File

@@ -3,7 +3,7 @@
3 3
 #
4 4
 #  jogobot.py
5 5
 #
6
-#  Copyright 2015 GOLDERWEB – Jonathan Golder <jonathan@golderweb.de>
6
+#  Copyright 2017 Jonathan Golder <jonathan@golderweb.de>
7 7
 #
8 8
 #  This program is free software; you can redistribute it and/or modify
9 9
 #  it under the terms of the GNU General Public License as published by
@@ -23,15 +23,199 @@
23 23
 #
24 24
 
25 25
 import os
26
+import shlex
27
+from datetime import datetime
26 28
 from email.mime.text import MIMEText
27 29
 from subprocess import Popen, PIPE, TimeoutExpired
28 30
 
29 31
 import pywikibot
30 32
 
33
+# Location of logging related stuff in pywikibot was changed with
34
+# commit d7d7a14 on Mon Sep 7 14:41:43 2015
35
+# This is to be compatible with recent versions as well as 2.0-branch
36
+try:
37
+    from pywikibot.logging import(
38
+        DEBUG, INFO, WARNING, ERROR, CRITICAL, STDOUT, VERBOSE, logoutput )
39
+except( ImportError ):
40
+    # Legacy support (pywikibot 2.0 branch)
41
+    from pywikibot.bot import(
42
+        DEBUG, INFO, WARNING, ERROR, CRITICAL, STDOUT, VERBOSE, logoutput )
31 43
 
32
-class JogoBot:
44
+from jogobot.config import config
45
+
46
+
47
+def output( text, level="INFO", decoder=None, newline=True,
48
+            layer=None, **kwargs ):
49
+    """
50
+    Wrapper for pywikibot output functions
51
+    """
52
+
53
+    text = datetime.utcnow().strftime( config["log_timestamp"] ) + " " + text
54
+
55
+    if ( level.upper() == "STDOUT" ):
56
+        _level = STDOUT
57
+    elif( level.upper() == "INFO" ):
58
+        _level = INFO
59
+    elif( level.upper() == "WARNING" ):
60
+        _level = WARNING
61
+    elif( level.upper() == "ERROR" ):
62
+        _level = ERROR
63
+    elif( level.upper() == "LOG" or level.upper() == "VERBOSE" ):
64
+        _level = VERBOSE
65
+    elif( level.upper() == "CRITICAL" ):
66
+        _level = CRITICAL
67
+    elif( level.upper() == "DEBUG" ):
68
+        _level = DEBUG
69
+    else:
70
+        pass
71
+
72
+    if ( level == DEBUG ):
73
+        logoutput(text, decoder, newline, _level, layer, **kwargs)
74
+    else:
75
+        logoutput(text, decoder, newline, _level, **kwargs)
76
+
77
+
78
+# Since we like to have timestamps in Output for logging, we replace
79
+# pywikibot.output with jogobot.output via monkey patching
80
+def pywikibot_output( text, decoder=None, newline=True,
81
+                      toStdout=False, **kwargs ):
82
+    r"""Output a message to the user via the userinterface.
83
+
84
+    Works like print, but uses the encoding used by the user's console
85
+    (console_encoding in the configuration file) instead of ASCII.
86
+
87
+    If decoder is None, text should be a unicode string. Otherwise it
88
+    should be encoded in the given encoding.
89
+
90
+    If newline is True, a line feed will be added after printing the text.
91
+
92
+    If toStdout is True, the text will be sent to standard output,
93
+    so that it can be piped to another process. All other text will
94
+    be sent to stderr. See: https://en.wikipedia.org/wiki/Pipeline_%28Unix%29
95
+
96
+    text can contain special sequences to create colored output. These
97
+    consist of the escape character \03 and the color name in curly braces,
98
+    e. g. \03{lightpurple}. \03{default} resets the color.
99
+
100
+    Other keyword arguments are passed unchanged to the logger; so far, the
101
+    only argument that is useful is "exc_info=True", which causes the
102
+    log message to include an exception traceback.
103
+
104
+    """
105
+    if toStdout:  # maintained for backwards-compatibity only
106
+        output(text, "STDOUT", decoder, newline, **kwargs)
107
+    else:
108
+        output(text, "INFO", decoder, newline, **kwargs)
109
+
110
+pywikibot.output = pywikibot_output
111
+
112
+
113
+def sendmail( Subject, Body, To=None, CC=None, BCC=None,
114
+              From=config["mail_from"] ):
115
+    """
116
+    Provides a simple wrapper for exim (MTA) on tool labs
117
+    Params should be formated according related fields in RFC 5322
118
+
119
+    @param subject  Mail subject
120
+    @type subject str
121
+    @param body    Mail body as (formated) string
122
+    @type body  unicode-str
123
+    @param to   Mail-Recipiends (comma-separeded)
124
+    @type str
125
+    @param from Mail-Sender
126
+    @type str
127
+    """
128
+
129
+    # Create mail body as MIME-Object
130
+    msg = MIMEText(Body)
131
+
132
+    # Set up mail header
133
+    msg['Subject'] = Subject
134
+
135
+    msg['From'] = From
136
+
137
+    if To:
138
+        msg['To'] = To
139
+
140
+    if CC:
141
+        msg['CC'] = CC
142
+
143
+    if BCC:
144
+        msg['BCC'] = BCC
145
+
146
+    msg['Content-Type'] = 'text/plain; charset="utf-8"'
147
+
148
+    # Make sure we have a recipient
149
+    if not( To or CC or BCC):
150
+        raise MailError( "No recipient was provided!" )
151
+
152
+    # We have no local MTA so we need to catch errors and write to file instead
153
+    try:
154
+        # Send the message via exim
155
+        with Popen( shlex.split(config['mail_cmd']), stdin=PIPE,
156
+                    universal_newlines=True ) as MTA:
157
+
158
+            MTA.communicate(msg.as_string())
159
+
160
+            # Try to get returncode of MTA
161
+            # Process is not terminated until timeout, set returncode to None
162
+            try:
163
+                returncode = MTA.wait(timeout=30)
164
+            except TimeoutExpired:
165
+                returncode = None
166
+
167
+        # Catch MTA errors
168
+        if returncode:
169
+            raise MailError( "/usr/sbin/exim terminated with " +
170
+                             "returncode != 0. Returncode was " +
171
+                             str( returncode ) )
172
+
173
+    except FileNotFoundError:
174
+
175
+        # Local fallback
176
+        with open( config["dir"] + "/Mail.txt", "a" ) as mail:
177
+            mail.write( "\n\n" )
178
+            mail.write( datetime.utcnow().strftime( config["log_timestamp"]))
179
+            mail.write( "\n" + msg.as_string() )
180
+
181
+
182
+def is_active( task_slug, write=True ):
33 183
     """
34
-    Basic bot framework
184
+    Simple wrapper function for our ActiveAPI to use in Tasks
185
+    """
186
+
187
+    status = StatusAPI()
188
+
189
+    # First check if Bot is blocked
190
+    if write and status.is_blocked():
191
+
192
+        status.blocked()
193
+
194
+    task_slugs = ( None, task_slug )
195
+
196
+    for _task_slug in task_slugs:
197
+        # Then check if whole Bot is disabled by file
198
+        if status.is_disabled_by_file(_task_slug):
199
+
200
+            # Disabling by file normaly results out of Disabling on wiki
201
+            if status.is_disabled_on_wiki(_task_slug):
202
+
203
+                status.disabled_on_wiki(_task_slug, True)
204
+
205
+            else:
206
+
207
+                status.disabled_by_file(_task_slug)
208
+
209
+        # Status disabled is set on wiki but not yet by file
210
+        elif status.is_disabled_on_wiki(_task_slug):
211
+
212
+                status.disabled_on_wiki(_task_slug)
213
+
214
+
215
+class StatusAPI:
216
+    """
217
+    Provide an API for checking if Jogobot or specific task is blocked,
218
+    disabled on wiki or by file
35 219
     """
36 220
 
37 221
     def __init__( self ):
@@ -43,18 +227,9 @@ class JogoBot:
43 227
         self.site = pywikibot.Site()
44 228
 
45 229
         # We need the shell working directory
46
-        self.cwd = os.getcwd()
47
-
48
-    def is_active( self ):
49
-        """
50
-        Checks if whole bot or task specified by task_slug is:
51
-        * not blocked
52
-        * not disabled by file
53
-        * not disabled on wiki
54
-        """
55
-        pass
230
+        self.cwd = config["dir"]
56 231
 
57
-    def is_active_on_wiki( self, task_slug=None ):
232
+    def is_disabled_on_wiki( self, task_slug=None ):
58 233
         """
59 234
         Checks if whole bot or task specified by task_slug is disabled
60 235
         on wiki
@@ -65,37 +240,35 @@ class JogoBot:
65 240
 
66 241
         # Define page for look up
67 242
         if task_slug:
68
-            page_title = "Benutzer:JogoBot/" + task_slug + "/active.js"
243
+            page_title = "Benutzer:JogoBot/" + task_slug + "/active"
69 244
         else:
70 245
             page_title = "Benutzer:JogoBot/active"
71 246
 
72 247
         # Get pywikibot page object
73 248
         page = pywikibot.Page( self.site, page_title )
74 249
 
250
+        # Make sure page exists
251
+        if not page.exists():
252
+            raise DisablingPageError
253
+
75 254
         # Get page text
76 255
         page_text = page.get()
77 256
 
78 257
         if "true" not in page_text.lower():
79
-            pass
80
-            # Disabled
258
+            return True
81 259
 
82
-            # Return False
83
-            # Send E-Mail
84
-            # Create disable-file
260
+        return False
85 261
 
86
-    def is_blocked_on_wiki( self ):
262
+    def is_blocked( self ):
87 263
         """
88 264
         Checks if bot user is blocked on wiki
89 265
         """
90 266
         if self.site.is_blocked():
91
-            pass
92
-            # Blocked
267
+            return True
93 268
 
94
-            # Return False
95
-            # Send E-Mail
96
-            # Create disable-file
269
+        return False
97 270
 
98
-    def is_active_by_file(self, task_slug=None):
271
+    def is_disabled_by_file(self, task_slug=None):
99 272
         """
100 273
         Checks if whole bot or task specified by task_slug is disabled
101 274
         by file
@@ -111,11 +284,9 @@ class JogoBot:
111 284
             disable_file = self.cwd + "/disabled"
112 285
 
113 286
         if os.path.isfile( disable_file ):
114
-            pass
115
-            # Disabled
287
+            return True
116 288
 
117
-            # Return False
118
-            # Send E-Mail
289
+        return False
119 290
 
120 291
     def create_disable_file( self, task_slug=None ):
121 292
         """
@@ -135,66 +306,107 @@ class JogoBot:
135 306
         with open(disable_file, 'a'):
136 307
             pass
137 308
 
138
-    @staticmethod
139
-    def sendmail( Subject, Body, To=None, CC=None, BCC=None,
140
-                  From="JogoBot <tools.jogobot@tools.wmflabs.org>" ):
309
+    def blocked( self ):
310
+        """
311
+        Handles process if Bot user is blocked
141 312
         """
142
-        Provides a simple wrapper for exim (MTA) on tool labs
143
-        Params should be formated according related fields in RFC 5322
144 313
 
145
-        @param subject  Mail subject
146
-        @type subject str
147
-        @param body    Mail body as (formated) string
148
-        @type body  unicode-str
149
-        @param to   Mail-Recipiends (comma-separeded)
150
-        @type str
151
-        @param from Mail-Sender
152
-        @type str
314
+        # Mail-Fields
315
+        subject = "JogoBot: Bot-Account is blocked"
316
+        body = """Your Bot-Account is blocked on Wiki"""
317
+        mailto = "jogobot-status@golderweb.de"
318
+
319
+        sendmail( subject, body, mailto )
320
+
321
+        raise Blocked( body )
322
+
323
+    def disabled_by_file( self, task_slug=None ):
324
+        """
325
+        Handles process if Bot/Task is disabled by file
153 326
         """
154 327
 
155
-        # Create mail body as MIME-Object
156
-        msg = MIMEText(Body)
328
+        if task_slug:
329
+            subject = "JogoBot: Task " + task_slug + " is disabled by file!"
330
+            body = """
331
+The Bot-Task with slug %s is disabled by file!
332
+""" % task_slug
333
+            mailto = "jogobot-" + task_slug + "-status@golderweb.de"
157 334
 
158
-        # Set up mail header
159
-        msg['Subject'] = Subject
335
+        else:
336
+            subject = "JogoBot: Bot is disabled by file!"
337
+            body = """The Bot is disabled by file!"""
338
+            mailto = "jogobot-status@golderweb.de"
160 339
 
161
-        msg['From'] = From
340
+        sendmail( subject, body, mailto )
162 341
 
163
-        if To:
164
-            msg['To'] = To
342
+        raise DisabledByFile( body )
165 343
 
166
-        if CC:
167
-            msg['CC'] = CC
344
+    def disabled_on_wiki( self, task_slug=None, file=False ):
345
+        """
346
+        Handles process if Bot/Task is disabled on wiki
347
+        """
168 348
 
169
-        if BCC:
170
-            msg['BCC'] = BCC
349
+        if file:
350
+            suffix = " and also by file!"
351
+        else:
352
+            suffix = "!\nA disabled file is going to be created."
171 353
 
172
-        msg['Content-Type'] = 'text/plain; charset=utf-8'
354
+        if task_slug:
355
+            subject = "JogoBot: Task " + task_slug + " is disabled on wiki!"
356
+            body = """
357
+The Bot-Task with slug %s is disabled on wiki%s
358
+""" % (task_slug, suffix)
359
+            mailto = "jogobot-" + task_slug + "-status@golderweb.de"
360
+        else:
361
+            subject = "JogoBot: Bot is disabled on wiki!"
362
+            body = """
363
+The Bot is disabled by on wiki%s
364
+""" % suffix
365
+            mailto = "jogobot-status@golderweb.de"
173 366
 
174
-        # Make sure we have a recipient
175
-        if not( To or CC or BCC):
176
-            raise JogoBotMailError( "No recipient was provided!" )
367
+        sendmail( subject, body, mailto )
177 368
 
178
-        # Send the message via exim
179
-        with Popen( ["/usr/sbin/exim", "-odf", "-i", "-t"],
180
-                    stdin=PIPE, universal_newlines=True) as MTA:
181
-            MTA.communicate(msg.as_string())
369
+        self.create_disable_file( task_slug )
182 370
 
183
-            # Try to get returncode of MTA
184
-            # Process is not terminated until timeout, set returncode to None
185
-            try:
186
-                returncode = MTA.wait(timeout=30)
187
-            except TimeoutExpired:
188
-                returncode = None
371
+        raise DisabledOnWiki( body )
189 372
 
190
-        # Catch MTA errors
191
-        if returncode:
192
-            raise JogoBotMailError( "/usr/sbin/exim terminated with " +
193
-                                    "returncode != 0. Returncode was " +
194
-                                    str( returncode ) )
373
+
374
+class Disabled( Exception ):
375
+    """
376
+    Handles disabled Bot/Task
377
+    """
378
+    pass
379
+
380
+
381
+class DisablingPageError( Disabled ):
382
+    """
383
+    Handles errors with missing disabling pages
384
+    """
385
+    pass
386
+
387
+
388
+class Blocked( Disabled ):
389
+    """
390
+    Raised if Bot-Account is blocked
391
+    """
392
+    pass
393
+
394
+
395
+class DisabledByFile( Disabled ):
396
+    """
397
+    Raised if Bot/Task is disabled by File
398
+    """
399
+    pass
400
+
401
+
402
+class DisabledOnWiki( Disabled ):
403
+    """
404
+    Raised if Bot/Task is disabled on Wiki
405
+    """
406
+    pass
195 407
 
196 408
 
197
-class JogoBotMailError( Exception ):
409
+class MailError( Exception ):
198 410
     """
199 411
     Handles errors occuring in class JogoBot related to mail actions
200 412
     """

+ 188
- 0
license.txt View File

@@ -0,0 +1,188 @@
1
+GNU GENERAL PUBLIC LICENSE
2
+
3
+Version 3, 29 June 2007
4
+
5
+Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
6
+
7
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
8
+
9
+Preamble
10
+
11
+The GNU General Public License is a free, copyleft license for software and other kinds of works.
12
+
13
+The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
14
+
15
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
16
+
17
+To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
18
+
19
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
20
+
21
+Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
22
+
23
+For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
24
+
25
+Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
26
+
27
+Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
28
+
29
+The precise terms and conditions for copying, distribution and modification follow.
30
+TERMS AND CONDITIONS
31
+0. Definitions.
32
+
33
+“This License” refers to version 3 of the GNU General Public License.
34
+
35
+“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
36
+
37
+“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
38
+
39
+To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
40
+
41
+A “covered work” means either the unmodified Program or a work based on the Program.
42
+
43
+To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
44
+
45
+To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
46
+
47
+An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
48
+1. Source Code.
49
+
50
+The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
51
+
52
+A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
53
+
54
+The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
55
+
56
+The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
57
+
58
+The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
59
+
60
+The Corresponding Source for a work in source code form is that same work.
61
+2. Basic Permissions.
62
+
63
+All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
64
+
65
+You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
66
+
67
+Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
68
+3. Protecting Users' Legal Rights From Anti-Circumvention Law.
69
+
70
+No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
71
+
72
+When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
73
+4. Conveying Verbatim Copies.
74
+
75
+You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
76
+
77
+You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
78
+5. Conveying Modified Source Versions.
79
+
80
+You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
81
+
82
+    a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
83
+    b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
84
+    c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
85
+    d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
86
+
87
+A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
88
+6. Conveying Non-Source Forms.
89
+
90
+You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
91
+
92
+    a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
93
+    b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
94
+    c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
95
+    d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
96
+    e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
97
+
98
+A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
99
+
100
+A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
101
+
102
+“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
103
+
104
+If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
105
+
106
+The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
107
+
108
+Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
109
+7. Additional Terms.
110
+
111
+“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
112
+
113
+When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
114
+
115
+Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
116
+
117
+    a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
118
+    b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
119
+    c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
120
+    d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
121
+    e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
122
+    f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
123
+
124
+All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
125
+
126
+If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
127
+
128
+Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
129
+8. Termination.
130
+
131
+You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
132
+
133
+However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
134
+
135
+Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
136
+
137
+Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
138
+9. Acceptance Not Required for Having Copies.
139
+
140
+You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
141
+10. Automatic Licensing of Downstream Recipients.
142
+
143
+Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
144
+
145
+An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
146
+
147
+You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
148
+11. Patents.
149
+
150
+A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
151
+
152
+A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
153
+
154
+Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
155
+
156
+In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
157
+
158
+If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
159
+
160
+If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
161
+
162
+A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
163
+
164
+Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
165
+12. No Surrender of Others' Freedom.
166
+
167
+If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
168
+13. Use with the GNU Affero General Public License.
169
+
170
+Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
171
+14. Revised Versions of this License.
172
+
173
+The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
174
+
175
+Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
176
+
177
+If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
178
+
179
+Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
180
+15. Disclaimer of Warranty.
181
+
182
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
183
+16. Limitation of Liability.
184
+
185
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
186
+17. Interpretation of Sections 15 and 16.
187
+
188
+If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.