• Bash script for document import

  • We tried to make OpenKM as intuitive as possible, but an advice is always welcome.
We tried to make OpenKM as intuitive as possible, but an advice is always welcome.
Forum rules: Please, before asking something see the documentation wiki or use the search feature of the forum. And remember we don't have a crystal ball or mental readers, so if you post about an issue tell us which OpenKM are you using and also the browser and operating system version. For more info read How to Report Bugs Effectively.
 #27544  by JoergPalmer
 
I have created a bash script to import files from the command line ... well, on Linux systems that is. The script calls the OpenKM web services to log on, import a file and log off again.

For myself I have combined this with a "scan-and-create-pdf-with-text-layer" script. Also, on my favorite file commander I can now import any file with a right click. As I found that very convenient, I can offer to post this script somewhere. Just drop me a line if you are interested.
 #27546  by jllort
 
Hi, if you post the script here we will share in wiki documentation for all community users.
 #27547  by JoergPalmer
 
Sure, here it is:
Code: Select all
#!/bin/sh
##############################################################################
# Copyright (c) 2013: Jörg Palmer, JoergPalmer @ OpenKM forums
#
# Script for importing a document into OpenKM via web services
# 1. Logon using an "import user"
# 2. Import the document into a pre-defined folder
# 3. Logoff the server
##############################################################################

### Configuration section, please adjust to your setup
OKM_ID="autoImport"                     # User ID / name
OKM_PW="Import42"                       # Password
### Configuration section ends here
### DO NOT CHANGE FROM HERE UNLESS YOU KNOW WHAT YOU ARE DOING!

# Constants definition
TOOLNAME="OpenKM_import"
VERSION="v1.0"

# Possible exit codes
EXIT_OK="0"                             # 0=success
EXIT_BAD_ARGS="1"                       # 1=wrong number of parameters
EXIT_BAD_LOGON="2"                      # 2=logon to OpenKM failed
EXIT_BAD_LOGOFF="3"                     # 3=Logoff from OpenKM failed

# LOG Level
LOG_ERR="0"                             # 0=only error messages
LOG_INFO="1"                            # 1=error messages and some infos
LOG_DEBUG="2"                           # 2=debug level logging


START=`date +%s`

usage() {
        cat << EOF
--------------------------------------------------------------------------------------
Script to import a document into an OpenKM server, using SOAP web services.
Please adjust the user id settings at the beginning of the script to your needs.

Copyright: Jörg Palmer
Version: $VERSION

Usage: OpenKM_import.sh  [-h] [-v] [-g] [-u url] [-p path] document

Options:

-h      : Display this help message
-v      : Increase the verbosity (this option can be used more than once)
-g      : Activate debug mode:
         - Set the verbosity to the highest possible
-u url  : Set the url to the OpenKM instance
         Default: http://localhost:8080/OpenKM
-p path : Set the taxonomy path to be imported to
         Default: /okm:root/imported

document : The file to be imported
--------------------------------------------------------------------------------------
EOF
}

#################################################
# Get an absolute path from a relative path to a file
#
# Param1 : Relative path
# Returns: 1 if the folder in which the file is located does not exist
#          0 otherwise
################################################# 
absolutePath() {
   local wdsave absolutepath 
   wdsave="$(pwd)"
   ! cd "$(dirname "$1")" 1> /dev/null 2> /dev/null && return 1
   absolutepath="$(pwd)/$(basename "$1")"
   cd "$wdsave"
   echo "$absolutepath"
   return 0
}

# Initialization the configuration parameters with default values
VERBOSITY="$LOG_ERR"                    # default verbosity level
OKM_URL="http://localhost:8080/OpenKM"  # OpenKM URL
OKM_PATH="/okm:root/imported"           # Taxonomy path to be imported to

# Parse optional command line arguments
while getopts ":hvgu:p:" opt; do
        case $opt in
                h) usage ; exit 0 ;;
                v) VERBOSITY=$(($VERBOSITY+1)) ;;
                g) VERBOSITY="10" ;;
                u) OKM_URL="$OPTARG" ;;
                p) OKM_PATH="$OPTARG" ;;
                \?)
                        echo "Invalid option: -$OPTARG" >&2
                        usage
                        exit $EXIT_BAD_ARGS ;;
                :)
                        echo "Option -$OPTARG requires an argument" >&2
                        usage
                        exit $EXIT_BAD_ARGS ;;
        esac
done

# Remove the optional arguments parsed above.
shift $((OPTIND-1))

# Check if the number of mandatory parameters
# provided is as expected
if [ "$#" -ne "1" ]; then
        echo "Document file name is missing! ($# arguments provided)" >&2
        usage
        exit $EXIT_BAD_ARGS
fi

[ $VERBOSITY -ge $LOG_INFO ] && echo "$TOOLNAME, version: $VERSION"

# Generate the document information
FILENAME="`absolutePath "$1"`"
FILENAME_BASE="${FILENAME##*/}"

[ $VERBOSITY -ge $LOG_INFO ] && echo "Document file: '$FILENAME', basename: '$FILENAME_BASE'"

# Logon
[ $VERBOSITY -ge $LOG_DEBUG ] && echo "Logging on to OpenKM Server '$OKM_URL' with '$OKM_ID'"
response_Auth_logon=$(curl --silent --header "Content-Type: text/xml;charset=UTF-8" \
 --header "SOAPAction:action" --data @- \
 --request POST "${OKM_URL}/services/OKMAuth" << EOF
   <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.openkm.com">
      <soapenv:Header/>
      <soapenv:Body>
         <ws:login>
            <user>$OKM_ID</user>
            <password>$OKM_PW</password>
         </ws:login>
      </soapenv:Body>
   </soapenv:Envelope>
EOF
)

# Check for response code -> Got access token?
token=$(grep -oPm1 "(?<=<return>)[^<]+" <<< "$response_Auth_logon")
if [ -z "$token" ]; then
  echo "Error logging on to OpenKM server!" >&2
  echo "Response: "$response_Auth_logon >&2 && exit $EXIT_BAD_LOGON
else
  [ $VERBOSITY -ge $LOG_DEBUG ] && echo "Logon successful (Token: '"$token"')"
fi

# Content must be base64 -> read and encode
[ $VERBOSITY -ge $LOG_DEBUG ] && echo "Encoding input file as Base64"
content="`base64 "$FILENAME"`"

# Import the document
[ $VERBOSITY -ge $LOG_DEBUG ] && echo "Importing document '$FILENAME_BASE' to '$OKM_PATH/$FILENAME_BASE'"
response_Doc=$(curl --silent --header "Content-Type: text/xml;charset=UTF-8" \
 --header "SOAPAction:action" --data @- \
 --request POST "${OKM_URL}/services/OKMDocument" << EOF
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.openkm.com">
   <soapenv:Header/>
   <soapenv:Body>
      <ws:createSimple>
         <token>$token</token>
         <docPath>$OKM_PATH/$FILENAME_BASE</docPath>
         <content>$content</content>
      </ws:createSimple>
   </soapenv:Body>
</soapenv:Envelope>
EOF
)

# Check for success
fault=$(grep -oPm1 "(?<=<faultcode>)[^<]+" <<< "$response_Doc")
if [ -n "$fault" ]; then
  echo "Error importing document: "$fault": '" \
         $(grep -oPm1 "(?<=<faultstring>)[^<]+" <<< "$response_Doc") \
         "' -> "$(grep -oPm1 "[^:]+Exception" <<< "$response_Doc") >&2
  echo "Response: "$response_Doc >&2
else
  uuid=$(grep -oPm1 "(?<=<uuid>)[^<]+" <<< "$response_Doc")
  [ $VERBOSITY -ge $LOG_DEBUG ] && echo "Document '$uuid' imported successfully"
fi

# Logoff
[ $VERBOSITY -ge $LOG_DEBUG ] && echo "Logging off from OpenKM server"
response_Auth_logoff=$(curl --silent --header "ConteONnt-Type: text/xml;charset=UTF-8" \
 --header "SOAPAction:action" --data @- \
 --request POST "${OKM_URL}/services/OKMAuth" << EOF
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.openkm.com">
   <soapenv:Header/>
   <soapenv:Body>
      <ws:logout>
         <token>$token</token>
      </ws:logout>
   </soapenv:Body>
</soapenv:Envelope>
EOF
)

# Check for success
fault=$(grep -oPm1 "(?<=<faultcode>)[^<]+" <<< "$response_Auth_logoff")
if [ -n "$fault" ]; then
  echo "Error logging off from server: "$fault": '" \
         $(grep -oPm1 "(?<=<faultstring>)[^<]+" <<< "$response_Auth_logoff") \
         "' -> "$(grep -oPm1 "[^:]+Exception" <<< "$response_Auth_logoff") >&2
  echo "Response: "$response_Auth_logoff >&2
else
  [ $VERBOSITY -ge $LOG_DEBUG ] && echo "Logoff successful"
fi

END=`date +%s`
[ $VERBOSITY -ge $LOG_DEBUG ] && echo "Script took $(($END-$START)) seconds"

exit $EXIT_OK
Right now working on an extension to set keywords and a note. But I'm struggling with the setProperties() web service. Anyway, I found this very handy.

About Us

OpenKM is part of the management software. A management software is a program that facilitates the accomplishment of administrative tasks. OpenKM is a document management system that allows you to manage business content and workflow in a more efficient way. Document managers guarantee data protection by establishing information security for business content.