Here naverokê

Bikarhêner:Balyozxane/skrîpt/py/updatewin.py

Ji Wîkîpediya, ensîklopediya azad.
"""
Skrîpt to automate sending files to Toolforge Home using pywinauto and WinSCP

python pwb.py updatewin -file:"updatewin.py" -s:"Fix"
"""
import argparse
import pywikibot
import pywintypes  # pywinauto won't work without this even if it's not used?
from pywinauto import Application, keyboard, findwindows, mouse
import time
import keys
import os
import webbrowser

toolforge_key = keys.toolforge_key
script_dir = keys.script_dir


def start_winscp():
    # Find all WinSCP windows
    winscp_windows = findwindows.find_elements(title_re=".*Balyozbotkuwiki – WinSCP", visible_only=False, backend="win32")
    app = None
    # Iterate through each WinSCP window
    for winscp_window in winscp_windows:
        # Connect to the WinSCP application using its process ID
        winscp_app = Application(backend="win32").connect(process=winscp_window.process_id)
        # Get the main WinSCP window
        winscp_main_window = winscp_app.top_window()
        app = winscp_app
        time.sleep(2)
        # Loop to switch through Alt+Tab until the WinSCP window is found
        while True:
            winscp_main_window.set_focus()  # Set focus to the WinSCP window
            time.sleep(1)
            # Check if the current active window title matches WinSCP
            if winscp_main_window.is_active():
                break
        break

    if not app:
        print("Starting WinSCP application...")
        app = Application().start(cmd_line=r"C:\Program Files (x86)\WinSCP\WinSCP.exe")
        time.sleep(2)  # Adjust as necessary
        login(app)
    return app


def login(app):
    if not app:
        print("WinSCP application not started.")
        return

    # Wait for the Login dialog window to appear
    print("Waiting for the Login dialog window to appear...")
    login_dialog = app.window(title="Login")
    if login_dialog.exists():
        print("Login dialog found.")
    # Expand the TreeView and select the "Balyozbotkuwiki" session
    print("Expanding the TreeView and selecting the 'Balyozbotkuwiki' session...")
    balyozbotkuwiki_item = login_dialog.TreeView.get_item("\\Balyozbotkuwiki")
    balyozbotkuwiki_item.click_input(double=True)

    # Find and click the "Login" button associated with the "Balyozbotkuwiki" session
    print("Finding and clicking the 'Login' button...")
    login_button = login_dialog.child_window(title="Login", control_type="Button")

    # Wait for the new child window to appear and become enabled
    print("Waiting for the new child window to appear and become enabled...")
    passhrase_win = None
    for _ in range(10):  # Try waiting for up to 10 seconds
        passhrase_win = app.window(title_re='Key passphrase')
        if passhrase_win.exists() and passhrase_win.enabled:
            break
        time.sleep(1)

    print("New window found:", passhrase_win.exists())

    # Once the window is ready, set the keyphrase in the input field
    if passhrase_win:
        print("Setting keyphrase in the input field...")
        keyphrase_field = passhrase_win.Edit
        keyphrase_field.set_text(toolforge_key)
        time.sleep(2)
        keyboard.send_keys("{ENTER}")
        time.sleep(10)
    else:
        print("Failed to find the new window.")


def upload_file(file_name):
    app = start_winscp()  # Add parentheses to call the function
    if not app:
        print("WinSCP application not started.")
        return

    # Ensure the main window is visible
    main_window = app.window(title="userscripts – Balyozbotkuwiki – WinSCP")
    test_window = app.window(title="balyozbot – Balyozbotkuwiki – WinSCP")

    if not main_window.exists() and test_window.exists():
        mouse.click(coords=(642, 388))
        time.sleep(2)
        main_window = app.window(title="userscripts – Balyozbotkuwiki – WinSCP")
        time.sleep(2)

    if main_window.exists():
        print("Main window found. Continuing with file upload operations.")
        main_window.set_focus()
        time.sleep(2)  # Placeholder for file upload operations
        # Perform file upload operations here

        # Click the '+' key on the numeric keypad
        keyboard.send_keys('{VK_ADD}')
        print("Clicked '+' key on the numeric keypad.")
        time.sleep(2)
        keyboard.send_keys(file_name, with_spaces=True)
        time.sleep(3)
        keyboard.send_keys("{ENTER}")
        time.sleep(3)  # Placeholder for further operations
        keyboard.send_keys('{F5}')
        time.sleep(3)
        keyboard.send_keys("{ENTER}")
        time.sleep(3)
        confirm_panel = main_window.child_window(title="Confirm", control_type="TPanel")
        confirm_win = None
        for _ in range(10):  # Try waiting for up to 10 seconds
            confirm_win = app.window(title_re='^Confirm$')
            if confirm_win.exists() and confirm_win.enabled:
                break
        if confirm_win.exists() and confirm_win.enabled:
            keyboard.send_keys("{ENTER}")
            time.sleep(2)


file_to_page_title = {
    'kucosmetics.py': 'kuCosmeticsCore.py',
    'kucosmrun.py': 'kuCosmeticsRun.py',
    'citekurdifier.py': 'citeKurdifier.py',
    'categorizewithcreator.py': 'categorizeWithCreator.py',
    'category_creator.py': 'category creator.py'
}


def update_wiki(file_name, summary):
    # Define the directory where the file is located

    # Construct the full path to the file
    file_path = os.path.join(script_dir, file_name)

    site = pywikibot.Site('ku', 'wikipedia')

    # Get the corresponding page title from the dictionary
    page_title = file_to_page_title.get(file_name, file_name)
    page_title = f'Bikarhêner:Balyozxane/skrîpt/py/{page_title}'
    page = pywikibot.Page(site, page_title)

    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            page_text = '<syntaxhighlight lang="python">\n'
            page_text += content
            page_text += '\n

'

           page.text = page_text
           # Save the changes to the wiki page
           page.save(summary=summary, botflag=True)
           print(f"Content from '{file_path}' uploaded to wiki page '{page_title}' successfully.")
           # Open the last revision of the page
           webbrowser.open(page.full_url() + '?action=history')
   except FileNotFoundError:
       print(f"File '{file_path}' not found.")
   except Exception as e:
       print(f"An error occurred: {e}")
   confirm = input("Upload? e bo erê, n bo na: ")
   if confirm == "e":
       upload_file(file_name)


def main():

   parser = argparse.ArgumentParser(description="Upload file using WinSCP")
   parser.add_argument("-f", "--file", type=str, help="Path to the file to upload")
   parser.add_argument("-s", "--summary", type=str, help="Include this flag to enable summary mode")
   parser.add_argument("--nowiki", action="store_true", help="If called, update_wiki function will not be executed")
   args = parser.parse_args()
   if args.file:
       if args.summary:
           summary = args.summary.split(":")[-1]  # Extracting the filename part after ':'
           file_name = args.file.split(":")[-1]  # Extracting the filename part after ':'
           update_wiki(file_name, summary)
   else:
       print("Please provide the path to the file using the -f or --file argument.")


if __name__ == "__main__":

   main()

</syntaxhighlight>