private void download(String url) {
    try {
      mFile =
          FileUtil.getDestinationInExternalPublicDir(
              getFileDownloadPath(), mFileObject.getSaveName(mProjectObjectId));

      PersistentCookieStore cookieStore =
          new PersistentCookieStore(AttachmentsDownloadDetailActivity.this);
      String cookieString = "";
      for (Cookie cookie : cookieStore.getCookies()) {
        cookieString += cookie.getName() + "=" + cookie.getValue() + ";";
      }

      DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
      request.addRequestHeader("Cookie", cookieString);
      request.setDestinationInExternalPublicDir(
          getFileDownloadPath(), mFileObject.getSaveName(mProjectObjectId));
      request.setTitle(mFileObject.getName());
      // request.setDescription(mFileObject.name);
      // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
      request.setVisibleInDownloadsUi(false);
      // request.allowScanningByMediaScanner();
      // request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
      // request.setShowRunningNotification(false);

      downloadId = downloadManager.enqueue(request);
      downloadListEditor.putLong(mFileObject.file_id, downloadId);
      downloadListEditor.commit();
    } catch (Exception e) {
      Toast.makeText(this, R.string.no_system_download_service, Toast.LENGTH_LONG).show();
    }
  }
  @AfterViews
  protected final void initAttachmentsDownloadDetailActivity() {
    share =
        AttachmentsDownloadDetailActivity.this.getSharedPreferences(
            FileUtil.DOWNLOAD_SETTING, Context.MODE_PRIVATE);
    defaultPath = Environment.DIRECTORY_DOWNLOADS + File.separator + FileUtil.DOWNLOAD_FOLDER;
    mFileObject = mAttachmentFileObject;

    if (mAttachmentFileObject != null) {
      File file =
          FileUtil.getDestinationInExternalPublicDir(
              getFileDownloadPath(), mAttachmentFileObject.getSaveName(mProjectObjectId));
      if (file.exists() && file.isFile()) {
        jumpTextHtmlActivity();
        showState(STATE_FINISHDOWNLOAD);
      }
    }

    getSupportActionBar().setTitle(mAttachmentFileObject.getName());
    handler = new MyHandler();
    downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    downloadManagerPro = new DownloadManagerPro(downloadManager);

    completeReceiver = new CompleteReceiver();
    registerReceiver(completeReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    downloadList =
        AttachmentsDownloadDetailActivity.this.getSharedPreferences(
            FileUtil.DOWNLOAD_LIST, Context.MODE_PRIVATE);
    downloadListEditor = downloadList.edit();

    client = MyAsyncHttpClient.createClient(AttachmentsDownloadDetailActivity.this);

    //        urlPages = String.format(urlFiles, mProjectObjectId, mAttachmentFileObject.file_id,
    // mAttachmentFolderObject.file_id);
    urlFiles = String.format(urlFiles, mProjectObjectId, mAttachmentFileObject.file_id);
    urlDownload = String.format(urlDownload, mProjectObjectId, mAttachmentFileObject.file_id);
    if (mAttachmentFileObject == null) {
      mainLayout.setVisibility(View.GONE);
      showDialogLoading();
      getFileUrlFromNetwork();
    } else {
      bindView();
    }

    if (mHideHistoryLayout) {
      layout_dynamic_history.setVisibility(View.INVISIBLE);
    }
  }
  public void showRightTopPop() {

    if (mRightTopPopupWindow == null) {
      initRightTopPop();
    }

    // DialogUtil.RightTopPopupItem moveItem = mRightTopPopupWindow.adapter.getItem(0);
    DialogUtil.RightTopPopupItem deleteItem = mRightTopPopupWindow.adapter.getItem(0);

    if (!mAttachmentFileObject.isOwner()) {
      deleteItem.enabled = false;
    } else {
      deleteItem.enabled = true;
    }

    mRightTopPopupWindow.adapter.notifyDataSetChanged();

    Rect rectgle = new Rect();
    Window window = getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
    int StatusBarHeight = rectgle.top;
    int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
    // int TitleBarHeight= contentViewTop - StatusBarHeight;
    mRightTopPopupWindow.adapter.notifyDataSetChanged();
    mRightTopPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
    mRightTopPopupWindow.showAtLocation(icon, Gravity.TOP | Gravity.RIGHT, 0, contentViewTop);
  }
 @OptionsItem
 protected final void action_delete() {
   String messageFormat = "确定要删除文件 \"%s\" 么?";
   AlertDialog.Builder builder = new AlertDialog.Builder(AttachmentsDownloadDetailActivity.this);
   builder
       .setTitle("删除文件")
       .setMessage(String.format(messageFormat, mAttachmentFileObject.getName()))
       .setPositiveButton(
           "确定",
           new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
               showDialogLoading("正在删除");
               deleteNetwork(
                   String.format(
                       HOST_FILE_DELETE, mProjectObjectId, mAttachmentFileObject.file_id),
                   HOST_FILE_DELETE);
             }
           })
       .setNegativeButton(
           "取消",
           new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {}
           });
   // builder.create().show();
   AlertDialog dialog = builder.create();
   dialog.show();
   dialogTitleLineColor(dialog);
 }
  private void bindView() {
    hideProgressDialog();

    icon.setVisibility(View.VISIBLE);
    icon.setImageResource(mFileObject.getIconResourceId());

    iconTxt.setVisibility(View.GONE);

    name.setText(mFileObject.getName());

    content.setText(Global.HumanReadableFilesize(mFileObject.getSize()));

    tvDownload.setText(
        String.format(
            downloadFormat,
            Global.HumanReadableFilesize(0.0),
            Global.HumanReadableFilesize(mFileObject.getSize())));
    progressBar.setMax(mFileObject.getSize());
    mainLayout.setVisibility(View.VISIBLE);

    mFile =
        FileUtil.getDestinationInExternalPublicDir(
            getFileDownloadPath(), mFileObject.getSaveName(mProjectObjectId));
    Log.d(TAG, "downloadId:" + downloadId);

    File file =
        FileUtil.getDestinationInExternalPublicDir(
            getFileDownloadPath(), mAttachmentFileObject.getSaveName(mProjectObjectId));
    if (file.exists() && file.isFile()) {
      showState(STATE_FINISHDOWNLOAD);
    } else {
      showState(STATE_NEEDDOWNLOAD);
    }
  }
  @Override
  public void parseJson(int code, JSONObject response, String tag, int pos, Object data)
      throws JSONException {
    if (tag.equals(urlFiles)) {
      if (code == 0) {
        hideProgressDialog();
        JSONObject file = response.getJSONObject("data").getJSONObject("file");
        mFileObject = new AttachmentFileObject(file);
        downloadId = downloadList.getLong(mFileObject.file_id, 0L);

        icon.setVisibility(View.VISIBLE);
        icon.setImageResource(mFileObject.getIconResourceId());

        iconTxt.setVisibility(View.GONE);

        name.setText(mFileObject.name);

        content.setText(Global.HumanReadableFilesize(mFileObject.size));

        tvDownload.setText(
            String.format(
                downloadFormat,
                Global.HumanReadableFilesize(0.0),
                Global.HumanReadableFilesize(mFileObject.size)));
        progressBar.setMax(mFileObject.size);
        mainLayout.setVisibility(View.VISIBLE);

        mFile = FileUtil.getDestinationInExternalPublicDir(getFileDownloadPath(), mFileObject.name);
        Log.d(TAG, "downloadId:" + downloadId);
        if (mFile.exists() && mFile.isFile() && mFile.length() == mFileObject.size) {
          Log.d(TAG, "mFile exists:");
          if (downloadId != 0L) {
            updateView();
          }
          showState(STATE_FINISHDOWNLOAD);
        } else {
          Log.d(TAG, "mFile not exists:");
          showState(STATE_NEEDDOWNLOAD);
        }

      } else {
        hideProgressDialog();
        showErrorMsg(code, response);
      }
    } else if (tag.equals(HOST_FILE_DELETE)) {
      if (code == 0) {
        hideProgressDialog();
        showButtomToast("删除完成");
        Intent resultIntent = new Intent();
        resultIntent.putExtra("mAttachmentFileObject", mAttachmentFileObject);
        setResult(RESULT_OK, resultIntent);
        finish();
      } else {
        showErrorMsg(code, response);
      }
    }
  }
 private void jumpTextHtmlActivity() {
   if (mAttachmentFileObject.isMd()) {
     AttachmentsHtmlDetailActivity_.intent(this)
         .mProjectObjectId(mProjectObjectId)
         .mAttachmentFolderObject(mAttachmentFolderObject)
         .mAttachmentFileObject(mAttachmentFileObject)
         .mHideHistory(mHideHistoryLayout)
         .mProject(mProject)
         .startForResult(RESULT_EDIT_FILE);
   } else if (mAttachmentFileObject.isTxt()) {
     AttachmentsTextDetailActivity_.intent(this)
         .mProjectObjectId(mProjectObjectId)
         .mAttachmentFolderObject(mAttachmentFolderObject)
         .mProject(mProject)
         .mAttachmentFileObject(mAttachmentFileObject)
         .mHideHistory(mHideHistoryLayout)
         .startForResult(RESULT_EDIT_FILE);
   }
 }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    //        if (fileUrlSuccess) {
    getMenuInflater().inflate(R.menu.project_attachment_download, menu);
    if (!mAttachmentFileObject.isOwner()) {
      menu.findItem(R.id.action_delete).setVisible(false);
    }
    //        } else {
    //            getMenuInflater().inflate(R.menu.menu_empty, menu);
    //        }

    return super.onCreateOptionsMenu(menu);
  }
 @Override
 public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
   switch (position) {
     case 0:
       if (!mAttachmentFileObject.isOwner()) {
         return;
       } else {
         action_delete();
       }
       break;
   }
   mRightTopPopupWindow.dismiss();
 }
  @Override
  public void parseJson(int code, JSONObject respanse, String tag, int pos, Object data)
      throws JSONException {
    if (tag.equals(TAG_SAVE_CONTENT)) {
      showProgressBar(false);
      if (code == 0) {
        showProgressBar(true, "正在保存");
        setResult(RESULT_OK);
        String url = mParam.getHtttpFileView();
        getNetwork(url, TAG_HTTP_FILE_VIEW);

      } else {
        showErrorMsg(code, respanse);
      }
    } else if (tag.equals(TAG_HTTP_FILE_VIEW)) {
      showProgressBar(false);
      if (code == 0) {
        JSONObject json = respanse.optJSONObject("data").optJSONObject("file");
        AttachmentFileObject fileObject = new AttachmentFileObject(json);

        FileSaveHelp help = new FileSaveHelp(this);
        mParam.setFileObject(fileObject);
        File localFile = mParam.getLocalFile(help.getFileDownloadPath());
        writeFile(localFile, editText.getText().toString());
        fileObject.isDownload = true;

        Intent intent = new Intent();
        intent.putExtra(AttachmentFileObject.RESULT, fileObject);
        intent.putExtra(
            AttachmentsActivity.FileActions.ACTION_NAME,
            AttachmentsActivity.FileActions.ACTION_EDIT);
        setResult(RESULT_OK, intent);
        finish();
      } else {
        showErrorMsg(code, respanse);
      }
    }
  }
 @OptionsItem
 void action_info() {
   AlertDialog.Builder builder = new AlertDialog.Builder(this);
   AlertDialog dialog =
       builder
           .setTitle("文件信息")
           .setMessage(
               String.format(
                   fileInfoFormat,
                   mAttachmentFileObject.fileType,
                   Global.HumanReadableFilesize(mAttachmentFileObject.getSize()),
                   Global.dayToNow(mAttachmentFileObject.created_at),
                   Global.dayToNow(mAttachmentFileObject.updated_at),
                   mAttachmentFileObject.owner.name))
           .setPositiveButton("确定", null)
           .show();
   dialogTitleLineColor(dialog);
 }
Example #12
0
  public static void openActivityByUri(Context context, String uriString, boolean newTask) {
    Intent intent = new Intent();
    if (newTask) {
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }

    // 用户名
    final String atSomeOne = "^(?:https://[\\w.-]+)?/u/([\\w.-]+)$";
    Pattern pattern = Pattern.compile(atSomeOne);
    Matcher matcher = pattern.matcher(uriString);
    if (matcher.find()) {
      String global = matcher.group(1);
      intent.setClass(context, UserDetailActivity_.class);
      intent.putExtra("globalKey", global);
      context.startActivity(intent);
      return;
    }

    // 项目讨论
    // https://coding.net/u/8206503/p/AndroidCoding/topic/9638?page=1
    final String topic =
        "^https://[\\w.-]*/u/([\\w.-]+)/p/([\\w.-]+)/topic/(\\w+)(?:\\?[\\w=&-]*)?$";
    pattern = Pattern.compile(topic);
    matcher = pattern.matcher(uriString);
    if (matcher.find()) {
      intent.setClass(context, TopicListDetailActivity_.class);
      TopicListDetailActivity.TopicDetailParam param =
          new TopicListDetailActivity.TopicDetailParam(
              matcher.group(1), matcher.group(2), matcher.group(3));
      intent.putExtra("mJumpParam", param);
      context.startActivity(intent);
      return;
    }

    // 项目
    // https://coding.net/u/8206503/p/AndroidCoding
    final String project = "^https://[\\w.-]+/u/([\\w.-]+)/p/([\\w.-]+)$";
    pattern = Pattern.compile(project);
    matcher = pattern.matcher(uriString);
    if (matcher.find()) {
      intent.setClass(context, ProjectActivity_.class);
      ProjectActivity.ProjectJumpParam param =
          new ProjectActivity.ProjectJumpParam(matcher.group(1), matcher.group(2));
      intent.putExtra("mJumpParam", param);
      context.startActivity(intent);
      return;
    }

    // 冒泡
    // https://coding.net/u/8206503/pp/9275
    final String maopao = "^https://[\\w.-]+/u/([\\w.-]+)/pp/([\\w.-]+)$";
    pattern = Pattern.compile(maopao);
    matcher = pattern.matcher(uriString);
    if (matcher.find()) {
      intent.setClass(context, MaopaoDetailActivity_.class);
      MaopaoDetailActivity.ClickParam param =
          new MaopaoDetailActivity.ClickParam(matcher.group(1), matcher.group(2));
      intent.putExtra("mClickParam", param);
      context.startActivity(intent);
      return;
    }

    // 任务详情
    // https://coding.net/u/wzw/p/coding/task/9220
    final String task = "^https://[\\w.-]*/u/(\\w+)/p/([\\w-]+)/task/(\\w+)$";
    pattern = Pattern.compile(task);
    matcher = pattern.matcher(uriString);
    if (matcher.find()) {
      Log.d("", "gg " + matcher.group(1) + " " + matcher.group(2) + " " + matcher.group(3));
      intent.setClass(context, TaskAddActivity_.class);
      intent.putExtra(
          "mJumpParams",
          new TaskAddActivity.TaskJumpParams(matcher.group(1), matcher.group(2), matcher.group(3)));
      context.startActivity(intent);
      return;
    }

    // 私信推送
    // https://coding.net/user/messages/history/1984
    final String message = "^https://[\\w.-]*/user/messages/history/([\\w-]+)$";
    pattern = Pattern.compile(message);
    matcher = pattern.matcher(uriString);
    if (matcher.find()) {
      Log.d("", "gg " + matcher.group(1));
      intent.setClass(context, MessageListActivity_.class);
      intent.putExtra("mGlobalKey", matcher.group(1));
      context.startActivity(intent);
      return;
    }

    // 文件夹,这个url后面的字段是添加上去的
    // https://coding.net/u/8206503/p/TestIt2/attachment/65138/projectid/5741/name/aa.jpg
    final String dir =
        "^https://[\\w.-]+/u/([\\w.-]+)/p/([\\w.-]+)/attachment/([\\w.-]+)/projectid/([\\d]+)/name/(.*+)$";
    pattern = Pattern.compile(dir);
    matcher = pattern.matcher(uriString);
    if (matcher.find()) {
      AttachmentFolderObject folder = new AttachmentFolderObject();
      folder.file_id = matcher.group(3);
      folder.name = matcher.group(5);
      AttachmentsActivity_.intent(context)
          .mAttachmentFolderObject(folder)
          .mProjectObjectId(matcher.group(4))
          .start();
      return;
    }

    // 文件,这个url后面的字段是添加上去的
    // https://coding.net/u/8206503/p/TestIt2/attachment/65138/preview/66171/projectid/5741/name/aa.jpg
    final String dirFile =
        "^https://[\\w.-]+/u/([\\w.-]+)/p/([\\w.-]+)/attachment/([\\w.-]+)/preview/([\\d]+)/projectid/([\\d]+)/name/(.*+)$";
    pattern = Pattern.compile(dirFile);
    matcher = pattern.matcher(uriString);
    if (matcher.find()) {
      AttachmentFolderObject folder = new AttachmentFolderObject();
      folder.name = matcher.group(3);

      AttachmentFileObject folderFile = new AttachmentFileObject();
      folderFile.file_id = matcher.group(4);
      folderFile.name = matcher.group(6);

      String projectId = matcher.group(5);

      String extension = folderFile.name.toLowerCase();
      final String imageType = ".*\\.(gif|png|jpeg|jpg)$";
      final String htmlMdType = ".*\\.(html|htm|markd|markdown|md|mdown)$";
      final String txtType = ".*\\.(txt)$";
      if (extension.matches(imageType)) {
        AttachmentsPicDetailActivity_.intent(context)
            .mProjectObjectId(projectId)
            .mAttachmentFolderObject(folder)
            .mAttachmentFileObject(folderFile)
            .start();

      } else if (extension.matches(htmlMdType)) {
        AttachmentsHtmlDetailActivity_.intent(context)
            .mProjectObjectId(projectId)
            .mAttachmentFolderObject(folder)
            .mAttachmentFileObject(folderFile)
            .start();

      } else if (extension.matches(txtType)) {
        AttachmentsTextDetailActivity_.intent(context)
            .mProjectObjectId(projectId)
            .mAttachmentFolderObject(folder)
            .mAttachmentFileObject(folderFile)
            .start();
      } else {
        AttachmentsDownloadDetailActivity_.intent(context)
            .mProjectObjectId(projectId)
            .mAttachmentFolderObject(folder)
            .mAttachmentFileObject(folderFile)
            .start();
      }

      return;
    }

    final String imageSting = "(http|https):.*?.[.]{1}(gif|jpg|png|bmp)";
    pattern = Pattern.compile(imageSting);
    matcher = pattern.matcher(uriString);
    if (matcher.find()) {
      intent.setClass(context, ImagePagerActivity_.class);
      intent.putExtra("mSingleUri", uriString);
      context.startActivity(intent);
      return;
    }

    // 加了自定义图片前缀的链接
    if (uriString.indexOf(HtmlContent.TYPE_IMAGE_HEAD) == 0) {
      //            String imageUrl = uriString.replaceFirst(HtmlContent.TYPE_IMAGE_HEAD, "");
      //                intent.setClass(context, ImagePagerActivity_.class);
      //                intent.putExtra("mSingleUri", imageUrl);
      //                intent.putExtra("isPrivate", true);
      //                context.startActivity(intent);

      return;
    }

    Uri uri = Uri.parse(uriString);
    intent = new Intent(Intent.ACTION_VIEW, uri);
    if (newTask) {
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
    context.startActivity(intent);
  }