Exemple #1
0
def id_to_human(id_string):
    """
    Turn an id into a human readable hash digest.

    :param id_string:
        The subject string to generate a human hash of.

    >>> id_to_human('i-ceebb70c')
    'friendisland'
    """
    id_sha512 = hashlib.sha512(id_string).hexdigest()
    return humanhash.humanize(id_sha512, 2, '')
def create_calendar(term, classes):
    digest = sha1(str(term) + str(classes)).hexdigest()
    name = humanize(digest, words=3)
    term_start = TERMS[term]['start']
    term_end = TERMS[term]['end']
    cal = Calendar(name=name)
    cal.add('x-wr-calname', name)
    cal['dtstart'] = term_start
    cal['dtend'] = term_end
    for c in classes:
        for day in c['days_numbered']:
            e = Event()
            e['summary'] = '%(subject)s %(catalog_number)s %(instructor)s %(section)s' % c
            e['description'] = 'Instructors: %(instructors)s\nClass number:%(class_number)s' % c
            e['location'] = c['location']['building'] + ' ' + c['location']['room']
            first_class = next_weekday(term_start , day)
            e.add('dtstart', tz.localize(datetime.datetime.combine(first_class, datetime.time(c['start_hour'], c['start_minute']))))
            e.add('dtend', tz.localize(datetime.datetime.combine(first_class, datetime.time(c['end_hour'], c['end_minute']))))
            e['uid'] = ('1149' + c['subject'] + c['catalog_number'] + c['section'] +
                        'day' + str(day) + 'v0.0.1').replace(r' ', '-')
            e.add('rrule', {'freq': 'weekly', 'until': term_end})
            cal.add_component(e)
    return cal.to_ical()
Exemple #3
0
			# assemble post components
			post_author = email_address.split('@')[0]
			post_date = email_message['Date']
			post_title = email_message['Subject']
			
			post_slug = unicodedata.normalize('NFKD', unicode(post_title))
			post_slug = post_slug.encode('ascii', 'ignore').lower()
			post_slug = re.sub(r'[^a-z0-9]+', '-', post_slug).strip('-')
			post_slug = re.sub(r'[-]+', '-', post_slug)
			
			# check for blog subdir
			email_hash = hashlib.md5()
			email_hash.update(email_address)
			blog_directory = email_hash.hexdigest()
			blog_physical_path = WEB_ROOT + '/' + blog_directory
			humane_blog_name = humanhash.humanize(blog_directory)
			if not os.path.exists(WEB_ROOT + '/' + blog_directory):
			
				# create directory for new blog
				os.makedirs(blog_physical_path)
				os.makedirs(os.path.join(blog_physical_path, 'assets'))
			
				# copy over the default stylsheet
				shutil.copytree('css', blog_physical_path + '/css')
	
				# create human-readable link to blog directory
				os.symlink(blog_directory, os.path.join(WEB_ROOT, humane_blog_name))
				
				# create html blog post index
				template = open('postindextemplate.html', 'r').read()
				new_index = template
Exemple #4
0
def handle_launch():
    """
    (QUESTION) Responds to the launch of the Skill with a welcome statement and a card.

    Templates:
    * Initial statement: 'welcome'
    * Reprompt statement: 'welcome_re'
    * Card title: 'uplink
    * Card body: 'welcome_card'
    """

    # ===================CREATE RENTER ACCOUNT ===================
    pk1, sk1 = ecdsa_new()
    metadata = {
        'name': 'Renter John',
    }
    renter_acct = create_account(metadata=metadata)
    privkey_pem = sk1.to_pem()

    location = "./keys/{}".format("renter-" + renter_acct.address)
    save_key(privkey_pem, location)

    # =================== CREATE LANDLORD ACCOUNT ===================
    pk, sk = ecdsa_new()
    meta = {'name': "Landlord Bob"}

    landlord_acct = create_account(metadata=meta)

    landlord_hid = humanhash.humanize(landlord_acct.address.encode("hex"))
    renter_hid = humanhash.humanize(renter_acct.address.encode("hex"))

    print("landlord HID: " + landlord_hid + "|" + landlord_acct.address)
    print("renter HID: " + renter_hid + "|" + renter_acct.address)

    privkey_pem = sk.to_pem()
    location = "./keys/{}".format("landlord-" + landlord_acct.address)
    save_key(privkey_pem, location)

    # =================== CREATE ASSET TO USE ======================
    private_key = sk
    origin = landlord_acct.address
    name = "GBP"
    asset_type = "Discrete"
    reference = "Token"
    supply = 100000
    issuer = landlord_acct.address

    asset = create_asset(private_key, origin, name, supply, asset_type,
                         reference, issuer)

    asset_hid = humanhash.humanize(asset.encode("hex"))
    print(asset_hid)

    # =================== CIRCULATE ASSET ======================
    amount = 100000
    receipt = uplink.circulate_asset(private_key, origin, amount, asset)

    gevent.sleep(1)  # :(

    if receipt['tag'] == 'RPCRespOK':
        print(receipt)
    else:
        print("ERROR with circulation")

    # =================== TRANSFER ASSET ================
    balance = 10000
    receipt = uplink.transfer_asset(private_key, origin, renter_acct.address,
                                    balance, asset)

    gevent.sleep(1)  # :(

    if receipt['tag'] == 'RPCRespOK':
        print(receipt)
    else:
        print("ERROR with Transfer")

    # =================== WELCOME TEXT =====================
    welcome_text = render_template('welcome')
    welcome_re_text = render_template('welcome_re')
    welcome_card_text = render_template('welcome_card')

    return question(welcome_text).reprompt(welcome_re_text).standard_card(
        title="uplink", text=welcome_card_text)
Exemple #5
0
def getTxBlock(block_num, tx_num):

    blocks = uplink.blocks()
    block_tx = len(blocks[int(block_num)].transactions)

    tx = blocks[int(block_num)].transactions[int(tx_num)]

    timestamp = datetimeformat(tx.get("timestamp"))
    origin = str(tx.get('origin'))
    action = str(tx.get('header').get('contents').get('tag'))
    body = tx.get("header").get('contents').get('contents')
    tx_details = ""

    if action == CreateAccount:
        tz = body.get('timezone')
        tz_text = "Account is associated with timezone {}. ".format(tz)

        if len(body.get("metadata")) > 0:
            meta_txt = ""
            for key, value in body.get('metadata'):
                meta = str(key) + " " + str(value) + ", "
                meta_txt = meta_txt + " " + meta

            meta_txt = "The metadata associated with account contains: {}".format(
                meta_txt)
        else:
            meta_txt = "There isn't any metadata."

        tx_details = tz_text + meta_txt

    if action == CirculateAsset:
        amount = body.get('amount')
        assetAddr = body.get('assetAddr')[:-10]

        asset_hid = humanhash.humanize(assetAddr.encode("hex"))

        tx_details = "{} of asset id: {} was circulated".format(
            amount, asset_hid)

    if action == TransferAsset:
        assetAddr = body.get("assetAddr")
        asset_hid = humanhash.humanize(assetAddr.encode("hex"))
        balance = body.get("balance")
        toAddr = body.get("toAddr")
        account_hid = humanhash.humanize(toAddr.encode("hex"))

        tx_details = "{} of asset ID {}, was transferred to account ID {}.".format(
            balance, asset_hid, account_hid)

    if action == CreateAsset:
        asset_addr = body.get("assetAddr")
        asset_hid = humanhash.humanize(asset_addr.encode("hex"))
        asset_name = body.get("assetName")
        asset_type = body.get("assetType").get("tag")
        reference = body.get("reference")
        supply = body.get("supply")

        if asset_type != "Fractional":
            precision = body.get("assetType").get("contents")
        else:
            precision = None

        tx_details = "Asset {} has a supply of {} with an id of {}".format(
            asset_name, supply, asset_hid)

    if action == CreateContract:
        contract_addr = body.get("address")
        contract_hid = humanhash.humanize(contract_addr.encode("hex"))
        owner_addr = body.get("owner")
        owner_hid = humanhash.humanize(owner_addr.encode("hex"))
        script = body.get("script")
        timestamp = datetimeformat(body.get("timestamp"))

        tx_details = "Contract {} was created on {} by account {}.".format(
            contract_hid, timestamp, owner_hid)

    if action == CallContract:
        contract_addr = body.get("address")
        contract_hid = humanhash.humanize(contract_addr.encode("hex"))
        method = body.get("method")

        tx_details = "Called {} method on contract {}".format(
            method, contract_hid)

    if action == RevokeAsset:
        asset_addr = body.get("address")
        asset_hid = humanhash.humanize(asset_addr.encode("hex"))

        tx_detail = "Asset {} was revoked.".format(asset_hid)

    if action == RevokeAccount:
        acct_addr = body.get("address")
        acct_hid = humanhash.humanize(acct_addr.encode("hex"))

        tx_detail = "Account {} was revoked.".format(acct_hid)

    # Complete Text Output
    text = "{} transaction executed on {}. Here are the details: {}".format(
        action, timestamp, tx_details)

    # return question(text).reprompt('would you like the
    # details?').standard_card('Transactions details?', text)
    return statement(text).simple_card("Transaction Details", text)
Exemple #6
0
def digest_and_humanize(word):
    m = hashlib.md5()
    m.update(word)
    return humanhash.humanize(m.hexdigest())
Exemple #7
0
    def __init__(self, bulletin_secret, wallet_mode=False):
        Mongo.init()
        self.wallet_mode = wallet_mode
        self.friend_requests = []
        self.sent_friend_requests = []
        self.friends = []
        self.posts = []
        self.logins = []
        self.messages = []
        self.new_messages = []
        self.already_added_messages = []
        self.bulletin_secret = str(bulletin_secret)

        if self.wallet_mode:
            return self.with_private_key()
        else:
            self.registered = False
            self.pending_registration = False
            bulletin_secrets = sorted(
                [str(Config.get_bulletin_secret()),
                 str(bulletin_secret)],
                key=str.lower)
            rid = hashlib.sha256(
                str(bulletin_secrets[0]) +
                str(bulletin_secrets[1])).digest().encode('hex')
            self.rid = rid

            res = Mongo.site_db.usernames.find({"rid": self.rid})
            if res.count():
                self.human_hash = res[0]['username']
            else:
                self.human_hash = humanhash.humanize(self.rid)
            start_height = 0
            # this will get any transactions between the client and server
            nodes = BU.get_transactions_by_rid(bulletin_secret,
                                               raw=True,
                                               returnheight=True)
            already_done = []
            for node in nodes:
                if node.get('dh_public_key'):
                    test = {
                        'rid': node.get('rid'),
                        'requester_rid': node.get('requester_id'),
                        'requested_rid': node.get('requested_id'),
                        'id': node.get('id')
                    }
                    node['username'] = '******'
                    if test in already_done:
                        continue
                    else:
                        self.friends.append(node)
                        already_done.append(test)

            registered = Mongo.site_db.friends.find(
                {'relationship.bulletin_secret': bulletin_secret})
            if registered.count():
                self.registered = True

            if not self.registered:
                # not regisered, let's check for a pending transaction
                res = Mongo.db.miner_transactions.find({
                    'rid': self.rid,
                    'public_key': {
                        '$ne': Config.public_key
                    }
                })
                res2 = Mongo.db.miner_transactions.find({
                    'rid':
                    self.rid,
                    'public_key':
                    Config.public_key
                })

                if res.count() and res2.count():
                    self.pending_registration = True

            if self.registered:
                for x in self.friends:
                    for y in x['outputs']:
                        if y['to'] != Config.address:
                            Mongo.site_db.usernames.update(
                                {
                                    'rid': self.rid,
                                    'username': self.human_hash,
                                }, {
                                    'rid': self.rid,
                                    'username': self.human_hash,
                                    'to': y['to'],
                                    'relationship': {
                                        'bulletin_secret': bulletin_secret
                                    }
                                },
                                upsert=True)
Exemple #8
0
            # assemble post components
            post_author = email_address.split('@')[0]
            post_date = email_message['Date']
            post_title = email_message['Subject']

            post_slug = unicodedata.normalize('NFKD', unicode(post_title))
            post_slug = post_slug.encode('ascii', 'ignore').lower()
            post_slug = re.sub(r'[^a-z0-9]+', '-', post_slug).strip('-')
            post_slug = re.sub(r'[-]+', '-', post_slug)

            # check for blog subdir
            email_hash = hashlib.md5()
            email_hash.update(email_address)
            blog_directory = email_hash.hexdigest()
            blog_physical_path = WEB_ROOT + '/' + blog_directory
            humane_blog_name = humanhash.humanize(blog_directory)
            if not os.path.exists(WEB_ROOT + '/' + blog_directory):

                # create directory for new blog
                os.makedirs(blog_physical_path)
                os.makedirs(os.path.join(blog_physical_path, 'assets'))

                # copy over the default stylsheet
                shutil.copytree('css', blog_physical_path + '/css')

                # create human-readable link to blog directory
                os.symlink(blog_directory,
                           os.path.join(WEB_ROOT, humane_blog_name))

                # create html blog post index
                template = open('postindextemplate.html', 'r').read()
Exemple #9
0
def random_id():
    return humanhash.humanize(hashlib.md5(os.urandom(32)).hexdigest())
Exemple #10
0
def digest_and_humanize(word):
    m = hashlib.md5()
    m.update(word)
    return humanhash.humanize(m.hexdigest())
Exemple #11
0
    def do_push(self, txn, bulletin_secret):
        config = app.config['yada_config']
        mongo = app.config['yada_mongo']
        my_bulletin_secret = config.bulletin_secret
        rids = sorted([str(my_bulletin_secret), str(bulletin_secret)], key=str.lower)
        rid = hashlib.sha256(str(rids[0]) + str(rids[1])).digest().encode('hex')

        res1 = mongo.site_db.usernames.find({'rid': rid})
        if res1.count():
            username = res1[0]['username']
        else:
            username = humanhash.humanize(rid)

        if txn.get('relationship') and txn.get('dh_public_key') and txn.get('requester_rid') == rid:
            #friend request
            #if rid is the requester_rid, then we send a friend request notification to the requested_rid
            res = mongo.site_db.fcmtokens.find({"rid": txn['requested_rid']})
            for token in res:
                result = self.push_service.notify_single_device(
                    registration_id=token['token'],
                    message_title='%s sent you a friend request!' % username,
                    message_body="See the request and approve!",
                    extra_kwargs={'priority': 'high'}
                )

        elif txn.get('relationship') and txn.get('dh_public_key') and txn.get('requested_rid') == rid:
            #friend accept
            #if rid is the requested_rid, then we send a friend accepted notification to the requester_rid
            res = mongo.site_db.fcmtokens.find({"rid": txn['requester_rid']})
            for token in res:
                result = self.push_service.notify_single_device(
                    registration_id=token['token'],
                    message_title='%s approved your friend request!' % username,
                    message_body='Say "hi" to your friend!',
                    extra_kwargs={'priority': 'high'}
                )

        elif txn.get('relationship') and not txn.get('dh_public_key') and not txn.get('rid'):
            #post
            #we find all mutual friends of rid and send new post notifications to them
            rids = []
            rids.extend([x['requested_rid'] for x in BU().get_sent_friend_requests(rid)])
            rids.extend([x['requester_rid'] for x in BU().get_friend_requests(rid)])
            for friend_rid in rids:
                res = mongo.site_db.fcmtokens.find({"rid": friend_rid})
                used_tokens = []
                for token in res:
                    if token['token'] in used_tokens:
                        continue
                    used_tokens.append(token['token'])

                    result = self.push_service.notify_single_device(
                        registration_id=token['token'],
                        message_title='%s has posted something!' % username,
                        message_body='Check out what your friend posted!',
                        extra_kwargs={'priority': 'high'}
                    )

        elif txn.get('relationship') and not txn.get('dh_public_key') and txn.get('rid'):
            #message
            #we find the relationship of the transaction rid and send a new message notification to the rid
            #of the relationship that does not match the arg rid
            txns = [x for x in BU().get_transactions_by_rid(txn['rid'], config.bulletin_secret, rid=True, raw=True)]
            rids = []
            rids.extend([x['requested_rid'] for x in txns if 'requested_rid' in x and rid != x['requested_rid']])
            rids.extend([x['requester_rid'] for x in txns if 'requester_rid' in x and rid != x['requester_rid']])
            for friend_rid in rids:
                res = mongo.site_db.fcmtokens.find({"rid": friend_rid})
                used_tokens = []
                for token in res:
                    if token['token'] in used_tokens:
                        continue
                    used_tokens.append(token['token'])

                    result = self.push_service.notify_single_device(
                        registration_id=token['token'],
                        message_title='New message from %s!' % username,
                        message_body='Go see what your friend said!',
                        extra_kwargs={'priority': 'high'}
                    )
                    print(result)
Exemple #12
0
def humanize_filter(digest):
    return humanhash.humanize(str(digest), words=5)