Skip to content

Instantly share code, notes, and snippets.

@yuasatakayuki
Created March 7, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuasatakayuki/8328cf89477ab90b87e0 to your computer and use it in GitHub Desktop.
Save yuasatakayuki/8328cf89477ab90b87e0 to your computer and use it in GitHub Desktop.
Upload file to MediaWiki using Ruby Mechanize
#!/usr/bin/env ruby
if(ARGV.length<1)then
puts "Provide file to be uploaded."
exit
end
require "mechanize"
#check file
filePath=ARGV[0]
if(!File.exist?(filePath))then
STDERR.puts "Error: file not found #{filePath}"
exit
end
#prepare destination file name
fileName=File.basename(filePath)
fileName=fileName[0].capitalize+fileName[1...(fileName.length)]
extname=File.extname(filePath)
if(extname=="")then
extname=fileName
end
#destination url and access password
url="http://wiki_url/index.php/Special:Upload"
hostPort="http://wiki_url"
http_user="username"
http_password="password"
#show message
puts "---------------------------------------------"
puts "Source file: #{filePath}"
puts "Destination name: #{fileName}"
puts "Paste the following command to the MediaWiki."
puts ""
puts "[[Media:#{fileName}|#{extname}]]"
puts "---------------------------------------------"
puts "#{Time.now} Loading the Upload page..."
#instantiate mechanize agent
agent = Mechanize.new
#add authentication info
agent.add_auth(hostPort,http_user,http_password)
#open the upload page
begin
page = agent.get(url)
rescue
STDERR.puts "Error: Connection failed"
exit
end
#select file, then upload
puts "#{Time.now} Upload page loaded."
page.form_with(:id=>"mw-upload-form"){|form|
form.file_upload_with(:name=>"wpUploadFile"){|file|
file.file_name=filePath
}
form.field_with(:name=>"wpDestFile"){|field|
field.value = fileName
}
form.checkbox_with(:name=>"wpIgnoreWarning").check
puts "#{Time.now} Uploading file..."
form.click_button
puts "#{Time.now} Receiving result..."
resultPage=agent.page
puts "#{Time.now} Upload completed."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment