Пример #1
0
def is_activity_report(rec):
    if (not rec.project.resources) or (not rec.project.resources.file):
        return False
    name = PurePath(rec.project.resources.file.path).name
    debug("Activity file name is: %s" % name)
    if not current_app.config.get("ACTIVITY_UPLOAD", False):
        return True
    url = current_app.config.get("OWN_CLOUD_URL", None)
    if not url:
        raise ValueError("Failed to find own cloud url. Please try later")
    oc = OwnClient(url)
    login = current_app.config.get("OWN_CLOUD_LOGIN", None)
    password = current_app.config.get("OWN_CLOUD_PASSWORD", None)
    try:
        oc.login(login, password)
    except Exception as err:
        raise ValueError("Failed to connect to the cloud: %s" % err)
    remote_dir = current_app.config.get("ACTIVITY_DIR", "/")
    if remote_dir[-1] is not "/":
        remote_dir += "/"
    remote = remote_dir + name
    debug("Checking is file %s exists" % remote)
    try:
        oc.file_info(remote)
    except Exception as e:
        raise ValueError("Failed to find activity report %s on the cloud:"
                         " %s\nProbably you should re-upload it" % (name, e))
    return True
Пример #2
0
def upload_file_cloud(path, remote=None):
    """
    Function which uploads a file to OwnCloud instance
    :param path: String. Path to file to upload.
    :param remote: String. Name of the remote directory to store files in.
    :return: Boolean. Return result of put_file() function call for OwnCloud
             instance. Result of this function call is boolean
    """
    url = current_app.config.get("OWN_CLOUD_URL", None)
    if not url:
        error("No url to the cloud given")
        return False
    oc = OwnClient(url)
    login = current_app.config.get("OWN_CLOUD_LOGIN", None)
    password = current_app.config.get("OWN_CLOUD_PASSWORD", None)
    try:
        oc.login(login, password)
    except Exception as err:
        error("Failed to connect to the cloud: %s" % err)
        return False
    po = Path(path)
    if not po.exists() or not po.is_file():
        error("Can't upload a file to a cloud. '%s' doesn't exists or not "
              "a file" % path)
        return False
    if not remote:
        remote_dir = current_app.config.get("ACTIVITY_DIR", "/")
        if remote_dir[-1] is not "/":
            remote_dir += "/"
        remote = remote_dir + po.name
    debug("Uploading file %s to %s" % (path, remote))
    return oc.put_file(remote, path)
Пример #3
0
def _login(oc: owncloud.Client):
    kvstore_dirty = False

    # initial case: no username or password present
    if "username" not in kvstore.keys() or "password" not in kvstore.keys():
        kvstore["username"], kvstore["password"] = _get_credentials()
        kvstore_dirty = True

    while True:
        try:
            # try to log in with given credentials
            oc.login(kvstore["username"], kvstore["password"])

            # login worked: save credentials if they're new, break loop
            if kvstore_dirty:
                kvstore.sync()
            return True
        except owncloud.HTTPResponseError as e:
            if e.status_code == 401:  # auth failure: read credentials again
                print("Authentication Failure.")
                kvstore["username"], kvstore["password"] = _get_credentials()
                kvstore_dirty = True
            else:  # other owncloud error
                logging.error(
                    "Upload failed. Owncloud Server reply: {}".format(
                        e.status_code))
                return False
        except RuntimeError as e:  # any other error
            logging.error("Upload failed. Error details: {}".format(e))
            return False
Пример #4
0
    def credentials_are_valid(self, user_settings, client=None):
        node = self.node_settings
        external_account = node.external_account
        provider = self.node_settings.oauth_provider(external_account)

        try:
            oc = OwnCloudClient(provider.host, verify_certs=USE_SSL)
            oc.login(provider.username, provider.password)
            oc.logout()
            return True
        except Exception:
            return False
Пример #5
0
    def credentials_are_valid(self, user_settings, client=None):
        node = self.node_settings
        external_account = node.external_account
        provider = self.node_settings.oauth_provider(external_account)

        try:
            oc = OwnCloudClient(provider.host, verify_certs=USE_SSL)
            oc.login(provider.username, provider.password)
            oc.logout()
            return True
        except Exception:
            return False
Пример #6
0
    def get_folders(self, **kwargs):
        path = kwargs.get('path')
        if path is None:
            return [{
                'addon': 'nextcloud',
                'path': '/',
                'kind': 'folder',
                'id': '/',
                'name': '/ (Full Nextcloud)',
                'urls': {
                    'folders':
                    api_v2_url('nodes/{}/addons/nextcloud/folders/'.format(
                        self.owner._id),
                               params={
                                   'path': '/',
                               })
                }
            }]

        provider = NextcloudProvider(account=self.external_account)

        c = NextcloudClient(provider.host, verify_certs=settings.USE_SSL)
        c.login(provider.username, provider.password)

        ret = []
        for item in c.list(path):
            if item.file_type is 'dir':
                ret.append({
                    'addon': 'nextcloud',
                    'path': item.path,
                    'kind': 'folder',
                    'id': item.path,
                    'name': item.path.strip('/').split('/')[-1],
                    'urls': {
                        'folders':
                        api_v2_url('nodes/{}/addons/nextcloud/folders/'.format(
                            self.owner._id),
                                   params={
                                       'path': item.path,
                                   })
                    }
                })

        return ret
Пример #7
0
    def get_folders(self, **kwargs):
        path = kwargs.get('path')
        if path is None:
            return [{
                'addon': 'owncloud',
                'path': '/',
                'kind': 'folder',
                'id': '/',
                'name': '/ (Full ownCloud)',
                'urls': {
                    'folders': api_v2_url('nodes/{}/addons/owncloud/folders/'.format(self.owner._id),
                        params={
                            'path': '/',
                    })
                }
            }]

        provider = OwnCloudProvider(account=self.external_account)

        c = OwnCloudClient(provider.host, verify_certs=settings.USE_SSL)
        c.login(provider.username, provider.password)

        ret = []
        for item in c.list(path):
            if item.file_type is 'dir':
                ret.append({
                    'addon': 'owncloud',
                    'path': item.path,
                    'kind': 'folder',
                    'id': item.path,
                    'name': item.path.strip('/').split('/')[-1],
                    'urls': {
                        'folders': api_v2_url('nodes/{}/addons/owncloud/folders/'.format(self.owner._id),
                            params={
                                'path': item.path,
                        })

                    }
                })

        return ret
Пример #8
0
# Set up environment variables for the Database
client_key = os.getenv('DISCORD_CLIENT_KEY', '0')
username = os.getenv('MYSQL_USERNAME', 'root')
password = os.getenv('MYSQL_PASSWORD', 'password')
address = os.getenv('MYSQL_ADDRESS', 'localhost:3306')
discord_db = os.getenv('MYSQL_DISCORD_DB', 'THALIA')
oc_username = os.getenv("NEXTCLOUD_USERNAME", "username")
oc_password = os.getenv("NEXTCLOUD_PASSWORD", "pw")
db_man = dbmanager(
    username=username,
    password=password,
    db_location=address,
    db_name=discord_db
)

oc = Client('https://nextcloud.chaoticdevelopment.com/')
oc.login(oc_username, oc_password)

thalia = Thalia(db_man, bot, oc)

@bot.event
async def on_ready():
    """
    called when the bot launches and successfully connects to discord
    :return:
    """
    print(f'Logged in as {bot.user.name} ID:  {bot.user.id}) | Connected to \n'
          f'{len(bot.guilds)} servers | Connected to {len(set(bot.get_all_members()))} users\n'
          f'--------\n'
          f'Current Discord.py Version: {discord.__version__} | Current Python Version: {platform.python_version()}\n'
          f'--------\n'