From d7f9017abd7fe62f63a3251bbcec62ea42ccb46e Mon Sep 17 00:00:00 2001 From: shagi Date: Fri, 6 Nov 2020 15:45:30 +0100 Subject: [PATCH] Add ipfs command --- negromate/web/commands/__init__.py | 3 +- negromate/web/commands/ipfs.py | 67 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100755 negromate/web/commands/ipfs.py diff --git a/negromate/web/commands/__init__.py b/negromate/web/commands/__init__.py index 05cac3b..f1d3234 100644 --- a/negromate/web/commands/__init__.py +++ b/negromate/web/commands/__init__.py @@ -1,7 +1,7 @@ import argparse import sys -from . import run, build, thumbnail, rsync +from . import run, build, thumbnail, rsync, ipfs def main(): @@ -24,6 +24,7 @@ def main(): run, thumbnail, rsync, + ipfs, ] parser = argparse.ArgumentParser() diff --git a/negromate/web/commands/ipfs.py b/negromate/web/commands/ipfs.py new file mode 100755 index 0000000..d711115 --- /dev/null +++ b/negromate/web/commands/ipfs.py @@ -0,0 +1,67 @@ +from pathlib import Path +import subprocess +import urllib.request + + +name = 'ipfs' +help_text = 'Upload the web to IPFS' + + +def options(parser): + parser.add_argument( + 'song_folder', type=Path, + help="Folder with the song database.") + parser.add_argument( + '-a', '--api', default='http://localhost:5001', + help="IPFS API server, defaults to http://localhost:5001.") + parser.add_argument( + '-p', '--pinfile', default='~/.negromate/ipfs.hash', type=Path, + help="file to store the current ipfs hash, defaults to ~/.negromate/ipfs.") + + +def run(args): + # add to local + command = [ + "ipfs", + "add", + "--recursive", + "--quieter", + args.song_folder, + ] + final_hash = subprocess.check_output(command).decode('utf-8').strip() + + # pin in server + url = "{}/api/v0/pin/add?arg={}&progress=false".format( + args.api, + final_hash, + ) + urllib.request.urlopen(url) + + # read previous hash and update value + pinfile = args.pinfile.expanduser() + if pinfile.exists(): + with pinfile.open() as f: + previous_hash = f.read() + else: + if not pinfile.parent.exists(): + pinfile.parent.mkdir() + previous_hash = None + with pinfile.open('w') as f: + f.write(final_hash) + + if previous_hash is not None: + # remove previous pin on local + command = [ + 'ipfs', + 'pin', + 'rm', + previous_hash, + ] + subprocess.check_call(command) + + # remove previous pin on server + url = "{}/api/v0/pin/rm?arg={}".format( + args.api, + previous_hash, + ) + urllib.request.urlopen(url)