1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.contacts.vcard;
17 
18 import android.app.Notification;
19 import android.app.NotificationManager;
20 import android.app.Service;
21 import android.content.Intent;
22 import android.media.MediaScannerConnection;
23 import android.media.MediaScannerConnection.MediaScannerConnectionClient;
24 import android.net.Uri;
25 import android.os.Binder;
26 import android.os.IBinder;
27 import android.util.Log;
28 import android.util.SparseArray;
29 
30 import java.util.ArrayList;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Set;
34 import java.util.concurrent.ExecutorService;
35 import java.util.concurrent.Executors;
36 import java.util.concurrent.RejectedExecutionException;
37 
38 /**
39  * The class responsible for handling vCard import/export requests.
40  *
41  * This Service creates one ImportRequest/ExportRequest object (as Runnable) per request and push
42  * it to {@link ExecutorService} with single thread executor. The executor handles each request
43  * one by one, and notifies users when needed.
44  */
45 // TODO: Using IntentService looks simpler than using Service + ServiceConnection though this
46 // works fine enough. Investigate the feasibility.
47 public class VCardService extends Service {
48     private final static String LOG_TAG = "VCardService";
49 
50     /* package */ final static boolean DEBUG = false;
51 
52     /**
53      * Specifies the type of operation. Used when constructing a notification, canceling
54      * some operation, etc.
55      */
56     /* package */ static final int TYPE_IMPORT = 1;
57     /* package */ static final int TYPE_EXPORT = 2;
58 
59     /* package */ static final String CACHE_FILE_PREFIX = "import_tmp_";
60 
61     /* package */ static final String X_VCARD_MIME_TYPE = "text/x-vcard";
62 
63     private class CustomMediaScannerConnectionClient implements MediaScannerConnectionClient {
64         final MediaScannerConnection mConnection;
65         final String mPath;
66 
CustomMediaScannerConnectionClient(String path)67         public CustomMediaScannerConnectionClient(String path) {
68             mConnection = new MediaScannerConnection(VCardService.this, this);
69             mPath = path;
70         }
71 
start()72         public void start() {
73             mConnection.connect();
74         }
75 
76         @Override
onMediaScannerConnected()77         public void onMediaScannerConnected() {
78             if (DEBUG) { Log.d(LOG_TAG, "Connected to MediaScanner. Start scanning."); }
79             mConnection.scanFile(mPath, null);
80         }
81 
82         @Override
onScanCompleted(String path, Uri uri)83         public void onScanCompleted(String path, Uri uri) {
84             if (DEBUG) { Log.d(LOG_TAG, "scan completed: " + path); }
85             mConnection.disconnect();
86             removeConnectionClient(this);
87         }
88     }
89 
90     // Should be single thread, as we don't want to simultaneously handle import and export
91     // requests.
92     private final ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
93 
94     private int mCurrentJobId = 1;
95 
96     // Stores all unfinished import/export jobs which will be executed by mExecutorService.
97     // Key is jobId.
98     private final SparseArray<ProcessorBase> mRunningJobMap = new SparseArray<ProcessorBase>();
99     // Stores ScannerConnectionClient objects until they finish scanning requested files.
100     // Uses List class for simplicity. It's not costly as we won't have multiple objects in
101     // almost all cases.
102     private final List<CustomMediaScannerConnectionClient> mRemainingScannerConnections =
103             new ArrayList<CustomMediaScannerConnectionClient>();
104 
105     private MyBinder mBinder;
106 
107     private String mCallingActivity;
108 
109     // File names currently reserved by some export job.
110     private final Set<String> mReservedDestination = new HashSet<String>();
111     /* ** end of vCard exporter params ** */
112 
113     public class MyBinder extends Binder {
getService()114         public VCardService getService() {
115             return VCardService.this;
116         }
117     }
118 
119    @Override
onCreate()120     public void onCreate() {
121         super.onCreate();
122         mBinder = new MyBinder();
123         if (DEBUG) Log.d(LOG_TAG, "vCard Service is being created.");
124     }
125 
126     @Override
onStartCommand(Intent intent, int flags, int id)127     public int onStartCommand(Intent intent, int flags, int id) {
128         if (intent != null && intent.getExtras() != null) {
129             mCallingActivity = intent.getExtras().getString(
130                     VCardCommonArguments.ARG_CALLING_ACTIVITY);
131         } else {
132             mCallingActivity = null;
133             // The intent will be null if the service is restarted after the app
134             // is killed but the notification may still exist so remove it.
135             NotificationManager nm = getSystemService(NotificationManager.class);
136             nm.cancelAll();
137         }
138         return START_STICKY;
139     }
140 
141     @Override
onBind(Intent intent)142     public IBinder onBind(Intent intent) {
143         return mBinder;
144     }
145 
146     @Override
onDestroy()147     public void onDestroy() {
148         if (DEBUG) Log.d(LOG_TAG, "VCardService is being destroyed.");
149         cancelAllRequestsAndShutdown();
150         clearCache();
151         stopForeground(/* removeNotification */ false);
152         super.onDestroy();
153     }
154 
handleImportRequest(List<ImportRequest> requests, VCardImportExportListener listener)155     public synchronized void handleImportRequest(List<ImportRequest> requests,
156             VCardImportExportListener listener) {
157         if (DEBUG) {
158             final ArrayList<String> uris = new ArrayList<String>();
159             final ArrayList<String> displayNames = new ArrayList<String>();
160             for (ImportRequest request : requests) {
161                 uris.add(request.uri.toString());
162                 displayNames.add(request.displayName);
163             }
164             Log.d(LOG_TAG,
165                     String.format("received multiple import request (uri: %s, displayName: %s)",
166                             uris.toString(), displayNames.toString()));
167         }
168         final int size = requests.size();
169         for (int i = 0; i < size; i++) {
170             ImportRequest request = requests.get(i);
171 
172             if (tryExecute(new ImportProcessor(this, listener, request, mCurrentJobId))) {
173                 if (listener != null) {
174                     final Notification notification =
175                             listener.onImportProcessed(request, mCurrentJobId, i);
176                     if (notification != null) {
177                         startForeground(mCurrentJobId, notification);
178                     }
179                 }
180                 mCurrentJobId++;
181             } else {
182                 if (listener != null) {
183                     listener.onImportFailed(request);
184                 }
185                 // A rejection means executor doesn't run any more. Exit.
186                 break;
187             }
188         }
189     }
190 
handleExportRequest(ExportRequest request, VCardImportExportListener listener)191     public synchronized void handleExportRequest(ExportRequest request,
192             VCardImportExportListener listener) {
193         if (tryExecute(new ExportProcessor(this, request, mCurrentJobId, mCallingActivity))) {
194             final String path = request.destUri.getEncodedPath();
195             if (DEBUG) Log.d(LOG_TAG, "Reserve the path " + path);
196             if (!mReservedDestination.add(path)) {
197                 Log.w(LOG_TAG,
198                         String.format("The path %s is already reserved. Reject export request",
199                                 path));
200                 if (listener != null) {
201                     listener.onExportFailed(request);
202                 }
203                 return;
204             }
205 
206             if (listener != null) {
207                 final Notification notification = listener.onExportProcessed(request,mCurrentJobId);
208                 if (notification != null) {
209                     startForeground(mCurrentJobId, notification);
210                 }
211             }
212             mCurrentJobId++;
213         } else {
214             if (listener != null) {
215                 listener.onExportFailed(request);
216             }
217         }
218     }
219 
220     /**
221      * Tries to call {@link ExecutorService#execute(Runnable)} toward a given processor.
222      * @return true when successful.
223      */
tryExecute(ProcessorBase processor)224     private synchronized boolean tryExecute(ProcessorBase processor) {
225         try {
226             if (DEBUG) {
227                 Log.d(LOG_TAG, "Executor service status: shutdown: " + mExecutorService.isShutdown()
228                         + ", terminated: " + mExecutorService.isTerminated());
229             }
230             mExecutorService.execute(processor);
231             mRunningJobMap.put(mCurrentJobId, processor);
232             return true;
233         } catch (RejectedExecutionException e) {
234             Log.w(LOG_TAG, "Failed to excetute a job.", e);
235             return false;
236         }
237     }
238 
handleCancelRequest(CancelRequest request, VCardImportExportListener listener)239     public synchronized void handleCancelRequest(CancelRequest request,
240             VCardImportExportListener listener) {
241         final int jobId = request.jobId;
242         if (DEBUG) Log.d(LOG_TAG, String.format("Received cancel request. (id: %d)", jobId));
243 
244         final ProcessorBase processor = mRunningJobMap.get(jobId);
245         mRunningJobMap.remove(jobId);
246 
247         if (processor != null) {
248             processor.cancel(true);
249             final int type = processor.getType();
250             if (listener != null) {
251                 listener.onCancelRequest(request, type);
252             }
253             if (type == TYPE_EXPORT) {
254                 final String path =
255                         ((ExportProcessor)processor).getRequest().destUri.getEncodedPath();
256                 Log.i(LOG_TAG,
257                         String.format("Cancel reservation for the path %s if appropriate", path));
258                 if (!mReservedDestination.remove(path)) {
259                     Log.w(LOG_TAG, "Not reserved.");
260                 }
261             }
262         } else {
263             // In case notification of import is still present and app is killed remove it
264             NotificationManager nm = getSystemService(NotificationManager.class);
265             nm.cancel(NotificationImportExportListener.DEFAULT_NOTIFICATION_TAG, jobId);
266             Log.w(LOG_TAG, String.format("Tried to remove unknown job (id: %d)", jobId));
267         }
268         stopServiceIfAppropriate();
269     }
270 
271     /**
272      * Checks job list and call {@link #stopSelf()} when there's no job and no scanner connection
273      * is remaining.
274      * A new job (import/export) cannot be submitted any more after this call.
275      */
stopServiceIfAppropriate()276     private synchronized void stopServiceIfAppropriate() {
277         if (mRunningJobMap.size() > 0) {
278             final int size = mRunningJobMap.size();
279 
280             // Check if there are processors which aren't finished yet. If we still have ones to
281             // process, we cannot stop the service yet. Also clean up already finished processors
282             // here.
283 
284             // Job-ids to be removed. At first all elements in the array are invalid and will
285             // be filled with real job-ids from the array's top. When we find a not-yet-finished
286             // processor, then we start removing those finished jobs. In that case latter half of
287             // this array will be invalid.
288             final int[] toBeRemoved = new int[size];
289             for (int i = 0; i < size; i++) {
290                 final int jobId = mRunningJobMap.keyAt(i);
291                 final ProcessorBase processor = mRunningJobMap.valueAt(i);
292                 if (!processor.isDone()) {
293                     Log.i(LOG_TAG, String.format("Found unfinished job (id: %d)", jobId));
294 
295                     // Remove processors which are already "done", all of which should be before
296                     // processors which aren't done yet.
297                     for (int j = 0; j < i; j++) {
298                         mRunningJobMap.remove(toBeRemoved[j]);
299                     }
300                     return;
301                 }
302 
303                 // Remember the finished processor.
304                 toBeRemoved[i] = jobId;
305             }
306 
307             // We're sure we can remove all. Instead of removing one by one, just call clear().
308             mRunningJobMap.clear();
309         }
310 
311         if (!mRemainingScannerConnections.isEmpty()) {
312             Log.i(LOG_TAG, "MediaScanner update is in progress.");
313             return;
314         }
315 
316         Log.i(LOG_TAG, "No unfinished job. Stop this service.");
317         mExecutorService.shutdown();
318         stopSelf();
319     }
320 
updateMediaScanner(String path)321     /* package */ synchronized void updateMediaScanner(String path) {
322         if (DEBUG) {
323             Log.d(LOG_TAG, "MediaScanner is being updated: " + path);
324         }
325 
326         if (mExecutorService.isShutdown()) {
327             Log.w(LOG_TAG, "MediaScanner update is requested after executor's being shut down. " +
328                     "Ignoring the update request");
329             return;
330         }
331         final CustomMediaScannerConnectionClient client =
332                 new CustomMediaScannerConnectionClient(path);
333         mRemainingScannerConnections.add(client);
334         client.start();
335     }
336 
removeConnectionClient( CustomMediaScannerConnectionClient client)337     private synchronized void removeConnectionClient(
338             CustomMediaScannerConnectionClient client) {
339         if (DEBUG) {
340             Log.d(LOG_TAG, "Removing custom MediaScannerConnectionClient.");
341         }
342         mRemainingScannerConnections.remove(client);
343         stopServiceIfAppropriate();
344     }
345 
handleFinishImportNotification( int jobId, boolean successful)346     /* package */ synchronized void handleFinishImportNotification(
347             int jobId, boolean successful) {
348         if (DEBUG) {
349             Log.d(LOG_TAG, String.format("Received vCard import finish notification (id: %d). "
350                     + "Result: %b", jobId, (successful ? "success" : "failure")));
351         }
352         mRunningJobMap.remove(jobId);
353         stopServiceIfAppropriate();
354     }
355 
handleFinishExportNotification( int jobId, boolean successful)356     /* package */ synchronized void handleFinishExportNotification(
357             int jobId, boolean successful) {
358         if (DEBUG) {
359             Log.d(LOG_TAG, String.format("Received vCard export finish notification (id: %d). "
360                     + "Result: %b", jobId, (successful ? "success" : "failure")));
361         }
362         final ProcessorBase job = mRunningJobMap.get(jobId);
363         mRunningJobMap.remove(jobId);
364         if (job == null) {
365             Log.w(LOG_TAG, String.format("Tried to remove unknown job (id: %d)", jobId));
366         } else if (!(job instanceof ExportProcessor)) {
367             Log.w(LOG_TAG,
368                     String.format("Removed job (id: %s) isn't ExportProcessor", jobId));
369         } else {
370             final String path = ((ExportProcessor)job).getRequest().destUri.getEncodedPath();
371             if (DEBUG) Log.d(LOG_TAG, "Remove reserved path " + path);
372             mReservedDestination.remove(path);
373         }
374 
375         stopServiceIfAppropriate();
376     }
377 
378     /**
379      * Cancels all the import/export requests and calls {@link ExecutorService#shutdown()}, which
380      * means this Service becomes no longer ready for import/export requests.
381      *
382      * Mainly called from onDestroy().
383      */
cancelAllRequestsAndShutdown()384     private synchronized void cancelAllRequestsAndShutdown() {
385         for (int i = 0; i < mRunningJobMap.size(); i++) {
386             mRunningJobMap.valueAt(i).cancel(true);
387         }
388         mRunningJobMap.clear();
389         mExecutorService.shutdown();
390     }
391 
392     /**
393      * Removes import caches stored locally.
394      */
clearCache()395     private void clearCache() {
396         for (final String fileName : fileList()) {
397             if (fileName.startsWith(CACHE_FILE_PREFIX)) {
398                 // We don't want to keep all the caches so we remove cache files old enough.
399                 Log.i(LOG_TAG, "Remove a temporary file: " + fileName);
400                 deleteFile(fileName);
401             }
402         }
403     }
404 }
405