Skip to content

Instantly share code, notes, and snippets.

@chtzvt
Last active January 25, 2022 19:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chtzvt/41f2d40022f2e0c3bd8940f38fc69285 to your computer and use it in GitHub Desktop.
Save chtzvt/41f2d40022f2e0c3bd8940f38fc69285 to your computer and use it in GitHub Desktop.
Nextcloud Backer-Upper for Calendar/Contacts/Todo lists, with a dash of Git
#!/usr/bin/env ruby
# frozen_string_literal: true
# NextCloud Backer-Upper
# Charlton Trezevant, 2021
# This script is provided as-is, under the MIT license.
#
# The purpose of this script is to automatically fetch backup exports of my contacts,
# calendars, and todo lists from Nextcloud.
#
# It grabs these, sorts them into the appropriate directory structure, and checks
# them into Git if the current directory is a repo. If the repo has a remote defined,
# the script will also push the changed files upstream.
require 'net/http'
require 'pathname'
require 'git'
# NextcloudFetcher takes care of authenticating to the NextCloud
# instance, grabbing our data, and organizing it on disk for us.
class NextcloudFetcher
attr_accessor :dir, :outfile
attr_writer :username, :password
def initialize(dir, outfile, uri)
@dir = dir
@outfile = outfile
self.uri = uri
end
def fetch
req = Net::HTTP::Get.new(@uri)
req.basic_auth @username, @password
res = Net::HTTP.start(@uri.hostname, @uri.port, use_ssl: true) do |http|
http.request(req)
end
raise("Error contacting server: #{res.code}") unless res.code == '200'
Dir.mkdir(@dir) unless Dir.exist?(@dir)
File.open(filename, 'wb') do |file|
file.write(res.body)
end
end
def filename
Pathname.new("#{dir}/#{outfile}")
end
def uri=(uri)
@uri = URI(uri)
end
end
def save_to_git
puts 'Committing changes to Git...'
g = Git.open(Dir.getwd)
g.add(all: true)
time = Time.new
g.commit_all("Backups for #{time.year}/#{time.month}/#{time.day} at #{time.hour}:#{time.min}")
g.push unless g.remotes.empty?
end
def git_repo?
File.directory?("#{Dir.getwd}/.git")
end
backups = [
['Contacts', 'My Contacts.vcf', 'https://nextcloud.example.org/remote.php/dav/addressbooks/users/username/contacts/?export'],
['Calendars', 'My Calendar.ics', 'https://nextcloud.example.org/remote.php/dav/calendars/username/calendar_name/?export']
]
backups.each do |item|
fetcher = NextcloudFetcher.new(item[0], item[1], item[2])
fetcher.username = ENV['NC_USER']
fetcher.password = ENV['NC_PASS']
puts "Fetching #{fetcher.filename}..."
fetcher.fetch
end
save_to_git if git_repo?
puts 'Backup finished.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment