PicasaSource.java 17.9 KB
Newer Older
Chris Wren's avatar
Chris Wren committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.dreams.phototable;

import android.content.Context;
19
import android.content.SharedPreferences;
Chris Wren's avatar
Chris Wren committed
20
import android.database.Cursor;
Chris Wren's avatar
Chris Wren committed
21
import android.net.ConnectivityManager;
Chris Wren's avatar
Chris Wren committed
22
import android.net.Uri;
23
import android.util.DisplayMetrics;
24
import android.util.Log;
25
import android.view.WindowManager;
Chris Wren's avatar
Chris Wren committed
26 27 28

import java.io.FileNotFoundException;
import java.io.InputStream;
29
import java.util.Collection;
30
import java.util.Collections;
31
import java.util.HashMap;
Chris Wren's avatar
Chris Wren committed
32
import java.util.LinkedList;
33
import java.util.Set;
Chris Wren's avatar
Chris Wren committed
34 35

/**
36
 * Loads images from Picasa.
Chris Wren's avatar
Chris Wren committed
37
 */
Chris Wren's avatar
Chris Wren committed
38
public class PicasaSource extends CursorPhotoSource {
Chris Wren's avatar
Chris Wren committed
39 40
    private static final String TAG = "PhotoTable.PicasaSource";

41 42 43 44 45
    private static final String PICASA_AUTHORITY =
            "com.google.android.gallery3d.GooglePhotoProvider";

    private static final String PICASA_PHOTO_PATH = "photos";
    private static final String PICASA_ALBUM_PATH = "albums";
Chris Wren's avatar
Chris Wren committed
46
    private static final String PICASA_USER_PATH = "users";
47

Chris Wren's avatar
Chris Wren committed
48 49 50 51
    private static final String PICASA_ID = "_id";
    private static final String PICASA_URL = "content_url";
    private static final String PICASA_ROTATION = "rotation";
    private static final String PICASA_ALBUM_ID = "album_id";
52 53 54
    private static final String PICASA_TITLE = "title";
    private static final String PICASA_THUMB = "thumbnail_url";
    private static final String PICASA_ALBUM_TYPE = "album_type";
Chris Wren's avatar
Chris Wren committed
55
    private static final String PICASA_ALBUM_USER = "user_id";
56
    private static final String PICASA_ALBUM_UPDATED = "date_updated";
Chris Wren's avatar
Chris Wren committed
57
    private static final String PICASA_ACCOUNT = "account";
Chris Wren's avatar
Chris Wren committed
58 59 60

    private static final String PICASA_URL_KEY = "content_url";
    private static final String PICASA_TYPE_KEY = "type";
61 62 63
    private static final String PICASA_TYPE_FULL_VALUE = "full";
    private static final String PICASA_TYPE_SCREEN_VALUE = "screennail";
    private static final String PICASA_TYPE_IMAGE_VALUE = "image";
Chris Wren's avatar
Chris Wren committed
64 65
    private static final String PICASA_POSTS_TYPE = "Buzz";
    private static final String PICASA_UPLOAD_TYPE = "InstantUpload";
Chris Wren's avatar
Chris Wren committed
66
    private static final String PICASA_UPLOADAUTO_TYPE = "InstantUploadAuto";
Chris Wren's avatar
Chris Wren committed
67

68
    private final int mMaxPostAblums;
Chris Wren's avatar
Chris Wren committed
69 70 71
    private final String mPostsAlbumName;
    private final String mUploadsAlbumName;
    private final String mUnknownAlbumName;
Chris Wren's avatar
Chris Wren committed
72 73 74
    private final LinkedList<ImageData> mRecycleBin;
    private final ConnectivityManager mConnectivityManager;
    private final int mMaxRecycleSize;
Chris Wren's avatar
Chris Wren committed
75

76
    private Set<String> mFoundAlbumIds;
77
    private int mLastPosition;
78
    private int mDisplayLongSide;
79

80 81
    public PicasaSource(Context context, SharedPreferences settings) {
        super(context, settings);
82
        mSourceName = TAG;
83
        mLastPosition = INVALID;
84
        mMaxPostAblums = mResources.getInteger(R.integer.max_post_albums);
Chris Wren's avatar
Chris Wren committed
85 86 87
        mPostsAlbumName = mResources.getString(R.string.posts_album_name, "Posts");
        mUploadsAlbumName = mResources.getString(R.string.uploads_album_name, "Instant Uploads");
        mUnknownAlbumName = mResources.getString(R.string.unknown_album_name, "Unknown");
Chris Wren's avatar
Chris Wren committed
88 89 90 91
        mMaxRecycleSize = mResources.getInteger(R.integer.recycle_image_pool_size);
        mConnectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        mRecycleBin = new LinkedList<ImageData>();
Chris Wren's avatar
Chris Wren committed
92

Chris Wren's avatar
Chris Wren committed
93
        fillQueue();
94 95 96 97 98 99 100 101 102
        mDisplayLongSide = getDisplayLongSide();
    }

    private int getDisplayLongSide() {
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager wm = (WindowManager)
                mContext.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);
        return Math.max(metrics.heightPixels, metrics.widthPixels);
Chris Wren's avatar
Chris Wren committed
103 104
    }

Chris Wren's avatar
Chris Wren committed
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    @Override
    protected void openCursor(ImageData data) {
        log(TAG, "opening single album");

        String[] projection = {PICASA_ID, PICASA_URL, PICASA_ROTATION, PICASA_ALBUM_ID};
        String selection = PICASA_ALBUM_ID + " = '" + data.albumId + "'";

        Uri.Builder picasaUriBuilder = new Uri.Builder()
                .scheme("content")
                .authority(PICASA_AUTHORITY)
                .appendPath(PICASA_PHOTO_PATH);
        data.cursor = mResolver.query(picasaUriBuilder.build(),
                projection, selection, null, null);
    }

    @Override
    protected void findPosition(ImageData data) {
        if (data.position == UNINITIALIZED) {
            if (data.cursor == null) {
                openCursor(data);
            }
            if (data.cursor != null) {
                int idIndex = data.cursor.getColumnIndex(PICASA_ID);
                data.cursor.moveToPosition(-1);
                while (data.position == -1 && data.cursor.moveToNext()) {
                    String id = data.cursor.getString(idIndex);
                    if (id != null && id.equals(data.id)) {
                        data.position = data.cursor.getPosition();
                    }
                }
                if (data.position == -1) {
                    // oops!  The image isn't in this album. How did we get here?
                    data.position = INVALID;
                }
            }
        }
    }

    @Override
    protected ImageData unpackImageData(Cursor cursor, ImageData data) {
        if (data == null) {
            data = new ImageData();
        }
        int idIndex = cursor.getColumnIndex(PICASA_ID);
        int urlIndex = cursor.getColumnIndex(PICASA_URL);
        int bucketIndex = cursor.getColumnIndex(PICASA_ALBUM_ID);

        data.id = cursor.getString(idIndex);
        if (bucketIndex >= 0) {
            data.albumId = cursor.getString(bucketIndex);
        }
        if (urlIndex >= 0) {
            data.url = cursor.getString(urlIndex);
        }
        data.position = UNINITIALIZED;
        data.cursor = null;
        return data;
    }

164 165 166 167
    @Override
    protected Collection<ImageData> findImages(int howMany) {
        log(TAG, "finding images");
        LinkedList<ImageData> foundImages = new LinkedList<ImageData>();
Chris Wren's avatar
Chris Wren committed
168 169 170 171 172 173 174 175 176 177
        if (mConnectivityManager.isActiveNetworkMetered()) {
            howMany = Math.min(howMany, mMaxRecycleSize);
            log(TAG, "METERED: " + howMany);
            if (!mRecycleBin.isEmpty()) {
                foundImages.addAll(mRecycleBin);
                log(TAG, "recycled " + foundImages.size() + " items.");
                return foundImages;
            }
        }

Chris Wren's avatar
Chris Wren committed
178
        String[] projection = {PICASA_ID, PICASA_URL, PICASA_ROTATION, PICASA_ALBUM_ID};
Chris Wren's avatar
Chris Wren committed
179
        LinkedList<String> albumIds = new LinkedList<String>();
180 181
        for (String id : getFoundAlbums()) {
            if (mSettings.isAlbumEnabled(id)) {
182
                String[] parts = id.split(":");
Chris Wren's avatar
Chris Wren committed
183 184 185 186
                if (parts.length > 2) {
                    albumIds.addAll(resolveAlbumIds(id));
                } else {
                    albumIds.add(parts[1]);
187
                }
Chris Wren's avatar
Chris Wren committed
188 189
            }
        }
Chris Wren's avatar
Chris Wren committed
190

191 192 193 194
        if (albumIds.size() > mMaxPostAblums) {
            Collections.shuffle(albumIds);
        }

Chris Wren's avatar
Chris Wren committed
195
        StringBuilder selection = new StringBuilder();
196
        int albumIdx = 0;
Chris Wren's avatar
Chris Wren committed
197
        for (String albumId : albumIds) {
198
            if (albumIdx < mMaxPostAblums) {
199 200 201
                if (selection.length() > 0) {
                    selection.append(" OR ");
                }
Chris Wren's avatar
Chris Wren committed
202
                log(TAG, "adding: " + albumId);
203 204 205
                selection.append(PICASA_ALBUM_ID + " = '" + albumId + "'");
            } else {
                log(TAG, "too many albums, dropping: " + albumId);
206
            }
207
            albumIdx++;
208 209 210 211 212
        }

        if (selection.length() == 0) {
            return foundImages;
        }
Chris Wren's avatar
Chris Wren committed
213

214
        log(TAG, "selection is (" + selection.length() + "): " + selection.toString());
215

Chris Wren's avatar
Chris Wren committed
216 217
        Uri.Builder picasaUriBuilder = new Uri.Builder()
                .scheme("content")
218 219
                .authority(PICASA_AUTHORITY)
                .appendPath(PICASA_PHOTO_PATH);
Chris Wren's avatar
Chris Wren committed
220
        Cursor cursor = mResolver.query(picasaUriBuilder.build(),
221
                projection, selection.toString(), null, null);
Chris Wren's avatar
Chris Wren committed
222
        if (cursor != null) {
223 224
            if (cursor.getCount() > howMany && mLastPosition == INVALID) {
                mLastPosition = pickRandomStart(cursor.getCount(), howMany);
Chris Wren's avatar
Chris Wren committed
225
            }
226 227 228

            log(TAG, "moving to position: " + mLastPosition);
            cursor.moveToPosition(mLastPosition);
Chris Wren's avatar
Chris Wren committed
229 230 231 232

            int idIndex = cursor.getColumnIndex(PICASA_ID);

            if (idIndex < 0) {
233
                log(TAG, "can't find the ID column!");
Chris Wren's avatar
Chris Wren committed
234
            } else {
235
                while (cursor.moveToNext()) {
Chris Wren's avatar
Chris Wren committed
236
                    if (idIndex >= 0) {
Chris Wren's avatar
Chris Wren committed
237
                        ImageData data = unpackImageData(cursor, null);
238
                        foundImages.offer(data);
Chris Wren's avatar
Chris Wren committed
239
                    }
240
                    mLastPosition = cursor.getPosition();
Chris Wren's avatar
Chris Wren committed
241 242
                }
                if (cursor.isAfterLast()) {
243 244 245 246
                    mLastPosition = -1;
                }
                if (cursor.isBeforeFirst()) {
                    mLastPosition = INVALID;
Chris Wren's avatar
Chris Wren committed
247 248 249 250
                }
            }

            cursor.close();
251 252
        } else {
            Log.w(TAG, "received a null cursor in findImages()");
Chris Wren's avatar
Chris Wren committed
253
        }
254 255
        log(TAG, "found " + foundImages.size() + " items.");
        return foundImages;
Chris Wren's avatar
Chris Wren committed
256 257
    }

Chris Wren's avatar
Chris Wren committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    private String resolveAccount(String id) {
        String displayName = "unknown";
        String[] projection = {PICASA_ACCOUNT};
        Uri.Builder picasaUriBuilder = new Uri.Builder()
                .scheme("content")
                .authority(PICASA_AUTHORITY)
                .appendPath(PICASA_USER_PATH)
                .appendPath(id);
        Cursor cursor = mResolver.query(picasaUriBuilder.build(),
                projection, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int accountIndex = cursor.getColumnIndex(PICASA_ACCOUNT);
            if (accountIndex >= 0) {
                displayName = cursor.getString(accountIndex);
            }
            cursor.close();
275 276
        } else {
            Log.w(TAG, "received a null cursor in resolveAccount()");
Chris Wren's avatar
Chris Wren committed
277 278 279 280
        }
        return displayName;
    }

Chris Wren's avatar
Chris Wren committed
281 282 283 284 285 286 287 288 289 290 291
    private Collection<String> resolveAlbumIds(String id) {
        LinkedList<String> albumIds = new LinkedList<String>();
        log(TAG, "resolving " + id);

        String[] parts = id.split(":");
        if (parts.length < 3) {
            return albumIds;
        }

        String[] projection = {PICASA_ID, PICASA_ALBUM_TYPE, PICASA_ALBUM_UPDATED,
                               PICASA_ALBUM_USER};
292
        String order = PICASA_ALBUM_UPDATED + " DESC";
Chris Wren's avatar
Chris Wren committed
293
        String selection = (PICASA_ALBUM_USER + " = '" + parts[2] + "' AND " +
Chris Wren's avatar
Chris Wren committed
294
                            PICASA_ALBUM_TYPE + " = '" + parts[1] + "'");
295 296 297 298 299 300
        Uri.Builder picasaUriBuilder = new Uri.Builder()
                .scheme("content")
                .authority(PICASA_AUTHORITY)
                .appendPath(PICASA_ALBUM_PATH)
                .appendQueryParameter(PICASA_TYPE_KEY, PICASA_TYPE_IMAGE_VALUE);
        Cursor cursor = mResolver.query(picasaUriBuilder.build(),
Chris Wren's avatar
Chris Wren committed
301
                projection, selection, null, order);
302
        if (cursor != null) {
303
            log(TAG, " " + id + " resolved to " + cursor.getCount() + " albums");
304
            cursor.moveToPosition(-1);
305 306 307 308 309 310

            int idIndex = cursor.getColumnIndex(PICASA_ID);

            if (idIndex < 0) {
                log(TAG, "can't find the ID column!");
            } else {
311
                while (cursor.moveToNext()) {
Chris Wren's avatar
Chris Wren committed
312
                    albumIds.add(cursor.getString(idIndex));
313 314 315
                }
            }
            cursor.close();
316 317
        } else {
            Log.w(TAG, "received a null cursor in resolveAlbumIds()");
318
        }
Chris Wren's avatar
Chris Wren committed
319
        return albumIds;
320 321
    }

322 323 324 325 326 327 328
    private Set<String> getFoundAlbums() {
        if (mFoundAlbumIds == null) {
            findAlbums();
        }
        return mFoundAlbumIds;
    }

329 330 331 332
    @Override
    public Collection<AlbumData> findAlbums() {
        log(TAG, "finding albums");
        HashMap<String, AlbumData> foundAlbums = new HashMap<String, AlbumData>();
Chris Wren's avatar
Chris Wren committed
333
        HashMap<String, String> accounts = new HashMap<String, String>();
334
        String[] projection = {PICASA_ID, PICASA_TITLE, PICASA_THUMB, PICASA_ALBUM_TYPE,
Chris Wren's avatar
Chris Wren committed
335
                               PICASA_ALBUM_USER, PICASA_ALBUM_UPDATED};
336 337 338 339 340 341 342 343
        Uri.Builder picasaUriBuilder = new Uri.Builder()
                .scheme("content")
                .authority(PICASA_AUTHORITY)
                .appendPath(PICASA_ALBUM_PATH)
                .appendQueryParameter(PICASA_TYPE_KEY, PICASA_TYPE_IMAGE_VALUE);
        Cursor cursor = mResolver.query(picasaUriBuilder.build(),
                projection, null, null, null);
        if (cursor != null) {
344
            cursor.moveToPosition(-1);
345 346 347 348 349 350

            int idIndex = cursor.getColumnIndex(PICASA_ID);
            int thumbIndex = cursor.getColumnIndex(PICASA_THUMB);
            int titleIndex = cursor.getColumnIndex(PICASA_TITLE);
            int typeIndex = cursor.getColumnIndex(PICASA_ALBUM_TYPE);
            int updatedIndex = cursor.getColumnIndex(PICASA_ALBUM_UPDATED);
Chris Wren's avatar
Chris Wren committed
351
            int userIndex = cursor.getColumnIndex(PICASA_ALBUM_USER);
352 353 354 355

            if (idIndex < 0) {
                log(TAG, "can't find the ID column!");
            } else {
356
                while (cursor.moveToNext()) {
357
                    String id = constructId(cursor.getString(idIndex));
Chris Wren's avatar
Chris Wren committed
358 359 360
                    String user = (userIndex >= 0 ? cursor.getString(userIndex) : "-1");
                    String type = (typeIndex >= 0 ? cursor.getString(typeIndex) : "none");
                    boolean isPosts = (typeIndex >= 0 && PICASA_POSTS_TYPE.equals(type));
Chris Wren's avatar
Chris Wren committed
361 362
                    boolean isUpload = (typeIndex >= 0 &&
                            (PICASA_UPLOAD_TYPE.equals(type) || PICASA_UPLOADAUTO_TYPE.equals(type)));
Chris Wren's avatar
Chris Wren committed
363

Chris Wren's avatar
Chris Wren committed
364 365 366 367 368 369
                    String account = accounts.get(user);
                    if (account == null) {
                        account = resolveAccount(user);
                        accounts.put(user, account);
                    }

Chris Wren's avatar
Chris Wren committed
370
                    if (isPosts) {
371
                        log(TAG, "replacing " + id + " with " + PICASA_POSTS_TYPE);
372
                        id = constructId(PICASA_POSTS_TYPE + ":" + user);
Chris Wren's avatar
Chris Wren committed
373
                    }
374

Chris Wren's avatar
Chris Wren committed
375
                    if (isUpload) {
376
                        log(TAG, "replacing " + id + " with " + PICASA_UPLOAD_TYPE);
377
                        id = constructId(PICASA_UPLOAD_TYPE + ":" + user);
378
                    }
Chris Wren's avatar
Chris Wren committed
379 380 381

                    String thumbnailUrl = null;
                    long updated = 0;
Chris Wren's avatar
Chris Wren committed
382 383 384
                    AlbumData data = foundAlbums.get(id);
                    if (data == null) {
                        data = new AlbumData();
385
                        data.id = id;
Chris Wren's avatar
Chris Wren committed
386
                        data.account = account;
387

Chris Wren's avatar
Chris Wren committed
388
                        if (isPosts) {
Chris Wren's avatar
Chris Wren committed
389
                            data.title = mPostsAlbumName;
Chris Wren's avatar
Chris Wren committed
390
                        } else if (isUpload) {
Chris Wren's avatar
Chris Wren committed
391
                            data.title = mUploadsAlbumName;
392 393 394
                        } else if (titleIndex >= 0) {
                            data.title = cursor.getString(titleIndex);
                        } else {
Chris Wren's avatar
Chris Wren committed
395
                            data.title = mUnknownAlbumName;
396 397
                        }

Chris Wren's avatar
Chris Wren committed
398
                        log(TAG, "found " + data.title + "(" + data.id + ")" +
399
                                " of type " + type + " owned by " + user);
400 401 402
                        foundAlbums.put(id, data);
                    }

Chris Wren's avatar
Chris Wren committed
403
                    if (updatedIndex >= 0) {
404
                        updated = cursor.getLong(updatedIndex);
Chris Wren's avatar
Chris Wren committed
405 406
                    }

407 408 409 410 411 412
                    if (thumbIndex >= 0) {
                        thumbnailUrl = cursor.getString(thumbIndex);
                    }

                    data.updated = (long) Math.max(data.updated, updated);

Chris Wren's avatar
Chris Wren committed
413 414
                    if (data.thumbnailUrl == null || data.updated == updated) {
                        data.thumbnailUrl = thumbnailUrl;
Chris Wren's avatar
Chris Wren committed
415
                    }
416 417 418 419
                }
            }
            cursor.close();

420 421
        } else {
            Log.w(TAG, "received a null cursor in findAlbums()");
422 423
        }
        log(TAG, "found " + foundAlbums.size() + " items.");
424
        mFoundAlbumIds = foundAlbums.keySet();
425 426 427
        return foundAlbums.values();
    }

428 429 430 431
    public static String constructId(String serverId) {
        return  TAG + ":" + serverId;
    }

432
    @Override
433
    protected InputStream getStream(ImageData data, int longSide) {
434 435 436 437
        InputStream is = null;
        try {
            Uri.Builder photoUriBuilder = new Uri.Builder()
                    .scheme("content")
438 439
                    .authority(PICASA_AUTHORITY)
                    .appendPath(PICASA_PHOTO_PATH)
Chris Wren's avatar
Chris Wren committed
440
                    .appendPath(data.id);
441 442
            if (mConnectivityManager.isActiveNetworkMetered() ||
                    ((2 * longSide) <= mDisplayLongSide)) {
Chris Wren's avatar
Chris Wren committed
443 444 445 446
                photoUriBuilder.appendQueryParameter(PICASA_TYPE_KEY, PICASA_TYPE_SCREEN_VALUE);
            } else {
                photoUriBuilder.appendQueryParameter(PICASA_TYPE_KEY, PICASA_TYPE_FULL_VALUE);
            }
447 448
            if (data.url != null) {
                photoUriBuilder.appendQueryParameter(PICASA_URL_KEY, data.url);
Chris Wren's avatar
Chris Wren committed
449
            }
450 451 452 453
            is = mResolver.openInputStream(photoUriBuilder.build());
        } catch (FileNotFoundException fnf) {
            log(TAG, "file not found: " + fnf);
            is = null;
Chris Wren's avatar
Chris Wren committed
454 455
        }

Chris Wren's avatar
Chris Wren committed
456 457 458 459 460 461 462
        if (is != null) {
            mRecycleBin.offer(data);
            log(TAG, "RECYCLED");
            while (mRecycleBin.size() > mMaxRecycleSize) {
                mRecycleBin.poll();
            }
        }
463
        return is;
Chris Wren's avatar
Chris Wren committed
464 465
    }
}