Search in sources :

Example 1 with ExpansionIndexItem

use of scal.io.liger.model.sqlbrite.ExpansionIndexItem in project storymaker by StoryMaker.

the class StorymakerDownloadHelper method checkAndDownload.

public static boolean checkAndDownload(Context context, AvailableIndexItemDao availableDao, InstalledIndexItemDao installedDao, QueueItemDao queueDao) {
    boolean expansionFilesOk = true;
    boolean contentPacksOk = true;
    // just call new method
    expansionFilesOk = checkAndDownloadNew(context);
    HashMap<String, ExpansionIndexItem> installedIndex = StorymakerIndexManager.loadInstalledIdIndex(context, installedDao);
    HashMap<String, ExpansionIndexItem> availableIndex = StorymakerIndexManager.loadAvailableIdIndex(context, availableDao);
    HashMap<String, ExpansionIndexItem> updatedIndex = new HashMap<String, ExpansionIndexItem>();
    ExpansionIndexItem tempIndexItem = null;
    boolean updateFlag = false;
    // loop through installed items to see if we need to update any of them
    for (String id : installedIndex.keySet()) {
        ExpansionIndexItem installedItem = installedIndex.get(id);
        ExpansionIndexItem availableItem = availableIndex.get(id);
        // if availableItem is null, this was likely removed from the available index and we should purge it from the installed and remove the obb file
        if (availableItem == null) {
            Timber.d("item removed from availabe index. deleting obb file and removing from isntalled index");
            updateFlag = true;
            String absPath = StorymakerIndexManager.buildFileAbsolutePath(installedItem, scal.io.liger.Constants.MAIN, context);
            new File(absPath).delete();
            absPath = StorymakerIndexManager.buildFileAbsolutePath(installedItem, scal.io.liger.Constants.PATCH, context);
            File file = new File(absPath);
            if (file.exists()) {
                file.delete();
            }
        } else {
            // DO STUFF
            tempIndexItem = updateItem(context, installedItem, availableItem);
            if (tempIndexItem == null) {
                // if (checkAndDownload(context, installedItem, installedDao, queueDao, false).size() > 0) {
                //     contentPacksOk = false;
                // }
                updatedIndex.put(installedItem.getExpansionId(), installedItem);
            } else {
                // if (checkAndDownload(context, tempIndexItem, installedDao, queueDao, false).size() > 0) {
                //     contentPacksOk = false;
                // }
                updatedIndex.put(tempIndexItem.getExpansionId(), tempIndexItem);
                updateFlag = true;
            }
        }
    }
    if (updateFlag) {
        // persist updated index
        StorymakerIndexManager.saveInstalledIndex(context, updatedIndex, installedDao);
        // need a better solution
        try {
            synchronized (waitObj) {
                Timber.d("PERSISTING INDEX WITH UPDATED VALUES");
                // FIXME holy race condition, batman
                waitObj.wait(1000);
            }
        } catch (InterruptedException e) {
        // nop
        }
    }
    if (expansionFilesOk && contentPacksOk) {
        // everything is fine
        return true;
    } else {
        // something is being downloaded
        return false;
    }
}
Also used : HashMap(java.util.HashMap) ExpansionIndexItem(scal.io.liger.model.sqlbrite.ExpansionIndexItem) File(java.io.File)

Example 2 with ExpansionIndexItem

use of scal.io.liger.model.sqlbrite.ExpansionIndexItem in project storymaker by StoryMaker.

the class InstanceIndexItemAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Context context = holder.card.getContext();
    final BaseIndexItem baseItem = mDataset.get(position);
    String description = baseItem.getDescription();
    if (baseItem instanceof InstanceIndexItem) {
        final InstanceIndexItem instanceItem = (InstanceIndexItem) baseItem;
        holder.title.setText(String.format("%s %s", !TextUtils.isEmpty(instanceItem.getTitle()) ? instanceItem.getTitle() : context.getString(R.string.no_title), instanceItem.getStoryCreationDate() == 0 ? "" : sdf.format(new Date(instanceItem.getStoryCreationDate()))));
        int mediumStringResId;
        String storyType = TextUtils.isEmpty(instanceItem.getStoryType()) ? "?" : instanceItem.getStoryType();
        switch(storyType) {
            case "video":
                mediumStringResId = R.string.lbl_video;
                break;
            case "audio":
                mediumStringResId = R.string.lbl_audio;
                break;
            case "photo":
                mediumStringResId = R.string.lbl_photo;
                break;
            default:
                mediumStringResId = R.string.no_medium;
                break;
        }
        description = context.getString(mediumStringResId) + ". " + context.getString(org.storymaker.app.R.string.last_modified) + ": ";
        if (!TextUtils.isEmpty(instanceItem.getInstanceFilePath())) {
            description += sdf.format(new Date(new File(instanceItem.getInstanceFilePath()).lastModified()));
        }
        /*
            holder.card.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onStorySelected(instanceItem);
                    }
                }
            });
            */
        String thumbnailPath = baseItem.getThumbnailPath();
        if (!TextUtils.isEmpty(thumbnailPath)) {
            if (thumbnailPath.startsWith("http")) {
                Picasso.with(context).load(thumbnailPath).into(holder.thumb);
            } else {
                Picasso.with(context).load(// FIXME leaving for now, but doesnt picasso handle making teh File object iteself?
                new File(thumbnailPath)).into(holder.thumb);
            }
        } else {
            Picasso.with(context).load(R.drawable.no_thumbnail).into(holder.thumb);
        }
    } else {
        ExpansionIndexItem expansionIndexItem = (ExpansionIndexItem) baseItem;
        // check if this is already installed or waiting to be downloaded to change which picture we show
        HashMap<String, ExpansionIndexItem> installedIds = StorymakerIndexManager.loadInstalledIdIndex(context, installedDao);
        holder.title.setText(baseItem.getTitle());
        // show the content pack version info for help debugging upgrade issues
        if (BuildConfig.DEBUG) {
            int patchVer = !TextUtils.isEmpty(expansionIndexItem.getPatchFileVersion()) ? Integer.parseInt(expansionIndexItem.getPatchFileVersion()) : 0;
            String ver = expansionIndexItem.getExpansionFileVersion() + ((patchVer > 0) ? ("." + patchVer) : "");
            description = "v" + ver + ": " + description;
        }
        // need to verify that content pack containing thumbnail actually exists
        File contentCheck = new File(StorymakerIndexManager.buildFilePath(expansionIndexItem, context), StorymakerIndexManager.buildFileName(expansionIndexItem, Constants.MAIN));
        // need to verify that index item has been updated with content pack thumbnail path
        String contentPath = expansionIndexItem.getPackageName() + File.separator + expansionIndexItem.getExpansionId();
        if (installedIds.containsKey(expansionIndexItem.getExpansionId()) && contentCheck.exists() && baseItem.getThumbnailPath().startsWith(contentPath)) {
            //              ZipHelper.getTempFile((baseItem.getThumbnailPath(), "/sdcard/"
            holder.thumb.setImageBitmap(BitmapFactory.decodeStream(ZipHelper.getFileInputStream(baseItem.getThumbnailPath(), context)));
        } else {
            String thumbnailPath = baseItem.getThumbnailPath();
            if (!TextUtils.isEmpty(thumbnailPath)) {
                if (thumbnailPath.startsWith("http")) {
                    Picasso.with(context).load(thumbnailPath).into(holder.thumb);
                } else {
                    File file = StorymakerIndexManager.copyThumbnail(context, expansionIndexItem.getThumbnailPath());
                    Picasso.with(context).load(file).into(holder.thumb);
                }
            } else {
                Picasso.with(context).load(R.drawable.no_thumbnail).into(holder.thumb);
            }
        // FIXME desaturate image and overlay the downarrow
        }
    }
    holder.card.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mListener != null) {
                mListener.onStorySelected(baseItem);
            }
        }
    });
    holder.card.setOnLongClickListener(new DeleteListener(context, baseItem));
    holder.description.setText(description);
}
Also used : Context(android.content.Context) ExpansionIndexItem(scal.io.liger.model.sqlbrite.ExpansionIndexItem) BaseIndexItem(scal.io.liger.model.sqlbrite.BaseIndexItem) ImageView(android.widget.ImageView) View(android.view.View) CardView(android.support.v7.widget.CardView) RecyclerView(android.support.v7.widget.RecyclerView) TextView(android.widget.TextView) InstanceIndexItem(scal.io.liger.model.sqlbrite.InstanceIndexItem) Date(java.util.Date) File(java.io.File)

Example 3 with ExpansionIndexItem

use of scal.io.liger.model.sqlbrite.ExpansionIndexItem in project storymaker by StoryMaker.

the class StorymakerDownloadHelper method getDownloadProgress.

public static float getDownloadProgress(Context context, String fileName, InstalledIndexItemDao installedDao) {
    //Timber.d("CHECKING PROGRESS FOR " + fileName);
    long totalExpectedSize = 0;
    long totalCurrentSize = 0;
    boolean sizeUndefined = false;
    // omitting main and patch files for now
    // also currently omitting .part files...
    HashMap<String, ExpansionIndexItem> contentPacksMap = StorymakerIndexManager.loadInstalledFileIndex(context, installedDao);
    ExpansionIndexItem contentPack = contentPacksMap.get(fileName);
    if (contentPack != null) {
        File contentPackFile = null;
        if (fileName.contains(scal.io.liger.Constants.MAIN)) {
            contentPackFile = new File(StorymakerIndexManager.buildFileAbsolutePath(contentPack, scal.io.liger.Constants.MAIN, context));
        } else if (fileName.contains(scal.io.liger.Constants.PATCH)) {
            contentPackFile = new File(StorymakerIndexManager.buildFileAbsolutePath(contentPack, scal.io.liger.Constants.PATCH, context));
        } else {
            //Timber.e("CAN'T DETERMINE IF " + fileName + " IS A MAIN OR PATCH FILE");
            sizeUndefined = true;
        }
        if ((contentPackFile == null) || (contentPack.getExpansionFileSize() == 0)) {
            // no size defined, can't evaluate
            //Timber.e("NO FILE SIZE FOUND FOR " + fileName);
            sizeUndefined = true;
        } else {
            if (fileName.contains(scal.io.liger.Constants.MAIN)) {
                totalExpectedSize = totalExpectedSize + contentPack.getExpansionFileSize();
            } else if (fileName.contains(scal.io.liger.Constants.PATCH)) {
                totalExpectedSize = totalExpectedSize + contentPack.getPatchFileSize();
            } else {
                //Timber.e("CAN'T DETERMINE IF " + fileName + " IS A MAIN OR PATCH FILE");
                sizeUndefined = true;
            }
            if (!contentPackFile.exists()) {
                // actual file doesn't exist, check for temp file
                File contentPackFileTemp = new File(contentPackFile.getPath() + ".tmp");
                if (!contentPackFileTemp.exists()) {
                // still no file, add nothing to current size
                } else {
                    totalCurrentSize = totalCurrentSize + contentPackFileTemp.length();
                }
                // also check for partial file
                File contentPackFilePart = new File(contentPackFile.getPath() + ".part");
                if (!contentPackFilePart.exists()) {
                // still no file, add nothing to current size
                } else {
                    totalCurrentSize = totalCurrentSize + contentPackFilePart.length();
                }
            } else {
                totalCurrentSize = totalCurrentSize + contentPackFile.length();
            }
        }
    } else {
        // no file information found, can't evaluate
        //Timber.e("NO METADATA FOUND FOR " + fileName);
        sizeUndefined = true;
    }
    if (sizeUndefined) {
        return -1;
    } else if (totalExpectedSize == 0) {
        //Timber.e("TOTAL EXPECTED SIZE IS 0 BYTES (NO CURRENT DOWNLOADS?)");
        return -1;
    } else {
        //Timber.d("CURRENT DOWNLOAD PROGRESS: " + totalCurrentSize + " BYTES OUT OF " + totalExpectedSize + " BYTES");
        return (float) totalCurrentSize / (float) totalExpectedSize;
    }
}
Also used : ExpansionIndexItem(scal.io.liger.model.sqlbrite.ExpansionIndexItem) File(java.io.File)

Example 4 with ExpansionIndexItem

use of scal.io.liger.model.sqlbrite.ExpansionIndexItem in project storymaker by StoryMaker.

the class BaseHomeActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // copy index file
    // TODO: REPLACE THIS WITH INDEX DOWNLOAD (IF LOGGED IN) <- NEED TO COPY FILE FOR BASELINE CONTENT
    StorymakerIndexManager.copyAvailableIndex(this, false);
    // initialize db
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    // version check (sqlite upgrade requires migration)
    int appMigrationVersion = preferences.getInt("APP_MIGRATION_VERSION", 0);
    Timber.d("MIGRATION CHECK: " + appMigrationVersion + " vs. " + Constants.APP_MIGRATION_VERSION);
    if (appMigrationVersion != Constants.APP_MIGRATION_VERSION) {
        Timber.d("MIGRATION REQUIRED, RE-ENCRYPTING DATABASE");
        final boolean[] dbStatus = { false };
        try {
            SQLiteDatabaseHook dbHook = new SQLiteDatabaseHook() {

                public void preKey(SQLiteDatabase database) {
                }

                public void postKey(SQLiteDatabase database) {
                    Cursor cursor = database.rawQuery("PRAGMA cipher_migrate", new String[] {});
                    String value = "";
                    if (cursor != null) {
                        cursor.moveToFirst();
                        value = cursor.getString(0);
                        cursor.close();
                    }
                    // this result is currently ignored, checking if db is null instead
                    dbStatus[0] = Integer.valueOf(value) == 0;
                }
            };
            File dbPath = getDatabasePath("sm.db");
            Timber.d("MIGRATING DATABASE AT " + dbPath.getPath());
            SQLiteDatabase sqldb = SQLiteDatabase.openOrCreateDatabase(dbPath, "foo", null, dbHook);
            if (sqldb != null) {
                Timber.d("MIGRATED DATABASE NOT NULL");
                sqldb.close();
                // update preferences if migration succeeded
                preferences.edit().putInt("APP_MIGRATION_VERSION", Constants.APP_MIGRATION_VERSION).commit();
            } else {
                Timber.e("MIGRATED DATABASE IS NULL");
            }
        } catch (Exception ex) {
            Timber.e("EXCEPTION WHILE MIGRATING DATABASE: " + ex.getMessage());
        }
    }
    int availableIndexVersion = preferences.getInt("AVAILABLE_INDEX_VERSION", 0);
    Timber.d("VERSION CHECK: " + availableIndexVersion + " vs. " + scal.io.liger.Constants.AVAILABLE_INDEX_VERSION);
    if (availableIndexVersion != scal.io.liger.Constants.AVAILABLE_INDEX_VERSION) {
        // load db from file
        HashMap<String, scal.io.liger.model.ExpansionIndexItem> availableItemsFromFile = scal.io.liger.IndexManager.loadAvailableIdIndex(this);
        if (availableItemsFromFile.size() == 0) {
            Timber.d("NOTHING LOADED FROM AVAILABLE FILE");
        } else {
            for (scal.io.liger.model.ExpansionIndexItem item : availableItemsFromFile.values()) {
                Timber.d("ADDING " + item.getExpansionId() + " TO DATABASE (AVAILABLE)");
                // replaces existing items, should trigger updates to installed items and table as needed
                availableIndexItemDao.addAvailableIndexItem(item, true);
                // ugly solution to deal with the fact that the popup menu assumes there will be threads for an item we tried to download/install
                ArrayList<Thread> noThreads = new ArrayList<Thread>();
                downloadThreads.put(item.getExpansionId(), noThreads);
            }
        }
        // the following migration stuff is currently piggy-backing on the index update stuff
        // if found, migrate installed index
        File installedFile = new File(StorageHelper.getActualStorageDirectory(this), "installed_index.json");
        if (installedFile.exists()) {
            HashMap<String, scal.io.liger.model.ExpansionIndexItem> installedItemsFromFile = scal.io.liger.IndexManager.loadInstalledIdIndex(this);
            if (installedItemsFromFile.size() == 0) {
                Timber.d("NOTHING LOADED FROM INSTALLED INDEX FILE");
            } else {
                for (scal.io.liger.model.ExpansionIndexItem item : installedItemsFromFile.values()) {
                    Timber.d("ADDING " + item.getExpansionId() + " TO DATABASE (INSTALLED)");
                    // replaces existing items, should trigger updates to installed items and table as needed
                    installedIndexItemDao.addInstalledIndexItem(item, true);
                }
            }
            installedFile.delete();
        } else {
            Timber.d("NO INSTALLED INDEX FILE");
        }
        // if found, migrate instance index
        File instanceFile = new File(StorageHelper.getActualStorageDirectory(this), "instance_index.json");
        if (instanceFile.exists()) {
            HashMap<String, scal.io.liger.model.InstanceIndexItem> instanceItemsFromFile = scal.io.liger.IndexManager.loadInstanceIndex(this);
            if (instanceItemsFromFile.size() == 0) {
                Timber.d("NOTHING LOADED FROM INSTANCE INDEX FILE");
            } else {
                for (scal.io.liger.model.InstanceIndexItem item : instanceItemsFromFile.values()) {
                    Timber.d("ADDING " + item.getInstanceFilePath() + " TO DATABASE (INSTANCE)");
                    // replaces existing items, should trigger updates to installed items and table as needed
                    instanceIndexItemDao.addInstanceIndexItem(item, true);
                }
            }
            instanceFile.delete();
        } else {
            Timber.d("NO INSTANCE INDEX FILE");
        }
        // update preferences
        preferences.edit().putInt("AVAILABLE_INDEX_VERSION", scal.io.liger.Constants.AVAILABLE_INDEX_VERSION).commit();
        if (getIntent() != null && getIntent().hasExtra("showlauncher")) {
            if (getIntent().getBooleanExtra("showlauncher", false)) {
                showLauncherIcon();
            }
        }
    }
    // dumb test
    // check values
    availableIndexItemDao.getAvailableIndexItems().take(1).subscribe(new Action1<List<AvailableIndexItem>>() {

        @Override
        public void call(List<AvailableIndexItem> expansionIndexItems) {
            for (ExpansionIndexItem item : expansionIndexItems) {
                Timber.d("AVAILABLE ITEM " + item.getExpansionId() + ", TITLE: " + item.getTitle());
            }
        }
    });
    installedIndexItemDao.getInstalledIndexItems().take(1).subscribe(new Action1<List<InstalledIndexItem>>() {

        @Override
        public void call(List<InstalledIndexItem> expansionIndexItems) {
            for (ExpansionIndexItem item : expansionIndexItems) {
                Timber.d("INSTALLED ITEM " + item.getExpansionId() + ", TITLE: " + item.getTitle());
            }
        }
    });
    // file cleanup
    File actualStorageDirectory = StorageHelper.getActualStorageDirectory(this);
    if (actualStorageDirectory != null) {
        JsonHelper.cleanup(actualStorageDirectory.getPath());
    } else {
    // this is an error, will deal with it below
    }
    // default
    loggedIn = false;
    if (actualStorageDirectory != null) {
        // NEW/TEMP
        // DOWNLOAD AVAILABE INDEX FOR CURRENT USER AND SAVE TO TARGET FILE
        // NEED TO ACCOUNT FOR POSSIBLE MISSING INDEX
        // force download at startup (maybe only force on a timetable?)
        IndexTask iTask = new IndexTask(this, true);
        iTask.execute();
    } else {
        //show storage error message
        new AlertDialog.Builder(this).setTitle(Utils.getAppName(this)).setIcon(android.R.drawable.ic_dialog_info).setMessage(R.string.err_storage_not_available).show();
    }
    // we want to grab required updates without restarting the app
    // integrate with index task
    // if (!DownloadHelper.checkAndDownload(this)) {
    //     Toast.makeText(this, "Downloading content and/or updating installed files", Toast.LENGTH_LONG).show(); // FIXME move to strings.xml
    // }
    // i don't think we ever want to do this
    // IndexManager.copyInstalledIndex(this);
    //setContentView(R.layout.activity_home);
    //mRecyclerView = (RecyclerView) findViewById(scal.io.liger.R.id.recyclerView);
    //mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    //mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    //mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    //    @Override
    //    public void onRefresh() {
    //        IndexTask iTask = new IndexTask(HomeActivity.this, true); // force download on manual refresh
    //        iTask.execute();
    //    }
    //});
    //mTabMenu = getMenu("home");
    // action bar stuff
    getActionBar().setDisplayHomeAsUpEnabled(true);
    checkForTor();
    checkForUpdates();
}
Also used : ArrayList(java.util.ArrayList) ExpansionIndexItem(scal.io.liger.model.sqlbrite.ExpansionIndexItem) InstalledIndexItem(scal.io.liger.model.sqlbrite.InstalledIndexItem) Cursor(net.sqlcipher.Cursor) InstanceIndexItem(scal.io.liger.model.sqlbrite.InstanceIndexItem) AvailableIndexItem(scal.io.liger.model.sqlbrite.AvailableIndexItem) List(java.util.List) ArrayList(java.util.ArrayList) SharedPreferences(android.content.SharedPreferences) IOException(java.io.IOException) SQLiteDatabase(net.sqlcipher.database.SQLiteDatabase) File(java.io.File) SQLiteDatabaseHook(net.sqlcipher.database.SQLiteDatabaseHook)

Example 5 with ExpansionIndexItem

use of scal.io.liger.model.sqlbrite.ExpansionIndexItem in project storymaker by StoryMaker.

the class HomeActivity method initActivityList.

public void initActivityList() {
    // menu items now locked during downloads, i think this can be removed
    /*
        if (!DownloadHelper.checkAllFiles(this)) { // FIXME the app should define these, not the library
            Toast.makeText(this, "Please wait for the content pack to finish downloading and reload the app", Toast.LENGTH_LONG).show(); // FIXME move to strings.xml
            return;
        }
        */
    JsonHelper.setupFileStructure(this);
    // NEW: load instance index
    String lang = StoryMakerApp.getCurrentLocale().getLanguage();
    Timber.d("lang returned from getCurrentLocale: " + lang);
    HashMap<String, InstanceIndexItem> instanceIndex = StorymakerIndexManager.fillInstanceIndex(HomeActivity.this, StorymakerIndexManager.loadInstanceIndex(HomeActivity.this, instanceIndexItemDao), lang, instanceIndexItemDao);
    boolean fileAddedFlag = StorymakerIndexManager.fillInstalledIndex(HomeActivity.this, StorymakerIndexManager.loadInstalledFileIndex(HomeActivity.this, installedIndexItemDao), StorymakerIndexManager.loadAvailableFileIndex(HomeActivity.this, availableIndexItemDao), lang, installedIndexItemDao);
    if (fileAddedFlag) {
        Timber.d("HomeActivity", "file added");
    }
    // FIXME --- this should only happen on app updates in a migration
    if (instanceIndex.size() > 0) {
        Timber.d("INITACTIVITYLIST - FOUND INSTANCE INDEX WITH " + instanceIndex.size() + " ITEMS");
    // dumb test
    // put in values
    /*
            for (InstanceIndexItem item : instanceIndex.values()) {
                instanceIndexItemDao.addInstanceIndexItem(item);
            }

            // read out values
            instanceIndexItemDao.getInstanceIndexItems().subscribe(new Action1<List<org.storymaker.app.db.InstanceIndexItem>>() {

                @Override
                public void call(List<org.storymaker.app.db.InstanceIndexItem> instanceIndexItems) {

                    // just process the list

                    for (org.storymaker.app.db.InstanceIndexItem item : instanceIndexItems) {
                        Timber.d("GOT ITEM " + item.getId() + ", TITLE: " + item.getTitle());
                    }
                }
            });
            */
    } else {
        Timber.d("INITACTIVITYLIST - FOUND INSTANCE INDEX WITH NO ITEMS");
    }
    ArrayList<BaseIndexItem> instances = new ArrayList<BaseIndexItem>(instanceIndex.values());
    ArrayList<BaseIndexItem> installations = new ArrayList<BaseIndexItem>();
    ArrayList<BaseIndexItem> guides = new ArrayList<BaseIndexItem>();
    ArrayList<BaseIndexItem> lessons = new ArrayList<BaseIndexItem>();
    ArrayList<BaseIndexItem> templates = new ArrayList<BaseIndexItem>();
    ArrayList<BaseIndexItem> homeitems = new ArrayList<BaseIndexItem>();
    //HashMap<String, ExpansionIndexItem> availableIds = StorymakerIndexManager.loadAvailableIdIndex(this, availableIndexItemDao);
    //ArrayList<String> availableGuideIds = getIndexItemIdsByType(availableIndexItemDao, "guide");
    //ArrayList<String> availableLessonIds = getIndexItemIdsByType(availableIndexItemDao, "lesson");
    //ArrayList<String> availableTemplateIds = getIndexItemIdsByType(availableIndexItemDao, "template");
    //HashMap<String, ExpansionIndexItem> installedIds = StorymakerIndexManager.loadInstalledIdIndex(this, installedIndexItemDao);
    //ArrayList<String> installedIdList = StorymakerIndexManager.loadInstalledIdIndexList(this, installedIndexItemDao);
    StorymakerIndexManager.IndexKeyMap installedIndexKeyMap = StorymakerIndexManager.loadInstalledIdIndexKeyMap(this, installedIndexItemDao);
    HashMap<String, scal.io.liger.model.sqlbrite.ExpansionIndexItem> installedIds = installedIndexKeyMap.getIndexMap();
    ArrayList<String> installedKeys = installedIndexKeyMap.getIndexKeys();
    ArrayList<String> installedGuideIds = getIndexItemIdsByType(installedIds, "guide");
    ArrayList<String> installedLessonIds = getIndexItemIdsByType(installedIds, "lesson");
    ArrayList<String> installedTemplateIds = getIndexItemIdsByType(installedIds, "template");
    for (String id : installedKeys) {
        // we don't want to populate the home screen with anything that hasn't finished downloading
        InstalledIndexItem checkItem = (InstalledIndexItem) installedIds.get(id);
        if (checkItem.isInstalled()) {
            // if the available item has been installed, add the corresponding item from the installed index
            installations.add(installedIds.get(id));
            if (installedGuideIds.contains(id)) {
                guides.add(checkItem);
            } else if (installedLessonIds.contains(id)) {
                lessons.add(checkItem);
            } else if (installedTemplateIds.contains(id)) {
                templates.add(checkItem);
            }
        } else {
            Timber.d("HomeActivity - " + checkItem.getExpansionId() + " has not finished downloading, it will be skipped");
        }
    }
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(instances, Collections.reverseOrder());
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(lessons, Collections.reverseOrder());
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(guides, Collections.reverseOrder());
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(templates, Collections.reverseOrder());
    // FIXME we should sort this down a layer, perhaps in loadInstanceIndexAsList
    Collections.sort(installations, Collections.reverseOrder());
    mHomeTabInstanceCount = 0;
    mHomeTabInstallationCount = 0;
    for (int i = 0; i < instances.size(); i++) {
        //System.out.println(list.get(i));
        homeitems.add(instances.get(i));
        mHomeTabInstanceCount++;
        if (i == 1) {
            break;
        }
    }
    if (installations.size() > 0) {
        homeitems.add(installations.get(0));
        mHomeTabInstallationCount++;
    }
    //mRecyclerView.setAdapter(new InstanceIndexItemAdapter(instances, new InstanceIndexItemAdapter.BaseIndexItemSelectedListener() {
    InstanceIndexItemAdapter.BaseIndexItemSelectedListener myBaseIndexItemSelectedListener = new InstanceIndexItemAdapter.BaseIndexItemSelectedListener() {

        @Override
        public void onStorySelected(BaseIndexItem selectedItem) {
            if (selectedItem instanceof InstanceIndexItem) {
                updateInstanceIndexItemLastOpenedDate((InstanceIndexItem) selectedItem);
                launchLiger(HomeActivity.this, null, ((InstanceIndexItem) selectedItem).getInstanceFilePath(), null);
            } else {
                // get clicked item
                final ExpansionIndexItem eItem = ((ExpansionIndexItem) selectedItem);
                Timber.d("HomeActivity - clicked an item: " + eItem.getExpansionId());
                // get installed items
                final HashMap<String, ExpansionIndexItem> installedIds = StorymakerIndexManager.loadInstalledIdIndex(HomeActivity.this, installedIndexItemDao);
                if (!installedIds.containsKey(eItem.getExpansionId())) {
                    // this state should be unreachable, not sure what to do here
                    Timber.e("HomeActivity - " + eItem.getExpansionId() + " was not found in the installed index, something went wrong");
                } else {
                    // proceed as usual
                    Timber.d("HomeActivity - handle click for item: " + eItem.getExpansionId());
                    handleClick(eItem, installedIds, true);
                }
            }
        }
    };
    myHomeItemsInstanceIndexItemAdapter = new InstanceIndexItemAdapter(homeitems, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    myInstancesInstanceIndexItemAdapter = new InstanceIndexItemAdapter(instances, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    myGuidesInstanceIndexItemAdapter = new InstanceIndexItemAdapter(guides, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    myLessonsInstanceIndexItemAdapter = new InstanceIndexItemAdapter(lessons, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    myTemplatesInstanceIndexItemAdapter = new InstanceIndexItemAdapter(templates, myBaseIndexItemSelectedListener, installedIndexItemDao, instanceIndexItemDao);
    ArrayList<InstanceIndexItemAdapter> myInstanceIndexItemAdapters = new ArrayList<InstanceIndexItemAdapter>();
    myInstanceIndexItemAdapters.add(myHomeItemsInstanceIndexItemAdapter);
    myInstanceIndexItemAdapters.add(myInstancesInstanceIndexItemAdapter);
    myInstanceIndexItemAdapters.add(myGuidesInstanceIndexItemAdapter);
    myInstanceIndexItemAdapters.add(myLessonsInstanceIndexItemAdapter);
    myInstanceIndexItemAdapters.add(myTemplatesInstanceIndexItemAdapter);
    ArrayList<Integer> myListLengths = new ArrayList<Integer>();
    myListLengths.add(homeitems.size());
    myListLengths.add(instances.size());
    myListLengths.add(guides.size());
    myListLengths.add(lessons.size());
    myListLengths.add(templates.size());
    ArrayList<String> myListNames = new ArrayList<String>();
    myListNames.add("home");
    myListNames.add("stories");
    myListNames.add("guides");
    myListNames.add("lessons");
    myListNames.add("templates");
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager(), myInstanceIndexItemAdapters, myListLengths, myListNames, mHomeTabInstanceCount, mHomeTabInstallationCount);
    // Set up the ViewPager with the sections adapter.
    //mViewPager = (SwipelessViewPager) findViewById(R.id.pager);
    mViewPager = (ViewPager) findViewById(R.id.home_pager);
    mViewPager.setAdapter(mDemoCollectionPagerAdapter);
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            currentPage = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
    });
    //mViewPager.setPagingEnabled(false);
    // Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
    // it's PagerAdapter set.
    mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.home_sliding_tabs);
    mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.white));
    //mSlidingTabLayout.setDistributeEvenly(true);
    mSlidingTabLayout.setViewPager(mViewPager);
    if (currentPage != -1) {
        mViewPager.setCurrentItem(currentPage);
    }
//} else {
// empty list
//    TextView textView = (TextView) findViewById(R.id.textViewEmptyState);
//    textView.setVisibility(View.VISIBLE);
//mSwipeRefreshLayout.setVisibility(View.GONE);
//}
}
Also used : ArrayList(java.util.ArrayList) ExpansionIndexItem(scal.io.liger.model.sqlbrite.ExpansionIndexItem) InstalledIndexItem(scal.io.liger.model.sqlbrite.InstalledIndexItem) BaseIndexItem(scal.io.liger.model.sqlbrite.BaseIndexItem) InstanceIndexItem(scal.io.liger.model.sqlbrite.InstanceIndexItem) StorymakerIndexManager(scal.io.liger.StorymakerIndexManager) ViewPager(android.support.v4.view.ViewPager)

Aggregations

ExpansionIndexItem (scal.io.liger.model.sqlbrite.ExpansionIndexItem)6 File (java.io.File)4 InstanceIndexItem (scal.io.liger.model.sqlbrite.InstanceIndexItem)3 ArrayList (java.util.ArrayList)2 BaseIndexItem (scal.io.liger.model.sqlbrite.BaseIndexItem)2 InstalledIndexItem (scal.io.liger.model.sqlbrite.InstalledIndexItem)2 Context (android.content.Context)1 SharedPreferences (android.content.SharedPreferences)1 ViewPager (android.support.v4.view.ViewPager)1 CardView (android.support.v7.widget.CardView)1 RecyclerView (android.support.v7.widget.RecyclerView)1 View (android.view.View)1 ImageView (android.widget.ImageView)1 TextView (android.widget.TextView)1 IOException (java.io.IOException)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Cursor (net.sqlcipher.Cursor)1 SQLiteDatabase (net.sqlcipher.database.SQLiteDatabase)1