Esempio n. 1
0
def mode(mode_switch=11):
    """

    :type mode_switch: int
    """

    if mode_switch == 11:
        user = user_data()
        username = '******'
        passwords_limit = 1000000
        brute_force(username, user_specific_credential_generator(user),
                    passwords_limit)

    if mode_switch == 12:
        user = user_data()
        brute_force(user_specific_credential_generator(user),
                    user_specific_credential_generator(user), 1000000)

    elif mode_switch == 21:
        username = config.get('login')
        passwords_limit = 10000
        # file_path = 'resources/10-million-password-list-top-1000000.txt'
        file_path = 'resources/10k-most-common.txt'
        brute_force(username, common_password_generator(file_path),
                    passwords_limit)

    elif mode_switch == 22:
        username = config.get('login')
        passwords_limit = 10000
        brute_force(username, PickupCommon(file_path), passwords_limit)

    elif mode_switch == 3:
        username = config.get('login')
        brute_force(username, password_generator(), 100000)
Esempio n. 2
0
    def run(self):
        if config.get("codeEnabled"):
            vscode.switch_to_dark()

        if config.get("atomEnabled"):
            atom.switch_to_dark()

        if config.get("kdeEnabled"):
            kde.switch_to_dark()

        if config.get("wallpaperEnabled"):
            wallpaper.switch_to_dark()

        # kde support
        if config.get("gtkEnabled") and config.get("desktop") == "kde":
            gtkkde.switch_to_dark()

        # gnome and budgie support
        if config.get("gtkEnabled") and config.get("desktop") == "gtk":
            gtk.switch_to_dark()

        # gnome-shell
        if config.get("gnomeEnabled"):
            gnome.switch_to_dark()

        # firefox support
        if config.get("firefoxEnabled"):
            firefox.switch_to_dark()
        play_sound("/assets/dark.wav")
Esempio n. 3
0
def authAPI():
    config = src.config.readConfig()
    u = flask.request.args.get("u")  # USERNAME
    p = flask.request.args.get("p")  # PASSWORD
    a = flask.request.args.get("a")  # AUTH
    rules = flask.request.args.get("rules") # RULES
    if config.get("auth") == False:
        return (
            flask.jsonify(
                {
                    "success": {
                        "code": 200,
                        "content": "/browse",
                        "message": "Authentication completed successfully!",
                    }
                }
            ),
            200,
        )
    elif rules == "signup":
        return (
            flask.jsonify(
                {
                    "success": {
                        "code": 202,
                        "conntent": config.get("signup"),
                        "message": "Signup is available on this server.",
                    }
                }
            ),
            202,
        )
    elif any(u == account["username"] for account in config["account_list"]) and any(
        p == account["password"] for account in config["account_list"]
    ):
        account = next(
            (
                i
                for i in config["account_list"]
                if i["username"] == u and i["password"] == p
            ),
            None,
        )
        return flask.jsonify(account)
    elif any(a == account["auth"] for account in config["account_list"]):
        account = next((i for i in config["account_list"] if i["auth"] == a), None)
        return flask.jsonify(account)
    else:
        return (
            flask.jsonify(
                {
                    "error": {
                        "code": 401,
                        "message": "The username and/or password provided was incorrect.",
                    }
                }
            ),
            401,
        )
Esempio n. 4
0
def send_config(plugin: str) -> dict:
    """
    Returns the configuration for the plugin plus some general necessary stuff (scheduled, dark_mode, times)
    :param plugin: the plugin for which the configuration should be returned
    :return: a dictionary containing config information
    """
    logger.debug('Building message')

    enabled = config.get(plugin + 'Enabled')
    message = {'enabled': enabled, 'dark_mode': config.get('theme') == 'dark'}

    if enabled:
        mode: str
        if config.get('schedule'):
            mode = 'schedule'
        elif config.get('followSun'):
            mode = 'followSun'
        else:
            mode = 'manual'

        message['scheduled'] = mode != 'manual'
        message['themes'] = [
            config.get(plugin + 'LightTheme'),
            config.get(plugin + 'DarkTheme')
        ]
        if message['scheduled']:
            # time string is parsed to time object
            time_light = datetimetime.fromisoformat(config.get('switchToDark'))
            time_dark = datetimetime.fromisoformat(config.get('switchToLight'))
            time_now = datetime.now()

            message['times'] = _move_times(time_now, time_light, time_dark)

    return message
Esempio n. 5
0
def main():
    # using ArgumentParser for parsing arguments
    parser = ArgumentParser()
    parser.add_argument("-t",
                        "--toggle",
                        help="toggles Yin-Yang",
                        action="store_true")
    parser.add_argument("-s",
                        "--schedule",
                        help="schedule theme toggle, starts daemon in bg",
                        action="store_true")
    args = parser.parse_args()

    # Check and see if there are new keys we need to add to the config.
    should_update_config = assembly_version != config.get_version()
    if should_update_config:
        update_config()

    # checks whether $ yin-yang is ran without args
    if len(sys.argv) == 1 and not args.toggle:
        # load GUI
        app = QtWidgets.QApplication(sys.argv)
        window = gui.MainWindow()
        window.show()
        sys.exit(app.exec_())

    # checks whether the script should be ran as a daemon
    if args.schedule:
        config.update("running", False)
        print("START thread listener")

        if config.get("followSun"):
            # calculate time if needed
            config.set_sun_time()

        if config.get("schedule"):
            yin_yang.start_daemon()
        else:
            print("looks like you did not specified a time")
            print("You can use the gui with yin-yang -gui")
            print(
                "Or edit the config found in ~/.config/yin_yang/yin_yang.json")
            print(
                "You need to set schedule to True and edit the time to toggles"
            )

    # gui is set as parameter
    if args.toggle:
        toggle_theme()
Esempio n. 6
0
def switch_to_light():
    wallpaper_light = config.get("wallpaperLightTheme")

    if wallpaper_light == "":
        subprocess.run(["notify-send", "looks like no light wallpaper is set"])
    else:
        if config.get("desktop") == "kde":
            subprocess.run([
                "sh", "/opt/yin-yang/src/change_wallpaper.sh", wallpaper_light
            ])
        if config.get("desktop") == "gtk":
            subprocess.run([
                "gsettings", "set", "org.gnome.desktop.background",
                "picture-uri", "file://" + wallpaper_light
            ])
Esempio n. 7
0
def main(limit, names):

    # logs
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    logging.basicConfig(filename=config.get('log', 'filename'), level=logging.DEBUG, format='%(asctime)s %(message)s')

    # récupérer les différents éléments présent sur le serveur
    rows = find_rows(config, config.get('server', 'uri'))
    elements = parse_rows(config, config.get('server', 'uri'), rows)

    # filtrer les éléments à télécharger
    elements = filter_medias(config, elements, limit, names)

    # téléchargement
    update_medias(config, elements)
Esempio n. 8
0
def main():
    # using ArgumentParser for parsing arguments
    parser = ArgumentParser()
    parser.add_argument("-t",
                        "--toggle",
                        help="toggles Yin-Yang",
                        action="store_true")
    parser.add_argument("-s",
                        "--schedule",
                        help="schedule theme toggle, starts daemon in bg",
                        action="store_true")
    args = parser.parse_args()

    # checks whether $ yin-yang is ran without args
    if len(sys.argv) == 1 and not args.toggle:
        # load GUI
        app = QtWidgets.QApplication(sys.argv)
        window = gui.MainWindow()
        window.show()
        sys.exit(app.exec_())

    # checks whether the script should be ran as a daemon
    if args.schedule:
        config.update("running", False)
        logger.debug("START thread listener")

        if config.get("followSun"):
            # calculate time if needed
            config.set_sun_time()

        if config.get("schedule"):
            yin_yang.start_daemon()
        else:
            logger.warning(
                "Tried to start scheduler, but schedule was not enabled.")
            print(
                "Looks like you have not specified a time."
                "You can use the GUI by running Yin & Yang or "
                "edit the config found in ~/.config/yin_yang/yin_yang.json."
                "You need to set schedule to true and edit the time to toggles."
            )

    if args.toggle:
        # terminate any running instances
        config.update("running", False)
        config.update("followSun", False)
        config.update("schedule", False)
        toggle_theme()
Esempio n. 9
0
def password_generator():
    alphabet = string.digits
    alphabet += string.ascii_lowercase
    base = len(alphabet)

    shift = 0
    length = int(config.get('minimal_password_length'))

    while True:
        password = ''
        temp = shift
        while temp > 0:
            k = temp // base
            rest = temp % base
            password = alphabet[rest] + password
            temp = k

        while len(password) < length:
            password = alphabet[0] + password

        yield password

        if alphabet[-1] * length == password:
            length += 1
            shift = 0
        else:
            shift += 1
Esempio n. 10
0
def switch_to_dark():
    code_theme = config.get("codeDarkTheme")
    possible_editors = [
        path + "/VSCodium/User/settings.json",
        path + "/Code - OSS/User/settings.json",
        path + "/Code/User/settings.json",
        path + "/Code - Insiders/User/settings.json",
    ]

    for editor in possible_editors:
        if os.path.isfile(editor):
            # getting the old theme to replace it
            with open(editor, "r") as sett:
                try:
                    settings = json.load(sett)
                except json.decoder.JSONDecodeError:
                    settings = {}
                    settings["workbench.colorTheme"] = ""
                    write_new_settings(settings, editor)
                try:
                    old_theme = settings["workbench.colorTheme"]
                except KeyError:
                    # happens when the default theme in vscode is used
                    write_new_settings(settings, editor)
            inplace_change(editor, old_theme, code_theme)
Esempio n. 11
0
def environmentAPI():
    config = src.config.readConfig()
    a = flask.request.args.get("a")  # AUTH
    if (
        any(a == account["auth"] for account in config["account_list"])
        or config.get("auth") == False
    ):
        account = next((i for i in config["account_list"] if i["auth"] == a), None)
        if account:
            if account.get("whitelist"):
                category_list = []
                for category in config["category_list"]:
                    if any(
                        category["id"] == whitelist for whitelist in account["whitelist"]
                    ):
                        category_list.append(category)
                    else:
                        pass
                tmp_environment = {
                    "account_list": account,
                    "category_list": category_list,
                }
                return flask.jsonify(tmp_environment)
            else:
                tmp_environment = {
                    "account_list": account,
                    "category_list": config["category_list"],
                }
                return flask.jsonify(tmp_environment)
        else:
            tmp_environment = {
                "account_list": {"pic": "k"},
                "category_list": config["category_list"],
            }
            return flask.jsonify(tmp_environment)
Esempio n. 12
0
def should_be_light():
    # desc: return if the Theme should be light
    # returns: True if it should be light
    # returns: False if the theme should be dark

    d_hour = int(config.get("switchToDark").split(":")[0])
    d_minute = int(config.get("switchToDark").split(":")[1])
    l_hour = int(config.get("switchToLight").split(":")[0])
    l_minute = int(config.get("switchToLight").split(":")[1])
    hour = datetime.datetime.now().time().hour
    minute = datetime.datetime.now().time().minute

    if (hour >= l_hour and hour < d_hour):
        return not (hour == l_hour and minute <= l_minute)
    else:
        return hour == d_hour and minute <= d_minute
Esempio n. 13
0
File: gtk.py Progetto: yeus/Yin-Yang
def switch_to_dark():
    gtk_theme = config.get("gtkDarkTheme")
    # uses a kde api to switch to a dark theme
    subprocess.run([
        "gsettings", "set", "org.gnome.desktop.interface", "gtk-theme",
        gtk_theme
    ])  # Applications theme
Esempio n. 14
0
    def run(self):
        while True:

            if terminate:
                config.update("running", False)
                break

            if not config.is_scheduled():
                config.update("running", False)
                break

            editable = config.get_config()

            theme = config.get("theme")

            if should_be_light():
                if theme == "light":
                    time.sleep(30)
                    continue
                else:
                    switch_to_light()
            else:
                if theme == "dark":
                    time.sleep(30)
                    continue
                else:
                    switch_to_dark()

            time.sleep(30)
Esempio n. 15
0
def switch_to_light():
    spotify_theme = config.get("spotifyLightTheme")
    if spotify_theme:
        subprocess.run(['spicetify', 'config', 'current_theme', 'Dribbblish', 'color_scheme', spotify_theme]) # Shell theme
        subprocess.run(['spicetify', 'apply'])
        sleep(2.5)
        subprocess.run(['spotify'])
Esempio n. 16
0
def configAPI():
    config = src.config.readConfig()
    if flask.request.method == "GET":
        secret = flask.request.args.get("secret")
        if secret == config.get("secret_key"):
            return flask.jsonify(config), 200
        else:
            return (
                flask.jsonify({
                    "error": {
                        "code": 401,
                        "message": "The secret key provided was incorrect.",
                    }
                }),
                401,
            )
    elif flask.request.method == "POST":
        secret = flask.request.args.get("secret")
        if secret == None:
            secret = ""
        if secret == config.get("secret_key"):
            data = flask.request.json
            data["token_expiry"] = str(datetime.datetime.utcnow())
            if data.get("category_list") != config.get("category_list"):
                src.config.updateConfig(data)
                threaded_metadata()
            else:
                src.config.updateConfig(data)
            return (
                flask.jsonify({
                    "success": {
                        "code": 200,
                        "message": "libDrive is updating your config",
                    }
                }),
                200,
            )
        else:
            return (
                flask.jsonify({
                    "error": {
                        "code": 401,
                        "message": "The secret key provided was incorrect.",
                    }
                }),
                401,
            )
Esempio n. 17
0
File: gtk.py Progetto: yeus/Yin-Yang
def switch_to_light():
    gtk_theme = config.get("gtkLightTheme")
    # gtk_theme = "Default"
    # uses a kde api to switch to a light theme
    subprocess.run([
        "gsettings", "set", "org.gnome.desktop.interface", "gtk-theme",
        gtk_theme
    ])  # Applications theme
Esempio n. 18
0
def downloadRedirectAPI(name):
    id = flask.request.args.get("id")
    itag = flask.request.args.get("itag")

    config = src.config.readConfig()
    if (datetime.datetime.strptime(
            config.get("token_expiry", datetime.datetime.utcnow()),
            "%Y-%m-%d %H:%M:%S.%f",
    ) <= datetime.datetime.utcnow()):
        config, drive = src.credentials.refreshCredentials(config)

    tmp_metadata = src.metadata.jsonExtract(src.metadata.readMetadata(config),
                                            "id", id, False)
    if tmp_metadata:
        name = tmp_metadata.get("name", name)
    args = "?"
    for arg in flask.request.args:
        args += "%s=%s&" % (arg, flask.request.args[arg])
    session = {"access_token": config.get("access_token")}

    session[
        "url"] = "https://www.googleapis.com/drive/v3/files/%s?alt=media" % (
            id)
    if itag and itag != "" and config.get("transcoded") == True:
        req = requests.get(
            "https://drive.google.com/get_video_info?docid=%s" % (id),
            headers={
                "Authorization": "Bearer %s" % (config.get("access_token"))
            },
        )
        parsed = urllib.parse.parse_qs(urllib.parse.unquote(req.text))
        if parsed.get("status") == ["ok"]:
            for stream in parsed["url"]:
                if ("itag=%s" % (itag)) in stream:
                    url = stream
                    break
            cookie_string = "; ".join(
                [str(x) + "=" + str(y) for x, y in req.cookies.items()])
            session["cookie"] = cookie_string
            session["transcoded"] = config.get("transcoded")
            session["url"] = url

    sessionB64 = base64.b64encode(
        json.dumps(session).encode("ascii")).decode("ascii")

    if config.get("cloudflare") and config.get("cloudflare") != "":
        return flask.redirect(
            config.get("cloudflare") + "/api/v1/download/%s%ssession=%s&" %
            (name, args, sessionB64),
            code=302,
        )
    else:
        return flask.redirect("/api/v1/download/%s%ssession=%s&" %
                              (name, args, sessionB64),
                              code=302)
Esempio n. 19
0
def switch_to_dark():
    # get theme out of config
    atom_theme = config.get("atomDarkTheme")

    # getting the old theme first
    current_theme = get_old_theme(path + "config.cson")

    # updating the old theme with theme specfied in config
    inplace_change(path + "config.cson", current_theme, atom_theme)
Esempio n. 20
0
 def __init__(self):
     desktop = config.get('desktop')
     if desktop == 'kde':
         self._strategy_instance = _Kde()
     elif desktop == 'gtk':
         self._strategy_instance = _Gnome()
     else:
         raise ValueError('Unsupported desktop environment!')
     super().__init__()
Esempio n. 21
0
 def run(self):
     if config.get("codeEnabled"):
         vscode.switch_to_light()
     if config.get("atomEnabled"):
         atom.switch_to_light()
     if config.get("kdeEnabled"):
         kde.switch_to_light()
     if config.get("wallpaperEnabled"):
         wallpaper.switch_to_light()
     if config.get("gtkEnabled") and config.get("desktop") == "kde":
         gtkkde.switch_to_light()
     if config.get("gtkEnabled") and config.get("desktop") == "gtk":
         gtk.switch_to_light()
     if config.get("gnomeEnabled"):
         gnome.switch_to_light()
     if config.get("firefoxEnabled"):
         firefox.switch_to_light()
     play_sound("./assets/light.wav")
Esempio n. 22
0
def archive_course():
    database = DataBase()
    data, data_ok = SlackCommandUtils.read_data(request=request,
                                                text_tokens_length=1)
    if not data_ok:
        return 'Invalid request format', 400
    response = requests.post(default_protocol + '://' +
                             config.get('flask_address') + ':' +
                             config.get('flask_port') +
                             '/ui/channel/archive?tag=' + data['text'][1:])
    success_flag = response.status_code == 200
    slack_command_log = SlackCommandUtils.create_slack_command_log(
        data, success_flag)
    database.insert(slack_command_log)
    if success_flag:
        return '', 200
    else:
        return 'Error has occurred while archiving the channel', 500
Esempio n. 23
0
    def get_rates_by_date(requested_date: str = None):
        """requested_date parameter must be in YYYYMMDD format"""

        if requested_date is None:
            requested_date = date.today().strftime("%Y%m%d")

        response = requests.get(url=config.get(
            'API', 'EXCHANGE_RATES_ENDPOINT').format(requested_date))

        return json.loads(response.content), requested_date
Esempio n. 24
0
    def test_dark_mode_detection(self):
        time_light = config.get('switchToLight')
        time_light = time.fromisoformat(time_light)
        time_dark = config.get('switchToDark')
        time_dark = time.fromisoformat(time_dark)

        # get unix times
        time_current = datetime.today()
        time_light_unix, time_dark_unix = communicate._move_times(
            time_current, time_light, time_dark)

        is_dark = not should_be_light()
        # NOTE: this should be equal to how the extension calculates the theme
        detected_dark = should_be_dark_extensions(
            int(time_current.timestamp()), time_dark_unix)

        self.assertEqual(
            is_dark, detected_dark,
            f'Dark mode should be {"active" if is_dark else "inactive"} at {time_current.isoformat()}'
        )
Esempio n. 25
0
def switch_to_light():
    # get theme out of config
    atom_theme = config.get("atomLightTheme")

    # getting the old theme first
    current_theme = get_old_theme(path+"config.cson")

    # check if already used
    if atom_theme != current_theme:
        # updating the old theme with theme specfied in config
        inplace_change(path+"config.cson", current_theme, atom_theme)
Esempio n. 26
0
def switch_to_dark():
    gtk_theme = config.get("gtkDarkTheme")
    # uses a kde api to switch to a dark theme
    subprocess.run([
        "gsettings", "set", "org.gnome.desktop.interface", "gtk-theme",
        gtk_theme
    ])  # Applications theme
    subprocess.run([
        "gsettings", "set", "org.gnome.shell.extensions.user-theme", "name",
        '"{}"'.format(gtk_theme)
    ])  # Shell theme
Esempio n. 27
0
    def send_notification(user_token: str):
        notification = {
            'data': {
                'notification': {
                    'title': 'Hello',
                    'body': 'How are you?'
                 }
            },
           'to': user_token
        }

        response = requests.post(
            url=config.get('API', 'FIREBASE_NOTIFICATION_ENDPOINT_URL'),
            data=json.dumps(notification),
            headers={
                'Authorization': 'key='+config.get('API', 'FIREBASE_NOTIFICATION_ENDPOINT_KEY'),
                'Content-Type': 'application/json'
            }
        )

        return response
Esempio n. 28
0
def update_medias(config, elements):
    
    for medias in elements:
        fileout = os.path.join(config.get('directory', 'downloads'), medias[2])

        with request_server(config, medias[1], stream=True) as req:
            req.raise_for_status()
            with open(fileout, 'wb') as openfile:
                for chunk in req.iter_content(chunk_size=config.getint('download', 'chunk_size')):
                    openfile.write(chunk)
                    if config.getint('download', 'test') == 1:
                        break
                add_to_already_downloaded(config, medias)
Esempio n. 29
0
def should_be_light():
    # desc: return if the Theme should be light
    # returns: True if it should be light
    # returns: False if the theme should be dark

    d_hour = int(config.get("switchToDark").split(":")[0])
    d_minute = int(config.get("switchToDark").split(":")[1])
    l_hour = int(config.get("switchToLight").split(":")[0])
    l_minute = int(config.get("switchToLight").split(":")[1])
    hour = datetime.datetime.now().time().hour
    minute = datetime.datetime.now().time().minute

    # if light comes before dark (True if 00:00 -> light -> dark -> 23:59)
    if l_hour < d_hour or (l_hour == d_hour and l_minute < d_minute):
        if hour >= l_hour and hour < d_hour:
            return not (hour == l_hour and minute <= l_minute)
        else:
            return hour == d_hour and minute <= d_minute
    else:
        # same as above, but checks for dark and inverts the result
        if hour >= d_hour and hour < l_hour:
            return hour == d_hour and minute <= d_minute
        else:
            return not (hour == l_hour and minute <= l_minute)
Esempio n. 30
0
def signupAPI():
    config = src.config.readConfig()
    u = flask.request.args.get("u")  # USERNAME
    p = flask.request.args.get("p")  # PASSWORD
    if config.get("signup"):
        if any(u == account["username"] for account in config["account_list"]):
            return (
                flask.jsonify(
                    {
                        "error": {
                            "code": 409,
                            "message": "An account with this username already exists.",
                        }
                    }
                ),
                409,
            )
        else:
            auth = "".join(
                random.choices("abcdefghijklmnopqrstuvwxyz" + "0123456789", k=50)
            )
            account = {"username": u, "password": p, "pic": "", "auth": auth}
            config["account_list"].append(account)
            src.config.updateConfig(config)
            return (
                flask.jsonify(
                    {
                        "success": {
                            "code": 200,
                            "content": account,
                            "message": "Registration successful!",
                        }
                    }
                ),
                200,
            )
    else:
        return (
            flask.jsonify(
                {
                    "error": {
                        "code": 401,
                        "message": "This server has disabled user sign up.",
                    }
                }
            ),
            401,
        )