Example #1
0
def shatner (request):
  da = DriveAuth(request)
  creds = da.get_session_credentials()
  if creds is None:
    return http.HttpResponseForbidden('Login Again')
    
  task = request.POST.get('task', '')
  if task in ('open', 'save'):
    service = CreateService('drive', 'v2', creds)
    
    if service is None:
      return http.HttpResponseServerError('Something broke')
      
    if task == 'open':
      file_id = request.POST.get('file_id', '')
      if file_id:
        try:
          f = service.files().get(fileId=file_id).execute()
          
        except AccessTokenRefreshError:
          return http.HttpResponseForbidden('Login Again')
          
        downloadUrl = f.get('downloadUrl')
        f['content'] = ''
        if downloadUrl:
          resp, f['content'] = service._http.request(downloadUrl)
          
        return http.HttpResponse(
          json.dumps({'status': 'ok', 'file': f}),
          content_type='application/json'
        )
        
    elif task == 'save':
      mt = 'text/plain'
      name = request.POST.get('name')
      content = request.POST.get('content', '')
      file_id = request.POST.get('file_id', '')
        
      resource = {'title': name, 'mimeType': mt}
      
      file = MediaInMemoryUpload(content.encode('utf-8'), mt)
      try:
        google = service.files().update(
          fileId=file_id,
          newRevision=True,
          body=resource,
          media_body=file,
          useContentAsIndexableText=True,
        ).execute()
        
      except AccessTokenRefreshError:
        return http.HttpResponseForbidden('Login Again')
        
      return http.HttpResponse(
        json.dumps({'status': 'ok'}),
        content_type='application/json'
      )
      
    return http.HttpResponseBadRequest('Bad Request')
    
Example #2
0
    def get(self):
        try:
            driveid = self.request.get('id')

            if not driveid:
                return self.abort(401)

            preslink = models.PresentationLink.gql("WHERE driveid = :1", driveid).get()
            userid = preslink.userid

            if not userid:
                return self.abort(404)

            credentials = StorageByKeyName(models.UserCredentials, userid, 'credentials').get()
            
            if not credentials:
                return self.abort(403)

            drive = DriveCommunicator(credentials)
            
            presentation = GoogleDrivePresentation(drive, driveid)

            self.response.headers['Content-Type'] = 'application/json'
            self.response.out.write(json.dumps(presentation.get_data()))

        except errors.HttpError, error:
            return self.remove_auth()
Example #3
0
  def RespondJSON(self, data):
    """Generate a JSON response and return it to the client.

    Args:
      data: The data that will be converted to JSON to return.
    """
    self.response.headers['Content-Type'] = 'application/json'
    self.response.out.write(json.dumps(data))
Example #4
0
    def RespondJSON(self, data):
        """Generate a JSON response and return it to the client.

    Args:
      data: The data that will be converted to JSON to return.
    """
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(data))
Example #5
0
def UpdateSlide(driveid, slideid):
    channel.send_message(
        driveid,
        json.dumps({
                "action" : "changeSlide",
                "slideid" : slideid
            })
    )
Example #6
0
 def ServiceDecoratedView(handler, view=view):
     service = CreateDrive(handler)
     if handler.request.body:
         data = json.loads(handler.request.body)
     else:
         data = None
     response_data = json.dumps(view(handler, service, data))
     handler.response.headers['Content-Type'] = 'application/json'
     handler.response.out.write(response_data)
 def ServiceDecoratedView(handler, view=view):
   service = CreateDrive(handler)
   if handler.request.body:
     data = json.loads(handler.request.body)
   else:
     data = None
   response_data = json.dumps(view(handler, service, data))
   handler.response.headers['Content-Type'] = 'application/json'
   handler.response.out.write(response_data)
Example #8
0
    def RespondJSON(self, data):
        """Generate a JSON response and return it to the client.

        Args:
          data: The data that will be converted to JSON to return.
        """
        self.response.headers['Access-Control-Allow-Origin'] = 'https://www.udacity.com'
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(data))
Example #9
0
    def put(self):
        """
        Called when HTTP PUT requests are received by the web application.

        The PUT body is JSON which is deserialized and used as values to update
        a file in Drive. The authorization access token for this action is
        retreived 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))

        logging.info('Updating file %s', data['id'])

        # Create a new file data structure.
        content = FileUtils.get_content_from_data(data)
        #data['indexableText'] = {'text': content['content']}

        max_try = 5
        for n in range(0, max_try):
            try:
                if content is not None:
                    # Make an update request to update the file. A MediaInMemoryUpload
                    # instance is used to upload the file body. Because of a limitation, this
                    # request must be made in two parts, the first to update the metadata, and
                    # the second to update the body.
                    resource = service.files().update(
                        fileId=data['id'],
                        newRevision=self.request.get('newRevision', False),
                        body=data,
                        media_body=MediaInMemoryUpload(
                            content, data['mimeType'], resumable=True)
                    ).execute()
                else:
                    # Only update the metadata, a patch request is prefered but not yet
                    # supported on Google App Engine; see
                    # http://code.google.com/p/googleappengine/issues/detail?id=6316.
                    resource = service.files().update(
                        fileId=data['id'],
                        newRevision=self.request.get('newRevision', False),
                        body=data).execute()
                    # Respond with the new file id as JSON.
                return self.RespondJSON({'id': resource['id']})
            except HttpError, http_error:
                logging.getLogger("error").exception("Try #%d: Exception occurred when updating 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 updating file", n)
                time.sleep((2 ** n) + (random.randint(0, 1000) / 1000))
Example #10
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))
Example #11
0
    def put(self):
        """
        Called when HTTP PUT requests are received by the web application.

        The PUT body is JSON which is deserialized and used as values to update
        a file in Drive. The authorization access token for this action is
        retreived 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))

        logging.info('Updating file %s', data['id'])

        # Create a new file data structure.
        content = FileUtils.get_content_from_data(data)
        #data['indexableText'] = {'text': content['content']}

        max_try = 5
        for n in range(0, max_try):
            try:
                if content is not None:
                    # Make an update request to update the file. A MediaInMemoryUpload
                    # instance is used to upload the file body. Because of a limitation, this
                    # request must be made in two parts, the first to update the metadata, and
                    # the second to update the body.
                    resource = service.files().update(
                        fileId=data['id'],
                        newRevision=self.request.get('newRevision', False),
                        body=data,
                        media_body=MediaInMemoryUpload(
                            content, data['mimeType'],
                            resumable=True)).execute()
                else:
                    # Only update the metadata, a patch request is prefered but not yet
                    # supported on Google App Engine; see
                    # http://code.google.com/p/googleappengine/issues/detail?id=6316.
                    resource = service.files().update(
                        fileId=data['id'],
                        newRevision=self.request.get('newRevision', False),
                        body=data).execute()
                    # Respond with the new file id as JSON.
                return self.RespondJSON({'id': resource['id']})
            except HttpError, http_error:
                logging.getLogger("error").exception(
                    "Try #%d: Exception occurred when updating 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 updating file", n)
                time.sleep((2**n) + (random.randint(0, 1000) / 1000))
Example #12
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))