示例#1
0
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // get settings
    getSortAndFilterSettings();

    // prepare view adapter
    int resIdStar =
        Utils.resolveAttributeToResourceId(getSherlockActivity().getTheme(), R.attr.drawableStar);
    int resIdStarZero =
        Utils.resolveAttributeToResourceId(getSherlockActivity().getTheme(), R.attr.drawableStar0);
    mAdapter = new SlowAdapter(getActivity(), null, 0, resIdStar, resIdStarZero, this);

    // setup grid view
    mGrid = (GridView) getView().findViewById(R.id.gridViewShows);
    mGrid.setAdapter(mAdapter);
    mGrid.setOnItemClickListener(this);
    registerForContextMenu(mGrid);

    // start loading data
    getLoaderManager().initLoader(LOADER_ID, null, this);

    // listen for some settings changes
    PreferenceManager.getDefaultSharedPreferences(getActivity())
        .registerOnSharedPreferenceChangeListener(mPrefsListener);

    setHasOptionsMenu(true);
  }
 @Override
 public void onReceive(Context context, Intent intent) {
   if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
     // postpone notification service launch a minute,
     // we don't want to slow down booting
     Timber.d("Postponing notifications service launch");
     Utils.runNotificationServiceDelayed(context);
   } else {
     // run the notification service right away
     Timber.d("Run notifications service right away");
     Utils.runNotificationService(context);
   }
 }
 private void setWatchedToggleState(int unwatchedEpisodes) {
   mWatchedAllEpisodes = unwatchedEpisodes == 0;
   mButtonWatchedAll.setImageResource(
       mWatchedAllEpisodes
           ? Utils.resolveAttributeToResourceId(
               getActivity().getTheme(), R.attr.drawableWatchedAll)
           : Utils.resolveAttributeToResourceId(
               getActivity().getTheme(), R.attr.drawableWatchAll));
   mButtonWatchedAll.setContentDescription(
       getString(mWatchedAllEpisodes ? R.string.unmark_all : R.string.mark_all));
   // set onClick listener not before here to avoid unexpected actions
   mButtonWatchedAll.setOnClickListener(
       new OnClickListener() {
         @Override
         public void onClick(View v) {
           PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
           if (!mWatchedAllEpisodes) {
             popupMenu.getMenu().add(0, CONTEXT_WATCHED_SHOW_ALL_ID, 0, R.string.mark_all);
           }
           popupMenu.getMenu().add(0, CONTEXT_WATCHED_SHOW_NONE_ID, 0, R.string.unmark_all);
           popupMenu.setOnMenuItemClickListener(
               new PopupMenu.OnMenuItemClickListener() {
                 @Override
                 public boolean onMenuItemClick(MenuItem item) {
                   switch (item.getItemId()) {
                     case CONTEXT_WATCHED_SHOW_ALL_ID:
                       {
                         onFlagShowWatched(true);
                         Utils.trackAction(getActivity(), TAG, "Flag all watched (inline)");
                         return true;
                       }
                     case CONTEXT_WATCHED_SHOW_NONE_ID:
                       {
                         onFlagShowWatched(false);
                         Utils.trackAction(getActivity(), TAG, "Flag all unwatched (inline)");
                         return true;
                       }
                   }
                   return false;
                 }
               });
           popupMenu.show();
         }
       });
 }
  private void onSortOrderChanged() {
    getPreferences();

    Utils.trackCustomEvent(getActivity(), TAG, "Sorting", mSorting.name());

    // restart loader and update menu description
    getLoaderManager()
        .restartLoader(OverviewActivity.SEASONS_LOADER_ID, null, SeasonsFragment.this);
    getActivity().invalidateOptionsMenu();
  }
示例#5
0
  @Override
  protected Integer doInBackground(Void... params) {
    if (!Utils.isTraktCredentialsValid(mContext)) {
      return FAILED_CREDENTIALS;
    }

    ServiceManager manager;
    try {
      manager = Utils.getServiceManagerWithAuth(mContext, false);
    } catch (Exception e1) {
      // password could not be decrypted
      return FAILED_CREDENTIALS;
    }

    if (mIsSyncToTrakt) {
      return syncToTrakt(manager);
    } else {
      return syncToSeriesGuide(manager, Utils.getTraktUsername(mContext));
    }
  }
  @Override
  public List<Movie> loadInBackground() {
    ServiceManager manager = ServiceUtils.getTmdbServiceManager(getContext());

    try {
      ResultsPage page;
      if (TextUtils.isEmpty(mQuery)) {
        page = manager.moviesService().nowPlaying().fire();
      } else {
        page = manager.searchService().movieSearch(mQuery).fire();
      }
      if (page != null && page.results != null) {
        return page.results;
      }
    } catch (TmdbException e) {
      Utils.trackException(getContext(), TAG, e);
      Log.w(TAG, e);
    } catch (ApiException e) {
      Utils.trackException(getContext(), TAG, e);
      Log.w(TAG, e);
    }

    return null;
  }
  @Override
  public void onCreate() {
    super.onCreate();

    // set provider authority
    CONTENT_AUTHORITY = getPackageName() + ".provider";

    // initialize settings on first run
    PreferenceManager.setDefaultValues(this, R.xml.settings_basic, false);
    PreferenceManager.setDefaultValues(this, R.xml.settings_advanced, false);

    // ensure the notifications service is started (we also restart it on
    // boot)
    Utils.runNotificationService(this);

    // load the current theme into a global variable
    final String theme =
        PreferenceManager.getDefaultSharedPreferences(this)
            .getString(SeriesGuidePreferences.KEY_THEME, "0");
    Utils.updateTheme(theme);

    // set a context for Google Analytics
    EasyTracker.getInstance().setContext(getApplicationContext());
  }
示例#8
0
  private void onFavoriteShow(String showId, boolean isFavorite) {
    ContentValues values = new ContentValues();
    values.put(Shows.FAVORITE, isFavorite);
    getActivity().getContentResolver().update(Shows.buildShowUri(showId), values, null, null);

    Utils.runNotificationService(getActivity());

    Toast.makeText(
            getActivity(),
            getString(isFavorite ? R.string.favorited : R.string.unfavorited),
            Toast.LENGTH_SHORT)
        .show();

    fireTrackerEventContext(isFavorite ? "Favorite show" : "Unfavorite show");
  }
示例#9
0
  public static String toSHA1(Context context, String message) {
    try {
      MessageDigest md = MessageDigest.getInstance("SHA-1");
      byte[] messageBytes = message.getBytes("UTF-8");
      byte[] digest = md.digest(messageBytes);

      String result = "";
      for (int i = 0; i < digest.length; i++) {
        result += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
      }

      return result;
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
      Utils.trackExceptionAndLog(context, TAG, e);
    }
    return null;
  }
示例#10
0
 private void setCollectedToggleState(int uncollectedEpisodes) {
   mCollectedAllEpisodes = uncollectedEpisodes == 0;
   mButtonCollectedAll.setImageResource(
       mCollectedAllEpisodes
           ? R.drawable.ic_collected
           : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableCollect));
   // set onClick listener not before here to avoid unexpected actions
   mButtonCollectedAll.setOnClickListener(
       new OnClickListener() {
         @Override
         public void onClick(View v) {
           PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
           if (mCollectedAllEpisodes) {
             popupMenu.getMenu().add(0, CONTEXT_COLLECTED_SHOW_NONE_ID, 0, R.string.uncollect_all);
           } else {
             popupMenu.getMenu().add(0, CONTEXT_COLLECTED_SHOW_ALL_ID, 0, R.string.collect_all);
           }
           popupMenu.setOnMenuItemClickListener(
               new PopupMenu.OnMenuItemClickListener() {
                 @Override
                 public boolean onMenuItemClick(MenuItem item) {
                   switch (item.getItemId()) {
                     case CONTEXT_COLLECTED_SHOW_ALL_ID:
                       {
                         onFlagShowCollected(true);
                         fireTrackerEvent("Flag all collected (inline)");
                         return true;
                       }
                     case CONTEXT_COLLECTED_SHOW_NONE_ID:
                       {
                         onFlagShowCollected(false);
                         fireTrackerEvent("Flag all uncollected (inline)");
                         return true;
                       }
                   }
                   return false;
                 }
               });
           popupMenu.show();
         }
       });
   CheatSheet.setup(
       mButtonCollectedAll, mCollectedAllEpisodes ? R.string.uncollect_all : R.string.collect_all);
 }
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
   int itemId = item.getItemId();
   if (itemId == R.id.menu_action_lists_add) {
     AddListDialogFragment.showAddListDialog(getSupportFragmentManager());
     Utils.trackAction(this, TAG, "Add list");
     return true;
   }
   if (itemId == R.id.menu_action_lists_search) {
     startActivity(new Intent(this, SearchActivity.class));
     return true;
   }
   if (itemId == R.id.menu_action_lists_edit) {
     int selectedListIndex = mPager.getCurrentItem();
     showListManageDialog(selectedListIndex);
     return true;
   }
   if (itemId == R.id.menu_action_lists_sort_title) {
     if (ListsDistillationSettings.getSortOrderId(this) == ListsSortOrder.TITLE_ALPHABETICAL_ID) {
       changeSortOrder(ListsSortOrder.TITLE_REVERSE_ALHPABETICAL_ID);
     } else {
       changeSortOrder(ListsSortOrder.TITLE_ALPHABETICAL_ID);
     }
     return true;
   }
   if (itemId == R.id.menu_action_lists_sort_episode) {
     if (ListsDistillationSettings.getSortOrderId(this)
         == ListsSortOrder.NEWEST_EPISODE_FIRST_ID) {
       changeSortOrder(ListsSortOrder.OLDEST_EPISODE_FIRST_ID);
     } else {
       changeSortOrder(ListsSortOrder.NEWEST_EPISODE_FIRST_ID);
     }
     return true;
   }
   if (itemId == R.id.menu_action_lists_sort_ignore_articles) {
     toggleSortIgnoreArticles();
     return true;
   }
   if (itemId == R.id.menu_action_lists_reorder) {
     ListsReorderDialogFragment.show(getSupportFragmentManager());
     return true;
   }
   return super.onOptionsItemSelected(item);
 }
示例#12
0
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      if (!mDataValid) {
        throw new IllegalStateException("this should only be called when the cursor is valid");
      }
      if (!mCursor.moveToPosition(position)) {
        throw new IllegalStateException("couldn't move cursor to position " + position);
      }

      final ViewHolder viewHolder;

      if (convertView == null) {
        convertView = mLayoutInflater.inflate(LAYOUT, null);

        viewHolder = new ViewHolder();
        viewHolder.name = (TextView) convertView.findViewById(R.id.seriesname);
        viewHolder.timeAndNetwork =
            (TextView) convertView.findViewById(R.id.textViewShowsTimeAndNetwork);
        viewHolder.episode = (TextView) convertView.findViewById(R.id.TextViewShowListNextEpisode);
        viewHolder.episodeTime = (TextView) convertView.findViewById(R.id.episodetime);
        viewHolder.poster = (ImageView) convertView.findViewById(R.id.showposter);
        viewHolder.favorited = (ImageView) convertView.findViewById(R.id.favoritedLabel);
        viewHolder.contextMenu =
            (ImageView) convertView.findViewById(R.id.imageViewShowsContextMenu);

        convertView.setTag(viewHolder);
      } else {
        viewHolder = (ViewHolder) convertView.getTag();
      }

      // set text properties immediately
      viewHolder.name.setText(mCursor.getString(ShowsQuery.TITLE));

      // favorite toggle
      final String showId = mCursor.getString(ShowsQuery._ID);
      final boolean isFavorited = mCursor.getInt(ShowsQuery.FAVORITE) == 1;
      viewHolder.favorited.setImageResource(isFavorited ? mStarDrawableId : mStarZeroDrawableId);
      viewHolder.favorited.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              onFavoriteShow(showId, !isFavorited);
            }
          });

      // next episode info
      String fieldValue = mCursor.getString(ShowsQuery.NEXTTEXT);
      if (fieldValue.length() == 0) {
        // show show status if there are currently no more
        // episodes
        int status = mCursor.getInt(ShowsQuery.STATUS);

        // Continuing == 1 and Ended == 0
        if (status == 1) {
          viewHolder.episodeTime.setText(getString(R.string.show_isalive));
        } else if (status == 0) {
          viewHolder.episodeTime.setText(getString(R.string.show_isnotalive));
        } else {
          viewHolder.episodeTime.setText("");
        }
        viewHolder.episode.setText("");
      } else {
        viewHolder.episode.setText(fieldValue);
        fieldValue = mCursor.getString(ShowsQuery.NEXTAIRDATETEXT);
        viewHolder.episodeTime.setText(fieldValue);
      }

      // airday
      final String[] values =
          Utils.parseMillisecondsToTime(
              mCursor.getLong(ShowsQuery.AIRSTIME),
              mCursor.getString(ShowsQuery.AIRSDAYOFWEEK),
              mContext);
      if (getResources().getBoolean(R.bool.isLargeTablet)) {
        // network first, then time, one line
        viewHolder.timeAndNetwork.setText(
            mCursor.getString(ShowsQuery.NETWORK) + " / " + values[1] + " " + values[0]);
      } else {
        // smaller screen, time first, network second line
        viewHolder.timeAndNetwork.setText(
            values[1] + " " + values[0] + "\n" + mCursor.getString(ShowsQuery.NETWORK));
      }

      // set poster
      final String imagePath = mCursor.getString(ShowsQuery.POSTER);
      ImageProvider.getInstance(mContext).loadPosterThumb(viewHolder.poster, imagePath);

      // context menu
      viewHolder.contextMenu.setVisibility(View.VISIBLE);
      viewHolder.contextMenu.setOnClickListener(mOnClickListener);

      return convertView;
    }
  @TargetApi(android.os.Build.VERSION_CODES.KITKAT)
  @Override
  protected void onHandleIntent(Intent intent) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    /*
     * Handle a possible delete intent.
     */
    if (handleDeleteIntent(this, intent)) {
      return;
    }

    /*
     * Unschedule notification service wake-ups for disabled notifications
     * and non-supporters.
     */
    if (!NotificationSettings.isNotificationsEnabled(this) || !Utils.hasAccessToX(this)) {
      // cancel any pending alarm
      AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
      Intent i = new Intent(this, OnAlarmReceiver.class);
      PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
      am.cancel(pi);

      resetLastEpisodeAirtime(prefs);

      return;
    }

    long wakeUpTime = 0;

    /*
     * Get pool of episodes which air from 12 hours ago until eternity which
     * match the users settings.
     */
    StringBuilder selection = new StringBuilder(SELECTION);
    final long fakeNow = Utils.getFakeCurrentTime(prefs);
    boolean isFavsOnly = NotificationSettings.isNotifyAboutFavoritesOnly(this);
    if (isFavsOnly) {
      selection.append(Shows.SELECTION_FAVORITES);
    }
    boolean isNoSpecials = DisplaySettings.isHidingSpecials(this);
    if (isNoSpecials) {
      selection.append(Episodes.SELECTION_NOSPECIALS);
    }
    final Cursor upcomingEpisodes =
        getContentResolver()
            .query(
                Episodes.CONTENT_URI_WITHSHOW,
                PROJECTION,
                selection.toString(),
                new String[] {String.valueOf(fakeNow - 12 * DateUtils.HOUR_IN_MILLIS)},
                SORTING);

    if (upcomingEpisodes != null) {
      int notificationThreshold = NotificationSettings.getLatestToIncludeTreshold(this);
      if (DEBUG) {
        // a week, for debugging (use only one show to get single
        // episode notifications)
        notificationThreshold = 10080;
        // notify again for same episodes
        resetLastEpisodeAirtime(prefs);
      }
      final long latestTimeToInclude = fakeNow + DateUtils.MINUTE_IN_MILLIS * notificationThreshold;
      final long nextTimePlanned = NotificationSettings.getNextToNotifyAbout(this);
      final long nextWakeUpPlanned =
          Utils.convertToFakeTime(nextTimePlanned, prefs, false)
              - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

      /*
       * Set to -1 as on first run nextTimePlanned will be 0. This assures
       * we still see notifications of upcoming episodes then.
       */
      int newEpisodesAvailable = -1;

      // Check if we did wake up earlier than planned
      if (System.currentTimeMillis() < nextWakeUpPlanned) {
        newEpisodesAvailable = 0;
        long latestTimeNotified = NotificationSettings.getLastNotified(this);

        // Check if there are any earlier episodes to notify about
        while (upcomingEpisodes.moveToNext()) {
          final long airtime = upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS);
          if (airtime < nextTimePlanned) {
            if (airtime > latestTimeNotified) {
              /**
               * This will not get new episodes which would have aired the same time as the last one
               * we notified about. Sad, but the best we can do right now.
               */
              newEpisodesAvailable = 1;
              break;
            }
          } else {
            break;
          }
        }
      }

      if (newEpisodesAvailable == 0) {
        // Go to sleep, wake up as planned
        wakeUpTime = nextWakeUpPlanned;
      } else {
        // Get episodes which are within the notification threshold
        // (user set) and not yet cleared
        int count = 0;
        final List<Integer> notifyPositions = Lists.newArrayList();
        final long latestTimeCleared = NotificationSettings.getLastCleared(this);

        upcomingEpisodes.moveToPosition(-1);
        while (upcomingEpisodes.moveToNext()) {
          final long airtime = upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS);
          if (airtime <= latestTimeToInclude) {
            count++;
            /*
             * Only add those after the last one the user cleared.
             * At most those of the last 24 hours (see query above).
             */
            if (airtime > latestTimeCleared) {
              notifyPositions.add(count);
            }
          } else {
            // Too far into the future, stop!
            break;
          }
        }

        // Notify if we found any episodes
        if (notifyPositions.size() > 0) {
          // store latest air time of all episodes we notified about
          upcomingEpisodes.moveToPosition(notifyPositions.get(notifyPositions.size() - 1));
          long latestAirtime = upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS);
          if (!AndroidUtils.isHoneycombOrHigher()) {
            /*
             * Everything below HC does not have delete intents, so
             * we just never notify about the same episode twice.
             */
            prefs.edit().putLong(NotificationSettings.KEY_LAST_CLEARED, latestAirtime).commit();
          }
          prefs.edit().putLong(NotificationSettings.KEY_LAST_NOTIFIED, latestAirtime).commit();

          onNotify(prefs, upcomingEpisodes, count, latestAirtime);
        }

        /*
         * Plan next episode to notify about, calc wake-up alarm as
         * early as user wants.
         */
        upcomingEpisodes.moveToPosition(-1);
        while (upcomingEpisodes.moveToNext()) {
          final long airtime = upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS);
          if (airtime > latestTimeToInclude) {
            // store next episode we plan to notify about
            prefs.edit().putLong(NotificationSettings.KEY_NEXT_TO_NOTIFY, airtime).commit();

            // convert it to actual device time for setting the
            // alarm
            wakeUpTime =
                Utils.convertToFakeTime(airtime, prefs, false)
                    - DateUtils.MINUTE_IN_MILLIS * notificationThreshold;

            break;
          }
        }
      }

      upcomingEpisodes.close();
    }

    // Set a default wake-up time if there are no future episodes for now
    if (wakeUpTime <= 0) {
      wakeUpTime = System.currentTimeMillis() + 6 * DateUtils.HOUR_IN_MILLIS;
    }

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    if (AndroidUtils.isKitKatOrHigher()) {
      am.setExact(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    } else {
      am.set(AlarmManager.RTC_WAKEUP, wakeUpTime, pi);
    }
  }
示例#14
0
 @Override
 protected void fireTrackerEvent(String label) {
   Utils.trackAction(this, TAG, label);
 }
  private void onNotify(
      final SharedPreferences prefs, final Cursor upcomingEpisodes, int count, long latestAirtime) {
    final Context context = getApplicationContext();
    CharSequence tickerText = "";
    CharSequence contentTitle = "";
    CharSequence contentText = "";
    PendingIntent contentIntent = null;

    // notification sound
    final String ringtoneUri = NotificationSettings.getNotificationsRingtone(context);
    // vibration
    final boolean isVibrating = NotificationSettings.isNotificationVibrating(context);

    if (count == 1) {
      // notify in detail about one episode
      upcomingEpisodes.moveToFirst();
      final String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE);
      final String airs =
          Utils.formatToTimeAndDay(upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS), this)[
              0];
      final String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);

      tickerText = getString(R.string.upcoming_show, showTitle);
      contentTitle =
          showTitle
              + " "
              + Utils.getEpisodeNumber(
                  this,
                  upcomingEpisodes.getInt(NotificationQuery.SEASON),
                  upcomingEpisodes.getInt(NotificationQuery.NUMBER));
      contentText = getString(R.string.upcoming_show_detailed, airs, network);

      Intent notificationIntent = new Intent(context, EpisodesActivity.class);
      notificationIntent.putExtra(
          EpisodesActivity.InitBundle.EPISODE_TVDBID,
          upcomingEpisodes.getInt(NotificationQuery._ID));
      notificationIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
      contentIntent =
          PendingIntent.getActivity(context, REQUEST_CODE_SINGLE_EPISODE, notificationIntent, 0);
    } else if (count > 1) {
      // notify about multiple episodes
      tickerText = getString(R.string.upcoming_episodes);
      contentTitle = getString(R.string.upcoming_episodes_number, count);
      contentText = getString(R.string.upcoming_display);

      Intent notificationIntent = new Intent(context, UpcomingRecentActivity.class);
      notificationIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
      contentIntent =
          PendingIntent.getActivity(context, REQUEST_CODE_MULTIPLE_EPISODES, notificationIntent, 0);
    }

    final NotificationCompat.Builder nb = new NotificationCompat.Builder(context);

    if (AndroidUtils.isJellyBeanOrHigher()) {
      // JELLY BEAN and above

      if (count == 1) {
        // single episode
        upcomingEpisodes.moveToFirst();
        final String imagePath = upcomingEpisodes.getString(NotificationQuery.POSTER);
        nb.setLargeIcon(ImageProvider.getInstance(context).getImage(imagePath, true));

        final String episodeTitle = upcomingEpisodes.getString(NotificationQuery.TITLE);
        final String episodeSummary = upcomingEpisodes.getString(NotificationQuery.OVERVIEW);

        final SpannableStringBuilder bigText = new SpannableStringBuilder();
        bigText.append(episodeTitle);
        bigText.setSpan(new ForegroundColorSpan(Color.WHITE), 0, bigText.length(), 0);
        bigText.append("\n");
        bigText.append(episodeSummary);

        nb.setStyle(
            new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(contentText));

        // Action button to check in
        Intent checkInActionIntent = new Intent(context, QuickCheckInActivity.class);
        checkInActionIntent.putExtra(
            QuickCheckInActivity.InitBundle.EPISODE_TVDBID,
            upcomingEpisodes.getInt(NotificationQuery._ID));
        PendingIntent checkInIntent =
            PendingIntent.getActivity(context, REQUEST_CODE_ACTION_CHECKIN, checkInActionIntent, 0);
        nb.addAction(R.drawable.ic_action_checkin, getString(R.string.checkin), checkInIntent);
      } else {
        // multiple episodes
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

        // display at most the first five
        final int displayCount = Math.min(count, 5);
        for (int i = 0; i < displayCount; i++) {
          if (upcomingEpisodes.moveToPosition(i)) {
            // add show title, air time and network
            final SpannableStringBuilder lineText = new SpannableStringBuilder();
            lineText.append(upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE));
            lineText.setSpan(new ForegroundColorSpan(Color.WHITE), 0, lineText.length(), 0);
            lineText.append(" ");
            String airs =
                Utils.formatToTimeAndDay(
                    upcomingEpisodes.getLong(NotificationQuery.FIRSTAIREDMS), this)[0];
            String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
            lineText.append(getString(R.string.upcoming_show_detailed, airs, network));
            inboxStyle.addLine(lineText);
          }
        }

        // tell if we could not display all episodes
        if (count > 5) {
          inboxStyle.setSummaryText(getString(R.string.more, count - 5));
        }

        nb.setStyle(inboxStyle);
        nb.setContentInfo(String.valueOf(count));
      }
    } else {
      // ICS and below

      if (count == 1) {
        // single episode
        upcomingEpisodes.moveToFirst();
        final String posterPath = upcomingEpisodes.getString(NotificationQuery.POSTER);
        nb.setLargeIcon(ImageProvider.getInstance(context).getImage(posterPath, true));
      }
    }

    // If the string is empty, the user chose silent...
    if (ringtoneUri.length() != 0) {
      // ...otherwise set the specified ringtone
      nb.setSound(Uri.parse(ringtoneUri));
    }
    if (isVibrating) {
      nb.setVibrate(VIBRATION_PATTERN);
    }
    nb.setDefaults(Notification.DEFAULT_LIGHTS);
    nb.setWhen(System.currentTimeMillis());
    nb.setAutoCancel(true);
    nb.setTicker(tickerText);
    nb.setContentTitle(contentTitle);
    nb.setContentText(contentText);
    nb.setContentIntent(contentIntent);
    nb.setSmallIcon(R.drawable.ic_notification);
    nb.setPriority(NotificationCompat.PRIORITY_DEFAULT);

    Intent i = new Intent(this, NotificationService.class);
    i.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
    PendingIntent deleteIntent = PendingIntent.getService(this, 1, i, 0);
    nb.setDeleteIntent(deleteIntent);

    // build the notification
    Notification notification = nb.build();

    // use string resource id, always unique within app
    final NotificationManager nm =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(R.string.upcoming_show, notification);
  }
示例#16
0
  @Override
  protected Response doInBackground(Void... params) {
    // we need this value in onPostExecute, so get it already here
    mAction = TraktAction.values()[mArgs.getInt(InitBundle.TRAKTACTION)];

    // check for network connection
    if (!AndroidUtils.isNetworkConnected(mContext)) {
      Response r = new Response();
      r.status = TraktStatus.FAILURE;
      r.error = mContext.getString(R.string.offline);
      return r;
    }

    // check for valid credentials
    if (!ServiceUtils.isTraktCredentialsValid(mContext)) {
      // return null so a credentials dialog is displayed
      // it will call us again with valid credentials
      return null;
    }

    // get an authenticated trakt-java ServiceManager
    ServiceManager manager = ServiceUtils.getTraktServiceManagerWithAuth(mContext, false);
    if (manager == null) {
      // password could not be decrypted
      Response r = new Response();
      r.status = TraktStatus.FAILURE;
      r.error = mContext.getString(R.string.trakt_generalerror);
      return r;
    }

    // get values used by all actions
    final int showTvdbId = mArgs.getInt(InitBundle.SHOW_TVDBID);
    final int season = mArgs.getInt(InitBundle.SEASON);
    final int episode = mArgs.getInt(InitBundle.EPISODE);

    // last chance to abort
    if (isCancelled()) {
      return null;
    }

    try {
      Response r = null;

      switch (mAction) {
        case CHECKIN_EPISODE:
          {
            final String message = mArgs.getString(InitBundle.MESSAGE);

            final CheckinBuilder checkinBuilder =
                manager.showService().checkin(showTvdbId).season(season).episode(episode);
            if (!TextUtils.isEmpty(message)) {
              checkinBuilder.message(message);
            }
            r = checkinBuilder.fire();

            if (TraktStatus.SUCCESS.equals(r.status)) {
              SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
              r.message =
                  mContext.getString(
                      R.string.checkin_success_trakt,
                      (r.show != null ? r.show.title + " " : "")
                          + Utils.getEpisodeNumber(prefs, season, episode));
            }

            break;
          }
        case CHECKIN_MOVIE:
          {
            final String imdbId = mArgs.getString(InitBundle.IMDB_ID);
            final String message = mArgs.getString(InitBundle.MESSAGE);

            final MovieService.CheckinBuilder checkinBuilder =
                manager.movieService().checkin(imdbId);
            if (!TextUtils.isEmpty(message)) {
              checkinBuilder.message(message);
            }
            r = checkinBuilder.fire();

            if (TraktStatus.SUCCESS.equals(r.status)) {
              r.message =
                  mContext.getString(
                      R.string.checkin_success_trakt, (r.movie != null ? r.movie.title + " " : ""));
            }

            break;
          }
        case RATE_EPISODE:
          {
            final Rating rating = Rating.fromValue(mArgs.getString(InitBundle.RATING));
            r =
                manager
                    .rateService()
                    .episode(showTvdbId)
                    .season(season)
                    .episode(episode)
                    .rating(rating)
                    .fire();
            break;
          }
        case RATE_SHOW:
          {
            final Rating rating = Rating.fromValue(mArgs.getString(InitBundle.RATING));
            r = manager.rateService().show(showTvdbId).rating(rating).fire();
            break;
          }
        case SHOUT:
          {
            final String shout = mArgs.getString(InitBundle.MESSAGE);
            final boolean isSpoiler = mArgs.getBoolean(InitBundle.ISSPOILER);

            if (episode == 0) {
              r =
                  manager
                      .commentService()
                      .show(showTvdbId)
                      .comment(shout)
                      .spoiler(isSpoiler)
                      .fire();
            } else {
              r =
                  manager
                      .commentService()
                      .episode(showTvdbId)
                      .season(season)
                      .episode(episode)
                      .comment(shout)
                      .spoiler(isSpoiler)
                      .fire();
            }
            break;
          }
        case WATCHLIST_MOVIE:
          {
            final int tmdbId = mArgs.getInt(InitBundle.TMDB_ID);
            manager.movieService().watchlist().movie(tmdbId).fire();
            // In case of failure this will just return an exception, so
            // we need to construct our own response
            r = new Response();
            r.status = TraktStatus.SUCCESS;
            r.message = mContext.getString(R.string.watchlist_added);
            break;
          }
        case UNWATCHLIST_MOVIE:
          {
            final int tmdbId = mArgs.getInt(InitBundle.TMDB_ID);
            manager.movieService().unwatchlist().movie(tmdbId).fire();
            // In case of failure this will just return an exception, so
            // we need to construct our own response
            r = new Response();
            r.status = TraktStatus.SUCCESS;
            r.message = mContext.getString(R.string.watchlist_removed);
            break;
          }
        default:
          break;
      }

      return r;
    } catch (TraktException e) {
      Utils.trackExceptionAndLog(mContext, TAG, e);
      Response r = new Response();
      r.status = TraktStatus.FAILURE;
      r.error = mContext.getString(R.string.trakt_generalerror);
      return r;
    } catch (ApiException e) {
      Utils.trackExceptionAndLog(mContext, TAG, e);
      Response r = new Response();
      r.status = TraktStatus.FAILURE;
      r.error = mContext.getString(R.string.trakt_generalerror);
      return r;
    }
  }
示例#17
0
  @Override
  protected void log(int priority, String tag, String message, Throwable t) {
    if (priority == Log.ERROR) {
      // remove any stack trace attached by Timber
      if (message != null) {
        int newLine = message.indexOf('\n');
        if (newLine > 0) {
          message = message.substring(0, newLine);
        }
      }

      // special treatment for some exceptions
      if (t instanceof TvdbException) {
        TvdbException e = (TvdbException) t;
        Utils.trackCustomEvent(
            context, CATEGORY_THETVDB_ERROR, tag + ": " + message, e.getMessage());
        return;
      } else if (t instanceof OAuthProblemException) {
        // log trakt OAuth failures
        OAuthProblemException e = (OAuthProblemException) t;
        StringBuilder exceptionMessage = new StringBuilder();
        if (!TextUtils.isEmpty(e.getError())) {
          exceptionMessage.append(e.getError());
        }
        if (!TextUtils.isEmpty(e.getDescription())) {
          exceptionMessage.append(", ").append(e.getDescription());
        }
        if (!TextUtils.isEmpty(e.getUri())) {
          exceptionMessage.append(", ").append(e.getUri());
        }
        Utils.trackCustomEvent(
            context, "OAuth Error", tag + ": " + message, exceptionMessage.toString());
        return;
      } else if (t instanceof OAuthSystemException) {
        // log trakt OAuth failures
        OAuthSystemException e = (OAuthSystemException) t;
        Utils.trackCustomEvent(context, "OAuth Error", tag + ": " + message, e.getMessage());
        return;
      }
    }

    // drop empty messages
    if (message == null) {
      return;
    }
    // drop debug and verbose logs
    if (priority == Log.DEBUG || priority == Log.VERBOSE) {
      return;
    }

    // transform priority into string
    String level = null;
    switch (priority) {
      case Log.INFO:
        level = "INFO";
        break;
      case Log.WARN:
        level = "WARN";
        break;
      case Log.ERROR:
        level = "ERROR";
        break;
    }

    // finally log to crashlytics
    Crashlytics.log(level + "/" + tag + ": " + message);

    // track some non-fatal exceptions with crashlytics
    if (priority == Log.ERROR) {
      if (t instanceof SQLiteException) {
        Crashlytics.logException(t);
      }
    }
  }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
      mShowTvdbId = cursor.getInt(DetailsQuery.REF_SHOW_ID);
      mSeasonNumber = cursor.getInt(DetailsQuery.SEASON);
      mEpisodeNumber = cursor.getInt(DetailsQuery.NUMBER);
      final String showTitle = cursor.getString(DetailsQuery.SHOW_TITLE);
      final String episodeTitle = cursor.getString(DetailsQuery.TITLE);
      final long airTime = cursor.getLong(DetailsQuery.FIRSTAIREDMS);

      // Title and description
      ((TextView) view.findViewById(R.id.title)).setText(cursor.getString(DetailsQuery.TITLE));
      ((TextView) view.findViewById(R.id.description))
          .setText(cursor.getString(DetailsQuery.OVERVIEW));

      // Show title button
      TextView showtitle = (TextView) view.findViewById(R.id.showTitle);
      if (!isShowingShowLink()) {
        showtitle.setVisibility(View.GONE);
      } else {
        showtitle.setVisibility(View.VISIBLE);
        showtitle.setText(showTitle);
        showtitle.setOnClickListener(
            new OnClickListener() {
              public void onClick(View v) {
                Intent upIntent = new Intent(getActivity(), OverviewActivity.class);
                upIntent.putExtra(OverviewFragment.InitBundle.SHOW_TVDBID, mShowTvdbId);
                upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(upIntent);
                getActivity()
                    .overridePendingTransition(
                        R.anim.fragment_slide_right_enter, R.anim.fragment_slide_right_exit);
                getActivity().finish();
              }
            });
      }

      // Show poster background
      if (getArguments().getBoolean("showposter")) {
        final ImageView background =
            (ImageView) getActivity().findViewById(R.id.episodedetails_background);
        Utils.setPosterBackground(
            background, cursor.getString(DetailsQuery.SHOW_POSTER), getActivity());
      }

      SpannableStringBuilder airTimeAndNumberText = new SpannableStringBuilder();
      // Air day and time
      TextView airdateText = (TextView) view.findViewById(R.id.airDay);
      TextView airtimeText = (TextView) view.findViewById(R.id.airTime);
      if (airTime != -1) {
        airdateText.setText(Utils.formatToDate(airTime, getActivity()));
        String[] dayAndTime = Utils.formatToTimeAndDay(airTime, getActivity());
        airTimeAndNumberText
            .append(
                getString(R.string.release_date_and_day, dayAndTime[2], dayAndTime[1])
                    .toUpperCase(Locale.getDefault()))
            .append("  ");
      } else {
        airdateText.setText(R.string.unknown);
      }

      // number
      int numberStartIndex = airTimeAndNumberText.length();
      airTimeAndNumberText.append(
          getString(R.string.season_number, mSeasonNumber).toUpperCase(Locale.getDefault()));
      airTimeAndNumberText.append(" ");
      airTimeAndNumberText.append(
          getString(R.string.episode_number, mEpisodeNumber).toUpperCase(Locale.getDefault()));
      final int episodeAbsoluteNumber = cursor.getInt(DetailsQuery.ABSOLUTE_NUMBER);
      if (episodeAbsoluteNumber > 0 && episodeAbsoluteNumber != mEpisodeNumber) {
        airTimeAndNumberText.append(" (").append(String.valueOf(episodeAbsoluteNumber)).append(")");
      }
      airTimeAndNumberText.setSpan(
          new TextAppearanceSpan(mContext, R.style.TextAppearance_Small_Dim),
          numberStartIndex,
          airTimeAndNumberText.length(),
          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
      airtimeText.setText(airTimeAndNumberText);

      // Last edit date
      TextView lastEdit = (TextView) view.findViewById(R.id.lastEdit);
      long lastEditRaw = cursor.getLong(DetailsQuery.LASTEDIT);
      if (lastEditRaw > 0) {
        lastEdit.setText(
            DateUtils.formatDateTime(
                context,
                lastEditRaw * 1000,
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME));
      } else {
        lastEdit.setText(R.string.unknown);
      }

      // Guest stars
      Utils.setLabelValueOrHide(
          view.findViewById(R.id.labelGuestStars),
          (TextView) view.findViewById(R.id.guestStars),
          Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.GUESTSTARS)));
      // DVD episode number
      Utils.setLabelValueOrHide(
          view.findViewById(R.id.labelDvd),
          (TextView) view.findViewById(R.id.dvdNumber),
          cursor.getDouble(DetailsQuery.DVDNUMBER));
      // Directors
      String directors = Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.DIRECTORS));
      Utils.setValueOrPlaceholder(view.findViewById(R.id.directors), directors);
      // Writers
      String writers = Utils.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.WRITERS));
      Utils.setValueOrPlaceholder(view.findViewById(R.id.writers), writers);

      // Episode image
      FrameLayout imageContainer = (FrameLayout) view.findViewById(R.id.imageContainer);
      final String imagePath = cursor.getString(DetailsQuery.IMAGE);
      onLoadImage(imagePath, imageContainer);
      imageContainer.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              Intent fullscreen = new Intent(getActivity(), FullscreenImageActivity.class);
              fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_PATH, imagePath);
              fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_TITLE, showTitle);
              fullscreen.putExtra(FullscreenImageActivity.InitBundle.IMAGE_SUBTITLE, episodeTitle);
              ActivityCompat.startActivity(
                  getActivity(),
                  fullscreen,
                  ActivityOptionsCompat.makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight())
                      .toBundle());
            }
          });

      mEpisodeFlag = cursor.getInt(DetailsQuery.WATCHED);
      // Watched button
      boolean isWatched = EpisodeTools.isWatched(mEpisodeFlag);
      ImageButton seenButton = (ImageButton) view.findViewById(R.id.imageButtonBarWatched);
      seenButton.setImageResource(
          isWatched
              ? R.drawable.ic_ticked
              : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableWatch));
      seenButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              onToggleWatched();
              fireTrackerEvent("Toggle watched");
            }
          });
      CheatSheet.setup(seenButton, isWatched ? R.string.unmark_episode : R.string.mark_episode);

      // skip button
      boolean isSkipped = EpisodeTools.isSkipped(mEpisodeFlag);
      ImageButton skipButton = (ImageButton) view.findViewById(R.id.imageButtonBarSkip);
      skipButton.setVisibility(
          isWatched ? View.GONE : View.VISIBLE); // if watched do not allow skipping
      skipButton.setImageResource(
          isSkipped
              ? R.drawable.ic_action_playback_next_highlight
              : Utils.resolveAttributeToResourceId(getActivity().getTheme(), R.attr.drawableSkip));
      skipButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              onToggleSkipped();
              fireTrackerEvent("Toggle skipped");
            }
          });
      CheatSheet.setup(skipButton, isSkipped ? R.string.action_dont_skip : R.string.action_skip);

      // Collected button
      mCollected = cursor.getInt(DetailsQuery.COLLECTED) == 1;
      ImageButton collectedButton = (ImageButton) view.findViewById(R.id.imageButtonBarCollected);
      collectedButton.setImageResource(
          mCollected
              ? R.drawable.ic_collected
              : Utils.resolveAttributeToResourceId(
                  getActivity().getTheme(), R.attr.drawableCollect));
      collectedButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              onToggleCollected();
              fireTrackerEvent("Toggle collected");
            }
          });
      CheatSheet.setup(collectedButton, mCollected ? R.string.uncollect : R.string.collect);

      // menu button
      View menuButton = view.findViewById(R.id.imageButtonBarMenu);
      registerForContextMenu(menuButton);
      menuButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              getActivity().openContextMenu(v);
            }
          });

      // TVDb rating
      RelativeLayout ratings = (RelativeLayout) view.findViewById(R.id.ratingbar);
      String ratingText = cursor.getString(DetailsQuery.RATING);
      if (ratingText != null && ratingText.length() != 0) {
        TextView ratingValue = (TextView) ratings.findViewById(R.id.textViewRatingsTvdbValue);
        ratingValue.setText(ratingText);
      }
      ratings.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              onRateOnTrakt();
            }
          });
      ratings.setFocusable(true);
      CheatSheet.setup(ratings, R.string.menu_rate_episode);

      // fetch trakt ratings
      onLoadTraktRatings(ratings, true);

      // Google Play button
      View playButton = view.findViewById(R.id.buttonGooglePlay);
      ServiceUtils.setUpGooglePlayButton(showTitle + " " + episodeTitle, playButton, TAG);

      // Amazon button
      View amazonButton = view.findViewById(R.id.buttonAmazon);
      ServiceUtils.setUpAmazonButton(showTitle + " " + episodeTitle, amazonButton, TAG);

      // YouTube button
      View youtubeButton = view.findViewById(R.id.buttonYouTube);
      ServiceUtils.setUpYouTubeButton(showTitle + " " + episodeTitle, youtubeButton, TAG);

      // IMDb button
      String imdbId = cursor.getString(DetailsQuery.IMDBID);
      if (TextUtils.isEmpty(imdbId)) {
        // fall back to show IMDb id
        imdbId = cursor.getString(DetailsQuery.SHOW_IMDBID);
      }
      ServiceUtils.setUpImdbButton(
          imdbId, view.findViewById(R.id.buttonShowInfoIMDB), TAG, getActivity());

      // TVDb button
      final int seasonTvdbId = cursor.getInt(DetailsQuery.REF_SEASON_ID);
      ServiceUtils.setUpTvdbButton(
          mShowTvdbId, seasonTvdbId, getEpisodeTvdbId(), view.findViewById(R.id.buttonTVDB), TAG);

      // trakt button
      ServiceUtils.setUpTraktButton(
          mShowTvdbId, mSeasonNumber, mEpisodeNumber, view.findViewById(R.id.buttonTrakt), TAG);

      // Web search button
      View webSearch = view.findViewById(R.id.buttonWebSearch);
      ServiceUtils.setUpWebSearchButton(showTitle + " " + episodeTitle, webSearch, TAG);

      // trakt shouts button
      view.findViewById(R.id.buttonShouts)
          .setOnClickListener(
              new OnClickListener() {
                @Override
                public void onClick(View v) {
                  Intent intent = new Intent(getActivity(), TraktShoutsActivity.class);
                  intent.putExtras(
                      TraktShoutsActivity.createInitBundleEpisode(
                          mShowTvdbId, mSeasonNumber, mEpisodeNumber, episodeTitle));
                  startActivity(intent);
                  fireTrackerEvent("Comments");
                }
              });

      // Check in button
      final int episodeTvdbId = cursor.getInt(DetailsQuery._ID);
      View checkinButton = view.findViewById(R.id.imageButtonBarCheckin);
      checkinButton.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              // display a check-in dialog
              CheckInDialogFragment f =
                  CheckInDialogFragment.newInstance(getActivity(), episodeTvdbId);
              f.show(getFragmentManager(), "checkin-dialog");
              fireTrackerEvent("Check-In");
            }
          });
      CheatSheet.setup(checkinButton);
    }
示例#19
0
  @Override
  protected Integer doInBackground(Void... params) {
    // Ensure external storage
    if (!AndroidUtils.isExtStorageAvailable()) {
      return ERROR_STORAGE_ACCESS;
    }

    // Ensure no large database ops are running
    TaskManager tm = TaskManager.getInstance(mContext);
    if (SgSyncAdapter.isSyncActive(mContext, false) || tm.isAddTaskRunning()) {
      return ERROR_LARGE_DB_OP;
    }

    // Ensure JSON file is available
    File path = JsonExportTask.getExportPath(mIsAutoBackupMode);
    File backup = new File(path, JsonExportTask.EXPORT_JSON_FILE_SHOWS);
    if (!backup.exists() || !backup.canRead()) {
      return ERROR_FILE_ACCESS;
    }

    // Clean out all existing tables
    mContext.getContentResolver().delete(Shows.CONTENT_URI, null, null);
    mContext.getContentResolver().delete(Seasons.CONTENT_URI, null, null);
    mContext.getContentResolver().delete(Episodes.CONTENT_URI, null, null);
    mContext.getContentResolver().delete(SeriesContract.Lists.CONTENT_URI, null, null);
    mContext.getContentResolver().delete(ListItems.CONTENT_URI, null, null);

    // Access JSON from backup folder to create new database
    try {
      InputStream in = new FileInputStream(backup);

      Gson gson = new Gson();

      JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
      reader.beginArray();

      while (reader.hasNext()) {
        Show show = gson.fromJson(reader, Show.class);
        addShowToDatabase(show);
      }

      reader.endArray();
      reader.close();

    } catch (JsonParseException e) {
      // the given Json might not be valid or unreadable
      Utils.trackExceptionAndLog(mContext, TAG, e);
      return ERROR;
    } catch (IOException e) {
      Utils.trackExceptionAndLog(mContext, TAG, e);
      return ERROR;
    }

    /*
     * Lists
     */
    File backupLists = new File(path, JsonExportTask.EXPORT_JSON_FILE_LISTS);
    if (!backupLists.exists() || !backupLists.canRead()) {
      // Skip lists if the file is not accessible
      return SUCCESS;
    }

    // Access JSON from backup folder to create new database
    try {
      InputStream in = new FileInputStream(backupLists);

      Gson gson = new Gson();

      JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
      reader.beginArray();

      while (reader.hasNext()) {
        List list = gson.fromJson(reader, List.class);
        addListToDatabase(list);
      }

      reader.endArray();
      reader.close();

    } catch (JsonParseException e) {
      // the given Json might not be valid or unreadable
      Utils.trackExceptionAndLog(mContext, TAG, e);
      return ERROR;
    } catch (IOException e) {
      Utils.trackExceptionAndLog(mContext, TAG, e);
      return ERROR;
    }

    // Renew search table
    mContext
        .getContentResolver()
        .query(EpisodeSearch.CONTENT_URI_RENEWFTSTABLE, null, null, null, null);

    return SUCCESS;
  }
示例#20
0
 private void fireTrackerEventAction(String label) {
   Utils.trackAction(getActivity(), TAG, label);
 }
 @Override
 public void onStart() {
   super.onStart();
   Utils.trackView(getActivity(), "Show Check-In Dialog");
 }
示例#22
0
 public void onEvent(FlagTaskCompletedEvent event) {
   if (isAdded()) {
     Utils.updateLatestEpisode(getActivity(), event.mType.getShowTvdbId());
   }
 }
  @TargetApi(11)
  private void fillData() {
    TextView seriesname = (TextView) findViewById(R.id.title);
    TextView overview = (TextView) findViewById(R.id.TextViewShowInfoOverview);
    TextView airstime = (TextView) findViewById(R.id.TextViewShowInfoAirtime);
    TextView network = (TextView) findViewById(R.id.TextViewShowInfoNetwork);
    TextView status = (TextView) findViewById(R.id.TextViewShowInfoStatus);

    final Series show = DBUtils.getShow(this, String.valueOf(getShowId()));
    if (show == null) {
      finish();
      return;
    }

    // Name
    seriesname.setText(show.getSeriesName());

    // Overview
    if (show.getOverview().length() == 0) {
      overview.setText("");
    } else {
      overview.setText(show.getOverview());
    }

    // Airtimes
    if (show.getAirsDayOfWeek().length() == 0 || show.getAirsTime() == -1) {
      airstime.setText(getString(R.string.show_noairtime));
    } else {
      String[] values =
          Utils.parseMillisecondsToTime(
              show.getAirsTime(), show.getAirsDayOfWeek(), getApplicationContext());
      airstime.setText(getString(R.string.show_airs) + " " + values[1] + " " + values[0]);
    }

    // Network
    if (show.getNetwork().length() == 0) {
      network.setText("");
    } else {
      network.setText(getString(R.string.show_network) + " " + show.getNetwork());
    }

    // Running state
    if (show.getStatus() == 1) {
      status.setTextColor(Color.GREEN);
      status.setText(getString(R.string.show_isalive));
    } else if (show.getStatus() == 0) {
      status.setTextColor(Color.GRAY);
      status.setText(getString(R.string.show_isnotalive));
    }

    // first airdate
    long airtime = Utils.buildEpisodeAirtime(show.getFirstAired(), show.getAirsTime());
    Utils.setValueOrPlaceholder(
        findViewById(R.id.TextViewShowInfoFirstAirdate), Utils.formatToDate(airtime, this));

    // Others
    Utils.setValueOrPlaceholder(
        findViewById(R.id.TextViewShowInfoActors), Utils.splitAndKitTVDBStrings(show.getActors()));
    Utils.setValueOrPlaceholder(
        findViewById(R.id.TextViewShowInfoContentRating), show.getContentRating());
    Utils.setValueOrPlaceholder(
        findViewById(R.id.TextViewShowInfoGenres), Utils.splitAndKitTVDBStrings(show.getGenres()));
    Utils.setValueOrPlaceholder(
        findViewById(R.id.TextViewShowInfoRuntime),
        show.getRuntime() + " " + getString(R.string.show_airtimeunit));

    // TVDb rating
    String ratingText = show.getRating();
    if (ratingText != null && ratingText.length() != 0) {
      RatingBar ratingBar = (RatingBar) findViewById(R.id.bar);
      ratingBar.setProgress((int) (Double.valueOf(ratingText) / 0.1));
      TextView rating = (TextView) findViewById(R.id.value);
      rating.setText(ratingText + "/10");
    }

    // IMDb button
    View imdbButton = (View) findViewById(R.id.buttonShowInfoIMDB);
    final String imdbid = show.getImdbId();
    if (imdbButton != null) {
      imdbButton.setOnClickListener(
          new OnClickListener() {
            public void onClick(View v) {
              fireTrackerEvent("Show IMDb page");

              if (imdbid.length() != 0) {
                Intent myIntent =
                    new Intent(Intent.ACTION_VIEW, Uri.parse("imdb:///title/" + imdbid + "/"));
                try {
                  startActivity(myIntent);
                } catch (ActivityNotFoundException e) {
                  myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(IMDB_TITLE_URL + imdbid));
                  startActivity(myIntent);
                }
              } else {
                Toast.makeText(
                        getApplicationContext(),
                        getString(R.string.show_noimdbentry),
                        Toast.LENGTH_LONG)
                    .show();
              }
            }
          });
    }

    // TVDb button
    View tvdbButton = (View) findViewById(R.id.buttonTVDB);
    final String tvdbId = show.getId();
    if (tvdbButton != null) {
      tvdbButton.setOnClickListener(
          new OnClickListener() {
            public void onClick(View v) {
              fireTrackerEvent("Show TVDb page");
              Intent i =
                  new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.TVDB_SHOW_URL + tvdbId));
              startActivity(i);
            }
          });
    }

    // Shout button
    findViewById(R.id.buttonShouts)
        .setOnClickListener(
            new OnClickListener() {
              @Override
              public void onClick(View v) {
                fireTrackerEvent("Show Trakt Shouts");
                TraktShoutsFragment newFragment =
                    TraktShoutsFragment.newInstance(show.getSeriesName(), Integer.valueOf(tvdbId));

                newFragment.show(getSupportFragmentManager(), "shouts-dialog");
              }
            });

    // Share intent
    mShareIntentBuilder =
        ShareCompat.IntentBuilder.from(this)
            .setChooserTitle(R.string.share)
            .setText(
                getString(R.string.share_checkout)
                    + " \""
                    + show.getSeriesName()
                    + "\" via @SeriesGuide "
                    + ShowInfoActivity.IMDB_TITLE_URL
                    + imdbid)
            .setType("text/plain");

    // Poster
    final ImageView poster = (ImageView) findViewById(R.id.ImageViewShowInfoPoster);
    ImageProvider.getInstance(this).loadImage(poster, show.getPoster(), false);

    // trakt ratings
    TraktSummaryTask task = new TraktSummaryTask(this, findViewById(R.id.ratingbar)).show(tvdbId);
    AndroidUtils.executeAsyncTask(task, new Void[] {null});
  }
示例#24
0
 private void fireTrackerEventContext(String label) {
   Utils.trackContextMenu(getActivity(), TAG, label);
 }
示例#25
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    if (!mDataValid) {
      throw new IllegalStateException("this should only be called when the cursor is valid");
    }
    if (!mCursor.moveToPosition(position)) {
      throw new IllegalStateException("couldn't move cursor to position " + position);
    }

    final ViewHolder viewHolder;

    if (convertView == null) {
      convertView = newView(mContext, mCursor, parent);

      viewHolder = new ViewHolder();
      viewHolder.watchedBox = (WatchedBox) convertView.findViewById(R.id.watchedBoxEpisode);
      viewHolder.episodeTitle = (TextView) convertView.findViewById(R.id.textViewEpisodeTitle);
      viewHolder.episodeNumber = (TextView) convertView.findViewById(R.id.textViewEpisodeNumber);
      viewHolder.episodeAirdate = (TextView) convertView.findViewById(R.id.textViewEpisodeAirdate);
      viewHolder.episodeAlternativeNumbers =
          (TextView) convertView.findViewById(R.id.textViewEpisodeAlternativeNumbers);
      viewHolder.collected = (ImageView) convertView.findViewById(R.id.imageViewCollected);
      viewHolder.contextMenu = (ImageView) convertView.findViewById(R.id.imageViewContextMenu);

      convertView.setTag(viewHolder);
    } else {
      viewHolder = (ViewHolder) convertView.getTag();
    }

    // episode title
    viewHolder.episodeTitle.setText(mCursor.getString(EpisodesQuery.TITLE));

    // number
    final int episodeNumber = mCursor.getInt(EpisodesQuery.NUMBER);
    viewHolder.episodeNumber.setText(String.valueOf(episodeNumber));

    // watched box
    viewHolder.watchedBox.setEpisodeFlag(mCursor.getInt(EpisodesQuery.WATCHED));
    final int episodeId = mCursor.getInt(EpisodesQuery._ID);
    viewHolder.watchedBox.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            WatchedBox box = (WatchedBox) v;
            mOnFlagListener.onFlagEpisodeWatched(
                episodeId, episodeNumber, !EpisodeTools.isWatched(box.getEpisodeFlag()));
          }
        });
    CheatSheet.setup(
        viewHolder.watchedBox,
        EpisodeTools.isWatched(viewHolder.watchedBox.getEpisodeFlag())
            ? R.string.unmark_episode
            : R.string.mark_episode);

    // collected tag
    viewHolder.collected.setVisibility(
        mCursor.getInt(EpisodesQuery.COLLECTED) == 1 ? View.VISIBLE : View.INVISIBLE);

    // alternative numbers
    StringBuilder altNumbers = new StringBuilder();
    int absoluteNumber = mCursor.getInt(EpisodesQuery.ABSOLUTE_NUMBER);
    if (absoluteNumber > 0) {
      altNumbers
          .append(mContext.getString(R.string.episode_number_absolute))
          .append(" ")
          .append(absoluteNumber);
    }
    double dvdNumber = mCursor.getDouble(EpisodesQuery.DVDNUMBER);
    if (dvdNumber > 0) {
      if (altNumbers.length() != 0) {
        altNumbers.append(" | ");
      }
      altNumbers
          .append(mContext.getString(R.string.episode_number_disk))
          .append(" ")
          .append(dvdNumber);
    }
    viewHolder.episodeAlternativeNumbers.setText(altNumbers);

    // air date
    long airtime = mCursor.getLong(EpisodesQuery.FIRSTAIREDMS);
    if (airtime != -1) {
      viewHolder.episodeAirdate.setText(Utils.formatToTimeAndDay(airtime, mContext)[2]);
    } else {
      viewHolder.episodeAirdate.setText(mContext.getString(R.string.episode_firstaired_unknown));
    }

    // context menu
    viewHolder.contextMenu.setOnClickListener(mOnClickListener);

    return convertView;
  }