Browse Source

Rebase master

Signed-off-by: alperozturk <alper_ozturk@proton.me>
alperozturk 1 year ago
parent
commit
81cb6933be

+ 8 - 14
app/src/main/java/com/nextcloud/client/files/downloader/FileTransferService.kt

@@ -22,8 +22,6 @@ package com.nextcloud.client.files.downloader
 import android.app.Service
 import android.content.Context
 import android.content.Intent
-import android.content.pm.ServiceInfo
-import android.os.Build
 import android.os.IBinder
 import com.nextcloud.client.account.User
 import com.nextcloud.client.core.AsyncRunner
@@ -33,7 +31,9 @@ import com.nextcloud.client.logger.Logger
 import com.nextcloud.client.network.ClientFactory
 import com.nextcloud.client.network.ConnectivityService
 import com.nextcloud.client.notifications.AppNotificationManager
+import com.nextcloud.utils.ForegroundServiceHelper
 import com.owncloud.android.datamodel.FileDataStorageManager
+import com.owncloud.android.datamodel.ForegroundServiceType
 import com.owncloud.android.datamodel.UploadsStorageManager
 import dagger.android.AndroidInjection
 import javax.inject.Inject
@@ -109,18 +109,12 @@ class FileTransferService : Service() {
         }
 
         if (!isRunning) {
-            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
-                startForeground(
-                    AppNotificationManager.TRANSFER_NOTIFICATION_ID,
-                    notificationsManager.buildDownloadServiceForegroundNotification(),
-                    ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
-                )
-            } else {
-                startForeground(
-                    AppNotificationManager.TRANSFER_NOTIFICATION_ID,
-                    notificationsManager.buildDownloadServiceForegroundNotification()
-                )
-            }
+            ForegroundServiceHelper.start(
+                this,
+                AppNotificationManager.TRANSFER_NOTIFICATION_ID,
+                notificationsManager.buildDownloadServiceForegroundNotification(),
+                ForegroundServiceType.DataSync
+            )
         }
 
         val request: Request = intent.getParcelableExtra(EXTRA_REQUEST)!!

+ 8 - 10
app/src/main/java/com/nextcloud/client/media/PlayerService.kt

@@ -22,7 +22,6 @@ package com.nextcloud.client.media
 import android.app.PendingIntent
 import android.app.Service
 import android.content.Intent
-import android.content.pm.ServiceInfo
 import android.media.AudioManager
 import android.os.Build
 import android.os.Bundle
@@ -32,7 +31,9 @@ import android.widget.Toast
 import androidx.core.app.NotificationCompat
 import com.nextcloud.client.account.User
 import com.nextcloud.client.network.ClientFactory
+import com.nextcloud.utils.ForegroundServiceHelper
 import com.owncloud.android.R
+import com.owncloud.android.datamodel.ForegroundServiceType
 import com.owncloud.android.datamodel.OCFile
 import com.owncloud.android.ui.notifications.NotificationUtils
 import com.owncloud.android.utils.theme.ViewThemeUtils
@@ -173,15 +174,12 @@ class PlayerService : Service() {
             notificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA)
         }
 
-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
-            startForeground(
-                R.string.media_notif_ticker,
-                notificationBuilder.build(),
-                ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
-            )
-        } else {
-            startForeground(R.string.media_notif_ticker, notificationBuilder.build())
-        }
+        ForegroundServiceHelper.start(
+            this,
+            R.string.media_notif_ticker,
+            notificationBuilder.build(),
+            ForegroundServiceType.MediaPlayback
+        )
 
         isRunning = true
     }

+ 55 - 0
app/src/main/java/com/nextcloud/utils/ForegroundServiceHelper.kt

@@ -0,0 +1,55 @@
+/*
+ * Nextcloud Android client application
+ *
+ * @author Alper Ozturk
+ * Copyright (C) 2023 Alper Ozturk
+ * Copyright (C) 2023 Nextcloud GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+package com.nextcloud.utils
+
+import android.app.Notification
+import android.app.Service
+import android.content.pm.ServiceInfo
+import android.os.Build
+import androidx.core.app.ServiceCompat
+import com.owncloud.android.datamodel.ForegroundServiceType
+
+object ForegroundServiceHelper {
+    fun start(
+        service: Service,
+        id: Int,
+        notification: Notification,
+        foregroundServiceType: ForegroundServiceType
+    ) {
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+            val foregroundServiceTypeId: Int = if (foregroundServiceType == ForegroundServiceType.DataSync) {
+                ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
+            } else {
+                ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
+            }
+
+            ServiceCompat.startForeground(
+                service,
+                id,
+                notification,
+                foregroundServiceTypeId
+            )
+        } else {
+            service.startForeground(id, notification)
+        }
+    }
+}

+ 26 - 0
app/src/main/java/com/owncloud/android/datamodel/ForegroundServiceType.kt

@@ -0,0 +1,26 @@
+/*
+ * Nextcloud Android client application
+ *
+ * @author Alper Ozturk
+ * Copyright (C) 2023 Alper Ozturk
+ * Copyright (C) 2023 Nextcloud GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+
+package com.owncloud.android.datamodel
+
+enum class ForegroundServiceType {
+    DataSync, MediaPlayback
+}

+ 3 - 12
app/src/main/java/com/owncloud/android/files/services/FileDownloader.java

@@ -28,10 +28,8 @@ import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Service;
 import android.content.Intent;
-import android.content.pm.ServiceInfo;
 import android.graphics.BitmapFactory;
 import android.os.Binder;
-import android.os.Build;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.IBinder;
@@ -44,9 +42,11 @@ import com.nextcloud.client.account.User;
 import com.nextcloud.client.account.UserAccountManager;
 import com.nextcloud.client.files.downloader.DownloadTask;
 import com.nextcloud.java.util.Optional;
+import com.nextcloud.utils.ForegroundServiceHelper;
 import com.owncloud.android.R;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.ForegroundServiceType;
 import com.owncloud.android.datamodel.OCFile;
 import com.owncloud.android.datamodel.UploadsStorageManager;
 import com.owncloud.android.lib.common.OwnCloudAccount;
@@ -83,7 +83,6 @@ import java.util.Vector;
 import javax.inject.Inject;
 
 import androidx.core.app.NotificationCompat;
-import androidx.core.app.ServiceCompat;
 import androidx.localbroadcastmanager.content.LocalBroadcastManager;
 import dagger.android.AndroidInjection;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@@ -203,15 +202,7 @@ public class FileDownloader extends Service
     public int onStartCommand(Intent intent, int flags, int startId) {
         Log_OC.d(TAG, "Starting command with id " + startId);
 
-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
-            ServiceCompat.startForeground(
-                this,
-                FOREGROUND_SERVICE_ID,
-                mNotification,
-                ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
-        } else {
-            startForeground(FOREGROUND_SERVICE_ID, mNotification);
-        }
+        ForegroundServiceHelper.INSTANCE.start(this, FOREGROUND_SERVICE_ID, mNotification, ForegroundServiceType.DataSync);
 
         if (intent == null || !intent.hasExtra(EXTRA_USER) || !intent.hasExtra(EXTRA_FILE)) {
             Log_OC.e(TAG, "Not enough information provided in intent");

+ 50 - 54
app/src/main/java/com/owncloud/android/files/services/FileUploader.java

@@ -1,27 +1,24 @@
 /**
- *  ownCloud Android client application
+ * ownCloud Android client application
  *
- *  @author Bartek Przybylski
- *  @author masensio
- *  @author LukeOwnCloud
- *  @author David A. Velasco
- *  @author Chris Narkiewicz
- *
- *  Copyright (C) 2012 Bartek Przybylski
- *  Copyright (C) 2012-2016 ownCloud Inc.
- *  Copyright (C) 2020 Chris Narkiewicz <hello@ezaquarii.com>
- *
- *  This program is free software: you can redistribute it and/or modify
- *  it under the terms of the GNU General Public License version 2,
- *  as published by the Free Software Foundation.
- *
- *  This program is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU General Public License for more details.
- *
- *  You should have received a copy of the GNU General Public License
- *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ * @author Bartek Przybylski
+ * @author masensio
+ * @author LukeOwnCloud
+ * @author David A. Velasco
+ * @author Chris Narkiewicz
+ * <p>
+ * Copyright (C) 2012 Bartek Przybylski Copyright (C) 2012-2016 ownCloud Inc. Copyright (C) 2020 Chris Narkiewicz
+ * <hello@ezaquarii.com>
+ * <p>
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
+ * License version 2, as published by the Free Software Foundation.
+ * <p>
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
+ * details.
+ * <p>
+ * You should have received a copy of the GNU General Public License along with this program.  If not, see
+ * <http://www.gnu.org/licenses/>.
  */
 
 package com.owncloud.android.files.services;
@@ -37,7 +34,6 @@ import android.app.Service;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
-import android.content.pm.ServiceInfo;
 import android.graphics.BitmapFactory;
 import android.os.Binder;
 import android.os.Build;
@@ -59,10 +55,12 @@ import com.nextcloud.client.network.Connectivity;
 import com.nextcloud.client.network.ConnectivityService;
 import com.nextcloud.client.utils.FileUploaderDelegate;
 import com.nextcloud.java.util.Optional;
+import com.nextcloud.utils.ForegroundServiceHelper;
 import com.owncloud.android.MainApp;
 import com.owncloud.android.R;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.ForegroundServiceType;
 import com.owncloud.android.datamodel.OCFile;
 import com.owncloud.android.datamodel.ThumbnailsCacheManager;
 import com.owncloud.android.datamodel.UploadsStorageManager;
@@ -315,11 +313,7 @@ public class FileUploader extends Service
     public int onStartCommand(Intent intent, int flags, int startId) {
         Log_OC.d(TAG, "Starting command with id " + startId);
 
-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
-            startForeground(FOREGROUND_SERVICE_ID, mNotification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
-        } else {
-            startForeground(FOREGROUND_SERVICE_ID, mNotification);
-        }
+        ForegroundServiceHelper.INSTANCE.start(this, FOREGROUND_SERVICE_ID, mNotification, ForegroundServiceType.DataSync);
 
         if (intent == null) {
             Log_OC.e(TAG, "Intent is null");
@@ -389,7 +383,7 @@ public class FileUploader extends Service
         List<String> requestedUploads,
         boolean onWifiOnly,
         boolean whileChargingOnly
-    ) {
+                                            ) {
         String[] localPaths = null;
         String[] remotePaths = null;
         String[] mimeTypes = null;
@@ -428,7 +422,7 @@ public class FileUploader extends Service
                     remotePaths[i],
                     localPaths[i],
                     mimeTypes != null ? mimeTypes[i] : null
-                );
+                                                                      );
                 if (files[i] == null) {
                     Log_OC.e(TAG, "obtainNewOCFileToUpload() returned null for remotePaths[i]:" + remotePaths[i]
                         + " and localPaths[i]:" + localPaths[i]);
@@ -528,7 +522,7 @@ public class FileUploader extends Service
             user.getAccountName(),
             file.getRemotePath(),
             newUpload
-        );
+                                                                    );
 
         if (putResult != null) {
             requestedUploads.add(putResult.first);
@@ -575,7 +569,7 @@ public class FileUploader extends Service
             user.getAccountName(),
             upload.getRemotePath(),
             newUpload
-        );
+                                                                    );
         if (putResult != null) {
             String uploadKey = putResult.first;
             requestedUploads.add(uploadKey);
@@ -717,12 +711,12 @@ public class FileUploader extends Service
      */
     private void notifyUploadStart(UploadFileOperation upload) {
         // / create status notification with a progress bar
-        Intent notificationActionIntent = new Intent(getApplicationContext(),UploadNotificationActionReceiver.class);
-        notificationActionIntent.putExtra(EXTRA_ACCOUNT_NAME,upload.getUser().getAccountName());
-        notificationActionIntent.putExtra(EXTRA_REMOTE_PATH,upload.getRemotePath());
+        Intent notificationActionIntent = new Intent(getApplicationContext(), UploadNotificationActionReceiver.class);
+        notificationActionIntent.putExtra(EXTRA_ACCOUNT_NAME, upload.getUser().getAccountName());
+        notificationActionIntent.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath());
         notificationActionIntent.setAction(ACTION_CANCEL_BROADCAST);
 
-        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),secureRandomGenerator.nextInt(),notificationActionIntent, PendingIntent.FLAG_IMMUTABLE);
+        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), secureRandomGenerator.nextInt(), notificationActionIntent, PendingIntent.FLAG_IMMUTABLE);
         mLastPercent = 0;
         mNotificationBuilder = NotificationUtils.newNotificationBuilder(this, viewThemeUtils);
         mNotificationBuilder
@@ -735,7 +729,7 @@ public class FileUploader extends Service
                 String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName())
                            )
             .clearActions() // to make sure there is only one action
-            .addAction(R.drawable.ic_action_cancel_grey,getApplicationContext().getString(R.string.common_cancel),pendingIntent);
+            .addAction(R.drawable.ic_action_cancel_grey, getApplicationContext().getString(R.string.common_cancel), pendingIntent);
 
 
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@@ -773,7 +767,7 @@ public class FileUploader extends Service
         long totalTransferredSoFar,
         long totalToTransfer,
         String filePath
-    ) {
+                                  ) {
         int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
         if (percent != mLastPercent) {
             mNotificationBuilder.setProgress(100, percent, false);
@@ -839,11 +833,11 @@ public class FileUploader extends Service
                 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
                 updateAccountCredentials.putExtra(
                     AuthenticatorActivity.EXTRA_ACCOUNT, upload.getUser().toPlatformAccount()
-                );
+                                                 );
                 updateAccountCredentials.putExtra(
                     AuthenticatorActivity.EXTRA_ACTION,
                     AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN
-                );
+                                                 );
 
                 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
@@ -853,7 +847,7 @@ public class FileUploader extends Service
                     (int) System.currentTimeMillis(),
                     updateAccountCredentials,
                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE
-                ));
+                                                                               ));
             } else {
                 Intent intent;
                 if (uploadResult.getCode() == ResultCode.SYNC_CONFLICT) {
@@ -1179,11 +1173,11 @@ public class FileUploader extends Service
          */
         public void cancel(String accountName, String remotePath, @Nullable ResultCode resultCode) {
             // Cancel for Android version >= Android 11
-            if (useFilesUploadWorker(getApplicationContext())){
-                try{
+            if (useFilesUploadWorker(getApplicationContext())) {
+                try {
                     new FilesUploadHelper().cancelFileUpload(remotePath, accountManager.getUser(accountName).get());
-                }catch(NoSuchElementException e){
-                    Log_OC.e(TAG,"Error cancelling current upload because user does not exist!");
+                } catch (NoSuchElementException e) {
+                    Log_OC.e(TAG, "Error cancelling current upload because user does not exist!");
                 }
             } else {
                 // Cancel for Android version <= Android 10
@@ -1222,7 +1216,7 @@ public class FileUploader extends Service
             cancelPendingUploads(accountName);
             if (useFilesUploadWorker(getApplicationContext())) {
                 new FilesUploadHelper().restartUploadJob(accountManager.getUser(accountName).get());
-            }else{
+            } else {
                 if (mCurrentUpload != null && mCurrentUpload.getUser().nameEquals(accountName)) {
                     mCurrentUpload.cancel(ResultCode.CANCELLED);
                 }
@@ -1273,7 +1267,7 @@ public class FileUploader extends Service
             OnDatatransferProgressListener listener,
             User user,
             OCFile file
-        ) {
+                                                   ) {
             if (user == null || file == null || listener == null) {
                 return;
             }
@@ -1291,7 +1285,7 @@ public class FileUploader extends Service
         public void addDatatransferProgressListener(
             OnDatatransferProgressListener listener,
             OCUpload ocUpload
-        ) {
+                                                   ) {
             if (ocUpload == null || listener == null) {
                 return;
             }
@@ -1311,7 +1305,7 @@ public class FileUploader extends Service
             OnDatatransferProgressListener listener,
             User user,
             OCFile file
-        ) {
+                                                      ) {
             if (user == null || file == null || listener == null) {
                 return;
             }
@@ -1331,7 +1325,7 @@ public class FileUploader extends Service
         public void removeDatatransferProgressListener(
             OnDatatransferProgressListener listener,
             OCUpload ocUpload
-        ) {
+                                                      ) {
             if (ocUpload == null || listener == null) {
                 return;
             }
@@ -1348,7 +1342,7 @@ public class FileUploader extends Service
             long totalTransferredSoFar,
             long totalToTransfer,
             String fileName
-        ) {
+                                      ) {
             String key = buildRemoteName(mCurrentUpload.getUser().getAccountName(), mCurrentUpload.getFile().getRemotePath());
             OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
 
@@ -1373,7 +1367,7 @@ public class FileUploader extends Service
                         mCurrentUpload.getUser().getAccountName(),
                         mCurrentUpload.getFile().getRemotePath(),
                         cancelReason
-                    );
+                          );
                 }
             }
         }
@@ -1444,11 +1438,13 @@ public class FileUploader extends Service
             if (ACTION_CANCEL_BROADCAST.equals(action)) {
                 Log_OC.d(TAG, "Cancel broadcast received for file " + remotePath + " at " + System.currentTimeMillis());
 
-                if (accountName == null || remotePath == null) return;
+                if (accountName == null || remotePath == null) {
+                    return;
+                }
 
                 FileUploaderBinder uploadBinder = (FileUploaderBinder) mBinder;
                 uploadBinder.cancel(accountName, remotePath, null);
-            }else if(ACTION_PAUSE_BROADCAST.equals(action)){
+            } else if (ACTION_PAUSE_BROADCAST.equals(action)) {
 
             } else {
                 Log_OC.d(TAG, "Unknown action to perform as UploadNotificationActionReceiver.");