FileUploadService.java 84 KB

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