def send(self, message=None):
        """Sends the message through the Sparkpost service.

        Keyword Arguments:
            message {string} -- The message to be sent to Sparkpost. (default: {None})

        Returns:
            requests.post -- Returns the response as a requests object.
        """

        try:
            from sparkpost import SparkPost
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "sparkpost" library. Please pip install this library '
                'by running "pip install sparkpost"')

        if not message:
            message = self.message_body

        sp = SparkPost(api_key=self.config.DRIVERS['sparkpost']['api_key'])

        response = sp.transmissions.send(use_sandbox=self._sandbox_mode(),
                                         recipients=[self.to_address],
                                         html=message,
                                         from_email='{0} <{1}>'.format(
                                             self.config.FROM['name'],
                                             self.config.FROM['address']),
                                         subject=self.message_subject)

        return response
Example #2
0
    def handle(self):
        try:
            import pika
        except ImportError:
            raise DriverLibraryNotFound(
                "Could not find the 'pika' library. Run pip install pika to fix this."
            )

        connection = pika.BlockingConnection(
            pika.URLParameters('amqp://{}:{}@{}{}/{}'.format(
                queue.DRIVERS['amqp']['username'],
                queue.DRIVERS['amqp']['password'],
                queue.DRIVERS['amqp']['host'],
                ':' + str(queue.DRIVERS['amqp']['port'])
                if 'port' in queue.DRIVERS['amqp']
                and queue.DRIVERS['amqp']['port'] else '',
                queue.DRIVERS['amqp']['vhost']
                if 'vhost' in queue.DRIVERS['amqp']
                and queue.DRIVERS['amqp']['vhost'] else '%2F')))
        channel = connection.channel()

        channel.queue_declare(queue=self.option('channel'), durable=True)

        channel.basic_consume(callback, queue=self.option('channel'))
        if self.option('fair'):
            channel.basic_qos(prefetch_count=1)

        self.info(
            ' [*] Waiting to process jobs on the "{}" channel. To exit press CTRL+C'
            .format(self.option('channel')))
        channel.start_consuming()
Example #3
0
    def store(self, fileitem, location=None):
        """Store the file into Rackspace server.

        Arguments:
            fileitem {cgi.Storage} -- Storage object.
        Keyword Arguments:
            location {string} -- The location on disk you would like to store the file. (default: {None})
        Raises:
            DriverLibraryNotFound -- Raises when the rackspace library is not installed.
        Returns:
            string -- Returns the file name just saved.
        """

        try:
            from rackspace import connection
        except ImportError:
            raise DriverLibraryNotFound(
                "Could not find the required 'rackspace' library. 'pip install rackspace' to fix this."
            )

        conn = connection.Connection(
            username=self.config.DRIVERS['rackspace']['username'],
            api_key=self.config.DRIVERS['rackspace']['secret'],
            region=self.config.DRIVERS['rackspace']['region'])

        filename = random_string(25) + fileitem.filename

        self.validate_extension(filename)

        conn.object_store.upload_object(
            container=self.config.DRIVERS['rackspace']['container'],
            name=filename,
            data=fileitem.file.read())
        return filename
Example #4
0
    def connect(self):
        try:
            import pika
            self.pika = pika
        except ImportError:
            raise DriverLibraryNotFound(
                "Could not find the 'pika' library. Run pip install pika to fix this."
            )

        self.connection = pika.BlockingConnection(
            pika.URLParameters('amqp://{}:{}@{}{}/{}'.format(
                self.queue.DRIVERS['amqp']['username'],
                self.queue.DRIVERS['amqp']['password'],
                self.queue.DRIVERS['amqp']['host'],
                ':' + str(self.queue.DRIVERS['amqp']['port'])
                if 'port' in self.queue.DRIVERS['amqp']
                and self.queue.DRIVERS['amqp']['port'] else '',
                self.queue.DRIVERS['amqp']['vhost']
                if 'vhost' in self.queue.DRIVERS['amqp']
                and self.queue.DRIVERS['amqp']['vhost'] else '%2F')))

        self.channel = self.connection.channel()

        self.channel.queue_declare(self.publishing_channel, durable=True)

        return self
Example #5
0
    def store(self, fileitem, location=None):
        driver = self.upload.driver('disk')
        driver.store(fileitem, location)
        file_location = driver.file_location

        # Check if is a valid extension
        self.validate_extension(fileitem.filename)

        try:
            import boto3
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "boto3" library. Please pip install this library by running "pip install boto3"'
            )

        session = boto3.Session(
            aws_access_key_id=self.config.DRIVERS['s3']['client'],
            aws_secret_access_key=self.config.DRIVERS['s3']['secret'],
        )

        s3 = session.resource('s3')

        s3.meta.client.upload_file(file_location,
                                   self.config.DRIVERS['s3']['bucket'],
                                   fileitem.filename)

        return fileitem.filename
    def channel(self, channels, message, event='base-event'):
        """Specify which channel(s) you want to send information to.
        
        Arguments:
            channels {string|list} -- Can be a string for the channel or a list of strings for the channels.
            message {string} -- The message you want to send to the channel(s)
        
        Keyword Arguments:
            event {string} -- The event you want broadcasted along with your data. (default: {'base-event'})
        
        Raises:
            DriverLibraryNotFound -- Thrown when ably is not installed.
        
        Returns:
            string -- Returns the message sent.
        """

        try:
            from ably import AblyRest
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "ably" library. Please pip install this library running "pip install ably"'
            )

        client = AblyRest('{0}'.format(self.config.DRIVERS['ably']['secret']))

        if isinstance(channels, list):
            for channel in channels:
                ably_channel = client.channels.get(channel)
                ably_channel.publish(event, message)
        else:
            channel = client.channels.get(channels)
            channel.publish(event, message)

        return message
Example #7
0
    def store(self, fileitem, location=None):
        """Store the file into Microsoft Azure server.

        Arguments:
            fileitem {cgi.Storage} -- Storage object.
        Keyword Arguments:
            location {string} -- The location on disk you would like to store the file. (default: {None})
        Raises:
            DriverLibraryNotFound -- Raises when the azure library is not installed.
        Returns:
            string -- Returns the file name just saved.
        """

        try:
            from azure.storage.blob import BlockBlobService
        except ImportError:
            raise DriverLibraryNotFound("Could not find the 'azure' driver")

        block_blob_service = BlockBlobService(
            account_name=self.config.DRIVERS['azure']['name'],
            account_key=self.config.DRIVERS['azure']['secret'])

        # Store temporarily on disk
        driver = self.upload.driver('disk')
        driver.store(fileitem, location)
        file_location = driver.file_location

        filename = random_string(25) + fileitem.filename

        block_blob_service.create_blob_from_path(
            self.config.DRIVERS['azure']['container'], filename, file_location)

        return filename
Example #8
0
    def __init__(self, CacheConfig, Application):
        """Cache redis driver constructor
        
        Arguments:
            CacheConfig {config.cache} -- Cache configuration module.
            Application {config.application} -- Application configuration module.
        """

        self.appconfig = Application
        self.cache_forever = None
        self.app_name = os.getenv('APP_NAME', 'masonite')

        config = CacheConfig.DRIVERS['redis']

        try:
            import redis
            self.redis = redis
        except ImportError:
            raise DriverLibraryNotFound(
                "Could not find the 'redis' library. Run pip install redis to fix this.")

        self.connection = redis.StrictRedis(
            host=config['host'],
            port=config['port'],
            password=config['password'],
            decode_responses=True)
Example #9
0
    def _connect(self):
        try:
            import pika
            self.pika = pika
        except ImportError:
            raise DriverLibraryNotFound(
                "Could not find the 'pika' library. Run pip install pika to fix this."
            )

        connection = pika.BlockingConnection(
            pika.URLParameters('amqp://{}:{}@{}{}/{}'.format(
                queue.DRIVERS['amqp']['username'],
                queue.DRIVERS['amqp']['password'],
                queue.DRIVERS['amqp']['host'],
                ':' + str(queue.DRIVERS['amqp']['port'])
                if 'port' in queue.DRIVERS['amqp']
                and queue.DRIVERS['amqp']['port'] else '',
                queue.DRIVERS['amqp']['vhost']
                if 'vhost' in queue.DRIVERS['amqp']
                and queue.DRIVERS['amqp']['vhost'] else '%2F')))

        # Get the channel
        self.channel = connection.channel()

        # Declare what queue we are working with
        self.channel.queue_declare(queue=listening_channel, durable=True)
    def handle(self):
        if has_unmigrated_migrations():
            self.comment(
                "\nYou have unmigrated migrations. Run 'craft migrate' to migrate them\n"
            )

        if self.option('live-reload'):
            try:
                from livereload import Server
            except ImportError:
                raise DriverLibraryNotFound(
                    "Could not find the livereload library. Install it by running 'pip install livereload==2.5.1'"
                )

            from wsgi import container
            from config import application
            import glob

            server = Server(container.make('WSGI'))
            for filepath in glob.glob('resources/templates/**/*/'):
                server.watch(filepath)

            self.line('')
            self.info('Live reload server is starting...')
            self.info(
                'This will only work for templates. Changes to Python files may require a browser refresh.'
            )
            self.line('')
            application = server.serve(
                port=self.option('port'),
                restart_delay=self.option('reload-interval'),
                liveport=5500,
                root=application.BASE_DIRECTORY,
                debug=True)
            return

        if not self.option('dont-reload'):
            logger = DefaultLogger(LogLevel.INFO)

            # worker args are pickled and then passed to the new process
            worker_args = [
                self.option("host"),
                self.option("port"),
                "wsgi:application",
            ]

            reloader = Reloader(
                "masonite.commands._devserver.run",
                find_default_monitor_factory(logger),
                logger,
                worker_args=worker_args,
            )

            self._run_reloader(reloader, extra_files=[".env", "storage/"])

        else:
            from wsgi import application
            from ._devserver import run
            run(self.option("host"), self.option("port"), application)
Example #11
0
    def store(self, fileitem, filename=None, location=None):
        """Store the file into Amazon S3 server.

        Arguments:
            fileitem {cgi.Storage} -- Storage object.

        Keyword Arguments:
            location {string} -- The location on disk you would like to store the file. (default: {None})
            filename {string} -- A new file name you would like to name the file. (default: {None})

        Raises:
            DriverLibraryNotFound -- Raises when the boto3 library is not installed.

        Returns:
            string -- Returns the file name just saved.
        """
        try:
            import boto3
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "boto3" library. Please pip install this library by running "pip install boto3"'
            )

        driver = self.upload.driver('disk')
        driver.accept_file_types = self.accept_file_types
        driver.store(fileitem, filename=filename, location='storage/temp')
        file_location = driver.file_location

        # use the new filename or get it from the fileitem
        if filename is None:
            filename = self.get_name(fileitem)

        # Check if is a valid extension
        self.validate_extension(filename)

        session = boto3.Session(
            aws_access_key_id=self.config.DRIVERS['s3']['client'],
            aws_secret_access_key=self.config.DRIVERS['s3']['secret'],
        )

        s3 = session.resource('s3')

        if location:
            location = os.path.join(location, filename)
        else:
            location = os.path.join(filename)

        s3.meta.client.upload_file(file_location,
                                   self.config.DRIVERS['s3']['bucket'],
                                   location)

        return filename
Example #12
0
    def __init__(self, request: Request):
        """AuthCookieDriver initializer.

        Arguments:
            request {masonite.request.Request} -- The Masonite request class.
        """
        self.request = request
        try:
            import jwt
            self.jwt = jwt
        except ImportError:
            raise DriverLibraryNotFound(
                "Please install pyjwt by running 'pip install pyjwt'")
Example #13
0
    def store(self, fileitem, location=None):
        """Store the file into a Digital Ocean Space.

        Arguments:
            fileitem {cgi.Storage} -- Storage object.

        Keyword Arguments:
            location {string} -- The location on disk you would like to store the file. (default: {None})

        Raises:
            DriverLibraryNotFound -- Raises when the boto3 library is not installed.

        Returns:
            string -- Returns the file name just saved.
        """

        driver = self.upload.driver('disk')
        driver.store(fileitem, location)
        file_location = driver.file_location

        # Check if is a valid extension
        self.validate_extension(fileitem.filename)

        try:
            import boto3
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "boto3" library. Please pip install this library '
                'by running "pip install boto3"')

        session = boto3.Session()
        client = session.client(
            's3',
            region_name=self.config.DRIVERS['digitalocean']['region'],
            endpoint_url=self.config.DRIVERS['digitalocean']['endpoint'],
            aws_access_key_id=self.config.DRIVERS['digitalocean']['client'],
            aws_secret_access_key=self.config.DRIVERS['digitalocean']
            ['secret'])

        client.upload_file(file_location,
                           self.config.DRIVERS['digitalocean']['space'],
                           fileitem.filename)

        return fileitem.filename
Example #14
0
    def channel(self, channels, message, event='base-event'):
        try:
            from ably import AblyRest
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "ably" library. Please pip install this library running "pip install ably"')

        client = AblyRest('{0}'.format(
            self.config.DRIVERS['ably']['secret']
        ))

        if isinstance(channels, list):
            for channel in channels:
                ably_channel = client.channels.get(channel)
                ably_channel.publish(event, message)
        else:
            channel = client.channels.get(channels)
            channel.publish(event, message)

        return message
Example #15
0
    def channel(self, channels, message, event='base-event'):
        """Specify which channel(s) you want to send information to.

        Arguments:
            channels {string|list} -- Can be a string for the channel or a list of strings for the channels.
            message {string} -- The message you want to send to the channel(s)

        Keyword Arguments:
            event {string} -- The event you want broadcasted along with your data. (default: {'base-event'})

        Raises:
            DriverLibraryNotFound -- Thrown when pusher is not installed.

        Returns:
            string -- Returns the message sent.
        """

        try:
            import pusher
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "pusher" library. Please pip install this library running "pip install pusher"'
            )

        pusher_client = pusher.Pusher(
            app_id=self.config.DRIVERS['pusher']['app_id'],
            key=self.config.DRIVERS['pusher']['client'],
            secret=self.config.DRIVERS['pusher']['secret'],
            ssl=self.ssl_message)

        if isinstance(message, str):
            message = {'message': message}

        if isinstance(channels, list):
            for channel in channels:
                pusher_client.trigger(channel, event, message)
        else:
            pusher_client.trigger(channels, event, message)

        return message
    def store(self, fileitem, location=None):
        """Store the file into Dropbox.

        Arguments:
            fileitem {cgi.Storage} -- Storage object.

        Keyword Arguments:
            location {string} -- The location on disk you would like to store the file. (default: {None})

        Raises:
            DriverLibraryNotFound -- Raises when the boto3 library is not installed.

        Returns:
            string -- Returns the file name just saved.
        """

        driver = self.upload.driver('disk')
        driver.store(fileitem, location)
        file_location = driver.file_location

        # Check if is a valid extension
        self.validate_extension(fileitem.filename)

        try:
            import dropbox
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "dropbox" library. Please pip install this library '
                'by running "pip install dropbox"')

        import pathlib

        db = dropbox.Dropbox(self.config.DRIVERS['dropbox']['token'])

        filepath = pathlib.Path(file_location)
        with filepath.open('rb') as f:
            db.files_upload(f.read(), self.config.DRIVERS['dropbox']['folder'] + fileitem.filename)

        return fileitem.filename
Example #17
0
    def __init__(self, Container):
        """Queue AMQP Driver

        Arguments:
            Container {masonite.app.App} -- The application container.
        """

        try:
            import pika
            self.pika = pika
        except ImportError:
            raise DriverLibraryNotFound(
                "Could not find the 'pika' library. Run pip install pika to fix this."
            )

        # Start the connection
        connection = self.pika.BlockingConnection(
            self.pika.ConnectionParameters('localhost'))

        # Get the channel
        self.channel = connection.channel()

        # Declare what queue we are working with
        self.channel.queue_declare(queue=listening_channel, durable=True)
Example #18
0
    def channel(self, channels, message, event='base-event'):
        try:
            import pusher
        except ImportError:
            raise DriverLibraryNotFound(
                'Could not find the "pusher" library. Please pip install this library running "pip install pusher"')

        pusher_client = pusher.Pusher(
            app_id=self.config.DRIVERS['pusher']['app_id'],
            key=self.config.DRIVERS['pusher']['client'],
            secret=self.config.DRIVERS['pusher']['secret'],
            ssl=self.ssl_message
        )

        if isinstance(message, str):
            message = {'message': message}  

        if isinstance(channels, list):
            for channel in channels:
                pusher_client.trigger(channel, event, message)
        else:
            pusher_client.trigger(channels, event, message)

        return message
Example #19
0
from masonite.contracts.BroadcastContract import BroadcastContract
from masonite.exceptions import DriverLibraryNotFound

try:
    from ably import AblyRest
except ImportError:
    raise DriverLibraryNotFound(
        'Could not find the "ably" library. Please pip install this library running "pip install ably"')


class BroadcastAblyDriver(BroadcastContract):

    def __init__(self, BroadcastConfig):
        self.config = BroadcastConfig
        self.ssl_message = True

    def ssl(self, boolean):
        self.ssl_message = boolean
        return self

    def channel(self, channels, message, event='base-event'):
        client = AblyRest('{0}'.format(
            self.config.DRIVERS['ably']['secret']
        ))

        if isinstance(channels, list):
            for channel in channels:
                ably_channel = client.channels.get(channel)
                ably_channel.publish(event, message)
        else:
            channel = client.channels.get(channels)
from masonite.contracts.BroadcastContract import BroadcastContract
from masonite.exceptions import DriverLibraryNotFound

try:
    import pusher
except ImportError:
    raise DriverLibraryNotFound(
        'Could not find the "pusher" library. Please pip install this library running "pip install pusher"')


class BroadcastPusherDriver(BroadcastContract):

    def __init__(self, BroadcastConfig):
        self.config = BroadcastConfig
        self.ssl_message = True

    def ssl(self, boolean):
        self.ssl_message = boolean
        return self

    def channel(self, channels, message, event='base-event'):
        pusher_client = pusher.Pusher(
            app_id=self.config.DRIVERS['pusher']['app_id'],
            key=self.config.DRIVERS['pusher']['client'],
            secret=self.config.DRIVERS['pusher']['secret'],
            ssl=self.ssl_message
        )

        if isinstance(message, str):
            message = {'message': message}