suchwow/suchwow/cli.py

174 lines
6.3 KiB
Python

from os import makedirs, getenv
from random import choice
from datetime import datetime
import lorem
from flask import Blueprint
from suchwow._models import db, User, Post, AuditEvent, TipSent, TipReceived, Vote
from suchwow.models import Post as OldPost
from suchwow import wownero
from suchwow import config
bp = Blueprint('cli', 'cli', cli_group=None)
@bp.cli.command("init")
def init():
# create subdirs
for i in ["uploads", "db", "wallet"]:
makedirs(f"{config.DATA_FOLDER}/{i}", exist_ok=True)
# init db
db.create_tables([User, Post, AuditEvent, TipSent, TipReceived, Vote])
@bp.cli.command('generate_data')
def generate_data():
if getenv('FLASK_DEBUG', 0) == '1':
users = ['lza_menace', 'wowario', 'jwinterm', 'dsc', 'asymptotically']
for user in users:
moderator = False
if not User.select().where(User.username == user):
if user == 'lza_menace':
moderator = True
User.create(
username=user,
moderator=moderator
)
print(f'Created user {user}')
for i in range(1, 5):
wallet = wownero.Wallet()
address_idx, address = wallet.new_address(config.WALLET_ACCOUNT)
wallet.store()
Post.create(
title=lorem.sentence(),
text=lorem.sentence(),
user=choice(list(User.select())),
image_name='test.jpg',
account_index=config.WALLET_ACCOUNT,
address_index=address_idx,
address=address
)
@bp.cli.command('process_tips')
def process_tips():
w = wownero.Wallet()
for post in Post.select().order_by(Post.timestamp.desc()):
print(f'Checking new tips for post {post.id}')
txes = w.transfers(config.WALLET_ACCOUNT, [post.address_index])
addr = w.get_address(config.WALLET_ACCOUNT, [post.address_index])
if post.address != addr['addresses'][0]['address']:
print(f'addresses dont match. skipping.')
continue
if txes:
for tx in txes['in']:
if tx['unlock_time'] > 0:
print('someone added a lock time to this tx. skipping for now.')
continue
_tx = TipReceived.select().where(TipReceived.txid == tx['txid']).first()
if not _tx:
post = Post.select().where(Post.address == tx['address']).first()
if not post:
print('No post exists with that address. Not sure wat do.')
else:
TipReceived.create(
post=post,
txid=tx['txid'],
timestamp=datetime.utcfromtimestamp(tx['timestamp']),
amount=sum(tx['amounts']),
fee=tx['fee']
)
print('Saved tip {} ({} WOW) received for post {} by {}'.format(
tx['txid'], wownero.from_atomic(sum(tx['amounts'])),
post.id, post.user.username
))
@bp.cli.command('payout_users')
def payout_users():
wallet = wownero.Wallet()
balances = wallet.balances()
print('Wallet balances are {} locked, {} unlocked'.format(
wownero.from_atomic(balances[0]), wownero.from_atomic(balances[1])
))
for user in User.select():
rcvd = user.get_wow_received()
sent = user.get_wow_sent()
to_send = rcvd - sent
if to_send >= 1:
print('{} has received {} atomic WOW but sent {} atomic WOW. Sending {} atomic WOW'.format(
user.username, wownero.from_atomic(rcvd),
wownero.from_atomic(sent), wownero.from_atomic(to_send)
))
@bp.cli.command('rescan')
def rescan():
wallet = wownero.Wallet()
wallet.make_wallet_rpc('rescan_blockchain')
@bp.cli.command('save')
def rescan():
wallet = wownero.Wallet()
wallet.make_wallet_rpc('store')
print('Saved wallet.')
@bp.cli.command("create_accounts")
def create_accounts():
wallet = wownero.Wallet()
highest_account = OldPost.select().order_by(OldPost.timestamp.desc()).first().account_index
print(f'Highest post account index is {highest_account} but highest wallet account is {wallet.accounts()[-1]}. Generating new accounts!')
while wallet.accounts()[-1] < highest_account:
account = wallet.new_account()
print(f"Created account {account}")
wallet.make_wallet_rpc('store')
# @bp.cli.command("payout_users")
# def payout_users():
# wallet = wownero.Wallet()
# _fa = wownero.from_atomic
# _aw = wownero.as_wownero
# for post in Post.select():
# try:
# submitter = Profile.get(username=post.submitter)
# balances = wallet.balances(post.account_index)
# url = url_for('post.read', id=post.id, _external=True)
# if balances[1] > 0.05:
# print(f"Post #{post.id} has {balances[1]} funds unlocked and ready to send. Sweeping all funds to user's address ({submitter.address}).")
# sweep = wallet.sweep_all(account=post.account_index, dest_address=submitter.address)
# print(sweep)
# if "tx_hash_list" in sweep:
# amount = 0
# for amt in sweep["amount_list"]:
# amount += int(amt)
# except Exception as e:
# print(f"Failed because: {e}")
# @bp.cli.command("show")
# @click.argument("post_id")
# def post_id(post_id):
# p = Post.filter(id=post_id).first()
# if p:
# print(p.show())
# else:
# print("That post doesn't exist")
# @bp.cli.command("load_cache")
# def load_cache():
# current_app.logger.info('loading top posters into cache')
# get_top_posters()
# current_app.logger.info('done')
# current_app.logger.info('loading latest tipped into cache')
# get_latest_tipped_posts()
# current_app.logger.info('done')
# for i in [1, 3, 7, 30, 9999]:
# current_app.logger.info(f'loading top posts last {i} days into cache')
# get_top_posts(i)
# current_app.logger.info('done')