diff --git a/CHANGELOG.md b/CHANGELOG.md index 6954c2c..e8a2c9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## Version 0 ### Version 0.4.1 +* params[:format] is now automatically set to 'json', so it no longer needs to be defined in each method. +* Fixed a lot of styling issues thanks to Rubocop. * check_login and check_create now use case/when statements instead of elsifs. * check_create no longer returns anything. * Update minimum Ruby version to 2.1, for refinements. diff --git a/lib/mediawiki/auth.rb b/lib/mediawiki/auth.rb index f63bb6f..5d7a4de 100644 --- a/lib/mediawiki/auth.rb +++ b/lib/mediawiki/auth.rb @@ -2,85 +2,88 @@ module MediaWiki module Auth - - # Checks the login result for errors. Returns true if it is successful, else false with an error raised. + # Checks the login result for errors. Returns true if it is successful, + # else false with an error raised. # @param result [String] The parsed version of the result. - # @param secondtry [Boolean] Whether this login is the first or second try. False for first, true for second. + # @param secondtry [Boolean] Whether this login is the first or second try. + # False for first, true for second. # @return [Boolean] true if successful, else false. def check_login(result, secondtry) case result - when "Success" + when 'Success' @logged_in = true return true - when "NeedToken" + when 'NeedToken' if secondtry == true - raise MediaWiki::Butt::NeedTokenMoreThanOnceError + fail MediaWiki::Butt::NeedTokenMoreThanOnceError return false end - when "NoName" - raise MediaWiki::Butt::NoNameError + when 'NoName' + fail MediaWiki::Butt::NoNameError return false - when "Illegal" - raise MediaWiki::Butt::IllegalUsernameError + when 'Illegal' + fail MediaWiki::Butt::IllegalUsernameError return false - when "NotExists" - raise MediaWiki::Butt::UsernameNotExistsError + when 'NotExists' + fail MediaWiki::Butt::UsernameNotExistsError return false - when "EmptyPass" - raise MediaWiki::Butt::EmptyPassError + when 'EmptyPass' + fail MediaWiki::Butt::EmptyPassError return false - when "WrongPass" - raise MediaWiki::Butt::WrongPassError + when 'WrongPass' + fail MediaWiki::Butt::WrongPassError return false - when "WrongPluginPass" - raise MediaWiki::Butt::WrongPluginPassError + when 'WrongPluginPass' + fail MediaWiki::Butt::WrongPluginPassError return false - when "CreateBlocked" - raise MediaWiki::Butt::CreateBlockedError + when 'CreateBlocked' + fail MediaWiki::Butt::CreateBlockedError return false - when "Throttled" - raise MediaWiki::Butt::ThrottledError + when 'Throttled' + fail MediaWiki::Butt::ThrottledError return false - when "Blocked" - raise MediaWiki::Butt::BlockedError + when 'Blocked' + fail MediaWiki::Butt::BlockedError return false end end - # Checks the account creation result's error and raises the corresponding error. - # @param error [String] The parsed error "code" string + # Checks the account creation result's error and raises the corresponding + # exception. + # @param error [String] The parsed error code string def check_create(error) case error - when "noname" - raise MediaWiki::Butt::NoNameError - when "userexists" - raise MediaWiki::Butt::UserExistsError - when "password-name-match" - raise MediaWiki::Butt::UserPassMatchError - when "password-login-forbidden" - raise MediaWiki::Butt::PasswordLoginForbiddenError - when "noemailtitle" - raise MediaWiki::Butt::NoEmailTitleError - when "invalidemailaddress" - raise MediaWiki::Butt::InvalidEmailAddressError - when "passwordtooshort" - raise MediaWiki::Butt::PasswordTooShortError - when "noemail" - raise MediaWiki::Butt::NoEmailError - when "acct_creation_throttle_hit" - raise MediaWiki::Butt::ThrottledError - when "aborted" - raise MediaWiki::Butt::AbortedError - when "blocked" - raise MediaWiki::Butt::BlockedError - when "permdenied-createaccount" - raise MediaWiki::Butt::PermDeniedError - when "createaccount-hook-aborted" - raise MediaWiki::Butt::HookAbortedError + when 'noname' + fail MediaWiki::Butt::NoNameError + when 'userexists' + fail MediaWiki::Butt::UserExistsError + when 'password-name-match' + fail MediaWiki::Butt::UserPassMatchError + when 'password-login-forbidden' + fail MediaWiki::Butt::PasswordLoginForbiddenError + when 'noemailtitle' + fail MediaWiki::Butt::NoEmailTitleError + when 'invalidemailaddress' + fail MediaWiki::Butt::InvalidEmailAddressError + when 'passwordtooshort' + fail MediaWiki::Butt::PasswordTooShortError + when 'noemail' + fail MediaWiki::Butt::NoEmailError + when 'acct_creation_throttle_hit' + fail MediaWiki::Butt::ThrottledError + when 'aborted' + fail MediaWiki::Butt::AbortedError + when 'blocked' + fail MediaWiki::Butt::BlockedError + when 'permdenied-createaccount' + fail MediaWiki::Butt::PermDeniedError + when 'createaccount-hook-aborted' + fail MediaWiki::Butt::HookAbortedError end end - # Logs the user into the wiki. This is generally required for editing and getting restricted data. Will return the result of #check_login + # Logs the user into the wiki. This is generally required for editing and + # getting restricted data. Will return the result of #check_login # @param username [String] The username # @param password [String] The password # @return [Boolean] True if the login was successful, false if not. @@ -88,39 +91,39 @@ def login(username, password) params = { action: 'login', lgname: username, - lgpassword: password, - format: 'json' + lgpassword: password } result = post(params) - if check_login(result["login"]["result"], false) + if check_login(result['login']['result'], false) @logged_in = true @tokens.clear true - elsif result["login"]["result"] == "NeedToken" && result["login"]["token"] != nil - token = result["login"]["token"] + elsif result['login']['result'] == 'NeedToken' && + !result['login']['token'].nil? + token = result['login']['token'] token_params = { action: 'login', lgname: username, lgpassword: password, - format: 'json', lgtoken: token } - #Consider refactor the @cookie initialization. - @cookie = "#{result["login"]["cookieprefix"]}Session=#{result["login"]["sessionid"]}" - result = post(token_params, true, { 'Set-Cookie' => @cookie }) - check_login(result["login"]["result"], true) + # Consider refactor the @cookie initialization. + @cookie = "#{result['login']['cookieprefix']}" \ + "Session=#{result['login']['sessionid']}" + result = post(token_params, true, 'Set-Cookie' => @cookie) + check_login(result['login']['result'], true) end end # Logs the current user out. - # @return [Boolean] True if it was able to log anyone out, false if not (basically, if someone was logged in, it returns true). + # @return [Boolean] True if it was able to log anyone out, false if not + # (basically, if someone was logged in, it returns true). def logout if @logged_in params = { - action: 'logout', - format: 'json' + action: 'logout' } post(params) @@ -135,8 +138,11 @@ def logout # Creates an account using the standard procedure. # @param username [String] The desired username. # @param password [String] The desired password. - # @param language [String] The language code to be set as default for the account. Defaults to 'en', or English. Use the language code, not the name. - # @param reason [String] The reason for creating the account, as shown in the account creation log. Optional. + # @param language [String] The language code to be set as default for the + # account. Defaults to 'en', or English. Use the language code, not + # the name. + # @param reason [String] The reason for creating the account, as shown in + # the account creation log. Optional. # @return [Boolean] True if successful, false if not. def create_account(username, password, language = 'en', *reason) params = { @@ -148,28 +154,28 @@ def create_account(username, password, language = 'en', *reason) } result = post(params) - if result["error"] != nil - check_create(result["error"]["code"]) + unless result['error'].nil? + check_create(result['error']['code']) return false end - if result["createaccount"]["result"] == "Success" + if result['createaccount']['result'] == 'Success' @tokens.clear return true - elsif result["createaccount"]["result"] == "NeedToken" + elsif result['createaccount']['result'] == 'NeedToken' params = { name: username, password: password, reason: reason, language: language, - token: result["createaccount"]["token"] + token: result['createaccount']['token'] } result = post(params, true, true) - if result["error"] != nil - check_create(result["error"]["code"]) + if !result['error'].nil? + check_create(result['error']['code']) return false - elsif result["createaccount"]["result"] == "Success" + elsif result['createaccount']['result'] == 'Success' return true else return false @@ -180,8 +186,11 @@ def create_account(username, password, language = 'en', *reason) # Creates an account using the random password sent by email procedure. # @param username [String] The desired username # @param email [String] The desired email address - # @param language [String] The language code to be set as default for the account. Defaults to 'en', or English. Use the language code, not the name. - # @param reason [String] The reason for creating the account, as shown in the account creation log. Optional. + # @param language [String] The language code to be set as default for the + # account. Defaults to 'en', or English. Use the language code, not + # the name. + # @param reason [String] The reason for creating the account, as shown in + # the account creation log. Optional. # @return [Boolean] True if successful, false if not. def create_account_email(username, email, language = 'en', *reason) params = { @@ -194,30 +203,29 @@ def create_account_email(username, email, language = 'en', *reason) } result = post(params) - result = post(params) - if result["error"] != nil - check_create(result["error"]["code"]) + unless result['error'].nil? + check_create(result['error']['code']) return false end - if result["createaccount"]["result"] == "Success" + if result['createaccount']['result'] == 'Success' @tokens.clear return true - elsif result["createaccount"]["result"] == "NeedToken" + elsif result['createaccount']['result'] == 'NeedToken' params = { name: username, email: email, mailpassword: 'value', reason: reason, language: language, - token: result["createaccount"]["token"] + token: result['createaccount']['token'] } result = post(params, true, true) - if result["error"] != nil - check_create(result["error"]["code"]) + if !result['error'].nil? + check_create(result['error']['code']) return false - elsif result["createaccount"]["result"] == "Success" + elsif result['createaccount']['result'] == 'Success' return true else return false diff --git a/lib/mediawiki/butt.rb b/lib/mediawiki/butt.rb index a6b9c1f..bbc8a8e 100644 --- a/lib/mediawiki/butt.rb +++ b/lib/mediawiki/butt.rb @@ -14,9 +14,10 @@ class Butt include MediaWiki::Constants::Namespaces include MediaWiki::Edit - # Creates a new instance of MediaWiki::Butt. To work with any MediaWiki::Butt methods, you must first create an instance of it. - # - # @param url [String] The FULL wiki URL. api.php can be omitted, but it will make harsh assumptions about your wiki configuration. + # Creates a new instance of MediaWiki::Butt. To work with any + # MediaWiki::Butt methods, you must first create an instance of it. + # @param url [String] The FULL wiki URL. api.php can be omitted, but it + # will make harsh assumptions about your wiki configuration. # @param use_ssl [Boolean] Whether or not to use SSL. Will default to true. # @return [MediaWiki::Butt] new instance of MediaWiki::Butt def initialize(url, use_ssl = true) @@ -29,18 +30,32 @@ def initialize(url, use_ssl = true) @tokens = {} end - # Performs a generic HTTP POST action and provides the response. This method generally should not be used by the user, unless there is not a method provided by the Butt developers for a particular action. - # - # @param params [Hash] A basic hash containing MediaWiki API parameters. Please see the MediaWiki API for more information. - # @param autoparse [Boolean] Whether or not to provide a parsed version of the response's JSON. Will default to true. + # Performs a generic HTTP POST action and provides the response. This + # method generally should not be used by the user, unless there is not a + # method provided by the Butt developers for a particular action. + # @param params [Hash] A basic hash containing MediaWiki API parameters. + # Please see the MediaWiki API for more information. + # @param autoparse [Boolean] Whether or not to provide a parsed version + # of the response's JSON. Will default to true. # @param header [Hash] The header hash. Optional. - # @return [JSON/HTTPMessage] Parsed JSON if autoparse is true, or raw response if not. + # @return [JSON/HTTPMessage] Parsed JSON if autoparse is true, or raw + # response if not. def post(params, autoparse = true, header = nil) - # Note that defining the header argument as a splat argument (*header) causes errors in HTTPClient. - # We must use header.nil? rather than a splat argument and defined? header due to this error. - # For those interested, the error is: undefined method `downcase' for {"Set-Cookie"=>"cookie"}:Hash (NoMethodError) - # This is obvisouly an error in HTTPClient, but we must work around it until there is a fix in the gem. - res = header.nil? ? @client.post(@uri, params) : @client.post(@uri, params, header) + # Note that defining the header argument as a splat argument (*header) + # causes errors in HTTPClient. We must use header.nil? rather than a + # splat argument and defined? header due to this error. For those + # interested, the error is: + # undefined method `downcase' for {"Set-Cookie"=>"cookie"}:Hash + # This is obvisouly an error in HTTPClient, but we must work around it + # until there is a fix in the gem. + + params[:format] = 'json' + + if header.nil? + res = @client.post(@uri, params) + else + res = @client.post(@uri, params, header) + end if autoparse return JSON.parse(res.body) @@ -49,14 +64,18 @@ def post(params, autoparse = true, header = nil) end end - # Returns true if the currently logged in user is in the "bot" group. This can be helpful to some developers, but it is mostly for use internally in MediaWiki::Butt. - # @param username [String] The username to check. Optional. Defaults to the currently logged in user if nil. - # @return [Boolean] true if logged in as a bot, false if not logged in or logged in as a non-bot - def is_user_bot?(*username) + # Returns true if the currently logged in user is in the "bot" group. + # This can be helpful to some developers, but it is mostly for use + # internally in MediaWiki::Butt. + # @param username [String] The username to check. Optional. Defaults to + # the currently logged in user if nil. + # @return [Boolean] true if logged in as a bot, false if not logged in or + # logged in as a non-bot + def user_bot?(*username) groups = defined? username ? get_usergroups(username) : get_usergroups if groups != false - return groups.include?("bot") + return groups.include?('bot') else return false end diff --git a/lib/mediawiki/constants.rb b/lib/mediawiki/constants.rb index c754a0d..8f27f2b 100644 --- a/lib/mediawiki/constants.rb +++ b/lib/mediawiki/constants.rb @@ -3,216 +3,216 @@ module Constants # Constants Namespace IDs. Taken from https://www.mediawiki.org/wiki/Extension_default_namespaces module Namespaces $namespaces = { - "MAIN" => 0, - "TALK" => 1, - "USER" => 2, - "USER_TALK" => 3, - "PROJECT" => 4, - "PROJECT_TALK" => 5, - "FILE" => 6, - "FILE_TALK" => 7, - "MEDIAWIKI" => 8, - "MEDIAWIKI_TALK" => 9, - "TEMPLATE" => 10, - "TEMPLATE_TALK" => 11, - "HELP" => 12, - "HELP_TALK" => 13, - "CATEGORY" => 14, - "CATEGORY_TALK" => 15, - "SPECIAL" => -1, - "MEDIA" => -2, + 'MAIN' => 0, + 'TALK' => 1, + 'USER' => 2, + 'USER_TALK' => 3, + 'PROJECT' => 4, + 'PROJECT_TALK' => 5, + 'FILE' => 6, + 'FILE_TALK' => 7, + 'MEDIAWIKI' => 8, + 'MEDIAWIKI_TALK' => 9, + 'TEMPLATE' => 10, + 'TEMPLATE_TALK' => 11, + 'HELP' => 12, + 'HELP_TALK' => 13, + 'CATEGORY' => 14, + 'CATEGORY_TALK' => 15, + 'SPECIAL' => -1, + 'MEDIA' => -2, # Extension:LiquidThreads - "LQT_THREAD" => 90, - "LQT_THREAD_TALK" => 91, - "LQT_SUMMARY" => 92, - "LQT_SUMMARY_TALK" => 93, + 'LQT_THREAD' => 90, + 'LQT_THREAD_TALK' => 91, + 'LQT_SUMMARY' => 92, + 'LQT_SUMMARY_TALK' => 93, # Extension:Semantic MediaWiki / Extension:Semantic Forms - "SMW_RELATION" => 100, - "SMW_RELATION_TALK" => 101, - "SMW_PROPERTY" => 102, - "SMW_PROPERTY_TALK" => 103, - "SMW_TYPE" => 104, - "SMW_TYPE_TALK" => 105, - "SMW_FORM" => 106, - "SMW_FORM_TALK" => 107, - "SF_CONCEPT" => 108, - "SF_CONCEPT_TALK" => 109, + 'SMW_RELATION' => 100, + 'SMW_RELATION_TALK' => 101, + 'SMW_PROPERTY' => 102, + 'SMW_PROPERTY_TALK' => 103, + 'SMW_TYPE' => 104, + 'SMW_TYPE_TALK' => 105, + 'SMW_FORM' => 106, + 'SMW_FORM_TALK' => 107, + 'SF_CONCEPT' => 108, + 'SF_CONCEPT_TALK' => 109, # Extension:DPLforum - "DPLF_FORUM" => 110, - "DPLF_FORUM_TAlK" => 111, + 'DPLF_FORUM' => 110, + 'DPLF_FORUM_TAlK' => 111, # Extension:RefHelper - "RFH_CITE" => 120, - "RFH_CITE_TALK" => 121, + 'RFH_CITE' => 120, + 'RFH_CITE_TALK' => 121, # Extension:SemanticAccessControl - "ACL_USERGROUP" => 160, - "ACL_ACL" => 162, + 'ACL_USERGROUP' => 160, + 'ACL_ACL' => 162, # Extension:Semantic Drilldown - "SED_FILTER" => 170, - "SED_FILTER_TALK" => 171, + 'SED_FILTER' => 170, + 'SED_FILTER_TALK' => 171, # Extension:SocialProfile - "SCP_USERWIKI" => 200, - "SCP_USERWIKI_TALK" => 201, - "SCP_USERPROFILE" => 202, - "SCP_USERPROFILE_TALK" => 203, + 'SCP_USERWIKI' => 200, + 'SCP_USERWIKI_TALK' => 201, + 'SCP_USERPROFILE' => 202, + 'SCP_USERPROFILE_TALK' => 203, # Extension:Proofread Page - "PRP_PAGE" => 250, - "PRP_PAGE_TALK" => 251, - "PRP_INDEX" => 252, - "PRP_INDEX_TALK" => 253, + 'PRP_PAGE' => 250, + 'PRP_PAGE_TALK' => 251, + 'PRP_INDEX' => 252, + 'PRP_INDEX_TALK' => 253, # Extension:TrustedMath - "TRM_MATH" => 262, - "TRM_MATH_TALK" => 263, + 'TRM_MATH' => 262, + 'TRM_MATH_TALK' => 263, # Extension:Widgets - "WID_WIDGET" => 274, - "WID_WIDGET_TALK" => 275, + 'WID_WIDGET' => 274, + 'WID_WIDGET_TALK' => 275, # Extension:EmbedScript - "EMS_JSAPPLET" => 280, - "EMS_JSAPPLET_TALK" => 281, + 'EMS_JSAPPLET' => 280, + 'EMS_JSAPPLET_TALK' => 281, # Extension:PollNY - "PLN_POLL" => 300, - "PLN_POLL_TALK" => 301, + 'PLN_POLL' => 300, + 'PLN_POLL_TALK' => 301, # Extension:Semantic Image Annotator - "SIA_IMAGE_ANNOTATOR" => 380, + 'SIA_IMAGE_ANNOTATOR' => 380, # Extension:Wiki2LaTeX - "WTL_WIKI2LATEX" => 400, - "WTL_WIKI2LATEX_TALK" => 401, + 'WTL_WIKI2LATEX' => 400, + 'WTL_WIKI2LATEX_TALK' => 401, # Extension:Workflow - "WRF_WORKFLOW" => 410, - "WRF_WORKFLOW_TALK" => 411, + 'WRF_WORKFLOW' => 410, + 'WRF_WORKFLOW_TALK' => 411, # Extension:Maps - "MAP_LAYER" => 420, - "MAP_LAYER_TALK" => 421, + 'MAP_LAYER' => 420, + 'MAP_LAYER_TALK' => 421, # Extension:QuizTabulate - "QTB_QUIZ" => 430, - "QTB_QUIZ_TALK" => 431, + 'QTB_QUIZ' => 430, + 'QTB_QUIZ_TALK' => 431, # Extension:Education Program - "EDP_EDUCATION_PROGRAM" => 446, - "EDP_EDUCATION_PROGRAM_TALK" => 447, + 'EDP_EDUCATION_PROGRAM' => 446, + 'EDP_EDUCATION_PROGRAM_TALK' => 447, # Extension:BoilerRoom - "BLR_BOILERPLATE" => 450, - "BLR_BOILERPLATE_TALK" => 451, + 'BLR_BOILERPLATE' => 450, + 'BLR_BOILERPLATE_TALK' => 451, # Extension:UploadWizard - "UPW_CAMPAIGN" => 460, - "UPW_CAMPAIGN_TALK" => 461, + 'UPW_CAMPAIGN' => 460, + 'UPW_CAMPAIGN_TALK' => 461, # Extension:EventLogging - "ELG_SCHEMA" => 470, - "ELG_SCHEMA_TALK" => 471, + 'ELG_SCHEMA' => 470, + 'ELG_SCHEMA_TALK' => 471, # Extension:ZeroBanner - "ZRB_ZERO" => 480, - "ZRB_ZERO_TALK" => 481, + 'ZRB_ZERO' => 480, + 'ZRB_ZERO_TALK' => 481, # Extension:JsonConfig - "JSC_CONFIG" => 482, - "JSC_CONFIG_TALK" => 483, - "JSC_DATA" => 486, - "JSC_DATA_TALK" => 487, + 'JSC_CONFIG' => 482, + 'JSC_CONFIG_TALK' => 483, + 'JSC_DATA' => 486, + 'JSC_DATA_TALK' => 487, # Extension:Graph - "GRP_GRAPH" => 484, - "GRP_GRAPH_TALK" => 485, + 'GRP_GRAPH' => 484, + 'GRP_GRAPH_TALK' => 485, # Extension:OpenStackManager - "OSM_NOVA_RESOURCE" => 488, - "OSM_NOVA_RESOURCE_TALK" => 489, + 'OSM_NOVA_RESOURCE' => 488, + 'OSM_NOVA_RESOURCE_TALK' => 489, # Extension:GWToolset - "GWT_GWTOOLSET" => 490, - "GWT_GWTOOLSET_TALK" => 491, + 'GWT_GWTOOLSET' => 490, + 'GWT_GWTOOLSET_TALK' => 491, # Extension:BlogPage - "BLP_BLOG" => 500, - "BLP_BLOG_TALK" => 501, + 'BLP_BLOG' => 500, + 'BLP_BLOG_TALK' => 501, # Extension:XMLContentExtension - "XCE_XML" => 580, - "XCE_XML_TALK" => 581, - "XCE_SCHEMA" => 582, - "XCE_SCHEMA_TALK" => 583, + 'XCE_XML' => 580, + 'XCE_XML_TALK' => 581, + 'XCE_SCHEMA' => 582, + 'XCE_SCHEMA_TALK' => 583, # Extension:FanBoxes - "FNB_USERBOX" => 600, - "FNB_USERBOX_TALK" => 601, + 'FNB_USERBOX' => 600, + 'FNB_USERBOX_TALK' => 601, # Extension:LinkFilter - "LFT_LINK" => 700, - "LFT_LINK_TALK" => 701, + 'LFT_LINK' => 700, + 'LFT_LINK_TALK' => 701, # Extension:TimedMediaHandler - "TMH_TIMEDTEXT" => 710, - "TMH_TIMEDTEXT_TALK" => 711, + 'TMH_TIMEDTEXT' => 710, + 'TMH_TIMEDTEXT_TALK' => 711, # Extension:QPoll - "QPL_INTERPRETATION" => 800, - "QPL_INTERPRETATION_TALK" => 801, + 'QPL_INTERPRETATION' => 800, + 'QPL_INTERPRETATION_TALK' => 801, # Extension:SemanticMustacheFormat :3, - "SMF_MUSTACHE" => 806, - "SMF_MUSTACHE_TALK" => 807, + 'SMF_MUSTACHE' => 806, + 'SMF_MUSTACHE_TALK' => 807, # Extension:R - "R_R" => 814, - "R_R_TALK" => 815, + 'R_R' => 814, + 'R_R_TALK' => 815, # Extension:Scribunto - "SCR_MODULE" => 828, - "SCR_MODULE_TALK" => 829, + 'SCR_MODULE' => 828, + 'SCR_MODULE_TALK' => 829, # Extension:SecurePoll - "SEP_SECUREPOLL" => 830, - "SEP_SECUREPOLL_TALK" => 831, + 'SEP_SECUREPOLL' => 830, + 'SEP_SECUREPOLL_TALK' => 831, # Extension:CentralNotice - "CNT_CNBANNER" => 866, - "CNT_CNBANNER_TALK" => 867, + 'CNT_CNBANNER' => 866, + 'CNT_CNBANNER_TALK' => 867, # Extension:Translate - "TRN_TRANSLATIONS" => 1198, - "TRN_TRANSLATIOTALK" => 1199, + 'TRN_TRANSLATIONS' => 1198, + 'TRN_TRANSLATIOTALK' => 1199, # Extension:PackageForce - "PKF_PACKAGEFORCE" => 1300, - "PKF_PACKAGEFORCE_TALK" => 1301, + 'PKF_PACKAGEFORCE' => 1300, + 'PKF_PACKAGEFORCE_TALK' => 1301, # Extension:BlueSpice - "BLS_BLOG" => 1502, - "BLS_BLOG_TALK" => 1503, - "BLS_BOOK" => 1504, - "BLS_BOOK_TALK" => 1505, + 'BLS_BLOG' => 1502, + 'BLS_BLOG_TALK' => 1503, + 'BLS_BOOK' => 1504, + 'BLS_BOOK_TALK' => 1505, # Extension:Gadgets - "GDG_GADGET" => 2300, - "GDG_GADGET_TALK" => 2301, - "GDG_GADGET_DEFININTION" => 2302, - "GDG_GADGET_DEFININTION_TALK" => 2303, + 'GDG_GADGET' => 2300, + 'GDG_GADGET_TALK' => 2301, + 'GDG_GADGET_DEFININTION' => 2302, + 'GDG_GADGET_DEFININTION_TALK' => 2303, # Extension:VisualEditor - "VSE_VISUALEDITOR" => 2500, - "VSE_VISUALEDITOR_TALK" => 2501, + 'VSE_VISUALEDITOR' => 2500, + 'VSE_VISUALEDITOR_TALK' => 2501, # Extension:Flow - "FLW_TOPIC" => 2600 + 'FLW_TOPIC' => 2600 } end end diff --git a/lib/mediawiki/edit.rb b/lib/mediawiki/edit.rb index 2b75255..261f61c 100644 --- a/lib/mediawiki/edit.rb +++ b/lib/mediawiki/edit.rb @@ -1,10 +1,13 @@ module MediaWiki module Edit - # Performs a standard edit. It cannot create pages. Please use create_page for that. + # Performs a standard edit. + # It cannot create pages. Please use create_page for that. # @param title [String] The page title. # @param text [String] The new content. - # @param minor [Boolean] Will mark the edit as minor if true. Defaults to false. - # @param bot [Boolean] Will mark the edit as bot edit if true. Defualts to true, for your convenience, bot developers. + # @param minor [Boolean] Will mark the edit as minor if true. + # Defaults to false. + # @param bot [Boolean] Will mark the edit as bot edit if true. + # Defualts to true, for your convenience, bot developers. # @param summary [String] The edit summary. Optional. # @return [String] The new revision ID, or if it failed, the error code. def edit(title, text, minor = false, bot = true, *summary) @@ -25,20 +28,21 @@ def edit(title, text, minor = false, bot = true, *summary) response = post(params) - if response["edit"]["result"] == "Success" - return response["edit"]["newrevid"] + if response['edit']['result'] == 'Success' + return response['edit']['newrevid'] else - return response["error"]["code"] + return response['error']['code'] end end # Creates a new page. # @param title [String] The new page's title. # @param text [String] The new page's content. - # @param summary [String] The edit summary. Defaults to "New page". - # @param bot [Boolean] Will mark the edit as a bot edit if true. Defaults to true, for your convenience, bot developers. + # @param summary [String] The edit summary. Defaults to 'New page'. + # @param bot [Boolean] Will mark the edit as a bot edit if true. + # Defaults to true, for your convenience, bot developers. # @return [String] The new page ID, or if it failed, the error code. - def create_page(title, text, summary = "New page", bot = true) + def create_page(title, text, summary = 'New page', bot = true) params = { action: 'edit', title: title, @@ -55,17 +59,21 @@ def create_page(title, text, summary = "New page", bot = true) response = post(params) - if response["edit"]["result"] == "Success" - return response["edit"]["pageid"] + if response['edit']['result'] == 'Success' + return response['edit']['pageid'] else - return response["error"]["code"] + return response['error']['code'] end end # Uploads a file from a URL. # @param url [String] The URL to the file. - # @param filename [String] The preferred filename. This can include File: at the beginning, but it will be removed through regex. Optional. If ommitted, it will be everything after the last slash in the URL. - # @return [Boolean/String] true if the upload was successful, else the warning key. + # @param filename [String] The preferred filename. + # This can include File: at the beginning, but it will be removed + # through regex. Optional. If ommitted, it will be everything after + # the last slash in the URL. + # @return [Boolean/String] true if the upload was successful, else the + # warning's key. def upload(url, *filename) params = { action: 'upload', @@ -73,19 +81,21 @@ def upload(url, *filename) format: 'json' } - filename = defined? filename ? filename.sub(/$File:/, "") : url.split('/')[-1] + if defined? filename + filename = filename.sub(/$File:/, '') + else + filename = url.split('/')[-1] + end token = get_edit_token(filename) - params[:filename] = filename params[:token] = token response = post(params) - if response["upload"]["result"] == "Success" + if response['upload']['result'] == 'Success' return true - elsif response["upload"]["result"] == "Warning" - warnings = response["upload"]["warnings"] - return warnings.keys[0] + elsif response['upload']['result'] == 'Warning' + return response['upload']['warnings'].keys[0] end end end diff --git a/lib/mediawiki/exceptions.rb b/lib/mediawiki/exceptions.rb index c000570..eddeb33 100644 --- a/lib/mediawiki/exceptions.rb +++ b/lib/mediawiki/exceptions.rb @@ -4,122 +4,124 @@ class AuthenticationError < StandardError; end class NeedTokenMoreThanOnceError < AuthenticationError def message - "You tried to get the token more than once. You likely have some problem with your login call." + 'You tried to get the token more than once. You likely have some' \ + 'problem with your login call.' end end class NoNameError < AuthenticationError def message - "You did not set the lgname parameter." + 'You did not set the lgname parameter.' end end class IllegalUsernameError < AuthenticationError def message - "You provided an illegal username." + 'You provided an illegal username.' end end class UsernameNotExistsError < AuthenticationError def message - "You provided a username that does not exist." + 'You provided a username that does not exist.' end end class EmptyPassError < AuthenticationError def message - "You did not set the lgpassword paremeter." + 'You did not set the lgpassword paremeter.' end end class WrongPassError < AuthenticationError def message - "The password you provided is not correct." + 'The password you provided is not correct.' end end class WrongPluginPassError < AuthenticationError def message - "A plugin (not MediaWiki) claims your password is not correct." + 'A plugin (not MediaWiki) claims your password is not correct.' end end class CreateBlockedError < AuthenticationError def message - "MediaWiki tried to automatically create an account for you, but your IP is blocked from account creation." + 'MediaWiki tried to automatically create an account for you, but your' \ + 'IP is blocked from account creation.' end end class ThrottledError < AuthenticationError def message - "You've logged in too many times." + 'You\'ve logged in too many times.' end end class BlockedError < AuthenticationError def message - "User is blocked." + 'User is blocked.' end end # Start creation-specific errors class UserExistsError < AuthenticationError def message - "Username entered is already in use." + 'Username entered is already in use.' end end class UserPassMatchError < AuthenticationError def message - "Your password must be different from your username." + 'Your password must be different from your username.' end end class PasswordLoginForbiddenError < AuthenticationError def message - "The use of this username and password has been forbidden." + 'The use of this username and password has been forbidden.' end end class NoEmailTitleError < AuthenticationError def message - "No email address." + 'No email address.' end end class InvalidEmailAddressError < AuthenticationError def message - "The email address is invalid." + 'The email address is invalid.' end end class PasswordTooShortError < AuthenticationError def message - "The password was shorter than the value of $wgMinimalPasswordLength" + 'The password was shorter than the value of $wgMinimalPasswordLength' end end class NoEmailError < AuthenticationError def message - "There is no email address recorded for the user." + 'There is no email address recorded for the user.' end end class AbortedError < AuthenticationError def message - "Aborted by an extension." + 'Aborted by an extension.' end end class PermDeniedError < AuthenticationError def message - "You do not have the right to make an account." + 'You do not have the right to make an account.' end end class HookAbortedError < AuthenticationError def message - "An extension aborted the account creation." + 'An extension aborted the account creation.' end end end diff --git a/lib/mediawiki/query.rb b/lib/mediawiki/query.rb index 01f9d70..1c49728 100644 --- a/lib/mediawiki/query.rb +++ b/lib/mediawiki/query.rb @@ -3,42 +3,41 @@ module MediaWiki module Query - #TODO: Actually decide on a good way to deal with meta information queries. - # The metainformation could probably be handled in a much less verbose way. - # Perhaps we should get hashes instead? + # TODO: Actually decide on a good way to deal with meta information queries. + # The metainformation could probably be handled in a much less verbose + # way. Perhaps we should get hashes instead? module Meta - # Returns an array of all the wiki's file repository names. # @return [Array] All wiki's file repository names. def get_filerepo_names params = { action: 'query', meta: 'filerepoinfo', - friprop: 'name', - format: 'json' + friprop: 'name' } result = post(params) - ret = Array.new - result["query"]["repos"].each do |repo| - ret.push(repo["name"]) + ret = [] + result['query']['repos'].each do |repo| + ret.push(repo['name']) end - return ret + + ret end # Gets meta information for the currently logged in user. # @param prop [String] The uiprop to get. - # @return [Response/Boolean] Either a full, parsed response, or false if not logged in. + # @return [Response/Boolean] Either a full, parsed response, or false if + # not logged in. def get_current_user_meta(prop) if @logged_in params = { action: 'query', meta: 'userinfo', - uiprop: prop, - format: 'json' + uiprop: prop } - return response = post(params) + return post(params) else return false end @@ -46,8 +45,8 @@ def get_current_user_meta(prop) end module Properties - - # Gets the wiki text for the given page. Returns nil if it for some reason cannot get the text, for example, if the page does not exist. Returns a string. + # Gets the wiki text for the given page. Returns nil if it for some + # reason cannot get the text, for example, if the page does not exist. # @param title [String] The page title # @return [String/nil] String containing page contents, or nil def get_text(title) @@ -55,19 +54,19 @@ def get_text(title) action: 'query', prop: 'revisions', rvprop: 'content', - format: 'json', titles: title } response = post(params) - response["query"]["pages"].each do |revid, data| - $revid = revid + revid = nil + response['query']['pages'].each do |r, _| + revid = r end - if response["query"]["pages"][$revid]["missing"] == "" + if response['query']['pages'][revid]['missing'] == '' return nil else - return response["query"]["pages"][$revid]["revisions"][0]["*"] + return response['query']['pages'][revid]['revisions'][0]['*'] end end @@ -79,13 +78,12 @@ def get_id(title) action: 'query', prop: 'revisions', rvprop: 'content', - format: 'json', titles: title } response = post(params) - response["query"]["pages"].each do |revid, data| - if revid != "-1" + response['query']['pages'].each do |revid, _| + if revid != '-1' return revid.to_i else return nil @@ -93,28 +91,31 @@ def get_id(title) end end - # Gets the edit token for the given page. This method should rarely be used by normal users. - # @param page_name [String] The page title that you are going to be editing. - # @return [String] The edit token. If the butt isn't logged in, it returns with '+\\'. + # Gets the edit token for the given page. This method should rarely be + # used by normal users. + # @param page_name [String] The page title that you are going to be + # editing. + # @return [String] The edit token. If the butt isn't logged in, it returns + # with '+\\'. def get_edit_token(page_name) if @logged_in == true params = { action: 'query', prop: 'info', intoken: 'edit', - format: 'json', titles: page_name } response = post(params) - response["query"]["pages"].each do |revid, data| - $revid = revid + revid = nil + response['query']['pages'].each do |r, _| + revid = r end # URL encoding is not needed for some reason. - return response["query"]["pages"][$revid]["edittoken"] + return response['query']['pages'][revid]['edittoken'] else - return "+\\" + return '+\\' end end end @@ -124,13 +125,14 @@ module Lists # Gets an array of backlinks to a given title. # @param title [String] The page to get the backlinks of. - # @param limit [Int] The maximum number of pages to get. Defaults to 500, and cannot be greater than that unless the user is a bot. If the user is a bot, the limit cannot be greater than 5000. + # @param limit [Int] The maximum number of pages to get. Defaults to 500, + # and cannot be greater than that unless the user is a bot. If the user + # is a bot, the limit cannot be greater than 5000. # @return [Array] All backlinks until the limit def what_links_here(title, limit = 500) params = { action: 'query', - bltitle: title, - format: 'json' + bltitle: title } if limit > 500 @@ -147,24 +149,28 @@ def what_links_here(title, limit = 500) params[:bllimit] = limit end - ret = Array.new + ret = [] response = post(params) - response["query"]["backlinks"].each do |bl| - ret.push(bl["title"]) + response['query']['backlinks'].each do |bl| + ret.push(bl['title']) end - return ret + + ret end # Returns an array of all page titles that belong to a given category. - # @param category [String] The category title. It can include "Category:", or not, it doesn't really matter because we will add it if it is missing. - # @param limit [Int] The maximum number of members to get. Defaults to 500, and cannot be greater than that unless the user is a bot. If the user is a bot, the limit cannot be greater than 5000. + # @param category [String] The category title. It can include "Category:", + # or not, it doesn't really matter because we will add it if it is + # missing. + # @param limit [Int] The maximum number of members to get. Defaults to + # 500, and cannot be greater than that unless the user is a bot. + # If the user is a bot, the limit cannot be greater than 5000. # @return [Array] All category members until the limit def get_category_members(category, limit = 500) params = { action: 'query', list: 'categorymembers', - cmprop: 'title', - format: 'json' + cmprop: 'title' } if category =~ /[Cc]ategory\:/ @@ -187,26 +193,28 @@ def get_category_members(category, limit = 500) params[:cmlimit] = limit end - ret = Array.new + ret = [] response = post(params) - response["query"]["categorymembers"].each do |cm| - ret.push(cm["title"]) + response['query']['categorymembers'].each do |cm| + ret.push(cm['title']) end ret end # Returns an array of random pages titles. - # @param number_of_pages [Int] The number of articles to get. Defaults to 1. Cannot be greater than 10 for normal users, or 20 for bots. - # @param namespace [Int] The namespace ID. Defaults to '0' (the main namespace). Set to nil for all namespaces. + # @param number_of_pages [Int] The number of articles to get. + # Defaults to 1. Cannot be greater than 10 for normal users, + # or 20 for bots. + # @param namespace [Int] The namespace ID. Defaults to + # 0 (the main namespace). # @return [Array] All members def get_random_pages(number_of_pages = 1, namespace = 0) params = { action: 'query', - list: 'random', - format: 'json' + list: 'random' } - if $namespaces.has_value?(namespace) + if $namespaces.value?(namespace) params[:rnnamespace] = namespace else params[:rnnamespace] = 0 @@ -226,18 +234,22 @@ def get_random_pages(number_of_pages = 1, namespace = 0) params[:rnlimit] = number_of_pages end - ret = Array.new + ret = [] responce = post(params) - responce["query"]["random"].each do |a| - ret.push(a["title"]) + responce['query']['random'].each do |a| + ret.push(a['title']) end - return ret + + ret end - # Gets user information. This method should rarely be used by normal users. + # Gets user information. This method should rarely be used by + # normal users. # @param prop [String] The usprop parameter. - # @param username [String] The username to get info for. Optional. Defaults to the currently logged in user if ommitted. - # @return [String/Nil] Parsed full response if successful, nil if the username is nil and the Butt is not logged in. + # @param username [String] The username to get info for. Optional. + # Defaults to the currently logged in user if ommitted. + # @return [String/Nil] Parsed full response if successful, nil if + # the username is nil and the Butt is not logged in. def get_userlists(prop, username = nil) if username.nil? if @logged_in @@ -250,25 +262,26 @@ def get_userlists(prop, username = nil) action: 'query', list: 'users', usprop: prop, - ususers: username, - format: 'json' + ususers: username } response = post(params) end - return response + response end # Gets an array of all the user's groups. - # @param username [String] The username to get groups of. Optional. Defaults to the currently logged in user. - # @return [Array/Boolean] All of the user's groups, or false if username is nil and Butt is not logged in. + # @param username [String] The username to get groups of. Optional. + # Defaults to the currently logged in user. + # @return [Array/Boolean] All of the user's groups, or false if username + # is nil and Butt is not logged in. def get_usergroups(username = nil) - ret = Array.new + ret = [] if username.nil? if @logged_in info = get_userlists('groups') - info["query"]["userinfo"]["groups"].each do |i| + info['query']['userinfo']['groups'].each do |i| ret.push(i) end else @@ -276,25 +289,27 @@ def get_usergroups(username = nil) end else info = get_userlists('groups', username) - info["query"]["users"].each do |i| - i["groups"].each do |g| + info['query']['users'].each do |i| + i['groups'].each do |g| ret.push(g) end end end - return ret + ret end # Gets the user rights for the user. - # @param username [String] The user to get the rights for. Optional. Defaults to the currently logged in user. - # @return [Array/Boolean] All of the user's groups, or false if username is nil and Butt is not logged in. + # @param username [String] The user to get the rights for. Optional. + # Defaults to the currently logged in user. + # @return [Array/Boolean] All of the user's groups, or false if username + # is nil and Butt is not logged in. def get_userrights(username = nil) - ret = Array.new + ret = [] if username.nil? if @logged_in info = get_userlists('rights') - info["query"]["userinfo"]["rights"].each do |i| + info['query']['userinfo']['rights'].each do |i| ret.push(i) end else @@ -302,33 +317,38 @@ def get_userrights(username = nil) end else info = get_userlists('rights', username) - info["query"]["users"].each do |i| - i["rights"].each do |g| + info['query']['users'].each do |i| + i['rights'].each do |g| ret.push(g) end end end - return ret + ret end # Gets contribution count for the user. - # @param username [String] The username to get the contribution count of. Optional. Defaults to the currently logged in user. - # @param autoparse [Boolean] Whether to automatically format the string with commas. Defaults to true. - # @return [Boolean/Int/String] False if username is nil and Butt is not logged in. An integer value of the contribution count if autoparse is false. A formatted string version of the contribution count if autoparse is true. + # @param username [String] The username to get the contribution count of. + # Optional. Defaults to the currently logged in user. + # @param autoparse [Boolean] Whether to automatically format the string + # with commas using string-utility. Defaults to true. + # @return [Boolean/Int/String] False if username is nil and Butt is not + # logged in. An integer value of the contribution count if autoparse is + # false. A formatted string version of the contribution count if + # autoparse is true. def get_contrib_count(username = nil, autoparse = true) count = nil if username.nil? if @logged_in info = get_userlists('editcount') - count = info["query"]["userinfo"]["editcount"] + count = info['query']['userinfo']['editcount'] else return false end else info = get_userlists('editcount', username) - info["query"]["users"].each do |i| - count = i["editcount"] + info['query']['users'].each do |i| + count = i['editcount'] end end @@ -336,11 +356,13 @@ def get_contrib_count(username = nil, autoparse = true) countstring = count.to_s.separate return countstring end - return count + + count end # Gets when the user registered. - # @param username [String] The username to get the registration date and time of. Optional. Defaults to the currently logged in user. + # @param username [String] The username to get the registration date and + # time of. Optional. Defaults to the currently logged in user. # @return [DateTime] The registration date and time as a DateTime object. def get_registration_time(username = nil) time = nil @@ -348,48 +370,53 @@ def get_registration_time(username = nil) if username.nil? if @logged_in info = get_userlists('registrationdate') - time = info["query"]["userinfo"]["registrationdate"] + time = info['query']['userinfo']['registrationdate'] else return false end else info = get_userlists('registration', username) - info["query"]["users"].each do |i| - time = i["registration"] + info['query']['users'].each do |i| + time = i['registration'] end end - # %Y: Year including century, %m: Month num, %d day of month, %T Time as H:M:S - timeformat = "%Y-%m-%dT%T" + # %Y: Year including century + # %m: Month num + # %d: day of month + # %T: Time as HH:MM:SS + timeformat = '%Y-%m-%dT%T' time = DateTime.strptime(time, timeformat) + + time end # Gets the gender for the provded user. # @param username [String] The user. - # @return [String] The gender. "male", "female", or "unknown". + # @return [String] The gender. 'male', 'female', or 'unknown'. def get_user_gender(username) gender = nil info = get_userlists('gender', username) - info["query"]["users"].each do |i| - gender = i["gender"] + info['query']['users'].each do |i| + gender = i['gender'] end - return gender + gender end # Gets the amount of results for the search value. # @param search_value [String] The thing to search for. - # @param namespace [Int] The namespace to search in. Defaults to the main namespace. + # @param namespace [Int] The namespace to search in. + # Defaults to 0 (the main namespace). # @return [Int] The number of pages that matched the search. def get_search_result_amount(search_value, namespace = 0) params = { action: 'query', list: 'search', - srsearch: search_value, - format: 'json' + srsearch: search_value } - if $namespaces.has_value?(namespace) + if $namespaces.value?(namespace) params[:srnamespace] = namespace else params[:srnamespace] = 0 @@ -397,22 +424,22 @@ def get_search_result_amount(search_value, namespace = 0) response = post(params) - return response["query"]["searchinfo"]["totalhits"] + response['query']['searchinfo']['totalhits'] end # Gets an array containing page titles that matched the search. # @param search_value [String] The thing to search for. - # @param namespace [Int] The namespace to search in. Defaults to the main namespace. + # @param namespace [Int] The namespace to search in. + # Defaults to 0 (the main namespace). # @return [Array] The page titles that matched the search. def get_search_results(search_value, namespace = 0) params = { action: 'query', list: 'search', - srsearch: search_value, - format: 'json' + srsearch: search_value } - if $namespaces.has_value?(namespace) + if $namespaces.value?(namespace) params[:srnamespace] = namespace else params[:srnamespace] = 0 @@ -420,12 +447,12 @@ def get_search_results(search_value, namespace = 0) response = post(params) - ret = Array.new - response["query"]["search"].each do |search| - ret.push(search["title"]) + ret = [] + response['query']['search'].each do |search| + ret.push(search['title']) end - return ret + ret end end end diff --git a/mediawiki-butt.gemspec b/mediawiki-butt.gemspec index f856c5f..0c3b146 100644 --- a/mediawiki-butt.gemspec +++ b/mediawiki-butt.gemspec @@ -1,12 +1,13 @@ Gem::Specification.new do |s| s.authors = ['Eli Foster', 'Eric Schneider (xbony2)'] s.name = 'mediawiki-butt' - s.summary = "Interacting with the MediaWiki API" + s.summary = 'Interacting with the MediaWiki API' s.version = '0.4.1' s.license = 'CC-BY-NC-ND-4.0' # Expand on this description eventually. s.description = <<-EOF - MediaWiki::Butt is a Ruby Gem that provides a fully-featured MediaWiki API interface. + MediaWiki::Butt is a Ruby Gem that provides a fully-featured MediaWiki API \ + interface. EOF s.email = 'elifosterwy@gmail.com' s.homepage = 'https://github.com/ftb-gamepedia/mediawiki-butt-ruby' @@ -16,17 +17,17 @@ Gem::Specification.new do |s| s.post_install_message = 'ONE OF US! ONE OF US!' s.required_ruby_version = '>= 2.1' s.files = [ - "lib/mediawiki-butt.rb", - "lib/mediawiki/butt.rb", - "lib/mediawiki/auth.rb", - "lib/mediawiki/exceptions.rb", - "lib/mediawiki/query.rb", - "lib/mediawiki/constants.rb", - "lib/mediawiki/edit.rb", - "CHANGELOG.md" + 'lib/mediawiki-butt.rb', + 'lib/mediawiki/butt.rb', + 'lib/mediawiki/auth.rb', + 'lib/mediawiki/exceptions.rb', + 'lib/mediawiki/query.rb', + 'lib/mediawiki/constants.rb', + 'lib/mediawiki/edit.rb', + 'CHANGELOG.md' ] # TODO: Figure out what version we should require for JSON and HTTPClient - s.add_runtime_dependency("string-utility", ">= 2.0.0") - s.add_runtime_dependency("httpclient") + s.add_runtime_dependency('string-utility', '>= 2.0.0') + s.add_runtime_dependency('httpclient') end