private void logSetCookiesAtResponse(Header[] headers) {
   int counter = 0;
   for (int i = 0; i < headers.length; i++) {
     if (headers[i].getName().toLowerCase().equals("set-cookie")) {
       Log_OC.d(
           TAG + " #" + mInstanceNumber,
           "Set-Cookie (" + counter++ + "): " + headers[i].getValue());
     }
   }
   if (counter == 0) {
     Log_OC.d(TAG + " #" + mInstanceNumber, "No set-cookie");
   }
 }
 private void logCookiesAtRequest(Header[] headers, String when) {
   int counter = 0;
   for (int i = 0; i < headers.length; i++) {
     if (headers[i].getName().toLowerCase().equals("cookie")) {
       Log_OC.d(
           TAG + " #" + mInstanceNumber,
           "Cookies at request (" + when + ") (" + counter++ + "): " + headers[i].getValue());
     }
   }
   if (counter == 0) {
     Log_OC.d(TAG + " #" + mInstanceNumber, "No cookie at request before");
   }
 }
  /**
   * Registers a local file to be observed for changes.
   *
   * @param localPath Absolute path in the local file system to the file to be observed.
   * @param account OwnCloud account associated to the local file.
   */
  private void addObservedFile(String localPath, Account account) {
    File file = new File(localPath);
    String parentPath = file.getParent();
    FolderObserver observer = mFolderObserversMap.get(parentPath);
    if (observer == null) {
      observer = new FolderObserver(parentPath, account, getApplicationContext());
      mFolderObserversMap.put(parentPath, observer);
      Log_OC.d(TAG, "Observer added for parent folder " + parentPath + "/");
    }

    observer.startWatching(file.getName());
    Log_OC.d(TAG, "Added " + localPath + " to list of observed children");
  }
  /**
   * Unregisters a local file from being observed for changes.
   *
   * @param localPath Absolute path in the local file system to the target file.
   */
  private void removeObservedFile(String localPath) {
    File file = new File(localPath);
    String parentPath = file.getParent();
    FolderObserver observer = mFolderObserversMap.get(parentPath);
    if (observer != null) {
      observer.stopWatching(file.getName());
      if (observer.isEmpty()) {
        mFolderObserversMap.remove(parentPath);
        Log_OC.d(TAG, "Observer removed for parent folder " + parentPath + "/");
      }

    } else {
      Log_OC.d(TAG, "No observer to remove for path " + localPath);
    }
  }
  /**
   * Entry point to add a new operation to the queue of operations.
   *
   * <p>New operations are added calling to startService(), resulting in a call to this method. This
   * ensures the service will keep on working although the caller activity goes away.
   */
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log_OC.d(TAG, "Starting command with id " + startId);

    // WIP: for the moment, only SYNC_FOLDER is expected here;
    // the rest of the operations are requested through the Binder
    if (ACTION_SYNC_FOLDER.equals(intent.getAction())) {

      if (!intent.hasExtra(EXTRA_ACCOUNT) || !intent.hasExtra(EXTRA_REMOTE_PATH)) {
        Log_OC.e(TAG, "Not enough information provided in intent");
        return START_NOT_STICKY;
      }
      Account account = intent.getParcelableExtra(EXTRA_ACCOUNT);
      String remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);

      Pair<Account, String> itemSyncKey = new Pair<Account, String>(account, remotePath);

      Pair<Target, RemoteOperation> itemToQueue = newOperation(intent);
      if (itemToQueue != null) {
        mSyncFolderHandler.add(
            account, remotePath, (SynchronizeFolderOperation) itemToQueue.second);
        Message msg = mSyncFolderHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = itemSyncKey;
        mSyncFolderHandler.sendMessage(msg);
      }

    } else {
      Message msg = mOperationsHandler.obtainMessage();
      msg.arg1 = startId;
      mOperationsHandler.sendMessage(msg);
    }

    return START_NOT_STICKY;
  }
  /**
   * Handles requests to: - (re)start watching (ACTION_START_OBSERVE) - add an {@link OCFile} to be
   * watched (ATION_ADD_OBSERVED_FILE) - stop observing an {@link OCFile} (ACTION_DEL_OBSERVED_FILE)
   */
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    Log_OC.d(TAG, "Starting command " + intent);

    if (intent == null || ACTION_START_OBSERVE.equals(intent.getAction())) {
      // NULL occurs when system tries to restart the service after its
      // process was killed
      startObservation();
      return Service.START_STICKY;

    } else if (ACTION_ADD_OBSERVED_FILE.equals(intent.getAction())) {
      OCFile file = (OCFile) intent.getParcelableExtra(ARG_FILE);
      Account account = (Account) intent.getParcelableExtra(ARG_ACCOUNT);
      addObservedFile(file, account);

    } else if (ACTION_DEL_OBSERVED_FILE.equals(intent.getAction())) {
      removeObservedFile(
          (OCFile) intent.getParcelableExtra(ARG_FILE),
          (Account) intent.getParcelableExtra(ARG_ACCOUNT));

    } else {
      Log_OC.e(TAG, "Unknown action recieved; ignoring it: " + intent.getAction());
    }

    return Service.START_STICKY;
  }
  private RemoteOperationResult(boolean success, int httpCode) {
    mSuccess = success;
    mHttpCode = httpCode;

    if (success) {
      mCode = ResultCode.OK;

    } else if (httpCode > 0) {
      switch (httpCode) {
        case HttpStatus.SC_UNAUTHORIZED:
          mCode = ResultCode.UNAUTHORIZED;
          break;
        case HttpStatus.SC_NOT_FOUND:
          mCode = ResultCode.FILE_NOT_FOUND;
          break;
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
          mCode = ResultCode.INSTANCE_NOT_CONFIGURED;
          break;
        case HttpStatus.SC_CONFLICT:
          mCode = ResultCode.CONFLICT;
          break;
        case HttpStatus.SC_INSUFFICIENT_STORAGE:
          mCode = ResultCode.QUOTA_EXCEEDED;
          break;
        case HttpStatus.SC_FORBIDDEN:
          mCode = ResultCode.FORBIDDEN;
          break;
        default:
          mCode = ResultCode.UNHANDLED_HTTP_CODE;
          Log_OC.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode);
      }
    }
  }
Beispiel #8
0
    @Override
    public void run(AccountManagerFuture<Bundle> future) {
      FileActivity.this.mRedirectingToSetupAccount = false;
      boolean accountWasSet = false;
      if (future != null) {
        try {
          Bundle result;
          result = future.getResult();
          String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
          String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
          if (AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name)) {
            setAccount(new Account(name, type), false);
            accountWasSet = true;
          }
        } catch (OperationCanceledException e) {
          Log_OC.d(TAG, "Account creation canceled");

        } catch (Exception e) {
          Log_OC.e(TAG, "Account creation finished in exception: ", e);
        }

      } else {
        Log_OC.e(TAG, "Account creation callback with null bundle");
      }
      if (!accountWasSet) {
        moveTaskToBack(true);
      }
    }
  public RemoteOperationResult(boolean success, String bodyResponse, int httpCode) {
    mSuccess = success;
    mHttpCode = httpCode;

    if (success) {
      mCode = ResultCode.OK;

    } else if (httpCode > 0) {
      switch (httpCode) {
        case HttpStatus.SC_BAD_REQUEST:
          InputStream is = new ByteArrayInputStream(bodyResponse.getBytes());
          InvalidCharacterExceptionParser xmlParser = new InvalidCharacterExceptionParser();
          try {
            if (xmlParser.parseXMLResponse(is))
              mCode = ResultCode.INVALID_CHARACTER_DETECT_IN_SERVER;

          } catch (Exception e) {
            mCode = ResultCode.UNHANDLED_HTTP_CODE;
            Log_OC.e(TAG, "Exception reading exception from server", e);
          }
          break;
        default:
          mCode = ResultCode.UNHANDLED_HTTP_CODE;
          Log_OC.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode);
      }
    }
  }
 /**
  * Notifies the currently subscribed listeners about the end of an operation.
  *
  * @param operation Finished operation.
  * @param result Result of the operation.
  */
 protected void dispatchResultToOperationListeners(
     final RemoteOperation operation, final RemoteOperationResult result) {
   int count = 0;
   Iterator<OnRemoteOperationListener> listeners =
       mOperationsBinder.mBoundListeners.keySet().iterator();
   while (listeners.hasNext()) {
     final OnRemoteOperationListener listener = listeners.next();
     final Handler handler = mOperationsBinder.mBoundListeners.get(listener);
     if (handler != null) {
       handler.post(
           new Runnable() {
             @Override
             public void run() {
               listener.onRemoteOperationFinish(operation, result);
             }
           });
       count += 1;
     }
   }
   if (count == 0) {
     Pair<RemoteOperation, RemoteOperationResult> undispatched =
         new Pair<RemoteOperation, RemoteOperationResult>(operation, result);
     mUndispatchedFinishedOperations.put(((Runnable) operation).hashCode(), undispatched);
   }
   Log_OC.d(TAG, "Called " + count + " listeners");
 }
Beispiel #11
0
 @Override
 public void onServiceDisconnected(ComponentName component) {
   if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
     Log_OC.d(TAG, "Operations service disconnected");
     mOperationsServiceBinder = null;
     // TODO whatever could be waiting for the service is unbound
   }
 }
  @Override
  protected int uploadFile(OwnCloudClient client) throws HttpException, IOException {
    int status = -1;

    FileChannel channel = null;
    RandomAccessFile raf = null;
    try {
      File file = new File(mLocalPath);
      raf = new RandomAccessFile(file, "r");
      channel = raf.getChannel();
      mEntity = new ChunkFromFileChannelRequestEntity(channel, mMimeType, CHUNK_SIZE, file);
      // ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(getDataTransferListeners());
      synchronized (mDataTransferListeners) {
        ((ProgressiveDataTransferer) mEntity)
            .addDatatransferProgressListeners(mDataTransferListeners);
      }

      long offset = 0;
      String uriPrefix =
          client.getWebdavUri()
              + WebdavUtils.encodePath(mRemotePath)
              + "-chunking-"
              + Math.abs((new Random()).nextInt(9000) + 1000)
              + "-";
      long chunkCount = (long) Math.ceil((double) file.length() / CHUNK_SIZE);
      for (int chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++, offset += CHUNK_SIZE) {
        if (mPutMethod != null) {
          mPutMethod.releaseConnection(); // let the connection available for other methods
        }
        mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex);
        mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER);
        ((ChunkFromFileChannelRequestEntity) mEntity).setOffset(offset);
        mPutMethod.setRequestEntity(mEntity);
        status = client.executeMethod(mPutMethod);
        client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
        Log_OC.d(
            TAG,
            "Upload of "
                + mLocalPath
                + " to "
                + mRemotePath
                + ", chunk index "
                + chunkIndex
                + ", count "
                + chunkCount
                + ", HTTP result status "
                + status);
        if (!isSuccess(status)) break;
      }

    } finally {
      if (channel != null) channel.close();
      if (raf != null) raf.close();
      if (mPutMethod != null)
        mPutMethod.releaseConnection(); // let the connection available for other methods
    }
    return status;
  }
  private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT
        && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY
            || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

      Header location = method.getResponseHeader("Location");
      if (location == null) {
        location = method.getResponseHeader("location");
      }
      if (location != null) {
        Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());
        method.setURI(new URI(location.getValue(), true));
        Header destination = method.getRequestHeader("Destination");
        if (destination == null) {
          destination = method.getRequestHeader("destination");
        }
        if (destination != null) {
          String locationStr = location.getValue();
          int suffixIndex =
              locationStr.lastIndexOf(
                  (mCredentials instanceof OwnCloudBearerCredentials)
                      ? AccountUtils.ODAV_PATH
                      : AccountUtils.WEBDAV_PATH_4_0);
          String redirectionBase = locationStr.substring(0, suffixIndex);

          String destinationStr = destination.getValue();
          String destinationPath = destinationStr.substring(mBaseUri.toString().length());
          String redirectedDestination = redirectionBase + destinationPath;

          destination.setValue(redirectedDestination);
          method.setRequestHeader(destination);
        }
        status = super.executeMethod(method);
        redirectionsCount++;

      } else {
        Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
        status = HttpStatus.SC_NOT_FOUND;
      }
    }
    return status;
  }
 private void logCookie(Cookie cookie) {
   Log_OC.d(TAG, "Cookie name: " + cookie.getName());
   Log_OC.d(TAG, "       value: " + cookie.getValue());
   Log_OC.d(TAG, "       domain: " + cookie.getDomain());
   Log_OC.d(TAG, "       path: " + cookie.getPath());
   Log_OC.d(TAG, "       version: " + cookie.getVersion());
   Log_OC.d(
       TAG,
       "       expiryDate: "
           + (cookie.getExpiryDate() != null ? cookie.getExpiryDate().toString() : "--"));
   Log_OC.d(TAG, "       comment: " + cookie.getComment());
   Log_OC.d(TAG, "       secure: " + cookie.getSecure());
 }
  /**
   * Attempts to get a new socket connection to the given host within the given time limit.
   *
   * @param host the host name/IP
   * @param port the port on the host
   * @param clientHost the local host name/IP to bind the socket to
   * @param clientPort the port on the local machine
   * @param params {@link HttpConnectionParams Http connection parameters}
   * @return Socket a new socket
   * @throws IOException if an I/O error occurs while creating the socket
   * @throws UnknownHostException if the IP address of the host cannot be determined
   */
  public Socket createSocket(
      final String host,
      final int port,
      final InetAddress localAddress,
      final int localPort,
      final HttpConnectionParams params)
      throws IOException, UnknownHostException, ConnectTimeoutException {
    Log_OC.d(
        TAG,
        "Creating SSL Socket with remote "
            + host
            + ":"
            + port
            + ", local "
            + localAddress
            + ":"
            + localPort
            + ", params: "
            + params);
    if (params == null) {
      throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();

    // logSslInfo();

    SocketFactory socketfactory = mSslContext.getSocketFactory();
    Log_OC.d(
        TAG,
        " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket();
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.setSoTimeout(params.getSoTimeout());
    socket.bind(localaddr);
    ServerNameIndicator.setServerNameIndication(host, (SSLSocket) socket);
    socket.connect(remoteaddr, timeout);
    verifyPeerIdentity(host, port, socket);
    return socket;
  }
  @Override
  protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    GetMethod get = null;

    try {
      // Get Method
      get = new GetMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH);

      // Add Parameters to Get Method
      get.setQueryString(
          new NameValuePair[] {
            new NameValuePair(PARAM_PATH, mRemoteFilePath),
            new NameValuePair(PARAM_RESHARES, String.valueOf(mReshares)),
            new NameValuePair(PARAM_SUBFILES, String.valueOf(mSubfiles))
          });

      get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

      status = client.executeMethod(get);

      if (isSuccess(status)) {
        String response = get.getResponseBodyAsString();

        // Parse xml response and obtain the list of shares
        ShareToRemoteOperationResultParser parser =
            new ShareToRemoteOperationResultParser(new ShareXMLParser());
        parser.setOwnCloudVersion(client.getOwnCloudVersion());
        parser.setServerBaseUri(client.getBaseUri());
        result = parser.parse(response);

        if (result.isSuccess()) {
          Log_OC.d(TAG, "Got " + result.getData().size() + " shares");
        }

      } else {
        result = new RemoteOperationResult(false, status, get.getResponseHeaders());
      }

    } catch (Exception e) {
      result = new RemoteOperationResult(e);
      Log_OC.e(TAG, "Exception while getting shares", e);

    } finally {
      if (get != null) {
        get.releaseConnection();
      }
    }
    return result;
  }
Beispiel #17
0
  /** Initialize the service. */
  @Override
  public void onCreate() {
    Log_OC.d(TAG, "onCreate");
    super.onCreate();

    mDownloadReceiver = new DownloadCompletedReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(FileDownloader.getDownloadAddedMessage());
    filter.addAction(FileDownloader.getDownloadFinishMessage());
    registerReceiver(mDownloadReceiver, filter);

    mFolderObserversMap = new HashMap<String, FolderObserver>();
  }
  @Override
  public int executeMethod(HttpMethod method) throws IOException, HttpException {
    try { // just to log
      boolean customRedirectionNeeded = false;

      try {
        method.setFollowRedirects(mFollowRedirects);
      } catch (Exception e) {
        /*
           if (mFollowRedirects)
        	Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName()
        		+ " method, custom redirection will be used if needed");
        */
        customRedirectionNeeded = mFollowRedirects;
      }

      Log_OC.d(
          TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath());

      //	        logCookiesAtRequest(method.getRequestHeaders(), "before");
      //	        logCookiesAtState("before");

      int status = super.executeMethod(method);

      if (customRedirectionNeeded) {
        status = patchRedirection(status, method);
      }

      //	        logCookiesAtRequest(method.getRequestHeaders(), "after");
      //	        logCookiesAtState("after");
      //	        logSetCookiesAtResponse(method.getResponseHeaders());

      return status;

    } catch (IOException e) {
      Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occured", e);
      throw e;
    }
  }
 private void logCookiesAtState(String string) {
   Cookie[] cookies = getState().getCookies();
   if (cookies.length == 0) {
     Log_OC.d(TAG + " #" + mInstanceNumber, "No cookie at STATE before");
   } else {
     Log_OC.d(TAG + " #" + mInstanceNumber, "Cookies at STATE (before)");
     for (int i = 0; i < cookies.length; i++) {
       Log_OC.d(
           TAG + " #" + mInstanceNumber,
           "    ("
               + i
               + "):"
               + "\n        name: "
               + cookies[i].getName()
               + "\n        value: "
               + cookies[i].getValue()
               + "\n        domain: "
               + cookies[i].getDomain()
               + "\n        path: "
               + cookies[i].getPath());
     }
   }
 }
  /**
   * Returns the fule paths to the files checked by the user
   *
   * @return File paths to the files checked by the user.
   */
  public String[] getCheckedFilePaths() {
    ArrayList<String> result = new ArrayList<String>();
    SparseBooleanArray positions = ((ListView) mCurrentListView).getCheckedItemPositions();
    if (positions.size() > 0) {
      for (int i = 0; i < positions.size(); i++) {
        if (positions.get(positions.keyAt(i)) == true) {
          result.add(
              ((File) mCurrentListView.getItemAtPosition(positions.keyAt(i))).getAbsolutePath());
        }
      }

      Log_OC.d(TAG, "Returning " + result.size() + " selected files");
    }
    return result.toArray(new String[result.size()]);
  }
Beispiel #21
0
    @Override
    public void onReceive(Context context, Intent intent) {
      Log_OC.d(TAG, "Received broadcast intent " + intent);

      File downloadedFile = new File(intent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));
      String parentPath = downloadedFile.getParent();
      FolderObserver observer = mFolderObserversMap.get(parentPath);
      if (observer != null) {
        if (intent.getAction().equals(FileDownloader.getDownloadFinishMessage())
            && downloadedFile.exists()) {
          // no matter if the download was successful or not; the
          // file could be down anyway due to a former download or upload
          observer.startWatching(downloadedFile.getName());
          Log_OC.d(TAG, "Resuming observance of " + downloadedFile.getAbsolutePath());

        } else if (intent.getAction().equals(FileDownloader.getDownloadAddedMessage())) {
          observer.stopWatching(downloadedFile.getName());
          Log_OC.d(TAG, "Pausing observance of " + downloadedFile.getAbsolutePath());
        }

      } else {
        Log_OC.d(TAG, "No observer for path " + downloadedFile.getAbsolutePath());
      }
    }
Beispiel #22
0
  /** Release resources. */
  @Override
  public void onDestroy() {
    Log_OC.d(TAG, "onDestroy - finishing observation of favorite files");

    unregisterReceiver(mDownloadReceiver);

    Iterator<FolderObserver> itOCFolder = mFolderObserversMap.values().iterator();
    while (itOCFolder.hasNext()) {
      itOCFolder.next().stopWatching();
    }
    mFolderObserversMap.clear();
    mFolderObserversMap = null;

    super.onDestroy();
  }
Beispiel #23
0
    @Override
    public void onServiceConnected(ComponentName component, IBinder service) {
      if (component.equals(new ComponentName(FileActivity.this, OperationsService.class))) {
        Log_OC.d(TAG, "Operations service connected");
        mOperationsServiceBinder = (OperationsServiceBinder) service;
        /*if (!mOperationsServiceBinder.isPerformingBlockingOperation()) {
            dismissLoadingDialog();
        }*/
        if (mResumed) {
          doOnResumeAndBound();
        }

      } else {
        return;
      }
    }
  /** Service initialization */
  @Override
  public void onCreate() {
    super.onCreate();
    Log_OC.d(TAG, "Creating service");

    /// First worker thread for most of operations
    HandlerThread thread =
        new HandlerThread("Operations thread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mOperationsHandler = new ServiceHandler(thread.getLooper(), this);
    mOperationsBinder = new OperationsServiceBinder(mOperationsHandler);

    /// Separated worker thread for download of folders (WIP)
    thread = new HandlerThread("Syncfolder thread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mSyncFolderHandler = new SyncFolderHandler(thread.getLooper(), this);
  }
  /**
   * Check if a file exists in the OC server
   *
   * @deprecated Use ExistenceCheckOperation instead
   * @return 'true' if the file exists; 'false' it doesn't exist
   * @throws Exception When the existence could not be determined
   */
  @Deprecated
  public boolean existsFile(String path) throws IOException, HttpException {
    HeadMethod head = new HeadMethod(getWebdavUri() + WebdavUtils.encodePath(path));
    try {
      int status = executeMethod(head);
      Log_OC.d(
          TAG,
          "HEAD to "
              + path
              + " finished with HTTP status "
              + status
              + ((status != HttpStatus.SC_OK) ? "(FAIL)" : ""));
      exhaustResponse(head.getResponseBodyAsStream());
      return (status == HttpStatus.SC_OK);

    } finally {
      head.releaseConnection(); // let the connection available for other methods
    }
  }
Beispiel #26
0
  /**
   * Read from the local database the list of files that must to be kept synchronized and starts
   * observers to monitor local changes on them.
   *
   * <p>Updates the list of currently observed files if called multiple times.
   */
  private void startObservation() {
    Log_OC.d(TAG, "Loading all kept-in-sync files from database to start watching them");

    // query for any favorite file in any OC account
    Cursor cursorOnKeptInSync =
        getContentResolver()
            .query(
                ProviderTableMeta.CONTENT_URI,
                null,
                ProviderTableMeta.FILE_KEEP_IN_SYNC + " = ?",
                new String[] {String.valueOf(1)},
                null);

    if (cursorOnKeptInSync != null) {

      if (cursorOnKeptInSync.moveToFirst()) {

        String localPath = "";
        String accountName = "";
        Account account = null;
        do {
          localPath =
              cursorOnKeptInSync.getString(
                  cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
          accountName =
              cursorOnKeptInSync.getString(
                  cursorOnKeptInSync.getColumnIndex(ProviderTableMeta.FILE_ACCOUNT_OWNER));

          account = new Account(accountName, MainApp.getAccountType());
          if (!AccountUtils.exists(account, this) || localPath == null || localPath.length() <= 0) {
            continue;
          }

          addObservedFile(localPath, account);

        } while (cursorOnKeptInSync.moveToNext());
      }
      cursorOnKeptInSync.close();
    }

    // service does not stopSelf() ; that way it tries to be alive forever

  }
  /** Constructor */
  public OwnCloudClient(Uri baseUri, HttpConnectionManager connectionMgr) {
    super(connectionMgr);

    if (baseUri == null) {
      throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL");
    }
    mBaseUri = baseUri;

    mInstanceNumber = sIntanceCounter++;
    Log_OC.d(TAG + " #" + mInstanceNumber, "Creating OwnCloudClient");

    getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
    getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    getParams()
        .setParameter(
            PARAM_SINGLE_COOKIE_HEADER, // to avoid problems with some web servers
            PARAM_SINGLE_COOKIE_HEADER_VALUE);

    clearCredentials();
  }
Beispiel #28
0
  /**
   * @param operation Removal operation performed.
   * @param result Result of the removal.
   */
  @Override
  public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
    Log_OC.d(
        TAG,
        "Received result of operation in FileActivity - common behaviour for all the "
            + "FileActivities ");

    mFileOperationsHelper.setOpIdWaitingFor(Long.MAX_VALUE);

    dismissLoadingDialog();

    if (!result.isSuccess()
        && (result.getCode() == ResultCode.UNAUTHORIZED
            || result.isIdPRedirection()
            || (result.isException() && result.getException() instanceof AuthenticatorException))) {

      requestCredentialsUpdate();

      if (result.getCode() == ResultCode.UNAUTHORIZED) {
        dismissLoadingDialog();
        Toast t =
            Toast.makeText(
                this,
                ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
                Toast.LENGTH_LONG);
        t.show();
      }

    } else if (operation == null
        || operation instanceof CreateShareWithShareeOperation
        || operation instanceof UnshareOperation
        || operation instanceof SynchronizeFolderOperation
        || operation instanceof UpdateShareViaLinkOperation) {
      if (result.isSuccess()) {
        updateFileFromDB();

      } else if (result.getCode() != ResultCode.CANCELLED) {
        Toast t =
            Toast.makeText(
                this,
                ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
                Toast.LENGTH_LONG);
        t.show();
      }

    } else if (operation instanceof CreateShareViaLinkOperation) {
      onCreateShareViaLinkOperationFinish((CreateShareViaLinkOperation) operation, result);

    } else if (operation instanceof SynchronizeFileOperation) {
      onSynchronizeFileOperationFinish((SynchronizeFileOperation) operation, result);

    } else if (operation instanceof GetSharesForFileOperation) {
      if (result.isSuccess() || result.getCode() == ResultCode.SHARE_NOT_FOUND) {
        updateFileFromDB();

      } else {
        Toast t =
            Toast.makeText(
                this,
                ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
                Toast.LENGTH_LONG);
        t.show();
      }
    }
  }
 /** @see ProtocolSocketFactory#createSocket(java.lang.String,int) */
 public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
   Log_OC.d(TAG, "Creating SSL Socket with remote " + host + ":" + port);
   Socket socket = mSslContext.getSocketFactory().createSocket(host, port);
   verifyPeerIdentity(host, port, socket);
   return socket;
 }
  @Override
  protected RemoteOperationResult run(OwnCloudClient client) {
    AccountManager accountMngr = AccountManager.get(mContext);
    String statUrl = accountMngr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
    statUrl += AccountUtils.STATUS_PATH;
    RemoteOperationResult result = null;
    GetMethod get = null;
    try {
      get = new GetMethod(statUrl);
      int status = client.executeMethod(get);
      if (status != HttpStatus.SC_OK) {
        client.exhaustResponse(get.getResponseBodyAsStream());
        result = new RemoteOperationResult(false, status, get.getResponseHeaders());

      } else {
        String response = get.getResponseBodyAsString();
        if (response != null) {
          JSONObject json = new JSONObject(response);
          if (json != null && json.getString("version") != null) {

            String version = json.getString("version");
            mOwnCloudVersion = new OwnCloudVersion(version);
            if (mOwnCloudVersion.isVersionValid()) {
              accountMngr.setUserData(
                  mAccount, Constants.KEY_OC_VERSION, mOwnCloudVersion.getVersion());
              Log_OC.d(TAG, "Got new OC version " + mOwnCloudVersion.toString());

              result = new RemoteOperationResult(ResultCode.OK);

            } else {
              Log_OC.w(
                  TAG, "Invalid version number received from server: " + json.getString("version"));
              result = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);
            }
          }
        }
        if (result == null) {
          result =
              new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
        }
      }
      Log_OC.i(
          TAG,
          "Check for update of ownCloud server version at "
              + client.getWebdavUri()
              + ": "
              + result.getLogMessage());

    } catch (JSONException e) {
      result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
      Log_OC.e(
          TAG,
          "Check for update of ownCloud server version at "
              + client.getWebdavUri()
              + ": "
              + result.getLogMessage(),
          e);

    } catch (Exception e) {
      result = new RemoteOperationResult(e);
      Log_OC.e(
          TAG,
          "Check for update of ownCloud server version at "
              + client.getWebdavUri()
              + ": "
              + result.getLogMessage(),
          e);

    } finally {
      if (get != null) get.releaseConnection();
    }
    return result;
  }