package net.gotev.uploadservice;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Handler;
import androidx.core.app.NotificationCompat;
import com.bumptech.glide.load.Key;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.gotev.uploadservice.BroadcastData;
/* loaded from: classes.dex */
public abstract class UploadTask implements Runnable {
    protected static final byte[] EMPTY_RESPONSE = BuildConfig.FLAVOR.getBytes(Charset.forName(Key.STRING_CHARSET_NAME));
    private static final String LOG_TAG = "UploadTask";
    protected static final int TASK_COMPLETED_SUCCESSFULLY = 200;
    private int attempts;
    private long lastProgressNotificationTime;
    private Handler mainThreadHandler;
    private NotificationCompat.Builder notification;
    private int notificationId;
    private NotificationManager notificationManager;
    protected UploadService service;
    protected long totalBytes;
    protected long uploadedBytes;
    protected UploadTaskParameters params = null;
    private final List<String> successfullyUploadedFiles = new ArrayList();
    protected boolean shouldContinue = true;
    private final long startTime = new Date().getTime();

    protected void onSuccessfulUpload() {
    }

    protected abstract void upload() throws Exception;

    /* JADX INFO: Access modifiers changed from: protected */
    public void init(UploadService uploadService, Intent intent) throws IOException {
        this.notificationManager = (NotificationManager) uploadService.getSystemService("notification");
        this.notification = new NotificationCompat.Builder(uploadService);
        this.service = uploadService;
        this.mainThreadHandler = new Handler(uploadService.getMainLooper());
        this.params = (UploadTaskParameters) intent.getParcelableExtra("taskParameters");
    }

    @Override // java.lang.Runnable
    public final void run() {
        createNotification(new UploadInfo(this.params.getId()));
        this.attempts = 0;
        int i = UploadService.INITIAL_RETRY_WAIT_TIME;
        while (this.attempts <= this.params.getMaxRetries() && this.shouldContinue) {
            this.attempts++;
            try {
                upload();
                break;
            } catch (Exception e) {
                if (!this.shouldContinue) {
                    break;
                } else if (this.attempts > this.params.getMaxRetries()) {
                    broadcastError(e);
                } else {
                    Logger.error(LOG_TAG, "Error in uploadId " + this.params.getId() + " on attempt " + this.attempts + ". Waiting " + (i / 1000) + "s before next attempt. ", e);
                    long currentTimeMillis = System.currentTimeMillis();
                    while (this.shouldContinue && System.currentTimeMillis() < i + currentTimeMillis) {
                        try {
                            Thread.sleep(2000L);
                        } catch (Throwable unused) {
                        }
                    }
                    i *= UploadService.BACKOFF_MULTIPLIER;
                    if (i > UploadService.MAX_RETRY_WAIT_TIME) {
                        i = UploadService.MAX_RETRY_WAIT_TIME;
                    }
                }
            }
        }
        if (this.shouldContinue) {
            return;
        }
        broadcastCancelled();
    }

    /* JADX INFO: Access modifiers changed from: protected */
    public final UploadTask setLastProgressNotificationTime(long j) {
        this.lastProgressNotificationTime = j;
        return this;
    }

    /* JADX INFO: Access modifiers changed from: protected */
    public final UploadTask setNotificationId(int i) {
        this.notificationId = i;
        return this;
    }

    /* JADX INFO: Access modifiers changed from: protected */
    public final void broadcastProgress(long j, long j2) {
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis < this.lastProgressNotificationTime + 166) {
            return;
        }
        setLastProgressNotificationTime(currentTimeMillis);
        String str = LOG_TAG;
        Logger.debug(str, "Broadcasting upload progress for " + this.params.getId() + ": " + j + " bytes of " + j2);
        final UploadInfo uploadInfo = new UploadInfo(this.params.getId(), this.startTime, j, j2, this.attempts + (-1), this.successfullyUploadedFiles, this.params.getFiles().size() + this.successfullyUploadedFiles.size());
        BroadcastData uploadInfo2 = new BroadcastData().setStatus(BroadcastData.Status.IN_PROGRESS).setUploadInfo(uploadInfo);
        final UploadStatusDelegate uploadStatusDelegate = UploadService.getUploadStatusDelegate(this.params.getId());
        if (uploadStatusDelegate != null) {
            this.mainThreadHandler.post(new Runnable() { // from class: net.gotev.uploadservice.UploadTask.1
                @Override // java.lang.Runnable
                public void run() {
                    uploadStatusDelegate.onProgress(UploadTask.this.service, uploadInfo);
                }
            });
        } else {
            this.service.sendBroadcast(uploadInfo2.getIntent());
        }
        updateNotificationProgress(uploadInfo);
    }

    /* JADX INFO: Access modifiers changed from: protected */
    public final void broadcastCompleted(final ServerResponse serverResponse) {
        boolean z = serverResponse.getHttpCode() / 100 == 2;
        if (z) {
            onSuccessfulUpload();
            if (this.params.isAutoDeleteSuccessfullyUploadedFiles() && !this.successfullyUploadedFiles.isEmpty()) {
                for (String str : this.successfullyUploadedFiles) {
                    deleteFile(new File(str));
                }
            }
        }
        String str2 = LOG_TAG;
        Logger.debug(str2, "Broadcasting upload completed for " + this.params.getId());
        final UploadInfo uploadInfo = new UploadInfo(this.params.getId(), this.startTime, this.uploadedBytes, this.totalBytes, this.attempts + (-1), this.successfullyUploadedFiles, this.params.getFiles().size());
        final UploadStatusDelegate uploadStatusDelegate = UploadService.getUploadStatusDelegate(this.params.getId());
        if (uploadStatusDelegate != null) {
            this.mainThreadHandler.post(new Runnable() { // from class: net.gotev.uploadservice.UploadTask.2
                @Override // java.lang.Runnable
                public void run() {
                    uploadStatusDelegate.onCompleted(UploadTask.this.service, uploadInfo, serverResponse);
                }
            });
        } else {
            this.service.sendBroadcast(new BroadcastData().setStatus(BroadcastData.Status.COMPLETED).setUploadInfo(uploadInfo).setServerResponse(serverResponse).getIntent());
        }
        UploadNotificationConfig notificationConfig = this.params.getNotificationConfig();
        if (notificationConfig != null) {
            if (z) {
                updateNotification(uploadInfo, notificationConfig.getCompletedMessage(), notificationConfig.isAutoClearOnSuccess(), notificationConfig.getCompletedIconResourceID(), notificationConfig.getCompletedIconColorResourceID());
            } else {
                updateNotification(uploadInfo, notificationConfig.getErrorMessage(), notificationConfig.isAutoClearOnError(), notificationConfig.getErrorIconResourceID(), notificationConfig.getErrorIconColorResourceID());
            }
        }
        this.service.taskCompleted(this.params.getId());
    }

    protected final void broadcastCancelled() {
        String str = LOG_TAG;
        Logger.debug(str, "Broadcasting cancellation for upload with ID: " + this.params.getId());
        final UploadInfo uploadInfo = new UploadInfo(this.params.getId(), this.startTime, this.uploadedBytes, this.totalBytes, this.attempts + (-1), this.successfullyUploadedFiles, this.params.getFiles().size());
        BroadcastData uploadInfo2 = new BroadcastData().setStatus(BroadcastData.Status.CANCELLED).setUploadInfo(uploadInfo);
        final UploadStatusDelegate uploadStatusDelegate = UploadService.getUploadStatusDelegate(this.params.getId());
        if (uploadStatusDelegate != null) {
            this.mainThreadHandler.post(new Runnable() { // from class: net.gotev.uploadservice.UploadTask.3
                @Override // java.lang.Runnable
                public void run() {
                    uploadStatusDelegate.onCancelled(UploadTask.this.service, uploadInfo);
                }
            });
        } else {
            this.service.sendBroadcast(uploadInfo2.getIntent());
        }
        UploadNotificationConfig notificationConfig = this.params.getNotificationConfig();
        if (notificationConfig != null) {
            updateNotification(uploadInfo, notificationConfig.getCancelledMessage(), notificationConfig.isAutoClearOnCancel(), notificationConfig.getCancelledIconResourceID(), notificationConfig.getCancelledIconColorResourceID());
        }
        this.service.taskCompleted(this.params.getId());
    }

    /* JADX INFO: Access modifiers changed from: protected */
    public final void addSuccessfullyUploadedFile(String str) {
        if (this.successfullyUploadedFiles.contains(str)) {
            return;
        }
        this.successfullyUploadedFiles.add(str);
    }

    /* JADX INFO: Access modifiers changed from: protected */
    public final List<String> getSuccessfullyUploadedFiles() {
        return this.successfullyUploadedFiles;
    }

    private void broadcastError(final Exception exc) {
        String str = LOG_TAG;
        Logger.info(str, "Broadcasting error for upload with ID: " + this.params.getId() + ". " + exc.getMessage());
        final UploadInfo uploadInfo = new UploadInfo(this.params.getId(), this.startTime, this.uploadedBytes, this.totalBytes, this.attempts + (-1), this.successfullyUploadedFiles, this.params.getFiles().size());
        BroadcastData exception = new BroadcastData().setStatus(BroadcastData.Status.ERROR).setUploadInfo(uploadInfo).setException(exc);
        final UploadStatusDelegate uploadStatusDelegate = UploadService.getUploadStatusDelegate(this.params.getId());
        if (uploadStatusDelegate != null) {
            this.mainThreadHandler.post(new Runnable() { // from class: net.gotev.uploadservice.UploadTask.4
                @Override // java.lang.Runnable
                public void run() {
                    uploadStatusDelegate.onError(UploadTask.this.service, uploadInfo, exc);
                }
            });
        } else {
            this.service.sendBroadcast(exception.getIntent());
        }
        UploadNotificationConfig notificationConfig = this.params.getNotificationConfig();
        if (notificationConfig != null && notificationConfig.getErrorMessage() != null) {
            updateNotification(uploadInfo, notificationConfig.getErrorMessage(), notificationConfig.isAutoClearOnError(), notificationConfig.getErrorIconResourceID(), notificationConfig.getErrorIconColorResourceID());
        }
        this.service.taskCompleted(this.params.getId());
    }

    private void createNotification(UploadInfo uploadInfo) {
        if (this.params.getNotificationConfig() == null || this.params.getNotificationConfig().getInProgressMessage() == null) {
            return;
        }
        this.notification.setContentTitle(Placeholders.replace(this.params.getNotificationConfig().getTitle(), uploadInfo)).setContentText(Placeholders.replace(this.params.getNotificationConfig().getInProgressMessage(), uploadInfo)).setContentIntent(this.params.getNotificationConfig().getPendingIntent(this.service)).setSmallIcon(this.params.getNotificationConfig().getIconResourceID()).setColor(this.params.getNotificationConfig().getIconColorResourceID()).setGroup(UploadService.NAMESPACE).setProgress(100, 0, true).setOngoing(true);
        Notification build = this.notification.build();
        if (this.service.holdForegroundNotification(this.params.getId(), build)) {
            this.notificationManager.cancel(this.notificationId);
        } else {
            this.notificationManager.notify(this.notificationId, build);
        }
    }

    private void updateNotificationProgress(UploadInfo uploadInfo) {
        if (this.params.getNotificationConfig() == null || this.params.getNotificationConfig().getInProgressMessage() == null) {
            return;
        }
        this.notification.setContentTitle(Placeholders.replace(this.params.getNotificationConfig().getTitle(), uploadInfo)).setContentText(Placeholders.replace(this.params.getNotificationConfig().getInProgressMessage(), uploadInfo)).setContentIntent(this.params.getNotificationConfig().getPendingIntent(this.service)).setSmallIcon(this.params.getNotificationConfig().getIconResourceID()).setColor(this.params.getNotificationConfig().getIconColorResourceID()).setGroup(UploadService.NAMESPACE).setProgress((int) uploadInfo.getTotalBytes(), (int) uploadInfo.getUploadedBytes(), false).setOngoing(true);
        Notification build = this.notification.build();
        if (this.service.holdForegroundNotification(this.params.getId(), build)) {
            this.notificationManager.cancel(this.notificationId);
        } else {
            this.notificationManager.notify(this.notificationId, build);
        }
    }

    private void setRingtone() {
        if (this.params.getNotificationConfig().isRingToneEnabled()) {
            this.notification.setSound(RingtoneManager.getActualDefaultRingtoneUri(this.service, 2));
            this.notification.setOnlyAlertOnce(false);
        }
    }

    private void updateNotification(UploadInfo uploadInfo, String str, boolean z, int i, int i2) {
        if (this.params.getNotificationConfig() == null) {
            return;
        }
        this.notificationManager.cancel(this.notificationId);
        if (str == null || z) {
            return;
        }
        this.notification.setContentTitle(Placeholders.replace(this.params.getNotificationConfig().getTitle(), uploadInfo)).setContentText(Placeholders.replace(str, uploadInfo)).setContentIntent(this.params.getNotificationConfig().getPendingIntent(this.service)).setAutoCancel(this.params.getNotificationConfig().isClearOnAction()).setSmallIcon(i).setColor(i2).setGroup(UploadService.NAMESPACE).setProgress(0, 0, false).setOngoing(false);
        setRingtone();
        this.notificationManager.notify(this.notificationId + 1, this.notification.build());
    }

    private boolean deleteFile(File file) {
        boolean z;
        try {
            z = file.delete();
        } catch (Exception e) {
            e = e;
            z = false;
        }
        try {
            if (!z) {
                String str = LOG_TAG;
                Logger.error(str, "Unable to delete: " + file.getAbsolutePath());
            } else {
                String str2 = LOG_TAG;
                Logger.info(str2, "Successfully deleted: " + file.getAbsolutePath());
            }
        } catch (Exception e2) {
            e = e2;
            String str3 = LOG_TAG;
            Logger.error(str3, "Error while deleting: " + file.getAbsolutePath() + " Check if you granted: android.permission.WRITE_EXTERNAL_STORAGE", e);
            return z;
        }
        return z;
    }

    public final void cancel() {
        this.shouldContinue = false;
    }
}
