2020-06-09 16:59:27 +00:00
|
|
|
import re
|
|
|
|
import requests
|
2020-06-17 15:13:52 +00:00
|
|
|
import logging
|
2022-05-20 10:27:58 +00:00
|
|
|
import os
|
2020-06-09 16:59:27 +00:00
|
|
|
|
|
|
|
from ipfs import ipfsBinToText
|
|
|
|
|
2020-06-17 15:13:52 +00:00
|
|
|
LOG = logging.getLogger('root')
|
|
|
|
|
2022-05-20 10:27:58 +00:00
|
|
|
IPFS_GATEWAY = os.environ.get('IPFS_GATEWAY','https://gateway.ipfs.io/ipfs')
|
2020-06-08 15:29:34 +00:00
|
|
|
|
2020-06-08 10:45:38 +00:00
|
|
|
class StickerPack:
|
|
|
|
# https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1577.md
|
|
|
|
# All content hashes in Sticker Pack metadata have the same prefix.
|
|
|
|
content_hash_rgx = r'e30101701220\w+'
|
|
|
|
|
2020-06-08 15:29:34 +00:00
|
|
|
def __init__(self, chash):
|
|
|
|
self.content_hash = chash
|
|
|
|
|
|
|
|
resp = requests.get("{}/{}".format(IPFS_GATEWAY, chash))
|
2020-06-08 10:45:38 +00:00
|
|
|
resp.raise_for_status()
|
2020-06-08 15:29:34 +00:00
|
|
|
|
2020-06-09 16:59:27 +00:00
|
|
|
self.image_hashes = StickerPack.parse_clj_meta(resp.text)
|
2020-06-08 10:45:38 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def parse_clj_meta(data):
|
|
|
|
# Find all content hashes of images in the Clojure formatted metadata
|
2020-06-09 16:59:27 +00:00
|
|
|
matches = re.findall(StickerPack.content_hash_rgx, data)
|
2020-06-08 10:45:38 +00:00
|
|
|
# IPFS can't handle EIP-1577 content hashes
|
2020-06-09 16:59:27 +00:00
|
|
|
return [ipfsBinToText(ch) for ch in matches]
|
2020-06-15 14:57:15 +00:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '<Pack hash={} imgs={}>'.format(
|
|
|
|
self.content_hash, len(self.image_hashes))
|
2020-06-17 15:13:52 +00:00
|
|
|
|
|
|
|
def pin(self, ipfs):
|
|
|
|
LOG.info('Pinning: %s', self)
|
2020-07-27 11:51:24 +00:00
|
|
|
for chash in [self.content_hash] + self.image_hashes:
|
2020-06-17 15:13:52 +00:00
|
|
|
LOG.debug('Pinning hash: %s', chash)
|
2020-07-27 11:51:24 +00:00
|
|
|
status = ipfs.pin(chash)
|
|
|
|
if status == 'pinned':
|
|
|
|
LOG.info('Successfully pinned: %s', chash)
|
|
|
|
elif status == 'pinning':
|
|
|
|
LOG.info('Pinning in progress: %s', chash)
|
|
|
|
elif status == 'failed':
|
2020-06-17 15:13:52 +00:00
|
|
|
LOG.error('Failed to pin image: %s', chash)
|
2020-07-27 11:51:24 +00:00
|
|
|
else:
|
|
|
|
LOG.warning('Content status: %s, %s', status, chash)
|