def on_get(self, req, resp, start, finish): logger.info('COMMAND %s Received' % self.__class__.__name__) db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json')) memes =[] if start > finish: direction = -1 else: direction = 1 for height in range(int(start), int(finish) + 1, direction): meme_metadata = db.search_by_memechain_height(height) if not meme_metadata: logger.error('COMMAND %s Failed %s: %s' % (self.__class__.__name__, 'Database Error', "Meme {} not found.".format(height))) raise falcon.HTTPError(falcon.HTTP_404, 'Database Error', "Meme {} not found.".format(height)) else: memes.append(meme_metadata) resp.status = falcon.HTTP_200 resp.set_header('Powered-By', 'Memechain') logger.info('COMMAND %s Success' % self.__class__.__name__) resp.body = json.dumps({ 'success': True, 'result': memes})
def on_get(self, req, resp): logger.info('COMMAND %s Received' % self.__class__.__name__) db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json')) blockchain_info = get_blockchain_info() last_meme_info = db.get_last_meme() memechain_height = db.get_memechain_height() memechain_block_sync_height = pickle.load( open(os.path.join(config['DATA_DIR'], 'sync.p'), 'rb')) resp.status = falcon.HTTP_200 resp.set_header('Powered-By', 'Memechain') logger.info('COMMAND %s Success' % self.__class__.__name__) resp.body = json.dumps({ 'success': True, 'result': { 'memechain_version': MEMECHAIN_VERSION, 'blockchain_height': blockchain_info['blocks'], 'blockchain_balance': float(blockchain_info['balance']), 'memechain_block_sync_height': memechain_block_sync_height, 'memechain_height': memechain_height, 'last_meme_metadata': last_meme_info } })
def on_get(self, req, resp, height): logger.info('COMMAND %s Received' % self.__class__.__name__) db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json')) meme_metadata = db.search_by_memechain_height(height) # Generate image file path name = '{img_name}{ext}'.format(img_name=meme_metadata["ipfs_id"], ext=meme_metadata["imgformat"]) image_path = os.path.join(config['DATA_DIR'], name) if not self._IMAGE_NAME_PATTERN.match(name): # 404 Not found response logger.error('COMMAND %s Failed %s: %s' % (self.__class__.__name__, 'Database Error', "Meme not found.")) raise falcon.HTTPError(falcon.HTTP_404, 'Database Error', "Meme not found.") else: # Open image file stream = io.open(image_path, 'rb') stream_len = os.path.getsize(image_path) # Generate image response resp.status = falcon.HTTP_200 resp.set_header('Powered-By', 'Memechain') resp.content_type = mimetypes.guess_type(name)[0] logger.info('COMMAND %s Success' % self.__class__.__name__) resp.stream, resp.stream_len = stream, stream_len
def on_get(self, req, resp): logger.info('COMMAND %s Received' % self.__class__.__name__) db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json')) height = db.get_memechain_height() resp.status = falcon.HTTP_200 resp.set_header('Powered-By', 'Memechain') logger.info('COMMAND %s Success' % self.__class__.__name__) resp.body = json.dumps({'success': True, 'result': height})
def on_get(self, req, resp, height): logger.info('COMMAND %s Received' % self.__class__.__name__) db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json')) meme_metadata = db.search_by_memechain_height(height) if not meme_metadata: logger.error( 'COMMAND %s Failed %s: %s' % (self.__class__.__name__, 'Database Error', "Meme not found.")) raise falcon.HTTPError(falcon.HTTP_404, 'Database Error', "Meme not found.") resp.status = falcon.HTTP_200 resp.set_header('Powered-By', 'Memechain') logger.info('COMMAND %s Success' % self.__class__.__name__) resp.body = json.dumps({'success': True, 'result': meme_metadata})
def on_get(self, req, resp, ipfs_id): logger.info('COMMAND %s Received' % self.__class__.__name__) db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json')) meme_metadata = db.search_by_ipfs_id(ipfs_id) # Generate image file path name = '{img_name}.{ext}'.format(img_name=meme_metadata["ipfs_id"], ext=meme_metadata["imgformat"]) image_path = os.path.join(config['DATA_DIR'], name) # Open image file stream = io.open(image_path, 'rb') stream_len = os.path.getsize(image_path) # Generate image response resp.status = falcon.HTTP_200 resp.set_header('Powered-By', 'Memechain') resp.content_type = mimetypes.guess_type(name)[0] logger.info('COMMAND %s Success' % self.__class__.__name__) resp.stream, resp.stream_len = stream, stream_len
def check_running(): counter = 0 for q in psutil.process_iter(): if q.name().find('sync'): if len(q.cmdline()) > 1 and 'sync.py' in q.cmdline()[1]: counter = counter + 1 if counter > 1: return True else: return False if __name__ == '__main__': # Load database db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json')) if not config["MULTIPLE_SYNC_RUNNING"] and check_running(): logger.info('COMMAND %s Failed %s: %s' % ('Sync', 'Memechain', "Sync process already running.Shutdown current sync")) sys.exit(1) if config["CHECK_FILES_ON_RUNNING"]: check_files_status(db) # Check blockheight block_height = get_block_height() if db.get_memechain_height() == 0: # Load genesis meme
def on_post(self, req, resp): logger.info('COMMAND %s Received' % self.__class__.__name__) db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json')) while check_running(): time.sleep(3) logger.info('Waiting for the synchronization process to complete add_meme') # Generate random placeholder img name img_placeholder_name = str(random.random()).split(".")[1] ext = mimetypes.guess_extension(req.content_type) if ext == '.jpe': ext = '.jpg' name = '{img_name}{ext}'.format(img_name=img_placeholder_name, ext=ext) image_path = os.path.join(config['DATA_DIR'], name) # Write image to local storage with io.open(image_path, 'wb') as image_file: while True: chunk = req.stream.read(self._CHUNK_SIZE_BYTES) if not chunk: break image_file.write(chunk) if magic.from_file(image_path).lower().find(mimetypes.guess_extension(req.content_type)[1:]) < 0: raise falcon.HTTPBadRequest( "Memechain error", "Meme has not passed validation, file extension is wrong.") # Check file size meme_filesize = os.path.getsize(image_path) * 0.000001 # in MB if meme_filesize > 10: os.remove(image_path) logger.error('COMMAND %s Failed %s: %s' % (self.__class__.__name__, 'Upload Error', "Meme filesize too large.")) raise falcon.HTTPError(falcon.HTTP_400, "Upload error", "Meme filesize too large.") # Add image to ipfs ipfs_id = IPFSTools().add_meme(image_path)['Hash'] # Rename local img file to ipfs_id for easy reference new_name = '{img_name}{ext}'.format(img_name=ipfs_id, ext=ext) os.rename(image_path, os.path.join(config['DATA_DIR'], new_name)) # Add to Kekcoin chain memetx = MemeTx(ipfs_id) prev_block_memes = db.get_prev_block_memes() if prev_block_memes: memetx.generate_hashlink(prev_block_memes) try: Validate(memetx, db=db, ipfs_dir=config['DATA_DIR'], prev_block_memes=prev_block_memes) except TypeError as e: # Delete invalid Meme os.remove(os.path.join(config['DATA_DIR'], new_name)) logger.error('COMMAND %s Failed %s: %s' % (self.__class__.__name__, 'Memechain Error', "Meme has not passed memechain validation, file extension not supported.%s") ) raise falcon.HTTPError(falcon.HTTP_400, "Memechain error", "Meme has not passed validation, file extension not supported.%s" % e ) if memetx.is_meme_valid(): memetx.blockchain_write() db.add_meme(**{"ipfs_id": ipfs_id, "hashlink": memetx.get_hashlink(), "txid": memetx.get_txid(), "author": memetx.get_author(), "block": 0, "imgformat": ext[1:], "status": "unconfirm"}) resp.status = falcon.HTTP_201 resp.set_header('Powered-By', 'Memechain') logger.info('COMMAND %s Success' % self.__class__.__name__) resp.body = json.dumps({ 'success': True, 'result': {'ipfs_id' : ipfs_id, 'txid' : memetx.get_txid(), 'hashlink' : memetx.get_hashlink(), 'author' : memetx.get_author()}}) else: # Delete invalid Meme os.remove(os.path.join(config['DATA_DIR'], new_name)) logger.error('COMMAND %s Failed %s: %s' % (self.__class__.__name__, 'Memechain Error', "Meme has not passed memechain validation: ")) raise falcon.HTTPError(falcon.HTTP_400, "Memechain error", "Meme has not passed validation: ") else: # Genesis block logic memetx = MemeTx(ipfs_id) memetx.generate_genesis_hashlink() memetx.blockchain_write() resp.status = falcon.HTTP_201 resp.set_header('Powered-By', 'Memechain') logger.info('COMMAND %s Success' % self.__class__.__name__) resp.body = json.dumps({ 'success': True, 'result': {'ipfs_id' : ipfs_id, 'txid' : memetx.get_txid(), 'hashlink' : memetx.get_hashlink(), 'author' : memetx.get_author()}})
def on_post(self, req, resp): logger.info('COMMAND %s Received' % self.__class__.__name__) db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json')) # Generate random placeholder img name img_placeholder_name = random.random().split(".")[1] ext = mimetypes.guess_extension(req.content_type) name = '{img_name}{ext}'.format(img_name=img_placeholder_name, ext=ext) image_path = os.path.join(config['DATA_DIR'], name) # Write image to local storage with io.open(image_path, 'wb') as image_file: while True: chunk = req.stream.read(self._CHUNK_SIZE_BYTES) if not chunk: break image_file.write(chunk) # Add image to ipfs ipfs_id = IPFSTools().add_meme(imgage_path)['Hash'] # Rename local img file to ipfs_id for easy reference new_name = '{img_name}{ext}'.format(img_name=ipfs_id, ext=ext) os.rename(image_path, os.path.join(config['DATA_DIR'], new_name)) # Add to Kekcoin chain memetx = MemeTx(ipfs_id) prev_block_memes = db.get_prev_block_memes() if prev_block_memes: memetx.generate_hashlink(prev_block_memes) Validate(memetx, db=db, ipfs_dir=config['DATA_DIR'], prev_block_memes=prev_block_memes) if memetx.is_meme_valid(): memetx.blockchain_write() resp.status = falcon.HTTP_201 resp.set_header('Powered-By', 'Memechain') logger.info('COMMAND %s Success' % self.__class__.__name__) resp.body = json.dumps({ 'success': True, 'result': ipfs_id}) else: logger.error('COMMAND %s Failed %s: %s' % (self.__class__.__name__, 'Memechain Error', "Meme has not passed memechain validation.")) raise falcon.HTTPError(falcon.HTTP_400, "Memechain error", "Meme has not passed " + " validation.") else: # Genesis block logic memetx = MemeTx(ipfs_id) meme.generate_genesis_hashlink() memetx.blockchain_write() resp.status = falcon.HTTP_201 resp.set_header('Powered-By', 'Memechain') logger.info('COMMAND %s Success' % self.__class__.__name__) resp.body = json.dumps({ 'success': True, 'result': ipfs_id})