Example #1
0
def before_request():
    if current_user.is_authenticated:
        try:
            current_user.last_online = datetime.now().strftime(
                "%Y-%m-%d %H:%M:%S")
            db_session.commit()
            db_session.flush()
        except:
            db_session.rollback()
Example #2
0
 def remove(cid: int):
     from funding.factory import db_session
     from flask.ext.login import current_user
     if current_user.id != user_id and not current_user.admin:
         raise Exception("no rights to remove this comment")
     comment = Comment.get(cid=cid)
     try:
         comment.delete()
         db_session.commit()
         db_session.flush()
     except:
         db_session.rollback()
         raise
Example #3
0
 def edit(email: str, password: str):
     from funding.factory import db_session
     from funding.factory import bcrypt
     try:
         db_session.query(User).filter(User.email == email).update({
             'password':
             bcrypt.generate_password_hash(password).decode('utf8')
         })
         db_session.commit()
         db_session.flush()
     except Exception as ex:
         db_session.rollback()
         raise
Example #4
0
    def balance(self):
        """This property retrieves the current funding status
        of this proposal. It uses Redis cache to not spam the
        daemon too much. Returns a nice dictionary containing
        all relevant proposal funding info"""
        from funding.bin.utils import Summary, coin_to_usd
        from funding.factory import cache, db_session
        rtn = {'sum': 0.0, 'txs': [], 'pct': 0.0, 'available': 0.0}

        cache_key = 'coin_balance_pid_%d' % self.id
        data = cache.get(cache_key)
        if not data:
            from funding.bin.daemon import Daemon
            try:
                data = Daemon().get_transfers_in(index=self.id,
                                                 proposal_id=self.id)
                if not isinstance(data, dict):
                    print('error; get_transfers_in; %d' % self.id)
                    return rtn
                cache.set(cache_key, data=data, expiry=300)
            except:
                print('error; get_transfers_in; %d' % self.id)
                return rtn

        prices = Summary.fetch_prices()
        for tx in data['txs']:
            if prices:
                tx['amount_usd'] = coin_to_usd(amt=tx['amount_human'],
                                               btc_per_coin=prices['coin-btc'],
                                               usd_per_btc=prices['btc-usd'])
            tx['datetime'] = datetime.fromtimestamp(tx['timestamp'])

        if data.get('sum', 0.0):
            data['pct'] = 100 / float(self.funds_target / data.get('sum', 0.0))
            data['available'] = data['sum']
        else:
            data['pct'] = 0.0
            data['available'] = 0.0

        if data['pct'] != self.funds_progress:
            self.funds_progress = data['pct']
            db_session.commit()
            db_session.flush()

        if data['available']:
            data['remaining_pct'] = 100 / float(
                data['sum'] / data['available'])
        else:
            data['remaining_pct'] = 0.0

        return data
Example #5
0
    def add_comment(cls,
                    pid: int,
                    user_id: int,
                    message: str,
                    cid: int = None,
                    message_id: int = None,
                    automated=False):
        from flask.ext.login import current_user
        from funding.factory import db_session
        if not message:
            raise Exception("empty message")

        if current_user.id != user_id and not current_user.admin:
            raise Exception("no rights to add or modify this comment")

        if not message_id:
            proposal = Proposal.find_by_id(pid=pid)
            if not proposal:
                raise Exception("no proposal by that id")
            comment = Comment(user_id=user_id,
                              proposal_id=proposal.id,
                              automated=automated)
            if cid:
                parent = Comment.find_by_id(cid=cid)
                if not parent:
                    raise Exception("cannot reply to a non-existent comment")
                comment.replied_to = parent.id
        else:
            try:
                user = db_session.query(User).filter(
                    User.id == user_id).first()
                if not user:
                    raise Exception("no user by that id")
                comment = next(c for c in user.comments if c.id == message_id)
                if comment.locked and not current_user.admin:
                    raise Exception("your comment has been locked/removed")
            except StopIteration:
                raise Exception("no message by that id")
            except:
                raise Exception("unknown error")
        try:
            comment.message = message
            db_session.add(comment)
            db_session.commit()
            db_session.flush()
        except Exception as ex:
            db_session.rollback()
            raise Exception(str(ex))
        return comment
Example #6
0
 def lock(cid: int):
     from funding.factory import db_session
     from flask.ext.login import current_user
     if not current_user.admin:
         raise Exception("admin required")
     comment = Comment.find_by_id(cid=cid)
     if not comment:
         raise Exception("comment by that id not found")
     comment.locked = True
     try:
         db_session.commit()
         db_session.flush()
         return comment
     except:
         db_session.rollback()
         raise
Example #7
0
File: orm.py Project: AQ888/funding
    def add(cls, proposal_id, amount, to_address):
        # @TODO: validate that we can make this payout; check previous payouts
        from flask.ext.login import current_user
        if not current_user.admin:
            raise Exception("user must be admin to add a payout")
        from funding.factory import db_session

        try:
            payout = Payout(propsal_id=proposal_id, amount=amount, to_address=to_address)
            db_session.add(payout)
            db_session.commit()
            db_session.flush()
            return payout
        except Exception as ex:
            db_session.rollback()
            raise
Example #8
0
    def add(cls, username, password, email):
        from funding.factory import db_session
        from funding.validation import val_username, val_email

        try:
            # validate incoming username/email
            val_username(username)
            val_email(email)

            user = User(username, password, email)
            db_session.add(user)
            db_session.commit()
            db_session.flush()
            return user
        except Exception as ex:
            db_session.rollback()
            raise
Example #9
0
 def edit(cid: int, pid: int, message: str, user_id: int):
     from funding.factory import db_session
     from flask_login import current_user
     if current_user.id != user_id and not current_user.admin:
         raise Exception("no rights to remove this comment")
     comment = Comment.find_by_id(cid=cid)
     if not comment.locked:
         try:
             db_session.query(Comment).filter(Comment.id == cid).update(
                 {'message': message})
             db_session.commit()
             db_session.flush()
         except:
             db_session.rollback()
             raise
     else:
         raise Exception("Comment is locked and can not be edited")
Example #10
0
File: orm.py Project: AQ888/funding
    def get_addr_donation(self):
        from funding.factory import db_session
        from funding.bin.daemon import Daemon
        if self.addr_donation:
            return self.addr_donation

        try:
            addr_donation = Daemon().get_address(wallet_address=settings.RPC_WADDR, proposal_id=self.id)
            if not isinstance(addr_donation, dict):
                raise Exception('get_address, needs dict; %d' % self.id)
        except Exception as ex:
            print('error: %s' % str(ex))
            return

        if addr_donation.get('integrated_address'):
            self.addr_donation = addr_donation['integrated_address']
            db_session.commit()
            db_session.flush()
            return addr_donation['integrated_address']
Example #11
0
    def generate_donation_addr(cls):
        from funding.factory import db_session
        from funding.bin.daemon import Daemon
        if cls.addr_donation:
            return cls.addr_donation

        try:
            addr_donation = Daemon().get_address(index=cls.id, proposal_id=cls.id)
            if not isinstance(addr_donation, dict):
                raise Exception('get_address, needs dict; %d' % cls.id)
        except Exception as ex:
            print('error: %s' % str(ex))
            return

        if addr_donation.get('address'):
            cls.addr_donation = addr_donation['address']
            db_session.commit()
            db_session.flush()
            return addr_donation['address']
Example #12
0
    def generate_donation_addr(cls):
        from funding.factory import db_session
        from funding.bin.daemon import Daemon
        if cls.addr_donation:
            return cls.addr_donation

        # check if the current user has an account in the wallet
        account = Daemon().get_accounts(cls.id)
        if not account:
            account = Daemon().create_account(cls.id)
        index = account['account_index']

        address = account.get('address') or account.get('base_address')
        if not address:
            raise Exception('Cannot generate account/address for pid %d' % cls.id)

        # assign donation address, commit to db
        cls.addr_donation = address
        db_session.commit()
        db_session.flush()
        return address
Example #13
0
 def remove(cid: int, pid: int, puid: int):
     from funding.factory import db_session
     from flask_login import current_user
     if current_user.id != puid and not current_user.admin:
         raise Exception("no rights to remove this comment")
     comment = Comment.find_by_id(cid=cid)
     if not comment.replied_to:
         comment.message = "comment removed by %s" % current_user
         comment.locked = True
         try:
             db_session.commit()
             db_session.flush()
         except:
             db_session.rollback()
     else:
         try:
             db_session.delete(comment)
             db_session.commit()
             db_session.flush()
         except:
             db_session.rollback()
             raise
Example #14
0
 def generate_donation_addr_qr(donation_addr, pid):
     from funding.factory import db_session
     from PIL import Image
     url = pyqrcode.create(donation_addr, error='L')
     filename = os.path.abspath('funding/static/qr/' + donation_addr +
                                '.png')
     logod = os.path.abspath('funding/static/aeon.jpg')
     url.png(filename, scale=10)
     im = Image.open(filename)
     im = im.convert("RGBA")
     width, height = im.size
     logo_size = 76
     logo = Image.open(logod)
     xmin = ymin = int((width / 2) - (logo_size / 2))
     xmax = ymax = int((width / 2) + (logo_size / 2))
     logo = logo.resize((xmax - xmin, ymax - ymin))
     im.paste(logo, (xmin, ymin, xmax, ymax))
     im.save(filename)
     p = Proposal.find_by_id(pid)
     p.generated_qr = True
     db_session.commit()
     db_session.flush()
Example #15
0
def proposal_api_add(title, content, pid, funds_target, addr_receiving, category, status):
    import markdown2

    if current_user.is_anonymous:
        return make_response(jsonify('err'), 500)

    if len(title) <= 8:
        return make_response(jsonify('title too short'), 500)

    if len(content) <= 20:
        return make_response(jsonify('content too short'), 500)

    if category and category not in settings.FUNDING_CATEGORIES:
        return make_response(jsonify('unknown category'), 500)

    if status not in settings.FUNDING_STATUSES.keys():
        make_response(jsonify('unknown status'), 500)

    if status != 1 and not current_user.admin:
        return make_response(jsonify('no rights to change status'), 500)

    try:
        from funding.bin.anti_xss import such_xss
        content_escaped = such_xss(content)
        html = markdown2.markdown(content_escaped, safe_mode=True)
    except Exception as ex:
        return make_response(jsonify('markdown error'), 500)



    if pid:
        p = Proposal.find_by_id(pid=pid)
        if not p:
            return make_response(jsonify('proposal not found'), 500)

        if p.user.id != current_user.id and not current_user.admin:
            return make_response(jsonify('no rights to edit this proposal'), 500)

        p.headline = title
        p.content = content
        p.html = html
        if addr_receiving:
            p.addr_receiving = addr_receiving
        if category:
            p.category = category

        # detect if an admin moved a proposal to a new status and auto-comment
        if p.status != status and current_user.admin:
            msg = "Moved to status \"%s\"." % settings.FUNDING_STATUSES[status].capitalize()
            try:
                Comment.add_comment(user_id=current_user.id, message=msg, pid=pid, automated=True)
            except:
                pass

        p.status = status
        p.last_edited = datetime.now()


    else:
        try: 
            funds_target = float(funds_target) 
        except Exception as ex:
            return make_response(jsonify('letters detected'),500)
        if funds_target < 1:
                return make_response(jsonify('Proposal asking less than 1 error :)'), 500)
        if len(addr_receiving) != 95:
            return make_response(jsonify('Faulty address, should be of length 95'), 500)

        p = Proposal(headline=title, content=content, category='misc', user=current_user)
        proposalID = current_user
        addr_donation = Proposal.generate_proposal_subaccount(proposalID)
        p.addr_donation = addr_donation
        p.html = html
        p.last_edited = datetime.now()
        p.funds_target = funds_target
        p.addr_receiving = addr_receiving
        p.category = category
        p.status = status
        db_session.add(p)
    


    db_session.commit()
    db_session.flush()

    # reset cached statistics
    from funding.bin.utils import Summary
    Summary.fetch_stats(purge=True)

    return make_response(jsonify({'url': url_for('proposal', pid=p.id)}))