repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-facebook-v3/src/main/java/rx/parse2/ParseFacebookObservable.java
rxparse2-facebook-v3/src/main/java/rx/parse2/ParseFacebookObservable.java
/* * Copyright (C) 2015 8tory, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.parse2; import android.app.Activity; import com.parse.ParseFacebookUtils; import com.parse.ParseUser; import java.util.Collection; import java.util.Date; import io.reactivex.Completable; import io.reactivex.Single; import io.reactivex.annotations.CheckReturnValue; import io.reactivex.annotations.NonNull; import rx.bolts2.RxTask; public class ParseFacebookObservable { @NonNull public static Completable link(@NonNull final ParseUser user, @NonNull final Activity activity) { return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, activity)); } @NonNull public static Completable link(@NonNull final ParseUser user, @NonNull final Activity activity, int activityCode) { return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, activity, activityCode)); } @NonNull public static Completable link(@NonNull final ParseUser user, @NonNull final Collection<String> permissions, @NonNull final Activity activity) { return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, permissions, activity)); } @NonNull public static Completable link(@NonNull final ParseUser user, @NonNull final Collection<String> permissions, @NonNull final Activity activity, int activityCode) { return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, permissions, activity, activityCode)); } @NonNull public static Completable link(@NonNull final ParseUser user, @NonNull final String facebookId, @NonNull final String accessToken, @NonNull final Date expirationDate) { return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, facebookId, accessToken, expirationDate)); } @CheckReturnValue @NonNull public static Single<ParseUser> logIn(@NonNull final Collection<String> permissions, Activity activity, int activityCode) { return RxTask.single(() -> ParseFacebookUtils.logInInBackground(permissions, activity, activityCode)); } @CheckReturnValue @NonNull public static Single<ParseUser> logIn(@NonNull final Collection<String> permissions, @NonNull final Activity activity) { // package class com.parse.FacebookAuthenticationProvider.DEFAULT_AUTH_ACTIVITY_CODE // private com.facebook.android.Facebook.DEFAULT_AUTH_ACTIVITY_CODE = 32665 return logIn(permissions, activity, 32665); } @CheckReturnValue @NonNull public static Single<ParseUser> logIn(@NonNull final String facebookId, @NonNull final String accessToken, @NonNull final Date expirationDate) { return RxTask.single(() -> ParseFacebookUtils.logInInBackground(facebookId, accessToken, expirationDate)); } @NonNull public static Completable saveLatestSessionData(@NonNull final ParseUser user) { return RxTask.completable(() -> ParseFacebookUtils.saveLatestSessionDataInBackground(user)); } @NonNull public static Completable unlink(@NonNull final ParseUser user) { return RxTask.completable(() -> ParseFacebookUtils.unlinkInBackground(user)); } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-facebook-v4/src/main/java/rx/parse2/ParseFacebookObservable.java
rxparse2-facebook-v4/src/main/java/rx/parse2/ParseFacebookObservable.java
/* * Copyright (C) 2015 8tory, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.parse2; import android.app.Activity; import android.support.v4.app.Fragment; import com.parse.ParseFacebookUtils; import com.parse.ParseUser; import java.util.Collection; import io.reactivex.Completable; import io.reactivex.Single; import io.reactivex.annotations.CheckReturnValue; import io.reactivex.annotations.NonNull; import rx.bolts2.RxTask; public class ParseFacebookObservable { @NonNull public static Completable link(@NonNull final ParseUser user, @NonNull final com.facebook.AccessToken accessToken) { return RxTask.completable(() -> ParseFacebookUtils.linkInBackground(user, accessToken)); } @NonNull public static Completable linkWithPublishPermissions(@NonNull final ParseUser user, @NonNull final Activity activity, @NonNull final Collection<String> permissions) { return RxTask.completable(() -> ParseFacebookUtils.linkWithPublishPermissionsInBackground(user, activity, permissions)); } @NonNull public static Completable linkWithPublishPermissions(@NonNull final ParseUser user, @NonNull final Fragment fragment, @NonNull final Collection<String> permissions) { return RxTask.completable(() -> ParseFacebookUtils.linkWithPublishPermissionsInBackground(user, fragment, permissions)); } @NonNull public static Completable linkWithReadPermissions(@NonNull final ParseUser user, @NonNull final Activity activity, @NonNull final Collection<String> permissions) { return RxTask.completable(() -> ParseFacebookUtils.linkWithReadPermissionsInBackground(user, activity, permissions)); } @NonNull public static Completable linkWithReadPermissions(@NonNull final ParseUser user, @NonNull final Fragment fragment, @NonNull final Collection<String> permissions) { return RxTask.completable(() -> ParseFacebookUtils.linkWithReadPermissionsInBackground(user, fragment, permissions)); } @NonNull @CheckReturnValue public static Single<ParseUser> logIn(@NonNull final com.facebook.AccessToken accessToken) { return RxTask.single(() -> ParseFacebookUtils.logInInBackground(accessToken)); } @NonNull @CheckReturnValue public static Single<ParseUser> logInWithPublishPermissions(@NonNull final Activity activity, @NonNull final Collection<String> permissions) { return RxTask.single(() -> ParseFacebookUtils.logInWithPublishPermissionsInBackground(activity, permissions)); } @NonNull @CheckReturnValue public static Single<ParseUser> logInWithPublishPermissions(@NonNull final Fragment fragment, @NonNull final Collection<String> permissions) { return RxTask.single(() -> ParseFacebookUtils.logInWithPublishPermissionsInBackground(fragment, permissions)); } @NonNull @CheckReturnValue public static Single<ParseUser> logInWithReadPermissions(@NonNull final Activity activity, @NonNull final Collection<String> permissions) { return RxTask.single(() -> ParseFacebookUtils.logInWithReadPermissionsInBackground(activity, permissions)); } @NonNull @CheckReturnValue public static Single<ParseUser> logInWithReadPermissions(@NonNull final Fragment fragment, @NonNull final Collection<String> permissions) { return RxTask.single(() -> ParseFacebookUtils.logInWithReadPermissionsInBackground(fragment, permissions)); } @NonNull public static Completable unlink(@NonNull final ParseUser user) { return RxTask.completable(() -> ParseFacebookUtils.unlinkInBackground(user)); } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v4/src/main/java/rx/parse/app/MainFragment.java
rxparse2-app-v4/src/main/java/rx/parse/app/MainFragment.java
package rx.parse2.app; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import com.parse.ParseUser; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; import rx.android.app.AppObservable; import rx.functions.Action1; import rx.functions.Func2; import rx.parse2.ParseObservable; //import android.support.v4.app.NavUtils; //import android.support.v7.widget.StaggeredGridLayoutManager; //import android.support.v7.widget.Toolbar; public class MainFragment extends Fragment { @InjectView(R.id.list) public RecyclerView listView; @InjectView(R.id.loading) public SwipeRefreshLayout loading; private Handler handler; private ListRecyclerAdapter<ParseUser, ParseUserViewHolder> listAdapter; private SwipeRefreshLayout.OnRefreshListener refresher; private static final String ARG_SECTION_NUMBER = "section_number"; public static MainFragment newInstance(int sectionNumber) { MainFragment fragment = new MainFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public MainFragment() { handler = new Handler(); } @Override public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main, container, false); ButterKnife.inject(this, view); listAdapter = ListRecyclerAdapter.create(); listAdapter.createViewHolder(new Func2<ViewGroup, Integer, ParseUserViewHolder>() { @Override public ParseUserViewHolder call(@Nullable ViewGroup viewGroup, Integer position) { android.util.Log.d("RxParse", "ParseUserViewHolder"); return new ParseUserViewHolder(inflater.inflate(R.layout.item_parse_user, viewGroup, false)); } }); listView.setLayoutManager(new android.support.v7.widget.LinearLayoutManager(getActivity())); listView.setAdapter(listAdapter); refresher = new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { loading.setRefreshing(true); AppObservable.bindFragment(MainFragment.this, ParseObservable.find(ParseUser.getQuery())) .doOnNext(new Action1<ParseUser>() { @Override public void call(final ParseUser user) { android.util.Log.d("RxParse", "onNext: " + user.getObjectId()); } }) .toList() .subscribe(new Action1<List<ParseUser>>() { @Override public void call(final List<ParseUser> users) { loading.setRefreshing(false); android.util.Log.d("RxParse", "subscribe: " + users); handler.post(new Runnable() { @Override public void run() { listAdapter.getList().clear(); listAdapter.getList().addAll(users); listAdapter.notifyDataSetChanged(); } }); } }); } }; loading.setOnRefreshListener(refresher); handler.post(new Runnable() { @Override public void run() { refresher.onRefresh(); } }); return view; } public static class ParseUserViewHolder extends BindViewHolder<ParseUser> { @InjectView(R.id.icon) public SimpleDraweeView icon; @InjectView(R.id.text1) public TextView text1; public ParseUserViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); }; @Override public void onBind(int position, ParseUser item) { android.util.Log.d("RxParse", "onBind"); String email = item.getEmail() != null ? item.getEmail() : ""; if (!android.text.TextUtils.isEmpty(email)) { icon.setImageURI(Uri.parse("http://gravatar.com/avatar/" + MD5Util.md5Hex(email))); } text1.setText(email + ", " + item.getObjectId()); } } // ref. https://en.gravatar.com/site/implement/images/java/ public static class MD5Util { public static String hex(byte[] array) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } public static String md5Hex(String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return hex(md.digest(message.getBytes("CP1252"))); } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return null; } } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v4/src/main/java/rx/parse/app/BindViewHolder.java
rxparse2-app-v4/src/main/java/rx/parse/app/BindViewHolder.java
package rx.parse2.app; import android.view.View; import android.support.v7.widget.RecyclerView; public abstract class BindViewHolder<T> extends RecyclerView.ViewHolder { public BindViewHolder(View itemView) { super(itemView); } public abstract void onBind(int position, T item); }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v4/src/main/java/rx/parse/app/MainActivity.java
rxparse2-app-v4/src/main/java/rx/parse/app/MainActivity.java
package rx.parse2.app; import java.util.Locale; //import android.support.v7.app.ActionBarActivity; import android.support.v7.app.AppCompatActivity; //import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.os.Bundle; import android.support.v4.view.ViewPager; import butterknife.InjectView; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { @InjectView(R.id.pager) public ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); mViewPager.setAdapter(new SimpleFragmentPagerAdapter(getSupportFragmentManager())); } public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter { public SimpleFragmentPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return MainFragment.newInstance(position + 1); } @Override public int getCount() { return 1; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); default: return null; } } } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v4/src/main/java/rx/parse/app/ListRecyclerAdapter.java
rxparse2-app-v4/src/main/java/rx/parse/app/ListRecyclerAdapter.java
package rx.parse2.app; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.util.ArrayList; import java.util.Collections; import java.util.List; import rx.functions.Action3; import rx.functions.Func2; public class ListRecyclerAdapter<T, VH extends BindViewHolder<T>> extends RecyclerView.Adapter<VH> { private List<T> mList = Collections.emptyList(); protected Action3<VH, Integer, T> mOnBindViewHolder; protected Func2<ViewGroup, Integer, VH> mOnCreateViewHolder; private boolean onBindViewHolderSupered; public ListRecyclerAdapter(List<T> list) { mList = list; } public static <R, VHH extends BindViewHolder<R>> ListRecyclerAdapter<R, VHH> create() { return create(new ArrayList<R>()); } public static <R, VHH extends BindViewHolder<R>> ListRecyclerAdapter<R, VHH> create(List<R> list) { return new ListRecyclerAdapter<>(list); } @Override public VH onCreateViewHolder(ViewGroup parent, int viewType) { if (mOnCreateViewHolder != null) return mOnCreateViewHolder.call(parent, viewType); return null; } public ListRecyclerAdapter<T, VH> createViewHolder(Func2<ViewGroup, Integer, VH> onCreateViewHolder) { mOnCreateViewHolder = onCreateViewHolder; return this; } @Override public void onBindViewHolder(VH viewHolder, int position) { // final, DO NOT Override until certainly onBindViewHolderSupered = false; onBindViewHolder(viewHolder, position, mList.get(position)); if (!onBindViewHolderSupered) throw new IllegalArgumentException("super.onBindViewHolder() not be called"); } // super me public void onBindViewHolder(VH viewHolder, int position, T item) { // final, DO NOT Override until certainly onBindViewHolderSupered = true; if (mOnBindViewHolder == null) { mOnBindViewHolder = new Action3<VH, Integer, T>() { @Override public void call(VH vh, Integer i, T t) { vh.onBind(i, t); } }; } mOnBindViewHolder.call(viewHolder, position, item); } public ListRecyclerAdapter<T, VH> bindViewHolder(Action3<VH, Integer, T> onBindViewHolder) { mOnBindViewHolder = onBindViewHolder; return this; } @Override public int getItemCount() { int i = mList.size(); return i; } public List<T> getList() { return mList; } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v4/src/main/java/rx/parse/app/RxParseApplication.java
rxparse2-app-v4/src/main/java/rx/parse/app/RxParseApplication.java
package rx.parse2.app; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; import com.parse.Parse; //import android.support.multidex.MultiDexApplication; //import timber.log.Timber; //import com.sromku.simple.fb.Permission; //import com.sromku.simple.fb.SimpleFacebook; //import com.sromku.simple.fb.SimpleFacebookConfiguration; public class RxParseApplication extends Application { @Override public void onCreate() { super.onCreate(); //Timber.plant(new Timber.DebugTree()); //ParseACL defaultACL = new ParseACL(); //ParseACL.setDefaultACL(defaultACL, true); //Parse.enableLocalDatastore(getApplicationContext()); Parse.initialize(this, getString(R.string.parse_app_id), getString(R.string.parse_client_key)); //ParseInstallation.getCurrentInstallation().saveInBackground(); //ParseFacebookUtils.initialize(getString(R.string.app_id)); // //ParseInstallation.getCurrentInstallation().saveInBackground(); Fresco.initialize(this); } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v4/src/androidTest/java/rx/parse/app/ApplicationTest.java
rxparse2-app-v4/src/androidTest/java/rx/parse/app/ApplicationTest.java
package rx.parse2.app; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v3/src/main/java/rx/parse2/app/MainFragment.java
rxparse2-app-v3/src/main/java/rx/parse2/app/MainFragment.java
package rx.parse2.app; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import com.parse.ParseUser; import com.trello.rxlifecycle2.components.support.RxFragment; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.concurrent.Callable; import butterknife.ButterKnife; import butterknife.InjectView; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import rx.parse2.ParseObservable; public class MainFragment extends RxFragment { @InjectView(R.id.list) public RecyclerView listView; @InjectView(R.id.loading) public SwipeRefreshLayout loading; private Handler handler; private ListRecyclerAdapter<ParseUser, ParseUserViewHolder> listAdapter; private SwipeRefreshLayout.OnRefreshListener refresher; private static final String ARG_SECTION_NUMBER = "section_number"; public static MainFragment newInstance(int sectionNumber) { MainFragment fragment = new MainFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public MainFragment() { handler = new Handler(); } @Override public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main, container, false); ButterKnife.inject(this, view); listAdapter = ListRecyclerAdapter.create(); listAdapter.createViewHolder(new ListRecyclerAdapter.Func2<ViewGroup, Integer, ParseUserViewHolder>() { @Override public ParseUserViewHolder call(@Nullable ViewGroup viewGroup, Integer position) { android.util.Log.d("RxParse", "ParseUserViewHolder"); return new ParseUserViewHolder(inflater.inflate(R.layout.item_parse_user, viewGroup, false)); } }); listView.setLayoutManager(new android.support.v7.widget.LinearLayoutManager(getActivity())); listView.setAdapter(listAdapter); refresher = new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { loading.setRefreshing(true); ParseObservable.find(ParseUser.getQuery()) .compose(MainFragment.this.<ParseUser>bindToLifecycle()) .doOnNext(new Consumer<ParseUser>() { @Override public void accept(final ParseUser user) { android.util.Log.d("RxParse", "onNext: " + user.getObjectId()); } }) .toList() .subscribe(new Consumer<List<? super ParseUser>>() { @Override public void accept(final List<? super ParseUser> users) { loading.setRefreshing(false); android.util.Log.d("RxParse", "subscribe: " + users); handler.post(new Runnable() { @Override public void run() { listAdapter.getList().clear(); listAdapter.getList().addAll((List<ParseUser>) users); listAdapter.notifyDataSetChanged(); } }); } }); } }; loading.setOnRefreshListener(refresher); handler.post(new Runnable() { @Override public void run() { refresher.onRefresh(); } }); return view; } public static class ParseUserViewHolder extends BindViewHolder<ParseUser> { @InjectView(R.id.icon) public SimpleDraweeView icon; @InjectView(R.id.text1) public TextView text1; public ParseUserViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); }; @Override public void onBind(int position, ParseUser item) { android.util.Log.d("RxParse", "onBind"); String email = item.getEmail() != null ? item.getEmail() : ""; if (!android.text.TextUtils.isEmpty(email)) { icon.setImageURI(Uri.parse("http://gravatar.com/avatar/" + MD5Util.md5Hex(email))); } text1.setText(email + ", " + item.getObjectId()); } } // ref. https://en.gravatar.com/site/implement/images/java/ public static class MD5Util { public static String hex(byte[] array) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; ++i) { sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3)); } return sb.toString(); } public static String md5Hex(String message) { try { MessageDigest md = MessageDigest.getInstance("MD5"); return hex(md.digest(message.getBytes("CP1252"))); } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } return null; } } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v3/src/main/java/rx/parse2/app/BindViewHolder.java
rxparse2-app-v3/src/main/java/rx/parse2/app/BindViewHolder.java
package rx.parse2.app; import android.view.View; import android.support.v7.widget.RecyclerView; public abstract class BindViewHolder<T> extends RecyclerView.ViewHolder { public BindViewHolder(View itemView) { super(itemView); } public abstract void onBind(int position, T item); }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v3/src/main/java/rx/parse2/app/MainActivity.java
rxparse2-app-v3/src/main/java/rx/parse2/app/MainActivity.java
package rx.parse2.app; import java.util.Locale; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.os.Bundle; import android.support.v4.view.ViewPager; import com.trello.rxlifecycle2.components.support.RxAppCompatActivity; import butterknife.InjectView; import butterknife.ButterKnife; public class MainActivity extends RxAppCompatActivity { @InjectView(R.id.pager) public ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); mViewPager.setAdapter(new SimpleFragmentPagerAdapter(getSupportFragmentManager())); } public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter { public SimpleFragmentPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return MainFragment.newInstance(position + 1); } @Override public int getCount() { return 1; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch (position) { case 0: return getString(R.string.title_section1).toUpperCase(l); default: return null; } } } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v3/src/main/java/rx/parse2/app/ListRecyclerAdapter.java
rxparse2-app-v3/src/main/java/rx/parse2/app/ListRecyclerAdapter.java
package rx.parse2.app; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ListRecyclerAdapter<T, VH extends BindViewHolder<T>> extends RecyclerView.Adapter<VH> { private List<T> mList = Collections.emptyList(); public interface Action3<T, T2, T3> { void call(T t, T2 t2, T3 t3); } public interface Func2<T, T2, R> { R call(T t, T2 t2); } protected Action3<VH, Integer, T> mOnBindViewHolder; protected Func2<ViewGroup, Integer, VH> mOnCreateViewHolder; private boolean onBindViewHolderSupered; public ListRecyclerAdapter(List<T> list) { mList = list; } public static <R, VHH extends BindViewHolder<R>> ListRecyclerAdapter<R, VHH> create() { return create(new ArrayList<R>()); } public static <R, VHH extends BindViewHolder<R>> ListRecyclerAdapter<R, VHH> create(List<R> list) { return new ListRecyclerAdapter<>(list); } @Override public VH onCreateViewHolder(ViewGroup parent, int viewType) { if (mOnCreateViewHolder != null) return mOnCreateViewHolder.call(parent, viewType); return null; } public ListRecyclerAdapter<T, VH> createViewHolder(Func2<ViewGroup, Integer, VH> onCreateViewHolder) { mOnCreateViewHolder = onCreateViewHolder; return this; } @Override public void onBindViewHolder(VH viewHolder, int position) { // final, DO NOT Override until certainly onBindViewHolderSupered = false; onBindViewHolder(viewHolder, position, mList.get(position)); if (!onBindViewHolderSupered) throw new IllegalArgumentException("super.onBindViewHolder() not be called"); } // super me public void onBindViewHolder(VH viewHolder, int position, T item) { // final, DO NOT Override until certainly onBindViewHolderSupered = true; if (mOnBindViewHolder == null) { mOnBindViewHolder = new Action3<VH, Integer, T>() { @Override public void call(VH vh, Integer i, T t) { vh.onBind(i, t); } }; } mOnBindViewHolder.call(viewHolder, position, item); } public ListRecyclerAdapter<T, VH> bindViewHolder(Action3<VH, Integer, T> onBindViewHolder) { mOnBindViewHolder = onBindViewHolder; return this; } @Override public int getItemCount() { int i = mList.size(); return i; } public List<? super T> getList() { return mList; } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v3/src/main/java/rx/parse2/app/RxParseApplication.java
rxparse2-app-v3/src/main/java/rx/parse2/app/RxParseApplication.java
package rx.parse2.app; import android.app.Application; import com.facebook.drawee.backends.pipeline.Fresco; import com.parse.Parse; //import android.support.multidex.MultiDexApplication; //import timber.log.Timber; //import com.sromku.simple.fb.Permission; //import com.sromku.simple.fb.SimpleFacebook; //import com.sromku.simple.fb.SimpleFacebookConfiguration; public class RxParseApplication extends Application { @Override public void onCreate() { super.onCreate(); //Timber.plant(new Timber.DebugTree()); //ParseACL defaultACL = new ParseACL(); //ParseACL.setDefaultACL(defaultACL, true); //Parse.enableLocalDatastore(getApplicationContext()); Parse.initialize(this, getString(R.string.parse_app_id), getString(R.string.parse_client_key)); //ParseInstallation.getCurrentInstallation().saveInBackground(); //ParseFacebookUtils.initialize(getString(R.string.app_id)); // //ParseInstallation.getCurrentInstallation().saveInBackground(); Fresco.initialize(this); } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
yongjhih/RxParse
https://github.com/yongjhih/RxParse/blob/48ae27ab39b39cb78f32d22c9335751a4de29ee2/rxparse2-app-v3/src/androidTest/java/rx/parse2/app/ApplicationTest.java
rxparse2-app-v3/src/androidTest/java/rx/parse2/app/ApplicationTest.java
package rx.parse2.app; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
java
Apache-2.0
48ae27ab39b39cb78f32d22c9335751a4de29ee2
2026-01-05T02:41:47.442106Z
false
HugoSMPnet/HugoSMP-Client
https://github.com/HugoSMPnet/HugoSMP-Client/blob/e4b0d2dd64e33bfdba2a98e1e0cc6a5034447ce2/src/main/java/com/example/ExampleMod.java
src/main/java/com/example/ExampleMod.java
package com.example; import net.fabricmc.api.ModInitializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExampleMod implements ModInitializer { public static final String MOD_ID = "modid"; // This logger is used to write text to the console and the log file. // It is considered best practice to use your mod id as the logger's name. // That way, it's clear which mod wrote info, warnings, and errors. public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); @Override public void onInitialize() { // This code runs as soon as Minecraft is in a mod-load-ready state. // However, some things (like resources) may still be uninitialized. // Proceed with mild caution. LOGGER.info("Hello Fabric world!"); } }
java
CC0-1.0
e4b0d2dd64e33bfdba2a98e1e0cc6a5034447ce2
2026-01-05T02:41:49.301701Z
false
HugoSMPnet/HugoSMP-Client
https://github.com/HugoSMPnet/HugoSMP-Client/blob/e4b0d2dd64e33bfdba2a98e1e0cc6a5034447ce2/src/main/java/com/example/mixin/ExampleMixin.java
src/main/java/com/example/mixin/ExampleMixin.java
package com.example.mixin; import net.minecraft.server.MinecraftServer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(MinecraftServer.class) public class ExampleMixin { @Inject(at = @At("HEAD"), method = "loadLevel") private void init(CallbackInfo info) { // This code is injected into the start of MinecraftServer.loadLevel()V } }
java
CC0-1.0
e4b0d2dd64e33bfdba2a98e1e0cc6a5034447ce2
2026-01-05T02:41:49.301701Z
false
HugoSMPnet/HugoSMP-Client
https://github.com/HugoSMPnet/HugoSMP-Client/blob/e4b0d2dd64e33bfdba2a98e1e0cc6a5034447ce2/src/client/java/com/example/ExampleModClient.java
src/client/java/com/example/ExampleModClient.java
package com.example; import net.fabricmc.api.ClientModInitializer; public class ExampleModClient implements ClientModInitializer { @Override public void onInitializeClient() { // This entrypoint is suitable for setting up client-specific logic, such as rendering. } }
java
CC0-1.0
e4b0d2dd64e33bfdba2a98e1e0cc6a5034447ce2
2026-01-05T02:41:49.301701Z
false
HugoSMPnet/HugoSMP-Client
https://github.com/HugoSMPnet/HugoSMP-Client/blob/e4b0d2dd64e33bfdba2a98e1e0cc6a5034447ce2/src/client/java/com/example/mixin/client/ExampleClientMixin.java
src/client/java/com/example/mixin/client/ExampleClientMixin.java
package com.example.mixin.client; import net.minecraft.client.Minecraft; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(Minecraft.class) public class ExampleClientMixin { @Inject(at = @At("HEAD"), method = "run") private void init(CallbackInfo info) { // This code is injected into the start of Minecraft.run()V } }
java
CC0-1.0
e4b0d2dd64e33bfdba2a98e1e0cc6a5034447ce2
2026-01-05T02:41:49.301701Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/EndGameDialogFragment.java
app/src/main/java/com/gunshippenguin/openflood/EndGameDialogFragment.java
package com.gunshippenguin.openflood; import android.app.Activity; import android.app.Dialog; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.content.SharedPreferences; import android.preference.PreferenceManager; /** * Dialog Fragment that is displayed to the user upon a win or loss. */ public class EndGameDialogFragment extends DialogFragment { public interface EndGameDialogFragmentListener { public void onReplayClick(); public void onNewGameClick(); public void onGetSeedClick(); } EndGameDialogFragmentListener listener; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get steps and maxSteps from the arguments int steps = getArguments().getInt("steps"); boolean gameWon = getArguments().getBoolean("game_won"); // Inflate layout LayoutInflater inflater = getActivity().getLayoutInflater(); View layout = inflater.inflate(R.layout.dialog_endgame, null); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setView(layout); final AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(false); // Set up the dialog's title TextView endgameTitleTextView = (TextView) layout.findViewById(R.id.endGameTitle); if (gameWon) { endgameTitleTextView.setText(getString(R.string.endgame_win_title)); } else { endgameTitleTextView.setText(getString(R.string.endgame_lose_title)); } // Set up dialog's other text views TextView endgameTextView = (TextView) layout.findViewById(R.id.endGameText); TextView highScoreTextView = (TextView) layout.findViewById(R.id.highScoreText); ImageView highScoreMedalImageView = (ImageView) layout.findViewById(R.id.highScoreMedalImageView); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); HighScoreManager highScoreManager = new HighScoreManager(sp); int boardSize = sp.getInt("board_size", -1); int numColors = sp.getInt("num_colors", -1); if (gameWon) { String stepsString = String.format(getString(R.string.endgame_win_text), steps); endgameTextView.setText(stepsString); if (highScoreManager.isHighScore(boardSize, numColors, steps)) { highScoreManager.setHighScore(boardSize, numColors, steps); highScoreTextView.setText(getString(R.string.endgame_new_highscore_text)); highScoreTextView.setTypeface(null, Typeface.BOLD); } else { highScoreTextView.setText(String.format(getString(R.string.endgame_old_highscore_text), highScoreManager.getHighScore(boardSize, numColors))); highScoreMedalImageView.setVisibility(View.GONE); } } else { endgameTextView.setVisibility(View.GONE); if (highScoreManager.highScoreExists(boardSize, numColors)) { highScoreTextView.setText(String.format(getString(R.string.endgame_old_highscore_text), highScoreManager.getHighScore(boardSize, numColors))); highScoreMedalImageView.setVisibility(View.GONE); } else { highScoreTextView.setVisibility(View.GONE); highScoreMedalImageView.setVisibility(View.GONE); } } // Set up the get seed button TextView seedTextView = (TextView) layout.findViewById(R.id.seedTextView); seedTextView.setText(String.format(getString(R.string.endgame_seed), getArguments().getString("seed"))); seedTextView.setTextColor(Color.BLUE); seedTextView.setPaintFlags(seedTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); seedTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onGetSeedClick(); } }); // Show the replay butotn if the game has been lost Button replayButton = (Button) layout.findViewById(R.id.replayButton); if (gameWon) { replayButton.setVisibility(View.GONE); } else { replayButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onReplayClick(); dismiss(); } }); } // Set up the new game button callback Button newGameButton = (Button) layout.findViewById(R.id.newGameButton); newGameButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onNewGameClick(); dismiss(); } }); return dialog; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { listener = (EndGameDialogFragmentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement EndGameDialogListener"); } } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/Game.java
app/src/main/java/com/gunshippenguin/openflood/Game.java
package com.gunshippenguin.openflood; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Random; /** * Class representing a game in progress. */ public class Game { private int board[][]; private int boardSize; private int numColors; private int steps = 0; private int maxSteps; private String seed; private static final String SEED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"; private static final int SEED_LENGTH_LOWER = 5; private static final int SEED_LENGTH_UPPER = 15; public Game(int boardSize, int numColors) { // Initialize board this.boardSize = boardSize; this.numColors = numColors; this.seed = generateRandomSeed(); initBoard(); initMaxSteps(); } public Game(int boardSize, int numColors, String seed) { // Initialize board this.boardSize = boardSize; this.numColors = numColors; this.seed = seed; initBoard(); initMaxSteps(); } public Game(int[][] board, int boardSize, int numColors, int steps, String seed) { // Restore board this.board = board; this.boardSize = boardSize; this.numColors = numColors; this.steps = steps; this.seed = seed; initMaxSteps(); } private String generateRandomSeed() { Random rand = new Random(System.currentTimeMillis()); String currSeed = ""; for(int i=0;i<rand.nextInt((SEED_LENGTH_UPPER-SEED_LENGTH_LOWER)+1)+SEED_LENGTH_LOWER;i++) { currSeed += SEED_CHARS.charAt(rand.nextInt(SEED_CHARS.length())); } return currSeed; } public int[][] getBoard() { return board; } public int getColor(int x, int y) { return board[y][x]; } public int getBoardDimensions() { return boardSize; } public String getSeed() { return seed; } public int getSteps() { return steps; } public int getMaxSteps() { return maxSteps; } private void initBoard() { board = new int[boardSize][boardSize]; Random r = new Random(seed.hashCode()); for (int y = 0; y < boardSize; y++) { for (int x = 0; x < boardSize; x++) { board[y][x] = r.nextInt(numColors); } } return; } private void initMaxSteps() { maxSteps = (int) 30 * (boardSize * numColors) / (17 * 6); } public void flood(int replacementColor) { int targetColor = board[0][0]; if (targetColor == replacementColor) { return; } Queue<BoardPoint> queue = new LinkedList<BoardPoint>(); ArrayList<BoardPoint> processed = new ArrayList<BoardPoint>(); queue.add(new BoardPoint(0, 0)); BoardPoint currPoint; while (!queue.isEmpty()) { currPoint = queue.remove(); if (board[currPoint.getY()][currPoint.getX()] == targetColor) { board[currPoint.getY()][currPoint.getX()] = replacementColor; if (currPoint.getX() != 0 && !processed.contains(new BoardPoint(currPoint.getX() - 1, currPoint.getY()))) { queue.add(new BoardPoint(currPoint.getX() - 1, currPoint.getY())); } if (currPoint.getX() != boardSize - 1 && !processed.contains(new BoardPoint(currPoint.getX() + 1, currPoint.getY()))) { queue.add(new BoardPoint(currPoint.getX() + 1, currPoint.getY())); } if (currPoint.getY() != 0 && !processed.contains(new BoardPoint(currPoint.getX(), currPoint.getY() - 1))) { queue.add(new BoardPoint(currPoint.getX(), currPoint.getY() - 1)); } if (currPoint.getY() != boardSize - 1 && !processed.contains(new BoardPoint(currPoint.getX(), currPoint.getY() + 1))) { queue.add(new BoardPoint(currPoint.getX(), currPoint.getY() + 1)); } } } steps++; return; } public boolean checkWin() { int lastColor = board[0][0]; for (int y = 0; y < board.length; y++) { for (int x = 0; x < board.length; x++) { if (lastColor != board[y][x]) { return false; } lastColor = board[y][x]; } } return true; } private class BoardPoint { int x, y; public BoardPoint(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } @Override public boolean equals(Object obj) { if (!BoardPoint.class.isAssignableFrom(obj.getClass())) { return false; } BoardPoint bp = (BoardPoint) obj; return (this.x == bp.getX()) && (this.y == bp.getY()); } } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/HighScoreManager.java
app/src/main/java/com/gunshippenguin/openflood/HighScoreManager.java
package com.gunshippenguin.openflood; import android.content.SharedPreferences; public class HighScoreManager { SharedPreferences sp; public HighScoreManager(SharedPreferences sp) { this.sp = sp; } public boolean isHighScore(int boardSize, int numColors, int steps) { if (!highScoreExists(boardSize, numColors)) { return true; } else { return sp.getInt(getKey(boardSize, numColors), -1) > steps; } } public boolean highScoreExists(int boardSize, int numColors) { return sp.contains(getKey(boardSize, numColors)); } public int getHighScore(int boardSize, int numColors) { return sp.getInt(getKey(boardSize, numColors), -1); } public void setHighScore(int boardSize, int numColors, int steps) { SharedPreferences.Editor editor = sp.edit(); editor.putInt(getKey(boardSize, numColors), steps); editor.apply(); } public void removeHighScore(int boardSize, int numColors) { SharedPreferences.Editor editor = sp.edit(); editor.remove(getKey(boardSize, numColors)); editor.apply(); return; } private String getKey(int boardSize, int numColors) { return String.format("highscore_%1$d_%2$d", boardSize, numColors); } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/FloodView.java
app/src/main/java/com/gunshippenguin/openflood/FloodView.java
package com.gunshippenguin.openflood; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.view.View; /** * View that displays the game board to the user. */ public class FloodView extends View { private Game gameToDraw; private int boardSize; private int cellSize; private int xOffset; private int yOffset; private Paint textPaint; private Paint paints[]; public FloodView(Context context, AttributeSet attrs) { super(context, attrs); textPaint = new Paint(); textPaint.setColor(Color.BLACK); textPaint.setTextAlign(Paint.Align.CENTER); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { setDrawingInfo(); return; } private void setDrawingInfo(){ int dimension; if (getWidth() > getHeight()) { dimension = getHeight(); } else { dimension = getWidth(); } dimension -= (dimension % boardSize); if (boardSize != 0) { cellSize = dimension / boardSize; xOffset = (getWidth() - dimension) / 2 ; yOffset = (getHeight() - dimension) / 2 ; textPaint.setTextSize(cellSize); } return; } public void setBoardSize(int boardSize) { this.boardSize = boardSize; setDrawingInfo(); return; } public void drawGame(Game game) { gameToDraw = game; invalidate(); return; } public void setPaints(Paint[] paints) { this.paints = paints; invalidate(); return; } @Override protected void onDraw(Canvas c) { if (gameToDraw == null) { return; } // Draw colors for (int y = 0; y < gameToDraw.getBoardDimensions(); y++) { for (int x = 0; x < gameToDraw.getBoardDimensions(); x++) { c.drawRect(x * cellSize + xOffset, y * cellSize + yOffset, (x + 1) * cellSize + xOffset, (y + 1) * cellSize + yOffset, paints[gameToDraw.getColor(x, y)]); } } // Draw numbers if color blind mode is on if (PreferenceManager.getDefaultSharedPreferences(getContext()).getBoolean("color_blind_mode", false)) { String numToDraw; Rect currRect = new Rect(); for (int y = 0; y < gameToDraw.getBoardDimensions(); y++) { for (int x = 0; x < gameToDraw.getBoardDimensions(); x++) { currRect.set(x * cellSize + xOffset, y * cellSize + yOffset, (x + 1) * cellSize + xOffset, (y + 1) * cellSize + yOffset); numToDraw = Integer.toString(gameToDraw.getColor(x, y) + 1); c.drawText(numToDraw, currRect.centerX(), (int) (currRect.centerY() - ((textPaint.descent() + textPaint.ascent()) / 2)), textPaint); } } } return; } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/SettingsActivity.java
app/src/main/java/com/gunshippenguin/openflood/SettingsActivity.java
package com.gunshippenguin.openflood; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.util.TypedValue; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.RadioButton; import android.widget.RadioGroup; /** * Activity allowing the user to configure settings. */ public class SettingsActivity extends AppCompatActivity { CheckBox colorBlindCheckBox, oldColorsCheckBox; int[] boardSizeChoices, numColorsChoices; private int selectedBoardSize, selectedNumColors; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); // Set up the board size RadioGroup RadioGroup boardSizeRadioGroup = (RadioGroup) findViewById(R.id.boardSizeRadioGroup); boardSizeChoices = getResources().getIntArray(R.array.boardSizeChoices); selectedBoardSize = sp.getInt("board_size", getResources().getInteger(R.integer.default_board_size)); for (final int bs : boardSizeChoices) { RadioButton currRadioButton = new RadioButton(this); currRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.small_text_size)); currRadioButton.setText(String.format("%dx%d", bs, bs)); boardSizeRadioGroup.addView(currRadioButton); if (bs == selectedBoardSize) { boardSizeRadioGroup.check(currRadioButton.getId()); } currRadioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SettingsActivity.this.setSelectedBoardSize(bs); } }); } // Set up the num colors RadioGroup RadioGroup numColorsRadioGroup = (RadioGroup) findViewById(R.id.numColorsRadioGroup); numColorsChoices = getResources().getIntArray(R.array.numColorsChoices); selectedNumColors = sp.getInt("num_colors", getResources().getInteger(R.integer.default_num_colors)); for (final int nc : numColorsChoices) { RadioButton currRadioButton = new RadioButton(this); currRadioButton.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.small_text_size)); currRadioButton.setText(Integer.toString(nc)); numColorsRadioGroup.addView(currRadioButton); if (nc == selectedNumColors) { numColorsRadioGroup.check(currRadioButton.getId()); } currRadioButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SettingsActivity.this.setSelectedNumColors(nc); } }); } // Set up the color blind checkbox colorBlindCheckBox = (CheckBox) findViewById(R.id.colorBlindCheckBox); colorBlindCheckBox.setChecked(sp.getBoolean("color_blind_mode", false)); // Set up the old color scheme checkbox oldColorsCheckBox = (CheckBox) findViewById(R.id.oldColorsCheckBox); oldColorsCheckBox.setChecked(sp.getBoolean("use_old_colors", false)); // Set up the clear highscores button Button clearHighScoresButton = (Button) findViewById(R.id.clearHighScoresButton); clearHighScoresButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ClearHighScoresDialogFragment dialog = new ClearHighScoresDialogFragment(); dialog.show(getSupportFragmentManager(), "ClearHighScoresDialogFragment"); } }); // Set up the apply button Button applyButton = (Button) findViewById(R.id.applyButton); applyButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent s = saveSettings(); setResult(RESULT_OK, s); finish(); } }); } private void setSelectedBoardSize(int boardSize) { this.selectedBoardSize = boardSize; } private void setSelectedNumColors(int numColors) { this.selectedNumColors = numColors; } private Intent saveSettings() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor spEditor = sp.edit(); Intent dataIntent = new Intent(); dataIntent.putExtra("gameSettingsChanged", false); dataIntent.putExtra("colorSettingsChanged", false); // Update boardSize int defaultBoardSize = getResources().getInteger(R.integer.default_board_size); if (selectedBoardSize != sp.getInt("board_size", defaultBoardSize)) { dataIntent.putExtra("gameSettingsChanged", true); spEditor.putInt("board_size", selectedBoardSize); } // Update number of colors int defaultNumColors = getResources().getInteger(R.integer.default_num_colors); if (selectedNumColors != sp.getInt("num_colors", defaultNumColors)) { dataIntent.putExtra("gameSettingsChanged", true); spEditor.putInt("num_colors", selectedNumColors); } // Update color blind mode boolean selectedColorBlindMode = colorBlindCheckBox.isChecked(); if (selectedColorBlindMode != sp.getBoolean("color_blind_mode", false)) { dataIntent.putExtra("colorSettingsChanged", true); spEditor.putBoolean("color_blind_mode", selectedColorBlindMode); } // Update whether or not to use the old color scheme boolean selectedOldColorScheme = oldColorsCheckBox.isChecked(); if (selectedOldColorScheme != sp.getBoolean("use_old_colors", false)) { dataIntent.putExtra("colorSettingsChanged", true); spEditor.putBoolean("use_old_colors", selectedOldColorScheme); } spEditor.apply(); return dataIntent; } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/GameActivity.java
app/src/main/java/com/gunshippenguin/openflood/GameActivity.java
package com.gunshippenguin.openflood; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Paint; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; /** * Activity allowing the user to play the actual game. */ public class GameActivity extends AppCompatActivity implements EndGameDialogFragment.EndGameDialogFragmentListener, SeedDialogFragment.SeedDialogFragmentListener { private final int UPDATE_SETTINGS = 1; private Game game; private SharedPreferences sp; private SharedPreferences.Editor spEditor; private FloodView floodView; private TextView stepsTextView; private int lastColor; private boolean gameFinished; // Paints to be used for the board private Paint paints[]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); // Initialize the SharedPreferences and SharedPreferences editor sp = PreferenceManager.getDefaultSharedPreferences(this); spEditor = sp.edit(); // Get the FloodView floodView = (FloodView) findViewById(R.id.floodView); // Initialize the paints array and pass it to the FloodView initPaints(); floodView.setPaints(paints); ImageView settingsButton = (ImageView) findViewById(R.id.settingsButton); settingsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent launchSettingsIntent = new Intent(GameActivity.this, SettingsActivity.class); startActivityForResult(launchSettingsIntent, UPDATE_SETTINGS); } } ); ImageView infoButton = (ImageView) findViewById(R.id.infoButton); infoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent launchSettingsIntent = new Intent(GameActivity.this, InfoActivity.class); startActivity(launchSettingsIntent); } }); ImageView newGameButton = (ImageView) findViewById(R.id.newGameButton); newGameButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { newGame(); } }); newGameButton.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { SeedDialogFragment seedDialogFragment = new SeedDialogFragment(); seedDialogFragment.show(getSupportFragmentManager(), "SeedDialog"); return true; } }); // Get the steps text view stepsTextView = (TextView) findViewById(R.id.stepsTextView); if (sp.contains("state_saved")) { // Restore previous game restoreGame(); } else { // Set up a new game newGame(); } } @Override public void onStop() { super.onStop(); spEditor.putBoolean("state_saved", true); spEditor.putString("state_board", new Gson().toJson(game.getBoard())); spEditor.putInt("state_steps", game.getSteps()); spEditor.putString("state_seed", game.getSeed()); spEditor.apply(); } private int getBoardSize(){ int defaultBoardSize = getResources().getInteger(R.integer.default_board_size); if (!sp.contains("board_size")) { spEditor.putInt("board_size", defaultBoardSize); spEditor.apply(); } return sp.getInt("board_size", defaultBoardSize); } private int getNumColors(){ int defaultNumColors = getResources().getInteger(R.integer.default_num_colors); if (!sp.contains("num_colors")) { spEditor.putInt("num_colors", defaultNumColors); spEditor.apply(); } return sp.getInt("num_colors", defaultNumColors); } private void initPaints() { int[] colors; if (sp.getBoolean("use_old_colors", false)){ colors = getResources().getIntArray(R.array.oldBoardColorScheme); } else { colors = getResources().getIntArray(R.array.boardColorScheme); } paints = new Paint[colors.length]; for (int i = 0; i < colors.length; i++) { paints[i] = new Paint(); paints[i].setColor(colors[i]); } return; } private void initGame() { gameFinished = false; lastColor = game.getColor(0, 0); layoutColorButtons(); stepsTextView.setText(game.getSteps() + " / " + game.getMaxSteps()); floodView.setBoardSize(getBoardSize()); floodView.drawGame(game); } private void newGame() { game = new Game(getBoardSize(), getNumColors()); initGame(); } private void newGame(String seed) { game = new Game(getBoardSize(), getNumColors(), seed); initGame(); } private void restoreGame() { int board[][] = new Gson().fromJson(sp.getString("state_board", null), int[][].class); int steps = sp.getInt("state_steps", 0); String seed = sp.getString("state_seed", null); if (board == null || seed == null) { newGame(); } else { game = new Game(board, getBoardSize(), getNumColors(), steps, seed); initGame(); } } private void layoutColorButtons() { // Add color buttons LinearLayout buttonLayout = (LinearLayout) findViewById(R.id.buttonLayout); buttonLayout.removeAllViews(); int buttonPadding = (int) getResources().getDimension(R.dimen.color_button_padding); for (int i = 0; i < getNumColors(); i++) { final int localI = i; ColorButton newButton = new ColorButton(this); newButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { v.startAnimation(AnimationUtils.loadAnimation(GameActivity.this, R.anim.button_anim)); if (localI != lastColor) { doColor(localI); } } }); newButton.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f)); newButton.setPadding(buttonPadding, buttonPadding, buttonPadding, buttonPadding); newButton.setColorBlindText(Integer.toString(i + 1)); newButton.setColor(paints[i].getColor()); buttonLayout.addView(newButton); } return; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == UPDATE_SETTINGS) { if (resultCode == RESULT_OK) { Bundle extras = data.getExtras(); // Only start a new game if the settings have been changed if (extras.getBoolean("gameSettingsChanged")) { newGame(); } if (extras.getBoolean("colorSettingsChanged")) { initPaints(); floodView.setPaints(paints); layoutColorButtons(); } } } } private void doColor(int color) { if (gameFinished || game.getSteps() >= game.getMaxSteps()) { return; } game.flood(color); floodView.drawGame(game); lastColor = color; stepsTextView.setText(game.getSteps() + " / " + game.getMaxSteps()); if (game.checkWin() || game.getSteps() == game.getMaxSteps()) { gameFinished = true; showEndGameDialog(); } return; } public void onNewGameClick() { newGame(); return; } public void onReplayClick() { newGame(game.getSeed()); } public void onLaunchSeedDialogClick() { SeedDialogFragment seedDialogFragment = new SeedDialogFragment(); seedDialogFragment.show(getSupportFragmentManager(), "SeedDialog"); return; } public void onGetSeedClick() { ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("seed", game.getSeed()); clipboard.setPrimaryClip(clip); Toast toast = Toast.makeText(this, getString(R.string.game_seed_copied), Toast.LENGTH_SHORT); toast.show(); return; } public void onNewGameFromSeedClick(String seed) { newGame(seed); } private void showEndGameDialog() { DialogFragment endGameDialog = new EndGameDialogFragment(); Bundle args = new Bundle(); args.putInt("steps", game.getSteps()); args.putBoolean("game_won", game.checkWin()); args.putString("seed", game.getSeed()); endGameDialog.setArguments(args); endGameDialog.show(getSupportFragmentManager(), "EndGameDialog"); return; } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/ColorButton.java
app/src/main/java/com/gunshippenguin/openflood/ColorButton.java
package com.gunshippenguin.openflood; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.preference.PreferenceManager; import android.support.v4.content.ContextCompat; import android.view.View; public class ColorButton extends View { String text; Paint textPaint; Drawable buttonDrawable; public ColorButton(Context context) { super(context); buttonDrawable = ContextCompat.getDrawable(getContext(), R.drawable.button); textPaint = new Paint(); textPaint.setColor(Color.BLACK); textPaint.setTextAlign(Paint.Align.CENTER); } public void setColor(int color) { buttonDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); return; } public void setColorBlindText(String text) { this.text = text; } @Override public void onSizeChanged(int w, int h, int oldw, int oldh) { if (w > h) { textPaint.setTextSize(h); } else { textPaint.setTextSize(w); } } @Override public void onDraw(Canvas c) { buttonDrawable.setBounds(getPaddingLeft(), getPaddingTop(), c.getWidth() - getPaddingRight(), c.getHeight() - getPaddingBottom()); buttonDrawable.draw(c); boolean colorBlindMode = PreferenceManager.getDefaultSharedPreferences( getContext()).getBoolean("color_blind_mode", false); if (colorBlindMode && text != null) { c.drawText(text, getWidth() / 2, (int) (getHeight() / 2 - ((textPaint.descent() + textPaint.ascent()) / 2)), textPaint); } } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/SeedDialogFragment.java
app/src/main/java/com/gunshippenguin/openflood/SeedDialogFragment.java
package com.gunshippenguin.openflood; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * Dialog allowing the user to enter a seed to start a new game from. */ public class SeedDialogFragment extends DialogFragment { public interface SeedDialogFragmentListener { public void onNewGameFromSeedClick(String seed); } SeedDialogFragmentListener listener; public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(getContext()); View layout = inflater.inflate(R.layout.dialog_seed, null); final AlertDialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setView(layout); dialog = builder.create(); final EditText seedEditText = (EditText) layout.findViewById(R.id.seedEditText); seedEditText.requestFocus(); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); seedEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { switch (actionId) { case EditorInfo.IME_ACTION_DONE: listener.onNewGameFromSeedClick(seedEditText.getText().toString()); dialog.dismiss(); break; } return true; } }); Button startGameButton = (Button) layout.findViewById(R.id.startGameFromSeedButton); startGameButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onNewGameFromSeedClick(seedEditText.getText().toString()); dialog.dismiss(); } }); Button cancelButton = (Button) layout.findViewById(R.id.cancelStartGameFromSeedButton); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); return dialog; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { listener = (SeedDialogFragment.SeedDialogFragmentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement SeedDialogFragmentListener"); } } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/InfoActivity.java
app/src/main/java/com/gunshippenguin/openflood/InfoActivity.java
package com.gunshippenguin.openflood; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.method.LinkMovementMethod; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * Activity displaying information about the application. */ public class InfoActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info); // Set up the first line of the info TextView versionTextView = (TextView) findViewById(R.id.infoVersionTextView); String appName = getResources().getString(R.string.app_name); PackageInfo pInfo; try { pInfo = getPackageManager().getPackageInfo(this.getPackageName(), 0); versionTextView.setText(appName + " " + pInfo.versionName); } catch (PackageManager.NameNotFoundException e) { versionTextView.setText(appName); } // Set up the source link TextView sourceTextView = (TextView) findViewById(R.id.infoSourceTextView); sourceTextView.setMovementMethod(LinkMovementMethod.getInstance()); // Set up the back button Button backButton = (Button) findViewById(R.id.backButton); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); findViewById(R.id.appNameTextView).setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast toast = Toast.makeText(InfoActivity.this, "Eric Hamber Secondary Class of 2016", Toast.LENGTH_LONG); toast.show(); return true; } }); return; } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/main/java/com/gunshippenguin/openflood/ClearHighScoresDialogFragment.java
app/src/main/java/com/gunshippenguin/openflood/ClearHighScoresDialogFragment.java
package com.gunshippenguin.openflood; import android.app.Dialog; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.Toast; public class ClearHighScoresDialogFragment extends DialogFragment { public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(getContext()); View dialogView = inflater.inflate(R.layout.dialog_highscores_clear, null); final AlertDialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setView(dialogView); dialog = builder.create(); Button confirmButton = (Button) dialogView.findViewById(R.id.confirmHighScoresClearButton); confirmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HighScoreManager highScoreManager = new HighScoreManager( PreferenceManager.getDefaultSharedPreferences(getContext())); for (int boardSize : getResources().getIntArray(R.array.boardSizeChoices)) { for (int numColors : getResources().getIntArray(R.array.numColorsChoices)) { highScoreManager.removeHighScore(boardSize, numColors); } } dialog.dismiss(); Toast toast = Toast.makeText(getContext(), getString(R.string.settings_clear_high_scores_toast), Toast.LENGTH_SHORT); toast.show(); } }); Button cancelButton = (Button) dialogView.findViewById(R.id.cancelHighScoresClearButton); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); return dialog; } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/androidTest/java/com/gunshippenguin/openflood/InfoActivityTest.java
app/src/androidTest/java/com/gunshippenguin/openflood/InfoActivityTest.java
package com.gunshippenguin.openflood; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.scrollTo; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; @LargeTest @RunWith(AndroidJUnit4.class) public class InfoActivityTest { @Rule public ActivityTestRule<GameActivity> mActivityTestRule = new ActivityTestRule<>(GameActivity.class); @Test public void infoActivityTest() { // Launch the Info Activity ViewInteraction infoActivityButton = onView( allOf(withId(R.id.infoButton), isDisplayed())); infoActivityButton.perform(click()); // Click the back button ViewInteraction appCompatButton = onView( allOf(withId(R.id.backButton), withText("Back"))); appCompatButton.perform(scrollTo(), click()); // Verify that we are now back in the GameActivity by checking that the FloodView is displayed ViewInteraction view = onView( allOf(withId(R.id.floodView))); view.check(matches(isDisplayed())); } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/androidTest/java/com/gunshippenguin/openflood/NewGameTest.java
app/src/androidTest/java/com/gunshippenguin/openflood/NewGameTest.java
package com.gunshippenguin.openflood; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; import static android.support.test.espresso.action.ViewActions.longClick; import static android.support.test.espresso.action.ViewActions.replaceText; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; @LargeTest @RunWith(AndroidJUnit4.class) public class NewGameTest { @Rule public ActivityTestRule<GameActivity> mActivityTestRule = new ActivityTestRule<>(GameActivity.class); @Test public void newGameTest() { // New game button ViewInteraction newGameButton = onView( allOf(withId(R.id.newGameButton), isDisplayed())); // Generate a new game several times newGameButton.perform(click()); newGameButton.perform(click()); newGameButton.perform(click()); newGameButton.perform(click()); newGameButton.perform(click()); // Long click new game button for the new game from seed dialog newGameButton.perform(longClick()); // Hit cancel to close the dialog ViewInteraction cancelNewGameFromSeedButton = onView( allOf(withId(R.id.cancelStartGameFromSeedButton), withText("Cancel"), isDisplayed())); cancelNewGameFromSeedButton.perform(click()); // Reopen the new game from seed dialog newGameButton.perform(longClick()); // Add the seed 'abc' to the EditText ViewInteraction seedEditText = onView( allOf(withId(R.id.seedEditText), isDisplayed())); seedEditText.perform(replaceText("abc"), closeSoftKeyboard()); // Press start to start a new game from the given seed ViewInteraction startNewGameFromSeedButton = onView( allOf(withId(R.id.startGameFromSeedButton), withText("Start"), isDisplayed())); startNewGameFromSeedButton.perform(click()); } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
GunshipPenguin/open_flood
https://github.com/GunshipPenguin/open_flood/blob/7f834ffbc94b322091829f10798c228c6d172805/app/src/androidTest/java/com/gunshippenguin/openflood/SettingsTest.java
app/src/androidTest/java/com/gunshippenguin/openflood/SettingsTest.java
package com.gunshippenguin.openflood; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import android.view.View; import android.view.ViewGroup; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withClassName; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withParent; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.is; @LargeTest @RunWith(AndroidJUnit4.class) public class SettingsTest { private static Matcher<View> nthChildOf(final Matcher<View> parentMatcher, final int childPosition) { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("with "+childPosition+" child view of type parentMatcher"); } @Override public boolean matchesSafely(View view) { if (!(view.getParent() instanceof ViewGroup)) { return parentMatcher.matches(view.getParent()); } ViewGroup group = (ViewGroup) view.getParent(); return parentMatcher.matches(view.getParent()) && group.getChildAt(childPosition).equals(view); } }; } private static void clickColorButton(int index) { ViewInteraction colorButton = onView( allOf(withClassName(is("com.gunshippenguin.openflood.ColorButton")), withParent(withId(R.id.buttonLayout)), isDisplayed(), nthChildOf(withId(R.id.buttonLayout), index))); colorButton.perform(click()); } @Rule public ActivityTestRule<GameActivity> mActivityTestRule = new ActivityTestRule<>(GameActivity.class); @Test public void changeNumColorsTest() { // Click each of the 6 color buttons that should be initially present clickColorButton(0); clickColorButton(1); clickColorButton(2); clickColorButton(3); clickColorButton(4); clickColorButton(5); // Click the settings button to launch the SettingsActivity ViewInteraction settingsButton = onView( allOf(withId(R.id.settingsButton), isDisplayed())); settingsButton.perform(click()); // Click the 8 color button ViewInteraction changeNumColorsRadioButton = onView( allOf(withText("8"), withParent(withId(R.id.numColorsRadioGroup)), isDisplayed())); changeNumColorsRadioButton.perform(click()); // Apply the settings changes ViewInteraction applyButton = onView( allOf(withId(R.id.applyButton), withText("Apply"), isDisplayed())); applyButton.perform(click()); // We should now have 8 color buttons, click them all clickColorButton(0); clickColorButton(1); clickColorButton(2); clickColorButton(3); clickColorButton(4); clickColorButton(5); clickColorButton(6); clickColorButton(7); // Go back to the SettingsActivity settingsButton.perform(click()); // Enable color blind mode ViewInteraction colorBlindModeCheckBox = onView( allOf(withId(R.id.colorBlindCheckBox), isDisplayed())); colorBlindModeCheckBox.perform(click()); // Enable the old color scheme ViewInteraction oldColorSchemeCheckBox = onView( allOf(withId(R.id.oldColorsCheckBox), isDisplayed())); oldColorSchemeCheckBox.perform(click()); // Set the board size to 24x24 ViewInteraction changeBoardSizeRadioButton = onView( allOf(withText("24x24"), withParent(withId(R.id.boardSizeRadioGroup)), isDisplayed())); changeBoardSizeRadioButton.perform(click()); // Apply the new settings applyButton.perform(click()); // Click all 8 of the color buttons again clickColorButton(0); clickColorButton(1); clickColorButton(2); clickColorButton(3); clickColorButton(4); clickColorButton(5); clickColorButton(6); clickColorButton(7); } }
java
MIT
7f834ffbc94b322091829f10798c228c6d172805
2026-01-05T02:41:51.070842Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/GzipRequest.java
src/main/java/org/telegram/api/engine/GzipRequest.java
package org.telegram.api.engine; import org.telegram.tl.TLContext; import org.telegram.tl.TLGzipObject; import org.telegram.tl.TLMethod; import org.telegram.tl.TLObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; import static org.telegram.tl.StreamingUtils.*; import static org.telegram.tl.StreamingUtils.writeByteArray; /** * Created by ex3ndr on 07.12.13. */ public class GzipRequest<T extends TLObject> extends TLMethod<T> { private static final int CLASS_ID = TLGzipObject.CLASS_ID; private TLMethod<T> method; public GzipRequest(TLMethod<T> method) { this.method = method; } @Override public T deserializeResponse(InputStream stream, TLContext context) throws IOException { return method.deserializeResponse(stream, context); } @Override public int getClassId() { return CLASS_ID; } @Override public void serializeBody(OutputStream stream) throws IOException { ByteArrayOutputStream resOutput = new ByteArrayOutputStream(); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(resOutput); method.serialize(gzipOutputStream); gzipOutputStream.flush(); gzipOutputStream.close(); byte[] body = resOutput.toByteArray(); writeTLBytes(body, stream); } @Override public void deserializeBody(InputStream stream, TLContext context) throws IOException { throw new IOException("Unsupported operation"); } @Override public String toString() { return "gzip<" + method + ">"; } }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/ApiCallback.java
src/main/java/org/telegram/api/engine/ApiCallback.java
package org.telegram.api.engine; import org.telegram.api.TLAbsUpdates; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 11.11.13 * Time: 7:42 */ public interface ApiCallback { public void onAuthCancelled(TelegramApi api); public void onUpdatesInvalidated(TelegramApi api); public void onUpdate(TLAbsUpdates updates); }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/AppInfo.java
src/main/java/org/telegram/api/engine/AppInfo.java
package org.telegram.api.engine; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 10.11.13 * Time: 2:31 */ public class AppInfo { protected int apiId; protected String deviceModel; protected String systemVersion; protected String appVersion; protected String langCode; public AppInfo(int apiId, String deviceModel, String systemVersion, String appVersion, String langCode) { this.apiId = apiId; this.deviceModel = deviceModel; this.systemVersion = systemVersion; this.appVersion = appVersion; this.langCode = langCode; } public int getApiId() { return apiId; } public String getDeviceModel() { return deviceModel; } public String getSystemVersion() { return systemVersion; } public String getAppVersion() { return appVersion; } public String getLangCode() { return langCode; } }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/TelegramApi.java
src/main/java/org/telegram/api/engine/TelegramApi.java
package org.telegram.api.engine; import org.telegram.actors.ActorSystem; import org.telegram.api.TLAbsUpdates; import org.telegram.api.TLApiContext; import org.telegram.api.TLConfig; import org.telegram.api.auth.TLExportedAuthorization; import org.telegram.api.engine.file.Downloader; import org.telegram.api.engine.file.Uploader; import org.telegram.api.engine.storage.AbsApiState; import org.telegram.api.requests.*; import org.telegram.api.upload.TLFile; import org.telegram.mtproto.CallWrapper; import org.telegram.mtproto.MTProto; import org.telegram.mtproto.MTProtoCallback; import org.telegram.mtproto.pq.Authorizer; import org.telegram.mtproto.pq.PqAuth; import org.telegram.mtproto.state.ConnectionInfo; import org.telegram.mtproto.util.BytesCache; import org.telegram.tl.*; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 04.11.13 * Time: 21:54 */ public class TelegramApi { private static final AtomicInteger rpcCallIndex = new AtomicInteger(0); private static final AtomicInteger instanceIndex = new AtomicInteger(1000); public static final int MODE_FULL_POWER = 0; public static final int MODE_LOW_POWER = 1; private static final int CHANNELS_MAIN = 1; private static final int CHANNELS_FS = 2; private static final int DEFAULT_TIMEOUT = 15000; private static final int FILE_TIMEOUT = 45000; private static final long PUSH_TIMEOUT = 7 * 24 * 60 * 60 * 1000L;// 7 days private final String TAG; private final int INSTANCE_INDEX; private boolean isClosed; private int primaryDc; private MTProto mainProto; private MTProto mainPushProto; private final HashMap<Integer, MTProto> dcProtos = new HashMap<Integer, MTProto>(); private final HashMap<Integer, Object> dcSync = new HashMap<Integer, Object>(); private ProtoCallback callback; private SenderThread senderThread; private final HashMap<Integer, RpcCallbackWrapper> callbacks = new HashMap<Integer, RpcCallbackWrapper>(); private final HashMap<Integer, Integer> sentRequests = new HashMap<Integer, Integer>(); private TLApiContext apiContext; private TimeoutThread timeoutThread; private final TreeMap<Long, Integer> timeoutTimes = new TreeMap<Long, Integer>(); private ConnectionThread dcThread; private final TreeMap<Integer, Boolean> dcRequired = new TreeMap<Integer, Boolean>(); private HashSet<Integer> registeredInApi = new HashSet<Integer>(); private AbsApiState state; private AppInfo appInfo; private ApiCallback apiCallback; private Downloader downloader; private Uploader uploader; private ActorSystem actorSystem; private int mode; public TelegramApi(AbsApiState state, AppInfo _appInfo, ApiCallback _apiCallback) { this.INSTANCE_INDEX = instanceIndex.incrementAndGet(); this.TAG = "TelegramApi#" + INSTANCE_INDEX; this.actorSystem = new ActorSystem(); this.actorSystem.addThread("connector"); long start = System.currentTimeMillis(); this.apiCallback = _apiCallback; this.appInfo = _appInfo; this.state = state; this.primaryDc = state.getPrimaryDc(); this.isClosed = false; this.callback = new ProtoCallback(); this.mode = MODE_FULL_POWER; Logger.d(TAG, "Phase 0 in " + (System.currentTimeMillis() - start) + " ms"); start = System.currentTimeMillis(); this.apiContext = new TLApiContext() { private AtomicInteger integer = new AtomicInteger(0); @Override public TLObject deserializeMessage(int clazzId, InputStream stream) throws IOException { if (integer.incrementAndGet() % 10 == 9) { Thread.yield(); } return super.deserializeMessage(clazzId, stream); } @Override public TLBytes allocateBytes(int size) { return new TLBytes(BytesCache.getInstance().allocate(size), 0, size); } @Override public void releaseBytes(TLBytes unused) { BytesCache.getInstance().put(unused.getData()); } }; Logger.d(TAG, "Phase 1 in " + (System.currentTimeMillis() - start) + " ms"); start = System.currentTimeMillis(); this.timeoutThread = new TimeoutThread(); this.timeoutThread.start(); this.dcThread = new ConnectionThread(); this.dcThread.start(); this.senderThread = new SenderThread(); this.senderThread.start(); Logger.d(TAG, "Phase 2 in " + (System.currentTimeMillis() - start) + " ms"); start = System.currentTimeMillis(); this.downloader = new Downloader(this); this.uploader = new Uploader(this); Logger.d(TAG, "Phase 3 in " + (System.currentTimeMillis() - start) + " ms"); } public Downloader getDownloader() { return downloader; } public Uploader getUploader() { return uploader; } public void switchToDc(int dcId) { if (this.mainProto != null) { this.mainProto.close(); } if (this.mainPushProto != null) { this.mainPushProto.close(); } this.mainPushProto = null; this.mainProto = null; this.primaryDc = dcId; this.state.setPrimaryDc(dcId); synchronized (dcRequired) { dcRequired.notifyAll(); } } public void switchMode(int mode) { if (this.mode != mode) { this.mode = mode; if (mode == MODE_FULL_POWER) { if (mainProto != null) { mainProto.switchMode(MTProto.MODE_GENERAL); } } else { if (mainProto != null) { mainProto.switchMode(MTProto.MODE_GENERAL_LOW_MODE); } } } } @Override public String toString() { return "api#" + INSTANCE_INDEX; } private TLMethod wrapForDc(int dcId, TLMethod method) { if (registeredInApi.contains(dcId)) { return new TLRequestInvokeWithLayer12(method); } return new TLRequestInvokeWithLayer12(new TLRequestInitConnection( appInfo.getApiId(), appInfo.getDeviceModel(), appInfo.getSystemVersion(), appInfo.getAppVersion(), appInfo.getLangCode(), method)); } public AbsApiState getState() { return state; } public TLApiContext getApiContext() { return apiContext; } protected void onMessageArrived(TLObject object) { if (object instanceof TLAbsUpdates) { Logger.d(TAG, "<< update " + object.toString()); apiCallback.onUpdate((TLAbsUpdates) object); } else { Logger.d(TAG, "<< unknown object " + object.toString()); } } public boolean isClosed() { return isClosed; } public void close() { if (!this.isClosed) { apiCallback.onAuthCancelled(this); this.isClosed = true; if (this.timeoutThread != null) { this.timeoutThread.interrupt(); this.timeoutThread = null; } if (mainProto != null) { mainProto.close(); } if (mainPushProto != null) { mainPushProto.close(); } } } public void resetNetworkBackoff() { if (mainProto != null) { mainProto.resetNetworkBackoff(); } if (mainPushProto != null) { mainPushProto.resetNetworkBackoff(); } for (MTProto mtProto : dcProtos.values()) { mtProto.resetNetworkBackoff(); } } public void resetConnectionInfo() { mainProto.reloadConnectionInformation(); mainPushProto.reloadConnectionInformation(); synchronized (dcProtos) { for (MTProto proto : dcProtos.values()) { proto.reloadConnectionInformation(); } } } // Basic sync and async methods private <T extends TLObject> void doRpcCall(TLMethod<T> method, int timeout, RpcCallback<T> callback, int destDc) { doRpcCall(method, timeout, callback, destDc, true); } private <T extends TLObject> void doRpcCall(TLMethod<T> method, int timeout, RpcCallback<T> callback, int destDc, boolean authRequired) { if (isClosed) { if (callback != null) { callback.onError(0, null); } return; } int localRpcId = rpcCallIndex.getAndIncrement(); synchronized (callbacks) { RpcCallbackWrapper wrapper = new RpcCallbackWrapper(localRpcId, method, callback); wrapper.dcId = destDc; wrapper.timeout = timeout; wrapper.isAuthRequred = authRequired; callbacks.put(localRpcId, wrapper); if (callback != null) { long timeoutTime = System.nanoTime() + timeout * 1000 * 1000L; synchronized (timeoutTimes) { while (timeoutTimes.containsKey(timeoutTime)) { timeoutTime++; } timeoutTimes.put(timeoutTime, localRpcId); timeoutTimes.notifyAll(); } wrapper.timeoutTime = timeoutTime; } if (authRequired) { checkDcAuth(destDc); } else { checkDc(destDc); } callbacks.notifyAll(); } Logger.d(TAG, ">> #" + +localRpcId + ": " + method.toString()); } private <T extends TLObject> T doRpcCall(TLMethod<T> method, int timeout, int destDc) throws IOException { return doRpcCall(method, timeout, destDc, true); } private <T extends TLObject> T doRpcCall(TLMethod<T> method, int timeout, int destDc, boolean authRequired) throws IOException { if (isClosed) { throw new TimeoutException(); } final Object waitObj = new Object(); final Object[] res = new Object[3]; final boolean[] completed = new boolean[1]; completed[0] = false; doRpcCall(method, timeout, new RpcCallback<T>() { @Override public void onResult(T result) { synchronized (waitObj) { if (completed[0]) { return; } completed[0] = true; res[0] = result; res[1] = null; res[2] = null; waitObj.notifyAll(); } } @Override public void onError(int errorCode, String message) { synchronized (waitObj) { if (completed[0]) { return; } completed[0] = true; res[0] = null; res[1] = errorCode; res[2] = message; waitObj.notifyAll(); } } }, destDc, authRequired); synchronized (waitObj) { try { waitObj.wait(timeout); completed[0] = true; } catch (InterruptedException e) { throw new TimeoutException(); } } if (res[0] == null) { if (res[1] != null) { Integer code = (Integer) res[1]; if (code == 0) { throw new TimeoutException(); } else { throw new RpcException(code, (String) res[2]); } } else { throw new TimeoutException(); } } else { return (T) res[0]; } } // Public async methods public <T extends TLObject> void doRpcCallWeak(TLMethod<T> method) { doRpcCallWeak(method, DEFAULT_TIMEOUT); } public <T extends TLObject> void doRpcCallWeak(TLMethod<T> method, int timeout) { doRpcCall(method, timeout, (RpcCallback) null); } public <T extends TLObject> void doRpcCall(TLMethod<T> method, RpcCallback<T> callback) { doRpcCall(method, DEFAULT_TIMEOUT, callback); } public <T extends TLObject> void doRpcCall(TLMethod<T> method, int timeout, RpcCallback<T> callback) { doRpcCall(method, timeout, callback, 0); } // Public sync methods public <T extends TLObject> T doRpcCall(TLMethod<T> method) throws IOException { return doRpcCall(method, DEFAULT_TIMEOUT); } public <T extends TLObject> T doRpcCall(TLMethod<T> method, int timeout) throws IOException { return doRpcCall(method, timeout, 0); } public <T extends TLObject> T doRpcCallSide(TLMethod<T> method) throws IOException { return doRpcCall(method, DEFAULT_TIMEOUT, primaryDc, true); } public <T extends TLObject> T doRpcCallSide(TLMethod<T> method, int timeout) throws IOException { return doRpcCall(method, timeout, primaryDc, true); } public <T extends TLObject> T doRpcCallSideGzip(TLMethod<T> method, int timeout) throws IOException { return doRpcCall(new GzipRequest<T>(method), timeout, primaryDc, true); } public <T extends TLObject> T doRpcCallGzip(TLMethod<T> method, int timeout) throws IOException { return doRpcCall(new GzipRequest<T>(method), timeout, 0); } public <T extends TLObject> T doRpcCallNonAuth(TLMethod<T> method) throws IOException { return doRpcCallNonAuth(method, DEFAULT_TIMEOUT, primaryDc); } public <T extends TLObject> T doRpcCallNonAuth(TLMethod<T> method, int dcId) throws IOException { return doRpcCallNonAuth(method, DEFAULT_TIMEOUT, dcId); } public <T extends TLObject> T doRpcCallNonAuth(TLMethod<T> method, int timeout, int dcId) throws IOException { return doRpcCall(method, timeout, dcId, false); } public <T extends TLObject> void doRpcCallNonAuth(TLMethod<T> method, int timeout, RpcCallback<T> callback) { doRpcCall(method, timeout, callback, 0, false); } public boolean doSaveFilePart(long _fileId, int _filePart, byte[] _bytes) throws IOException { TLBool res = doRpcCall( new TLRequestUploadSaveFilePart(_fileId, _filePart, new TLBytes(_bytes)), FILE_TIMEOUT, primaryDc, true); return res instanceof TLBoolTrue; } public boolean doSaveBigFilePart(long _fileId, int _filePart, int _totalParts, byte[] _bytes) throws IOException { TLBool res = doRpcCall( new TLRequestUploadSaveBigFilePart(_fileId, _filePart, _totalParts, new TLBytes(_bytes)), FILE_TIMEOUT, primaryDc); return res instanceof TLBoolTrue; } public TLFile doGetFile(int dcId, org.telegram.api.TLAbsInputFileLocation _location, int _offset, int _limit) throws IOException { return doRpcCall(new TLRequestUploadGetFile(_location, _offset, _limit), FILE_TIMEOUT, dcId); } private void checkDcAuth(int dcId) { if (dcId != 0) { synchronized (dcProtos) { if (!dcProtos.containsKey(dcId)) { synchronized (dcRequired) { dcRequired.put(dcId, true); dcRequired.notifyAll(); } } else if (!state.isAuthenticated(dcId)) { synchronized (dcRequired) { dcRequired.put(dcId, true); dcRequired.notifyAll(); } } } } } private void checkDc(int dcId) { if (dcId != 0) { synchronized (dcProtos) { if (!dcProtos.containsKey(dcId)) { synchronized (dcRequired) { if (!dcRequired.containsKey(dcId)) { dcRequired.put(dcId, false); } dcRequired.notifyAll(); } } } } else if (mainProto == null) { synchronized (dcRequired) { dcRequired.notifyAll(); } } } private class ProtoCallback implements MTProtoCallback { @Override public void onSessionCreated(MTProto proto) { if (isClosed) { return; } Logger.w(TAG, proto + ": onSessionCreated"); if (proto == mainProto) { registeredInApi.add(primaryDc); } else { for (Map.Entry<Integer, MTProto> p : dcProtos.entrySet()) { if (p.getValue() == proto) { registeredInApi.add(p.getKey()); break; } } } apiCallback.onUpdatesInvalidated(TelegramApi.this); } @Override public void onAuthInvalidated(MTProto proto) { if (isClosed) { return; } if (proto == mainProto) { synchronized (dcRequired) { mainProto.close(); mainProto = null; state.setAuthenticated(primaryDc, false); dcRequired.notifyAll(); } synchronized (dcProtos) { for (Map.Entry<Integer, MTProto> p : dcProtos.entrySet()) { p.getValue().close(); state.setAuthenticated(p.getKey(), false); } } apiCallback.onAuthCancelled(TelegramApi.this); } else { synchronized (dcProtos) { for (Map.Entry<Integer, MTProto> p : dcProtos.entrySet()) { if (p.getValue() == proto) { state.setAuthenticated(p.getKey(), false); dcProtos.remove(p.getKey()); break; } } } synchronized (dcRequired) { dcRequired.notifyAll(); } } } @Override public void onApiMessage(byte[] message, MTProto proto) { if (isClosed) { return; } if (proto == mainProto) { registeredInApi.add(primaryDc); } else { for (Map.Entry<Integer, MTProto> p : dcProtos.entrySet()) { if (p.getValue() == proto) { registeredInApi.add(p.getKey()); break; } } } try { TLObject object = apiContext.deserializeMessage(message); onMessageArrived(object); } catch (Throwable t) { Logger.e(TAG, t); } } @Override public void onRpcResult(int callId, byte[] response, MTProto proto) { if (isClosed) { return; } if (proto == mainProto) { registeredInApi.add(primaryDc); } else { for (Map.Entry<Integer, MTProto> p : dcProtos.entrySet()) { if (p.getValue() == proto) { registeredInApi.add(p.getKey()); break; } } } try { RpcCallbackWrapper currentCallback = null; synchronized (callbacks) { if (sentRequests.containsKey(callId)) { currentCallback = callbacks.remove(sentRequests.remove(callId)); } } if (currentCallback != null && currentCallback.method != null) { long start = System.currentTimeMillis(); TLObject object = currentCallback.method.deserializeResponse(response, apiContext); Logger.d(TAG, "<< #" + +currentCallback.id + " deserialized " + object + " in " + (System.currentTimeMillis() - start) + " ms"); synchronized (currentCallback) { if (currentCallback.isCompleted) { Logger.d(TAG, "<< #" + +currentCallback.id + " ignored " + object + " in " + currentCallback.elapsed() + " ms"); return; } else { currentCallback.isCompleted = true; } } Logger.d(TAG, "<< #" + +currentCallback.id + " " + object + " in " + currentCallback.elapsed() + " ms"); synchronized (timeoutTimes) { timeoutTimes.remove(currentCallback.timeoutTime); } if (currentCallback.callback != null) { currentCallback.callback.onResult(object); } } } catch (Throwable t) { Logger.e(TAG, t); } } @Override public void onRpcError(int callId, int errorCode, String message, MTProto proto) { if (isClosed) { return; } if (errorCode == 400 && message != null && (message.startsWith("CONNECTION_NOT_INITED") || message.startsWith("CONNECTION_LAYER_INVALID"))) { Logger.w(TAG, proto + ": (!)Error #400 " + message); int dc = -1; if (proto == mainProto) { dc = primaryDc; } else { for (Map.Entry<Integer, MTProto> p : dcProtos.entrySet()) { if (p.getValue() == proto) { dc = p.getKey(); break; } } } if (dc < 0) { return; } registeredInApi.remove(dc); RpcCallbackWrapper currentCallback; synchronized (callbacks) { currentCallback = callbacks.remove(sentRequests.remove(callId)); if (currentCallback != null) { currentCallback.isSent = false; callbacks.notifyAll(); } } return; } else { if (proto == mainProto) { registeredInApi.add(primaryDc); } else { for (Map.Entry<Integer, MTProto> p : dcProtos.entrySet()) { if (p.getValue() == proto) { registeredInApi.add(p.getKey()); break; } } } } try { RpcCallbackWrapper currentCallback = null; synchronized (callbacks) { if (sentRequests.containsKey(callId)) { currentCallback = callbacks.remove(sentRequests.remove(callId)); } } if (currentCallback != null) { synchronized (currentCallback) { if (currentCallback.isCompleted) { Logger.d(TAG, "<< #" + +currentCallback.id + " ignored error #" + errorCode + " " + message + " in " + currentCallback.elapsed() + " ms"); return; } else { currentCallback.isCompleted = true; } } Logger.d(TAG, "<< #" + +currentCallback.id + " error #" + errorCode + " " + message + " in " + currentCallback.elapsed() + " ms"); synchronized (timeoutTimes) { timeoutTimes.remove(currentCallback.timeoutTime); } if (currentCallback.callback != null) { currentCallback.callback.onError(errorCode, message); } } } catch (Throwable t) { Logger.e(TAG, t); } } @Override public void onConfirmed(int callId) { RpcCallbackWrapper currentCallback = null; synchronized (callbacks) { if (sentRequests.containsKey(callId)) { currentCallback = callbacks.get(sentRequests.get(callId)); } } if (currentCallback != null) { Logger.d(TAG, "<< #" + +currentCallback.id + " confirmed in " + currentCallback.elapsed() + " ms"); synchronized (currentCallback) { if (currentCallback.isCompleted || currentCallback.isConfirmed) { return; } else { currentCallback.isConfirmed = true; } } if (currentCallback.callback instanceof RpcCallbackEx) { ((RpcCallbackEx) currentCallback.callback).onConfirmed(); } } } } private class SenderThread extends Thread { public SenderThread() { setName("Sender#" + hashCode()); } @Override public void run() { setPriority(Thread.MIN_PRIORITY); while (!isClosed) { Logger.d(TAG, "Sender iteration"); RpcCallbackWrapper wrapper = null; synchronized (callbacks) { for (RpcCallbackWrapper w : callbacks.values()) { if (!w.isSent) { if (w.dcId == 0 && mainProto != null) { if (state.isAuthenticated(primaryDc) || !w.isAuthRequred) { wrapper = w; break; } } if (w.dcId != 0 && dcProtos.containsKey(w.dcId)) { if (state.isAuthenticated(w.dcId) || !w.isAuthRequred) { wrapper = w; break; } } } } if (wrapper == null) { try { callbacks.wait(); } catch (InterruptedException e) { Logger.e(TAG, e); return; } continue; } } if (mainProto == null) { continue; } if (wrapper.dcId == 0) { if (!state.isAuthenticated(primaryDc) && wrapper.isAuthRequred) { continue; } synchronized (callbacks) { boolean isHighPriority = wrapper.callback != null && wrapper.callback instanceof RpcCallbackEx; int rpcId = mainProto.sendRpcMessage(wrapper.method, wrapper.timeout, isHighPriority); sentRequests.put(rpcId, wrapper.id); wrapper.isSent = true; Logger.d(TAG, "#> #" + wrapper.id + " sent to MTProto #" + mainProto.getInstanceIndex() + " with id #" + rpcId); } } else { if (!dcProtos.containsKey(wrapper.dcId) || (!state.isAuthenticated(wrapper.dcId) && wrapper.isAuthRequred)) { continue; } MTProto proto = dcProtos.get(wrapper.dcId); synchronized (callbacks) { boolean isHighPriority = wrapper.callback != null && wrapper.callback instanceof RpcCallbackEx; int rpcId = proto.sendRpcMessage(wrapper.method, wrapper.timeout, isHighPriority); sentRequests.put(rpcId, wrapper.id); wrapper.isSent = true; Logger.d(TAG, "#> #" + wrapper.id + " sent to MTProto #" + proto.getInstanceIndex() + " with id #" + rpcId); } } } } } private class ConnectionThread extends Thread { public ConnectionThread() { setName("Connection#" + hashCode()); } private MTProto waitForDc(final int dcId) throws IOException { Logger.d(TAG, "#" + dcId + ": waitForDc"); if (isClosed) { Logger.w(TAG, "#" + dcId + ": Api is closed"); throw new TimeoutException(); } // if (!state.isAuthenticated(primaryDc)) { // Logger.w(TAG, "#" + dcId + ": Dc is not authenticated"); // throw new TimeoutException(); // } Object syncObj; synchronized (dcSync) { syncObj = dcSync.get(dcId); if (syncObj == null) { syncObj = new Object(); dcSync.put(dcId, syncObj); } } synchronized (syncObj) { MTProto proto; synchronized (dcProtos) { proto = dcProtos.get(dcId); if (proto != null) { if (proto.isClosed()) { Logger.d(TAG, "#" + dcId + "proto removed because of death"); dcProtos.remove(dcId); proto = null; } } } if (proto == null) { Logger.d(TAG, "#" + dcId + ": Creating proto for dc"); ConnectionInfo[] connectionInfo = state.getAvailableConnections(dcId); if (connectionInfo.length == 0) { Logger.w(TAG, "#" + dcId + ": Unable to find proper dc config"); TLConfig config = doRpcCall(new TLRequestHelpGetConfig()); state.updateSettings(config); resetConnectionInfo(); connectionInfo = state.getAvailableConnections(dcId); } if (connectionInfo.length == 0) { Logger.w(TAG, "#" + dcId + ": Still unable to find proper dc config"); throw new TimeoutException(); } if (state.getAuthKey(dcId) != null) { byte[] authKey = state.getAuthKey(dcId); if (authKey == null) { throw new TimeoutException(); } proto = new MTProto(state.getMtProtoState(dcId), callback, new CallWrapper() { @Override public TLObject wrapObject(TLMethod srcRequest) { return wrapForDc(dcId, srcRequest); } }, CHANNELS_FS, MTProto.MODE_FILE ); dcProtos.put(dcId, proto); return proto; } else { Logger.w(TAG, "#" + dcId + ": Creating key"); Authorizer authorizer = new Authorizer(); PqAuth auth = authorizer.doAuth(connectionInfo); if (auth == null) { Logger.w(TAG, "#" + dcId + ": Timed out"); throw new TimeoutException(); } state.putAuthKey(dcId, auth.getAuthKey()); state.setAuthenticated(dcId, false); state.getMtProtoState(dcId).initialServerSalt(auth.getServerSalt());
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
true
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/TimeoutException.java
src/main/java/org/telegram/api/engine/TimeoutException.java
package org.telegram.api.engine; import java.io.IOException; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 06.11.13 * Time: 1:27 */ public class TimeoutException extends IOException { public TimeoutException() { } public TimeoutException(String s) { super(s); } public TimeoutException(String s, Throwable throwable) { super(s, throwable); } public TimeoutException(Throwable throwable) { super(throwable); } }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/RpcCallbackEx.java
src/main/java/org/telegram/api/engine/RpcCallbackEx.java
package org.telegram.api.engine; import org.telegram.tl.TLObject; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 09.11.13 * Time: 18:06 */ public interface RpcCallbackEx<T extends TLObject> extends RpcCallback<T> { public void onConfirmed(); }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/RpcException.java
src/main/java/org/telegram/api/engine/RpcException.java
package org.telegram.api.engine; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 05.11.13 * Time: 13:59 */ public class RpcException extends IOException { private static final Pattern REGEXP_PATTERN = Pattern.compile("[A-Z_0-9]+"); private static String getErrorTag(String srcMessage) { if (srcMessage == null) { return "UNKNOWN"; } Matcher matcher = REGEXP_PATTERN.matcher(srcMessage); if (matcher.find()) { return matcher.group(); } return "UNKNOWN"; } private static String getErrorMessage(String srcMessage) { if (srcMessage == null) { return "Unknown error"; } int index = srcMessage.indexOf(":"); if (index > 0) { return srcMessage.substring(index); } else { return srcMessage; } } private int errorCode; private String errorTag; public RpcException(int errorCode, String message) { super(getErrorMessage(message)); this.errorCode = errorCode; this.errorTag = getErrorTag(message); } public int getErrorCode() { return errorCode; } public String getErrorTag() { return errorTag; } }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/RpcCallback.java
src/main/java/org/telegram/api/engine/RpcCallback.java
package org.telegram.api.engine; import org.telegram.tl.TLObject; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 05.11.13 * Time: 14:10 */ public interface RpcCallback<T extends TLObject> { public void onResult(T result); public void onError(int errorCode, String message); }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/Logger.java
src/main/java/org/telegram/api/engine/Logger.java
package org.telegram.api.engine; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 11.11.13 * Time: 4:48 */ public class Logger { private static LoggerInterface logInterface; public static void registerInterface(LoggerInterface logInterface) { Logger.logInterface = logInterface; } public static void w(String tag, String message) { if (logInterface != null) { logInterface.w(tag, message); } else { System.out.println(tag + ":" + message); } } public static void d(String tag, String message) { if (logInterface != null) { logInterface.d(tag, message); } else { System.out.println(tag + ":" + message); } } public static void e(String tag, Throwable t) { if (logInterface != null) { logInterface.e(tag, t); } else { t.printStackTrace(); } } }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/LoggerInterface.java
src/main/java/org/telegram/api/engine/LoggerInterface.java
package org.telegram.api.engine; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 11.11.13 * Time: 4:48 */ public interface LoggerInterface { void w(String tag, String message); void d(String tag, String message); void e(String tag, Throwable t); }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/storage/AbsApiState.java
src/main/java/org/telegram/api/engine/storage/AbsApiState.java
package org.telegram.api.engine.storage; import org.telegram.api.TLConfig; import org.telegram.mtproto.state.AbsMTProtoState; import org.telegram.mtproto.state.ConnectionInfo; import org.telegram.mtproto.state.KnownSalt; import java.util.HashMap; import java.util.Map; /** * Created with IntelliJ IDEA. * User: ex3ndr * Date: 07.11.13 * Time: 10:19 */ public interface AbsApiState { int getPrimaryDc(); public void setPrimaryDc(int dc); boolean isAuthenticated(int dcId); void setAuthenticated(int dcId, boolean auth); void updateSettings(TLConfig config); byte[] getAuthKey(int dcId); void putAuthKey(int dcId, byte[] key); ConnectionInfo[] getAvailableConnections(int dcId); AbsMTProtoState getMtProtoState(int dcId); void resetAuth(); void reset(); }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/file/DownloadListener.java
src/main/java/org/telegram/api/engine/file/DownloadListener.java
package org.telegram.api.engine.file; /** * Created by ex3ndr on 18.11.13. */ public interface DownloadListener { public void onPartDownloaded(int percent, int downloadedSize); public void onDownloaded(); public void onFailed(); }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/file/Uploader.java
src/main/java/org/telegram/api/engine/file/Uploader.java
package org.telegram.api.engine.file; import org.telegram.api.engine.Logger; import org.telegram.api.engine.TelegramApi; import org.telegram.mtproto.secure.CryptoUtils; import org.telegram.mtproto.secure.Entropy; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; /** * Created by ex3ndr on 19.11.13. */ public class Uploader { private static final int KB = 1024; private static final int MB = 1024 * KB; private final AtomicInteger fileIds = new AtomicInteger(1); public static final int FILE_QUEUED = 0; public static final int FILE_IN_PROGRESS = 1; public static final int FILE_COMPLETED = 2; public static final int FILE_CANCELED = 3; private static final int BLOCK_QUEUED = 0; private static final int BLOCK_DOWNLOADING = 1; private static final int BLOCK_COMPLETED = 2; private static final int PARALLEL_DOWNLOAD_COUNT = 2; private static final int PARALLEL_PARTS_COUNT = 4; private static final int[] BLOCK_SIZES = new int[]{8 * KB, 16 * KB, 32 * KB, 64 * KB, 128 * KB, 256 * KB, 512 * KB}; private static final long DEFAULT_DELAY = 15 * 1000; private static final int BIG_FILE_MIN = 10 * 1024 * 1024; private static final int MAX_BLOCK_COUNT = 3000; private final String TAG; private TelegramApi api; private ArrayList<UploadTask> tasks = new ArrayList<UploadTask>(); private ArrayList<UploadFileThread> threads = new ArrayList<UploadFileThread>(); private final Object threadLocker = new Object(); private Random rnd = new Random(); public Uploader(TelegramApi api) { this.TAG = api.toString() + "#Uploader"; this.api = api; for (int i = 0; i < PARALLEL_PARTS_COUNT; i++) { UploadFileThread thread = new UploadFileThread(); thread.start(); threads.add(thread); } } public TelegramApi getApi() { return api; } private synchronized UploadTask getTask(int taskId) { for (UploadTask task : tasks) { if (task.taskId == taskId) { return task; } } return null; } public synchronized void cancelTask(int taskId) { UploadTask task = getTask(taskId); if (task != null && task.state != FILE_COMPLETED) { task.state = FILE_CANCELED; Logger.d(TAG, "File #" + task.taskId + "| Canceled"); } updateFileQueueStates(); } public synchronized int getTaskState(int taskId) { UploadTask task = getTask(taskId); if (task != null) { return task.state; } return FILE_CANCELED; } public void waitForTask(int taskId) { while (true) { int state = getTaskState(taskId); if ((state == FILE_COMPLETED) || (state == FILE_CANCELED)) { return; } synchronized (threadLocker) { try { threadLocker.wait(DEFAULT_DELAY); } catch (InterruptedException e) { Logger.e(TAG, e); return; } } } } public UploadResult getUploadResult(int taskId) { UploadTask task = getTask(taskId); if (task == null) { return null; } if (task.state != FILE_COMPLETED) { return null; } return new UploadResult(task.uniqId, task.blocks.length, task.hash, task.usedBigFile); } public synchronized int requestTask(String srcFile, UploadListener listener) { UploadTask task = new UploadTask(); task.taskId = fileIds.getAndIncrement(); task.uniqId = Entropy.generateRandomId(); task.listener = listener; task.srcFile = srcFile; try { task.file = new RandomAccessFile(srcFile, "r"); task.size = (int) task.file.length(); if (task.size >= BIG_FILE_MIN) { task.usedBigFile = true; Logger.d(TAG, "File #" + task.uniqId + "| Using big file method"); } else { task.usedBigFile = false; } long start = System.currentTimeMillis(); Logger.d(TAG, "File #" + task.uniqId + "| Calculating hash"); task.hash = CryptoUtils.MD5(task.file); Logger.d(TAG, "File #" + task.uniqId + "| Hash " + task.hash + " in " + (System.currentTimeMillis() - start) + " ms"); } catch (FileNotFoundException e) { Logger.e(TAG, e); } catch (IOException e) { Logger.e(TAG, e); } task.blockSize = BLOCK_SIZES[BLOCK_SIZES.length - 1]; for (int size : BLOCK_SIZES) { int totalBlockCount = (int) Math.ceil(((double) task.size) / size); if (totalBlockCount < MAX_BLOCK_COUNT) { task.blockSize = size; break; } } Logger.d(TAG, "File #" + task.uniqId + "| Using block size: " + task.blockSize); int totalBlockCount = (int) Math.ceil(((double) task.size) / task.blockSize); task.blocks = new UploadBlock[totalBlockCount]; for (int i = 0; i < totalBlockCount; i++) { task.blocks[i] = new UploadBlock(); task.blocks[i].task = task; task.blocks[i].index = i; task.blocks[i].state = BLOCK_QUEUED; } task.state = FILE_QUEUED; task.queueTime = System.nanoTime(); tasks.add(task); Logger.d(TAG, "File #" + task.uniqId + "| Requested"); updateFileQueueStates(); return task.taskId; } private synchronized UploadTask[] getActiveTasks() { ArrayList<UploadTask> res = new ArrayList<UploadTask>(); for (UploadTask task : tasks) { if (task.state == FILE_IN_PROGRESS) { res.add(task); } } return res.toArray(new UploadTask[res.size()]); } private synchronized void updateFileQueueStates() { UploadTask[] activeTasks = getActiveTasks(); outer: for (UploadTask task : activeTasks) { for (UploadBlock block : task.blocks) { if (block.state != BLOCK_COMPLETED) { continue outer; } } onTaskCompleted(task); } activeTasks = getActiveTasks(); int count = activeTasks.length; while (count < PARALLEL_DOWNLOAD_COUNT) { long mintime = Long.MAX_VALUE; UploadTask minTask = null; for (UploadTask task : tasks) { if (task.state == FILE_QUEUED && task.queueTime < mintime) { minTask = task; } } if (minTask == null) { break; } minTask.state = FILE_IN_PROGRESS; Logger.d(TAG, "File #" + minTask.uniqId + "| Uploading"); } synchronized (threadLocker) { threadLocker.notifyAll(); } } private synchronized void onTaskCompleted(UploadTask task) { if (task.state != FILE_COMPLETED) { Logger.d(TAG, "File #" + task.uniqId + "| Completed in " + (System.nanoTime() - task.queueTime) / (1000 * 1000L) + " ms"); task.state = FILE_COMPLETED; try { if (task.file != null) { task.file.close(); task.file = null; } } catch (IOException e) { Logger.e(TAG, e); } } updateFileQueueStates(); } private synchronized UploadTask fetchTask() { UploadTask[] activeTasks = getActiveTasks(); if (activeTasks.length == 0) { return null; } else if (activeTasks.length == 1) { return activeTasks[0]; } else { return activeTasks[rnd.nextInt(activeTasks.length)]; } } private synchronized UploadBlock fetchBlock() { UploadTask task = fetchTask(); if (task == null) { return null; } for (int i = 0; i < task.blocks.length; i++) { if (task.blocks[i].state == BLOCK_QUEUED) { task.blocks[i].state = BLOCK_DOWNLOADING; byte[] block = new byte[Math.min(task.size - task.blockSize * i, task.blockSize)]; try { task.file.seek(task.blockSize * i); task.file.readFully(block); } catch (IOException e) { Logger.e(TAG, e); } task.blocks[i].workData = block; return task.blocks[i]; } } return null; } private synchronized void onBlockUploaded(UploadBlock block) { block.state = BLOCK_COMPLETED; if (block.task.listener != null) { int downloadedCount = 0; for (UploadBlock b : block.task.blocks) { if (b.state == BLOCK_COMPLETED) { downloadedCount++; } } int percent = downloadedCount * 100 / block.task.blocks.length; block.task.listener.onPartUploaded(percent, downloadedCount); } updateFileQueueStates(); } private synchronized void onBlockFailure(UploadBlock block) { block.state = BLOCK_QUEUED; updateFileQueueStates(); } public static class UploadResult { private long fileId; private boolean usedBigFile; private int partsCount; private String hash; public UploadResult(long fileId, int partsCount, String hash, boolean usedBigFile) { this.fileId = fileId; this.partsCount = partsCount; this.hash = hash; this.usedBigFile = usedBigFile; } public long getFileId() { return fileId; } public boolean isUsedBigFile() { return usedBigFile; } public int getPartsCount() { return partsCount; } public String getHash() { return hash; } } private class UploadTask { public UploadListener listener; public boolean usedBigFile; public long uniqId; public int taskId; public int blockSize; public long queueTime; public int state; public int size; public UploadBlock[] blocks; public String srcFile; public RandomAccessFile file; public String hash; } private class UploadBlock { public UploadTask task; public int state; public int index; public byte[] workData; } private class UploadFileThread extends Thread { public UploadFileThread() { setName("UploadFileThread#" + hashCode()); } @Override public void run() { setPriority(Thread.MIN_PRIORITY); while (true) { Logger.d(TAG, "UploadFileThread iteration"); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); return; } UploadBlock block = fetchBlock(); if (block == null) { synchronized (threadLocker) { try { threadLocker.wait(); continue; } catch (InterruptedException e) { Logger.e(TAG, e); return; } } } long start = System.nanoTime(); Logger.d(TAG, "Block #" + block.index + " of #" + block.task.uniqId + "| Starting"); try { if (block.task.usedBigFile) { api.doSaveBigFilePart(block.task.uniqId, block.index, block.task.blocks.length, block.workData); } else { api.doSaveFilePart(block.task.uniqId, block.index, block.workData); } block.workData = null; Logger.d(TAG, "Block #" + block.index + " of #" + block.task.uniqId + "| Uploaded in " + (System.nanoTime() - start) / (1000 * 1000L) + " ms"); onBlockUploaded(block); } catch (IOException e) { Logger.d(TAG, "Block #" + block.index + " of #" + block.task.uniqId + "| Failure"); Logger.e(TAG, e); onBlockFailure(block); } } } } }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/file/Downloader.java
src/main/java/org/telegram/api/engine/file/Downloader.java
package org.telegram.api.engine.file; import org.telegram.api.TLAbsInputFileLocation; import org.telegram.api.engine.Logger; import org.telegram.api.engine.TelegramApi; import org.telegram.api.upload.TLFile; import org.telegram.tl.TLBytes; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; /** * Created by ex3ndr on 18.11.13. */ public class Downloader { public static final int FILE_QUEUED = 0; public static final int FILE_DOWNLOADING = 1; public static final int FILE_COMPLETED = 2; public static final int FILE_CANCELED = 3; public static final int FILE_FAILURE = 4; private final AtomicInteger fileIds = new AtomicInteger(1); private final String TAG; private TelegramApi api; private static final long DOWNLOAD_TIMEOUT = 30 * 1000; private static final long DEFAULT_DELAY = 15 * 1000; private static final int BLOCK_SIZE = 16 * 1024; private static final int PARALLEL_DOWNLOAD_COUNT = 2; private static final int PARALLEL_PARTS_COUNT = 4; private static final int BLOCK_QUEUED = 0; private static final int BLOCK_DOWNLOADING = 1; private static final int BLOCK_COMPLETED = 2; private ArrayList<DownloadTask> tasks = new ArrayList<DownloadTask>(); private ArrayList<DownloadFileThread> threads = new ArrayList<DownloadFileThread>(); private final Object threadLocker = new Object(); private Random rnd = new Random(); public Downloader(TelegramApi api) { this.TAG = api.toString() + "#Downloader"; this.api = api; for (int i = 0; i < PARALLEL_PARTS_COUNT; i++) { DownloadFileThread thread = new DownloadFileThread(); thread.start(); threads.add(thread); } } public TelegramApi getApi() { return api; } private synchronized DownloadTask getTask(int taskId) { for (DownloadTask task : tasks) { if (task.taskId == taskId) { return task; } } return null; } public synchronized void cancelTask(int taskId) { DownloadTask task = getTask(taskId); if (task != null && task.state != FILE_COMPLETED) { task.state = FILE_CANCELED; Logger.d(TAG, "File #" + task.taskId + "| Canceled"); } updateFileQueueStates(); } public synchronized int getTaskState(int taskId) { DownloadTask task = getTask(taskId); if (task != null) { return task.state; } return FILE_CANCELED; } public void waitForTask(int taskId) { while (true) { int state = getTaskState(taskId); if ((state == FILE_COMPLETED) || (state == FILE_FAILURE) || (state == FILE_CANCELED)) { return; } synchronized (threadLocker) { try { threadLocker.wait(DEFAULT_DELAY); } catch (InterruptedException e) { Logger.e(TAG, e); return; } } } } public synchronized int requestTask(int dcId, TLAbsInputFileLocation location, int size, String destFile, DownloadListener listener) { int blockSize = BLOCK_SIZE; int totalBlockCount = (int) Math.ceil(((double) size) / blockSize); DownloadTask task = new DownloadTask(); task.listener = listener; task.blockSize = blockSize; task.destFile = destFile; try { task.file = new RandomAccessFile(destFile, "rw"); task.file.setLength(size); } catch (FileNotFoundException e) { Logger.e(TAG, e); } catch (IOException e) { Logger.e(TAG, e); } task.taskId = fileIds.getAndIncrement(); task.dcId = dcId; task.location = location; task.size = size; task.blocks = new DownloadBlock[totalBlockCount]; for (int i = 0; i < totalBlockCount; i++) { task.blocks[i] = new DownloadBlock(); task.blocks[i].task = task; task.blocks[i].index = i; task.blocks[i].state = BLOCK_QUEUED; } task.state = FILE_QUEUED; task.queueTime = System.nanoTime(); tasks.add(task); Logger.d(TAG, "File #" + task.taskId + "| Requested"); updateFileQueueStates(); return task.taskId; } private synchronized DownloadTask[] getActiveTasks() { ArrayList<DownloadTask> res = new ArrayList<DownloadTask>(); for (DownloadTask task : tasks) { if (task.state == FILE_DOWNLOADING) { res.add(task); } } return res.toArray(new DownloadTask[res.size()]); } private synchronized void updateFileQueueStates() { DownloadTask[] activeTasks = getActiveTasks(); outer: for (DownloadTask task : activeTasks) { for (DownloadBlock block : task.blocks) { if (block.state != BLOCK_COMPLETED) { continue outer; } } onTaskCompleted(task); } activeTasks = getActiveTasks(); int count = activeTasks.length; while (count < PARALLEL_DOWNLOAD_COUNT) { long mintime = Long.MAX_VALUE; DownloadTask minTask = null; for (DownloadTask task : tasks) { if (task.state == FILE_QUEUED && task.queueTime < mintime) { minTask = task; } } if (minTask == null) { break; } minTask.state = FILE_DOWNLOADING; Logger.d(TAG, "File #" + minTask.taskId + "| Downloading"); } synchronized (threadLocker) { threadLocker.notifyAll(); } } private synchronized void onTaskCompleted(DownloadTask task) { if (task.state != FILE_COMPLETED) { Logger.d(TAG, "File #" + task.taskId + "| Completed in " + (System.nanoTime() - task.queueTime) / (1000 * 1000L) + " ms"); task.state = FILE_COMPLETED; try { if (task.file != null) { task.file.close(); task.file = null; } } catch (IOException e) { Logger.e(TAG, e); } } updateFileQueueStates(); } private synchronized void onTaskFailure(DownloadTask task) { if (task.state != FILE_FAILURE) { Logger.d(TAG, "File #" + task.taskId + "| Failure in " + (System.nanoTime() - task.queueTime) / (1000 * 1000L) + " ms"); task.state = FILE_FAILURE; try { if (task.file != null) { task.file.close(); task.file = null; } } catch (IOException e) { Logger.e(TAG, e); } } updateFileQueueStates(); } private synchronized DownloadTask fetchTask() { DownloadTask[] activeTasks = getActiveTasks(); if (activeTasks.length == 0) { return null; } else if (activeTasks.length == 1) { return activeTasks[0]; } else { return activeTasks[rnd.nextInt(activeTasks.length)]; } } private synchronized DownloadBlock fetchBlock() { DownloadTask task = fetchTask(); if (task == null) { return null; } for (int i = 0; i < task.blocks.length; i++) { if (task.blocks[i].state == BLOCK_QUEUED) { task.blocks[i].state = BLOCK_DOWNLOADING; if (task.lastSuccessBlock == 0) { task.lastSuccessBlock = System.nanoTime(); } return task.blocks[i]; } } return null; } private synchronized void onBlockDownloaded(DownloadBlock block, TLBytes data) { try { if (block.task.file != null) { block.task.file.seek(block.index * block.task.blockSize); block.task.file.write(data.getData(), data.getOffset(), data.getLength()); } else { return; } } catch (IOException e) { Logger.e(TAG, e); } finally { api.getApiContext().releaseBytes(data); } block.task.lastSuccessBlock = System.nanoTime(); block.state = BLOCK_COMPLETED; if (block.task.listener != null) { int downloadedCount = 0; for (DownloadBlock b : block.task.blocks) { if (b.state == BLOCK_COMPLETED) { downloadedCount++; } } int percent = downloadedCount * 100 / block.task.blocks.length; block.task.listener.onPartDownloaded(percent, downloadedCount); } updateFileQueueStates(); } private synchronized void onBlockFailure(DownloadBlock block) { block.state = BLOCK_QUEUED; if (block.task.lastSuccessBlock != 0 && (System.nanoTime() - block.task.lastSuccessBlock > DOWNLOAD_TIMEOUT * 1000L * 1000L)) { onTaskFailure(block.task); } updateFileQueueStates(); } private class DownloadTask { public DownloadListener listener; public long lastNotifyTime; public int taskId; public int blockSize; public int dcId; public TLAbsInputFileLocation location; public int size; public long queueTime; public int state; public DownloadBlock[] blocks; public String destFile; public RandomAccessFile file; public long lastSuccessBlock; } private class DownloadBlock { public DownloadTask task; public int state; public int index; } private class DownloadFileThread extends Thread { public DownloadFileThread() { setName("DownloadFileThread#" + hashCode()); } @Override public void run() { setPriority(Thread.MIN_PRIORITY); while (true) { Logger.d(TAG, "DownloadFileThread iteration"); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); return; } DownloadBlock block = fetchBlock(); if (block == null) { synchronized (threadLocker) { try { threadLocker.wait(); continue; } catch (InterruptedException e) { Logger.e(TAG, e); return; } } } long start = System.nanoTime(); Logger.d(TAG, "Block #" + block.index + " of #" + block.task.taskId + "| Starting"); try { TLFile file = api.doGetFile(block.task.dcId, block.task.location, block.index * block.task.blockSize, block.task.blockSize); Logger.d(TAG, "Block #" + block.index + " of #" + block.task.taskId + "| Downloaded in " + (System.nanoTime() - start) / (1000 * 1000L) + " ms"); onBlockDownloaded(block, file.getBytes()); } catch (IOException e) { Logger.d(TAG, "Block #" + block.index + " of #" + block.task.taskId + "| Failure"); Logger.e(TAG, e); onBlockFailure(block); } } } } }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
telegram-s/telegram-api-old
https://github.com/telegram-s/telegram-api-old/blob/ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2/src/main/java/org/telegram/api/engine/file/UploadListener.java
src/main/java/org/telegram/api/engine/file/UploadListener.java
package org.telegram.api.engine.file; /** * Created by ex3ndr on 19.11.13. */ public interface UploadListener { public void onPartUploaded(int percent, int downloadedSize); }
java
MIT
ac6e15aa142ffe76d97961c02ee5f0b4a56a8ff2
2026-01-05T02:41:51.937161Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/brightcove/BrightcoveCatalog.java
content/src/main/java/com/cube/lush/player/content/brightcove/BrightcoveCatalog.java
package com.cube.lush.player.content.brightcove; import com.brightcove.player.edge.Catalog; import com.brightcove.player.event.EventEmitterImpl; import com.cube.lush.player.content.BuildConfig; /** * Created by Jamie Cruwys of 3 SIDED CUBE on 31/05/2017. */ public class BrightcoveCatalog { public static final BrightcoveCatalog INSTANCE = new BrightcoveCatalog(); private Catalog catalog; private BrightcoveCatalog() { catalog = new Catalog(new EventEmitterImpl(), BuildConfig.BRIGHTCOVE_ACCOUNT_ID, BuildConfig.BRIGHTCOVE_POLICY_KEY); } public Catalog getCatalog() { return catalog; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/brightcove/BrightcoveUtils.java
content/src/main/java/com/cube/lush/player/content/brightcove/BrightcoveUtils.java
package com.cube.lush.player.content.brightcove; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.brightcove.player.model.Playlist; import com.brightcove.player.model.Video; import com.cube.lush.player.content.model.VideoInfo; import com.google.gson.internal.bind.util.ISO8601Utils; import com.lush.player.api.model.Tag; import java.text.ParseException; import java.text.ParsePosition; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Brightcove Utility class to abstract away Brightcove's implementation * * @author Jamie Cruwys */ public class BrightcoveUtils { public static final int SECOND = 1000; public static final int MINUTE = 60 * SECOND; public static final int HOUR = 60 * MINUTE; public static final int DAY = 24 * HOUR; @SuppressWarnings("HardCodedStringLiteral") private static final String PROPERTY_NAME = "name"; @SuppressWarnings("HardCodedStringLiteral") private static final String PROPERTY_POSTER_SOURCES = "poster_sources"; @SuppressWarnings("HardCodedStringLiteral") private static final String PROPERTY_SRC = "src"; @SuppressWarnings("HardCodedStringLiteral") private static final String PROPERTY_THUMBNAIL = "thumbnail"; @SuppressWarnings("HardCodedStringLiteral") private static final String PROPERTY_TAGS = "tags"; public static String getVideoName(@NonNull Video video) { return video.getStringProperty(PROPERTY_NAME); } public static String getVideoThumbnail(@NonNull Video video) { Object posterSourcesObject = video.getProperties().get(PROPERTY_POSTER_SOURCES); // Painfully find an appropriate image to display as the background if (posterSourcesObject instanceof List) { List posterSources = (List)posterSourcesObject; if (!posterSources.isEmpty() && posterSources.get(0) instanceof Map) { Map firstPosterSource = (Map) posterSources.get(0); if (firstPosterSource.get(PROPERTY_SRC) instanceof String) { return (String)firstPosterSource.get(PROPERTY_SRC); } } } return video.getStringProperty(PROPERTY_THUMBNAIL); } public static List<Tag> getVideoTags(@NonNull Video video) { Object tagsObject = video.getProperties().get(PROPERTY_TAGS); ArrayList<Tag> tags = new ArrayList<>(); if (tagsObject instanceof List) { List tagsList = (List)tagsObject; if (!tagsList.isEmpty()) { for (Object tagItem : tagsList) { if (tagItem instanceof String) { String tagString = (String)tagItem; tags.add(new Tag(tagString, tagString)); } } } } return tags; } /** * Determines which video, if any, in a playlist is currently "live" * * @param playlist * @return */ @Nullable public static VideoInfo findCurrentLiveVideo(Playlist playlist) { long nowUtc = System.currentTimeMillis(); for (Video video: playlist.getVideos()) { try { if (video.getProperties().get("customFields") instanceof Map) { Map customFields = (Map) video.getProperties().get("customFields"); Object startTimeString = customFields.get("starttime"); if (startTimeString instanceof String) { long startTimeUtc = ISO8601Utils.parse((String) startTimeString, new ParsePosition(0)).getTime(); long duration = getDuration(video); long endTimeUtc = startTimeUtc + duration; if (nowUtc >= startTimeUtc && nowUtc < endTimeUtc) { VideoInfo videoInfo = new VideoInfo(); videoInfo.setVideo(video); videoInfo.setStartTimeUtc(startTimeUtc); videoInfo.setEndTimeUtc(endTimeUtc); return videoInfo; } } } } catch (ParseException parseEx) { // Ignore parse exception Log.e("3SC", parseEx.getMessage(), parseEx); } } return null; } private static long getDuration(@NonNull Video video) { try { Map<String, Object> properties = video.getProperties(); Map customFields = (Map) properties.get("customFields"); Object liveBroadcastLengthObject = customFields.get("livebroadcastlength"); long duration = 0; if (liveBroadcastLengthObject instanceof String) { String liveBroadcastLength = (String)liveBroadcastLengthObject; if (liveBroadcastLength != null) { String[] liveBroadcastLengthParts = liveBroadcastLength.split(":"); // length is in the format HH:MM:SS if (liveBroadcastLengthParts.length == 3) { duration += Long.parseLong(liveBroadcastLengthParts[2]) * SECOND; duration += Long.parseLong(liveBroadcastLengthParts[1]) * MINUTE; duration += Long.parseLong(liveBroadcastLengthParts[0]) * HOUR; } } } if (duration > 0) { return duration; } else { Integer durationProperty = (Integer)properties.get("duration"); return durationProperty.longValue(); } } catch (Exception e) { e.printStackTrace(); return 0; } } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/util/MediaSorter.java
content/src/main/java/com/cube/lush/player/content/util/MediaSorter.java
package com.cube.lush.player.content.util; import android.support.annotation.NonNull; import com.lush.player.api.model.Programme; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Orders a set of programmes * * @author Jamie Cruwys */ public enum MediaSorter { MOST_RECENT_FIRST, OLDEST_FIRST; /** * Sorts items * * @param items * @return programmes */ public List<Programme> sort(@NonNull List<Programme> items) { if (this == MOST_RECENT_FIRST) { return byDateAscending(items, false); } else if (this == OLDEST_FIRST) { return byDateAscending(items, true); } return items; } /** * Sorts the media content by date either ascending or descending * * @param items * @param ascending true for ascending, false for descending * @return programmes */ private List<Programme> byDateAscending(@NonNull List<Programme> items, final boolean ascending) { Collections.sort(items, new Comparator<Programme>() { @Override public int compare(Programme programme, Programme t1) { if (t1 == null || t1.getDate() == null) { return 1; } if (programme == null || programme.getDate() == null) { return -1; } int result = programme.getDate().compareTo(t1.getDate()); // Currently ordered with the oldest date first e.g. 1st July, 1st August, 1st September // Flip the sorting order from ascending to descending if (!ascending) { // Now ordered with the most recent date first e.g. 1st September, 1st August, 1st July result *= -1; } return result; } }); return items; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/model/VideoInfo.java
content/src/main/java/com/cube/lush/player/content/model/VideoInfo.java
package com.cube.lush.player.content.model; import com.brightcove.player.model.Video; /** * Brightcove video wrapper * * @author Jamie Cruwys */ public class VideoInfo { private Video video; private long startTimeUtc; private long endTimeUtc; public Video getVideo() { return video; } public void setVideo(Video video) { this.video = video; } public long getStartTimeUtc() { return startTimeUtc; } public void setStartTimeUtc(long startTimeUtc) { this.startTimeUtc = startTimeUtc; } public long getEndTimeUtc() { return endTimeUtc; } public void setEndTimeUtc(long endTimeUtc) { this.endTimeUtc = endTimeUtc; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/LatestProgrammesRepository.java
content/src/main/java/com/cube/lush/player/content/repository/LatestProgrammesRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.util.MediaSorter; import com.google.gson.reflect.TypeToken; import com.lush.player.api.model.Programme; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Latest Programmes Repository * * @author Jamie Cruwys */ public class LatestProgrammesRepository extends BaseProgrammeRepository { private static LatestProgrammesRepository instance; public LatestProgrammesRepository(@NonNull Context context) { super(context); } public static LatestProgrammesRepository getInstance(@NonNull Context context) { if (instance == null) { instance = new LatestProgrammesRepository(context); } return instance; } @Override void getItemsFromNetwork(@NonNull final ResponseHandler<Programme> callback) { final List<Programme> composite = new ArrayList<>(); Call<List<Programme>> videoArchive = api.getVideoArchive(); videoArchive.enqueue(new Callback<List<Programme>>() { @Override public void onResponse(Call<List<Programme>> call, Response<List<Programme>> response) { try { if (response != null && response.isSuccessful() && response.body() != null) { composite.addAll(response.body()); } } finally { if (composite.isEmpty()) { if (callback != null) { callback.onFailure(null); } } else { MediaSorter.MOST_RECENT_FIRST.sort(composite); if (callback != null) { callback.onSuccess(composite); } } } } @Override public void onFailure(Call<List<Programme>> call, Throwable t) { if (callback != null) { callback.onFailure(t); } } }); Call<List<Programme>> radioArchive = api.getRadioArchive(); radioArchive.enqueue(new Callback<List<Programme>>() { @Override public void onResponse(Call<List<Programme>> call, Response<List<Programme>> response) { try { if (response != null && response.isSuccessful() && response.body() != null) { composite.addAll(response.body()); } } finally { if (composite.isEmpty()) { if (callback != null) { callback.onFailure(null); } } else { MediaSorter.MOST_RECENT_FIRST.sort(composite); if (callback != null) { callback.onSuccess(composite); } } } } @Override public void onFailure(Call<List<Programme>> call, Throwable t) { if (callback != null) { callback.onFailure(t); } } }); } @Override protected TypeToken<List<Programme>> provideGsonTypeToken() { return new TypeToken<List<Programme>>(){}; } @Override protected String providePreferenceName() { return "LatestProgrammes"; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/ChannelProgrammesRepository.java
content/src/main/java/com/cube/lush/player/content/repository/ChannelProgrammesRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import com.cube.lush.player.content.handler.ResponseHandler; import com.google.gson.reflect.TypeToken; import com.lush.player.api.model.Programme; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Channels Programme respository to provide a list of programmes for a channel * * @author Jamie Cruwys */ public class ChannelProgrammesRepository extends BaseProgrammeRepository { private static ChannelProgrammesRepository instance; public ChannelProgrammesRepository(@NonNull Context context) { super(context); } public static ChannelProgrammesRepository getInstance(@NonNull Context context) { if (instance == null) { instance = new ChannelProgrammesRepository(context); } return instance; } private String channelTag; public String getChannelTag() { return channelTag; } public void setChannelTag(String channelTag) { this.channelTag = channelTag; } @Override void getItemsFromNetwork(@NonNull final ResponseHandler<Programme> callback) { Call<List<Programme>> programmes = api.getChannelProgrammes(channelTag); programmes.enqueue(new Callback<List<Programme>>() { @Override public void onResponse(Call<List<Programme>> call, Response<List<Programme>> response) { if (response != null && response.isSuccessful() && response.body() != null) { if (callback != null) { callback.onSuccess(response.body()); } } } @Override public void onFailure(Call<List<Programme>> call, Throwable t) { if (callback != null) { callback.onFailure(t); } } }); } @Override protected TypeToken<List<Programme>> provideGsonTypeToken() { return new TypeToken<List<Programme>>(){}; } @Override protected String providePreferenceName() { return "ChannelProgrammes"; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/EventProgrammesRepository.java
content/src/main/java/com/cube/lush/player/content/repository/EventProgrammesRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import com.cube.lush.player.content.handler.ResponseHandler; import com.google.gson.reflect.TypeToken; import com.lush.player.api.model.Programme; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Event Programme repository to provide a list of programmes for a event * * @author Jamie Cruwys */ public class EventProgrammesRepository extends BaseProgrammeRepository { private static EventProgrammesRepository instance; public EventProgrammesRepository(@NonNull Context context) { super(context); } public static EventProgrammesRepository getInstance(@NonNull Context context) { if (instance == null) { instance = new EventProgrammesRepository(context); } return instance; } private String eventTag = ""; public String getEventTag() { return eventTag; } public void setEventTag(String eventTag) { this.eventTag = eventTag; } @Override void getItemsFromNetwork(@NonNull final ResponseHandler<Programme> callback) { Call<List<Programme>> programmes = api.getEventProgrammes(eventTag); programmes.enqueue(new Callback<List<Programme>>() { @Override public void onResponse(Call<List<Programme>> call, Response<List<Programme>> response) { if (response != null && response.isSuccessful() && response.body() != null) { if (callback != null) { callback.onSuccess(response.body()); } } } @Override public void onFailure(Call<List<Programme>> call, Throwable t) { if (callback != null) { callback.onFailure(t); } } }); } @Override protected TypeToken<List<Programme>> provideGsonTypeToken() { return new TypeToken<List<Programme>>(){}; } @Override protected String providePreferenceName() { return "EventProgrammes"; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/Repository.java
content/src/main/java/com/cube/lush/player/content/repository/Repository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.cube.lush.player.content.handler.ResponseHandler; import com.google.gson.reflect.TypeToken; import com.lush.player.api.LushAPI; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Repository designed to be able to allow you to cache, know which content is new and get the data from the network * * @author Jamie Cruwys */ public abstract class Repository<T> { public static final String TAG = Repository.class.getSimpleName(); public static final String PREFERENCE_CACHE_STORE = "RepositoryCache"; public static final int SECOND = 1000; public static final int MINUTE = 60 * SECOND; public static final int HOUR = 60 * MINUTE; public static final int DAY = 24 * HOUR; private Set<T> items = new HashSet<>(); private Set<T> newItems = new HashSet<>(); private long lastRequestTime = 0; protected LushAPI api; protected Context context; public interface ItemRetrieval<T> { void onItemsRetrieved(@NonNull Set<T> items); void onItemRetrievalFailed(@NonNull Throwable throwable); } public Repository(@NonNull Context context) { this.context = context; api = APIManager.INSTANCE.getAPI(); } public Set<T> getNewItems() { return newItems; } /** * Get items from the network and callback using the response handler * @param callback to use to provide the results of the network request */ abstract void getItemsFromNetwork(@NonNull ResponseHandler<T> callback); /** * Provide the cache expiry time using the constants in {@link Repository} * @return an int representing the cache expiry time in milliseconds */ public @IntRange(from=0) int getCacheExpiryTime() { return 5 * MINUTE; } /** * Get items from either the cache, or make a network request if the cache has expired. */ public void getItems(@Nullable final ResponseHandler<T> callback) { if (isFirstUsage()) { loadItemsFromDisk(); } if (cacheOutdated()) { getItemsFromNetwork(new ResponseHandler<T>() { /** * When the items have come back from the network * @param latestItems {@link List<T>} that have come back from the network. This can be empty, but not null. */ @Override public void onSuccess(@NonNull List<T> latestItems) { updateItems(latestItems); if (callback != null) { callback.onSuccess(latestItems); } } /** * When the network request fails * @param t {@link Throwable} for the failure */ @Override public void onFailure(@Nullable Throwable t) { if (items != null) { // Use cached content if (callback != null) { callback.onSuccess(getCachedItems()); } Log.w(TAG, "Network unavailable, using cache"); } else { if (callback != null) { callback.onFailure(t); } } } }); } else { if (callback != null) { callback.onSuccess(getCachedItems()); } } } private List<T> getCachedItems() { List<T> cachedItems = new ArrayList<>(); cachedItems.addAll(items); return cachedItems; } private boolean isFirstUsage() { return items.isEmpty() && newItems.isEmpty() && lastRequestTime == 0; } /** * Gets items from the cache synchronously, and requests new data if necessary so the next call has the correct dataset. * This should only be used for edge cases. For most cases, you should use {@link #getItems(ResponseHandler)} * @return {@link List<T>} of items which can be empty, but not null. */ public List<T> getItemsSynchronously() { ArrayList<T> cachedItems = new ArrayList<T>(); cachedItems.addAll(items); if (cacheOutdated()) { getItems(null); } return cachedItems; } /** * Works out if the cache is outdated * @return true if the cache is outdated, false if it is not. */ private boolean cacheOutdated() { return System.currentTimeMillis() > (lastRequestTime + getCacheExpiryTime()); } /** * Update the items * @param latestItems to update */ protected void updateItems(@NonNull List<T> latestItems) { items.addAll(latestItems); newItems = new HashSet<>(items); newItems.removeAll(latestItems); saveItemsToDisk(items); } private void saveItemsToDisk(@Nullable Set<T> itemsToSave) { String json = GsonSingleton.getInstance().toJson(itemsToSave); SharedPreferences sharedPreferences = context.getSharedPreferences(PREFERENCE_CACHE_STORE, Context.MODE_PRIVATE); sharedPreferences.edit() .putString(providePreferenceName(), json) .apply(); } private void loadItemsFromDisk() { try { SharedPreferences sharedPreferences = context.getSharedPreferences(PREFERENCE_CACHE_STORE, Context.MODE_PRIVATE); String json = sharedPreferences.getString(providePreferenceName(), null); List<T> itemsFromDisk = GsonSingleton.getInstance().fromJson(json, provideGsonTypeToken().getType()); if (itemsFromDisk == null || itemsFromDisk.isEmpty()) { items = new HashSet<T>(); } else { items = new HashSet<T>(itemsFromDisk); } } catch (Exception e) { Log.e("Repository", "Failed to load cached JSON content"); } } protected abstract TypeToken<List<T>> provideGsonTypeToken(); /** * Provide the preference name to use to store cached data for this repository * @return String for the */ protected abstract String providePreferenceName(); /** * Is this item new? * @param item that we want to check if it is new * @return true if the item is new, false if it is not new */ public boolean isNew(@NonNull T item) { return items.contains(item); } /** * Mark the item as watched and remove it from the new items * @param item that we have just watched */ public void watched(@NonNull T item) { newItems.remove(item); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/TaggedProgrammeRepository.java
content/src/main/java/com/cube/lush/player/content/repository/TaggedProgrammeRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import com.cube.lush.player.content.handler.ResponseHandler; import com.google.gson.reflect.TypeToken; import com.lush.player.api.model.Programme; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Tagged Programme respository to provide a list of programmes for a tag * * @author Jamie Cruwys */ public class TaggedProgrammeRepository extends BaseProgrammeRepository { private static TaggedProgrammeRepository instance; @NonNull private String tag = ""; public TaggedProgrammeRepository(@NonNull Context context) { super(context); } @NonNull public String getTag() { return tag; } public void setTag(@NonNull String tag) { this.tag = tag; } public static TaggedProgrammeRepository getInstance(@NonNull Context context) { if (instance == null) { instance = new TaggedProgrammeRepository(context); } return instance; } @Override void getItemsFromNetwork(@NonNull final ResponseHandler<Programme> callback) { tag = tag.replace("#", ""); Call<List<Programme>> programmes = api.getProgrammesForTag(tag); programmes.enqueue(new Callback<List<Programme>>() { @Override public void onResponse(Call<List<Programme>> call, Response<List<Programme>> response) { if (response != null && response.isSuccessful() && response.body() != null) { if (callback != null) { callback.onSuccess(response.body()); } } } @Override public void onFailure(Call<List<Programme>> call, Throwable t) { if (callback != null) { callback.onFailure(t); } } }); } @Override protected TypeToken<List<Programme>> provideGsonTypeToken() { return new TypeToken<List<Programme>>(){}; } @Override protected String providePreferenceName() { return "TaggedProgramme"; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/LivePlaylistRepository.java
content/src/main/java/com/cube/lush/player/content/repository/LivePlaylistRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import com.cube.lush.player.content.handler.ResponseHandler; import com.google.gson.reflect.TypeToken; import com.lush.player.api.model.LivePlaylist; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Live Playlist respository to provide a list of live playlists * * @author Jamie Cruwys */ public class LivePlaylistRepository extends Repository<LivePlaylist> { private static LivePlaylistRepository instance; public LivePlaylistRepository(@NonNull Context context) { super(context); } public static LivePlaylistRepository getInstance(@NonNull Context context) { if (instance == null) { instance = new LivePlaylistRepository(context); } return instance; } @Override public int getCacheExpiryTime() { return 0; } @Override void getItemsFromNetwork(@NonNull final ResponseHandler<LivePlaylist> callback) { Call<List<LivePlaylist>> livePlaylist = api.getLivePlaylist("0"); livePlaylist.enqueue(new Callback<List<LivePlaylist>>() { @Override public void onResponse(Call<List<LivePlaylist>> call, Response<List<LivePlaylist>> response) { if (response != null && response.isSuccessful() && response.body() != null) { if (callback != null) { callback.onSuccess(response.body()); } } } @Override public void onFailure(Call<List<LivePlaylist>> call, Throwable t) { if (callback != null) { callback.onFailure(t); } } }); } @Override protected TypeToken<List<LivePlaylist>> provideGsonTypeToken() { return new TypeToken<List<LivePlaylist>>(){}; } @Override protected String providePreferenceName() { return "LivePlaylist"; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/BaseProgrammeRepository.java
content/src/main/java/com/cube/lush/player/content/repository/BaseProgrammeRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import com.lush.player.api.model.ContentType; import com.lush.player.api.model.Programme; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.lush.player.api.model.ContentType.RADIO; import static com.lush.player.api.model.ContentType.TV; /** * Base Programme repository to provide filtering by content type * * @author Jamie Cruwys */ abstract class BaseProgrammeRepository extends Repository<Programme> { protected Set<Programme> videos = new HashSet<>(); protected Set<Programme> radios = new HashSet<>(); public BaseProgrammeRepository(@NonNull Context context) { super(context); } public Set<Programme> getVideos() { return videos; } public Set<Programme> getRadios() { return radios; } @Override protected void updateItems(@NonNull List<Programme> latestItems) { super.updateItems(latestItems); if (latestItems.isEmpty()) { return; } for (Programme programme : latestItems) { if (programme == null || TextUtils.isEmpty(programme.getId())) { continue; } ContentType type = programme.getType(); if (type == TV) { videos.add(programme); } else if (type == RADIO) { radios.add(programme); } } } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/SearchProgrammeRepository.java
content/src/main/java/com/cube/lush/player/content/repository/SearchProgrammeRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import com.cube.lush.player.content.handler.ResponseHandler; import com.google.gson.reflect.TypeToken; import com.lush.player.api.model.Programme; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Search Programme respository to provide a list of programmes for a search term * * @author Jamie Cruwys */ public class SearchProgrammeRepository extends BaseProgrammeRepository { private static SearchProgrammeRepository instance; @NonNull private String searchTerm = ""; public SearchProgrammeRepository(@NonNull Context context) { super(context); } @NonNull public String getSearchTerm() { return searchTerm; } public void setSearchTerm(@NonNull String searchTerm) { this.searchTerm = searchTerm; } public static SearchProgrammeRepository getInstance(@NonNull Context context) { if (instance == null) { instance = new SearchProgrammeRepository(context); } return instance; } @Override void getItemsFromNetwork(@NonNull final ResponseHandler<Programme> callback) { String requestSearchTerm = searchTerm; requestSearchTerm = requestSearchTerm.replace(" ", "+"); Call<List<Programme>> programmes = api.search(requestSearchTerm); programmes.enqueue(new Callback<List<Programme>>() { @Override public void onResponse(Call<List<Programme>> call, Response<List<Programme>> response) { if (response != null && response.isSuccessful() && response.body() != null) { if (callback != null) { callback.onSuccess(response.body()); } } } @Override public void onFailure(Call<List<Programme>> call, Throwable t) { if (callback != null) { callback.onFailure(t); } } }); } @Override protected TypeToken<List<Programme>> provideGsonTypeToken() { return new TypeToken<List<Programme>>(){}; } @Override protected String providePreferenceName() { return "SearchProgramme"; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/ChannelRepository.java
content/src/main/java/com/cube/lush/player/content/repository/ChannelRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import com.cube.lush.player.content.handler.ResponseHandler; import com.google.gson.reflect.TypeToken; import com.lush.player.api.model.Channel; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Channels respository to provide a list of channels * * @author Jamie Cruwys */ public class ChannelRepository extends Repository<Channel> { private static ChannelRepository instance; public ChannelRepository(@NonNull Context context) { super(context); } public static ChannelRepository getInstance(@NonNull Context context) { if (instance == null) { instance = new ChannelRepository(context); } return instance; } @Override void getItemsFromNetwork(@NonNull final ResponseHandler<Channel> callback) { Call<List<Channel>> channels = api.getChannels(); channels.enqueue(new Callback<List<Channel>>() { @Override public void onResponse(Call<List<Channel>> call, Response<List<Channel>> response) { if (response != null && response.isSuccessful() && response.body() != null) { if (callback != null) { callback.onSuccess(response.body()); } } else { if (callback != null) { callback.onFailure(null); } } } @Override public void onFailure(Call<List<Channel>> call, Throwable t) { if (callback != null) { callback.onFailure(t); } } }); } @Override protected TypeToken<List<Channel>> provideGsonTypeToken() { return new TypeToken<List<Channel>>(){}; } @Override protected String providePreferenceName() { return "Channel"; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/GsonSingleton.java
content/src/main/java/com/cube/lush/player/content/repository/GsonSingleton.java
package com.cube.lush.player.content.repository; import com.google.gson.Gson; /** * <Class Description> * * @author Jamie Cruwys */ public class GsonSingleton { private static Gson gson; public static Gson getInstance() { if (gson == null) { gson = new Gson(); } return gson; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/EventRepository.java
content/src/main/java/com/cube/lush/player/content/repository/EventRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import com.cube.lush.player.content.handler.ResponseHandler; import com.google.gson.reflect.TypeToken; import com.lush.player.api.model.Event; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Event respository to provide a list of all events * * @author Jamie Cruwys */ public class EventRepository extends Repository<Event> { public static final Event ALL_EVENTS = new Event("All Events"); private static EventRepository instance; public EventRepository(@NonNull Context context) { super(context); } public static EventRepository getInstance(@NonNull Context context) { if (instance == null) { instance = new EventRepository(context); } return instance; } @Override void getItemsFromNetwork(@NonNull final ResponseHandler<Event> callback) { Call<List<Event>> events = api.getEvents(); events.enqueue(new Callback<List<Event>>() { @Override public void onResponse(Call<List<Event>> call, Response<List<Event>> response) { if (response != null && response.isSuccessful() && response.body() != null) { if (callback != null) { callback.onSuccess(response.body()); } } } @Override public void onFailure(Call<List<Event>> call, Throwable t) { if (callback != null) { callback.onFailure(t); } } }); } @Override protected TypeToken<List<Event>> provideGsonTypeToken() { return new TypeToken<List<Event>>(){}; } @Override protected String providePreferenceName() { return "Event"; } public List<Event> getEventTabs() { ArrayList<Event> events = new ArrayList<Event>(); events.add(ALL_EVENTS); events.addAll(getItemsSynchronously()); return events; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/APIManager.java
content/src/main/java/com/cube/lush/player/content/repository/APIManager.java
package com.cube.lush.player.content.repository; import com.lush.player.api.API; import com.lush.player.api.LushAPI; /** * API Manager * * @author Jamie Cruwys */ public class APIManager { private APIManager() { } public static final APIManager INSTANCE = new APIManager(); public LushAPI getAPI() { return API.INSTANCE.getApi(); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/repository/ProgrammeRepository.java
content/src/main/java/com/cube/lush/player/content/repository/ProgrammeRepository.java
package com.cube.lush.player.content.repository; import android.content.Context; import android.support.annotation.NonNull; import com.lush.player.api.model.Programme; /** * Programme Repository convenience class * * @author Jamie Cruwys */ public class ProgrammeRepository { public static boolean isNew(@NonNull Context context, @NonNull Programme programme) { if (ChannelProgrammesRepository.getInstance(context).isNew(programme)) { return true; } if (EventProgrammesRepository.getInstance(context).isNew(programme)) { return true; } if (LatestProgrammesRepository.getInstance(context).isNew(programme)) { return true; } if (SearchProgrammeRepository.getInstance(context).isNew(programme)) { return true; } if (TaggedProgrammeRepository.getInstance(context).isNew(programme)) { return true; } return false; } public static void watched(@NonNull Context context, @NonNull Programme programme) { ChannelProgrammesRepository.getInstance(context).watched(programme); EventProgrammesRepository.getInstance(context).watched(programme); LatestProgrammesRepository.getInstance(context).watched(programme); SearchProgrammeRepository.getInstance(context).watched(programme); TaggedProgrammeRepository.getInstance(context).watched(programme); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/content/src/main/java/com/cube/lush/player/content/handler/ResponseHandler.java
content/src/main/java/com/cube/lush/player/content/handler/ResponseHandler.java
package com.cube.lush.player.content.handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.List; /** * Interface for outcomes given in response to a request for a list of items. * * @param <T> response data model * @author Jamie Cruwys */ public interface ResponseHandler<T> { void onSuccess(@NonNull List<T> items); void onFailure(@Nullable Throwable t); }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/test/java/com/lush/player/ChannelBrowseFragmentRegressionUnitTest.java
app/src/test/java/com/lush/player/ChannelBrowseFragmentRegressionUnitTest.java
package com.lush.player; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import static org.junit.Assert.assertTrue; /** * <Class Description> * * @author Jamie Cruwys */ @RunWith(MockitoJUnitRunner.class) public class ChannelBrowseFragmentRegressionUnitTest { private MockChannelBrowseFragment fragment; @Test public void null_channel_causing_null_pointer_regression() { fragment = new MockChannelBrowseFragment(); fragment.channel = null; // Fetch data should cause a crash by now if the regression exists fragment.fetchData(); // If it didn't crash then mark the test as successful assertTrue(true); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/test/java/com/lush/player/MockChannelBrowseFragment.java
app/src/test/java/com/lush/player/MockChannelBrowseFragment.java
package com.lush.player; import com.cube.lush.player.tv.channels.ChannelBrowseFragment; import com.lush.player.api.model.Channel; /** * <Class Description> * * @author Jamie Cruwys */ public class MockChannelBrowseFragment extends ChannelBrowseFragment { public Channel channel; @Override public void fetchData() { super.fetchData(); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/LushImageLoader.java
app/src/main/java/com/cube/lush/player/LushImageLoader.java
package com.cube.lush.player; import android.support.annotation.NonNull; import android.util.DisplayMetrics; import android.util.TypedValue; import android.widget.ImageView; import com.squareup.picasso.Picasso; /** * <Class Description> * * @author Jamie Cruwys */ public class LushImageLoader { public static void display(@NonNull String url, @NonNull ImageView imageView) { DisplayMetrics displayMetrics = imageView.getContext().getResources().getDisplayMetrics(); float width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 360, displayMetrics); float height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 480, displayMetrics); display(url, imageView, (int)width, (int)height); } public static void display(@NonNull String url, @NonNull ImageView imageView, int widthDp, int heightDp) { Picasso.with(imageView.getContext()) .load(url) .resize(widthDp, heightDp) .into(imageView); } public static void cancelDisplay(@NonNull ImageView imageView) { Picasso.with(imageView.getContext()) .cancelRequest(imageView); imageView.setImageDrawable(null); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/MainApplication.java
app/src/main/java/com/cube/lush/player/MainApplication.java
package com.cube.lush.player; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import com.cube.lush.player.analytics.Track; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.repository.ChannelProgrammesRepository; import com.cube.lush.player.content.repository.ChannelRepository; import com.cube.lush.player.content.repository.EventProgrammesRepository; import com.cube.lush.player.content.repository.EventRepository; import com.cube.lush.player.content.repository.LatestProgrammesRepository; import com.lush.LushApplication; import com.lush.player.api.API; import com.lush.player.api.model.Channel; import com.lush.player.api.model.Event; import com.lush.player.api.model.Programme; import com.squareup.picasso.Picasso; import java.util.List; /** * Main Application * * @author Jamie Cruwys */ public class MainApplication extends LushApplication { private static Context context; @Override public void onCreate() { super.onCreate(); context = this; API.INSTANCE.initialise(this); Track.initialise(this); if (BuildConfig.DEBUG) { Picasso picasso = Picasso.with(context); picasso.setLoggingEnabled(true); picasso.setIndicatorsEnabled(true); } preloadData(); } private void preloadData() { final Context context = this; ChannelRepository.getInstance(context).getItems(new ResponseHandler<Channel>() { @Override public void onSuccess(@NonNull List<Channel> items) { for (Channel channel : items) { if (channel == null) { continue; } preloadImageUrl(channel.getImage()); if (TextUtils.isEmpty(channel.getTag())) { continue; } ChannelProgrammesRepository.getInstance(context).setChannelTag(channel.getTag()); ChannelProgrammesRepository.getInstance(context).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { // Preload all images for (Programme programme : items) { if (programme == null || TextUtils.isEmpty(programme.getThumbnail())) { continue; } } } @Override public void onFailure(@Nullable Throwable t) { // NO-OP, just trying to initialise the data set } }); } } @Override public void onFailure(@Nullable Throwable t) { // NO-OP, just trying to initialise the data set } }); EventRepository.getInstance(context).getItems(new ResponseHandler<Event>() { @Override public void onSuccess(@NonNull List<Event> items) { for (Event event : items) { if (event == null || TextUtils.isEmpty(event.getTag())) { continue; } EventProgrammesRepository.getInstance(context).setEventTag(event.getTag()); EventProgrammesRepository.getInstance(context).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { // Preload all images for (Programme programme : items) { if (programme == null || TextUtils.isEmpty(programme.getThumbnail())) { continue; } } } @Override public void onFailure(@Nullable Throwable t) { // NO-OP, just trying to initialise the data set } }); } } @Override public void onFailure(@Nullable Throwable t) { // NO-OP, just trying to initialise the data set } }); LatestProgrammesRepository.getInstance(this).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { // Preload all images for (Programme programme : items) { if (programme == null || TextUtils.isEmpty(programme.getThumbnail())) { continue; } } } @Override public void onFailure(@Nullable Throwable t) { // NO-OP, just trying to initialise the data set } }); } private void preloadImageUrl(@Nullable String url) { if (!TextUtils.isEmpty(url)) { Picasso.with(context) .load(url) .fetch(); } } public static Context getContext() { return context; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/MainActivity.java
app/src/main/java/com/cube/lush/player/mobile/MainActivity.java
package com.cube.lush.player.mobile; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.view.KeyEvent; import android.widget.FrameLayout; import android.widget.Toast; import com.aurelhubert.ahbottomnavigation.AHBottomNavigation; import com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem; import com.cube.lush.player.R; import com.cube.lush.player.mobile.base.BaseMobileActivity; import com.cube.lush.player.mobile.channels.ChannelsFragment; import com.cube.lush.player.mobile.details.DetailsFragment; import com.cube.lush.player.mobile.events.EventsFragment; import com.cube.lush.player.mobile.home.HomeFragment; import com.cube.lush.player.mobile.live.LiveFragment; import com.cube.lush.player.mobile.playback.LushPlaybackActivity; import com.cube.lush.player.mobile.search.SearchFragment; import com.lush.player.api.API; import com.lush.player.api.model.Programme; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import uk.co.jamiecruwys.ViewState; /** * Main Activity * * @author Jamie Cruwys */ public class MainActivity extends BaseMobileActivity implements AHBottomNavigation.OnTabSelectedListener { @BindView(R.id.bottom_navigation) AHBottomNavigation bottomNavigation; @BindView(R.id.container) FrameLayout container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ButterKnife.bind(this); setupNavigation(); if (savedInstanceState == null) { selectTab(LushTab.HOME); } String appLinkProgrammeAlias = getAppLinkProgrammeAlias(getIntent()); // Has been launched by app link if (!TextUtils.isEmpty(appLinkProgrammeAlias)) { setViewState(ViewState.LOADING); Call<List<Programme>> programmeCall = API.INSTANCE.getApi().getProgramme(appLinkProgrammeAlias); programmeCall.enqueue(new Callback<List<Programme>>() { @Override public void onResponse(Call<List<Programme>> call, Response<List<Programme>> response) { if (response != null && response.body() != null && !response.body().isEmpty()) { setViewState(ViewState.LOADED); Programme programme = response.body().get(0); DetailsFragment detailsFragment = DetailsFragment.newInstance(programme); showNoHistoryFragment(detailsFragment); } else { onError(); } } @Override public void onFailure(Call<List<Programme>> call, Throwable throwable) { onError(); } private void onError() { Toast.makeText(MainActivity.this, "We weren't able to load this video. Please try again later.", Toast.LENGTH_LONG).show(); finish(); } }); } } @Nullable private String getAppLinkProgrammeAlias(@Nullable Intent intent) { if (intent != null) { Uri data = intent.getData(); if (data != null) { List<String> pathSegments = data.getPathSegments(); if (pathSegments != null && !pathSegments.isEmpty() && pathSegments.size() > 1) { // 1st segment should be "radio" or "tv" // 2nd segment should be the video id return pathSegments.get(1); } } } return null; } private void setupNavigation() { ArrayList<AHBottomNavigationItem> items = new ArrayList<>(); items.add(new AHBottomNavigationItem(R.string.title_home, R.drawable.ic_home, android.R.color.black)); items.add(new AHBottomNavigationItem(R.string.title_live, R.drawable.ic_live, android.R.color.black)); items.add(new AHBottomNavigationItem(R.string.title_channels, R.drawable.ic_channels, android.R.color.black)); items.add(new AHBottomNavigationItem(R.string.title_events, R.drawable.ic_events, android.R.color.black)); items.add(new AHBottomNavigationItem(R.string.title_search, R.drawable.ic_search, android.R.color.black)); for (AHBottomNavigationItem item : items) { bottomNavigation.addItem(item); } // Colour for selected item bottomNavigation.setAccentColor(Color.BLACK); // Colour for unselected items bottomNavigation.setInactiveColor(ContextCompat.getColor(this, R.color.dark_grey)); // Background colour bottomNavigation.setDefaultBackgroundColor(Color.WHITE); // Forces titles to show, which the standard bottom bar does not support bottomNavigation.setForceTitlesDisplay(true); // Tab selection bottomNavigation.setOnTabSelectedListener(this); } @Override public int provideLoadingLayout() { return R.layout.main_loading; } @Override public int provideEmptyLayout() { return R.layout.main_empty; } @Override public int provideLoadedLayout() { return R.layout.main_loaded; } @Override public int provideErrorLayout() { return R.layout.main_error; } @Override public ViewState provideInitialViewState() { return ViewState.LOADED; } @Override public boolean onTabSelected(int position, boolean wasSelected) { switch (position) { case 0: showNoHistoryFragment(HomeFragment.newInstance()); return true; case 1: showNoHistoryFragment(LiveFragment.newInstance()); return true; case 2: showNoHistoryFragment(ChannelsFragment.newInstance()); return true; case 3: showNoHistoryFragment(EventsFragment.newInstance()); return true; case 4: showNoHistoryFragment(SearchFragment.newInstance()); return true; default: throw new RuntimeException("Unknown tab selected"); } } public void selectTab(@NonNull LushTab tab) { bottomNavigation.setCurrentItem(tab.getPosition()); } public void showFragment(@NonNull Fragment fragment) { showFragment(fragment, true); } private void showNoHistoryFragment(@NonNull Fragment fragment) { showFragment(fragment, false); } private void showFragment(@NonNull Fragment fragment, boolean preserveHistory) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); if (preserveHistory) { transaction.add(container.getId(), fragment); transaction.addToBackStack(null); } else { // Tab selection transaction.replace(container.getId(), fragment); } transaction.commit(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (getSupportFragmentManager().getBackStackEntryCount() == 0) { finish(); return false; } getSupportFragmentManager().popBackStack(); return false; } return super.onKeyDown(keyCode, event); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == LushPlaybackActivity.RESULT_CODE) { int startTime = data.getIntExtra(LushPlaybackActivity.EXTRA_START_TIME, 0); Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container); if (fragment instanceof DetailsFragment) { DetailsFragment detailsFragment = (DetailsFragment)fragment; detailsFragment.seekTo(startTime); } } } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/LushTab.java
app/src/main/java/com/cube/lush/player/mobile/LushTab.java
package com.cube.lush.player.mobile; /** * Lush Tab * * @author Jamie Cruwys */ public enum LushTab { HOME(0), LIVE(1), CHANNELS(2), EVENTS(3), SEARCH(4); private int position; LushTab(int position) { this.position = position; } public int getPosition() { return position; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/content/ChannelContentFragment.java
app/src/main/java/com/cube/lush/player/mobile/content/ChannelContentFragment.java
package com.cube.lush.player.mobile.content; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.text.TextUtils; import com.cube.lush.player.R; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.repository.ChannelProgrammesRepository; import com.cube.lush.player.content.util.MediaSorter; import com.cube.lush.player.mobile.base.BaseContentFragment; import com.cube.lush.player.mobile.model.ProgrammeFilterOption; import com.lush.player.api.model.Channel; import com.lush.player.api.model.ContentType; import com.lush.player.api.model.Programme; import java.util.ArrayList; import java.util.List; import uk.co.jamiecruwys.contracts.ListingData; /** * Channel Content Fragment * * @author Jamie Cruwys */ public class ChannelContentFragment extends BaseContentFragment { @SuppressWarnings("HardCodedStringLiteral") private static final String ARG_CHANNEL = "arg_channel"; private Channel channel; public ChannelContentFragment() { // Required empty public constructor } public static ChannelContentFragment newInstance(@NonNull Channel channel) { ChannelContentFragment fragment = new ChannelContentFragment(); Bundle args = new Bundle(); args.putSerializable(ARG_CHANNEL, channel); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); channel = (Channel)getArguments().getSerializable(ARG_CHANNEL); } @Override public void getListDataForFilterOption(@NonNull final ProgrammeFilterOption filterOption, @NonNull final ListingData callback) { ChannelProgrammesRepository.getInstance(getContext()).setChannelTag(channel.getTag()); ChannelProgrammesRepository.getInstance(getContext()).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { if (filterOption == ProgrammeFilterOption.TV) { items = filterByContentType(items, ContentType.TV); } else if (filterOption == ProgrammeFilterOption.RADIO) { items = filterByContentType(items, ContentType.RADIO); } items = filterByChannel(items, channel.getTag()); MediaSorter.MOST_RECENT_FIRST.sort(items); if (callback != null) { callback.onListingDataRetrieved(items); } } @Override public void onFailure(@Nullable Throwable t) { if (callback != null) { callback.onListingDataError(t); } } }); } private List<Programme> filterByChannel(@NonNull List<Programme> items, @NonNull String channelName) { ArrayList<Programme> channelProgrammes = new ArrayList<>(); for (Programme item : items) { if (item != null && !TextUtils.isEmpty(item.getChannel()) && item.getChannel().equals(channelName)) { channelProgrammes.add(item); } } return channelProgrammes; } private List<Programme> filterByContentType(@NonNull List<Programme> items, @NonNull ContentType contentType) { ArrayList<Programme> contentTypeProgrammes = new ArrayList<>(); for (Programme item : items) { if (item != null && item.getType() != null && item.getType() == contentType) { contentTypeProgrammes.add(item); } } return contentTypeProgrammes; } @NonNull @Override public String provideContentTitle() { return channel.getName(); } @NonNull @Override public LinearLayoutManager provideLayoutManagerForFilterOption(ProgrammeFilterOption filterOption) { final int NUMBER_COLUMNS = getResources().getInteger(R.integer.channel_content_columns); return new GridLayoutManager(getContext(), NUMBER_COLUMNS); } @Override public void onSaveInstanceState(Bundle outState) { outState.putSerializable(ARG_CHANNEL, channel); super.onSaveInstanceState(outState); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/content/TagContentFragment.java
app/src/main/java/com/cube/lush/player/mobile/content/TagContentFragment.java
package com.cube.lush.player.mobile.content; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import com.cube.lush.player.R; import com.lush.player.api.model.Programme; import com.lush.player.api.model.Tag; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.repository.TaggedProgrammeRepository; import com.cube.lush.player.content.util.MediaSorter; import com.cube.lush.player.mobile.base.BaseContentFragment; import com.cube.lush.player.mobile.model.ProgrammeFilterOption; import java.util.ArrayList; import java.util.List; import java.util.Set; import uk.co.jamiecruwys.contracts.ListingData; /** * Tag Content Fragment * * @author Jamie Cruwys */ public class TagContentFragment extends BaseContentFragment { @SuppressWarnings("HardCodedStringLiteral") private static final String ARG_TAG = "arg_tag"; private Tag tag; public TagContentFragment() { // Required empty public constructor } public static TagContentFragment newInstance(@NonNull Tag tag) { TagContentFragment fragment = new TagContentFragment(); Bundle args = new Bundle(); args.putSerializable(ARG_TAG, tag); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); tag = (Tag)getArguments().getSerializable(ARG_TAG); } @Override public void getListDataForFilterOption(@NonNull final ProgrammeFilterOption filterOption, @NonNull final ListingData callback) { TaggedProgrammeRepository.getInstance(getContext()).setTag(tag.getTag()); TaggedProgrammeRepository.getInstance(getContext()).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { if (filterOption == ProgrammeFilterOption.ALL) { MediaSorter.MOST_RECENT_FIRST.sort(items); if (callback != null) { callback.onListingDataRetrieved(items); } } else if (filterOption == ProgrammeFilterOption.TV) { Set<Programme> videos = TaggedProgrammeRepository.getInstance(getContext()).getVideos(); List videosList = new ArrayList(); videosList.addAll(videos); MediaSorter.MOST_RECENT_FIRST.sort(videosList); if (callback != null) { callback.onListingDataRetrieved(videosList); } } else if (filterOption == ProgrammeFilterOption.RADIO) { Set<Programme> radios = TaggedProgrammeRepository.getInstance(getContext()).getRadios(); List radiosList = new ArrayList(); radiosList.addAll(radios); MediaSorter.MOST_RECENT_FIRST.sort(radiosList); if (callback != null) { callback.onListingDataRetrieved(radiosList); } } } @Override public void onFailure(@Nullable Throwable t) { if (callback != null) { callback.onListingDataError(t); } } }); } @NonNull @Override public String provideContentTitle() { return "Tag: " + tag.getName(); } @NonNull @Override public LinearLayoutManager provideLayoutManagerForFilterOption(ProgrammeFilterOption filterOption) { final int NUMBER_COLUMNS = getResources().getInteger(R.integer.tag_content_columns); return new GridLayoutManager(getContext(), NUMBER_COLUMNS); } @Override public void onSaveInstanceState(Bundle outState) { outState.putSerializable(ARG_TAG, tag); super.onSaveInstanceState(outState); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/content/adapter/ContentAdapter.java
app/src/main/java/com/cube/lush/player/mobile/content/adapter/ContentAdapter.java
package com.cube.lush.player.mobile.content.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cube.lush.player.R; import com.lush.player.api.model.Programme; import com.cube.lush.player.mobile.content.holder.ContentViewHolder; import com.lush.lib.adapter.BaseSelectableListAdapter; import com.lush.lib.listener.OnListItemClickListener; import com.lush.view.holder.BaseViewHolder; import java.util.List; /** * Content Adapter * * @author Jamie Cruwys */ public class ContentAdapter extends BaseSelectableListAdapter<Programme> { public ContentAdapter(List<Programme> items, OnListItemClickListener<Programme> listener) { super(items, listener); } @Override public BaseViewHolder<Programme> onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_item, parent, false); return new ContentViewHolder(view); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/content/adapter/ContentCarouselAdapter.java
app/src/main/java/com/cube/lush/player/mobile/content/adapter/ContentCarouselAdapter.java
package com.cube.lush.player.mobile.content.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cube.lush.player.R; import com.lush.player.api.model.Programme; import com.cube.lush.player.mobile.content.holder.ContentViewHolder; import com.lush.lib.adapter.BaseSelectableListAdapter; import com.lush.lib.listener.OnListItemClickListener; import com.lush.view.holder.BaseViewHolder; import java.util.List; /** * Content Adapter for the horizontal scrolling carousel * * @author Jamie Cruwys */ public class ContentCarouselAdapter extends BaseSelectableListAdapter<Programme> { public ContentCarouselAdapter(List<Programme> items, OnListItemClickListener<Programme> listener) { super(items, listener); } @Override public BaseViewHolder<Programme> onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_carousel_item, parent, false); return new ContentViewHolder(view); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/content/holder/ContentViewHolder.java
app/src/main/java/com/cube/lush/player/mobile/content/holder/ContentViewHolder.java
package com.cube.lush.player.mobile.content.holder; import android.graphics.drawable.Drawable; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.cube.lush.player.LushImageLoader; import com.cube.lush.player.R; import com.lush.player.api.model.ContentType; import com.lush.player.api.model.Programme; import com.lush.view.holder.BaseViewHolder; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; /** * Content View Holder * * @author Jamie Cruwys */ public class ContentViewHolder extends BaseViewHolder<Programme> { @BindView(R.id.image) public ImageView image; @BindView(R.id.channel) public TextView channel; @BindView(R.id.title) public TextView title; @BindView(R.id.type) public ImageView type; @BindView(R.id.date) public TextView date; // @BindView(R.id.new_indicator) public TextView newIndicator; public ContentViewHolder(View view) { super(view); ButterKnife.bind(this, view); } @Override public void bind(Programme programme) { Picasso.with(image.getContext()) .load(programme.getThumbnail()) .fit() .centerCrop() .into(image); setTextOrHide(programme.getChannel(), channel); setTextOrHide(programme.getTitle(), title); setTextOrHide(programme.getRelativeDate(), date); setType(programme.getType(), type); } private void setTextOrHide(@Nullable String text, @NonNull TextView textView) { if (text == null || TextUtils.isEmpty(text)) { textView.setText(""); textView.setVisibility(View.GONE); } else { textView.setText(text); textView.setVisibility(View.VISIBLE); } } private void setType(@Nullable ContentType type, @NonNull ImageView imageView) { if (type == null) { imageView.setVisibility(View.GONE); } else { @DrawableRes int icon = 0; if (type == ContentType.TV) { icon = R.drawable.video_icon; } else if (type == ContentType.RADIO) { icon = R.drawable.radio_icon; } Drawable drawable = ContextCompat.getDrawable(imageView.getContext(), icon); if (drawable == null) { imageView.setVisibility(View.GONE); } else { imageView.setImageDrawable(drawable); imageView.setVisibility(View.VISIBLE); } } } @Override public void recycle() { super.recycle(); LushImageLoader.cancelDisplay(image); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/base/FilterableListingFragment.java
app/src/main/java/com/cube/lush/player/mobile/base/FilterableListingFragment.java
package com.cube.lush.player.mobile.base; import android.os.Bundle; import android.support.annotation.ColorInt; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import com.cube.lush.player.R; import java.io.Serializable; import java.util.List; import uk.co.jamiecruwys.StatefulListingFragment; import uk.co.jamiecruwys.ViewState; import uk.co.jamiecruwys.contracts.ListingData; /** * Filterable Listing Fragment which provides most of the functionality for statefulviews and leaves little to be implemented by the subclasses * * @author Jamie Cruwys */ public abstract class FilterableListingFragment<ITEM_TYPE, FILTER_OPTION extends Serializable> extends StatefulListingFragment<ITEM_TYPE> { @NonNull public abstract List<FILTER_OPTION> provideFilterOptions(); public abstract void getListDataForFilterOption(@NonNull FILTER_OPTION option, @NonNull ListingData callback); @NonNull public abstract String getTitleForFilterOption(FILTER_OPTION option); @NonNull public abstract FILTER_OPTION provideDefaultTab(); @NonNull public abstract RecyclerView.LayoutManager provideLayoutManagerForFilterOption(FILTER_OPTION option); @NonNull public abstract RecyclerView.Adapter provideAdapterForFilterOption(FILTER_OPTION option, @NonNull List<ITEM_TYPE> items); @Nullable public abstract RecyclerView.ItemDecoration provideItemDecorationForFilterOption(FILTER_OPTION option); private static final String ARG_FILTER_OPTION = "filter_option"; private FILTER_OPTION chosenOption; private LinearLayout tabContainer; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); if (view != null) { tabContainer = (LinearLayout)view.findViewById(R.id.tab_container); recycler.setBackgroundColor(provideBackgroundColor()); view.setBackgroundColor(provideBackgroundColor()); if (savedInstanceState == null) { chosenOption = provideDefaultTab(); } else { chosenOption = (FILTER_OPTION)savedInstanceState.getSerializable(ARG_FILTER_OPTION); } final ListingData callback = this; for (final FILTER_OPTION option : provideFilterOptions()) { Button itemView = (Button)inflater.inflate(R.layout.default_filter_item, tabContainer, false); String titleString = getTitleForFilterOption(option); itemView.setText(titleString); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { chosenOption = option; clearButtonStates(); view.setActivated(true); setViewState(ViewState.LOADING); getListDataForFilterOption(option, callback); } }); tabContainer.addView(itemView); } selectOption(chosenOption); } return view; } public void selectOption(@NonNull FILTER_OPTION option) { clearButtonStates(); String titleForOption = getTitleForFilterOption(option); for (int index = 0; index < tabContainer.getChildCount(); index++) { Button childView = (Button)tabContainer.getChildAt(index); if (childView.getText().equals(titleForOption)) { childView.setActivated(true); } } chosenOption = option; getListData(this); } private void clearButtonStates() { for (int index = 0; index < tabContainer.getChildCount(); index++) { Button childView = (Button)tabContainer.getChildAt(index); childView.setActivated(false); } } @Override public int provideLayout() { return R.layout.default_filter_listing; } @Override public int provideStatefulViewId() { return R.id.statefulview; } @Override protected void getListData(@NonNull ListingData callback) { setViewState(ViewState.LOADING); getListDataForFilterOption(chosenOption, callback); } @NonNull protected RecyclerView.LayoutManager provideLayoutManager() { return provideLayoutManagerForFilterOption(chosenOption); } @NonNull protected RecyclerView.Adapter provideAdapter(@NonNull List<ITEM_TYPE> items) { return provideAdapterForFilterOption(chosenOption, items); } @Nullable protected RecyclerView.ItemDecoration provideItemDecoration() { return provideItemDecorationForFilterOption(chosenOption); } @ColorInt public int provideBackgroundColor() { return ContextCompat.getColor(getContext(), android.R.color.black); } @Override public void onSaveInstanceState(Bundle outState) { outState.putSerializable(ARG_FILTER_OPTION, chosenOption); super.onSaveInstanceState(outState); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/base/BaseContentFragment.java
app/src/main/java/com/cube/lush/player/mobile/base/BaseContentFragment.java
package com.cube.lush.player.mobile.base; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.cube.lush.player.R; import com.lush.player.api.model.Programme; import com.cube.lush.player.mobile.MainActivity; import com.cube.lush.player.mobile.content.adapter.ContentAdapter; import com.cube.lush.player.mobile.details.DetailsFragment; import com.cube.lush.player.mobile.model.ProgrammeFilterOption; import com.lush.lib.listener.OnListItemClickListener; import java.util.List; /** * Base Content Fragment for most of the screens * * @author Jamie Cruwys */ public abstract class BaseContentFragment extends FilterableListingFragment<Programme, ProgrammeFilterOption> implements OnListItemClickListener<Programme> { @NonNull abstract public String provideContentTitle(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); if (view != null) { TextView contentTitle = (TextView)view.findViewById(R.id.content_title); contentTitle.setText(provideContentTitle()); } return view; } @NonNull @Override public List<ProgrammeFilterOption> provideFilterOptions() { return ProgrammeFilterOption.listValues(); } @NonNull @Override public String getTitleForFilterOption(ProgrammeFilterOption filterOption) { return filterOption.getName(); } @NonNull @Override public ProgrammeFilterOption provideDefaultTab() { return ProgrammeFilterOption.ALL; } @NonNull @Override public RecyclerView.LayoutManager provideLayoutManagerForFilterOption(ProgrammeFilterOption filterOption) { return new LinearLayoutManager(getContext()); } @NonNull @Override public RecyclerView.Adapter provideAdapterForFilterOption(ProgrammeFilterOption filterOption, @NonNull List<Programme> items) { return new ContentAdapter(items, this); } @Nullable @Override public RecyclerView.ItemDecoration provideItemDecorationForFilterOption(ProgrammeFilterOption filterOption) { return null; } @Override public int provideLoadingLayout() { return R.layout.content_loading; } @Override public int provideEmptyLayout() { return R.layout.content_empty; } @Override public int provideLoadedLayout() { return R.layout.content_loaded; } @Override public int provideErrorLayout() { return R.layout.content_error; } @Override public void onItemClick(Programme mediaContent, View view) { ((MainActivity)getActivity()).showFragment(DetailsFragment.newInstance(mediaContent)); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/base/BaseMobileActivity.java
app/src/main/java/com/cube/lush/player/mobile/base/BaseMobileActivity.java
package com.cube.lush.player.mobile.base; import android.content.Context; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; import uk.co.jamiecruwys.StatefulActivity; /** * Base activity for mobile * * @author Jamie Cruwys */ public abstract class BaseMobileActivity extends StatefulActivity { @Override protected void attachBaseContext(Context newBase) { // Context wrapper to apply custom fonts super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/model/ProgrammeFilterOption.java
app/src/main/java/com/cube/lush/player/mobile/model/ProgrammeFilterOption.java
package com.cube.lush.player.mobile.model; import java.util.Arrays; import java.util.List; /** * Filter options for lists of programmes * * @author Jamie Cruwys */ public enum ProgrammeFilterOption { ALL("All Episodes"), TV("TV"), RADIO("Radio"); private String name; ProgrammeFilterOption(String name) { this.name = name; } public String getName() { return name; } public static List<ProgrammeFilterOption> listValues() { return Arrays.asList(ProgrammeFilterOption.values()); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/home/HomeTab.java
app/src/main/java/com/cube/lush/player/mobile/home/HomeTab.java
package com.cube.lush.player.mobile.home; import java.util.Arrays; import java.util.List; /** * Home Tab * * @author Jamie Cruwys */ public enum HomeTab { @SuppressWarnings("HardCodedStringLiteral") ALL("All Episodes", null), @SuppressWarnings("HardCodedStringLiteral") SUMMIT("Lush Summit 2017", "summit"), @SuppressWarnings("HardCodedStringLiteral") SHOWCASE("Creative Showcase 2016", "showcase 2016"); /** * The name used for the tabs in the UI */ private String displayName; /** * Name of the tag that will be used to find the content */ private String tag; HomeTab(String displayName, String tag) { this.displayName = displayName; this.tag = tag; } public String getDisplayName() { return displayName; } public String getTag() { return tag; } public static List<HomeTab> listValues() { return Arrays.asList(HomeTab.values()); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/home/HomeFragment.java
app/src/main/java/com/cube/lush/player/mobile/home/HomeFragment.java
package com.cube.lush.player.mobile.home; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.cube.lush.player.R; import com.lush.player.api.model.Programme; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.repository.LatestProgrammesRepository; import com.cube.lush.player.content.util.MediaSorter; import com.cube.lush.player.mobile.MainActivity; import com.cube.lush.player.mobile.content.adapter.ContentAdapter; import com.cube.lush.player.mobile.details.DetailsFragment; import com.lush.lib.listener.OnListItemClickListener; import java.util.List; import uk.co.jamiecruwys.StatefulListingFragment; import uk.co.jamiecruwys.contracts.ListingData; /** * Home Fragment * * @author Jamie Cruwys */ public class HomeFragment extends StatefulListingFragment<Programme> implements OnListItemClickListener<Programme> { public HomeFragment() { // Required empty public constructor } public static HomeFragment newInstance() { HomeFragment fragment = new HomeFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @NonNull @Override protected RecyclerView.LayoutManager provideLayoutManager() { final int NUMBER_COLUMNS = getResources().getInteger(R.integer.home_columns); return new GridLayoutManager(getContext(), NUMBER_COLUMNS); } @NonNull @Override protected RecyclerView.Adapter provideAdapter(@NonNull List<Programme> items) { return new ContentAdapter(items, this); } @Override protected void getListData(@NonNull final ListingData callback) { LatestProgrammesRepository.getInstance(getContext()).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { MediaSorter.MOST_RECENT_FIRST.sort(items); if (callback != null) { callback.onListingDataRetrieved(items); } } @Override public void onFailure(@Nullable Throwable t) { if (callback != null) { callback.onListingDataError(t); } } }); } @Override public int provideLoadingLayout() { return R.layout.home_loading; } @Override public int provideEmptyLayout() { return R.layout.home_empty; } @Override public int provideErrorLayout() { return R.layout.home_error; } @Override public void onItemClick(Programme programme, View view) { ((MainActivity)getActivity()).showFragment(DetailsFragment.newInstance(programme)); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/live/LiveFragment.java
app/src/main/java/com/cube/lush/player/mobile/live/LiveFragment.java
package com.cube.lush.player.mobile.live; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.brightcove.player.edge.PlaylistListener; import com.brightcove.player.model.Playlist; import com.brightcove.player.model.Video; import com.cube.lush.player.R; import com.cube.lush.player.content.brightcove.BrightcoveCatalog; import com.cube.lush.player.content.brightcove.BrightcoveUtils; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.model.VideoInfo; import com.cube.lush.player.content.repository.LivePlaylistRepository; import com.cube.lush.player.mobile.LushTab; import com.cube.lush.player.mobile.MainActivity; import com.cube.lush.player.mobile.content.TagContentFragment; import com.cube.lush.player.mobile.playback.LushPlaybackActivity; import com.cube.lush.player.mobile.view.TagClickListener; import com.cube.lush.player.mobile.view.TagSectionView; import com.lush.player.api.model.ContentType; import com.lush.player.api.model.LivePlaylist; import com.lush.player.api.model.Programme; import com.lush.player.api.model.Tag; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.Collections; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import uk.co.jamiecruwys.StatefulFragment; import uk.co.jamiecruwys.ViewState; import uk.co.jamiecruwys.contracts.ListingData; import static android.text.format.DateUtils.FORMAT_SHOW_TIME; import static android.text.format.DateUtils.FORMAT_UTC; /** * Live Fragment * * @author Jamie Cruwys */ public class LiveFragment extends StatefulFragment<Playlist> { @BindView(R.id.thumbnail) ImageView thumbnail; @BindView(R.id.meta) TextView meta; @BindView(R.id.title) TextView title; @BindView(R.id.description) TextView description; @BindView(R.id.time_remaining) TextView timeRemaining; @BindView(R.id.tag_section) TagSectionView tagSection; @BindView(R.id.play_button) ImageButton playButton; public LiveFragment() { // Required empty public constructor } public static LiveFragment newInstance() { LiveFragment fragment = new LiveFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); if (view != null) { ButterKnife.bind(this, view); } return view; } @Override public int provideLoadingLayout() { return R.layout.live_loading; } @Override public int provideEmptyLayout() { return R.layout.live_empty; } @Override public int provideLoadedLayout() { return R.layout.live_loaded; } @Override public int provideErrorLayout() { return R.layout.live_error; } @Override public ViewState provideInitialViewState() { return ViewState.EMPTY; } @Override protected boolean shouldReloadOnResume() { return true; } @Override protected void getListData(@NonNull final ListingData callback) { LivePlaylistRepository.getInstance(getContext()).getItems(new ResponseHandler<LivePlaylist>() { @Override public void onSuccess(@NonNull List<LivePlaylist> items) { if (getActivity() == null) { if (callback != null) { callback.onListingDataError(null); } return; } if (items.isEmpty()) { if (callback != null) { callback.onListingDataRetrieved(Collections.EMPTY_LIST); } return; } final String playlistId = items.get(0).getId(); // Get the playlist that is live BrightcoveCatalog.INSTANCE.getCatalog().findPlaylistByID(playlistId, new PlaylistListener() { @Override public void onPlaylist(Playlist playlist) { if (getActivity() == null || playlist == null) { if (callback != null) { callback.onListingDataError(null); } return; } playlist.getProperties().put("id", playlistId); ArrayList<Playlist> playlists = new ArrayList<>(); playlists.add(playlist); if (callback != null) { callback.onListingDataRetrieved(playlists); } } @Override public void onError(String error) { if (callback != null) { callback.onListingDataError(null); } } }); } @Override public void onFailure(@Nullable Throwable t) { if (callback != null) { callback.onListingDataError(null); } } }); } @Override public void onListingDataRetrieved(@NonNull List<Playlist> items) { // Cover us from null pointers where the activity/fragment is detached if (!isAdded() || getActivity() == null) { return; } super.onListingDataRetrieved(items); if (getViewState() == ViewState.LOADED) { // Will only be one playlist element Playlist playlist = items.get(0); String playlistId = playlist.getStringProperty("id"); VideoInfo liveVideoInfo = BrightcoveUtils.findCurrentLiveVideo(playlist); if (liveVideoInfo == null) { setViewState(ViewState.EMPTY); return; } setLiveVideoInfo(playlistId, liveVideoInfo); } } private void setLiveVideoInfo(@NonNull final String playlistId, @NonNull final VideoInfo videoInfo) { Video brightcoveVideo = videoInfo.getVideo(); if (brightcoveVideo == null) { setViewState(ViewState.EMPTY); return; } // Title String titleString = BrightcoveUtils.getVideoName(brightcoveVideo); title.setText(getString(R.string.live_title, titleString)); // Thumbnail Picasso.with(getContext()) .load(BrightcoveUtils.getVideoThumbnail(brightcoveVideo)) .into(thumbnail); long nowUtc = System.currentTimeMillis(); long timeRemainingMillis = videoInfo.getEndTimeUtc() - nowUtc; long timeRemainingMins = (timeRemainingMillis / 1000 / 60) + 1; // Start and end times meta String startEndTimesString = DateUtils.formatDateRange(getContext(), videoInfo.getStartTimeUtc(), videoInfo.getEndTimeUtc(), FORMAT_SHOW_TIME | FORMAT_UTC); meta.setText(startEndTimesString); // Time remaining timeRemaining.setText(getString(R.string.minutes_remaining, timeRemainingMins)); // Play button playButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { play(playlistId, videoInfo); } }); tagSection.setTagClickListener(new TagClickListener() { @Override public void onTagClick(@NonNull Tag tag) { ((MainActivity)getActivity()).showFragment(TagContentFragment.newInstance(tag)); } }); List<Tag> tags = BrightcoveUtils.getVideoTags(brightcoveVideo); tagSection.setTags(tags); } private void play(@NonNull String playlistId, @NonNull final VideoInfo videoInfo) { Programme programme = new Programme(); programme.setId(videoInfo.getVideo().getId()); programme.setType(ContentType.TV); Intent playbackIntent = LushPlaybackActivity.getIntent(getContext(), programme, 0); getActivity().startActivity(playbackIntent); } @OnClick(R.id.show_channels) void onShowChannelsClicked() { ((MainActivity)getActivity()).selectTab(LushTab.CHANNELS); } @OnClick(R.id.share) void onShareClicked() { // TODO: Once we can get the web url } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/details/DetailsFragment.java
app/src/main/java/com/cube/lush/player/mobile/details/DetailsFragment.java
package com.cube.lush.player.mobile.details; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.brightcove.player.analytics.Analytics; import com.brightcove.player.appcompat.BrightcovePlayerFragment; import com.brightcove.player.edge.VideoListener; import com.brightcove.player.media.DeliveryType; import com.brightcove.player.mediacontroller.BrightcoveMediaController; import com.brightcove.player.model.Video; import com.brightcove.player.view.BaseVideoView; import com.brightcove.player.view.BrightcoveExoPlayerVideoView; import com.cube.lush.player.R; import com.cube.lush.player.analytics.Track; import com.cube.lush.player.content.brightcove.BrightcoveCatalog; import com.cube.lush.player.content.repository.ProgrammeRepository; import com.cube.lush.player.mobile.MainActivity; import com.cube.lush.player.mobile.content.TagContentFragment; import com.cube.lush.player.mobile.playback.LushPlaybackActivity; import com.cube.lush.player.mobile.view.TagClickListener; import com.cube.lush.player.mobile.view.TagSectionView; import com.lush.player.api.model.ContentType; import com.lush.player.api.model.Programme; import com.lush.player.api.model.Tag; import com.squareup.picasso.MemoryPolicy; import com.squareup.picasso.Picasso; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Details Fragment * * @author Jamie Cruwys */ public class DetailsFragment extends BrightcovePlayerFragment { @SuppressWarnings("HardCodedStringLiteral") private static final String ARG_CONTENT = "arg_content"; private static final String ARG_WATCHED_MILLISECONDS = "arg_watched_milliseconds"; private static final String ARG_PLAYING = "arg_playing"; private Programme programme; public static final int REQUEST_CODE = 453; @BindView(R.id.playOverlay) ImageView playOverlay; @BindView(R.id.content_type) TextView contentType; @BindView(R.id.title) TextView title; @BindView(R.id.description) TextView description; @BindView(R.id.toggle_description_length) Button toggleDescriptionButton; @BindView(R.id.tag_section) TagSectionView tagSection; @BindView(R.id.brightcove_video_view) BrightcoveExoPlayerVideoView brightcoveExoPlayerVideoView; public DetailsFragment() { // Required empty public constructor } public static DetailsFragment newInstance(@NonNull Programme programme) { DetailsFragment fragment = new DetailsFragment(); Bundle args = new Bundle(); args.putSerializable(ARG_CONTENT, programme); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); programme = (Programme)getArguments().getSerializable(ARG_CONTENT); if (savedInstanceState != null) { programme = (Programme)savedInstanceState.getSerializable(ARG_CONTENT); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.detail_loaded, container, false); baseVideoView = (BaseVideoView) view.findViewById(R.id.brightcove_video_view); // Our custom media controller, which is in one line BrightcoveMediaController brightcoveMediaController = new BrightcoveMediaController(baseVideoView, R.layout.one_line_brightcove_media_controller); baseVideoView.setMediaController(brightcoveMediaController); // Brightcove player onCreateView super.onCreateView(inflater, container, savedInstanceState); ButterKnife.bind(this, view); // Setup account credentials Analytics analytics = baseVideoView.getAnalytics(); analytics.setAccount(com.cube.lush.player.content.BuildConfig.BRIGHTCOVE_ACCOUNT_ID); if (savedInstanceState != null) { int watchedMilliseconds = savedInstanceState.getInt(ARG_WATCHED_MILLISECONDS, 0); baseVideoView.seekTo(watchedMilliseconds); boolean wasPlaying = savedInstanceState.getBoolean(ARG_PLAYING, false); if (wasPlaying) { onPlayClicked(); } } tagSection.setTagClickListener(new TagClickListener() { @Override public void onTagClick(@NonNull Tag tag) { ((MainActivity)getActivity()).showFragment(TagContentFragment.newInstance(tag)); } }); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); populateUi(); } private void populateUi() { contentType.setText(programme.getType().getName()); title.setText(programme.getTitle()); if (!TextUtils.isEmpty(programme.getDescription())) { description.setText(programme.getDescription().trim()); } loadBrightcoveStillImage(); List<Tag> tags = programme.getTags(); tagSection.setTags(tags); description.post(new Runnable() { @Override public void run() { int condensedMaxLines = getResources().getInteger(R.integer.description_condensed_lines); // If the text is truncated, show the "show full description" button if (description.getLineCount() > condensedMaxLines) { toggleDescriptionButton.setVisibility(View.VISIBLE); } else { toggleDescriptionButton.setVisibility(View.INVISIBLE); } description.setMaxLines(condensedMaxLines); } }); } private void loadBrightcoveStillImage() { // TODO: Fix this try { // Load image into brightcove video view Picasso.with(baseVideoView.getContext()) .load(programme.getThumbnail()) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) .into(baseVideoView.getStillView()); } catch (Exception e) { e.printStackTrace(); } } @OnClick(R.id.playOverlay) void onPlayClicked() { playOverlay.setVisibility(View.GONE); String mediaId = programme.getId(); if (programme.getType() == ContentType.TV) { // TV Content from Brightcove BrightcoveCatalog.INSTANCE.getCatalog().findVideoByID(mediaId, new VideoListener() { @Override public void onVideo(Video video) { playVideo(video); } @Override public void onError(String error) { playOverlay.setVisibility(View.VISIBLE); Toast.makeText(playOverlay.getContext(), "Error playing video, please try again later", Toast.LENGTH_SHORT).show(); Log.e(DetailsFragment.class.getSimpleName(), "Brightcove findVideoByID error: " + error); } }); } else if (programme.getType() == ContentType.RADIO) { // Radio Content from mp3 files, shown as videos in the brightcove player Video video = Video.createVideo(programme.getFile(), DeliveryType.MP4); playVideo(video); Track.event("Play", programme.getId()); } ProgrammeRepository.watched(getContext(), programme); } public void playVideo(@NonNull Video video) { baseVideoView.add(video); baseVideoView.start(); baseVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { baseVideoView.stopPlayback(); playOverlay.setVisibility(View.VISIBLE); // TODO: Get the still view to show again loadBrightcoveStillImage(); Track.event("End", programme.getId()); } }); } @OnClick(R.id.toggle_description_length) void onToggleDescriptionLengthClicked() { int maxLines = description.getMaxLines(); int condensedMaxLines = getResources().getInteger(R.integer.description_condensed_lines); int expandedMaxLines = getResources().getInteger(R.integer.description_expanded_lines); if (maxLines <= condensedMaxLines) { description.setMaxLines(expandedMaxLines); toggleDescriptionButton.setText(R.string.show_less); } else { description.setMaxLines(condensedMaxLines); toggleDescriptionButton.setText(R.string.show_more); } } @OnClick(R.id.share) void onShareClicked() { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, programme.getWebLink()); shareIntent.setType("text/plain"); startActivity(Intent.createChooser(shareIntent, getString(R.string.share_via))); Track.event("Share", programme.getId()); } @OnClick(R.id.full_screen) void onFullscreenClicked() { // Use current seek position and pass it off to the playback activity/fragment to continue playback int currentSeekPosition = baseVideoView.getCurrentPosition(); Intent fullscreenPlaybackIntent = LushPlaybackActivity.getIntent(getContext(), programme, currentSeekPosition); startActivityForResult(fullscreenPlaybackIntent, REQUEST_CODE); } public void seekTo(int milliseconds) { if (baseVideoView != null) { baseVideoView.seekTo(milliseconds); } } @Override public void onSaveInstanceState(Bundle bundle) { bundle.putSerializable(ARG_CONTENT, programme); bundle.putInt(ARG_WATCHED_MILLISECONDS, baseVideoView.getCurrentPosition()); bundle.putBoolean(ARG_PLAYING, baseVideoView.isPlaying()); super.onSaveInstanceState(bundle); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/events/EventsFragment.java
app/src/main/java/com/cube/lush/player/mobile/events/EventsFragment.java
package com.cube.lush.player.mobile.events; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.TypedValue; import android.view.View; import com.cube.lush.player.R; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.repository.EventProgrammesRepository; import com.cube.lush.player.content.repository.EventRepository; import com.cube.lush.player.content.repository.LatestProgrammesRepository; import com.cube.lush.player.content.util.MediaSorter; import com.cube.lush.player.mobile.MainActivity; import com.cube.lush.player.mobile.base.FilterableListingFragment; import com.cube.lush.player.mobile.content.adapter.ContentAdapter; import com.cube.lush.player.mobile.decoration.InsideSpacingItemDecoration; import com.cube.lush.player.mobile.details.DetailsFragment; import com.cube.lush.player.mobile.events.adapter.EventsAdapter; import com.lush.lib.listener.OnListItemClickListener; import com.lush.player.api.model.Event; import com.lush.player.api.model.Programme; import java.util.ArrayList; import java.util.List; import uk.co.jamiecruwys.contracts.ListingData; /** * Events Fragment * * @author Jamie Cruwys */ public class EventsFragment extends FilterableListingFragment<Programme, Event> implements OnListItemClickListener<Programme>, EventTabSelection { public EventsFragment() { // Required empty public constructor } public static EventsFragment newInstance() { EventsFragment fragment = new EventsFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @NonNull @Override public List<Event> provideFilterOptions() { return EventRepository.getInstance(getContext()).getEventTabs(); } @Override public void getListDataForFilterOption(@NonNull Event event, @NonNull final ListingData callback) { if (event == EventRepository.ALL_EVENTS) { LatestProgrammesRepository.getInstance(getContext()).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { MediaSorter.MOST_RECENT_FIRST.sort(items); if (callback != null) { callback.onListingDataRetrieved(items); } } @Override public void onFailure(@Nullable Throwable t) { if (callback != null) { callback.onListingDataError(t); } } }); } else { EventProgrammesRepository.getInstance(getContext()).setEventTag(event.getTag()); EventProgrammesRepository.getInstance(getContext()).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { MediaSorter.MOST_RECENT_FIRST.sort(items); if (callback != null) { callback.onListingDataRetrieved(items); } } @Override public void onFailure(@Nullable Throwable t) { if (callback != null) { callback.onListingDataError(t); } } }); } } @NonNull @Override public String getTitleForFilterOption(Event event) { return event.getName(); } @NonNull @Override public Event provideDefaultTab() { return EventRepository.ALL_EVENTS; } @NonNull @Override public LinearLayoutManager provideLayoutManagerForFilterOption(Event event) { final int NUMBER_COLUMNS; if (event == EventRepository.ALL_EVENTS) { NUMBER_COLUMNS = getResources().getInteger(R.integer.paging_columns); } else { NUMBER_COLUMNS = getResources().getInteger(R.integer.events_columns); } return new GridLayoutManager(getContext(), NUMBER_COLUMNS); } @NonNull @Override public RecyclerView.Adapter provideAdapterForFilterOption(Event event, @NonNull List<Programme> items) { if (event == EventRepository.ALL_EVENTS) { return new EventsAdapter(EventRepository.getInstance(getContext()).getItemsSynchronously(), this, this); } else { ArrayList<Programme> programmesForEvent = new ArrayList<>(); for (Programme item : items) { if (item != null && !TextUtils.isEmpty(item.getEvent()) && event != null && !TextUtils.isEmpty(event.getTag()) && item.getEvent().equals(event.getTag())) { programmesForEvent.add(item); } } return new ContentAdapter(programmesForEvent, this); } } @Nullable @Override public RecyclerView.ItemDecoration provideItemDecorationForFilterOption(Event event) { // TODO: Remove top spacing on phones/tablet if (event == EventRepository.ALL_EVENTS) { int spacing = (int)(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getContext().getResources().getDisplayMetrics())); final int NUMBER_COLUMNS = getResources().getInteger(R.integer.paging_columns); return new InsideSpacingItemDecoration(spacing, 0 ,0 ,0, NUMBER_COLUMNS); } return null; } @Override public int provideLoadingLayout() { return R.layout.event_loading; } @Override public int provideEmptyLayout() { return R.layout.event_empty; } @Override public int provideErrorLayout() { return R.layout.event_error; } @Override public void onItemClick(Programme item, View view) { ((MainActivity)getActivity()).showFragment(DetailsFragment.newInstance(item)); } @Override public void selectTab(@NonNull Event event) { selectOption(event); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/events/EventTab.java
app/src/main/java/com/cube/lush/player/mobile/events/EventTab.java
package com.cube.lush.player.mobile.events; import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Event Tab * * @author Jamie Cruwys */ public enum EventTab { @SuppressWarnings("HardCodedStringLiteral") ALL("All Events", null), @SuppressWarnings("HardCodedStringLiteral") SUMMIT("Lush Summit 2017", "summit"), @SuppressWarnings("HardCodedStringLiteral") SHOWCASE("Creative Showcase 2016", "showcase 2016"); /** * The name used for the tabs in the UI */ private String displayName; /** * Name of the tag that will be used to find the content */ private String tag; EventTab(String displayName, String tag) { this.displayName = displayName; this.tag = tag; } public String getDisplayName() { return displayName; } public String getTag() { return tag; } public static List<EventTab> listValues() { return Arrays.asList(EventTab.values()); } public static List<EventTab> listValuesExcluding(@NonNull EventTab... tabsToExclude) { List<EventTab> tabs = new ArrayList<>(listValues()); if (tabs == null) { tabs = Collections.EMPTY_LIST; } if (!tabs.isEmpty()) { for (EventTab tabToExclude : tabsToExclude) { tabs.remove(tabToExclude); } } return tabs; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/events/EventTabSelection.java
app/src/main/java/com/cube/lush/player/mobile/events/EventTabSelection.java
package com.cube.lush.player.mobile.events; import android.support.annotation.NonNull; import com.lush.player.api.model.Event; /** * Event Tab Selection * @author Jamie Cruwys. */ public interface EventTabSelection { void selectTab(@NonNull Event event); }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/events/adapter/EventsAdapter.java
app/src/main/java/com/cube/lush/player/mobile/events/adapter/EventsAdapter.java
package com.cube.lush.player.mobile.events.adapter; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cube.lush.player.R; import com.cube.lush.player.mobile.events.EventTabSelection; import com.cube.lush.player.mobile.events.holder.EventViewHolder; import com.lush.lib.adapter.BaseListAdapter; import com.lush.lib.listener.OnListItemClickListener; import com.lush.player.api.model.Event; import com.lush.player.api.model.Programme; import com.lush.view.holder.BaseViewHolder; import java.util.List; /** * Events Adapter * * @author Jamie Cruwys */ public class EventsAdapter extends BaseListAdapter<Event> { private final OnListItemClickListener<Programme> itemListener; private final EventTabSelection tabListener; public EventsAdapter(@NonNull List<Event> events, @NonNull OnListItemClickListener<Programme> itemListener, @NonNull EventTabSelection tabListener) { super(events, null); this.itemListener = itemListener; this.tabListener = tabListener; } @Override public BaseViewHolder<Event> onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_all_item, parent, false); return new EventViewHolder(view, itemListener, tabListener); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/events/holder/EventViewHolder.java
app/src/main/java/com/cube/lush/player/mobile/events/holder/EventViewHolder.java
package com.cube.lush.player.mobile.events.holder; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.cube.lush.player.R; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.repository.EventProgrammesRepository; import com.cube.lush.player.content.util.MediaSorter; import com.cube.lush.player.mobile.content.adapter.ContentCarouselAdapter; import com.cube.lush.player.mobile.events.EventTabSelection; import com.lush.lib.listener.OnListItemClickListener; import com.lush.player.api.model.Event; import com.lush.player.api.model.Programme; import com.lush.view.holder.BaseViewHolder; import java.util.ArrayList; import java.util.Collections; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Event View Holder * * @author Jamie Cruwys */ public class EventViewHolder extends BaseViewHolder<Event> { @BindView(R.id.section_title) public TextView title; @BindView(R.id.event_recycler) public RecyclerView eventRecycler; @BindView(R.id.event_more) public Button moreButton; private final OnListItemClickListener<Programme> itemListener; private final EventTabSelection tabListener; public EventViewHolder(@NonNull View view, @NonNull OnListItemClickListener<Programme> itemListener, @NonNull EventTabSelection tabListener) { super(view); this.itemListener = itemListener; this.tabListener = tabListener; ButterKnife.bind(this, view); } @Override public void bind(@NonNull final Event event) { title.setText(event.getName()); final int MAX_HORIZONTAL_ITEMS = title.getContext().getResources().getInteger(R.integer.paging_max_items); if (event != null) { EventProgrammesRepository.getInstance(title.getContext()).setEventTag(event.getTag()); EventProgrammesRepository.getInstance(title.getContext()).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { ArrayList<Programme> itemsWithMatchingTag = new ArrayList<Programme>(); // Filter items by tag, due to caching keeping hold of all tagged content and not just for this event for (Programme programme : items) { if (programme == null) { continue; } String programmeEvent = programme.getEvent(); if (programmeEvent == null || TextUtils.isEmpty(programmeEvent)) { continue; } if (programmeEvent.equals(event.getTag())) { itemsWithMatchingTag.add(programme); } } items = itemsWithMatchingTag; int toIndex = MAX_HORIZONTAL_ITEMS; if (items.isEmpty()) { toIndex = 0; } else if (items.size() < MAX_HORIZONTAL_ITEMS) { toIndex = items.size(); } items = items.subList(0, toIndex); MediaSorter.MOST_RECENT_FIRST.sort(items); bindProgrammes(items); } @Override public void onFailure(@Nullable Throwable t) { bindProgrammes(Collections.EMPTY_LIST); } }); } // TODO: Use PAGE_SIZE final LinearLayoutManager layoutManager = new LinearLayoutManager(eventRecycler.getContext(), LinearLayoutManager.HORIZONTAL, false); eventRecycler.setLayoutManager(layoutManager); moreButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tabListener.selectTab(event); } }); } private void bindProgrammes(@NonNull List<Programme> programmes) { ContentCarouselAdapter contentAdapter = new ContentCarouselAdapter(programmes, itemListener); eventRecycler.setAdapter(contentAdapter); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/view/TagSectionView.java
app/src/main/java/com/cube/lush/player/mobile/view/TagSectionView.java
package com.cube.lush.player.mobile.view; import android.content.Context; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import com.cube.lush.player.R; import com.lush.player.api.model.Tag; import java.util.List; /** * <Class Description> * * @author Jamie Cruwys */ public class TagSectionView extends LinearLayout { private TagFlowLayout tagFlowLayout; public TagSectionView(Context context) { super(context); init(context); } public TagSectionView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context); } public TagSectionView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public TagSectionView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context); } private void init(Context context) { View view = inflate(context, R.layout.tag_subview, this); tagFlowLayout = (TagFlowLayout)view.findViewById(R.id.tag_list); } public void setTags(@NonNull List<Tag> tags) { if (tagFlowLayout != null) { if (tags.isEmpty()) { tagFlowLayout.hide(); setVisibility(View.GONE); } else { tagFlowLayout.show(tags); setVisibility(View.VISIBLE); } } else { setVisibility(View.GONE); } } public void setTagClickListener(@NonNull TagClickListener listener) { if (tagFlowLayout != null) { tagFlowLayout.setOnTagClickListener(listener); } } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/view/TagFlowLayout.java
app/src/main/java/com/cube/lush/player/mobile/view/TagFlowLayout.java
package com.cube.lush.player.mobile.view; import android.content.Context; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.cube.lush.player.R; import com.lush.player.api.model.Tag; import org.apmem.tools.layouts.FlowLayout; import java.util.List; /** * <Class Description> * * @author Jamie Cruwys */ public class TagFlowLayout extends FlowLayout { private Context context; private TagClickListener listener; public TagFlowLayout(Context context) { super(context); init(context); } public TagFlowLayout(Context context, AttributeSet attributeSet) { super(context, attributeSet); init(context); } public TagFlowLayout(Context context, AttributeSet attributeSet, int defStyle) { super(context, attributeSet, defStyle); init(context); } private void init(Context context) { this.context = context; } public void setOnTagClickListener(@NonNull TagClickListener listener) { this.listener = listener; } public void show(@NonNull List<Tag> tags) { clearTags(); LayoutInflater inflater = LayoutInflater.from(context); for (final Tag tag : tags) { View view = inflater.inflate(R.layout.tag_item, this, false); TextView text = (TextView)view.findViewById(R.id.text); text.setText(tag.getName()); if (listener != null) { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { listener.onTagClick(tag); } }); } addView(view); } setVisibility(View.VISIBLE); } public void hide() { clearTags(); setVisibility(View.GONE); } private void clearTags() { removeAllViews(); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/view/TagClickListener.java
app/src/main/java/com/cube/lush/player/mobile/view/TagClickListener.java
package com.cube.lush.player.mobile.view; import android.support.annotation.NonNull; import com.lush.player.api.model.Tag; /** * <Class Description> * * @author Jamie Cruwys */ public interface TagClickListener { void onTagClick(@NonNull Tag tag); }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/playback/LushPlaybackActivity.java
app/src/main/java/com/cube/lush/player/mobile/playback/LushPlaybackActivity.java
package com.cube.lush.player.mobile.playback; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.os.Bundle; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import com.brightcove.player.analytics.Analytics; import com.brightcove.player.appcompat.BrightcovePlayerActivity; import com.brightcove.player.edge.VideoListener; import com.brightcove.player.media.DeliveryType; import com.brightcove.player.mediacontroller.BrightcoveMediaController; import com.brightcove.player.model.Video; import com.brightcove.player.view.BaseVideoView; import com.cube.lush.player.R; import com.cube.lush.player.content.brightcove.BrightcoveCatalog; import com.cube.lush.player.content.repository.ProgrammeRepository; import com.lush.player.api.model.ContentType; import com.lush.player.api.model.Programme; import com.squareup.picasso.MemoryPolicy; import com.squareup.picasso.Picasso; import butterknife.ButterKnife; import butterknife.OnClick; /** * Lush Playback Activity * * @author Jamie Cruwys */ public class LushPlaybackActivity extends BrightcovePlayerActivity { @SuppressWarnings("HardCodedStringLiteral") public static final String EXTRA_MEDIA_CONTENT = "media_content"; @SuppressWarnings("HardCodedStringLiteral") public static final String EXTRA_START_TIME = "start_time"; public static final int RESULT_CODE = 236; private Programme programme; @IntRange(from = 0) private int startTimeMilliseconds; public static Intent getIntent(@NonNull Context context, @NonNull Programme mediaContent, @IntRange(from = 0) int startTimeMilliseconds) { Intent intent = new Intent(context, LushPlaybackActivity.class); intent.putExtra(EXTRA_MEDIA_CONTENT, mediaContent); intent.putExtra(EXTRA_START_TIME, startTimeMilliseconds); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.playback_fragment); baseVideoView = (BaseVideoView) findViewById(R.id.brightcove_video_view); // Our custom media controller, which is in one line BrightcoveMediaController brightcoveMediaController = new BrightcoveMediaController(baseVideoView, R.layout.one_line_brightcove_media_controller); baseVideoView.setMediaController(brightcoveMediaController); super.onCreate(savedInstanceState); ButterKnife.bind(this); Analytics analytics = baseVideoView.getAnalytics(); analytics.setAccount(com.cube.lush.player.content.BuildConfig.BRIGHTCOVE_ACCOUNT_ID); programme = (Programme)getIntent().getSerializableExtra(EXTRA_MEDIA_CONTENT); startTimeMilliseconds = getIntent().getIntExtra(EXTRA_START_TIME, 0); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); startTimeMilliseconds = savedInstanceState.getInt(EXTRA_START_TIME); } @Override protected void onResume() { super.onResume(); if (programme.getType() == ContentType.RADIO) { // TODO: Fix this try { // Load image into brightcove video view Picasso.with(baseVideoView.getContext()) .load(programme.getThumbnail()) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) .into(baseVideoView.getStillView()); } catch (Exception e) { e.printStackTrace(); } } playMediaContent(programme, startTimeMilliseconds); } private void playMediaContent(@NonNull Programme mediaContent, @IntRange(from = 0) int startTimeMilliseconds) { if (mediaContent.getType() == ContentType.TV) { playTVContent(mediaContent, startTimeMilliseconds); } else if (mediaContent.getType() == ContentType.RADIO) { playRadioContent(mediaContent, startTimeMilliseconds); } } private void playTVContent(@NonNull Programme tv, @IntRange(from = 0) final int startTimeMilliseconds) { // TV Content from Brightcove BrightcoveCatalog.INSTANCE.getCatalog().findVideoByID(tv.getId(), new VideoListener() { @Override public void onVideo(Video video) { playVideo(video, startTimeMilliseconds); } @Override public void onError(String error) { super.onError(error); } }); } private void playRadioContent(@NonNull Programme radio, @IntRange(from = 0) final int startTimeMilliseconds) { // Radio Content from mp3 files, shown as videos in the brightcove player Video video = Video.createVideo(radio.getFile(), DeliveryType.MP4); playVideo(video, startTimeMilliseconds); } private void playVideo(@NonNull Video video, @IntRange(from = 0) int startTimeMilliseconds) { // Mark programme as watched ProgrammeRepository.watched(this, programme); baseVideoView.add(video); baseVideoView.start(); if (startTimeMilliseconds > 0) { baseVideoView.seekTo(startTimeMilliseconds); } baseVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { finish(); } }); } @OnClick(R.id.full_screen) void onFullscreenClicked() { // Pass back the current time to anyone who starts this activity for a result Intent intent = new Intent(); intent.putExtra(EXTRA_MEDIA_CONTENT, programme); intent.putExtra(EXTRA_START_TIME, baseVideoView.getCurrentPosition()); setResult(RESULT_CODE, intent); finish(); } @Override protected void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putInt(EXTRA_START_TIME, baseVideoView.getCurrentPosition()); super.onSaveInstanceState(savedInstanceState); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/decoration/InsideSpacingItemDecoration.java
app/src/main/java/com/cube/lush/player/mobile/decoration/InsideSpacingItemDecoration.java
package com.cube.lush.player.mobile.decoration; import android.graphics.Rect; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Inside Spacing Decoration, for list items where spacing is applied to the inside of the area * * @author Jamie Cruwys */ public class InsideSpacingItemDecoration extends RecyclerView.ItemDecoration { private int topSpace, bottomSpace, leftSpace, rightSpace; private int columns; public InsideSpacingItemDecoration(int space, int columns) { this(space, space, columns); } public InsideSpacingItemDecoration(int verticalSpace, int horizontalSpace, int columns) { this(verticalSpace, verticalSpace, horizontalSpace, horizontalSpace, columns); } public InsideSpacingItemDecoration(int topSpace, int bottomSpace, int leftSpace, int rightSpace, int columns) { this.topSpace = topSpace; this.bottomSpace = bottomSpace; this.leftSpace = leftSpace; this.rightSpace = rightSpace; this.columns = columns; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int index = parent.getChildAdapterPosition(view); int items = parent.getAdapter().getItemCount(); boolean isFirstRow = index < columns; boolean isLastRow = index >= (items - columns); boolean isSingleColumn = columns == 1; boolean isLeftColumn = index % columns == 0; boolean isRightColumn = index % columns == (columns - 1); int top = 0; int bottom = 0; int left = 0; int right = 0; // Apply top spacing to all rows apart from the first if (!isFirstRow) { top = topSpace; } // Apply bottom spacing to all rows apart from the last if (!isLastRow) { bottom = bottomSpace; } // Can only space the inside if there is more than one column if (!isSingleColumn) { // Apply left spacing to all columns apart from the furthest left one if (!isLeftColumn) { left = leftSpace; } // Apply right spacing to all columns apart from the furthest right one if (!isRightColumn) { right = rightSpace; } } outRect.top = top; outRect.bottom = bottom; outRect.left = left; outRect.right = right; } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/search/SearchFragment.java
app/src/main/java/com/cube/lush/player/mobile/search/SearchFragment.java
package com.cube.lush.player.mobile.search; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cube.lush.player.R; import com.cube.lush.player.analytics.Track; import com.lush.player.api.model.Programme; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.repository.SearchProgrammeRepository; import com.cube.lush.player.mobile.MainActivity; import com.cube.lush.player.mobile.decoration.InsideSpacingItemDecoration; import com.cube.lush.player.mobile.details.DetailsFragment; import com.cube.lush.player.mobile.search.adapter.SearchAdapter; import com.lush.lib.listener.OnListItemClickListener; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import uk.co.jamiecruwys.StatefulListingFragment; import uk.co.jamiecruwys.contracts.ListingData; /** * Search Fragment * * @author Jamie Cruwys */ public class SearchFragment extends StatefulListingFragment<Programme> implements OnListItemClickListener<Programme> { private static final String ARG_QUERY = "search_query"; @BindView(R.id.search) SearchView searchView; public static String query = ""; public SearchFragment() { // Required empty public constructor } public static SearchFragment newInstance() { SearchFragment fragment = new SearchFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = super.onCreateView(inflater, container, savedInstanceState); if (view != null) { ButterKnife.bind(this, view); } return view; } @NonNull @Override protected RecyclerView.Adapter provideAdapter(@NonNull List<Programme> items) { return new SearchAdapter(items, this); } @NonNull @Override protected RecyclerView.LayoutManager provideLayoutManager() { final int NUMBER_COLUMNS = getResources().getInteger(R.integer.search_columns); return new GridLayoutManager(getContext(), NUMBER_COLUMNS); } @Nullable @Override protected RecyclerView.ItemDecoration provideItemDecoration() { int spacing = (int)(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics())); final int NUMBER_COLUMNS = getResources().getInteger(R.integer.search_columns); return new InsideSpacingItemDecoration(spacing, 0, 0, 0, NUMBER_COLUMNS); } @Override protected void getListData(@NonNull final ListingData callback) { SearchProgrammeRepository.getInstance(getContext()).setSearchTerm(query); SearchProgrammeRepository.getInstance(getContext()).getItems(new ResponseHandler<Programme>() { @Override public void onSuccess(@NonNull List<Programme> items) { if (isAdded() && getActivity() != null) { if (callback != null) { callback.onListingDataRetrieved(items); } Track.event("Search", query); } } @Override public void onFailure(@Nullable Throwable t) { if (isAdded() || getActivity() != null) { if (callback != null) { callback.onListingDataError(t); } } } }); } @Override public int provideLayout() { return R.layout.search_layout; } @Override public int provideStatefulViewId() { return R.id.statefulview; } @Override public int provideLoadedLayout() { return R.layout.search_loaded; } @Override public int provideLoadingLayout() { return R.layout.search_loading; } @Override public int provideEmptyLayout() { return R.layout.search_empty; } @Override public int provideErrorLayout() { return R.layout.search_error; } @Override protected boolean shouldReloadOnResume() { return false; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); populateUi(); if (savedInstanceState != null) { String query = savedInstanceState.getString(ARG_QUERY, null); searchView.setQuery(query, true); } } private void populateUi() { // Make it default to the expanded state searchView.onActionViewExpanded(); final ListingData callback = this; // Set the listener to get data on submit searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { SearchFragment.query = query; getListData(callback); return true; } @Override public boolean onQueryTextChange(String newText) { return false; } }); } @Override public void onItemClick(Programme searchResult, View view) { ((MainActivity)getActivity()).showFragment(DetailsFragment.newInstance(searchResult)); } @OnClick(R.id.search_again) void onSearchAgainClicked() { // Clear existing query and show the expanded state, ready for the user to input their new query searchView.setQuery("", false); searchView.onActionViewCollapsed(); searchView.onActionViewExpanded(); } @Override public void onSaveInstanceState(Bundle outState) { CharSequence query = searchView.getQuery(); if (!TextUtils.isEmpty(query)) { outState.putString(ARG_QUERY, String.valueOf(query)); } super.onSaveInstanceState(outState); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/search/adapter/SearchAdapter.java
app/src/main/java/com/cube/lush/player/mobile/search/adapter/SearchAdapter.java
package com.cube.lush.player.mobile.search.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cube.lush.player.R; import com.lush.player.api.model.Programme; import com.cube.lush.player.mobile.search.holder.SearchViewHolder; import com.lush.lib.adapter.BaseSelectableListAdapter; import com.lush.lib.listener.OnListItemClickListener; import com.lush.view.holder.BaseViewHolder; import java.util.List; /** * Search Adapter * * @author Jamie Cruwys */ public class SearchAdapter extends BaseSelectableListAdapter<Programme> { public SearchAdapter(List<Programme> items, OnListItemClickListener<Programme> listener) { super(items, listener); } @Override public BaseViewHolder<Programme> onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_item, parent, false); return new SearchViewHolder(view); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/search/holder/SearchViewHolder.java
app/src/main/java/com/cube/lush/player/mobile/search/holder/SearchViewHolder.java
package com.cube.lush.player.mobile.search.holder; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.cube.lush.player.LushImageLoader; import com.cube.lush.player.R; import com.lush.player.api.model.Programme; import com.lush.view.holder.BaseViewHolder; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; /** * Search View Holder * * @author Jamie Cruwys */ public class SearchViewHolder extends BaseViewHolder<Programme> { @BindView(R.id.image) public ImageView image; @BindView(R.id.type) public TextView type; @BindView(R.id.title) public TextView title; public SearchViewHolder(View view) { super(view); ButterKnife.bind(this, view); } @Override public void bind(Programme searchResult) { type.setText(searchResult.getType().getName()); title.setText(searchResult.getTitle()); Picasso.with(image.getContext()) .load(searchResult.getThumbnail()) .fit() .centerInside() .into(image); } @Override public void recycle() { super.recycle(); LushImageLoader.cancelDisplay(image); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/channels/ChannelsFragment.java
app/src/main/java/com/cube/lush/player/mobile/channels/ChannelsFragment.java
package com.cube.lush.player.mobile.channels; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.View; import com.cube.lush.player.R; import com.lush.player.api.model.Channel; import com.cube.lush.player.content.handler.ResponseHandler; import com.cube.lush.player.content.repository.ChannelRepository; import com.cube.lush.player.mobile.MainActivity; import com.cube.lush.player.mobile.channels.adapter.ChannelsAdapter; import com.cube.lush.player.mobile.content.ChannelContentFragment; import com.cube.lush.player.mobile.decoration.InsideSpacingItemDecoration; import com.lush.lib.listener.OnListItemClickListener; import java.util.List; import uk.co.jamiecruwys.StatefulListingFragment; import uk.co.jamiecruwys.contracts.ListingData; /** * Channels Fragment * * @author Jamie Cruwys */ public class ChannelsFragment extends StatefulListingFragment<Channel> implements OnListItemClickListener<Channel> { public ChannelsFragment() { // Required empty public constructor } public static ChannelsFragment newInstance() { ChannelsFragment fragment = new ChannelsFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @NonNull @Override protected RecyclerView.LayoutManager provideLayoutManager() { final int NUMBER_COLUMNS = getResources().getInteger(R.integer.channel_columns); return new GridLayoutManager(getContext(), NUMBER_COLUMNS); } @NonNull @Override protected RecyclerView.Adapter provideAdapter(@NonNull List<Channel> items) { final int NUMBER_COLUMNS = getResources().getInteger(R.integer.channel_columns); int itemsToAdd = items.size() % NUMBER_COLUMNS; for (int index = 0; index < itemsToAdd; index++) { items.add(null); } return new ChannelsAdapter(items, this); } @Nullable @Override protected RecyclerView.ItemDecoration provideItemDecoration() { final int NUMBER_COLUMNS = getResources().getInteger(R.integer.channel_columns); int spacing = (int)(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics())); return new InsideSpacingItemDecoration(spacing, NUMBER_COLUMNS); } @Override protected void getListData(@NonNull final ListingData callback) { ChannelRepository.getInstance(getContext()).getItems(new ResponseHandler<Channel>() { @Override public void onSuccess(@NonNull List<Channel> items) { if (callback != null) { callback.onListingDataRetrieved(items); } } @Override public void onFailure(@Nullable Throwable t) { if (callback != null) { callback.onListingDataError(t); } } }); } @Override public int provideLoadedLayout() { return R.layout.channel_layout; } @Override public int provideLoadingLayout() { return R.layout.channel_loading; } @Override public int provideEmptyLayout() { return R.layout.channel_empty; } @Override public int provideErrorLayout() { return R.layout.channel_error; } @Override public void onItemClick(Channel channel, View view) { if (channel != null) { ((MainActivity)getActivity()).showFragment(ChannelContentFragment.newInstance(channel)); } } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/channels/adapter/ChannelsAdapter.java
app/src/main/java/com/cube/lush/player/mobile/channels/adapter/ChannelsAdapter.java
package com.cube.lush.player.mobile.channels.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.cube.lush.player.R; import com.lush.player.api.model.Channel; import com.cube.lush.player.mobile.channels.holder.ChannelViewHolder; import com.lush.lib.adapter.BaseSelectableListAdapter; import com.lush.lib.listener.OnListItemClickListener; import com.lush.view.holder.BaseViewHolder; import java.util.List; /** * Channels Adapter * * @author Jamie Cruwys */ public class ChannelsAdapter extends BaseSelectableListAdapter<Channel> { public ChannelsAdapter(List<Channel> items, OnListItemClickListener<Channel> listener) { super(items, listener); } @Override public BaseViewHolder<Channel> onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.channel_item, parent, false); return new ChannelViewHolder(view); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/mobile/channels/holder/ChannelViewHolder.java
app/src/main/java/com/cube/lush/player/mobile/channels/holder/ChannelViewHolder.java
package com.cube.lush.player.mobile.channels.holder; import android.text.TextUtils; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.cube.lush.player.LushImageLoader; import com.cube.lush.player.R; import com.lush.player.api.model.Channel; import com.lush.view.holder.BaseViewHolder; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; /** * Channel View Holder * * @author Jamie Cruwys */ public class ChannelViewHolder extends BaseViewHolder<Channel> { @BindView(R.id.image) public ImageView image; @BindView(R.id.alternative_text) public TextView alternativeText; public ChannelViewHolder(View view) { super(view); ButterKnife.bind(this, view); } @Override public void bind(Channel channel) { if (channel == null) { return; } String imageUri = channel.getImage(); if (TextUtils.isEmpty(imageUri)) { image.setVisibility(View.GONE); alternativeText.setText(channel.getName()); alternativeText.setVisibility(View.VISIBLE); return; } Picasso.with(image.getContext()) .load(imageUri) .fit() .centerInside() .into(image); } @Override public void recycle() { super.recycle(); LushImageLoader.cancelDisplay(image); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false
LUSHDigital/android-player
https://github.com/LUSHDigital/android-player/blob/980f805ab47d1cec23a9885f028c762115811aea/app/src/main/java/com/cube/lush/player/tv/MainFragment.java
app/src/main/java/com/cube/lush/player/tv/MainFragment.java
package com.cube.lush.player.tv; import android.os.Bundle; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.InvisibleRowPresenter; import android.support.v17.leanback.widget.PageRow; import android.widget.ImageView; import com.cube.lush.player.R; import com.cube.lush.player.tv.base.LushBrowseFragment; import com.cube.lush.player.tv.browse.MenuFragmentFactory; import com.cube.lush.player.tv.channels.ChannelsFragment; import com.cube.lush.player.tv.details.LiveDetailsFragment; import com.cube.lush.player.tv.home.HomeFragment; import java.util.Arrays; /** * Landing page for the app, displaying a menu for "Home", "Live", and "Channels" on the left, and associated content on the right. * <p/> * Modifies the default BrowseFragment to use PageRows, instead of ListRows. This is to meet the design requirements that (i) only one row is displayed at once, * instead of the grid behaviour implemented by RowsFragment, and (ii) to enable a vertical grid style for the home and channels pages. * <p> * Created by tim on 24/11/2016. */ public class MainFragment extends LushBrowseFragment { @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initialiseMenu(); } @Override protected void initialiseUI() { super.initialiseUI(); // The badge is very wide compared to its height, so reduce the height a bit or it looks too big ImageView badge = (ImageView) getTitleView().findViewById(R.id.title_badge); badge.getLayoutParams().height /= 4; } private void initialiseMenu() { // Create the objects backing the main menu PageRow homeRow = new PageRow(new HeaderItem(getString(R.string.title_home))); PageRow liveRow = new PageRow(new HeaderItem(getString(R.string.title_live))); PageRow channelsRow = new PageRow(new HeaderItem(getString(R.string.title_channels))); // Setup the fragment factory for the menu items MenuFragmentFactory fragmentFactory = new MenuFragmentFactory(); fragmentFactory.registerFragment(homeRow, new HomeFragment()); fragmentFactory.registerFragment(liveRow, new LiveDetailsFragment()); fragmentFactory.registerFragment(channelsRow, new ChannelsFragment()); getMainFragmentRegistry().registerFragment(PageRow.class, fragmentFactory); // Create and populate the main adapter ArrayObjectAdapter mainAdapter = new ArrayObjectAdapter(new InvisibleRowPresenter()); mainAdapter.addAll(0, Arrays.asList(homeRow, liveRow, channelsRow)); setAdapter(mainAdapter); } }
java
Apache-2.0
980f805ab47d1cec23a9885f028c762115811aea
2026-01-05T02:41:24.516248Z
false