Class: MediaWiki::Butt

Inherits:
Object
  • Object
show all
Includes:
Administration, Auth, Constants, Edit, Purge, Query, Query::Lists, Query::Meta::FileRepoInfo, Query::Meta::SiteInfo, Query::Meta::UserInfo, Query::Properties, Watch
Defined in:
lib/mediawiki/butt.rb,
lib/mediawiki/exceptions.rb

Defined Under Namespace

Classes: AuthenticationError, BlockError, EditError, NotBotError, NotLoggedInError, PatrolError, UploadInvalidFileExtError

Constant Summary

Constants included from Constants

Constants::MISSING_PAGEID_PROC, Constants::NAMESPACES

Constants included from Query::Meta

Query::Meta::TOKEN_TYPES

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Purge

#purge, #purge_link_update, #purge_recursive_link_update, #purge_request

Methods included from Watch

#unwatch, #watch, #watch_request

Methods included from Administration

#block, #unblock

Methods included from Edit

#create_page, #delete, #edit, #move, #patrol, #upload

Methods included from Query::Lists::QueryPage

#get_ancientpages_page, #get_brokenredirects_page, #get_doubleredirects_page, #get_fewestrevisions_page, #get_listduplicatedfiles_page, #get_listredirects_page, #get_lonelypages_page, #get_longpages_page, #get_mostcategories_page, #get_mostimages_page, #get_mostinterwikis_page, #get_mostlinked_page, #get_mostlinkedcategories_page, #get_mostlinkedtemplates_page, #get_mostrevisions_page, #get_querypage, #get_shortpages_page, #get_uncategorizedcategories_page, #get_uncategorizedpages_page, #get_uncategorizedtemplates_page, #get_unusedcategories_page, #get_unusedtemplates_page, #get_unwatchedpages_page, #get_wantedcategories_page, #get_wantedfiles_page, #get_wantedpages_page, #get_wantedtemplates_page, #get_withoutinterwiki_page

Methods included from Query::Lists::Users

#get_contrib_count, #get_full_watchlist, #get_registration_time, #get_user_contributions, #get_user_gender, #get_usergroups, #get_userlists, #get_userrights

Methods included from Query::Lists::RecentChanges

#get_recent_changes, #get_recent_deleted_revisions

Methods included from Query::Lists::Log

#get_log, #get_overall_log, #loghash_block, #loghash_general, #loghash_importinterwiki, #loghash_importupload, #loghash_merge, #loghash_move, #loghash_patrol, #loghash_protect, #loghash_protectmoveprot, #loghash_protectunprotect, #loghash_rightsautopromote, #loghash_rightsrights, #loghash_unblock, #loghash_upload, #loghash_user

Methods included from Query::Lists::Log::Upload

#get_upload_log, #get_upload_overwrite_log

Methods included from Query::Lists::Log::Rights

#get_autopromotion_log, #get_rights_log

Methods included from Query::Lists::Log::Protect

#get_modify_protection_log, #get_move_protected_log, #get_protect_log, #get_unprotect_log

Methods included from Query::Lists::Log::Patrol

#get_patrol_log

Methods included from Query::Lists::Log::NewUsers

#get_autocreate_users_log, #get_user_create2_log, #get_user_create_log

Methods included from Query::Lists::Log::Move

#get_move_log, #get_move_redirect_log

Methods included from Query::Lists::Log::Merge

#get_merge_log

Methods included from Query::Lists::Log::Import

#get_interwiki_import_log, #get_upload_import_log

Methods included from Query::Lists::Log::Delete

#get_delete_log, #get_deletion_restore_log

Methods included from Query::Lists::Log::Block

#get_block_log, #get_reblock_log, #get_unblock_log

Methods included from Query::Lists::Miscellaneous

#get_random_pages, #get_tags

Methods included from Query::Lists::Search

#get_prefix_search, #get_search_result_amount, #get_search_results, #get_search_text_results

Methods included from Query::Lists::All

#get_all_blocks, #get_all_categories, #get_all_deleted_files, #get_all_images, #get_all_pages_in_namespace, #get_all_protected_titles, #get_all_transcluders, #get_all_users

Methods included from Query::Lists::Categories

#get_category_members, #get_files_in_category, #get_subcategories

Methods included from Query::Lists::Backlinks

#get_image_backlinks, #get_interwiki_backlinks, #get_language_backlinks, #get_url_backlinks, #what_links_here

Methods included from Query::Properties::Files

#get_all_duplicated_files, #get_duplicated_files_of, #get_image_bytes, #get_image_dimensions, #get_image_sizes

Methods included from Query::Properties::Pages

#can_i_read?, #do_i_watch?, #get_all_links_in_page, #get_basic_page_info, #get_categories_in_page, #get_display_title, #get_external_links, #get_id, #get_images_in_page, #get_interwiki_links_in_page, #get_number_of_watchers, #get_other_langs_of_page, #get_page_size, #get_protection_levels, #get_templates_in_page, #get_text, #page_info_contains_key, #page_info_get_val, #page_new?, #page_redirect?

Methods included from Query::Properties::Contributors

#get_anonymous_contributors_count, #get_contributors_response, #get_logged_in_contributors, #get_total_contributors

Methods included from Query::Meta::UserInfo

#current_user_hasmsg?, #get_changeable_groups, #get_current_user_meta, #get_current_user_name, #get_current_user_options, #get_email_address, #get_realname

Methods included from Query::Meta::FileRepoInfo

#get_filerepo_favicons, #get_filerepo_names, #get_filerepo_rooturls, #get_filerepo_thumburls, #get_filerepo_urls, #get_filerepoinfo, #get_local_filerepos, #get_nonlocal_filerepos

Methods included from Query::Meta::SiteInfo

#get_all_usergroups, #get_allowed_file_extensions, #get_article_path, #get_base_article_path, #get_extension_tags, #get_extensions, #get_function_hooks, #get_general, #get_languages, #get_magic_words, #get_namespace_aliases, #get_namespaces, #get_restriction_levels, #get_restriction_types, #get_restrictions_data, #get_server, #get_siteinfo, #get_skins, #get_special_page_aliases, #get_statistics, #get_variables

Methods included from Query::Meta

#get_token

Methods included from Auth

#create_account, #create_account_email, #login, #logout

Constructor Details

#initialize(url, opts = {}) ⇒ Butt

Creates a new instance of MediaWiki::Butt.

Parameters:

  • url (String)

    The FULL wiki URL. api.php can be omitted, but it will make harsh assumptions about your wiki configuration.

  • opts (Hash<Symbol, Any>) (defaults to: {})

    The options hash for configuring this instance of Butt.

Options Hash (opts):

  • :custom_agent (String)

    A custom User-Agent to use. Optional.

  • :query_limit_default (Fixnum)

    The query limit to use if no limit parameter is explicitly given to the various query methods. In other words, if you pass a limit parameter to the valid query methods, it will use that, otherwise, it will use this. Defaults to ‘max’ to use MW’s default max for each API.

  • :use_continuation (Boolean)

    Whether to use the continuation API on queries. Defaults to true.

  • :assertion (Symbol)

    If set to :user or :bot, will use the assert parameter in all requests. Setting this will open up the possibility for NotLoggedInErrors and NotBotErrors. It is important to keep in mind that methods that check if the user is logged in do not use the API, but check if the user has ever logged in as this Butt instance. In other words, it is a safety check for performance and not a valid API check.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/mediawiki/butt.rb', line 43

def initialize(url, opts = {})
  @url = url =~ /api.php$/ ? url : "#{url}/api.php"
  @query_limit_default = opts[:query_limit_default] || 'max'
  @custom_agent = opts[:custom_agent]
  @session = Patron::Session.new
  @session.timeout = 60
  @session.handle_cookies
  @session.headers['User-Agent'] = @custom_agent if @custom_agent
  @logged_in = false
  @use_continuation = opts[:use_continuation] || true
  # Token cache, populated in #get_token and depopulated in #post. Type => Token
  @tokens = {}
  # The most recent kind of token acquired. Used in #post, set/reset in #get_token.
  @prev_token_type = ''
  # Set to prevent token cache handling from producing an infinite call loop. Defaults to true, set to false when
  # token recache is being handled.
  @first_token_try = true

  assertion = opts[:assertion]
  @assertion = assertion == :user || assertion == :bot ? assertion : nil
end

Instance Attribute Details

#assertionObject

Returns the value of attribute assertion.



28
29
30
# File 'lib/mediawiki/butt.rb', line 28

def assertion
  @assertion
end

#query_limit_defaultObject

Returns the value of attribute query_limit_default.



26
27
28
# File 'lib/mediawiki/butt.rb', line 26

def query_limit_default
  @query_limit_default
end

#use_continuationObject

Returns the value of attribute use_continuation.



27
28
29
# File 'lib/mediawiki/butt.rb', line 27

def use_continuation
  @use_continuation
end

Instance Method Details

#get_limited(integer, max_user = 500, max_bot = 5000) ⇒ Fixnum (protected)

Gets the limited version of the integer, to ensure nobody provides an int that is too large.

Parameters:

  • integer (Fixnum)

    The number to limit.

  • max_user (Fixnum) (defaults to: 500)

    The maximum limit for normal users.

  • max_bot (Fixnum) (defaults to: 5000)

    The maximum limit for bot users.

Returns:

  • (Fixnum)

    The capped number.

Since:

  • 0.8.0



179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/mediawiki/butt.rb', line 179

def get_limited(integer, max_user = 500, max_bot = 5000)
  if integer.is_a?(String)
    return integer if integer == 'max'
    return 500
  end
  return integer if integer <= max_user

  if user_bot?
    integer > max_bot ? max_bot : integer
  else
    max_user
  end
end

#logged_in?Boolean

Checks whether this instance is logged in.

Returns:

  • (Boolean)

    true if logged in, false if not.



164
165
166
167
168
169
# File 'lib/mediawiki/butt.rb', line 164

def logged_in?
  post({ action: 'query', assert: 'user' })
  true
rescue MediaWiki::Butt::NotLoggedInError
  false
end

#post(params) ⇒ Hash

Performs an HTTP POST request and provides the response. This method generally should not be used by the user, unless there is not a helper method provided by Butt for a particular action.

Parameters:

  • params (Hash)

    A hash containing MediaWiki API parameters. Please see the MediaWiki API for more information. The method automatically sets the format and assert values, unless they are specified in this hash argument.

Returns:

  • (Hash)

    Parsed JSON returned by the MediaWiki API

Since:

  • 0.1.0



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
# File 'lib/mediawiki/butt.rb', line 72

def post(params)
  base_params = {
    format: 'json'
  }
  base_params[:assert] = @assertion.to_s if @assertion
  params = base_params.merge(params)

  unless @custom_agent
    @session.headers['User-Agent'] = @logged_in ? "#{@name}/MediaWiki::Butt" : 'NotLoggedIn/MediaWiki::Butt'
  end

  response = JSON.parse(@session.post(@url, params).body)

  # If our tokens have expired, clear them, re-set the relevant token argument, and re-call this #post method
  if response.dig('error', 'code') == 'badtoken' && @first_token_try
    @tokens.clear
    token_param = params.keys.select { |i| i.to_s.end_with?('token') }[0]
    params[token_param] = get_token(@prev_token_type)
    # Prevent token retry attempt in next #post call
    @first_token_try = false
    return post(params)
  end
  # Reset token retry value if no badtoken error has occurred.
  @first_token_try = true

  if @assertion
    code = response.dig('error', 'code')
    fail MediaWiki::Butt::NotLoggedInError.new(response['error']['info']) if code == 'assertuserfailed'
    fail MediaWiki::Butt::NotBotError.new(response['error']['info']) if code == 'assertbotfailed'
  end
  response
end

#query(params, base_return = []) {|base_return, query| ... } ⇒ Any

Performs a Mediawiki API query and provides the response, dealing with continuation as necessary.

Parameters:

  • params (Hash)

    A hash containing MediaWiki API parameters.

  • base_return (Any) (defaults to: [])

    The return value to start with. Defaults to an empty array.

Yields:

  • (base_return, query)

    Provides the value provided to the base_return parameter, and the value in the ‘query’ key in the API response. See the API documentation for more information on this. If the base_return value is modified in the block, its modifications will persist across each continuation loop.

Returns:

  • (Any)

    The base_return value as modified by the yielded block.



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/mediawiki/butt.rb', line 112

def query(params, base_return = [])
  params[:action] = 'query'
  params[:continue] = ''

  loop do
    result = post(params)
    yield(base_return, result['query']) if result.key?('query')
    break unless @use_continuation
    break unless result.key?('continue')
    continue = result['continue']
    continue.each do |key, val|
      params[key.to_sym] = val
    end
  end

  base_return
end

#query_ary(params, base_response_key, property_key) ⇒ Object

Helper method for query methods that return an array built from the query objects.

Parameters:

  • params (Hash)

    A hash containing MediaWiki API parameters.

  • base_response_key (String)

    The key inside the “query” object to collect.

  • property_key (String)

    The key inside the object (under the base_response_key) to collect.



143
144
145
146
147
# File 'lib/mediawiki/butt.rb', line 143

def query_ary(params, base_response_key, property_key)
  query(params) do |return_val, query|
    return_val.concat(query[base_response_key].collect { |obj| obj[property_key] })
  end
end

#query_ary_irrelevant_keys(params, base_response_key, property_key) ⇒ Object

Helper method for query methods that return a two-dimensional hashes in which the keys are not relevant to the returning value. In most cases this key is a redundant page or revision ID that is also available in the object.

Parameters:

  • params (Hash)

    A hash containing MediaWiki API parameters.

  • base_response_key (String)

    The key inside the “query” object to collect.

  • property_key (String)

    The key inside the object (under the base_response_key) to collect.



133
134
135
136
137
# File 'lib/mediawiki/butt.rb', line 133

def query_ary_irrelevant_keys(params, base_response_key, property_key)
  query(params) do |return_val, query|
    return_val.concat(query[base_response_key].values.collect { |obj| obj[property_key] })
  end
end

#user_bot?Boolean

Gets whether the currently logged in user is a bot.

Returns:

  • (Boolean)

    true if logged in as a bot, false if not logged in or logged in as a non-bot

Since:

  • 0.1.0 as is_current_user_bot

  • 0.3.0 as is_user_bot?

  • 0.4.1 as user_bot?



155
156
157
158
159
160
# File 'lib/mediawiki/butt.rb', line 155

def user_bot?
  post({ action: 'query', assert: 'bot' })
  true
rescue MediaWiki::Butt::NotBotError
  false
end

#validate_namespace(namespace) ⇒ Fixnum (protected)

Safely validates the given namespace ID, and returns 0 for the main namespace if invalid.

Parameters:

  • namespace (Fixnum)

    The namespace ID.

Returns:

  • (Fixnum)

    Either the given namespace, if valid, or the main namespace ID 0 if invalid.



196
197
198
# File 'lib/mediawiki/butt.rb', line 196

def validate_namespace(namespace)
  MediaWiki::Constants::NAMESPACES.value?(namespace) ? namespace : 0
end