コード例 #1
0
ファイル: main.py プロジェクト: kived/bleserver
 def on_connection_established(self, characteristic, error):
     if error:
         Logger.error("BLE: connection failed: {}".format(error))
         self.on_device_disconnect(None)
         return
     Logger.info("BLE: connection established {}".format(repr(characteristic.value)))
     self.start_data()
コード例 #2
0
ファイル: os_changes.py プロジェクト: GreenJon902/HexOS
def try_update_for_testing():
    try:
        bar = window("update")
        if open(os.path.join(globals.baseSysPath,
                             globals.baseSysConfig.get("main", "name") + "Files", "OSVer"), "r").read() \
                != open(os.path.join(globals.HexOSPath, "OSVer"), "r").read():
            copy(
                bar,
                os.path.join(
                    globals.baseSysPath,
                    globals.baseSysConfig.get("main", "name") + "Files"))

    except FileNotFoundError:
        bar.parent.parent.parent.dismiss()
        Logger.error(
            "HexOSBase: Could not find OSVer file, asking user to hard reinstall"
        )

        popup = Popup(
            title="HexOS has missing files",
            content=Button(text="Reinstall",
                           on_release=lambda *args: install(),
                           on_press=lambda *args: popup.dismiss()),
            size_hint=(globals.baseSysConfig.get("os_changes", "size_hint_x"),
                       globals.baseSysConfig.get("os_changes", "size_hint_y")),
            auto_dismiss=False)

        popup.open()
コード例 #3
0
def GetIPAddressV6() -> str:

    uPreferredAdapter: str = u'eth0'
    uInet_Type: str = u'AF_INET6'
    uRet: str = u'127.0.0.0'
    aFound: List[str] = []
    iInet_num: int

    try:
        iInet_num = getattr(netifaces, uInet_Type)
        aInterfaces: List = netifaces.interfaces()

        for uNetiface in aInterfaces:
            dNetInfo: Dict = netifaces.ifaddresses(uNetiface)
            aNetDetails: List = dNetInfo.get(iInet_num)
            if aNetDetails is not None and len(aNetDetails) > 0:
                dNetDetails: Dict = aNetDetails[0]
                uIP = dNetDetails["addr"]
                if uIP != "::1":
                    aFound.append(uIP)
                    if uNetiface == uPreferredAdapter:
                        aFound = [uIP]
                        break
    except Exception as e:
        Logger.error("Error on GetIPAddressV6:" + str(e))

    if len(aFound) > 0:
        uRet = aFound[-1]

    # remove stuff like %eth0 that gets thrown on end of some addrs
    uRet = uRet.split('%')[0]
    return uRet
コード例 #4
0
ファイル: mediafax.py プロジェクト: talpah/pivystation
    def update(self):
        self.news = feedparser.parse(self.feed_url)

        article_list = []

        xlocale = locale.getlocale(locale.LC_TIME)
        locale.setlocale(locale.LC_TIME, 'en_US.utf-8')

        if not self.news['items']:
            Logger.error('NEWS: Seems there\'s no news')
            return # Return here so we keep old news (if any)

        for x in self.news['items']:
            description = unicode(x['description']).strip()
            description = description.split('<', 1)[0].strip()
            title = unicode(x['title']).strip()
            if description == '.':
                title = u'[color=#FFDD63]{}[/color]'.format(title)
                description = ''
            article_date = (datetime.strptime(x['published'], "%a, %d %b %Y %H:%M:%S %Z") + timedelta(hours=2))
            article_relative_date = format_timedelta(article_date - datetime.now(),
                                                     granularity='minute',
                                                     locale='ro_RO.utf-8',
                                                     add_direction=True)
            article_list.append(u'{}\n[color=#777777]{}[/color]\n\n{}'.format(title,
                                                                              article_relative_date,
                                                                              description))
        locale.setlocale(locale.LC_TIME, xlocale)
        self.articles = deque(article_list)
コード例 #5
0
def GetMACAddress() -> List:

    uInet_Type: str = u'AF_INET'
    iInet_num: int

    uRetColon: str = u'00:00:00:00:00:00'
    uRetDash: str = u'00-00-00-00-00-00'

    try:
        iInet_num = getattr(netifaces, uInet_Type)
        aInterfaces: List = netifaces.interfaces()
        for uNetiface in aInterfaces:
            dNetInfo: Dict = netifaces.ifaddresses(uNetiface)
            aNetDetails: List = dNetInfo.get(iInet_num)
            if aNetDetails is not None and len(aNetDetails) > 0:
                dNetDetails: Dict = aNetDetails[0]
                if dNetDetails["addr"] == Globals.uIPAddressV4:
                    uRetColon = netifaces.ifaddresses(uNetiface)[
                        netifaces.AF_LINK][0]['addr']
                    uRetDash = uRetColon.replace(":", "-")
                    return [uRetColon, uRetDash]
    except Exception:
        pass

    try:
        uRetColon = u':'.join(re.findall('..', '%012x' % uuid.getnode()))
        uRetDash = u'-'.join(re.findall('..', '%012x' % uuid.getnode()))
    except Exception as e:
        Logger.error("Error on GetMACAdress:" + str(e))
    return [uRetColon, uRetDash]
コード例 #6
0
ファイル: openweathermap.py プロジェクト: talpah/pivystation
 def refresh(self, place):
     last_updated = now = datetime.now()
     tomorrow = now + timedelta(days=1)
     place_cache = self.weather_data.get(place, {})
     if place in self.update_stamps:
         last_updated = self.update_stamps[place]
     if not place_cache or (now - last_updated).total_seconds() >= self.update_interval:
         try:
             self.weather_data[place] = self.api_object.weather_at_place(place).get_weather()
             self.forecast_today_data[place] = self.api_object.daily_forecast(place).get_weather_at(
                 now.replace(hour=12))
             try:
                 self.forecast_tomorrow_data[place] = self.api_object.daily_forecast(place).get_weather_at(
                     tomorrow.replace(hour=12))
             except Exception:
                 self.forecast_tomorrow_data[place] = {}
             self.update_stamps[place] = datetime.now()
         except Exception as e:
             self.update_stamps[place] = datetime.now()
             Logger.error('WEATHER: Failed to get data: {}'.format(e))
             return False
         except APICallError as e:
             self.update_stamps[place] = datetime.now()
             Logger.error('WEATHER: Failed to get data: {}'.format(e))
             return False
     return True
コード例 #7
0
ファイル: datepicker.py プロジェクト: wilsenmuts/KivyMD
    def on_release(self):
        if (self.owner.mode == "range" and self.owner._end_range_date
                and self.owner._start_range_date):
            return
        if (not self.owner._input_date_dialog_open
                and not self.owner._select_year_dialog_open):
            if self.owner.mode == "range" and not self.owner._start_range_date:
                self.owner._start_range_date = date(self.current_year,
                                                    self.current_month,
                                                    int(self.text))
                self.owner.min_date = self.owner._start_range_date
            elif (self.owner.mode == "range" and not self.owner._end_range_date
                  and self.owner._start_range_date):
                self.owner._end_range_date = date(self.current_year,
                                                  self.current_month,
                                                  int(self.text))
                if self.owner._end_range_date <= self.owner.min_date:
                    toast(self.owner.date_range_text_error)
                    Logger.error(
                        "`Data Picker: max_date` value cannot be less than "
                        "or equal to 'min_date' value.")
                    self.owner._start_range_date = 0
                    self.owner._end_range_date = 0
                    return
                self.owner.max_date = self.owner._end_range_date
                self.owner.update_calendar_for_date_range()

            self.owner.set_selected_widget(self)
コード例 #8
0
    def vibrate(self, length):
        if not self.turned_on():
            Logger.error(
                "Android Vibration: won't vibrate, turned off in settings...")
            return

        Logger.info("Vibrator: vibrate %s milliseconds...", length)
コード例 #9
0
ファイル: main.py プロジェクト: kived/bleserver
 def on_device_disconnect(self, device, error=None):
     if error:
         Logger.error("BLE: device disconnected: {}".format(error))
     else:
         Logger.info("BLE: device disconnected")
     self.connected = None
     self.ble_should_scan = True
コード例 #10
0
    def beta_testers_group(self, *args, **kwargs):
        try:
            import webbrowser
            import settings

            webbrowser.open(settings.BETA_TESTERS_GROUP_URL)
        except Exception:
            Logger.error("Browser: could not start google group...")
コード例 #11
0
    def facebook(self, *args, **kwargs):
        try:
            import webbrowser
            import settings

            webbrowser.open(settings.FACEBOOK_PAGE_URL)
        except Exception:
            Logger.error("Browser: could not start facebook...")
コード例 #12
0
    def mail(self, ref, *args, **kwargs):
        try:
            import webbrowser
            from utils import _  # noqa F401 looks like i18n on mail subject wouldn't work without this import

            webbrowser.open("mailto:[email protected]?subject=%s" % ref)
        except Exception:
            Logger.error("Browser: could not start mailto...")
コード例 #13
0
 def logout(self):
     super(AndroidGoogleClient, self).logout()
     if self.client and self.is_connected():
         try:
             Games.signOut(self.client)
             self.client = None
         except JavaException:
             Logger.error("Google: error while logout")
コード例 #14
0
 def privmsg(self, user, channel, msg):
     """This will get called when the bot receives a message."""
     user = user.split('!', 1)[0]
     Logger.debug('{}->{}: {}'.format(user, channel, msg))
     #self.factory.app.message_callback("<%s> %s" % (user, msg))
     try:
         self._handle_privmsg(user, channel, msg)
     except Exception as e:
         Logger.error('{}->{}: {} | {}'.format(user, channel, msg, e))
コード例 #15
0
 def import_extension_module(self, module_name):
     try:
         mod = importlib.import_module(module_name)
         Logger.debug('Loaded extension {}'.format(module_name))
         return mod, module_name
     except Exception as e:
         Logger.error('Error loading extension {}: {}'.format(
             module_name, e))
         self.errors.add(module_name)
         return None, module_name
コード例 #16
0
ファイル: radio.py プロジェクト: talpah/pivystation
 def play(self, *args):
     if not self._loaded_stream:
         self.select_stream(self.current_stream)
     try:
         self._loaded_stream.play()
         Logger.info("Radio: playing %s" % self.stream_list[0])
         self.is_playing = True
         self.play_status = 'Radio: Pornit'
     except Exception as e:
         self.play_status = 'Radio: Eroare'
         Logger.error('Radio: Failed to play stream: {}'.format(e.message))
コード例 #17
0
 def to_screen(self, name):
     # pure performance tweak to postpone screens instantiation
     if not self.has_screen(name):
         self._build_screen(name)
     from kivy.uix.widget import WidgetException
     Logger.info("Root Widget: switch to screen %s" % name)
     try:
         self.current = name
     except WidgetException as ex:
         Logger.error("Root Widget: can't switch %s, because %s" %
                      (name, unicode(ex)))
コード例 #18
0
ファイル: utils.py プロジェクト: pythonic64/kognitivo
    def __new__(cls, s, *args, **kwargs):
        if 'KIVY_UNITTEST' in os.environ:
            _.switch_lang('en')

        if _.lang is None:
            Logger.error(
                "Gettext __new__ is called before configuration read. "
                "Put statements in constructors, not on the class/function/module level"
            )
            _.switch_lang('en')

        s = _.translate(s, *args, **kwargs)
        return super(_, cls).__new__(cls, s)
コード例 #19
0
ファイル: main.py プロジェクト: kived/bleserver
    def on_discover_services(self, services, error):
        if error:
            Logger.error("BLE: error discovering services: {}".format(error))
            return

        Logger.info("BLE: discovered services: {}".format(services.keys()))

        service = services[self.connect_uuid]
        if not service:
            Logger.error("BLE: service not found!")
            return

        service.discover_characteristics(on_discover=self.on_discover_characteristics)
コード例 #20
0
ファイル: main.py プロジェクト: kived/bleserver
    def on_discover_characteristics(self, characteristics, error):
        if error:
            Logger.error("BLE: error discovering characteristics: {}".format(error))
            return

            # Logger.info('BLE: discovered characteristics: {}'.format(characteristics.keys()))
        for uuid, char in characteristics.items():
            Logger.info("BLE: discovered characteristic: {} {:02x}".format(uuid, char.properties))
            if uuid == self.connection_uuid:
                Logger.info("BLE: found connection characteristic")
                char.read(on_read=self.on_connection_established)
            elif uuid == self.module_message_uuid:
                Logger.info("BLE: found module message characteristic")
                self.module_message_characteristic = char
コード例 #21
0
def GetGatewayV4() -> str:

    uFamily: str = u'AF_INET'
    iInet_num: int

    try:
        iInet_num = getattr(netifaces, uFamily)
        dGateways: Dict = netifaces.gateways()
        # noinspection PyTypeChecker
        uIP = dGateways['default'][iInet_num][0]
    except Exception as e:
        Logger.error("Error on GetGatewayV4, using fallback:" + str(e))
        uIP: str = Globals.uIPAddressV4[:Globals.uIPAddressV4.rfind("."
                                                                    )] + '.1'
    return uIP
コード例 #22
0
ファイル: main.py プロジェクト: hirossan4049/Schreen
    def stop_server(self, *args):
        try:
            import server.flaskserver as flaskserver
            flaskserver.shutdown_server()
        except ImportError:
            pass
        except:
            Logger.error("flaskserver:shutdown_server() func error.")
            self.error_dialog(
                "内部エラー\nflaskserver: shutdown_server() func error.\napp/main.py:147"
            )

        self.ids.stop_btn.disabled = True
        self.ids.start_btn.text = "起動"
        Logger.info("EVENT CLEAR")
コード例 #23
0
ファイル: tmpdir.py プロジェクト: GreenJon902/HexOS
def clear_tmp_dir():
    try:
        folder = os.path.join(globals.userDataDir, "tmp")

        for filename in os.listdir(folder):
            file_path = os.path.join(folder, filename)

            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)

        Logger.info("HexOSBase: tmp dir cleared")

    except Exception as e:
        Logger.error("HexOSBase: Failed to clear tmp folder - " + str(e))
コード例 #24
0
        def vibrate(self, length):
            if not self.turned_on():
                Logger.error(
                    "Android Vibration: won't vibrate, turned off in settings..."
                )
                return
            super(AndroidVibrationManager, self).vibrate(length)

            if not self.service:
                self.initialize()
                if not self.service:
                    Logger.error(
                        "Android Vibration: failed to initialize vibration service"
                    )
                    return
            self.service.vibrate(int(length))
コード例 #25
0
ファイル: main.py プロジェクト: hirossan4049/Schreen
 def quality(self) -> int:
     item = self.ids.quality_dropdown.current_item
     res = 0
     if item == "普通":
         res = 2
     elif item == "高品質":
         res = 1
     elif item == "低品質":
         res = 4
     # 正直調停品質はいらねぇとおもった、
     # elif item == "超低品質":
     #     res = 8
     else:
         Logger.error("ERROR QUALITY FUNC LINE:57")
         self.error_dialog(
             "内部エラー\nmain.py:60\n\nご不便をおかけして申し訳ございません。\n製作者にお問い合わせください。")
     return res
コード例 #26
0
ファイル: main.py プロジェクト: hirossan4049/Schreen
    def server_stop(self, *args):
        global server_thread
        try:
            import server.flaskserver as flaskserver
            flaskserver.shutdown_server()
        except ImportError:
            pass
        except:
            Logger.error(
                "flaskserver:MAINAPP ERROR.shutdown_server() func error.")

        try:
            Logger.info("server thread join now...")
            server_thread.join()
            Logger.info("Server join end!!")
        except:
            Logger.error("joinできません。")
コード例 #27
0
ファイル: main.py プロジェクト: kived/bleserver
    def on_device_connect(self, device, error=None):
        self.connecting = None
        if error:
            Logger.error("BLE: failed to connect to device: {}".format(error))
            self.ble_should_scan = True
            return

        Logger.info("BLE: connected to device {}".format(device))
        self.connected = device

        # device.discover_services(uuids=(self.connect_uuid,), on_discover=self.on_discover_services)
        service = device.services[self.connect_uuid]
        if service:
            Logger.info("BLE: found service {}".format(service))
            self.on_discover_services(device.services, None)
        else:
            device.discover_services(on_discover=self.on_discover_services)
コード例 #28
0
ファイル: tmpdir.py プロジェクト: GreenJon902/HexOS
def make_tmp_dir(doing):
    try:
        if not os.path.exists(os.path.join(globals.userDataDir, "tmp")):
            os.mkdir(os.path.join(globals.userDataDir, "tmp"))

        path = os.path.join(globals.userDataDir, "tmp", doing)
        os.mkdir(path)

        Logger.info("HexOSBase: tmp dir " + doing + " created")

    except FileExistsError:

        Logger.error("HexOSBase: Failed to create tmp folder named " + doing +
                     ", creating a different one")
        path = make_tmp_dir(doing + str(2))

    return path
コード例 #29
0
ファイル: utilities.py プロジェクト: vaizguy/cryptikchaos
def criptiklogo():
    """
    Read the logo and return it as string.
    """

    logofile = "{}/../data/logo.txt".format(dirname(realpath(__file__)))

    try:
        # Open and read logo file
        with open(logofile, "r") as f:
            logo = "".join(f.readlines())
    except IOError:
        # No logo present
        Logger.error("UTILITIES: Failed to read cryptikchaos logo.")
        return None
    else:
        # Return logo if success
        return logo.format(md5hash(str(getnode()))[0:8], __version__)
コード例 #30
0
ファイル: helper.py プロジェクト: myasul/ekt_dictionary
def load_data(csv_path, table_name):
    # TODO :: Add docstring
    Logger.info(f"Application: Data migration for {table_name} started.")
    start = timer()
    try:
        with open(csv_path) as f:
            csv_reader = csv.reader(f, delimiter=",")

            for row in csv_reader:

                try:
                    if table_name == "dictionary":
                        db_helper.add_dictionary(row)
                    elif table_name == "screens":
                        db_helper.add_screen(row)
                    elif table_name == "scroll_direction":
                        db_helper.add_scroll_direction(row)
                    else:
                        raise ValueError(f"Invalid table name: {table_name}.")
                except SQLAlchemyError:
                    Logger.error(f"Application: {traceback.format_exc()}")
                    continue
                except ValueError:
                    Logger.error(f"Application: {traceback.format_exc()}")
                    raise

    except Exception:
        Logger.error(f"Application: {traceback.format_exc()}")
        raise
    end = timer()
    Logger.info(
        f"Application: Data migration for {table_name} "
        f"completed in {end-start:.2f} secs."
    )
コード例 #31
0
ファイル: widgets.py プロジェクト: jamesmunns/python-sdk
    def update(self, readings):
        for reading in readings:
            meaning = reading['meaning']
            if meaning not in settings.MEANING_COLORS:
                continue
            if meaning not in self.sensors:
                sensor = SensorWidget(device=self)
                sensor.meaning = meaning
                self.sensors[meaning] = sensor
                self.sensor_container.add_widget(sensor)

                if not self.history.meaning:
                    self.history.meaning = meaning

            self.sensors[meaning].timestamp = reading['recorded']
            try:
                self.sensors[meaning].value = reading['value']
            except ValueError:
                Logger.error("Sensor: %s:%s got bad value %s" % (self.device_id, meaning, reading['value']))
                self.sensors[meaning].value = 0

            if meaning == self.history.meaning:
                self.history.add_value(reading['value'], reading['recorded'])
コード例 #32
0
ファイル: widgets.py プロジェクト: jamesmunns/python-sdk
    def update(self, readings):
        for reading in readings:
            meaning = reading['meaning']
            if meaning not in settings.MEANING_COLORS:
                continue
            if meaning not in self.sensors:
                sensor = SensorWidget(device=self)
                sensor.meaning = meaning
                self.sensors[meaning] = sensor
                self.sensor_container.add_widget(sensor)

                if not self.history.meaning:
                    self.history.meaning = meaning

            self.sensors[meaning].timestamp = reading['recorded']
            try:
                self.sensors[meaning].value = reading['value']
            except ValueError:
                Logger.error("Sensor: %s:%s got bad value %s" %
                             (self.device_id, meaning, reading['value']))
                self.sensors[meaning].value = 0

            if meaning == self.history.meaning:
                self.history.add_value(reading['value'], reading['recorded'])
コード例 #33
0
def GetIPAddressV4() -> str:

    uPreferredAdapter: str = u'eth0'
    uInet_Type: str = u'AF_INET'
    uRet: str = u'127.0.0.1'
    aFound: List[str] = []
    iInet_num: int

    try:
        iInet_num = getattr(netifaces, uInet_Type)
        aInterfaces: List = netifaces.interfaces()

        for uNetiface in aInterfaces:
            dNetInfo: Dict = netifaces.ifaddresses(uNetiface)
            aNetDetails: List = dNetInfo.get(iInet_num)
            if aNetDetails is not None and len(aNetDetails) > 0:
                dNetDetails: Dict = aNetDetails[0]
                aFound.append(dNetDetails["addr"])
                if uNetiface == uPreferredAdapter:
                    aFound = [dNetDetails["addr"]]
                    break
    except Exception as e:
        Logger.error("Error on GetIPAddressV4:" + str(e))

    # we prefer a local subnet if given
    for uFound in aFound:
        if uFound.startswith("192"):
            uRet = uFound
            break
        if not uFound.startswith("127"):
            uRet = uFound

    if uRet.startswith(u'127'):
        uRet = GetLocalIPV4()

    return uRet
コード例 #34
0
 def deactivate(self):
     super(AndroidFacebookManager, self).deactivate()
     try:
         AppEventsLogger.deactivateApp(python_activity)
     except JavaException as ex:
         Logger.error("Facebook Android: %s" % ex)
コード例 #35
0
ファイル: main.py プロジェクト: kived/bleserver
 def peripheral_service_error(self, service, error):
     Logger.error("BLE: connect: peripheral service error: {}: {}".format(service, error))
コード例 #36
0
ファイル: main.py プロジェクト: kived/bleserver
 def peripheral_advertising_error(self, error):
     Logger.error("BLE: connect: advertisement error: {}".format(error))
コード例 #37
0
# print(path.resolve())          # 絶対パスを表示 (デバッグ用)

from DEBUG import DEBUG,resource_path

# どういう書き方がいちばんいいのかいまいちわからん。
# if __name__ == '__main__':
#     from sct_loop import Sct_loop
# else:
#     from server.sct_loop import Sct_loop
try:
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    localIP = s.getsockname()[0]
    s.close()
except:
    Logger.error("INTERNET ERROR")
# FIXME:Flaskってどうやったらきれいにかけるんや?

do_run = True
quality = 0
port = 2525
SHUTDOWN_UUID = uuid.uuid4()

sct_cls = Sct_loop(quality)


def client_loop():
    global do_run
    while do_run:
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + sct_cls.get_value() + b'\r\n\r\n')
コード例 #38
0
ファイル: main.py プロジェクト: kived/bleserver
 def on_char_write(self, char, error):
     if error:
         Logger.error("BLE: error writing data: {}: {}".format(char, error))
     else:
         Logger.debug("BLE: write successful: {}".format(char))
コード例 #39
0
ファイル: sslcontext.py プロジェクト: vaizguy/cryptikchaos
    def getContext(self):
        "Get SSL context."

        # Now the options you can set Standard OpenSSL Library options

        # Selecting Transport Layer Security v1
        # The SSL protocol to use, one of SSLv23_METHOD, SSLv2_METHOD,
        # SSLv3_METHOD, TLSv1_METHOD. Defaults to TLSv1_METHOD.
        self.method = SSL.TLSv1_METHOD

        # If True, verify certificates received from the peer and fail
        # the handshake if verification fails. Otherwise, allow anonymous
        # sessions and sessions with certificates which fail validation.
        self.verify = True

        # Depth in certificate chain down to which to verify.
        self.verifyDepth = 1

        # If True, do not allow anonymous sessions.
        self.requireCertification = True

        # If True, do not re-verify the certificate on session resumption.
        self.verifyOnce = True

        # If True, generate a new key whenever ephemeral DH parameters are used
        # to prevent small subgroup attacks.
        self.enableSingleUseKeys = True

        # If True, set a session ID on each context. This allows a shortened
        # handshake to be used when a known client reconnects.
        self.enableSessions = True

        # If True, enable various non-spec protocol fixes for broken
        # SSL implementations.
        self.fixBrokenPeers = False

        # Get the client context factory
        ctx = ssl.ClientContextFactory.getContext(self)

        # Load certificate
        try:
            ctx.use_certificate_file(self.crt)

        except SSL.Error as exception:
            Logger.error("SSLCONTEXT: "+exception.message[0][2])
            raise SSLCertReadError(self.crt)

        else:
            Logger.info("SSLCONTEXT: Loaded Peer SSL Certificate.")

        # Load private key
        try:
            ctx.use_privatekey_file(self.key)

        except SSL.Error as exception:
            Logger.error("SSLCONTEXT"+exception.message[0][2])
            raise SSLKeyReadError(self.key)

        else:
            Logger.info("SSLCONTEXT: Loaded Peer SSL key.")

        # Set verify mode and verify callback chain.
        ctx.set_verify(
            SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
            self.verifyCallback
        )

        # Since we have self-signed certs we have to explicitly
        # tell the server to trust them.
        ctx.load_verify_locations(self.ca)

        return ctx
コード例 #40
0
 def buy(self, sku, callbacks=None):
     Logger.info("Billing: buy attempt %s" % sku)
     self.callbacks = callbacks
     if sku in self.get_purchased_items():
         Logger.error("Billing: attempt to buy already bought product...")
         raise AlreadyBoughtException()
コード例 #41
0
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

from typing import Dict
from kivy import Logger
import ORCA.Globals as Globals

try:
    import netifaces
except Exception as ex:
    Logger.error("Can't load netifaces:" + str(ex))

__all__ = ['GetGatewayV4']


def GetGatewayV4() -> str:

    uFamily: str = u'AF_INET'
    iInet_num: int

    try:
        iInet_num = getattr(netifaces, uFamily)
        dGateways: Dict = netifaces.gateways()
        # noinspection PyTypeChecker
        uIP = dGateways['default'][iInet_num][0]
    except Exception as e:
コード例 #42
0
ファイル: manager.py プロジェクト: vaizguy/cryptikchaos
    def unpack_stream(self, stream, shared_key=None):
        "Unpack serial data into stream."

        # Decompress data stream
        if constants.ENABLE_COMPRESSION:
            Logger.info("STREAM: Decompressing Stream...")
            stream = decompress(stream)

        # Check if data is of expected chunk size
        if len(stream) != constants.STREAM_SIZE_AUTH_BLOCK and \
           len(stream) != constants.STREAM_SIZE_MSG_BLOCK:
            raise StreamOverflowError()

        if len(stream) == constants.STREAM_SIZE_AUTH_BLOCK:
            Logger.info("STREAM: Unpacking Authentication Stream...")

            # Unpack auth stream to variables
            (
                stream_flag,
                stream_type,
                stream_content,
                stream_token,
                stream_hmac
            ) = struct.unpack(
                "!?{}s{}s{}s{}s".format(
                    constants.STREAM_TYPE_LEN,
                    constants.STREAM_CONTENT_LEN,
                    constants.STREAM_PEER_KEY_LEN,
                    constants.STREAM_CHKSUM_LEN
                ), stream
            )

        elif len(stream) == constants.STREAM_SIZE_MSG_BLOCK:
            Logger.info("STREAM: Unpacking Message Stream...")

            # Unpack msg block stream to variables
            (
                stream_flag,
                stream_type,
                stream_content,
                stream_token,
                stream_hmac
            ) = struct.unpack(
                "!?{}s{}s{}s{}s".format(
                    constants.STREAM_TYPE_LEN,
                    constants.STREAM_CONTENT_LEN,
                    constants.STREAM_TOKEN_LEN,
                    constants.STREAM_CHKSUM_LEN
                ), stream
            )

        else:
            Logger.error("STREAM: Invalid Stream Length received.")
            return [None] * 3

        # Remove all null characters if present
        stream_content = stream_content.rstrip('\0')
        stream_token = stream_token.rstrip('\0')

        # Get  uid
        stream_uid = generate_uuid(self.peer_host)

        # Get stream object
        stream_obj = Stream(
            stream_uid,
            stream_flag,
            stream_type,
            stream_content,
            stream_token,
        )

        # Add stream to store
        self.add_store(stream_uid, stream_obj.dict)

        # Verify stream integrity
        if not self.check_hmac(stream_uid, stream_hmac):
            Logger.error("STREAM: Stream Checksum mismatch.")
            return [None] * 3

        # Check stream signing mode
        if stream_flag == STREAM_TYPES.UNAUTH:
            # Stream key is peer public key
            pass

        elif stream_flag == STREAM_TYPES.AUTH:
            # Generate token at destination side
            # Perform key challenge
            if generate_token(stream_uid, shared_key) != stream_token:
                Logger.error("STREAM: Token challenge Fail!")
                Logger.error("STREAM: RCVD: {}".format(b64encode(stream_token)))
                Logger.error("STREAM: EXPD: {}".format(b64encode(generate_token(stream_uid, shared_key))))
                return [None] * 3
            else:
                Logger.info("STREAM: Token challenge Pass!")

            # AES Decryption
            if constants.AES_AVAILABLE:
                Logger.info("STREAM: Decrypting content...")
                # Generate iv from stream token
                iv = md5hash(stream_token, hexdigest=False)
                # Create AES object
                AES_obj = AES.new(shared_key, AES.MODE_CBC, iv)
                # Decrypt content
                stream_content = AES_obj.decrypt(stream_content)
                # Upad decrypted content
                stream_content = self.unpad(stream_content)
                
        def pkey_action(val):
            
            val = md5hash(val)
            return val               
        
        if stream_flag == STREAM_TYPES.UNAUTH:
            Logger.debug("""STREAM: Unpacking: \n{}""".format(
                self.storage_table(shorten_len=64, action_dict={"STREAM_PKEY":pkey_action}) ))
            
        Logger.debug("""DEBUG STREAM:
        FLAG: {}
        TYPE: {}
        CONTENT: {}
        KEY: {}
        CHECKSUM: {}
        """.format(
                self.get_store_item(stream_uid, 'STREAM_FLAG'),
                self.get_store_item(stream_uid, 'STREAM_TYPE'),
                stream_content,
                b64encode(self.get_store_item(stream_uid, 'STREAM_PKEY')),
                self.get_store_hmac(stream_uid)))

        # Unshuffle contentself._storage[sid].hmac()
        if constants.ENABLE_SHUFFLE:
            Logger.info("STREAM: Unscrambling content...")

            stream_content = unshuffler(
                shuffled_string=stream_content,
                iterations=constants.STREAM_CONT_SHUFF_ITER
            )

        if stream_flag == STREAM_TYPES.UNAUTH:
            Logger.info("STREAM: Successfully unpacked AUTH Stream.")
            return (self.get_store_item(stream_uid, "STREAM_TYPE"),
                    self.get_store_item(stream_uid, "STREAM_CONTENT"),
                    bytes_to_num(
                        self.get_store_item(stream_uid, "STREAM_PKEY")
                    ))

        elif stream_flag == STREAM_TYPES.AUTH:
            Logger.info("STREAM: Successfully unpacked MSG Stream.")
            return (self.get_store_item(stream_uid, "STREAM_TYPE"),
                    stream_content,
                    self.get_store_item(stream_uid, "STREAM_PKEY"))

        else:
            Logger.info("STREAM: Unpack of stream unsuccessfull.")
            return [None] * 3
コード例 #43
0
ファイル: manager.py プロジェクト: vaizguy/cryptikchaos
    def pack_stream(self, stream_type, stream_content, stream_host,
                    stream_flag=STREAM_TYPES.AUTH, shared_key=None):
        "Pack data into stream."

        # Check length of content.
        if len(stream_content) > constants.STREAM_CONTENT_LEN:
            raise StreamOverflowError(constants.STREAM_CONTENT_LEN)

        # Check length of capsule type.
        if len(stream_type) > constants.STREAM_TYPE_LEN:
            raise StreamOverflowError(constants.STREAM_TYPE_LEN)

        # Generate uid
        stream_uid = generate_uuid(stream_host)
        # Stream type
        stream_type = stream_type.upper()
        # Stream peer key
        stream_token = None
        
        #For testing
        _debug_stream_content = stream_content

        # Shuffle content
        if constants.ENABLE_SHUFFLE:
            Logger.info("STREAM: Scrambling content...")

            stream_content = shuffler(
                string=stream_content,
                iterations=constants.STREAM_CONT_SHUFF_ITER
            )

        # Check stream signing mode
        if stream_flag == STREAM_TYPES.UNAUTH:
            # Stream key is peer key
            # NOTE peer public key is sent during
            # authentication.
            stream_token = num_to_bytes(self.public_key)

        elif stream_flag == STREAM_TYPES.AUTH:
            # Generate token at source side
            stream_token = generate_token(stream_uid, shared_key)

            # AES Encryption
            if constants.AES_AVAILABLE:
                Logger.info("STREAM: Encrypting content...")
                # Generate iv from stream token
                iv = md5hash(stream_token, hexdigest=False)
                # Create AES object
                AES_obj = AES.new(shared_key, AES.MODE_CBC, iv)
                # Pad string
                stream_content = self.pad(stream_content)
                # Encrypt string
                stream_content = AES_obj.encrypt(stream_content)

        # Create stream object
        stream_obj = Stream(
            stream_uid,
            stream_flag,
            stream_type,
            stream_content,
            stream_token,
        )

        # Add stream to store
        self.add_store(
            stream_uid, stream_obj.dict
        )

        if stream_flag == STREAM_TYPES.UNAUTH:
            Logger.info("STREAM: Packing Authentication Stream...")

            # Pack store into authentication stream
            stream = struct.pack(
                "!?{}s{}s{}s{}s".format(
                    constants.STREAM_TYPE_LEN,
                    constants.STREAM_CONTENT_LEN,
                    constants.STREAM_PEER_KEY_LEN,
                    constants.STREAM_CHKSUM_LEN
                ),
                self.get_store_item(stream_uid, 'STREAM_FLAG'),
                self.get_store_item(stream_uid, 'STREAM_TYPE'),
                self.get_store_item(stream_uid, 'STREAM_CONTENT'),
                self.get_store_item(stream_uid, 'STREAM_PKEY'),
                self.get_store_hmac(stream_uid)
            )

        elif stream_flag == STREAM_TYPES.AUTH:
            Logger.info("STREAM: Packing Message Stream...")

            # Pack store into message block stream
            stream = struct.pack(
                "!?{}s{}s{}s{}s".format(
                    constants.STREAM_TYPE_LEN,
                    constants.STREAM_CONTENT_LEN,
                    constants.STREAM_TOKEN_LEN,
                    constants.STREAM_CHKSUM_LEN
                ),
                self.get_store_item(stream_uid, 'STREAM_FLAG'),
                self.get_store_item(stream_uid, 'STREAM_TYPE'),
                self.get_store_item(stream_uid, 'STREAM_CONTENT'),
                self.get_store_item(stream_uid, 'STREAM_PKEY'),
                self.get_store_hmac(stream_uid)
            )

        else:
            Logger.error("STREAM: Invalid Stream Flag received.")
            return None
        
        def pkey_action(val):
            
            val = md5hash(val)
            return val
            
        if stream_flag == STREAM_TYPES.UNAUTH:
            Logger.debug("""STREAM: Packing: \n{}""".format(
                self.storage_table(shorten_len=64, action_dict={"STREAM_PKEY":pkey_action}) ))
        
        Logger.debug("""DEBUG STREAM:
        FLAG: {}
        TYPE: {}
        CONTENT: {}
        KEY: {}
        CHECKSUM: {}
        """.format(
                self.get_store_item(stream_uid, 'STREAM_FLAG'),
                self.get_store_item(stream_uid, 'STREAM_TYPE'),
                _debug_stream_content,
                b64encode(self.get_store_item(stream_uid, 'STREAM_PKEY')),
                self.get_store_hmac(stream_uid)))

        # Compress stream
        if constants.ENABLE_COMPRESSION:
            Logger.info("STREAM: Compressing Stream...")
            stream = compress(stream)

        Logger.info("STREAM: Succesfully packed stream.")
        return stream
コード例 #44
0
 def initialize(self):
     super(AndroidFacebookManager, self).initialize()
     try:
         FacebookSdk.sdkInitialize(python_activity.getApplicationContext())
     except JavaException as ex:
         Logger.error("Facebook Android: %s" % ex)