예제 #1
0
def _connect():
    # Create transport object
    try:
        transport = paramiko.Transport((HOSTNAME, PORT))
    except paramiko.ssh_exception.SSHException:
        logging.error("Connection to the host failed. Check hostname and port.")
        sys.exit(0)

    # Start SSH session based on authentication type
    try:
        if AUTHENTICATION_TYPE == "password":
            # FIXME: Use encrypted KVStore for password
            password = CONFIG.get(_name, "password")
            transport.connect(username=USERNAME, password=password)

        elif AUTHENTICATION_TYPE == "key":
            # FIXME: Use encrypted KVStore for password
            key_filepath = CONFIG.get(_name, "key_filepath")
            key_passphrase = CONFIG.get(_name, "key_passphrase")
            private_key = paramiko.RSAKey.from_private_key_file(key_filepath, key_passphrase)
            transport.connect(username=USERNAME, pkey=private_key)

        else:
            logging.error("Unknown authentication type.")

    except paramiko.ssh_exception.AuthenticationException:
        logging.error("Login failed. Check username and password or private key and passphrase.")
        sys.exit(0)

    return transport, paramiko.SFTPClient.from_transport(transport)
예제 #2
0
def upload(file: str) -> str:
    flags = Namespace(
        auth_host_name="localhost", auth_host_port=[8080, 8090], logging_level="ERROR", noauth_local_webserver=False
    )
    credentials = _get_credentials(flags)
    http = credentials.authorize(httplib2.Http())
    service = discovery.build("drive", "v2", http=http)
    # Returns a list of folders in the root directory with a title equaling the screenshot_dir
    results = (
        service.files()
        .list(
            q="'root' in parents and trashed=false and mimeType='application/vnd.google-apps.folder'"
            " and title='" + CONFIG.get(CONFIG.general, "screenshot_dir") + "'",
            maxResults=100,
        )
        .execute()
    )
    items = results.get("items", [])

    # Checks if the directory already exists and if not it will create it
    if not items:
        folder_body = {
            "title": CONFIG.get(CONFIG.general, "screenshot_dir"),
            "parents": ["root"],
            "mimeType": "application/vnd.google-apps.folder",
        }
        try:
            return_folder = service.files().insert(body=folder_body).execute()
            folder_id = return_folder.get("id")
        except errors.HttpError as e:
            logging.error(e)
            return None
    else:
        folder_id = items[0]["id"]

    # Defines some bodies for communicating with Google Drive
    media_body = MediaFileUpload(file, resumable=True)
    body = {
        "title": ntpath.basename(file),
        "description": "Screenshot",
        "parents": [{"id": folder_id}],
        "writersCanShare": True,
    }

    new_permission = {"role": "reader", "type": "anyone"}

    try:
        # Uploads the file to Drive
        return_file = service.files().insert(body=body, media_body=media_body).execute()
        logging.info("Google Drive upload done")
        # Shares the file so everybody with the link can read it
        service.permissions().insert(fileId=return_file["id"], body=new_permission).execute()
        logging.info("Google Drive permissions set")
        # Inserts the file ID into another URL for a better image view in the browser
        ret_str = "http://drive.google.com/uc?export=view&id=" + return_file["selfLink"].split("/files/")[1]
        return ret_str
    except errors.HttpError as e:
        logging.info(e)
        return None
예제 #3
0
def upload(file: str):
    # Upload preparations
    transport, sftp_client = _connect()
    try:
        sftp_client.chdir(SFTP_BASE_DIR)
    except IOError:
        logging.error(
            "Can not change into base directory. Please provide a working base directory in your SFTP configuration.")
        sys.exit(0)

    screenshot_dir = CONFIG.get(CONFIG.general, "screenshot_dir")
    sftp_filepath = screenshot_dir + "/" + ntpath.basename(file)

    _create_dir_if_not_exists(screenshot_dir, sftp_client)

    # Upload
    try:
        sftp_client.put(file, sftp_filepath)
    except IOError:
        # State reason for failue without exposing Traceback? Is IOError the correct exception?
        # Documentation: http://docs.paramiko.org/en/2.0/api/sftp.html
        logging.error("Upload failed.")

    # Close
    sftp_client.close()
    transport.close()

    return "http://" + HOSTNAME + "/" + sftp_filepath
예제 #4
0
def upload(file: str) -> str:
    # TODO: Use another way to find out if the access token is valid
    # FIXME: Check for authorization failure
    if "access_token" not in kvstore.keys():
        authorization_successful = _authorize()
        if not authorization_successful:
            return None  # unable to upload without successful authorization

    token = kvstore["access_token"]
    dropbox_client = dropbox.Dropbox(token)
    dropbox_filepath = "/" + CONFIG.get(CONFIG.general, "screenshot_dir") + "/" + ntpath.basename(file)
    file_object = open(file, 'rb')

    try:
        dropbox_client.files_upload(
            file_object,
            dropbox_filepath,
            mode=WriteMode("overwrite", None),
            client_modified=None,
            mute=False
        )
    except dropbox.exceptions.ApiError as e:
        logging.error("Upload failed. Error message: {0}".format(e.error_msg))
        return None

    try:
        url = dropbox_client.sharing_create_shared_link_with_settings(dropbox_filepath, None).url
    except dropbox.exceptions.ApiError as e:
        logging.error("Could not create shared link. Error message: {0}".format(e.error_msg))
        return None

    return _change_url_suffix(url)
예제 #5
0
def main(argv):
    args = docopt(__doc__, argv=argv)

    # import modules dynamically
    scrtool = args["--tool"] if args["--tool"] else CONFIG.get(CONFIG.general, "screenshot_tool")
    storage = args["--storage"] if args["--storage"] else CONFIG.get(CONFIG.general, "storage")
    scrtool = import_module("screenshot." + scrtool)
    storage = import_module("storage." + storage)

    # build filename
    file = "{}/instantscreen_{}.png".format(gettempdir(), strftime("%Y-%m-%d_%H-%I-%S"))

    # take screenshot
    if args["--whole"]:
        scrtool.take_screenshot_whole(file)
    else:
        scrtool.take_screenshot_crop(file)

    if not os.path.isfile(file):
        # Capture screen cancelled
        logging.debug("Screen capture cancelled.")
        return

    # upload to storage
    url = storage.upload(file)
    logging.info("Uploaded screenshot to: " + url)

    # execute user defined action
    if CONFIG.getboolean(CONFIG.general, "cb_autocopy"):
        import tools.clipboard as c
        c.Clipboard().set(url)
    else:
        import webbrowser as w
        w.open_new_tab(url)

    # notify user if set
    if CONFIG.getboolean(CONFIG.general, "notification_sound"):
        import tools.audio as a
        a.play_wave_file("res/notification.wav")
예제 #6
0
def _authorize():
    authorization_endpoint = "https://www.dropbox.com/oauth2/authorize"
    app_key = CONFIG.get(_name, "app_key")

    # Start OAuth2 implicit flow
    auth_response = implicit_flow(authorization_endpoint, app_key)

    # Check if authorization was successful
    if "error" in auth_response and auth_response["error"] is not None:
        logging.error("Authentication failed. Error message: {0}".format(auth_response["error_description"]))
        return False

    kvstore["access_token"] = auth_response["access_token"]
    kvstore.sync()

    return True
예제 #7
0
def upload(file: str) -> str:
    # Anonymous upload.
    # TODO: Upload to a specific user account. See #8.
    client_id = CONFIG.get(_name, "client_id")

    # access_token = kvstore["access_token"]
    # refresh_token = kvstore["refresh_token"]

    imgur_client = ImgurClient(client_id, None, None, None)

    file_metadata = None
    try:
        file_metadata = imgur_client.upload_from_path(file)
    except ImgurClientError as e:
        logging.error("Upload failed. Error message: {0}".format(e.error_message))

    url = file_metadata["link"] if file_metadata else None
    return url
예제 #8
0
def _authorize():
    # For issue #8
    authorization_endpoint = "https://api.imgur.com/oauth2/authorize"
    client_id = CONFIG.get(_name, "client_id")

    # Start OAuth2 implicit flow
    auth_response = implicit_flow(authorization_endpoint, client_id)

    # Check if authorization was successful
    if "error" in auth_response and auth_response["error"] is not None:
        logging.error("Authentication failed. Error message: {0}".format(auth_response["error_description"]))
        return False

    kvstore["access_token"] = auth_response["access_token"]
    kvstore["refresh_token"] = auth_response["refresh_token"]
    kvstore["expires_in"] = auth_response["expires_in"]
    kvstore.sync()

    return True
예제 #9
0
def main(argv):
    args = docopt(__doc__, argv)

    # Event Queue for main thread
    event_queue = Queue()

    # define callbacks for menu items in system tray context menu
    tray_callbacks = (
        lambda: delay_execution(0.3, lambda: execute_command("screen --whole")),
        lambda: delay_execution(0.3, lambda: execute_command("screen"))
    )

    # assign callbacks to hotkey options of config file
    hotkey_options_with_callbacks = {
        "screenshot_whole": lambda: execute_command("screen --whole"),
        "screenshot_crop": lambda: execute_command("screen")
    }

    # parse hotkeys from config file and add them to hotkey daemon
    hotkey_daemon = Hotkey(event_queue)
    for hotkey_option, callback in hotkey_options_with_callbacks.items():
        try:
            hotkey = CONFIG.get("hotkeys", hotkey_option).split("+")
            hotkey_daemon.add_hotkey(hotkey, callback)
        except (HotkeyInUseError, InvalidHotkeyError) as e:
            logging.warning(e.error_msg)

    # enable hotkey functionality
    hotkey_daemon.listen()

    # create tray
    logging.info("Creating tray icon for instantshare")
    traymenu_daemon = Tray(event_queue, *tray_callbacks)
    traymenu_daemon.show()

    while True:
        event = event_queue.get()
        event()
예제 #10
0
import logging
import ntpath
import sys

import paramiko

from tools.config import CONFIG
from tools.persistence import KVStore

_name = "sftp"
# TODO: encryption
kvstore = KVStore(_name)

# Load SFTP server info from config file
HOSTNAME = CONFIG.get(_name, "hostname")
PORT = CONFIG.getint(_name, "port")
USERNAME = CONFIG.get(_name, "username")
AUTHENTICATION_TYPE = CONFIG.get(_name, "authentication_type")
SFTP_BASE_DIR = CONFIG.get(_name, "base_dir")


# The provided user for SFTP upload must have read and write permissions in the SFTP_BASE_DIR
# (The SFTP_BASE_DIR has to exist, the user doesn't need permissions in the parent directory).
# A lack of permissions in SFTP_BASE_DIR will break the SFTP upload functionality.


def upload(file: str):
    # Upload preparations
    transport, sftp_client = _connect()
    try:
        sftp_client.chdir(SFTP_BASE_DIR)