Beispiel #1
0
def shatner(request):
    da = DriveAuth(request)
    creds = da.get_session_credentials()
    if creds is None:
        return JsonResponse({'status': 'auth_needed'})

    task = request.POST.get('task', '')
    service = CreateService('drive', 'v2', creds)

    if service is None:
        return JsonResponse({'status': 'no_service'})

    if task == 'delete':
        file_id = request.POST.get('file_id', '')
        fid = file_id
        if file_id.endswith('/'):
            fid = file_id[:-1]

        try:
            service.files().trash(fileId=fid).execute()

        except AccessTokenRefreshError:
            return JsonResponse({'status': 'auth_needed'})

        return JsonResponse({'status': 'ok', 'file_id': file_id})

    elif task == 'revs':
        file_id = request.POST.get('file_id', '')
        try:
            revisions = service.revisions().list(fileId=file_id).execute()

        except AccessTokenRefreshError:
            return JsonResponse({'status': 'auth_needed'})

        else:
            #for item in revisions.get('items', []):
            #  logging.info('PIN: ' + str(item['pinned']))
            #  logging.info('PUB: ' + str(item['published']))
            #
            html = render_to_string('main/revs.html', {
                'file_id': file_id,
                'items': revisions.get('items', [])
            })

        return JsonResponse({'status': 'ok', 'file_id': file_id, 'html': html})

    elif task == 'get_url':
        file_id = request.POST.get('file_id', '')
        url = request.POST.get('url', '')

        try:
            resp, content = service._http.request(url)

        except AccessTokenRefreshError:
            return JsonResponse({'status': 'auth_needed'})

        return JsonResponse({
            'status': 'ok',
            'file_id': file_id,
            'text': content
        })

    elif task == 'get_urls':
        file_id = request.POST.get('file_id', '')
        url1 = request.POST.get('url1', '')
        url2 = request.POST.get('url2', '')

        try:
            resp1, content1 = service._http.request(url1)
            resp2, content2 = service._http.request(url2)

        except AccessTokenRefreshError:
            return JsonResponse({'status': 'auth_needed'})

        return JsonResponse({
            'status': 'ok',
            'file_id': file_id,
            'text1': content1,
            'text2': content2
        })

    elif task == 'open':
        file_id = request.POST.get('file_id', '')
        if file_id:
            try:
                f = service.files().get(fileId=file_id).execute()

            except AccessTokenRefreshError:
                return JsonResponse({'status': 'auth_needed'})

            downloadUrl = f.get('downloadUrl')

            if downloadUrl:
                resp, f['content'] = service._http.request(downloadUrl)

            else:
                f['content'] = ''

            fo = FileOpen(userid=da.userid,
                          fileid=file_id,
                          filename=f['title'])
            fo.put()
            return JsonResponse({'status': 'ok', 'file': f})

        return JsonResponse({'status': 'Invalid File'})

    elif task == 'save':
        name = request.POST.get('name')
        mimetype = request.POST.get('mimetype')
        content = request.POST.get('content', '')
        file_id = request.POST.get('file_id', '')
        new_file = request.POST.get('new_file')
        major = request.POST.get('major', '')
        md5hash = request.POST.get('md5hash', '')
        undos = int(request.POST.get('undos', '0'))

        new_revision = False
        if major == 'true':
            new_revision = True

        resource = {'title': name, 'mimeType': mimetype}

        encoding = chardet.detect(content)['encoding']
        dump = None
        if encoding:
            try:
                dump = content.encode(encoding)

            except:
                dump = None

        if dump is None:
            dump = content.encode('utf-8')

        file = MediaInMemoryUpload(dump, mimetype)
        try:
            if new_file == 'false':
                google = service.files().update(fileId=file_id,
                                                newRevision=new_revision,
                                                body=resource,
                                                media_body=file).execute()

            else:
                google = service.files().insert(body=resource,
                                                media_body=file).execute()

        except AccessTokenRefreshError:
            return JsonResponse({'status': 'auth_needed'})

        else:
            file_id = google['id']

        return JsonResponse(ok={
            'file_id': file_id,
            'md5hash': md5hash,
            'undos': undos
        })

    elif task == 'rename':
        name = request.POST.get('name')
        file_id = request.POST.get('file_id', '')
        rtype = request.POST.get('rtype', '')

        resource = {'title': name}
        if rtype == 'd':
            file_id = file_id[:-1]
            resource['mimeType'] = 'application/vnd.google-apps.folder'

        else:
            newm, enc = mimetypes.guess_type(name)
            if newm:
                resource['mimeType'] = newm

        google = service.files().update(fileId=file_id,
                                        newRevision=True,
                                        body=resource).execute()
        parents = []
        for p in google['parents']:
            if p['isRoot']:
                parents.append('')

            else:
                parents.append(p['id'])

        if not parents:
            parents.append('')

        return JsonResponse(ok={
            'file_id': file_id,
            'parents': parents,
            'name': name
        })

    elif task == 'new':
        name = request.POST.get('name')
        parent = request.POST.get('parent', '')

        mime_type, enc = mimetypes.guess_type(name)
        root, ext = os.path.splitext(name)
        if not mime_type:
            mime_type = 'application/octet-stream'

        if ext:
            ext = ext[1:]

        media_body = MediaInMemoryUpload('', mime_type)
        body = {'title': name, 'mimeType': mime_type}

        if parent:
            body['parents'] = [{'id': parent}]

        try:
            google = service.files().insert(body=body,
                                            media_body=media_body).execute()

        except AccessTokenRefreshError:
            return JsonResponse({'status': 'auth_needed'})

        else:
            return JsonResponse(
                ok={
                    'file_id': google['id'],
                    'title': name,
                    'ext': ext,
                    'mime': mime_type,
                    'url': google['alternateLink'],
                    'parent': parent
                })

    elif task == 'new_dir':
        name = request.POST.get('name')
        parent = request.POST.get('parent', '')
        dmt = 'application/vnd.google-apps.folder'

        body = {'title': name, 'mimeType': dmt}

        if parent:
            body['parents'] = [{'id': parent}]

        try:
            google = service.files().insert(body=body).execute()

        except AccessTokenRefreshError:
            return JsonResponse({'status': 'auth_needed'})

        else:
            return JsonResponse(
                ok={
                    'file_id': google['id'],
                    'title': name,
                    'mime': dmt,
                    'parent': parent
                })

    return http.HttpResponseBadRequest('Invalid Task', mimetype='text/plain')
Beispiel #2
0
def shatner (request):
  da = DriveAuth(request)
  creds = da.get_session_credentials()
  if creds is None:
    return JsonResponse({'status': 'auth_needed'})
    
  task = request.POST.get('task', '')
  service = CreateService('drive', 'v2', creds)
  
  if service is None:
    return JsonResponse({'status': 'no_service'})
    
  if task == 'delete':
    file_id = request.POST.get('file_id', '')
    fid = file_id
    if file_id.endswith('/'):
      fid = file_id[:-1]
      
    try:
      service.files().trash(fileId=fid).execute()
      
    except AccessTokenRefreshError:
      return JsonResponse({'status': 'auth_needed'})
      
    return JsonResponse({'status': 'ok', 'file_id': file_id})
    
  elif task == 'revs':
    file_id = request.POST.get('file_id', '')
    try:
      revisions = service.revisions().list(fileId=file_id).execute()
      
    except AccessTokenRefreshError:
      return JsonResponse({'status': 'auth_needed'})
      
    else:
      #for item in revisions.get('items', []):
      #  logging.info('PIN: ' + str(item['pinned']))
      #  logging.info('PUB: ' + str(item['published']))
      #  
      html = render_to_string('main/revs.html', {'file_id': file_id, 'items': revisions.get('items', [])})
      
    return JsonResponse({'status': 'ok', 'file_id': file_id, 'html': html})
    
  elif task == 'get_url':
    file_id = request.POST.get('file_id', '')
    url = request.POST.get('url', '')
    
    try:
      resp, content = service._http.request(url)
      
    except AccessTokenRefreshError:
      return JsonResponse({'status': 'auth_needed'})
      
    return JsonResponse({'status': 'ok', 'file_id': file_id, 'text': content})
    
  elif task == 'get_urls':
    file_id = request.POST.get('file_id', '')
    url1 = request.POST.get('url1', '')
    url2 = request.POST.get('url2', '')
    
    try:
      resp1, content1 = service._http.request(url1)
      resp2, content2 = service._http.request(url2)
      
    except AccessTokenRefreshError:
      return JsonResponse({'status': 'auth_needed'})
      
    return JsonResponse({'status': 'ok', 'file_id': file_id, 'text1': content1, 'text2': content2})
    
  elif task == 'open':
    file_id = request.POST.get('file_id', '')
    if file_id:
      try:
        f = service.files().get(fileId=file_id).execute()
        
      except AccessTokenRefreshError:
        return JsonResponse({'status': 'auth_needed'})
        
      downloadUrl = f.get('downloadUrl')
      
      if downloadUrl:
        resp, f['content'] = service._http.request(downloadUrl)
        
      else:
        f['content'] = ''
        
      fo = FileOpen(userid=da.userid, fileid=file_id, filename=f['title'])
      fo.put()
      return JsonResponse({'status': 'ok', 'file': f})
      
    return JsonResponse({'status': 'Invalid File'})
    
  elif task == 'save':
    name = request.POST.get('name')
    mimetype = request.POST.get('mimetype')
    content = request.POST.get('content', '')
    file_id = request.POST.get('file_id', '')
    new_file = request.POST.get('new_file')
    major = request.POST.get('major', '')
    md5hash = request.POST.get('md5hash', '')
    undos = int(request.POST.get('undos', '0'))
    
    new_revision = False
    if major == 'true':
      new_revision = True
      
    resource = {
      'title': name,
      'mimeType': mimetype
    }
    
    encoding = chardet.detect(content)['encoding']
    dump = None
    if encoding:
      try:
        dump = content.encode(encoding)
        
      except:
        dump = None
        
    if dump is None:
      dump = content.encode('utf-8')
      
    file = MediaInMemoryUpload(dump, mimetype)
    try:
      if new_file == 'false':
        google = service.files().update(fileId=file_id, newRevision=new_revision, body=resource, media_body=file).execute()
        
      else:
        google = service.files().insert(body=resource, media_body=file).execute()
        
    except AccessTokenRefreshError:
      return JsonResponse({'status': 'auth_needed'})
      
    else:
      file_id = google['id']
      
    return JsonResponse(ok={'file_id': file_id, 'md5hash': md5hash, 'undos': undos})
    
  elif task == 'rename':
    name = request.POST.get('name')
    file_id = request.POST.get('file_id', '')
    rtype = request.POST.get('rtype', '')
    
    resource = {'title': name}
    if rtype == 'd':
      file_id = file_id[:-1]
      resource['mimeType'] = 'application/vnd.google-apps.folder'
      
    else:
      newm, enc = mimetypes.guess_type(name)
      if newm:
        resource['mimeType'] = newm
        
    google = service.files().update(fileId=file_id, newRevision=True, body=resource).execute()
    parents = []
    for p in google['parents']:
      if p['isRoot']:
        parents.append('')
        
      else:
        parents.append(p['id'])
        
    if not parents:
      parents.append('')
      
    return JsonResponse(ok={'file_id': file_id, 'parents': parents, 'name': name})
    
  elif task == 'new':
    name = request.POST.get('name')
    parent = request.POST.get('parent', '')
    
    mime_type, enc = mimetypes.guess_type(name)
    root, ext = os.path.splitext(name)
    if not mime_type:
      mime_type = 'application/octet-stream'
      
    if ext:
      ext = ext[1:]
      
    media_body = MediaInMemoryUpload('', mime_type)
    body = {
      'title': name,
      'mimeType': mime_type
    }
    
    if parent:
      body['parents'] = [{'id': parent}]
      
    try:
      google = service.files().insert(body=body, media_body=media_body).execute()
      
    except AccessTokenRefreshError:
      return JsonResponse({'status': 'auth_needed'})
      
    else:
      return JsonResponse(ok={'file_id': google['id'], 'title': name, 'ext': ext, 'mime': mime_type, 'url': google['alternateLink'], 'parent': parent})
      
  elif task == 'new_dir':
    name = request.POST.get('name')
    parent = request.POST.get('parent', '')
    dmt = 'application/vnd.google-apps.folder'
    
    body = {'title': name, 'mimeType': dmt}
    
    if parent:
      body['parents'] = [{'id': parent}]
      
    try:
      google = service.files().insert(body=body).execute()
      
    except AccessTokenRefreshError:
      return JsonResponse({'status': 'auth_needed'})
      
    else:
      return JsonResponse(ok={'file_id': google['id'], 'title': name, 'mime': dmt, 'parent': parent})
        
  return http.HttpResponseBadRequest('Invalid Task', mimetype='text/plain')
Beispiel #3
0
def edit(request):
    error = request.REQUEST.get('error', '')
    if error == 'access_denied':
        return TemplateResponse(request, 'main/access_denied.html', {})

    da = DriveAuth(request)
    creds = da.get_credentials(check_cookie=False)

    if creds is None:
        return da.redirect_auth()

    state = request.REQUEST.get('state', '')
    open_ids = []
    new_in = None

    if state:
        state = json.loads(state)
        if state["action"] == 'open':
            if "exportIds" in state:
                return TemplateResponse(request, 'main/not_supported.html', {})

            elif "ids" in state:
                open_ids = state["ids"]

        elif state["action"] == 'create' and "parentId" in state:
            new_in = state['parentId']

    if da.prefs.save_session and da.prefs.session:
        for oid in da.prefs.session.split(','):
            if oid not in open_ids:
                open_ids.append(oid)

    recent_files = OrderedDict()
    for f in FileOpen.all().filter("userid =",
                                   da.userid).order("-created").fetch(30):
        if f.fileid not in recent_files:
            recent_files[f.fileid] = f.filename
            if len(recent_files) >= 10:
                break

    c = {
        'MODES': MODES,
        'NDEBUG': settings.NDEBUG,
        'CLIENT_ID': settings.GOOGLE_API_CLIENT_ID.split('.')[0],
        'prefs': da.prefs,
        'themes': ETHEMES,
        'sizes': ESIZES,
        'binds': EKBINDS,
        'wraps': EWRAPS,
        'open_ids': open_ids,
        'new_in': new_in,
        'recent_files': recent_files
    }
    response = TemplateResponse(request, 'main/edit.html', c)

    expires = datetime.datetime.utcnow() + datetime.timedelta(
        seconds=settings.MAX_AGE)
    response.set_signed_cookie(
        settings.USERID_COOKIE,
        value=da.userid,
        salt=settings.SALT,
        expires=expires,
        secure=settings.CSRF_COOKIE_SECURE,
        httponly=False,
    )
    return response
Beispiel #4
0
def edit (request):
  error = request.REQUEST.get('error', '')
  if error == 'access_denied':
    return TemplateResponse(request, 'main/access_denied.html', {})
    
  da = DriveAuth(request)
  creds = da.get_credentials(check_cookie=False)
  
  if creds is None:
    return da.redirect_auth()
    
  state = request.REQUEST.get('state', '')
  open_ids = []
  new_in = None
  
  if state:
    state = json.loads(state)
    if state["action"] == 'open':
      if "exportIds" in state:
        return TemplateResponse(request, 'main/not_supported.html', {})
        
      elif "ids" in state:
        open_ids = state["ids"]
        
    elif state["action"] == 'create' and "parentId" in state:
      new_in = state['parentId']
      
  if da.prefs.save_session and da.prefs.session:
    for oid in da.prefs.session.split(','):
      if oid not in open_ids:
        open_ids.append(oid)
        
  recent_files = OrderedDict()
  for f in FileOpen.all().filter("userid =", da.userid).order("-created").fetch(30):
    if f.fileid not in recent_files:
      recent_files[f.fileid] = f.filename
      if len(recent_files) >= 10:
        break
      
  c = {
    'MODES': MODES,
    'NDEBUG': settings.NDEBUG,
    'CLIENT_ID': settings.GOOGLE_API_CLIENT_ID.split('.')[0],
    'prefs': da.prefs,
    'themes': ETHEMES,
    'sizes': ESIZES,
    'binds': EKBINDS,
    'wraps': EWRAPS,
    'open_ids': open_ids,
    'new_in': new_in,
    'recent_files': recent_files
  }
  response = TemplateResponse(request, 'main/edit.html', c)
  
  expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.MAX_AGE)
  response.set_signed_cookie(
    settings.USERID_COOKIE,
    value=da.userid,
    salt=settings.SALT,
    expires=expires,
    secure=settings.CSRF_COOKIE_SECURE,
    httponly=False,
  )
  return response