コード例 #1
0
ファイル: test.py プロジェクト: habibah-adam/fuel_app
 def test_getStations(self):
     ah = ApiHandler()
     result1 = ah.get_stations("2194")
     result2 = ah.get_stations("830000")
     self.assertIsInstance(result1, list, msg="result is not list.")
     self.assertEqual(result2, [],
                      msg="for wrong postcode should return empty list.")
コード例 #2
0
ファイル: test.py プロジェクト: habibah-adam/fuel_app
 def test_accessToken(self):
     ah = ApiHandler()
     result = ah.get_accessToken()
     self.assertIsInstance(result, str, msg="not valid access token.")
     self.assertEqual(len(result),
                      28,
                      msg="access token length is not equal to 28.")
コード例 #3
0
 def __init__(self, version):
     self.path = os.getcwd()
     self.version = version
     self.parser = create_parser(self.version)
     uuid_v4 = str(uuid.uuid4())
     self.args = vars(self.parser.parse_args())
     self.debug = self.args.get("debug")
     self.tcp_handler = TcpHandler(uuid_v4, self.args.get("debug"))
     self.api_handler = ApiHandler(uuid_v4)
コード例 #4
0
    def __init__(
        self,
        identity: str,
        start_port: int,
        transport_protocol: str,
        endpoint: str,
        ledger_url: str,
        local_ip: str,
        wallet_name: str,
        wallet_key: str,
        seed: str = "random",
        public_did: bool = True,
        auto_response: bool = False,
    ):
        # Construct docker container object to maintain a running container
        self.docker_container = Container(
            identity=identity,
            endpoint=endpoint,
            seed=seed,
            indbound_transport_port=start_port,
            outbound_transport_port=start_port + 1,
            transport_protocol=transport_protocol,
            wallet_name=wallet_name,
            wallet_key=wallet_key,
            webhook_url=
            f"{transport_protocol}://{local_ip}:{start_port+2}/webhooks",  #TODO:
            genesis_url=f"{ledger_url}/genesis")

        # Construct Api Handler object that handles all Api calls
        self.api_handler = ApiHandler(  # TODO: Ledger transport protocol toevoegen
            api_url=local_ip,
            port=start_port + 1)

        # Construct a webhook server object that handles incoming messages
        self.webhook_server = WebhookServer(
            identity=identity,
            webhook_ip=local_ip,
            webhook_protocol=transport_protocol,
            webhook_port=start_port + 2,
            api_handler=self.api_handler
        )  # TODO: webhook IP is not per definitie gelijk aan ledger ip

        self.identity = identity
        self.start_port = start_port
        self.ledger_url = ledger_url
        self.local_ip = local_ip
        self.seed = seed
        self.public_did = public_did
        self.auto_response = auto_response
        # TODO: Register DID weghalen en verplaatsen naar api handler
        self.client_session = ClientSession()
        self.transport_protocol = transport_protocol

        # TODO: random seed ja?
        rand_name = str(random.randint(100_000, 999_999))
        self.seed = (("my_seed_000000000000000000000000" +
                      rand_name)[-32:] if seed == "random" else seed)
コード例 #5
0
ファイル: test.py プロジェクト: habibah-adam/fuel_app
    def test_postCode(self):
        ah = ApiHandler()
        result = ah.get_postcode("liverpool")
        self.assertTrue(result.isnumeric(), msg="postcode is not numeric.")
        self.assertEqual(len(result),
                         4,
                         msg="postcode length is not equal to 4.")

        result = ah.get_postcode("urumqi")
        self.assertIsNone(result, msg="for wrong suburb should return None.")
コード例 #6
0
class ParkingService(Base):
    def __init__(self):
        super(ParkingService, self).__init__()
        self._api_handler = ApiHandler()
        self._content_handler = ContentHandler()
        # db_handler is public for testing purpose
        self.db_handler = DateBaseHandler()

    # TODO: implement functionality for multiple images
    def check_plate(self, image_name):
        response = self._api_handler.post_by_file_name(image_name)
        text = self._content_handler.get_parsed_text(response)

        is_allowed = not self._is_transport_with_no_letters(text) and \
            not self._is_public_transport(text) and \
            not self._is_military_transport(text)

        self._store_result(text, is_allowed)
        self.debug_info('Plate', text)
        self._print_result(is_allowed)

        # Returning text and status for testing purpose
        return [text, is_allowed]

    def set_wrong_api_url(self):
        """
        For testing purpose ONLY
        """
        self._api_handler = ApiHandler(
            api_url='https://api.ocr.space/parse/imageasd')

    def _is_public_transport(self, text):
        last_symbol = text[-1]
        return last_symbol == 'G' or last_symbol == '6'

    def _is_military_transport(self, text):
        return 'L' in text or 'M' in text

    def _is_transport_with_no_letters(self, text):
        return text.isdecimal()

    def _store_result(self, plate, is_allowed):
        if is_allowed:
            status = 'allowed'
        else:
            status = 'rejected'
        self.db_handler.store_plate_info(plate, status)

    def _print_result(self, is_allowed):
        if is_allowed:
            print('You may park here')
            return

        print('YOU SHALL NOT PASS')
コード例 #7
0
ファイル: main.py プロジェクト: habibah-adam/fuel_app
def ask_region():
    '''
    User Input:
        Either NSW Suburb name or Postcode (Delivery Area)
    Returns:
        Postal Code of NSW Delivery Area
    Example: 2000, 2170
    '''
    # Create ApiHandler Class instance
    # This class handles all API calls and data collections
    api = ApiHandler()
    print("This app will find petrol stations around you")
    print("based on the 'suburb' or 'postcode' provided.\n")
    print("press 'q' to quit.\n")

    user_input = input('Please Enter your Postcode or Suburb: (q to exit)\n')
    while True:
        clear()
        if user_input.lower() == 'q':
            print('Thanks for using this app, Bye!')
            sys.exit()
        if user_input.isnumeric():
            if postcode_exists(user_input):
                return user_input
            else:
                print(
                    'Entered Postcode is not valid NSW Delivery Area Postal Code'
                )
                print(
                    'Please make sure the postcode is a valid postcode (e.g.: starts with 2 and 4 digit long)'
                )
        else:
            postcode = api.get_postcode(user_input)
            if postcode:
                return postcode
            else:
                print(
                    "The system cannot match the entered suburb to a valid NSW postal code."
                )
                print("Please enter valided or nearby adjacent suburbs...")
        user_input = input('Please Enter Postcode or Suburb: \n')
コード例 #8
0
ファイル: test.py プロジェクト: habibah-adam/fuel_app
 def test_fuelName(self):
     ah = ApiHandler()
     fuel_names = [
         "Unleaded 91", "Ethanol 94", "Premium 95", "Premium 98", "Diesel"
     ]
     result1 = ah.get_fuel_name("E10")
     result2 = ah.get_fuel_name("U91")
     result3 = ah.get_fuel_name("DL")
     result4 = ah.get_fuel_name("P98")
     result5 = ah.get_fuel_name("P93")
     self.assertIn(result1,
                   fuel_names,
                   msg=f"{result1} not in {fuel_names}")
     self.assertIn(result2,
                   fuel_names,
                   msg=f"{result2} not in {fuel_names}")
     self.assertIn(result3,
                   fuel_names,
                   msg=f"{result3} not in {fuel_names}")
     self.assertIn(result4,
                   fuel_names,
                   msg=f"{result4} not in {fuel_names}")
     self.assertIsNone(result5, msg=f"{result5} is not None.")
コード例 #9
0
ファイル: main.py プロジェクト: habibah-adam/fuel_app
def stations_by_postcode():
    '''
    User need to provide Location (NSW Only):
     - Postcode (Delivery Area)
     - Suburb
    '''
    # Initiate API Handling Class
    api = ApiHandler()
    # Obtain User  input (location info)
    region = ask_region()
    # calling API stage
    # API call uses free account, hence the limit of API call per minute
    # if quoata is exceeded, Error will be thrown, catching it here
    try:
        ps = api.stations_with_fuel_types(region)
    except Exception as e:
        # Trying to wait for one more minute to see if the quoata limit is lifted.
        print(e)
        print("There has been an network issue, trying in a minute again...")
        print("Please be patient...")
        for i in range(1, 7):
            time.sleep(10)
            print(f'{i * 10} seconds elapsed...')
        try:
            # calling API again
            ps = api.stations_with_fuel_types(region)
        except Exception as e2:
            print(e2)
            print(
                "An unknow Network error occurred. The Data(API) privder is being now contacted for further troubleshoot."
            )
            print(
                "Sorry for any inconvenience, please try this app later again. Thanks!!!"
            )
            sys.exit()
    return ps
コード例 #10
0
class TitsaBot:
    CUSTOM_OR_DEFAULT, INSERT_CUSTOM, TRANVIA, BROADCAST_TEXT = range(4)

    def __init__(self):
        config = configparser.ConfigParser()
        config.read('bot_config.ini')

        bot_token = config.get("TELEGRAM", "token")

        titsa_idApp = config.get("TITSA", "idApp")

        self.adminId = config.get("ADMIN", "chatId")

        self.apiHandler = ApiHandler(titsa_idApp)

        self.dbHandler = DbHandler()

        self.transportThread = OpenTransitThread(
            "http://www.titsa.com/Google_transit.zip", 7 * 24 * 60 * 60)
        self.transportThread.start()

        updater = Updater(token=bot_token, use_context=True)
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.INFO)

        b1 = telegram.KeyboardButton("⭐ Consultar favorito ⭐")
        b2 = telegram.KeyboardButton("✖️ Borrar favorito ✖️")
        b3 = telegram.KeyboardButton("🚊 Tranvia de Tenerife 🚊")
        b4 = telegram.KeyboardButton("📍 Ver paradas cercanas 📍",
                                     request_location=True)
        self.keyboard = telegram.ReplyKeyboardMarkup([[b3, b4], [b1, b2]],
                                                     resize_keyboard=True)

        h1 = MessageHandler(Filters.regex(r"^.+Consultar favorito.+$"),
                            self.favKeyBoard)
        h2 = MessageHandler(Filters.regex(u"^\U0001F68F.+(\d{4})"),
                            self.replyToFav)
        h3 = MessageHandler(Filters.regex(r"^.+Borrar favorito.+$"),
                            self.favKeyBoard)
        h4 = MessageHandler(Filters.regex(u"^\u2716.+(\d{4})"), self.eraseFav)

        updater.dispatcher.add_handler(CommandHandler("start", self.start))
        updater.dispatcher.add_handler(
            MessageHandler(Filters.regex(r"^\d{4}$"), self.responder_a_codigo))
        updater.dispatcher.add_handler(h1)
        updater.dispatcher.add_handler(h2)
        updater.dispatcher.add_handler(h3)
        updater.dispatcher.add_handler(h4)

        updater.dispatcher.add_handler(
            ConversationHandler(
                entry_points=[
                    MessageHandler(Filters.regex(r"^.+Tranvia de Tenerife.+$"),
                                   self.listStops),
                ],
                states={
                    TitsaBot.TRANVIA:
                    [MessageHandler(Filters.all, self.queryTram)]
                },
                fallbacks=[]))

        updater.dispatcher.add_handler(
            MessageHandler(Filters.location, self.nearStops))

        updater.dispatcher.add_handler(
            ConversationHandler(
                entry_points=[
                    CommandHandler("broadcast", self.newBroadcast),
                ],
                states={
                    TitsaBot.BROADCAST_TEXT:
                    [MessageHandler(Filters.all, self.broadcast)]
                },
                fallbacks=[]))

        updater.dispatcher.add_handler(
            ConversationHandler(entry_points=[
                CommandHandler("addFav",
                               self.addFavCommand,
                               pass_args=True,
                               pass_user_data=True),
                CallbackQueryHandler(self.addFavQuery,
                                     pattern=r"^\d{4}$",
                                     pass_user_data=True)
            ],
                                states={
                                    TitsaBot.CUSTOM_OR_DEFAULT: [
                                        CallbackQueryHandler(
                                            self.setFavNameOption,
                                            pass_user_data=True)
                                    ],
                                    TitsaBot.INSERT_CUSTOM: [
                                        MessageHandler(Filters.text,
                                                       self.customName,
                                                       pass_user_data=True)
                                    ]
                                },
                                fallbacks=[h1, h2, h3, h4]))

        updater.dispatcher.add_handler(
            ConversationHandler(entry_points=[
                CallbackQueryHandler(self.reloadStationQuery,
                                     pattern=r"^Repetir \d{4}$",
                                     pass_user_data=True)
            ],
                                states={
                                    TitsaBot.CUSTOM_OR_DEFAULT: [
                                        CallbackQueryHandler(
                                            self.reloadStationQuery,
                                            pass_user_data=True)
                                    ]
                                },
                                fallbacks=[h1, h2, h3, h4]))

        updater.dispatcher.add_handler(
            CallbackQueryHandler(self.sendStopAndLocation,
                                 pattern=r"^Locate \d{4}$",
                                 pass_user_data=True))

        updater.start_polling()
        updater.idle()
        self.dbHandler.save()
        self.transportThread.stop()

    def build_minutes_text(self, status, bus=True):
        if status is not None:
            text = "🚏 *" + status.name + "* 🚏\n\n"
            sorted_lines = sorted(status.minutes.items(),
                                  key=lambda line: int(line[1][0]["minutes"]))
            print(sorted_lines)
            for linea, data in sorted_lines:
                for entry in data:
                    emoji = "🚊*" if not bus else "🚍*"
                    text += emoji + linea + "* (" + entry["dest"] + \
                            "): "+ entry["minutes"] + " minutos \n"

            return text, 1
        else:
            text = "⚠ Parada no encontrada o sin pasos registrados ⚠"
            return text, 0

    def start(self, update: Update, context: CallbackContext):
        context.bot.send_message(
            chat_id=update.message.chat_id,
            text=
            "Hola! Gracias por usarme! \nEnvíame el código de una parada :)",
            reply_markup=self.keyboard)

    def addFavCommand(self, update: Update, context: CallbackContext):
        return self.newFavMethod(update.message.from_user.id, context.args[0],
                                 context.bot, update.message.chat.id,
                                 context.user_data)

    def addFavQuery(self, update: Update, context: CallbackContext):
        return self.newFavMethod(update.callback_query.from_user.id,
                                 update.callback_query.data, context.bot,
                                 update.callback_query.message.chat.id,
                                 context.user_data)

    def reloadStationQuery(self, update: Update, context: CallbackContext):
        codeText = update.callback_query.data.replace("Repetir ", "")
        self.stationQuery(context.bot, update.callback_query.message.chat_id,
                          update.callback_query.from_user.id, codeText)

    def newFavMethod(self, user, station, bot, chat, user_data):
        if self.dbHandler.check_duplicate(user, station):
            bot.send_message(chat_id=chat,
                             text="Ya está en favoritos",
                             reply_markup=None)
            return -1
        else:
            logging.info(msg="New fav required user:%s id:%s" %
                         (user, station))
            stationName = StopsHandler.stationName(station)
            text = "Nombre: " + stationName + "\n¿Quiere usar otro?"
            b1 = telegram.InlineKeyboardButton(text="Sí", callback_data="si")
            b2 = telegram.InlineKeyboardButton(text="No", callback_data="no")
            b3 = telegram.InlineKeyboardButton(text="❌Cancelar",
                                               callback_data="cancel")
            bot.send_message(chat_id=chat,
                             text=text,
                             reply_markup=telegram.InlineKeyboardMarkup(
                                 [[b1, b2, b3]]))
            user_data["currentFavStationId"] = station
            user_data["currentFavStationName"] = stationName
            return TitsaBot.CUSTOM_OR_DEFAULT

    def responder_a_codigo(self, update: Update, context: CallbackContext):
        self.stationQuery(context.bot, update.message.chat_id,
                          update.message.from_user.id, update.message.text)

    def stationQuery(self, bot, chat_id, user_id, text):
        if not self.dbHandler.check_duplicate_user(chat_id):
            self.dbHandler.addUser(chat_id)
        logging.info(msg="Message %s" % (text))
        if text.isdigit() and len(text) == 4:
            texto = self.build_minutes_text(self.apiHandler.new_request(text),
                                            True)[0]
            button = telegram.InlineKeyboardButton(
                text="⭐ Añadir a favoritos ⭐", callback_data=text)
            buttonReload = telegram.InlineKeyboardButton(
                text="🔃 Repetir consulta 🔃", callback_data="Repetir " + text)
            if not self.dbHandler.check_duplicate(user_id, text):
                keyboard = telegram.InlineKeyboardMarkup([[button],
                                                          [buttonReload]])
            else:
                keyboard = telegram.InlineKeyboardMarkup([[buttonReload]])
            bot.send_message(chat_id=chat_id,
                             text=texto,
                             parse_mode=telegram.ParseMode.MARKDOWN,
                             reply_markup=keyboard)
        else:
            bot.send_message(chat_id=chat_id, text="Código inválido")

        bot.send_message(chat_id=chat_id,
                         text="Escribe el número de parada",
                         reply_markup=self.keyboard)

    def setFavNameOption(self, update: Update, context: CallbackContext):
        logging.info(
            msg="Answer for the fav question: user:%s reply:%s" %
            (update.callback_query.from_user.id, update.callback_query.data))
        if update.callback_query.data == "no":
            self.dbHandler.addUserFav(
                update.callback_query.from_user.id,
                context.user_data["currentFavStationId"],
                context.user_data["currentFavStationName"])
            text = "*Favorito añadido*\n" + context.user_data[
                "currentFavStationName"] + "(" + context.user_data[
                    "currentFavStationId"] + ")"
            context.bot.edit_message_text(
                text,
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id,
                reply_markup=None,
                parse_mode=telegram.ParseMode.MARKDOWN)
            context.bot.send_message(
                chat_id=update.callback_query.message.chat.id,
                text="Escribe el número de parada",
                reply_markup=self.keyboard)
            return -1
        elif update.callback_query.data == "si":
            context.bot.edit_message_text(
                "¿Qué nombre?",
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id,
                reply_markup=None)
            return TitsaBot.INSERT_CUSTOM
        else:
            context.bot.delete_message(
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id, None)
            context.user_data.pop("currentFavStationId", None)
            context.user_data.pop("currentFavStationName", None)
            context.bot.send_message(
                chat_id=update.callback_query.message.chat.id,
                text="Escribe el número de parada",
                reply_markup=self.keyboard)
            return -1

    def customName(self, update: Update, context: CallbackContext):
        logging.info(msg="Custom name: user:%s reply:%s" %
                     (update.message.from_user.id, update.message.text))
        self.dbHandler.addUserFav(update.message.from_user.id,
                                  context.user_data["currentFavStationId"],
                                  update.message.text)
        text = "*Favorito añadido*\n" + update.message.text + "(" + context.user_data[
            "currentFavStationId"] + ")"
        context.bot.send_message(update.message.chat.id,
                                 text=text,
                                 reply_markup=self.keyboard,
                                 parse_mode=telegram.ParseMode.MARKDOWN)
        return -1

    def listStops(self, update: Update, context: CallbackContext):
        if not self.dbHandler.check_duplicate_user(update.message.chat_id):
            self.dbHandler.addUser(update.message.chat_id)
        logging.info(msg="Listing tram stations")
        stations = self.apiHandler.tranvia_stations()
        if stations is not None and len(stations) > 0:
            buttons = []
            for station in stations.items():
                buttons.append([
                    telegram.KeyboardButton(u"🚋" + station[0] + " (" +
                                            station[1] + ")")
                ])
            context.bot.send_message(
                update.message.chat.id,
                text="Elige estación",
                reply_markup=telegram.ReplyKeyboardMarkup(buttons),
                resize_keyboard=True)
            return TitsaBot.TRANVIA
        return -1

    def queryTram(self, update: Update, context: CallbackContext):
        p = re.compile(u"^\U0001F68B.+(\w{3})")
        stop = p.search(update.message.text).group(1)
        status = self.apiHandler.tranvia_request(stop)
        texto = self.build_minutes_text(status, False)[0]
        context.bot.send_message(chat_id=update.message.chat_id,
                                 text=texto,
                                 parse_mode=telegram.ParseMode.MARKDOWN,
                                 reply_markup=self.keyboard)
        return -1

    def favKeyBoard(self, update: Update, context: CallbackContext):
        logging.info(msg="Fav request from user %s" %
                     (update.message.from_user.id))

        stations = self.dbHandler.getUserFavs(update.message.from_user.id)
        if len(stations) > 0:
            buttons = []
            emoji = u"🚏" if not "Borrar" in update.message.text else u"✖️"
            for station in stations:
                buttons.append([
                    telegram.KeyboardButton(emoji + station[1] + " (" +
                                            station[0] + ")")
                ])
            context.bot.send_message(
                update.message.chat.id,
                text="Elige estación",
                reply_markup=telegram.ReplyKeyboardMarkup(buttons),
                resize_keyboard=True)
        else:
            context.bot.send_message(update.message.chat.id,
                                     text="No tienes favoritos",
                                     reply_markup=self.keyboard,
                                     resize_keyboard=True)

    def replyToFav(self, update: Update, context: CallbackContext):
        p = re.compile(u"^\U0001F68F.+(\d{4})")
        code = p.search(update.message.text).group(1)
        update.message.text = code
        self.responder_a_codigo(update, context)

    def eraseFav(self, update: Update, context: CallbackContext):
        p = re.compile(u"^\u2716.+(\d{4})")
        code = p.search(update.message.text).group(1)
        self.dbHandler.deleteUserFav(update.message.from_user.id, code)
        context.bot.send_message(update.message.chat.id,
                                 text="Favorito eliminado",
                                 reply_markup=self.keyboard,
                                 resize_keyboard=True)

    def broadcast(self, update: Update, context: CallbackContext):
        logging.info(msg="Broadcasting message %s" % update.message.text)
        if (update.message.chat.id == int(self.adminId)):
            for user in self.dbHandler.getAllUsers():
                logging.info(msg="Broadcasted to %s" % (user))
                context.bot.send_message(str(user),
                                         text=update.message.text,
                                         reply_markup=self.keyboard,
                                         resize_keyboard=True)

        return -1

    def newBroadcast(self, update: Update, context: CallbackContext):
        return TitsaBot.BROADCAST_TEXT

    def nearStops(self, update: Update, context: CallbackContext):
        logging.info(msg="Nearest from user %s" %
                     (update.message.from_user.id))

        stations = StopsHandler.nearestStops(
            4, float(update.message.location.latitude),
            float(update.message.location.longitude))
        if stations is not None:
            buttons = []

            for station in stations:
                buttons.append([
                    telegram.InlineKeyboardButton(
                        text=f"{station.name} ({station.id})",
                        callback_data=f"Locate {station.id}")
                ])
            context.bot.send_message(
                update.message.chat.id,
                text="Estas son tus estaciones cercanas",
                reply_markup=telegram.InlineKeyboardMarkup(buttons))
        else:
            context.bot.send_message(update.message.chat.id,
                                     text="⚠ No hay información disponible ⚠",
                                     reply_markup=self.keyboard,
                                     resize_keyboard=True)

    def sendStopAndLocation(self, update: Update, context: CallbackContext):
        context.bot.answer_callback_query(update.callback_query.id)
        logging.info(msg="Requested from nearest( user %s)" %
                     (update.callback_query.message.chat_id))
        id = update.callback_query.data.replace("Locate ", "")
        location = StopsHandler.stopLocation(id)
        context.bot.send_location(update.callback_query.message.chat_id,
                                  latitude=location[0],
                                  longitude=location[1])

        self.stationQuery(context.bot, update.callback_query.message.chat_id,
                          update.callback_query.from_user.id, id)
コード例 #11
0
ファイル: wsgi.py プロジェクト: Godlux/home_gate
    data = request.json
    devices_info = api_handler.get_devices_info()
    return devices_info


# Static files
@app.route('/favicon.ico')
def send_favicon():
    return send_from_directory('static/ico/', "favicon.ico")


@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('static/js', path)


@app.route('/css/<path:path>')
def send_css(path):
    return send_from_directory('static/css', path)


if __name__ == '__main__':
    print("Initializing Devices...")
    api_handler = ApiHandler()
    api_handler.start()
    print("Devices Initialized.")
    app.run(debug=True,
            use_debugger=False,
            use_reloader=False,
            passthrough_errors=True)
コード例 #12
0
class Client:
    def __init__(self, version):
        self.path = os.getcwd()
        self.version = version
        self.parser = create_parser(self.version)
        uuid_v4 = str(uuid.uuid4())
        self.args = vars(self.parser.parse_args())
        self.debug = self.args.get("debug")
        self.tcp_handler = TcpHandler(uuid_v4, self.args.get("debug"))
        self.api_handler = ApiHandler(uuid_v4)

    def go_config(self):
        if self.args.get("set_token"):
            set_token_to_json_config(self.args.get("set_token"))
        elif self.args.get("set_default_namespace"):
            if not self.test_namespace(self.args.get("set_default_namespace")):
                return
            set_default_namespace_to_json_config(
                self.args.get("set_default_namespace"))
        else:
            show_namespace_token_from_config()

    @staticmethod
    def logout():
        set_token_to_json_config("")
        print("Bye!")

    def login(self):
        email_regex = r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
        is_valid = re.compile(email_regex)
        try:
            email = input('Enter your email: ')
        except KeyboardInterrupt:
            return
        if not is_valid.findall(email):
            print("Email is not valid")
            return
        try:
            pwd = getpass()
        except KeyboardInterrupt:
            return
        json_to_send = {
            "username": email,
            "password": md5((email + pwd).encode()).hexdigest()
        }
        if self.args.get("debug"):
            self.log_time()
        self.tcp_connect()
        api_result = self.api_handler.login(json_to_send)
        if 'ok' in api_result:
            set_token_to_json_config(api_result['token'])
        if not self.handle_api_result(api_result):
            return

        json_result = self.get_and_handle_tcp_result('post')
        self.tcp_handler.close()
        if not check_http_status(json_result, self.args.get("command")):
            return

    def go(self):
        self.check_file_existence()
        self.check_arguments()

        if self.args.get("kind") in ("deployments", "deploy", "deployment"):
            self.args["kind"] = "deployments"
        elif self.args.get("kind") in ("po", "pods", "pod"):
            self.args["kind"] = "pods"
        elif self.args.get("kind") in ("service", "services", "svc"):
            self.args["kind"] = "services"
        else:
            self.args["kind"] = "namespaces"

        if self.args['command'] == 'run':
            self.go_run()

        elif self.args['command'] == 'create':
            self.go_create()

        elif self.args['command'] == 'get':
            self.go_get()

        elif self.args['command'] == 'delete':
            self.go_delete()

        elif self.args['command'] == 'replace':
            self.go_replace()

        elif self.args['command'] == 'config':
            self.go_config()

        elif self.args['command'] == 'expose':
            self.go_expose()

        elif self.args['command'] == 'login':
            self.login()

        elif self.args['command'] == 'logout':
            self.logout()

        elif self.args['command'] == 'set':
            self.go_set()

        elif self.args['command'] == 'restart':
            self.go_restart()

        elif self.args['command'] == 'scale':
            self.go_scale()

    def go_restart(self):
        self.log_time()
        self.tcp_connect()

        namespace = self.args['namespace']
        if not namespace:
            namespace = config_json_data.get("default_namespace")
        api_result = self.api_handler.delete("deployments", self.args["name"],
                                             namespace, True)
        if not self.handle_api_result(api_result):
            return

        json_result = self.get_and_handle_tcp_result('restart')
        self.tcp_handler.close()
        if not check_http_status(json_result, self.args.get("command")):
            return

    def go_scale(self):
        if self.args.get("debug"):
            self.log_time()
        self.tcp_connect()

        namespace = self.args.get('namespace')
        if not namespace:
            namespace = config_json_data.get("default_namespace")

        count = self.args.get("count")
        try:
            replicas_count = int(count)
            json_to_send = {"replicas": replicas_count}
            api_result = self.api_handler.scale(json_to_send,
                                                self.args.get("name"),
                                                namespace)
        except (ValueError, TypeError):
            print('{}{}{} {}'.format(
                BColors.FAIL,
                "Error: ",
                "Count is not integer",
                BColors.ENDC,
            ))
            return
        if not self.handle_api_result(api_result):
            return

        json_result = self.get_and_handle_tcp_result('scale')
        self.tcp_handler.close()
        if not check_http_status(json_result, self.args.get("command")):
            return

    def go_set(self):
        if self.args.get("debug"):
            self.log_time()
        self.tcp_connect()

        namespace = self.args.get('namespace')
        if not namespace:
            namespace = config_json_data.get("default_namespace")

        args = self.args.get("args")
        if args:
            if '=' in args:
                container_name, image = args.split('=')
                json_to_send = {"name": self.args.get("name"), "image": image}
                api_result = self.api_handler.set(json_to_send, container_name,
                                                  namespace)
            else:
                try:
                    replicas_count = int(args)
                    json_to_send = {"replicas": replicas_count}
                    api_result = self.api_handler.set(json_to_send,
                                                      self.args.get("name"),
                                                      namespace)
                except (ValueError, TypeError):
                    print('{}{}{} {}'.format(
                        BColors.FAIL,
                        "Error: ",
                        "Count is not integer",
                        BColors.ENDC,
                    ))
                    return

            if not self.handle_api_result(api_result):
                return

            json_result = self.get_and_handle_tcp_result('set')
            self.tcp_handler.close()
            if not check_http_status(json_result, self.args.get("command")):
                return
        else:
            print('{}{}{} {}'.format(
                BColors.FAIL,
                "Error: ",
                "Empty args",
                BColors.ENDC,
            ))
            return

    def go_run(self):
        json_to_send = self.construct_run()
        if not json_to_send:
            return
        if self.debug:
            self.log_time()

        self.tcp_connect()
        namespace = self.args.get('namespace')
        if not namespace:
            namespace = config_json_data.get("default_namespace")
        api_result = self.api_handler.run(json_to_send, namespace)
        if not self.handle_api_result(api_result):
            return
        json_result = self.get_and_handle_tcp_result('run')

        self.tcp_handler.close()
        if not check_http_status(json_result, self.args.get("command")):
            return

    def go_expose(self):
        namespace = self.args.get('namespace')
        if not namespace:
            namespace = config_json_data.get("default_namespace")

        json_to_send = self.construct_expose(namespace)
        if self.debug:
            self.log_time()

        if not json_to_send:
            return
        self.tcp_connect()

        api_result = self.api_handler.expose(json_to_send, namespace)
        if not self.handle_api_result(api_result):
            return

        json_result = self.get_and_handle_tcp_result('expose')
        self.tcp_handler.close()
        if not check_http_status(json_result, self.args.get("command")):
            return

    def go_create(self):
        if self.args.get("debug"):
            self.log_time()
        self.tcp_connect()

        json_to_send = self.get_json_from_file()
        namespace = json_to_send["metadata"].get("namespace")
        if not namespace:
            namespace = self.args.get('namespace')
            if not namespace:
                namespace = config_json_data.get("default_namespace")

        api_result = self.api_handler.create(json_to_send, namespace)
        if not self.handle_api_result(api_result):
            return

        json_result = self.get_and_handle_tcp_result('create')
        self.tcp_handler.close()
        if not check_http_status(json_result, self.args.get("command")):
            return

    def test_namespace(self, namespace):
        if self.debug:
            self.log_time()
        self.tcp_connect()

        api_result = self.api_handler.get_namespaces(namespace)

        if not self.handle_api_result(api_result):
            return

        json_result = self.get_and_handle_tcp_result('check namespace')
        self.tcp_handler.close()
        if not check_http_status(json_result, "check namespace"):
            return
        return True

    def go_get(self):
        kind, name = self.construct_get()
        if self.debug:
            self.log_time()
        self.tcp_connect()

        self.namespace = self.args.get('namespace')
        if not self.namespace:
            self.namespace = config_json_data.get("default_namespace")

        if kind == "namespaces":
            if self.args.get("name"):
                api_result = self.api_handler.get_namespaces(
                    self.args.get("name"))
            else:
                api_result = self.api_handler.get_namespaces()
        else:
            api_result = self.api_handler.get(kind, name, self.namespace)
        if not self.handle_api_result(api_result):
            return

        json_result = self.get_and_handle_tcp_result('get')
        self.tcp_handler.close()
        if not check_http_status(json_result, "get"):
            return
        return json_result

    def get_and_handle_tcp_result(self, command_name):
        try:
            tcp_result = self.tcp_handler.receive()
            if command_name == 'get':
                if not tcp_result.get('status') == 'Failure':
                    if self.args.get("debug"):

                        print('{}{}{}'.format(BColors.OKBLUE, 'get result:\n',
                                              BColors.ENDC))
                    self.print_result(tcp_result)

            return tcp_result

        except RuntimeError as e:
            print('{}{}{}'.format(BColors.FAIL, e, BColors.ENDC))
            return None

    def go_delete(self):
        kind, name = self.construct_delete()

        self.log_time()
        self.tcp_connect()

        self.args['output'] = 'yaml'
        namespace = self.args['namespace']
        if not namespace:
            namespace = config_json_data.get("default_namespace")
        if kind != 'namespaces':
            api_result = self.api_handler.delete(kind, name, namespace,
                                                 self.args.get("pods"))
        else:
            api_result = self.api_handler.delete_namespaces(name)
        if not self.handle_api_result(api_result):
            return

        json_result = self.get_and_handle_tcp_result('delete')
        self.tcp_handler.close()
        if not check_http_status(json_result, self.args.get("command")):
            return

    def go_replace(self):
        self.log_time()
        self.tcp_connect()

        self.args['output'] = 'yaml'
        namespace = self.args['namespace']

        json_to_send = self.get_json_from_file()
        kind = '{}s'.format(json_to_send.get('kind')).lower()

        if kind != 'namespaces':
            api_result = self.api_handler.replace(json_to_send, namespace)
        else:
            api_result = self.api_handler.replace_namespaces(json_to_send)
        if not self.handle_api_result(api_result):
            return

        json_result = self.get_and_handle_tcp_result('replace')

        self.tcp_handler.close()
        if not check_http_status(json_result, self.args.get("command")):
            return

    def check_file_existence(self):
        if 'file' in self.args:
            if self.args.get('file'):
                if not os.path.isfile(
                        os.path.join(self.path, self.args.get('file'))):
                    self.parser.error('no such file: {}'.format(
                        os.path.join(self.path, self.args.get('file'))))

    def check_arguments(self):
        if not (self.args.get('version') or self.args.get('help')
                or self.args.get('command')):
            self.parser.print_help()

    def handle_api_result(self, api_result):
        if api_result.get('id'):
            if self.debug:
                print('{}{}...{} {}OK{}'.format(BColors.OKBLUE,
                                                'api connection', BColors.ENDC,
                                                BColors.BOLD, BColors.ENDC))
                print('{}{}{}{}'.format(
                    BColors.OKGREEN,
                    'Command Id: ',
                    api_result.get('id'),
                    BColors.ENDC,
                ))
            return True
        elif 'error' in api_result:
            print('{}api error: {}{}'.format(BColors.FAIL,
                                             api_result.get('error'),
                                             BColors.ENDC))
            self.tcp_handler.close()
            return

    def tcp_connect(self):
        try:
            tcp_auth_result = self.tcp_handler.connect()
            if tcp_auth_result.get('ok') and self.debug:
                # print(tcp_auth_result)
                print('{}{}...{} {}OK{}'.format(BColors.OKBLUE,
                                                'tcp authorization',
                                                BColors.ENDC, BColors.BOLD,
                                                BColors.ENDC))
        except RuntimeError as e:
            print('{}{}{}'.format(BColors.FAIL, e, BColors.ENDC))

    def print_result(self, result):
        if self.args.get("command") != "expose":
            if self.args.get('output') == 'yaml':
                result = result["results"]
                print(yaml.dump(result, default_flow_style=False))
            elif self.args['output'] == 'json':
                result = result["results"]
                print(json.dumps(result, indent=4))
            else:
                deploy = self.args.get("deploy")
                TcpApiParser(result, deploy=deploy)

    def log_time(self):
        if self.args["debug"]:
            print('{}{}{}'.format(BColors.WARNING,
                                  str(datetime.now())[11:19:], BColors.ENDC))

    def construct_run(self):
        json_to_send = deployment_json
        if not self.args["name"].islower():
            e = LOWER_CASE_ERROR
            print('{}{}{} {}'.format(
                BColors.FAIL,
                "Error: ",
                e,
                BColors.ENDC,
            ))
            return
        json_to_send['metadata']['name'] = self.args['name']

        if self.args["configure"] and not self.args.get("image"):
            runconfigure = RunConfigure()
            param_dict = runconfigure.get_data_from_console()
            if not param_dict:
                return
            image = param_dict["image"]
            ports = param_dict["ports"]
            labels = param_dict["labels"]
            env = param_dict["env"]
            cpu = param_dict["cpu"]
            memory = param_dict["memory"]
            replicas = param_dict["replicas"]
            commands = param_dict["commands"]

        elif self.args.get("image") and not self.args["configure"]:
            image = self.args["image"]
            ports = self.args["ports"]
            labels = self.args["labels"]
            env = self.args["env"]
            cpu = self.args["cpu"]
            memory = self.args["memory"]
            replicas = self.args["replicas"]
            commands = self.args["commands"]

        if not self.args["configure"] and not self.args["image"]:
            self.parser.error(NO_IMAGE_AND_CONFIGURE_ERROR)
            return

        json_to_send['spec']['replicas'] = replicas
        json_to_send['spec']['template']['spec']['containers'][0][
            'name'] = self.args['name']
        json_to_send['spec']['template']['spec']['containers'][0][
            'image'] = image
        if commands:
            json_to_send['spec']['template']['spec']['containers'][0][
                'command'] = commands
        if ports:
            json_to_send['spec']['template']['spec']['containers'][0][
                'ports'] = []
            for port in ports:
                json_to_send['spec']['template']['spec']['containers'][0][
                    'ports'].append({'containerPort': port})
        if labels:
            for key, value in labels.items():
                json_to_send['metadata']['labels'].update({key: value})
                json_to_send['spec']['template']['metadata']['labels'].update(
                    {key: value})
        if env:
            json_to_send['spec']['template']['spec']['containers'][0][
                'env'] = [{
                    "name": key,
                    "value": value
                } for key, value in env.items()]
        json_to_send['spec']['template']['spec']['containers'][0]['resources'][
            "requests"]['cpu'] = cpu
        json_to_send['spec']['template']['spec']['containers'][0]['resources'][
            "requests"]['memory'] = memory
        with open(os.path.join(
                os.getenv("HOME") + "/.containerum/src/",
                JSON_TEMPLATES_RUN_FILE),
                  'w',
                  encoding='utf-8') as w:
            json.dump(json_to_send, w, indent=4)

        return json_to_send

    def get_json_from_file(self):
        file_name = os.path.join(self.path, self.args['file'])
        try:
            with open(file_name, 'r', encoding='utf-8') as f:
                body = json.load(f)
                return body
        except FileNotFoundError:
            self.parser.error('no such file: {}'.format(file_name))
        except json.decoder.JSONDecodeError as e:
            pass

        try:
            with open(file_name, 'r', encoding='utf-8') as f:
                body = yaml.load(f)
                return body
        except FileNotFoundError:
            self.parser.error('no such file: {}'.format(file_name))
        except yaml.YAMLError as e:
            self.parser.error('bad json or yaml: {}'.format(e))

    def construct_delete(self):
        if self.args['file'] and self.args[
                'kind'] == "namespaces" and not self.args['name']:
            body = self.get_json_from_file()
            name = body['metadata']['name']
            kind = '{}s'.format(body['kind'].lower())
            return kind, name

        elif not self.args['file'] and self.args[
                'kind'] != "namespaces" and self.args['name']:
            kind = self.args['kind']
            name = self.args['name']
            return kind, name

        elif not self.args['file'] and self.args['kind'] == "namespaces":
            self.parser.error(ONE_REQUIRED_ARGUMENT_ERROR)
        elif self.args['file'] and self.args['kind'] == "namespaces":
            self.parser.error(KIND_OR_FILE_BOTH_ERROR)
        elif self.args['file'] and self.args['name']:
            self.parser.error(NAME_OR_FILE_BOTH_ERROR)
        elif self.args['kind'] != "namespaces" and not self.args['name']:
            self.parser.error(NAME_WITH_KIND_ERROR)

    def construct_get(self):
        if self.args.get('file') and not self.args.get(
                'kind') and not self.args.get('name'):
            body = self.get_json_from_file()
            name = body['metadata']['name']
            kind = '{}s'.format(body['kind'].lower())
            return kind, name

        elif not self.args.get('file') and self.args.get('kind'):
            kind = self.args['kind']
            name = self.args.get('name')
            return kind, name

        elif not self.args['file'] and not self.args['kind']:
            self.parser.error(ONE_REQUIRED_ARGUMENT_ERROR)
        elif self.args['file'] and self.args['kind']:
            self.parser.error(KIND_OR_FILE_BOTH_ERROR)
        elif self.args['file'] and self.args['name']:
            self.parser.error(NAME_OR_FILE_BOTH_ERROR)

    def construct_expose(self, namespace):
        labels = {}
        is_external = {"external": "true"}
        json_to_send = service_json
        ports = self.args.get("ports")
        self.args["kind"] = "deployments"
        if ports:
            for p in ports:
                p = p.split(":")
                if len(p) == 3:
                    if p[2].upper() == "TCP" or p[2].upper() == "UDP":
                        json_to_send["spec"]["ports"].append({
                            "name":
                            p[0],
                            "protocol":
                            p[2].upper(),
                            "targetPort":
                            int(p[1])
                        })
                    else:
                        json_to_send["spec"]["ports"].append({
                            "name":
                            p[0],
                            "protocol":
                            "TCP",
                            "port":
                            int(p[2]),
                            "targetPort":
                            int(p[1])
                        })
                        is_external["external"] = "false"
                if len(p) == 4:
                    json_to_send["spec"]["ports"].append({
                        "name":
                        p[0],
                        "port":
                        int(p[2]),
                        "protocol":
                        p[3].upper(),
                        "targetPort":
                        int(p[1])
                    })
                    is_external["external"] = "false"
                elif len(p) == 2:
                    json_to_send["spec"]["ports"].append({
                        "name":
                        p[0],
                        "protocol":
                        "TCP",
                        "targetPort":
                        int(p[1])
                    })
        result = self.go_get()
        if not result:
            return
        namespace_hash = sha256(namespace.encode('utf-8')).hexdigest()[:32]
        labels.update({namespace_hash: self.args.get("name")})
        json_to_send["metadata"]["labels"].update(labels)

        json_to_send["metadata"]["labels"].update(is_external)
        json_to_send["metadata"]["name"] = self.args["name"] + "-" + \
                                           md5((self.args.get("name")+str(datetime.now()))
                                               .encode("utf-8")).hexdigest()[:4]
        json_to_send["spec"]["selector"].update(labels)
        with open(os.path.join(
                os.getenv("HOME") + "/.containerum/src/",
                JSON_TEMPLATES_EXPOSE_FILE),
                  'w',
                  encoding='utf-8') as w:
            json.dump(json_to_send, w, indent=4)
        return json_to_send
コード例 #13
0
#!/usr/bin/python3

from http_server_socket import HttpServerSocket
from api_handler import ApiHandler
from web_handler import WebHandler
from db_manager import DbManager
from console_breaker import ConsoleBreaker

breaker = ConsoleBreaker()

web_server = HttpServerSocket('127.0.0.1', 80)
web_server.bind_http_handler(
    ApiHandler(DbManager('./db/api.db', './db/api_db.sql', './db/queries/')))
web_server.bind_http_handler(WebHandler('./web'))

breaker.install_breaker()
コード例 #14
0
 def set_wrong_api_url(self):
     """
     For testing purpose ONLY
     """
     self._api_handler = ApiHandler(
         api_url='https://api.ocr.space/parse/imageasd')
コード例 #15
0
    def __init__(self):
        config = configparser.ConfigParser()
        config.read('bot_config.ini')

        bot_token = config.get("TELEGRAM", "token")

        titsa_idApp = config.get("TITSA", "idApp")

        self.adminId = config.get("ADMIN", "chatId")

        self.apiHandler = ApiHandler(titsa_idApp)

        self.dbHandler = DbHandler()

        self.transportThread = OpenTransitThread(
            "http://www.titsa.com/Google_transit.zip", 7 * 24 * 60 * 60)
        self.transportThread.start()

        updater = Updater(token=bot_token, use_context=True)
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            level=logging.INFO)

        b1 = telegram.KeyboardButton("⭐ Consultar favorito ⭐")
        b2 = telegram.KeyboardButton("✖️ Borrar favorito ✖️")
        b3 = telegram.KeyboardButton("🚊 Tranvia de Tenerife 🚊")
        b4 = telegram.KeyboardButton("📍 Ver paradas cercanas 📍",
                                     request_location=True)
        self.keyboard = telegram.ReplyKeyboardMarkup([[b3, b4], [b1, b2]],
                                                     resize_keyboard=True)

        h1 = MessageHandler(Filters.regex(r"^.+Consultar favorito.+$"),
                            self.favKeyBoard)
        h2 = MessageHandler(Filters.regex(u"^\U0001F68F.+(\d{4})"),
                            self.replyToFav)
        h3 = MessageHandler(Filters.regex(r"^.+Borrar favorito.+$"),
                            self.favKeyBoard)
        h4 = MessageHandler(Filters.regex(u"^\u2716.+(\d{4})"), self.eraseFav)

        updater.dispatcher.add_handler(CommandHandler("start", self.start))
        updater.dispatcher.add_handler(
            MessageHandler(Filters.regex(r"^\d{4}$"), self.responder_a_codigo))
        updater.dispatcher.add_handler(h1)
        updater.dispatcher.add_handler(h2)
        updater.dispatcher.add_handler(h3)
        updater.dispatcher.add_handler(h4)

        updater.dispatcher.add_handler(
            ConversationHandler(
                entry_points=[
                    MessageHandler(Filters.regex(r"^.+Tranvia de Tenerife.+$"),
                                   self.listStops),
                ],
                states={
                    TitsaBot.TRANVIA:
                    [MessageHandler(Filters.all, self.queryTram)]
                },
                fallbacks=[]))

        updater.dispatcher.add_handler(
            MessageHandler(Filters.location, self.nearStops))

        updater.dispatcher.add_handler(
            ConversationHandler(
                entry_points=[
                    CommandHandler("broadcast", self.newBroadcast),
                ],
                states={
                    TitsaBot.BROADCAST_TEXT:
                    [MessageHandler(Filters.all, self.broadcast)]
                },
                fallbacks=[]))

        updater.dispatcher.add_handler(
            ConversationHandler(entry_points=[
                CommandHandler("addFav",
                               self.addFavCommand,
                               pass_args=True,
                               pass_user_data=True),
                CallbackQueryHandler(self.addFavQuery,
                                     pattern=r"^\d{4}$",
                                     pass_user_data=True)
            ],
                                states={
                                    TitsaBot.CUSTOM_OR_DEFAULT: [
                                        CallbackQueryHandler(
                                            self.setFavNameOption,
                                            pass_user_data=True)
                                    ],
                                    TitsaBot.INSERT_CUSTOM: [
                                        MessageHandler(Filters.text,
                                                       self.customName,
                                                       pass_user_data=True)
                                    ]
                                },
                                fallbacks=[h1, h2, h3, h4]))

        updater.dispatcher.add_handler(
            ConversationHandler(entry_points=[
                CallbackQueryHandler(self.reloadStationQuery,
                                     pattern=r"^Repetir \d{4}$",
                                     pass_user_data=True)
            ],
                                states={
                                    TitsaBot.CUSTOM_OR_DEFAULT: [
                                        CallbackQueryHandler(
                                            self.reloadStationQuery,
                                            pass_user_data=True)
                                    ]
                                },
                                fallbacks=[h1, h2, h3, h4]))

        updater.dispatcher.add_handler(
            CallbackQueryHandler(self.sendStopAndLocation,
                                 pattern=r"^Locate \d{4}$",
                                 pass_user_data=True))

        updater.start_polling()
        updater.idle()
        self.dbHandler.save()
        self.transportThread.stop()
コード例 #16
0
class Agent:
    """
    An Aries CloudAgent object

    This object has all the tools needed to interact with the ledger.
        1. It sets-up a docker container,
        2. It sets-up a webhook server to handle incoming communications
        3. It has a build-in API handler to handle interaction with the ledger
    """
    def __init__(
        self,
        identity: str,
        start_port: int,
        transport_protocol: str,
        endpoint: str,
        ledger_url: str,
        local_ip: str,
        wallet_name: str,
        wallet_key: str,
        seed: str = "random",
        public_did: bool = True,
        auto_response: bool = False,
    ):
        # Construct docker container object to maintain a running container
        self.docker_container = Container(
            identity=identity,
            endpoint=endpoint,
            seed=seed,
            indbound_transport_port=start_port,
            outbound_transport_port=start_port + 1,
            transport_protocol=transport_protocol,
            wallet_name=wallet_name,
            wallet_key=wallet_key,
            webhook_url=
            f"{transport_protocol}://{local_ip}:{start_port+2}/webhooks",  #TODO:
            genesis_url=f"{ledger_url}/genesis")

        # Construct Api Handler object that handles all Api calls
        self.api_handler = ApiHandler(  # TODO: Ledger transport protocol toevoegen
            api_url=local_ip,
            port=start_port + 1)

        # Construct a webhook server object that handles incoming messages
        self.webhook_server = WebhookServer(
            identity=identity,
            webhook_ip=local_ip,
            webhook_protocol=transport_protocol,
            webhook_port=start_port + 2,
            api_handler=self.api_handler
        )  # TODO: webhook IP is not per definitie gelijk aan ledger ip

        self.identity = identity
        self.start_port = start_port
        self.ledger_url = ledger_url
        self.local_ip = local_ip
        self.seed = seed
        self.public_did = public_did
        self.auto_response = auto_response
        # TODO: Register DID weghalen en verplaatsen naar api handler
        self.client_session = ClientSession()
        self.transport_protocol = transport_protocol

        # TODO: random seed ja?
        rand_name = str(random.randint(100_000, 999_999))
        self.seed = (("my_seed_000000000000000000000000" +
                      rand_name)[-32:] if seed == "random" else seed)

    async def initialize(self) -> None:
        """
        Start a webhook server, register a DID and start a docker container process
        """
        await self.webhook_server.start_process()
        await self.register_did()
        await self.docker_container.start_process()

        # TODO:  Timeout toevoegen, wanneer verkeerde key wordt gegeven, geeft hij alsog aan dat er een goeie connectie is
        if self.api_handler.test_connection() is False:
            return
        self.admin_url = f"{self.transport_protocol}://{self.local_ip}:{self.start_port+1}"
        self.endpoint = f"{self.transport_protocol}://{self.local_ip}:{self.start_port}"
        log_msg(f"Admin URL is at: {self.admin_url}", color=LOG_COLOR)
        log_msg(f"Endpoint URL is at: {self.endpoint}", color=LOG_COLOR)

    async def connections(self,
                          *,
                          alias_query: str = None,
                          invitation_key_query: str = None,
                          my_did_query: str = None,
                          connection_state_query: str = None,
                          their_did_query: str = None,
                          their_role_query: str = None) -> dict:
        """
        List and Query agent-to-agent connections

        Function can be called with no KWARGS to list ALL conenctions
        Function can also be called with KWARGS to query the list of connections

        :param alias_query: Only list connections with this alias
        :param invitation_key_query: Only list connections with this invitation key
        :param my_did_query: Only list connections with this "my did" value
        :param connection_state_query: Only list connections with this connection state
        :param their_did_query: Only list connections with this "their did" value
        :param their_role_query: Only list connections with this "their role" value
        :return: Queried list of agent-to-agent connections with their states
        """
        return self.api_handler.connections(
            alias_query=alias_query,
            invitation_key_query=invitation_key_query,
            my_did_query=my_did_query,
            connection_state_query=connection_state_query,
            their_did_query=their_did_query,
            their_role_query=their_did_query)

    async def generate_invitation(self,
                                  auto_accept: bool = True,
                                  multi_use: bool = False,
                                  display_qr: bool = False) -> tuple:
        """
        Create a connection invitation

        :param auto_accept: Auto accept connection handshake?
        :param multi_use: Can this invite be used multiple times?
        :param display_qr: Bool to indicate whether a QR code should be displayed in the terminal
        :return: A tuple containing the connection id and base64 encoded invite url
        """
        invitation_id, invitation = self.api_handler.create_invitation(
            alias=self.identity, multi_use=multi_use, auto_accept=auto_accept)
        if display_qr:
            qr = QRCode(border=1)
            qr.add_data(json.dumps(invitation))
            log_msg(
                f"Use the following JSON to accept the invite from another demo agent. Or use the QR code to connect from a mobile agent.",
                color=LOG_COLOR)
            log_msg(f"Invitation Data:",
                    json.dumps(invitation),
                    color=LOG_COLOR)
            qr.print_ascii(invert=True)
        return invitation_id, invitation

    async def send_message(self, connection_id: str, message: str):
        """
        Send a message to another connected agent

        :param connection_id: The connection id of the connection between this agent and the connected agent
        :param message: Message to send to the other agent
        :return: Response of the operation
        """
        connection_id = await prompt(
            "Send message to <connection id> :"
        )  # TODO: Throw exception when invitation is invalid
        message = await prompt("Message <message>:")
        self.api_handler.send_message(connection_id, message)

    async def create_schema(self, schema: dict = None) -> dict:
        """
        Create a schema on the ACA-Py instance

        :param schema: The schema to create
        :return: The created schema as a dict
        """
        schema = await prompt("Schema :"
                              )  # TODO: Throw exception when schema is invalid
        schema = json.loads(schema)
        return self.api_handler.create_schema(schema)

    async def create_credential_definition(
            self,
            schema_id: str = None,
            schema_tag: str = None,
            support_revocation: bool = False) -> str:
        """
        Create a credentials definition on the Ledger

        :param schema_id: The id of the schema that the credential definition needs to be created from
        :param schema_tag: The tag of the schema
        :param supports_revocation: Bool to indicate if the credential definition needs to support revocation or not
        """
        schema_id = await prompt(
            "Schema ID <id>:"
        )  # TODO: Throw exception when invitation is invalid
        schema_tag = await prompt(
            "Schema tag <tag>:"
        )  # TODO: Throw exception when invitation is invalid
        return self.api_handler.create_credential_definition(
            schema_id, schema_tag, support_revocation)

    async def issue_credential(self) -> dict:
        """
        Issue a credential to one of the agent. Promts the user for inputs.

        :return: The result of the issue credential operation
        """
        connection_id = await prompt("Connection ID <id>: ")
        cred_def_id = await prompt("Connection definition ID <id>: ")
        schema = json.loads(await prompt("Schema <schema>: "))
        log_msg(schema)
        attributes = json.loads(await prompt("Attributes <attributes>: "))
        log_msg(attributes)
        return self.api_handler.issue_credential(connection_id, cred_def_id,
                                                 attributes, schema)

    async def get_credentials(self):
        return self.api_handler.get_credentials()

    async def register_did(self,
                           ledger_ip: str = None,
                           alias: str = None,
                           did: str = None,
                           verkey: str = None,
                           role: str = "TRUST_ANCHOR"):
        """
        Function registers a DID on the ledger

        :param ledger_url: The ledger_url of the ledger
        :param alias: The alias to gerister on the ledger
        :param did: Did to register
        :param verkey: Verkey to register
        :param role: role of the registered DID
        :raises Exception: raises an exception when an invalid response is given by the ledger
        """
        log_msg(f"Registering {self.identity} ...", color=LOG_COLOR)
        data = {"alias": alias or self.identity, "role": role}
        if did and verkey:
            data["did"] = did
            data["verkey"] = verkey
        else:
            data["seed"] = self.seed
        async with self.client_session.post(f"{self.ledger_url}/register",
                                            json=data) as resp:
            if resp.status != 200:
                raise Exception(
                    f"Error registering DID, response code {resp.status}")
            nym_info = await resp.json()
            self.did = nym_info["did"]
            log_msg(f"nym_info: {nym_info}", color=LOG_COLOR)
        log_msg(f"Registered DID: {self.did}", color=LOG_COLOR)

    async def receive_invitation(self,
                                 invitation,
                                 alias=None,
                                 auto_accept=False) -> str:
        """
        Receive invitation url

        :param invitation: The base64 encoded invite url str
        :param alias: The alias to give to the connection as a str
        :param auto_accept: Auto accept connection handshake?
        :return: The connection id as a str
        """
        # TODO: Throw exception when invitation is invalid
        invitation = await prompt("Invite details: ")
        auto_accept = await prompt("Auto accept invitation? n/y: ")
        if auto_accept == "y":
            auto_accept = True
        else:
            auto_accept = False
        return self.api_handler.receive_invitation(invitation_url=invitation,
                                                   alias=self.identity,
                                                   auto_accept=True)

    async def get_connection_state(self, connection_id) -> int:
        """
        Get the connection state of a given connection id

        :param connection_id: The connection id
        :return: The state (see states dict)
        """
        # TODO: Throw exception when connection_id is invalid
        connection_id = await prompt("Connection state: ")
        return self.api_handler.get_connection_state(connection_id)

    async def terminate(self):
        """
        Terminate the Agent by closing the admin API, webhook server and docker container.

        :return: True if termination is complete
        """
        log_msg(f"Shutting down {self.identity}", color=LOG_COLOR)

        await self.client_session.close()  # Close session to admin api
        await self.webhook_server.terminate()  # Shut down web hooks first
        await self.docker_container.terminate()  # now shut down the agent

        return True
コード例 #17
0
import json
import textwrap
from qrcode import QRCode

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append('../Lib')

from localtunnel import LocalTunnel
from utilities import log_msg, prompt_loop
from api_handler import ApiHandler

LOG_COLOR = "hot pink"

if __name__ == "__main__":
    print(sys.argv[1], sys.argv[2])
    api_handler = ApiHandler(sys.argv[1], sys.argv[2])

    options = (
        "1. Show Connections\n2. Generate invitation\n3. Receive inivtaiotn\n4. Send Message\n5. Get connection state\n6. Create Schema\n7. Create credential definition\n8. Issue credential\n9. Get credentials\n10. Exit\n"
    )
    alias = "api_handler_test"

    while True:
        option = input(options)
        try:
            if int(option) == 1:
                connections = api_handler.connections()
                log_msg(f"{json.dumps(connections, indent=4, sort_keys=True)}",
                        color=LOG_COLOR)
                log_msg(f"Total connections:",
                        len(connections["results"]),
コード例 #18
0
 def __init__(self):
     super(ParkingService, self).__init__()
     self._api_handler = ApiHandler()
     self._content_handler = ContentHandler()
     # db_handler is public for testing purpose
     self.db_handler = DateBaseHandler()
コード例 #19
0
from flask_api import FlaskAPI
from flask import request
from api_handler import ApiHandler
from form.form import MainForm
from flask import render_template, flash

app = FlaskAPI(__name__)
app.config['SECRET_KEY'] = 'you-will-never-guess'

api_handler = ApiHandler()


@app.route('/example/')
def example():
    return {'hello': 'world'}


@app.route('/recommend/', methods=["GET", "POST"])
def recommend():
    inputs = request.args.getlist('inputs')
    print(inputs)
    output = api_handler.get_recommend_output(inputs=inputs)
    return output


@app.route('/index/', methods=["GET", "POST"])
def index():
    if request.method == 'POST':
        print()

    form = MainForm()
コード例 #20
0
ファイル: bittercrawler.py プロジェクト: rkalz/CS334
from api_handler import ApiHandler
import sys
import math
"""Creates the ApiHndler"""
authorization = {
    "email": sys.argv[1],
    "password": sys.argv[2],
    "grant_type": "password"
}

handler = ApiHandler(authorization, True)
users_friends = []
vertices = []
checked = []
unchecked = []
beets = []
flags = []


def verticeMaker(people_friends):
    while (people_friends):
        if (people_friends[0][1]['friends']):
            if ((people_friends[0][0],
                 people_friends[0][0][1]['friends'][0]['uid'],
                 people_friends[0][0][1]['friends'][0]['length'])
                    not in vertices):
                vertices.append(
                    people_friends[0][0],
                    people_friends[0][0][1]['friends'][0]['uid'],
                    people_friends[0][0][1]['friends'][0]['length'])
                people_friends.remove(people_friends[0][0][1]['friends'][0])