Пример #1
0
    def get(self):
        creds = self.GetCodeCredentials() or self.GetSessionCredentials()

        if not creds:
            logging.debug('No credentials, redirecting to Oauth2 URL')
            next = self.request.get('next')
            if next and BaseHandler.is_authorized_domain(next):
                self.session['next'] = next

            file_id = self.request.get('file_id')
            if file_id:
                self.session['fileId'] = file_id

            redirect_uri = self.RedirectAuth()
            return self.redirect(redirect_uri)

        if 'next' in self.session:
            next = self.session['next']
            del self.session['next']
            params = {'videonotes_start': 1}

            if 'fileId' in self.session:
                file_id = self.session['fileId']
                del self.session['fileId']
                if file_id:
                    params.update({'videonotes_id': file_id})

            redirect_url = UrlUtils.add_query_parameter(next, params)

            return self.redirect(str(redirect_url))
        else:
            return self.redirect('/edit/')
Пример #2
0
    def get(self):
        creds = self.GetCodeCredentials() or self.GetSessionCredentials()

        if not creds:
            logging.debug('No credentials, redirecting to Oauth2 URL')
            next = self.request.get('next')
            if next and BaseHandler.is_authorized_domain(next):
                self.session['next'] = next

            file_id = self.request.get('file_id')
            if file_id:
                self.session['fileId'] = file_id

            redirect_uri = self.RedirectAuth()
            return self.redirect(redirect_uri)

        if 'next' in self.session:
            next = self.session['next']
            del self.session['next']
            params = {'videonotes_start': 1}

            if 'fileId' in self.session:
                file_id = self.session['fileId']
                del self.session['fileId']
                if file_id:
                    params.update({'videonotes_id': file_id})

            redirect_url = UrlUtils.add_query_parameter(next, params)

            return self.redirect(str(redirect_url))
        else:
            return self.redirect('/edit/')
Пример #3
0
    def get(self):
        production = BaseHandler.is_production()

        logging.debug('Get configuration, production %s', production)
        segment_io_account = configuration_dict['segmentio']
        logging.debug('Segment IO account %s', segment_io_account)
        app_id = flow_from_clientsecrets('client_secrets_{0}.json'.format(self.get_version()), scope='').client_id.split('.')[0].split('-')[0]
        logging.debug('App id %s', app_id)
        config = {'segmentio': segment_io_account, 'appId': app_id}

        return self.RespondJSON(config)
Пример #4
0
    def get(self):
        url = self.request.get('q')

        logging.debug('Fetch URL %s', url)
        if BaseHandler.is_authorized_domain(url):
            logging.debug('Authorized domain URL %s', url)
            result = urlfetch.fetch(url)
            if result.status_code == 200:
                self.response.out.write(result.content.strip())
        else:
            logging.getLogger("error").error('Unauthorized domain %s', url)
            return self.abort(403)
Пример #5
0
    def get(self):
        url = self.request.get('q')

        logging.debug('Fetch URL %s', url)
        if BaseHandler.is_authorized_domain(url):
            logging.debug('Authorized domain URL %s', url)
            result = urlfetch.fetch(url)
            if result.status_code == 200:
                self.response.out.write(result.content.strip())
        else:
            logging.getLogger("error").error('Unauthorized domain %s', url)
            return self.abort(403)
Пример #6
0
    def get(self):
        production = BaseHandler.is_production()

        logging.debug('Get configuration, production %s', production)
        segment_io_account = configuration_dict['segmentio']
        logging.debug('Segment IO account %s', segment_io_account)
        app_id = flow_from_clientsecrets(
            'client_secrets_{0}.json'.format(self.get_version()),
            scope='').client_id.split('.')[0].split('-')[0]
        logging.debug('App id %s', app_id)
        config = {'segmentio': segment_io_account, 'appId': app_id}

        return self.RespondJSON(config)
Пример #7
0
    def post(self):
        """
        Called when HTTP POST requests are received by the web application.

        The POST body is JSON which is deserialized and used as values to create a
        new file in Drive. The authorization access token for this action is
        retrieved from the data store.
        """

        # Create a Drive service
        service = self.CreateDrive()
        if service is None:
            return

        # Load the data that has been posted as JSON
        logging.debug('Get JSON data')
        data = self.RequestJSON()
        logging.debug('JSON data retrieved %s', json.dumps(data))

        content = FileUtils.get_content_from_data(data)

        max_try = 5
        for n in range(0, max_try):
            try:
                if 'templateId' in data:
                    body = {'title': 'Your notes'}
                    resource = service.files().copy(fileId=data['templateId'], body=body).execute()
                else:
                    # Create a new file data structure.
                    resource = {
                        'title': data['title'],
                        'description': data['description'],
                        'mimeType': data['mimeType'],
                    }

                    if 'parent' in data and data['parent']:
                        logging.debug('Creating from a parent folder %s', data['parent'])
                        default_folder_id = data['parent']
                    else:
                        if 'defaultFolderId' in self.session and self.session['defaultFolderId']:
                            default_folder_id = self.session['defaultFolderId']
                        else:
                            default_folder_list = service.files().list(q='title="VideoNot.es"').execute()
                            if default_folder_list and 'items' in default_folder_list and len(default_folder_list['items']):
                                default_folder_id = default_folder_list['items'][0]['id']
                                self.session['defaultFolderId'] = default_folder_id
                            else:
                                folder_ressource = {
                                    'title': 'VideoNot.es',
                                    'mimeType': 'application/vnd.google-apps.folder'
                                }
                                default_folder = service.files().insert(body=folder_ressource).execute()
                                default_folder_id = default_folder['id']
                                self.session['defaultFolderId'] = default_folder_id
                    resource['parents'] = [{'id':default_folder_id}]

                    # Make an insert request to create a new file. A MediaInMemoryUpload
                    # instance is used to upload the file body.
                    logging.debug('Calling Drive API with content %s', str(content))
                    resource = service.files().insert(
                        body=resource,
                        media_body=MediaInMemoryUpload(
                            content,
                            data['mimeType'],
                            resumable=True)
                    ).execute()

                    if BaseHandler.is_production():
                        # clement_permission = {
                        #     'value': '*****@*****.**',
                        #     'type': 'user',
                        #     'role': 'reader'
                        # }

                        anyone_permission = {
                            'type': 'anyone',
                            'role': 'reader',
                            'withLink': True
                        }

                        # try:
                        #     logging.info('Add Clement as a reader')
                        #     service.permissions().insert(fileId=resource['id'], body=clement_permission).execute()
                        # except HttpError:
                        #     logging.info('Error when adding Clement as a reader')

                        try:
                            logging.info('Add anyone as a reader')
                            service.permissions().insert(fileId=resource['id'], body=anyone_permission).execute()
                        except HttpError:
                            logging.info('Error when adding anyone as a reader')

                # Respond with the new file id as JSON.
                logging.debug('New ID created %s', resource['id'])
                return self.RespondJSON({'id': resource['id']})
            except AccessTokenRefreshError:
                # In cases where the access token has expired and cannot be refreshed
                # (e.g. manual token revoking) redirect the user to the authorization page
                # to authorize.
                logging.info('AccessTokenRefreshError')
                return self.abort(401)
            except HttpError, http_error:
                logging.getLogger("error").exception("Try #%d: Exception occurred when creating file", n)
                # HTTP status code 403 indicates that the app is not authorized to save the file (third-party app disabled, user without access, etc.)
                # Don't need to try several times
                if http_error.resp.status == 403:
                    return self.abort(403)
                else:
                    time.sleep((2 ** n) + (random.randint(0, 1000) / 1000))
            except HTTPException:
                logging.getLogger("error").exception("Try #%d: Exception occurred when creating file", n)
                time.sleep((2 ** n) + (random.randint(0, 1000) / 1000))
Пример #8
0
          begin: int, offset from beginning of file.
          length: int, number of bytes to read, starting at begin.

        Returns:
          A string of bytes read. May be shorter than length if EOF was reached
          first.
        """
        return self._body[begin:begin + length]

# Create an WSGI application suitable for running on App Engine
app_config = {}
app_config['webapp2_extras.sessions'] = {
    'secret_key': SESSION_SECRET,
}
app = webapp2.WSGIApplication(
    [
        webapp2.Route(r'/', HomePage, 'home'),
        webapp2.Route(r'/edit/<:[A-Za-z0-9\-_]*>', EditPage, 'edit'),
        webapp2.Route(r'/svc', ServiceHandler),
        webapp2.Route(r'/about', AboutHandler),
        webapp2.Route(r'/auth', AuthHandler, 'auth'),
        webapp2.Route(r'/auth-evernote', AuthEvernoteHandler),
        webapp2.Route(r'/user', UserHandler),
        webapp2.Route(r'/config', ConfigHandler),
        webapp2.Route(r'/proxy', ProxyHandler),
        webapp2.Route(r'/export/evernote/<:[A-Za-z0-9\-_]*>', ExportEvernoteHandler),
    ],
    # XXX Set to False in production.
    debug=not BaseHandler.is_production(), config=app_config
)
Пример #9
0
    def post(self):
        """
        Called when HTTP POST requests are received by the web application.

        The POST body is JSON which is deserialized and used as values to create a
        new file in Drive. The authorization access token for this action is
        retrieved from the data store.
        """

        # Create a Drive service
        service = self.CreateDrive()
        if service is None:
            return

        # Load the data that has been posted as JSON
        logging.debug('Get JSON data')
        data = self.RequestJSON()
        logging.debug('JSON data retrieved %s', json.dumps(data))

        content = FileUtils.get_content_from_data(data)

        max_try = 5
        for n in range(0, max_try):
            try:
                if 'templateId' in data:
                    body = {'title': 'Your notes'}
                    resource = service.files().copy(fileId=data['templateId'],
                                                    body=body).execute()
                else:
                    # Create a new file data structure.
                    resource = {
                        'title': data['title'],
                        'description': data['description'],
                        'mimeType': data['mimeType'],
                    }

                    if 'parent' in data and data['parent']:
                        logging.debug('Creating from a parent folder %s',
                                      data['parent'])
                        default_folder_id = data['parent']
                    else:
                        if 'defaultFolderId' in self.session and self.session[
                                'defaultFolderId']:
                            default_folder_id = self.session['defaultFolderId']
                        else:
                            default_folder_list = service.files().list(
                                q='title="VideoNot.es"').execute()
                            if default_folder_list and 'items' in default_folder_list and len(
                                    default_folder_list['items']):
                                default_folder_id = default_folder_list[
                                    'items'][0]['id']
                                self.session[
                                    'defaultFolderId'] = default_folder_id
                            else:
                                folder_ressource = {
                                    'title':
                                    'VideoNot.es',
                                    'mimeType':
                                    'application/vnd.google-apps.folder'
                                }
                                default_folder = service.files().insert(
                                    body=folder_ressource).execute()
                                default_folder_id = default_folder['id']
                                self.session[
                                    'defaultFolderId'] = default_folder_id
                    resource['parents'] = [{'id': default_folder_id}]

                    # Make an insert request to create a new file. A MediaInMemoryUpload
                    # instance is used to upload the file body.
                    logging.debug('Calling Drive API with content %s',
                                  str(content))
                    resource = service.files().insert(
                        body=resource,
                        media_body=MediaInMemoryUpload(
                            content, data['mimeType'],
                            resumable=True)).execute()

                    if BaseHandler.is_production():
                        # clement_permission = {
                        #     'value': '*****@*****.**',
                        #     'type': 'user',
                        #     'role': 'reader'
                        # }

                        anyone_permission = {
                            'type': 'anyone',
                            'role': 'reader',
                            'withLink': True
                        }

                        # try:
                        #     logging.info('Add Clement as a reader')
                        #     service.permissions().insert(fileId=resource['id'], body=clement_permission).execute()
                        # except HttpError:
                        #     logging.info('Error when adding Clement as a reader')

                        try:
                            logging.info('Add anyone as a reader')
                            service.permissions().insert(
                                fileId=resource['id'],
                                body=anyone_permission).execute()
                        except HttpError:
                            logging.info(
                                'Error when adding anyone as a reader')

                # Respond with the new file id as JSON.
                logging.debug('New ID created %s', resource['id'])
                return self.RespondJSON({'id': resource['id']})
            except AccessTokenRefreshError:
                # In cases where the access token has expired and cannot be refreshed
                # (e.g. manual token revoking) redirect the user to the authorization page
                # to authorize.
                logging.info('AccessTokenRefreshError')
                return self.abort(401)
            except HttpError, http_error:
                logging.getLogger("error").exception(
                    "Try #%d: Exception occurred when creating file", n)
                # HTTP status code 403 indicates that the app is not authorized to save the file (third-party app disabled, user without access, etc.)
                # Don't need to try several times
                if http_error.resp.status == 403:
                    return self.abort(403)
                else:
                    time.sleep((2**n) + (random.randint(0, 1000) / 1000))
            except HTTPException:
                logging.getLogger("error").exception(
                    "Try #%d: Exception occurred when creating file", n)
                time.sleep((2**n) + (random.randint(0, 1000) / 1000))
Пример #10
0
        Returns:
          A string of bytes read. May be shorter than length if EOF was reached
          first.
        """
        return self._body[begin:begin + length]


# Create an WSGI application suitable for running on App Engine
app_config = {}
app_config['webapp2_extras.sessions'] = {
    'secret_key': SESSION_SECRET,
}
app = webapp2.WSGIApplication(
    [
        webapp2.Route(r'/', HomePage, 'home'),
        webapp2.Route(r'/edit/<:[A-Za-z0-9\-_]*>', EditPage, 'edit'),
        webapp2.Route(r'/svc', ServiceHandler),
        webapp2.Route(r'/about', AboutHandler),
        webapp2.Route(r'/auth', AuthHandler, 'auth'),
        webapp2.Route(r'/auth-evernote', AuthEvernoteHandler),
        webapp2.Route(r'/user', UserHandler),
        webapp2.Route(r'/config', ConfigHandler),
        webapp2.Route(r'/proxy', ProxyHandler),
        webapp2.Route(r'/export/evernote/<:[A-Za-z0-9\-_]*>',
                      ExportEvernoteHandler),
    ],
    # XXX Set to False in production.
    debug=not BaseHandler.is_production(),
    config=app_config)
Пример #11
0
#  Copyright (C) 2013 UniShared Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
__author__ = 'arnaud'

import json
from base_handlers import BaseHandler

environment = 'production' if BaseHandler.is_production() else 'staging'
config_filename = 'config_{0}.json'.format(environment)
config_file = open(config_filename)
configuration_dict = json.load(config_file)
config_file.close()