FileUploader.java 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012 Bartek Przybylski
  3. * Copyright (C) 2012-2013 ownCloud Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package com.owncloud.android.files.services;
  20. import java.io.File;
  21. import java.util.AbstractList;
  22. import java.util.Iterator;
  23. import java.util.Vector;
  24. import java.util.concurrent.ConcurrentHashMap;
  25. import java.util.concurrent.ConcurrentMap;
  26. import org.apache.http.HttpStatus;
  27. import org.apache.jackrabbit.webdav.MultiStatus;
  28. import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
  29. import android.accounts.Account;
  30. import android.accounts.AccountManager;
  31. import android.app.Notification;
  32. import android.app.NotificationManager;
  33. import android.app.PendingIntent;
  34. import android.app.Service;
  35. import android.content.Intent;
  36. import android.os.Binder;
  37. import android.os.Handler;
  38. import android.os.HandlerThread;
  39. import android.os.IBinder;
  40. import android.os.Looper;
  41. import android.os.Message;
  42. import android.os.Process;
  43. import android.util.Log;
  44. import android.webkit.MimeTypeMap;
  45. import android.widget.RemoteViews;
  46. import android.widget.Toast;
  47. import com.owncloud.android.R;
  48. import com.owncloud.android.authenticator.AccountAuthenticator;
  49. import com.owncloud.android.datamodel.FileDataStorageManager;
  50. import com.owncloud.android.datamodel.OCFile;
  51. import com.owncloud.android.db.DbHandler;
  52. import com.owncloud.android.network.OwnCloudClientUtils;
  53. import com.owncloud.android.operations.ChunkedUploadFileOperation;
  54. import com.owncloud.android.operations.RemoteOperationResult;
  55. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  56. import com.owncloud.android.operations.UploadFileOperation;
  57. import com.owncloud.android.ui.activity.FailedUploadActivity;
  58. import com.owncloud.android.ui.activity.FileDetailActivity;
  59. import com.owncloud.android.ui.activity.InstantUploadActivity;
  60. import com.owncloud.android.ui.fragment.FileDetailFragment;
  61. import com.owncloud.android.utils.OwnCloudVersion;
  62. import eu.alefzero.webdav.OnDatatransferProgressListener;
  63. import eu.alefzero.webdav.WebdavClient;
  64. import eu.alefzero.webdav.WebdavEntry;
  65. import eu.alefzero.webdav.WebdavUtils;
  66. public class FileUploader extends Service implements OnDatatransferProgressListener {
  67. public static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
  68. public static final String EXTRA_UPLOAD_RESULT = "RESULT";
  69. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  70. public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
  71. public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
  72. public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
  73. public static final String KEY_FILE = "FILE";
  74. public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
  75. public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
  76. public static final String KEY_MIME_TYPE = "MIME_TYPE";
  77. public static final String KEY_ACCOUNT = "ACCOUNT";
  78. public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
  79. public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
  80. public static final String KEY_INSTANT_UPLOAD = "INSTANT_UPLOAD";
  81. public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
  82. public static final int LOCAL_BEHAVIOUR_COPY = 0;
  83. public static final int LOCAL_BEHAVIOUR_MOVE = 1;
  84. public static final int LOCAL_BEHAVIOUR_FORGET = 2;
  85. public static final int UPLOAD_SINGLE_FILE = 0;
  86. public static final int UPLOAD_MULTIPLE_FILES = 1;
  87. private static final String TAG = FileUploader.class.getSimpleName();
  88. private Looper mServiceLooper;
  89. private ServiceHandler mServiceHandler;
  90. private IBinder mBinder;
  91. private WebdavClient mUploadClient = null;
  92. private Account mLastAccount = null;
  93. private FileDataStorageManager mStorageManager;
  94. private ConcurrentMap<String, UploadFileOperation> mPendingUploads = new ConcurrentHashMap<String, UploadFileOperation>();
  95. private UploadFileOperation mCurrentUpload = null;
  96. private NotificationManager mNotificationManager;
  97. private Notification mNotification;
  98. private int mLastPercent;
  99. private RemoteViews mDefaultNotificationContentView;
  100. /**
  101. * Builds a key for mPendingUploads from the account and file to upload
  102. *
  103. * @param account Account where the file to download is stored
  104. * @param file File to download
  105. */
  106. private String buildRemoteName(Account account, OCFile file) {
  107. return account.name + file.getRemotePath();
  108. }
  109. private String buildRemoteName(Account account, String remotePath) {
  110. return account.name + remotePath;
  111. }
  112. /**
  113. * Checks if an ownCloud server version should support chunked uploads.
  114. *
  115. * @param version OwnCloud version instance corresponding to an ownCloud
  116. * server.
  117. * @return 'True' if the ownCloud server with version supports chunked
  118. * uploads.
  119. */
  120. private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
  121. return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
  122. }
  123. /**
  124. * Service initialization
  125. */
  126. @Override
  127. public void onCreate() {
  128. super.onCreate();
  129. Log.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
  130. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  131. HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
  132. thread.start();
  133. mServiceLooper = thread.getLooper();
  134. mServiceHandler = new ServiceHandler(mServiceLooper, this);
  135. mBinder = new FileUploaderBinder();
  136. }
  137. /**
  138. * Entry point to add one or several files to the queue of uploads.
  139. *
  140. * New uploads are added calling to startService(), resulting in a call to
  141. * this method. This ensures the service will keep on working although the
  142. * caller activity goes away.
  143. */
  144. @Override
  145. public int onStartCommand(Intent intent, int flags, int startId) {
  146. if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE)
  147. || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
  148. Log.e(TAG, "Not enough information provided in intent");
  149. return Service.START_NOT_STICKY;
  150. }
  151. int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
  152. if (uploadType == -1) {
  153. Log.e(TAG, "Incorrect upload type provided");
  154. return Service.START_NOT_STICKY;
  155. }
  156. Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  157. String[] localPaths = null, remotePaths = null, mimeTypes = null;
  158. OCFile[] files = null;
  159. if (uploadType == UPLOAD_SINGLE_FILE) {
  160. if (intent.hasExtra(KEY_FILE)) {
  161. files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };
  162. } else {
  163. localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
  164. remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
  165. mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
  166. }
  167. } else { // mUploadType == UPLOAD_MULTIPLE_FILES
  168. if (intent.hasExtra(KEY_FILE)) {
  169. files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO
  170. // will
  171. // this
  172. // casting
  173. // work
  174. // fine?
  175. } else {
  176. localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  177. remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  178. mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  179. }
  180. }
  181. FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
  182. boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  183. boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
  184. int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY);
  185. boolean fixed = false;
  186. if (isInstant) {
  187. fixed = checkAndFixInstantUploadDirectory(storageManager); // MUST
  188. // be
  189. // done
  190. // BEFORE
  191. // calling
  192. // obtainNewOCFileToUpload
  193. }
  194. if (intent.hasExtra(KEY_FILE) && files == null) {
  195. Log.e(TAG, "Incorrect array for OCFiles provided in upload intent");
  196. return Service.START_NOT_STICKY;
  197. } else if (!intent.hasExtra(KEY_FILE)) {
  198. if (localPaths == null) {
  199. Log.e(TAG, "Incorrect array for local paths provided in upload intent");
  200. return Service.START_NOT_STICKY;
  201. }
  202. if (remotePaths == null) {
  203. Log.e(TAG, "Incorrect array for remote paths provided in upload intent");
  204. return Service.START_NOT_STICKY;
  205. }
  206. if (localPaths.length != remotePaths.length) {
  207. Log.e(TAG, "Different number of remote paths and local paths!");
  208. return Service.START_NOT_STICKY;
  209. }
  210. files = new OCFile[localPaths.length];
  211. for (int i = 0; i < localPaths.length; i++) {
  212. files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i], ((mimeTypes != null) ? mimeTypes[i]
  213. : (String) null), storageManager);
  214. if (files[i] == null) {
  215. // TODO @andromaex add failure Notiification
  216. return Service.START_NOT_STICKY;
  217. }
  218. }
  219. }
  220. OwnCloudVersion ocv = new OwnCloudVersion(AccountManager.get(this).getUserData(account,
  221. AccountAuthenticator.KEY_OC_VERSION));
  222. boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
  223. AbstractList<String> requestedUploads = new Vector<String>();
  224. String uploadKey = null;
  225. UploadFileOperation newUpload = null;
  226. try {
  227. for (int i = 0; i < files.length; i++) {
  228. uploadKey = buildRemoteName(account, files[i].getRemotePath());
  229. if (chunked) {
  230. newUpload = new ChunkedUploadFileOperation(account, files[i], isInstant, forceOverwrite,
  231. localAction);
  232. } else {
  233. newUpload = new UploadFileOperation(account, files[i], isInstant, forceOverwrite, localAction);
  234. }
  235. if (fixed && i == 0) {
  236. newUpload.setRemoteFolderToBeCreated();
  237. }
  238. mPendingUploads.putIfAbsent(uploadKey, newUpload);
  239. newUpload.addDatatransferProgressListener(this);
  240. requestedUploads.add(uploadKey);
  241. }
  242. } catch (IllegalArgumentException e) {
  243. Log.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  244. return START_NOT_STICKY;
  245. } catch (IllegalStateException e) {
  246. Log.e(TAG, "Bad information provided in intent: " + e.getMessage());
  247. return START_NOT_STICKY;
  248. } catch (Exception e) {
  249. Log.e(TAG, "Unexpected exception while processing upload intent", e);
  250. return START_NOT_STICKY;
  251. }
  252. if (requestedUploads.size() > 0) {
  253. Message msg = mServiceHandler.obtainMessage();
  254. msg.arg1 = startId;
  255. msg.obj = requestedUploads;
  256. mServiceHandler.sendMessage(msg);
  257. }
  258. Log.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
  259. return Service.START_NOT_STICKY;
  260. }
  261. /**
  262. * Provides a binder object that clients can use to perform operations on
  263. * the queue of uploads, excepting the addition of new files.
  264. *
  265. * Implemented to perform cancellation, pause and resume of existing
  266. * uploads.
  267. */
  268. @Override
  269. public IBinder onBind(Intent arg0) {
  270. return mBinder;
  271. }
  272. /**
  273. * Binder to let client components to perform operations on the queue of
  274. * uploads.
  275. *
  276. * It provides by itself the available operations.
  277. */
  278. public class FileUploaderBinder extends Binder {
  279. /**
  280. * Cancels a pending or current upload of a remote file.
  281. *
  282. * @param account Owncloud account where the remote file will be stored.
  283. * @param file A file in the queue of pending uploads
  284. */
  285. public void cancel(Account account, OCFile file) {
  286. UploadFileOperation upload = null;
  287. synchronized (mPendingUploads) {
  288. upload = mPendingUploads.remove(buildRemoteName(account, file));
  289. }
  290. if (upload != null) {
  291. upload.cancel();
  292. }
  293. }
  294. /**
  295. * Returns True when the file described by 'file' is being uploaded to
  296. * the ownCloud account 'account' or waiting for it
  297. *
  298. * If 'file' is a directory, returns 'true' if some of its descendant
  299. * files is downloading or waiting to download.
  300. *
  301. * @param account Owncloud account where the remote file will be stored.
  302. * @param file A file that could be in the queue of pending uploads
  303. */
  304. public boolean isUploading(Account account, OCFile file) {
  305. if (account == null || file == null)
  306. return false;
  307. String targetKey = buildRemoteName(account, file);
  308. synchronized (mPendingUploads) {
  309. if (file.isDirectory()) {
  310. // this can be slow if there are many downloads :(
  311. Iterator<String> it = mPendingUploads.keySet().iterator();
  312. boolean found = false;
  313. while (it.hasNext() && !found) {
  314. found = it.next().startsWith(targetKey);
  315. }
  316. return found;
  317. } else {
  318. return (mPendingUploads.containsKey(targetKey));
  319. }
  320. }
  321. }
  322. }
  323. /**
  324. * Upload worker. Performs the pending uploads in the order they were
  325. * requested.
  326. *
  327. * Created with the Looper of a new thread, started in
  328. * {@link FileUploader#onCreate()}.
  329. */
  330. private static class ServiceHandler extends Handler {
  331. // don't make it a final class, and don't remove the static ; lint will
  332. // warn about a possible memory leak
  333. FileUploader mService;
  334. public ServiceHandler(Looper looper, FileUploader service) {
  335. super(looper);
  336. if (service == null)
  337. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  338. mService = service;
  339. }
  340. @Override
  341. public void handleMessage(Message msg) {
  342. @SuppressWarnings("unchecked")
  343. AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
  344. if (msg.obj != null) {
  345. Iterator<String> it = requestedUploads.iterator();
  346. while (it.hasNext()) {
  347. mService.uploadFile(it.next());
  348. }
  349. }
  350. mService.stopSelf(msg.arg1);
  351. }
  352. }
  353. /**
  354. * Core upload method: sends the file(s) to upload
  355. *
  356. * @param uploadKey Key to access the upload to perform, contained in
  357. * mPendingUploads
  358. */
  359. public void uploadFile(String uploadKey) {
  360. synchronized (mPendingUploads) {
  361. mCurrentUpload = mPendingUploads.get(uploadKey);
  362. }
  363. if (mCurrentUpload != null) {
  364. notifyUploadStart(mCurrentUpload);
  365. // / prepare client object to send requests to the ownCloud server
  366. if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) {
  367. mLastAccount = mCurrentUpload.getAccount();
  368. mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver());
  369. mUploadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());
  370. }
  371. // / create remote folder for instant uploads
  372. if (mCurrentUpload.isRemoteFolderToBeCreated()) {
  373. mUploadClient.createDirectory(InstantUploadService.INSTANT_UPLOAD_DIR);
  374. // ignoring result fail could just mean that it already exists,
  375. // but local database is not synchronized the upload will be
  376. // tried anyway
  377. }
  378. // / perform the upload
  379. RemoteOperationResult uploadResult = null;
  380. try {
  381. uploadResult = mCurrentUpload.execute(mUploadClient);
  382. if (uploadResult.isSuccess()) {
  383. saveUploadedFile();
  384. }
  385. } finally {
  386. synchronized (mPendingUploads) {
  387. mPendingUploads.remove(uploadKey);
  388. Log.i(TAG, "Remove CurrentUploadItem from pending upload Item Map.");
  389. }
  390. }
  391. // notify result
  392. notifyUploadResult(uploadResult, mCurrentUpload);
  393. sendFinalBroadcast(mCurrentUpload, uploadResult);
  394. }
  395. }
  396. /**
  397. * Saves a OC File after a successful upload.
  398. *
  399. * A PROPFIND is necessary to keep the props in the local database
  400. * synchronized with the server, specially the modification time and Etag
  401. * (where available)
  402. *
  403. * TODO refactor this ugly thing
  404. */
  405. private void saveUploadedFile() {
  406. OCFile file = mCurrentUpload.getFile();
  407. long syncDate = System.currentTimeMillis();
  408. file.setLastSyncDateForData(syncDate);
  409. // / new PROPFIND to keep data consistent with server in theory, should
  410. // return the same we already have
  411. PropFindMethod propfind = null;
  412. RemoteOperationResult result = null;
  413. try {
  414. propfind = new PropFindMethod(mUploadClient.getBaseUri()
  415. + WebdavUtils.encodePath(mCurrentUpload.getRemotePath()));
  416. int status = mUploadClient.executeMethod(propfind);
  417. boolean isMultiStatus = (status == HttpStatus.SC_MULTI_STATUS);
  418. if (isMultiStatus) {
  419. MultiStatus resp = propfind.getResponseBodyAsMultiStatus();
  420. WebdavEntry we = new WebdavEntry(resp.getResponses()[0], mUploadClient.getBaseUri().getPath());
  421. updateOCFile(file, we);
  422. file.setLastSyncDateForProperties(syncDate);
  423. } else {
  424. mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
  425. }
  426. result = new RemoteOperationResult(isMultiStatus, status);
  427. Log.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
  428. + result.getLogMessage());
  429. } catch (Exception e) {
  430. result = new RemoteOperationResult(e);
  431. Log.e(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
  432. + result.getLogMessage(), e);
  433. } finally {
  434. if (propfind != null)
  435. propfind.releaseConnection();
  436. }
  437. // / maybe this would be better as part of UploadFileOperation... or
  438. // maybe all this method
  439. if (mCurrentUpload.wasRenamed()) {
  440. OCFile oldFile = mCurrentUpload.getOldFile();
  441. if (oldFile.fileExists()) {
  442. oldFile.setStoragePath(null);
  443. mStorageManager.saveFile(oldFile);
  444. } // else: it was just an automatic renaming due to a name
  445. // coincidence; nothing else is needed, the storagePath is right
  446. // in the instance returned by mCurrentUpload.getFile()
  447. }
  448. mStorageManager.saveFile(file);
  449. }
  450. private void updateOCFile(OCFile file, WebdavEntry we) {
  451. file.setCreationTimestamp(we.createTimestamp());
  452. file.setFileLength(we.contentLength());
  453. file.setMimetype(we.contentType());
  454. file.setModificationTimestamp(we.modifiedTimestamp());
  455. file.setModificationTimestampAtLastSyncForData(we.modifiedTimestamp());
  456. // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where
  457. // available
  458. }
  459. private boolean checkAndFixInstantUploadDirectory(FileDataStorageManager storageManager) {
  460. OCFile instantUploadDir = storageManager.getFileByPath(InstantUploadService.INSTANT_UPLOAD_DIR);
  461. if (instantUploadDir == null) {
  462. // first instant upload in the account, or never account not
  463. // synchronized after the remote InstantUpload folder was created
  464. OCFile newDir = new OCFile(InstantUploadService.INSTANT_UPLOAD_DIR);
  465. newDir.setMimetype("DIR");
  466. OCFile path = storageManager.getFileByPath(OCFile.PATH_SEPARATOR);
  467. if (path != null) {
  468. newDir.setParentId(path.getFileId());
  469. storageManager.saveFile(newDir);
  470. return true;
  471. } else {
  472. return false;
  473. }
  474. }
  475. return false;
  476. }
  477. private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType,
  478. FileDataStorageManager storageManager) {
  479. OCFile newFile = new OCFile(remotePath);
  480. newFile.setStoragePath(localPath);
  481. newFile.setLastSyncDateForProperties(0);
  482. newFile.setLastSyncDateForData(0);
  483. // size
  484. if (localPath != null && localPath.length() > 0) {
  485. File localFile = new File(localPath);
  486. newFile.setFileLength(localFile.length());
  487. newFile.setLastSyncDateForData(localFile.lastModified());
  488. } // don't worry about not assigning size, the problems with localPath
  489. // are checked when the UploadFileOperation instance is created
  490. // MIME type
  491. if (mimeType == null || mimeType.length() <= 0) {
  492. try {
  493. mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
  494. remotePath.substring(remotePath.lastIndexOf('.') + 1));
  495. } catch (IndexOutOfBoundsException e) {
  496. Log.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
  497. }
  498. }
  499. if (mimeType == null) {
  500. mimeType = "application/octet-stream";
  501. }
  502. newFile.setMimetype(mimeType);
  503. // parent dir
  504. String parentPath = new File(remotePath).getParent();
  505. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR;
  506. OCFile parentDir = storageManager.getFileByPath(parentPath);
  507. if (parentDir == null) {
  508. Toast t = Toast
  509. .makeText(
  510. getApplicationContext(),
  511. "The first time the InstantUpload is running you must be online, so the target folder can successfully created by the upload process",
  512. 30);
  513. t.show();
  514. return null;
  515. }
  516. long parentDirId = parentDir.getFileId();
  517. newFile.setParentId(parentDirId);
  518. return newFile;
  519. }
  520. /**
  521. * Creates a status notification to show the upload progress
  522. *
  523. * @param upload Upload operation starting.
  524. */
  525. private void notifyUploadStart(UploadFileOperation upload) {
  526. // / create status notification with a progress bar
  527. mLastPercent = 0;
  528. mNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_in_progress_ticker),
  529. System.currentTimeMillis());
  530. mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
  531. mDefaultNotificationContentView = mNotification.contentView;
  532. mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(),
  533. R.layout.progressbar_layout);
  534. mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
  535. mNotification.contentView.setTextViewText(R.id.status_text,
  536. String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
  537. mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
  538. // / includes a pending intent in the notification showing the details
  539. // view of the file
  540. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  541. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
  542. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
  543. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  544. mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
  545. (int) System.currentTimeMillis(), showDetailsIntent, 0);
  546. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
  547. }
  548. /**
  549. * Callback method to update the progress bar in the status notification
  550. */
  551. @Override
  552. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {
  553. int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
  554. if (percent != mLastPercent) {
  555. mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
  556. String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
  557. mNotification.contentView.setTextViewText(R.id.status_text, text);
  558. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
  559. }
  560. mLastPercent = percent;
  561. }
  562. /**
  563. * Callback method to update the progress bar in the status notification
  564. * (old version)
  565. */
  566. @Override
  567. public void onTransferProgress(long progressRate) {
  568. // NOTHING TO DO HERE ANYMORE
  569. }
  570. /**
  571. * Updates the status notification with the result of an upload operation.
  572. *
  573. * @param uploadResult Result of the upload operation.
  574. * @param upload Finished upload operation
  575. */
  576. private void notifyUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
  577. Log.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
  578. if (uploadResult.isCancelled()) {
  579. // / cancelled operation -> silent removal of progress notification
  580. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  581. } else if (uploadResult.isSuccess()) {
  582. // / success -> silent update of progress notification to success
  583. // message
  584. mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove
  585. // the
  586. // ongoing
  587. // flag
  588. mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
  589. mNotification.contentView = mDefaultNotificationContentView;
  590. // / includes a pending intent in the notification showing the
  591. // details view of the file
  592. Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
  593. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, upload.getFile());
  594. showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, upload.getAccount());
  595. showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  596. mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
  597. (int) System.currentTimeMillis(), showDetailsIntent, 0);
  598. mNotification.setLatestEventInfo(getApplicationContext(),
  599. getString(R.string.uploader_upload_succeeded_ticker),
  600. String.format(getString(R.string.uploader_upload_succeeded_content_single), upload.getFileName()),
  601. mNotification.contentIntent);
  602. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification); // NOT
  603. // AN
  604. DbHandler db = new DbHandler(this.getBaseContext());
  605. db.removeIUPendingFile(mCurrentUpload.getFile().getStoragePath());
  606. db.close();
  607. } else {
  608. // / fail -> explicit failure notification
  609. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  610. Notification finalNotification = new Notification(R.drawable.icon,
  611. getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
  612. finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
  613. String content = null;
  614. if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL
  615. || uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
  616. // TODO we need a class to provide error messages for the users
  617. // from a RemoteOperationResult and a RemoteOperation
  618. content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(),
  619. getString(R.string.app_name));
  620. } else if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
  621. content = getString(R.string.failed_upload_quota_exceeded_text);
  622. } else {
  623. content = String
  624. .format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
  625. }
  626. // we add only for instant-uploads the InstantUploadActivity and the
  627. // db entry
  628. Intent detailUploadIntent = null;
  629. if (upload.isInstant()) {
  630. detailUploadIntent = new Intent(this, InstantUploadActivity.class);
  631. detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
  632. } else {
  633. detailUploadIntent = new Intent(this, FailedUploadActivity.class);
  634. detailUploadIntent.putExtra(FailedUploadActivity.MESSAGE, content);
  635. }
  636. finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
  637. (int) System.currentTimeMillis(), detailUploadIntent, PendingIntent.FLAG_UPDATE_CURRENT
  638. | PendingIntent.FLAG_ONE_SHOT);
  639. if (upload.isInstant()) {
  640. DbHandler db = null;
  641. try {
  642. db = new DbHandler(this.getBaseContext());
  643. String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
  644. Log.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
  645. if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
  646. message = getString(R.string.failed_upload_quota_exceeded_text);
  647. }
  648. if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
  649. message) == 0) {
  650. db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name, message);
  651. }
  652. } finally {
  653. if (db != null) {
  654. db.close();
  655. }
  656. }
  657. }
  658. finalNotification.setLatestEventInfo(getApplicationContext(),
  659. getString(R.string.uploader_upload_failed_ticker), content, finalNotification.contentIntent);
  660. mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
  661. }
  662. }
  663. /**
  664. * Sends a broadcast in order to the interested activities can update their
  665. * view
  666. *
  667. * @param upload Finished upload operation
  668. * @param uploadResult Result of the upload operation
  669. */
  670. private void sendFinalBroadcast(UploadFileOperation upload, RemoteOperationResult uploadResult) {
  671. Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
  672. end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  673. // path, after
  674. // possible
  675. // automatic
  676. // renaming
  677. if (upload.wasRenamed()) {
  678. end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  679. }
  680. end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  681. end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  682. end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  683. sendStickyBroadcast(end);
  684. }
  685. }