Esempio n. 1
0
    async def drawme(self, ctx, *, set):
        """Generate a drawing of yourself.
           140% accurately drawn

           Acceptable set options/arguments : any, set1, set2, set3, set4"""
        channel = ctx.message.channel
        hash = ctx.message.author.id
        drawed = PATH + "generated-" + hash + ".png"
        sets = ['any', 'set1', 'set2', 'set3', 'set4']
        if not Robo:
            await self.bot.say(
                "Robohash is not installed. Install it using `pip3 install robohash`"
            )
        else:
            pass
        if set not in sets:
            await self.bot.say(
                "Incorrect options!\nAcceptable options are : any, set1, set2, set3, or set4"
            )
        else:
            x = Rh(hash)
            x.assemble(roboset=set)
            with open(PATH + "generated-" + hash + ".png", "wb") as f:
                x.img.save(f, format="png")
            a = await self.bot.say("Drawing...")
            await asyncio.sleep(2)
            b = await self.bot.say(rnd(comments))
            await self.bot.delete_message(a)
            await asyncio.sleep(1)
            await self.bot.delete_message(b)
            await asyncio.sleep(1)
            await self.bot.send_file(channel, drawed)
Esempio n. 2
0
def GetRobot(hash=None, set='set1', background=None):
    # if no hash is passed in
    if hash == None:
        length = 20
        letters = string.ascii_lowercase
        hash = ''.join(random.choice(letters) for i in range(length))

    # create Robohash object
    rh = Robohash(hash)

    # assemble robot from parameters
    rh.assemble(roboset=set, bgset=background, sizex=500, sizey=500)

    # open/create image
    with open(os.path.join(sys.path[0], 'Robot.png'), 'wb') as f:
        # save robot image
        rh.img.save(f, format="png")

    #create robot message
    if set == 'set1':
        robotMessage = "**beep boop**"
    if set == 'set2':
        robotMessage = "**aarooo**"
    if set == 'set3':
        robotMessage = "**beep boop**"
    if set == 'set4':
        robotMessage = "**meow**"
    if set == 'set5':
        robotMessage = "**ayaya**"

    # return filename
    return 'Robot.png', robotMessage
Esempio n. 3
0
def user_avatar(request, user_id):
    rh = Robohash(user_id)
    rh.assemble(roboset="set4", bgset="bg2")  # 🐱
    avatar = io.BytesIO()
    rh.img.save(avatar, format="PNG")
    avatar.seek(0)
    return HttpResponse(avatar, content_type="image/png")
Esempio n. 4
0
    def do_GET(self):
        # Set default values
        sizex = 300
        sizey = 300
        format = "png"
        bgset = None
        color = None

        parsed_path = urllib.parse.urlparse(self.path)
        args = urllib.parse.parse_qs(parsed_path.query)

        address = args.get('address').pop()

        # Ensure we have something to hash!
        if address is None:
            address = self.request.remote_ip

        # Split the size variable in to sizex and sizey
        if "size" in args:
            sizex, sizey = args.get('size').pop().split("x")
            sizex = int(sizex)
            sizey = int(sizey)
            if sizex > 4096 or sizex < 0:
                sizex = 300
            if sizey > 4096 or sizey < 0:
                sizey = 300

        # Create our Robohashing object
        r = Robohash(address)

        # Build our Robot.
        r.assemble(roboset='set1',
                   format=format,
                   bgset=bgset,
                   color=color,
                   sizex=sizex,
                   sizey=sizey)

        self.send_response(200)

        # We're going to be returning the image directly, so tell the browser to expect a binary.
        self.send_header("Content-Type", "image/" + format)
        self.send_header("Cache-Control", "public,max-age=31536000")
        self.end_headers()

        # Print the Robot to the handler, as a file-like obj
        if r.format != 'datauri':
            r.img.save(self.wfile, format=format)
        else:
            # Or, if requested, base64 encode first.
            fakefile = io.BytesIO()
            r.img.save(fakefile, format='PNG')
            fakefile.seek(0)
            b64ver = base64.b64encode(fakefile.read())
            b64ver = b64ver.decode('utf-8')
            self.wfile.write("data:image/png;base64," + str(b64ver))

        return
Esempio n. 5
0
    def _find_image(self, kode):
        path = os.path.join(self.imgdir, kode + '.png')

        if not os.path.isfile(path):
            rh = Robohash(kode)
            rh.assemble(roboset='set4')
            rh.img.save(path, 'png')

        return path
Esempio n. 6
0
def robohash(request, hash_string, set_number):
    robohash = Robohash(hash_string)
    robohash.assemble(roboset='set%d' % (set_number, ))
    response = HttpResponse(content_type='image/png')
    robohash.img.save(response, format='PNG')
    patch_cache_control(response,
                        public=True,
                        max_age=365 * 24 * 60 * 60,
                        immutable=True)
    return response
Esempio n. 7
0
def robo_hash(request, slug):
    set = request.GET.get('set', None)
    rh = Robohash(slug)
    rh.assemble(roboset="set" + set)
    try:
        print("TRY")
        image_data = open("icons/" + slug + ".png", "rb").read()
    except:
        print("except")
        with open("icons/" + slug + ".png", "wb") as f:
            rh.img.save(f, format="png")
        image_data = open("icons/" + slug + ".png", "rb").read()
    return HttpResponse(image_data, content_type="image/png")
Esempio n. 8
0
    def _create(cls, model_class, *args, **kwargs):
        image = model_class.objects.create(*args, **kwargs)

        name = uuid.uuid4().hex
        robohash = Robohash(name)
        roboset = robohash.sets[0]
        robohash.assemble(roboset=roboset)

        with NamedTemporaryFile() as f:
            robohash.img.convert('RGB').save(f, format='jpeg')
            f.seek(0)
            image.file.save(name, f)

        return image
Esempio n. 9
0
    def _create(cls, model_class, *args, **kwargs):
        image = model_class.objects.create(*args, **kwargs)

        name = uuid.uuid4().hex
        robohash = Robohash(name)
        roboset = robohash.sets[0]
        robohash.assemble(roboset=roboset)

        with NamedTemporaryFile() as f:
            robohash.img.convert('RGB').save(f, format='jpeg')
            f.seek(0)
            image.file.save(name, f)

        return image
Esempio n. 10
0
 def create_profile_icon(self, username, is_male):
     rh = Robohash(username)
     if is_male:
         set = '1'
     else:
         set = '4'
     rh.assemble(roboset="set" + set)
     image_url = "media/profiles-icon/" + username + ".png"
     try:
         image_data = open(image_url, "rb").read()
     except:
         with open(image_url, "wb") as icon:
             rh.img.save(icon, format="png")
     final_url = "profiles-icon/" + username + ".png"
     return final_url
Esempio n. 11
0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument("-s", "--set", default="set1")
  parser.add_argument("-x", "--width", type=int, default=300)
  parser.add_argument("-y", "--height", type=int, default=300)
  parser.add_argument("-f", "--format", default="png")
  parser.add_argument("-b", "--bgset")
  parser.add_argument("-o", "--output", default="robohash.png")
  parser.add_argument("text", help="Text to use for the hash")
  
  args = parser.parse_args()
  
  robohash = Robohash(args.text)
  robohash.assemble(roboset=args.set, bgset=args.bgset,
  					sizex=args.width, sizey=args.height)
  
  robohash.img.save(args.output, format=args.format)
Esempio n. 12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-s", "--set", default="set1")
    parser.add_argument("-x", "--width", type=int, default=300)
    parser.add_argument("-y", "--height", type=int, default=300)
    parser.add_argument("-f", "--format", default="png")
    parser.add_argument("-b", "--bgset")
    parser.add_argument("-o", "--output", default="robohash.png")
    parser.add_argument("text", help="Text to use for the hash")

    args = parser.parse_args()

    robohash = Robohash(args.text)
    robohash.assemble(roboset=args.set,
                      bgset=args.bgset,
                      sizex=args.width,
                      sizey=args.height)

    robohash.img.save(args.output, format=args.format)
Esempio n. 13
0
    def handle(self, *args, **options):
        profile_queryset = Profile.objects.filter(user__username__startswith=options['username_prefix'])
        self.stdout.write("Attaching robot avatars to {} profiles...".format(profile_queryset.count()))

        for count, profile in enumerate(profile_queryset):
            name = "{}.jpg".format(profile.user.username)
            robohash = Robohash(name)
            roboset = robohash.sets[0]
            robohash.assemble(roboset=roboset)

            with NamedTemporaryFile() as f:
                robohash.img.convert('RGB').save(f, format='jpeg')
                f.seek(0)
                profile.image.save(name, f)
            profile.save(update_image=True)

            if count % 10 == 0:
                self.stdout.write("Updated {} profiles...".format(count))

        self.stdout.write("Done updating profiles!")
Esempio n. 14
0
from robohash import Robohash
from test import Test
from vms import VMs
from positions import Positions

app = Flask(__name__)

# The handler classes for each route type
about = About()
help = Help()
events = Events()
index = Index()
inventory = Inventory()
people = People()
requests_ = Requests_()
robohash = Robohash()
test = Test()
vms = VMs()
presentations = Presentations()
positions = Positions()

# parsed config from config.ini
config = globals.config


# Two helper functions to save typing
def encode_id(id):
    id = globals.base58_hashids.encode(id)
    if id == None: return None
    return id
Esempio n. 15
0
    def get(self, string=None):
        """
        The ImageHandler is our tornado class for creating a robot.
        called as Robohash.org/$1, where $1 becomes the seed string for the Robohash obj
        """

        # Ensure we have something to hash!
        if string is None:
            string = self.request.remote_ip

        # Set default values
        imageFormat = self.get_argument('format', 'png', True).upper()
        sizex, sizey = self.getImageSize()

        # Allow Gravatar lookups -
        # This allows people to pass in a gravatar-style hash, and return their gravatar image, instead of a Robohash.
        # This is often used for example, to show a Gravatar if it's set for an email, or a Robohash if not.
        gravatar = self.get_argument('gravatar', '').lower()
        if gravatar:
            if gravatar == 'yes':
                # They have requested that we hash the email, and send it to Gravatar.
                gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(
                    string.lower().encode('utf-8')).hexdigest() + "?"
                gravatar_url += urlencode({'size': str(sizey)})
            elif gravatar == 'hashed':
                # They have sent us a pre-hashed email address.
                gravatar_url = "https://secure.gravatar.com/avatar/" + string + "?"
                gravatar_url += urlencode({'size': str(sizey)})

            # If we do want a gravatar, request one. If we can't get it, just keep going, and return a robohash
            if gravatar in ['hashed', 'yes']:
                try:
                    print(gravatar_url)
                    f = urlopen(gravatar_url)
                    self.redirect(gravatar_url, permanent=False)
                    return
                except Exception as e:
                    print(e)

        # Detect if the user has passed in a flag to ignore extensions.
        # Pass this along to to Robohash obj later on.
        # ignoreext = self.get_argument('ignoreext', 'false', True).lower() == 'true'

        # Create our Robohashing object
        r = Robohash(string)

        # Get image set
        roboset = None
        imageSet = self.getImageSet()
        if not imageSet:
            roboset = r.sets[0]
        if imageSet in r.sets:
            roboset = imageSet
        elif imageSet == 'any':
            # Add ugly hack.
            # Adding cats and people per submitted/requested code, but I don't want to change existing hashes for set=any
            # so we'll ignore those sets for the 'any' config.
            roboset = r.sets[r.hasharray[1] % (len(r.sets) - 2)]
        else:
            self.set_status(404)
            self.set_header("Content-Type", "application/json")
            self.write(
                '{"status":"error","error":"Not Found", "message": "set=' +
                imageSet + ' not found."}')
            return

        # Allow them to set a background, or keep as None
        bgset = self.get_argument('bgset', None, True)
        if bgset:
            if str != type(bgset):
                bgset = bgset.decode('utf-8')
            elif bgset not in r.bgsets + ['any']:
                self.set_status(404)
                self.set_header("Content-Type", "application/json")
                self.write(
                    '{"status":"error","error":"Not Found", "message": "bgset='
                    + bgset + ' not found."}')
                return

        # We're going to be returning the image directly, so tell the browser to expect a binary.
        self.set_header("Content-Type", "image/" + imageFormat)
        self.set_header("Cache-Control", "public,max-age=31536000")

        # Build our Robot.
        r.assemble(roboset=roboset,
                   format=imageFormat,
                   bgset=bgset,
                   sizex=sizex,
                   sizey=sizey)

        # # Print the Robot to the handler, as a file-like obj
        if r.format != 'datauri':
            r.img.save(self, format=r.format)
        else:
            # Or, if requested, base64 encode first.
            fakefile = io.BytesIO()
            r.img.save(fakefile, format='PNG')
            fakefile.seek(0)
            b64ver = base64.b64encode(fakefile.read())
            b64ver = b64ver.decode('utf-8')
            self.write("data:image/png;base64," + str(b64ver))
Esempio n. 16
0
def localgetinfo():
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    lncli = " getinfo"
    lsd = os.popen(lndconnectload['ln'] + lncli).read()
    lsd0 = str(lsd)
    d = json.loads(lsd0)
    hash = d['identity_pubkey']
    rh = Robohash(hash)
    rh.assemble(roboset='set1')
    if not os.path.isfile(str(hash + ".png")):
        with open(hash + ".png", "wb") as f:
            rh.img.save(f, format="png")

        img_path = open(hash + ".png", "rb")
        img = Image.open(img_path)

        h = 20
        w = int((img.width / img.height) * 50)

        img = img.resize((w, h), Image.ANTIALIAS)
        img_arr = np.asarray(img)
        h, w, c = img_arr.shape

    img_path = open(hash + ".png", "rb")
    img = Image.open(img_path)

    h = 20
    w = int((img.width / img.height) * 50)

    img = img.resize((w, h), Image.ANTIALIAS)
    img_arr = np.asarray(img)
    h, w, c = img_arr.shape

    for x in range(h):
        for y in range(w):
            pix = img_arr[x][y]
            print(get_color(pix[0], pix[1], pix[2]), sep='', end='')
        print()
    print(
        "\n----------------------------------------------------------------------------------------------------"
    )
    print("""
    \tNODE INFORMATION

    Version: {}
    Node ID: {}
    Alias: {}
    Color: {}
    Pending Channels: {}
    Active Channels: {}
    Inactive Channels: {}
    Peers: {}
    URLS: {}
    """.format(d['version'], d['identity_pubkey'], d['alias'], d['color'],
               d['num_pending_channels'], d['num_active_channels'],
               d['num_inactive_channels'], d['num_peers'], d['uris']))
    print("\033[1;30;47m")
    qr.add_data(d['identity_pubkey'])
    qr.print_ascii()
    print("\033[0;37;40m")
    qr.clear()
    print(
        "----------------------------------------------------------------------------------------------------\n"
    )
    input("\nContinue... ")
import uuid
from robohash import Robohash

# generate 24 robots (one to be used for each team)
for i in range(1, 51):
    hash = str(uuid.uuid4())
    rh = Robohash(hash)
    rh.assemble(roboset='set1', sizex=80, sizey=80)

    filename = 'robots/robot-{}.png'.format(i)
    print(filename)
    with open(filename, "wb") as f:
        rh.img.save(f, format="png")
Esempio n. 18
0
def getinfo():
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    cert_path = lndconnectload["tls"]
    macaroon = codecs.encode(
        open(lndconnectload["macaroon"], 'rb').read(), 'hex')
    headers = {'Grpc-Metadata-macaroon': macaroon}
    url = 'https://{}/v1/getinfo'.format(lndconnectload["ip_port"])
    r = requests.get(url, headers=headers, verify=cert_path)
    a = r.json()
    hash = a['identity_pubkey']
    rh = Robohash(hash)
    rh.assemble(roboset='set1')
    if not os.path.isfile(str(hash + ".png")):
        with open(hash + ".png", "wb") as f:
            rh.img.save(f, format="png")

        img_path = open(hash + ".png", "rb")
        img = Image.open(img_path)

        h = 20
        w = int((img.width / img.height) * 50)

        img = img.resize((w, h), Image.ANTIALIAS)
        img_arr = np.asarray(img)
        h, w, c = img_arr.shape

    img_path = open(hash + ".png", "rb")
    img = Image.open(img_path)

    h = 20
    w = int((img.width / img.height) * 50)

    img = img.resize((w, h), Image.ANTIALIAS)
    img_arr = np.asarray(img)
    h, w, c = img_arr.shape

    for x in range(h):
        for y in range(w):
            pix = img_arr[x][y]
            print(get_color(pix[0], pix[1], pix[2]), sep='', end='')
        print()
    print(
        "\n----------------------------------------------------------------------------------------------------"
    )
    print("""
    \t NODE INFORMATION
    Version: {}
    Node ID: {}
    Alias: {}
    Color: {}
    Pending Channels: {}
    Active Channels: {}
    Inactive Channels: {}
    Peers: {}
    URLS: {}
    """.format(a['version'], a['identity_pubkey'], a['alias'], a['color'],
               a['num_pending_channels'], a['num_active_channels'],
               a['num_inactive_channels'], a['num_peers'], a['uris']))
    print("\033[1;30;47m")
    qr.add_data(a['identity_pubkey'])
    qr.print_ascii()
    print("\033[0;37;40m")
    qr.clear()
    print(
        "----------------------------------------------------------------------------------------------------\n"
    )
    input("\nContinue... ")
Esempio n. 19
0
def channels():
    cert_path = lndconnectload["tls"]
    macaroon = codecs.encode(
        open(lndconnectload["macaroon"], 'rb').read(), 'hex')
    headers = {'Grpc-Metadata-macaroon': macaroon}
    url = 'https://{}/v1/channels'.format(lndconnectload["ip_port"])
    r = requests.get(url, headers=headers, verify=cert_path)
    a = r.json()
    n = a['channels']
    while True:
        clear()
        print("\033[1;32;40m")
        blogo()
        print("\033[0;37;40m")
        print("<<< Back to the Main Menu Press Control + C.\n\n")
        print("\t\nChannels\n")
        try:
            print("\n\tLIST CHANNELS\n")
            for r in range(len(n)):
                s = n[r]
                hash = s['remote_pubkey']
                rh = Robohash(hash)
                rh.assemble(roboset='set1')
                if not os.path.isfile(str(hash + ".png")):
                    with open(hash + ".png", "wb") as f:
                        rh.img.save(f, format="png")

                    img_path = open(hash + ".png", "rb")
                    img = Image.open(img_path)

                    h = 1
                    w = int((img.width / img.height) * 5)

                    img = img.resize((w, h), Image.ANTIALIAS)
                    img_arr = np.asarray(img)
                    h, w, c = img_arr.shape

                img_path = open(hash + ".png", "rb")
                img = Image.open(img_path)

                h = 1
                w = int((img.width / img.height) * 5)

                img = img.resize((w, h), Image.ANTIALIAS)
                img_arr = np.asarray(img)
                h, w, c = img_arr.shape

                for x in range(h):
                    for y in range(w):
                        pix = img_arr[x][y]
                        print(get_color(pix[0], pix[1], pix[2]),
                              sep='',
                              end='')
                    print()
                print("Node ID: " + s['remote_pubkey'])

            nd = input("\nSelect a Node ID: ")
            for item in n:
                s = item
                nn = s['remote_pubkey']
                if nd == nn:
                    hash = s['remote_pubkey']
                    rh = Robohash(hash)
                    rh.assemble(roboset='set1')

                    img_path = open(hash + ".png", "rb")
                    img = Image.open(img_path)

                    h = 20
                    w = int((img.width / img.height) * 50)

                    img = img.resize((w, h), Image.ANTIALIAS)
                    img_arr = np.asarray(img)
                    h, w, c = img_arr.shape

                    for x in range(h):
                        for y in range(w):
                            pix = img_arr[x][y]
                            print(get_color(pix[0], pix[1], pix[2]),
                                  sep='',
                                  end='')
                        print()
                    print(
                        "\n----------------------------------------------------------------------------------------------------"
                    )
                    print("""
                    \tCHANNEL DECODED
                    Active: {}
                    Node ID: {}
                    Channel Point: {}
                    Channel Capacity: {} sats
                    Local Balance: {} sats
                    Remote Balance: {} sats
                    Total Sent: {} sats
                    Total Received: {} sats
                    """.format(s['active'], s['remote_pubkey'],
                               s['channel_point'], s['capacity'],
                               s['local_balance'], s['remote_balance'],
                               s['total_satoshis_sent'],
                               s['total_satoshis_received']))
                    print(
                        "----------------------------------------------------------------------------------------------------\n"
                    )

            input("\nContinue... ")
        except:
            break
Esempio n. 20
0
    def get(self, request, *args, **kwargs):  # pylint: disable=too-many-branches,too-many-statements,too-many-locals,too-many-return-statements
        '''
        Override get from parent class
        '''
        model = ConfirmedEmail
        size = get_size(request)
        imgformat = 'png'
        obj = None
        default = None
        forcedefault = False
        gravatarredirect = False
        gravatarproxy = True
        uri = request.build_absolute_uri()

        # Check the cache first
        if CACHE_RESPONSE:
            centry = caches['filesystem'].get(uri)
            if centry:
                # For DEBUG purpose only print('Cached entry for %s' % uri)
                return HttpResponse(
                    centry['content'], 
                    content_type=centry['content_type'], 
                    status=centry['status'], 
                    reason = centry['reason'], 
                    charset = centry['charset'])

        # In case no digest at all is provided, return to home page
        if not 'digest' in kwargs:
            return HttpResponseRedirect(reverse_lazy('home'))

        if 'd' in request.GET:
            default = request.GET['d']
        if 'default' in request.GET:
            default = request.GET['default']

        if 'f' in request.GET:
            if request.GET['f'] == 'y':
                forcedefault = True
        if 'forcedefault' in request.GET:
            if request.GET['forcedefault'] == 'y':
                forcedefault = True

        if 'gravatarredirect' in request.GET:
            if request.GET['gravatarredirect'] == 'y':
                gravatarredirect = True

        if 'gravatarproxy' in request.GET:
            if request.GET['gravatarproxy'] == 'n':
                gravatarproxy = False

        try:
            obj = model.objects.get(digest=kwargs['digest'])
        except ObjectDoesNotExist:
            try:
                obj = model.objects.get(digest_sha256=kwargs['digest'])
            except ObjectDoesNotExist:
                model = ConfirmedOpenId
                try:
                    d = kwargs['digest']
                    # OpenID is tricky. http vs. https, versus trailing slash or not
                    # However, some users eventually have added their variations already
                    # and therfore we need to use filter() and first()
                    obj = model.objects.filter(
                        Q(digest=d) |
                        Q(alt_digest1=d) |
                        Q(alt_digest2=d) |
                        Q(alt_digest3=d)).first()
                except:
                    pass


        # If that mail/openid doesn't exist, or has no photo linked to it
        if not obj or not obj.photo or forcedefault:
            gravatar_url = 'https://secure.gravatar.com/avatar/' + kwargs['digest'] \
                + '?s=%i' % size

            # If we have redirection to Gravatar enabled, this overrides all
            # default= settings, except forcedefault!
            if gravatarredirect and not forcedefault:
                return HttpResponseRedirect(gravatar_url)

            # Request to proxy Gravatar image - only if not forcedefault
            if gravatarproxy and not forcedefault:
                url = reverse_lazy('gravatarproxy', args=[kwargs['digest']]) \
                    + '?s=%i' % size + '&default=%s' % default
                return HttpResponseRedirect(url)

            # Return the default URL, as specified, or 404 Not Found, if default=404
            if default:
                # Proxy to gravatar to generate wavatar - lazy me
                if str(default) == 'wavatar':
                    url = reverse_lazy('gravatarproxy', args=[kwargs['digest']]) \
                        + '?s=%i' % size + '&default=%s&f=y' % default
                    return HttpResponseRedirect(url)

                if str(default) == str(404):
                    return HttpResponseNotFound(_('<h1>Image not found</h1>'))

                if str(default) == 'monsterid':
                    monsterdata = BuildMonster(seed=kwargs['digest'], size=(size, size))
                    data = BytesIO()
                    monsterdata.save(data, 'PNG', quality=JPEG_QUALITY)
                    data.seek(0)
                    response = CachingHttpResponse(
                        uri,
                        data,
                        content_type='image/png')
                    response['Cache-Control'] = 'max-age=%i' % CACHE_IMAGES_MAX_AGE
                    return response

                if str(default) == 'robohash':
                    roboset = 'any'
                    if request.GET.get('robohash'):
                        roboset = request.GET.get('robohash')
                    robohash = Robohash(kwargs['digest'])
                    robohash.assemble(roboset=roboset, sizex=size, sizey=size)
                    data = BytesIO()
                    robohash.img.save(data, format='png')
                    data.seek(0)
                    response = CachingHttpResponse(
                        uri,
                        data,
                        content_type='image/png')
                    response['Cache-Control'] = 'max-age=%i' % CACHE_IMAGES_MAX_AGE
                    return response

                if str(default) == 'retro':
                    identicon = Identicon.render(kwargs['digest'])
                    data = BytesIO()
                    img = Image.open(BytesIO(identicon))
                    img = img.resize((size, size), Image.ANTIALIAS)
                    img.save(data, 'PNG', quality=JPEG_QUALITY)
                    data.seek(0)
                    response =  CachingHttpResponse(
                        uri,
                        data,
                        content_type='image/png')
                    response['Cache-Control'] = 'max-age=%i' % CACHE_IMAGES_MAX_AGE
                    return response

                if str(default) == 'pagan':
                    paganobj = pagan.Avatar(kwargs['digest'])
                    data = BytesIO()
                    img = paganobj.img.resize((size, size), Image.ANTIALIAS)
                    img.save(data, 'PNG', quality=JPEG_QUALITY)
                    data.seek(0)
                    response = CachingHttpResponse(
                        uri,
                        data,
                        content_type='image/png')
                    response['Cache-Control'] = 'max-age=%i' % CACHE_IMAGES_MAX_AGE
                    return response

                if str(default) == 'identicon':
                    p = Pydenticon5()
                    # In order to make use of the whole 32 bytes digest, we need to redigest them.
                    newdigest = hashlib.md5(bytes(kwargs['digest'], 'utf-8')).hexdigest()
                    img = p.draw(newdigest, size, 0)
                    data = BytesIO()
                    img.save(data, 'PNG', quality=JPEG_QUALITY)
                    data.seek(0)
                    response = CachingHttpResponse(
                        uri,
                        data,
                        content_type='image/png')
                    response['Cache-Control'] = 'max-age=%i' % CACHE_IMAGES_MAX_AGE
                    return response

                if str(default) == 'mm' or str(default) == 'mp':
                    # If mm is explicitly given, we need to catch that
                    static_img = path.join('static', 'img', 'mm', '%s%s' % (str(size), '.png'))
                    if not path.isfile(static_img):
                        # We trust this exists!!!
                        static_img = path.join('static', 'img', 'mm', '512.png')
                    # We trust static/ is mapped to /static/
                    return HttpResponseRedirect('/' + static_img)
                return HttpResponseRedirect(default)

            static_img = path.join('static', 'img', 'nobody', '%s%s' % (str(size), '.png'))
            if not path.isfile(static_img):
                # We trust this exists!!!
                static_img = path.join('static', 'img', 'nobody', '512.png')
            # We trust static/ is mapped to /static/
            return HttpResponseRedirect('/' + static_img)

        imgformat = obj.photo.format
        photodata = Image.open(BytesIO(obj.photo.data))
        # If the image is smaller than what was requested, we need
        # to use the function resize
        if photodata.size[0] < size or photodata.size[1] < size:
            photodata = photodata.resize((size, size), Image.ANTIALIAS)
        else:
            photodata.thumbnail((size, size), Image.ANTIALIAS)
        data = BytesIO()
        photodata.save(data, pil_format(imgformat), quality=JPEG_QUALITY)
        data.seek(0)
        obj.photo.access_count += 1
        obj.photo.save()
        obj.access_count += 1
        obj.save()
        if imgformat == 'jpg':
            imgformat = 'jpeg'
        response = CachingHttpResponse(
            uri,
            data,
            content_type='image/%s' % imgformat)
        response['Cache-Control'] = 'max-age=%i' % CACHE_IMAGES_MAX_AGE
        return response
Esempio n. 21
0
def locallistpeersQQ():
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    while True:
        clear()
        print("\033[1;32;40m")
        blogo()
        print("\033[0;37;40m")
        print("<<< Back to the Main Menu Press Control + C.\n\n")
        lncli = " listpeers"
        lsd = os.popen(lndconnectload['ln'] + lncli).read()
        lsd0 = str(lsd)
        d = json.loads(lsd0)
        n = d['peers']
        try:
            print("\n\tLIST PEERS\n")
            for item_ in n:
                s = item_
                hash = s['pub_key']
                rh = Robohash(hash)
                rh.assemble(roboset='set1')
                if not os.path.isfile(str(hash + ".png")):
                    with open(hash + ".png", "wb") as f:
                        rh.img.save(f, format="png")

                    img_path = open(hash + ".png", "rb")
                    img = Image.open(img_path)

                    h = 1
                    w = int((img.width / img.height) * 5)

                    img = img.resize((w, h), Image.ANTIALIAS)
                    img_arr = np.asarray(img)
                    h, w, c = img_arr.shape

                img_path = open(hash + ".png", "rb")
                img = Image.open(img_path)

                h = 1
                w = int((img.width / img.height) * 5)

                img = img.resize((w, h), Image.ANTIALIAS)
                img_arr = np.asarray(img)
                h, w, c = img_arr.shape

                for x in range(h):
                    for y in range(w):
                        pix = img_arr[x][y]
                        print(get_color(pix[0], pix[1], pix[2]),
                              sep='',
                              end='')
                    print()
                print("PubKey: " + s['pub_key'] + " @" + s['address'])

            nd = input("\nSelect PubKey: ")
            for item in n:
                s = item
                nn = s['pub_key']
                if nd == nn:
                    hash = s['pub_key']
                    rh = Robohash(hash)
                    rh.assemble(roboset='set1')

                    img_path = open(hash + ".png", "rb")
                    img = Image.open(img_path)

                    h = 20
                    w = int((img.width / img.height) * 50)

                    img = img.resize((w, h), Image.ANTIALIAS)
                    img_arr = np.asarray(img)
                    h, w, c = img_arr.shape

                    for x in range(h):
                        for y in range(w):
                            pix = img_arr[x][y]
                            print(get_color(pix[0], pix[1], pix[2]),
                                  sep='',
                                  end='')
                        print()
                    print(
                        "\n----------------------------------------------------------------------------------------------------"
                    )
                    print("""
                        PEER DECODED\n
                        Bytes Sent: {}
                        Bytes Recv: {}
                        Sat Sent: {} sats
                        Sat Recv: {} sats
                    """.format(s['bytes_sent'], s['bytes_recv'], s['sat_sent'],
                               s['sat_recv']))
                    print(
                        "-----------------------------------------------------------------------------------------------------\n"
                    )
                    print("\n\tPeer: " + nd)
                    print("\033[1;30;47m")
                    qr.add_data(s['pub_key'])
                    qr.print_ascii()
                    print("\033[0;37;40m")
                    qr.clear()

            pp = input("\nDo you want to disconnect? Y/n: ")
            if pp in ["Y", "y"]:
                lncli = " disconnect"
                lsd = os.popen(lndconnectload['ln'] + lncli + " " + nd).read()
                lsd0 = str(lsd)
                d = json.loads(lsd0)
                print("\n\tDisconnected from peer " + nd)
                input("\nContinue... ")
            elif pp in ["N", "n"]:
                input("\nContinue... ")
        except:
            break
Esempio n. 22
0
    def get(self,string=None):


        # Set default values
        sizex = 300
        sizey = 300
        format = "png"
        bgset = None
        color = None

        # Normally, we pass in arguments with standard HTTP GET variables, such as
        # ?set=any and &size=100x100
        #
        # Some sites don't like this though.. They cache it weirdly, or they just don't allow GET queries.
        # Rather than trying to fix the intercows, we can support this with directories... <grumble>
        # We'll translate /abc.png/s_100x100/set_any to be /abc.png?set=any&s=100x100
        # We're using underscore as a replacement for = and / as a replacement for [&?]

        args = self.request.arguments.copy()

        for k in list(args.keys()):
            v = args[k]
            if type(v) is list:
                if len(v) > 0:
                    args[k] = args[k][0]
                else:
                    args[k] = ""

        # Detect if they're using the above slash-separated parameters..
        # If they are, then remove those parameters from the query string.
        # If not, don't remove anything.
        split = string.split('/')
        if len(split) > 1:
            for st in split:
                b = st.split('_')
                if len(b) == 2:
                    if b[0] in ['gravatar','ignoreext','size','set','bgset','color']:
                        args[b[0]] = b[1]
                        string = re.sub("/" + st,'',string)

        # Ensure we have something to hash!
        if string is None:
                string = self.request.remote_ip


        # Detect if the user has passed in a flag to ignore extensions.
        # Pass this along to to Robohash obj later on.

        ignoreext = args.get('ignoreext','false').lower() == 'true'

        # Split the size variable in to sizex and sizey
        if "size" in args:
                sizex,sizey = args['size'].split("x")
                sizex = int(sizex)
                sizey = int(sizey)
                if sizex > 4096 or sizex < 0:
                    sizex = 300
                if sizey > 4096 or sizey < 0:
                    sizey = 300

        # Allow Gravatar lookups -
        # This allows people to pass in a gravatar-style hash, and return their gravatar image, instead of a Robohash.
        # This is often used for example, to show a Gravatar if it's set for an email, or a Robohash if not.
        if args.get('gravatar','').lower() == 'yes':
            # They have requested that we hash the email, and send it to Gravatar.
            default = "404"
            gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(string.lower()).hexdigest() + "?"
            gravatar_url += urlencode({'default':default, 'size':str(sizey)})
        elif args.get('gravatar','').lower() == 'hashed':
            # They have sent us a pre-hashed email address.
            default = "404"
            gravatar_url = "https://secure.gravatar.com/avatar/" + string + "?"
            gravatar_url += urlencode({'default':default, 'size':str(sizey)})

        # If we do want a gravatar, request one. If we can't get it, just keep going, and return a robohash
        if args.get('gravatar','').lower() in ['hashed','yes']:
            try:
                f = urlopen(gravatar_url)
                self.redirect(gravatar_url, permanent=False)
                return
            except:
                args['avatar'] = False

        # Create our Robohashing object
        r = Robohash(string)


        # Allow users to manually specify a robot 'set' that they like.
        # Ensure that this is one of the allowed choices, or allow all
        # If they don't set one, take the first entry from sets above.

        if args.get('set',r.sets[0]) in r.sets:
            roboset = args.get('set',r.sets[0])
        elif args.get('set',r.sets[0]) == 'any':
            # Add ugly hack.

            # Adding cats and people per submitted/requested code, but I don't want to change existing hashes for set=any
            # so we'll ignore those sets for the 'any' config.
            roboset = r.sets[r.hasharray[1] % (len(r.sets)-2) ]
        else:
            roboset = r.sets[0]

        # If they specified multiple sets, use up a bit of randomness to choose one.
        # If they didn't specify one, default to whatever we decided above.

        possiblesets = []
        for tmpset in args.get('sets',roboset).split(','):
            if tmpset in r.sets:
                possiblesets.append(tmpset)
        if possiblesets:
            roboset = possiblesets[r.hasharray[1] % len(possiblesets) ]


        # Only set1 is setup to be color-seletable. The others don't have enough pieces in various colors.
        # This could/should probably be expanded at some point..
        # Right now, this feature is almost never used. ( It was < 44 requests this year, out of 78M reqs )

        if args.get('color') in r.colors:
            roboset = 'set1'
            color = args.get('color')

        # If they DID choose set1, randomly choose a color.
        if roboset == 'set1' and color is None:
            color = r.colors[r.hasharray[0] % len(r.colors) ]
            roboset = 'set1'

        # Allow them to set a background, or keep as None
        if args.get('bgset') in r.bgsets + ['any']:
            bgset = args.get('bgset')

        # We're going to be returning the image directly, so tell the browser to expect a binary.
        self.set_header("Content-Type", "image/" + format)
        self.set_header("Cache-Control", "public,max-age=31536000")

        # Build our Robot.
        r.assemble(roboset=roboset,format=format,bgset=bgset,color=color,sizex=sizex,sizey=sizey)

        # Print the Robot to the handler, as a file-like obj
        if r.format != 'datauri':
            r.img.save(self,format=r.format)
        else:
            # Or, if requested, base64 encode first.
            fakefile = io.BytesIO()
            r.img.save(fakefile,format='PNG')
            fakefile.seek(0)
            b64ver = base64.b64encode(fakefile.read())
            b64ver = b64ver.decode('utf-8')
            self.write("data:image/png;base64," + str(b64ver))
Esempio n. 23
0
    def get(self, string=None):

        # Set default values
        sizex = 300
        sizey = 300
        format = "png"
        bgset = None
        color = None

        # Normally, we pass in arguments with standard HTTP GET variables, such as
        # ?set=any and &size=100x100
        #
        # Some sites don't like this though.. They cache it weirdly, or they just don't allow GET queries.
        # Rather than trying to fix the intercows, we can support this with directories... <grumble>
        # We'll translate /abc.png/s_100x100/set_any to be /abc.png?set=any&s=100x100
        # We're using underscore as a replacement for = and / as a replacement for [&?]

        args = self.request.arguments.copy()

        for k in list(args.keys()):
            v = args[k]
            if type(v) is list:
                if len(v) > 0:
                    args[k] = args[k][0]
                else:
                    args[k] = ""

        # Detect if they're using the above slash-separated parameters..
        # If they are, then remove those parameters from the query string.
        # If not, don't remove anything.
        split = string.split('/')
        if len(split) > 1:
            for st in split:
                b = st.split('_')
                if len(b) == 2:
                    if b[0] in [
                            'gravatar', 'ignoreext', 'size', 'set', 'bgset',
                            'color'
                    ]:
                        args[b[0]] = b[1]
                        string = re.sub("/" + st, '', string)

        # Ensure we have something to hash!
        if string is None:
            string = self.request.remote_ip

        # Detect if the user has passed in a flag to ignore extensions.
        # Pass this along to to Robohash obj later on.

        ignoreext = args.get('ignoreext', 'false').lower() == 'true'

        # Split the size variable in to sizex and sizey
        if "size" in args:
            sizex, sizey = args['size'].split("x")
            sizex = int(sizex)
            sizey = int(sizey)
            if sizex > 4096 or sizex < 0:
                sizex = 300
            if sizey > 4096 or sizey < 0:
                sizey = 300

        # Allow Gravatar lookups -
        # This allows people to pass in a gravatar-style hash, and return their gravatar image, instead of a Robohash.
        # This is often used for example, to show a Gravatar if it's set for an email, or a Robohash if not.
        if args.get('gravatar', '').lower() == 'yes':
            # They have requested that we hash the email, and send it to Gravatar.
            default = "404"
            gravatar_url = "https://secure.gravatar.com/avatar/" + hashlib.md5(
                string.lower()).hexdigest() + "?"
            gravatar_url += urlencode({'default': default, 'size': str(sizey)})
        elif args.get('gravatar', '').lower() == 'hashed':
            # They have sent us a pre-hashed email address.
            default = "404"
            gravatar_url = "https://secure.gravatar.com/avatar/" + string + "?"
            gravatar_url += urlencode({'default': default, 'size': str(sizey)})

        # If we do want a gravatar, request one. If we can't get it, just keep going, and return a robohash
        if args.get('gravatar', '').lower() in ['hashed', 'yes']:
            try:
                f = urlopen(gravatar_url)
                self.redirect(gravatar_url, permanent=False)
                return
            except:
                args['avatar'] = False

        # Create our Robohashing object
        r = Robohash(string)

        # Allow users to manually specify a robot 'set' that they like.
        # Ensure that this is one of the allowed choices, or allow all
        # If they don't set one, take the first entry from sets above.

        if args.get('set', r.sets[0]) in r.sets:
            roboset = args.get('set', r.sets[0])
        elif args.get('set', r.sets[0]) == 'any':
            # Add ugly hack.
            # Adding cats, per issue-17, but I don't want to change existing hashes.
            # so we'll ignore that set for the 'any' config.

            roboset = r.sets[r.hasharray[1] % (len(r.sets) - 1)]
        else:
            roboset = r.sets[0]

        # If they specified multiple sets, use up a bit of randomness to choose one.
        # If they didn't specify one, default to whatever we decided above.

        possiblesets = []
        for tmpset in args.get('sets', roboset).split(','):
            if tmpset in r.sets:
                possiblesets.append(tmpset)
        if possiblesets:
            roboset = possiblesets[r.hasharray[1] % len(possiblesets)]

        # Only set1 is setup to be color-seletable. The others don't have enough pieces in various colors.
        # This could/should probably be expanded at some point..
        # Right now, this feature is almost never used. ( It was < 44 requests this year, out of 78M reqs )

        if args.get('color') in r.colors:
            roboset = 'set1'
            color = args.get('color')

        # If they DID choose set1, randomly choose a color.
        if roboset == 'set1' and color is None:
            color = r.colors[r.hasharray[0] % len(r.colors)]
            roboset = 'set1'

        # Allow them to set a background, or keep as None
        if args.get('bgset') in r.bgsets + ['any']:
            bgset = args.get('bgset')

        # We're going to be returning the image directly, so tell the browser to expect a binary.
        self.set_header("Content-Type", "image/" + format)
        self.set_header("Cache-Control", "public,max-age=31536000")

        # Build our Robot.
        r.assemble(roboset=roboset,
                   format=format,
                   bgset=bgset,
                   color=color,
                   sizex=sizex,
                   sizey=sizey)

        # Print the Robot to the handler, as a file-like obj
        if r.format != 'datauri':
            r.img.save(self, format=r.format)
        else:
            # Or, if requested, base64 encode first.
            fakefile = io.BytesIO()
            r.img.save(fakefile, format='PNG')
            fakefile.seek(0)
            b64ver = base64.b64encode(fakefile.read())
            b64ver = b64ver.decode('utf-8')
            self.write("data:image/png;base64," + str(b64ver))
Esempio n. 24
0
def locallistchannels():
    lncli = " listchannels"
    lsd = os.popen(lndconnectload['ln'] + lncli).read()
    lsd0 = str(lsd)
    d = json.loads(lsd0)
    n = d['channels']
    while True:
        clear()
        print("\033[1;32;40m")
        blogo()
        print("\033[0;37;40m")
        print("<<< Back to the Main Menu Press Control + C.\n\n")
        print("\t\nChannels\n")
        try:
            print("\n\tLIST CHANNELS\n")
            for item_ in n:
                s = item_
                hash = s['remote_pubkey']
                rh = Robohash(hash)
                rh.assemble(roboset='set1')
                if not os.path.isfile(str(hash + ".png")):
                    with open(hash + ".png", "wb") as f:
                        rh.img.save(f, format="png")

                    img_path = open(hash + ".png", "rb")
                    img = Image.open(img_path)

                    h = 1
                    w = int((img.width / img.height) * 5)

                    img = img.resize((w, h), Image.ANTIALIAS)
                    img_arr = np.asarray(img)
                    h, w, c = img_arr.shape

                img_path = open(hash + ".png", "rb")
                img = Image.open(img_path)

                h = 1
                w = int((img.width / img.height) * 5)

                img = img.resize((w, h), Image.ANTIALIAS)
                img_arr = np.asarray(img)
                h, w, c = img_arr.shape

                for x in range(h):
                    for y in range(w):
                        pix = img_arr[x][y]
                        print(get_color(pix[0], pix[1], pix[2]),
                              sep='',
                              end='')
                    print()
                print("Node ID: " + s['remote_pubkey'])

            nd = input("\nSelect a Node ID: ")
            for item in n:
                s = item
                nn = s['remote_pubkey']
                if nd == nn:
                    hash = s['remote_pubkey']
                    rh = Robohash(hash)
                    rh.assemble(roboset='set1')

                    img_path = open(hash + ".png", "rb")
                    img = Image.open(img_path)

                    h = 20
                    w = int((img.width / img.height) * 50)

                    img = img.resize((w, h), Image.ANTIALIAS)
                    img_arr = np.asarray(img)
                    h, w, c = img_arr.shape

                    for x in range(h):
                        for y in range(w):
                            pix = img_arr[x][y]
                            print(get_color(pix[0], pix[1], pix[2]),
                                  sep='',
                                  end='')
                        print()
                    print(
                        "\n----------------------------------------------------------------------------------------------------"
                    )
                    print("""
                    \tCHANNEL DECODED
                    Active: {}
                    Node ID: {}
                    Channel Point: {}
                    Channel Capacity: {} sats
                    Local Balance: {} sats
                    Remote Balance: {} sats
                    Total Sent: {} sats
                    Total Received: {} sats
                    """.format(s['active'], s['remote_pubkey'],
                               s['channel_point'], s['capacity'],
                               s['local_balance'], s['remote_balance'],
                               s['total_satoshis_sent'],
                               s['total_satoshis_received']))
                    print(
                        "----------------------------------------------------------------------------------------------------\n"
                    )

            input("\nContinue... ")
        except:
            break