Skip to content

Instantly share code, notes, and snippets.

@albertopasqualetto
Last active October 9, 2024 21:10
Show Gist options
  • Save albertopasqualetto/6cc968cda1e487094f57302e6be10850 to your computer and use it in GitHub Desktop.
Save albertopasqualetto/6cc968cda1e487094f57302e6be10850 to your computer and use it in GitHub Desktop.
Backup di OneNote on Google Drive using Rclone
$TAB = "`t"
# ****** BACKUP OF ONENOTE TO GOOGLE DRIVE USING RCLONE ******
Write-Host "****** RClone OneNote backup on Google Drive ******"
# ****** BACKUP TO UNI DRIVE ******
Write-Host "Backup on Uni Drive..."
Write-Host "$TAB Upload..."
rclone copy "C:\Users\alber\AppData\Local\Microsoft\OneNote\16.0\Backup\Primo Semestre - Quarto anno" "GDrive Uni:_Backup OneNote/Primo Semestre - Quarto anno"
rclone copy "C:\Users\alber\AppData\Local\Microsoft\OneNote\16.0\Backup\Secondo Semestre - Quarto anno" "GDrive Uni:_Backup OneNote/Secondo Semestre - Quarto anno"
rclone copy "C:\Users\alber\AppData\Local\Microsoft\OneNote\16.0\Backup\Primo Semestre - Quinto anno (Grenoble)" "GDrive Uni:_Backup OneNote/Primo Semestre - Quinto anno (Grenoble)"
Write-Host "$TAB Delete old files..."
python OneNoteDeleteScript.py "GDrive Uni:_Backup OneNote/" 10
Write-Host "Done."
# ****** BACKUP TO PERSONAL DRIVE WITH 3-BACKUP LIMIT IMPOSED BY ONENOTE EVERY 5 DAYS ******
if (-not ($args[0] -eq "--all" -or $args[0] -eq "-a")) {
if (-not (((Get-Date).Day % 5) -eq 0)) {
exit 0
}
}
Write-Host "Backup on Personal Drive..."
Write-Host "$TAB Upload..."
rclone copy "C:\Users\alber\AppData\Local\Microsoft\OneNote\16.0\Backup\Primo Semestre - Quarto anno" "GDrive Personale:/Uni/Backup OneNote/Primo Semestre - Quarto anno"
rclone copy "C:\Users\alber\AppData\Local\Microsoft\OneNote\16.0\Backup\Secondo Semestre - Quarto anno" "GDrive Personale:/Uni/Backup OneNote/Secondo Semestre - Quarto anno"
rclone copy "C:\Users\alber\AppData\Local\Microsoft\OneNote\16.0\Backup\Primo Semestre - Quinto anno (Grenoble)" "GDrive Personale:/Uni/Backup OneNote/Primo Semestre - Quinto anno (Grenoble)"
# Uncomment if necessary
# rclone copy "C:\Users\alber\AppData\Local\Microsoft\OneNote\16.0\Backup\Alberto Personale" "GDrive Personale:/Uni/Backup OneNote/Alberto Personale"
# rclone copy "C:\Users\alber\AppData\Local\Microsoft\OneNote\16.0\Backup\Note rapide" "GDrive Personale:/Uni/Backup OneNote/Note rapide"
Write-Host "$TAB Delete old files..."
python OneNoteDeleteScript.py "GDrive Personale:Uni/Backup OneNote/" 3
Write-Host "Done."
Write-Host "Backups completed"
import sys
import subprocess
import json
from datetime import datetime
import logging
import re
LOCAL_FOLDER = "C:/Users/alber/AppData/Local/Microsoft/OneNote/16.0/Backup/"
logging.basicConfig(filename="./pyLog.txt", level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%m/%d/%Y %H:%M:%S')
def remove_oldests(basedir, n=3):
count = 0
logging.info("Getting files from " + basedir)
result_fetch = subprocess.run(['rclone', 'lsjson', basedir, '-R'], capture_output=True)
drive_tree_list = json.loads(result_fetch.stdout.decode('utf-8'))
drive_tree_list = [x for x in drive_tree_list if not x['IsDir'] if x['MimeType'] != 'application/pdf'] # exclude folders and pdfs
logging.debug("drive_tree_list: " + str(drive_tree_list))
logging.info("Selecting subjects for dict keys")
dict_by_subjects = {}
for element in drive_tree_list:
if "OneNote_RecycleBin" not in element['Path']: # ignore recycle bin
dict_by_subjects[element['Name'].split(".one")[0]] = []
else: #if recycle bin
# if after 15 of month, delete all recycle bin files
if datetime.now().day < 15:
try:
result_delete_RecycleBin = subprocess.run(['rclone', 'delete', basedir + element['Path'], '-v'], check=True, stdout=subprocess.DEVNULL)
count += 1
logging.info("Deleted recycle bin file: " + basedir + element['Path'])
except subprocess.CalledProcessError as e:
logging.exception("Error deleting recycle bin file: " + basedir + element['Path'])
logging.info("Adding files to dict")
for subject in dict_by_subjects:
for element in drive_tree_list:
if subject in element['Name']:
dict_by_subjects[subject].append(element['Path'])
logging.info("Creating dicts by dates")
for subject in dict_by_subjects:
logging.debug("Processing ubject: " + subject)
dates = {}
# get date from string
for element in dict_by_subjects[subject]:
date = re.search('On \\d{2}-\\d{2}-\\d{4}', element)
if not date:
print("No date in "+element)
continue
date = date.group()
date = date[3:]
date = datetime.strptime(date, '%d-%m-%Y').date()
dates[date] = element
# delete old backups if >3 per subject
while len(dates) > n:
selected = min(dates.keys())
try:
result_delete_file = subprocess.run(['rclone', 'deletefile', basedir + dates[selected], '-v'], check=True, stdout=subprocess.DEVNULL)
count += 1
logging.info("Deleted file: " + basedir + dates[selected])
dates.pop(selected) # dict_by_subjects dictionary is not updated
except subprocess.CalledProcessError as e:
logging.exception("Error deleting file: " + basedir + dates[selected])
return count
if __name__ == '__main__':
if len(sys.argv) < 2 or len(sys.argv) > 3 or not isinstance(sys.argv[1], str) or (sys.argv[2] and not sys.argv[2].isnumeric()):
logging.error("Invalid args")
exit(1)
deleted_items = remove_oldests(basedir=sys.argv[1], n=int(sys.argv[2]) if sys.argv[2] else 3)
print("Deleted " + str(deleted_items) + " items")
logging.info("Deleted " + str(deleted_items) + " items")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment