コード例 #1
0
ファイル: CacheManager.java プロジェクト: jmsloat/RedReader
    private WritableCacheFile(final CacheRequest request, final UUID session, final String mimetype)
        throws IOException {

      this.request = request;
      compressed = request.isJson;

      final File tmpFile =
          new File(General.getBestCacheDir(context), UUID.randomUUID().toString() + tempExt);
      final FileOutputStream fos = new FileOutputStream(tmpFile);

      final OutputStream compressedOs;

      if (compressed) {
        compressedOs = new GZIPOutputStream(new BufferedOutputStream(fos, 8 * 1024));
      } else {
        compressedOs = new BufferedOutputStream(fos, 8 * 1024);
      }

      final NotifyOutputStream.Listener listener =
          new NotifyOutputStream.Listener() {
            public void onClose() throws IOException {

              cacheFileId = dbManager.newEntry(request, session, mimetype);

              final File dstFile = new File(General.getBestCacheDir(context), cacheFileId + ext);
              General.moveFile(tmpFile, dstFile);

              dbManager.setEntryDone(cacheFileId);

              readableCacheFile = new ReadableCacheFile(cacheFileId, compressed);
            }
          };

      this.os = new NotifyOutputStream(compressedOs, listener);
    }
コード例 #2
0
  public ImgurAlbumListEntryView(final Context context) {

    super(context);

    setOrientation(HORIZONTAL);

    mThumbnail = new ImageView(context);
    mTitle = new TextView(context);
    mSubtitle = new TextView(context);

    final LinearLayout textLayout = new LinearLayout(context);
    textLayout.setOrientation(VERTICAL);

    textLayout.addView(mTitle);
    textLayout.addView(mSubtitle);

    addView(mThumbnail);
    addView(textLayout);

    textLayout.setGravity(Gravity.CENTER_VERTICAL);
    setGravity(Gravity.CENTER_VERTICAL);

    final int thumbnailSizePx = General.dpToPixels(context, 64);
    mThumbnail.getLayoutParams().width = thumbnailSizePx;
    mThumbnail.getLayoutParams().height = thumbnailSizePx;

    final int paddingSidesPx = General.dpToPixels(context, 15.0f);
    final int paddingTopBottomPx = General.dpToPixels(context, 10.0f);
    final int paddingSeparationPx = General.dpToPixels(context, 3.0f);

    textLayout.setPadding(paddingSidesPx, paddingTopBottomPx, paddingSidesPx, paddingTopBottomPx);
    mSubtitle.setPadding(0, paddingSeparationPx, 0, 0);

    mTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
    mSubtitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
    mSubtitle.setTextColor(Color.rgb(0x90, 0x90, 0x90));
  }
コード例 #3
0
  @Override
  public void onCreate(final Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    url = General.uriFromString(getArguments().getString("url"));

    if (getArguments().containsKey("current")) {
      current = UUID.fromString(getArguments().getString("current"));
    } else {
      current = null;
    }

    type = SessionChangeListener.SessionChangeType.valueOf(getArguments().getString("type"));
  }
コード例 #4
0
  private void revertToWeb() {

    final Runnable r =
        new Runnable() {
          public void run() {
            if (!mHaveReverted) {
              mHaveReverted = true;
              LinkHandler.onLinkClicked(AlbumListingActivity.this, mUrl, true);
              finish();
            }
          }
        };

    if (General.isThisUIThread()) {
      r.run();
    } else {
      AndroidApi.UI_THREAD_HANDLER.post(r);
    }
  }
コード例 #5
0
 @Override
 public void onBackPressed() {
   if (General.onBackPressed()) super.onBackPressed();
 }
コード例 #6
0
  @Override
  public void onBackPressed() {

    if (General.onBackPressed() && !webView.onBackButtonPressed()) super.onBackPressed();
  }
コード例 #7
0
    public static SubredditPostListURL parse(final Uri uri) {

      Integer limit = null;
      String before = null, after = null;

      for (final String parameterKey : General.getUriQueryParameterNames(uri)) {

        if (parameterKey.equalsIgnoreCase("after")) {
          after = uri.getQueryParameter(parameterKey);

        } else if (parameterKey.equalsIgnoreCase("before")) {
          before = uri.getQueryParameter(parameterKey);

        } else if (parameterKey.equalsIgnoreCase("limit")) {
          try {
            limit = Integer.parseInt(uri.getQueryParameter(parameterKey));
          } catch (Throwable ignored) {
          }

        } else {
          Log.e(
              "SubredditPostListURL", String.format("Unknown query parameter '%s'", parameterKey));
        }
      }

      final String[] pathSegments;
      {
        final List<String> pathSegmentsList = uri.getPathSegments();

        final ArrayList<String> pathSegmentsFiltered =
            new ArrayList<String>(pathSegmentsList.size());
        for (String segment : pathSegmentsList) {

          while (segment.toLowerCase().endsWith(".json")
              || segment.toLowerCase().endsWith(".xml")) {
            segment = segment.substring(0, segment.lastIndexOf('.'));
          }

          if (segment.length() > 0) {
            pathSegmentsFiltered.add(segment);
          }
        }

        pathSegments = pathSegmentsFiltered.toArray(new String[pathSegmentsFiltered.size()]);
      }

      final PostListingController.Sort order;
      if (pathSegments.length > 0) {
        order = getOrder(pathSegments[pathSegments.length - 1], uri.getQueryParameter("t"));
      } else {
        order = null;
      }

      switch (pathSegments.length) {
        case 0:
          return new SubredditPostListURL(
              Type.FRONTPAGE, null, PostListingController.Sort.HOT, limit, before, after);

        case 1:
          {
            if (order != null) {
              return new SubredditPostListURL(Type.FRONTPAGE, null, order, limit, before, after);
            } else {
              return null;
            }
          }

        case 2:
        case 3:
          {
            if (!pathSegments[0].equals("r")) return null;

            final String subreddit = pathSegments[1];

            if (subreddit.equals("all")) {

              if (pathSegments.length == 2) {
                return new SubredditPostListURL(
                    Type.ALL, null, PostListingController.Sort.HOT, limit, before, after);

              } else if (order != null) {
                return new SubredditPostListURL(Type.ALL, null, order, limit, before, after);

              } else {
                return null;
              }

            } else if (subreddit.matches("all(\\-\\w+)+")) {

              if (pathSegments.length == 2) {
                return new SubredditPostListURL(
                    Type.ALL_SUBTRACTION,
                    subreddit,
                    PostListingController.Sort.HOT,
                    limit,
                    before,
                    after);

              } else if (order != null) {
                return new SubredditPostListURL(
                    Type.ALL_SUBTRACTION, subreddit, order, limit, before, after);

              } else {
                return null;
              }

            } else if (subreddit.matches("\\w+(\\+\\w+)+")) {

              if (pathSegments.length == 2) {
                return new SubredditPostListURL(
                    Type.SUBREDDIT_COMBINATION,
                    subreddit,
                    PostListingController.Sort.HOT,
                    limit,
                    before,
                    after);

              } else if (order != null) {
                return new SubredditPostListURL(
                    Type.SUBREDDIT_COMBINATION, subreddit, order, limit, before, after);

              } else {
                return null;
              }

            } else if (subreddit.matches("\\w+")) {

              if (pathSegments.length == 2) {
                return new SubredditPostListURL(
                    Type.SUBREDDIT,
                    subreddit,
                    PostListingController.Sort.HOT,
                    limit,
                    before,
                    after);

              } else if (order != null) {
                return new SubredditPostListURL(
                    Type.SUBREDDIT, subreddit, order, limit, before, after);

              } else {
                return null;
              }

            } else {
              return null;
            }
          }

        default:
          return null;
      }
    }
コード例 #8
0
    public static SearchPostListURL parse(final Uri uri) {

      boolean restrict_sr = false;
      String query = "";
      Integer limit = null;
      String before = null, after = null;

      for (final String parameterKey : General.getUriQueryParameterNames(uri)) {

        if (parameterKey.equalsIgnoreCase("after")) {
          after = uri.getQueryParameter(parameterKey);

        } else if (parameterKey.equalsIgnoreCase("before")) {
          before = uri.getQueryParameter(parameterKey);

        } else if (parameterKey.equalsIgnoreCase("limit")) {
          try {
            limit = Integer.parseInt(uri.getQueryParameter(parameterKey));
          } catch (Throwable ignored) {
          }

        } else if (parameterKey.equalsIgnoreCase("q")) {
          query = uri.getQueryParameter(parameterKey);

        } else if (parameterKey.equalsIgnoreCase("restrict_sr")) {
          restrict_sr = "on".equalsIgnoreCase(uri.getQueryParameter(parameterKey));

        } else {
          Log.e("SearchPostListURL", String.format("Unknown query parameter '%s'", parameterKey));
        }
      }

      final String[] pathSegments;
      {
        final List<String> pathSegmentsList = uri.getPathSegments();

        final ArrayList<String> pathSegmentsFiltered =
            new ArrayList<String>(pathSegmentsList.size());
        for (String segment : pathSegmentsList) {

          while (segment.toLowerCase().endsWith(".json")
              || segment.toLowerCase().endsWith(".xml")) {
            segment = segment.substring(0, segment.lastIndexOf('.'));
          }

          if (segment.length() > 0) {
            pathSegmentsFiltered.add(segment);
          }
        }

        pathSegments = pathSegmentsFiltered.toArray(new String[pathSegmentsFiltered.size()]);
      }

      if (pathSegments.length != 1 && pathSegments.length != 3) return null;
      if (!pathSegments[pathSegments.length - 1].equalsIgnoreCase("search")) return null;

      switch (pathSegments.length) {
        case 1:
          {
            return new SearchPostListURL(null, query, limit, before, after);
          }

        case 3:
          {
            if (!pathSegments[0].equals("r")) return null;

            final String subreddit = pathSegments[1];
            return new SearchPostListURL(
                restrict_sr ? subreddit : null, query, limit, before, after);
          }

        default:
          return null;
      }
    }
コード例 #9
0
    public static UserPostListingURL parse(Uri uri) {

      Integer limit = null;
      String before = null, after = null;

      for (final String parameterKey : General.getUriQueryParameterNames(uri)) {

        if (parameterKey.equalsIgnoreCase("after")) {
          after = uri.getQueryParameter(parameterKey);

        } else if (parameterKey.equalsIgnoreCase("before")) {
          before = uri.getQueryParameter(parameterKey);

        } else if (parameterKey.equalsIgnoreCase("limit")) {
          try {
            limit = Integer.parseInt(uri.getQueryParameter(parameterKey));
          } catch (Throwable ignored) {
          }

        } else {
          Log.e(
              "SubredditPostListURL", String.format("Unknown query parameter '%s'", parameterKey));
        }
      }

      final String[] pathSegments;
      {
        final List<String> pathSegmentsList = uri.getPathSegments();

        final ArrayList<String> pathSegmentsFiltered =
            new ArrayList<String>(pathSegmentsList.size());
        for (String segment : pathSegmentsList) {

          while (segment.toLowerCase().endsWith(".json")
              || segment.toLowerCase().endsWith(".xml")) {
            segment = segment.substring(0, segment.lastIndexOf('.'));
          }

          if (segment.length() > 0) {
            pathSegmentsFiltered.add(segment);
          }
        }

        pathSegments = pathSegmentsFiltered.toArray(new String[pathSegmentsFiltered.size()]);
      }

      if (pathSegments.length < 3) {
        return null;
      }

      if (!pathSegments[0].equalsIgnoreCase("user")) {
        return null;
      }

      // TODO validate username with regex
      final String username = pathSegments[1];
      final String typeName = pathSegments[2].toUpperCase();
      final Type type;

      try {
        type = Type.valueOf(typeName);
      } catch (Throwable t) {
        return null;
      }

      return new UserPostListingURL(type, username, limit, before, after);
    }
コード例 #10
0
  public void reset(final int listPosition, final ImageInfo info) {

    mImageInfo = info;

    if (info.title == null || info.title.trim().isEmpty()) {
      mTitle.setText("Image " + (listPosition + 1));
    } else {
      mTitle.setText((listPosition + 1) + ". " + info.title.trim());
    }

    String subtitle = "";

    if (info.type != null) {
      subtitle += info.type;
    }

    if (info.width != null && info.height != null) {

      if (!subtitle.isEmpty()) subtitle += ", ";

      subtitle += info.width + "x" + info.height;
    }

    if (info.size != null) {

      if (!subtitle.isEmpty()) subtitle += ", ";

      long size = info.size;

      if (size < 512 * 1024) {
        subtitle += String.format("%.1f kB", (float) size / 1024);
      } else {
        subtitle += String.format("%.1f MB", (float) size / (1024 * 1024));
      }
    }

    if (subtitle.isEmpty()) {
      mSubtitle.setVisibility(GONE);
    } else {
      mSubtitle.setVisibility(VISIBLE);
    }

    mSubtitle.setText(subtitle);

    mThumbnail.setImageBitmap(null);

    final boolean isConnectionWifi = General.isConnectionWifi(getContext());

    final PrefsUtility.AppearanceThumbnailsShow thumbnailsPref =
        PrefsUtility.appearance_thumbnails_show(
            getContext(), PreferenceManager.getDefaultSharedPreferences(getContext()));

    final boolean downloadThumbnails =
        thumbnailsPref == PrefsUtility.AppearanceThumbnailsShow.ALWAYS
            || (thumbnailsPref == PrefsUtility.AppearanceThumbnailsShow.WIFIONLY
                && isConnectionWifi);

    if (!downloadThumbnails) {
      mThumbnail.setVisibility(GONE);

    } else {

      mThumbnail.setVisibility(VISIBLE);

      CacheManager.getInstance(getContext())
          .makeRequest(
              new CacheRequest(
                  General.uriFromString(info.urlBigSquare),
                  RedditAccountManager.getAnon(),
                  null,
                  Constants.Priority.THUMBNAIL,
                  listPosition,
                  CacheRequest.DownloadType.IF_NECESSARY,
                  Constants.FileType.THUMBNAIL,
                  CacheRequest.DownloadQueueType.IMMEDIATE,
                  false,
                  false,
                  getContext()) {
                @Override
                protected void onCallbackException(final Throwable t) {
                  Log.e("ImgurAlbumListEntryView", "Error in album thumbnail fetch callback", t);
                }

                @Override
                protected void onDownloadNecessary() {}

                @Override
                protected void onDownloadStarted() {}

                @Override
                protected void onFailure(
                    final RequestFailureType type,
                    final Throwable t,
                    final Integer status,
                    final String readableMessage) {
                  Log.e("ImgurAlbumListEntryView", "Failed to fetch thumbnail " + url.toString());
                }

                @Override
                protected void onProgress(
                    final boolean authorizationInProgress,
                    final long bytesRead,
                    final long totalBytes) {}

                @Override
                protected void onSuccess(
                    final CacheManager.ReadableCacheFile cacheFile,
                    final long timestamp,
                    final UUID session,
                    final boolean fromCache,
                    final String mimetype) {

                  if (mImageInfo != info) return;

                  // TODO post message rather than runnable
                  AndroidApi.UI_THREAD_HANDLER.post(
                      new Runnable() {
                        @Override
                        public void run() {
                          try {
                            mThumbnail.setImageURI(cacheFile.getUri());
                          } catch (IOException e) {
                            throw new RuntimeException(e);
                          }
                        }
                      });
                }
              });
    }
  }
コード例 #11
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    final TextView title = new TextView(this);
    title.setText(R.string.bug_title);
    layout.addView(title);
    title.setTextSize(20.0f);

    final TextView text = new TextView(this);
    text.setText(R.string.bug_message);

    layout.addView(text);
    text.setTextSize(15.0f);

    final int paddingPx = General.dpToPixels(this, 20);
    title.setPadding(paddingPx, paddingPx, paddingPx, paddingPx);
    text.setPadding(paddingPx, paddingPx, paddingPx, paddingPx);

    final Button send = new Button(this);
    send.setText(R.string.bug_button_send);

    send.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {

            final LinkedList<RRError> errors = BugReportActivity.getErrors();

            StringBuilder sb = new StringBuilder(1024);

            sb.append("Error report -- RedReader v")
                .append(Constants.version(BugReportActivity.this))
                .append("\r\n\r\n");

            for (RRError error : errors) {
              sb.append("-------------------------------");
              if (error.title != null) sb.append("Title: ").append(error.title).append("\r\n");
              if (error.message != null)
                sb.append("Message: ").append(error.message).append("\r\n");
              if (error.httpStatus != null)
                sb.append("HTTP Status: ").append(error.httpStatus).append("\r\n");
              appendException(sb, error.t, 25);
            }

            final Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("message/rfc822");
            intent.putExtra(
                Intent.EXTRA_EMAIL,
                new String[] {
                  "bug" + "reports" + '@' + "redreader" + '.' + "org"
                }); // no spam, thanks
            intent.putExtra(Intent.EXTRA_SUBJECT, "Bug Report");
            intent.putExtra(Intent.EXTRA_TEXT, sb.toString());

            try {
              startActivity(Intent.createChooser(intent, "Email bug report"));
            } catch (android.content.ActivityNotFoundException ex) {
              General.quickToast(BugReportActivity.this, "No email apps installed!");
            }

            finish();
          }
        });

    final Button ignore = new Button(this);
    ignore.setText(R.string.bug_button_ignore);

    ignore.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            finish();
          }
        });

    layout.addView(send);
    layout.addView(ignore);

    final ScrollView sv = new ScrollView(this);
    sv.addView(layout);

    setContentView(sv);
  }