Esempio n. 1
0
 public void setPlaylists(List<Playlist> playlists) {
   if (playlists != null) {
     for (Playlist playlist : playlists) {
       playlist.setUserId(mId);
     }
   }
   mPlaylists = playlists;
 }
Esempio n. 2
0
  /** Construct a new {@link User} with the given id */
  private User(String id) {
    super(User.class, id);

    mId = id;
    mPlaybackLog = Playlist.fromEmptyList(id + User.PLAYLIST_PLAYBACKLOG_ID, false, "");
    mFavorites = Playlist.fromEmptyList(id + User.PLAYLIST_FAVORITES_ID, false, "");
    mSocialActionsPlaylist = Playlist.fromEmptyList(id + User.PLAYLIST_SOCIALACTIONS_ID, false, "");
    mFriendsFeedPlaylist = Playlist.fromEmptyList(id + User.PLAYLIST_FRIENDSFEED_ID, false, "");
  }
 /**
  * @return If current {@link Playlist} is empty or null, return 1. If current {@link Playlist} is
  *     repeating, return FAKE_INFINITY_COUNT. Else return the current {@link Playlist}'s length.
  */
 @Override
 public int getCount() {
   if (mPlaylist == null || mPlaylist.getCount() == 0) {
     return 1;
   }
   if (mPlaylist.isRepeating()) {
     return FAKE_INFINITY_COUNT;
   }
   return mPlaylist.getCount();
 }
Esempio n. 4
0
 private void fillPlaylist(
     Playlist playlist, TreeMap<Date, List<SocialAction>> actions, Set<Date> doneConversions) {
   for (Date date : actions.keySet()) {
     if (!doneConversions.contains(date)) {
       doneConversions.add(date);
       List<List<SocialAction>> mergedActions =
           SocialActionsFragment.mergeSocialActions(actions.get(date));
       for (List<SocialAction> actionsList : mergedActions) {
         for (SocialAction action : actionsList) {
           if (action.getTargetObject() instanceof Query) {
             Query query = (Query) action.getTargetObject();
             PlaylistEntry entry = playlist.addQuery(playlist.size(), query);
             mPlaylistEntryMap.put(action, entry);
           }
         }
       }
     }
   }
 }
Esempio n. 5
0
 public static void fillView(View view, Playlist playlist, int height, boolean isPagerFragment) {
   ArrayList<Image> artistImages = new ArrayList<>();
   String[] artists = playlist.getTopArtistNames();
   if (artists != null) {
     for (int i = 0; i < artists.length && i < 5 && artistImages.size() < 3; i++) {
       Artist artist = Artist.get(artists[i]);
       if (artist.getImage() != null) {
         artistImages.add(artist.getImage());
       }
     }
   }
   fillView(view, artistImages, height, isPagerFragment);
 }
Esempio n. 6
0
 public void fillView(Playlist playlist) {
   if (findViewById(R.id.imageview_create_playlist) != null) {
     findViewById(R.id.imageview_create_playlist).setVisibility(View.GONE);
   }
   ArrayList<Image> artistImages = new ArrayList<>();
   String topArtistsString = "";
   String[] artists = playlist.getTopArtistNames();
   if (artists != null) {
     for (int i = 0; i < artists.length && i < 5 && artistImages.size() < 3; i++) {
       Artist artist = Artist.get(artists[i]);
       topArtistsString += artists[i];
       if (i != artists.length - 1) {
         topArtistsString += ", ";
       }
       if (artist.getImage() != null) {
         artistImages.add(artist.getImage());
       }
     }
   }
   fillView(mRootView, artistImages, 0, false);
   TextView textView1 = (TextView) findViewById(R.id.textview1);
   if (textView1 != null) {
     textView1.setText(playlist.getName());
   }
   TextView textView2 = (TextView) findViewById(R.id.textview2);
   if (textView2 != null) {
     textView2.setText(topArtistsString);
     textView2.setVisibility(View.VISIBLE);
   }
   TextView textView3 = (TextView) findViewById(R.id.textview3);
   if (textView3 != null) {
     textView3.setVisibility(View.VISIBLE);
     textView3.setText(
         TomahawkApp.getContext()
             .getResources()
             .getQuantityString(
                 R.plurals.songs_with_count, (int) playlist.getCount(), playlist.getCount()));
   }
 }
 private void unpackArgs() {
   if (getArguments() != null) {
     if (getArguments().containsKey(TomahawkFragment.HIDE_REMOVE_BUTTON)) {
       mHideRemoveButton = getArguments().getBoolean(TomahawkFragment.HIDE_REMOVE_BUTTON);
     }
     if (getArguments().containsKey(TomahawkFragment.FROM_PLAYBACKFRAGMENT)) {
       mFromPlaybackFragment = getArguments().getBoolean(TomahawkFragment.FROM_PLAYBACKFRAGMENT);
     }
     if (getArguments().containsKey(TomahawkFragment.TOMAHAWKLISTITEM_TYPE)
         && getArguments().containsKey(TomahawkFragment.TOMAHAWKLISTITEM)) {
       String type = getArguments().getString(TomahawkFragment.TOMAHAWKLISTITEM_TYPE);
       String key = getArguments().getString(TomahawkFragment.TOMAHAWKLISTITEM);
       switch (type) {
         case TomahawkFragment.ALBUM:
           mAlbum = Album.getByKey(key);
           break;
         case TomahawkFragment.PLAYLIST:
           mPlaylist = Playlist.getByKey(key);
           break;
         case TomahawkFragment.ARTIST:
           mArtist = Artist.getByKey(key);
           break;
         case TomahawkFragment.QUERY:
           mQuery = Query.getByKey(key);
           break;
         case TomahawkFragment.SOCIALACTION:
           SocialAction socialAction = SocialAction.getByKey(key);
           Object targetObject = socialAction.getTargetObject();
           if (targetObject instanceof Artist) {
             mArtist = (Artist) targetObject;
           } else if (targetObject instanceof Album) {
             mAlbum = (Album) targetObject;
           } else if (targetObject instanceof Query) {
             mQuery = (Query) targetObject;
           } else if (targetObject instanceof Playlist) {
             mPlaylist = (Playlist) targetObject;
           }
           break;
         case TomahawkFragment.PLAYLISTENTRY:
           mPlaylistEntry = PlaylistEntry.getByKey(key);
           break;
       }
     }
     if (getArguments().containsKey(TomahawkFragment.COLLECTION_ID)) {
       mCollection =
           CollectionManager.get()
               .getCollection(getArguments().getString(TomahawkFragment.COLLECTION_ID));
     }
   }
 }
 /**
  * Instantiate an item in the {@link PagerAdapter}. Fill it async with the correct AlbumArt image.
  */
 @Override
 public Object instantiateItem(View collection, int position) {
   ImageView albumArtImageView = new ImageView(mContext);
   if (mPlaylist != null && mPlaylist.getCount() > 0) {
     if (mPlaylist.isRepeating()
         && mPlaylist.peekTrackAtPos((position) % mPlaylist.getCount()).getAlbum() != null) {
       mPlaylist
           .peekTrackAtPos((position) % mPlaylist.getCount())
           .getAlbum()
           .loadBitmap(mContext, albumArtImageView);
     } else if (!mPlaylist.isRepeating()
         && mPlaylist.peekTrackAtPos(position).getAlbum() != null) {
       mPlaylist.peekTrackAtPos(position).getAlbum().loadBitmap(mContext, albumArtImageView);
     } else {
       albumArtImageView.setImageResource(R.drawable.no_album_art_placeholder);
     }
   } else {
     albumArtImageView.setImageResource(R.drawable.no_album_art_placeholder);
   }
   ((ViewPager) collection).addView(albumArtImageView);
   return albumArtImageView;
 }
 /**
  * @param position to set the current item to
  * @param smoothScroll boolean to determine whether or not to show a scrolling animation
  */
 public void setCurrentItem(int position, boolean smoothScroll) {
   if (position != mCurrentViewPage) {
     if (mPlaylist.isRepeating()) {
       if (position == (mCurrentViewPage % mPlaylist.getCount()) + 1
           || ((mCurrentViewPage % mPlaylist.getCount()) == mPlaylist.getCount() - 1
               && position == 0)) {
         setCurrentToNextItem(smoothScroll);
       } else if (position == (mCurrentViewPage % mPlaylist.getCount()) - 1
           || ((mCurrentViewPage % mPlaylist.getCount()) == 0
               && position == mPlaylist.getCount() - 1)) {
         setCurrentToPreviousItem(smoothScroll);
       } else {
         mViewPager.setCurrentItem(position, false);
       }
     } else {
       mViewPager.setCurrentItem(position, smoothScroll);
     }
     mCurrentViewPage = mViewPager.getCurrentItem();
   }
 }
 /**
  * update the {@link Playlist} of the {@link AlbumArtSwipeAdapter} to the given {@link Playlist}
  */
 public void updatePlaylist() {
   if (mPlaybackService != null) {
     mPlaylist = mPlaybackService.getCurrentPlaylist();
     notifyDataSetChanged();
   }
   if (mPlaylist != null && mPlaylist.getCount() > 0) {
     mFakeInfinityOffset =
         mPlaylist.getCount() * ((FAKE_INFINITY_COUNT / 2) / mPlaylist.getCount());
     setByUser(false);
     if (mPlaylist.isRepeating()) {
       setCurrentItem(mPlaylist.getCurrentTrackIndex() + getFakeInfinityOffset(), false);
     } else {
       setCurrentItem(mPlaylist.getCurrentTrackIndex(), false);
     }
     setByUser(true);
   }
 }
 private void setupTextViews(View view) {
   if (mAlbum != null) {
     View v = ViewUtils.ensureInflation(view, R.id.album_name_button_stub, R.id.album_name_button);
     TextView textView = (TextView) v.findViewById(R.id.textview);
     textView.setText(mAlbum.getName());
     v.setOnClickListener(constructAlbumNameClickListener(mAlbum.getCacheKey()));
   } else if (mQuery != null || mPlaylistEntry != null || mPlaylist != null) {
     View v = ViewUtils.ensureInflation(view, R.id.track_name_stub, R.id.track_name);
     TextView textView = (TextView) v;
     if (mQuery != null) {
       textView.setText(mQuery.getName());
     } else if (mPlaylistEntry != null) {
       textView.setText(mPlaylistEntry.getName());
     } else if (mPlaylist != null) {
       textView.setText(mPlaylist.getName());
     }
   }
   if (mAlbum != null || mQuery != null || mPlaylistEntry != null || mArtist != null) {
     View v =
         ViewUtils.ensureInflation(view, R.id.artist_name_button_stub, R.id.artist_name_button);
     TextView textView = (TextView) v.findViewById(R.id.textview);
     String cacheKey;
     if (mQuery != null) {
       textView.setText(mQuery.getArtist().getPrettyName());
       cacheKey = mQuery.getArtist().getCacheKey();
     } else if (mAlbum != null) {
       textView.setText(mAlbum.getArtist().getPrettyName());
       cacheKey = mAlbum.getArtist().getCacheKey();
     } else if (mPlaylistEntry != null) {
       textView.setText(mPlaylistEntry.getArtist().getPrettyName());
       cacheKey = mPlaylistEntry.getArtist().getCacheKey();
     } else {
       textView.setText(mArtist.getPrettyName());
       cacheKey = mArtist.getCacheKey();
     }
     v.setOnClickListener(constructArtistNameClickListener(cacheKey));
   }
 }
  private void setupContextMenuItems(View view) {
    final TomahawkMainActivity activity = (TomahawkMainActivity) getActivity();

    // set up "Add to playlist" context menu item
    if (mAlbum != null || mQuery != null || mPlaylistEntry != null || mPlaylist != null) {
      View v =
          ViewUtils.ensureInflation(
              view, R.id.context_menu_addtoplaylist_stub, R.id.context_menu_addtoplaylist);
      TextView textView = (TextView) v.findViewById(R.id.textview);
      ImageView imageView = (ImageView) v.findViewById(R.id.imageview);
      imageView.setImageResource(R.drawable.ic_action_playlist_light);
      textView.setText(R.string.context_menu_add_to_playlist);
      v.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              getActivity().getSupportFragmentManager().popBackStack();
              if (mAlbum != null) {
                mCollection
                    .getAlbumTracks(mAlbum)
                    .done(
                        new DoneCallback<CollectionCursor<Query>>() {
                          @Override
                          public void onDone(CollectionCursor<Query> cursor) {
                            List<Query> queries = new ArrayList<>();
                            if (cursor != null) {
                              for (int i = 0; i < cursor.size(); i++) {
                                Query query = cursor.get(i);
                                if (query == null) {
                                  Log.e(
                                      TAG,
                                      "setupContextMenuItems - Can't call "
                                          + "showAddToPlaylist. Cursor has been "
                                          + "closed.");
                                  cursor.close();
                                  return;
                                }
                                queries.add(cursor.get(i));
                              }
                              cursor.close();
                            }
                            showAddToPlaylist(activity, queries);
                          }
                        });
              } else if (mQuery != null) {
                ArrayList<Query> queries = new ArrayList<>();
                queries.add(mQuery);
                showAddToPlaylist(activity, queries);
              } else if (mPlaylistEntry != null) {
                ArrayList<Query> queries = new ArrayList<>();
                queries.add(mPlaylistEntry.getQuery());
                showAddToPlaylist(activity, queries);
              } else if (mPlaylist != null) {
                showAddToPlaylist(activity, mPlaylist.getQueries());
              }
            }
          });
    }

    // set up "Add to collection" context menu item
    if (mAlbum != null || mArtist != null) {
      int drawableResId;
      int stringResId;
      if ((mAlbum != null && DatabaseHelper.get().isItemLoved(mAlbum))
          || (mArtist != null && DatabaseHelper.get().isItemLoved(mArtist))) {
        drawableResId = R.drawable.ic_action_collection_underlined;
        stringResId = R.string.context_menu_removefromcollection;
      } else {
        drawableResId = R.drawable.ic_action_collection;
        stringResId = R.string.context_menu_addtocollection;
      }
      View v =
          ViewUtils.ensureInflation(
              view, R.id.context_menu_addtocollection_stub, R.id.context_menu_addtocollection);
      TextView textView = (TextView) v.findViewById(R.id.textview);
      ImageView imageView = (ImageView) v.findViewById(R.id.imageview);
      imageView.setImageResource(drawableResId);
      textView.setText(stringResId);
      v.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              getActivity().getSupportFragmentManager().popBackStack();
              if (mAlbum != null) {
                CollectionManager.get().toggleLovedItem(mAlbum);
              } else {
                CollectionManager.get().toggleLovedItem(mArtist);
              }
            }
          });
    }

    // set up "Add to favorites" context menu item
    if (mQuery != null || mPlaylistEntry != null) {
      final Query query = mQuery != null ? mQuery : mPlaylistEntry.getQuery();
      int drawableResId;
      int stringResId;
      if (DatabaseHelper.get().isItemLoved(query)) {
        drawableResId = R.drawable.ic_action_favorites_underlined;
        stringResId = R.string.context_menu_unlove;
      } else {
        drawableResId = R.drawable.ic_action_favorites;
        stringResId = R.string.context_menu_love;
      }
      View v =
          ViewUtils.ensureInflation(
              view, R.id.context_menu_favorite_stub, R.id.context_menu_favorite);
      TextView textView = (TextView) v.findViewById(R.id.textview);
      ImageView imageView = (ImageView) v.findViewById(R.id.imageview);
      imageView.setImageResource(drawableResId);
      textView.setText(stringResId);
      v.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              getActivity().getSupportFragmentManager().popBackStack();
              CollectionManager.get().toggleLovedItem(query);
            }
          });
    }

    // set up "Share" context menu item
    View v = ViewUtils.ensureInflation(view, R.id.context_menu_share_stub, R.id.context_menu_share);
    TextView textView = (TextView) v.findViewById(R.id.textview);
    ImageView imageView = (ImageView) v.findViewById(R.id.imageview);
    imageView.setImageResource(R.drawable.ic_action_share);
    textView.setText(R.string.context_menu_share);
    v.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            getActivity().getSupportFragmentManager().popBackStack();
            if (mAlbum != null) {
              ShareUtils.sendShareIntent(activity, mAlbum);
            } else if (mArtist != null) {
              ShareUtils.sendShareIntent(activity, mArtist);
            } else if (mQuery != null) {
              ShareUtils.sendShareIntent(activity, mQuery);
            } else if (mPlaylistEntry != null) {
              ShareUtils.sendShareIntent(activity, mPlaylistEntry.getQuery());
            } else if (mPlaylist != null) {
              ShareUtils.sendShareIntent(activity, mPlaylist);
            }
          }
        });

    // set up "Remove" context menu item
    if (mPlaylist != null || mPlaylistEntry != null) {
      final String playlistId =
          mPlaylist != null ? mPlaylist.getId() : mPlaylistEntry.getPlaylistId();
      if (!mHideRemoveButton) {
        int stringResId;
        if (mPlaylistEntry != null) {
          stringResId = R.string.context_menu_removefromplaylist;
        } else {
          stringResId = R.string.context_menu_delete;
        }
        v =
            ViewUtils.ensureInflation(
                view, R.id.context_menu_remove_stub, R.id.context_menu_remove);
        textView = (TextView) v.findViewById(R.id.textview);
        imageView = (ImageView) v.findViewById(R.id.imageview);
        imageView.setImageResource(R.drawable.ic_player_exit_light);
        textView.setText(stringResId);
        v.setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
                if (mPlaylistEntry != null) {
                  CollectionManager.get().deletePlaylistEntry(playlistId, mPlaylistEntry.getId());
                } else {
                  CollectionManager.get().deletePlaylist(playlistId);
                }
              }
            });
      }
    }

    // set up "Add to queue" context menu item
    if (mAlbum != null || mQuery != null || mPlaylistEntry != null || mPlaylist != null) {
      int drawableResId = R.drawable.ic_action_queue;
      int stringResId = R.string.context_menu_add_to_queue;
      v =
          ViewUtils.ensureInflation(
              view, R.id.context_menu_addtoqueue_stub, R.id.context_menu_addtoqueue);
      textView = (TextView) v.findViewById(R.id.textview);
      imageView = (ImageView) v.findViewById(R.id.imageview);
      imageView.setImageResource(drawableResId);
      textView.setText(stringResId);
      v.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              getActivity().getSupportFragmentManager().popBackStack();
              if (mAlbum != null) {
                mCollection
                    .getAlbumTracks(mAlbum)
                    .done(
                        new DoneCallback<CollectionCursor<Query>>() {
                          @Override
                          public void onDone(CollectionCursor<Query> collectionCursor) {
                            List<Query> albumTracks = new ArrayList<>();
                            for (int i = 0; i < collectionCursor.size(); i++) {
                              albumTracks.add(collectionCursor.get(i));
                            }
                            ((TomahawkMainActivity) getActivity())
                                .getPlaybackService()
                                .addQueriesToQueue(albumTracks);
                          }
                        });
              } else if (mQuery != null) {
                ((TomahawkMainActivity) getActivity()).getPlaybackService().addQueryToQueue(mQuery);
              } else if (mPlaylistEntry != null) {
                ((TomahawkMainActivity) getActivity())
                    .getPlaybackService()
                    .addQueryToQueue(mPlaylistEntry.getQuery());
              } else if (mPlaylist != null) {
                ((TomahawkMainActivity) getActivity())
                    .getPlaybackService()
                    .addQueriesToQueue(mPlaylist.getQueries());
              }
            }
          });
    }
  }
Esempio n. 13
0
 public void setFavorites(Playlist favorites) {
   if (favorites != null) {
     favorites.setUserId(mId);
   }
   mFavorites = favorites;
 }
Esempio n. 14
0
 public void setName(String name) {
   mName = name;
   mPlaybackLog.setName(
       TomahawkApp.getContext().getString(R.string.users_playbacklog_suffix, name));
   mFavorites.setName(TomahawkApp.getContext().getString(R.string.users_favorites_suffix, name));
 }
  /**
   * Update this {@link org.tomahawk.tomahawk_android.fragments.TomahawkFragment}'s {@link
   * org.tomahawk.tomahawk_android.adapters.TomahawkListAdapter} content
   */
  @Override
  protected void updateAdapter() {
    if (!mIsResumed) {
      return;
    }

    if (mAlbum != null) {
      showContentHeader(mAlbum);
      if (mContainerFragmentClass == null) {
        showAlbumFancyDropDown();
      }
      mCollection
          .getAlbumTracks(mAlbum)
          .done(
              new DoneCallback<Playlist>() {
                @Override
                public void onDone(Playlist playlist) {
                  mCurrentPlaylist = playlist;
                  Segment.Builder builder =
                      new Segment.Builder(playlist)
                          .headerLayout(R.layout.single_line_list_header)
                          .headerString(mAlbum.getArtist().getPrettyName());
                  if (playlist != null && playlist.allFromOneArtist()) {
                    builder.hideArtistName(true);
                    builder.showDuration(true);
                  }
                  builder.showNumeration(true, 1);
                  fillAdapter(builder.build());
                }
              });
    } else if (mUser != null || mPlaylist != null) {
      if (mUser != null) {
        if (mShowMode == SHOW_MODE_PLAYBACKLOG) {
          mCurrentPlaylist = mUser.getPlaybackLog();
        } else if (mShowMode == SHOW_MODE_LOVEDITEMS) {
          mCurrentPlaylist = mUser.getFavorites();
        }
      }
      if (mPlaylist != null) {
        mCurrentPlaylist = mPlaylist;
      }
      if (!mCurrentPlaylist.isFilled()) {
        User.getSelf()
            .done(
                new DoneCallback<User>() {
                  @Override
                  public void onDone(User user) {
                    if (mShowMode < 0) {
                      if (mUser != user) {
                        String requestId = InfoSystem.get().resolve(mCurrentPlaylist);
                        if (requestId != null) {
                          mCorrespondingRequestIds.add(requestId);
                        }
                      } else if (mPlaylist != null) {
                        mPlaylist = DatabaseHelper.get().getPlaylist(mPlaylist.getId());
                        updateAdapter();
                      }
                    }
                  }
                });
      } else {
        Segment.Builder builder = new Segment.Builder(mCurrentPlaylist);
        if (mContainerFragmentClass == null
            || !mContainerFragmentClass.equals(SearchPagerFragment.class.getName())) {
          builder.showNumeration(true, 1);
          if (mContainerFragmentClass == null
              || !mContainerFragmentClass.equals(ChartsPagerFragment.class.getName())) {
            builder
                .headerLayout(R.layout.single_line_list_header)
                .headerString(R.string.playlist_details);
          }
        } else if (mContainerFragmentClass.equals(SearchPagerFragment.class.getName())) {
          builder.showResolverIcon(true);
        }
        Segment segment = builder.build();
        fillAdapter(segment);
        showContentHeader(mCurrentPlaylist);
        showFancyDropDown(0, mCurrentPlaylist.getName(), null, null);
        ThreadManager.get()
            .execute(
                new TomahawkRunnable(TomahawkRunnable.PRIORITY_IS_INFOSYSTEM_LOW) {
                  @Override
                  public void run() {
                    if (mCurrentPlaylist.getTopArtistNames() == null
                        || mCurrentPlaylist.getTopArtistNames().length == 0) {
                      boolean isFavorites =
                          mUser != null && mCurrentPlaylist == mUser.getFavorites();
                      mCurrentPlaylist.updateTopArtistNames(isFavorites);
                    } else {
                      for (int i = 0;
                          i < mCurrentPlaylist.getTopArtistNames().length && i < 5;
                          i++) {
                        String artistName = mCurrentPlaylist.getTopArtistNames()[i];
                        if (!mResolvingTopArtistNames.contains(artistName)) {
                          String requestId =
                              InfoSystem.get().resolve(Artist.get(artistName), false);
                          if (requestId != null) {
                            mCorrespondingRequestIds.add(requestId);
                          }
                          mResolvingTopArtistNames.add(artistName);
                        }
                      }
                    }
                  }
                });
      }
    } else {
      mCollection
          .getQueries(getSortMode())
          .done(
              new DoneCallback<Playlist>() {
                @Override
                public void onDone(final Playlist playlist) {
                  new Thread(
                          new Runnable() {
                            @Override
                            public void run() {
                              mCurrentPlaylist = playlist;
                              String id = mCollection.getId();
                              Segment segment =
                                  new Segment.Builder(playlist)
                                      .headerLayout(R.layout.dropdown_header)
                                      .headerStrings(constructDropdownItems())
                                      .spinner(
                                          constructDropdownListener(
                                              COLLECTION_TRACKS_SPINNER_POSITION + id),
                                          getDropdownPos(COLLECTION_TRACKS_SPINNER_POSITION + id))
                                      .build();
                              fillAdapter(segment);
                            }
                          })
                      .start();
                }
              });
    }
  }
Esempio n. 16
0
  public List storeRecords(
      JsonObject object,
      int resultType,
      int requestType,
      boolean isBackgroundRequest,
      QueryParams params)
      throws IOException {
    List results = new ArrayList();
    JsonElement elements = object.get("images");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          Image image = (Image) mCache.get(TYPE_IMAGES).get(id);
          if (image == null) {
            String url = getAsString(o, "url");
            int width = getAsInt(o, "width");
            int height = getAsInt(o, "height");
            image = Image.get(url, true, width, height);
            mCache.get(TYPE_IMAGES).put(id, image);
          }
          if (resultType == TYPE_IMAGES) {
            results.add(image);
          }
        }
      }
    }
    elements = object.get("artists");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          Artist artist = (Artist) mCache.get(TYPE_ARTISTS).get(id);
          if (artist == null) {
            String name = getAsString(o, "name");
            String wiki = getAsString(o, "wikiabstract");
            artist = Artist.get(name);
            artist.setBio(new ListItemString(wiki));
            JsonElement images = get(o, "images");
            if (images instanceof JsonArray && ((JsonArray) images).size() > 0) {
              String imageId = ((JsonArray) images).get(0).getAsString();
              Image image = (Image) findRecord(imageId, TYPE_IMAGES, isBackgroundRequest);
              artist.setImage(image);
            }
            mCache.get(TYPE_ARTISTS).put(id, artist);
          }

          if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_ARTISTS_ALBUMS) {
            JsonElement rawAlbums = get(o, "albums");
            if (rawAlbums instanceof JsonObject) {
              results.addAll(
                  storeRecords((JsonObject) rawAlbums, TYPE_ALBUMS, isBackgroundRequest));
            }
          } else if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_ARTISTS_TOPHITS) {
            JsonElement rawTopHits = get(o, "topHits");
            if (rawTopHits instanceof JsonObject) {
              results.addAll(
                  storeRecords((JsonObject) rawTopHits, TYPE_TRACKS, isBackgroundRequest));
            }
          }
          if (resultType == TYPE_ARTISTS) {
            results.add(artist);
          }
        }
      }
    }
    elements = object.get("albums");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          Album album = (Album) mCache.get(TYPE_ALBUMS).get(id);
          if (album == null) {
            String name = getAsString(o, "name");
            String artistId = getAsString(o, "artist");
            Artist artist = (Artist) findRecord(artistId, TYPE_ARTISTS, isBackgroundRequest);
            album = Album.get(name, artist);
            JsonElement images = get(o, "images");
            if (images instanceof JsonArray && ((JsonArray) images).size() > 0) {
              String imageId = ((JsonArray) images).get(0).getAsString();
              Image image = (Image) findRecord(imageId, TYPE_IMAGES, isBackgroundRequest);
              album.setImage(image);
            }
            mCache.get(TYPE_ALBUMS).put(id, album);
          }

          if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_ALBUMS_TRACKS) {
            JsonElement rawTracks = get(o, "tracks");
            if (rawTracks instanceof JsonObject) {
              results.addAll(
                  storeRecords((JsonObject) rawTracks, TYPE_TRACKS, isBackgroundRequest));
            }
          }
          if (resultType == TYPE_ALBUMS) {
            results.add(album);
          }
        }
      }
    }
    elements = object.get("tracks");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          Query query = (Query) mCache.get(TYPE_TRACKS).get(id);
          if (query == null) {
            String name = getAsString(o, "name");
            String artistId = getAsString(o, "artist");
            Artist artist = (Artist) findRecord(artistId, TYPE_ARTISTS, isBackgroundRequest);
            query = Query.get(name, null, artist.getName(), false, true);
            mCache.get(TYPE_TRACKS).put(id, query);
          }
          if (resultType == TYPE_TRACKS) {
            results.add(query);
          }
        }
      }
    }
    elements = object.get("users");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          User user = User.get(id);
          String name = getAsString(o, "name");
          user.setName(name);
          String about = getAsString(o, "about");
          user.setAbout(about);
          int followersCount = getAsInt(o, "followersCount");
          user.setFollowersCount(followersCount);
          int followCount = getAsInt(o, "followCount");
          user.setFollowCount(followCount);
          String nowplayingId = getAsString(o, "nowplaying");
          if (nowplayingId != null) {
            Query nowplaying = (Query) findRecord(nowplayingId, TYPE_TRACKS, isBackgroundRequest);
            user.setNowPlaying(nowplaying);
          }
          String nowplayingtimestamp = getAsString(o, "nowplayingtimestamp");
          user.setNowPlayingTimeStamp(ISO8601Utils.parse(nowplayingtimestamp));
          String avatar = getAsString(o, "avatar");
          if (avatar != null) {
            Image image = (Image) findRecord(avatar, TYPE_IMAGES, isBackgroundRequest);
            user.setImage(image);
          }

          if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_USERS_PLAYLISTS) {
            JsonElement rawPlaylists = get(o, "playlists");
            if (rawPlaylists instanceof JsonObject) {
              List playlists =
                  storeRecords((JsonObject) rawPlaylists, TYPE_PLAYLISTS, isBackgroundRequest);
              user.setPlaylists(playlists);
            }
          } else if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_USERS_LOVEDITEMS) {
            JsonElement rawLovedItems = get(o, "lovedItems");
            if (rawLovedItems instanceof JsonObject) {
              List playlists =
                  storeRecords((JsonObject) rawLovedItems, TYPE_PLAYLISTS, isBackgroundRequest);
              if (playlists != null && playlists.size() > 0) {
                user.setFavorites((Playlist) playlists.get(0));
              }
            }
          } else if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_USERS_LOVEDALBUMS) {
            JsonElement rawLovedAlbums = get(o, "lovedAlbums");
            if (rawLovedAlbums instanceof JsonObject) {
              List albums =
                  storeRecords((JsonObject) rawLovedAlbums, TYPE_ALBUMS, isBackgroundRequest);
              user.setStarredAlbums(albums);
            }
          } else if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_USERS_LOVEDARTISTS) {
            JsonElement rawLovedArtists = get(o, "lovedArtists");
            if (rawLovedArtists instanceof JsonObject) {
              List artists =
                  storeRecords((JsonObject) rawLovedArtists, TYPE_ARTISTS, isBackgroundRequest);
              user.setStarredArtists(artists);
            }
          } else if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_USERS_PLAYBACKLOG) {
            JsonElement rawPlaybackLog = get(o, "playbacklog");
            if (rawPlaybackLog instanceof JsonObject) {
              List playlists =
                  storeRecords((JsonObject) rawPlaybackLog, TYPE_PLAYLISTS, isBackgroundRequest);
              if (playlists != null && playlists.size() > 0) {
                user.setPlaybackLog((Playlist) playlists.get(0));
              }
            }
          } else if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_USERS_FOLLOWS
              || requestType == InfoRequestData.INFOREQUESTDATA_TYPE_USERS_FOLLOWERS) {
            boolean isFollows = requestType == InfoRequestData.INFOREQUESTDATA_TYPE_USERS_FOLLOWS;
            JsonElement rawFollows = get(o, isFollows ? "follows" : "followers");
            if (rawFollows instanceof JsonObject) {
              JsonObject follows = (JsonObject) rawFollows;
              storeRecords(follows, -1, isBackgroundRequest);
              JsonElement relationships = get(follows, "relationships");
              if (relationships instanceof JsonArray) {
                TreeMap<User, String> followsMap = new TreeMap<>(new AlphaComparator());
                for (JsonElement relationship : (JsonArray) relationships) {
                  JsonObject relationshipObj = (JsonObject) relationship;
                  String relationshipId = getAsString(relationshipObj, "id");
                  String userId = getAsString(relationshipObj, isFollows ? "targetUser" : "user");
                  User followedUser = (User) findRecord(userId, TYPE_USERS, isBackgroundRequest);
                  followsMap.put(followedUser, relationshipId);
                }
                if (isFollows) {
                  user.setFollowings(followsMap);
                } else {
                  user.setFollowers(followsMap);
                }
              }
            }
          } else if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_USERS_PLAYBACKLOG) {
            JsonElement rawPlaybackLog = get(o, "playbacklog");
            if (rawPlaybackLog instanceof JsonObject) {
              List playlists =
                  storeRecords((JsonObject) rawPlaybackLog, TYPE_PLAYLISTS, isBackgroundRequest);
              if (playlists != null && playlists.size() > 0) {
                user.setPlaybackLog((Playlist) playlists.get(0));
              }
            }
          }
          mCache.get(TYPE_USERS).put(id, user);
          if (resultType == TYPE_USERS) {
            results.add(user);
          }
        }
      }
    }
    elements = object.get("playlistEntries");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          Query query = (Query) mCache.get(TYPE_PLAYLISTENTRIES).get(id);
          if (query == null) {
            String trackId = getAsString(o, "track");
            query = (Query) findRecord(trackId, TYPE_TRACKS, isBackgroundRequest);
            mCache.get(TYPE_PLAYLISTENTRIES).put(id, query);
          }
          if (resultType == TYPE_PLAYLISTENTRIES) {
            results.add(query);
          }
        }
      }
    }
    elements = object.get("playlists");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          String title = getAsString(o, "title");
          String currentrevision = getAsString(o, "currentrevision");
          String localId = DatabaseHelper.get().getPlaylistLocalId(id);
          if (localId == null) {
            localId = id;
          }
          Playlist playlist = null;
          if (requestType == InfoRequestData.INFOREQUESTDATA_TYPE_PLAYLISTS_PLAYLISTENTRIES) {
            JsonElement rawEntries = get(o, "playlistEntries");
            if (rawEntries instanceof JsonObject) {
              List<PlaylistEntry> entries =
                  storeRecords((JsonObject) rawEntries, TYPE_PLAYLISTENTRIES, isBackgroundRequest);
              if (entries != null) {
                playlist = Playlist.fromEntriesList(localId, null, null, entries);
                playlist.setFilled(true);
              }
            }
          } else {
            JsonElement entryIds = o.get("playlistEntries");
            if (entryIds instanceof JsonArray) {
              List<Query> queries = new ArrayList<>();
              for (JsonElement entryId : (JsonArray) entryIds) {
                Query query =
                    (Query)
                        findRecord(
                            entryId.getAsString(), TYPE_PLAYLISTENTRIES, isBackgroundRequest);
                queries.add(query);
              }
              playlist = Playlist.fromQueryList(localId, null, null, queries);
              playlist.setFilled(true);
            }
          }
          if (playlist == null) {
            playlist = Playlist.get(localId);
          }
          playlist.setName(title);
          playlist.setCurrentRevision(currentrevision);
          playlist.setHatchetId(id);
          JsonElement popularArtists = get(o, "popularArtists");
          if (popularArtists instanceof JsonArray) {
            ArrayList<String> topArtistNames = new ArrayList<>();
            for (JsonElement popularArtist : (JsonArray) popularArtists) {
              String artistId = popularArtist.getAsString();
              Artist artist = (Artist) findRecord(artistId, TYPE_ARTISTS, isBackgroundRequest);
              if (artist != null) {
                topArtistNames.add(artist.getName());
              }
            }
            playlist.setTopArtistNames(topArtistNames.toArray(new String[topArtistNames.size()]));
          }
          mCache.get(TYPE_PLAYLISTS).put(id, playlist);
          if (resultType == TYPE_PLAYLISTS) {
            results.add(playlist);
          }
        }
      }
    }
    elements = object.get("playbacklogEntries");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          Query query = (Query) mCache.get(TYPE_PLAYLISTENTRIES).get(id);
          if (query == null) {
            String trackId = getAsString(o, "track");
            query = (Query) findRecord(trackId, TYPE_TRACKS, isBackgroundRequest);
            mCache.get(TYPE_PLAYLISTENTRIES).put(id, query);
          }
          if (resultType == TYPE_PLAYLISTENTRIES) {
            results.add(query);
          }
        }
      }
    }
    elements = object.get("playbacklogs");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          JsonArray playbacklogEntries = get(o, "playbacklogEntries").getAsJsonArray();
          ArrayList<Query> queries = new ArrayList<>();
          for (JsonElement entry : playbacklogEntries) {
            String entryId = entry.getAsString();
            Query query = (Query) findRecord(entryId, TYPE_PLAYLISTENTRIES, isBackgroundRequest);
            queries.add(query);
          }
          Playlist playlist =
              Playlist.fromQueryList(
                  TomahawkMainActivity.getLifetimeUniqueStringId(), "Playbacklog", null, queries);
          playlist.setHatchetId(id);
          playlist.setFilled(true);
          mCache.get(TYPE_PLAYLISTS).put(id, playlist);
          if (resultType == TYPE_PLAYLISTS) {
            results.add(playlist);
          }
        }
      }
    }
    elements = object.get("socialActions");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          SocialAction socialAction = (SocialAction) mCache.get(TYPE_SOCIALACTIONS).get(id);
          if (socialAction == null) {
            socialAction = SocialAction.get(id);
            String action = getAsString(o, "action");
            socialAction.setAction(action);
            String date = getAsString(o, "date");
            socialAction.setDate(ISO8601Utils.parse(date));
            String actionType = getAsString(o, "type");
            socialAction.setType(actionType);
            String trackId = getAsString(o, "track");
            if (trackId != null) {
              Query query = (Query) findRecord(trackId, TYPE_TRACKS, isBackgroundRequest);
              socialAction.setQuery(query);
            }
            String artistId = getAsString(o, "artist");
            if (artistId != null) {
              Artist artist = (Artist) findRecord(artistId, TYPE_ARTISTS, isBackgroundRequest);
              socialAction.setArtist(artist);
            }
            String albumId = getAsString(o, "album");
            if (albumId != null) {
              Album album = (Album) findRecord(albumId, TYPE_ALBUMS, isBackgroundRequest);
              socialAction.setAlbum(album);
            }
            String userId = getAsString(o, "user");
            if (userId != null) {
              User user = (User) findRecord(userId, TYPE_USERS, isBackgroundRequest);
              socialAction.setUser(user);
            }
            String targetId = getAsString(o, "target");
            if (targetId != null) {
              User target = (User) findRecord(targetId, TYPE_USERS, isBackgroundRequest);
              socialAction.setTarget(target);
            }
            String playlistId = getAsString(o, "playlist");
            if (playlistId != null) {
              Playlist playlist =
                  (Playlist) findRecord(playlistId, TYPE_PLAYLISTS, isBackgroundRequest);
              socialAction.setPlaylist(playlist);
            }
            mCache.get(TYPE_SOCIALACTIONS).put(id, socialAction);
          }
          if (resultType == TYPE_SOCIALACTIONS) {
            results.add(socialAction);
          }
        }
      }
      if (params != null) {
        User user = (User) findRecord(params.userid, TYPE_USERS, false);
        if (user != null) {
          if (HatchetInfoPlugin.HATCHET_SOCIALACTION_PARAMTYPE_FRIENDSFEED.equals(params.type)) {
            user.setFriendsFeed(results, params.before_date);
          } else {
            user.setSocialActions(results, params.before_date);
          }
        }
      }
    }
    elements = object.get("searchResults");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          SearchResult searchResult = (SearchResult) mCache.get(TYPE_SEARCHRESULTS).get(id);
          if (searchResult == null) {
            float score = getAsFloat(o, "score");
            String trackId = getAsString(o, "track");
            if (trackId != null) {
              Query query = (Query) findRecord(trackId, TYPE_TRACKS, isBackgroundRequest);
              searchResult = new SearchResult(score, query);
            }
            String artistId = getAsString(o, "artist");
            if (artistId != null) {
              Artist artist = (Artist) findRecord(artistId, TYPE_ARTISTS, isBackgroundRequest);
              searchResult = new SearchResult(score, artist);
            }
            String albumId = getAsString(o, "album");
            if (albumId != null) {
              Album album = (Album) findRecord(albumId, TYPE_ALBUMS, isBackgroundRequest);
              searchResult = new SearchResult(score, album);
            }
            String userId = getAsString(o, "user");
            if (userId != null) {
              User user = (User) findRecord(userId, TYPE_USERS, isBackgroundRequest);
              searchResult = new SearchResult(score, user);
            }
            String playlistId = getAsString(o, "playlist");
            if (playlistId != null) {
              Playlist playlist =
                  (Playlist) findRecord(playlistId, TYPE_PLAYLISTS, isBackgroundRequest);
              searchResult = new SearchResult(score, playlist);
            }
            if (searchResult == null) {
              throw new IOException("searchResult contained no actual result object!");
            }
            mCache.get(TYPE_SEARCHRESULTS).put(id, searchResult);
          }
          if (resultType == TYPE_SEARCHRESULTS) {
            results.add(searchResult);
          }
        }
      }
    }
    elements = object.get("searches");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          JsonArray rawSearchResults = get(o, "searchResults").getAsJsonArray();
          ArrayList<SearchResult> searchResults = new ArrayList<>();
          for (JsonElement rawSearchResult : rawSearchResults) {
            String resultId = rawSearchResult.getAsString();
            SearchResult searchResult =
                (SearchResult) findRecord(resultId, TYPE_SEARCHRESULTS, isBackgroundRequest);
            searchResults.add(searchResult);
          }
          Search search = new Search(searchResults);
          mCache.get(TYPE_SEARCHES).put(id, search);
          if (resultType == TYPE_SEARCHES) {
            results.add(search);
          }
        }
      }
    }
    elements = object.get("relationships");
    if (elements instanceof JsonArray) {
      for (JsonElement element : (JsonArray) elements) {
        if (element instanceof JsonObject) {
          JsonObject o = (JsonObject) element;
          String id = getAsString(o, "id");
          String type = getAsString(o, "type");
          if (type.equals(HatchetInfoPlugin.HATCHET_RELATIONSHIPS_TYPE_LOVE)) {
            String userId = getAsString(o, "user");
            User user = (User) findRecord(userId, TYPE_USERS, isBackgroundRequest);
            String trackId = getAsString(o, "targetTrack");
            if (trackId != null) {
              Query query = (Query) findRecord(trackId, TYPE_TRACKS, isBackgroundRequest);
              user.putRelationShipId(query, id);
            }
            String albumId = getAsString(o, "targetAlbum");
            if (albumId != null) {
              Album album = (Album) findRecord(albumId, TYPE_ALBUMS, isBackgroundRequest);
              user.putRelationShipId(album, id);
            }
            String artistId = getAsString(o, "targetArtist");
            if (artistId != null) {
              Artist artist = (Artist) findRecord(artistId, TYPE_ARTISTS, isBackgroundRequest);
              user.putRelationShipId(artist, id);
            }
          }
        }
      }
    }
    return results;
  }