Skip to content

Commit

Permalink
Add support for customising the Dropbox filename
Browse files Browse the repository at this point in the history
  • Loading branch information
d0ugal committed Oct 5, 2018
1 parent 36186c0 commit f486e8f
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 44 deletions.
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ a directory name.
{
"access_token": "ACCESS TOKEN",
"dropbox_dir": "/hass-snapshots/"
"keep": 10,
"mins_between_backups": 30
}
```

Expand All @@ -41,9 +43,6 @@ Here is the automation I use to create a snapshot and upload it to Dropbox.
- service: hassio.snapshot_full
data_template:
name: Automated Backup {{ now().strftime('%Y-%m-%d') }}
- service: hassio.addon_start
data:
addon: 8aef3602_dropbox_upload
```


Expand Down
1 change: 1 addition & 0 deletions dropbox-upload/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"access_token": "str",
"dropbox_dir": "str",
"keep": "int?",
"filename_fmt": "str?",
"mins_between_backups": "int?",
"debug": "bool?"
}
Expand Down
23 changes: 15 additions & 8 deletions dropbox-upload/dropbox_upload/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pathlib

import arrow
import jinja2

from . import dropbox, util

Expand All @@ -14,16 +15,22 @@ def local_path(snapshot):
return BACKUP_DIR / f"{snapshot['slug']}.tar"


def dropbox_path(dropbox_dir, snapshot):
return dropbox_dir / f"{snapshot['slug']}.tar"
def dropbox_path(config, snapshot):
dropbox_dir = pathlib.Path(config["dropbox_dir"])
if config.get("filename_fmt"):
ctx = snapshot.copy()
ctx["date"] = arrow.get(ctx["date"]).strftime("%Y-%m-%d %H.%M.%S")
template = jinja2.Template(config["filename_fmt"])
name = template.render(**ctx)
else:
name = snapshot["slug"]
return dropbox_dir / f"{name}.tar"


def backup(dbx, config, snapshots):

dropbox_dir = pathlib.Path(config["dropbox_dir"])

LOG.info(f"Backing up {len(snapshots)} snapshots")
LOG.info(f"Backing up to Dropbox directory: {dropbox_dir}")
LOG.info(f"Backing up to Dropbox directory: {config['dropbox_dir']}")

if not snapshots:
LOG.warning("No snapshots found to backup")
Expand All @@ -35,14 +42,14 @@ def backup(dbx, config, snapshots):

for i, snapshot in enumerate(snapshots, start=1):
LOG.info(f"Snapshot: {snapshot['name']} ({i}/{len(snapshots)})")
process_snapshot(dropbox_dir, dbx, snapshot)
process_snapshot(config, dbx, snapshot)


def process_snapshot(dropbox_dir, dbx, snapshot):
def process_snapshot(config, dbx, snapshot):
path = local_path(snapshot)
created = arrow.get(snapshot["date"])
size = util.bytes_to_human(os.path.getsize(path))
target = str(dropbox_path(dropbox_dir, snapshot))
target = str(dropbox_path(config, snapshot))
LOG.info(f"Slug: {snapshot['slug']}")
LOG.info(f"Created: {created}")
LOG.info(f"Size: {size}")
Expand Down
4 changes: 1 addition & 3 deletions dropbox-upload/dropbox_upload/limit.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import logging
import pathlib

import arrow

Expand All @@ -11,7 +10,6 @@
def limit_snapshots(dbx, config, snapshots):

keep = config.get("keep")
dropbox_dir = pathlib.Path(config["dropbox_dir"])

if not keep:
LOG.warning("keep not set. We wont remove old snapshots")
Expand All @@ -33,5 +31,5 @@ def limit_snapshots(dbx, config, snapshots):
for snapshot in expired_snapshots:
LOG.info(f"Deleting {snapshot['name']} (slug: {snapshot['slug']}")
hassio.hassio_post(f"snapshots/{snapshot['slug']}/remove")
path = str(backup.dropbox_path(dropbox_dir, snapshot))
path = str(backup.dropbox_path(config, snapshot))
dbx.files_delete(path)
1 change: 1 addition & 0 deletions dropbox-upload/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
arrow
dropbox
jinja2
requests
retrace
41 changes: 41 additions & 0 deletions tests/test_backup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import datetime
import logging
import pathlib

from dropbox_upload import backup


def test_local_path():
expected = pathlib.Path("/backup/SLUG.tar")
assert backup.local_path({"slug": "SLUG"}) == expected


def test_dropbox_path(cfg):
cfg["dropbox_dir"] = "/dropbox_dir"
expected = pathlib.Path("/dropbox_dir/SLUG.tar")
assert backup.dropbox_path(cfg, {"slug": "SLUG"}) == expected


def test_backup_no_snapshots(cfg, caplog):
backup.backup(None, cfg, [])

assert (
"dropbox_upload.backup",
logging.WARNING,
"No snapshots found to backup",
) in caplog.record_tuples


def test_dropbox_path_date_filenames(cfg):
cfg["filename_fmt"] = "{{date}} {{slug}} {{name}}"
cfg["dropbox_dir"] = "/dropbox_dir"
expected = pathlib.Path(
"/dropbox_dir/2018-09-13 19.50.22 SLUG Automated backup.tar"
)
snapshot = {
"slug": "SLUG",
"name": "Automated backup",
"date": datetime.datetime(2018, 9, 13, 19, 50, 22).isoformat(),
}
result = backup.dropbox_path(cfg, snapshot)
assert result == expected
30 changes: 1 addition & 29 deletions tests/test_dropbox_upload.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import json
import logging
import pathlib

from dropbox_upload import backup, config, dropbox, hassio, limit, util
from dropbox_upload import config, dropbox, hassio, limit, util


def test_bytes_to_human():
Expand All @@ -21,17 +20,6 @@ def test_load_config(tmpdir):
assert config.load_config(p.strpath) == {}


def test_local_path():
expected = pathlib.Path("/backup/SLUG.tar")
assert backup.local_path({"slug": "SLUG"}) == expected


def test_dropbox_path():
dropbox_dir = pathlib.Path("/dropbox_dir/")
expected = pathlib.Path("/dropbox_dir/SLUG.tar")
assert backup.dropbox_path(dropbox_dir, {"slug": "SLUG"}) == expected


def test_setup_logging_normal():
logger = config.setup_logging({})
assert logger.level == logging.INFO
Expand All @@ -53,22 +41,6 @@ def test_list_snapshots(requests_mock):
assert hassio.list_snapshots() == []


def test_backup_no_snapshots(tmpdir, requests_mock, caplog):

# Create config file
p = tmpdir.join("config.json")
p.write(json.dumps({"dropbox_dir": "snapshots", "access_token": "token"}))
cfg = config.load_config(p.strpath)

backup.backup(None, cfg, [])

assert (
"dropbox_upload.backup",
logging.WARNING,
"No snapshots found to backup",
) in caplog.record_tuples


def test_limit_snapshots_no_setting(cfg, caplog):
cfg["keep"] = None
limit.limit_snapshots(None, cfg, [])
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ deps =
-rtest-requirements.txt
commands=
pytest -v --basetemp={envtmpdir} \
--cov=dropbox_upload --cov-fail-under=70 --cov-report=term-missing {posargs}
--cov=dropbox_upload --cov-fail-under=70 {posargs}

[testenv:format]
basepython=python3
Expand Down

0 comments on commit f486e8f

Please sign in to comment.