Created
March 16, 2017 13:12
-
-
Save arieljannai/650f6a918fe82a333404ff4ef53bb065 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# based on https://github.com/ltalirz/moodle-qformat_qtex/blob/master/moodle-converter/moodle_question_converter.sh | |
function usage { | |
printf \ | |
"usage: %s <URL to Moodle> <username> <password> <input file>\n" $(basename $0) | |
exit 1 | |
} | |
nCommandLineArgs=$# | |
if (( $nCommandLineArgs != 4 )) | |
then | |
usage | |
fi | |
argUrlToMoodle=$1 | |
argUsername=$2 | |
argPassword=$3 | |
argInputFile=$4 | |
COOKIE_FILE=$(mktemp) | |
LOGIN_URL="$argUrlToMoodle/login/index.php" | |
LOGOUT_URL="$argUrlToMoodle/login/logout.php" | |
UPLOAD_URL="$argUrlToMoodle/repository/repository_ajax.php?action=upload" | |
# Moodle login using the given username and password. | |
# @param 1 username | |
# @param 2 password | |
# As a result echoes the sesskey. | |
function login { | |
username=$1 | |
password=$2 | |
local loginResponse=$(curl --silent --cookie-jar $COOKIE_FILE --location \ | |
--data "username=$username" --data "password=$password" \ | |
$LOGIN_URL) | |
local sesskey="" | |
if [[ $loginResponse =~ sesskey=([^=\"]*) ]] | |
then | |
sesskey=${BASH_REMATCH[1]} | |
fi | |
echo "$sesskey" | |
} | |
# Moodle logout. | |
# @param 1 sesskey | |
function logOut { | |
sesskey=$1 | |
local logoutResponse=$(curl --silent --cookie-jar $COOKIE_FILE --location \ | |
"${LOGOUT_URL}?sesskey=$sesskey") | |
# printf "%s\n" $logoutResponse | |
} | |
# Moodle file upload. | |
# @param 1 The file to upload. | |
# @param 2 itemid, the id to associate with the uploaded file. | |
# @param 3 clientid | |
# @param 4 sesskey | |
function upload { | |
local file=$1 | |
local itemid=$2 | |
local clientid=$3 | |
local sesskey=$4 | |
local uploadResponse=$(curl --silent --cookie $COOKIE_FILE --location \ | |
--header "Content-Type: multipart/form-data" \ | |
--form "repo_upload_file=@$file" \ | |
--form "title=" --form "author=" --form "license=" \ | |
--form "itemid=$itemid" --form "repo_id=4" --form "p=" \ | |
--form "page=" --form "env=filepicker" --form "sesskey=$sesskey" \ | |
--form "client_id=$clientid" --form "maxbytes=-1" \ | |
--form "areamaxbytes=-1" \ | |
--form "ctx_id=2" --form "savepath=/" \ | |
$UPLOAD_URL) | |
printf "%s\n" "$uploadResponse" | |
} | |
# Echoes a timestamp, i. e. the seconds since 1970-01-01 00:00:00 UTC | |
function timestamp { | |
date +"%s" | |
} | |
itemid=$RANDOM | |
clientid=$RANDOM | |
sesskey=$(login $argUsername $argPassword) | |
upload $argInputFile $itemid $clientid $sesskey | |
logOut $sesskey | |
rm $COOKIE_FILE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment