#!/bin/bash # This sample script is provided as-is! I take no responsibility for the damage it might cause to your server! Please test this before using it in production! # If it works as intended, it will remove all messages in $roomName older than $daysToClean # This script requires you install the program jq that can parse json. This makes reading the output from the api easy. # Replace the values below with your requirements. Feel free to modify this to use command line parameters. server='http://chat.rethinklegal.com' user='david.mund' pass='20GcdE13' daysToClean='7' # Rudimentary attempt to make sure jq is installed. if [[ $(jq -V 2>&1 ) == *"found"* ]]; then echo "You must have the program jq installed for this script to work! Please install this and try again." exit 1 fi # To be clear, the cleanHistory api call will delete all messages starting at $cleanFrom (set to 10 years back) up until $expirationDate cleanFrom=$(date +%Y-%m-%dT%T.000Z -d "-10 years") expirationDate=$(date -d "-$daysToClean days" +%Y-%m-%dT%T.000Z) success=0 # Initial success value # Logging in loginResult=$(curl -s $server/api/v1/login -d "username=$user&password=$pass") # Check if we got an error if [[ $loginResult == *"error"* ]]; then echo "There was an error logging in!" exit 1 fi # $authToken and $userId are used in all calls to the api authToken=$(echo $loginResult | sed 's/.*authToken\":\ \"//' | sed 's/\".*//') userId=$(echo $loginResult | sed 's/.*userId\":\ \"//' | sed 's/\".*//') # Getting a list of all rooms. roomList=$(curl -s -H "X-Auth-Token: $authToken" -H "X-User-Id: $userId" $server/api/v1/channels.list | jq -r '.channels[] | ._id + " " + .name') # This is in a function so that later if the private channels are allowed to be cleaned it's just a matter of calling this same function on them. function cleanhistory() { roomName=${roomInfo#*\ } roomId=${roomInfo%\ *} cleanResult=$(curl -s -H "X-Auth-Token: $authToken" -H "X-User-Id: $userId" -H "Content-type: application/json" $server/api/v1/channels.cleanHistory -d "{ \"roomId\": \"$roomId\", \"latest\": \"$expirationDate\", \"oldest\": \"$cleanFrom\" }" ) # And report back the results if [[ $cleanResult == *"true"* ]]; then echo "Successfully cleaned messages older than $daysToClean from $roomId" else echo "There was an error cleaning messages older than $daysToClean from $roomName! Please see response below:" echo $cleanResult success=1 fi } # Setting IFS so that the roomList isn't split weird. OIFS="$IFS" IFS=$'\n' # Loop that calls cleanhistory api room by room echo "=== Cleaning all public rooms ===" for roomInfo in $roomList; do cleanhistory $authToken $userId $roomInfo $expirationDate $cleanFrom done # Setting IFS back to what it was before IFS="$OIFS" # exiting with success value used above exit $success