@Override
  public <T extends ExtRepositoryObject> T getExtRepositoryObject(
      ExtRepositoryObjectType<T> extRepositoryObjectType,
      String extRepositoryFolderKey,
      String title)
      throws PortalException {

    try {
      StringBundler sb = new StringBundler();

      sb.append("'");
      sb.append(extRepositoryFolderKey);
      sb.append("' in parents and title contains '");
      sb.append(title);
      sb.append(" and mimeType ");

      if (extRepositoryObjectType.equals(ExtRepositoryObjectType.FOLDER)) {

        sb.append("= ");
      } else {
        sb.append("!= ");
      }

      sb.append(_FOLDER_MIME_TYPE);

      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

      Drive.Files.List driveFilesList = driveFiles.list();

      driveFilesList.setQ(sb.toString());

      FileList fileList = driveFilesList.execute();

      List<File> files = fileList.getItems();

      if (files.isEmpty()) {
        if (extRepositoryObjectType == ExtRepositoryObjectType.FOLDER) {
          throw new NoSuchFolderException(title);
        }

        throw new NoSuchFileEntryException(title);
      }

      if (extRepositoryObjectType.equals(ExtRepositoryObjectType.FOLDER)) {

        return (T) new GoogleDriveFolder(files.get(0), getRootFolderKey());
      }

      return (T) new GoogleDriveFileEntry(files.get(0));
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  @Override
  public List<ExtRepositorySearchResult<?>> search(
      SearchContext searchContext, Query query, ExtRepositoryQueryMapper extRepositoryQueryMapper)
      throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

      Drive.Files.List driveFilesList = driveFiles.list();

      String searchQuery =
          getSearchQuery(
              searchContext.getKeywords(), searchContext.getFolderIds(), extRepositoryQueryMapper);

      driveFilesList.setQ(searchQuery);

      FileList fileList = driveFilesList.execute();

      List<File> files = fileList.getItems();

      List<ExtRepositorySearchResult<?>> extRepositorySearchResults = new ArrayList<>(files.size());

      for (File file : files) {
        if (_FOLDER_MIME_TYPE.equals(file.getMimeType())) {
          GoogleDriveFolder googleDriveFolder = new GoogleDriveFolder(file, getRootFolderKey());

          ExtRepositorySearchResult<GoogleDriveFolder> extRepositorySearchResult =
              new ExtRepositorySearchResult<>(googleDriveFolder, 1.0f, StringPool.BLANK);

          extRepositorySearchResults.add(extRepositorySearchResult);
        } else {
          GoogleDriveFileEntry googleDriveFileEntry = new GoogleDriveFileEntry(file);

          ExtRepositorySearchResult<GoogleDriveFileEntry> extRepositorySearchResult =
              new ExtRepositorySearchResult<>(googleDriveFileEntry, 1.0f, StringPool.BLANK);

          extRepositorySearchResults.add(extRepositorySearchResult);
        }
      }

      return extRepositorySearchResults;
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
Example #3
0
  /**
   * Store all text/plain files from Drive that the app has access to. This is called the first time
   * the app synchronize the database with Google Drive for the current user.
   */
  private void storeAllDriveFiles() {
    try {
      Files.List request = mService.files().list().setQ("mimeType = '" + TEXT_PLAIN + "'");
      Map<String, File> textFiles = new HashMap<String, File>();

      do {
        try {
          FileList files = request.execute();

          for (File file : files.getItems()) {
            textFiles.put(file.getId(), file);
          }
          request.setPageToken(files.getNextPageToken());
        } catch (IOException e) {
          System.out.println("An error occurred: " + e);
          request.setPageToken(null);
        }
      } while (request.getPageToken() != null && request.getPageToken().length() > 0);

      // Merge with files that are already in the database.
      try {
        Uri uri = getNotesUri(mAccount.name);
        Cursor cursor =
            mProvider.query(
                uri, PROJECTION, NotePad.Notes.COLUMN_NAME_FILE_ID + " IS NOT NULL", null, null);

        if (cursor.moveToFirst()) {
          do {
            String fileId = cursor.getString(COLUMN_INDEX_FILE_ID);

            if (textFiles.containsKey(fileId)) {
              Uri localFileUri = getNoteUri(mAccount.name, cursor.getString(COLUMN_INDEX_ID));
              mergeFiles(localFileUri, cursor, textFiles.get(fileId));
              textFiles.remove(fileId);
            }
          } while (cursor.moveToNext());
        }
      } catch (RemoteException e) {
        e.printStackTrace();
      }

      insertNewDriveFiles(textFiles.values());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #4
0
  /**
   * Searches docs in user's Google Documents.
   *
   * @param title the title of doc
   * @param activity to get context
   * @param accountName the name of Google account
   * @return the file list of the document, null means can not find the spreadsheets
   */
  public static List<File> searchAllSpreadsheetByTitle(
      String title, Activity activity, String accountName) {
    try {
      GoogleAccountCredential driveCredential =
          SendToGoogleUtils.getGoogleAccountCredential(
              activity.getApplicationContext(), accountName, SendToGoogleUtils.DRIVE_SCOPE);
      if (driveCredential == null) {
        return null;
      }

      Drive drive = SyncUtils.getDriveService(driveCredential);
      com.google.api.services.drive.Drive.Files.List list =
          drive
              .files()
              .list()
              .setQ(
                  String.format(Locale.US, SendSpreadsheetsAsyncTask.GET_SPREADSHEET_QUERY, title));
      FileList result = list.execute();
      return result.getItems();
    } catch (Exception e) {
      Log.e(EndToEndTestUtils.LOG_TAG, "Search spreadsheet failed.");
    }
    return null;
  }
  @Override
  public <T extends ExtRepositoryObject> List<T> getExtRepositoryObjects(
      ExtRepositoryObjectType<T> extRepositoryObjectType, String extRepositoryFolderKey)
      throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Files driveFiles = drive.files();

      Drive.Files.List driveFilesList = driveFiles.list();

      StringBundler sb = new StringBundler();

      if (extRepositoryFolderKey != null) {
        sb.append("'");
        sb.append(extRepositoryFolderKey);
        sb.append("' in parents and ");
      }

      if (!extRepositoryObjectType.equals(ExtRepositoryObjectType.OBJECT)) {

        sb.append("mimeType");

        if (extRepositoryObjectType.equals(ExtRepositoryObjectType.FILE)) {

          sb.append(" != '");
        } else {
          sb.append(" = '");
        }

        sb.append(_FOLDER_MIME_TYPE);
        sb.append("' and ");
      }

      sb.append("trashed = false");

      driveFilesList.setQ(sb.toString());

      FileList fileList = driveFilesList.execute();

      List<File> files = fileList.getItems();

      List<T> extRepositoryObjects = new ArrayList<>();

      GoogleDriveCache googleDriveCache = GoogleDriveCache.getInstance();

      for (File file : files) {
        if (_FOLDER_MIME_TYPE.equals(file.getMimeType())) {
          extRepositoryObjects.add((T) new GoogleDriveFolder(file, getRootFolderKey()));
        } else {
          extRepositoryObjects.add((T) new GoogleDriveFileEntry(file));
        }

        googleDriveCache.put(file);
      }

      return extRepositoryObjects;
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  private void syncNotes(final String syncAccountName, final String accessToken) {
    final Drive drive = getDriveService(syncAccountName, accessToken);
    ContentResolver cr = getContentResolver();
    try {
      // loop over saved files and add any new notes to drive
      Cursor savedNotes =
          cr.query(NotesProvider.CONTENT_URI, NotesSyncQuery.PROJECTION, null, null, null);
      if (savedNotes.moveToFirst()) {
        do {
          final String driveId = savedNotes.getString(NotesSyncQuery.DRIVE_ID);
          if (TextUtils.isEmpty(driveId)) {
            // exists locally but not in drive Ð upload it
            File newNote = new File();
            newNote.setTitle(savedNotes.getString(NotesSyncQuery.TITLE));
            newNote.setMimeType(NOTE_MIME_TYPE);

            File inserted =
                drive
                    .files()
                    .insert(
                        newNote,
                        ByteArrayContent.fromString(
                            NOTE_MIME_TYPE, savedNotes.getString(NotesSyncQuery.BODY)))
                    .execute();

            // save the drive id to the db
            ContentValues cv = new ContentValues();
            cv.put(NotesProvider.KEY_DRIVE_ID, inserted.getId());
            Uri noteUri =
                ContentUris.withAppendedId(
                    NotesProvider.CONTENT_URI, savedNotes.getLong(NotesSyncQuery.ID));
            cr.update(noteUri, cv, null, null);
          } else {
            // TODO compare timestamps etc.
          }
        } while (savedNotes.moveToNext());
      }

      // loop over all files in drive and see if any need to be
      // synced locally
      FileList driveFilesList = drive.files().list().execute();
      for (File remote : driveFilesList.getItems()) {
        if (remote.getLabels().getTrashed()) {
          // skip deleted files
          continue;
        }
        final String where = NotesProvider.KEY_DRIVE_ID + "=?";
        final String[] arguments = new String[] {remote.getId()};
        Cursor c =
            cr.query(
                NotesProvider.CONTENT_URI, NotesDownloadQuery.PROJECTION, where, arguments, null);
        if (c.getCount() == 0) {
          // exists in drive but not locally Ð download it
          final String title = remote.getTitle();
          final String body = getFileContents(drive, remote.getDownloadUrl());
          final ContentValues cv = new ContentValues();
          cv.put(NotesProvider.KEY_TITLE, title);
          cv.put(NotesProvider.KEY_BODY, body);
          cv.put(NotesProvider.KEY_DRIVE_ID, remote.getId());
          cv.put(NotesProvider.KEY_LAST_MODIFIED, remote.getModifiedDate().getValue());
          cr.insert(NotesProvider.CONTENT_URI, cv);
        } else {
          // TODO compare timestamps etc.
        }
      }

    } catch (IOException e) {
      // FIXME error handling
      Log.e(getClass().getSimpleName(), "Drive esplode", e);
    }
  }