Esempio n. 1
0
def regenerate_all_slideshows():
    utils.print_warning(
        "This takes a LONG time, best to start this after school to let it run for few hours!"
    )

    do_it = utils.confirm(
        "Are you sure you want to recreate all the slideshow videos?",
        yes_is_default=False)

    if not do_it:
        return

    # connects and checks to see if file with the same name already exisits
    ssh_connection = SSH(TV_FILE_SERVER, TV_FILE_SERVER_USER,
                         TV_FILE_SERVER_PW)

    print("Updating movie maker script...")
    copy_movie_maker_to_host(ssh_connection)

    # Cycle through TV directories
    for tv in range(1, 5):
        filepath = "{}/tv{}/".format(TV_ROOT, tv)
        command = 'ls {}'.format(filepath)
        dir_contents = ssh_connection.send_cmd(command,
                                               print_stdout=False).split()

        for student_number in dir_contents:

            # TODO: check if it's a directory or not, skip non-directories
            test_dir_cmd = "test -d {}{}{} || echo nope".format(
                filepath, os.sep, student_number)
            not_a_dir = ssh_connection.send_cmd(test_dir_cmd,
                                                print_stdout=False)
            # note this is an empty string if dir exists
            if not_a_dir:
                continue  # skip to next one

            utils.print_success("Found art folder for {} on TV# {}".format(
                student_number, tv))

            # refresh the video
            utils.print_warning(
                "\nGonna regenerate video slideshow now, THIS MIGHT TAKE A WHILE!"
            )
            generate_new_movie_file(ssh_connection,
                                    student_number,
                                    tv,
                                    silent=True)

        utils.print_success("\nFinished TV #{}\n".format(tv))

    utils.print_success("Done!")
def grant_user_docker_access():

    fullname, username = user_utils.get_and_confirm_user()
    if not fullname:
        return False

    if not utils.confirm(
            f"Confirm you want to add {fullname} to the {GROUP} group?"):
        return False

    success = user_utils.add_user_to_group(username, GROUP)

    return success
def change_username(current_username=None,
                    new_username=None,
                    auto=False,
                    password=None):

    utils.print_warning(
        "\nMake sure the student is logged out before making this change!\n")

    if not current_username:
        fullname, current_username = user_utils.get_and_confirm_user()
        if not fullname:
            return False

    if not new_username:
        new_username = user_utils.get_new_username()
    if not new_username:
        return False

    if not auto:
        if not utils.confirm(
                f"Confirm you want to change {current_username} to {new_username}?",
                yes_is_default=False):
            print("Bailing...")
            return False

    if not password:
        password = getpass("Enter the admin password: "******"sudo ldaprenameuser {} {}".format(current_username,
                                                 new_username)
    ssh_connection.send_cmd(command, sudo=True)
    ssh_connection.close()

    utils.print_warning(
        "Now gonna change the name of their home directory to match the new username"
    )

    ssh_connection = SSH(file_hostname, username, password)
    command = "mv /nfshome/{} /nfshome/{}".format(current_username,
                                                  new_username)
    ssh_connection.send_cmd(command, sudo=True)
    ssh_connection.close()
    utils.print_success("Done!")

    utils.print_warning("Now gonna tell LDAP where the new home directory is")

    user_utils.modify_user(new_username,
                           {'homeDirectory': f'/home/{new_username}'},
                           password)

    return True
def grant_user_color_printer():

    fullname, username = user_utils.get_and_confirm_user()
    if not fullname:
        return False

    if not utils.confirm(
            f"Confirm you want to give {fullname} the ability to use the color printer?"
    ):
        return False

    success = user_utils.add_user_to_group(username, COLORPRINTER_GROUP)

    return success
def grant_user_advanced_usb_access():

    fullname, username = user_utils.get_and_confirm_user()
    if not fullname:
        return False

    if not utils.confirm(
            f"Confirm you want to add {fullname} to the dialout group? If they are unable to access a USB port for some advanced task, this might solve the problem."
    ):
        return False

    success = user_utils.add_user_to_group(username, USB_ACCESS_GROUP)

    return success
Esempio n. 6
0
def get_and_confirm_user(username=None):
    """ Ask for a username (if not provided) and checks if it exists. If it does, returns a tuple of
    (fullname, username), if it does not, will return None, username
    """
    if not username:
        username = utils.input_styled("Enter username: "******"I couldn't find an account for user {}.".format(username))
        return None, username
    else:
        utils.print_success("Found {}: {}.".format(username, fullname))
        is_correct_user = utils.confirm("Is this the correct student?", yes_is_default=False)

        if is_correct_user:
            return fullname, username
        else:
            return None, username
Esempio n. 7
0
def change_first_and_last_name():

    fullname, username = user_utils.get_and_confirm_user()
    if not fullname:
        return False

    print(
        "OK, let's do this! Please enter first and last names seperately. They will be converted to all upper case."
    )

    new_first = utils.input_styled(
        "What would you like to change their FIRST name to? ").upper()
    new_last = utils.input_styled(
        "What would you like to change their LAST name to? ").upper()

    confirmed = utils.confirm(
        f"Confirm you want to change {fullname} to {new_first} {new_last}?",
        yes_is_default=False)

    if not confirmed:
        print("Bailing...")
        return

    new_fullname = f"{new_first} {new_last}"

    ldif_changes_dict = {
        'gecos': new_fullname,
        'displayName': new_fullname,
        'cn': new_fullname,
        'sn': new_last,
        'givenName': new_first,
    }

    success = user_utils.modify_user(username, ldif_changes_dict)

    return success
Esempio n. 8
0
def add_new_title():

    fullname, username = user_utils.get_and_confirm_user()

    fullname = fullname.title()

    # gets info of the student who made the art
    fullname_entered = utils.input_plus("Full name", fullname)
    if fullname_entered:
        fullname = fullname_entered

    grad_year = utils.input_styled("Grad Year: \n")

    last_name = username.split(".")[-1].title(
    )  # get the last word if the username tyere.couture will get couture

    # https://pypi.org/project/inquirer/

    subject_list = [
        inquirer.List(
            'subject',
            message="What subject is the student in?",
            choices=[
                'Digital Art', 'Digital Photography',
                '3D Modelling & Animation', 'Custom subject:'
            ],
        ),
    ]

    choose_subject = inquirer.prompt(subject_list)["subject"]

    # gets user to input a custom subject if they so choose
    if choose_subject == "Custom subject:":
        custom_subject = utils.input_styled("Well then what are they in? \n")
        choose_subject = custom_subject

    default_tv = '1' if last_name.upper()[0] <= 'M' else '2'

    tv = utils.input_plus(
        "Which TV # are you sending this to (1 for lastname A-M, 2 for N-Z, 3 for Grads)?",
        default_tv)

    if not tv:
        tv = default_tv

    filename = username + ".a.title"
    template = "_template.svg"
    source_file = "scripts/TVs/{}".format(template)
    temp_filepath_svg = "{}{}.svg".format(temp_dir, filename)
    filename_png = filename + ".png"
    temp_filepath_png = temp_dir + filename_png

    # creates copy of template with the filename it will use
    os.system("cp {} {}".format(source_file, temp_filepath_svg))

    # writes the student information into the copy of the svg template
    os.system('sed -i -e "s/FIRSTNAME LASTNAME/{}/g" {}'.format(
        fullname, temp_filepath_svg))

    os.system('sed -i -e "s/YYYY/{}/g" {}'.format(grad_year,
                                                  temp_filepath_svg))

    # need to escape the ampersand character in "3D Modelling & Animation"
    os.system('sed -i -e "s/SUBJECT/{}/g" {}'.format(
        choose_subject.replace('&', '\&amp;'), temp_filepath_svg))

    # creates a png image from the svg
    os.system('inkscape -z -e {} -w 1920 -h 1080 {}'.format(
        temp_filepath_png, temp_filepath_svg))

    server_filepath = "tv{}/{}/".format(tv, username)

    # setup a connect so we can makesure the directory exists
    ssh_connection = SSH(hostname, SERVER_USERNAME, pi.password)
    # make sure the directory exists, if not create it:
    if not ssh_connection.file_exists(server_filepath):
        ssh_connection.send_cmd('mkdir {}'.format(server_filepath))

    # move image onto the server with scp (this will fail if they've never connected to hightower before, hence warning at bottom)
    command = 'sshpass -p "{}" scp {} {}@{}:{}'.format(pi.password,
                                                       temp_filepath_png,
                                                       SERVER_USERNAME,
                                                       hostname,
                                                       server_filepath)

    os.system(command)

    # removes all temp files we created
    os.system('rm {}'.format(temp_filepath_png))
    os.system('rm {}'.format(temp_filepath_svg))

    # Check if file now exists on the server
    title_exists = ssh_connection.file_exists(server_filepath, filename_png)

    if title_exists:
        utils.print_success(
            f"{filename_png} was successfully sent over to TV {tv}")
        add_images = utils.confirm(
            f"Would you like to add images to {fullname}'s new shrine?")
        if add_images:
            add_new_media(username, tv)
        else:
            gen_video = utils.confirm(
                "Would you like to regenerate the video file?")
            if gen_video:
                refresh_slideshow(username=username)
    else:
        utils.print_error(
            f"The title image '{filename_png}' was not added. Maybe inkscape isn't installed? Or it's possible you've never connected to this server before. \n\n"
            "Try connecting once first by typing `ssh hightower` into a terminal, then answering yes."
        )
def add_new_media(username=None, tv=None):
    media_url = True
    while media_url:
        # gets and checks the url of the file
        media_url, name_without_ext, extension = get_media_url()
        if media_url is None:
            return

        # collects information to name the file, and as to which tv to send it to
        username_input = utils.input_styled(
            "Enter username (default = {}): \n".format(username))
        if not username_input:
            pass
        else:
            username = username_input

        tv = guess_tv(username)
        tv_input = utils.input_styled(
            "What TV # are you sending this to? (default = {}): ".format(tv))
        if not tv_input:
            pass
        else:
            tv = tv_input

        image_name = None
        name_good = utils.input_styled(
            "What is the name of this image? (default = {}): ".format(
                name_without_ext))
        if not name_good:
            image_name = name_without_ext
        else:
            image_name = name_good

        filename = username + ".z." + image_name + extension

        # Save videos directly in the tv's rtoot directory.
        if is_video(extension.lower()):
            filepath = "{}/tv{}/".format(TV_ROOT, tv)
        # Save images into a subfolder, which will be used to generate a slideshow video
        else:
            filepath = "{}/tv{}/{}/".format(TV_ROOT, tv, username)

        utils.print_warning(
            "Sending {} to hightower to see if file exists already with that name."
            .format(filename))

        # connects and checks to see if file with the same name already exisits
        ssh_connection = SSH(TV_FILE_SERVER, TV_FILE_SERVER_USER,
                             TV_FILE_SERVER_PW)
        already_exists = ssh_connection.file_exists(filepath, filename)

        # if it does exist, asks user if they want to overwrite it
        while already_exists and not utils.confirm(
                "There is a file that already exists with that name. Do you want to overwrite it?",
                yes_is_default=False):
            # don't want to overwrite, so get a new name:
            image_name = utils.input_styled(
                "Provide a different name for the image: ")
            filename = username + ".z." + image_name + extension
            # check again
            already_exists = ssh_connection.file_exists(filepath, filename)

        command = "wget -O {}{} '{}' && exit".format(filepath, filename,
                                                     media_url)

        # make sure the directory exists, if not create it:
        if not ssh_connection.file_exists(filepath):
            ssh_connection.send_cmd('mkdir {}'.format(filepath))

        success = ssh_connection.send_cmd(command)
        if success:
            utils.print_success(
                "{} was succesfully sent over to pi-tv{}".format(filename, tv))
        else:
            utils.print_error(
                "Something went wrong.  Check the filename, is it wonky with weird characters?"
            )

        # asks user if they want to add another image
        if utils.confirm("Would you like to add another image?"):
            media_url = True
        else:
            break

    ssh_connection.close()

    if utils.confirm(
            "Do you want to generate a new video slideshow of this student's art?"
    ):
        refresh_slideshow(username=username)
Esempio n. 10
0
def remove_media(username=None, tv=None):

    ssh_connection = SSH(TV_FILE_SERVER, TV_FILE_SERVER_USER,
                         TV_FILE_SERVER_PW)

    username = utils.input_plus("Enter username", default=username)

    if username == "q":
        return False

    while True:

        tv = get_tv_containing_student(username)
        if tv is None:
            utils.print_error("No art found for {}".format(username))
            return False

        # get of list of the student's art and display the list
        filepath = "{}/tv{}/{}/".format(TV_ROOT, tv, username)
        command = 'ls {}'.format(filepath)
        dir_contents = ssh_connection.send_cmd(command,
                                               print_stdout=False).split()

        media_list = [
            inquirer.List(
                'art',
                message=
                "Which file do you want to delete? I'll display it first so you can confirm.",
                choices=dir_contents,
            ),
        ]

        art_file = inquirer.prompt(media_list)["art"]
        art_file_full_path = filepath + art_file

        # Show the image with Pillow
        # Transfer locally
        local_copy = "/tmp/" + art_file
        ssh_connection.get_file(art_file_full_path, local_copy)

        try:
            img = Image.open(local_copy)
        except IOError:
            utils.print_error("File not found")
            ssh_connection.close()
            return False

        w, h = img.size
        aspect_ratio = w / h
        thumb = img.resize((400, int(400 / aspect_ratio)))
        thumb.show()

        delete_file = utils.confirm(
            "Are you sure you want to delete {}? Hopefully it popped up for you"
            .format(art_file),
            yes_is_default=False)

        if delete_file:
            cmd = "rm {}".format(art_file_full_path)
            ssh_connection.send_cmd(cmd, print_stdout=True)

            # confirm it's gone:
            if ssh_connection.file_exists(art_file_full_path):
                utils.print_error(
                    "\nNot sure what happened there, but the file didn't get deleted.  Sorry!"
                )
            else:
                utils.print_success("\nThe file was successfully deleted.")

        # Keep deleting files ina  loop if they want to
        keep_going = utils.confirm("Remove another file for this student?")

        if not keep_going:
            ssh_connection.close()
            utils.print_warning(
                "\nDon't forget to refresh the user's video slideshow!\n")
            return True
Esempio n. 11
0
def add_new_theme():
    # gets and checks the url of the file
    mp3_url = True
    while mp3_url is True:
        have_good_input = False
        mp3_url = ""
        while not have_good_input:
            mp3_url = utils.input_styled("Paste the url to the mp3 file you want to add. (q to quit): \n")

            if mp3_url == 'q':
                break

            # check content to ensure proper mp3 type
            mime_type_good = utils.verify_mimetype(mp3_url, "audio/mpeg")

            have_good_input = mime_type_good

        if have_good_input:  # then get file number

            have_good_input = False
            while not have_good_input:
                filename = os.path.basename(urlparse(mp3_url).path)
                name, ext = os.path.splitext(filename)
                # check if filename is already a number, and offer to use it
                try:
                    name = int(name)
                    good_name_already = True
                except ValueError:
                    good_name_already = False

                prompt = "What code do you want to give it?" + (" [Enter] = {}".format(name) if good_name_already else "") + "\n"
                mp3_code = utils.input_styled(prompt)

                # try:
                if good_name_already and not mp3_code:
                    mp3_code = name
                # else:
                #     mp3_number = int(mp3_number)
                have_good_input = True
                # except ValueError:
                #     utils.print_error("Dude, that wasn't an integer! ")
                #     have_good_input = False
            filename = "{}.mp3".format(mp3_code)

            # print("test: {}".format(filename))

            print("Sending {} to pi-themes to see if file exists already with that name.".format(filename))

            command = "wget -O {}{} {} && exit".format(THEMES_PATH, filename, mp3_url)

            ssh_connection = SSH(hostname, pi.username, pi.password)

            # checks if file exists, and if user wants to overwrite it
            already_exists = ssh_connection.file_exists(THEMES_PATH, filename)

            # asks user if they want to overwrite https://www.quora.com/I%E2%80%99m-new-to-Python-how-can-I-write-a-yes-no-question
            if already_exists:
                overwrite = utils.confirm(
                    "There is a file that already exists with that name. Do you want to overwrite it?", 
                    yes_is_default=False
                )
                if not overwrite:
                    mp3_url = True
                else:
                    already_exists = False
                    pass
            elif not already_exists:
                pass
            else:
                utils.print_error("Something went wrong. Expected true or false but got something else")

            # sends the command
            if not already_exists:
                ssh_connection.send_cmd(command)

            another_code = utils.confirm("Would you like to add another code?")
            if another_code:
                mp3_url = True
                pass
            else:
                mp3_url = False

            ssh_connection.close()