package com.novelbook.android; import android.Manifest; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.pdf.PdfDocument; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.Message; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.gson.Gson; import com.novelbook.android.adapter.BookListAdapter; import com.novelbook.android.bean.NovelSites; import com.novelbook.android.db.Chapter; import com.novelbook.android.db.DownloadTask; import com.novelbook.android.db.Novel; import com.novelbook.android.filechooser.FileChooserActivity; import com.novelbook.android.netsubscribe.BookSubscribe; import com.novelbook.android.netsubscribe.MovieSubscribe; import com.novelbook.android.netutils.HttpMethods; import com.novelbook.android.netutils.NetUtil; import com.novelbook.android.netutils.OnSuccessAndFaultListener; import com.novelbook.android.netutils.OnSuccessAndFaultSub; import com.novelbook.android.service.ChapterDownloadSvrc; import com.novelbook.android.service.MyIntentService; import com.novelbook.android.service.ServiceDownload; import com.novelbook.android.utils.BookUtil; import com.novelbook.android.utils.CommonUtil; import com.novelbook.android.utils.Constants; import com.novelbook.android.utils.GaoSiTransForm; import com.novelbook.android.utils.GsonUtil; import com.novelbook.android.utils.ImageUtil; import com.novelbook.android.utils.MyImageLoader; import com.novelbook.android.utils.NovelParseUtil; import com.novelbook.android.utils.PageFactory; import com.youth.banner.loader.ImageLoader; import org.json.JSONException; import org.json.JSONObject; import org.litepal.LitePal; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Date; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import jp.wasabeef.glide.transformations.BlurTransformation; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import static com.novelbook.android.FileActivity.EXTERNAL_STORAGE_REQ_CODE; public class BookActivity extends Activity_base { public static final String TAG=BookActivity.class.getSimpleName(); private PageFactory pageFactory; int novelId = 0; // String muluUrl = "https://www.qu.la/book/390/"; private Novel mNovel; private Chapter mChapter; BookListAdapter mAdapterAuthor; // private BookListAdapter mAdapter; private List mDataAuthor; BookListAdapter mAdapterRelated; // private BookListAdapter mAdapter; private List mDataRelated; ; //private Gson gson = new Gson(); private List mChapters = new ArrayList<>(); // @BindView(R.id.toolbar) // Toolbar toolbar; @BindView(R.id.rvBooklist) RecyclerView rvBooklistAuthor; @BindView(R.id.btnShelf) Button btnShelf; @BindView(R.id.imageView) ImageView imageView; @BindView(R.id.title) TextView txtTitle; @BindView(R.id.desc) TextView txtDesc; @BindView(R.id.author) TextView txtAuth; @BindView(R.id.category) TextView txtCategory; @BindView(R.id.txtDesc2) com.timqi.collapsibletextview.CollapsibleTextView txtDesc2; @BindView(R.id.txtLatestCate) TextView txtLatestCate; @BindView(R.id.btnCacheBook) Button btnCach; @BindView(R.id.rvBooklistRelated) RecyclerView rvBooklistRelated; Intent serviceIntent ; @BindView(R.id.imageViewHead) ImageView imageViewHead; @BindView(R.id.ll_others) LinearLayout llAuthorMore; @BindView(R.id.tvAuthorMore) TextView tvAuthorMore; @BindView(R.id.tvTonglei) TextView tvTonglei; @BindView(R.id.txtLatestUpdate) TextView tvLastUpdate; @BindView(R.id.progress) TextView tvProgress; @BindView(R.id.smallCate) TextView tvSmallcate; public Intent getSvrIntent(){ if(serviceIntent ==null){ serviceIntent= new Intent(this, ServiceDownload.class); } return serviceIntent; } @Override public int getLayoutRes() { return R.layout.activity_book; } @Override protected void initViews() { rvBooklistRelated.setVisibility(View.GONE); rvBooklistAuthor.setVisibility(View.GONE); tvTonglei.setVisibility(View.GONE); llAuthorMore. setVisibility(View.GONE); tvAuthorMore.setText( ""); initiDownloadReceiver(); /* if(Constants.SHOWAD){ loadNativeBannerAd(mBannerContainer,BuildConfig.AD_SLOT_TOUTIAO_BANNER_NATIVE_ID); mBannerContainer.setVisibility(View.VISIBLE); }else{ mBannerContainer.setVisibility(View.GONE); }*/ } @Override protected void setupToolbar() { super.setupToolbar(); // toolbar.setTitleMarginBottom(1); // toolbar.setTitleTextAppearance(this,R.style.TitleText); /* toolbar.inflateMenu(R.menu.menu_book);//设置右上角的填充菜单 toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { int menuItemId = item.getItemId(); if (menuItemId == R.id.menuShelf) { Toast.makeText(BookActivity.this,"show book shelf",Toast.LENGTH_LONG); } return true; } });*/ } public final static String EXTRA_BOOK ="book"; @Override protected void setTitle() { // getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.book_activity_custom_title); } @Override protected void initData() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkPermission(BookActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, EXTERNAL_STORAGE_REQ_CODE, "添加图书需要此权限,请允许"); } pageFactory = PageFactory.getInstance(getApplicationContext()); // pageFactory.clear(); setBookInfo();//set title ,data from novel list NetUtil.cancelRequest(mNovel.getNovelId()); getBookInfo(); } /** * 设置book list 传过来的基本信息 */ private void setBookInfo() { mNovel = (Novel) getIntent().getSerializableExtra(EXTRA_BOOK); novelId = mNovel.getNovelId(); this.setTitle(mNovel.getName()); btnCach.setText(R.string.cache_novel); // ((TextView) findViewById(R.id.left_text)).setText(mNovel.getName()); if(toolbar!=null) { toolbar.setTitle(mNovel.getName()); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Log.e("tag", "onNewINtent执行了"); setIntent(intent); initData(); } private void setNovelsSameAuthor(){ if(mDataAuthor!=null && mDataAuthor.size() >0){ tvAuthorMore.setText(mNovel.getAuthor()+ " 还写过"); llAuthorMore .setVisibility(View.VISIBLE); } else{ return; } rvBooklistAuthor.setVisibility(View.VISIBLE); // mAdapterAuthor = getBookListAdapter(mDataAuthor,R.layout.recycle_list_item_horizon); // rvBooklistAuthor.setLayoutManager(new LinearLayoutManager(this)); mAdapterAuthor = getBookListAdapter(mDataAuthor,R.layout.recycle_list_item_horizon); rvBooklistAuthor.setLayoutManager(new LinearLayoutManager(this)); rvBooklistAuthor.setAdapter(mAdapterAuthor); loadListAd_toutiao(mAdapterAuthor, 1 ,false); } private void setNovelsRelated(){ if(mDataRelated!=null && mDataRelated.size() >0){ tvTonglei.setVisibility(View.VISIBLE); }else { return; } rvBooklistRelated.setVisibility(View.VISIBLE); /* mAdapterRelated = getBookListAdapter(mDataRelated,R.layout.recycle_list_item); rvBooklistRelated.setLayoutManager(new GridLayoutManager(this, Constants.NOVEL_SPAN_CNT));*/ mAdapterRelated = getBookListAdapter(mDataRelated,R.layout.recycle_list_item_horizon); rvBooklistRelated.setLayoutManager(new LinearLayoutManager(this)); rvBooklistRelated.setAdapter(mAdapterRelated); loadListAd_toutiao(mAdapterRelated, 1 ,false); } /** * 设置服务器传来的详细信息 */ public void setBookDetailInfo() { setShelfButtonText(); //this.setTitle(mNovel.getName());//why not apply this.txtAuth.setText(mNovel.getAuthor()); this.txtCategory.setText(mNovel.getNovelType()); // this.txtDesc.setText(mNovel.getDesc ()); this.txtTitle.setText(mNovel.getName()); this.txtDesc2.setFullString(mNovel.getDesc ()); this.tvSmallcate.setText(mNovel.getSmallNovelType()); this.tvProgress.setText(mNovel.getProgress()); // txtDesc2.setCollapsedLines(2); // txtDesc2.setSuffixColor(R.color.colorPrimary); // txtDesc2.setExpanded(false); // txtDesc2.setSuffixTrigger(false); this.txtLatestCate.setText(mNovel.getChapterName()); tvLastUpdate.setText(CommonUtil.getDateString( mNovel.getLastUpdateTime())); loadImageView(mNovel.getCover(),imageView); try { gaosiHeadPic(); }catch (Exception e){ Log.e(TAG, "setBookDetailInfo: gosiheadpic error", e); } } void gaosiHeadPic(){ //new BlurTransformation(BookActivity.this, 10)).into(mImageView); /* URL url = null; try { url = new URL( NetUtil.getCoverUrl(mNovel.getCover())); } catch (MalformedURLException e) { e.printStackTrace(); }*/ String a =Uri.decode(NetUtil.getCoverUrl(mNovel.getCover())); Glide.with(BookActivity.this) .load( Uri.decode(NetUtil.getCoverUrl(mNovel.getCover()))) .dontAnimate() // .error(R.mipmap.side_bg2) .transform(new GaoSiTransForm(this, 150, 5)) // "14":模糊度;"3":图片缩放3倍后再进行模糊 .into(imageViewHead); // Glide.with(this).load(url) .transform(new BlurTransformation(BookActivity.this, 10)).into(imageViewHead); // Glide.with(this).load(imageView.getDrawable()).transform(new BlurTransformation(BookActivity.this, 10)).into(imageViewHead); } void setShelfButtonText() { String title = mNovel.isOnShelf() ? "移出书架" : "加入书架"; btnShelf.setText(title); } @OnClick({R.id.btnRead, R.id.btnCacheBook, R.id.btnShelf,R.id.llCate}) void submitButton(View view) { Intent intent; if(mNovel==null){ return; } switch (view.getId()) { case R.id.btnRead: readBook(); //testBook(); // openBook(new Novel() ); break; case R.id.btnCacheBook: cacheBook(); break; case R.id.btnShelf: shelfBook(); break; case R.id.llCate: // Log.d(TAG, String .format("prepareBook: current book %s, start to open book cate of %s" , mNovel.getName() , pageFactory.getNovle().getName())); intent = new Intent(BookActivity.this, MarkActivity.class); startActivity(intent);; break; } } private void shelfBook() { mNovel.setOnShelf(!mNovel.isOnShelf()); mNovel.save(); setShelfButtonText(); } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { int wt = msg.what; if (msg.what == 1) { setBookDetailInfo(); } else if (msg.what == 2) //准备数据,启动service { Toast.makeText(BookActivity.this, "已加入下载队列1", Toast.LENGTH_LONG).show(); } else if (msg.what == 3) { Toast.makeText(BookActivity.this, "获取目录信息失败,下载失败", Toast.LENGTH_LONG).show(); }else if (msg.what == 4) { Toast.makeText(BookActivity.this, String.format("亲,小说《%s》已经缓存完成了", mNovel.getName()), Toast.LENGTH_LONG).show(); }else if (msg.what == 5) { Toast.makeText(BookActivity.this, String.format("亲,小说《%s》已经在缓存队列了,请耐心等待", mNovel.getName()), Toast.LENGTH_LONG).show(); } hideProgress(); } }; private void readBook() { if (mNovel == null) { Toast.makeText(this, "网络错误", Toast.LENGTH_LONG); return; } ReadActivity.openBook(mNovel, BookActivity.this); } private void getChapters() { } boolean test=false; private void cacheBook() { if(test) { String url[] = { "https://img-blog.csdn.net/20160903083245762", "https://img-blog.csdn.net/20160903083252184", "https://img-blog.csdn.net/20160903083257871", "https://img-blog.csdn.net/20160903083257871", "https://img-blog.csdn.net/20160903083311972", "https://img-blog.csdn.net/20160903083319668", "https://img-blog.csdn.net/20160903083326871" }; Intent intent = new Intent(this, MyIntentService.class); for (int i=0;i<7;i++) {//循环启动任务 intent.putExtra(MyIntentService.DOWNLOAD_URL,url[i]); intent.putExtra(MyIntentService.INDEX_FLAG,i); startService(intent); } intent = getSvrIntent();//new Intent(this, ServiceDownload.class);;; for(int i=0;i<5;i++) { intent.putExtra("taskId",i); startService( intent); } // intent = new Intent(this, ChapterDownloadSvrc.class);;; // for(int i=0;i<3;i++) { // intent.putExtra("taskId",i); // startService( intent); } return; } // if (LitePal.where("novelId = ?", mNovel.getId() + "").count("DownloadTask") > 0) { // } new Thread() { @Override public void run() { int slepttime = 0; while (slepttime < 100 && pageFactory.getChapters().size() == 0) { try { sleep(50); slepttime++; } catch (InterruptedException e) { e.printStackTrace(); } } if (pageFactory.getChapters().size() == 0) { handler.sendEmptyMessage(3); } else { List dts = LitePal.where("novelId = ? and domain =?", mNovel.getId() + "",mNovel.getDomain()).limit(1).find(DownloadTask.class); if (dts.size() > 0) { if (dts.get(0).getStatus() == 1) { handler.sendEmptyMessage(4); } else { handler.sendEmptyMessage(5); startDownloadService(dts.get(0).getId()); // startService( getSvrIntent()); } return; } DownloadTask dt = new DownloadTask(); dt.setDomain(mNovel.getDomain()); dt.setDomainName(mNovel.getDomainName()); dt.setFinishedChpats(0); dt.setNovelId(mNovel.getId()); dt.setStatus(0); // dt.setTotalChapts(mNovel.getChaptCnt()); dt.setTotalChapts(pageFactory.getChapters().size()); dt.setNovelTitle(mNovel.getName()); dt.save(); // LitePal.deleteAll("chapter","novelId=?",mNovel.getId()+""); for (Chapter chapter : pageFactory.getChapters()) { chapter.setNovelId(mNovel.getId()); chapter.setTaskId(dt.getId()); chapter.save(); } startDownloadService(dt.getId()); handler.sendEmptyMessage(2); } // Toast.makeText(BookActivity.this,"已加入下载队列2",Toast.LENGTH_LONG).show(); } }.start(); showProgressDialog(false, "正在加入到队列,请等待"); } private void startDownloadService(int taskId) { Intent serviceIntent = getSvrIntent(); // serviceIntent.putExtra("taskId",taskId); // serviceIntent.putExtra("start",true); startService(serviceIntent); } void openBook(Novel book) { final String path = book.getNovelPath(); if (null == path) { List bookLists = LitePal.findAll(Novel.class); if (bookLists.size() > 0) { openBook(bookLists.get(0)); } return; } File file = new File(path); if (!file.exists()) { //to get book content txt from web new AlertDialog.Builder(this) .setTitle(this.getString(R.string.app_name)) .setMessage(path + "文件不存在,是否删除该书本?") .setPositiveButton("删除", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { LitePal.deleteAll(Novel.class, "bookpath = ?", path); } }).setCancelable(true).show(); return; } // ReadActivity.openBook(book ,null,this); } void getBookInfo() { boolean isLocalDbExist = LitePal.isExist(Novel.class, "novelId=?", novelId+""); showProgressDialog(false,"正在加载..."); BookSubscribe.getNovel(novelId, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() { @Override public void onSuccess(String result) { //成功 Novel nv; nv = gson.fromJson(result, Novel.class); // nv = GsonUtil.getNovel(result); if (!isLocalDbExist) { // nv.saveAsync(); nv.save(); mNovel =nv; } else { nv.checkAndUpdate(); // nv.updateAll("novelId=?", novelId+""); // mNovel = Novel.getNovelBySvrId(novelId); } if (null != mNovel) { handler.sendEmptyMessage(1); } pageFactory.prepareBook(mNovel); // Toast.makeText(BookActivity.this,"Novel 请求成功:"+result,Toast.LENGTH_SHORT).show(); } @Override public void onFault(String errorMsg) { //失败 Toast.makeText(BookActivity.this, mNovel.getName() +" 加载失败", Toast.LENGTH_SHORT).show(); mNovel = Novel.getNovelBySvrId(novelId); if (null != mNovel) { handler.sendEmptyMessage(1); pageFactory.prepareBook(mNovel); } } }, BookActivity.this)); BookSubscribe.getNovelsRelated(novelId, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() { @Override public void onSuccess(String result) { //成功 try { mDataRelated = GsonUtil. parserJsonArray(result,Constants.BLOCK_TITLE_NOVELS); setNovelsRelated(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onFault(String errorMsg) { } }, BookActivity.this)); BookSubscribe.getNovelsSameAuthor(novelId, new OnSuccessAndFaultSub(new OnSuccessAndFaultListener() { @Override public void onSuccess(String result) { //成功 try { mDataAuthor = GsonUtil. parserJsonArray(result,Constants.BLOCK_TITLE_NOVELS); setNovelsSameAuthor(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onFault(String errorMsg) { } }, BookActivity.this)); } /* void readChapters( String url){ //to get mulu list url = muluUrl;// "https://www.qu.la/book/161/";//"https://www.qu.la/book/746/"; Request request = new Request.Builder() .url(url) // .header("User-Agent", "OkHttp Example") .build(); HttpMethods.getOkClient().newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(TAG, "onFailure: " + e.getMessage()); } @Override public void onResponse(Call call, Response response){ ResponseBody body = response.body(); if (body != null) { try { String bodyStr = body.string(); Log.d(TAG, "onResponse: " +bodyStr); onResponseProcess(bodyStr,url); ReadActivity.openBook(mNovel ,mChapter,BookActivity.this); } catch (IOException e) { e.printStackTrace(); }finally { body.close(); } } } }); } void onResponseProcess( String content ,String url){ // HttpResult result ; // HttpResult result2 = null; try { JSONObject siteJson = new JSONObject(); siteJson.put("chapterUrlRegexOnMulu", ""); siteJson.put("chapterUrlPattern", "/book/[\\d]+/[\\d]+\\.html$"); siteJson.put("chapterUrlRegexOnMulu", "
]*href=\"(/book/[\\d]+/[\\d]+\\.html)\">([^<]+)
"); mChapters = NovelParseUtil.getChapters(url, content, siteJson); if (mChapters != null) { int lastReadChapt = mNovel.getLastReadChapt(); // int index =lastReadChapt*2-2; lastReadChapt = lastReadChapt >=mChapters.size() ? mChapters.size() -1:lastReadChapt; lastReadChapt = lastReadChapt <=0 ? 1:lastReadChapt; mChapter =mChapters.get(lastReadChapt-1); } } catch (JSONException e) { // } catch (JSONException | IOException e) { e.printStackTrace(); } finally { // result.close(); // if (result2 != null) result2.close(); } }*/ //----------------绑定列表 @Override protected void onResume() { super.onResume(); registerReceiver(receiver,filter); if(mNovel!=null && mNovel.getId()>0) { mNovel = LitePal.find(Novel.class, mNovel.getId()); //更新最新进度 if(pageFactory==null){ pageFactory = PageFactory.getInstance(getApplicationContext()); } if( pageFactory.isWorking() && ( pageFactory.getNovle()==null || mNovel.getId() !=pageFactory.getNovle().getId())){ pageFactory.prepareBook(mNovel); } setShelfButtonText(); } // View v =findViewById(R.id.head_img); // v.measure(0,0); // BlurKit.getInstance().blur(v, 20); // BlurKit.getInstance().fastBlur(v,20, 0.3f); } @Override public void onPause() { super.onPause(); unregisterReceiver(receiver); } @Override public void fillData() { } @Override protected void onStart() { super.onStart(); // blurLayout.startBlur(); // blurLayout.lockView(); } @Override protected void onStop() { super.onStop(); // blurLayout.pauseBlur(); } private IntentFilter filter; DownloadProcessReceiver receiver; void initiDownloadReceiver(){ if(filter==null) { filter = new IntentFilter("ServiceDownload.ChapterContent.finished"); filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new DownloadProcessReceiver(); } } class DownloadProcessReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent){ int novelId =0; int progress=0; if( intent.hasExtra("novelId")){ novelId = intent.getIntExtra("novelId",0); } if( intent.hasExtra("progress")){ progress = intent.getIntExtra("progress",0); } if(novelId == mNovel.getId()){ try { String cpsize = pageFactory.getChapters().size() >0 ? pageFactory.getChapters().size() +"":"--"; btnCach.setText(progress + "/" + cpsize); }catch (Exception e){ Log.e(TAG, "onReceive: ", e); } } } } }