FileUploadService.java 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author LukeOwncloud
  5. * Copyright (C) 2015 ownCloud Inc.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package com.owncloud.android.files.services;
  21. import android.accounts.Account;
  22. import android.accounts.AccountManager;
  23. import android.accounts.OnAccountsUpdateListener;
  24. import android.app.NotificationManager;
  25. import android.app.PendingIntent;
  26. import android.app.Service;
  27. import android.content.Context;
  28. import android.content.Intent;
  29. import android.os.Binder;
  30. import android.os.Handler;
  31. import android.os.HandlerThread;
  32. import android.os.IBinder;
  33. import android.os.Looper;
  34. import android.os.Message;
  35. import android.support.v4.app.NotificationCompat;
  36. import android.util.Pair;
  37. import android.webkit.MimeTypeMap;
  38. import com.owncloud.android.R;
  39. import com.owncloud.android.authentication.AccountUtils;
  40. import com.owncloud.android.authentication.AuthenticatorActivity;
  41. import com.owncloud.android.datamodel.FileDataStorageManager;
  42. import com.owncloud.android.datamodel.OCFile;
  43. import com.owncloud.android.datamodel.UploadsStorageManager;
  44. import com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus;
  45. import com.owncloud.android.db.OCUpload;
  46. import com.owncloud.android.db.UploadResult;
  47. import com.owncloud.android.lib.common.OwnCloudAccount;
  48. import com.owncloud.android.lib.common.OwnCloudClient;
  49. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  50. import com.owncloud.android.lib.common.network.OnDatatransferProgressListener;
  51. import com.owncloud.android.lib.common.operations.RemoteOperation;
  52. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  53. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  54. import com.owncloud.android.lib.common.utils.Log_OC;
  55. import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
  56. import com.owncloud.android.lib.resources.files.FileUtils;
  57. import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation;
  58. import com.owncloud.android.lib.resources.files.RemoteFile;
  59. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  60. import com.owncloud.android.notifications.NotificationBuilderWithProgressBar;
  61. import com.owncloud.android.notifications.NotificationDelayer;
  62. import com.owncloud.android.operations.CreateFolderOperation;
  63. import com.owncloud.android.operations.UploadFileOperation;
  64. import com.owncloud.android.operations.common.SyncOperation;
  65. import com.owncloud.android.ui.activity.FileActivity;
  66. import com.owncloud.android.ui.activity.UploadListActivity;
  67. import com.owncloud.android.utils.DisplayUtils;
  68. import com.owncloud.android.utils.ErrorMessageAdapter;
  69. import com.owncloud.android.utils.UploadUtils;
  70. import com.owncloud.android.utils.UriUtils;
  71. import java.io.File;
  72. import java.util.AbstractList;
  73. import java.util.Date;
  74. import java.util.HashMap;
  75. import java.util.Iterator;
  76. import java.util.Map;
  77. import java.util.Vector;
  78. import java.util.concurrent.ExecutorService;
  79. import java.util.concurrent.Executors;
  80. import java.util.concurrent.atomic.AtomicBoolean;
  81. /**
  82. * Service for uploading files. Invoke using context.startService(...). Files to
  83. * be uploaded are stored persistently using {@link UploadsStorageManager}.
  84. *
  85. * On next invocation of {@link FileUploadService} uploaded files which
  86. * previously failed will be uploaded again until either upload succeeded or a
  87. * fatal error occured.
  88. *
  89. * Every file passed to this service is uploaded. No filtering is performed.
  90. * However, Intent keys (e.g., KEY_WIFI_ONLY) are obeyed.
  91. *
  92. */
  93. public class FileUploadService extends Service implements OnDatatransferProgressListener,
  94. OnAccountsUpdateListener {
  95. private static final String TAG = FileUploadService.class.getSimpleName();
  96. private static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
  97. public static final String EXTRA_UPLOAD_RESULT = "RESULT";
  98. public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
  99. public static final String EXTRA_OLD_REMOTE_PATH = "OLD_REMOTE_PATH";
  100. public static final String EXTRA_OLD_FILE_PATH = "OLD_FILE_PATH";
  101. public static final String EXTRA_LINKED_TO_PATH = "LINKED_TO";
  102. public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
  103. public static final String KEY_FILE = "FILE";
  104. public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
  105. public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
  106. public static final String KEY_MIME_TYPE = "MIME_TYPE";
  107. /**
  108. * Call this Service with only this Intent key if all pending uploads are to be retried.
  109. */
  110. private static final String KEY_RETRY = "KEY_RETRY";
  111. /**
  112. * Call this Service with KEY_RETRY and KEY_RETRY_REMOTE_PATH to retry
  113. * download of file identified by KEY_RETRY_REMOTE_PATH.
  114. */
  115. private static final String KEY_RETRY_REMOTE_PATH = "KEY_RETRY_REMOTE_PATH";
  116. /**
  117. * {@link Account} to which file is to be uploaded.
  118. */
  119. public static final String KEY_ACCOUNT = "ACCOUNT";
  120. /**
  121. * Set whether single file or multiple files are to be uploaded. Value must be of type {@link UploadQuantity}.
  122. */
  123. public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
  124. /**
  125. * Set to true if remote file is to be overwritten. Default action is to upload with different name.
  126. */
  127. public static final String KEY_FORCE_OVERWRITE = "KEY_FORCE_OVERWRITE";
  128. /**
  129. * Set to true if remote folder is to be created if it does not exist.
  130. */
  131. public static final String KEY_CREATE_REMOTE_FOLDER = "CREATE_REMOTE_FOLDER";
  132. /**
  133. * Set to true if upload is to performed only when connected via wifi.
  134. */
  135. public static final String KEY_WIFI_ONLY = "WIFI_ONLY";
  136. /**
  137. * Set to true if upload is to performed only when phone is being charged.
  138. */
  139. public static final String KEY_WHILE_CHARGING_ONLY = "KEY_WHILE_CHARGING_ONLY";
  140. /**
  141. * Set to future UNIX timestamp. Upload will not be performed before this timestamp.
  142. */
  143. public static final String KEY_UPLOAD_TIMESTAMP= "KEY_UPLOAD_TIMESTAMP";
  144. public static final String KEY_LOCAL_BEHAVIOUR = "BEHAVIOUR";
  145. public static final String KEY_INSTANT_UPLOAD = "INSTANT_UPLOAD";
  146. public static final int LOCAL_BEHAVIOUR_COPY = 0;
  147. public static final int LOCAL_BEHAVIOUR_MOVE = 1;
  148. public static final int LOCAL_BEHAVIOUR_FORGET = 2;
  149. public static final int UPLOAD_SINGLE_FILE = 0;
  150. public static final int UPLOAD_MULTIPLE_FILES = 1;
  151. /**
  152. * Describes local behavior for upload.
  153. */
  154. public enum LocalBehaviour {
  155. /**
  156. * Creates a copy of file and stores it in tmp folder inside owncloud
  157. * folder on sd-card. After upload it is moved to local owncloud
  158. * storage. Original file stays untouched.
  159. */
  160. LOCAL_BEHAVIOUR_COPY(0),
  161. /**
  162. * Upload file from current storage. Afterwards original file is move to
  163. * local owncloud storage.
  164. */
  165. LOCAL_BEHAVIOUR_MOVE(1),
  166. /**
  167. * Just uploads file and leaves it where it is. Original file stays
  168. * untouched.
  169. */
  170. LOCAL_BEHAVIOUR_FORGET(2);
  171. private final int value;
  172. LocalBehaviour(int value) {
  173. this.value = value;
  174. }
  175. public int getValue() {
  176. return value;
  177. }
  178. public static LocalBehaviour fromValue(int value){
  179. switch (value)
  180. {
  181. case 0:
  182. return LOCAL_BEHAVIOUR_COPY;
  183. case 1:
  184. return LOCAL_BEHAVIOUR_MOVE;
  185. case 2:
  186. return LOCAL_BEHAVIOUR_FORGET;
  187. }
  188. return null;
  189. }
  190. }
  191. // public enum UploadQuantity {
  192. // UPLOAD_SINGLE_FILE(0), UPLOAD_MULTIPLE_FILES(1);
  193. // private final int value;
  194. //
  195. // UploadQuantity(int value) {
  196. // this.value = value;
  197. // }
  198. //
  199. // public int getValue() {
  200. // return value;
  201. // }
  202. // };
  203. private volatile Looper mServiceLooper;
  204. private volatile ServiceHandler mServiceHandler;
  205. private ExecutorService mUploadExecutor;
  206. private IBinder mBinder;
  207. private OwnCloudClient mUploadClient = null;
  208. private Account mCurrentAccount = null; // LastAccount in FileUploadService
  209. private FileDataStorageManager mStorageManager;
  210. //since there can be only one instance of an Android service, there also just one db connection.
  211. private UploadsStorageManager mUploadsStorageManager = null;
  212. private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
  213. private final AtomicBoolean mCancellationPossible = new AtomicBoolean(false);
  214. /**
  215. * List of uploads that are currently pending. Maps from remotePath to where file
  216. * is being uploaded to {@link UploadFileOperation}.
  217. */
  218. //private ConcurrentMap<String, OCUpload> mPendingUploads = new ConcurrentHashMap<String, OCUpload>();
  219. // TODO: change kind of mPendingUploads: List to IndexedForest
  220. private IndexedForest<UploadFileOperation> mPendingUploads = new IndexedForest<UploadFileOperation>();
  221. /**
  222. * {@link UploadFileOperation} object of ongoing upload. Can be null. Note: There can only be one concurrent upload!
  223. */
  224. private UploadFileOperation mCurrentUpload = null;
  225. private NotificationManager mNotificationManager;
  226. private NotificationCompat.Builder mNotificationBuilder;
  227. private int mLastPercent;
  228. private static final String MIME_TYPE_PDF = "application/pdf";
  229. private static final String FILE_EXTENSION_PDF = ".pdf";
  230. public FileUploadService() {
  231. super();
  232. }
  233. public static String getUploadFinishMessage() {
  234. return FileUploadService.class.getName().toString() + UPLOAD_FINISH_MESSAGE;
  235. }
  236. /**
  237. * Builds a key for mPendingUploads from the account and file to upload
  238. *
  239. * @param account Account where the file to upload is stored
  240. * @param file File to upload
  241. */
  242. private String buildRemoteName(Account account, OCFile file) {
  243. return account.name + file.getRemotePath();
  244. }
  245. private String buildRemoteName(Account account, String remotePath) {
  246. return account.name + remotePath;
  247. }
  248. private String buildRemoteName(OCUpload OCUpload) {
  249. return OCUpload.getAccountName() + OCUpload.getRemotePath();
  250. }
  251. /**
  252. * Checks if an ownCloud server version should support chunked uploads.
  253. *
  254. * @param version OwnCloud version instance corresponding to an ownCloud
  255. * server.
  256. * @return 'True' if the ownCloud server with version supports chunked
  257. * uploads.
  258. *
  259. * TODO - move to OCClient
  260. */
  261. private static boolean chunkedUploadIsSupported(OwnCloudVersion version) {
  262. return (version != null && version.compareTo(OwnCloudVersion.owncloud_v4_5) >= 0);
  263. }
  264. /**
  265. * Service initialization
  266. */
  267. // TODO: Clean method: comments on extra code
  268. @Override
  269. public void onCreate() {
  270. super.onCreate();
  271. Log_OC.d(TAG, "Creating service");
  272. //Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - onCreate");
  273. mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  274. // HandlerThread thread = new HandlerThread("FileUploadService-Requester"); --> From FileUploadService
  275. HandlerThread thread = new HandlerThread("FileUploaderThread",
  276. android.os.Process.THREAD_PRIORITY_BACKGROUND);
  277. thread.start();
  278. mServiceLooper = thread.getLooper();
  279. //mServiceHandler = new ServiceHandler(mServiceLooper); // FileUploaderService
  280. mServiceHandler = new ServiceHandler(mServiceLooper, this); // FileUploader
  281. mBinder = new FileUploaderBinder();
  282. // From FileUploaderService
  283. mUploadsStorageManager = new UploadsStorageManager(getContentResolver());
  284. //when this service starts there is no upload in progress. if db says so, app probably crashed before.
  285. mUploadsStorageManager.setAllCurrentToUploadLater();
  286. mUploadExecutor = Executors.newFixedThreadPool(1);
  287. Log_OC.d(TAG, "FileUploadService.retry() called by onCreate()");
  288. FileUploadService.retry(getApplicationContext());
  289. AccountManager am = AccountManager.get(getApplicationContext());
  290. am.addOnAccountsUpdatedListener(this, null, false);
  291. }
  292. /**
  293. * Service clean up
  294. */
  295. @Override
  296. public void onDestroy() {
  297. Log_OC.v(TAG, "Destroying service" );
  298. mBinder = null;
  299. mServiceHandler = null;
  300. mServiceLooper.quit();
  301. mServiceLooper = null;
  302. mNotificationManager = null;
  303. // From FileUploader
  304. //Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - onDestroy");
  305. Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.toString() + " - onDestroy");
  306. //mServiceLooper.quit();
  307. mUploadExecutor.shutdown();
  308. AccountManager am = AccountManager.get(getApplicationContext());
  309. am.removeOnAccountsUpdatedListener(this);
  310. super.onDestroy();
  311. }
  312. // Deprecated: TODO - Remove, not in FileUploader
  313. // @Override
  314. // public void onStart(Intent intent, int intentStartId) {
  315. // Message msg = mServiceHandler.obtainMessage();
  316. // msg.arg1 = intentStartId;
  317. // msg.obj = intent;
  318. // mServiceHandler.sendMessage(msg);
  319. // }
  320. /**
  321. * Entry point to add one or several files to the queue of uploads.
  322. *
  323. * New uploads are added calling to startService(), resulting in a call to
  324. * this method. This ensures the service will keep on working although the
  325. * caller activity goes away.
  326. */
  327. @Override
  328. public int onStartCommand(Intent intent, int flags, int startId) {
  329. Log_OC.d(TAG, "Starting command with id " + startId);
  330. if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE)
  331. || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
  332. Log_OC.e(TAG, "Not enough information provided in intent");
  333. return Service.START_NOT_STICKY;
  334. }
  335. int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
  336. if (uploadType == -1) {
  337. Log_OC.e(TAG, "Incorrect upload type provided");
  338. return Service.START_NOT_STICKY;
  339. }
  340. Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  341. if (!AccountUtils.exists(account, getApplicationContext())) {
  342. return Service.START_NOT_STICKY;
  343. }
  344. String[] localPaths = null, remotePaths = null, mimeTypes = null;
  345. OCFile[] files = null;
  346. if (uploadType == UPLOAD_SINGLE_FILE) {
  347. if (intent.hasExtra(KEY_FILE)) {
  348. files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };
  349. } else {
  350. localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
  351. remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
  352. mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
  353. }
  354. } else { // mUploadType == UPLOAD_MULTIPLE_FILES
  355. if (intent.hasExtra(KEY_FILE)) {
  356. files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO
  357. // will
  358. // this
  359. // casting
  360. // work
  361. // fine?
  362. } else {
  363. localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  364. remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  365. mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  366. }
  367. }
  368. FileDataStorageManager storageManager = new FileDataStorageManager(account,
  369. getContentResolver());
  370. boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  371. boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
  372. int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_FORGET);
  373. if (intent.hasExtra(KEY_FILE) && files == null) {
  374. Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
  375. return Service.START_NOT_STICKY;
  376. } else if (!intent.hasExtra(KEY_FILE)) {
  377. if (localPaths == null) {
  378. Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent");
  379. return Service.START_NOT_STICKY;
  380. }
  381. if (remotePaths == null) {
  382. Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent");
  383. return Service.START_NOT_STICKY;
  384. }
  385. if (localPaths.length != remotePaths.length) {
  386. Log_OC.e(TAG, "Different number of remote paths and local paths!");
  387. return Service.START_NOT_STICKY;
  388. }
  389. files = new OCFile[localPaths.length];
  390. for (int i = 0; i < localPaths.length; i++) {
  391. files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i],
  392. ((mimeTypes != null) ? mimeTypes[i] : null));
  393. if (files[i] == null) {
  394. // TODO @andomaex add failure Notification
  395. return Service.START_NOT_STICKY;
  396. }
  397. }
  398. }
  399. OwnCloudVersion ocv = AccountUtils.getServerVersion(account);
  400. boolean chunked = FileUploadService.chunkedUploadIsSupported(ocv);
  401. AbstractList<String> requestedUploads = new Vector<String>();
  402. String uploadKey = null;
  403. UploadFileOperation newUpload = null;
  404. try {
  405. for (int i = 0; i < files.length; i++) {
  406. newUpload = new UploadFileOperation(
  407. account,
  408. files[i],
  409. chunked,
  410. //isInstant,
  411. forceOverwrite,
  412. FileUploadService.LocalBehaviour.values()[localAction], // Change for compilation
  413. getApplicationContext()
  414. );
  415. if (isInstant) {
  416. newUpload.setRemoteFolderToBeCreated();
  417. }
  418. newUpload.addDatatransferProgressListener(this);
  419. newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
  420. Pair<String, String> putResult = mPendingUploads.putIfAbsent(
  421. account, files[i].getRemotePath(), newUpload
  422. );
  423. if (putResult != null) {
  424. uploadKey = putResult.first;
  425. requestedUploads.add(uploadKey);
  426. } // else, file already in the queue of uploads; don't repeat the request
  427. }
  428. } catch (IllegalArgumentException e) {
  429. Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
  430. return START_NOT_STICKY;
  431. } catch (IllegalStateException e) {
  432. Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
  433. return START_NOT_STICKY;
  434. } catch (Exception e) {
  435. Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
  436. return START_NOT_STICKY;
  437. }
  438. if (requestedUploads.size() > 0) {
  439. Message msg = mServiceHandler.obtainMessage();
  440. msg.arg1 = startId;
  441. msg.obj = requestedUploads;
  442. mServiceHandler.sendMessage(msg);
  443. }
  444. return Service.START_NOT_STICKY;
  445. }
  446. @Override
  447. public void onAccountsUpdated(Account[] accounts) {
  448. // Review current upload, and cancel it if its account doen't exist
  449. if (mCurrentUpload != null &&
  450. !AccountUtils.exists(mCurrentUpload.getAccount(), getApplicationContext())) {
  451. mCurrentUpload.cancel();
  452. }
  453. // The rest of uploads are cancelled when they try to start
  454. }
  455. /**
  456. * Provides a binder object that clients can use to perform operations on
  457. * the queue of uploads, excepting the addition of new files.
  458. *
  459. * Implemented to perform cancellation, pause and resume of existing
  460. * uploads.
  461. */
  462. @Override
  463. public IBinder onBind(Intent arg0) {
  464. return mBinder;
  465. }
  466. /**
  467. * Called when ALL the bound clients were onbound.
  468. */
  469. @Override
  470. public boolean onUnbind(Intent intent) {
  471. ((FileUploaderBinder) mBinder).clearListeners();
  472. return false; // not accepting rebinding (default behaviour)
  473. }
  474. /**
  475. * Binder to let client components to perform operations on the queue of
  476. * uploads.
  477. *
  478. * It provides by itself the available operations.
  479. */
  480. public class FileUploaderBinder extends Binder implements OnDatatransferProgressListener {
  481. /**
  482. * Map of listeners that will be reported about progress of uploads from
  483. * a {@link FileUploaderBinder} instance
  484. */
  485. private Map<String, OnDatatransferProgressListener> mBoundListeners = new HashMap<String, OnDatatransferProgressListener>();
  486. /**
  487. * Returns ongoing upload operation. May be null.
  488. */
  489. public UploadFileOperation getCurrentUploadOperation() {
  490. return mCurrentUpload;
  491. }
  492. /**
  493. * Cancels a pending or current upload of a remote file.
  494. *
  495. * @param account Owncloud account where the remote file will be stored.
  496. * @param file A file in the queue of pending uploads
  497. */
  498. public void cancel(Account account, OCFile file) {
  499. // From FileUploader
  500. Pair<UploadFileOperation, String> removeResult = mPendingUploads.remove(account, file.getRemotePath());
  501. UploadFileOperation upload = removeResult.first;
  502. if (upload != null) {
  503. upload.cancel();
  504. } else {
  505. if (mCurrentUpload != null && mCurrentAccount != null &&
  506. mCurrentUpload.getRemotePath().startsWith(file.getRemotePath()) &&
  507. account.name.equals(mCurrentAccount.name)) {
  508. mCurrentUpload.cancel();
  509. }
  510. }
  511. // From FileUploadService
  512. // updating current references (i.e., uploadStatus of current
  513. // upload) is handled by updateDataseUploadResult() which is called
  514. // after upload finishes. Following cancel call makes sure that is
  515. // does finish right now.
  516. if (mCurrentUpload != null && mCurrentUpload.isUploadInProgress()) {
  517. Log_OC.d(TAG, "Calling cancel for " + file.getRemotePath() + " during upload operation.");
  518. mCurrentUpload.cancel();
  519. } else if(mCancellationPossible.get()){
  520. Log_OC.d(TAG, "Calling cancel for " + file.getRemotePath() + " during preparing for upload.");
  521. mCancellationRequested.set(true);
  522. } else {
  523. Log_OC.d(TAG, "Calling cancel for " + file.getRemotePath() + " while upload is pending.");
  524. // upload not in progress, but pending.
  525. // in this case we have to update the db here.
  526. //OCUpload upload = mPendingUploads.remove(buildRemoteName(account, file));
  527. OCUpload ocUpload = mUploadsStorageManager.getUploadByLocalPath(upload.getStoragePath())[0];
  528. ocUpload.setUploadStatus(UploadStatus.UPLOAD_CANCELLED);
  529. ocUpload.setLastResult(UploadResult.CANCELLED);
  530. // storagePath inside upload is the temporary path. file
  531. // contains the correct path used as db reference.
  532. ocUpload.getOCFile().setStoragePath(file.getStoragePath());
  533. mUploadsStorageManager.updateUploadStatus(ocUpload);
  534. }
  535. }
  536. /**
  537. * Cancels a pending or current upload for an account
  538. *
  539. * @param account Owncloud accountName where the remote file will be stored.
  540. */
  541. public void cancel(Account account) {
  542. Log_OC.d(TAG, "Account= " + account.name);
  543. if (mCurrentUpload != null) {
  544. Log_OC.d(TAG, "Current Upload Account= " + mCurrentUpload.getAccount().name);
  545. if (mCurrentUpload.getAccount().name.equals(account.name)) {
  546. mCurrentUpload.cancel();
  547. }
  548. }
  549. // Cancel pending uploads
  550. cancelUploadsForAccount(account);
  551. }
  552. // TODO: Review: Method from FileUploadService with some changes because the merge with FileUploader
  553. public void remove(Account account, OCFile file) {
  554. Pair<UploadFileOperation, String> removeResult = mPendingUploads.remove(account, file.getRemotePath());
  555. UploadFileOperation upload = removeResult.first;
  556. //OCUpload upload = mPendingUploads.remove(buildRemoteName(account, file));
  557. if(upload == null) {
  558. Log_OC.e(TAG, "Could not delete upload "+ file +" from mPendingUploads.");
  559. }
  560. int d = mUploadsStorageManager.removeUpload(upload.getStoragePath());
  561. if(d == 0) {
  562. Log_OC.e(TAG, "Could not delete upload "+ file.getStoragePath() +" from database.");
  563. }
  564. }
  565. // TODO: Review: Method from FileUploadService with some changes because the merge with FileUploader
  566. // TODO Complete operation to retry the upload
  567. /**
  568. * Puts upload in upload list and tell FileUploadService to upload items in list.
  569. */
  570. public void retry(Account account, OCUpload upload) {
  571. String uploadKey = buildRemoteName(upload);
  572. //mPendingUploads.put(uploadKey, upload);
  573. FileUploadService.retry(getApplicationContext(), uploadKey);
  574. }
  575. public void clearListeners() {
  576. mBoundListeners.clear();
  577. }
  578. /**
  579. * Returns True when the file described by 'file' is being uploaded to
  580. * the ownCloud account 'account' or waiting for it
  581. *
  582. * If 'file' is a directory, returns 'true' if some of its descendant
  583. * files is uploading or waiting to upload.
  584. *
  585. * Warning: If remote file exists and !forceOverwrite the original file
  586. * is being returned here. That is, it seems as if the original file is
  587. * being updated when actually a new file is being uploaded.
  588. *
  589. * @param account Owncloud account where the remote file will be stored.
  590. * @param file A file that could be in the queue of pending uploads
  591. */
  592. public boolean isUploading(Account account, OCFile file) {
  593. if (account == null || file == null)
  594. return false;
  595. return (mPendingUploads.contains(account, file.getRemotePath()));
  596. // Commented code from FileUploadService
  597. // String targetKey = buildRemoteName(account, file);
  598. // synchronized (mPendingUploads) {
  599. // if (file.isFolder()) {
  600. // // this can be slow if there are many uploads :(
  601. // Iterator<String> it = mPendingUploads.keySet().iterator();
  602. // boolean found = false;
  603. // while (it.hasNext() && !found) {
  604. // found = it.next().startsWith(targetKey);
  605. // }
  606. // return found;
  607. // } else {
  608. // return (mPendingUploads.containsKey(targetKey));
  609. // }
  610. // }
  611. }
  612. /**
  613. * Adds a listener interested in the progress of the upload for a
  614. * concrete file.
  615. *
  616. * @param listener Object to notify about progress of transfer.
  617. * @param account ownCloud account holding the file of interest.
  618. * @param file {@link OCFile} of interest for listener.
  619. */
  620. public void addDatatransferProgressListener(OnDatatransferProgressListener listener, Account account,
  621. OCFile file) {
  622. if (account == null || file == null || listener == null)
  623. return;
  624. String targetKey = buildRemoteName(account, file);
  625. mBoundListeners.put(targetKey, listener);
  626. }
  627. /**
  628. * Removes a listener interested in the progress of the upload for a
  629. * concrete file.
  630. *
  631. * @param listener Object to notify about progress of transfer.
  632. * @param account ownCloud account holding the file of interest.
  633. * @param file {@link OCFile} of interest for listener.
  634. */
  635. public void removeDatatransferProgressListener(OnDatatransferProgressListener listener, Account account,
  636. OCFile file) {
  637. if (account == null || file == null || listener == null)
  638. return;
  639. String targetKey = buildRemoteName(account, file);
  640. if (mBoundListeners.get(targetKey) == listener) {
  641. mBoundListeners.remove(targetKey);
  642. }
  643. }
  644. // TODO: Review: Method from FileUploadService with some changes because the merge with FileUploader
  645. @Override
  646. public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer,
  647. String fileName) {
  648. String key = buildRemoteName(mCurrentUpload.getAccount(), mCurrentUpload.getFile());
  649. OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  650. if (boundListener != null) {
  651. boundListener.onTransferProgress(progressRate, totalTransferredSoFar,
  652. totalToTransfer, fileName);
  653. }
  654. //
  655. // Set<Entry<String, OCUpload>> uploads = mPendingUploads.entrySet();
  656. // UploadFileOperation currentUpload = mCurrentUpload;
  657. // if (currentUpload == null) {
  658. // Log_OC.e(TAG, "Found no current upload with remote path " + localFileName + ". Ignore.");
  659. // return;
  660. // }
  661. // String key = buildRemoteName(currentUpload.getAccount(), currentUpload.getFile());
  662. // OnDatatransferProgressListener boundListener = mBoundListeners.get(key);
  663. // if (boundListener != null) {
  664. // boundListener.onTransferProgress(progressRate, totalTransferredSoFar, totalToTransfer, localFileName);
  665. // }
  666. }
  667. }
  668. // TODO: Remove this comment: Class totally replaced by FileUploader ServiceHandler
  669. // TODO: Review merge modifications
  670. /**
  671. * Upload worker. Performs the pending uploads in the order they were
  672. * requested.
  673. *
  674. * Created with the Looper of a new thread, started in
  675. * {@link FileUploadService#onCreate()}.
  676. */
  677. private static class ServiceHandler extends Handler {
  678. // don't make it a final class, and don't remove the static ; lint will
  679. // warn about a possible memory leak
  680. FileUploadService mService;
  681. public ServiceHandler(Looper looper, FileUploadService service) {
  682. super(looper);
  683. if (service == null)
  684. throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
  685. mService = service;
  686. }
  687. @Override
  688. public void handleMessage(Message msg) {
  689. @SuppressWarnings("unchecked")
  690. AbstractList<String> requestedUploads = (AbstractList<String>) msg.obj;
  691. if (msg.obj != null) {
  692. Iterator<String> it = requestedUploads.iterator();
  693. while (it.hasNext()) {
  694. mService.uploadFile(it.next());
  695. }
  696. }
  697. Log_OC.d(TAG, "Stopping command after id " + msg.arg1);
  698. mService.stopSelf(msg.arg1);
  699. }
  700. }
  701. // TODO: Method from FileUploader
  702. /**
  703. * Core upload method: sends the file(s) to upload
  704. *
  705. * @param uploadKey Key to access the upload to perform, contained in mPendingUploads
  706. */
  707. public void uploadFile(String uploadKey) {
  708. mCurrentUpload = mPendingUploads.get(uploadKey);
  709. if (mCurrentUpload != null) {
  710. // Detect if the account exists
  711. if (AccountUtils.exists(mCurrentUpload.getAccount(), getApplicationContext())) {
  712. Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().name + " exists");
  713. notifyUploadStart(mCurrentUpload);
  714. RemoteOperationResult uploadResult = null, grantResult;
  715. try {
  716. /// prepare client object to send the request to the ownCloud server
  717. if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentUpload.getAccount())) {
  718. mCurrentAccount = mCurrentUpload.getAccount();
  719. mStorageManager = new FileDataStorageManager(
  720. mCurrentAccount,
  721. getContentResolver()
  722. );
  723. } // else, reuse storage manager from previous operation
  724. // always get client from client manager, to get fresh credentials in case of update
  725. OwnCloudAccount ocAccount = new OwnCloudAccount(mCurrentAccount, this);
  726. mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().
  727. getClientFor(ocAccount, this);
  728. /// check the existence of the parent folder for the file to upload
  729. String remoteParentPath = new File(mCurrentUpload.getRemotePath()).getParent();
  730. remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ?
  731. remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR;
  732. grantResult = grantFolderExistence(remoteParentPath);
  733. /// perform the upload
  734. if (grantResult.isSuccess()) {
  735. OCFile parent = mStorageManager.getFileByPath(remoteParentPath);
  736. mCurrentUpload.getFile().setParentId(parent.getFileId());
  737. uploadResult = mCurrentUpload.execute(mUploadClient);
  738. if (uploadResult.isSuccess()) {
  739. saveUploadedFile();
  740. } else if (uploadResult.getCode() == ResultCode.SYNC_CONFLICT) {
  741. mStorageManager.saveConflict(mCurrentUpload.getFile(),
  742. mCurrentUpload.getFile().getEtagInConflict());
  743. }
  744. } else {
  745. uploadResult = grantResult;
  746. }
  747. } catch (Exception e) {
  748. Log_OC.e(TAG, "Error uploading", e);
  749. uploadResult = new RemoteOperationResult(e);
  750. } finally {
  751. Pair<UploadFileOperation, String> removeResult;
  752. if (mCurrentUpload.wasRenamed()) {
  753. removeResult = mPendingUploads.removePayload(
  754. mCurrentAccount,
  755. mCurrentUpload.getOldFile().getRemotePath()
  756. );
  757. } else {
  758. removeResult = mPendingUploads.removePayload(
  759. mCurrentAccount,
  760. mCurrentUpload.getRemotePath()
  761. );
  762. }
  763. /// notify result
  764. notifyUploadResult(mCurrentUpload, uploadResult);
  765. sendBroadcastUploadFinished(mCurrentUpload, uploadResult, removeResult.second);
  766. }
  767. } else {
  768. // Cancel the transfer
  769. Log_OC.d(TAG, "Account " + mCurrentUpload.getAccount().toString() +
  770. " doesn't exist");
  771. cancelUploadsForAccount(mCurrentUpload.getAccount());
  772. }
  773. }
  774. }
  775. // TODO: Replaced by uploadFile(String uploadKey)
  776. /**
  777. * Core upload method: sends the file(s) to upload. This function blocks
  778. * until upload succeeded or failed.
  779. *
  780. * Before uploading starts mCurrentUpload is set.
  781. *
  782. * @param OCUpload Key to access the upload to perform, contained in
  783. * mPendingUploads
  784. * @return RemoteOperationResult of upload operation.
  785. */
  786. // private RemoteOperationResult uploadFile(OCUpload OCUpload) {
  787. //
  788. // if (mCurrentUpload != null) {
  789. // Log_OC.e(TAG,
  790. // "mCurrentUpload != null. Meaning there is another upload in progress, cannot start a new one. Fix that!");
  791. // return new RemoteOperationResult(new IllegalStateException("mCurrentUpload != null when calling uploadFile()"));
  792. // }
  793. //
  794. // AccountManager aMgr = AccountManager.get(this);
  795. // Account account = OCUpload.getAccount(getApplicationContext());
  796. // String version = aMgr.getUserData(account, Constants.KEY_OC_VERSION);
  797. // OwnCloudVersion ocv = new OwnCloudVersion(version);
  798. //
  799. // boolean chunked = FileUploadService.chunkedUploadIsSupported(ocv);
  800. // String uploadKey = null;
  801. //
  802. // uploadKey = buildRemoteName(account, OCUpload.getRemotePath());
  803. // OCFile file = OCUpload.getOCFile();
  804. // Log_OC.d(TAG, "mCurrentUpload = new UploadFileOperation");
  805. // mCurrentUpload = new UploadFileOperation(account, file, chunked, OCUpload.isForceOverwrite(),
  806. // OCUpload.getLocalAction(), getApplicationContext());
  807. // if (OCUpload.isCreateRemoteFolder()) {
  808. // mCurrentUpload.setRemoteFolderToBeCreated();
  809. // }
  810. // mCurrentUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
  811. // mCurrentUpload.addDatatransferProgressListener(this);
  812. //
  813. // mCancellationRequested.set(false);
  814. // mCancellationPossible.set(true);
  815. // notifyUploadStart(mCurrentUpload);
  816. //
  817. // RemoteOperationResult uploadResult = null, grantResult = null;
  818. // try {
  819. // // prepare client object to send requests to the ownCloud
  820. // // server
  821. // if (mUploadClient == null || !mCurrentAccount.equals(mCurrentUpload.getAccount())) {
  822. // mCurrentAccount = mCurrentUpload.getAccount();
  823. // mStorageManager = new FileDataStorageManager(mCurrentAccount, getContentResolver());
  824. // OwnCloudAccount ocAccount = new OwnCloudAccount(mCurrentAccount, this);
  825. // mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, this);
  826. // }
  827. //
  828. // // check the existence of the parent folder for the file to
  829. // // upload
  830. // String remoteParentPath = new File(mCurrentUpload.getRemotePath()).getParent();
  831. // remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ? remoteParentPath : remoteParentPath
  832. // + OCFile.PATH_SEPARATOR;
  833. // //TODO this might take a moment and should thus be cancelable, for now: cancel afterwards.
  834. // grantResult = grantFolderExistence(mCurrentUpload, remoteParentPath);
  835. //
  836. // if(mCancellationRequested.get()) {
  837. // throw new OperationCancelledException();
  838. // }
  839. // mCancellationPossible.set(false);
  840. //
  841. // // perform the upload
  842. // if (grantResult.isSuccess()) {
  843. // OCFile parent = mStorageManager.getFileByPath(remoteParentPath);
  844. // mCurrentUpload.getFile().setParentId(parent.getFileId());
  845. // // inside this call the remote path may be changed (if remote
  846. // // file exists and !forceOverwrite) in this case the map from
  847. // // mPendingUploads is wrong. This results in an upload
  848. // // indication in the GUI showing that the original file is being
  849. // // uploaded (instead that a new one is created)
  850. // uploadResult = mCurrentUpload.execute(mUploadClient);
  851. // if (uploadResult.isSuccess()) {
  852. // saveUploadedFile(mCurrentUpload);
  853. // }
  854. // } else {
  855. // uploadResult = grantResult;
  856. // }
  857. //
  858. // } catch (AccountsException e) {
  859. // Log_OC.e(TAG, "Error while trying to get autorization for " + mCurrentAccount.name, e);
  860. // uploadResult = new RemoteOperationResult(e);
  861. //
  862. // } catch (IOException e) {
  863. // Log_OC.e(TAG, "Error while trying to get autorization for " + mCurrentAccount.name, e);
  864. // uploadResult = new RemoteOperationResult(e);
  865. //
  866. // } catch (OperationCancelledException e) {
  867. // uploadResult = new RemoteOperationResult(e);
  868. // } finally {
  869. // Log_OC.d(TAG, "Remove CurrentUploadItem from pending upload Item Map.");
  870. // if (uploadResult.isException()) {
  871. // // enforce the creation of a new client object for next
  872. // // uploads; this grant that a new socket will
  873. // // be created in the future if the current exception is due
  874. // // to an abrupt lose of network connection
  875. // mUploadClient = null;
  876. // }
  877. // }
  878. // return uploadResult;
  879. // }
  880. /**
  881. * Checks the existence of the folder where the current file will be uploaded both
  882. * in the remote server and in the local database.
  883. *
  884. * If the upload is set to enforce the creation of the folder, the method tries to
  885. * create it both remote and locally.
  886. *
  887. * @param pathToGrant Full remote path whose existence will be granted.
  888. * @return An {@link OCFile} instance corresponding to the folder where the file
  889. * will be uploaded.
  890. */
  891. private RemoteOperationResult grantFolderExistence(String pathToGrant) {
  892. RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, this, false);
  893. RemoteOperationResult result = operation.execute(mUploadClient);
  894. if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND &&
  895. mCurrentUpload.isRemoteFolderToBeCreated()) {
  896. SyncOperation syncOp = new CreateFolderOperation( pathToGrant, true);
  897. result = syncOp.execute(mUploadClient, mStorageManager);
  898. }
  899. if (result.isSuccess()) {
  900. OCFile parentDir = mStorageManager.getFileByPath(pathToGrant);
  901. if (parentDir == null) {
  902. parentDir = createLocalFolder(pathToGrant);
  903. }
  904. if (parentDir != null) {
  905. result = new RemoteOperationResult(ResultCode.OK);
  906. } else {
  907. result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  908. }
  909. }
  910. return result;
  911. }
  912. // TODO: Replaced by grantFolderExistence(String pathToGrant
  913. // /**
  914. // * Checks the existence of the folder where the current file will be
  915. // * uploaded both in the remote server and in the local database.
  916. // *
  917. // * If the upload is set to enforce the creation of the folder, the method
  918. // * tries to create it both remote and locally.
  919. // *
  920. // * @param pathToGrant Full remote path whose existence will be granted.
  921. // * @return An {@link OCFile} instance corresponding to the folder where the
  922. // * file will be uploaded.
  923. // */
  924. // private RemoteOperationResult grantFolderExistence(UploadFileOperation currentUpload, String pathToGrant) {
  925. // RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, this, false);
  926. // RemoteOperationResult result = operation.execute(mUploadClient);
  927. // if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND
  928. // && currentUpload.isRemoteFolderToBeCreated()) {
  929. // SyncOperation syncOp = new CreateFolderOperation(pathToGrant, true);
  930. // result = syncOp.execute(mUploadClient, mStorageManager);
  931. // }
  932. // if (result.isSuccess()) {
  933. // OCFile parentDir = mStorageManager.getFileByPath(pathToGrant);
  934. // if (parentDir == null) {
  935. // parentDir = createLocalFolder(pathToGrant);
  936. // }
  937. // if (parentDir != null) {
  938. // result = new RemoteOperationResult(ResultCode.OK);
  939. // } else {
  940. // result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
  941. // }
  942. // }
  943. // return result;
  944. // }
  945. private OCFile createLocalFolder(String remotePath) {
  946. String parentPath = new File(remotePath).getParent();
  947. parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ?
  948. parentPath : parentPath + OCFile.PATH_SEPARATOR;
  949. OCFile parent = mStorageManager.getFileByPath(parentPath);
  950. if (parent == null) {
  951. parent = createLocalFolder(parentPath);
  952. }
  953. if (parent != null) {
  954. OCFile createdFolder = new OCFile(remotePath);
  955. createdFolder.setMimetype("DIR");
  956. createdFolder.setParentId(parent.getFileId());
  957. mStorageManager.saveFile(createdFolder);
  958. return createdFolder;
  959. }
  960. return null;
  961. }
  962. /**
  963. * Saves a OC File after a successful upload.
  964. *
  965. * A PROPFIND is necessary to keep the props in the local database
  966. * synchronized with the server, specially the modification time and Etag
  967. * (where available)
  968. *
  969. * TODO move into UploadFileOperation
  970. */
  971. private void saveUploadedFile() {
  972. OCFile file = mCurrentUpload.getFile();
  973. if (file.fileExists()) {
  974. file = mStorageManager.getFileById(file.getFileId());
  975. }
  976. long syncDate = System.currentTimeMillis();
  977. file.setLastSyncDateForData(syncDate);
  978. // new PROPFIND to keep data consistent with server
  979. // in theory, should return the same we already have
  980. ReadRemoteFileOperation operation =
  981. new ReadRemoteFileOperation(mCurrentUpload.getRemotePath());
  982. RemoteOperationResult result = operation.execute(mUploadClient);
  983. if (result.isSuccess()) {
  984. updateOCFile(file, (RemoteFile) result.getData().get(0));
  985. file.setLastSyncDateForProperties(syncDate);
  986. } else {
  987. Log_OC.e(TAG, "Error reading properties of file after successful upload; this is gonna hurt...");
  988. }
  989. // / maybe this would be better as part of UploadFileOperation... or
  990. // maybe all this method
  991. if (mCurrentUpload.wasRenamed()) {
  992. OCFile oldFile = mCurrentUpload.getOldFile();
  993. if (oldFile.fileExists()) {
  994. oldFile.setStoragePath(null);
  995. mStorageManager.saveFile(oldFile);
  996. mStorageManager.saveConflict(oldFile, null);
  997. } // else: it was just an automatic renaming due to a name
  998. // coincidence; nothing else is needed, the storagePath is right
  999. // in the instance returned by mCurrentUpload.getFile()
  1000. }
  1001. file.setNeedsUpdateThumbnail(true);
  1002. mStorageManager.saveFile(file);
  1003. mStorageManager.saveConflict(file, null);
  1004. mStorageManager.triggerMediaScan(file.getStoragePath());
  1005. }
  1006. private void updateOCFile(OCFile file, RemoteFile remoteFile) {
  1007. file.setCreationTimestamp(remoteFile.getCreationTimestamp());
  1008. file.setFileLength(remoteFile.getLength());
  1009. file.setMimetype(remoteFile.getMimeType());
  1010. file.setModificationTimestamp(remoteFile.getModifiedTimestamp());
  1011. file.setModificationTimestampAtLastSyncForData(remoteFile.getModifiedTimestamp());
  1012. file.setEtag(remoteFile.getEtag());
  1013. file.setRemoteId(remoteFile.getRemoteId());
  1014. }
  1015. private OCFile obtainNewOCFileToUpload(String remotePath, String localPath, String mimeType) {
  1016. // MIME type
  1017. if (mimeType == null || mimeType.length() <= 0) {
  1018. try {
  1019. mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
  1020. remotePath.substring(remotePath.lastIndexOf('.') + 1));
  1021. } catch (IndexOutOfBoundsException e) {
  1022. Log_OC.e(TAG, "Trying to find out MIME type of a file without extension: " + remotePath);
  1023. }
  1024. }
  1025. if (mimeType == null) {
  1026. mimeType = "application/octet-stream";
  1027. }
  1028. if (isPdfFileFromContentProviderWithoutExtension(localPath, mimeType)){
  1029. remotePath += FILE_EXTENSION_PDF;
  1030. }
  1031. OCFile newFile = new OCFile(remotePath);
  1032. newFile.setStoragePath(localPath);
  1033. newFile.setLastSyncDateForProperties(0);
  1034. newFile.setLastSyncDateForData(0);
  1035. // size
  1036. if (localPath != null && localPath.length() > 0) {
  1037. File localFile = new File(localPath);
  1038. newFile.setFileLength(localFile.length());
  1039. newFile.setLastSyncDateForData(localFile.lastModified());
  1040. } // don't worry about not assigning size, the problems with localPath
  1041. // are checked when the UploadFileOperation instance is created
  1042. newFile.setMimetype(mimeType);
  1043. return newFile;
  1044. }
  1045. /**
  1046. * Creates a status notification to show the upload progress
  1047. *
  1048. * @param upload Upload operation starting.
  1049. */
  1050. private void notifyUploadStart(UploadFileOperation upload) {
  1051. // / create status notification with a progress bar
  1052. mLastPercent = 0;
  1053. mNotificationBuilder =
  1054. NotificationBuilderWithProgressBar.newNotificationBuilderWithProgressBar(this);
  1055. mNotificationBuilder
  1056. .setOngoing(true)
  1057. .setSmallIcon(R.drawable.notification_icon)
  1058. .setTicker(getString(R.string.uploader_upload_in_progress_ticker))
  1059. .setContentTitle(getString(R.string.uploader_upload_in_progress_ticker))
  1060. .setProgress(100, 0, false)
  1061. .setContentText(
  1062. String.format(getString(R.string.uploader_upload_in_progress_content), 0, upload.getFileName()));
  1063. /// includes a pending intent in the notification showing the details
  1064. Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
  1065. showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  1066. showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  1067. showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1068. showUploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1069. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  1070. showUploadListIntent, 0));
  1071. // TODO: Review Old behaviour in FileUploader
  1072. /// includes a pending intent in the notification showing the details view of the file
  1073. // Intent showDetailsIntent = new Intent(this, FileDisplayActivity.class);
  1074. // showDetailsIntent.putExtra(FileActivity.EXTRA_FILE, (Parcelable) upload.getFile());
  1075. // showDetailsIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  1076. // showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1077. // mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
  1078. // this, (int) System.currentTimeMillis(), showDetailsIntent, 0
  1079. // ));
  1080. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  1081. updateDatabaseUploadStart(mCurrentUpload);
  1082. }
  1083. /**
  1084. * Updates the persistent upload database that upload is in progress.
  1085. */
  1086. private void updateDatabaseUploadStart(UploadFileOperation upload) {
  1087. mUploadsStorageManager.updateUploadStatus(
  1088. upload.getOriginalStoragePath(),
  1089. UploadStatus.UPLOAD_IN_PROGRESS, null
  1090. );
  1091. }
  1092. /**
  1093. * Callback method to update the progress bar in the status notification
  1094. */
  1095. @Override
  1096. public void onTransferProgress(
  1097. long progressRate, long totalTransferredSoFar, long totalToTransfer, String filePath
  1098. ) {
  1099. int percent = (int) (100.0 * ((double) totalTransferredSoFar) / ((double) totalToTransfer));
  1100. if (percent != mLastPercent) {
  1101. mNotificationBuilder.setProgress(100, percent, false);
  1102. String fileName = filePath.substring(filePath.lastIndexOf(FileUtils.PATH_SEPARATOR) + 1);
  1103. String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, fileName);
  1104. mNotificationBuilder.setContentText(text);
  1105. mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotificationBuilder.build());
  1106. }
  1107. mLastPercent = percent;
  1108. }
  1109. /**
  1110. * Updates the status notification with the result of an upload operation.
  1111. *
  1112. * @param uploadResult Result of the upload operation.
  1113. * @param upload Finished upload operation
  1114. */
  1115. private void notifyUploadResult(UploadFileOperation upload,
  1116. RemoteOperationResult uploadResult) {
  1117. Log_OC.d(TAG, "NotifyUploadResult with resultCode: " + uploadResult.getCode());
  1118. // / cancelled operation or success -> silent removal of progress
  1119. // notification
  1120. mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
  1121. // Show the result: success or fail notification
  1122. if (!uploadResult.isCancelled()) {
  1123. int tickerId = (uploadResult.isSuccess()) ? R.string.uploader_upload_succeeded_ticker
  1124. : R.string.uploader_upload_failed_ticker;
  1125. String content; // = null;
  1126. // check credentials error
  1127. boolean needsToUpdateCredentials = (
  1128. uploadResult.getCode() == ResultCode.UNAUTHORIZED ||
  1129. uploadResult.isIdPRedirection()
  1130. );
  1131. tickerId = (needsToUpdateCredentials) ?
  1132. R.string.uploader_upload_failed_credentials_error : tickerId;
  1133. mNotificationBuilder
  1134. .setTicker(getString(tickerId))
  1135. .setContentTitle(getString(tickerId))
  1136. .setAutoCancel(true)
  1137. .setOngoing(false)
  1138. .setProgress(0, 0, false);
  1139. content = ErrorMessageAdapter.getErrorCauseMessage(
  1140. uploadResult, upload, getResources()
  1141. );
  1142. if (needsToUpdateCredentials) {
  1143. // let the user update credentials with one click
  1144. Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
  1145. updateAccountCredentials.putExtra(
  1146. AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount()
  1147. );
  1148. updateAccountCredentials.putExtra(
  1149. AuthenticatorActivity.EXTRA_ACTION,
  1150. AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
  1151. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  1152. updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
  1153. updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
  1154. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(
  1155. this,
  1156. (int) System.currentTimeMillis(),
  1157. updateAccountCredentials,
  1158. PendingIntent.FLAG_ONE_SHOT));
  1159. mUploadClient = null;
  1160. // grant that future retries on the same account will get the fresh credentials
  1161. }else {
  1162. mNotificationBuilder.setContentText(content);
  1163. //Changes for compilation
  1164. // if (upload.isInstant()) {
  1165. // DbHandler db = null;
  1166. // try {
  1167. // db = new DbHandler(this.getBaseContext());
  1168. // String message = uploadResult.getLogMessage() + " errorCode: " +
  1169. // uploadResult.getCode();
  1170. // Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
  1171. // if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
  1172. // //message = getString(R.string.failed_upload_quota_exceeded_text);
  1173. // if (db.updateFileState(
  1174. // upload.getOriginalStoragePath(),
  1175. // DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
  1176. // message) == 0) {
  1177. // db.putFileForLater(
  1178. // upload.getOriginalStoragePath(),
  1179. // upload.getAccount().name,
  1180. // message
  1181. // );
  1182. // }
  1183. // }
  1184. // } finally {
  1185. // if (db != null) {
  1186. // db.close();
  1187. // }
  1188. // }
  1189. // }
  1190. }
  1191. if(!uploadResult.isSuccess()){
  1192. //in case of failure, do not show details file view (because there is no file!)
  1193. Intent showUploadListIntent = new Intent(this, UploadListActivity.class);
  1194. showUploadListIntent.putExtra(FileActivity.EXTRA_FILE, upload.getFile());
  1195. showUploadListIntent.putExtra(FileActivity.EXTRA_ACCOUNT, upload.getAccount());
  1196. mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
  1197. showUploadListIntent, 0));
  1198. }
  1199. mNotificationBuilder.setContentText(content);
  1200. mNotificationManager.notify(tickerId, mNotificationBuilder.build());
  1201. if (uploadResult.isSuccess()) {
  1202. //Changes for compilation
  1203. // DbHandler db = new DbHandler(this.getBaseContext());
  1204. // db.removeIUPendingFile(mCurrentUpload.getOriginalStoragePath());
  1205. // db.close();
  1206. // remove success notification, with a delay of 2 seconds
  1207. NotificationDelayer.cancelWithDelay(mNotificationManager, R.string.uploader_upload_succeeded_ticker,
  1208. 2000);
  1209. }
  1210. }
  1211. }
  1212. /**
  1213. * Updates the persistent upload database with upload result.
  1214. */
  1215. private void updateDatabaseUploadResult(RemoteOperationResult uploadResult, UploadFileOperation upload) {
  1216. // result: success or fail notification
  1217. Log_OC.d(TAG, "updateDataseUploadResult uploadResult: " + uploadResult + " upload: " + upload);
  1218. if (uploadResult.isCancelled()) {
  1219. mUploadsStorageManager.updateUploadStatus(
  1220. upload.getOriginalStoragePath(),
  1221. UploadStatus.UPLOAD_CANCELLED,
  1222. UploadResult.CANCELLED
  1223. );
  1224. } else {
  1225. if (uploadResult.isSuccess()) {
  1226. mUploadsStorageManager.updateUploadStatus(
  1227. upload.getOriginalStoragePath(),
  1228. UploadStatus.UPLOAD_SUCCEEDED,
  1229. UploadResult.UPLOADED
  1230. );
  1231. } else {
  1232. // TODO: Disable for testing of menu actions in uploads view
  1233. // if (shouldRetryFailedUpload(uploadResult)) {
  1234. // mUploadsStorageManager.updateUploadStatus(
  1235. // upload.getOriginalStoragePath(), UploadStatus.UPLOAD_FAILED_RETRY, uploadResult
  1236. // );
  1237. // } else {
  1238. // mUploadsStorageManager.updateUploadStatus(upload.getOriginalStoragePath(),
  1239. // UploadsStorageManager.UploadStatus.UPLOAD_FAILED_GIVE_UP, uploadResult);
  1240. // }
  1241. }
  1242. }
  1243. }
  1244. // TODO: Disable for testing of menu actions in uploads view
  1245. //
  1246. // /**
  1247. // * Determines whether with given uploadResult the upload should be retried later.
  1248. // * @param uploadResult
  1249. // * @return true if upload should be retried later, false if is should be abandoned.
  1250. // */
  1251. // private boolean shouldRetryFailedUpload(RemoteOperationResult uploadResult) {
  1252. // if (uploadResult.isSuccess()) {
  1253. // return false;
  1254. // }
  1255. // switch (uploadResult.getCode()) {
  1256. // case HOST_NOT_AVAILABLE:
  1257. // case NO_NETWORK_CONNECTION:
  1258. // case TIMEOUT:
  1259. // case WRONG_CONNECTION: // SocketException
  1260. // return true;
  1261. // default:
  1262. // return false;
  1263. // }
  1264. // }
  1265. /**
  1266. * Sends a broadcast in order to the interested activities can update their
  1267. * view
  1268. *
  1269. * @param upload Finished upload operation
  1270. * @param uploadResult Result of the upload operation
  1271. * @param unlinkedFromRemotePath Path in the uploads tree where the upload was unlinked from
  1272. */
  1273. private void sendBroadcastUploadFinished(
  1274. UploadFileOperation upload,
  1275. RemoteOperationResult uploadResult,
  1276. String unlinkedFromRemotePath) {
  1277. Intent end = new Intent(getUploadFinishMessage());
  1278. end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  1279. // path, after
  1280. // possible
  1281. // automatic
  1282. // renaming
  1283. if (upload.wasRenamed()) {
  1284. end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  1285. }
  1286. end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  1287. end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  1288. end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  1289. if (unlinkedFromRemotePath != null) {
  1290. end.putExtra(EXTRA_LINKED_TO_PATH, unlinkedFromRemotePath);
  1291. }
  1292. sendStickyBroadcast(end);
  1293. }
  1294. // TODO: Remove. Replace by sendBroadcastUploadFinished(UploadFileOperation, RemoteOperationResult, String)
  1295. // /**
  1296. // * Sends a broadcast in order to the interested activities can update their
  1297. // * view
  1298. // * @param uploadResult Result of the upload operation
  1299. // * @param upload Finished upload operation
  1300. // */
  1301. // private void sendFinalBroadcast(RemoteOperationResult uploadResult, UploadFileOperation upload) {
  1302. // Intent end = new Intent(getUploadFinishMessage());
  1303. // end.putExtra(EXTRA_REMOTE_PATH, upload.getRemotePath()); // real remote
  1304. // // path, after
  1305. // // possible
  1306. // // automatic
  1307. // // renaming
  1308. // if (upload.wasRenamed()) {
  1309. // end.putExtra(EXTRA_OLD_REMOTE_PATH, upload.getOldFile().getRemotePath());
  1310. // }
  1311. // end.putExtra(EXTRA_OLD_FILE_PATH, upload.getOriginalStoragePath());
  1312. // end.putExtra(ACCOUNT_NAME, upload.getAccount().name);
  1313. // end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult.isSuccess());
  1314. // sendStickyBroadcast(end);
  1315. // }
  1316. /**
  1317. * Checks if content provider, using the content:// scheme, returns a file with mime-type
  1318. * 'application/pdf' but file has not extension
  1319. * @param localPath Full path to a file in the local file system.
  1320. * @param mimeType MIME type of the file.
  1321. * @return true if is needed to add the pdf file extension to the file
  1322. */
  1323. private boolean isPdfFileFromContentProviderWithoutExtension(String localPath,
  1324. String mimeType) {
  1325. return localPath.startsWith(UriUtils.URI_CONTENT_SCHEME) &&
  1326. mimeType.equals(MIME_TYPE_PDF) &&
  1327. !localPath.endsWith(FILE_EXTENSION_PDF);
  1328. }
  1329. /**
  1330. * Remove uploads of an account
  1331. *
  1332. * @param account Downloads account to remove
  1333. */
  1334. private void cancelUploadsForAccount(Account account){
  1335. // Cancel pending uploads
  1336. mPendingUploads.remove(account);
  1337. }
  1338. // TODO: Remove
  1339. // /**
  1340. // * Remove uploads of an account
  1341. // * @param accountName Name of an OC account
  1342. // */
  1343. // private void cancelUploadForAccount(String accountName){
  1344. // // this can be slow if there are many uploads :(
  1345. // Iterator<String> it = mPendingUploads.keySet().iterator();
  1346. // Log_OC.d(TAG, "Number of pending updloads= " + mPendingUploads.size());
  1347. // while (it.hasNext()) {
  1348. // String key = it.next();
  1349. // Log_OC.d(TAG, "mPendingUploads CANCELLED " + key);
  1350. // if (key.startsWith(accountName)) {
  1351. // synchronized (mPendingUploads) {
  1352. // mPendingUploads.remove(key);
  1353. // }
  1354. // }
  1355. // }
  1356. // }
  1357. // TODO: onHandleIntent not used in the new FileUploadService
  1358. // TODO: Remove when clean code
  1359. /**
  1360. * The IntentService calls this method from the default worker thread with
  1361. * the intent that started the service. When this method returns,
  1362. * IntentService stops the service, as appropriate.
  1363. *
  1364. * Note: We use an IntentService here. It does not provide simultaneous
  1365. * requests, but instead internally queues them and gets them to this
  1366. * onHandleIntent method one after another. This makes implementation less
  1367. * error-prone but prevents files to be added to list while another upload
  1368. * is active. If everything else works fine, fixing this should be a TODO.
  1369. *
  1370. * Entry point to add one or several files to the queue of uploads.
  1371. *
  1372. * New uploads are added calling to startService(), resulting in a call to
  1373. * this method. This ensures the service will keep on working although the
  1374. * caller activity goes away.
  1375. *
  1376. * First, onHandleIntent() stores all information associated with the upload
  1377. * in a {@link OCUpload} which is stored persistently using
  1378. * {@link UploadsStorageManager}. Then, the oldest, pending upload from
  1379. * {@link UploadsStorageManager} is taken and upload is started.
  1380. * @param intentStartId
  1381. */
  1382. //
  1383. // protected void onHandleIntent(Intent intent, int intentStartId) {
  1384. // Log_OC.d(TAG, "onHandleIntent start");
  1385. // //Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - before adding new uploads.");
  1386. // Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.toString() + " - before adding new uploads.");
  1387. // if (intent == null || intent.hasExtra(KEY_RETRY)) {
  1388. // Log_OC.d(TAG, "Received null intent.");
  1389. // // service was restarted by OS or connectivity change was detected or
  1390. // // retry of pending upload was requested.
  1391. // // ==> First check persistent uploads, then perform upload.
  1392. // int countAddedEntries = 0;
  1393. // OCUpload[] list = mUploadsStorageManager.getPendingUploads();
  1394. // for (OCUpload OCUpload : list) {
  1395. // Log_OC.d(TAG, "Retrieved from DB: " + OCUpload.toFormattedString());
  1396. //
  1397. // String uploadKey = buildRemoteName(OCUpload);
  1398. // OCUpload previous = mPendingUploads.putIfAbsent(uploadKey, OCUpload);
  1399. // if(previous == null) {
  1400. // Log_OC.d(TAG, "mPendingUploads added: " + OCUpload.toFormattedString());
  1401. // countAddedEntries++;
  1402. // } else {
  1403. // //already pending. ignore.
  1404. // }
  1405. // }
  1406. // Log_OC.d(TAG, "added " + countAddedEntries
  1407. // + " entrie(s) to mPendingUploads (this should be 0 except for the first time).");
  1408. // // null intent is received when charging or wifi state changes.
  1409. // // fake a mUploadsStorageManager change event, so that GUI can update the reason for
  1410. // // LATER status of uploads.
  1411. // mUploadsStorageManager.notifyObserversNow();
  1412. // } else {
  1413. // Log_OC.d(TAG, "Receive upload intent.");
  1414. // UploadQuantity uploadType = (UploadQuantity) intent.getSerializableExtra(KEY_UPLOAD_TYPE);
  1415. // if (uploadType == null) {
  1416. // Log_OC.e(TAG, "Incorrect or no upload type provided");
  1417. // return;
  1418. // }
  1419. //
  1420. // Account account = intent.getParcelableExtra(KEY_ACCOUNT);
  1421. // if (!AccountUtils.exists(account, getApplicationContext())) {
  1422. // Log_OC.e(TAG, "KEY_ACCOUNT no set or provided KEY_ACCOUNT does not exist");
  1423. // return;
  1424. // }
  1425. // mStorageManager = new FileDataStorageManager(account, getContentResolver());
  1426. //
  1427. // OCFile[] files = null;
  1428. // // if KEY_FILE given, use it
  1429. // if (intent.hasExtra(KEY_FILE)) {
  1430. // if (uploadType == UploadQuantity.UPLOAD_SINGLE_FILE) {
  1431. // files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };
  1432. // } else {
  1433. // files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE);
  1434. // }
  1435. //
  1436. // } else { // else use KEY_LOCAL_FILE and KEY_REMOTE_FILE
  1437. //
  1438. // if (!intent.hasExtra(KEY_LOCAL_FILE) || !intent.hasExtra(KEY_REMOTE_FILE)) {
  1439. // Log_OC.e(TAG, "Not enough information provided in intent");
  1440. // return;
  1441. // }
  1442. //
  1443. // String[] localPaths;
  1444. // String[] remotePaths;
  1445. // String[] mimeTypes;
  1446. // if (uploadType == UploadQuantity.UPLOAD_SINGLE_FILE) {
  1447. // localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
  1448. // remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
  1449. // mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
  1450. // } else {
  1451. // localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
  1452. // remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
  1453. // mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
  1454. // }
  1455. // if (localPaths.length != remotePaths.length) {
  1456. // Log_OC.e(TAG, "Different number of remote paths and local paths!");
  1457. // return;
  1458. // }
  1459. //
  1460. // files = new OCFile[localPaths.length];
  1461. //
  1462. // for (int i = 0; i < localPaths.length; i++) {
  1463. // files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i],
  1464. // ((mimeTypes != null) ? mimeTypes[i] : (String) null));
  1465. // if (files[i] == null) {
  1466. // Log_OC.e(TAG, "obtainNewOCFileToUpload() returned null for remotePaths[i]:" + remotePaths[i]
  1467. // + " and localPaths[i]:" + localPaths[i]);
  1468. // return;
  1469. // }
  1470. // mStorageManager.saveFile(files[i]);
  1471. // files[i] = mStorageManager.getFileByLocalPath(files[i].getStoragePath());
  1472. // }
  1473. // }
  1474. //
  1475. // // at this point variable "OCFile[] files" is loaded correctly.
  1476. //
  1477. // boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
  1478. // boolean isCreateRemoteFolder = intent.getBooleanExtra(KEY_CREATE_REMOTE_FOLDER, false);
  1479. // boolean isUseWifiOnly = intent.getBooleanExtra(KEY_WIFI_ONLY, true);
  1480. // boolean isWhileChargingOnly = intent.getBooleanExtra(KEY_WHILE_CHARGING_ONLY, false);
  1481. // long uploadTimestamp = intent.getLongExtra(KEY_UPLOAD_TIMESTAMP, -1);
  1482. //
  1483. // LocalBehaviour localAction = (LocalBehaviour) intent.getSerializableExtra(KEY_LOCAL_BEHAVIOUR);
  1484. // if (localAction == null)
  1485. // localAction = LocalBehaviour.LOCAL_BEHAVIOUR_COPY;
  1486. //
  1487. // // save always persistently path of upload, so it can be retried if
  1488. // // failed.
  1489. // for (int i = 0; i < files.length; i++) {
  1490. // OCUpload upload = new OCUpload(files[i]);
  1491. // upload.setAccountName(account.name);
  1492. // upload.setForceOverwrite(forceOverwrite);
  1493. // upload.setCreateRemoteFolder(isCreateRemoteFolder);
  1494. // upload.setLocalAction(localAction);
  1495. // upload.setUseWifiOnly(isUseWifiOnly);
  1496. // upload.setWhileChargingOnly(isWhileChargingOnly);
  1497. // upload.setUploadTimestamp(uploadTimestamp);
  1498. // upload.setUploadStatus(UploadStatus.UPLOAD_LATER);
  1499. //
  1500. // String uploadKey = buildRemoteName(upload);
  1501. // OCUpload previous = mPendingUploads.putIfAbsent(uploadKey, upload);
  1502. //
  1503. // if(previous == null)
  1504. // {
  1505. // Log_OC.d(TAG, "mPendingUploads added: " + upload.toFormattedString());
  1506. //
  1507. // // if upload was not queued before, we can add it to
  1508. // // database because the user wants the file to be uploaded.
  1509. // // however, it can happened that the user uploaded the same
  1510. // // file before in which case there is an old db entry.
  1511. // // delete that to be sure we have the latest one.
  1512. // if(mUploadsStorageManager.removeUpload(upload.getLocalPath())>0) {
  1513. // Log_OC.w(TAG, "There was an old DB entry " + upload.getLocalPath()
  1514. // + " which had to be removed in order to add new one.");
  1515. // }
  1516. // boolean success = mUploadsStorageManager.storeUpload(upload);
  1517. // if(!success) {
  1518. // Log_OC.e(TAG, "Could not add upload " + upload.getLocalPath()
  1519. // + " to database. This should not happen.");
  1520. // }
  1521. // } else {
  1522. // Log_OC.w(TAG, "FileUploadService got upload intent for file which is already queued: "
  1523. // + upload.getRemotePath());
  1524. // // upload already pending. ignore.
  1525. // }
  1526. // }
  1527. // }
  1528. // // at this point mPendingUploads is filled.
  1529. //
  1530. //
  1531. //
  1532. // Iterator<String> it;
  1533. // if (intent != null && intent.getStringExtra(KEY_RETRY_REMOTE_PATH) != null) {
  1534. // ArrayList<String> list = new ArrayList<String>(1);
  1535. // String remotePath = intent.getStringExtra(KEY_RETRY_REMOTE_PATH);
  1536. // list.add(remotePath);
  1537. // it = list.iterator();
  1538. // // update db status for upload
  1539. // OCUpload OCUpload = mPendingUploads.get(remotePath);
  1540. // OCUpload.setUploadStatus(UploadStatus.UPLOAD_LATER);
  1541. // OCUpload.setLastResult(null);
  1542. // mUploadsStorageManager.updateUploadStatus(OCUpload);
  1543. //
  1544. // Log_OC.d(TAG, "Start uploading " + remotePath);
  1545. // } else {
  1546. // it = mPendingUploads.keySet().iterator();
  1547. // }
  1548. // if (it.hasNext()) {
  1549. // while (it.hasNext()) {
  1550. // String upload = it.next();
  1551. // OCUpload OCUpload = mPendingUploads.get(upload);
  1552. //
  1553. // if (OCUpload == null) {
  1554. // Log_OC.e(TAG, "Cannot upload null. Fix that!");
  1555. // continue;
  1556. // }
  1557. //
  1558. // UploadTask uploadTask = new UploadTask(OCUpload);
  1559. // mUploadExecutor.submit(uploadTask);
  1560. // }
  1561. // StopSelfTask stopSelfTask = new StopSelfTask(intentStartId);
  1562. // mUploadExecutor.submit(stopSelfTask);
  1563. //
  1564. // } else {
  1565. // stopSelf(intentStartId);
  1566. // }
  1567. //
  1568. // Log_OC.d(TAG, "onHandleIntent end");
  1569. // }
  1570. // TODO: StopSelfTask not used in the new FileUploadService
  1571. // TODO: Remove when clean code
  1572. /**
  1573. * Stops this services if latest intent id is intentStartId.
  1574. */
  1575. // public class StopSelfTask implements Runnable {
  1576. // int intentStartId;
  1577. //
  1578. // public StopSelfTask(int intentStartId) {
  1579. // this.intentStartId = intentStartId;
  1580. // }
  1581. //
  1582. // @Override
  1583. // public void run() {
  1584. // stopSelf(intentStartId);
  1585. // }
  1586. // }
  1587. // TODO: UploaTask not used in the new FileUploadService
  1588. // TODO: Remove when clean code
  1589. /**
  1590. * Tries uploading OCUpload, creates notifications, and updates mUploadsStorageManager.
  1591. */
  1592. // public class UploadTask implements Runnable {
  1593. // OCUpload OCUpload;
  1594. //
  1595. // public UploadTask(OCUpload OCUpload) {
  1596. // this.OCUpload = OCUpload;
  1597. // }
  1598. //
  1599. // @Override
  1600. // public void run() {
  1601. // Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - before uploading.");
  1602. // switch (canUploadFileNow(OCUpload)) {
  1603. // case NOW:
  1604. // Log_OC.d(TAG, "Calling uploadFile for " + OCUpload.getRemotePath());
  1605. // RemoteOperationResult uploadResult = uploadFile(OCUpload);
  1606. // //TODO store renamed upload path?
  1607. // updateDatabaseUploadResult(uploadResult, mCurrentUpload);
  1608. // notifyUploadResult(uploadResult, mCurrentUpload);
  1609. // sendFinalBroadcast(uploadResult, mCurrentUpload);
  1610. // // TODO: Disable for testing of menu actions in uploads view
  1611. //// if (!shouldRetryFailedUpload(uploadResult)) {
  1612. //// Log_OC.d(TAG, "Upload with result " + uploadResult.getCode() + ": " + uploadResult.getLogMessage()
  1613. //// + " will be abandoned.");
  1614. //// mPendingUploads.remove(buildRemoteName(OCUpload));
  1615. //// }
  1616. // Log_OC.d(TAG, "mCurrentUpload = null");
  1617. // mCurrentUpload = null;
  1618. // break;
  1619. // case LATER:
  1620. // // Schedule retry for later upload. Delay can be due to:
  1621. // // KEY_WIFI_ONLY - done by ConnectivityActionReceiver
  1622. // // KEY_WHILE_CHARGING_ONLY - TODO add PowerConnectionReceiver
  1623. // // KEY_UPLOAD_TIMESTAMP - TODO use AlarmManager to wake up this service
  1624. // break;
  1625. // case FILE_GONE:
  1626. // mUploadsStorageManager.updateUploadStatus(
  1627. // OCUpload.getLocalPath(),
  1628. // UploadStatus.UPLOAD_FAILED_GIVE_UP,
  1629. // com.owncloud.android.db.UploadResult.FILE_ERROR
  1630. // );
  1631. // if (mPendingUploads.remove(OCUpload.getRemotePath()) == null) {
  1632. // Log_OC.w(TAG, "Could remove " + OCUpload.getRemotePath()
  1633. // + " from mPendingUploads because it does not exist.");
  1634. // }
  1635. //
  1636. // break;
  1637. // case ERROR:
  1638. // Log_OC.e(TAG, "canUploadFileNow() returned ERROR. Fix that!");
  1639. // break;
  1640. // }
  1641. // Log_OC.d(TAG, "mPendingUploads size:" + mPendingUploads.size() + " - after uploading.");
  1642. // }
  1643. //
  1644. // }
  1645. /**
  1646. * Returns the reason as String why state of OCUpload is LATER. If
  1647. * upload state != LATER return null.
  1648. */
  1649. static public String getUploadLaterReason(Context context, OCUpload OCUpload) {
  1650. StringBuilder reason = new StringBuilder();
  1651. Date now = new Date();
  1652. if (now.getTime() < OCUpload.getUploadTimestamp()) {
  1653. reason.append("Waiting for " + DisplayUtils.unixTimeToHumanReadable(OCUpload.getUploadTimestamp()));
  1654. }
  1655. if (OCUpload.isUseWifiOnly() && !UploadUtils.isConnectedViaWiFi(context)) {
  1656. if (reason.length() > 0) {
  1657. reason.append(" and wifi connectivity");
  1658. } else {
  1659. reason.append("Waiting for wifi connectivity");
  1660. }
  1661. }
  1662. if (OCUpload.isWhileChargingOnly() && !UploadUtils.isCharging(context)) {
  1663. if (reason.length() > 0) {
  1664. reason.append(" and charging");
  1665. } else {
  1666. reason.append("Waiting for charging");
  1667. }
  1668. }
  1669. reason.append(".");
  1670. if (reason.length() > 1) {
  1671. return reason.toString();
  1672. }
  1673. if (OCUpload.getUploadStatus() == UploadStatus.UPLOAD_LATER) {
  1674. return "Upload is pending and will start shortly.";
  1675. }
  1676. return null;
  1677. }
  1678. enum CanUploadFileNowStatus {NOW, LATER, FILE_GONE, ERROR};
  1679. /**
  1680. * Returns true when the file may be uploaded now. This methods checks all
  1681. * restraints of the passed {@link OCUpload}, these include
  1682. * isUseWifiOnly(), check if local file exists, check if file was already
  1683. * uploaded...
  1684. *
  1685. * If return value is CanUploadFileNowStatus.NOW, uploadFile() may be
  1686. * called.
  1687. *
  1688. * @return CanUploadFileNowStatus.NOW is upload may proceed, <br>
  1689. * CanUploadFileNowStatus.LATER if upload should be performed at a
  1690. * later time, <br>
  1691. * CanUploadFileNowStatus.ERROR if a severe error happened, calling
  1692. * entity should remove upload from queue.
  1693. *
  1694. */
  1695. private CanUploadFileNowStatus canUploadFileNow(OCUpload OCUpload) {
  1696. if (OCUpload.getUploadStatus() == UploadStatus.UPLOAD_SUCCEEDED) {
  1697. Log_OC.w(TAG, "Already succeeded uploadObject was again scheduled for upload. Fix that!");
  1698. return CanUploadFileNowStatus.ERROR;
  1699. }
  1700. if (OCUpload.isUseWifiOnly()
  1701. && !UploadUtils.isConnectedViaWiFi(getApplicationContext())) {
  1702. Log_OC.d(TAG, "Do not start upload because it is wifi-only.");
  1703. return CanUploadFileNowStatus.LATER;
  1704. }
  1705. if(OCUpload.isWhileChargingOnly() && !UploadUtils.isCharging(getApplicationContext())) {
  1706. Log_OC.d(TAG, "Do not start upload because it is while charging only.");
  1707. return CanUploadFileNowStatus.LATER;
  1708. }
  1709. Date now = new Date();
  1710. if (now.getTime() < OCUpload.getUploadTimestamp()) {
  1711. Log_OC.d(
  1712. TAG,
  1713. "Do not start upload because it is schedule for "
  1714. + DisplayUtils.unixTimeToHumanReadable(OCUpload.getUploadTimestamp()));
  1715. return CanUploadFileNowStatus.LATER;
  1716. }
  1717. if (!new File(OCUpload.getLocalPath()).exists()) {
  1718. Log_OC.d(TAG, "Do not start upload because local file does not exist.");
  1719. return CanUploadFileNowStatus.FILE_GONE;
  1720. }
  1721. return CanUploadFileNowStatus.NOW;
  1722. }
  1723. /**
  1724. * Call if all pending uploads are to be retried.
  1725. */
  1726. public static void retry(Context context) {
  1727. retry(context, null);
  1728. }
  1729. /**
  1730. * Call to retry upload identified by remotePath
  1731. */
  1732. private static void retry(Context context, String remotePath) {
  1733. Log_OC.d(TAG, "FileUploadService.retry()");
  1734. Intent i = new Intent(context, FileUploadService.class);
  1735. i.putExtra(FileUploadService.KEY_RETRY, true);
  1736. if(remotePath != null) {
  1737. i.putExtra(FileUploadService.KEY_RETRY_REMOTE_PATH, remotePath);
  1738. }
  1739. context.startService(i);
  1740. }
  1741. }