Esempio n. 1
0
    def process_contract_image(self, image):
        uri = DataURI(image)
        imageData = uri.data
        #mime_type = uri.mimetype
        charset = uri.charset

        image = Image.open(StringIO(imageData))
        croppedImage = ImageOps.fit(image, (200, 200), centering=(0.5, 0.5))
        data = StringIO()
        croppedImage.save(data, format='PNG')
        new_uri = DataURI.make('image/png', charset=charset, base64=True, data=data.getvalue())
        data.close()

        return new_uri
Esempio n. 2
0
def addNewCover(series, updateDat):
    assert 'name' in updateDat
    assert 'file' in updateDat
    assert 'type' in updateDat

    data = DataURI(updateDat['file'])

    dathash = getHash(data.data).lower()
    have = Covers.query.filter(Covers.hash == dathash).scalar()
    if have:
        return getResponse(
            "A cover with that MD5 hash already exists! Are you accidentally adding a duplicate?",
            True)

    covpath = saveCoverFile(data.data, updateDat['name'])

    new = Covers(
        srcfname=updateDat['name'],
        series=series.id,
        description='',
        fspath=covpath,
        hash=dathash,
    )

    db.session.add(new)
    db.session.commit()
Esempio n. 3
0
def video():  
    if request.method == 'GET':
        response = make_response()
    
        result = authomatic.login(WerkzeugAdapter(request, response), 'tw')
        if result:
            if result.user:
                result.user.update()
                file_name = ''
                return render_template('video2.html', result=result,file_name=file_name)
        
        return response

    else:
        #post endpoint for saving the video
        data_url = request.form['data_url']
        epoch = str(int(time.time()*100))
        file_name = '%s.webm'%epoch

        video_file = open(os.path.join(app.config['UPLOAD_FOLDER'], file_name), 'wb')
        # video_file.write(data_url)

        uri = DataURI(data_url)

        video_file.write(uri.data)
        return render_template('video2.html',file_name=file_name)
Esempio n. 4
0
    def post(self, prob_id):
        # Requests a solution be graded
        # Body should contain: source code, output
        # Verify valid prob_id
        # Check permit, return error if expired
        # Dispatch to judge, return True or False based on accepted or not
        if not contest.is_running():
            raise web.HTTPError(503)
        if prob_id not in contest_cfg['prob_ids']:
            raise web.HTTPError(404)

        user_id = self.current_user_id()

        try:
            lang = self.get_argument('lang')[:32]
            filename = self.get_argument('filename')[:32]
            source = DataURI(self.get_argument('sourceFile')).data
        except:
            raise web.HTTPError(400)

        logger.info('%s requests judgement for a submission (%s, %s, %s)' %
                    (self.current_user_pretty(), filename, lang, prob_id))
        result, err = judge.enqueue_submission(user_id, prob_id, lang,
                                               filename, source)
        logger.info('Submission successfully added to judge queue'
                    if result else 'Failed to add to judge queue')
        self.set_header('Content-Type', 'application/json')
        self.write(json.dumps((result, err)))
Esempio n. 5
0
    def save_product(self, msg):
        #self._log.debug("Saving product: %s" % msg)

        msg['market_id'] = self._market_id


        product_id = msg['id'] if msg.has_key("id") else ""

        if product_id == "":
            product_id = random.randint(0, 1000000)

        if not msg.has_key("productPrice") or not msg['productPrice'] > 0:
            msg['productPrice'] = 0

        if not msg.has_key("productQuantity") or not msg['productQuantity'] > 0:
            msg['productQuantity'] = 1


        if msg.has_key('productImageData'):

            uri = DataURI(msg['productImageData'])
            imageData = uri.data
            mime_type = uri.mimetype
            charset = uri.charset

            image = Image.open(StringIO(imageData))
            croppedImage = ImageOps.fit(image, (100, 100), centering=(0.5, 0.5))
            data = StringIO()
            croppedImage.save(data, format='PNG')


            new_uri = DataURI.make('image/png', charset=charset, base64=True, data=data.getvalue())
            data.close()
            msg['productImageData'] = new_uri


        ''' Create product contract here and send to the network

        '''


        # Save product listing to DHT
        listing = json.dumps(msg)
        listing_key = hashlib.sha1(listing).hexdigest()

        hash_value = hashlib.new('ripemd160')
        hash_value.update(listing_key)
        listing_key = hash_value.hexdigest()

        msg['key'] = listing_key

        self._db.products.update({'id':product_id}, {'$set':msg}, True)

        self._log.debug('New Listing Key: %s' % listing_key)

        # Store listing
        self._transport._dht.iterativeStore(self._transport, listing_key, listing, self._transport._guid)

        self.update_listings_index()
Esempio n. 6
0
def lazy(content, id):
    if content == 'avatar':
        try:
            user = User.get(User.id == id)
        except DoesNotExist:
            abort(406)
        else:
            return base64.decodebytes(str.encode(DataURI(user.avatar).data))
    elif content == 'post':
        try:
            post = Post.get(Post.id == id)
        except DoesNotExist:
            abort(404)
        else:
            if post.image:
                return base64.decodebytes(str.encode(DataURI(post.image).data))
    else:
        abort(404)
Esempio n. 7
0
    def process_contract_image(image):
        uri = DataURI(image)
        imageData = uri.data
        # mime_type = uri.mimetype
        charset = uri.charset

        image = Image.open(StringIO(imageData))
        croppedImage = ImageOps.fit(image, (200, 200), centering=(0.5, 0.5))
        data = StringIO()
        croppedImage.save(data, format="PNG")
        new_uri = DataURI.make("image/png", charset=charset, base64=True, data=data.getvalue())
        data.close()

        return new_uri
Esempio n. 8
0
    def process_contract_image(image):
        """Get image from web client for use on server side"""
        uri = DataURI(image)
        imageData = uri.data
        # mime_type = uri.mimetype
        charset = uri.charset

        image = Image.open(StringIO(imageData))
        croppedImage = ImageOps.fit(image, (200, 200), centering=(0.5, 0.5))
        data = StringIO()
        croppedImage.save(data, format='PNG')
        new_uri = DataURI.make(
            'image/png',
            charset=charset,
            base64=True,
            data=data.getvalue())
        data.close()

        return new_uri
Esempio n. 9
0
    def save_contract(self, msg):

        contract_id = random.randint(0, 1000000)

        # Initialize default values if not set
        # if not msg.has_key("unit_price") or not msg['unit_price'] > 0:
        #     msg['unit_price'] = 0
        # if not msg.has_key("shipping_price") or not msg['shipping_price'] > 0:
        #     msg['shipping_price'] = 0
        # if not msg.has_key("item_quantity_available") or not msg['item_quantity_available'] > 0:
        #     msg['item_quantity_available'] = 1

        # Load gpg
        gpg = gnupg.GPG()

        # Insert PGP Key
        self.settings = self._db.selectEntries("settings", {"market_id":self._market_id})[0]

        self._log.debug('Settings %s' % self._transport.settings)
        msg['Seller']['seller_PGP'] = gpg.export_keys(self._transport.settings['PGPPubkeyFingerprint'], secret="P@ssw0rd")
        msg['Seller']['seller_BTC_uncompressed_pubkey'] = self._transport.settings['pubkey']
        msg['Seller']['seller_GUID'] = self._transport._guid

        # Process and crop thumbs for images
        if msg['Contract'].has_key('item_images'):
            if msg['Contract']['item_images'].has_key('image1'):

                img = msg['Contract']['item_images']['image1']

                uri = DataURI(img)
                imageData = uri.data
                mime_type = uri.mimetype
                charset = uri.charset

                image = Image.open(StringIO(imageData))
                croppedImage = ImageOps.fit(image, (200, 200), centering=(0.5, 0.5))
                data = StringIO()
                croppedImage.save(data, format='PNG')

                new_uri = DataURI.make('image/png', charset=charset, base64=True, data=data.getvalue())

                data.close()

                msg['Contract']['item_images'] = new_uri

        # TODO: replace default passphrase
        json_string = json.dumps(msg, indent=0)
        seg_len = 52
        out_text = string.join(map(lambda x : json_string[x:x+seg_len],
           range(0, len(json_string), seg_len)), "\n")
        signed_data = gpg.sign(out_text, passphrase='P@ssw0rd', keyid=self.settings.get('PGPPubkeyFingerprint'))

        # Save contract to DHT
        contract_key = hashlib.sha1(str(signed_data)).hexdigest()

        hash_value = hashlib.new('ripemd160')
        hash_value.update(contract_key)
        contract_key = hash_value.hexdigest()

        self._db.insertEntry("contracts", {"id": contract_id, "market_id": self._transport._market_id, "contract_body": json.dumps(msg), "signed_contract_body": str(signed_data), "state": "seed", "key": contract_key})

        self._log.debug('New Contract Key: %s' % contract_key)

        # Store listing
        self._transport._dht.iterativeStore(self._transport, contract_key, str(signed_data), self._transport._guid)

        self.update_listings_index()

        # If keywords store them in the keyword index
        keywords = msg['Contract']['item_keywords']
        self._log.info('Keywords: %s' % keywords)
        for keyword in keywords:

            hash_value = hashlib.new('ripemd160')
            hash_value.update('keyword-%s' % keyword)
            keyword_key = hash_value.hexdigest()

            self._transport._dht.iterativeStore(self._transport, keyword_key, json.dumps({'keyword_index_add':contract_key}), self._transport._guid)
Esempio n. 10
0
    def save_contract(self, msg):

        contract_id = random.randint(0, 1000000)

        # Initialize default values if not set
        # if not msg.has_key("unit_price") or not msg['unit_price'] > 0:
        #     msg['unit_price'] = 0
        # if not msg.has_key("shipping_price") or not msg['shipping_price'] > 0:
        #     msg['shipping_price'] = 0
        # if not msg.has_key("item_quantity_available") or not msg['item_quantity_available'] > 0:
        #     msg['item_quantity_available'] = 1

        # Load gpg
        gpg = gnupg.GPG(gnupghome='gpg')

        # Insert PGP Key
        self.settings = self._db.settings.find_one({'id':"%s" % self._market_id})

        self._log.debug('Settings %s' % self._transport.settings)
        msg['Seller']['seller_PGP'] = gpg.export_keys(self._transport.settings['PGPPubkeyFingerprint'], secret="P@ssw0rd")

        # Process and crop thumbs for images
        self._log.debug('Msg: %s' % msg)
        if msg['Contract'].has_key('item_images'):
            if msg['Contract']['item_images'].has_key('image1'):
                print 'multiple images'

                img = msg['Contract']['item_images']['image1']

                uri = DataURI(img)
                imageData = uri.data
                mime_type = uri.mimetype
                charset = uri.charset

                image = Image.open(StringIO(imageData))
                croppedImage = ImageOps.fit(image, (100, 100), centering=(0.5, 0.5))
                data = StringIO()
                croppedImage.save(data, format='PNG')

                new_uri = DataURI.make('image/png', charset=charset, base64=True, data=data.getvalue())
                data.close()

                # Break up line for signing with gnupg




                msg['Contract']['item_images'] = new_uri

        # TODO: replace default passphrase
        json_string = json.dumps(msg, indent=0)
        seg_len = 52
        out_text = string.join(map(lambda x : json_string[x:x+seg_len],
           range(0, len(json_string), seg_len)), "\n")
        signed_data = gpg.sign(out_text, passphrase='P@ssw0rd', keyid=self.settings.get('PGPPubkeyFingerprint'))

        # Save contract to DHT
        contract_key = hashlib.sha1(str(signed_data)).hexdigest()

        hash_value = hashlib.new('ripemd160')
        hash_value.update(contract_key)
        contract_key = hash_value.hexdigest()

        self._db.contracts.update({'id':contract_id}, {'$set':{'market_id':self._transport._market_id, 'contract_body':json.dumps(msg), 'signed_contract_body':str(signed_data), 'state':'seed', 'key':contract_key}}, True)

        self._log.debug('New Contract Key: %s' % contract_key)

        # Store listing
        self._transport._dht.iterativeStore(self._transport, contract_key, str(signed_data), self._transport._guid)

        self.update_listings_index()
Esempio n. 11
0
    def save_contract(self, msg):

        contract_id = random.randint(0, 1000000)

        # Initialize default values if not set
        # if not msg.has_key("unit_price") or not msg['unit_price'] > 0:
        #     msg['unit_price'] = 0
        # if not msg.has_key("shipping_price") or not msg['shipping_price'] > 0:
        #     msg['shipping_price'] = 0
        # if not msg.has_key("item_quantity_available") or not msg['item_quantity_available'] > 0:
        #     msg['item_quantity_available'] = 1

        # Load gpg
        gpg = gnupg.GPG()

        # Insert PGP Key
        self.settings = self._db.selectEntries(
            "settings", {"market_id": self._market_id})[0]

        self._log.debug('Settings %s' % self._transport.settings)
        msg['Seller']['seller_PGP'] = gpg.export_keys(
            self._transport.settings['PGPPubkeyFingerprint'],
            secret="P@ssw0rd")
        msg['Seller'][
            'seller_BTC_uncompressed_pubkey'] = self._transport.settings[
                'pubkey']
        msg['Seller']['seller_GUID'] = self._transport._guid

        # Process and crop thumbs for images
        if msg['Contract'].has_key('item_images'):
            if msg['Contract']['item_images'].has_key('image1'):

                img = msg['Contract']['item_images']['image1']

                uri = DataURI(img)
                imageData = uri.data
                mime_type = uri.mimetype
                charset = uri.charset

                image = Image.open(StringIO(imageData))
                croppedImage = ImageOps.fit(image, (200, 200),
                                            centering=(0.5, 0.5))
                data = StringIO()
                croppedImage.save(data, format='PNG')

                new_uri = DataURI.make('image/png',
                                       charset=charset,
                                       base64=True,
                                       data=data.getvalue())

                data.close()

                msg['Contract']['item_images'] = new_uri

        # TODO: replace default passphrase
        json_string = json.dumps(msg, indent=0)
        seg_len = 52
        out_text = string.join(
            map(lambda x: json_string[x:x + seg_len],
                range(0, len(json_string), seg_len)), "\n")
        signed_data = gpg.sign(out_text,
                               passphrase='P@ssw0rd',
                               keyid=self.settings.get('PGPPubkeyFingerprint'))

        # Save contract to DHT
        contract_key = hashlib.sha1(str(signed_data)).hexdigest()

        hash_value = hashlib.new('ripemd160')
        hash_value.update(contract_key)
        contract_key = hash_value.hexdigest()

        self._db.insertEntry(
            "contracts", {
                "id": contract_id,
                "market_id": self._transport._market_id,
                "contract_body": json.dumps(msg),
                "signed_contract_body": str(signed_data),
                "state": "seed",
                "key": contract_key
            })

        self._log.debug('New Contract Key: %s' % contract_key)

        # Store listing
        self._transport._dht.iterativeStore(self._transport, contract_key,
                                            str(signed_data),
                                            self._transport._guid)

        self.update_listings_index()

        # If keywords store them in the keyword index
        keywords = msg['Contract']['item_keywords']
        self._log.info('Keywords: %s' % keywords)
        for keyword in keywords:

            hash_value = hashlib.new('ripemd160')
            hash_value.update('keyword-%s' % keyword)
            keyword_key = hash_value.hexdigest()

            self._transport._dht.iterativeStore(
                self._transport, keyword_key,
                json.dumps({'keyword_index_add': contract_key}),
                self._transport._guid)