private void showErrorBox(String error) {
   if (getParentActivity() == null) {
     return;
   }
   new AlertDialog.Builder(getParentActivity())
       .setTitle(LocaleController.getString("AppName", R.string.AppName))
       .setMessage(error)
       .setPositiveButton(LocaleController.getString("OK", R.string.OK), null)
       .show();
 }
Example #2
0
  public static Dialog createMuteAlert(Context context, final long dialog_id) {
    if (context == null) {
      return null;
    }

    BottomSheet.Builder builder = new BottomSheet.Builder(context);
    builder.setTitle(LocaleController.getString("Notifications", R.string.Notifications));
    CharSequence[] items =
        new CharSequence[] {
          LocaleController.formatString(
              "MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Hours", 1)),
          LocaleController.formatString(
              "MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Hours", 8)),
          LocaleController.formatString(
              "MuteFor", R.string.MuteFor, LocaleController.formatPluralString("Days", 2)),
          LocaleController.getString("MuteDisable", R.string.MuteDisable)
        };
    builder.setItems(
        items,
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialogInterface, int i) {
            int untilTime = ConnectionsManager.getInstance().getCurrentTime();
            if (i == 0) {
              untilTime += 60 * 60;
            } else if (i == 1) {
              untilTime += 60 * 60 * 8;
            } else if (i == 2) {
              untilTime += 60 * 60 * 48;
            } else if (i == 3) {
              untilTime = Integer.MAX_VALUE;
            }

            SharedPreferences preferences =
                ApplicationLoader.applicationContext.getSharedPreferences(
                    "Notifications", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            long flags;
            if (i == 3) {
              editor.putInt("notify2_" + dialog_id, 2);
              flags = 1;
            } else {
              editor.putInt("notify2_" + dialog_id, 3);
              editor.putInt("notifyuntil_" + dialog_id, untilTime);
              flags = ((long) untilTime << 32) | 1;
            }
            MessagesStorage.getInstance().setDialogFlags(dialog_id, flags);
            editor.commit();
            TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id);
            if (dialog != null) {
              dialog.notify_settings = new TLRPC.TL_peerNotifySettings();
              dialog.notify_settings.mute_until = untilTime;
            }
            NotificationsController.updateServerNotificationsSettings(dialog_id);
          }
        });
    return builder.create();
  }
  public void setDocument(MessageObject document, boolean divider) {
    needDivider = divider;
    message = document;
    loaded = false;
    loading = false;

    if (document != null && document.messageOwner.media != null) {
      int idx;
      String name = FileLoader.getDocumentFileName(document.messageOwner.media.document);
      placeholderImabeView.setVisibility(VISIBLE);
      extTextView.setVisibility(VISIBLE);
      placeholderImabeView.setImageResource(
          getThumbForNameOrMime(name, document.messageOwner.media.document.mime_type));
      nameTextView.setText(name);
      extTextView.setText(
          (idx = name.lastIndexOf(".")) == -1 ? "" : name.substring(idx + 1).toLowerCase());
      if (document.messageOwner.media.document.thumb instanceof TLRPC.TL_photoSizeEmpty
          || document.messageOwner.media.document.thumb == null) {
        thumbImageView.setVisibility(INVISIBLE);
        thumbImageView.setImageBitmap(null);
      } else {
        thumbImageView.setVisibility(VISIBLE);
        thumbImageView.setImage(
            document.messageOwner.media.document.thumb.location, "40_40", (Drawable) null);
      }
      long date = (long) document.messageOwner.date * 1000;
      dateTextView.setText(
          String.format(
              "%s, %s",
              AndroidUtilities.formatFileSize(document.messageOwner.media.document.size),
              LocaleController.formatString(
                  "formatDateAtTime",
                  R.string.formatDateAtTime,
                  LocaleController.formatterYear.format(new Date(date)),
                  LocaleController.formatterDay.format(new Date(date)))));
    } else {
      nameTextView.setText("");
      extTextView.setText("");
      dateTextView.setText("");
      placeholderImabeView.setVisibility(VISIBLE);
      extTextView.setVisibility(VISIBLE);
      thumbImageView.setVisibility(INVISIBLE);
      thumbImageView.setImageBitmap(null);
    }

    setWillNotDraw(!needDivider);
    progressView.setProgress(0, false);
    updateFileExistIcon();
  }
 private String getRootSubtitle(String path) {
   try {
     StatFs stat = new StatFs(path);
     long total = (long) stat.getBlockCount() * (long) stat.getBlockSize();
     long free = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize();
     if (total == 0) {
       return "";
     }
     return LocaleController.formatString(
         "FreeOfTotal",
         R.string.FreeOfTotal,
         AndroidUtilities.formatFileSize(free),
         AndroidUtilities.formatFileSize(total));
   } catch (Exception e) {
     FileLog.e("tmessages", e);
   }
   return path;
 }
  @SuppressLint("NewApi")
  private void listRoots() {
    currentDir = null;
    items.clear();

    HashSet<String> paths = new HashSet<>();
    String defaultPath = Environment.getExternalStorageDirectory().getPath();
    boolean isDefaultPathRemovable =
        Build.VERSION.SDK_INT >= 9 && Environment.isExternalStorageRemovable();
    String defaultPathState = Environment.getExternalStorageState();
    if (defaultPathState.equals(Environment.MEDIA_MOUNTED)
        || defaultPathState.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
      ListItem ext = new ListItem();
      if (Build.VERSION.SDK_INT < 9 || Environment.isExternalStorageRemovable()) {
        ext.title = LocaleController.getString("SdCard", R.string.SdCard);
        ext.icon = R.drawable.ic_external_storage;
      } else {
        ext.title = LocaleController.getString("InternalStorage", R.string.InternalStorage);
        ext.icon = R.drawable.ic_storage;
      }
      ext.subtitle = getRootSubtitle(defaultPath);
      ext.file = Environment.getExternalStorageDirectory();
      items.add(ext);
      paths.add(defaultPath);
    }

    BufferedReader bufferedReader = null;
    try {
      bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        if (line.contains("vfat") || line.contains("/mnt")) {
          FileLog.e("tmessages", line);
          StringTokenizer tokens = new StringTokenizer(line, " ");
          String unused = tokens.nextToken();
          String path = tokens.nextToken();
          if (paths.contains(path)) {
            continue;
          }
          if (line.contains("/dev/block/vold")) {
            if (!line.contains("/mnt/secure")
                && !line.contains("/mnt/asec")
                && !line.contains("/mnt/obb")
                && !line.contains("/dev/mapper")
                && !line.contains("tmpfs")) {
              if (!new File(path).isDirectory()) {
                int index = path.lastIndexOf('/');
                if (index != -1) {
                  String newPath = "/storage/" + path.substring(index + 1);
                  if (new File(newPath).isDirectory()) {
                    path = newPath;
                  }
                }
              }
              paths.add(path);
              try {
                ListItem item = new ListItem();
                if (path.toLowerCase().contains("sd")) {
                  item.title = LocaleController.getString("SdCard", R.string.SdCard);
                } else {
                  item.title =
                      LocaleController.getString("ExternalStorage", R.string.ExternalStorage);
                }
                item.icon = R.drawable.ic_external_storage;
                item.subtitle = getRootSubtitle(path);
                item.file = new File(path);
                items.add(item);
              } catch (Exception e) {
                FileLog.e("tmessages", e);
              }
            }
          }
        }
      }
    } catch (Exception e) {
      FileLog.e("tmessages", e);
    } finally {
      if (bufferedReader != null) {
        try {
          bufferedReader.close();
        } catch (Exception e) {
          FileLog.e("tmessages", e);
        }
      }
    }
    ListItem fs = new ListItem();
    fs.title = "/";
    fs.subtitle = LocaleController.getString("SystemRoot", R.string.SystemRoot);
    fs.icon = R.drawable.ic_directory;
    fs.file = new File("/");
    items.add(fs);

    try {
      File telegramPath = new File(Environment.getExternalStorageDirectory(), "Telegram");
      if (telegramPath.exists()) {
        fs = new ListItem();
        fs.title = "Telegram";
        fs.subtitle = telegramPath.toString();
        fs.icon = R.drawable.ic_directory;
        fs.file = telegramPath;
        items.add(fs);
      }
    } catch (Exception e) {
      FileLog.e("tmessages", e);
    }

    fs = new ListItem();
    fs.title = LocaleController.getString("Gallery", R.string.Gallery);
    fs.subtitle = LocaleController.getString("GalleryInfo", R.string.GalleryInfo);
    fs.icon = R.drawable.ic_storage_gallery;
    fs.file = null;
    items.add(fs);

    AndroidUtilities.clearDrawableAnimation(listView);
    scrolling = true;
    listAdapter.notifyDataSetChanged();
  }
 private boolean listFiles(File dir) {
   if (!dir.canRead()) {
     if (dir.getAbsolutePath().startsWith(Environment.getExternalStorageDirectory().toString())
         || dir.getAbsolutePath().startsWith("/sdcard")
         || dir.getAbsolutePath().startsWith("/mnt/sdcard")) {
       if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
           && !Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
         currentDir = dir;
         items.clear();
         String state = Environment.getExternalStorageState();
         if (Environment.MEDIA_SHARED.equals(state)) {
           emptyView.setText(LocaleController.getString("UsbActive", R.string.UsbActive));
         } else {
           emptyView.setText(LocaleController.getString("NotMounted", R.string.NotMounted));
         }
         AndroidUtilities.clearDrawableAnimation(listView);
         scrolling = true;
         listAdapter.notifyDataSetChanged();
         return true;
       }
     }
     showErrorBox(LocaleController.getString("AccessError", R.string.AccessError));
     return false;
   }
   emptyView.setText(LocaleController.getString("NoFiles", R.string.NoFiles));
   File[] files;
   try {
     files = dir.listFiles();
   } catch (Exception e) {
     showErrorBox(e.getLocalizedMessage());
     return false;
   }
   if (files == null) {
     showErrorBox(LocaleController.getString("UnknownError", R.string.UnknownError));
     return false;
   }
   currentDir = dir;
   items.clear();
   Arrays.sort(
       files,
       new Comparator<File>() {
         @Override
         public int compare(File lhs, File rhs) {
           if (lhs.isDirectory() != rhs.isDirectory()) {
             return lhs.isDirectory() ? -1 : 1;
           }
           return lhs.getName().compareToIgnoreCase(rhs.getName());
           /*long lm = lhs.lastModified();
           long rm = lhs.lastModified();
           if (lm == rm) {
               return 0;
           } else if (lm > rm) {
               return -1;
           } else {
               return 1;
           }*/
         }
       });
   for (File file : files) {
     if (file.getName().startsWith(".")) {
       continue;
     }
     ListItem item = new ListItem();
     item.title = file.getName();
     item.file = file;
     if (file.isDirectory()) {
       item.icon = R.drawable.ic_directory;
       item.subtitle = LocaleController.getString("Folder", R.string.Folder);
     } else {
       String fname = file.getName();
       String[] sp = fname.split("\\.");
       item.ext = sp.length > 1 ? sp[sp.length - 1] : "?";
       item.subtitle = AndroidUtilities.formatFileSize(file.length());
       fname = fname.toLowerCase();
       if (fname.endsWith(".jpg")
           || fname.endsWith(".png")
           || fname.endsWith(".gif")
           || fname.endsWith(".jpeg")) {
         item.thumb = file.getAbsolutePath();
       }
     }
     items.add(item);
   }
   ListItem item = new ListItem();
   item.title = "..";
   if (history.size() > 0) {
     HistoryEntry entry = history.get(history.size() - 1);
     if (entry.dir == null) {
       item.subtitle = LocaleController.getString("Folder", R.string.Folder);
     } else {
       item.subtitle = entry.dir.toString();
     }
   } else {
     item.subtitle = LocaleController.getString("Folder", R.string.Folder);
   }
   item.icon = R.drawable.ic_directory;
   item.file = null;
   items.add(0, item);
   AndroidUtilities.clearDrawableAnimation(listView);
   scrolling = true;
   listAdapter.notifyDataSetChanged();
   return true;
 }
  @Override
  public View createView(Context context) {
    if (!receiverRegistered) {
      receiverRegistered = true;
      IntentFilter filter = new IntentFilter();
      filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
      filter.addAction(Intent.ACTION_MEDIA_CHECKING);
      filter.addAction(Intent.ACTION_MEDIA_EJECT);
      filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
      filter.addAction(Intent.ACTION_MEDIA_NOFS);
      filter.addAction(Intent.ACTION_MEDIA_REMOVED);
      filter.addAction(Intent.ACTION_MEDIA_SHARED);
      filter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
      filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
      filter.addDataScheme("file");
      ApplicationLoader.applicationContext.registerReceiver(receiver, filter);
    }

    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("SelectFile", R.string.SelectFile));
    actionBar.setActionBarMenuOnItemClick(
        new ActionBar.ActionBarMenuOnItemClick() {
          @Override
          public void onItemClick(int id) {
            if (id == -1) {
              finishFragment();
            } else if (id == -2) {
              selectedFiles.clear();
              actionBar.hideActionMode();
              listView.invalidateViews();
            } else if (id == done) {
              if (delegate != null) {
                ArrayList<String> files = new ArrayList<>();
                files.addAll(selectedFiles.keySet());
                delegate.didSelectFiles(DocumentSelectActivity.this, files);
              }
            }
          }
        });
    selectedFiles.clear();
    actionModeViews.clear();

    final ActionBarMenu actionMode = actionBar.createActionMode();
    actionModeViews.add(
        actionMode.addItem(
            -2,
            R.drawable.ic_ab_back_grey,
            R.drawable.bar_selector_mode,
            null,
            AndroidUtilities.dp(54)));

    selectedMessagesCountTextView = new TextView(actionMode.getContext());
    selectedMessagesCountTextView.setTextSize(18);
    selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    selectedMessagesCountTextView.setTextColor(0xff737373);
    selectedMessagesCountTextView.setSingleLine(true);
    selectedMessagesCountTextView.setLines(1);
    selectedMessagesCountTextView.setEllipsize(TextUtils.TruncateAt.END);
    selectedMessagesCountTextView.setPadding(AndroidUtilities.dp(11), 0, 0, AndroidUtilities.dp(2));
    selectedMessagesCountTextView.setGravity(Gravity.CENTER_VERTICAL);
    selectedMessagesCountTextView.setOnTouchListener(
        new View.OnTouchListener() {
          @Override
          public boolean onTouch(View v, MotionEvent event) {
            return true;
          }
        });
    actionMode.addView(selectedMessagesCountTextView);
    LinearLayout.LayoutParams layoutParams =
        (LinearLayout.LayoutParams) selectedMessagesCountTextView.getLayoutParams();
    layoutParams.weight = 1;
    layoutParams.width = 0;
    layoutParams.height = LayoutHelper.MATCH_PARENT;
    selectedMessagesCountTextView.setLayoutParams(layoutParams);

    actionModeViews.add(
        actionMode.addItem(
            done,
            R.drawable.ic_ab_done_gray,
            R.drawable.bar_selector_mode,
            null,
            AndroidUtilities.dp(54)));

    fragmentView =
        getParentActivity()
            .getLayoutInflater()
            .inflate(R.layout.document_select_layout, null, false);
    listAdapter = new ListAdapter(context);
    emptyView = (TextView) fragmentView.findViewById(R.id.searchEmptyView);
    emptyView.setOnTouchListener(
        new View.OnTouchListener() {
          @Override
          public boolean onTouch(View v, MotionEvent event) {
            return true;
          }
        });
    listView = (ListView) fragmentView.findViewById(R.id.listView);
    listView.setEmptyView(emptyView);
    listView.setAdapter(listAdapter);

    listView.setOnScrollListener(
        new AbsListView.OnScrollListener() {
          @Override
          public void onScrollStateChanged(AbsListView view, int scrollState) {
            scrolling = scrollState != SCROLL_STATE_IDLE;
          }

          @Override
          public void onScroll(
              AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {}
        });

    listView.setOnItemLongClickListener(
        new AdapterView.OnItemLongClickListener() {
          @Override
          public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long id) {
            if (actionBar.isActionModeShowed() || i < 0 || i >= items.size()) {
              return false;
            }
            ListItem item = items.get(i);
            File file = item.file;
            if (file != null && !file.isDirectory()) {
              if (!file.canRead()) {
                showErrorBox(LocaleController.getString("AccessError", R.string.AccessError));
                return false;
              }
              if (sizeLimit != 0) {
                if (file.length() > sizeLimit) {
                  showErrorBox(
                      LocaleController.formatString(
                          "FileUploadLimit",
                          R.string.FileUploadLimit,
                          AndroidUtilities.formatFileSize(sizeLimit)));
                  return false;
                }
              }
              if (file.length() == 0) {
                return false;
              }
              selectedFiles.put(file.toString(), item);
              selectedMessagesCountTextView.setText(String.format("%d", selectedFiles.size()));
              if (Build.VERSION.SDK_INT >= 11) {
                AnimatorSetProxy animatorSet = new AnimatorSetProxy();
                ArrayList<Object> animators = new ArrayList<>();
                for (int a = 0; a < actionModeViews.size(); a++) {
                  View view2 = actionModeViews.get(a);
                  AndroidUtilities.clearDrawableAnimation(view2);
                  if (a < 1) {
                    animators.add(
                        ObjectAnimatorProxy.ofFloat(
                            view2, "translationX", -AndroidUtilities.dp(56), 0));
                  } else {
                    animators.add(ObjectAnimatorProxy.ofFloat(view2, "scaleY", 0.1f, 1.0f));
                  }
                }
                animatorSet.playTogether(animators);
                animatorSet.setDuration(250);
                animatorSet.start();
              }
              scrolling = false;
              if (view instanceof SharedDocumentCell) {
                ((SharedDocumentCell) view).setChecked(true, true);
              }
              actionBar.showActionMode();
            }
            return true;
          }
        });

    listView.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (i < 0 || i >= items.size()) {
              return;
            }
            ListItem item = items.get(i);
            File file = item.file;
            if (file == null) {
              if (item.icon == R.drawable.ic_storage_gallery) {
                if (delegate != null) {
                  delegate.startDocumentSelectActivity();
                }
                finishFragment(false);
              } else {
                HistoryEntry he = history.remove(history.size() - 1);
                actionBar.setTitle(he.title);
                if (he.dir != null) {
                  listFiles(he.dir);
                } else {
                  listRoots();
                }
                listView.setSelectionFromTop(he.scrollItem, he.scrollOffset);
              }
            } else if (file.isDirectory()) {
              HistoryEntry he = new HistoryEntry();
              he.scrollItem = listView.getFirstVisiblePosition();
              he.scrollOffset = listView.getChildAt(0).getTop();
              he.dir = currentDir;
              he.title = actionBar.getTitle();
              history.add(he);
              if (!listFiles(file)) {
                history.remove(he);
                return;
              }
              actionBar.setTitle(item.title);
              listView.setSelection(0);
            } else {
              if (!file.canRead()) {
                showErrorBox(LocaleController.getString("AccessError", R.string.AccessError));
                file = new File("/mnt/sdcard");
              }
              if (sizeLimit != 0) {
                if (file.length() > sizeLimit) {
                  showErrorBox(
                      LocaleController.formatString(
                          "FileUploadLimit",
                          R.string.FileUploadLimit,
                          AndroidUtilities.formatFileSize(sizeLimit)));
                  return;
                }
              }
              if (file.length() == 0) {
                return;
              }
              if (actionBar.isActionModeShowed()) {
                if (selectedFiles.containsKey(file.toString())) {
                  selectedFiles.remove(file.toString());
                } else {
                  selectedFiles.put(file.toString(), item);
                }
                if (selectedFiles.isEmpty()) {
                  actionBar.hideActionMode();
                } else {
                  selectedMessagesCountTextView.setText(String.format("%d", selectedFiles.size()));
                }
                scrolling = false;
                if (view instanceof SharedDocumentCell) {
                  ((SharedDocumentCell) view)
                      .setChecked(selectedFiles.containsKey(item.file.toString()), true);
                }
              } else {
                if (delegate != null) {
                  ArrayList<String> files = new ArrayList<>();
                  files.add(file.getAbsolutePath());
                  delegate.didSelectFiles(DocumentSelectActivity.this, files);
                }
              }
            }
          }
        });

    listRoots();

    return fragmentView;
  }